blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 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
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
601e2e5c6f3735d45e420fbc4cebb6b4cceb80e4 | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/ClosableTabCtrl.cpp | 6054875f7d80e5da6629b3c8a4e08368df06f235 | []
| no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 20,467 | cpp | //this file is part of eMule
//Copyright (C)2002-2008 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.
#include "stdafx.h"
#include "emule.h"
#include "ClosableTabCtrl.h"
#include "OtherFunctions.h"
#include "MenuCmds.h"
#include "UserMsgs.h"
#include "VisualStylesXP.h"
// ==> Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle
#if _MSC_VER>=1600
#include "Preferences.h"
#endif
// <== Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// _WIN32_WINNT >= 0x0501 (XP only)
#define _WM_THEMECHANGED 0x031A
#define _ON_WM_THEMECHANGED() \
{ _WM_THEMECHANGED, 0, 0, 0, AfxSig_l, \
(AFX_PMSG)(AFX_PMSGW) \
(static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(void) > (_OnThemeChanged)) \
},
///////////////////////////////////////////////////////////////////////////////
// CClosableTabCtrl
IMPLEMENT_DYNAMIC(CClosableTabCtrl, CTabCtrl)
BEGIN_MESSAGE_MAP(CClosableTabCtrl, CTabCtrl)
ON_WM_LBUTTONUP()
ON_WM_LBUTTONDBLCLK()
ON_WM_MBUTTONUP()
ON_WM_CREATE()
ON_WM_SYSCOLORCHANGE()
ON_WM_CONTEXTMENU()
_ON_WM_THEMECHANGED()
ON_WM_CTLCOLOR_REFLECT()
ON_WM_CTLCOLOR()
ON_WM_ERASEBKGND()
ON_WM_MEASUREITEM()
ON_WM_MEASUREITEM_REFLECT()
END_MESSAGE_MAP()
CClosableTabCtrl::CClosableTabCtrl()
{
m_bCloseable = true;
memset(&m_iiCloseButton, 0, sizeof m_iiCloseButton);
m_ptCtxMenu.SetPoint(-1, -1);
m_clrBack = CLR_DEFAULT; // Design Settings [eWombat/Stulle] - Max
}
CClosableTabCtrl::~CClosableTabCtrl()
{
}
void CClosableTabCtrl::GetCloseButtonRect(int iItem, const CRect& rcItem, CRect& rcCloseButton, bool bItemSelected, bool bVistaThemeActive)
{
rcCloseButton.top = rcItem.top + 2;
rcCloseButton.bottom = rcCloseButton.top + (m_iiCloseButton.rcImage.bottom - m_iiCloseButton.rcImage.top);
rcCloseButton.right = rcItem.right - 2;
rcCloseButton.left = rcCloseButton.right - (m_iiCloseButton.rcImage.right - m_iiCloseButton.rcImage.left);
if (bVistaThemeActive)
rcCloseButton.left -= 1; // the close button does not look 'symetric' with a width of 16, give it 17
if (bItemSelected) {
rcCloseButton.OffsetRect(-1, 0);
if (bVistaThemeActive) {
int iItems = GetItemCount();
if (iItems > 1 && iItem == iItems - 1)
rcCloseButton.OffsetRect(-2, 0);
}
}
else {
if (bVistaThemeActive) {
int iItems = GetItemCount();
if (iItems > 1 && iItem < iItems - 1)
rcCloseButton.OffsetRect(2, 0);
}
}
}
int CClosableTabCtrl::GetTabUnderPoint(CPoint point) const
{
int iTabs = GetItemCount();
for (int i = 0; i < iTabs; i++)
{
CRect rcItem;
GetItemRect(i, rcItem);
rcItem.InflateRect(2, 2); // get the real tab item rect
if (rcItem.PtInRect(point))
return i;
}
return -1;
}
int CClosableTabCtrl::GetTabUnderContextMenu() const
{
if (m_ptCtxMenu.x == -1 || m_ptCtxMenu.y == -1)
return -1;
return GetTabUnderPoint(m_ptCtxMenu);
}
bool CClosableTabCtrl::SetDefaultContextMenuPos()
{
int iTab = GetCurSel();
if (iTab != -1)
{
CRect rcItem;
if (GetItemRect(iTab, &rcItem))
{
rcItem.InflateRect(2, 2); // get the real tab item rect
m_ptCtxMenu.x = rcItem.left + rcItem.Width()/2;
m_ptCtxMenu.y = rcItem.top + rcItem.Height()/2;
return true;
}
}
return false;
}
void CClosableTabCtrl::OnMButtonUp(UINT nFlags, CPoint point)
{
if (m_bCloseable)
{
int iTab = GetTabUnderPoint(point);
if (iTab != -1) {
GetParent()->SendMessage(UM_CLOSETAB, (WPARAM)iTab);
return;
}
}
CTabCtrl::OnMButtonUp(nFlags, point);
}
void CClosableTabCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
if (m_bCloseable)
{
int iTab = GetTabUnderPoint(point);
if (iTab != -1)
{
CRect rcItem;
GetItemRect(iTab, rcItem);
rcItem.InflateRect(2, 2); // get the real tab item rect
bool bVistaThemeActive = theApp.IsVistaThemeActive();
CRect rcCloseButton;
GetCloseButtonRect(iTab, rcItem, rcCloseButton, iTab == GetCurSel(), bVistaThemeActive);
// The visible part of our close icon is one pixel less on each side
if (!bVistaThemeActive) {
rcCloseButton.top += 1;
rcCloseButton.left += 1;
rcCloseButton.right -= 1;
rcCloseButton.bottom -= 1;
}
if (rcCloseButton.PtInRect(point)) {
GetParent()->SendMessage(UM_CLOSETAB, (WPARAM)iTab);
return;
}
}
}
CTabCtrl::OnLButtonUp(nFlags, point);
}
void CClosableTabCtrl::OnLButtonDblClk(UINT nFlags, CPoint point)
{
int iTab = GetTabUnderPoint(point);
if (iTab != -1) {
GetParent()->SendMessage(UM_DBLCLICKTAB, (WPARAM)iTab);
return;
}
CTabCtrl::OnLButtonDblClk(nFlags, point);
}
// It would be nice if there would the option to restrict the maximum width of a tab control.
// We would need that feature actually for almost all our tab controls. Especially for the
// search results list - those tab control labels can get quite large. But I did not yet a
// find a way to limit the width of tabs. Although MSDN says that an owner drawn
// tab control receives a WM_MEASUREITEM, I never got one.
// Vista: This gets never called for an owner drawn tab control
void CClosableTabCtrl::OnMeasureItem(int iCtlId, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
TRACE("CClosableTabCtrl::OnMeasureItem\n");
__super::OnMeasureItem(iCtlId, lpMeasureItemStruct);
}
// Vista: This gets never called for an owner drawn tab control
void CClosableTabCtrl::MeasureItem(LPMEASUREITEMSTRUCT)
{
TRACE("CClosableTabCtrl::MeasureItem\n");
}
void CClosableTabCtrl::DrawItem(LPDRAWITEMSTRUCT lpDIS)
{
CRect rect(lpDIS->rcItem);
int nTabIndex = lpDIS->itemID;
if (nTabIndex < 0)
return;
TCHAR szLabel[256];
TC_ITEM tci;
tci.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_STATE;
tci.pszText = szLabel;
tci.cchTextMax = _countof(szLabel);
tci.dwStateMask = TCIS_HIGHLIGHTED;
if (!GetItem(nTabIndex, &tci))
return;
szLabel[_countof(szLabel) - 1] = _T('\0');
//TRACE("CClosableTabCtrl::DrawItem: item=%u, state=%08x, color=%08x, rc=%3d,%3d,%3dx%3d\n", nTabIndex, tci.dwState, GetTextColor(lpDIS->hDC), lpDIS->rcItem.left, lpDIS->rcItem.top, lpDIS->rcItem.right - lpDIS->rcItem.left, lpDIS->rcItem.bottom - lpDIS->rcItem.top);
CDC* pDC = CDC::FromHandle(lpDIS->hDC);
if (!pDC)
return;
CRect rcFullItem(lpDIS->rcItem);
bool bSelected = (lpDIS->itemState & ODS_SELECTED) != 0;
///////////////////////////////////////////////////////////////////////////////////////
// Adding support for XP Styles (Vista Themes) for owner drawn tab controls simply
// does *not* work under Vista. Maybe it works under XP (did not try), but that is
// meaningless because under XP a owner drawn tab control is already rendered *with*
// the proper XP Styles. So, for XP there is no need to care about the theme API at all.
//
// However, under Vista, a tab control which has the TCS_OWNERDRAWFIXED
// style gets additional 3D-borders which are applied by Vista *after* WM_DRAWITEM
// was processed. Thus, there is no known workaround available to prevent Vista from
// adding those old fashioned 3D-borders. We can render the tab control items within
// the WM_DRAWITEM handler in whatever style we want, but Vista will in each case
// overwrite the borders of each tab control item with old fashioned 3D-borders...
//
// To complete this experience, tab controls also do not support NMCUSTOMDRAW. So, the
// only known way to customize a tab control is by using TCS_OWNERDRAWFIXED which does
// however not work properly under Vista.
//
// The "solution" which is currently implemented to prevent Vista from drawing those
// 3D-borders is by using "ExcludeClipRect" to reduce the drawing area which is used
// by Windows after WM_DRAWITEM was processed. This "solution" is very sensitive to
// the used rectangles and offsets in general. Incrementing/Decrementing one of the
// "rcItem", "rcFullItem", etc. rectangles makes the entire "solution" flawed again
// because some borders would become visible again.
//
HTHEME hTheme = NULL;
int iPartId = TABP_TABITEM;
int iStateId = TIS_NORMAL;
bool bVistaHotTracked = false;
bool bVistaThemeActive = theApp.IsVistaThemeActive();
if (bVistaThemeActive)
{
// To determine if the current item is in 'hot tracking' mode, we need to evaluate
// the current foreground color - there is no flag which would indicate this state
// more safely. This applies only for Vista and for tab controls which have the
// TCS_OWNERDRAWFIXED style.
bVistaHotTracked = pDC->GetTextColor() == GetSysColor(COLOR_HOTLIGHT);
hTheme = g_xpStyle.OpenThemeData(m_hWnd, L"TAB");
if (hTheme)
{
if (bSelected) {
// get the real tab item rect
rcFullItem.left += 1;
rcFullItem.right -= 1;
rcFullItem.bottom -= 1;
}
else
rcFullItem.InflateRect(2, 2); // get the real tab item rect
CRect rcBk(rcFullItem);
if (bSelected)
{
iStateId = TTIS_SELECTED;
if (nTabIndex == 0) {
// First item
if (nTabIndex == GetItemCount() - 1)
iPartId = TABP_TOPTABITEMBOTHEDGE; // First & Last item
else
iPartId = TABP_TOPTABITEMLEFTEDGE;
}
else if (nTabIndex == GetItemCount() - 1) {
// Last item
iPartId = TABP_TOPTABITEMRIGHTEDGE;
}
else {
iPartId = TABP_TOPTABITEM;
}
}
else
{
rcBk.top += 2;
iStateId = bVistaHotTracked ? TIS_HOT : TIS_NORMAL;
if (nTabIndex == 0) {
// First item
if (nTabIndex == GetItemCount() - 1)
iPartId = TABP_TABITEMBOTHEDGE; // First & Last item
else
iPartId = TABP_TABITEMLEFTEDGE;
}
else if (nTabIndex == GetItemCount() - 1) {
// Last item
iPartId = TABP_TABITEMRIGHTEDGE;
}
else {
iPartId = TABP_TABITEM;
}
}
if (g_xpStyle.IsThemeBackgroundPartiallyTransparent(hTheme, iPartId, iStateId))
g_xpStyle.DrawThemeParentBackground(m_hWnd, *pDC, &rcFullItem);
g_xpStyle.DrawThemeBackground(hTheme, *pDC, iPartId, iStateId, &rcBk, NULL);
}
}
// Following background clearing is needed for:
// WinXP/Vista (when used without an application theme)
// Vista (when used with an application theme but without a theme for the tab control)
if ( (!g_xpStyle.IsThemeActive() || !g_xpStyle.IsAppThemed())
|| (hTheme == NULL && bVistaThemeActive) )
pDC->FillSolidRect(&lpDIS->rcItem, GetSysColor(COLOR_BTNFACE));
int iOldBkMode = pDC->SetBkMode(TRANSPARENT);
// Draw image on left side
CImageList *piml = GetImageList();
if (tci.iImage >= 0 && piml && piml->m_hImageList)
{
IMAGEINFO ii;
piml->GetImageInfo(0, &ii);
rect.left += bSelected ? 8 : 4;
piml->Draw(pDC, tci.iImage, CPoint(rect.left, rect.top + 2), ILD_TRANSPARENT);
rect.left += (ii.rcImage.right - ii.rcImage.left);
if (!bSelected)
rect.left += 4;
}
bool bCloseable = m_bCloseable;
if (bCloseable && GetParent()->SendMessage(UM_QUERYTAB, nTabIndex))
bCloseable = false;
// Draw 'Close button' at right side
if (bCloseable && m_ImgLstCloseButton.m_hImageList)
{
CRect rcCloseButton;
GetCloseButtonRect(nTabIndex, rect, rcCloseButton, bSelected, bVistaThemeActive);
HTHEME hThemeNC = bVistaThemeActive ? g_xpStyle.OpenThemeData(m_hWnd, _T("WINDOW")) : NULL;
if (hThemeNC) {
// Possible "Close" parts: WP_CLOSEBUTTON, WP_SMALLCLOSEBUTTON, WP_MDICLOSEBUTTON
int iPartId = WP_SMALLCLOSEBUTTON;
int iStateId = (bSelected || bVistaHotTracked) ? CBS_NORMAL : CBS_DISABLED;
if (g_xpStyle.IsThemeBackgroundPartiallyTransparent(hTheme, iPartId, iStateId))
g_xpStyle.DrawThemeParentBackground(m_hWnd, *pDC, &rcCloseButton);
g_xpStyle.DrawThemeBackground(hThemeNC, *pDC, iPartId, iStateId, rcCloseButton, NULL);
g_xpStyle.CloseThemeData(hThemeNC);
}
else {
m_ImgLstCloseButton.Draw(pDC, (bSelected || bVistaHotTracked) ? 0 : 1, rcCloseButton.TopLeft(), ILD_TRANSPARENT);
}
rect.right = rcCloseButton.left - 2;
if (bSelected)
rect.left += hTheme ? 4 : 2;
}
COLORREF crOldColor = CLR_NONE;
if (tci.dwState & TCIS_HIGHLIGHTED)
crOldColor = pDC->SetTextColor(RGB(192, 0, 0));
else if (bVistaHotTracked)
crOldColor = pDC->SetTextColor(GetSysColor(COLOR_BTNTEXT));
rect.top += bSelected ? 4 : 3;
// Vista: Tab control has troubles with determining the width of a tab if the
// label contains one '&' character. To get around this, we use the old code which
// replaces one '&' character with two '&' characters and we do not specify DT_NOPREFIX
// here when drawing the text.
//
// Vista: "DrawThemeText" can not be used in case we need a certain foreground color. Thus we always us
// "DrawText" to always get the same font and metrics (just for safety).
pDC->DrawText(szLabel, rect, DT_SINGLELINE | DT_TOP | DT_CENTER /*| DT_NOPREFIX*/);
if (crOldColor != CLR_NONE)
pDC->SetTextColor(crOldColor);
pDC->SetBkMode(iOldBkMode);
if (hTheme)
{
CRect rcClip(rcFullItem);
if (bSelected) {
rcClip.left -= 2 + 1;
rcClip.right += 2 + 1;
}
else {
rcClip.top += 2;
}
pDC->ExcludeClipRect(&rcClip);
g_xpStyle.CloseThemeData(hTheme);
}
}
void CClosableTabCtrl::PreSubclassWindow()
{
CTabCtrl::PreSubclassWindow();
InternalInit();
}
int CClosableTabCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CTabCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
InternalInit();
return 0;
}
void CClosableTabCtrl::InternalInit()
{
ModifyStyle(0, TCS_OWNERDRAWFIXED);
#if 1
// Under Vista Aero, all tab controls get by default the TCS_HOTTRACK
// style even if it was not specified within the resource file. Though, to 'see'
// the hot tracking effect the control also need to get initialized explicitly with
// the WS_CLIPCHILDREN style within a *seperate* function call. Yes, there is no
// logic to all this, not at all. It simply is that way.
//
// So, do *not* "optimize" that code by using only one "ModifyStyle" function call.
// The 2nd function call to "ModifyStyle" is very much by intention!
//
// However, the hot tracking effect which is achived this way does not survive a
// theme change. After the theme is changed (regardless whether we switch between
// Vista themes or from/to a non-Vista theme), the hot tracking effect is gone even
// if we try to modify the styles again within OnThemeChanged...
if (theApp.IsVistaThemeActive())
ModifyStyle(0, WS_CLIPCHILDREN);
#else
// Remove the automatically applied hot tracking effect to avoid that the tab control
// may use it when it also sets the WS_CLIPCHILDREN (for other reasons) later.
ModifyStyle(TCS_HOTTRACK, 0);
#endif
SetAllIcons();
}
void CClosableTabCtrl::OnSysColorChange()
{
CTabCtrl::OnSysColorChange();
SetAllIcons();
}
void CClosableTabCtrl::SetAllIcons()
{
if (m_bCloseable)
{
const int iIconWidth = 16;
const int iIconHeight = 16;
m_ImgLstCloseButton.DeleteImageList();
m_ImgLstCloseButton.Create(iIconWidth, iIconHeight, theApp.m_iDfltImageListColorFlags | ILC_MASK, 0, 1);
m_ImgLstCloseButton.Add(CTempIconLoader(_T("CloseTabSelected"), iIconWidth, iIconHeight));
m_ImgLstCloseButton.Add(CTempIconLoader(_T("CloseTab"), iIconWidth, iIconHeight));
m_ImgLstCloseButton.GetImageInfo(0, &m_iiCloseButton);
Invalidate();
}
}
void CClosableTabCtrl::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
{
if (m_bCloseable)
{
if (point.x == -1 || point.y == -1) {
if (!SetDefaultContextMenuPos())
return;
point = m_ptCtxMenu;
ClientToScreen(&point);
}
else {
m_ptCtxMenu = point;
ScreenToClient(&m_ptCtxMenu);
}
int iTab = GetTabUnderPoint(m_ptCtxMenu);
if (iTab != -1)
{
if (GetParent()->SendMessage(UM_QUERYTAB, (WPARAM)iTab) == 0)
{
CMenu menu;
menu.CreatePopupMenu();
menu.AppendMenu(MF_STRING, MP_REMOVE, GetResString(IDS_FD_CLOSE));
menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
VERIFY( menu.DestroyMenu() ); // XP Style Menu [Xanatos] - Stulle
}
}
}
}
BOOL CClosableTabCtrl::OnCommand(WPARAM wParam, LPARAM lParam)
{
if (wParam == MP_REMOVE)
{
if (m_ptCtxMenu.x != -1 && m_ptCtxMenu.y != -1)
{
int iTab = GetTabUnderPoint(m_ptCtxMenu);
if (iTab != -1) {
GetParent()->SendMessage(UM_CLOSETAB, (WPARAM)iTab);
return TRUE;
}
}
}
return CTabCtrl::OnCommand(wParam, lParam);
}
LRESULT CClosableTabCtrl::_OnThemeChanged()
{
// Owner drawn tab control seems to have troubles with updating itself due to an XP theme change..
ModifyStyle(TCS_OWNERDRAWFIXED, 0); // Reset control style to not-owner drawn
Default(); // Process original WM_THEMECHANGED message
ModifyStyle(0, TCS_OWNERDRAWFIXED); // Apply owner drawn style again
return 0;
}
// Vista: This gets never called for an owner drawn tab control
HBRUSH CClosableTabCtrl::CtlColor(CDC* /*pDC*/, UINT /*nCtlColor*/)
{
// Change any attributes of the DC here
// Return a non-NULL brush if the parent's handler should not be called
return NULL;
}
// Vista: This gets never called for an owner drawn tab control
HBRUSH CClosableTabCtrl::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CTabCtrl::OnCtlColor(pDC, pWnd, nCtlColor);
// Change any attributes of the DC here
// Return a different brush if the default is not desired
return hbr;
}
// Vista: Can not be used to workaround the problems with owner drawn tab control
BOOL CClosableTabCtrl::OnEraseBkgnd(CDC* pDC)
{
// ==> Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle
#if _MSC_VER<1600
// ==> Design Settings [eWombat/Stulle] - Max
/*
return CTabCtrl::OnEraseBkgnd(pDC);
#else
if(thePrefs.GetWindowsVersion() >= _WINVER_VISTA_)
return CTabCtrl::OnEraseBkgnd(pDC);
// Set brush to desired background color
CBrush backBrush(GetSysColor(COLOR_BTNFACE));
*/
// Set brush to desired background color
CBrush backBrush((m_clrBack != CLR_DEFAULT)?m_clrBack:GetSysColor(COLOR_BTNFACE));
// Save old brush
CBrush* pOldBrush = pDC->SelectObject(&backBrush);
CRect rect;
pDC->GetClipBox(&rect); // Erase the area needed
pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(),
PATCOPY);
pDC->SelectObject(pOldBrush);
return TRUE;
#else
if(thePrefs.GetWindowsVersion() >= _WINVER_VISTA_ && m_clrBack == CLR_DEFAULT)
return CTabCtrl::OnEraseBkgnd(pDC);
// Set brush to desired background color
CBrush backBrush((m_clrBack != CLR_DEFAULT)?m_clrBack:GetSysColor(COLOR_BTNFACE));
// <== Design Settings [eWombat/Stulle] - Max
// Save old brush
CBrush* pOldBrush = pDC->SelectObject(&backBrush);
// So it seems this finally got broken on VS2010 for XP... so when we erase background now we just set it ourself now...
CRect rect;
pDC->GetClipBox(&rect); // Erase the area needed
pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(),
PATCOPY);
pDC->SelectObject(pOldBrush);
return TRUE;
#endif
// <== Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle
}
BOOL CClosableTabCtrl::DeleteItem(int nItem)
{
// if we remove a tab which would lead to scrolling back to other tabs, all those become hidden for... whatever reasons
// its easy enough wo work arround by scrolling to the first visible tab _before_ we delete the other one
SetCurSel(0);
return __super::DeleteItem(nItem);
}
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
]
| [
[
[
1,
23
],
[
29,
69
],
[
71,
558
],
[
563,
563
],
[
613,
613
]
],
[
[
24,
28
],
[
70,
70
],
[
559,
562
],
[
564,
612
]
]
]
|
f8eff40d4d5ad79ccce72a53cc611e1ac8db3b3d | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/Editable.cpp | 654847f1cb7a365526588a543899ec4d896d254f | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,292 | cpp | //----------------------------------------------------------
//
// MODULE : Editable.cpp
//
// PURPOSE : Editable aggreate
//
// CREATED : 3/10/99
//
//----------------------------------------------------------
#include "stdafx.h"
#include "Editable.h"
#include "iltserver.h"
#include "ObjectMsgs.h"
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::CEditable()
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
CEditable::CEditable() : IAggregate()
{
m_propList.Init(LTTRUE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::~CEditable()
//
// PURPOSE: Destructor
//
// ----------------------------------------------------------------------- //
CEditable::~CEditable()
{
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::EngineMessageFn()
//
// PURPOSE: Handle engine messages
//
// ----------------------------------------------------------------------- //
uint32 CEditable::ObjectMessageFn(LPBASECLASS pObject, HOBJECT hSender, ILTMessage_Read *pMsg)
{
pMsg->SeekTo(0);
uint32 messageID = pMsg->Readuint32();
switch(messageID)
{
case MID_TRIGGER:
{
const char* szMsg = (const char*)pMsg->Readuint32();
TriggerMsg(pObject, hSender, szMsg);
}
break;
default : break;
}
return IAggregate::ObjectMessageFn(pObject, hSender, pMsg);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddFloatProp
//
// PURPOSE: Add a float prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddFloatProp(char* pPropName, LTFLOAT* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_FLOAT_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddDWordProp
//
// PURPOSE: Add a dword prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddDWordProp(char* pPropName, uint32* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_DWORD_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddByteProp
//
// PURPOSE: Add a byte prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddByteProp(char* pPropName, uint8* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_BYTE_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddBoolProp
//
// PURPOSE: Add a bool prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddBoolProp(char* pPropName, LTBOOL* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_BOOL_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddVectorProp
//
// PURPOSE: Add a vector prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddVectorProp(char* pPropName, LTVector* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_VECTOR_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::TriggerMsg()
//
// PURPOSE: Process trigger messages
//
// --------------------------------------------------------------------------- //
void CEditable::TriggerMsg(LPBASECLASS pObject, HOBJECT hSender, const char* szMsg)
{
if (!szMsg) return;
// ConParse does not destroy szMsg, so this is safe
ConParse parse;
parse.Init((char*)szMsg);
while (g_pCommonLT->Parse(&parse) == LT_OK)
{
if (parse.m_nArgs > 0 && parse.m_Args[0])
{
if (_stricmp(parse.m_Args[0], "DISPLAYPROPERTIES") == 0)
{
ListProperties(pObject);
}
else if (_stricmp(parse.m_Args[0], "EDIT") == 0)
{
if (parse.m_nArgs > 2)
{
EditProperty(pObject, parse.m_Args[1], parse.m_Args[2]);
}
}
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::EditProperty()
//
// PURPOSE: Edit the specified property
//
// --------------------------------------------------------------------------- //
void CEditable::EditProperty(LPBASECLASS pObject, char* pPropName, char* pPropValue)
{
if (!pObject || !pPropName || !pPropValue) return;
// Edit the appropriate property...
CPropDef** pCur = m_propList.GetItem(TLIT_FIRST);
CPropDef* pPropDef = LTNULL;
while (pCur)
{
pPropDef = *pCur;
if (pPropDef)
{
const char* pName = pPropDef->GetPropName();
if (pName && _strnicmp(pName, pPropName, strlen(pName)) == 0)
{
if (pPropDef->SetValue(pPropName, pPropValue))
{
ListProperties(pObject);
}
else
{
g_pLTServer->CPrint("Couldn't set '%s' to '%s'!", pName, pPropValue);
}
return;
}
}
pCur = m_propList.GetItem(TLIT_NEXT);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::ListProperties()
//
// PURPOSE: List our properties/values
//
// --------------------------------------------------------------------------- //
void CEditable::ListProperties(LPBASECLASS pObject)
{
if (!pObject) return;
g_pLTServer->CPrint("Object Properties------------------------");
g_pLTServer->CPrint("'Name' = '%s'", GetObjectName(pObject->m_hObject));
CPropDef** pCur = m_propList.GetItem(TLIT_FIRST);
CPropDef* pPropDef = LTNULL;
while (pCur)
{
pPropDef = *pCur;
if (pPropDef)
{
const char* pPropName = pPropDef->GetPropName();
CString str;
pPropDef->GetStringValue(str);
g_pLTServer->CPrint("'%s' = %s", pPropName ? pPropName : "(Invalid name)",
str.GetLength() > 1 ? str.GetBuffer(1) : "(Invalid value)");
}
pCur = m_propList.GetItem(TLIT_NEXT);
}
g_pLTServer->CPrint("-----------------------------------------");
}
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
//
// CPropDef class methods
//
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::CPropDef()
//
// PURPOSE: Constructor
//
// --------------------------------------------------------------------------- //
CPropDef::CPropDef()
{
m_strPropName = LTNULL;
m_eType = PT_UNKNOWN_TYPE;
m_pAddress = LTNULL;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::~CPropDef()
//
// PURPOSE: Destructor
//
// --------------------------------------------------------------------------- //
CPropDef::~CPropDef()
{
if (m_strPropName)
{
g_pLTServer->FreeString(m_strPropName);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::Init()
//
// PURPOSE: Set up our data members
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::Init(char* pName, PropType eType, void* pAddress)
{
if (m_strPropName || !pName) return LTFALSE;
m_strPropName = g_pLTServer->CreateString(pName);
m_eType = eType;
m_pAddress = pAddress;
return LTTRUE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetFloatValue()
//
// PURPOSE: Get the value of the property as a float
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetFloatValue(LTFLOAT & fRet)
{
if (m_eType == PT_FLOAT_TYPE && m_pAddress)
{
fRet = *((LTFLOAT*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetDWordValue()
//
// PURPOSE: Get the value of the property as a dword
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetDWordValue(uint32 & dwRet)
{
if (m_eType == PT_DWORD_TYPE && m_pAddress)
{
dwRet = *((uint32*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetByteValue()
//
// PURPOSE: Get the value of the property as a byte
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetByteValue(uint8 & nRet)
{
if (m_eType == PT_BYTE_TYPE && m_pAddress)
{
nRet = *((uint8*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetBoolValue()
//
// PURPOSE: Get the value of the property as a bool
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetBoolValue(LTBOOL & bRet)
{
if (m_eType == PT_BOOL_TYPE && m_pAddress)
{
bRet = *((LTBOOL*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetVectorValue()
//
// PURPOSE: Get the value of the property as a vector
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetVectorValue(LTVector & vRet)
{
if (m_eType == PT_VECTOR_TYPE && m_pAddress)
{
vRet = *((LTVector*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetPropName()
//
// PURPOSE: Get the name of the property
//
// --------------------------------------------------------------------------- //
const char* CPropDef::GetPropName()
{
if (!m_strPropName) return LTNULL;
return g_pLTServer->GetStringData(m_strPropName);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetStringValue()
//
// PURPOSE: Get the value of the property as a string
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetStringValue(CString & str)
{
switch (m_eType)
{
case PT_BYTE_TYPE:
{
uint8 nVal;
if (GetByteValue(nVal))
{
str.Format("%d", nVal);
return LTTRUE;
}
}
break;
case PT_BOOL_TYPE:
{
LTBOOL bVal;
if (GetBoolValue(bVal))
{
str.Format("%s", bVal ? "True" : "False");
return LTTRUE;
}
}
break;
case PT_FLOAT_TYPE:
{
LTFLOAT fVal;
if (GetFloatValue(fVal))
{
str.Format("%.2f", fVal);
return LTTRUE;
}
}
break;
case PT_VECTOR_TYPE:
{
LTVector vVal;
if (GetVectorValue(vVal))
{
str.Format("(%.2f, %.2f, %.2f)", vVal.x, vVal.y, vVal.z);
return LTTRUE;
}
}
break;
case PT_DWORD_TYPE:
{
uint32 dwVal;
if (GetDWordValue(dwVal))
{
str.Format("%d", dwVal);
return LTTRUE;
}
}
break;
default : break;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::SetValue()
//
// PURPOSE: Set this property to the value specified...
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::SetValue(char* pPropName, char* pValue)
{
if (!pPropName || !pValue) return LTFALSE;
switch (m_eType)
{
case PT_BYTE_TYPE:
{
uint8 nVal = (uint8) atol(pValue);
*((uint8*)m_pAddress) = nVal;
}
break;
case PT_BOOL_TYPE:
{
LTBOOL bVal = (LTBOOL) atol(pValue);
*((LTBOOL*)m_pAddress) = bVal;
}
break;
case PT_FLOAT_TYPE:
{
LTFLOAT fVal = (LTFLOAT) atof(pValue);
*((LTFLOAT*)m_pAddress) = fVal;
}
break;
case PT_VECTOR_TYPE:
{
LTFLOAT fVal = (LTFLOAT) atof(pValue);
if (strstr(pPropName, ".x") || strstr(pPropName, ".r"))
{
((LTVector*)m_pAddress)->x = fVal;
}
else if (strstr(pPropName, ".y") || strstr(pPropName, ".g"))
{
((LTVector*)m_pAddress)->y = fVal;
}
else if (strstr(pPropName, ".z") || strstr(pPropName, ".b"))
{
((LTVector*)m_pAddress)->z = fVal;
}
}
break;
case PT_DWORD_TYPE:
{
uint32 dwVal = (uint32) atol(pValue);
*((uint32*)m_pAddress) = dwVal;
}
break;
default : break;
}
return LTTRUE;
} | [
"[email protected]"
]
| [
[
[
1,
593
]
]
]
|
67dc961e5d87fa8e0f7f81fd5518860c4311986f | 27167a5a0340fdc9544752bd724db27d3699a9a2 | /MDISample/MDISample.cpp | a5f765b049c67f57d6816f67310ee5c1d950c6d6 | []
| no_license | eaglexmw-gmail/wtl-dockwins | 2b464be3958e1683cd668a10abafb528f43ac695 | ae307a1978b73bfd2823945068224bb6c01ae350 | refs/heads/master | 2020-06-30T21:03:26.075864 | 2011-10-23T12:50:14 | 2011-10-23T12:50:14 | 200,951,487 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | // MDISample.cpp : main source file for MDISample.exe
//
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#include <atldlgs.h>
#include <atlctrlw.h>
#include "resource.h"
#include "MDISampleView.h"
#include "aboutdlg.h"
#include "ChildFrm.h"
#include "MainFrm.h"
CAppModule _Module;
int Run(LPTSTR /*lpstrCmdLine*/ = NULL, int nCmdShow = SW_SHOWDEFAULT)
{
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
CMainFrame wndMain;
if(wndMain.CreateEx() == NULL)
{
ATLTRACE(_T("Main window creation failed!\n"));
return 0;
}
// wndMain.ShowWindow(nCmdShow);
int nRet = theLoop.Run();
_Module.RemoveMessageLoop();
return nRet;
}
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
HRESULT hRes = ::CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call instead to
// make the EXE free threaded. This means that calls come in on a random RPC thread.
// HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
ATLASSERT(SUCCEEDED(hRes));
#if (_WIN32_IE >= 0x0300)
INITCOMMONCONTROLSEX iccx;
iccx.dwSize = sizeof(iccx);
iccx.dwICC = ICC_COOL_CLASSES | ICC_BAR_CLASSES;
BOOL bRet = ::InitCommonControlsEx(&iccx);
bRet;
ATLASSERT(bRet);
#else
::InitCommonControls();
#endif
HINSTANCE hInstRich = ::LoadLibrary(CRichEditCtrl::GetLibraryName());
hRes = _Module.Init(NULL, hInstance);
ATLASSERT(SUCCEEDED(hRes));
int nRet = Run(lpstrCmdLine, nCmdShow);
_Module.Term();
::FreeLibrary(hInstRich);
::CoUninitialize();
return nRet;
}
| [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
7a32f04d5f552590ba125ca0726397ecd618da00 | 28aa891f07cc2240c771b5fb6130b1f4025ddc84 | /inc/pbr_ctrl/pbr_ctrl.hpp | f435276e0b3617ad2b11c508f4497d9f45327440 | []
| no_license | Hincoin/mid-autumn | e7476d8c9826db1cc775028573fc01ab3effa8fe | 5271496fb820f8ab1d613a1c2355504251997fef | refs/heads/master | 2021-01-10T19:17:01.479703 | 2011-12-19T14:32:51 | 2011-12-19T14:32:51 | 34,730,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,607 | hpp | #ifndef _MA_INCLUDED_PBR_CTRL_HPP_
#define _MA_INCLUDED_PBR_CTRL_HPP_
#include "net.hpp"
#include "dispatcher.hpp"
#include "script.hpp"
#include "oolua_error.h"
#include "rpc_ctrl.hpp"
namespace ma{
class pbr_ctrl
{
public:
pbr_ctrl(OOLUA::Script& lua,boost::asio::io_service& io_service,
const std::string& host,
const std::string& service)
:lua_(lua),connection_(new net::Connection(io_service))
{
assert(!self_);
self_= this;
//resolve the host name into an ip address
using namespace boost::asio::ip;
tcp::resolver resol(io_service);
tcp::resolver::query query(host,service);
tcp::resolver::iterator endpoint_iterator =
resol.resolve(query);
tcp::endpoint endp= *endpoint_iterator;
connection_->socket().async_connect(endp,
boost::bind(&pbr_ctrl::handle_connect,
this,
boost::asio::placeholders::error,
++endpoint_iterator));
}
void handle_connect(const boost::system::error_code& e,
boost::asio::ip::tcp::resolver::iterator
endpoint_iterator)
{
if(!e)
{
onconnected();
connection_->async_read(msg_.size,msg_.buff,
boost::bind(&pbr_ctrl::handle_read,
this,
boost::asio::placeholders::error));
}
else if(endpoint_iterator != boost::asio::ip::tcp::resolver::iterator())
{
//try the next endpoint
connection_->socket().close();
boost::asio::ip::tcp::endpoint endpoint
= *endpoint_iterator;
connection_->socket().async_connect(endpoint,
boost::bind(&pbr_ctrl::handle_connect,
this,
boost::asio::placeholders::error,
++endpoint_iterator));
}
else
{
std::cerr<< e.message() <<std::endl;
}
}
void handle_read(const boost::system::error_code& e)
{
if(!e)
{
//deserialize and call rpc
if(!rpc::receive_rpc(connection_,msg_,rpc::s2ctrl_func_tbl))
{
printf("call rpc failed\n");
}
connection_->async_read(msg_.size,msg_.buff,
boost::bind(&pbr_ctrl::handle_read,
this,
boost::asio::placeholders::error));
}
else
{
std::cerr<< e.message()<<std::endl;
}
}
void onconnected()
{
connection_->set_context(this);
printf("onconnected\n");
if(!(lua_ && lua_.call("main")))
{
OOLUA::lua_stack_dump(lua_);
}
}
static pbr_ctrl& get_controller(){assert(self_);return *self_;}
void render_scene(const char* scene_desc,int,int);
private:
OOLUA::Script& lua_;
rpc::conn_t connection_;
rpc::rpc_msg_t msg_;
static pbr_ctrl* self_;
};
void register_functions(lua_State* );
}
#endif
| [
"luozhiyuan@ea6f400c-e855-0410-84ee-31f796524d81"
]
| [
[
[
1,
108
]
]
]
|
c8bfdb281f418982ec97c948116bb19acb18a8f5 | 03b001592deac331cc5f277f6365501f7b3871de | /UVa/lcd.cpp | 159aaf1d00bfa9219e3f092ea17c72fe2417debb | []
| no_license | raphamontana/usp-raphael | 1ba2cb88737ae1730dd6e8c62a5c56f3da4cfe25 | 5ffff4ae5c60b69c1d0535d4c79c1c7dfa6dbf25 | refs/heads/master | 2021-01-01T06:38:42.606950 | 2010-05-11T23:59:08 | 2010-05-11T23:59:08 | 32,346,740 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 7,129 | cpp | /* ======================================================================== */
/* Raphael Montanari Nš USP: 5890010 */
/* ======================================================================== */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ZeraSaida (char saida [192] [112]) {
int i, j;
for (i = 0; i < 192; i++)
for (j = 0; j < 112; j++)
saida [i][j] = ' ';
}
void Imprime (char saida [192] [112], int tamanho, int ndigitos) {
int i, j;
int UltimaLinha = (2 * tamanho) + 3;
int UltimaColuna = ((tamanho + 3) * ndigitos) - 1;
for (i = 0; i < UltimaLinha; i++) {
for (j = 0; j < UltimaColuna; j++){
printf ("%c", saida [i] [j]);
}
printf ("\n");
}
printf ("\n");
}
void InsereDigito (char saida [192] [112], int tamanho, char digito, int posicao) {
int i, j;
int PrimeiraLinha = 0;
int LinhaMeio = tamanho + 1;
int UltimaLinha = (2 * tamanho) + 2;
int PrimeiraColuna = posicao;
int UltimaColuna = posicao + tamanho + 1;
switch (digito) {
case '0': {
for (j = (PrimeiraColuna + 1); j < UltimaColuna; j++) {
saida [PrimeiraLinha] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
break;
}
case '1': {
for (i = (PrimeiraLinha + 1); i < LinhaMeio; i++)
saida [i] [UltimaColuna] = '|';
for (i = (LinhaMeio + 1); i < UltimaLinha; i++)
saida [i] [UltimaColuna] = '|';
break;
}
case '2': {
for (i = (PrimeiraLinha + 1); i < LinhaMeio; i++)
saida [i] [UltimaColuna] = '|';
for (i = (LinhaMeio + 1); i < UltimaLinha; i++)
saida [i] [PrimeiraColuna] = '|';
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++) {
saida [PrimeiraLinha] [j] = '-';
saida [LinhaMeio] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
break;
}
case '3': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++) {
saida [PrimeiraLinha] [j] = '-';
saida [LinhaMeio] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
for (i = (PrimeiraLinha + 1); i < (UltimaLinha); i++)
saida [i] [UltimaColuna] = '|';
saida [LinhaMeio] [UltimaColuna] = ' ';
break;
}
case '4': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++)
saida [LinhaMeio] [j] = '-';
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++)
saida [i] [UltimaColuna] = '|';
break;
}
case '5': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++) {
saida [PrimeiraLinha] [j] = '-';
saida [LinhaMeio] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++)
saida [i] [PrimeiraColuna] = '|';
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++)
saida [i] [UltimaColuna] = '|';
break;
}
case '6': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++) {
saida [PrimeiraLinha] [j] = '-';
saida [LinhaMeio] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++)
saida [i] [PrimeiraColuna] = '|';
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
break;
}
case '7': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++)
saida [PrimeiraLinha] [j] = '-';
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++)
saida [i] [UltimaColuna] = '|';
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++)
saida [i] [UltimaColuna] = '|';
break;
}
case '8': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++) {
saida [PrimeiraLinha] [j] = '-';
saida [LinhaMeio] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
break;
}
case '9': {
for (j = (PrimeiraColuna + 1); j < (UltimaColuna); j++) {
saida [PrimeiraLinha] [j] = '-';
saida [LinhaMeio] [j] = '-';
saida [UltimaLinha] [j] = '-';
}
for (i = (PrimeiraLinha + 1); i < (LinhaMeio); i++) {
saida [i] [PrimeiraColuna] = '|';
saida [i] [UltimaColuna] = '|';
}
for (i = (LinhaMeio + 1); i < (UltimaLinha); i++)
saida [i] [UltimaColuna] = '|';
break;
}
default: break;
}
}
int main (void) {
int s, n;
int i, posicao, ndigitos = 0;
char impressao [192] [112];
char string [10];
while (scanf ("%d %s", &s, string ) != EOF) {
ndigitos = strlen (string);
if((s == 0) && (string[0] == '0') || (s > 10) || (ndigitos > 8) || (s == 0))
break;
ZeraSaida (impressao);
posicao = 0;
for (i = 0; i < ndigitos; i++) {
InsereDigito (impressao, s, string [i], posicao);
posicao += (s + 3);
}
Imprime (impressao, s, ndigitos);
}
return (0);
}
| [
"[email protected]@ba5301f2-bfe1-11dd-871e-457e4afae058"
]
| [
[
[
1,
185
]
]
]
|
a732da04e1dccc45a0fb8f54ac0d9cfd90739529 | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /include/QGLViewer/manipulatedCameraFrame.cpp | fb86d7c162659c89059eb79a0e5b3facfafd5f47 | []
| 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 | 15,486 | cpp | /****************************************************************************
Copyright (C) 2002-2008 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.3.1.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "domUtils.h"
#include "manipulatedCameraFrame.h"
#include "qglviewer.h"
#if QT_VERSION >= 0x040000
# include <QMouseEvent>
#endif
using namespace qglviewer;
using namespace std;
/*! Default constructor.
flySpeed() is set to 0.0 and flyUpVector() is (0,1,0). The revolveAroundPoint() is set to (0,0,0).
\attention Created object is removeFromMouseGrabberPool(). */
ManipulatedCameraFrame::ManipulatedCameraFrame()
: driveSpeed_(0.0), flyUpVector_(0.0, 1.0, 0.0)
{
setFlySpeed(0.0);
removeFromMouseGrabberPool();
connect(&flyTimer_, SIGNAL(timeout()), SLOT(flyUpdate()));
}
/*! Equal operator. Calls ManipulatedFrame::operator=() and then copy attributes. */
ManipulatedCameraFrame& ManipulatedCameraFrame::operator=(const ManipulatedCameraFrame& mcf)
{
ManipulatedFrame::operator=(mcf);
setFlySpeed(mcf.flySpeed());
setFlyUpVector(mcf.flyUpVector());
return *this;
}
/*! Copy constructor. Performs a deep copy of all members using operator=(). */
ManipulatedCameraFrame::ManipulatedCameraFrame(const ManipulatedCameraFrame& mcf)
: ManipulatedFrame(mcf)
{
removeFromMouseGrabberPool();
connect(&flyTimer_, SIGNAL(timeout()), SLOT(flyUpdate()));
(*this)=(mcf);
}
////////////////////////////////////////////////////////////////////////////////
/*! Overloading of ManipulatedFrame::spin().
Rotates the ManipulatedCameraFrame around its revolveAroundPoint() instead of its origin. */
void ManipulatedCameraFrame::spin()
{
rotateAroundPoint(spinningQuaternion(), revolveAroundPoint());
}
#ifndef DOXYGEN
/*! Called for continuous frame motion in fly mode (see QGLViewer::MOVE_FORWARD). Emits
manipulated(). */
void ManipulatedCameraFrame::flyUpdate()
{
static Vec flyDisp(0.0, 0.0, 0.0);
switch (action_)
{
case QGLViewer::MOVE_FORWARD:
flyDisp.z = -flySpeed();
translate(localInverseTransformOf(flyDisp));
break;
case QGLViewer::MOVE_BACKWARD:
flyDisp.z = flySpeed();
translate(localInverseTransformOf(flyDisp));
break;
case QGLViewer::DRIVE:
flyDisp.z = flySpeed() * driveSpeed_;
translate(localInverseTransformOf(flyDisp));
break;
default:
break;
}
// Needs to be out of the switch since ZOOM/fastDraw()/wheelEvent use this callback to trigger a final draw().
// #CONNECTION# wheelEvent.
emit manipulated();
}
#endif
/*! This method will be called by the Camera when its orientation is changed, so that the
flyUpVector (private) is changed accordingly. You should not need to call this method. */
void ManipulatedCameraFrame::updateFlyUpVector()
{
flyUpVector_ = inverseTransformOf(Vec(0.0, 1.0, 0.0));
}
////////////////////////////////////////////////////////////////////////////////
// S t a t e s a v i n g a n d r e s t o r i n g //
////////////////////////////////////////////////////////////////////////////////
/*! Returns an XML \c QDomElement that represents the ManipulatedCameraFrame.
Adds to the ManipulatedFrame::domElement() the ManipulatedCameraFrame specific informations in a \c
ManipulatedCameraParameters child QDomElement.
\p name is the name of the QDomElement tag. \p doc is the \c QDomDocument factory used to create
QDomElement.
Use initFromDOMElement() to restore the ManipulatedCameraFrame state from the resulting
\c QDomElement.
See Vec::domElement() for a complete example. See also Quaternion::domElement(),
Frame::domElement(), Camera::domElement()... */
QDomElement ManipulatedCameraFrame::domElement(const QString& name, QDomDocument& document) const
{
QDomElement e = ManipulatedFrame::domElement(name, document);
QDomElement mcp = document.createElement("ManipulatedCameraParameters");
mcp.setAttribute("flySpeed", QString::number(flySpeed()));
mcp.appendChild(flyUpVector().domElement("flyUpVector", document));
e.appendChild(mcp);
return e;
}
/*! Restores the ManipulatedCameraFrame state from a \c QDomElement created by domElement().
First calls ManipulatedFrame::initFromDOMElement() and then initializes ManipulatedCameraFrame
specific parameters. */
void ManipulatedCameraFrame::initFromDOMElement(const QDomElement& element)
{
// No need to initialize, since default flyUpVector and flySpeed are not meaningful.
// It's better to keep current ones. And it would destroy constraint() and referenceFrame().
// *this = ManipulatedCameraFrame();
ManipulatedFrame::initFromDOMElement(element);
QDomElement child=element.firstChild().toElement();
while (!child.isNull())
{
if (child.tagName() == "ManipulatedCameraParameters")
{
setFlySpeed(DomUtils::floatFromDom(child, "flySpeed", flySpeed()));
QDomElement schild=child.firstChild().toElement();
while (!schild.isNull())
{
if (schild.tagName() == "flyUpVector")
setFlyUpVector(Vec(schild));
schild = schild.nextSibling().toElement();
}
}
child = child.nextSibling().toElement();
}
}
////////////////////////////////////////////////////////////////////////////////
// M o u s e h a n d l i n g //
////////////////////////////////////////////////////////////////////////////////
#ifndef DOXYGEN
/*! Protected internal method used to handle mouse events. */
void ManipulatedCameraFrame::startAction(int ma, bool withConstraint)
{
ManipulatedFrame::startAction(ma, withConstraint);
switch (action_)
{
case QGLViewer::MOVE_FORWARD:
case QGLViewer::MOVE_BACKWARD:
case QGLViewer::DRIVE:
#if QT_VERSION >= 0x040000
flyTimer_.setSingleShot(false);
#endif
flyTimer_.start(10);
break;
default:
break;
}
}
#endif
/*! Overloading of ManipulatedFrame::mouseMoveEvent().
Motion depends on mouse binding (see <a href="../mouse.html">mouse page</a> for details). The
resulting displacements are basically inverted from those of a ManipulatedFrame. */
void ManipulatedCameraFrame::mouseMoveEvent(QMouseEvent* const event, Camera* const camera)
{
// #CONNECTION# QGLViewer::mouseMoveEvent does the updateGL.
switch (action_)
{
case QGLViewer::TRANSLATE:
{
const QPoint delta = prevPos_ - event->pos();
Vec trans(static_cast<float>(delta.x()), static_cast<float>(-delta.y()), 0.0);
// Scale to fit the screen mouse displacement
switch (camera->type())
{
case Camera::PERSPECTIVE :
trans *= 2.0 * tan(camera->fieldOfView()/2.0) *
fabs((camera->frame()->coordinatesOf(revolveAroundPoint())).z) / camera->screenHeight();
break;
case Camera::ORTHOGRAPHIC :
{
GLdouble w,h;
camera->getOrthoWidthHeight(w, h);
trans[0] *= 2.0 * w / camera->screenWidth();
trans[1] *= 2.0 * h / camera->screenHeight();
break;
}
}
translate(inverseTransformOf(translationSensitivity()*trans));
break;
}
case QGLViewer::MOVE_FORWARD:
{
Quaternion rot = pitchYawQuaternion(event->x(), event->y(), camera);
rotate(rot);
//#CONNECTION# wheelEvent MOVE_FORWARD case
// actual translation is made in flyUpdate().
//translate(inverseTransformOf(Vec(0.0, 0.0, -flySpeed())));
break;
}
case QGLViewer::MOVE_BACKWARD:
{
Quaternion rot = pitchYawQuaternion(event->x(), event->y(), camera);
rotate(rot);
// actual translation is made in flyUpdate().
//translate(inverseTransformOf(Vec(0.0, 0.0, flySpeed())));
break;
}
case QGLViewer::DRIVE:
{
Quaternion rot = turnQuaternion(event->x(), camera);
rotate(rot);
// actual translation is made in flyUpdate().
driveSpeed_ = 0.01 * (event->y() - pressPos_.y());
break;
}
case QGLViewer::ZOOM:
{
//#CONNECTION# wheelEvent() ZOOM case
const float coef = qMax(fabsf((camera->frame()->coordinatesOf(camera->revolveAroundPoint())).z), 0.2f*camera->sceneRadius());
Vec trans(0.0, 0.0, -coef * (event->y() - prevPos_.y()) / camera->screenHeight());
translate(inverseTransformOf(trans));
break;
}
case QGLViewer::LOOK_AROUND:
{
Quaternion rot = pitchYawQuaternion(event->x(), event->y(), camera);
rotate(rot);
break;
}
case QGLViewer::ROTATE:
{
Vec trans = camera->projectedCoordinatesOf(revolveAroundPoint());
Quaternion rot = deformedBallQuaternion(event->x(), event->y(), trans[0], trans[1], camera);
//#CONNECTION# These two methods should go together (spinning detection and activation)
computeMouseSpeed(event);
setSpinningQuaternion(rot);
spin();
break;
}
case QGLViewer::SCREEN_ROTATE:
{
Vec trans = camera->projectedCoordinatesOf(revolveAroundPoint());
const float angle = atan2(event->y() - trans[1], event->x() - trans[0]) - atan2(prevPos_.y()-trans[1], prevPos_.x()-trans[0]);
Quaternion rot(Vec(0.0, 0.0, 1.0), angle);
//#CONNECTION# These two methods should go together (spinning detection and activation)
computeMouseSpeed(event);
setSpinningQuaternion(rot);
spin();
updateFlyUpVector();
break;
}
case QGLViewer::ROLL:
{
const float angle = M_PI * (event->x() - prevPos_.x()) / camera->screenWidth();
Quaternion rot(Vec(0.0, 0.0, 1.0), angle);
rotate(rot);
setSpinningQuaternion(rot);
updateFlyUpVector();
break;
}
case QGLViewer::SCREEN_TRANSLATE:
{
Vec trans;
int dir = mouseOriginalDirection(event);
if (dir == 1)
trans.setValue(static_cast<float>(prevPos_.x() - event->x()), 0.0, 0.0);
else if (dir == -1)
trans.setValue(0.0, static_cast<float>(event->y() - prevPos_.y()), 0.0);
switch (camera->type())
{
case Camera::PERSPECTIVE :
trans *= 2.0 * tan(camera->fieldOfView()/2.0) *
fabs((camera->frame()->coordinatesOf(revolveAroundPoint())).z) / camera->screenHeight();
break;
case Camera::ORTHOGRAPHIC :
{
GLdouble w,h;
camera->getOrthoWidthHeight(w, h);
trans[0] *= 2.0 * w / camera->screenWidth();
trans[1] *= 2.0 * h / camera->screenHeight();
break;
}
}
translate(inverseTransformOf(translationSensitivity()*trans));
break;
}
case QGLViewer::ZOOM_ON_REGION:
case QGLViewer::NO_MOUSE_ACTION:
break;
}
if (action_ != QGLViewer::NO_MOUSE_ACTION)
{
prevPos_ = event->pos();
if (action_ != QGLViewer::ZOOM_ON_REGION)
// ZOOM_ON_REGION should not emit manipulated().
// prevPos_ is used to draw rectangle feedback.
emit manipulated();
}
}
/*! This is an overload of ManipulatedFrame::mouseReleaseEvent(). The QGLViewer::MouseAction is
terminated. */
void ManipulatedCameraFrame::mouseReleaseEvent(QMouseEvent* const event, Camera* const camera)
{
if ((action_ == QGLViewer::MOVE_FORWARD) || (action_ == QGLViewer::MOVE_BACKWARD) || (action_ == QGLViewer::DRIVE))
flyTimer_.stop();
if (action_ == QGLViewer::ZOOM_ON_REGION)
camera->fitScreenRegion(QRect(pressPos_, event->pos()));
ManipulatedFrame::mouseReleaseEvent(event, camera);
}
/*! This is an overload of ManipulatedFrame::wheelEvent().
The wheel behavior depends on the wheel binded action. Current possible actions are QGLViewer::ZOOM,
QGLViewer::MOVE_FORWARD, QGLViewer::MOVE_BACKWARD. QGLViewer::ZOOM speed depends on
wheelSensitivity() while QGLViewer::MOVE_FORWARD and QGLViewer::MOVE_BACKWARD depend on flySpeed().
See QGLViewer::setWheelBinding() to customize the binding. */
void ManipulatedCameraFrame::wheelEvent(QWheelEvent* const event, Camera* const camera)
{
//#CONNECTION# QGLViewer::setWheelBinding, ManipulatedFrame::wheelEvent.
switch (action_)
{
case QGLViewer::ZOOM:
{
const float wheelSensitivityCoef = 8E-4f;
//#CONNECTION# mouseMoveEvent() ZOOM case
const float coef = qMax(fabsf((camera->frame()->coordinatesOf(camera->revolveAroundPoint())).z), 0.2f*camera->sceneRadius());
Vec trans(0.0, 0.0, coef * event->delta() * wheelSensitivity() * wheelSensitivityCoef);
translate(inverseTransformOf(trans));
emit manipulated();
break;
}
case QGLViewer::MOVE_FORWARD:
case QGLViewer::MOVE_BACKWARD:
//#CONNECTION# mouseMoveEvent() MOVE_FORWARD case
translate(inverseTransformOf(Vec(0.0, 0.0, 0.2*flySpeed()*event->delta())));
emit manipulated();
break;
default:
break;
}
// #CONNECTION# startAction should always be called before
if (previousConstraint_)
setConstraint(previousConstraint_);
// The wheel triggers a fastDraw. A final updateGL is needed after the last wheel event to
// polish the rendering using draw(). Since the last wheel event does not say its name, we use
// the flyTimer_ to trigger flyUpdate(), which emits manipulated. Two wheel events
// separated by more than this delay milliseconds will trigger a draw().
const int finalDrawAfterWheelEventDelay = 400;
// Starts (or prolungates) the timer.
#if QT_VERSION >= 0x040000
flyTimer_.setSingleShot(true);
flyTimer_.start(finalDrawAfterWheelEventDelay);
#else
flyTimer_.start(finalDrawAfterWheelEventDelay, true);
#endif
// This could also be done *before* manipulated is emitted, so that isManipulated() returns false.
// But then fastDraw would not be used with wheel.
// Detecting the last wheel event and forcing a final draw() is done using the timer_.
action_ = QGLViewer::NO_MOUSE_ACTION;
}
////////////////////////////////////////////////////////////////////////////////
/*! Returns a Quaternion that is a rotation around current camera Y, proportionnal to the horizontal mouse position. */
Quaternion ManipulatedCameraFrame::turnQuaternion(int x, const Camera* const camera)
{
return Quaternion(Vec(0.0, 1.0, 0.0), rotationSensitivity()*(prevPos_.x()-x)/camera->screenWidth());
}
/*! Returns a Quaternion that is the composition of two rotations, inferred from the
mouse pitch (X axis) and yaw (flyUpVector() axis). */
Quaternion ManipulatedCameraFrame::pitchYawQuaternion(int x, int y, const Camera* const camera)
{
const Quaternion rotX(Vec(1.0, 0.0, 0.0), rotationSensitivity()*(prevPos_.y()-y)/camera->screenHeight());
const Quaternion rotY(transformOf(flyUpVector()), rotationSensitivity()*(prevPos_.x()-x)/camera->screenWidth());
return rotY * rotX;
}
| [
"balint.miklos@localhost"
]
| [
[
[
1,
441
]
]
]
|
2141bbb7c3a81e1e0d28bd0ecfd674ae5a3ee1c2 | 880e5a47c23523c8e5ba1602144ea1c48c8c8f9a | /enginesrc/operating_system/systemresolution.hpp | ef64d34a346628080b34edf2bf2d45acbc297240 | []
| no_license | kfazi/Engine | 050cb76826d5bb55595ecdce39df8ffb2d5547f8 | 0cedfb3e1a9a80fd49679142be33e17186322290 | refs/heads/master | 2020-05-20T10:02:29.050190 | 2010-02-11T17:45:42 | 2010-02-11T17:45:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | hpp | #ifndef ENGINE_SYSTEM_RESOLUTION_HPP
#define ENGINE_SYSTEM_RESOLUTION_HPP
#include "../common.hpp"
namespace engine
{
class DLLEXPORTIMPORT CSystemResolution
{
private:
unsigned int m_iWidth;
unsigned int m_iHeight;
unsigned int m_iBPP;
unsigned int m_iRefreshRate;
public:
CSystemResolution(unsigned int iWidth, unsigned int iHeight, unsigned int iBPP, unsigned int iRefreshRate);
unsigned int GetWidth() const;
unsigned int GetHeight() const;
unsigned int GetBPP() const;
unsigned int GetRefreshRate() const;
bool operator < (const CSystemResolution &cResolution) const;
bool operator == (const CSystemResolution &cResolution) const;
static bool LessThanPointer(const CSystemResolution *pLeft, const CSystemResolution *pRight);
static bool EqualToPointer(const CSystemResolution *pLeft, const CSystemResolution *pRight);
};
}
#endif /* ENGINE_SYSTEM_RESOLUTION_HPP */
/* EOF */
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
e7dfdb41a83f30e5d1be7b6385c7262320c03ec8 | a30b091525dc3f07cd7e12c80b8d168a0ee4f808 | /EngineAll/Victor/GeneralizedEigensystems.cpp | dc3b6371295563fbd11998a49351f2d8637731c9 | []
| no_license | ghsoftco/basecode14 | f50dc049b8f2f8d284fece4ee72f9d2f3f59a700 | 57de2a24c01cec6dc3312cbfe200f2b15d923419 | refs/heads/master | 2021-01-10T11:18:29.585561 | 2011-01-23T02:25:21 | 2011-01-23T02:25:21 | 47,255,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 78,309 | cpp | #include <iostream>
#include <limits>
#include "TBLAS.h"
#include "TLASupport.h"
#include "GeneralizedEigensystems.h"
#include <cmath>
#include <complex>
#include <algorithm>
static inline double _abs1(const std::complex<double> &z){
return fabs(z.real()) + fabs(z.imag());
}
static void zggbal_(const char *job, size_t n, std::complex<double> *a, size_t
lda, std::complex<double> *b, size_t ldb, int *ilo, int *ihi,
double *lscale, double *rscale, double *work)
{
using namespace std;
int i, j, k, l;
int ip1, jp1;
/* ZGGBAL balances a pair of general complex matrices (A,B). This */
/* involves, first, permuting A and B by similarity transformations to */
/* isolate eigenvalues in the first 1 to ILO$-$1 and last IHI+1 to N */
/* elements on the diagonal; and second, applying a diagonal similarity */
/* transformation to rows and columns ILO to IHI to make the rows */
/* and columns as close in norm as possible. Both steps are optional. */
/* Balancing may reduce the 1-norm of the matrices, and improve the */
/* accuracy of the computed eigenvalues and/or eigenvectors in the */
/* generalized eigenvalue problem A*x = lambda*B*x. */
/* Arguments */
/* ========= */
/* JOB (input) CHARACTER*1 */
/* Specifies the operations to be performed on A and B: */
/* = 'N': none: simply set ILO = 1, IHI = N, LSCALE(I) = 1.0 */
/* and RSCALE(I) = 1.0 for i=1,...,N; */
/* = 'P': permute only; */
/* = 'S': scale only; */
/* = 'B': both permute and scale. */
/* N (input) INTEGER */
/* The order of the matrices A and B. N >= 0. */
/* A (input/output) COMPLEX*16 array, dimension (LDA,N) */
/* On entry, the input matrix A. */
/* On exit, A is overwritten by the balanced matrix. */
/* If JOB = 'N', A is not referenced. */
/* LDA (input) INTEGER */
/* The leading dimension of the array A. LDA >= max(1,N). */
/* B (input/output) COMPLEX*16 array, dimension (LDB,N) */
/* On entry, the input matrix B. */
/* On exit, B is overwritten by the balanced matrix. */
/* If JOB = 'N', B is not referenced. */
/* LDB (input) INTEGER */
/* The leading dimension of the array B. LDB >= max(1,N). */
/* ILO (output) INTEGER */
/* IHI (output) INTEGER */
/* ILO and IHI are set to integers such that on exit */
/* A(i,j) = 0 and B(i,j) = 0 if i > j and */
/* j = 1,...,ILO-1 or i = IHI+1,...,N. */
/* If JOB = 'N' or 'S', ILO = 1 and IHI = N. */
/* LSCALE (output) DOUBLE PRECISION array, dimension (N) */
/* Details of the permutations and scaling factors applied */
/* to the left side of A and B. If P(j) is the index of the */
/* row interchanged with row j, and D(j) is the scaling factor */
/* applied to row j, then */
/* LSCALE(j) = P(j) for J = 1,...,ILO-1 */
/* = D(j) for J = ILO,...,IHI */
/* = P(j) for J = IHI+1,...,N. */
/* The order in which the interchanges are made is N to IHI+1, */
/* then 1 to ILO-1. */
/* RSCALE (output) DOUBLE PRECISION array, dimension (N) */
/* Details of the permutations and scaling factors applied */
/* to the right side of A and B. If P(j) is the index of the */
/* column interchanged with column j, and D(j) is the scaling */
/* factor applied to column j, then */
/* RSCALE(j) = P(j) for J = 1,...,ILO-1 */
/* = D(j) for J = ILO,...,IHI */
/* = P(j) for J = IHI+1,...,N. */
/* The order in which the interchanges are made is N to IHI+1, */
/* then 1 to ILO-1. */
/* WORK (workspace) REAL array, dimension (lwork) */
/* lwork must be at least max(1,6n) when JOB = 'S' or 'B', and */
/* at least 1 when JOB = 'N' or 'P'. */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument had an illegal value. */
/* Further Details */
/* =============== */
/* See R.C. WARD, Balancing the generalized eigenvalue problem, */
/* SIAM J. Sci. Stat. Comp. 2 (1981), 141-152. */
/* ===================================================================== */
/* Test the input parameters */
/* Parameter adjustments */
size_t a_offset = 1 + lda;
a -= a_offset;
size_t b_offset = 1 + ldb;
b -= b_offset;
--lscale;
--rscale;
--work;
/* Quick return if possible */
if (n == 0) {
*ilo = 1;
*ihi = n;
return;
}
if (n == 1) {
*ilo = 1;
*ihi = n;
lscale[1] = 1.;
rscale[1] = 1.;
return;
}
if (job[0] == 'N'){
*ilo = 1;
*ihi = n;
for (i = 1; i <= (int)n; ++i) {
lscale[i] = 1.;
rscale[i] = 1.;
}
return;
}
l = n;
if (job[0] != 'S') {
// Permute the matrices A and B to isolate the eigenvalues.
// Find row with one nonzero in columns 1 through L
bool found_row_perm;
do{
found_row_perm = false;
for (i = l; i >= 1; --i) {
bool found = false;
for (j = 1; j <= l-1; ++j) {
jp1 = j + 1;
if ((0. != a[i+j*lda]) || (0. != b[i+j*ldb])) {
// We found a nonzero in column j, to the left of (i,l)
found = true;
break;
}
}
if(!found){
j = l;
}else{
bool found2 = false;
for (j = jp1; j <= l; ++j) {
if ((0. != a[i+j*lda]) || (0. != b[i+j*ldb])) {
// We found another nonzero in column j, between the first nonzero and (i,l+1)
found2 = true;
break;
}
}
if(found2){
// We found more than 1 nonzero, so let's try the next row up
continue;
}else{
j = jp1 - 1;
}
}
int m = l;
// Permute rows M and I
lscale[m] = (double) i;
if (i != m) {
RNP::TBLAS::Swap(n, &a[i + 1 * lda], lda, &a[m + 1 * lda], lda);
RNP::TBLAS::Swap(n, &b[i + 1 * ldb], ldb, &b[m + 1 * ldb], ldb);
}
// Permute columns M and J
rscale[m] = (double) j;
if (j != m) {
RNP::TBLAS::Swap(l, &a[j * lda + 1], 1, &a[m * lda + 1], 1);
RNP::TBLAS::Swap(l, &b[j * ldb + 1], 1, &b[m * ldb + 1], 1);
}
--l;
if (l == 1) {
// We have completely deflated the matrix from bottom up
rscale[1] = 1.;
lscale[1] = 1.;
}else{
found_row_perm = true;
}
break;
}
}while(found_row_perm);
// Find column with one nonzero in rows K through N */
k = 1;
bool found_col_perm;
do{
found_col_perm = false;
for (j = k; j <= l; ++j) {
bool found = false;
for (i = k; i <= l-1; ++i) {
ip1 = i + 1;
if ((0. != a[i+j*lda]) || (0. != b[i+j*ldb])) {
found = true;
break;
}
}
if(!found){
i = l;
}else{
bool found2 = false;
for (i = ip1; i <= l; ++i) {
if ((0. != a[i+j*lda]) || (0. != b[i+j*ldb])) {
found2 = true;
break;
}
}
if(found2){
continue;
}else{
i = ip1 - 1;
}
}
int m = k;
// Permute rows M and I
lscale[m] = (double) i;
if (i != m) {
RNP::TBLAS::Swap(n - k + 1, &a[i + k * lda], lda, &a[m + k * lda], lda);
RNP::TBLAS::Swap(n - k + 1, &b[i + k * ldb], ldb, &b[m + k * ldb], ldb);
}
// Permute columns M and J
rscale[m] = (double) j;
if (j != m) {
RNP::TBLAS::Swap(l, &a[j * lda + 1], 1, &a[m * lda + 1], 1);
RNP::TBLAS::Swap(l, &b[j * ldb + 1], 1, &b[m * ldb + 1], 1);
}
++k;
found_col_perm = true;
break;
}
}while(found_col_perm);
}
// End of permutations
*ilo = k;
*ihi = l;
if (job[0] == 'P') { // if permutations was all that was requested, end here
for (i = *ilo; i <= *ihi; ++i) {
lscale[i] = 1.;
rscale[i] = 1.;
}
return;
}
if (*ilo == *ihi) {
return;
}
// Balance the submatrix in rows ILO to IHI.
const size_t nr = *ihi - *ilo + 1;
for (i = *ilo; i <= *ihi; ++i) {
rscale[i] = 0.;
lscale[i] = 0.;
work[i] = 0.;
work[i + n] = 0.;
work[i + 2*n] = 0.;
work[i + n * 3] = 0.;
work[i + 2*n] = 0.;
work[i + n * 5] = 0.;
}
// Compute right side vector in resulting linear equations
for (i = *ilo; i <= *ihi; ++i) {
for (j = *ilo; j <= *ihi; ++j) {
double ta;
if (0. == a[i+j*lda]) {
ta = 0.;
}else{
ta = log10(_abs1(a[i+j*lda]));
}
double tb;
if (0. == b[i+j*ldb]) {
tb = 0.;
}else{
tb = log10(_abs1(b[i+j*ldb]));
}
work[i + 2*n] = work[i + 2*n] - ta - tb;
work[j + n * 5] = work[j + n * 5] - ta - tb;
}
}
const double coef = 1. / (double) (2*nr);
const double coef2 = coef * coef;
const double coef5 = coef2 * .5;
double beta = 0.;
const size_t nrp2 = nr + 2; // iteration limit
size_t it = 1;
double gamma_prev = 1;
do{ // Start generalized conjugate gradient iteration
double gamma = RNP::TBLAS::Dot(nr, &work[*ilo + 2*n], 1, &work[*ilo + 2*n], 1)
+ RNP::TBLAS::Dot(nr, &work[*ilo + n * 5], 1, &work[*ilo + n * 5], 1);
double ew = 0.;
double ewc = 0.;
for (i = *ilo; i <= *ihi; ++i) {
ew += work[i + 2*n];
ewc += work[i + n * 5];
}
double diff = ew - ewc;
gamma = coef * gamma - coef2 * (ew*ew + ewc*ewc) - coef5 * (diff*diff);
if (gamma == 0.) {
break;
}
if (it > 1) {
beta = gamma / gamma_prev;
}
double t = coef5 * (ewc - ew * 3.);
double tc = coef5 * (ew - ewc * 3.);
RNP::TBLAS::Scale(nr, beta, &work[*ilo], 1);
RNP::TBLAS::Scale(nr, beta, &work[*ilo + n], 1);
RNP::TBLAS::Axpy(nr, coef, &work[*ilo + 2*n], 1, &work[*ilo + n], 1);
RNP::TBLAS::Axpy(nr, coef, &work[*ilo + n * 5], 1, &work[*ilo], 1);
for (i = *ilo; i <= *ihi; ++i) {
work[i] += tc;
work[i + n] += t;
}
// Apply matrix to vector
for (i = *ilo; i <= *ihi; ++i) {
int kount = 0;
double sum = 0.;
for (j = *ilo; j <= *ihi; ++j) {
if (0. != a[i+j*lda]) {
++kount;
sum += work[j];
}
if (0. != b[i+j*ldb]) {
++kount;
sum += work[j];
}
}
work[i + 2*n] = (double) kount * work[i + n] + sum;
}
for (j = *ilo; j <= *ihi; ++j) {
int kount = 0;
double sum = 0.;
for (i = *ilo; i <= *ihi; ++i) {
if (0. != a[i+j*lda]) {
++kount;
sum += work[i + n];
}
if (0. != b[i+j*ldb]) {
++kount;
sum += work[i + n];
}
}
work[j + 3*n] = (double) kount * work[j] + sum;
}
double sum = RNP::TBLAS::Dot(nr, &work[*ilo + n], 1, &work[*ilo + 2*n], 1)
+ RNP::TBLAS::Dot(nr, &work[*ilo], 1, &work[*ilo + 3*n], 1);
double alpha = gamma / sum;
// Determine correction to current iteration
double cmax = 0.;
for (i = *ilo; i <= *ihi; ++i) {
double cor = alpha * work[i + n];
if (abs(cor) > cmax) {
cmax = abs(cor);
}
lscale[i] += cor;
cor = alpha * work[i];
if (abs(cor) > cmax) {
cmax = abs(cor);
}
rscale[i] += cor;
}
if (cmax < .5) {
break;
}
RNP::TBLAS::Axpy(nr, -alpha, &work[*ilo + 2*n], 1, &work[*ilo + 2*n], 1);
RNP::TBLAS::Axpy(nr, -alpha, &work[*ilo + 3*n], 1, &work[*ilo + 5*n], 1);
gamma_prev = gamma;
++it;
}while(it <= nrp2); // End generalized conjugate gradient iteration
const double sfmin = std::numeric_limits<double>::min();
const double sfmax = 1. / sfmin;
const int lsfmin = (int) (log10(sfmin) + 1.);
const int lsfmax = (int) (log10(sfmax));
for (i = *ilo; i <= *ihi; ++i) {
double da;
size_t irab = 1+RNP::TBLAS::MaximumIndex(n - *ilo + 1, (std::complex<double>*)&a[i + *ilo * lda], lda);
double rab = abs(a[i + (irab + *ilo - 1) * lda]);
irab = 1+RNP::TBLAS::MaximumIndex(n - *ilo + 1, (std::complex<double>*)&b[i + *ilo * ldb], ldb);
da = abs(b[i + (irab + *ilo - 1) * ldb]);
if(da > rab){ rab = da; }
int lrab = (int)(log10(rab + sfmin) + 1.);
int ir;
if(lscale[i] >= 0){
ir = (int) (lscale[i] + 0.5);
}else{
ir = (int) (lscale[i] - 0.5);
}
if(lsfmin > ir){ ir = lsfmin; }
if(lsfmax < ir){ ir = lsfmax; }
if(lsfmax-lrab < ir){ ir = lsfmax-lrab; }
lscale[i] = pow(10., ir);
size_t icab = 1+RNP::TBLAS::MaximumIndex(*ihi, (std::complex<double>*)&a[i * lda + 1], 1);
double cab = abs(a[icab + i * lda]);
icab = 1+RNP::TBLAS::MaximumIndex(*ihi, (std::complex<double>*)&b[i * ldb + 1], 1);
da = abs(b[icab + i * ldb]);
if(da > cab){ cab = da; }
int lcab = (int) (log10(cab + sfmin) + 1.);
int jc;
if(rscale[i] >= 0){
jc = (int) (rscale[i] + 0.5);
}else{
jc = (int) (rscale[i] - 0.5);
}
if(lsfmin > jc){ jc = lsfmin; }
if(lsfmax < jc){ jc = lsfmax; }
if(lsfmax-lcab < jc){ jc = lsfmax-lcab; }
rscale[i] = pow(10., jc);
}
// Row scaling of matrices A and B
for (i = *ilo; i <= *ihi; ++i) {
RNP::TBLAS::Scale(n - *ilo + 1, lscale[i], (std::complex<double>*)&a[i + *ilo * lda], lda);
RNP::TBLAS::Scale(n - *ilo + 1, lscale[i], (std::complex<double>*)&b[i + *ilo * ldb], ldb);
}
// Column scaling of matrices A and B
for (j = *ilo; j <= *ihi; ++j) {
RNP::TBLAS::Scale(*ihi, rscale[j], (std::complex<double>*)&a[j * lda + 1], 1);
RNP::TBLAS::Scale(*ihi, rscale[j], (std::complex<double>*)&b[j * ldb + 1], 1);
}
}
void zggbak_(char *job, char *side, int n, int ilo,
int ihi, const double *lscale, const double *rscale, int m,
std::complex<double> *v, int ldv)
{
using namespace std;
// Purpose
// =======
// ZGGBAK forms the right or left eigenvectors of a complex generalized
// eigenvalue problem A*x = lambda*B*x, by backward transformation on
// the computed eigenvectors of the balanced pair of matrices output by
// ZGGBAL.
// Arguments
// =========
// JOB (input) CHARACTER*1
// Specifies the type of backward transformation required:
// = 'N': do nothing, return immediately;
// = 'P': do backward transformation for permutation only;
// = 'S': do backward transformation for scaling only;
// = 'B': do backward transformations for both permutation and scaling.
// JOB must be the same as the argument JOB supplied to ZGGBAL.
// SIDE (input) CHARACTER*1
// = 'R': V contains right eigenvectors;
// = 'L': V contains left eigenvectors.
// N (input) int
// The number of rows of the matrix V. N >= 0.
// ILO (input) int
// IHI (input) int
// The ints ILO and IHI determined by ZGGBAL.
// 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0.
// LSCALE (input) DOUBLE PRECISION array, dimension (N)
// Details of the permutations and/or scaling factors applied
// to the left side of A and B, as returned by ZGGBAL.
// RSCALE (input) DOUBLE PRECISION array, dimension (N)
// Details of the permutations and/or scaling factors applied
// to the right side of A and B, as returned by ZGGBAL.
// M (input) int
// The number of columns of the matrix V. M >= 0.
// V (input/output) COMPLEX*16 array, dimension (LDV,M)
// On entry, the matrix of right or left eigenvectors to be
// transformed, as returned by ZTGEVC.
// On exit, V is overwritten by the transformed eigenvectors.
// LDV (input) int
// The leading dimension of the matrix V. LDV >= max(1,N).
// INFO (output) int
// = 0: successful exit.
// < 0: if INFO = -i, the i-th argument had an illegal value.
// Further Details
// ===============
// See R.C. Ward, Balancing the generalized eigenvalue problem,
// SIAM J. Sci. Stat. Comp. 2 (1981), 141-152.
int v_offset = 1 + ldv;
v -= v_offset;
const bool rightv = (side[0] == 'R');
const bool leftv = (side[0] == 'L');
if (n == 0 || m == 0 || job[0] == 'N') {
return;
}
if (ilo != ihi) {
// Backward balance
if ((job[0] == 'S') || (job[0] == 'B')) {
// Backward transformation on right eigenvectors
if (rightv) {
for (int i = ilo; i <= ihi; ++i) {
RNP::TBLAS::Scale(m, rscale[i-1], &v[i + ldv], ldv);
}
}
// Backward transformation on left eigenvectors
if (leftv) {
for (int i = ilo; i <= ihi; ++i) {
RNP::TBLAS::Scale(m, lscale[i-1], &v[i + ldv], ldv);
}
}
}
}
// Backward permutation
if ((job[0] == 'P') || (job[0] == 'B')) {
// Backward permutation on right eigenvectors
if (rightv) {
if (ilo != 1) {
for (int i = ilo - 1; i >= 1; --i) {
int k = (int) rscale[i-1];
if (k != i) {
RNP::TBLAS::Swap(m, &v[i + ldv], ldv, &v[k + ldv], ldv);
}
}
}
if (ihi != n) {
for (int i = ihi + 1; i <= n; ++i) {
int k = (int) rscale[i-1];
if (k != i) {
RNP::TBLAS::Swap(m, &v[i + ldv], ldv, &v[k + ldv], ldv);
}
}
}
}
// Backward permutation on left eigenvectors
if (leftv) {
if (ilo != 1) {
for (int i = ilo - 1; i >= 1; --i) {
int k = (int) lscale[i-1];
if (k != i) {
RNP::TBLAS::Swap(m, &v[i + ldv], ldv, &v[k + ldv], ldv);
}
}
}
if (ihi != n) {
for (int i = ihi + 1; i <= n; ++i) {
int k = (int) lscale[i-1];
if (k != i) {
RNP::TBLAS::Swap(m, &v[i + ldv], ldv, &v[k + ldv], ldv);
}
}
}
}
}
}
static int zhgeqz_(char *job, char *compq, char *compz, size_t n,
size_t ilo, size_t ihi, std::complex<double> *h, size_t ldh,
std::complex<double> *t, size_t ldt, std::complex<double> *alpha, std::complex<double> *
beta, std::complex<double> *q, size_t ldq, std::complex<double> *z, size_t
ldz, std::complex<double> *work, size_t lwork, double *rwork)
{
using namespace std;
// System generated locals
size_t h_offset, q_offset, t_offset, z_offset;
// Local variables
double c;
int j;
std::complex<double> s;
int jc;
int jr;
int jch;
bool ilq, ilz;
std::complex<double> ctemp;
bool ilschr;
int icompq, ilastm;
int ischur;
int icompz, ifirst;
int ifrstm;
// ZHGEQZ computes the eigenvalues of a complex matrix pair (H,T),
// where H is an upper Hessenberg matrix and T is upper triangular,
// using the single-shift QZ method.
// Matrix pairs of this type are produced by the reduction to
// generalized upper Hessenberg form of a complex matrix pair (A,B):
// A = Q1*H*Z1**H, B = Q1*T*Z1**H,
// as computed by ZGGHRD.
// If JOB='S', then the Hessenberg-triangular pair (H,T) is
// also reduced to generalized Schur form,
// H = Q*S*Z**H, T = Q*P*Z**H,
// where Q and Z are unitary matrices and S and P are upper triangular.
// Optionally, the unitary matrix Q from the generalized Schur
// factorization may be postmultiplied into an input matrix Q1, and the
// unitary matrix Z may be postmultiplied into an input matrix Z1.
// If Q1 and Z1 are the unitary matrices from ZGGHRD that reduced
// the matrix pair (A,B) to generalized Hessenberg form, then the output
// matrices Q1*Q and Z1*Z are the unitary factors from the generalized
// Schur factorization of (A,B):
// A = (Q1*Q)*S*(Z1*Z)**H, B = (Q1*Q)*P*(Z1*Z)**H.
// To avoid overflow, eigenvalues of the matrix pair (H,T)
// (equivalently, of (A,B)) are computed as a pair of complex values
// (alpha,beta). If beta is nonzero, lambda = alpha / beta is an
// eigenvalue of the generalized nonsymmetric eigenvalue problem (GNEP)
// A*x = lambda*B*x
// and if alpha is nonzero, mu = beta / alpha is an eigenvalue of the
// alternate form of the GNEP
// mu*A*y = B*y.
// The values of alpha and beta for the i-th eigenvalue can be read
// directly from the generalized Schur form: alpha = S(i,i),
// beta = P(i,i).
// Ref: C.B. Moler & G.W. Stewart, "An Algorithm for Generalized Matrix
// Eigenvalue Problems", SIAM J. Numer. Anal., 10(1973),
// pp. 241--256.
// Arguments
// =========
// JOB (input) CHARACTER*1
// = 'E': Compute eigenvalues only;
// = 'S': Computer eigenvalues and the Schur form.
// COMPQ (input) CHARACTER*1
// = 'N': Left Schur vectors (Q) are not computed;
// = 'I': Q is initialized to the unit matrix and the matrix Q
// of left Schur vectors of (H,T) is returned;
// = 'V': Q must contain a unitary matrix Q1 on entry and
// the product Q1*Q is returned.
// COMPZ (input) CHARACTER*1
// = 'N': Right Schur vectors (Z) are not computed;
// = 'I': Q is initialized to the unit matrix and the matrix Z
// of right Schur vectors of (H,T) is returned;
// = 'V': Z must contain a unitary matrix Z1 on entry and
// the product Z1*Z is returned.
// N (input) INTEGER
// The order of the matrices H, T, Q, and Z. N >= 0.
// ILO (input) INTEGER
// IHI (input) INTEGER
// ILO and IHI mark the rows and columns of H which are in
// Hessenberg form. It is assumed that A is already upper
// triangular in rows and columns 1:ILO-1 and IHI+1:N.
// If N > 0, 1 <= ILO <= IHI <= N; if N = 0, ILO=1 and IHI=0.
// H (input/output) COMPLEX*16 array, dimension (LDH, N)
// On entry, the N-by-N upper Hessenberg matrix H.
// On exit, if JOB = 'S', H contains the upper triangular
// matrix S from the generalized Schur factorization.
// If JOB = 'E', the diagonal of H matches that of S, but
// the rest of H is unspecified.
// LDH (input) INTEGER
// The leading dimension of the array H. LDH >= max( 1, N ).
// T (input/output) COMPLEX*16 array, dimension (LDT, N)
// On entry, the N-by-N upper triangular matrix T.
// On exit, if JOB = 'S', T contains the upper triangular
// matrix P from the generalized Schur factorization.
// If JOB = 'E', the diagonal of T matches that of P, but
// the rest of T is unspecified.
// LDT (input) INTEGER
// The leading dimension of the array T. LDT >= max( 1, N ).
// ALPHA (output) COMPLEX*16 array, dimension (N)
// The complex scalars alpha that define the eigenvalues of
// GNEP. ALPHA(i) = S(i,i) in the generalized Schur
// factorization.
// BETA (output) COMPLEX*16 array, dimension (N)
// The real non-negative scalars beta that define the
// eigenvalues of GNEP. BETA(i) = P(i,i) in the generalized
// Schur factorization.
// Together, the quantities alpha = ALPHA(j) and beta = BETA(j)
// represent the j-th eigenvalue of the matrix pair (A,B), in
// one of the forms lambda = alpha/beta or mu = beta/alpha.
// Since either lambda or mu may overflow, they should not,
// in general, be computed.
// Q (input/output) COMPLEX*16 array, dimension (LDQ, N)
// On entry, if COMPZ = 'V', the unitary matrix Q1 used in the
// reduction of (A,B) to generalized Hessenberg form.
// On exit, if COMPZ = 'I', the unitary matrix of left Schur
// vectors of (H,T), and if COMPZ = 'V', the unitary matrix of
// left Schur vectors of (A,B).
// Not referenced if COMPZ = 'N'.
// LDQ (input) INTEGER
// The leading dimension of the array Q. LDQ >= 1.
// If COMPQ='V' or 'I', then LDQ >= N.
// Z (input/output) COMPLEX*16 array, dimension (LDZ, N)
// On entry, if COMPZ = 'V', the unitary matrix Z1 used in the
// reduction of (A,B) to generalized Hessenberg form.
// On exit, if COMPZ = 'I', the unitary matrix of right Schur
// vectors of (H,T), and if COMPZ = 'V', the unitary matrix of
// right Schur vectors of (A,B).
// Not referenced if COMPZ = 'N'.
// LDZ (input) INTEGER
// The leading dimension of the array Z. LDZ >= 1.
// If COMPZ='V' or 'I', then LDZ >= N.
// WORK (workspace/output) COMPLEX*16 array, dimension (MAX(1,LWORK))
// On exit, if INFO >= 0, WORK(1) returns the optimal LWORK.
// LWORK (input) INTEGER
// The dimension of the array WORK. LWORK >= max(1,N).
// If LWORK = -1, then a workspace query is assumed; the routine
// only calculates the optimal size of the WORK array, returns
// this value as the first entry of the WORK array, and no error
// message related to LWORK is issued by XERBLA.
// RWORK (workspace) DOUBLE PRECISION array, dimension (N)
// INFO (output) INTEGER
// = 0: successful exit
// < 0: if INFO = -i, the i-th argument had an illegal value
// = 1,...,N: the QZ iteration did not converge. (H,T) is not
// in Schur form, but ALPHA(i) and BETA(i),
// i=INFO+1,...,N should be correct.
// = N+1,...,2n: the shift calculation failed. (H,T) is not
// in Schur form, but ALPHA(i) and BETA(i),
// i=INFO-N+1,...,N should be correct.
// Further Details
// ===============
// We assume that complex ABS works as long as its value is less than
// overflow.
h_offset = 1 + ldh;
h -= h_offset;
t_offset = 1 + ldt;
t -= t_offset;
--alpha;
--beta;
q_offset = 1 + ldq;
q -= q_offset;
z_offset = 1 + ldz;
z -= z_offset;
--work;
--rwork;
if(job[0] == 'E'){
ilschr = false;
ischur = 1;
}else if(job[0] == 'S'){
ilschr = true;
ischur = 2;
}else{
ischur = 0;
}
if(compq[0] == 'N'){
ilq = false;
icompq = 1;
}else if(compq[0] == 'V'){
ilq = true;
icompq = 2;
}else if(compq[0] == 'I'){
ilq = true;
icompq = 3;
}else{
icompq = 0;
}
if(compz[0] == 'N'){
ilz = false;
icompz = 1;
}else if(compz[0] == 'V'){
ilz = true;
icompz = 2;
}else if(compz[0] == 'I'){
ilz = true;
icompz = 3;
}else{
icompz = 0;
}
// Check Argument Values
int info = 0;
if(ischur == 0){
info = -1;
}else if(icompq == 0){
info = -2;
}else if(icompz == 0){
info = -3;
}else if(n < 0){
info = -4;
}else if(ilo < 1){
info = -5;
}else if(ihi > n || ihi < ilo - 1){
info = -6;
}else if(ldh < n){
info = -8;
}else if(ldt < n){
info = -10;
}else if(ldq < 1 || ilq && ldq < n){
info = -14;
}else if(ldz < 1 || ilz && ldz < n){
info = -16;
}
if(info != 0){
return info;
}
if(n <= 0){
return info;
}
// Initialize Q and Z
if(icompq == 3){
RNP::TBLAS::SetMatrix<'F'>(n, n, std::complex<double>(0), std::complex<double>(1), &q[q_offset], ldq);
}
if(icompz == 3){
RNP::TBLAS::SetMatrix<'F'>(n, n, std::complex<double>(0), std::complex<double>(1), &z[z_offset], ldz);
}
// Machine Constants
const int in = ihi+1 - ilo;
const double safmin = std::numeric_limits<double>::min();
const double ulp = std::numeric_limits<double>::epsilon() * 2;
double anorm, bnorm;
RNP::TLASupport::CheapHessenbergNorm<'F'>(in, &h[ilo+ilo* ldh], ldh, &anorm);
RNP::TLASupport::CheapHessenbergNorm<'F'>(in, &t[ilo+ilo* ldt], ldt, &bnorm);
// Computing MAX
const double atol = max(safmin,ulp*anorm);
// Computing MAX
const double btol = max(safmin,ulp*bnorm);
const double ascale = 1. / max(safmin,anorm);
const double bscale = 1. / max(safmin,bnorm);
// Set Eigenvalues IHI+1:N
for(j = ihi+1; j <= (int)n; ++j){
double absb = abs(t[j+j*ldt]);
if(absb > safmin){
std::complex<double> signbc = std::conj(t[j+j*ldt]/absb);
t[j+j*ldt] = absb;
if(ilschr){
RNP::TBLAS::Scale(j-1, signbc, &t[j*ldt+1], 1);
RNP::TBLAS::Scale(j, signbc, &h[j*ldh+1], 1);
}else{
h[j+j*ldh] *= signbc;
}
if(ilz){
RNP::TBLAS::Scale(n, signbc, &z[j*ldz+1], 1);
}
}else{
t[j+j*ldt] = 0;
}
alpha[j] = h[j+j*ldh];
beta[j] = t[j+j*ldt];
}
if(ilo <= ihi){ // If IHI < ILO, skip QZ steps
// MAIN QZ ITERATION LOOP
// Initialize dynamic indices
// Eigenvalues ILAST+1:N have been found.
// Column operations modify rows IFRSTM:whatever
// Row operations modify columns whatever:ILASTM
// If only eigenvalues are being computed, then
// IFRSTM is the row of the last splitting row above row ILAST;
// this is always at least ILO.
// IITER counts iterations since the last eigenvalue was found,
// to tell when to use an extraordinary shift.
// MAXIT is the maximum number of QZ sweeps allowed.
int ilast = ihi;
if(ilschr){
ifrstm = 1;
ilastm = n;
}else{
ifrstm = ilo;
ilastm = ihi;
}
int iiter = 0;
std::complex<double> eshift = 0;
const int maxit = (ihi - ilo+1) * 30;
bool converged = false;
for(int jiter = 1; jiter <= maxit; ++jiter){
// Split the matrix if possible.
// Two tests:
// 1: H(j,j-1)=0 or j=ILO
// 2: T(j,j)=0
bool ilazro;
bool ilazr2;
// Special case: j=ILAST
if(ilast == (int)ilo){
goto L60_zhgeqz;
}else if(_abs1(h[ilast+(ilast-1)*ldh]) <= atol){
h[ilast+(ilast-1)*ldh] = 0;
goto L60_zhgeqz;
}
if(abs(t[ilast+ilast*ldt]) <= btol){
t[ilast+ilast*ldt] = 0;
goto L50_zhgeqz;
}
// General case: j<ILAST
for(j = ilast - 1; j >= (int)ilo; --j){
// Test 1: for H(j,j-1)=0 or j=ILO
if(j == (int)ilo){
ilazro = true;
}else{
if(_abs1(h[j+(j-1)*ldh]) <= atol){
h[j+(j-1)*ldh] = 0;
ilazro = true;
}else{
ilazro = false;
}
}
// Test 2: for T(j,j)=0
if(abs(t[j+j*ldt]) < btol){
t[j+j*ldt] = 0;
// Test 1a: Check for 2 consecutive small subdiagonals in A
ilazr2 = false;
if(! ilazro){
if( _abs1(h[j+(j-1)*ldh])*( ascale*_abs1(h[j+1+j*ldh])) <= _abs1(h[j+j*ldh])*( ascale*atol ) ){
ilazr2 = true;
}
}
// If both tests pass (1 & 2), i.e., the leading diagonal
// element of B in the block is zero, split a 1x1 block off
// at the top. (I.e., at the J-th row/column) The leading
// diagonal element of the remainder can also be zero, so
// this may have to be done repeatedly.
if(ilazro || ilazr2){
for(jch = j; jch <= ilast-1; ++jch){
ctemp = h[jch+jch*ldh];
RNP::TLASupport::GeneratePlaneRotation(ctemp, h[jch+1+jch*ldh], &c, &s, &h[jch + jch*ldh]);
h[jch+1+jch*ldh] = 0;
RNP::TLASupport::ApplyPlaneRotation(ilastm-jch, &h[jch+(jch+1)*ldh], ldh, &h[jch+1+(jch+1)*ldh], ldh, c, s);
RNP::TLASupport::ApplyPlaneRotation(ilastm-jch, &t[jch+(jch+1)*ldt], ldt, &t[jch+1+(jch+1)*ldt], ldt, c, s);
if(ilq){
RNP::TLASupport::ApplyPlaneRotation(n, &q[jch*ldq+1], 1, &q[(jch+1)*ldq+1], 1, c, std::conj(s));
}
if(ilazr2){
h[jch+(jch-1)*ldh] *= c;
}
ilazr2 = false;
if(_abs1(t[jch+1+(jch+1)*ldt]) >= btol){
if(jch+1 >= ilast){
goto L60_zhgeqz;
}else{
ifirst = jch+1;
goto L70_zhgeqz;
}
}
t[jch+1+(jch+1)*ldt] = 0;
}
goto L50_zhgeqz;
}else{
// Only test 2 passed -- chase the zero to T(ILAST,ILAST)
// Then process as in the case T(ILAST,ILAST)=0
for(jch = j; jch <= ilast-1; ++jch){
ctemp = t[jch+(jch+1)*ldt];
RNP::TLASupport::GeneratePlaneRotation(ctemp, t[jch+1+(jch+1)*ldt], &c, &s, &t[jch+(jch+1)*ldt]);
t[jch+1+(jch+1)*ldt] = 0;
if(jch < ilastm - 1){
RNP::TLASupport::ApplyPlaneRotation(ilastm-jch-1, &t[jch+(jch+2)*ldt], ldt, &t[jch+1+(jch+2)*ldt], ldt, c, s);
}
RNP::TLASupport::ApplyPlaneRotation(ilastm-jch+2, &h[jch+(jch-1)*ldh], ldh, &h[jch+1+(jch-1)*ldh], ldh, c, s);
if(ilq){
RNP::TLASupport::ApplyPlaneRotation(n, &q[jch*ldq+1], 1, &q[(jch+1)*ldq+1], 1, c, std::conj(s));
}
ctemp = h[jch+1+jch*ldh];
RNP::TLASupport::GeneratePlaneRotation(ctemp, h[jch+1+(jch-1)*ldh], &c, &s, &h[jch+1+jch*ldh]);
h[jch+1+(jch-1)*ldh] = 0;
RNP::TLASupport::ApplyPlaneRotation(jch+1-ifrstm, &h[ifrstm + jch*ldh], 1, &h[ifrstm + (jch-1)*ldh], 1, c, s);
RNP::TLASupport::ApplyPlaneRotation(jch-ifrstm, &t[ifrstm + jch*ldt], 1, &t[ifrstm + (jch-1)*ldt], 1, c, s);
if(ilz){
RNP::TLASupport::ApplyPlaneRotation(n, &z[jch*ldz+1], 1, &z[(jch-1)*ldz+1], 1, c, s);
}
}
goto L50_zhgeqz;
}
}else if(ilazro){
// Only test 1 passed -- work on J:ILAST
ifirst = j;
goto L70_zhgeqz;
}
// Neither test passed -- try next J
}
// (Drop-through is "impossible")
return 2*n+1;
// T(ILAST,ILAST)=0 -- clear H(ILAST,ILAST-1) to split off a 1x1 block.
L50_zhgeqz:
ctemp = h[ilast+ilast*ldh];
RNP::TLASupport::GeneratePlaneRotation(ctemp, h[ilast + (ilast-1)*ldh], &c, &s, &h[ilast + ilast*ldh]);
h[ilast+(ilast-1)*ldh] = 0;
RNP::TLASupport::ApplyPlaneRotation(ilast-ifrstm, &h[ifrstm+ilast*ldh], 1, &h[ifrstm + (ilast-1)*ldh], 1, c, s);
RNP::TLASupport::ApplyPlaneRotation(ilast-ifrstm, &t[ifrstm+ilast*ldt], 1, &t[ifrstm + (ilast-1)*ldt], 1, c, s);
if(ilz){
RNP::TLASupport::ApplyPlaneRotation(n, &z[ilast*ldz+1], 1, &z[(ilast-1)*ldz+1], 1, c, s);
}
// H(ILAST,ILAST-1)=0 -- Standardize B, set ALPHA and BETA
L60_zhgeqz:
double absb = abs(t[ilast + ilast*ldt]);
if(absb > safmin){
std::complex<double> signbc = std::conj(t[ilast+ilast*ldt]/absb);
t[ilast+ilast*ldt] = absb;
if(ilschr){
RNP::TBLAS::Scale(ilast-ifrstm, signbc, &t[ifrstm + ilast*ldt], 1);
RNP::TBLAS::Scale(ilast+1-ifrstm, signbc, &h[ifrstm + ilast*ldh], 1);
}else{
h[ilast+ilast*ldh] *= signbc;
}
if(ilz){
RNP::TBLAS::Scale(n, signbc, &z[ilast*ldz+1], 1);
}
}else{
t[ilast+ilast*ldt] = 0;
}
alpha[ilast] = h[ilast+ilast*ldh];
beta[ilast] = t[ilast+ilast*ldt];
// Go to next block -- exit if finished.
--ilast;
if(ilast < (int)ilo){
converged = true;
break;
}
// Reset counters
iiter = 0;
eshift = 0;
if(! ilschr){
ilastm = ilast;
if(ifrstm > ilast){
ifrstm = ilo;
}
}
continue;
// QZ step
// This iteration only involves rows/columns IFIRST:ILAST. We
// assume IFIRST < ILAST, and that the diagonal of B is non-zero.
L70_zhgeqz:
++iiter;
if(! ilschr){
ifrstm = ifirst;
}
// Compute the Shift.
// At this point, IFIRST < ILAST, and the diagonal elements of
// T(IFIRST:ILAST,IFIRST,ILAST) are larger than BTOL (in
// magnitude)
std::complex<double> shift;
if(iiter / 10 * 10 != iiter){
// The Wilkinson shift (AEP p.512), i.e., the eigenvalue of
// the bottom-right 2x2 block of A inv(B) which is nearest to
// the bottom-right element.
// We factor B as U*D, where U has unit diagonals, and
// compute (A*inv(D))*inv(U).
std::complex<double> u12 = (bscale*t[ilast - 1 + ilast*ldt]) / (bscale * t[ilast + ilast*ldt]);
std::complex<double> ad11 = (ascale*h[ilast - 1+(ilast-1)*ldh]) / (bscale*t[ilast - 1+(ilast-1)*ldt]);
std::complex<double> ad21 = (ascale*h[ilast + (ilast-1)*ldh]) / (bscale*t[ilast - 1+(ilast-1)*ldt]);
std::complex<double> ad12 = (ascale*h[ilast - 1 + ilast*ldh]) / (bscale*t[ilast + ilast*ldt]);
std::complex<double> ad22 = (ascale*h[ilast + ilast*ldh]) / (bscale*t[ilast + ilast*ldt]);
std::complex<double> abi22 = ad22-u12*ad21;
std::complex<double> t1 = (ad11+abi22) / double(2);
std::complex<double> rtdisc = sqrt(t1*t1 + ad12*ad21 - ad11*ad22);
if(((t1-abi22)*std::conj(rtdisc)).real() <= 0.){
shift = t1 + rtdisc;
}else{
shift = t1 - rtdisc;
}
}else{
// Exceptional shift. Chosen for no particularly good reason.
eshift += std::conj((ascale*h[ilast - 1 + ilast*ldh]) / (bscale*t[ilast - 1+(ilast-1)*ldt]));
shift = eshift;
}
// Now check for two consecutive small subdiagonals.
bool found = false;
int istart;
for(j = ilast - 1; j >= ifirst+1; --j){
istart = j;
ctemp = ascale*h[j+j*ldh] - shift*(bscale*t[j+j*ldt]);
double abs1ctemp = _abs1(ctemp);
double abs1next = ascale * _abs1(h[j+1+j*ldh]);
double maxabs1 = max(abs1ctemp,abs1next);
if(maxabs1 < 1. && maxabs1 != 0.){
abs1ctemp /= maxabs1;
abs1next /= maxabs1;
}
if(_abs1(h[j+(j-1)*ldh]) * abs1next <= abs1ctemp * atol){
found = true;
break;
}
}
if(!found){
istart = ifirst;
ctemp = ascale*h[ifirst+ifirst*ldh] - shift*(bscale*t[ifirst+ifirst*ldt]);
}
// Do an implicit-shift QZ sweep.
// Initial Q
{
std::complex<double> ctemp3;
RNP::TLASupport::GeneratePlaneRotation(ctemp, ascale * h[istart+1+istart*ldh], &c, &s, &ctemp3);
}
// Sweep
for(j = istart; j <= ilast-1; ++j){
if(j > istart){
ctemp = h[j+(j-1)*ldh];
RNP::TLASupport::GeneratePlaneRotation(ctemp, h[j+1+(j-1)*ldh], &c, &s, &h[j+(j-1)*ldh]);
h[j+1+(j-1)*ldh] = 0;
}
for(jc = j; jc <= ilastm; ++jc){
ctemp = c*h[j+jc*ldh] + s*h[j+1+jc*ldh];
h[j+1+jc*ldh] = -std::conj(s)*h[j+jc*ldh] + c*h[j+1+jc*ldh];
h[j+jc*ldh] = ctemp;
ctemp = c*t[j+jc*ldt] + s*t[j+1+jc*ldt];
t[j+1+jc*ldt] = -std::conj(s)*t[j+jc*ldt] + c*t[j+1+jc*ldt];
t[j+jc*ldt] = ctemp;
}
if(ilq){
for(jr = 1; jr <= (int)n; ++jr){
ctemp = c*q[jr+j*ldq] + std::conj(s)*q[jr+(j+1)*ldq];
q[jr+(j+1)*ldq] = -s*q[jr + j*ldq] + c*q[jr+(j+1)*ldq];
q[jr+j*ldq] = ctemp;
}
}
ctemp = t[j+1+(j+1)*ldt];
RNP::TLASupport::GeneratePlaneRotation(ctemp, t[j+1+j*ldt], &c, &s, &t[j+1+(j+1)*ldt]);
t[j+1+j*ldt] = 0;
// Computing MIN
for(jr = ifrstm; jr <= min(j+2,ilast); ++jr){
ctemp = c*h[jr+(j+1)*ldh] + s*h[jr+j*ldh];
h[jr+j*ldh] = -std::conj(s)*h[jr+(j+1)*ldh] + c*h[jr+j*ldh];
h[jr+(j+1)*ldh] = ctemp;
}
for(jr = ifrstm; jr <= j; ++jr){
ctemp = c*t[jr+(j+1)*ldt] + s*t[jr+j*ldt];
t[jr+j*ldt] = -std::conj(s)*t[jr+(j+1)*ldt] + c*t[jr+j*ldt];
t[jr+(j+1)*ldt] = ctemp;
}
if(ilz){
for(jr = 1; jr <= (int)n; ++jr){
ctemp = c*z[jr+(j+1)*ldz] + s*z[jr+j*ldz];
z[jr+j*ldz] = -std::conj(s)*z[jr+(j+1)*ldz] + c*z[jr+j*ldz];
z[jr+(j+1)*ldz] = ctemp;
}
}
}
}
if(!converged){
return ilast;
}
// Successful completion of all QZ steps
}
// Set Eigenvalues 1:ILO-1
for(j = 1; j <= (int)ilo-1; ++j){
double absb = abs(t[j+j*ldt]);
if(absb > safmin){
std::complex<double> signbc = std::conj(t[j+j*ldt]/absb);
t[j+j*ldt] = absb;
if(ilschr){
RNP::TBLAS::Scale(j-1, signbc, &t[j*ldt+1], 1);
RNP::TBLAS::Scale(j, signbc, &h[j*ldh+1], 1);
}else{
h[j+j*ldh] *= signbc;
}
if(ilz){
RNP::TBLAS::Scale(n, signbc, &z[j*ldz+1], 1);
}
}else{
t[j+j*ldt] = 0;
}
alpha[j] = h[j+j*ldh];
beta[j] = t[j+j*ldt];
}
return 0;
}
static int ztgevc_(const char *howmny, bool *select,
size_t n, std::complex<double> *s, size_t lds, std::complex<double> *p, size_t
ldp, std::complex<double> *vl, size_t ldvl, std::complex<double> *vr, size_t
ldvr, size_t mm, size_t *m, std::complex<double> *work, double *rwork)
{
using namespace std;
/* System generated locals */
size_t p_offset, s_offset, vl_offset,
vr_offset;
double d__1, d__2, d__3, d__4, d__5, d__6;
/* Local variables */
std::complex<double> d;
int i, j;
int je, im, jr;
double big;
bool lsa, lsb;
double ulp;
int ibeg, ieig, iend;
double dmin__;
int isrc;
double temp;
double xmax, scale;
bool ilall;
int iside;
double sbeta;
double small;
bool bcoml;
double anorm, bnorm;
bool compr;
bool ilbbad;
double acoefa, bcoefa, acoeff;
std::complex<double> bcoeff;
bool ilback;
double ascale, bscale;
std::complex<double> salpha;
double safmin;
double bignum;
bool ilcomp;
int ihwmny;
/* Purpose */
/* ======= */
/* ZTGEVC computes some or all of the right and/or left eigenvectors of */
/* a pair of complex matrices (S,P), where S and P are upper triangular. */
/* Matrix pairs of this type are produced by the generalized Schur */
/* factorization of a complex matrix pair (A,B): */
/* A = Q*S*Z**H, B = Q*P*Z**H */
/* as computed by ZGGHRD + ZHGEQZ. */
/* The right eigenvector x and the left eigenvector y of (S,P) */
/* corresponding to an eigenvalue w are defined by: */
/* S*x = w*P*x, (y**H)*S = w*(y**H)*P, */
/* where y**H denotes the conjugate tranpose of y. */
/* The eigenvalues are not input to this routine, but are computed */
/* directly from the diagonal elements of S and P. */
/* This routine returns the matrices X and/or Y of right and left */
/* eigenvectors of (S,P), or the products Z*X and/or Q*Y, */
/* where Z and Q are input matrices. */
/* If Q and Z are the unitary factors from the generalized Schur */
/* factorization of a matrix pair (A,B), then Z*X and Q*Y */
/* are the matrices of right and left eigenvectors of (A,B). */
/* Arguments */
/* ========= */
/* SIDE (input) CHARACTER*1 */
/* = 'R': compute right eigenvectors only; */
/* = 'L': compute left eigenvectors only; */
/* = 'B': compute both right and left eigenvectors. */
/* HOWMNY (input) CHARACTER*1 */
/* = 'A': compute all right and/or left eigenvectors; */
/* = 'B': compute all right and/or left eigenvectors, */
/* backtransformed by the matrices in VR and/or VL; */
/* = 'S': compute selected right and/or left eigenvectors, */
/* specified by the bool array SELECT. */
/* SELECT (input) bool array, dimension (N) */
/* If HOWMNY='S', SELECT specifies the eigenvectors to be */
/* computed. The eigenvector corresponding to the j-th */
/* eigenvalue is computed if SELECT(j) = .TRUE.. */
/* Not referenced if HOWMNY = 'A' or 'B'. */
/* N (input) INTEGER */
/* The order of the matrices S and P. N >= 0. */
/* S (input) COMPLEX*16 array, dimension (LDS,N) */
/* The upper triangular matrix S from a generalized Schur */
/* factorization, as computed by ZHGEQZ. */
/* LDS (input) INTEGER */
/* The leading dimension of array S. LDS >= max(1,N). */
/* P (input) COMPLEX*16 array, dimension (LDP,N) */
/* The upper triangular matrix P from a generalized Schur */
/* factorization, as computed by ZHGEQZ. P must have real */
/* diagonal elements. */
/* LDP (input) INTEGER */
/* The leading dimension of array P. LDP >= max(1,N). */
/* VL (input/output) COMPLEX*16 array, dimension (LDVL,MM) */
/* On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must */
/* contain an N-by-N matrix Q (usually the unitary matrix Q */
/* of left Schur vectors returned by ZHGEQZ). */
/* On exit, if SIDE = 'L' or 'B', VL contains: */
/* if HOWMNY = 'A', the matrix Y of left eigenvectors of (S,P); */
/* if HOWMNY = 'B', the matrix Q*Y; */
/* if HOWMNY = 'S', the left eigenvectors of (S,P) specified by */
/* SELECT, stored consecutively in the columns of */
/* VL, in the same order as their eigenvalues. */
/* Not referenced if SIDE = 'R'. */
/* LDVL (input) INTEGER */
/* The leading dimension of array VL. LDVL >= 1, and if */
/* SIDE = 'L' or 'l' or 'B' or 'b', LDVL >= N. */
/* VR (input/output) COMPLEX*16 array, dimension (LDVR,MM) */
/* On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must */
/* contain an N-by-N matrix Q (usually the unitary matrix Z */
/* of right Schur vectors returned by ZHGEQZ). */
/* On exit, if SIDE = 'R' or 'B', VR contains: */
/* if HOWMNY = 'A', the matrix X of right eigenvectors of (S,P); */
/* if HOWMNY = 'B', the matrix Z*X; */
/* if HOWMNY = 'S', the right eigenvectors of (S,P) specified by */
/* SELECT, stored consecutively in the columns of */
/* VR, in the same order as their eigenvalues. */
/* Not referenced if SIDE = 'L'. */
/* LDVR (input) INTEGER */
/* The leading dimension of the array VR. LDVR >= 1, and if */
/* SIDE = 'R' or 'B', LDVR >= N. */
/* MM (input) INTEGER */
/* The number of columns in the arrays VL and/or VR. MM >= M. */
/* M (output) INTEGER */
/* The number of columns in the arrays VL and/or VR actually */
/* used to store the eigenvectors. If HOWMNY = 'A' or 'B', M */
/* is set to N. Each selected eigenvector occupies one column. */
/* WORK (workspace) COMPLEX*16 array, dimension (2*N) */
/* RWORK (workspace) DOUBLE PRECISION array, dimension (2*N) */
/* INFO (output) INTEGER */
/* = 0: successful exit. */
/* < 0: if INFO = -i, the i-th argument had an illegal value. */
/* ===================================================================== */
if(NULL != vl){
if(NULL != vr){
iside = 3;
bcoml = true;
compr = true;
}else{
iside = 2;
bcoml = true;
compr = false;
}
}else if(NULL != vr){
iside = 1;
bcoml = false;
compr = true;
}else{
iside = -1;
}
/* Parameter adjustments */
--select;
s_offset = 1 + lds;
s -= s_offset;
p_offset = 1 + ldp;
p -= p_offset;
vl_offset = 1 + ldvl;
vl -= vl_offset;
vr_offset = 1 + ldvr;
vr -= vr_offset;
--work;
--rwork;
/* Function Body */
if (howmny[0] == 'A') {
ihwmny = 1;
ilall = true;
ilback = false;
} else if (howmny[0] == 'S') {
ihwmny = 2;
ilall = false;
ilback = false;
} else if (howmny[0] == 'B') {
ihwmny = 3;
ilall = true;
ilback = true;
} else {
ihwmny = -1;
}
int info = 0;
if (iside < 0) {
info = -1;
} else if (ihwmny < 0) {
info = -2;
} else if (n < 0) {
info = -4;
} else if (lds < max((size_t)1,n)) {
info = -6;
} else if (ldp < max((size_t)1,n)) {
info = -8;
}
if (info != 0) {
return info;
}
/* Count the number of eigenvectors */
if (! ilall) {
im = 0;
for (j = 1; j <= (int)n; ++j) {
if (select[j]) {
++im;
}
}
} else {
im = n;
}
/* Check diagonal of B */
ilbbad = false;
for (j = 1; j <= (int)n; ++j) {
if (p[j+j*ldp].imag() != 0.) {
ilbbad = true;
}
}
if (ilbbad) {
info = -7;
} else if (bcoml && ldvl < n || ldvl < 1) {
info = -10;
} else if (compr && ldvr < n || ldvr < 1) {
info = -12;
} else if ((int)mm < im) {
info = -13;
}
if (info != 0) {
return info;
}
/* Quick return if possible */
*m = im;
if (n == 0) {
return 0;
}
/* Machine Constants */
safmin = std::numeric_limits<double>::min();
ulp = std::numeric_limits<double>::epsilon() * 2;
small = safmin * n / ulp;
big = 1. / small;
bignum = 1. / (safmin * n);
/* Compute the 1-norm of each column of the strictly upper triangular */
/* part of A and B to check for possible overflow in the triangular */
/* solver. */
anorm = _abs1(s[1+1*lds]);
bnorm = _abs1(p[1+1*ldp]);
rwork[1] = 0.;
rwork[n + 1] = 0.;
for (j = 2; j <= (int)n; ++j) {
rwork[j] = 0.;
rwork[n + j] = 0.;
for (i = 1; i <= j-1; ++i) {
rwork[j] += _abs1(s[i+j*lds]);
rwork[n + j] += _abs1(p[i+j*ldp]);
}
/* Computing MAX */
anorm = max(anorm,rwork[j] + _abs1(s[j+j*lds]));
/* Computing MAX */
bnorm = max(bnorm,rwork[n+j] + _abs1(p[j+j*ldp]));
}
ascale = 1. / max(anorm,safmin);
bscale = 1. / max(bnorm,safmin);
/* Left eigenvectors */
if (bcoml) {
ieig = 0;
/* Main loop over eigenvalues */
for (je = 1; je <= (int)n; ++je) {
if (ilall) {
ilcomp = true;
} else {
ilcomp = select[je];
}
if (ilcomp) {
++ieig;
if (_abs1(s[je+je*lds]) <= safmin && abs(p[je+je*ldp].real()) <= safmin) {
/* Singular matrix pencil -- return unit eigenvector */
for (jr = 1; jr <= (int)n; ++jr) {
vl[jr+ieig*ldvl] = 0;
}
vl[ieig+ieig*ldvl] = 1;
continue;
}
/* Non-singular eigenvalue: */
/* Compute coefficients a and b in */
/* H */
/* y ( a A - b B ) = 0 */
/* Computing MAX */
d__4 = _abs1(s[je+je*lds]) * ascale, d__5 = abs(p[je+je*ldp].real()) * bscale, d__4 = max(d__4,d__5);
temp = 1. / max(d__4,safmin);
salpha = (temp*s[je+je*lds]) * ascale;
sbeta = temp * p[je+je*ldp].real() * bscale;
acoeff = sbeta * ascale;
bcoeff = bscale * salpha;
/* Scale to avoid underflow */
lsa = abs(sbeta) >= safmin && abs(acoeff) < small;
lsb = _abs1(salpha) >= safmin && _abs1(bcoeff) < small;
scale = 1.;
if (lsa) {
scale = small / abs(sbeta) * min(anorm,big);
}
if (lsb) {
/* Computing MAX */
d__4 = small / _abs1(salpha) * min(bnorm,big);
scale = max(scale,d__4);
}
if (lsa || lsb) {
/* Computing MIN */
/* Computing MAX */
d__5 = 1., d__6 = abs(acoeff), d__5 = max(d__5,d__6),
d__6 = _abs1(bcoeff);
d__3 = scale, d__4 = 1. / (safmin * max(d__5,d__6));
scale = min(d__3,d__4);
if (lsa) {
acoeff = ascale * (scale * sbeta);
} else {
acoeff = scale * acoeff;
}
if (lsb) {
bcoeff = bscale * (scale*salpha);
} else {
bcoeff *= scale;
}
}
acoefa = abs(acoeff);
bcoefa = _abs1(bcoeff);
xmax = 1.;
for (jr = 1; jr <= (int)n; ++jr) {
work[jr] = 0;
}
work[je] = 1;
/* Computing MAX */
d__1 = ulp * acoefa * anorm, d__2 = ulp * bcoefa * bnorm,
d__1 = max(d__1,d__2);
dmin__ = max(d__1,safmin);
/* H */
/* Triangular solve of (a A - b B) y = 0 */
/* H */
/* (rowwise in (a A - b B) , or columnwise in a A - b B) */
for (j = je + 1; j <= (int)n; ++j) {
/* Compute */
/* j-1 */
/* SUM = sum conjg( a*S(k,j) - b*P(k,j) )*x(k) */
/* k=je */
/* (Scale if necessary) */
temp = 1. / xmax;
if (acoefa * rwork[j] + bcoefa * rwork[n + j] > bignum *
temp) {
for (jr = je; jr <= j-1; ++jr) {
work[jr] *= temp;
}
xmax = 1.;
}
std::complex<double> suma(0), sumb(0);
for (jr = je; jr <= j-1; ++jr) {
suma += std::conj(((std::complex<double>*)(s))[jr+j*lds]) * work[jr];
sumb += std::conj(((std::complex<double>*)(p))[jr+j*ldp]) * work[jr];
}
std::complex<double> sum = acoeff*suma - std::conj(bcoeff)*sumb;
/* Form x(j) = - SUM / conjg( a*S(j,j) - b*P(j,j) ) */
/* with scaling and perturbation of the denominator */
d = std::conj(acoeff*s[j+j*lds] - bcoeff*p[j+j*ldp]);
if (_abs1(d) <= dmin__) {
d = dmin__;
}
double abs1d = _abs1(d);
if (abs1d < 1.) {
double abs1sum = RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(sum);
if (abs1sum >= bignum * abs1d) {
temp = 1. / abs1sum;
for (jr = je; jr <= j-1; ++jr) {
work[jr] *= temp;
}
xmax *= temp;
sum *= temp;
}
}
work[j] = -sum/d;
/* Computing MAX */
xmax = max(xmax,RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(work[j]));
}
/* Back transform eigenvector if HOWMNY='B'. */
if (ilback) {
RNP::TBLAS::MultMV<'N'>(n, n + 1 - je, double(1), &vl[1+je*ldvl], ldvl, &work[je], 1, double(0), &work[n+1], 1);
isrc = 2;
ibeg = 1;
} else {
isrc = 1;
ibeg = je;
}
/* Copy and scale eigenvector into column of VL */
xmax = 0.;
for (jr = ibeg; jr <= (int)n; ++jr) {
xmax = max(xmax,RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(work[(isrc-1)*n+jr]));
}
if (xmax > safmin) {
temp = 1. / xmax;
for (jr = ibeg; jr <= (int)n; ++jr) {
vl[jr+ieig*ldvl] = temp * work[(isrc-1)*n+jr];
}
} else {
ibeg = n + 1;
}
for (jr = 1; jr <= ibeg - 1; ++jr) {
vl[jr+ieig*ldvl] = 0;
}
}
}
}
/* Right eigenvectors */
if (compr) {
ieig = im + 1;
/* Main loop over eigenvalues */
for (je = n; je >= 1; --je) {
if (ilall) {
ilcomp = true;
} else {
ilcomp = select[je];
}
if (ilcomp) {
--ieig;
if (_abs1(s[je+je*lds]) <= safmin && abs(p[je+je*ldp].real()) <= safmin) {
/* Singular matrix pencil -- return unit eigenvector */
for (jr = 1; jr <= (int)n; ++jr) {
vr[jr+ieig*ldvr] = 0;
}
vr[ieig+ieig*ldvr] = 1;
continue;
}
/* Non-singular eigenvalue: */
/* Compute coefficients a and b in */
/* ( a A - b B ) x = 0 */
/* Computing MAX */
d__4 = _abs1(s[je+je*lds]) * ascale, d__5 = _abs1(
p[je+je*ldp].real()) * bscale, d__4 = max(d__4,d__5);
temp = 1. / max(d__4,safmin);
salpha = (temp*s[je+je*lds]) * ascale;
sbeta = (temp * p[je+je*ldp].real()) * bscale;
acoeff = sbeta * ascale;
bcoeff = bscale * salpha;
/* Scale to avoid underflow */
lsa = abs(sbeta) >= safmin && abs(acoeff) < small;
lsb = _abs1(salpha) >= safmin && _abs1(bcoeff) < small;
scale = 1.;
if (lsa) {
scale = small / abs(sbeta) * min(anorm,big);
}
if (lsb) {
/* Computing MAX */
d__3 = scale, d__4 = small / _abs1(salpha) * min(bnorm,big);
scale = max(d__3,d__4);
}
if (lsa || lsb) {
/* Computing MIN */
/* Computing MAX */
d__5 = 1., d__6 = abs(acoeff), d__5 = max(d__5,d__6),
d__6 = _abs1(bcoeff);
d__3 = scale, d__4 = 1. / (safmin * max(d__5,d__6));
scale = min(d__3,d__4);
if (lsa) {
acoeff = ascale * (scale * sbeta);
} else {
acoeff = scale * acoeff;
}
if (lsb) {
bcoeff = bscale * (scale*salpha);
} else {
bcoeff *= scale;
}
}
acoefa = abs(acoeff);
bcoefa = _abs1(bcoeff);
xmax = 1.;
for (jr = 1; jr <= (int)n; ++jr) {
work[jr] = 0;
}
work[je] = 1;
/* Computing MAX */
d__1 = ulp * acoefa * anorm, d__2 = ulp * bcoefa * bnorm,
d__1 = max(d__1,d__2);
dmin__ = max(d__1,safmin);
/* Triangular solve of (a A - b B) x = 0 (columnwise) */
/* WORK(1:j-1) contains sums w, */
/* WORK(j+1:JE) contains x */
for (jr = 1; jr <= je - 1; ++jr) {
work[jr] = acoeff*((std::complex<double>*)s)[jr+je*lds] - bcoeff*((std::complex<double>*)p)[jr+je*ldp];
}
work[je] = 1;
for (j = je - 1; j >= 1; --j) {
/* Form x(j) := - w(j) / d */
/* with scaling and perturbation of the denominator */
d = acoeff*s[j+j*lds] - bcoeff*p[j+j*ldp];
if (_abs1(d) <= dmin__) {
d = dmin__;
}
double _abs1d = _abs1(d);
if (_abs1d < 1.) {
double abs1workj = RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(work[j]);
if (abs1workj >= bignum * _abs1d) {
temp = 1. / abs1workj;
for (jr = 1; jr <= je; ++jr) {
work[jr] *= temp;
}
}
}
work[j] = -work[j]/d;
if (j > 1) {
/* w = w + x(j)*(a S(*,j) - b P(*,j) ) with scaling */
double abs1workj = RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(work[j]);
if (abs1workj > 1.) {
temp = 1. / abs1workj;
if (acoefa * rwork[j] + bcoefa * rwork[n + j] >=
bignum * temp) {
for (jr = 1; jr <= je; ++jr) {
work[jr] *= temp;
}
}
}
std::complex<double> ca = acoeff*work[j];
std::complex<double> cb = bcoeff*work[j];
for (jr = 1; jr <= j - 1; ++jr) {
work[jr] += ca*((std::complex<double>*)s)[jr+j*lds] - cb*((std::complex<double>*)p)[jr+j*ldp];
}
}
}
/* Back transform eigenvector if HOWMNY='B'. */
if (ilback) {
RNP::TBLAS::MultMV<'N'>(n, je, double(1), &vr[vr_offset], ldvr, &work[1], 1, double(0), &work[n+1], 1);
isrc = 2;
iend = n;
} else {
isrc = 1;
iend = je;
}
/* Copy and scale eigenvector into column of VR */
xmax = 0.;
for (jr = 1; jr <= iend; ++jr) {
xmax = max(xmax,RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(work[(isrc-1)*n+jr]));
}
if (xmax > safmin) {
temp = 1. / xmax;
for (jr = 1; jr <= iend; ++jr) {
vr[jr+ieig*ldvr] = temp * work[(isrc-1)*n+jr];
}
} else {
iend = 0;
}
for (jr = iend + 1; jr <= (int)n; ++jr) {
vr[jr+ieig*ldvr] = 0;
}
}
}
}
return 0;
}
// Computes for a pair of N-by-N complex nonsymmetric matrices (A,B),
// the generalized eigenvalues, and optionally, the left and/or right
// generalized eigenvectors.
// A generalized eigenvalue for a pair of matrices (A,B) is a scalar
// lambda or a ratio alpha/beta = lambda, such that A - lambda*B is
// singular. It is usually represented as the pair (alpha,beta), as
// there is a reasonable interpretation for beta=0, and even for both
// being zero.
// The right generalized eigenvector v(j) corresponding to the
// generalized eigenvalue lambda(j) of (A,B) satisfies
// A * v(j) = lambda(j) * B * v(j).
// The left generalized eigenvector u(j) corresponding to the
// generalized eigenvalues lambda(j) of (A,B) satisfies
// u(j)^H * A = lambda(j) * u(j)^H * B
// where u(j)^H is the conjugate-transpose of u(j).
// Arguments
// =========
// N The order of the matrices A, B, VL, and VR. N >= 0.
// A (input/output) COMPLEX*16 array, dimension (LDA, N)
// On entry, the matrix A in the pair (A,B).
// On exit, A has been overwritten.
// LDA The leading dimension of A. LDA >= max(1,N).
// B (input/output) COMPLEX*16 array, dimension (LDB, N)
// On entry, the matrix B in the pair (A,B).
// On exit, B has been overwritten.
// LDB The leading dimension of B. LDB >= max(1,N).
// ALPHA (output) COMPLEX*16 array, dimension (N)
// BETA (output) COMPLEX*16 array, dimension (N)
// On exit, ALPHA(j)/BETA(j), j=1,...,N, will be the
// generalized eigenvalues.
// Note: the quotients ALPHA(j)/BETA(j) may easily over- or
// underflow, and BETA(j) may even be zero. Thus, the user
// should avoid naively computing the ratio alpha/beta.
// However, ALPHA will be always less than and usually
// comparable with norm(A) in magnitude, and BETA always less
// than and usually comparable with norm(B).
// VL (output) COMPLEX*16 array, dimension (LDVL,N)
// If VL != NULL, the left generalized eigenvectors u(j) are
// stored one after another in the columns of VL, in the same
// order as their eigenvalues.
// Each eigenvector is scaled so the largest component has
// abs(real part) + abs(imag. part) = 1.
// LDVL The leading dimension of the matrix VL. LDVL >= 1, and
// if VL != NULL, LDVL >= N.
// VR (output) COMPLEX*16 array, dimension (LDVR,N)
// If VR != NULL, the right generalized eigenvectors v(j) are
// stored one after another in the columns of VR, in the same
// order as their eigenvalues.
// Each eigenvector is scaled so the largest component has
// abs(real part) + abs(imag. part) = 1.
// LDVR The leading dimension of the matrix VR. LDVR >= 1, and
// if VR != NULL, LDVR >= N.
// WORK (workspace/output) COMPLEX*16 array, dimension (MAX(1,2*N))
// RWORK (workspace/output) DOUBLE PRECISION array, dimension (8*N)
// return: = 0: successful exit
// < 0: if INFO = -i, the i-th argument had an illegal value.
// =1,...,N:
// The QZ iteration failed. No eigenvectors have been
// calculated, but ALPHA(j) and BETA(j) should be
// correct for j=INFO+1,...,N.
// > N: =N+1: other then QZ iteration failed in DHGEQZ,
// =N+2: error return from DTGEVC.
int RNP::GeneralizedEigensystem(size_t n,
std::complex<double> *a, size_t lda, std::complex<double> *b, size_t ldb,
std::complex<double> *alpha, std::complex<double> *beta,
std::complex<double> *vl, size_t ldvl, std::complex<double> *vr, size_t ldvr,
std::complex<double> *work, double *rwork)
{
/* System generated locals */
size_t a_offset, b_offset, vl_offset,
vr_offset;
using namespace std;
/* Local variables */
int ihi, ilo;
double anrm, bnrm;
int itau;
double temp;
int iwrk;
int ileft, icols, irwrk, irows;
bool ilascl, ilbscl;
bool ldumma[1];
double anrmto;
double bnrmto;
const bool ilvl = (NULL != vl);
const bool ilvr = (NULL != vr);
const bool ilv = (ilvl || ilvr);
/* Parameter adjustments */
a_offset = 1 + lda;
a -= a_offset;
b_offset = 1 + ldb;
b -= b_offset;
--alpha;
--beta;
vl_offset = 1 + ldvl;
vl -= vl_offset;
vr_offset = 1 + ldvr;
vr -= vr_offset;
--work;
--rwork;
// Test the input arguments
if (n < 0) {
return -3;
} else if (lda < max((size_t)1,n)) {
return -5;
} else if (ldb < max((size_t)1,n)) {
return -7;
} else if (ldvl < 1 || ilvl && ldvl < n) {
return -11;
} else if (ldvr < 1 || ilvr && ldvr < n) {
return -13;
}
if (n == 0) {
return 0;
}
const double eps = std::numeric_limits<double>::epsilon() * 2;
const double smlnum = sqrt(std::numeric_limits<double>::min()) / eps;
const double bignum = 1. / smlnum;
// Scale A if max element outside range [SMLNUM,BIGNUM]
RNP::TLASupport::CheapMatrixNorm<'M'>(n, n, &a[a_offset], lda, &anrm);
ilascl = false;
if (anrm > 0. && anrm < smlnum) {
anrmto = smlnum;
ilascl = true;
} else if (anrm > bignum) {
anrmto = bignum;
ilascl = true;
}
if (ilascl) {
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, anrm, anrmto, n, n, &a[a_offset], lda);
}
// Scale B if max element outside range [SMLNUM,BIGNUM]
RNP::TLASupport::CheapMatrixNorm<'M'>(n, n, &b[b_offset], ldb, &bnrm);
ilbscl = false;
if (bnrm > 0. && bnrm < smlnum) {
bnrmto = smlnum;
ilbscl = true;
} else if (bnrm > bignum) {
bnrmto = bignum;
ilbscl = true;
}
if (ilbscl) {
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, bnrm, bnrmto, n, n, &b[b_offset], ldb);
}
// Permute the matrices A, B to isolate eigenvalues if possible
// (Real Workspace: need 6*N)
ileft = 1;
int iright = n + 1;
irwrk = iright + n;
zggbal_("P", n, &a[a_offset], lda, &b[b_offset], ldb, &ilo, &ihi, &rwork[ileft], &rwork[iright], &rwork[irwrk]);
// Reduce B to triangular form (QR decomposition of B)
// (Complex Workspace: need N)
irows = ihi + 1 - ilo;
if (ilv) {
icols = n + 1 - ilo;
} else {
icols = irows;
}
itau = 1;
iwrk = itau + irows;
RNP::TLASupport::QRFactorization(irows, icols, &b[ilo + ilo * ldb], ldb, &work[itau], &work[iwrk]);
// Apply the orthogonal transformation to matrix A
// (Complex Workspace: need N)
RNP::TLASupport::ApplyOrthognalMatrixFromElementaryReflectors<'L','C'>(
irows, icols, irows, &b[ilo + ilo * ldb], ldb, &
work[itau], &a[ilo + ilo * lda], lda, &work[iwrk]);
// Initialize VL
// (Complex Workspace: need N)
if (ilvl) {
RNP::TBLAS::SetMatrix<'F'>(n, n, std::complex<double>(0), std::complex<double>(1), &vl[vl_offset], ldvl);
if (irows > 1) {
RNP::TBLAS::CopyMatrix<'L'>(irows-1, irows-1, &b[ilo + 1 + ilo * ldb], ldb, &vl[ilo + 1 + ilo * ldvl], ldvl);
}
RNP::TLASupport::GenerateOrthognalMatrixFromElementaryReflectors(irows, irows, irows, &vl[ilo + ilo * ldvl], ldvl, &work[
itau], &work[iwrk]);
}
// Initialize VR
if (ilvr) {
RNP::TBLAS::SetMatrix<'F'>(n, n, std::complex<double>(0), std::complex<double>(1), &vr[vr_offset], ldvr);
}
// Reduce to generalized Hessenberg form
if(ilvl){
if(ilvr){
RNP::TLASupport::GeneralizedHessenbergReduction<'V','V'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr);
}else{
RNP::TLASupport::GeneralizedHessenbergReduction<'V','N'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr);
}
}else{
if(ilvr){
RNP::TLASupport::GeneralizedHessenbergReduction<'N','V'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr);
}else{
RNP::TLASupport::GeneralizedHessenbergReduction<'N','N'>(irows, 0, irows-1, &a[ilo + ilo * lda], lda, &b[ilo + ilo * ldb], ldb, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr);
}
}
// Perform QZ algorithm (Compute eigenvalues, and optionally, the
// Schur form and Schur vectors)
// (Complex Workspace: need N)
// (Real Workspace: need N)
iwrk = itau;
char chtemp[1];
if (ilv) {
chtemp[0] = 'S';
} else {
chtemp[0] = 'E';
}
char jobvl[1], jobvr[1];
if(ilvl){
jobvl[0] = 'V';
}else{
jobvl[0] = 'N';
}
if(ilvr){
jobvr[0] = 'V';
}else{
jobvr[0] = 'N';
}
int ierr = zhgeqz_(chtemp, jobvl, jobvr, n, ilo, ihi, &a[a_offset], lda, &b[
b_offset], ldb, &alpha[1], &beta[1], &vl[vl_offset], ldvl, &vr[
vr_offset], ldvr, &work[iwrk], 2*n + 1 - iwrk, &rwork[irwrk]);
if (ierr != 0) {
if (ierr > 0 && ierr <= (int)n) {
return ierr;
} else if (ierr > (int)n && ierr <= (int)n << 1) {
return ierr - n;
} else {
return n + 1;
}
return ierr;
}
// Compute Eigenvectors
// (Real Workspace: need 2*N)
// (Complex Workspace: need 2*N)
if (ilv) {
size_t in;
ierr = ztgevc_("B", ldumma, n, &a[a_offset], lda, &b[b_offset], ldb,
&vl[vl_offset], ldvl, &vr[vr_offset], ldvr, n, &in, &work[
iwrk], &rwork[irwrk]);
if (ierr != 0) {
return n+2;
}
// Undo balancing on VL and VR and normalization
// (Workspace: none needed)
if (ilvl) {
zggbak_("P", "L", n, ilo, ihi, &rwork[ileft], &rwork[iright], n, &vl[vl_offset], ldvl);
for (size_t jc = 1; jc <= n; ++jc) {
temp = 0.;
for (size_t jr = 1; jr <= n; ++jr) {
double abs1vl = RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(vl[jr+jc*ldvl]);
if(abs1vl > temp){ temp = abs1vl; }
}
if (temp >= smlnum) {
temp = 1. / temp;
for (size_t jr = 1; jr <= n; ++jr) {
vl[jr+jc*ldvl] *= temp;
}
}
}
}
if (ilvr) {
zggbak_("P", "R", n, ilo, ihi, &rwork[ileft], &rwork[iright], n, &vr[vr_offset], ldvr);
for (size_t jc = 1; jc <= n; ++jc) {
temp = 0.;
for (size_t jr = 1; jr <= n; ++jr) {
double abs1vr = RNP::TBLAS::_RealOrComplexChooser<std::complex<double> >::_abs1(vr[jr+jc*ldvr]);
if(abs1vr > temp){ temp = abs1vr; }
}
if (temp >= smlnum) {
temp = 1. / temp;
for (size_t jr = 1; jr <= n; ++jr) {
vr[jr+jc*ldvr] *= temp;
}
}
}
}
}
// Undo scaling if necessary
if (ilascl) {
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, anrmto, anrm, n, 1, &alpha[1], n);
}
if (ilbscl) {
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, bnrmto, bnrm, n, 1, &beta[1], n);
}
return 0;
}
// Computes for a pair of N-by-N complex nonsymmetric matrices (A,B),
// the generalized eigenvalues, the generalized complex Schur form
// (S, T), and optionally left and/or right Schur vectors (VSL and
// VSR). This gives the generalized Schur factorization
// (A,B) = ( (VSL)*S*(VSR)^H, (VSL)*T*(VSR)^H )
// where (VSR)^H is the conjugate-transpose of VSR.
// A generalized eigenvalue for a pair of matrices (A,B) is a scalar w
// or a ratio alpha/beta = w, such that A - w*B is singular. It is
// usually represented as the pair (alpha,beta), as there is a
// reasonable interpretation for beta=0, and even for both being zero.
// A pair of matrices (S,T) is in generalized complex Schur form if S
// and T are upper triangular and, in addition, the diagonal elements
// of T are non-negative real numbers.
// Arguments
// =========
// N The order of the matrices A, B, VSL, and VSR. N >= 0.
// A (input/output) COMPLEX*16 array, dimension (LDA, N)
// On entry, the first of the pair of matrices.
// On exit, A has been overwritten by its generalized Schur
// form S.
// LDA The leading dimension of A. LDA >= max(1,N).
// B On entry, the second of the pair of matrices.
// On exit, B has been overwritten by its generalized Schur
// form T.
// LDB The leading dimension of B. LDB >= max(1,N).
// ALPHA (output) COMPLEX*16 array, dimension (N)
// BETA (output) COMPLEX*16 array, dimension (N)
// On exit, ALPHA(j)/BETA(j), j=1,...,N, will be the
// generalized eigenvalues. ALPHA(j), j=1,...,N and BETA(j),
// j=1,...,N are the diagonals of the complex Schur form (A,B)
// of the output. The BETA(j) will be non-negative real.
// Note: the quotients ALPHA(j)/BETA(j) may easily over- or
// underflow, and BETA(j) may even be zero. Thus, the user
// should avoid naively computing the ratio alpha/beta.
// However, ALPHA will be always less than and usually
// comparable with norm(A) in magnitude, and BETA always less
// than and usually comparable with norm(B).
// VSL (output) COMPLEX*16 array, dimension (LDVSL,N)
// If VSL != NULL, VSL will contain the left Schur vectors.
// Ignored if NULL
// LDVSL The leading dimension of the matrix VSL. LDVSL >= 1, and
// if VSL != NULL, LDVSL >= N.
// VSR (output) COMPLEX*16 array, dimension (LDVSR,N)
// If VSR != NULL, VSR will contain the right Schur vectors.
// LDVSR The leading dimension of the matrix VSR. LDVSR >= 1, and
// if VSR != NULL, LDVSR >= N.
// WORK (workspace/output) COMPLEX*16 array, dimension (MAX(1,2*N))
// RWORK (workspace) DOUBLE PRECISION array, dimension (8*N)
// return: = 0: successful exit
// < 0: if INFO = -i, the i-th argument had an illegal value.
// =1,...,N:
// The QZ iteration failed. (A,B) are not in Schur
// form, but ALPHA(j) and BETA(j) should be correct for
// j=INFO+1,...,N.
// > N: =N+1: other than QZ iteration failed in ZHGEQZ
int RNP::GeneralizedSchurDecomposition(size_t n,
std::complex<double> *a, size_t lda, std::complex<double> *b, size_t ldb,
std::complex<double> *alpha, std::complex<double> *beta,
std::complex<double> *vsl, size_t ldvsl, std::complex<double> *vsr, size_t ldvsr,
std::complex<double> *work, double *rwork)
{
using namespace std;
/* System generated locals */
size_t a_offset, b_offset, vsl_offset, vsr_offset;
/* Local variables */
int ihi, ilo;
double anrm, bnrm;
int itau, iwrk;
int ileft, icols;
int irwrk, irows;
bool ilascl, ilbscl;
int iright;
double anrmto;
double bnrmto;
const bool ilvsl = (NULL != vsl);
const bool ilvsr = (NULL != vsr);
/* Parameter adjustments */
a_offset = 1 + lda;
a -= a_offset;
b_offset = 1 + ldb;
b -= b_offset;
--alpha;
--beta;
vsl_offset = 1 + ldvsl;
vsl -= vsl_offset;
vsr_offset = 1 + ldvsr;
vsr -= vsr_offset;
--work;
--rwork;
if (n < 0) {
return -1;
} else if (lda < max((size_t)1,n)) {
return -3;
} else if (ldb < max((size_t)1,n)) {
return -5;
} else if (ldvsl < 1 || ilvsl && ldvsl < n) {
return -9;
} else if (ldvsr < 1 || ilvsr && ldvsr < n) {
return -11;
}
if (n == 0) {
return 0;
}
/* Get machine constants */
const double eps = 2*std::numeric_limits<double>::epsilon();
const double smlnum = sqrt(std::numeric_limits<double>::min()) / eps;
const double bignum = 1. / smlnum;
/* Scale A if max element outside range [SMLNUM,BIGNUM] */
RNP::TLASupport::CheapMatrixNorm<'M'>(n, n, &a[a_offset], lda, &anrm);
ilascl = false;
if (anrm > 0. && anrm < smlnum) {
anrmto = smlnum;
ilascl = true;
} else if (anrm > bignum) {
anrmto = bignum;
ilascl = true;
}
if (ilascl) {
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, anrm, anrmto, n, n, &a[a_offset], lda);
}
/* Scale B if max element outside range [SMLNUM,BIGNUM] */
RNP::TLASupport::CheapMatrixNorm<'M'>(n, n, &b[b_offset], ldb, &bnrm);
ilbscl = false;
if (bnrm > 0. && bnrm < smlnum) {
bnrmto = smlnum;
ilbscl = true;
} else if (bnrm > bignum) {
bnrmto = bignum;
ilbscl = true;
}
if (ilbscl) {
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, bnrm, bnrmto, n, n, &b[b_offset], ldb);
}
/* Permute the matrix to make it more nearly triangular */
/* (Real Workspace: need 6*N) */
ileft = 1;
iright = n + 1;
irwrk = iright + n;
zggbal_("P", n, &a[a_offset], lda, &b[b_offset], ldb, &ilo, &ihi, &rwork[ileft], &rwork[iright], &rwork[irwrk]);
/* Reduce B to triangular form (QR decomposition of B) */
/* (Complex Workspace: need N, prefer N*NB) */
irows = ihi + 1 - ilo;
icols = n + 1 - ilo;
itau = 1;
iwrk = itau + irows;
RNP::TLASupport::QRFactorization(irows, icols, &b[ilo + ilo * ldb], ldb, &work[itau], &work[iwrk]);
/* Apply the orthogonal transformation to matrix A */
/* (Complex Workspace: need N, prefer N*NB) */
RNP::TLASupport::ApplyOrthognalMatrixFromElementaryReflectors<'L','C'>(
irows, icols, irows, &b[ilo + ilo * ldb], ldb, &
work[itau], &a[ilo + ilo * lda], lda, &work[iwrk]);
/* Initialize VSL */
/* (Complex Workspace: need N, prefer N*NB) */
if (ilvsl) {
RNP::TBLAS::SetMatrix<'F'>(n, n, std::complex<double>(0), std::complex<double>(1), &vsl[vsl_offset], ldvsl);
if (irows > 1) {
RNP::TBLAS::CopyMatrix<'L'>(irows-1, irows-1, &b[ilo + 1 + ilo * ldb], ldb, &vsl[ilo + 1 + ilo * ldvsl], ldvsl);
}
RNP::TLASupport::GenerateOrthognalMatrixFromElementaryReflectors(irows, irows, irows, &vsl[ilo + ilo * ldvsl], ldvsl, &work[itau], &work[iwrk]);
}
/* Initialize VSR */
if (ilvsr) {
RNP::TBLAS::SetMatrix<'F'>(n, n, std::complex<double>(0), std::complex<double>(1), &vsr[vsr_offset], ldvsr);
}
/* Reduce to generalized Hessenberg form */
/* (Workspace: none needed) */
if(ilvsl){
if(ilvsr){
RNP::TLASupport::GeneralizedHessenbergReduction<'V','V'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vsl[vsl_offset], ldvsl, &vsr[vsr_offset], ldvsr);
}else{
RNP::TLASupport::GeneralizedHessenbergReduction<'V','N'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vsl[vsl_offset], ldvsl, &vsr[vsr_offset], ldvsr);
}
}else{
if(ilvsr){
RNP::TLASupport::GeneralizedHessenbergReduction<'N','V'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vsl[vsl_offset], ldvsl, &vsr[vsr_offset], ldvsr);
}else{
RNP::TLASupport::GeneralizedHessenbergReduction<'N','N'>(n, ilo-1, ihi-1, &a[a_offset], lda, &b[b_offset], ldb, &vsl[vsl_offset], ldvsl, &vsr[vsr_offset], ldvsr);
}
}
/* Perform QZ algorithm, computing Schur vectors if desired */
/* (Complex Workspace: need N) */
/* (Real Workspace: need N) */
iwrk = itau;
char jobvl[1], jobvr[1];
if(ilvsl){
jobvl[0] = 'V';
}else{
jobvl[0] = 'N';
}
if(ilvsr){
jobvr[0] = 'V';
}else{
jobvr[0] = 'N';
}
int ierr = zhgeqz_("S", jobvl, jobvr, n, ilo, ihi, &a[a_offset], lda, &b[
b_offset], ldb, &alpha[1], &beta[1], &vsl[vsl_offset], ldvsl, &vsr[
vsr_offset], ldvsr, &work[iwrk], 2*n + 1 - iwrk, &rwork[irwrk]);
if (ierr != 0) {
if (ierr > 0 && ierr <= (int)n) {
return ierr;
} else if (ierr > (int)n && ierr <= 2*(int)n) {
return ierr - n;
} else {
return n + 1;
}
return ierr;
}
/* Apply back-permutation to VSL and VSR */
/* (Workspace: none needed) */
if (ilvsl) {
zggbak_("P", "L", n, ilo, ihi, &rwork[ileft], &rwork[iright], n, &vsl[vsl_offset], ldvsl);
}
if (ilvsr) {
zggbak_("P", "R", n, ilo, ihi, &rwork[ileft], &rwork[iright], n, &vsr[vsr_offset], ldvsr);
}
/* Undo scaling */
if (ilascl) {
RNP::TLASupport::RescaleMatrix<'U'>(0, 0, anrmto, anrm, n, n, &a[a_offset], lda);
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, anrmto, anrm, n, 1, &alpha[1], n);
}
if (ilbscl) {
RNP::TLASupport::RescaleMatrix<'U'>(0, 0, bnrmto, bnrm, n, n, &b[b_offset], ldb);
RNP::TLASupport::RescaleMatrix<'G'>(0, 0, bnrmto, bnrm, n, 1, &beta[1], n);
}
return 0;
}
| [
"zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2"
]
| [
[
[
1,
2517
]
]
]
|
f8752224a2cf775895ed987f88797fcaf81a8ba6 | e01dc698db930a300bd6e27412cd027635151f6a | /rodador-de-mepa/simulador-memoria/simulador-memoria/memoria/processador.cpp | 678f6dfc9d57a68de1c9bfadcec27c78b94616f3 | []
| no_license | lucasjcastro/rodador-de-mepa | becda6a9cdb6bbbec6e339f7bb52ec1dda48a89f | 933fe3f522f55c55e8056c182016f9f06280b3e0 | refs/heads/master | 2021-01-10T07:37:40.226661 | 2008-09-25T02:27:58 | 2008-09-25T02:27:58 | 46,521,554 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,017 | cpp | #include "processador.h"
#include "gerenciadorMemoria.h"
#include "coordenadas.h"
#include <iostream>
using namespace std;
processador::processador(memorias *alocar){
memorizu = alocar;
endereco = 0;
};
void processador::run(){
string instrucao = "finito!";
//int *enderecoFisico;
pagina sidePagina;
coordenadas enderecoFisico;
// Inicializa a paginação, recebendo o nome do primeiro processo a executar
nomeProcesso = proManager.iniciarPaginas(memorizu, memManager);
do{
// Envia o endereço lógico, recebe o físico - ou um sinal de erro neste
enderecoFisico = memManager.resolverEndereco(endereco, nomeProcesso);
// Se a página não foi encontrada, carrega páginas para a memória física
if(enderecoFisico.coord1 == -1){
cout << "Pretty bad actually." << endl;
system("pause");
proManager.carregarPaginas(memorizu, nomeProcesso, endereco, memManager);
std::cout << "Troca de páginas concluida." << endl;
enderecoFisico.coord1 = 0;
system("pause");
// Senão, carrega a instrução da memória física e "executa"
}else{
//cout << "Pagina que chegou: " << enderecoFisico.coord1 << " e linha: " << enderecoFisico.coord2 << endl << endl;
//system("pause");
sidePagina = memorizu->memoriaFisica[enderecoFisico.coord1];
instrucao = sidePagina.comando[enderecoFisico.coord2];
// "execução" de instrução
std::cout << instrucao << endl << endl;
system("pause");
endereco++;
}
}while(instrucao != "finito!");
cout << endl << endl << "I did it! I got the internets, darn it!!" << endl;
system("pause");
};
| [
"solenoide.spm@33f839a4-89d3-11dd-bc3c-d57f4316d18f"
]
| [
[
[
1,
54
]
]
]
|
0591a7cc0691bc40e8b36ccdc56aa7d25711d08b | 6eef3e34d3fe47a10336a53df1a96a591b15cd01 | /ASearch/Session/Certif.cpp | af3aef4ea6af5984cd5771678455be34cc5a8a08 | []
| no_license | praveenmunagapati/alkaline | 25013c233a80b07869e0fdbcf9b8dfa7888cc32e | 7cf43b115d3e40ba48854f80aca8d83b67f345ce | refs/heads/master | 2021-05-27T16:44:12.356701 | 2009-10-29T11:23:09 | 2009-10-29T11:23:09 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 4,968 | cpp | /*
© Vestris Inc., Geneva, Switzerland
http://www.vestris.com, 1994-1999 All Rights Reserved
_____________________________________________________
written by Daniel Doubrovkine - [email protected]
*/
#include <alkaline.hpp>
#include "Certif.hpp"
#include <Socket/Socket.hpp>
#include <Socket/Dns.hpp>
#include <Main/TraceTags.hpp>
CCertif::CCertif(const CString& Category, const CString& Extension) : CObject() {
m_Category = Category;
m_Extension = Extension;
m_Certified = false;
#ifdef _UNIX
m_Filename = CLocalPath::GetCurrentDirectory() + ".certificate";
#endif
#ifdef _WIN32
m_Filename = CLocalPath::GetCurrentDirectory() + "certif";
#endif
MakeHostCertifEntry();
}
CCertif::~CCertif(void) {
}
CString CCertif::CalculateCertif(void) const {
return CalculateCertif(true);
}
void CCertif::MakeHostCertifEntry(void) {
m_HostCertifEntry.Empty();
sockaddr_in LocalHost;
CVector<CString> PeerAddresses;
CVector<CString> PeerAliases;
CString LocalHostname;
CSocket :: m_pDNService->GetHostname(& LocalHostname);
CSocket :: m_pDNService->GetHostname(LocalHostname, LocalHost, & PeerAddresses, & PeerAliases);
if (PeerAddresses.GetSize()) {
m_HostCertifEntry += PeerAddresses[0];
} else {
m_HostCertifEntry += "127.0.0.1";
}
if (PeerAliases.GetSize()) {
m_HostCertifEntry += '\t';
m_HostCertifEntry += PeerAliases[0];
} else {
m_HostCertifEntry += "\tlocalhost";
}
#ifdef _UNIX
m_HostCertifEntry += "\t";
struct utsname UTS;
if (uname(& UTS) >= 0) {
m_HostCertifEntry += UTS.sysname;
} else {
m_HostCertifEntry += "UNIX";
}
m_HostCertifEntry += "\t";
#else
m_HostCertifEntry += "\tWINNT\t";
#endif
Trace(tagClient, levInfo, ("CCertif::MakeHostCertifEntry - {%s}.", m_HostCertifEntry.GetBuffer()));
}
CString CCertif::CalculateCertif(bool Encrypt) const {
CString Result = m_HostCertifEntry;
if (m_Category.GetLength()) Result+=m_Category;
if (Encrypt) {
Result = CEncryption::Encrypt(CEncryption::Encrypt(Result));
}
return Result;
}
bool CCertif::Certify(void) {
CLocalFile CertifFile(m_Filename + m_Extension);
if (CertifFile.OpenReadBinary()) {
CString Data;
CertifFile.Read(&Data);
if (Certify(Data)) return true;
}
m_Certified = false;
return false;
}
bool CCertif::IsValidCertificate(const CString& Key) const {
CString ICertif = CalculateCertif(false);
CVector<CString> ICertifVector;
CString::StrToVector(ICertif, '\t', &ICertifVector);
CString ICertifResult;
for (int i=(int) ICertifVector.GetSize()-1;i>=0;i--)
ICertifResult+=ICertifVector[i];
ICertifResult.Trim32();
CString DKey(Key); DKey = CEncryption::Decrypt(DKey); DKey = CEncryption::Decrypt(DKey); DKey.Trim32();
return (DKey == ICertifResult);
}
bool CCertif::Certify(const CString& Key) {
if (IsValidCertificate(Key)) {
m_Certified = true;
return true;
} else {
m_Certified = false;
return false;
}
}
void CCertif::CertifyFail(CHttpIo& Io, bool ShowLinks) {
long int CheckSum = 0;
unsigned int i = 0;
for (i=0;i<strlen(UnregBinary);i++) CheckSum+=UnregBinary[i];
for (i=0;i<strlen(UnregCertif);i++) CheckSum+=UnregCertif[i];
for (i=0;i<strlen(ManageCertif);i++) CheckSum+=ManageCertif[i];
if (!(strlen(UnregBinary)+strlen(UnregCertif)+strlen(ManageCertif))||(CheckSum != 12300)) {
int l=0xFF;
CString Tmp;
for (int ii=0;ii<(l*l);ii++) Tmp += ((char) ((char *) this)[ii]);
Io.Write(Tmp);
}
CString UnregString = "<h1><center>" + CEncryption::Decrypt(CString(UnregBinary)) + "</h1>\n";
if (ShowLinks)
UnregString += CEncryption::Decrypt(AdminCertif);
Io.Write(UnregString);
}
bool CCertif::WriteCertificate(const CString& Certificate) {
if (Certify(Certificate)) {
CLocalFile CertifFile(m_Filename + m_Extension);
if (CertifFile.Open(O_WRONLY|O_TRUNC|O_CREAT)) {
CertifFile.Write(Certificate);
}
m_Certified = true;
return true;
}
return false;
}
void CCertif::PopulateXmlTree(CXmlTree& XmlTree) const {
static const CString CertifXml(
"<certificate>" \
" <valid>0</valid>" \
" <request></request>" \
" <key></key>" \
"</certificate>");
XmlTree.SetXml(CertifXml);
if (m_Certified) {
XmlTree.SetValue("/certificate/valid", "1");
CLocalFile CertifFile(m_Filename + m_Extension);
if (CertifFile.OpenReadBinary()) {
CString Data;
CertifFile.Read(&Data);
Data.Trim32();
XmlTree.SetValue("/certificate/key", Data);
}
}
XmlTree.SetValue("/certificate/request", CalculateCertif());
}
| [
"[email protected]"
]
| [
[
[
1,
179
]
]
]
|
4d7bb7291db4a954ecfdba4daea619b36df61046 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /TextureShaderTile/main.cpp | 1ab10be0dc0527390e2b9f70d1e5e692b4c56e6e | []
| no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,230 | cpp | #include "TextureShaderTile.h"
#include "KeyboardHandler.h"
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
int main()
{
osg::ref_ptr< TextureShaderTile > plane = new TextureShaderTile;
// Create a Viewer.
osgViewer::Viewer viewer;
// add the stats handler
viewer.addEventHandler( new osgViewer::StatsHandler );
KeyboardHandler *key = new KeyboardHandler;
//передать Uniform смещения
key->SetOffsetX( plane->GetUniformOffsetX().get() );
key->SetOffsetY( plane->GetUniformOffsetY().get() );
key->SetScaleX( plane->GetUniformScaleX().get() );
key->SetScaleY( plane->GetUniformScaleY().get() );
key->SetOffsetScaleX( plane->GetUniformOffsetScaleX().get() );
key->SetOffsetScaleY( plane->GetUniformOffsetScaleY().get() );
viewer.addEventHandler( key );
//настройка камеры
viewer.getCamera()->setProjectionMatrixAsPerspective( 45.0, 1050.0 / 1680.0 , 1.0 , 30000.0 );
viewer.setSceneData( plane->getRootNode().get() );
viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
// Display, and main loop.
return viewer.run();
} | [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
]
| [
[
[
1,
43
]
]
]
|
808982763fef89089772cf36d45ce2b019311d85 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/CompilerSource/general/macro_integration.cpp | c37055fa0bcc756961c7d20afd1ad07a98af739a | []
| no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,075 | cpp | /********************************************************************************\
** **
** Copyright (C) 2008 Josh Ventura **
** **
** This file is a part of the ENIGMA Development Environment. **
** **
** **
** ENIGMA 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 3 of the license or any later version. **
** **
** This application and its source code is distributed AS-IS, 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 recieved a copy of the GNU General Public License along **
** with this code. If not, see <http://www.gnu.org/licenses/> **
** **
** ENIGMA is an environment designed to create games and other programs with a **
** high-level, fully compilable language. Developers of ENIGMA or anything **
** associated with ENIGMA are in no way responsible for its users or **
** applications created by its users, or damages caused by the environment **
** or programs made in the environment. **
** **
\********************************************************************************/
#include <string>
#include <cstdlib>
using namespace std;
#include "parse_basics.h"
#include "macro_integration.h"
void macro_push_info::grab(string id, string c, pt p) {
name = id;
code = c; pos = p;
}
void macro_push_info::release(string &c, pt &p) {
c = code; p = pos;
}
bool macro_recurses(string name, macro_stack_t &mymacrostack, unsigned mymacroind) {
for (unsigned int iii = 0; iii < mymacroind; iii++)
if (mymacrostack[iii].name == name)
return 1;
return 0;
}
pt skip_comments(const string& code, pt cwp) {
while (is_useless(code[cwp]) or (code[cwp]=='/' and (code[cwp+1]=='/' or code[cwp+1]=='*')))
{
if (code[cwp++] == '*') {
if (code[cwp] == '/') while (cwp < code.length() and code[cwp] != '\r' and code[cwp] != '\n') cwp++;
else { cwp += 2; while (cwp < code.length() and (code[cwp] != '/' or code[cwp-1] != '*')) cwp++; }
}
}
return cwp;
}
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
9f581bc3041cbb0e8c101a0e5b44b999ac4787ec | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/TextStatistics.cpp | 8359b462e727c5711351222d3a2da226f07e7471 | []
| no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,487 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "TextStatistics.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define debug(p) cout << #p << "=" << p << endl;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
#define pb push_back
class TextStatistics {
public:
double averageLength(string text) {
double ret=0.0;
if((int)text.size()==0) return 0.0;
vector<int> lens;
int len=0;
fors(i,text){
if(text[i]>='A' && text[i]<='z'){
len++;
}else{
if(len!=0) lens.pb(len);
len=0;
}
}
if(text[(int)text.size()-1]>='A' && text[(int)text.size()-1]<='z'){
lens.pb(len);
}
if(lens.empty()) lens.pb(0);
ret = (double)accumulate(all(lens),0)/(double)lens.size();
return ret;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
static const double MAX_DOUBLE_ERROR = 1e-9; static bool topcoder_fequ(double expected, double result) { if (isnan(expected)) { return isnan(result); } else if (isinf(expected)) { if (expected > 0) { return result > 0 && isinf(result); } else { return result < 0 && isinf(result); } } else if (isnan(result) || isinf(result)) { return false; } else if (fabs(result - expected) < MAX_DOUBLE_ERROR) { return true; } else { double mmin = min(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); double mmax = max(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); return result > mmin && result < mmax; } }
double moj_relative_error(double expected, double result) { if (isnan(expected) || isinf(expected) || isnan(result) || isinf(result) || expected == 0) return 0; return fabs(result-expected) / fabs(expected); }
int verify_case(int casenum, const double &expected, const double &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (topcoder_fequ(expected, received)) {
verdict = "PASSED";
double rerr = moj_relative_error(expected, received);
if (rerr > 0) {
sprintf(buf, "relative error %.3e", rerr);
info.push_back(buf);
}
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
case 0: {
string text = "This is div2 easy problem.";
double expected__ = 4.0;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 1: {
string text = "Hello, world!";
double expected__ = 5.0;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 2: {
string text = "Simple";
double expected__ = 6.0;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 3: {
string text = "";
double expected__ = 0.0;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 4: {
string text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
double expected__ = 50.0;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}
// custom cases
case 5: {
string text = ",";
double expected__ = 0.0;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}
/* case 6: {
string text = ;
double expected__ = ;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 7: {
string text = ;
double expected__ = ;
clock_t start__ = clock();
double received__ = TextStatistics().averageLength(text);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
]
| [
[
[
1,
222
]
]
]
|
f30e003cd344c5a7040fa9d1aba214e99c380ea9 | 57508120082342c08bed234569434262b83557c2 | /blk_file.cpp | acb47628a6c822396894be559b0b8b2d5b3f8511 | []
| no_license | chtlp/mv-tp-r-tree | a3214b074912f8e56a0e5fc8219fe9da97fa644a | f19fe09eb4966181739424b93e9de953f963840a | refs/heads/master | 2020-07-22T01:00:47.582484 | 2011-05-02T05:36:58 | 2011-05-02T05:36:58 | 32,191,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,968 | cpp | /* seq_file.cc :: Implementation einer sequentiellen Filestruktur durch
gecachede Bloecke. Tobias Mayr(mayrt) 4/95
soll einmal Alternative zu SequentialList sein */
#include "blk_file.h"
void error(char *t, bool ex);
//================================================================
//===========================BlockFile============================
// Interne Funktionen:
void BlockFile::fwrite_number(int value)
// schreibt an SEEK_CUR eine Zahl, siehe fread_number
{
put_bytes((char *) &value,sizeof(int));
}
int BlockFile::fread_number()
// liest von SEEK_CUR eine Zahl, siehe fwrite_number
{
char ca[sizeof(int)];
get_bytes(ca,sizeof(int));
return *((int *)ca);
}
// Zugriffsfunktionen:-------------------------------------------------
BlockFile::BlockFile(char* name,int b_length)
{
char *buffer;
int l;
filename = new char[strlen(name) + 1];
strcpy(filename,name);
blocklength = b_length; // nur fuer neue Files relevant
number = 0;
iocount=0;
if((fp=fopen(name,"rb+"))!=0) // zum update oeffnen
// bekanntes File
{
new_flag = FALSE;
blocklength = fread_number();
// printf("Read number: %d\n", blocklength);
number = fread_number(); // Gesamtzahl der Bloecke lesen
}
else
// unbekanntes File
{
if (blocklength < BFHEAD_LENGTH) {
error("BlockFile::BlockFile: Blocks zu kurz\n",TRUE);
}
fp=fopen(filename,"wb+");
if (fp == 0)
error("BlockFile::new_file: Schreibfehler",TRUE);
new_flag = TRUE;
fwrite_number(blocklength);
// Gesamtzahl Bloecke ist 0
fwrite_number(0);
buffer = new char[(l=blocklength-(int)ftell(fp))];
memset(buffer, 0, sizeof(buffer));
put_bytes(buffer,l);
delete [] buffer;
}
fseek(fp,0,SEEK_SET); // auf Anfang (Header) gehen
act_block=0; // aktueller Block ist der Header
}
BlockFile::~BlockFile()
{
delete[] filename;
fclose(fp);
}
void BlockFile::read_header(char* buffer)
{
fseek(fp,BFHEAD_LENGTH,SEEK_SET);
get_bytes(buffer,blocklength-BFHEAD_LENGTH);
if(number<1)
{
fseek(fp,0,SEEK_SET);
act_block=0;
}
else
act_block=1;
}
void BlockFile::set_header(char* header)
{
fseek(fp,BFHEAD_LENGTH,SEEK_SET);
put_bytes(header,blocklength-BFHEAD_LENGTH);
if(number<1)
{
fseek(fp,0,SEEK_SET);
act_block=0;
}
else
act_block=1;
}
bool BlockFile::read_block(Block b,int pos)
// pos bezieht sich auf externe Nummerierung beginnend bei 0 NACH dem Header
{
// Externe Num. --> interne Num.
pos++;
if (pos<=number && pos>0)
seek_block(pos);
else
{
error("BlockFile::read_block--The requested block number has not been allocated\n",true);
return FALSE;
}
get_bytes(b,blocklength);
if (pos+1>number)
{
fseek(fp,0,SEEK_SET);
act_block=0;
}
else
act_block=pos+1;
iocount++;
return TRUE;
}
bool BlockFile::write_block(const Block block,int pos)
// pos bezieht sich auf externe Nummerierung beginnend bei 0 NACH dem Header
{
// Externe Num. --> interne Num.
pos++;
if (pos<=number && pos>0)
seek_block(pos);
else
return FALSE;
put_bytes(block,blocklength);
if (pos+1>number)
{
fseek(fp,0,SEEK_SET);
act_block=0;
}
else
act_block=pos+1;
//iocount++; I disabled this line to make sure we only count reading's in a query
return TRUE;
}
int BlockFile::append_block(const Block block)
// Das Resulat bezieht sich auf externe Nummerierung
{
fseek(fp,0,SEEK_END);
put_bytes(block,blocklength);
number++;
fseek(fp,sizeof(int),SEEK_SET);
fwrite_number(number);
fseek(fp,-blocklength,SEEK_END);
// -1 zur Umrechnung in externe Num.
return (act_block=number)-1;
}
bool BlockFile::delete_last_blocks(int num)
{
if (num>number)
return FALSE;
#ifdef UNIX
if (truncate(filename,(number-num+1)*blocklength) != 0)
error("BlockFile::delete_last_blocks : truncate-Fehler",TRUE);
#endif
number -= num;
fseek(fp,sizeof(int),SEEK_SET);
fwrite_number(number);
fseek(fp,0,SEEK_SET);
act_block=0;
return TRUE;
}
//================================================================
//========================CachedBlockFile=========================
// Interne Funktionen:--------------------------------------------
int CachedBlockFile::next()
// liefert freien Platz im Cache oder -1
// ptr rotiert ueber den vollen Cache, um diesen gleichmaessig
// 'auszulasten'
{
int ret_val, tmp;
if (cachesize==0)
return -1;
else
if (fuf_cont[ptr]==free)
{
ret_val = ptr++;
if(ptr==cachesize)
ptr=0;
return ret_val;
}
else
{
tmp= (ptr+1)%cachesize;
//find the first free block
while (tmp!=ptr && fuf_cont[tmp]!=free)
if(++tmp==cachesize)
tmp=0;
if (ptr==tmp) //failed to find a free block
{
/*
if(fuf_cont[ptr]==fixed)
{
tmp=ptr+1;
if (tmp==cachesize)
tmp=0;
// suche unfixed Pos.
while(tmp!=ptr && fuf_cont[tmp]!=used)
if(++tmp==cachesize)
//tmp rotiert ueber der Liste
tmp=0;
if (ptr==tmp)
// alles fix
return -1;
else
// tmp zeigt auf used
ptr=tmp;
}
*/
// select a victim page to be written back to disk
int lru_index=0; // the index of the victim page
for (int i=1; i<cachesize; i++)
if (LRU_indicator[i]>LRU_indicator[lru_index])
lru_index=i;
ptr = lru_index;
BlockFile::write_block(cache[ptr],cache_cont[ptr]-1);
fuf_cont[ptr]=free;
ret_val=ptr++;
if (ptr==cachesize)
ptr=0;
return ret_val;
}
else
return tmp;
}
}
int CachedBlockFile::in_cache(int index)
// liefert Pos. eines Blocks im Cache, sonst -1
{
int i;
for (i = 0; i<cachesize; i++)
if (cache_cont[i] == index && fuf_cont[i] != free)
{
LRU_indicator[i]=0;
return i;
}
else if (fuf_cont[i] != free)
LRU_indicator[i]++; // increase indicator for this block
return -1;
}
// Zugriffsfunktionen:-------------------------------------------------
CachedBlockFile::CachedBlockFile(char* name,int blength, int csize)
: BlockFile(name,blength)
{
int i;
pagefault=0;
ptr=0;
if (csize>=0)
cachesize=csize;
else
error("CachedBlockFile::CachedBlockFile: neg. Cachesize",TRUE);
cache_cont = new int[cachesize];
fuf_cont = new uses[cachesize];
LRU_indicator = new int[cachesize];
for (i=0; i<cachesize; i++)
{
cache_cont[i]=0; // 0 bedeutet Cache unbenutzt (leer)
fuf_cont[i]=free;
}
cache = new char*[cachesize];
for (i=0; i<cachesize; i++)
cache[i] = new char[get_blocklength()];
}
CachedBlockFile::~CachedBlockFile()
{
flush();
delete[] cache_cont;
delete[] fuf_cont;
delete[] LRU_indicator;
for (int i=0;i<cachesize;i++)
delete[] cache[i];
delete[] cache;
printf("Total I/O: %d\n",pagefault);
}
bool CachedBlockFile::read_block(Block block,int index)
{
int c_ind;
index++; // Externe Num. --> interne Num.
if(index<=get_num_of_blocks() && index>0)
{
if((c_ind=in_cache(index))>=0)
// gecached?
{
memcpy(block,cache[c_ind],get_blocklength());
}
else
// nicht im Cache
{
pagefault++;
c_ind = next();
if (c_ind >= 0)
// Ist im Cache noch was frei?
{
BlockFile::read_block(cache[c_ind],index-1); // ext. Num.
cache_cont[c_ind]=index;
fuf_cont[c_ind]=used;
LRU_indicator[c_ind] = 0;
memcpy(block,cache[c_ind],get_blocklength());
}
else
// kein Cache mehr verfuegbar
BlockFile::read_block(block,index-1); // read-through (ext.Num.)
}
return TRUE;
}
else
return FALSE;
}
bool CachedBlockFile::write_block(const Block block,int index)
{
int c_ind;
index++; // Externe Num. --> interne Num.
if(index <= get_num_of_blocks() && index > 0)
{
c_ind = in_cache(index);
if(c_ind >= 0) // gecached?
memcpy(cache[c_ind], block, get_blocklength());
else // nicht im C.
{
c_ind = next();
if (c_ind >= 0)
// im Cache was frei? (cachesize==0?)
{
memcpy(cache[c_ind],block,get_blocklength());
cache_cont[c_ind]=index;
fuf_cont[c_ind]=used;
}
else
// kein Cache verfuegbar
// write-through (ext.Num.)
BlockFile::write_block(block,index-1);
}
return TRUE;
}
else
return FALSE;
}
bool CachedBlockFile::fix_block(int index)
// gefixte Bloecke bleiben immer im Cache
{
int c_ind;
index++; // Externe Num. --> interne Num.
if (index<=get_num_of_blocks() && index>0)
{
if((c_ind=in_cache(index))>=0) // gecached?
fuf_cont[c_ind]=fixed;
else // nicht im C.
if((c_ind=next())>=0) // im Cache was frei?
{
BlockFile::read_block(cache[c_ind],index-1); // ext.Num.
cache_cont[c_ind]=index;
fuf_cont[c_ind]=fixed;
}
else // kein Cache verfuegbar
return FALSE;
return TRUE;
}
else
return FALSE;
}
bool CachedBlockFile::unfix_block(int index)
// Fixierung eines Blocks durch fix_block wieder aufheben
{
int i;
i =0;
index++; // Externe Num. --> interne Num.
if(index<=get_num_of_blocks() && index>0)
{
while(i<cachesize && (cache_cont[i]!=index || fuf_cont[i]==free))
i++;
if (i!=cachesize)
fuf_cont[i]=used;
return TRUE;
}
else
return FALSE;
}
void CachedBlockFile::unfix_all()
// Hebt alle Fixierungen auf
{
int i;
for (i=0; i<cachesize; i++)
if (fuf_cont[i]==fixed)
fuf_cont[i]=used;
}
void CachedBlockFile::set_cachesize(int size)
// sichert und loescht alten Cache, und baut neuen auf (size>=0)
{
int i;
if (size>=0)
{
ptr=0;
flush();
for(i=0; i<cachesize; i++)
delete[] cache[i];
delete[] cache;
delete[] cache_cont;
delete[] fuf_cont;
cachesize = size;
cache_cont = new int[cachesize];
fuf_cont = new uses[cachesize];
for (i=0; i<cachesize; i++)
{
cache_cont[i]=0; // 0 bedeutet Cache unbenutzt (leer)
fuf_cont[i]=free;
}
cache = new char*[cachesize];
for (i=0; i<cachesize; i++)
cache[i] = new char[get_blocklength()];
}
else
error("CachedBlockFile::set_cachesize : neg. cachesize",TRUE);
}
void CachedBlockFile::flush()
// schreibt den Cache auf Platte, gibt ihn nicht frei
{
int i;
for (i=0; i<cachesize; i++)
if (fuf_cont[i]!=free) // Cache besetzt?
BlockFile::write_block(cache[i], cache_cont[i]-1); // ext.Num.
}
| [
"chnttlp@5fd1ae55-4be7-57d6-6470-c356376a0a7e"
]
| [
[
[
1,
486
]
]
]
|
088c25cfc00807cf6b26dd58c7a884efc333de3c | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientShellDLL/ClientShellShared/JumpVolumeFX.h | 18ce18dbbad56b6a54c5ac34ba94ef1530ccdf68 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | h | // ----------------------------------------------------------------------- //
//
// MODULE : JumpVolumeFX.h
//
// PURPOSE : JumpVolume special fx class - Definition
//
// CREATED : 1/24/02
//
// (c) 2002 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#ifndef __JUMP_VOLUME_FX_H__
#define __JUMP_VOLUME_FX_H__
//
// Includes...
//
#include "SpecialFX.h"
class CJumpVolumeFX : public CSpecialFX
{
public : // Methods...
CJumpVolumeFX();
~CJumpVolumeFX();
virtual LTBOOL Init( HLOCALOBJ hServObj, ILTMessage_Read *pMsg );
virtual LTBOOL OnServerMessage( ILTMessage_Read *pMsg );
virtual uint32 GetSFXID() { return SFX_JUMPVOLUME_ID; }
inline LTVector GetVelocity() const { return m_vVelocity; }
protected : // Members...
LTVector m_vVelocity;
};
#endif // __JUMP_VOLUME_FX_H__ | [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
0c52736cd96601611c7d621b18b739809e2be5af | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/World/Camera.h | 82d920488b189e8effa245012973a332da89b28a | []
| no_license | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,144 | h | #pragma once
#include "Entity.h"
namespace P3D
{
namespace World
{
/*
Camera can loads camera transform into OpenGL.
*/
class Camera : public Entity
{
public:
Camera(World* world);
/*
Return entity class.
*/
override EntityClass GetClass() const { return Entity_Camera; }
/*
Loads projection & transform matrix into OpenGL system.
(replaces current matrices).
Take into account that camera can be inside CompoundEntity.
*/
void LoadCameraTransform() const;
/*
Get field of view value expressed in radians.
*/
inline float GetFOV() const { return _fov;}
/*
Set field of view value expressed in radians.
*/
inline void SetFOV(float fov) { _fov = fov; _frustum.Invalidate(); }
/*
Get 'screen plane width' / 'screen plane height'.
*/
inline float GetAspectRatio() const { return _aspectRatio; }
/*
Set 'screen plane width' / 'screen plane height'.
*/
inline void SetAspectRatio(float aspectRatio) { _aspectRatio = aspectRatio; _frustum.Invalidate(); }
/*
Get near projection plane.
*/
inline float GetNearPlane() const { return _nearPlane; }
/*
Set near projection plane.
*/
inline void SetNearPlane(float nearPlane) { _nearPlane = nearPlane; _frustum.Invalidate(); }
/*
Get far projection plane.
*/
inline float GetFarPlane() const { return _farPlane; }
/*
Set far projection plane.
*/
inline void SetFarPlane(float farPlane) { _farPlane = farPlane; _frustum.Invalidate(); }
/*
Get coresponding Frustum object in camera space.
*/
inline const Frustum& GetFrustum() const { return _frustum(); }
/*
Return sphere (in object space) that encloses all frustrum.
*/
inline const Sphere& GetBoundingSphere() const { _frustum.Update(); return _sphere; }
/*
Rotate camera so it looks at specific direction.
*/
void LookAt(const Vector& direction, const Vector& up = Vector(0, 0, 1));
protected:
virtual void DoRender(const RendererContext& params);
private:
void RecalculateFrustum(Frustum& frustum)
{
frustum.Construct(_fov, _aspectRatio, _nearPlane, _farPlane);
_sphere = frustum.GetBoundingSphere();
}
protected:
float _fov;
float _aspectRatio;
float _nearPlane, _farPlane;
Lazy<Camera, Frustum> _frustum;
Sphere _sphere;
};
}
} | [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
]
| [
[
[
1,
103
]
]
]
|
4439bfad1215c9dfa94b6ab6e1b7824aa07016ba | 09ea547305ed8be9f8aa0dc6a9d74752d660d05d | /smf/smfservermodule/smfserver/server/smfserver.cpp | 37e2268e65319876311f8bbfa0ecb59301223624 | []
| no_license | SymbianSource/oss.FCL.sf.mw.socialmobilefw | 3c49e1d1ae2db8703e7c6b79a4c951216c9c5019 | 7020b195cf8d1aad30732868c2ed177e5459b8a8 | refs/heads/master | 2021-01-13T13:17:24.426946 | 2010-10-12T09:53:52 | 2010-10-12T09:53:52 | 72,676,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,490 | cpp | /**
* Copyright (c) 2010 Sasken Communication Technologies Ltd.
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html"
*
* Initial Contributors:
* Chandradeep Gandhi, Sasken Communication Technologies Ltd - Initial contribution
*
* Contributors:
* Manasij Roy, Nalina Hariharan
*
* Description:
* SMF Server component which handles the client requests and delegates
* them properly to the appropriate component
*
*/
#include <QDebug>
#include <qglobal.h>
#include <smfcontact.h>
#include <smfgroup.h>
#include <smfpost.h>
#include <smflocation.h>
#include <smfpicture.h>
#include <smfcomment.h>
#include <smfcredmgrclient.h>
#include <smfrelationmgr.h>
#include "smfserver.h"
#include "smfpluginmanager.h"
#include "smftransportmanager.h"
#include "dsm.h"
#ifdef Q_OS_SYMBIAN
#include "smfserversymbian_p.h"
#else
#include "smfserverqt_p.h"
#include "smfserverqtsession.h"
#endif
SmfServer::SmfServer(QObject* parent)
: QObject(parent)
{
m_transportManager = NULL;
m_pluginManager = NULL;
m_credentialMngr = NULL;
}
SmfServer::~SmfServer()
{
qDebug()<<"Inside Smfserver::~SmfServer()";
if(m_transportManager)
delete m_transportManager;
if(m_pluginManager)
delete m_pluginManager;
if(m_credentialMngr)
delete m_credentialMngr;
if(m_SmfServerPrivate)
{
delete m_SmfServerPrivate;
m_SmfServerPrivate = NULL;
}
}
bool SmfServer::startServer()
{
bool success = false;
//Initialize all the component handles
SmfTransportInitializeResult networkStatus = prepareTransport();
m_pluginManager = SmfPluginManager::getInstance(this);
qDebug()<<"After m_pluginManager construction";
// m_dataStoreManager = new SmfDataStoreManager();
#ifdef Q_OS_SYMBIAN
//Initialize private implementation
TRAPD(err, m_SmfServerPrivate = SmfServerSymbian::NewL(CActive::EPriorityStandard,this));
qDebug()<<"SmfServerSymbian::NewL() = "<<err;
if( KErrNone != err )
return success;
TInt error = m_SmfServerPrivate->Start( KSmfServerName );
qDebug()<<"m_SmfServerPrivate->Start = "<<error;
RSemaphore semaphore;
User::LeaveIfError( semaphore.OpenGlobal( KSmfServerSemaphoreName ) );
// Semaphore opened ok
semaphore.Signal();
semaphore.Close();
if( KErrNone == error )
{
success = true;
}
else
{
//error
return success;
}
#else
// For non-symbian platforms
m_SmfServerPrivate = new SmfServerQt(this);
success = m_SmfServerPrivate->start();
if (!success)
{
return success;
}
#endif
m_credentialMngr = new SmfCredMgrClient();
return success;
}
//Note:- Almost all the following APIs are called by private impl via the handle
/**
* This API is called by the private impl when client is authorized
* @param interfaceID Interface id, provided by the private impl (it gets it from client)
* @param pluginIDMap Map of plugins who implement this interface and corresponding provider,
* this is returned to the private impl
* It calls PM to get the list. Note:- PM may return SmfProviderBase which is superset of SmfProvider.
* TODO:- session should store this map for future ref?
*/
void SmfServer::getPlugins(const SmfInterfaceID& interfaceID, QMap<SmfPluginID,SmfProvider>& pluginIDMap)
{
qDebug()<<"Inside SmfServer::getPlugins()";
m_pluginManager->getPlugins(interfaceID,pluginIDMap);
}
SmfPluginID SmfServer::getPlugin(const SmfInterfaceID& interfaceID,SmfProvider provider)
{
qDebug()<<"Inside SmfServer::getPlugin()";
SmfPluginID id;
m_pluginManager->getPluginId(interfaceID,provider, id);
return id;
}
/**
* This API is called by the private impl to get a list of authorized plugins from CM
* @param list List of plugins to be filtered
* @param authList List of authorised plugins filled by CM
* this is returned to the private impl
* It calls CMclient to get the list synchronously
* TODO:- session should store this for future ref?
*/
void SmfServer::getAuthorizedPlugins(QList<SmfPluginID>& list,QList<SmfPluginID>& authList)
{
qDebug()<<"Inside SmfServer::getAuthorizedPlugins()";
authList.clear();
for(int i=0;i<list.count();i++)
{
bool isAuthorized = false;
isAuthorized = m_credentialMngr->CheckPluginAuthentication(list[i]);
if(isAuthorized)
authList.append(list[i]);
}
}
SmfTransportInitializeResult SmfServer::prepareTransport()
{
m_transportManager = SmfTransportManager::getInstance();
//checking the network status
SmfTransportInitializeResult networkStatus = m_transportManager->initializeTransport();
qDebug()<<"m_transportManager->initializeTransport() return = "<<networkStatus;
return networkStatus;
}
SmfError SmfServer::sendToPluginManager ( int requestID, SmfPluginID pluginID,
SmfInterfaceID interfaceID, SmfRequestTypeID requestTypeID,
QByteArray dataForPlugin )
{
qDebug()<<"Inside SmfServer::sendToPluginManager()";
Q_UNUSED(interfaceID)
#ifdef DETAILEDDEBUGGING
qDebug()<<"Request ID = "<<requestID;
qDebug()<<"PluginID = "<<pluginID;
qDebug()<<"Interface = "<<interfaceID;
qDebug()<<"RequestType = "<<requestTypeID;
#endif
//TODO:-PM should take page info too
SmfError err = m_pluginManager->createRequest(requestID,pluginID,requestTypeID,dataForPlugin);
qDebug()<<"m_pluginManager->createRequest() ret value = "<<err;
return err;
}
/**
* Request the Plugin manager to get the data.
* @param requestID Corresponds to a client's session
* @param pluginID Plugin for which the request is intended
* @param interfaceID Interface name
* @param dataForPlugin Data to be sent for this request
*/
SmfError SmfServer::sendToPluginManager ( SmfPluginID pluginID,
SmfInterfaceID interfaceID, SmfRequestTypeID requestTypeID,
QByteArray dataForPlugin, QByteArray &outputData)
{
qDebug()<<"Inside SmfServer::sendToPluginManager() for sync req";
Q_UNUSED(interfaceID)
#ifdef DETAILEDDEBUGGING
qDebug()<<"PluginID = "<<pluginID;
qDebug()<<"Interface = "<<interfaceID;
qDebug()<<"RequestType = "<<requestTypeID;
#endif
//TODO:-PM should take page info too
SmfError err = m_pluginManager->createSyncRequest(pluginID,requestTypeID,dataForPlugin, outputData);
qDebug()<<"m_pluginManager->createSyncRequest() = "<<err;
return err;
}
SmfError SmfServer::sendToDSM ( QByteArray qtdataForDSM, SmfRequestTypeID opcode,
QByteArray& qtdataFromDSM )
{
qDebug()<<"Inside SmfServer::sendToDSM()";
SmfError err = SmfNoError;
DataStoreManager* dsm = DataStoreManager::getDataStoreManager();
//Note:- deserialization and formation of user profile and social profile are done by server
QDataStream readStream(&qtdataForDSM,QIODevice::ReadOnly);
QDataStream writeStream(&qtdataFromDSM,QIODevice::WriteOnly);
quint8 flag = 0;
switch(opcode)
{
case SmfRelationCreate:
{
//read the incoming data
SmfProvider *provider = new SmfProvider();
SmfContact *contact = new SmfContact();
readStream>>flag;
if(flag)
readStream>>*provider;
else
{
delete provider;
provider = NULL;
}
readStream>>flag;
if(flag)
readStream>>*contact;
else
{
delete contact;
contact = NULL;
}
SmfRelationId relnId;
relnId.clear();
err = dsm->create(relnId,provider,contact);
writeStream<<relnId;
if(provider != NULL)
delete provider;
if(contact != NULL)
delete contact;
}
break;
case SmfRelationAssociate:
{
SmfRelationId relnId;
SmfContact *contact = new SmfContact();
SmfProvider *provider = new SmfProvider();
readStream>>relnId;
readStream>>flag;
if(flag)
readStream>>*contact;
else
{
delete contact;
contact = NULL;
}
readStream>>flag;
if(flag)
readStream>>*provider;
else
{
delete provider;
provider = NULL;
}
err = dsm->associate(relnId,contact,provider);
int errInt = err;
writeStream<<errInt;
if(contact != NULL)
delete contact;
if(provider != NULL)
delete provider;
}
break;
case SmfRelationRemove:
{
SmfRelationId relnId;
SmfContact *contact = new SmfContact();
readStream>>relnId;
readStream>>flag;
if(flag)
readStream>>*contact;
else
{
delete contact;
contact = NULL;
}
err = dsm->remove(relnId, contact);
int errInt = err;
writeStream<<errInt;
if(NULL != contact)
delete contact;
break;
}
case SmfRelationSearchById:
{
SmfRelationId relnId;
readStream>>relnId;
SmfRelationItem* relnItem = dsm->searchById(relnId);
quint8 flag = 1;
if(relnItem)
{
writeStream<<flag;
writeStream<<*(relnItem);
}
else
{
flag = 0;
writeStream<<flag;
}
}
break;
case SmfRelationSearchByContact:
{
SmfContact contact;
readStream>>contact;
SmfRelationId relnId = dsm->searchByContact(contact);
writeStream<<relnId;
break;
}
case SmfRelationCount:
{
SmfRelationId relationId;
readStream>>relationId;
int cnt = dsm->count(relationId);
writeStream<<cnt;
}
break;
case SmfRelationGet:
{
SmfRelationId relationId;
quint32 index;
readStream>>relationId;
readStream>>index;
SmfRelationItem* relnItem = dsm->getContact(relationId,index);
quint8 flag = 1;
if(relnItem)
{
writeStream<<flag;
writeStream<<*(relnItem);
}
else
{
flag = 0;
writeStream<<flag;
}
break;
}
case SmfRelationGetAll:
{
SmfRelationId relationId;
readStream>>relationId;
QList<SmfRelationItem> relnIditemList = dsm->getAll(relationId);
writeStream<<relnIditemList;
}
break;
case SmfRelationGetAllRelations:
{
QList<SmfRelationId> relnIdList = dsm->getAllRelations();
writeStream<<relnIdList;
}
break;
case SmfRelationDeleteRelation:
{
SmfRelationId relnId;
readStream>>relnId;
err = dsm->deleteRelation(relnId);
int errInt = err;
writeStream<<errInt;
break;
}
default:
break;
}
return err;
}
#ifdef Q_FOR_FUTURE
/**
* This slot is invoked when CM finishes the authorization of the client.
* @param authID As it contains the session ptr, sever directly invokes the session's API to notify success
*/
void SmfServer::clientAuthorizationFinished(bool success,SmfClientAuthID authID )
{
qDebug()<<"Inside SmfServer::clientAuthorizationFinished()";
//TODO:- implement this api in session class
//note:- in case success is false client completes the request with SmfErrClientAuthFailed
//TODO:- define set of smf wide error after consulting with other module owners
authID.session->clientAuthorizationFinished(success);
}
#endif
/**
* This API is called by PM once its done with request and parsing
* @param requestID The request id which is completed
* @param parsedData Serialized data(as per request type) filled by PM
* @param error Error occured
* TODO:- should use smf wide global errors instead
*/
void SmfServer::resultsAvailable ( int requestID, QByteArray* parsedData, SmfError error )
{
qDebug()<<"Inside SmfServer::resultsAvailable()";
#ifdef DETAILEDDEBUGGING
qDebug()<<"requestID = "<<requestID;
qDebug()<<"parsedData->size() = "<<parsedData->size();
qDebug()<<"Error = "<<error;
#endif
//Serialize error followed by actual data
QByteArray dataWithError;
QDataStream writer(&dataWithError,QIODevice::WriteOnly);
writer<<error;
if(parsedData->size())
{
writer<<*(parsedData);
}
//find out the appropriate session and request id and service that
m_SmfServerPrivate->findAndServiceclient(requestID,&dataWithError,error);
}
/**
* This is called when CMclient notifies client expiry.
* @param type notification type, set of enums for future expansion
* @param id Plugin Id for which the authentication has expired
*/
void SmfServer::authenticationKeysExpired(NotificationType type,SmfPluginID id)
{
Q_UNUSED(type)
Q_UNUSED(id)
//resend the notify request
//CMclient->requestAuthExpiryNotify();
}
| [
"[email protected]",
"none@none",
"[email protected]"
]
| [
[
[
1,
4
],
[
6,
13
],
[
19,
20
],
[
25,
28
],
[
30,
31
],
[
36,
36
],
[
38,
38
],
[
41,
42
],
[
46,
46
],
[
50,
50
],
[
61,
65
],
[
68,
71
],
[
73,
73
],
[
75,
75
],
[
78,
78
],
[
81,
82
],
[
85,
86
],
[
88,
88
],
[
91,
92
],
[
94,
96
],
[
98,
106
],
[
110,
114
],
[
116,
119
],
[
121,
129
],
[
131,
131
],
[
133,
135
],
[
137,
137
],
[
139,
142
],
[
144,
153
],
[
156,
157
],
[
160,
161
],
[
163,
163
],
[
165,
167
],
[
169,
170
],
[
172,
173
],
[
205,
205
],
[
214,
214
],
[
218,
218
],
[
222,
222
],
[
225,
225
],
[
227,
228
],
[
231,
235
],
[
257,
257
],
[
262,
266
],
[
269,
269
],
[
286,
286
],
[
288,
289
],
[
294,
295
],
[
316,
321
],
[
333,
334
],
[
344,
358
],
[
370,
370
],
[
372,
386
],
[
396,
398
],
[
400,
400
],
[
403,
408
],
[
410,
412
],
[
414,
414
],
[
417,
423
],
[
425,
425
],
[
433,
440
],
[
442,
444
],
[
446,
457
]
],
[
[
5,
5
],
[
14,
18
],
[
21,
24
],
[
29,
29
],
[
32,
35
],
[
37,
37
],
[
39,
40
],
[
43,
43
],
[
47,
49
],
[
53,
60
],
[
66,
66
],
[
72,
72
],
[
74,
74
],
[
76,
77
],
[
79,
80
],
[
83,
84
],
[
87,
87
],
[
89,
90
],
[
93,
93
],
[
97,
97
],
[
107,
109
],
[
115,
115
],
[
120,
120
],
[
130,
130
],
[
132,
132
],
[
136,
136
],
[
138,
138
],
[
143,
143
],
[
154,
155
],
[
158,
159
],
[
162,
162
],
[
164,
164
],
[
168,
168
],
[
171,
171
],
[
174,
204
],
[
206,
213
],
[
215,
217
],
[
219,
221
],
[
223,
224
],
[
226,
226
],
[
229,
230
],
[
236,
256
],
[
258,
261
],
[
267,
268
],
[
270,
285
],
[
287,
287
],
[
290,
293
],
[
296,
315
],
[
322,
332
],
[
335,
343
],
[
359,
369
],
[
371,
371
],
[
387,
395
],
[
399,
399
],
[
401,
402
],
[
409,
409
],
[
413,
413
],
[
415,
416
],
[
424,
424
],
[
426,
432
],
[
441,
441
],
[
445,
445
],
[
458,
458
]
],
[
[
44,
45
],
[
51,
52
],
[
67,
67
]
]
]
|
d50c6ff94590c0fa3754a9d652aa2c07619d291f | 41c264ec05b297caa2a6e05e4476ce0576a8d7a9 | /OpenHoldem/DialogSAPrefs7.h | 323bea067574ae8f1d7cfb2c266d37edc321c85d | []
| no_license | seawei/openholdem | cf19a90911903d7f4d07f956756bd7e521609af3 | ba408c835b71dc1a9d674eee32958b69090fb86c | refs/heads/master | 2020-12-25T05:40:09.628277 | 2009-01-25T01:17:10 | 2009-01-25T01:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | #ifndef INC_DIALOGSAPREFS7_H
#define INC_DIALOGSAPREFS7_H
#include "resource.h"
// CDlgSAPrefs7 dialog
class CDlgSAPrefs7 : public CSAPrefsSubDlg
{
DECLARE_DYNAMIC(CDlgSAPrefs7)
public:
CDlgSAPrefs7(CWnd* pParent = NULL); // standard constructor
virtual ~CDlgSAPrefs7();
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
virtual void OnOK();
enum { IDD = IDD_SAPREFS7 };
CEdit m_ICM1, m_ICM2, m_ICM3, m_ICM4;
DECLARE_MESSAGE_MAP()
};
#endif //INC_DIALOGSAPREFS7_H | [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
9f402c93fc88c4ef4c3a7a3caa573ad9d5276fde | 5d96cda7cfe68e9b8d54ca4f9b21cf2d45123048 | /include/user.h | 376a5ade570f00d3a204daac12f3d1431414f5cd | []
| no_license | BadPractice/twmailer | d97dee56ebb3558dd97e05171cad2db248421fa7 | 9ed2e8d2763680bb89be273ccc601b9928191d34 | refs/heads/master | 2021-01-19T07:37:12.550837 | 2011-11-04T19:57:55 | 2011-11-04T19:57:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | h | #ifndef USER_H
#define USER_H
#include <string>
#include <fstream>
#include <iostream>
#include <list>
#include <stdlib.h>
using namespace std;
class user
{
public:
user(string aaa);
void send(string to, string message);
string do_list();
void do_del(int);
string do_read(int msg);
int writefile(string);
~user();
protected:
private:
string name;
int getfilenames(list<string > *);
string getfile(string filename, int anz);
bool sortnumb (string first, string second);
};
#endif // USER_H
| [
"philipp@philipp-Latitude-E6400",
"[email protected]"
]
| [
[
[
1,
5
],
[
8,
14
],
[
19,
21
],
[
27,
28
]
],
[
[
6,
7
],
[
15,
18
],
[
22,
26
]
]
]
|
0a10d3db8a126e95b2493694f72d163d7d5fa87e | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Core/ComponentBaseClasses/elxResamplerBase.hxx | e25e51b08a80f242e53c1766691ffbc9d16eacdc | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,262 | hxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxResamplerBase_hxx
#define __elxResamplerBase_hxx
#include "elxResamplerBase.h"
#include "itkImageFileCastWriter.h"
#include "itkChangeInformationImageFilter.h"
#include "elxTimer.h"
namespace elastix
{
using namespace itk;
/*
* ******************* BeforeRegistrationBase *******************
*/
template<class TElastix>
void
ResamplerBase<TElastix>
::BeforeRegistrationBase( void )
{
/** Connect the components. */
this->SetComponents();
/** Set the size of the image to be produced by the resampler. */
/** Get a pointer to the fixedImage.
* \todo make it a cast to the fixed image type
*/
typedef typename ElastixType::FixedImageType FixedImageType;
FixedImageType * fixedImage = this->m_Elastix->GetFixedImage();
/** Set the region info to the same values as in the fixedImage. */
this->GetAsITKBaseType()->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
this->GetAsITKBaseType()->SetOutputStartIndex( fixedImage->GetLargestPossibleRegion().GetIndex() );
this->GetAsITKBaseType()->SetOutputOrigin( fixedImage->GetOrigin() );
this->GetAsITKBaseType()->SetOutputSpacing( fixedImage->GetSpacing() );
this->GetAsITKBaseType()->SetOutputDirection( fixedImage->GetDirection() );
/** Set the DefaultPixelValue (for pixels in the resampled image
* that come from outside the original (moving) image.
*/
double defaultPixelValue = NumericTraits<double>::Zero;
bool found = this->m_Configuration->ReadParameter(
defaultPixelValue, "DefaultPixelValue", 0, false );
/** Set the defaultPixelValue. int values overrule double values. */
if ( found )
{
this->GetAsITKBaseType()->SetDefaultPixelValue(
static_cast<OutputPixelType>( defaultPixelValue ) );
}
} // end BeforeRegistrationBase()
/*
* ******************* AfterEachResolutionBase ********************
*/
template<class TElastix>
void
ResamplerBase<TElastix>
::AfterEachResolutionBase( void )
{
/** Set the final transform parameters. */
this->GetElastix()->GetElxTransformBase()->SetFinalParameters();
/** What is the current resolution level? */
const unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel();
/** Decide whether or not to write the result image this resolution. */
bool writeResultImageThisResolution = false;
this->m_Configuration->ReadParameter( writeResultImageThisResolution,
"WriteResultImageAfterEachResolution", "", level, 0, false );
/** Writing result image. */
if ( writeResultImageThisResolution )
{
/** Create a name for the final result. */
std::string resultImageFormat = "mhd";
this->m_Configuration->ReadParameter( resultImageFormat,
"ResultImageFormat", 0, false );
std::ostringstream makeFileName( "" );
makeFileName
<< this->m_Configuration->GetCommandLineArgument( "-out" )
<< "result." << this->m_Configuration->GetElastixLevel()
<< ".R" << level
<< "." << resultImageFormat;
/** Time the resampling. */
typedef tmr::Timer TimerType;
TimerType::Pointer timer = TimerType::New();
timer->StartTimer();
/** Apply the final transform, and save the result. */
elxout << "Applying transform this resolution ..." << std::endl;
try
{
this->WriteResultImage( makeFileName.str().c_str() );
}
catch( itk::ExceptionObject & excp )
{
xl::xout["error"] << "Exception caught: " << std::endl;
xl::xout["error"] << excp
<< "Resuming elastix." << std::endl;
}
/** Print the elapsed time for the resampling. */
timer->StopTimer();
elxout << " Applying transform took "
<< static_cast<long>( timer->GetElapsedClockSec() )
<< " s." << std::endl;
} // end if
} // end AfterEachResolutionBase()
/*
* ******************* AfterRegistrationBase ********************
*/
template<class TElastix>
void
ResamplerBase<TElastix>
::AfterRegistrationBase( void )
{
/** Set the final transform parameters. */
this->GetElastix()->GetElxTransformBase()->SetFinalParameters();
/** Decide whether or not to write the result image. */
std::string writeResultImage = "true";
this->m_Configuration->ReadParameter(
writeResultImage, "WriteResultImage", 0 );
/** Release memory to be able to resample in case a limited
* amount of memory is available.
*/
this->ReleaseMemory();
/** Writing result image. */
if ( writeResultImage == "true" )
{
/** Create a name for the final result. */
std::string resultImageFormat = "mhd";
this->m_Configuration->ReadParameter(
resultImageFormat, "ResultImageFormat", 0);
std::ostringstream makeFileName( "" );
makeFileName
<< this->m_Configuration->GetCommandLineArgument( "-out" )
<< "result." << this->m_Configuration->GetElastixLevel()
<< "." << resultImageFormat;
/** Time the resampling. */
typedef tmr::Timer TimerType;
TimerType::Pointer timer = TimerType::New();
timer->StartTimer();
/** Apply the final transform, and save the result,
* by calling WriteResultImage.
*/
elxout << "\nApplying final transform ..." << std::endl;
try
{
this->WriteResultImage( makeFileName.str().c_str() );
}
catch( itk::ExceptionObject & excp )
{
xl::xout["error"] << "Exception caught: " << std::endl;
xl::xout["error"] << excp
<< "Resuming elastix." << std::endl;
}
/** Print the elapsed time for the resampling. */
timer->StopTimer();
elxout << " Applying final transform took "
<< static_cast<long>( timer->GetElapsedClockSec() )
<< " s." << std::endl;
}
else
{
/** Do not apply the final transform. */
elxout << std::endl
<< "Skipping applying final transform, no resulting output image generated."
<< std::endl;
} // end if
} // end AfterRegistrationBase()
/*
* *********************** SetComponents ************************
*/
template <class TElastix>
void
ResamplerBase<TElastix>
::SetComponents( void )
{
/** Set the transform, the interpolator and the inputImage
* (which is the moving image).
*/
this->GetAsITKBaseType()->SetTransform( dynamic_cast<TransformType *>(
this->m_Elastix->GetElxTransformBase() ) );
this->GetAsITKBaseType()->SetInterpolator( dynamic_cast<InterpolatorType *>(
this->m_Elastix->GetElxResampleInterpolatorBase() ) );
this->GetAsITKBaseType()->SetInput( dynamic_cast<InputImageType *>(
this->m_Elastix->GetMovingImage() ) );
} // end SetComponents()
/*
* ******************* WriteResultImage ********************
*/
template<class TElastix>
void
ResamplerBase<TElastix>
::WriteResultImage( const char * filename )
{
/** Make sure the resampler is updated. */
this->GetAsITKBaseType()->Modified();
/** Add a progress observer to the resampler. */
typename ProgressCommandType::Pointer progressObserver = ProgressCommandType::New();
progressObserver->ConnectObserver( this->GetAsITKBaseType() );
progressObserver->SetStartString( " Progress: " );
progressObserver->SetEndString( "%" );
/** Do the resampling. */
try
{
this->GetAsITKBaseType()->Update();
}
catch( itk::ExceptionObject & excp )
{
/** Add information to the exception. */
excp.SetLocation( "ResamplerBase - WriteResultImage()" );
std::string err_str = excp.GetDescription();
err_str += "\nError occurred while resampling the image.\n";
excp.SetDescription( err_str );
/** Pass the exception to an higher level. */
throw excp;
}
/** Read output pixeltype from parameter the file. Replace possible " " with "_". */
std::string resultImagePixelType = "short";
this->m_Configuration->ReadParameter( resultImagePixelType,
"ResultImagePixelType", 0, false );
std::basic_string<char>::size_type pos = resultImagePixelType.find( " " );
const std::basic_string<char>::size_type npos = std::basic_string<char>::npos;
if ( pos != npos ) resultImagePixelType.replace( pos, 1, "_" );
/** Read from the parameter file if compression is desired. */
bool doCompression = false;
this->m_Configuration->ReadParameter(
doCompression, "CompressResultImage", 0, false );
/** Typedef's for writing the output image. */
typedef ImageFileCastWriter< OutputImageType > WriterType;
typedef typename WriterType::Pointer WriterPointer;
typedef ChangeInformationImageFilter<
OutputImageType > ChangeInfoFilterType;
/** Possibly change direction cosines to their original value, as specified
* in the tp-file, or by the fixed image. This is only necessary when
* the UseDirectionCosines flag was set to false.
*/
typename ChangeInfoFilterType::Pointer infoChanger = ChangeInfoFilterType::New();
DirectionType originalDirection;
bool retdc = this->GetElastix()->GetOriginalFixedImageDirection( originalDirection );
infoChanger->SetOutputDirection( originalDirection );
infoChanger->SetChangeDirection( retdc & !this->GetElastix()->GetUseDirectionCosines() );
infoChanger->SetInput( this->GetAsITKBaseType()->GetOutput() );
/** Create writer. */
WriterPointer writer = WriterType::New();
/** Setup the pipeline. */
writer->SetInput( infoChanger->GetOutput() );
writer->SetFileName( filename );
writer->SetOutputComponentType( resultImagePixelType.c_str() );
writer->SetUseCompression( doCompression );
/** Do the writing. */
xl::xout["coutonly"] << std::flush;
xl::xout["coutonly"] << "\n Writing image ..." << std::endl;
try
{
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
/** Add information to the exception. */
excp.SetLocation( "ResamplerBase - AfterRegistrationBase()" );
std::string err_str = excp.GetDescription();
err_str += "\nError occurred while writing resampled image.\n";
excp.SetDescription( err_str );
/** Pass the exception to an higher level. */
throw excp;
}
/** Disconnect from the resampler. */
progressObserver->DisconnectObserver( this->GetAsITKBaseType() );
} // end WriteResultImage()
/*
* ************************* ReadFromFile ***********************
*/
template<class TElastix>
void
ResamplerBase<TElastix>
::ReadFromFile( void )
{
/** Connect the components. */
this->SetComponents();
/** Get spacing, origin and size of the image to be produced by the resampler. */
SpacingType spacing;
IndexType index;
OriginPointType origin;
SizeType size;
DirectionType direction;
direction.SetIdentity();
for ( unsigned int i = 0; i < ImageDimension; i++ )
{
/** No default size. Read size from the parameter file. */
this->m_Configuration->ReadParameter( size[ i ], "Size", i );
/** Default index. Read index from the parameter file. */
index[ i ] = 0;
this->m_Configuration->ReadParameter( index[ i ], "Index", i );
/** Default spacing. Read spacing from the parameter file. */
spacing[ i ] = 1.0;
this->m_Configuration->ReadParameter( spacing[ i ], "Spacing", i );
/** Default origin. Read origin from the parameter file. */
origin[ i ] = 0.0;
this->m_Configuration->ReadParameter( origin[ i ], "Origin", i );
/** Read direction cosines. Default identity */
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
this->m_Configuration->ReadParameter( direction( j, i ),
"Direction", i * ImageDimension + j );
}
}
/** Check for image size. */
unsigned int sum = 0;
for ( unsigned int i = 0; i < ImageDimension; i++ )
{
if ( size[ i ] == 0 ) sum++;
}
if ( sum > 0 )
{
xl::xout["error"] << "ERROR: One or more image sizes are 0!" << std::endl;
/** \todo quit program nicely. */
}
/** Set the region info to the same values as in the fixedImage. */
this->GetAsITKBaseType()->SetSize( size );
this->GetAsITKBaseType()->SetOutputStartIndex( index );
this->GetAsITKBaseType()->SetOutputOrigin( origin );
this->GetAsITKBaseType()->SetOutputSpacing( spacing );
/** Set the direction cosines. If no direction cosines
* should be used, set identity cosines, to simulate the
* old ITK behavior.
*/
if ( ! this->GetElastix()->GetUseDirectionCosines() )
{
direction.SetIdentity();
}
this->GetAsITKBaseType()->SetOutputDirection( direction );
/** Set the DefaultPixelValue (for pixels in the resampled image
* that come from outside the original (moving) image.
*/
double defaultPixelValue = NumericTraits<double>::Zero;
bool found = this->m_Configuration->ReadParameter( defaultPixelValue,
"DefaultPixelValue", 0, false );
if ( found )
{
this->GetAsITKBaseType()->SetDefaultPixelValue(
static_cast<OutputPixelType>( defaultPixelValue ) );
}
} // end ReadFromFile()
/**
* ******************* WriteToFile ******************************
*/
template <class TElastix>
void
ResamplerBase<TElastix>
::WriteToFile( void ) const
{
/** Write resampler specific things. */
xl::xout["transpar"] << std::endl << "// Resampler specific" << std::endl;
/** Write the name of the resampler. */
xl::xout["transpar"] << "(Resampler \""
<< this->elxGetClassName() << "\")" << std::endl;
/** Write the DefaultPixelValue. */
xl::xout["transpar"] << "(DefaultPixelValue "
<< this->GetAsITKBaseType()->GetDefaultPixelValue() << ")" << std::endl;
/** Write the output image format. */
std::string resultImageFormat = "mhd";
this->m_Configuration->ReadParameter(
resultImageFormat, "ResultImageFormat", 0, false );
xl::xout["transpar"] << "(ResultImageFormat \""
<< resultImageFormat << "\")" << std::endl;
/** Write output pixel type. */
std::string resultImagePixelType = "short";
this->m_Configuration->ReadParameter(
resultImagePixelType, "ResultImagePixelType", 0, false );
xl::xout["transpar"] << "(ResultImagePixelType \""
<< resultImagePixelType << "\")" << std::endl;
/** Write compression flag. */
std::string doCompression = "false";
this->m_Configuration->ReadParameter(
doCompression, "CompressResultImage", 0, false );
xl::xout["transpar"] << "(CompressResultImage \""
<< doCompression << "\")" << std::endl;
} // end WriteToFile()
/*
* ******************* ReleaseMemory ********************
*/
template<class TElastix>
void ResamplerBase<TElastix>
::ReleaseMemory( void )
{
/** Release some memory. Sometimes it is not possible to
* resample and write an image, because too much memory is consumed by
* elastix. Releasing some memory at this point helps a lot.
*/
/** Release more memory, but only if this is the final elastix level. */
if ( this->GetConfiguration()->GetElastixLevel() + 1
== this->GetConfiguration()->GetTotalNumberOfElastixLevels() )
{
/** Release fixed image memory. */
const unsigned int nofi = this->GetElastix()->GetNumberOfFixedImages();
for ( unsigned int i = 0; i < nofi; ++i )
{
this->GetElastix()->GetFixedImage( i )->ReleaseData();
}
/** Release fixed mask image memory. */
const unsigned int nofm = this->GetElastix()->GetNumberOfFixedMasks();
for ( unsigned int i = 0; i < nofm; ++i )
{
if ( this->GetElastix()->GetFixedMask( i ) != 0 )
{
this->GetElastix()->GetFixedMask( i )->ReleaseData();
}
}
/** Release moving mask image memory. */
const unsigned int nomm = this->GetElastix()->GetNumberOfMovingMasks();
for ( unsigned int i = 0; i < nomm; ++i )
{
if ( this->GetElastix()->GetMovingMask( i ) != 0 )
{
this->GetElastix()->GetMovingMask( i )->ReleaseData();
}
}
} // end if final elastix level
/** The B-spline interpolator stores a coefficient image of doubles the
* size of the moving image. We clear it by setting the input image to
* zero. The interpolator is not needed anymore, since we have the
* resampler interpolator.
*/
this->GetElastix()->GetElxInterpolatorBase()->GetAsITKBaseType()->SetInputImage( 0 );
// Clear ImageSampler, metric, optimizer, interpolator, registration, internal images?
} // end ReleaseMemory()
} // end namespace elastix
#endif // end #ifndef __elxResamplerBase_hxx
| [
"[email protected]"
]
| [
[
[
1,
523
]
]
]
|
0d27a8bf19b9b9b5b318411c10e5ff8a4e8134b7 | 08ae3ea8a00336fc7952958b33fb57be7cc6ccba | /halo_sdk/Engine/objects.cpp | 6bb6b763de8b679f36f94ce7d500bb3adcd0215e | []
| no_license | XShARk/halo-devkit | e2811079e68793fbcd67917f6c421043e7a76556 | b23865afbead9ed7edb7f0b9175326b78b276c0f | refs/heads/master | 2021-01-10T14:40:58.225503 | 2009-04-16T06:30:29 | 2009-04-16T06:30:29 | 53,686,521 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,342 | cpp | #include "objects.h"
#include "Map/tags.h"
#include "../Debug/debug.h"
CObjects::CObjects()
{
ObjectData = (AObjectData*)OBJECT_ADDRESS;
}
CObjects::~CObjects()
{
}
ident CObjects::GetObjectIdent(unsigned char object_index)
{
ident default_ident = {0,0};
if(!ObjectData->ObjectHeader[object_index].Object)
return default_ident;
else
return ObjectData->ObjectHeader[object_index].Object->ModelTag;
}
void CObjects::PrintObjectInfo()
{
CTags tags;
/*
for(unsigned short i = 0; i < ObjectData->ObjectsHeader.Max; i++)
{
if(!ObjectData->ObjectHeader[i].Object)
continue;
DEBUG("Path: %s", tags.GetTagPath(ObjectData->ObjectHeader[i].Object->ModelTag.Index));
DEBUG("ID: %X", ObjectData->ObjectHeader[i].ID);
DEBUG("Flags: %X", ObjectData->ObjectHeader[i].Flags);
DEBUG("Type: %X", ObjectData->ObjectHeader[i].Type);
DEBUG("Cluster: %i", ObjectData->ObjectHeader[i].CluserIndex);
DEBUG("Size: %i\n", ObjectData->ObjectHeader[i].Size);
}
*/
for(unsigned long i = 0; i < tags.TagIndex->TagCount; i++)
{
ATagInstance* TagInstance = tags.GetTagInstance(i);
if(TagInstance->TagParent != 'ÿÿÿÿ')
{
DEBUG("Parent: %X", TagInstance->TagParent);
}
if(TagInstance->TagChild != 'ÿÿÿÿ')
{
DEBUG("Child: %X", TagInstance->TagChild);
}
}
} | [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
41360942d2367d78c8d46b7a705365e225fa49ae | 9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e | /src/VeryIE.h | 1f4541a066d2f6ac3f0db40b5b50f88edb400ef0 | []
| no_license | correosdelbosque/veryie | e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff | 6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1 | refs/heads/master | 2021-01-10T13:17:59.755108 | 2010-06-16T04:23:26 | 2010-06-16T04:23:26 | 53,365,953 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,810 | h | // VeryIE.h : main header file for the VeryIE application
//
#if !defined(AFX_VeryIE_H__19E497BD_4ECF_11D3_9B1D_0000E85300AE__INCLUDED_)
#define AFX_VeryIE_H__19E497BD_4ECF_11D3_9B1D_0000E85300AE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h"
#include "VeryIE_i.h"
//##############################################################
#define WM_USER_SHELL_OPEN (WM_USER + 0x1000)
#define WM_UPDATE_FAV (WM_USER+0x1001)
#define WM_UPDATE_TAB (WM_USER + 0x1002)
#define WM_UPDATE_TAB_TIP (WM_USER + 0x1003)
#define WM_UPDATE_TOOLBAR (WM_USER + 0x1004)
#define WM_ACTIVATE_WINDOW (WM_USER + 0x1005)
#define WM_DELAYLOAD_CONFIG (WM_USER + 0x1006)
#define WM_SEL_TAB (WM_USER + 0x1007)
#ifndef WM_APPCOMMAND
#define WM_APPCOMMAND 0x0319
#define FAPPCOMMAND_MASK 0xF000
#define APPCOMMAND_BROWSER_BACKWARD 1
#define APPCOMMAND_BROWSER_FORWARD 2
#define APPCOMMAND_BROWSER_REFRESH 3
#define APPCOMMAND_BROWSER_STOP 4
#define APPCOMMAND_BROWSER_HOME 7
#define APPCOMMAND_FIND 28
#define APPCOMMAND_NEW 29
#define APPCOMMAND_OPEN 30
#define APPCOMMAND_CLOSE 31
#define APPCOMMAND_SAVE 32
#define APPCOMMAND_PRINT 33
#define APPCOMMAND_COPY 36
#define APPCOMMAND_CUT 37
#define APPCOMMAND_PASTE 38
#define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK))
#endif
#define WM_MENURBUTTONUP 0x0122
#define WM_MENUDRAG 0x0123
#define WM_MENUGETOBJECT 0x0124
#define WM_UNINITMENUPOPUP 0x0125
#define WM_MENUCOMMAND 0x0126
/////////////////////////////////////////////////////////////////////////////
// CVeryIEApp:
// See VeryIE.cpp for the implementation of this class
//
class CVeryIEApp : public CWinApp
{
public:
BOOL m_bUseLngFile;//use lng file
BOOL m_bAutoStart;
int m_nDelay;
CString m_strLngFile;//lng file name
CString m_strRoot;
CString m_strUser;
CString m_strFormDataPath;
CString m_strGroupPath;
CString m_strImagePath;
CString m_strDefaultDirSort;
CString m_strDefaultDir;
CString m_strSkinPath;
CString m_strProfile;
//function
CVeryIEApp();
void SaveConfg();
void LoadConfg();
class CImpIDispatch* m_pDispOM;
class CImpIDropTarget* m_pDropTarget;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CVeryIEApp)
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
virtual BOOL OnIdle(LONG lCount);
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CVeryIEApp)
afx_msg void OnAppAbout();
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
BOOL m_bATLInited;
BOOL InitATL();
BOOL ThreadOnIdle(LONG lCount);
};
extern CVeryIEApp theApp;
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_VeryIE_H__19E497BD_4ECF_11D3_9B1D_0000E85300AE__INCLUDED_)
| [
"songbohr@af2e6244-03f2-11de-b556-9305e745af9e"
]
| [
[
[
1,
140
]
]
]
|
1f1f7017e76fe3aef2d3cda75338d8ae2346ccd8 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/MyGUI/include/MyGUI_PointerInfo.h | 029965fd1e4ebaf4d0b89187114244a2fa081222 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,673 | h | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*//*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_POINTER_INFO_H__
#define __MYGUI_POINTER_INFO_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Types.h"
#include "MyGUI_ResourceImageSet.h"
namespace MyGUI
{
struct PointerInfo
{
public:
PointerInfo() :
resource( 0 )
{
}
PointerInfo(const FloatRect &_offset, const IntPoint & _point, const IntSize& _size, const std::string& _texture) :
offset( _offset ),
point( _point ),
size( _size ),
texture( _texture ),
resource( 0 )
{
}
PointerInfo(const IntPoint & _point, const IntSize& _size, ResourceImageSetPtr _resource) :
point( _point ),
size( _size ),
resource( _resource )
{
}
FloatRect offset;
IntPoint point;
IntSize size;
std::string texture;
ResourceImageSetPtr resource;
};
typedef std::map<std::string, PointerInfo> MapPointerInfo;
} // namespace MyGUI
#endif // __MYGUI_POINTER_INFO_H__
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
68
]
]
]
|
b49945c8d54d182129c8a1972a7e60325a96e72e | 2391d12c7d1de6f0b542c2c3b171fa286d84f433 | /CModManager.cpp | c568f3f3cb9b5264e42f80e294067bcfbb1a3232 | []
| no_license | DadyaIgor/ddblivion | cc0405cb062c7ec8e019c4fd820a6cdd34e4dfec | 4450e54ae55e6888e5feda6b6550c8943c274fb1 | refs/heads/master | 2021-01-10T18:03:02.470209 | 2010-05-05T08:49:53 | 2010-05-05T08:49:53 | 46,456,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,574 | cpp | #include "stdafx.h"
#include "Global.h"
#include "CModManager.h"
#include "CTreeManager.h"
CModule::CModule()
{
main_header=NULL;
}
CModule::~CModule()
{
if(main_header) delete main_header;
}
void CModule::LoadMod(HANDLE mod_handle, CModManager *mod_handler,char *mod_name)
{
DWORD readen;
unsigned long filesize,headersize;
unsigned char *buf;
//Allocate buffer for the file
filesize=GetFileSize(mod_handle,NULL);
buf=new unsigned char[filesize];
//Read the file
SetFilePointer(mod_handle,0,NULL,FILE_BEGIN);
ReadFile(mod_handle,buf,filesize,&readen,NULL);
//Add a check for ReadFile return value maybe
if(filesize!=readen)
{
delete [] buf;
throw L"Error, filesize!=readen";
}
//Read the TES4 to get the master list
headersize=LoadHeader(buf,filesize);
//Add the mod to its own masterlist
masterlist.push_back(mod_name);
//Process the masterlist
BuildFormidTranslation(mod_handler);
pTreeManager->LoadTreeRawGrup(&buf[headersize],filesize-headersize,NULL,this);
delete [] buf;
}
unsigned long CModule::LoadHeader(unsigned char *pointer,unsigned long filesize)
{
unsigned long curpointer;
char *master_filename;
RecordHeader tes4header;
SubRecordHeader subrecord;
curpointer=0;
//Read the header
memcpy(&tes4header,pointer,sizeof(RecordHeader));
curpointer+=sizeof(RecordHeader);
//Read the subrecords
while(curpointer<tes4header.size)
{
memcpy(&subrecord,&pointer[curpointer],sizeof(SubRecordHeader));
if(strncmp(subrecord.type,"MAST",4)==0)
{
master_filename=new char[MAX_PATH];
//Get the string
memset(master_filename,0,MAX_PATH);
strcpy_s(master_filename,MAX_PATH,(char *)&pointer[6+curpointer]);
//Add to the local master list
masterlist.push_back(master_filename);
}
curpointer+=(6+subrecord.size);
}
return(sizeof(RecordHeader)+tes4header.size);
}
void CModule::BuildFormidTranslation(CModManager *mod_handler)
{
unsigned long index;
for(index=0;index<masterlist.size();index++)
{
if(index!=(masterlist.size()-1)) local_to_global_formid.push_back(mod_handler->GetModIndex(masterlist[index],1));
else local_to_global_formid.push_back(mod_handler->GetModIndex(masterlist[index],0));
}
}
unsigned long CModule::TranslateFormID(unsigned long formID)
{
if((formID>>24)==0) return formID;
if((formID>>24)>=local_to_global_formid.size())
{
//output_text_hex(L"Possible invalid formID:",formID);
return((formID&0x00FFFFFF)|(local_to_global_formid[local_to_global_formid.size()-1]<<24));
//throw L"Error formID, out of range formID!";
}
return((formID&0x00FFFFFF)|(local_to_global_formid[(formID>>24)]<<24));
}
CModManager::CModManager()
{
}
CModManager::~CModManager()
{
unsigned long index;
for(index=0;index<modlist.size();index++)
{
delete modlist[index];
}
modlist.clear();
}
void CModManager::Init()
{
char sPathPluginsTxt[MAX_PATH];
unsigned long index,index2;
unsigned char *bPluginsTxt;
unsigned long iPluginsTxtSize;
unsigned long readen;
ModInfo *currentmod;
HKEY resultkey;
HANDLE hPluginsTxt;
DWORD keyType=REG_SZ;
DWORD keySize=MAX_PATH;
//Get oblivion installation path
#ifdef WIN64_BUILD
if(RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SOFTWARE\\WOW6432Node\\Bethesda Softworks\\Oblivion\\",0,KEY_READ,&resultkey)!=ERROR_SUCCESS) throw L"Couldn't open/find the key associated with Oblivion in the registry...\r\n";
#else
if(RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SOFTWARE\\Bethesda Softworks\\Oblivion\\",0,KEY_READ,&resultkey)!=ERROR_SUCCESS) throw L"Couldn't open/find the key associated with Oblivion in the registry...\r\n";
#endif
if(RegQueryValueExA(resultkey,"Installed Path",0,&keyType,(LPBYTE)sOblivionDir,&keySize)!=ERROR_SUCCESS) throw L"Couldn't read the Installed Path in registry...\r\n";
RegCloseKey(resultkey);
strcat_s(sOblivionDir,MAX_PATH,"\\data\\");
//Get the directory for the plugins.txt
if(SHGetFolderPathA(NULL,CSIDL_LOCAL_APPDATA,NULL,SHGFP_TYPE_CURRENT,sPathPluginsTxt)!=S_OK) throw L"Error getting appdata path...";
strcat_s(sPathPluginsTxt,MAX_PATH,"\\Oblivion\\Plugins.txt");
hPluginsTxt=CreateFileA(sPathPluginsTxt,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);
if(hPluginsTxt==INVALID_HANDLE_VALUE) throw L"Can't open plugins.txt to see the list of active plugins...\r\n";
iPluginsTxtSize=GetFileSize(hPluginsTxt,NULL);
bPluginsTxt=new unsigned char[iPluginsTxtSize];
SetFilePointer(hPluginsTxt,0,NULL,FILE_BEGIN);
ReadFile(hPluginsTxt,bPluginsTxt,iPluginsTxtSize,&readen,NULL);
CloseHandle(hPluginsTxt);
//Parse the plugins.txt to get the list of active plugins
currentmod=new ModInfo;
memset(currentmod->path,0,MAX_PATH);
index2=0;
for(index=0;index<iPluginsTxtSize;index++)
{
if(bPluginsTxt[index]=='\r'||bPluginsTxt[index]=='\n')
{
if(index2>4&¤tmod->path[0]!='#')
{
modnames.push_back(currentmod);
currentmod=new ModInfo;
}
else
{
memset(currentmod->path,0,MAX_PATH);
}
index2=0;
}
else
{
currentmod->path[index2]=bPluginsTxt[index];
index2++;
}
}
//In case there is a mod with no rn at the end
if(index2>4&¤tmod->path[0]!='#')
{
modnames.push_back(currentmod);
currentmod=new ModInfo;
}
delete [] bPluginsTxt;
for(index=0;index<modnames.size();index++)
{
if(_stricmp(&modnames[index]->path[strlen(modnames[index]->path)-4],".esm")==0)
{
modnames[index]->type=0;
}
else
{
if(_stricmp(&modnames[index]->path[strlen(modnames[index]->path)-4],".esp")==0)
{
modnames[index]->type=1;
}
else
{
throw L"Unknown mod type(not .esm/.esp)!";
}
}
}
//Reorder the mods(by modified date/time
char fullmodpath[MAX_PATH];
WIN32_FILE_ATTRIBUTE_DATA modtimeinfo;
for(index=0;index<modnames.size();index++)
{
memset(fullmodpath,0,MAX_PATH);
strcpy_s(fullmodpath,MAX_PATH,sOblivionDir);
strcat_s(fullmodpath,MAX_PATH,modnames[index]->path);
if(GetFileAttributesExA(fullmodpath,GetFileExInfoStandard,&modtimeinfo)==0)
{
output_text_char(L"Couldn't get the timestamp of",fullmodpath);
throw L"Error timestamp!";
}
modnames[index]->timestamp.dwHighDateTime=modtimeinfo.ftLastWriteTime.dwHighDateTime;
modnames[index]->timestamp.dwLowDateTime=modtimeinfo.ftLastWriteTime.dwLowDateTime;
modnames[index]->loaded=0;
}
unsigned long numchange=0;
ModInfo *tempinfos;
unsigned long swapped=1;
while(swapped)
{
swapped=0;
for(index=0;index<(modnames.size()-1);index++)
{
if(modnames[index]->type==modnames[index+1]->type)
{
if(modnames[index]->timestamp.dwHighDateTime==modnames[index+1]->timestamp.dwHighDateTime)
{
//check low date time
if(modnames[index]->timestamp.dwLowDateTime==modnames[index+1]->timestamp.dwLowDateTime)
{
output_text(L"Two mods have the exact same timestamp...\r\n");
output_text(L"Time to use OBMM/Wrye Bash/BOSS!\r\n");
throw L"Error identical timestamps!\r\n";
}
if(modnames[index]->timestamp.dwLowDateTime>modnames[index+1]->timestamp.dwLowDateTime)
{
swapped=1;
numchange++;
//exchange the 2
tempinfos=modnames[index];
modnames[index]=modnames[index+1];
modnames[index+1]=tempinfos;
}
}
else
{
if(modnames[index]->timestamp.dwHighDateTime>modnames[index+1]->timestamp.dwHighDateTime)
{
swapped=1;
numchange++;
//exchange the 2
tempinfos=modnames[index];
modnames[index]=modnames[index+1];
modnames[index+1]=tempinfos;
}
}
}
else
{
//One is an esm and the other an .esp
if(modnames[index]->type==1)
{
swapped=1;
numchange++;
//exchange the 2
tempinfos=modnames[index];
modnames[index]=modnames[index+1];
modnames[index+1]=tempinfos;
}
}
}
}
if(numchange==0)
{
output_text(L"Ah, a plugins.txt already sorted, I like that!\r\n");
}
}
void CModManager::LoadMod(char *name,char *short_name)
{
HANDLE mod_handle;
mod_handle=CreateFileA(name,GENERIC_READ,NULL,NULL,OPEN_EXISTING,NULL,NULL);
if(mod_handle==INVALID_HANDLE_VALUE) throw L"Error opening a mod!";
CModule *newmod;
newmod=new CModule();
newmod->LoadMod(mod_handle,this,short_name);
CloseHandle(mod_handle);
modlist.push_back(newmod);
}
void CModManager::LoadAllMods()
{
unsigned long index;
char fullpath[MAX_PATH];
//for(index=0;index<modnames.size();index++)
for(index=0;index<1;index++)
{
output_text_char(L"Loading",modnames[index]->path);
memset(fullpath,0,MAX_PATH);
strcpy_s(fullpath,MAX_PATH,sOblivionDir);
strcat_s(fullpath,MAX_PATH,modnames[index]->path);
LoadMod(fullpath,modnames[index]->path);
modnames[index]->loaded=1;
process_messages();
}
}
unsigned long CModManager::GetModIndex(char *filename,unsigned long tocheck)
{
unsigned long index;
for(index=0;index<modnames.size();index++)
{
if(_stricmp(modnames[index]->path,filename)==0)
{
if(tocheck==1&&modnames[index]->loaded==0)
{
output_text_char(L"MasterFile not loaded before the mod:",filename);
output_text(L"Please configure your load order correctly before using this tool!\r\n");
throw L"MasterFile not loaded error!";
}
return index;
}
}
throw L"Couldn't find the master in the mod list, critical failure!";
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
348
]
]
]
|
e686f669881aa6745fd696f4f7dd257b0fa1f8b6 | 5e218a340cd9aead53409c6384847d3b66173aa7 | /dxlibp/tags/0.4.14/LibTest/main.cpp | d2241f832a7657060c20e6d220a96a9de446b320 | []
| no_license | PSP-Archive/DX-Portable | effdf3a618391ec5abad87d86b874b33aa4d83aa | a843a9b67dcc74f31a8539be182b7be70441a0bc | refs/heads/master | 2023-07-30T08:09:52.763727 | 2011-01-15T14:31:56 | 2011-01-15T14:31:56 | 409,765,794 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,132 | cpp |
#include "../DXLibraryPortable/dxlibp.h"
PSP_MODULE_INFO("Test", 0, 1, 1); //モジュール情報を設定
PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER); //ユーザーモードに設定
int main()
{
if(DxLib_Init() == -1)return -1;
int t = LoadSoundMem("cs.wav");
int gh = LoadGraph("test.png");
UnswizzleGraph(gh);
SetDisplayFormat(DXP_FMT_5650);
ConvertGraphFormat(gh,DXP_FMT_5650);
printfDx("%d",t);
ScreenFlip();
PlaySoundMem(t,DX_PLAYTYPE_BACK);
int t1 = 1,t2 = 1;
while(ProcessMessage() != -1)
{
t1 = GetNowCount();
ClearDrawScreen();
DrawFormatString(0,100,0xffffffff,"%d",t2);
for(int i = 0;i < 50000;++i)DrawGraph(200,100,gh,0);
ScreenFlip();
t2 = GetNowCount() - t1;
}
DxLib_End() ; // DXライブラリ使用の終了処理
return 0 ; // ソフトの終了
}
| [
"yreeen@789d3128-3d88-4037-835d-562945579167"
]
| [
[
[
1,
181
]
]
]
|
84d6ca15bcf0d40a9b6edd6ec0f2a8770c7b4539 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/pch.cpp | 3f2f7b58f68a28e5b61b7c999900101820644e41 | []
| no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Precompiled header generator stub.
//
// The compiler builds this file (and only this file) in order to
// generate the precompiled header, which is then used by all the
// other code modules.
//
#include "pch.h"
| [
"[email protected]"
]
| [
[
[
1,
12
]
]
]
|
775e046c7b2fc540dc2f365599f3f601ce29d7b9 | 65fe6f7017f90fa55acf45773470f8f039724748 | /antbuster/include/ca/caInterpolaters.h | b5787b3f73bbf9c9837c2be2b3945cb61f83505e | []
| no_license | ashivers/antbusterhge | bd37276c29d1bb5b3da8d0058d2a3e8421dfa3ab | 575a21c56fa6c8633913b7e2df729767ac8a7850 | refs/heads/master | 2021-01-20T22:40:19.612909 | 2007-10-03T10:56:44 | 2007-10-03T10:56:44 | 40,769,210 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,654 | h | /*
常用插值器
可以自己创建新的插值器,比如sin曲线函数插值器,curvedataset内保存曲线参数,建议仍然使用时间-状态组合
此时,可表示随着时间的变化,sin曲线的参数也在变化。如模拟阻尼振动。
*/
#ifndef CANI_INTERPOLATERS_H
#define CANI_INTERPOLATERS_H
#include "curvedani.h"
#include "caImage.h"
#include "caBspline.h"
#pragma warning(push)
#pragma warning(disable:4554)
namespace cAni
{
// 插值器
/// 越变型插值器
template<class T>
class StepInterpolater : public iCurveInterpolater
{
public:
virtual const char *getTypeName() const;
virtual bool getSample(StateId sid, const iCurveDataSet &cds, int time, void *result) const
{
sid;
size_t lo = 0, hi = cds.getDataCount();
if (hi <= 0)
return false;
if (time <= cds.getTime(0))
{
*(T*)result = *(T*)cds.getData(0);
return true;
}
if (time >= cds.getTime(hi - 1))
{
*(T*)result = *(T*)cds.getData(hi - 1);
return true;
}
while(lo + 1 < hi)
{
size_t id = lo + hi >> 1;
if (cds.getTime(id) <= time)
lo = id;
else
hi = id;
}
assert(lo + 1 == hi);
*(T*)result = *(T*)cds.getData(lo);
return true;
}
};
/// 线性插值器
template<class T>
class LinearInterpolater : public iCurveInterpolater
{
public:
virtual const char *getTypeName() const;
virtual bool getSample(StateId sid, const iCurveDataSet &cds, int time, void *result) const
{
sid;
size_t lo = 0, hi = cds.getDataCount();
if (hi <= 0)
return false;
if (time <= cds.getTime(0))
{
*(T*)result = *(T*)cds.getData(0);
return true;
}
if (time >= cds.getTime(hi - 1))
{
*(T*)result = *(T*)cds.getData(hi - 1);
return true;
}
assert(hi >= 2);
while(lo + 1 < hi)
{
size_t id = lo + hi >> 1;
if (cds.getTime(id) <= time)
lo = id;
else
hi = id;
}
assert(lo + 1 == hi && lo + 1 != cds.getDataCount());
const T &t1 = *(const T*)cds.getData(lo);
const T &t2 = *(const T*)cds.getData(lo + 1);
float d = float(cds.getTime(lo + 1) - cds.getTime(lo));
d = (time - cds.getTime(lo)) / d;
*(T*)result = t1 + (t2 - t1) * d;
return true;
}
};
template<class T>
class BsplineInterpolater : public iCurveInterpolater
{
public:
virtual const char *getTypeName() const;
virtual bool getSample(StateId sid, const iCurveDataSet &cds, int time, void *result) const
{
sid;
size_t lo = 0, hi = cds.getDataCount();
if (hi <= 3)
return false;
int time1 = cds.getTime(1);
int time2 = cds.getTime(hi - 2);
if (time <= time1)
{
lo = 2;
time = time1;
}
else if (time >= time2)
{
lo = hi - 2;
time = time2;
}
else
{
while(lo + 1 < hi)
{
size_t id = lo + hi >> 1;
if (cds.getTime(id) <= time)
lo = id;
else
hi = id;
}
if (lo > hi - 2)
return false;
}
float dd = (float)cds.getTime(lo - 1);
const float (&d4)[4] = spline::bspline_d((time - dd) / (cds.getTime(lo) - dd));
const T &a = *(const T*)cds.getData(lo - 2);
const T &b = *(const T*)cds.getData(lo - 1);
const T &c = *(const T*)cds.getData(lo);
const T &d = *(const T*)cds.getData(lo + 1);
*(T*)result = T(a * d4[0] + b * d4[1] + c * d4[2] + d * d4[3]);
return true;
}
};
};
#pragma warning(pop)
#endif//CANI_INTERPOLATERS_H | [
"zikaizhang@b4c9a983-0535-0410-ac72-75bbccfdc641"
]
| [
[
[
1,
154
]
]
]
|
e7b884400ba342567d355b1b0ac583002e3de6ad | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /ytk/test/TestSqlite3/main.cpp | b7ae25ee36cd82d8d28e6c58ca8c5263f26ab2f8 | []
| no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,273 | cpp | #include <iostream>
#include "sqlite3/sqlite3.h"
int callback(void* data, int ncols, char** values, char** headers);
int main(int argc, char *argv[]){
sqlite3 *db;
char *zErr;
int rc;
char *sql;
//open db
rc = sqlite3_open("test.db", &db);
if(rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
//create table
sql = "create table episodes(id int, name text)";
rc = sqlite3_exec(db, sql, NULL, NULL, &zErr);
if(rc != SQLITE_OK) {
if (zErr != NULL) {
fprintf(stderr, "SQL error: %s\n", zErr);
sqlite3_free(zErr);
}
}
//insert
sql = "insert into episodes values (10, 'The Dinner Party')";
rc = sqlite3_exec(db, sql, NULL, NULL, &zErr);
//select
sql = "insert into episodes (id, name) values (11,'Mackinaw Peaches');"
"select * from episodes;";
const char* data = "Callback function called";
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErr);
if(rc != SQLITE_OK) {
if (zErr != NULL) {
fprintf(stderr, "SQL error: %s\n", zErr);
sqlite3_free(zErr);
}
}
//select by sqlite3_get_table
/**
name | id
-----------------------
The Junior Mint | 43
The Smelly Car | 28
The Fusilli Jerry | 21
result [0] = "name";
result [1] = "id";
result [2] = "The Junior Mint";
result [3] = "43";
result [4] = "The Smelly Car";
result [5] = "28";
result [6] = "The Fusilli Jerry";
result [7] = "21";
char *result[];
int row;
int col;
sql = "select * from episodes;";
rc = sqlite3_get_table(db, sql, &result, &row, &col, &zErr);
sqlite3_free_table(result);
*/
//prepared sql stetement
sqlite3_stmt *stmt;
const char *tail;
sql = "select * from episodes;";
rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, &tail);
if(rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
}
rc = sqlite3_step(stmt);
int ncols = sqlite3_column_count(stmt);
while(rc == SQLITE_ROW) {
for(int i=0; i < ncols; i++) {
fprintf(stderr, "'%s' ", sqlite3_column_text(stmt, i));
}
fprintf(stderr, "\n");
rc = sqlite3_step(stmt);
}
//prepared sql of multiple SQL statements
/*while(sqlite3_complete(sql) {
rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, &tail);
// Process query results
// Skip to next command in string.
sql = tail;
}*/
//or int sqlite3_reset(sqlite3_stmt *pStmt); for future use.
sqlite3_finalize(stmt);
/* Parameterized Queries
const char* sql = "insert into foo values(?,?,?)";
sqlite3_prepare(db, sql, strlen(sql), &stmt, &tail);
sqlite3_bind_int(stmt, 1, 2);
sqlite3_bind_text(stmt, 2, "pi");
sqlite3_bind_double(stmt, 3, 3.14);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
*/
/* Transaction
db = open('foods.db')
db.exec('BEGIN')
db.exec('SELECT * FROM episodes')
db.exec('SELECT * FROM episodes')
db.exec('COMMIT')
db.close()
*/
//close db
sqlite3_close(db);
std::cin.get();
return 0;
}
int callback(void* data, int ncols, char** values, char** headers)
{
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i=0; i < ncols; i++) {
fprintf(stderr, "%s=%s ", headers[i], values[i]);
}
fprintf(stderr, "\n");
return 0;
} | [
"yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
]
| [
[
[
1,
136
]
]
]
|
4878d415a896ce75f812eb010e8baec91c546aba | 0b1111e870b496aae0d6210806eebf1c942c9d3a | /LinearAlgebra/TBLAS/blas/tblas_1_rotmg.hpp | e857618033a1ce964124889d03fe1293442c4d43 | [
"WTFPL"
]
| permissive | victorliu/Templated-Numerics | 8ca3fabd79435fa40e95e9c8c944ecba42a0d8db | 35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9 | refs/heads/master | 2016-09-05T16:32:22.250276 | 2009-12-30T07:48:03 | 2009-12-30T07:48:03 | 318,857 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | hpp | template <typename ScalarRealT>
void TBLAS_NAME(rotmg,ROTMG)(
ScalarRealT &d1,
ScalarRealT &d2,
ScalarRealT &b1,
const ScalarRealT &b2,
ScalarRealT P[5]){
ScalarRealT D1 = d1, D2 = d2, x = b1, y = b2;
ScalarRealT h11,h12,h21,h22, u, c, s;
const ScalarRealT G = 4096, G2 = G*G;
// Taken from GSL
/* case of d1 < 0, appendix A, second to last paragraph */
if (D1 < 0.0) {
P[0] = -1;
P[1] = 0;
P[2] = 0;
P[3] = 0;
P[4] = 0;
d1 = 0;
d2 = 0;
b1 = 0;
return;
}
if (D2 * y == 0.0) {
P[0] = -2; /* case of H = I, page 315 */
return;
}
c = fabs(D1 * x * x);
s = fabs(D2 * y * y);
if (c > s) {
/* case of equation A6 */
P[0] = 0.0;
h11 = 1;
h12 = (D2 * y) / (D1 * x);
h21 = -y / x;
h22 = 1;
u = 1 - h21 * h12;
if (u <= 0.0) { /* the case u <= 0 is rejected */
P[0] = -1;
P[1] = 0;
P[2] = 0;
P[3] = 0;
P[4] = 0;
*d1 = 0;
*d2 = 0;
*b1 = 0;
return;
}
D1 /= u;
D2 /= u;
x *= u;
} else {
/* case of equation A7 */
if (D2 * y * y < 0.0) {
P[0] = -1;
P[1] = 0;
P[2] = 0;
P[3] = 0;
P[4] = 0;
*d1 = 0;
*d2 = 0;
*b1 = 0;
return;
}
P[0] = 1;
h11 = (D1 * x) / (D2 * y);
h12 = 1;
h21 = -1;
h22 = x / y;
u = 1 + h11 * h22;
D1 /= u;
D2 /= u;
{
TBLAS_SWAP(D2,D1);
}
x = y * u;
}
/* rescale D1 to range [1/G2,G2] */
while (D1 <= 1.0 / G2 && D1 != 0.0) {
P[0] = -1;
D1 *= G2;
x /= G;
h11 /= G;
h12 /= G;
}
while (D1 >= G2) {
P[0] = -1;
D1 /= G2;
x *= G;
h11 *= G;
h12 *= G;
}
/* rescale D2 to range [1/G2,G2] */
while (fabs(D2) <= 1.0 / G2 && D2 != 0.0) {
P[0] = -1;
D2 *= G2;
h21 /= G;
h22 /= G;
}
while (fabs(D2) >= G2) {
P[0] = -1;
D2 /= G2;
h21 *= G;
h22 *= G;
}
*d1 = D1;
*d2 = D2;
*b1 = x;
if (P[0] == -1.0) {
P[1] = h11;
P[2] = h21;
P[3] = h12;
P[4] = h22;
} else if (P[0] == 0.0) {
P[2] = h21;
P[3] = h12;
} else if (P[0] == 1.0) {
P[1] = h11;
P[4] = h22;
}
}
| [
"victor@onyx.(none)"
]
| [
[
[
1,
150
]
]
]
|
a98ece7a3cdfd55a06797cbf936974d291983fa8 | 21dcab8a06b80b13f2536f4932e23eccae1dd13d | /src/BlackJack/FormLobby.cpp | 929b71c6a8ffd10e1c64d7a66002a407b7d5d76f | []
| no_license | demontiejr/blackjackpoker | 2cff7e07d5f52144f44d95137f0ff57b99a75d53 | 7ff5e4b1fb4966d6d6ad30cffe1f29d053bfa34b | refs/heads/master | 2016-08-11T12:13:11.927157 | 2011-10-25T13:23:36 | 2011-10-25T13:23:36 | 46,422,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,828 | cpp | #include "BlackJack/FormLobby.h"
#include "BlackJack/FormMgr.h"
#include "BlackJack/Ranking.h"
#include "BlackJack/InfoRanking.h"
#include "BlackJack/Controlador.h"
#include "BlackJack/Jogador.h"
using namespace Osp::Base;
using namespace Osp::Ui;
using namespace Osp::Ui::Controls;
using namespace Osp::App;
using namespace Osp::Media;
using namespace Osp::Graphics;
FormLobby::FormLobby()
{
}
FormLobby::~FormLobby(void)
{
}
bool
FormLobby::Initialize()
{
Form::Construct(L"IDF_FORM_LOBBY");
return true;
}
result
FormLobby::OnInitializing(void)
{
result r = E_SUCCESS;
__pButtonMesa1 = static_cast<Button*> (GetControl(L"IDC_BUTTON_MESA1"));
if(__pButtonMesa1 != null){
__pButtonMesa1->SetActionId(ID_BUTTON_MESA1);
__pButtonMesa1->AddActionEventListener(*this);
}
__pButtonMesa2 = static_cast<Button*> (GetControl(L"IDC_BUTTON_MESA2"));
if(__pButtonMesa2 != null){
__pButtonMesa2->SetActionId(ID_BUTTON_MESA2);
__pButtonMesa2->AddActionEventListener(*this);
}
__pButtonMesa3 = static_cast<Button*> (GetControl(L"IDC_BUTTON_MESA3"));
if(__pButtonMesa3 != null){
__pButtonMesa3->SetActionId(ID_BUTTON_MESA3);
__pButtonMesa3->AddActionEventListener(*this);
}
__pButtonVoltar = static_cast<Button*> (GetControl(L"IDC_BUTTON_VOLTAR"));
if(__pButtonVoltar != null){
__pButtonVoltar->SetActionId(ID_BUTTON_VOLTAR);
__pButtonVoltar->AddActionEventListener(*this);
}
__pLabelNome = static_cast<Label *>(GetControl(L"IDC_LABEL_NOME"));
__pLabelNome->SetText("Name: " + Controlador::GetInstance()->GetJogador()->GetNome());
__pLabelDinheiro = static_cast<Label *>(GetControl(L"IDC_LABEL_DINHEIRO"));
__pLabelDinheiro->SetText("Points: " + Integer::ToString(Controlador::GetInstance()->GetJogador()->GetPontos()));
return r;
}
result
FormLobby::OnTerminating(void)
{
result r = E_SUCCESS;
// TODO: Add your termination code here
return r;
}
void FormLobby::IrParaMesa1()
{
AppLog("Mesa 1");
Frame *pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
FormMgr *pFormMgr = static_cast<FormMgr *> (pFrame->GetControl(
"FormMgr"));
Osp::Base::Collection::ArrayList* args = new Osp::Base::Collection::ArrayList();
args->Construct();
args->Add(*new Integer(1));
args->Add(*new String("/Home/background3.jpg"));
if (pFormMgr != null)
pFormMgr->SendUserEvent(FormMgr::REQUEST_FORM_JOGO, args);
}
void FormLobby::IrParaMesa2()
{
AppLog("Mesa 2");
Frame *pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
FormMgr *pFormMgr = static_cast<FormMgr *> (pFrame->GetControl(
"FormMgr"));
Osp::Base::Collection::ArrayList* args = new Osp::Base::Collection::ArrayList();
args->Construct();
args->Add(*new Integer(2));
args->Add(*new String("/Home/background.jpg"));
if (pFormMgr != null)
pFormMgr->SendUserEvent(FormMgr::REQUEST_FORM_JOGO, args);
}
void FormLobby::IrParaMesa3()
{
AppLog("Mesa 3");
Frame *pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
FormMgr *pFormMgr = static_cast<FormMgr *> (pFrame->GetControl(
"FormMgr"));
Osp::Base::Collection::ArrayList* args = new Osp::Base::Collection::ArrayList();
args->Construct();
args->Add(*new Integer(3));
args->Add(*new String("/Home/background2.jpg"));
if (pFormMgr != null)
pFormMgr->SendUserEvent(FormMgr::REQUEST_FORM_JOGO, args);
}
void FormLobby::IrParaMenu()
{
Ranking* ranking = new Ranking();
ranking->Construct();
Jogador* jogador = Controlador::GetInstance()->GetJogador();
// if (jogador->GetNumeroDePartidas() > 0)
InfoRanking *info = new InfoRanking();
info->Construct(jogador->GetNome(), jogador->GetMaxPontos());
ranking->Inserir(info);
Controlador::GetInstance()->constructed = false;
Frame *pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
FormMgr *pFormMgr = static_cast<FormMgr *> (pFrame->GetControl(
"FormMgr"));
if (pFormMgr != null)
pFormMgr->SendUserEvent(FormMgr::REQUEST_FORM_MENU, null);
}
void FormLobby::OnActionPerformed(const Osp::Ui::Control & source, int actionId) {
switch (actionId) {
case ID_BUTTON_MESA1:
IrParaMesa1();
break;
case ID_BUTTON_MESA2:
IrParaMesa2();
break;
case ID_BUTTON_MESA3:
IrParaMesa3();
break;
case ID_BUTTON_VOLTAR:
IrParaMenu();
break;
default:
break;
}
}
result FormLobby::OnDraw(void) {
Image *pImage = new Image();
result r = pImage->Construct();
if (IsFailed(r))
return r;
Bitmap *pBitmap = pImage->DecodeN("/Home/background1.png",
BITMAP_PIXEL_FORMAT_ARGB8888);
Canvas* pCanvas = GetCanvasN();
if(pCanvas != null){
pCanvas->DrawBitmap(Point(0, 0), *pBitmap);
delete pCanvas;
}
delete pImage;
delete pBitmap;
return r;
}
| [
"[email protected]"
]
| [
[
[
1,
185
]
]
]
|
d90489f6a2380cd2cc7d7f4c14c8a5473c47358f | a9cf0c2a8904e42a206c3575b244f8b0850dd7af | /forms/TextBookForm.h | ce0459408276bcddeabe44e6bf6a6bd5fde58293 | []
| no_license | jayrulez/ourlib | 3a38751ccb6a38785d4df6f508daeff35ccfd09f | e4727d638f2d69ea29114dc82b9687ea1fd17a2d | refs/heads/master | 2020-04-22T15:42:00.891099 | 2010-01-06T20:00:17 | 2010-01-06T20:00:17 | 40,554,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | h | /*
@Group: BSC2D
@Group Members:
<ul>
<li>Robert Campbell: 0701334</li>
<li>Audley Gordon: 0802218</li>
<li>Dale McFarlane: 0801042</li>
<li>Dyonne Duberry: 0802189</li>
<li>Xavier Lowe: 0802488</li>
</ul>
@
*/
#ifndef _TEXTBOOKFORM_H
#define _TEXTBOOKFORM_H
#ifndef _TEXTBOOK_H
#include "../TextBook.h"
#endif
#ifndef CONSOLE_H
#include "../gui/console/console.h"
#endif
#include "FormInputBuilder.h"
#include "Form.h"
class TextBookForm: public Form
{
private:
int TextBookCoord[7][3];
console consoleObj;
FormInputBuilder FormInputBuilderObj;
TextBook *textBookPtr;
int FieldPosition;
string input;
string AllInput[7];
string *InputPtr;
string tag;
//string ReferenceNumber;
public:
TextBookForm();
~TextBookForm();
void browseForm();
void browseEditForm(string);
void show();
void save();
void editSave();
bool validate();
};
#endif
| [
"[email protected]",
"portmore.leader@2838b242-c2a8-11de-a0e9-83d03c287164"
]
| [
[
[
1,
46
],
[
48,
50
]
],
[
[
47,
47
]
]
]
|
1a8a7ec58fe4420841d2864287774284d680de9d | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/dibmgr/dibmgr.cpp | 28333ba8948ff6ac5abede1675f760d4d784ea25 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,363 | cpp | /****************************************************************************
;
; MODULE: DIBMGR (.CPP)
;
; PURPOSE: DIB Manager Class
;
; HISTORY: 02/15/96 [blg] This file was created
;
; COMMENT: Copyright (c) 1996, Monolith Inc.
;
****************************************************************************/
// Includes...
#include "stdafx.h"
#include "dibmgr.h"
// Statics...
HINSTANCE CDibMgr::s_hInst = NULL;
// Functions...
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::Init
//
// PURPOSE: Initialization
//
// ----------------------------------------------------------------------- //
BOOL CDibMgr::Init(HINSTANCE hInst, HWND hWnd, DWORD flags)
{
// Sanity checks...
ASSERT(!IsValid());
ASSERT(hInst);
ASSERT(hWnd);
// Set simple member variables...
m_hInst = hInst;
m_hWnd = hWnd;
m_dwFlags = flags;
// All done...
return(TRUE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::Term
//
// PURPOSE: Termination
//
// ----------------------------------------------------------------------- //
void CDibMgr::Term()
{
RemoveAllDibs();
RemoveAllPals();
m_hInst = NULL;
m_hWnd = NULL;
m_dwFlags = 0;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::RemoveDib
//
// PURPOSE: Removes the given dib
//
// ----------------------------------------------------------------------- //
void CDibMgr::RemoveDib(CDib* pDib)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pDib && pDib->IsValid());
if (!pDib) return;
// Remove a palette if necessary...
CDibPal* pPal = pDib->GetPalette();
if (pPal && pDib->IsPaletteOwner())
{
RemovePal(pPal);
SetPalette(NULL, FALSE);
}
// Remove the dib from our list...
POSITION pos = pDib->GetPos();
ASSERT(pos);
if (pos) m_collDibs.RemoveAt(pos);
// Destroy the dib...
delete pDib;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::RemovePal
//
// PURPOSE: Removes the given palette
//
// ----------------------------------------------------------------------- //
void CDibMgr::RemovePal(CDibPal* pPal)
{
// Sanity checks...
ASSERT(IsValid());
if (!pPal) return;
// Remove the palette from our list...
POSITION pos = pPal->GetPos();
ASSERT(pos);
if (pos) m_collPals.RemoveAt(pos);
// Destroy the palette...
delete pPal;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::RemoveAllDibs
//
// PURPOSE: Removes all dibs that we are managing
//
// ----------------------------------------------------------------------- //
void CDibMgr::RemoveAllDibs()
{
// Delete all dibs from our collection...
POSITION pos = m_collDibs.GetHeadPosition();
while (pos)
{
CDib* pDib = (CDib*)m_collDibs.GetNext(pos);
ASSERT(pDib && pDib->IsValid());
delete pDib;
}
m_collDibs.RemoveAll();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::RemoveAllPals
//
// PURPOSE: Removes all pals that we are managing
//
// ----------------------------------------------------------------------- //
void CDibMgr::RemoveAllPals()
{
// Delete all pals from our collection...
POSITION pos = m_collPals.GetHeadPosition();
while (pos)
{
CDibPal* pPal = (CDibPal*)m_collPals.GetNext(pos);
ASSERT(pPal && pPal->IsValid());
delete pPal;
}
m_collPals.RemoveAll();
m_pCurPal = NULL;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::AddDib
//
// PURPOSE: Adds a new Dib object
//
// ----------------------------------------------------------------------- //
CDib* CDibMgr::AddDib(int width, int height, int depth, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
// Get an hDC to our window...
HDC hDC = GetDC(FALSE);
// Create and init a new dib...
CDib* pDib = new CDib();
if (!pDib->Init(hDC, width, height, depth, flags))
{
ReleaseDC(hDC);
delete pDib;
return(NULL);
}
// Add the new dib to our collection...
POSITION pos = m_collDibs.AddTail(pDib);
pDib->SetPos(pos);
// Clean up...
ReleaseDC(hDC);
// All done...
return(pDib);
}
CDib* CDibMgr::AddDib(BYTE* pBytes, int width, int height, int depth, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pBytes);
// Get an hDC to our window...
HDC hDC = GetDC(FALSE);
// Create and init a new dib...
CDib* pDib = new CDib();
if (!pDib->Init(pBytes, hDC, width, height, depth, flags))
{
ReleaseDC(hDC);
delete pDib;
return(NULL);
}
// Add the new dib to our collection...
POSITION pos = m_collDibs.AddTail(pDib);
pDib->SetPos(pos);
// Clean up...
ReleaseDC(hDC);
// All done...
return(pDib);
}
CDib* CDibMgr::AddDib(BYTE* pBytes, int type, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pBytes);
// Get an hDC to our window...
HDC hDC = GetDC(FALSE);
// Create and init a new dib...
CDib* pDib = new CDib();
if (!pDib->Init(pBytes, type, hDC, flags))
{
ReleaseDC(hDC);
delete pDib;
return(NULL);
}
// Add the new dib to our collection...
POSITION pos = m_collDibs.AddTail(pDib);
pDib->SetPos(pos);
// Clean up...
ReleaseDC(hDC);
// All done...
return(pDib);
}
CDib* CDibMgr::AddDib(const char* sFile, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(sFile);
// Get an hDC to our window...
HDC hDC = GetDC(FALSE);
// Set the global hInst in case we are trying to load a res...
s_hInst = m_hInst;
// Create and init a new dib...
CDib* pDib = new CDib();
if (!pDib->Init(sFile, hDC, flags))
{
ReleaseDC(hDC);
delete pDib;
return(NULL);
}
// Add the new dib to our collection...
POSITION pos = m_collDibs.AddTail(pDib);
pDib->SetPos(pos);
// Clean up...
ReleaseDC(hDC);
// All done...
return(pDib);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::AddDib
//
// PURPOSE: Copies the dib you pass in, and promotes FROM 8 TO 16 ONLY.
//
// ----------------------------------------------------------------------- //
CDib* CDibMgr::AddDib( CDib *pOriginalDib, CDibPal *pPal )
{
ASSERT( IsValid() );
ASSERT( pOriginalDib->GetDepth() == 8 );
HDC hDC = GetDC( FALSE );
CDib *pDib = new CDib();
if( !pDib->Init(hDC, pOriginalDib, pPal) )
{
ReleaseDC( hDC );
delete pDib;
return NULL;
}
POSITION pos = m_collDibs.AddTail(pDib);
pDib->SetPos(pos);
ReleaseDC( hDC );
return pDib;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::AddPal
//
// PURPOSE: Adds a new Pal object
//
// ----------------------------------------------------------------------- //
CDibPal* CDibMgr::AddPal(PALETTEENTRY* pPes, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pPes);
// Create and init a new palette...
CDibPal* pPal = new CDibPal();
if (!pPal->Init(pPes, flags))
{
delete pPal;
return(NULL);
}
// Add the new palette to our collection...
POSITION pos = m_collPals.AddTail(pPal);
pPal->SetPos(pos);
// All done...
return(pPal);
}
CDibPal* CDibMgr::AddPal(BYTE* pRgbs, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pRgbs);
// Create and init a new palette...
CDibPal* pPal = new CDibPal();
if (!pPal->Init(pRgbs, flags))
{
delete pPal;
return(NULL);
}
// Add the new palette to our collection...
POSITION pos = m_collPals.AddTail(pPal);
pPal->SetPos(pos);
// All done...
return(pPal);
}
CDibPal* CDibMgr::AddPal(const char* sFile, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
// Set the global hInst in case we are trying to load a res...
s_hInst = m_hInst;
// Create and init a new palette...
CDibPal* pPal = new CDibPal();
if (!pPal->Init(sFile, flags))
{
delete pPal;
return(NULL);
}
// Add the new palette to our collection...
POSITION pos = m_collPals.AddTail(pPal);
pPal->SetPos(pos);
// All done...
return(pPal);
}
CDibPal* CDibMgr::AddPal(BYTE *pData, DWORD dataLen, int type, DWORD flags)
{
ASSERT( IsValid() );
CDibPal *pPal = new CDibPal();
if( !pPal->Init(pData, dataLen, type, flags) )
{
delete pPal;
return NULL;
}
POSITION pos = m_collPals.AddTail( pPal );
pPal->SetPos( pos );
return pPal;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::AddPal
//
// PURPOSE: Adds a new Pal object
//
// ----------------------------------------------------------------------- //
BOOL CDibMgr::ResizeDib(CDib* pDib, int width, int height, int depth, DWORD flags)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pDib && pDib->IsValid());
if (!pDib) return(FALSE);
// Get an hDC to our window...
HDC hDC = GetDC(FALSE);
// Resize the dib...
BOOL bRet = pDib->Resize(hDC, width, height, depth, flags);
// Clean up...
ReleaseDC(hDC);
// All done...
return(bRet);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CDibMgr::AddPal
//
// PURPOSE: Adds a new Pal object
//
// ----------------------------------------------------------------------- //
void CDibMgr::SetPalette(CDib* pDib, CDibPal* pPal, BOOL bOwner)
{
// Sanity checks...
ASSERT(IsValid());
ASSERT(pDib && pDib->IsValid());
ASSERT(pPal && pPal->IsValid());
// Remove an old palette if necessary...
CDibPal* pOldPal = pDib->GetPalette();
if (pOldPal && pDib->IsPaletteOwner())
{
RemovePal(pOldPal);
pDib->SetPalette(NULL, FALSE);
}
// Set the new palette...
pDib->SetPalette(pPal, bOwner);
}
| [
"[email protected]"
]
| [
[
[
1,
614
]
]
]
|
d873b4e943f2e4f46e74a500a3fb31a619337f82 | ad6a37b326227901f75bad781f2cbf357b42544f | /Effects/VolumetricLightScattering.h | 9c6eed359226e814aa51e18949496b9c0fdc4ec6 | []
| no_license | OpenEngineDK/branches-PostProcessingEffects | 83b4e1dc1a390b66357bed6bc94d4cab16ef756a | c4f4585cbdbb905d382499bf12fd8bfe7d27812c | refs/heads/master | 2021-01-01T05:43:32.564360 | 2009-04-20T14:50:03 | 2009-04-20T14:50:03 | 58,077,144 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | h | #ifndef __VOLUMETRICLIGHTSCATTERING_H__
#define __VOLUMETRICLIGHTSCATTERING_H__
#include <PostProcessing/OpenGL/PostProcessingEffect.h>
#include <PostProcessing/IPostProcessingPass.h>
#include <Display/Viewport.h>
#include <Core/IEngine.h>
#include <vector>
#include <stdio.h>
using namespace OpenEngine::PostProcessing;
class VolumetricLightScattering : public PostProcessingEffect {
private:
IPostProcessingPass* pass1;
vector<float> screenlightpos; // <- in screen coordinates
public:
VolumetricLightScattering(Viewport* viewport, IEngine& engine);
void Setup();
void PerFrame(const float deltaTime);
void SetLightPos(vector<float> pos);
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
21
],
[
23,
29
]
],
[
[
7,
7
],
[
22,
22
]
]
]
|
44bd7467728191a68659244c392e907eeadfa206 | 0cc69d496cec99267f1de8b883799758be4ff53e | /single-image-dehaze/DehazeTools/DehazeTools/FastGuidedBilateralFilter.h | 1b20ce3028b4ad3253dc42836d8540d0cb133ca4 | []
| no_license | whluo/single-image-dehaze | 0f9fc99c962fa27594aa0604710c818f08e87201 | ff396af094db2282abfa29fac72475072d9145ea | refs/heads/master | 2021-01-10T02:16:35.044019 | 2011-04-12T07:29:01 | 2011-04-12T07:29:01 | 46,693,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,252 | h | #ifndef SUPER_JOINT_H
#define SUPER_JOINT_H
#define Y_MOVE_ADD 1
#define Y_MOVE_SUB -1
#define X_MOVE_ADD 2
#define X_MOVE_SUB -2
#define MOVE_DOWN 0
#define MOVE_UP 1
#include "cv.h"
#include "highgui.h"
typedef unsigned char uchar;
typedef const double *CPD;
class fast_GuidedBilateralFilter
{
public:
// Constructors and deconstructor
fast_GuidedBilateralFilter();
fast_GuidedBilateralFilter( const unsigned int KernelSize,
const unsigned int BinNum,
const double DrC,
const double DrL,
const double DdL);
void SetKernelSize( const unsigned int KernelSize );
void SetBinNum( const unsigned int BinNum );
void SetDrC( const double DrC );
void SetDrL( const double DrL );
void SetDdL( const double DdL );
void doGuidedBilateralFilter( const IplImage *SrcImageL, const IplImage *SrcImageR, IplImage *result );
protected:
void Unit( const IplImage *SrcImage, double *UnitedImage );
void GetParamCompare( const double *UnitedImageL, const double *UnitedImageR, double *ParamCompare );
void GetParamDistance( double *ParamDistance );
void GetWkJk( const double *UnitedImageL, const double *UnitedImageR, double *Wk, double *Jk );;
void GetJkB( const double *Wk, const double *Jk, const double *ParamCompare, const double *ParamDistance, double *JkB );
void GetUnitedResult( const double *UnitedImage, const double *JkB, double *UnitedResult );
void ExtractImage( const double *UnitedImage );
void DealMove( int k, int x, int y, double &SumW, double &SumJ, CPD *Param, int flag );
protected:
unsigned int m_KernelSize;
unsigned int m_BinNum;
unsigned int m_ImageHeight;
unsigned int m_ImageWidth;
// Gauss range variance between the pixels on the same position of the two source images
double m_DrC;
// Gauss range variance on the local image
double m_DrL;
// Gauss spatial variance
double m_DdL;
// The result image
IplImage *m_ResultImg;
};
namespace fast
{
class GuidedBilateralFilter : public fast_GuidedBilateralFilter
{
public:
GuidedBilateralFilter();
GuidedBilateralFilter( const unsigned int KernelSize,
const unsigned int BinNum,
const double DrC,
const double DrL,
const double DdL);
};
};
#endif | [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
9ed925c76c10abbb70c3415045d02d14861152fe | 81c2cbcc1615b61c3e2e9ad9a6ceb6c1a68d4c72 | /test.h | c0000c2299d3a6ab0dfb411072953de933d5fdee | []
| no_license | grainiac/qtrunner | 4988352cd6ffd64c9a1f84fa5093f70579024504 | 2dbcc5c5391ff936ee99c422b0a52fe1858c65b4 | refs/heads/master | 2018-12-31T09:45:02.834592 | 2010-01-17T14:35:15 | 2010-01-17T14:35:15 | 33,924,515 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,464 | h | /****************************************************************************
** $Id$
**
** This file is part of QTRunner.
**
** Copyright (C) Alex Skoruppa 2010
** All rights reserved.
**
** Base class for classes that represent a unit test.
** The NullTest class will be returned by the factory e.g. if something goes
** wrong during the construction of an object whose class is derived from Test.
**
** QTRunner 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.
**
** QTRunner 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 QTRunner. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#ifndef TEST_H
#define TEST_H
#include <QString>
#include "testtypes.h"
class QXmlStreamWriter;
enum TestRunState
{
TRS_PAUSED,
TRS_RUNNING,
TRS_SUCCESS,
TRS_FAILURE,
};
class Test
{
public:
Test(QString name, QString filePathTest, QString filePathOutput);
virtual ~Test() {};
static QString testType2String(TestType type);
static TestType string2TestType(QString type);
virtual TestType getTestType() = 0;
virtual bool execute();
virtual QString getName();
virtual QString getTestFileName();
virtual QString getTestOutputFileName();
virtual void save(QXmlStreamWriter* xml);
void setState(TestRunState state) { m_state=state; }
TestRunState getState() { return m_state; }
private:
QString getLogFileName();
bool checkLogFileIfTestWasSuccessfulAfterExecution();
QString m_name;
QString m_executable;
QString m_ouputfile;
TestRunState m_state;
};
class NullTest : public Test
{
public:
NullTest(QString name, QString filePathTest, QString filePathOutput) : Test("", "", ""){}
virtual ~NullTest(){}
virtual TestType getTestType() { return TT_NULLTEST; }
virtual bool testExecutedWithSuccess() { return false; }
};
#endif // TEST_H
| [
"Alex.Skoruppa@6a216882-0102-11df-bca2-d32778fd5087"
]
| [
[
[
1,
84
]
]
]
|
7ed59034c556d87289c8c6bfba8f8a906177a6f3 | 643b298913089cfe39d8e60974b5d33cf4cf24e7 | /rt/src/Crt/CrtAnimation.cpp | a5378ff28e7cc5fb6e6f055b11ac39a92d9877ec | [
"MIT"
]
| permissive | stevenlovegrove/collada-dom | afd20abb635a3a7419e37edbf15905928d18309d | c493230dd1d1856e0ebd3c8b9229bfe957438eb1 | refs/heads/master | 2021-04-15T12:06:32.135616 | 2011-03-07T23:38:34 | 2011-03-07T23:38:34 | 1,430,859 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,608 | cpp | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the MIT Open Source License, for details please see license.txt or the website
* http://www.opensource.org/licenses/mit-license.php
*
*/
#include "Crt/CrtMatrix.h"
#include "Crt/CrtAnimation.h"
#include "Crt/CrtUtils.h"
#include "dae/daeSIDResolver.h"
#include <string>
CrtBool CrtAnimSrc::Parse( const CrtChar * data )
{
// parse data
const CrtChar * d = data;
// allocate for the keys
Array = CrtNewData( CrtFloat, Count );
// copy the data
for( CrtUInt i = 0; i < Count; i++)
{
Array[i] = CrtGetFloatString( &d );
//CrtPrint(" coping %d ",i);fflush(stdout);
}
return CrtTrue;
}
CrtBool CrtAnimChannel::AddSrc( CrtAnimSrc * channel )
{
(void)channel;
return CrtTrue;
}
CrtFloat CrtAnimChannel::Interpolate( CrtFloat time )
{
(void)time;
float val = 0;
return val;
}
const int ANIM_SAMPLE_RATE = 30;
CrtVoid CrtAnimation::GenerateKeys()
{
CrtPrint("Generating Keys for Animation Channel %s \n", Name );
// generate key frames for the channels in this animation
CrtAnimChannel * chan = Channels[0];
// allocating for generic key channels New way
AnimKeySets = CrtNewData( CrtKeySet, NumAnimChannels );
//CrtPrint("AnimKeySets = %x,time\n", &AnimKeySets.Keys, &AnimKeySets.Time );
CrtUInt animSet = 0;
for ( CrtUInt i = 0; i < Channels.size(); i++)
{
chan = Channels[i];
CrtUInt NumKeys = chan->InputSrcPtr->Count;
// new way //
for ( CrtUInt t = 0; t < chan->GetNumElementTargets(); t++)
{
AnimKeySets[animSet+t].AllocateKeys( NumKeys );
}
// set the actual key info //
for ( CrtUInt i = 0 ; i < NumKeys; i ++)
{
// fill in all the keys for each anim key set
CrtUInt numCh = chan->GetNumElementTargets();
for ( CrtUInt ch = 0; ch < chan->GetNumElementTargets(); ch ++)
{
AnimKeySets[animSet+ch].Time[i] = chan->InputSrcPtr->Array[i];
AnimKeySets[animSet+ch].Keys[i] = chan->OutputSrcPtr->Array[i*numCh+ch];
if ( AnimKeySets[animSet+ch].Time[i] > EndTime )
EndTime = AnimKeySets[animSet+ch].Time[i];
// set the animKey in the channel for later interpolation
chan->SetKeySet( &AnimKeySets[animSet+ch], ch );
}
}
// update the current animSet
animSet += chan->GetNumElementTargets();
}
};
CrtVoid CrtAnimation::Interp( CrtFloat & val, CrtKeySet * keySet, CrtFloat time )
{
if ( ! keySet->Keys )
return;
if ( time > keySet->Time[keySet->NumKeys-1] )
val = keySet->Keys[keySet->NumKeys-1];
else
{
// here need to get an actual interpolated value for this channel but for not just
// goint to return the first anim value
val = keySet->Keys[0];
// need to first find out where the time lies in the keys
int next = -1;
int prev = -1;
for( int i = 0; i < keySet->NumKeys - 1; i ++)
{
if ( time >= keySet->Time[i] && time < keySet->Time[i+1] )
{
prev = i;
next = i+1;
break;
}
}
if ( prev == -1 )
{
if ( time < keySet->Time[0] )
val = keySet->Keys[0];
else
// if time is not in range just set to last key value
val = keySet->Keys[keySet->NumKeys-1];
}
else
{
CrtFloat tSize = keySet->Time[next] - keySet->Time[prev];
CrtFloat tDiff = time - keySet->Time[prev];
CrtFloat tFactor = 1-((tSize-tDiff)/tSize);
CrtFloat vSize = keySet->Keys[next] - keySet->Keys[prev];
val = keySet->Keys[prev] + (vSize * tFactor);
}
}
}
CrtVoid CrtAnimation::AnimateChannelFloat( CrtFloat & value, CrtAnimTarget target, CrtUInt c, CrtFloat time )
{
switch(target)
{
case eSource:
Interp(value, &AnimKeySets[c], time);
break;
default:
CrtPrint("Animation Target not found\n");
break;
}
}
CrtVoid CrtAnimation::AnimateChannel( CrtTransform * transform, CrtAnimTarget target, CrtUInt c, CrtFloat time )
{
CrtVec4f & vec = transform->GetVecTrans();
switch( target )
{
// new way
case eAnimTargetX:
case eScaleXAxis:
case eTransXAxis:
Interp(vec.x, &AnimKeySets[c], time );
break;
case eAnimTargetY:
case eScaleYAxis:
case eTransYAxis:
Interp(vec.y, &AnimKeySets[c], time );
break;
case eAnimTargetZ:
case eScaleZAxis:
case eTransZAxis:
Interp(vec.z, &AnimKeySets[c], time );
break;
case eRotXAxis:
case eRotYAxis:
case eRotZAxis:
case eAnimTargetAngle:
Interp(vec.w, &AnimKeySets[c], time );
break;
case eTranslate:
case eScale:
case eAnimTargetXYZ:
Interp(vec.x, &AnimKeySets[c], time );
Interp(vec.y, &AnimKeySets[c+1], time );
Interp(vec.z, &AnimKeySets[c+2], time );
break;
case eMatrix:
{
CrtMatrix & matrix = transform->GetMatrix();
for (int m=0; m<16; m++)
Interp(matrix[m], &AnimKeySets[c+m], time );
CrtMatrixTranspose(matrix, matrix);
break;
}
default:
CrtPrint("Animation Target not found\n");
break;
}
};
CrtAnimation::~CrtAnimation()
{
while(!Sources.empty())
{
std::map<std::string, CrtAnimSrc*>::iterator iter = Sources.begin();
CrtDelete(iter->second);
Sources.erase(iter);
}
while(!Samplers.empty())
{
std::map<std::string, CrtAnimSampler*>::iterator iter = Samplers.begin();
CrtDelete(iter->second);
Samplers.erase(iter);
}
while(!Channels.empty())
{
CrtDelete( Channels[0] );
Channels.erase(Channels.begin());
}
for ( CrtUInt t = 0; t < NumAnimChannels; t++)
{
AnimKeySets[t].DeallocateKeys();
}
CrtDeleteData(AnimKeySets);
} | [
"sceahklaw@dfea1ed5-6b0d-0410-973e-e49e28f48b26",
"dhou@dfea1ed5-6b0d-0410-973e-e49e28f48b26",
"steve314@dfea1ed5-6b0d-0410-973e-e49e28f48b26"
]
| [
[
[
1,
6
]
],
[
[
7,
226
]
],
[
[
227,
227
]
]
]
|
1681988420f60113c6393f7319495adf1cf558b4 | 672d939ad74ccb32afe7ec11b6b99a89c64a6020 | /FileSystem/fswizard/FSWizardDlg.cpp | fdd221fe102d07e0170493244674a9ddb52747a1 | []
| 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 | GB18030 | C++ | false | false | 8,656 | cpp | // FSWizardDlg.cpp : implementation file
//
#include "stdafx.h"
#include "FSWizard.h"
#include "FSWizardDlg.h"
#include "NewDiskWizard.h"
#include <fstream.h>
#include <io.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CFSWizardDlg dialog
CFSWizardDlg::CFSWizardDlg(CWnd* pParent /*=NULL*/)
: CDialog(CFSWizardDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CFSWizardDlg)
m_Res = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CFSWizardDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CFSWizardDlg)
DDX_Control(pDX, IDC_LIST1, m_DiskList);
DDX_Text(pDX, IDC_RESULT, m_Res);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CFSWizardDlg, CDialog)
//{{AFX_MSG_MAP(CFSWizardDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_NEW, OnNew)
ON_BN_CLICKED(ID_START, OnStart)
ON_LBN_DBLCLK(IDC_LIST1, OnDblclkDiskList)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFSWizardDlg message handlers
BOOL CFSWizardDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
SearchVDK();
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CFSWizardDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CFSWizardDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CFSWizardDlg::OnWizard()
{
// TODO: The property sheet attached to your project
// via this function is not hooked up to any message
// handler. In order to actually use the property sheet,
// you will need to associate this function with a control
// in your project such as a menu item or tool bar button.
int nRet;
CNewDiskWizard myWizard;
// myWizard.m_psh.dwFlags &= ~(PSH_HASHELP);
nRet=myWizard.DoModal();
switch ( nRet )
{
case -1:
AfxMessageBox("Dialog box could not be created!");
break;
case IDABORT:
// Do something.
break;
case IDOK:
SearchVDK();
break;
case IDCANCEL:
// Do something.
break;
default:
// Do something.
break;
};
}
void CFSWizardDlg::OnNew()
{
OnWizard();
}
int CFSWizardDlg::SearchVDK()
{
WIN32_FIND_DATA FileData;
HANDLE hSearch;
BOOL fFinished = FALSE;
m_DiskList.ResetContent();
// Start searching for .VDK files in the current directory.
hSearch = FindFirstFile("*.vdk", &FileData);
if (hSearch == INVALID_HANDLE_VALUE)
{
m_Res.Format("No Avaliable Disks found");
UpdateData(FALSE);
return 1;
}
while (!fFinished)
{
m_DiskList.AddString(FileData.cFileName);
if (!FindNextFile(hSearch, &FileData))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
fFinished = TRUE;
}
}
// Close the search handle.
if (!FindClose(hSearch))
{
AfxMessageBox("Fatal Error, Please check your settings");
EndDialog(1);
return -1;
}
m_Res.Format("Avaliable Disks found here");
UpdateData(FALSE);
return 0;
}
void CFSWizardDlg::OnStart()
{
// 磁盘文件第一个字节是magic number(0xF7)
// 第二个字节为格式化标志
// 0x00: formated 0x01: not formated
// 3,4自己存放块大小 (永远存在)
// 5,6,7,8字节存放文件大小(format 后消失)
// 该数据由FSNewDiskWizard产生
// 创建根目录由FS.exe完成
// 创建成功标志为第2个字节的第一位为1
// 磁盘clean位为第2个字节的第二位
int DiskSize,FATBlock,BlockSize;
char file[100];
int i=m_DiskList.GetCurSel();
if( LB_ERR == i){
AfxMessageBox("No Disk file Selected");
return ;
}
else
m_DiskList.GetText(i,file);
int res=IsFormated(file,DiskSize,BlockSize,FATBlock);
if( 0 == res)
{
// prompt for format :: MessageBox
if(IDYES == AfxMessageBox("Not Formated\nDo you want to format it now?",MB_YESNO)){
Format(file,DiskSize,FATBlock);
}
else
return;
char str[256];
sprintf(str,"fs.exe %s %d %d %d",file,DiskSize,BlockSize,FATBlock);
STARTUPINFO sp={1};
PROCESS_INFORMATION pi;
m_pSplash = new CFSLogo;
m_pSplash->DoModal();
if( FALSE == CreateProcess(NULL,str,NULL,NULL,0,0,NULL,NULL,&sp,&pi)){
AfxMessageBox("Fatal Error: Can't find FS.exe");
delete m_pSplash;
return ;
}
delete m_pSplash;
EndDialog(0);
}
else if( 1 == res || 2 == res)
{
// start New Process of File System
char str[256];
sprintf(str,"fs.exe %s %d %d %d",file,DiskSize,BlockSize,FATBlock);
// AfxMessageBox(str);
STARTUPINFO sp={1};
PROCESS_INFORMATION pi;
m_pSplash = new CFSLogo;
m_pSplash->DoModal();
if( FALSE == CreateProcess(NULL,str,NULL,NULL,0,0,NULL,NULL,&sp,&pi)){
AfxMessageBox("Fatal Error: Can't find FS.exe");
delete m_pSplash;
return;
}
delete m_pSplash;
EndDialog(0);
}else if( 3 == res)
{
// disk not supported
AfxMessageBox("Disk Not Supported");
}
else{
// prompt for error :: interl error
AfxMessageBox("Fatal Error!\nPlease check that your disk file is not modified out of this program");
EndDialog(1);
}
}
int CFSWizardDlg::IsFormated(char* filename,int& DiskSize,int& BlockSize,int& FATBlock)
{
fstream disk;
disk.open(filename,ios::in | ios::binary | ios::nocreate);
char byte;
disk.seekp(ios::beg);
disk.read(&byte,1);
unsigned char temp[4];
if( 0xF7 == (unsigned char)byte ) // Magic Number
{
disk.read(&byte,1);
if( 0x01 == (unsigned char)byte ) // not formated
{
BlockSize=0;
disk.read(temp,2);
memcpy(&BlockSize,temp,2);
disk.read(temp,4);
memcpy(&DiskSize,temp,4);
FATBlock=DiskSize/BlockSize;
FATBlock=2*FATBlock / BlockSize;
disk.close();
return 0;
}
else if ( 0x80 == (unsigned char)byte || 0xC0 == (unsigned char)byte) // root dir has been created
{
BlockSize=0;
disk.read(temp,2);
memcpy(&BlockSize,temp,2);
long fd=disk.fd();
DiskSize=_filelength(fd);
FATBlock=DiskSize/BlockSize;
FATBlock=2*FATBlock / BlockSize;
disk.close();
return 1;
}
else if ( 0x00 == (unsigned char)byte ){ // root dir not created
BlockSize=0;
disk.read(temp,2);
memcpy(&BlockSize,temp,2);
long fd=disk.fd();
DiskSize=_filelength(fd);
FATBlock=DiskSize/BlockSize;
FATBlock=2*FATBlock / BlockSize;
disk.close();
return 2;
}
else{
disk.close(); // fatal error
return -1;
}
}
else{
disk.close();
return 3; // disk not support
}
}
int CFSWizardDlg::Format(char* filename,int DiskSize,int FATBlock)
{
fstream disk;
disk.open(filename,ios::in | ios::out | ios::binary | ios::nocreate);
unsigned char Temp=0;
disk.seekp(4,ios::beg);
for (int i=4; i<DiskSize;i++)
{
if (disk.write(&Temp,1)==NULL)
{
return 1;
}
//*/
}
// 写FAT
Temp=255;
disk.seekp(4,ios::beg);
for (i=4;i<2*FATBlock;i++) //每个块号项占2Byte
{
if (disk.write(&Temp,1)==NULL)
return 1;
}
// 写format标志位,但并没有创建根目录
disk.seekp(0,ios::beg);
Temp=0xF7;
if (disk.write(&Temp,1)==NULL)
return 1;
Temp=0x00;
if (disk.write(&Temp,1)==NULL)
return 1;
disk.close();
return 0;
}
void CFSWizardDlg::OnDblclkDiskList()
{
// TODO: Add your control notification handler code here
OnStart();
}
| [
"xmzhang@5428276e-be0b-f542-9301-ee418ed919ad"
]
| [
[
[
1,
360
]
]
]
|
9dbed9457d7240562dd730acca6b845f89b4edd6 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/locationsrv/landmarks_api/src/testcposlmitemiterator.cpp | 87156240a7ce23bdfafb773ab7e6c72b68c8850e | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,700 | cpp | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// INCLUDE FILES
#include <EPos_CPosLandmark.h>
#include <EPos_CPosLandmarkDatabase.h>
#include <EPos_CPosLmCategoryManager.h>
#include <EPos_CPosLandmarkCategory.h>
#include <LbsPosition.h>
#include "testcposlmitemiterator.h"
// Literals
// Test Database URI
_LIT( KDBUri, "file://c:eposlmtest.ldb" );
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::CTestPosLmItemIterator
// C++ default constructor can NOT contain any code, that
// might leave.
// -----------------------------------------------------------------------------
//
CTestPosLmItemIterator::CTestPosLmItemIterator( CStifLogger* aLog )
{
iLog = aLog;
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::NewL
//
//
// -----------------------------------------------------------------------------
//
CTestPosLmItemIterator* CTestPosLmItemIterator::NewL(CStifLogger* aLog)
{
CTestPosLmItemIterator* self = new (ELeave) CTestPosLmItemIterator( aLog );
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop();
return self;
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::ConstructL
//
//
// -----------------------------------------------------------------------------
//
void CTestPosLmItemIterator::ConstructL()
{
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::~CTestPosLmItemIterator
//
//
// -----------------------------------------------------------------------------
//
CTestPosLmItemIterator::~CTestPosLmItemIterator()
{
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::NumOfItems
//
//
// -----------------------------------------------------------------------------
//
TInt CTestPosLmItemIterator::NumOfItemsL( CStifItemParser& /*aItem*/ )
{
// Open and init default database
CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri );
CleanupStack::PushL( lmkDatabase );
ExecuteAndDeleteLD( lmkDatabase->InitializeL() );
// Get Landmark Iterator
CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL();
CleanupStack::PushL( iterator );
// Get number of landmarks in database, which are iterated through iterator
TUint number = iterator->NumOfItemsL();
// Print number
TBuf<10> buf;
buf.AppendNum( number );
iLog->Log( buf );
iLog->Log(_L("NumOfItemsL Success"));
CleanupStack::PopAndDestroy( 2, lmkDatabase );
ReleaseLandmarkResources();
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::NextItem
//
//
// -----------------------------------------------------------------------------
//
TInt CTestPosLmItemIterator::NextItemL( CStifItemParser& /*aItem*/ )
{
// Open and init default database
CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri );
CleanupStack::PushL( lmkDatabase );
ExecuteAndDeleteLD(lmkDatabase->InitializeL());
iLog->Log(_L("Database done"));
// Get Landmark Iterator
CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL();
CleanupStack::PushL( iterator );
// Call NextL to get id of next landmark in database
TPosLmItemId id;
id = iterator->NextL();
// Print name of landmark
CPosLandmark* landmark = lmkDatabase->ReadLandmarkLC(id);
TPtrC name;
landmark->GetLandmarkName( name );
iLog->Log( name );
// NextL successful
iLog->Log(_L("NextItem successful"));
CleanupStack::PopAndDestroy( 3, lmkDatabase );
ReleaseLandmarkResources();
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::GetItemIdsL
//
//
// -----------------------------------------------------------------------------
//
TInt CTestPosLmItemIterator::GetItemIdsL( CStifItemParser& /*aItem*/ )
{
// Open and init default database
CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri );
CleanupStack::PushL( lmkDatabase );
ExecuteAndDeleteLD( lmkDatabase->InitializeL() );
// Get Landmark Iterator
CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL();
CleanupStack::PushL( iterator );
// Get number of landmarks in database, which are iterated through iterator
TUint number = iterator->NumOfItemsL();
// Get ids of all the items in array
RArray<TPosLmItemId> idArray;
iterator->GetItemIdsL( idArray, 0, number );
//
if ( idArray.Count() != number )
{
iLog->Log(_L("GetItemIdsL fails"));
User::Leave( KErrGeneral );
}
iLog->Log(_L("GetItemIdsL successful"));
CleanupStack::PopAndDestroy( 2, lmkDatabase );
ReleaseLandmarkResources();
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestPosLmItemIterator::ResetIteratorL
//
//
// -----------------------------------------------------------------------------
//
TInt CTestPosLmItemIterator::ResetIteratorL( CStifItemParser& /*aItem*/ )
{
// Open and init default database
CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri );
CleanupStack::PushL( lmkDatabase );
ExecuteAndDeleteLD( lmkDatabase->InitializeL() );
// Get Landmark Iterator
CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL();
CleanupStack::PushL( iterator );
// Get id of first item befor reset
TPosLmItemId idBeforeReset = iterator->NextL();
// Reset iterator
iterator->Reset();
// Get id after reset, should return id of first item
TPosLmItemId idAfterReset = iterator->NextL();
// Compare both the ids
if ( idBeforeReset != idAfterReset )
{
iLog->Log(_L("ResetIteratorL fails"));
User::Leave( KErrGeneral );
}
TBuf<5> buf;
buf.Append(idAfterReset);
iLog->Log(buf);
iLog->Log(_L("ResetIteratorL successful"));
CleanupStack::PopAndDestroy( 2, lmkDatabase );
ReleaseLandmarkResources();
return KErrNone;
}
| [
"none@none"
]
| [
[
[
1,
206
]
]
]
|
3cf01e804ca72ec43b079e0b79d30bbe26a04c68 | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/gui/Dialogs/BiosSelectorDialog.cpp | 48540051c2cc5816971fe715cd12f4e0050481e1 | []
| 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 | 2,301 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "System.h"
#include "App.h"
#include "ConfigurationDialog.h"
#include "ModalPopups.h"
#include "Panels/ConfigurationPanels.h"
#include <wx/filepicker.h>
using namespace Panels;
using namespace pxSizerFlags;
// ----------------------------------------------------------------------------
Dialogs::BiosSelectorDialog::BiosSelectorDialog( wxWindow* parent )
: BaseApplicableDialog( parent, _("BIOS Selector") )
{
m_selpan = new Panels::BiosSelectorPanel( this );
*this += m_selpan | StdExpand();
AddOkCancel();
Connect( wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(BiosSelectorDialog::OnOk_Click) );
Connect( wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(BiosSelectorDialog::OnDoubleClicked) );
}
bool Dialogs::BiosSelectorDialog::Show( bool show )
{
if( show && m_selpan )
m_selpan->OnShown();
return _parent::Show( show );
}
int Dialogs::BiosSelectorDialog::ShowModal()
{
if( m_selpan )
m_selpan->OnShown();
return _parent::ShowModal();
}
void Dialogs::BiosSelectorDialog::OnOk_Click( wxCommandEvent& evt )
{
if( m_ApplyState.ApplyAll() )
{
Close();
evt.Skip();
}
}
void Dialogs::BiosSelectorDialog::OnDoubleClicked( wxCommandEvent& evt )
{
wxWindow* forwardButton = FindWindow( wxID_OK );
if( forwardButton == NULL ) return;
wxCommandEvent nextpg( wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK );
nextpg.SetEventObject( forwardButton );
forwardButton->GetEventHandler()->ProcessEvent( nextpg );
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
75
]
]
]
|
8b2107cc92f8f901a4d166ea60aafa82e3e5aeca | 30e4267e1a7fe172118bf26252aa2eb92b97a460 | /code/pkg_Utility/Modules/ConfigDB/Cx_ConfigFactory.h | 18afc50df40370582f90d83836779da70fcc1464 | [
"Apache-2.0"
]
| permissive | thinkhy/x3c_extension | f299103002715365160c274314f02171ca9d9d97 | 8a31deb466df5d487561db0fbacb753a0873a19c | refs/heads/master | 2020-04-22T22:02:44.934037 | 2011-01-07T06:20:28 | 2011-01-07T06:20:28 | 1,234,211 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | h | // Copyright 2008-2011 Zhang Yun Gui, [email protected]
// https://sourceforge.net/projects/x3c/
//
// 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.
#ifndef _X3_CONFIGDB_CONFIGFACTORY_H
#define _X3_CONFIGDB_CONFIGFACTORY_H
#include <Ix_ConfigDBFactory.h>
class Cx_ConfigFactory
: public Ix_ConfigDBFactory
{
public:
Cx_ConfigFactory();
virtual ~Cx_ConfigFactory();
protected:
// From Ix_ConfigDBFactory
//
virtual Cx_Ptr OpenAccessDB(
const std::wstring& filename,
const std::wstring& user = L"",
const std::wstring& password = L"");
virtual Cx_Ptr OpenSQLServerDB(
const std::wstring& server,
const std::wstring& database,
const std::wstring& user = L"",
const std::wstring& password = L"");
};
#endif // _X3_CONFIGDB_CONFIGFACTORY_H
| [
"rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3"
]
| [
[
[
1,
42
]
]
]
|
5c8c4314e4a09bbaafa53c55bbd98d7ab0b7719d | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlZBufferState.h | 526595068212289c10ab4aac42c879d5f4bd34d8 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,300 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLZBUFFERSTATE_H
#define WMLZBUFFERSTATE_H
#include "WmlRenderState.h"
namespace Wml
{
WmlSmartPointer(ZBufferState);
class WML_ITEM ZBufferState : public RenderState
{
WmlDeclareDefaultState(ZBufferState);
WmlDeclareRTTI;
WmlDeclareStream;
public:
ZBufferState ();
virtual Type GetType () const;
enum CompareFunction
{
CF_NEVER,
CF_LESS,
CF_EQUAL,
CF_LEQUAL,
CF_GREATER,
CF_NOTEQUAL,
CF_GEQUAL,
CF_ALWAYS,
CF_QUANTITY
};
bool& Enabled (); // default: false
bool& Writeable (); // default: false
CompareFunction& Compare (); // default: CF_ALWAYS
protected:
bool m_bEnabled, m_bWriteable;
CompareFunction m_eCompare;
};
WmlRegisterStream(ZBufferState);
#include "WmlZBufferState.inl"
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
d164860e5769157512f67abf3419273f77c27a14 | 48c6de8cb63cf11147049ce07b2bd7e020d0d12b | /opencollada/include/COLLADASaxFrameworkLoader/include/COLLADASaxFWLPostProcessor.h | b4ab12d3145f1659b0985c46dba715c325f43f90 | []
| no_license | ngbinh/libBlenderWindows | 73effaa1aab8d9d1745908f5528ded88eca21ce3 | 23fbaaaad973603509b23f789a903959f6ebb560 | refs/heads/master | 2020-06-08T00:41:55.437544 | 2011-03-25T05:13:25 | 2011-03-25T05:13:25 | 1,516,625 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,628 | h | /*
Copyright (c) 2008-2009 NetAllied Systems GmbH
This file is part of COLLADASaxFrameworkLoader.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#ifndef __COLLADASAXFWL_POSTPROCESSOR_H__
#define __COLLADASAXFWL_POSTPROCESSOR_H__
#include "COLLADASaxFWLPrerequisites.h"
#include "COLLADASaxFWLDocumentProcessor.h"
namespace COLLADASaxFWL
{
/** TODO Documentation */
class PostProcessor : public DocumentProcessor
{
private:
public:
/** Constructor.
@param colladaLoader The collada loader this file loader is being used by. Used to retrieve document
global properties.
@param saxParserErrorHandler The error handler all sax parser errors should be passed to.
@param objectFlags Flags (Loader::ObjectFlags) of objects that should be parsed. Set these
if you don't want to parse the entire file, but only those parts required to create the objects in
objectFlags.
@param parsedObjectFlags Flags (Loader::ObjectFlags) of objects already parsed by @a colladaLoader.
Will be set to all objects parsed after a call of load().*/
PostProcessor( Loader* colladaLoader,
SaxParserErrorHandler* saxParserErrorHandler,
int objectFlags,
int& /*[in,out]*/ parsedObjectFlags);
/** Destructor. */
virtual ~PostProcessor();
/** Performs all the required post processing.:*/
void postProcess();
/************** should be removed after a redesign of IFileLoader **********/
/** Sets the parser to @a parserToBeSet.*/
virtual void setParser( COLLADASaxFWL14::ColladaParserAutoGen14* parserToBeSet ){ COLLADABU_ASSERT(false);}
/** Sets the parser to @a parserToBeSet.*/
virtual void setParser( COLLADASaxFWL15::ColladaParserAutoGen15* parserToBeSet ){ COLLADABU_ASSERT(false);}
/** Returns the absolute uri of the currently parsed file*/
virtual const COLLADABU::URI& getFileUri(){ COLLADABU_ASSERT(false); return COLLADABU::URI::INVALID; }
/****************************************************************************/
private:
/** Writes all the visual scenes.*/
void writeVisualScenes();
/** Writes all the library nodes.*/
void writeLibraryNodes();
/** Writes all the effects.*/
void writeEffects();
/** Writes all the lights.*/
void writeLights();
/** Writes all the cameras.*/
void writeCameras();
/** Creates all the animation lists.*/
void createMissingAnimationLists();
/** Stores the binding stored in @a binding in the appropriate animation list*/
void createMissingAnimationList( const Loader::AnimationSidAddressBinding& binding );
/** Writes all the morph controllers, stored in the loaders morph controller list.*/
bool writeMorphControllers();
/** Writes all animation lists.*/
void writeAnimationLists();
void linkAndWriteFormulas();
/** Creates and writes the kinematics scene.*/
void createAndWriteKinematicsScene();
/** Returns a pointer to the file loader. */
virtual FileLoader* getFileLoader() { return 0; }
/** Returns a pointer to the file loader. */
virtual const FileLoader* getFileLoader() const { return 0; }
/** Disable default copy ctor. */
PostProcessor( const PostProcessor& pre );
/** Disable default assignment operator. */
const PostProcessor& operator= ( const PostProcessor& pre );
};
} // namespace COLLADASAXFWL
#endif // __COLLADASAXFWL_POSTPROCESSOR_H__
| [
"[email protected]"
]
| [
[
[
1,
113
]
]
]
|
7784b62415cc44d5fd7a6833fe9243b702be0dca | 8403411fa78af2109c30e7c33ad9bc860d12ed83 | /src/tools/dup_component_tool.cc | 40e61e7e11d930849946943d9901b3e564cdb2f9 | []
| no_license | virtualritz/topmod | 7676b10e24f95547ccbb2e42cdb8b787a1461d59 | 95717591fc11afa67551a72e6824043887f971ba | refs/heads/master | 2020-04-01T21:00:55.192983 | 2008-11-01T23:45:41 | 2008-11-01T23:45:41 | 60,533,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,609 | cc | /*
* dup_component_tool.cc
*
* Created on: Sep 12, 2008
* Author: david.morris
*/
#include <algorithm>
#include <queue>
#include "dup_component_tool.h"
// Implementation of the class DupComponentTool.
// Constructor.
DupComponentTool::DupComponentTool(QWidget *parent) {
parent_ = parent;
layout_ = new QGridLayout;
layout_->setVerticalSpacing(1);
layout_->setHorizontalSpacing(1);
apply_button_ = new QPushButton(tr("&Duplicate"));
connect(apply_button_, SIGNAL(clicked()), this, SLOT(Apply()));
layout_->addWidget(apply_button_, 1, 0, 1, 1);
layout_->setRowStretch(1, 1);
layout_->setColumnStretch(1, 1);
widget_ = new QWidget;
widget_->setWindowTitle(tr("DupComponent Mode"));
widget_->setLayout(layout_);
action_ = new QAction(tr("Duplicate Component"), parent_);
action_->setIcon(QIcon(":/images/transforms.png"));
action_->setCheckable(true);
action_->setStatusTip(tr("Enter DupComponent Mode"));
action_->setToolTip(tr("DupComponent Mode"));
connect(action_, SIGNAL(triggered()), this, SLOT(Activate()));
}
// Apply the current changes.
void DupComponentTool::Apply() {
// Duplicate the current selected connected component.
GLWidget *glw = ((MainWindow*) parent_)->getActive();
DLFLObjectPtr object = ((MainWindow*) parent_)->GetObject();
// Collect all selected vertices.
DLFLVertexPtrSet old_vertices;
DLFLEdgePtrSet old_edges;
DLFLFacePtrSet old_faces;
DLFLVertexPtrArray selected_vertices = glw->getSelectedVertices();
DLFLEdgePtrArray selected_edges = glw->getSelectedEdges();
DLFLFacePtrArray selected_faces = glw->getSelectedFaces();
if (selected_vertices.size() > 0) {
old_vertices.insert(*selected_vertices.begin());
} else if (selected_edges.size() > 0) {
DLFLVertexPtr u, v;
(*selected_edges.begin())->getVertexPointers(u, v);
old_vertices.insert(u);
} else if (selected_faces.size() > 0) {
DLFLFaceVertexPtr current = (*selected_faces.begin())->front()->next();
old_vertices.insert((*selected_faces.begin())->front()->getVertexPtr());
}
if (old_vertices.size() <= 0) return;
((MainWindow*)parent_)->undoPush();
//get all faces, edges, and vertices in the connected component.
std::queue<DLFLVertexPtr> Q;
Q.push(*old_vertices.begin());
while (!Q.empty()) {
DLFLVertexPtr u = Q.front();
Q.pop();
DLFLEdgePtrArray edges;
u->getEdges(edges);
//loop through edges, select all vertices connected to these edges
for (DLFLEdgePtrArray::iterator eit = edges.begin(); eit != edges.end(); eit++) {
old_edges.insert(*eit);
DLFLFacePtr face1, face2;
(*eit)->getFacePointers(face1, face2);
old_faces.insert(face1);
old_faces.insert(face2);
DLFLVertexPtr vp1, vp2;
(*eit)->getVertexPointers(vp1, vp2);
if (old_vertices.count(vp1) <= 0) {
old_vertices.insert(vp1);
Q.push(vp1);
}
if (old_vertices.count(vp2) <= 0) {
old_vertices.insert(vp2);
Q.push(vp2);
}
}
}
double min_old_x = std::numeric_limits<float>::max();
double max_old_x = std::numeric_limits<float>::min();
for (DLFLVertexPtrSet::iterator it = old_vertices.begin(); it
!= old_vertices.end(); ++it) {
Vector3d p = (*it)->getCoords();
min_old_x = min(min_old_x, p.getCArray()[0]);
}
DLFLVertexPtrArray all_vertices(object->beginVertex(), object->endVertex());
for (DLFLVertexPtrArray::iterator it = all_vertices.begin(); it
!= all_vertices.end(); ++it) {
Vector3d p = (*it)->getCoords();
max_old_x = max(max_old_x, p.getCArray()[0]);
}
// Now we have all the vertices, edges and faces.
// Add vertices first, we need a map to reconstruct the new component.
map<DLFLVertexPtr, DLFLVertexPtr> old2new_vertices;
vector<DLFLVertexPtr> new_vertices;
for (DLFLVertexPtrSet::iterator it = old_vertices.begin(); it
!= old_vertices.end(); ++it) {
DLFLVertexPtr new_vertex = new DLFLVertex((*it)->getCoords());
object->addVertexPtr(new_vertex);
old2new_vertices[*it] = new_vertex;
new_vertices.push_back(new_vertex);
}
map<int, map<int, DLFLEdgePtr> > new_edges;
// Trace all faces to insert edges and corners.
for (DLFLFacePtrSet::iterator it = old_faces.begin(); it != old_faces.end(); ++it) {
DLFLFacePtr face = *it;
DLFLFaceVertexPtr face_vertex = face->front();
if (face_vertex == NULL) continue; // Ignore empty faces.
DLFLFacePtr new_face = new DLFLFace;
// New vertices.
DLFLVertexPtr u, v;
// New corner to create.
DLFLFaceVertexPtr u_corner;
do {
u = old2new_vertices[face_vertex->getVertexPtr()];
v = old2new_vertices[face_vertex->next()->getVertexPtr()];
// Create corners for new_v.
u_corner = new DLFLFaceVertex;
u_corner->vertex = u;
new_face->addVertexPtr(u_corner);
DLFLEdgePtr new_edge = NULL;
int uid = u->getID();
int vid = v->getID();
if (new_edges.find(uid) != new_edges.end() && new_edges[uid].find(vid)
!= new_edges[uid].end()) new_edge = new_edges[uid][vid];
if (new_edge == NULL) { // Insert the new edge.
new_edge = new DLFLEdge;
// Does the order matter?
// new_edge->setFaceVertexPointers(u_corner, v_corner);
new_edge->setFaceVertexPtr1(u_corner, false);
new_edges[uid][vid] = new_edge;
new_edges[vid][uid] = new_edge;
} else {
new_edge->setFaceVertexPtr2(u_corner, false);
new_edge->updateFaceVertices();
object->addEdgePtr(new_edge);
}
face_vertex = face_vertex->next();
} while (face_vertex != face->front());
new_face->setMaterial(face->material());
new_face->updateFacePointers();
new_face->addFaceVerticesToVertices();
object->addFacePtr(new_face);
}
glw->recomputeNormals();
((MainWindow*) parent_)->redraw();
GeometricTool * geo_tool = GeometricTool::GetInstance(parent_);
geo_tool->Activate();
((MainWindow*) parent_)->clearSelected();
for (vector<DLFLVertexPtr>::iterator it = new_vertices.begin(); it
!= new_vertices.end(); ++it) {
((MainWindow*) parent_)->selectVertex(*it);
}
geo_tool->SetTranslation(max_old_x + 2 - min_old_x, 0, 0);
}
// This is called when the user activate this tool.
void DupComponentTool::Activate() {
((MainWindow*) parent_)->setToolOptions(widget_);
}
void DupComponentTool::RetranslateUi(){
}
| [
"dvmorris@e0e46c49-be69-4f5a-ad62-21024a331aea"
]
| [
[
[
1,
192
]
]
]
|
a4eef9fef82c0e8419849648c73ef512e90bcc8a | 6c8c4728e608a4badd88de181910a294be56953a | /CommunicationModule/TelepathyIM/VideoSession.h | 5b7e06bc50b3c63f60bcf4a99bc2b53d5d6297ca | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_Communication_TelepathyIM_VideoSession_h
#define incl_Communication_TelepathyIM_VideoSession_h
//#include "interface.h"
namespace TelepathyIM
{
class VideoSession // : public CommunicaVideoSessionInterface
{
public:
VideoSession();
};
} // end of namespace: TelepathyIM
#endif // incl_Communication_TelepathyIM_VideoSession_h
| [
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3",
"mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
2
],
[
7,
7
],
[
17,
17
]
],
[
[
3,
5
],
[
8,
16
]
],
[
[
6,
6
]
]
]
|
630d7251f6384a7950210b8474447abe2856e6a8 | 56d19e2be913ff0bf884b2a462374d9acb6f91ce | /Window.cpp | 56bc25e1c77abebc4133d9a6b80d7389fea04708 | []
| no_license | cgoakley/laser-surfsprint | 0169dddae05e0baf52cd86dc5d82ad6a32ecd402 | 52466d80978fb2530bcb6107196f089163d62ef4 | refs/heads/master | 2020-07-23T11:43:14.813042 | 2006-03-15T12:00:00 | 2016-11-17T15:57:36 | 73,809,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,205 | cpp | #define WINDOBJ_MAIN
#include <WindObj/Private.h>
#include <malloc.h>
#include <stdio.h>
static LRESULT CALLBACK WindowWndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
Cursor g_arrowCursor(Cursor::arrow), g_waitCursor(Cursor::hourGlass);
bool g_isWaiting = false;
void SetWaitCursor(bool value)
{
g_isWaiting = value;
(value? &g_waitCursor: &g_arrowCursor)->Set();
}
static void WindowClassName(char *className, int classID)
{
int i, n = GetModuleFileName(NULL, className, 256);
for (i = n - 1; i > 0 && className[i] != '\\' && className[i] != ':'; i--)
{
if (className[i] == '.') className[n = i] = '\0';
}
memmove(className, className + i + 1, n - i);
sprintf(className + n - i - 1, "WndClass%d", classID);
}
WindowClassData s_windowClassData = {0, 0, NULL, NULL};
Window::Window() : m_parent(NULL)
{
}
DWORD TranslateWindowStyle(int flags)
{
DWORD dwStyle = WS_CAPTION;
if (!(flags & WS_drawOnChildren)) dwStyle |= WS_CLIPCHILDREN;
if (flags & WS_sizeBorder) dwStyle |= WS_SIZEBOX;
if (flags & (WS_sysMenu | WS_sysMenuWithExit)) dwStyle |= WS_SYSMENU;
if (flags & WS_minButton) dwStyle |= WS_MINIMIZEBOX;
if (flags & WS_maxButton) dwStyle |= WS_MAXIMIZEBOX;
if (flags & WS_containedByParent) dwStyle |= WS_CHILD | WS_CLIPSIBLINGS;
if ((flags & WS_displayMask) != WS_hidden) dwStyle |= WS_VISIBLE;
return dwStyle;
}
// Window with title bar ...
void Window_Window(Window &thisWindow, Window *parent, const void *caption, bool captionIsWide, const Rect &rect,
int flags, Menu *menu, const Icon *icon, Cursor *cursor)
{
memset(thisWindow.m_windowData = new WindowData, 0, sizeof(WindowData));
thisWindow.m_parent = parent;
HMENU hMenu;
if (thisWindow.m_windowData->menu = menu)
{
menu->Activate();
hMenu = (HMENU)menu->m_menuData->id;
MENUINFO menuInfo = {sizeof(MENUINFO), MIM_MENUDATA, 0, 0, NULL, 0, (DWORD)&thisWindow};
SetMenuInfo(hMenu, &menuInfo);
}
else hMenu = NULL;
/* Within a Windows class it seems to be possible to customise everything for a particular window
except for the icon, so the classes that we create by RegisterClass will therefore group
windows with the same icon. The case of no icon at all is covered by the first class, named
"<AppName>WndClass0". Subsequent ones are named "<AppName>WndClass1", etc. --- the icon of a new
window being compared with the registered ones until a match is found, or, if there is none, a
new class is created. */
int classID;
WindowClassData *wcd = &s_windowClassData, *prevWcd = &s_windowClassData;
if (icon)
{
classID = 1;
for (wcd = s_windowClassData.nextWCD; wcd && wcd->icon != icon && *wcd->icon != *icon;
prevWcd = wcd, wcd = wcd->nextWCD)
if (classID == wcd->id) classID++;
}
else classID = 0;
if (!wcd)
{
wcd = new WindowClassData;
wcd->refs = 0;
wcd->id = classID;
wcd->icon = new Icon(*icon);
wcd->nextWCD = NULL;
prevWcd->nextWCD = wcd;
}
thisWindow.m_windowData->wcd = wcd;
if (flags & WS_backingBitmap) thisWindow.m_windowData->screenCache = (HBITMAP)-1;
char className[256];
WindowClassName(className, classID);
if (wcd->refs++ == 0) // Window class created on first use
{
WNDCLASSEX wndClassEx =
{
sizeof(WNDCLASSEX), CS_DBLCLKS, WindowWndProc, 0, 0, g_hInst,
(HICON)(icon? wcd->icon->m_iconData: NULL), (HCURSOR)g_arrowCursor.m_cursorData, (HBRUSH)NULL,
NULL, className, (HICON)NULL
};
wcd->atom = RegisterClassEx(&wndClassEx);
}
DWORD dwStyle = TranslateWindowStyle(flags) | WS_BORDER | WS_HSCROLL | WS_VSCROLL;
if (flags & WS_displayMask) dwStyle &= ~WS_VISIBLE;
int x, y, width, height;
if (&rect)
{
if ((x = rect.left) == CW_USEDEFAULT) width = rect.right;
else width = rect.right - rect.left;
if ((y = rect.top) == CW_USEDEFAULT) height = rect.bottom;
else height = rect.bottom - rect.top;
}
else x = y = width = height = CW_USEDEFAULT;
HWND hWnd;
if (captionIsWide)
{
wchar_t classNameW[256];
size_t n = strlen(className);
UINT nWide = MultiByteToWideChar(CP_UTF8, 0, className, (int)n, NULL, 0);
MultiByteToWideChar(CP_UTF8, 0, className, (int)n, classNameW, nWide);
hWnd = CreateWindowExW(flags & WS_topmost? WS_EX_TOPMOST: 0, classNameW, (const wchar_t *)caption, dwStyle, x, y, width, height,
parent? parent->m_windowData->hWnd: NULL, hMenu, g_hInst, &thisWindow);
}
else
{
hWnd = CreateWindowExA(flags & WS_topmost? WS_EX_TOPMOST: 0, className, (const char *)caption, dwStyle, x, y, width, height,
parent? parent->m_windowData->hWnd: NULL, hMenu, g_hInst, &thisWindow);
}
if (!hWnd) throw WindObjError();
SetClassLong(hWnd, GCL_HCURSOR, (LONG)cursor->m_cursorData);
ShowScrollBar(thisWindow.m_windowData->hWnd, SB_BOTH, FALSE);
if (menu) thisWindow.ActivateSpecialKey(); // Activate accelerators, if any
if (flags & WS_sysMenuWithExit)
{
HMENU hSysMenu = GetSystemMenu(thisWindow.m_windowData->hWnd, FALSE);
AppendMenu(hSysMenu, MF_SEPARATOR, 0, NULL);
AppendMenu(hSysMenu, MF_STRING, 0x58, "&Exit");
}
int nCmdShow;
switch (flags & WS_displayMask)
{
default: nCmdShow = flags & WS_notActivated? SW_SHOWNOACTIVATE: SW_SHOWNORMAL; break;
case WS_hidden: nCmdShow = SW_HIDE; break;
case WS_minimized: nCmdShow = flags & WS_notActivated? SW_SHOWMINNOACTIVE: SW_SHOWMINIMIZED; break;
case WS_maximized: nCmdShow = SW_SHOWMAXIMIZED; break;
}
ShowWindow(thisWindow.m_windowData->hWnd, nCmdShow);
}
Window::Window(Window *parent, const char *caption, const Rect &rect,
int flags, Menu *menu, const Icon *icon, Cursor *cursor)
{
Window_Window(*this, parent, caption, false, rect, flags, menu, icon, cursor);
}
Window::Window(Window *parent, const wchar_t *caption, const Rect &rect,
int flags, Menu *menu, const Icon *icon, Cursor *cursor)
{
Window_Window(*this, parent, caption, true, rect, flags, menu, icon, cursor);
}
// Window with no title bar ...
Window::Window(Window *parent, const Rect &rect, int flags, Cursor *cursor)
{
memset(m_windowData = new WindowData, 0, sizeof(WindowData));
m_parent = parent;
/* Within a Windows class it seems to be possible to customise everything for a particular window
except for the icon, so the classes that we create by RegisterClass will therefore group
windows with the same icon. In this case, there is icon at all so we use the window class
"<AppName>WndClass0". */
m_windowData->wcd = &s_windowClassData;
if (flags & WS_backingBitmap) m_windowData->screenCache = (HBITMAP)-1;
char className[256];
WindowClassName(className, 0);
if (s_windowClassData.refs++ == 0) // Window class created on first use
{
WNDCLASSEX wndClassEx =
{
sizeof(WNDCLASSEX), CS_DBLCLKS, WindowWndProc, 0, 0, g_hInst,
(HICON)NULL, (HCURSOR)NULL, (HBRUSH)NULL, NULL, className, (HICON)NULL
};
s_windowClassData.atom = RegisterClassEx(&wndClassEx);
}
DWORD dwStyle = flags & WS_containedByParent && parent? WS_CHILD | WS_CLIPSIBLINGS: WS_POPUP;
if (!(flags & WS_drawOnChildren)) dwStyle |= WS_CLIPCHILDREN;
if (flags & WS_thinBorder) dwStyle |= WS_BORDER;
int x = 0, y = 0, nWidth = 100, nHeight = 100;
if (&rect) {x = rect.left; y = rect.top; nWidth = rect.right - rect.left; nHeight = rect.bottom - rect.top;}
if (!CreateWindowEx((flags & WS_topmost? WS_EX_TOPMOST: 0) | (flags & WS_notInTaskbar? WS_EX_TOOLWINDOW: 0),
className, NULL, dwStyle, x, y, nWidth, nHeight, parent? parent->m_windowData->hWnd: NULL, NULL, g_hInst, this))
throw WindObjError();
if (cursor)
{
DWORD ret = SetClassLong(m_windowData->hWnd, GCL_HCURSOR, (LONG)cursor->m_cursorData);
ret = ret;
}
ShowWindow(m_windowData->hWnd, flags & WS_hidden || !&rect? SW_HIDE: SW_SHOWDEFAULT);
}
LRESULT CALLBACK WindowWndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
Window *w = (Window *)GetWindowLong(hWnd, GWL_USERDATA);
WindowData *wd;
LRESULT lRes;
if (w && StdMessageProcessing(&lRes, w, hWnd, message, wParam, lParam)) return lRes;
/* WM_GETMINMAXINFO, WM_NCCREATE & WM_NCCALCSIZE are sent before this message, but do not
need to be processed (yet) ... */
if (!w && message == WM_CREATE)
{
CREATESTRUCT *cs = (LPCREATESTRUCT)lParam;
w = (Window *)cs->lpCreateParams;
wd = w->m_windowData;
wd->hWnd = hWnd;
SetWindowLong(wd->hWnd = hWnd, GWL_USERDATA, (LONG)w);
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
/* Windows are either destroyed directly by a delete operator or indirectly when a parent is destroyed.
In the latter case the window receives a WM_DESTROY message, where the USERDATA is set to NULL and this
destructor called. Thus the destructor will only call DestroyWindow if the USERDATA is not NULL... */
Window::~Window()
{
if (GetWindowLong(m_windowData->hWnd, GWL_USERDATA))
{
SetWindowLong(m_windowData->hWnd, GWL_USERDATA, NULL); // to prevent a feedback loop
// BCW claims that there is a resource leak unless this line is included ...
if (m_windowData->menu) DestroyMenu((HMENU)m_windowData->menu->m_menuData->id);
DestroyWindow(m_windowData->hWnd); // the WM_DESTROY triggered by this now goes to default processing only
}
if (m_windowData->menu)
{
delete (MenuTable *)m_windowData->menu->m_menuData->data; // stop menus being destroyed twice
m_windowData->menu->m_menuData->data = NULL;
delete m_windowData->menu;
}
delete m_windowData->accMP;
if (m_windowData->palette) DeleteObject(m_windowData->palette);
if (m_windowData->wcd && !(--m_windowData->wcd->refs))
{
UnregisterClass((LPCTSTR)m_windowData->wcd->atom, g_hInst);
if (m_windowData->wcd->icon) // class must be unregistered before icon deleted
{
delete m_windowData->wcd->icon;
WindowClassData *wcd = &s_windowClassData;
for (; wcd->nextWCD != m_windowData->wcd; wcd = wcd->nextWCD);
wcd->nextWCD = m_windowData->wcd->nextWCD;
delete m_windowData->wcd;
}
}
if (m_windowData->screenCache && m_windowData->screenCache != (HBITMAP)-1)
DeleteObject(m_windowData->screenCache);
if (m_windowData->nSpecialKeys > 0)
{
for (int i = 0; i < m_windowData->nSpecialKeys; i++)
delete [] m_windowData->specialKey[i].keyStroke;
delete [] m_windowData->specialKey;
}
delete m_windowData;
m_windowData = NULL;
if (g_mouseWind == this) g_mouseWind = NULL;
}
void Window::ErrorMessageBox(const char *formatString, ...)
{
va_list args;
va_start(args, formatString);
char errorText[256], windowTitle[80];
_vsnprintf(errorText, sizeof(errorText), formatString, args);
GetWindowText(m_windowData->hWnd, windowTitle, 80);
windowTitle[sizeof(windowTitle) - 1] = '\0';
MessageBox(m_windowData->hWnd, errorText, windowTitle, MB_OK | MB_ICONEXCLAMATION);
}
void Window::ErrorMessageBox(const wchar_t *formatString, ...)
{
va_list args;
va_start(args, formatString);
wchar_t errorText[256], windowTitle[80];
_vsnwprintf(errorText, sizeof(errorText) / sizeof(wchar_t), formatString, args);
GetWindowTextW(m_windowData->hWnd, windowTitle, sizeof(windowTitle) / sizeof(wchar_t));
windowTitle[sizeof(windowTitle) / sizeof(wchar_t) - 1] = '\0';
MessageBoxW(m_windowData->hWnd, errorText, windowTitle, MB_OK | MB_ICONEXCLAMATION);
}
void Window::SetMenus(Menu *menuBar)
{
if (m_windowData->menu) delete m_windowData->menu;
(m_windowData->menu = menuBar)->Activate();
HMENU hMenu = (HMENU)menuBar->m_menuData->id;
MENUINFO menuInfo = {sizeof(MENUINFO), MIM_MENUDATA, 0, 0, NULL, 0, (DWORD)this};
BOOL b = SetMenuInfo(hMenu, &menuInfo);
SetMenu(m_windowData->hWnd, hMenu);
ActivateSpecialKey(); // Activate accelerators, if any
}
struct OwnedWindEnum
{
HWND hWnd;
int n;
};
static BOOL __stdcall EnumThreadWP(HWND hWnd, LPARAM lParam)
{
OwnedWindEnum *OWE = (OwnedWindEnum *)lParam;
if (OWE->hWnd == GetWindow(hWnd, GW_OWNER) && GetWindowLong(hWnd, GWL_USERDATA))
{
if (OWE->n-- == 0) {OWE->hWnd = hWnd; return FALSE;}
}
return TRUE;
}
int Window::NumChildren() const
{
int n = 0;
for (HWND hChild = GetWindow(m_windowData->hWnd, GW_CHILD); hChild;
hChild = GetWindow(hChild, GW_HWNDNEXT))
{
if (GetWindowLong(hChild, GWL_USERDATA)) n++;
}
OwnedWindEnum OWE = {m_windowData->hWnd, -1};
EnumThreadWindows(GetCurrentThreadId(), (WNDENUMPROC)EnumThreadWP, (LPARAM)&OWE);
return n - OWE.n - 1;
}
Window *Window::Child(int index)
{
Window *child = NULL;
for (HWND hChild = GetWindow(m_windowData->hWnd, GW_CHILD); hChild;
hChild = GetWindow(hChild, GW_HWNDNEXT))
{
child = (Window *)GetWindowLong(hChild, GWL_USERDATA);
if (!child) continue;
if (index-- == 0) return child;
}
OwnedWindEnum OWE = {m_windowData->hWnd, index};
EnumThreadWindows(GetCurrentThreadId(), (WNDENUMPROC)EnumThreadWP, (LPARAM)&OWE);
if (OWE.hWnd != m_windowData->hWnd)
{
child = (Window *)GetWindowLong(OWE.hWnd, GWL_USERDATA);
}
return child;
}
void Window::Closed()
{
delete this;
}
void Window::Exposed(DrawingSurface &DS, const Rect &invRect)
{
DS.Rectangle(invRect, Pen(), Brush(Colour(Colour::window)));
}
void Window::SysColoursChanged()
{
Draw();
}
void Window::AcceptDroppedFiles()
{
DragAcceptFiles(m_windowData->hWnd, TRUE);
}
void Window::RejectDroppedFiles()
{
DragAcceptFiles(m_windowData->hWnd, FALSE);
}
void Window::FileDropped(int number, const char *fileName) {}
void Window::FileDropped(int number, const wchar_t *fileName) {}
void Window::ActivateSpecialKey(char *keyStroke, KeyAction keyAction)
{
if (!m_windowData->accMP) m_windowData->accMP = new AcceleratorMP(m_windowData->hWnd);
m_windowData->accMP->Modify(this, keyStroke, keyAction);
}
void Window::SetPalette(const Bitmap *bm)
{
if (m_windowData->palette) DeleteObject(m_windowData->palette);
m_windowData->palette = NULL;
if (bm)
{
m_windowData->palette = ClonePalette(bm->m_bitmapData->hPalette);
SendMessage(m_windowData->hWnd, WM_QUERYNEWPALETTE, 0, 0);
}
}
void Window::SetPalette()
{
SetPalette(NULL);
}
int Window::GetText(char *text)
{
int n = GetWindowTextLength(m_windowData->hWnd);
if (text) GetWindowText(m_windowData->hWnd, text, n + 1);
return n;
}
int Window::GetText(wchar_t *text)
{
int n = GetWindowTextLengthW(m_windowData->hWnd);
if (text) GetWindowTextW(m_windowData->hWnd, text, n + 1);
return n;
}
float Window::GetFloatValue()
{
int n = GetWindowTextLength(m_windowData->hWnd);
char *buff = (char *)_alloca(n + 1);
GetWindowText(m_windowData->hWnd, buff, n + 1);
return (float)atof(buff);
}
int Window::GetIntValue()
{
int n = GetWindowTextLength(m_windowData->hWnd);
char *buff = (char *)_alloca(n + 1);
GetWindowText(m_windowData->hWnd, buff, n + 1);
return atoi(buff);
}
void Window::SetText(const char *text)
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
SetWindowText(g_hWndNuu, text? text: "");
g_hWndNuu = hWndNuu;
}
void Window::SetText(const wchar_t *text)
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
SetWindowTextW(g_hWndNuu, text? text: L"");
g_hWndNuu = hWndNuu;
}
void Window::SetText(const char *text, int nText)
{
char *buff = (char *)_alloca(nText + 1);
if (nText) memcpy(buff, text, nText);
buff[nText] = '\0';
SetText(buff);
}
void Window::SetText(const wchar_t *text, int nText)
{
wchar_t *buff = (wchar_t *)_alloca((nText + 1) * sizeof(wchar_t));
if (nText) memcpy(buff, text, nText * sizeof(wchar_t));
buff[nText] = L'\0';
SetText(buff);
}
void Window::SetText(double value)
{
char buff[25];
sprintf(buff, "%lg", value);
SetText(buff);
}
void Window::SetText(float value)
{
char buff[20];
sprintf(buff, "%g", value);
SetText(buff);
}
void Window::SetText(int value)
{
char buff[15];
sprintf(buff, "%d", value);
SetText(buff);
}
void Window::Size(int width, int height)
{
SetWindowSize(m_windowData->hWnd, width, height);
}
void Window::SetCanvas(int canvasW, int canvasH)
{
SetCanvas(0, 0, canvasW, canvasH);
}
void Window::SetCanvas(int canvasX, int canvasY, int canvasW, int canvasH)
{
m_windowData->org.x = canvasX;
m_windowData->org.y = canvasY;
m_windowData->canvasW = canvasW;
m_windowData->canvasH = canvasH;
SetCanvas();
}
void Window::SetCanvasToChildren()
{
int n = NumChildren();
if (n < 1) return;
Rect r = Child(0)->BoundingRect();
for (int i = 1; i < n; i++) r |= Child(i)->BoundingRect();
SetCanvas(r.right - r.left, r.bottom - r.top);
}
static void MoveChildren(Window *w, const Point &offset)
{
int n = w->NumChildren();
for (int i = 0; i < n; i++)
{
Window *child = w->Child(i);
if (GetWindowLong(child->m_windowData->hWnd, GWL_STYLE) & WS_CHILD) // Do not move child overlapped windows
{
Point p = child->BoundingRect().TopLeft() - w->ClientOrigin() + offset;
child->Move(p.x, p.y);
}
}
}
void Window::SetCanvasOrg(const Point &newOrigin, bool isRelative)
{
// NB: newOrigin can be out of range: the SetScrollInfo call below will adjust as required
Point oldOrg = m_windowData->org, shift, newOrg = newOrigin;
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd; // To avoid processing the messages generated by the scroll functions
if (isRelative) newOrg += m_windowData->org;
m_windowData->org = newOrg;
shift = newOrg - oldOrg;
// MoveChildren(this, -shift);
SCROLLINFO si = {sizeof(SCROLLINFO), SIF_POS, 0, 0, 0, m_windowData->org.x};
if (oldOrg.x != m_windowData->org.x)
m_windowData->org.x = SetScrollInfo(m_windowData->hWnd, SB_HORZ, &si, TRUE);
if (oldOrg.y != m_windowData->org.y)
{
si.nPos = m_windowData->org.y;
m_windowData->org.y = SetScrollInfo(m_windowData->hWnd, SB_VERT, &si, TRUE);
}
g_hWndNuu = hWndNuu;
ScrollWindowEx(m_windowData->hWnd, oldOrg.x - m_windowData->org.x,
oldOrg.y - m_windowData->org.y, NULL, NULL, NULL, NULL, SW_INVALIDATE | SW_SCROLLCHILDREN);
}
Rect Window::Canvas() const
{
return Rect(m_windowData->org.x, m_windowData->org.y,
m_windowData->org.x + m_windowData->canvasW,
m_windowData->org.y + m_windowData->canvasH);
}
static bool SetBitmapSize(HBITMAP &hBM, int width, int height)
{
if (!hBM) return false;
if (hBM != (HBITMAP)-1)
{
BITMAP bm;
GetObject(hBM, sizeof(BITMAP), &bm);
if (width == bm.bmWidth && height == bm.bmHeight) return false;
DeleteObject(hBM);
}
HDC hDCscreen = CreateIC("DISPLAY", NULL, NULL, NULL);
hBM = CreateCompatibleBitmap(hDCscreen, width, height);
DeleteDC(hDCscreen);
return true;
}
bool Window::SetCanvas()
{
RECT rect;
Point oldOrg = m_windowData->org;
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowScrollBar(m_windowData->hWnd, SB_BOTH, FALSE);
GetClientRect(m_windowData->hWnd, &rect);
BOOL showHorizSB, showVertSB;
int scrollW = GetSystemMetrics(SM_CXVSCROLL), scrollH = GetSystemMetrics(SM_CXHSCROLL);
if (showVertSB = m_windowData->canvasH > rect.bottom)
{
showHorizSB = m_windowData->canvasW > rect.right - scrollW;
}
else
{
if (showHorizSB = m_windowData->canvasW > rect.right)
showVertSB = m_windowData->canvasH > rect.bottom - scrollH;
}
if (showHorizSB)
{
SCROLLINFO si = {sizeof(SCROLLINFO), SIF_ALL, 0, m_windowData->canvasW - 1,
rect.right - (showVertSB? scrollW: 0), m_windowData->org.x};
m_windowData->org.x = SetScrollInfo(m_windowData->hWnd, SB_HORZ, &si, TRUE);
ShowScrollBar(m_windowData->hWnd, SB_HORZ, TRUE);
}
else m_windowData->org.x = 0;
if (showVertSB)
{
SCROLLINFO si = {sizeof(SCROLLINFO), SIF_ALL, 0, m_windowData->canvasH - 1,
rect.bottom - (showHorizSB? scrollH: 0), m_windowData->org.y};
m_windowData->org.y = SetScrollInfo(m_windowData->hWnd, SB_VERT, &si, TRUE);
ShowScrollBar(m_windowData->hWnd, SB_VERT, TRUE);
}
else m_windowData->org.y = 0;
if (SetBitmapSize(m_windowData->screenCache,
m_windowData->canvasW? m_windowData->canvasW: rect.right,
m_windowData->canvasH? m_windowData->canvasH: rect.bottom))
{
DrawingSurface DS(*this);
Exposed(DS, ClientRect());
}
g_hWndNuu = hWndNuu;
return oldOrg != m_windowData->org;
}
void Window::Size(Rect rect)
{
MoveWindow(m_windowData->hWnd, rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, TRUE);
}
void Window::SetClientWidth(int width)
{
SetWindowClientWidth(m_windowData->hWnd, width);
}
void Window::Disable()
{
EnableWindow(m_windowData->hWnd, FALSE);
}
void Window::Draw()
{
InvalidateRect(m_windowData->hWnd, NULL, FALSE);
UpdateWindow(m_windowData->hWnd);
}
void Window::Draw(const Rect &rect)
{
Rect rect1 = rect - m_windowData->org;
InvalidateRect(m_windowData->hWnd, (CONST RECT *)&rect1, FALSE);
UpdateWindow(m_windowData->hWnd);
}
void Window::Enable(bool state)
{
EnableWindow(m_windowData->hWnd, state);
}
bool Window::IsEnabled()
{
return IsWindowEnabled(m_windowData->hWnd) == TRUE;
}
void Window::Block(bool state)
{
m_windowData->blocked = state;
}
void Window::Unblock() {Block(false);}
bool Window::IsBlocked() {return m_windowData->blocked;}
void Window::Hide()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, SW_HIDE);
g_hWndNuu = hWndNuu;
}
void Window::Show()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, SW_SHOW);
g_hWndNuu = hWndNuu;
}
void Window::Show(bool state)
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, state? SW_SHOW: SW_HIDE);
g_hWndNuu = hWndNuu;
}
void Window::ShowWithoutActivating()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, SW_SHOWNOACTIVATE);
g_hWndNuu = hWndNuu;
}
bool Window::IsShown()
{
return IsWindowVisible(m_windowData->hWnd) == TRUE;
}
void Window::Minimize()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, SW_MINIMIZE);
g_hWndNuu = hWndNuu;
}
bool Window::IsMinimized()
{
WINDOWPLACEMENT WP;
GetWindowPlacement(m_windowData->hWnd, &WP);
return WP.showCmd == SW_MINIMIZE ||
WP.showCmd == SW_SHOWMINIMIZED ||
WP.showCmd == SW_FORCEMINIMIZE ||
WP.showCmd == SW_SHOWMINNOACTIVE;
}
void Window::Maximize()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, SW_MAXIMIZE);
g_hWndNuu = hWndNuu;
}
bool Window::IsMaximized()
{
WINDOWPLACEMENT WP;
GetWindowPlacement(m_windowData->hWnd, &WP);
return WP.showCmd == SW_MAXIMIZE ||
WP.showCmd == SW_SHOWMAXIMIZED;
}
void Window::SizeNormal()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
ShowWindow(g_hWndNuu, SW_RESTORE);
g_hWndNuu = hWndNuu;
}
void Window::BringToTop()
{
BringWindowToTop(m_windowData->hWnd);
}
void Window::SetFocus()
{
HWND hWndNuu = g_hWndNuu;
g_hWndNuu = m_windowData->hWnd;
::SetFocus(g_hWndNuu);
g_hWndNuu = hWndNuu;
}
bool Window::IsFocal() const
{
return m_windowData->hWnd == ::GetFocus();
}
void Window::SetMouseCapture() {SetCapture(m_windowData->hWnd);}
void Window::ReleaseMouseCapture() {ReleaseCapture();}
bool Window::IsMouseCaptured() const {return GetCapture() == m_windowData->hWnd;}
Rect Window::BoundingRect() const
{
RECT rect;
if (!GetWindowRect(m_windowData->hWnd, &rect)) throw "Failed to get window co-ordinates";
return Rect(rect.left, rect.top, rect.right, rect.bottom);
}
void Window::BoundingRect(const Rect &rect)
{
Rect rect1 = rect;
if (GetWindowLong(m_windowData->hWnd, GWL_STYLE) & WS_CHILD)
MapWindowPoints(NULL, GetParent(m_windowData->hWnd), (LPPOINT)&rect1, 2);
if (!MoveWindow(m_windowData->hWnd, rect1.left, rect1.top, rect1.right - rect1.left, rect1.bottom - rect1.top, FALSE))
throw "MoveWindow call failed";
}
Rect Window::NormalBoundingRect() const
{
WINDOWPLACEMENT WP;
GetWindowPlacement(m_windowData->hWnd, &WP);
return Rect(WP.rcNormalPosition.left, WP.rcNormalPosition.top, WP.rcNormalPosition.right, WP.rcNormalPosition.bottom);
}
void Window::NormalBoundingRect(const Rect &rect)
{
WINDOWPLACEMENT WP;
GetWindowPlacement(m_windowData->hWnd, &WP);
WP.rcNormalPosition.left = rect.left;
WP.rcNormalPosition.top = rect.top;
WP.rcNormalPosition.right = rect.right;
WP.rcNormalPosition.bottom = rect.bottom;
if (!SetWindowPlacement(m_windowData->hWnd, &WP)) throw "Failed to set bounding rectangle of window";
}
Rect Window::ClientRect() const
{
Rect rect;
if (!GetClientRect(m_windowData->hWnd, (RECT *)&rect)) throw "Failed to get window client rectangle";
return rect + m_windowData->org;
}
void Window::ClientRect(const Rect &rect)
{
Rect crect = ClientRect();
HWND hWnd = m_windowData->hWnd;
RECT brect;
GetWindowRect1(hWnd, &brect);
MoveWindow(hWnd, brect.left, brect.top,
rect.right - rect.left + brect.right - brect.left - (crect.right - crect.left),
rect.bottom - rect.top + brect.bottom - brect.top - (crect.bottom - crect.top), TRUE);
}
Point Window::ClientOrigin() const
{
Point pt;
MapWindowPoints(m_windowData->hWnd, NULL, (LPPOINT)&pt, 1);
return pt;
}
void Window::Move(int x, int y)
{
SetWindowPos(m_windowData->hWnd, x, y);
}
void Window::KeyPressed(VirtualKeyCode vkcode, char ascii, unsigned short repeat) {}
void Window::KeyReleased(VirtualKeyCode vkcode) {}
void Window::MouseLButtonPressed(int x, int y, int flags) {}
void Window::MouseLButtonReleased(int x, int y, int flags) {}
void Window::MouseLButtonDblClicked(int x, int y, int flags) {}
void Window::MouseRButtonPressed(int x, int y, int flags) {}
void Window::MouseRButtonReleased(int x, int y, int flags) {}
void Window::MouseRButtonDblClicked(int x, int y, int flags) {}
void Window::MouseMoved(int x, int y) {}
void Window::SetCursor(Cursor *&cursor) {}
void Window::MouseLeft() {}
void Window::Moved() {}
void Window::Sized() {}
void Window::Minimized() {}
void Window::Exited() {}
void Window::UserMessage(unsigned int msgId, unsigned int wParam, long lParam) {}
void Window::PostUserMessage(unsigned int msgId, unsigned int wParam, long lParam)
{
if (!PostMessage(m_windowData->hWnd, msgId, wParam, lParam))
throw WindObjError();
}
void Window::LostFocus() {}
void Window::GotFocus() {}
void Window::OtherMessage(unsigned int,unsigned int,long) {}
/* This message processing is common to all classes derived from <Window> & provides the link
from the WM messages to the invocation of the methods that process them. If FALSE is returned
then either the message was not processed or it may be subject to further processing & so should
be passed to the relevant default processing ... */
HBRUSH s_hBr;
BOOL StdMessageProcessing(LRESULT *lRes, Window *w, HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WindowData *wd = w->m_windowData;
int i;
static char buff[256];
LRESULT lRes1;
DrawingSurface *DS;
PAINTSTRUCT ps;
Rect invRect;
DSData *dsd;
HDC hDC;
Window *ctrl;
if (lRes) *lRes = 0;
if (wd->blocked) // if input is blocked, then suppress processing of user input messages
{
switch (message)
{
case WM_KEYDOWN:
case WM_KEYUP:
case WM_CHAR:
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
return TRUE;
}
}
if (ProcessMenuMessage(*lRes, wd, message, wParam, lParam))
return TRUE;
switch (message)
{
case WM_CHAR:
w->KeyPressed((VirtualKeyCode)0, (char)wParam, (unsigned short)lParam);
break;
// case WM_CHILDACTIVATE:
// SendMessage(hWnd, WM_NCACTIVATE, TRUE, 0);
// break;
case WM_CLOSE:
w->Closed();
return TRUE;
case WM_COMMAND:
if (lParam)
{
Window *child = (Window *)GetWindowLong((HWND)lParam, GWL_USERDATA);
if (child && child->m_windowData->hWnd != g_hWndNuu) // block messages not generated by the user
{
switch (HIWORD(wParam))
{
case BN_CLICKED: ((Button *)child)->Clicked(); return TRUE;
case CBN_EDITCHANGE: ((ComboBox *)child)->TextChanged(); return TRUE;
case CBN_SELCHANGE: ((ComboBox *)child)->ListIndexChanged(); return TRUE;
case EN_CHANGE: ((EditBox *)child)->TextChanged(); return TRUE;
}
}
}
else
{
if (wParam == 1 || wParam == 2) // Return or Cancel with no Default or Cancel button
{
HWND hWndChild = GetFocus();
if (hWnd != GetParent(hWndChild))
{
if (GetParent(hWndChild = GetParent(hWndChild)) != hWnd) break; // combo box edit box is child of combo
}
if (ctrl = (Window *)GetWindowLong(hWndChild, GWL_USERDATA))
{
if (wParam == 1) ctrl->KeyPressed(VKC_return, VKC_return, 1);
else ctrl->KeyPressed(VKC_escape, VKC_escape, 1);
}
break;
}
if (wParam >= 105536 && wParam < 105536 + (unsigned int)wd->nSpecialKeys)
{
(*wd->specialKey[wParam - 105536].keyAction)(w);
return TRUE;
}
}
break;
case WM_SYSCOMMAND:
if (wParam == 0x58)
{
w->Exited();
return TRUE;
}
break;
case WM_CTLCOLOREDIT:
if ((ctrl = (Window *)GetWindowLong((HWND)lParam, GWL_USERDATA)) ||
(ctrl = (Window *)GetWindowLong(GetParent((HWND)lParam), GWL_USERDATA)))
{
ControlData *cd = (ControlData *)ctrl->m_windowData;
SetBkMode((HDC)wParam, TRANSPARENT);
SetTextColor((HDC)wParam, cd->foreColour);
LOGBRUSH logBrush;
GetObject(cd->backBrush, sizeof(LOGBRUSH), &logBrush);
SetBkColor((HDC)wParam, logBrush.lbColor);
if (lRes) *lRes = (LRESULT)cd->backBrush;
return TRUE;
}
break;
case WM_CTLCOLORBTN:
case WM_CTLCOLORDLG:
case WM_CTLCOLORLISTBOX:
case WM_CTLCOLORMSGBOX:
case WM_CTLCOLORSCROLLBAR:
case WM_CTLCOLORSTATIC:
if ((ctrl = (Window *)GetWindowLong((HWND)lParam, GWL_USERDATA)) ||
(ctrl = (Window *)GetWindowLong(GetParent((HWND)lParam), GWL_USERDATA)))
{
ControlData *cd = (ControlData *)ctrl->m_windowData;
SetBkMode((HDC)wParam, TRANSPARENT);
SetTextColor((HDC)wParam, cd->foreColour);
if (lRes) *lRes = (LRESULT)cd->backBrush;
return TRUE;
}
break;
case WM_DESTROY:
SetWindowLong(hWnd, GWL_USERDATA, NULL);
{
HWND hWndChild;
hWndChild = GetWindow(hWnd, GW_CHILD);
while (hWndChild)
{
hWndChild = GetWindow(hWndChild, GW_HWNDNEXT);
}
}
delete w;
break;
case WM_DROPFILES:
for (i = DragQueryFile((HDROP)wParam, (UINT)-1, NULL, 0); i > 0; i--)
{
DragQueryFile((HDROP)wParam, i - 1, buff, 256);
w->FileDropped(i, buff);
wchar_t wbuff[256];
DragQueryFileW((HDROP)wParam, i - 1, wbuff, sizeof(wbuff) / sizeof(wchar_t));
w->FileDropped(i, wbuff);
}
break;
case WM_HSCROLL:
if (!wd->canvasW) break;
{
int orgX = wd->org.x;
GetClientRect(hWnd, (RECT *)&invRect);
switch (LOWORD(wParam))
{
case SB_BOTTOM: orgX = wd->canvasW - invRect; break;
case SB_LINELEFT: orgX -= 10; break;
case SB_LINERIGHT: orgX += 10; break;
case SB_PAGELEFT: orgX -= invRect.right; break;
case SB_PAGERIGHT: orgX += invRect.right; break;
case SB_TOP: orgX = 0; break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK: orgX = HIWORD(wParam); break;
default: return FALSE;
}
w->SetCanvasOrg(Point(orgX, wd->org.y), false);
}
break;
case WM_KEYDOWN:
w->KeyPressed((VirtualKeyCode)wParam, 0, (unsigned short)lParam);
break;
case WM_KEYUP:
w->KeyReleased((VirtualKeyCode)wParam);
break;
case WM_KILLFOCUS:
{
/* Deactivate the title bar unless this window is an ancestor of the one receiving the focus ...
for (HWND lostTo = (HWND)wParam; lostTo = GetParent(lostTo);)
if (!lostTo || lostTo == hWnd) goto KFND;
SendMessage(hWnd, WM_NCACTIVATE, 0, 0);
KFND: */
if (!g_hWndNuu) w->LostFocus();
}
break;
case WM_LBUTTONDBLCLK:
w->MouseLButtonDblClicked((short)LOWORD(lParam) + wd->org.x, (short)HIWORD(lParam) + wd->org.y, wParam);
break;
case WM_LBUTTONDOWN:
w->MouseLButtonPressed((short)LOWORD(lParam) + wd->org.x, (short)HIWORD(lParam) + wd->org.y, wParam);
break;
case WM_LBUTTONUP:
w->MouseLButtonReleased((short)LOWORD(lParam) + wd->org.x, (short)HIWORD(lParam) + wd->org.y, wParam);
break;
case WM_RBUTTONDBLCLK:
w->MouseRButtonDblClicked((short)LOWORD(lParam) + wd->org.x, (short)HIWORD(lParam) + wd->org.y, wParam);
break;
case WM_RBUTTONDOWN:
w->MouseRButtonPressed((short)LOWORD(lParam) + wd->org.x, (short)HIWORD(lParam) + wd->org.y, wParam);
break;
case WM_RBUTTONUP:
w->MouseRButtonReleased((short)LOWORD(lParam) + wd->org.x, (short)HIWORD(lParam) + wd->org.y, wParam);
break;
case WM_MOUSEACTIVATE:
SendMessage(hWnd, WM_NCACTIVATE, TRUE, 0);
SetFocus(hWnd);
if (lRes) *lRes = MA_ACTIVATE;
return TRUE;
case WM_MOUSEMOVE:
w->MouseMoved((short)lParam + wd->org.x, (short)((unsigned long)lParam >> 16) + wd->org.y);
break;
case WM_MOVE:
w->Moved();
break;
case WM_NCHITTEST:
lRes1 = DefWindowProc(hWnd, message, wParam, lParam);
if (g_mouseWind && (lRes1 != HTCLIENT || g_mouseWind != w)) g_mouseWind->MouseLeft();
g_mouseWind = lRes1 != HTCLIENT? NULL: w;
if (lRes) *lRes = lRes1;
break;
case WM_PAINT:
BeginPaint(hWnd, &ps);
DS = new DrawingSurface(*(Window *)NULL);
dsd = (DSData *)DS->m_dsData;
dsd->wnd = w;
if (ps.hdc)
{
dsd->hDC = ps.hdc;
*(RECT *)&invRect = ps.rcPaint;
}
else // when the whole window is redrawn, you get a null hDC
{
dsd->hDC = GetDC(wd->hWnd);
GetClientRect(hWnd, (RECT *)&invRect);
}
if (wd->palette) SelectPalette(dsd->hDC, wd->palette, FALSE);
SetViewportOrgEx(dsd->hDC, -wd->org.x, -wd->org.y, NULL);
SetBkMode(dsd->hDC, TRANSPARENT);
invRect += wd->org;
if (wd->screenCache)
{
Rect clientRect = w->ClientRect();
if (SetBitmapSize(wd->screenCache, clientRect.right, clientRect.bottom))
{
DrawingSurface ds1(*w);
w->Exposed(ds1, clientRect);
}
hDC = CreateCompatibleDC(dsd->hDC);
SelectObject(hDC, wd->screenCache);
BitBlt(dsd->hDC, invRect.left, invRect.top, invRect.right - invRect.left,
invRect.bottom - invRect.top, hDC, invRect.left, invRect.top, SRCCOPY);
DeleteDC(hDC);
}
else w->Exposed(*DS, invRect);
s_hBr = (HBRUSH)GetCurrentObject(dsd->hDC, OBJ_BRUSH);
delete DS;
EndPaint(hWnd, &ps);
return TRUE;
case WM_PALETTECHANGED:
if (wd->palette && wParam != (WPARAM)hWnd)
{
hDC = GetDC(hWnd);
SelectPalette(hDC, wd->palette, FALSE);
UpdateColors(hDC);
ReleaseDC(hWnd, hDC);
}
break;
case WM_QUERYNEWPALETTE:
if (wd->palette)
{
hDC = GetDC(hWnd);
SelectPalette(hDC, wd->palette, FALSE);
i = RealizePalette(hDC);
ReleaseDC(hWnd, hDC);
if (i) InvalidateRect(hWnd, NULL, TRUE);
}
break;
case WM_SETCURSOR:
if (g_isWaiting) g_waitCursor.Set(); // If the application is in a wait state, set the cursor to the Wait one regardless
else
{
Cursor *cursor = (Cursor *)-1;
w->SetCursor(cursor);
if (cursor == (Cursor *)-1) return FALSE; // No cursor was set - go to default processing
if (cursor) cursor->Set();
}
return TRUE;
case WM_SETFOCUS:
if (hWnd != g_hWndNuu) w->GotFocus();
break;
case WM_SIZE:
if (hWnd == g_hWndNuu) break;
if (wParam == SIZE_MINIMIZED) w->Minimized();
else if (wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED)
{
if (wd->canvasW || wd->canvasH)
{
Point org = wd->org;
w->SetCanvas();
if (org != wd->org)
{
MoveChildren(w, org - wd->org);
ScrollWindowEx(wd->hWnd, org.x - wd->org.x, org.y - wd->org.y,
NULL, NULL, NULL, NULL, SW_INVALIDATE);
}
}
w->Sized();
}
break;
case WM_SYSCOLORCHANGE:
w->SysColoursChanged();
break;
case WM_VSCROLL:
{
if (!wd->canvasH) break;
GetClientRect(hWnd, (RECT *)&invRect);
int orgY = wd->org.y, newOrgY;
switch (LOWORD(wParam))
{
case SB_BOTTOM: newOrgY = wd->canvasH - invRect.bottom; break;
case SB_LINELEFT: newOrgY = orgY - 10; break;
case SB_LINERIGHT: newOrgY = orgY + 10; break;
case SB_PAGELEFT: newOrgY = orgY - invRect.bottom; break;
case SB_PAGERIGHT: newOrgY = orgY + invRect.bottom; break;
case SB_TOP: newOrgY = 0; break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK: newOrgY = HIWORD(wParam); break;
default: return FALSE;
}
w->SetCanvasOrg(Point(wd->org.x, newOrgY), false);
}
break;
case 0x020A: // WM_MOUSEWHEEL - this #define is not being picked up. I don't know why.
if (wd->canvasH)
{
Point newOrg = wd->org + Point(0, -(short)HIWORD(wParam));
if (newOrg.y < 0) newOrg.y = 0;
else
{
Rect rect;
GetClientRect(wd->hWnd, (RECT *)&rect);
int maxY = max(wd->canvasH - rect.bottom, 0);
if (newOrg.y > maxY) newOrg.y = maxY;
}
w->SetCanvasOrg(newOrg, false);
}
break;
/* This message is handled rather than being sent to default processing in order to avoid
WM_MOVE and WM_SIZE messages coming from function calls rather than just user interaction
case WM_WINDOWPOSCHANGED:
return TRUE; */
default:
if (message >= WM_USER && message <= 0x7FFF)
{
w->UserMessage(message, wParam, lParam);
}
else
{
w->OtherMessage(message, wParam, lParam);
}
break;
}
return FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
1280
]
]
]
|
e56203f7e70f6260351803babaf2853ea6577844 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /CloverDemo/source/control/inc/ListBoxPainter.h | 30bf73acc26801192ae842575c1b0782ae737024 | []
| 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,763 | h | /*
============================================================================
Name : ListBoxPainter.h
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CListBoxPainter declaration
============================================================================
*/
#ifndef LISTBOXPAINTER_H
#define LISTBOXPAINTER_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include <GDI.H>
// CLASS DECLARATION
/**
* CListBoxPainter
*
*/
const TInt KItemAnimationFrame = 4;
class CListBoxPainter : public CBase
{
public:
// Constructors and destructor
/**
* Destructor.
*/
~CListBoxPainter();
/**
* Two-phased constructor.
*/
static CListBoxPainter* NewL();
/**
* Two-phased constructor.
*/
static CListBoxPainter* NewLC();
private:
/**
* Constructor for performing 1st stage construction
*/
CListBoxPainter();
/**
* EPOC default constructor for performing 2nd stage construction
*/
void ConstructL();
public:
const CFont* GetFont() ;
void SetWidth (const TInt& aWidth) {iWidth = aWidth; }
TInt GetWidth() const {return iWidth;};
TInt GetItemHeight();
TRgb GetHightLightClock() {return KRgbGray;}
TRgb GetTextColor() {return KRgbRed;};
TInt GetAnimationItemScrollFrame() const {return KItemAnimationFrame;}
TInt GetAnimationScrollStartFadeFrame() const {return KItemAnimationFrame * 6;}
TInt GetAnimationScrollFrame() const {return KItemAnimationFrame * 10;}
TInt GetScrollWidth() const {return 8;}
TInt GetAnimationMarqueeStartFrame() const {return KItemAnimationFrame * 4;}
private:
TInt iWidth;
TInt iItemHeight;
TInt iItemPadding;
};
#endif // LISTBOXPAINTER_H
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
84
]
]
]
|
6fde03a77edb90e2a35972fc54c324858ef6fb02 | fa134e5f64c51ccc1c2cac9b9cb0186036e41563 | /GT/GridView.cpp | 7968fc8adb03c3da7ba57fabc61b97d2fb0b6342 | []
| 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 | GB18030 | C++ | false | false | 21,497 | cpp | // GridView.cpp : 实现文件
//
#include "stdafx.h"
#include <gl/glut.h>
#include <algorithm>
#include <fstream>
#include "GT.h"
#include "MainFrm.h"
#include "GridView.h"
#include "GTDoc.h"
#include "GTView.h"
#include "Singleton.h"
#include "MsgType.h"
#include "FlightPathSetController.h"
bool lowerSorter(PathPointData* p1, PathPointData* p2)
{
return p1->serial <= p2->serial;
}
// CGridView
IMPLEMENT_DYNCREATE(CGridView, CFormView)
CGridView::CGridView()
: CFormView(CGridView::IDD)
{
m_pGridCtrl = NULL;
mapTex = NULL;
controller = new CFlightPathSetController();
isChange = false;
}
CGridView::~CGridView()
{
if (m_pGridCtrl) {
delete m_pGridCtrl;
}
if (mapTex)
delete mapTex;
if (controller)
delete controller;
}
void CGridView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
DDX_GridControl(pDX, IDC_GRID, *m_pGridCtrl);
}
BEGIN_MESSAGE_MAP(CGridView, CFormView)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_ERASEBKGND()
ON_NOTIFY(GVN_ENDLABELEDIT, IDC_GRID, OnGridEndEdit)
ON_NOTIFY(GVN_BEGINLABELEDIT, IDC_GRID, OnGridStartEdit)
ON_NOTIFY(NM_CLICK, IDC_GRID, OnGridClick)
ON_BN_CLICKED(IDC_SET_POINT_COM, &CGridView::OnBnClickedSetPointCompleted)
ON_BN_CLICKED(IDC_SCHEDULE_PATH, &CGridView::OnBnClickedSchedulePath)
ON_BN_CLICKED(IDC_ASSURE_PATH, &CGridView::OnBnClickedAssurePath)
ON_MESSAGE(LOAD_POINT_REPLY_MSG, &CGridView::OnLoadReply)
ON_MESSAGE(PATH_CHECK_REPLY_MSG, &CGridView::OnCheckReply)
ON_BN_CLICKED(IDC_ADD_POINT, &CGridView::OnBnClickedAddPoint)
ON_BN_CLICKED(IDC_SELECT_POINT, &CGridView::OnBnClickedSelectPoint)
ON_BN_CLICKED(IDC_LOAD_IMAGE_BUTTON, &CGridView::OnBnClickedLoadImageButton)
ON_BN_CLICKED(IDC_LOAD_FILE_BUTTON, &CGridView::OnBnClickedLoadFileButton)
ON_BN_CLICKED(IDC_SAVE_FP_BUTTON, &CGridView::OnBnClickedSaveFpButton)
END_MESSAGE_MAP()
// CGridView 诊断
#ifdef _DEBUG
void CGridView::AssertValid() const
{
CFormView::AssertValid();
}
CGTDoc* CGridView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CGTDoc)));
return (CGTDoc*)m_pDocument;
}
#ifndef _WIN32_WCE
void CGridView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif
#endif //_DEBUG
// CGridView 消息处理程序
void CGridView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
}
int CGridView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFormView::OnCreate(lpCreateStruct) == -1)
return -1;
GetDocument()->gridView = this;
if (m_pGridCtrl == NULL)
{
// Create the grid control object
m_pGridCtrl = new CGridCtrl;
if (!m_pGridCtrl)
return -1;
// Create the grid control window
CRect rect;
GetClientRect(rect);
rect.bottom /= 2;
m_pGridCtrl->Create(rect, this, IDC_GRID);
// Fill it up with stuff
m_pGridCtrl->SetEditable(TRUE);
m_pGridCtrl->GetDefaultCell(FALSE, FALSE)->SetBackClr(RGB(0xFF, 0xFF, 0xE0));
m_pGridCtrl->EnableDragAndDrop(TRUE);
try {
m_pGridCtrl->SetRowCount(NUM_OF_ROW + 1);
m_pGridCtrl->SetColumnCount(NUM_OF_COL + 1);
m_pGridCtrl->SetFixedRowCount(1);
m_pGridCtrl->SetFixedColumnCount(1);
} catch (CMemoryException* e) {
e->ReportError();
e->Delete();
return -1;
}
// Just fill the row headings
for (int row = 1; row < m_pGridCtrl->GetRowCount(); row++) {
GV_ITEM Item;
Item.mask = GVIF_TEXT;
Item.row = row;
Item.col = 0;
Item.strText.Format(_T("%d"), row);
m_pGridCtrl->SetItem(&Item);
}
// Just fill the column headings
for (int col = 1; col < m_pGridCtrl->GetRowCount(); col++) {
GV_ITEM Item;
Item.mask = GVIF_TEXT;
Item.row = 0;
Item.col = col;
switch (col) {
case 1:
Item.strText.Format(_T("X"));
break;
case 2:
Item.strText.Format(_T("Y"));
break;
case 3:
Item.strText.Format(_T("Z"));
break;
case 4:
Item.strText.Format(_T("T"));
break;
case 5:
Item.strText.Format(_T("Action"));
break;
default:
break;
}
m_pGridCtrl->SetItem(&Item);
}
// Just fill the row buttons
for (int row = 1; row < m_pGridCtrl->GetRowCount(); row++) {
GV_ITEM Item;
Item.mask = GVIF_TEXT;
Item.row = row;
Item.col = NUM_OF_COL;
Item.strText.Format(_T("Add"));
m_pGridCtrl->SetItem(&Item);
m_pGridCtrl->SetItemState(row, NUM_OF_COL, m_pGridCtrl->GetItemState(row, NUM_OF_COL) | GVIS_READONLY);
}
}
return 0;
}
void CGridView::OnSize(UINT nType, int cx, int cy)
{
CFormView::OnSize(nType, cx, cy);
if (m_pGridCtrl->GetSafeHwnd())
{
CRect rect;
GetClientRect(rect);
rect.bottom = rect.bottom / 2;
m_pGridCtrl->MoveWindow(rect);
// Because the grid control's client area size is 23 smaller then the CRect object which is passed
// as a parameter of Create function, a user-defined function is invoked for resize the columns' width
ResizeColumns(FALSE);
//TRACE("Size: %d %d %d %d\n", rect.right, rect.bottom, rect.Width(), rect.Height());
}
}
BOOL CGridView::OnEraseBkgnd(CDC* pDC)
{
/*
* If just return true, then the form view can't be updated each time we drag the splitter bar
*/
return CFormView::OnEraseBkgnd(pDC);
}
void CGridView::OnGridStartEdit(NMHDR *pNotifyStruct, LRESULT *pResult)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNotifyStruct;
TRACE(_T("Start Edit on row %d, col %d\n"), pItem->iRow, pItem->iColumn);
}
void CGridView::OnGridEndEdit(NMHDR *pNotifyStruct, LRESULT *pResult)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNotifyStruct;
TRACE(_T("End Edit on row %d, col %d\n"), pItem->iRow, pItem->iColumn);
}
BOOL CGridView::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
if (wParam == (WPARAM)m_pGridCtrl->GetDlgCtrlID())
{
*pResult = 1;
GV_DISPINFO *pDispInfo = (GV_DISPINFO*)lParam;
if (GVN_GETDISPINFO == pDispInfo->hdr.code)
{
//TRACE2("Getting Display info for cell %d,%d\n", pDispInfo->item.row, pDispInfo->item.col);
pDispInfo->item.strText.Format(_T("Message %d,%d"),pDispInfo->item.row, pDispInfo->item.col);
return TRUE;
}
else if (GVN_ODCACHEHINT == pDispInfo->hdr.code)
{
GV_CACHEHINT *pCacheHint = (GV_CACHEHINT*)pDispInfo;
TRACE(_T("Cache hint received for cell range %d,%d - %d,%d\n"),
pCacheHint->range.GetMinRow(), pCacheHint->range.GetMinCol(),
pCacheHint->range.GetMaxRow(), pCacheHint->range.GetMaxCol());
}
}
return CFormView::OnNotify(wParam, lParam, pResult);
}
void CGridView::OnGridClick(NMHDR *pNotifyStruct, LRESULT* /*pResult*/)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNotifyStruct;
CSingleton *instance = CSingleton::getInstance();
std::vector<pPathPointData> *path = instance->getPath();
// When clicking the last cell, then should check if the text is 'Add' or 'Update'
if (pItem->iColumn == NUM_OF_COL) {
PathPointData *ppd = NULL, *editedPoint = NULL;
CString label = m_pGridCtrl->GetItemText(pItem->iRow, pItem->iColumn);
if (label == "Add") {
// New a path point
ppd = new PathPointData();
memset(ppd, 0, sizeof(PathPointData));
// Set the serial number
ppd->serial = pItem->iRow - 1;
for (int i = 1; i <= NUM_OF_COL - 1; i++) {
CString itemText = m_pGridCtrl->GetItemText(pItem->iRow, i);
switch (i - 1) {
case 0:
sscanf_s(itemText, "%f", &ppd->Coordinate_X);
break;
case 1:
sscanf_s(itemText, "%f", &ppd->Coordinate_Y);
break;
case 2:
sscanf_s(itemText, "%f", &ppd->Coordinate_Z);
break;
case 3:
sscanf_s(itemText, "%f", &ppd->StayTime);
break;
default:
break;
}
}
// Change the text
m_pGridCtrl->SetItemText(pItem->iRow, pItem->iColumn, "Update");
m_pGridCtrl->Invalidate();
// Add the path point to the path vector
path->push_back(ppd);
} else if (label == "Update") {
editedPoint = findBySerial(path, pItem->iRow - 1);
if (editedPoint != NULL) {
// Update the path point's data
for (int i = 1; i <= NUM_OF_COL - 1; i++) {
CString itemText = m_pGridCtrl->GetItemText(pItem->iRow, i);
switch (i - 1) {
case 0:
sscanf_s(itemText, "%f", &editedPoint->Coordinate_X);
break;
case 1:
sscanf_s(itemText, "%f", &editedPoint->Coordinate_Y);
break;
case 2:
sscanf_s(itemText, "%f", &editedPoint->Coordinate_Z);
break;
case 3:
sscanf_s(itemText, "%f", &editedPoint->StayTime);
break;
default:
break;
}
}
}
} else {
return;
}
// Inform the CGTView to update
// Set the path
isChange = true;
GetDocument()->lowerRightView->setPath(path);
if (ppd)
GetDocument()->lowerRightView->addPathPoint(ppd);
else
GetDocument()->lowerRightView->updatePathPoint(editedPoint);
}
}
void CGridView::OnBnClickedSetPointCompleted()
{
/***** Set the state variable *****/
isPathCompleted = TRUE;
}
void CGridView::OnBnClickedSchedulePath()
{
schedulePath();
}
void CGridView::OnBnClickedAssurePath()
{
CSingleton* instance = CSingleton::getInstance();
std::vector<pPathPointData>* path = instance->getPath();
// Here we must send all the path point data to the server
if (path->size() == 0)
return;
// Sort the path
sort(path->begin(), path->end(), lowerSorter);
// Construct the content of the command to start send path points
char command[2];
__int16 *c = (__int16 *)command;
c[0] = TPT_LOADPATHPOINT_START;
// First send the LOAD START command
CNetCln* cln = ((CGTApp*)AfxGetApp())->getCln();
cln->SendSvr(command, sizeof(command));
// Then send the first path point
char pointCommand[sizeof(PathPointData) + 2];
c = (__int16 *)pointCommand;
c[0] = TPT_LOADPATHPOINTS;
memcpy(pointCommand + 2, (char *)(*path)[0], sizeof(PathPointData));
cln->SendSvr(pointCommand, sizeof(pointCommand));
}
void CGridView::schedulePath(void)
{
// TODO: 路径规划
}
LRESULT CGridView::OnLoadReply(WPARAM w, LPARAM l)
{
/*
* A point sent before has been received, so be ready to send the next point
*/
CSingleton* instance = CSingleton::getInstance();
std::vector<pPathPointData> *path = instance->getPath();
(*received)++;
__int16 *c;
CNetCln* cln = ((CGTApp*)AfxGetApp())->getCln();
if ((*received) == path->size()) {
char overCommand[2];
c = (__int16 *)overCommand;
c[0] = TPT_LOADPATHPOINT_STOP;
cln->SendSvr(overCommand, sizeof (overCommand));
return TRUE;
}
// Send one point
char pointCommand[sizeof(PathPointData) + INSTRUCTION_LENGTH];
c = (__int16 *)pointCommand;
c[0] = TPT_LOADPATHPOINTS;
memcpy(pointCommand + 2, (char *)((*path)[*received]), sizeof(PathPointData));
cln->SendSvr(pointCommand, sizeof(pointCommand));
TRACE(_T("Point:%d, %f, %f, %f\n"), (*path)[*received]->serial, (*path)[*received]->Coordinate_X, (*path)[*received]->Coordinate_Z);
return TRUE;
}
LRESULT CGridView::OnCheckReply(WPARAM w, LPARAM l)
{
CSingleton *instance = CSingleton::getInstance();
std::vector<pPathPointData> *path = instance->getPath();
PConfigStruct pCS = instance->getCS();
static int version = 0;
CTime t = CTime::GetCurrentTime();
CString timeString = t.Format("%Y-%m-%d %H-%M-%S");
CString verStr;
if (*state) {
// Set the global state variable
instance->setIsPathSet(TRUE);
// And need to save the data into the files
verStr.Format(_T("-%d.fp"), version++);
timeString.Append(verStr);
//pCS->isPathSet = 1;
memcpy(pCS->flightPathFileName, (LPCTSTR)timeString, timeString.GetLength());
std::ofstream ofs(timeString, std::ios::binary);
std::vector<PathPointData*>::iterator iter;
for (iter = path->begin(); iter != path->end(); iter++) {
ofs.write((char*)(*iter), sizeof(**iter));
}
ofs.close();
} else {
AfxMessageBox(_T("Failed to check the path"), MB_OK | MB_ICONSTOP);
instance->setIsPathSet(FALSE);
}
return TRUE;
}
pPathPointData CGridView::findBySerial(std::vector<pPathPointData>* path, int serial)
{
std::vector<pPathPointData>::iterator iter;
for (iter = path->begin(); iter != path->end(); iter++) {
if ((*iter)->serial == serial)
return *iter;
}
return NULL;
}
void CGridView::OnBnClickedAddPoint()
{
setCheckBoxStates("Add");
}
void CGridView::OnBnClickedSelectPoint()
{
setCheckBoxStates("Select");
}
/*
* Load a image, and turn it into a texture
*/
void CGridView::OnBnClickedLoadImageButton()
{
// Open the image file
char strFilter[] = {
"Joint Photographic Experts Group(*.jpg;*.jpeg)|*.jpg;*.jpeg|Graphic Interchange Format(*.gif)|*.gif|Bitmap(*.bmp)| *.bmp||" };
while (TRUE) {
CFileDialog fileDlg(TRUE, NULL, NULL, 0, strFilter);
CString fileName;
if (fileDlg.DoModal() == IDOK) {
fileName = fileDlg.GetPathName();
if (!mapTex)
mapTex = new Texture();
if (!mapTex->loadTexture(fileName) ) {
AfxMessageBox(_T("Invalidate image file\nChoose another one"), MB_OK | MB_ICONINFORMATION);
delete mapTex;
mapTex = NULL;
continue;
} else {
mapTex->setX1(0.0f);
mapTex->setX2(1.0f);
mapTex->setY1(0.0f);
mapTex->setY2(1.0f);
GetDocument()->lowerRightView->setMapTex(mapTex);
break;
}
} else {
break;
}
}
}
void CGridView::ResizeColumns(BOOL isFixedResize)
{
if (isFixedResize) {
if (m_pGridCtrl->GetColumnCount() <= 0)
return;
} else {
if (m_pGridCtrl->GetColumnCount() <= m_pGridCtrl->GetFixedColumnCount())
return;
}
int nChanged = 0;
int nFirstColumn = isFixedResize ? 0 : m_pGridCtrl->GetFixedColumnCount();
int col;
for (col = nFirstColumn; col < m_pGridCtrl->GetColumnCount(); col++) {
if (m_pGridCtrl->GetColumnWidth(col) >= 0)
nChanged++;
}
if (nChanged <= 0)
return;
long virtualWidth = m_pGridCtrl->GetVirtualWidth();
CRect rect;
GetClientRect(&rect);
int nDiffer;
if (isFixedResize)
nDiffer = rect.Width()/* - virtualWidth*//*- m_pGridCtrl->GetFixedColumnWidth()*/;
else
nDiffer = rect.Width() - m_pGridCtrl->GetFixedColumnWidth();
if (nDiffer <= 0)
nDiffer = rect.Width();
int nAdjustment = nDiffer / nChanged;
for (col = nFirstColumn; col < m_pGridCtrl->GetColumnCount(); col++) {
// The width of columns > 1
if (m_pGridCtrl->GetColumnWidth(col) >= 0) {
if (nAdjustment > 1) {
m_pGridCtrl->SetColumnWidth(col, nAdjustment - 1);
} else {
m_pGridCtrl->SetColumnWidth(col, nAdjustment);
}
}
}
//if (nDiffer > 0) {
// int remainder = nDiffer % nChanged;
// for (int nCount = 0, col = nFirstColumn; (col < m_pGridCtrl->GetColumnCount() && nCount < remainder); col++, nCount++)
// {
// if (m_pGridCtrl->GetColumnWidth(col) > 0) {
// int originWidth = m_pGridCtrl->GetColumnWidth(col);
// TRACE(_T("Remainder:%d\n"), originWidth);
// m_pGridCtrl->SetColumnWidth(col, originWidth - 1);
// }
// }
//} else {
// int remainder = (-nDiffer) % nChanged;
// for (int nCount = 0, col = nFirstColumn; (col < m_pGridCtrl->GetColumnCount() && nCount < remainder); col++, nCount++)
// {
// if (m_pGridCtrl->GetColumnWidth(col) > 0)
// m_pGridCtrl->SetColumnWidth(col, m_pGridCtrl->GetColumnWidth(col) - 1);
// }
//}
TRACE(_T("Changed:%d %d %d %ld\n"), nChanged, rect.right, rect.bottom, m_pGridCtrl->GetVirtualWidth());
m_pGridCtrl->Invalidate();
}
void CGridView::updateFormView(pPathPointData pP)
{
if (!pP)
return;
int nCol = 1;
int nRow = pP->serial + 1;
CString label;
label.Format("%.4g", pP->Coordinate_X);
m_pGridCtrl->SetItemText(nRow, nCol++, label);
label.Format("%.4g", pP->Coordinate_Y);
m_pGridCtrl->SetItemText(nRow, nCol++, label);
label.Format("%.4g", pP->Coordinate_Z);
m_pGridCtrl->SetItemText(nRow, nCol++, label);
label.Format("%.4g", pP->StayTime);
m_pGridCtrl->SetItemText(nRow, nCol++, label);
GetDocument()->lowerRightView->updatePathPoint(pP);
m_pGridCtrl->Invalidate();
isChange = true;
}
void CGridView::setCheckBoxStates(int state, CString label)
{
CButton* addPointButton = reinterpret_cast<CButton*>(GetDlgItem(IDC_ADD_POINT));
CButton* selectPointButton = reinterpret_cast<CButton*>(GetDlgItem(IDC_SELECT_POINT));
if (label == "Add") {
addPointButton->SetCheck(state);
selectPointButton->SetCheck(BST_UNCHECKED);
} else if (label == "Select") {
selectPointButton->SetCheck(state);
addPointButton->SetCheck(BST_UNCHECKED);
}
}
void CGridView::setCheckBoxStates(CString label)
{
CButton* addPointButton = reinterpret_cast<CButton*>(GetDlgItem(IDC_ADD_POINT));
CButton* selectPointButton = reinterpret_cast<CButton*>(GetDlgItem(IDC_SELECT_POINT));
if (selectPointButton && label == "Add")
selectPointButton->SetCheck(BST_UNCHECKED);
else if (label == "Select")
addPointButton->SetCheck(BST_UNCHECKED);
int checkState;
if (label == "Add")
checkState = addPointButton->GetCheck();
else if (label == "Select")
checkState = selectPointButton->GetCheck();
((CMainFrame*)AfxGetMainWnd())->setCheckBoxStates(checkState, label);
if (checkState == BST_CHECKED) {
if (label == "Add")
GetDocument()->lowerRightView->setEditState(1);
else
GetDocument()->lowerRightView->setEditState(2);
} else {
GetDocument()->lowerRightView->setEditState(-1);
}
}
void CGridView::OnBnClickedLoadFileButton()
{
char szFilter[] = {"All Files(*.*)|*.*||"};
CFileDialog fileDlg(TRUE, NULL, NULL, 0, szFilter);
UINT_PTR result = fileDlg.DoModal();
if (result == IDOK) {
CString fileName = fileDlg.GetFileName();
CSingleton* instance = CSingleton::getInstance();
instance->getPath()->clear();
GetDocument()->lowerRightView->restore();
controller->openPathFile(fileName, instance->getPath());
updateAllViews();
}
}
void CGridView::updateAllViews(void)
{
CSingleton* instance = CSingleton::getInstance();
std::vector<pPathPointData>* path = instance->getPath();
if (!path->size())
return;
// Inform the CGTView to update
// Set the path
CGTView* gtView = GetDocument()->lowerRightView;
gtView->setPath(path);
std::vector<pPathPointData>::iterator iter;
for (iter = path->begin(); iter != path->end(); iter++) {
gtView->addPathPoint(*iter);
// Inform the form view to update
updateFormView(*iter);
}
}
void CGridView::OnBnClickedSaveFpButton()
{
CSingleton *instance = CSingleton::getInstance();
std::vector<pPathPointData> *path = instance->getPath();
// Set the global state variable
instance->setIsPathSet(TRUE);
if (isChange) {
if (controller->checkPath(instance->getCurFlightPathFileName())) {
CString namePrefix;
while (true) {
CFPNamePrefixDialog npd;
if (npd.DoModal() == IDOK) {
if (npd.namePrefix.GetLength() != 0)
{
namePrefix = npd.namePrefix;
break;
}
}
}
controller->savePathFile(namePrefix, path);
} else {
controller->updatePathFile(path);
}
}
instance->updateCurConfiguration();
TRACE("Current Path: %s\n", instance->getCS()->flightPathFileName);
}
void CGridView::addRow(double wx, double wz)
{
/********** Sort the path **********/
std::vector<pPathPointData>* path = CSingleton::getInstance()->getPath();
sort(path->begin(), path->end(), lowerSorter);
if (path->size() >= 10)
return;
int nRow;
if (path->size() == 0) {
nRow = 1;
} else {
pPathPointData lastElement = path->back();
nRow = lastElement->serial + 2;
}
int nCol = 1;
CString buffer;
buffer.Format("%.3g", wx);
m_pGridCtrl->SetItemText(nRow, nCol++, buffer);
buffer.Format("%.3g", 0.0);
m_pGridCtrl->SetItemText(nRow, nCol++, buffer);
buffer.Format("%.3g", wz);
m_pGridCtrl->SetItemText(nRow, nCol++, buffer);
buffer.Format("%.3g", 0.0);
m_pGridCtrl->SetItemText(nRow, nCol++, buffer);
buffer.Format("Update");
m_pGridCtrl->SetItemText(nRow, nCol++, buffer);
pPathPointData pP = new PathPointData;
pP->Coordinate_X = wx;
pP->Coordinate_Y = 0.0;
pP->Coordinate_Z = wz;
pP->serial = nRow -1;
pP->StayTime = 0.0;
path->push_back(pP);
GetDocument()->lowerRightView->setPath(path);
GetDocument()->lowerRightView->addPathPoint(pP);
m_pGridCtrl->Invalidate();
isChange = true;
}
// E:\Workspace\Visual Studio 2008\GraduationThesis\GT\GridView.cpp : implementation file
//
//#include "stdafx.h"
//#include "GT.h"
//#include "E:\Workspace\Visual Studio 2008\GraduationThesis\GT\GridView.h"
// CFPNamePrefixDialog dialog
IMPLEMENT_DYNAMIC(CFPNamePrefixDialog, CDialog)
CFPNamePrefixDialog::CFPNamePrefixDialog(CWnd* pParent /*=NULL*/)
: CDialog(CFPNamePrefixDialog::IDD, pParent)
, namePrefix(_T(""))
{
}
CFPNamePrefixDialog::~CFPNamePrefixDialog()
{
}
void CFPNamePrefixDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_FP_NAME_PREFIX_EDIT, namePrefix);
}
BEGIN_MESSAGE_MAP(CFPNamePrefixDialog, CDialog)
END_MESSAGE_MAP()
// CFPNamePrefixDialog message handlers
| [
"[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6"
]
| [
[
[
1,
786
]
]
]
|
441e608f37e5bda0cd7ff2b1a7dd80390041b7db | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/sipcodec/src/t_sipcodecapiserver.cpp | b1068e6438af568b90e1cd1ad69af835510b093b | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,231 | cpp | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// This contains CT_SIPCodecServer
#include "t_sipcodecapiserver.h"
CT_SIPCodecServer* CT_SIPCodecServer::NewL()
/**
* @return - Instance of the test server
* Same code for Secure and non-secure variants
* Called inside the MainL() function to create and start the
* CTestServer derived server.
*/
{
CT_SIPCodecServer* server = new (ELeave)CT_SIPCodecServer();
CleanupStack::PushL(server);
server->ConstructL();
CleanupStack::Pop(server);
return server;
}
CTestBlockController* CT_SIPCodecServer::CreateTestBlock()
{
CTestBlockController* controller = new CT_SIPCodecBlock();
return controller;
}
LOCAL_C void MainL()
/**
* Secure variant
* Much simpler, uses the new Rendezvous() call to sync with the client
*/
{
#if (defined __DATA_CAGING__)
RProcess().DataCaging(RProcess::EDataCagingOn);
RProcess().SecureApi(RProcess::ESecureApiOn);
#endif
CActiveScheduler* sched=NULL;
sched=new(ELeave) CActiveScheduler;
CActiveScheduler::Install(sched);
CT_SIPCodecServer* server = NULL;
// Create the CTestServer derived server
TRAPD(err,server = CT_SIPCodecServer::NewL());
if(!err)
{
// Sync with the client and enter the active scheduler
RProcess::Rendezvous(KErrNone);
sched->Start();
}
delete server;
delete sched;
}
GLDEF_C TInt E32Main()
/**
* @return - Standard Epoc error code on process exit
* Secure variant only
* Process entry point. Called by client using RProcess API
*/
{
__UHEAP_MARK;
CTrapCleanup* cleanup = CTrapCleanup::New();
if(cleanup == NULL)
{
return KErrNoMemory;
}
#if (defined TRAP_IGNORE)
TRAP_IGNORE(MainL());
#else
TRAPD(err,MainL());
#endif
delete cleanup;
__UHEAP_MARKEND;
return KErrNone;
}
| [
"none@none"
]
| [
[
[
1,
91
]
]
]
|
4765f2ce70e6bce21c55381c2d5da73eed635b8a | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/IColorable.h | bb8810332e920ed797bde7078457d79c7e9971cc | []
| no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | h | #pragma once
#include <cv.h>
namespace baluchon { namespace core { namespace datas {
class IColorable
{
public:
virtual ~IColorable(void) {}
virtual void setColor(int b, int g, int r) {
mColor = cvScalar(b, g, r);
}
virtual void setColor(CvScalar color) {
mColor = color;
}
virtual CvScalar getColor(void) {
return mColor;
}
protected:
CvScalar mColor;
};
}}}; | [
"jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
]
| [
[
[
1,
28
]
]
]
|
3757272669e627512d282b36db9f6a1dd0635a4f | 89d2197ed4531892f005d7ee3804774202b1cb8d | /GWEN/src/Controls/TreeControl.cpp | 29e11c1164130192304fd17f2bbc55d90746f5e4 | [
"MIT",
"Zlib"
]
| permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "stdafx.h"
#include "Gwen/Controls/TreeControl.h"
#include "Gwen/Controls/ScrollControl.h"
#include "Gwen/Utility.h"
using namespace Gwen;
using namespace Gwen::Controls;
GWEN_CONTROL_CONSTRUCTOR( TreeControl )
{
m_TreeControl = this;
m_ToggleButton->DelayedDelete();
m_ToggleButton = NULL;
m_Title->DelayedDelete();
m_Title = NULL;
m_InnerPanel->DelayedDelete();
m_InnerPanel = NULL;
m_bAllowMultipleSelection = false;
m_ScrollControl = new ScrollControl( this );
m_ScrollControl->Dock( Pos::Fill );
m_ScrollControl->SetScroll( false, true );
m_ScrollControl->SetAutoHideBars( true );
m_ScrollControl->SetMargin( Margin( 1, 1, 1, 1 ) );
m_InnerPanel = m_ScrollControl;
m_ScrollControl->SetInnerSize( 1000, 1000 );
}
void TreeControl::Render( Skin::Base* skin )
{
if ( ShouldDrawBackground() )
skin->DrawTreeControl( this );
}
void TreeControl::OnChildBoundsChanged( Rect oldChildBounds, Base* pChild )
{
m_ScrollControl->UpdateScrollBars();
}
void TreeControl::Clear()
{
m_ScrollControl->Clear();
}
void TreeControl::Layout( Skin::Base* skin )
{
BaseClass::BaseClass::Layout( skin );
}
void TreeControl::PostLayout( Skin::Base* skin )
{
BaseClass::BaseClass::PostLayout( skin );
}
void TreeControl::OnNodeAdded( TreeNode* pNode )
{
pNode->onNamePress.Add( this, &TreeControl::OnNodeSelection );
}
void TreeControl::OnNodeSelection( Controls::Base* control )
{
if ( !m_bAllowMultipleSelection || !Gwen::Input::IsKeyDown( Key::Control ) )
DeselectAll();
} | [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
]
| [
[
[
1,
74
]
]
]
|
5fda4aa33a2465cb9e79a4c5e7b24df9e2def059 | 2fd3cf69d422c2e62db908a5f6ec85890cc12f80 | /ID_Win.h | 7ab74f12d04ac95a86db5b5cfcc00a42a4b75a2a | []
| no_license | ksherlock/BShisen | 24ec5fb05c8bda250a1090ec32f7dc6f3df7c036 | f5f9db386d847ea3f26a1116ff465676290b3aa9 | refs/heads/master | 2016-09-06T01:37:57.086749 | 2010-06-10T02:18:14 | 2010-06-10T02:18:14 | 18,947,831 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | #ifndef __ID_WIN_H__
#define __ID_WIN_H__
#include <Window.h>
#include <Button.h>
#include <TextControl.h>
#include <OS.h>
enum { ACCEPT_BUTTON = 0x5000, CANCEL_BUTTON };
class ID_Win: public BWindow
{
public:
ID_Win(BLooper *, unsigned int);
//unsigned int Go(unsigned int);
~ID_Win();
virtual void MessageReceived(BMessage *);
virtual bool QuitRequested(void);
private:
BTextControl *Txt_Ctl;
int done;
unsigned int Game;
BLooper *loop;
//port_id Port;
};
#endif
| [
"(no author)@5590a31f-7b70-45f8-8c82-aa3a8e5f4507"
]
| [
[
[
1,
30
]
]
]
|
cd3f550c34126794a4d1c0ed8ed6ae8da9440d00 | 68bfdfc18f1345d1ff394b8115681110644d5794 | /Examples/Example01/Jpeg.cpp | 1711a1a32815b11a935e03128eabb43680df7bfc | []
| no_license | y-gupta/glwar3 | 43afa1efe475d937ce0439464b165c745e1ec4b1 | bea5135bd13f9791b276b66490db76d866696f9a | refs/heads/master | 2021-05-28T12:20:41.532727 | 2010-12-09T07:52:12 | 2010-12-09T07:52:12 | 32,911,819 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,548 | cpp | //+-----------------------------------------------------------------------------
//| Included files
//+-----------------------------------------------------------------------------
#include "Jpeg.h"
//+-----------------------------------------------------------------------------
//| Global objects
//+-----------------------------------------------------------------------------
JPEG Jpeg;
//+-----------------------------------------------------------------------------
//| Constructor
//+-----------------------------------------------------------------------------
JPEG::JPEG()
{
//Empty
}
//+-----------------------------------------------------------------------------
//| Destructor
//+-----------------------------------------------------------------------------
JPEG::~JPEG()
{
//Empty
}
//+-----------------------------------------------------------------------------
//| Writes JPEG data
//+-----------------------------------------------------------------------------
BOOL JPEG::Write(CONST BUFFER& SourceBuffer, BUFFER& TargetBuffer, INT Width, INT Height, INT Quality)
{
INT Stride;
INT RealSize;
INT DummySize;
BUFFER TempBuffer;
JSAMPROW Pointer[1];
jpeg_compress_struct Info;
jpeg_error_mgr ErrorManager;
Info.err = jpeg_std_error(&ErrorManager);
DummySize = ((Width * Height * 4) * 2) + 10000;
TempBuffer.Resize(DummySize);
jpeg_create_compress(&Info);
SetMemoryDestination(&Info, reinterpret_cast<UCHAR*>(TempBuffer.GetData()), TempBuffer.GetSize());
Info.image_width = Width;
Info.image_height = Height;
Info.input_components = 4;
Info.in_color_space = JCS_UNKNOWN;
jpeg_set_defaults(&Info);
jpeg_set_quality(&Info, Quality, TRUE);
jpeg_start_compress(&Info, TRUE);
Stride = Width * 4;
while(Info.next_scanline < Info.image_height)
{
Pointer[0] = reinterpret_cast<JSAMPROW>(&SourceBuffer[Info.next_scanline * Stride]);
jpeg_write_scanlines(&Info, Pointer, 1);
}
jpeg_finish_compress(&Info);
RealSize = DummySize - static_cast<INT>(Info.dest->free_in_buffer);
TargetBuffer.Resize(RealSize);
std::memcpy(&TargetBuffer[0], &TempBuffer[0], RealSize);
jpeg_destroy_compress(&Info);
return TRUE;
}
//+-----------------------------------------------------------------------------
//| Reads JPEG data
//+-----------------------------------------------------------------------------
BOOL JPEG::Read(CONST BUFFER& SourceBuffer, BUFFER& TargetBuffer, INT* Width, INT* Height)
{
INT i;
INT Stride;
INT Offset;
CHAR Opaque;
JSAMPARRAY Pointer;
jpeg_decompress_struct Info;
jpeg_error_mgr ErrorManager;
Info.err = jpeg_std_error(&ErrorManager);
jpeg_create_decompress(&Info);
SetMemorySource(&Info, reinterpret_cast<UCHAR*>(SourceBuffer.GetData()), SourceBuffer.GetSize());
jpeg_read_header(&Info, TRUE);
jpeg_start_decompress(&Info);
if((Info.output_components != 3) && (Info.output_components != 4))
{
Error.SetMessage("Nr of channels must be 3 or 4!");
return FALSE;
}
TargetBuffer.Resize(Info.output_width * Info.output_height * 4);
Stride = Info.output_width * Info.output_components;
Offset = 0;
Pointer = (*Info.mem->alloc_sarray)(reinterpret_cast<j_common_ptr>(&Info), JPOOL_IMAGE, Stride, 1);
while(Info.output_scanline < Info.output_height)
{
jpeg_read_scanlines(&Info, Pointer, 1);
std::memcpy(&TargetBuffer[Offset], Pointer[0], Stride);
Offset += Stride;
}
jpeg_finish_decompress(&Info);
(*reinterpret_cast<BYTE*>(&Opaque)) = 255;
if(Info.output_components == 3)
{
for(i = (Info.output_width * Info.output_height - 1); i >= 0; i--)
{
TargetBuffer[(i * 4) + 3] = Opaque;
TargetBuffer[(i * 4) + 2] = TargetBuffer[(i * 3) + 2];
TargetBuffer[(i * 4) + 1] = TargetBuffer[(i * 3) + 1];
TargetBuffer[(i * 4) + 0] = TargetBuffer[(i * 3) + 0];
}
}
if(Width != NULL) (*Width) = Info.output_width;
if(Height != NULL) (*Height) = Info.output_height;
jpeg_destroy_decompress(&Info);
return TRUE;
}
//+-----------------------------------------------------------------------------
//| Sets the memory source
//+-----------------------------------------------------------------------------
VOID JPEG::SetMemorySource(jpeg_decompress_struct* Info, UCHAR* Buffer, ULONG Size)
{
JPEG_SOURCE_MANAGER* SourceManager;
Info->src = reinterpret_cast<jpeg_source_mgr*>((*Info->mem->alloc_small)(reinterpret_cast<j_common_ptr>(Info), JPOOL_PERMANENT, sizeof(JPEG_SOURCE_MANAGER)));
SourceManager = reinterpret_cast<JPEG_SOURCE_MANAGER*>(Info->src);
SourceManager->Buffer = reinterpret_cast<JOCTET*>((*Info->mem->alloc_small)(reinterpret_cast<j_common_ptr>(Info), JPOOL_PERMANENT, Size * sizeof(JOCTET)));
SourceManager->SourceBuffer = Buffer;
SourceManager->SourceBufferSize = Size;
SourceManager->Manager.init_source = SourceInit;
SourceManager->Manager.fill_input_buffer = SourceFill;
SourceManager->Manager.skip_input_data = SourceSkip;
SourceManager->Manager.resync_to_restart = jpeg_resync_to_restart;
SourceManager->Manager.term_source = SourceTerminate;
SourceManager->Manager.bytes_in_buffer = 0;
SourceManager->Manager.next_input_byte = NULL;
}
//+-----------------------------------------------------------------------------
//| Sets the memory destination
//+-----------------------------------------------------------------------------
VOID JPEG::SetMemoryDestination(jpeg_compress_struct* Info, UCHAR* Buffer, ULONG Size)
{
JPEG_DESTINATION_MANAGER* DestinationManager;
Info->dest = reinterpret_cast<jpeg_destination_mgr*>((*Info->mem->alloc_small)(reinterpret_cast<j_common_ptr>(Info), JPOOL_PERMANENT, sizeof(JPEG_DESTINATION_MANAGER)));
DestinationManager = reinterpret_cast<JPEG_DESTINATION_MANAGER*>(Info->dest);
DestinationManager->Buffer = NULL;
DestinationManager->DestinationBuffer = Buffer;
DestinationManager->DestinationBufferSize = Size;
DestinationManager->Manager.init_destination = DestinationInit;
DestinationManager->Manager.empty_output_buffer = DestinationEmpty;
DestinationManager->Manager.term_destination = DestinationTerminate;
}
//+-----------------------------------------------------------------------------
//| Initiates the memory source
//+-----------------------------------------------------------------------------
VOID JPEG::SourceInit(jpeg_decompress_struct* Info)
{
//Empty
}
//+-----------------------------------------------------------------------------
//| Fills the memory source
//+-----------------------------------------------------------------------------
BOOLEAN JPEG::SourceFill(jpeg_decompress_struct* Info)
{
JPEG_SOURCE_MANAGER* SourceManager;
SourceManager = reinterpret_cast<JPEG_SOURCE_MANAGER*>(Info->src);
SourceManager->Buffer = SourceManager->SourceBuffer;
SourceManager->Manager.next_input_byte = SourceManager->Buffer;
SourceManager->Manager.bytes_in_buffer = SourceManager->SourceBufferSize;
return TRUE;
}
//+-----------------------------------------------------------------------------
//| Skips the memory source
//+-----------------------------------------------------------------------------
VOID JPEG::SourceSkip(jpeg_decompress_struct* Info, LONG NrOfBytes)
{
JPEG_SOURCE_MANAGER* SourceManager;
SourceManager = reinterpret_cast<JPEG_SOURCE_MANAGER*>(Info->src);
if(NrOfBytes > 0)
{
while(NrOfBytes > static_cast<LONG>(SourceManager->Manager.bytes_in_buffer))
{
NrOfBytes -= static_cast<LONG>(SourceManager->Manager.bytes_in_buffer);
SourceFill(Info);
}
SourceManager->Manager.next_input_byte += NrOfBytes;
SourceManager->Manager.bytes_in_buffer -= NrOfBytes;
}
}
//+-----------------------------------------------------------------------------
//| Terminates the memory source
//+-----------------------------------------------------------------------------
VOID JPEG::SourceTerminate(jpeg_decompress_struct* Info)
{
//Empty
}
//+-----------------------------------------------------------------------------
//| Initiates the memory destination
//+-----------------------------------------------------------------------------
VOID JPEG::DestinationInit(jpeg_compress_struct* Info)
{
JPEG_DESTINATION_MANAGER* DestinationManager;
DestinationManager = reinterpret_cast<JPEG_DESTINATION_MANAGER*>(Info->dest);
DestinationManager->Buffer = DestinationManager->DestinationBuffer;
DestinationManager->Manager.next_output_byte = DestinationManager->Buffer;
DestinationManager->Manager.free_in_buffer = DestinationManager->DestinationBufferSize;
}
//+-----------------------------------------------------------------------------
//| Empties the memory destination
//+-----------------------------------------------------------------------------
BOOLEAN JPEG::DestinationEmpty(jpeg_compress_struct* Info)
{
JPEG_DESTINATION_MANAGER* DestinationManager;
DestinationManager = reinterpret_cast<JPEG_DESTINATION_MANAGER*>(Info->dest);
DestinationManager->Manager.next_output_byte = DestinationManager->Buffer;
DestinationManager->Manager.free_in_buffer = DestinationManager->DestinationBufferSize;
return TRUE;
}
//+-----------------------------------------------------------------------------
//| Terminates the memory destination
//+-----------------------------------------------------------------------------
VOID JPEG::DestinationTerminate(jpeg_compress_struct* Info)
{
//Empty
}
| [
"sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83"
]
| [
[
[
1,
281
]
]
]
|
2cfaece2dd9dcec0676cd60e9da855fc7613b244 | 4cfa1921fdde92141c413ee7622b66379736494c | /objects/keyboard.h | f5bb49beaa4671ebacae2219b50b0ec767c6bea4 | []
| no_license | dragonshx/gps-sdr | aca4341650ba4a8f8ca046a1217410807a029032 | 1d31fcad1479b0d047c6dac7464b19e6189097fa | refs/heads/master | 2021-01-18T05:52:58.837305 | 2009-01-08T22:13:26 | 2009-01-08T22:13:26 | 119,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | h | /*! \file Keyboard.h
Defines the class Keyboard
*/
/************************************************************************************************
Copyright 2008 Gregory W Heckler
This file is part of the GPS Software Defined Radio (GPS-SDR)
The GPS-SDR 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.
The GPS-SDR 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 GPS-SDR; if not,
write to the:
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
************************************************************************************************/
#ifndef KEYBOARD_H_
#define KEYBOARD_H_
#include "includes.h"
/*! \ingroup CLASSES
*
*/
class Keyboard : public Threaded_Object
{
private:
public:
Keyboard();
~Keyboard();
void Start(); //!< Start the thread
void Import(); //!< Get data into the thread
void Export(); //!< Get data out of the thread
};
#endif /* Keyboard_H */
| [
"gheckler@core2duo.(none)",
"gheckler@gs-mesa3079963w.(none)"
]
| [
[
[
1,
17
],
[
19,
22
],
[
25,
28
],
[
30,
30
],
[
32,
40
],
[
44,
47
]
],
[
[
18,
18
],
[
23,
24
],
[
29,
29
],
[
31,
31
],
[
41,
43
]
]
]
|
644a5c6f1a96baaf15df3a58c6304b7372aed198 | 10c14a95421b63a71c7c99adf73e305608c391bf | /GradientComboBox/GradientComboBoxPpg.cpp | c0645be61f8a3058f96d508e462560eed3cdb501 | []
| no_license | eaglezzb/wtlcontrols | 73fccea541c6ef1f6db5600f5f7349f5c5236daa | 61b7fce28df1efe4a1d90c0678ec863b1fd7c81c | refs/heads/master | 2021-01-22T13:47:19.456110 | 2009-05-19T10:58:42 | 2009-05-19T10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,632 | cpp | // GradientComboBoxPpg.cpp : Implementation of the CGradientComboBoxPropPage property page class.
#include "stdafx.h"
#include "GradientComboBox.h"
#include "GradientComboBoxPpg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGradientComboBoxPropPage, COlePropertyPage)
/////////////////////////////////////////////////////////////////////////////
// Message map
BEGIN_MESSAGE_MAP(CGradientComboBoxPropPage, COlePropertyPage)
//{{AFX_MSG_MAP(CGradientComboBoxPropPage)
// NOTE - ClassWizard will add and remove message map entries
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid
IMPLEMENT_OLECREATE_EX(CGradientComboBoxPropPage, "GRADIENTCOMBOBOX.GradientComboBoxPropPage.1",
0x1fe71c3, 0x6a9f, 0x41f8, 0x9c, 0xbd, 0x30, 0x41, 0x33, 0xda, 0x63, 0xfd)
/////////////////////////////////////////////////////////////////////////////
// CGradientComboBoxPropPage::CGradientComboBoxPropPageFactory::UpdateRegistry -
// Adds or removes system registry entries for CGradientComboBoxPropPage
BOOL CGradientComboBoxPropPage::CGradientComboBoxPropPageFactory::UpdateRegistry(BOOL bRegister)
{
if (bRegister)
return AfxOleRegisterPropertyPageClass(AfxGetInstanceHandle(),
m_clsid, IDS_GRADIENTCOMBOBOX_PPG);
else
return AfxOleUnregisterClass(m_clsid, NULL);
}
/////////////////////////////////////////////////////////////////////////////
// CGradientComboBoxPropPage::CGradientComboBoxPropPage - Constructor
CGradientComboBoxPropPage::CGradientComboBoxPropPage() :
COlePropertyPage(IDD, IDS_GRADIENTCOMBOBOX_PPG_CAPTION)
{
//{{AFX_DATA_INIT(CGradientComboBoxPropPage)
// NOTE: ClassWizard will add member initialization here
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_DATA_INIT
}
/////////////////////////////////////////////////////////////////////////////
// CGradientComboBoxPropPage::DoDataExchange - Moves data between page and properties
void CGradientComboBoxPropPage::DoDataExchange(CDataExchange* pDX)
{
//{{AFX_DATA_MAP(CGradientComboBoxPropPage)
// NOTE: ClassWizard will add DDP, DDX, and DDV calls here
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_DATA_MAP
DDP_PostProcessing(pDX);
}
/////////////////////////////////////////////////////////////////////////////
// CGradientComboBoxPropPage message handlers
| [
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
]
| [
[
[
1,
76
]
]
]
|
7018849525e5492f6ec39a15797ff98b6f706de4 | b7b58c5e83ae0e868414e8a6900b92fcfa87b4b1 | /Tools/Adisasm/AdisasM.h | b32c91e33390179399d10084ff5952a6d9469a27 | []
| no_license | dailongao/cheat-fusion | 87df8bd58845f30808600b72167ff6c778a36245 | ab7cd0fe56df0edabb9064da70b93a2856df7fac | refs/heads/master | 2021-01-10T12:42:37.958692 | 2010-12-31T13:42:51 | 2010-12-31T13:42:51 | 51,513,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,462 | h | typedef unsigned long word;
typedef unsigned short uhword;
typedef unsigned char ubyte;
typedef signed long sword;
typedef signed short shword;
typedef signed char sbyte;
#include "mipscrap.h"
struct CPsxHeader
{
char ID[8];
word Pad1[2];
word JumpAddress;
word Pad2;
word LoadAddress;
word TextLength;
char Pad3[16];
word StackAddress;
char Pad4[61];
char Territory;
char Pad5[1934];
};
#define IF_CODE 0x8000 // reachable code that is, except if the 'consider unreachable code'-option is specified
#define IFC_LABEL 0x0001 // target of normal branch
#define IFC_TERM 0x0002 // terminator: delay slot of J(r), but not jr ra
#define IFC_PROC 0x4000 // procedure body, if set:
#define IFP_BEGIN 0x2000
#define IFP_END 0x1000
#define IFC_LOOP 0x0800 // body of loop
#define IFL_BEGIN 0x0400
#define IFL_END 0x0200
#define IFC_BRANCH 0x0080 // any kind of branching
#define IFB_VAR 0x0040 // j(al)r, but not jr ra
#define IFB_LINK 0x0020
#define IFB_UNCOND 0x0010
#define IF_DATA 0x0000 // data
// the IFD_ defines are only guesses (as far as a program can take a guess)
#define IFD_UNKNOWN 0x0000 // i don't know ! :-/
#define IFD_ADDRESS 0x0002 // probably an address (ie. a pointer)
#define IFD_STRING 0x0004 // string
struct CCodeLine
{
uhword flag; // see IFx_ constants above
word instruction; // index in our pool o' strings if flag&IFD_STRING
CCodeLine() { memset(this,0,sizeof(*this)); }
};
class CCrossRefTbl
{
public:
void addRef(word target, word src);
void printAllRefs(FILE* f);
private:
};
#define ST_PROC_EP 1
#define ST_LABEL 2
#define ST_MEM_VAR 3
typedef map<word, string> SYMTBL;
class CPsxExe;
class CSymbolTbl
{
public:
CSymbolTbl() {inited=false;}
void addSym(word val, string name, ubyte type);
bool lookup(word val, string& name);
void load(FILE* f);
void psyLoad(FILE* f);
void markCode(CPsxExe* exe);
private:
SYMTBL symbols;
void handlePsySym8a(FILE* f);
bool inited;
};
#define INIT_STRINGS 40
#define MAX_STRINGLENGTH 255
class CPsxExe
{
public:
friend CSymbolTbl;
CPsxExe();
bool doCmdLine(int argc, char* argv[]);
virtual ~CPsxExe();
word loadAddress;
word entryPoint;
word codeLength;
void loadLines(word* lines);
void loadExe(char* name);
void loadSymTbl(char* name);
bool isValidInstruction(word d, word pc);
void decodeInstruction(word d, word pc);
void disassemble(char *name, word from, word to);
void disassemble(char *name);
word extractASCIIZStr(word start, word end, char* buffer);
// options:
static bool optVerbose;
static bool optForceBin; // always handle as binary file
static bool optForceMachCode; // display the codeword
static bool optDumbString; // <sniff> don't try to extract a string.. just be dumb
static bool optConsiderUnreachableCode; // also disasm code (that seems) unreachable
static bool optResourceC; // high level disasm
static word optLoadAddress;
static word optCodeLength;
static word optJumpAddress;
private:
CCodeLine* lines;
CCrossRefTbl crossRef;
CSymbolTbl syms;
char strings[INIT_STRINGS][MAX_STRINGLENGTH]; // swimming pool for our ladies wearing nothing but strings #-D
word nextFreeString; // next chick in our pool
}; | [
"forbbsneo@1e91e87a-c719-11dd-86c2-0f8696b7b6f9"
]
| [
[
[
1,
134
]
]
]
|
26bef4b5335787da8980c827e089132415a5823d | 965bcb2cd3d377b03840ae3899bc1243d2b6203d | /engineTest/engineTest/canEntity.cpp | 4ec3b0fa76d426d5e04888fefba8d6f471b3247d | []
| no_license | VirtuosoChris/gameaiproject1 | 42cd6245a824e2a5c09384b1f756a31b4ec904e7 | 789a6a420559bf32e15fa56db64c7c063df668e7 | refs/heads/master | 2020-06-01T19:00:15.998072 | 2009-04-19T19:25:29 | 2009-04-19T19:25:29 | 32,121,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,718 | cpp | #include "canEntity.h"
using namespace irr;
using namespace irr::core;
#include <iostream>
canEntity::canEntity(IrrlichtDevice *device){
irr::scene::ISceneManager* smgr = device->getSceneManager();
video::IVideoDriver* driver = device->getVideoDriver();
cannode = smgr->addSphereSceneNode(25,128);
//cannode->setScale(irr::core::vector3df(5,5,5));
//CPTODO::replace constant with something better
cannode->setPosition(irr::core::vector3df(107,30,93));
this->setPosition(cannode->getPosition());
cannode->setMaterialFlag(irr::video::EMF_LIGHTING, true);
cannode->setMaterialTexture(0,driver->getTexture("../media/skydome.jpg"));
cannode->setMaterialType(irr::video::EMT_SPHERE_MAP);
irr::scene::ILightSceneNode *lightscenenode = smgr->addLightSceneNode(0, irr::core::vector3df(25,25,25), irr::video::SColor(255, 255, 0, 0),500);
irr::scene::ILightSceneNode *lightscenenode2 = smgr->addLightSceneNode(0, irr::core::vector3df(-25,-25,-25), irr::video::SColor(255, 255, 0, 0),500);
cannode->addChild(lightscenenode);
cannode->addChild(lightscenenode2);
const double startAngle = 0;
const double endAngle = 2*3.14159;
const double nodeCount =12.0f;
const double radius = 45.0f;
double increment = (startAngle - endAngle) / nodeCount;
for(int i = 0; i < nodeCount; i++){
double currentAngle = endAngle + increment*i;
irr::scene::ISceneNode* a = smgr->addSphereSceneNode(5,16);
a->setPosition(radius*vector3df( cos(currentAngle) ,sin(currentAngle),0 ));
this->getSceneNode()->addChild(a);
a->setMaterialTexture(0,driver->getTexture("../media/skydome.jpg"));
a->setMaterialType(video::EMT_SPHERE_MAP);
}
for(int i = 0; i < nodeCount; i++){
double currentAngle = endAngle + increment*i;
irr::scene::ISceneNode* a = smgr->addSphereSceneNode(3,16);
a->setPosition(30*vector3df( 0,cos(currentAngle) ,sin(currentAngle) ));
this->getSceneNode()->addChild(a);
a->setMaterialTexture(0,driver->getTexture("../media/skydome.jpg"));
//a->setMaterialType(video::EMT_SPHERE_MAP);
}
}
void canEntity::update(const irr::ITimer* timer){
static double LASTUPDATE = timer->getTime();
double timeelapsed = timer->getTime() - LASTUPDATE;
this->velocity = (cannode->getPosition() - this->position) / timeelapsed;
//std::cout<<"SPEED"<<this->velocity.getLength()<<std::endl;
this->setPosition(cannode->getPosition());
cannode->setPosition(vector3df(107.0f,30.0f,93.0f) + 2.0f*(float)sin((double)timer->getTime()/500)*vector3df(0,1,0));
LASTUPDATE = timer->getTime();
mynodep->setRotation(vector3df(0,1,0)*timer->getTime()/3);
}
bool canEntity::processMessage(const Message* m){
return true;
} | [
"ChrisPugh666@be266342-eca9-11dd-a550-c997509ed985",
"javidscool@be266342-eca9-11dd-a550-c997509ed985"
]
| [
[
[
1,
6
],
[
8,
9
],
[
13,
13
],
[
25,
26
],
[
33,
71
],
[
74,
74
]
],
[
[
7,
7
],
[
10,
12
],
[
14,
24
],
[
27,
32
],
[
72,
73
]
]
]
|
1018f8b45665360f458fcd0fa0495103da9cdc1f | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_20090206_代码统计专用文件夹/C++Primer中文版(第4版)/第五章 表达式/20090121_习题5.22_每种内置类型的长度.cpp | 2e611471edaf3182bcd7964015aaf5bc5c72af03 | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,023 | cpp | //输出每种内置类型的长度
#include <iostream>
using namespace std;
int main()
{
cout << "type\t\t\t" << "size" << endl
<< "bool\t\t\t" << sizeof(bool) << endl
<< "char\t\t\t" << sizeof(char) << endl
<< "signed char\t\t" << sizeof(signed char) << endl
<< "unsigned char\t\t" << sizeof(unsigned char) <<endl
<< "wchar_t\t\t\t" << sizeof(wchar_t) << endl
<< "short\t\t\t" << sizeof(short) << endl
<< "signed short\t\t" << sizeof(signed short) << endl
<< "unsigned short\t\t" << sizeof(unsigned short) << endl
<< "int\t\t\t" << sizeof(int) << endl
<< "signed int\t\t" << sizeof(signed int) << endl
<< "unsigned int \t\t" << sizeof(unsigned int) << endl
<< "long\t\t\t" << sizeof(long) << endl
<< "signed long\t\t" << sizeof(signed long) << endl
<< "unsigned long\t\t" << sizeof(unsigned long) << endl
<< "float\t\t\t" << sizeof(float) << endl
<< "double\t\t\t" << sizeof(double) << endl
<< "long double\t\t" << sizeof(long double) << endl;
return 0;
}
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
27
]
]
]
|
29250745796b7c456cb04d7887286a5252a1abb6 | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/zNotepad/ZFileDlg.h | 6dd7e14450b20ca828ce2cc046908b513378feb3 | []
| 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 | 1,526 | h | //
// C++ Interface: ZFileDlg
//
// Description:
//
//
// Author: root <root@andLinux>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef ZFILEDLG_H
#define ZFILEDLG_H
#include "BaseDlg.h"
#include <ZMultiLineEdit.h>
#include <ZMessageDlg.h>
#include <ZOptionsMenu.h>
#include <ZKbMainWidget.h>
#include <ZListBox.h>
#include <ZPressButton.h>
#include <ZCheckBox.h>
class ZMyCheckBox : public ZCheckBox {
Q_OBJECT
public:
ZMyCheckBox( const QString & text, QWidget * parent, const char* name = 0, bool value = false);
~ZMyCheckBox();
QString ParamName;
QString ParamGroup;
bool GetChecked() const;
public slots:
void SetChecked(bool state);
private:
bool curState;
};
class ZSearch : public MyBaseDlg {
Q_OBJECT
public:
ZSearch(int nota);
~ZSearch();
QString texto;
ZMyCheckBox *marcado;
public slots:
void slot_cancel();
void slot_save();
void checktext();
private:
ZListBox* browser;
ZMultiLineEdit* lineEdit;
ZSoftKey *softKey;
ZOptionsMenu * menu1;
protected:
//virtual void keyPressEvent(QKeyEvent* e);
};
class ZView : public MyBaseDlg {
Q_OBJECT
public:
ZView(int nota);
~ZView();
ZLabel* lineEdit;
ZLabel* lineM2;
public slots:
void slot_edit();
void slot_delete();
void slot_send();
private:
ZSoftKey *softKey;
ZOptionsMenu * menu1;
protected:
//virtual void keyPressEvent(QKeyEvent* e);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
94
]
]
]
|
718c1b2a74ff7c765a60c6975824ee73e1c3c3ef | 617426f05b3b0914930b05c668a1d9de3d541466 | /goruntu-aktarimi/HidCom64bit/HidMapperCOM/HidManager/HidManagerModule.cpp | 22a6c8aca78597a4b5a9c5ba9819fb2b93b9db2f | []
| no_license | jasongaoks/screenswitcher | 19048183ff320c5bca607924ceb5830b83c0166d | bde18199221c8b57bc42efd63514a7f5e513161b | refs/heads/master | 2020-03-26T19:57:04.517600 | 2008-07-12T08:07:40 | 2008-07-12T08:07:40 | null | 0 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 3,302 | cpp | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, Intel Corporation. All Rights Reserved. //
// //
// Portions used from the MSDN are Copyright (c) Microsoft Corporation. //
// //
// INTEL CORPORATION PROPRIETARY INFORMATION //
// //
// The source code contained or described herein and all documents related to //
// the source code (Material) are owned by Intel Corporation or its suppliers //
// or licensors. Title to the Material remains with Intel Corporation or its //
// suppliers and licensors. The Material contains trade secrets and //
// proprietary and confidential information of Intel or its suppliers and //
// licensors. The Material is protected by worldwide copyright and trade //
// secret laws and treaty provisions. No part of the Material may be used, //
// copied, reproduced, modified, published, uploaded, posted, transmitted, //
// distributed, or disclosed in any way without Intelís prior express written //
// permission. //
// //
// No license under any patent, copyright, trade secret or other intellectual //
// property right is granted to or conferred upon you by disclosure or //
// delivery of the Materials, either expressly, by implication, inducement, //
// estoppel or otherwise. Any license under such intellectual property rights //
// must be express and approved by Intel in writing. //
// //
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY //
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE //
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR //
// PURPOSE. //
// //
////////////////////////////////////////////////////////////////////////////////
//
// $Archive: /Lorado/HidMapperCOM/HidManager/HidManagerModule.cpp $
//
// $Author: Nmnguye1 $
//
// $Date: 2/27/08 12:19p $
//
////////////////////////////////////////////////////////////////////////////////
//
// HidManagerModule.cpp : Declaration of the HidManager COM DLL module.
//
#include "stdafx.h"
#include "resource.h"
// The module attribute causes DllMain, DllRegisterServer and DllUnregisterServer to be automatically implemented for you.
[ module(dll,
name = "HidManager",
version = "1.0",
uuid = "{17A600B7-4DD1-4d8d-BAF8-E4FFC592B999}",
helpstring = "HidManager 1.0.0.4 Type Library"
// resource_name = "IDR_HIDMANAGER"
) ]
class CHidManagerModule
{
public:
// Override CAtlDllModuleT members
};
| [
"comp.ogz@0e33d388-c051-0410-92da-0324861a6c34"
]
| [
[
[
1,
60
]
]
]
|
6b1dbccf3686674673ecf3fc022454f5f7ea5c6e | 6581dacb25182f7f5d7afb39975dc622914defc7 | /EDStock/GridCellBase.cpp | ffa7b0aafcf62f99f9a79b6a0e5c5296cd019ed5 | []
| 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 | WINDOWS-1252 | C++ | false | false | 26,935 | cpp | // GridCellBase.cpp : implementation file
//
// MFC Grid Control - Main grid cell base class
//
// Provides the implementation for the base cell type of the
// grid control. No data is stored (except for state) but default
// implementations of drawing, printingetc provided. MUST be derived
// from to be used.
//
// Written by Chris Maunder <[email protected]>
// Copyright (c) 1998-2005. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.22+
//
// History:
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// C Maunder - 19 May 2000 - Fixed sort arrow drawing (Ivan Ilinov)
// C Maunder - 29 Aug 2000 - operator= checks for NULL font before setting (Martin Richter)
// C Maunder - 15 Oct 2000 - GetTextExtent fixed (Martin Richter)
// C Maunder - 1 Jan 2001 - Added ValidateEdit
// Yogurt - 13 Mar 2004 - GetCellExtent fixed
//
// NOTES: Each grid cell should take care of it's own drawing, though the Draw()
// method takes an "erase background" paramter that is called if the grid
// decides to draw the entire grid background in on hit. Certain ambient
// properties such as the default font to use, and hints on how to draw
// fixed cells should be fetched from the parent grid. The grid trusts the
// cells will behave in a certain way, and the cells trust the grid will
// supply accurate information.
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCtrl.h"
#include "GridCellBase.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNAMIC(CGridCellBase, CObject)
/////////////////////////////////////////////////////////////////////////////
// GridCellBase
CGridCellBase::CGridCellBase()
{
Reset();
}
CGridCellBase::~CGridCellBase()
{
}
/////////////////////////////////////////////////////////////////////////////
// GridCellBase Operations
void CGridCellBase::Reset()
{
m_nState = 0;
}
void CGridCellBase::operator=(const CGridCellBase& cell)
{
if (this == &cell) return;
SetGrid(cell.GetGrid()); // do first in case of dependencies
SetText(cell.GetText());
SetImage(cell.GetImage());
SetData(cell.GetData());
SetState(cell.GetState());
SetFormat(cell.GetFormat());
SetTextClr(cell.GetTextClr());
SetBackClr(cell.GetBackClr());
SetFont(cell.IsDefaultFont()? NULL : cell.GetFont());
SetMargin(cell.GetMargin());
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Attributes
// Returns a pointer to a cell that holds default values for this particular type of cell
CGridCellBase* CGridCellBase::GetDefaultCell() const
{
if (GetGrid())
return GetGrid()->GetDefaultCell(IsFixedRow(), IsFixedCol());
return NULL;
}
void CGridCellBase::RemoveSortSign()
{
CString strTitle = GetText();
CString s = strTitle.Right(2);
if(s == "¡ü" || s == "¡ý")
{
strTitle = strTitle.Left(strTitle.GetLength()-2);
}
SetText(strTitle);
}
void CGridCellBase::SetSortSign()
{
CString strTitle = GetText();
CString strSortSign;
if (GetGrid()->GetSortAscending())
strSortSign = "¡ü";
else
strSortSign = "¡ý";
strTitle = strTitle + strSortSign;
SetText(strTitle);
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Operations
// EFW - Various changes to make it draw cells better when using alternate
// color schemes. Also removed printing references as that's now done
// by PrintCell() and fixed the sort marker so that it doesn't draw out
// of bounds.
BOOL CGridCellBase::Draw(CDC* pDC, int nRow, int nCol, CRect rect, BOOL bEraseBkgnd /*=TRUE*/)
{
// Note - all through this function we totally brutalise 'rect'. Do not
// depend on it's value being that which was passed in.
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
if (!pGrid || !pDC)
return FALSE;
if( rect.Width() <= 0 || rect.Height() <= 0) // prevents imagelist item from drawing even
return FALSE; // though cell is hidden
//TRACE3("Drawing %scell %d, %d\n", IsFixed()? _T("Fixed ") : _T(""), nRow, nCol);
int nSavedDC = pDC->SaveDC();
pDC->SetBkMode(TRANSPARENT);
// Get the default cell implementation for this kind of cell. We use it if this cell
// has anything marked as "default"
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return FALSE;
// Set up text and background colours
COLORREF TextClr, TextBkClr;
TextClr = (GetTextClr() == CLR_DEFAULT)? pDefaultCell->GetTextClr() : GetTextClr();
if (GetBackClr() == CLR_DEFAULT)
TextBkClr = pDefaultCell->GetBackClr();
else
{
bEraseBkgnd = TRUE;
TextBkClr = GetBackClr();
}
// Draw cell background and highlighting (if necessary)
if ( IsFocused() || IsDropHighlighted() )
{
// Always draw even in list mode so that we can tell where the
// cursor is at. Use the highlight colors though.
if(GetState() & GVIS_SELECTED)
{
TextBkClr = pDefaultCell->GetSelectedBkClr();
TextClr = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
bEraseBkgnd = TRUE;
}
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
if (bEraseBkgnd)
{
TRY
{
CBrush brush(TextBkClr);
pDC->FillRect(rect, &brush);
}
CATCH(CResourceException, e)
{
//e->ReportError();
}
END_CATCH
}
// Don't adjust frame rect if no grid lines so that the
// whole cell is enclosed.
if(pGrid->GetGridLines() != GVL_NONE)
{
rect.right--;
rect.bottom--;
}
if (pGrid->GetFrameFocusCell())
{
// Use same color as text to outline the cell so that it shows
// up if the background is black.
TRY
{
CBrush brush(TextClr);
pDC->FrameRect(rect, &brush);
}
CATCH(CResourceException, e)
{
//e->ReportError();
}
END_CATCH
}
pDC->SetTextColor(TextClr);
// Adjust rect after frame draw if no grid lines
if(pGrid->GetGridLines() == GVL_NONE)
{
rect.right--;
rect.bottom--;
}
//rect.DeflateRect(0,1,1,1); - Removed by Yogurt
}
else if ((GetState() & GVIS_SELECTED))
{
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
pDC->FillSolidRect(rect, pDefaultCell->GetSelectedBkClr());
rect.right--; rect.bottom--;
pDC->SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else
{
if (bEraseBkgnd)
{
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
CBrush brush(TextBkClr);
pDC->FillRect(rect, &brush);
rect.right--; rect.bottom--;
}
pDC->SetTextColor(TextClr);
}
// Draw lines only when wanted
if (IsFixed() && pGrid->GetGridLines() != GVL_NONE)
{
CCellID FocusCell = pGrid->GetFocusCell();
// As above, always show current location even in list mode so
// that we know where the cursor is at.
BOOL bHiliteFixed = pGrid->GetTrackFocusCell() && pGrid->IsValid(FocusCell) &&
(FocusCell.row == nRow || FocusCell.col == nCol);
// If this fixed cell is on the same row/col as the focus cell,
// highlight it.
if (bHiliteFixed)
{
rect.right++; rect.bottom++;
pDC->DrawEdge(rect, BDR_SUNKENINNER /*EDGE_RAISED*/, BF_RECT);
rect.DeflateRect(1,1);
}
else
{
CPen lightpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DHIGHLIGHT)),
darkpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DDKSHADOW)),
*pOldPen = pDC->GetCurrentPen();
pDC->SelectObject(&lightpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.left, rect.top);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(&darkpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(pOldPen);
rect.DeflateRect(1,1);
}
}
// Draw Text and image
#if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING)
if (!pDC->m_bPrinting)
#endif
{
CFont *pFont = GetFontObject();
ASSERT(pFont);
if (pFont)
pDC->SelectObject(pFont);
}
//rect.DeflateRect(GetMargin(), 0); - changed by Yogurt
rect.DeflateRect(GetMargin(), GetMargin());
rect.right++;
rect.bottom++;
if (pGrid->GetImageList() && GetImage() >= 0)
{
IMAGEINFO Info;
if (pGrid->GetImageList()->GetImageInfo(GetImage(), &Info))
{
// would like to use a clipping region but seems to have issue
// working with CMemDC directly. Instead, don't display image
// if any part of it cut-off
//
// CRgn rgn;
// rgn.CreateRectRgnIndirect(rect);
// pDC->SelectClipRgn(&rgn);
// rgn.DeleteObject();
/*
// removed by Yogurt
int nImageWidth = Info.rcImage.right-Info.rcImage.left+1;
int nImageHeight = Info.rcImage.bottom-Info.rcImage.top+1;
if( nImageWidth + rect.left <= rect.right + (int)(2*GetMargin())
&& nImageHeight + rect.top <= rect.bottom + (int)(2*GetMargin()) )
{
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
}
*/
// Added by Yogurt
int nImageWidth = Info.rcImage.right-Info.rcImage.left;
int nImageHeight = Info.rcImage.bottom-Info.rcImage.top;
if ((nImageWidth + rect.left <= rect.right) && (nImageHeight + rect.top <= rect.bottom))
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
//rect.left += nImageWidth+GetMargin();
}
}
if (nRow == 0)
{
RemoveSortSign();
// Draw sort arrow
if(pGrid->GetSortColumn() == nCol)
{
BOOL bSortSign = TRUE;
if(bSortSign)
{
SetSortSign();
}
else
{
CSize size = pDC->GetTextExtent(_T("M"));
int nOffset = 2;
// Base the size of the triangle on the smaller of the column
// height or text height with a slight offset top and bottom.
// Otherwise, it can get drawn outside the bounds of the cell.
size.cy -= (nOffset * 2);
if (size.cy >= rect.Height())
size.cy = rect.Height() - (nOffset * 2);
size.cx = size.cy; // Make the dimensions square
// Kludge for vertical text
BOOL bVertical = (GetFont()->lfEscapement == 900);
// Only draw if it'll fit!
//if (size.cx + rect.left < rect.right + (int)(2*GetMargin())) - changed / Yogurt
if (size.cx + rect.left < rect.right)
{
int nTriangleBase = rect.bottom - nOffset - size.cy; // Triangle bottom right
//int nTriangleBase = (rect.top + rect.bottom - size.cy)/2; // Triangle middle right
//int nTriangleBase = rect.top + nOffset; // Triangle top right
//int nTriangleLeft = rect.right - size.cx; // Triangle RHS
//int nTriangleLeft = (rect.right + rect.left - size.cx)/2; // Triangle middle
//int nTriangleLeft = rect.left; // Triangle LHS
int nTriangleLeft;
if (bVertical)
nTriangleLeft = (rect.right + rect.left - size.cx)/2; // Triangle middle
else
nTriangleLeft = rect.right - size.cx; // Triangle RHS
CPen penShadow(PS_SOLID, 0, ::GetSysColor(COLOR_3DSHADOW));
CPen penLight(PS_SOLID, 0, ::GetSysColor(COLOR_3DHILIGHT));
if (pGrid->GetSortAscending())
{
// Draw triangle pointing upwards
CPen *pOldPen = (CPen*) pDC->SelectObject(&penLight);
pDC->MoveTo( nTriangleLeft + 1, nTriangleBase + size.cy + 1);
pDC->LineTo( nTriangleLeft + (size.cx / 2) + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + size.cx + 1, nTriangleBase + size.cy + 1);
pDC->LineTo( nTriangleLeft + 1, nTriangleBase + size.cy + 1);
pDC->SelectObject(&penShadow);
pDC->MoveTo( nTriangleLeft, nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft + (size.cx / 2), nTriangleBase );
pDC->LineTo( nTriangleLeft + size.cx, nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft, nTriangleBase + size.cy );
pDC->SelectObject(pOldPen);
}
else
{
// Draw triangle pointing downwards
CPen *pOldPen = (CPen*) pDC->SelectObject(&penLight);
pDC->MoveTo( nTriangleLeft + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + (size.cx / 2) + 1, nTriangleBase + size.cy + 1 );
pDC->LineTo( nTriangleLeft + size.cx + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + 1, nTriangleBase + 1 );
pDC->SelectObject(&penShadow);
pDC->MoveTo( nTriangleLeft, nTriangleBase );
pDC->LineTo( nTriangleLeft + (size.cx / 2), nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft + size.cx, nTriangleBase );
pDC->LineTo( nTriangleLeft, nTriangleBase );
pDC->SelectObject(pOldPen);
}
if (!bVertical)
rect.right -= size.cy;
}
}
}
}
// We want to see '&' characters so use DT_NOPREFIX
GetTextRect(rect);
rect.right++;
rect.bottom++;
DrawText(pDC->m_hDC, GetText(), -1, rect, GetFormat() | DT_NOPREFIX);
pDC->RestoreDC(nSavedDC);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Mouse and Cursor events
// Not yet implemented
void CGridCellBase::OnMouseEnter()
{
TRACE0("Mouse entered cell\n");
}
void CGridCellBase::OnMouseOver()
{
//TRACE0("Mouse over cell\n");
}
// Not Yet Implemented
void CGridCellBase::OnMouseLeave()
{
TRACE0("Mouse left cell\n");
}
void CGridCellBase::OnClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse Left btn up in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnClickDown( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse Left btn down in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnRClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse right-clicked in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnDblClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse double-clicked in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
// Return TRUE if you set the cursor
BOOL CGridCellBase::OnSetCursor()
{
#ifndef _WIN32_WCE_NO_CURSOR
SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
#endif
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase editing
void CGridCellBase::OnEndEdit()
{
ASSERT( FALSE);
}
BOOL CGridCellBase::ValidateEdit(LPCTSTR str)
{
UNUSED_ALWAYS(str);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Sizing
BOOL CGridCellBase::GetTextRect( LPRECT pRect) // i/o: i=dims of cell rect; o=dims of text rect
{
if (GetImage() >= 0)
{
IMAGEINFO Info;
CGridCtrl* pGrid = GetGrid();
CImageList* pImageList = pGrid->GetImageList();
if (pImageList && pImageList->GetImageInfo( GetImage(), &Info))
{
int nImageWidth = Info.rcImage.right-Info.rcImage.left+1;
pRect->left += nImageWidth + GetMargin();
}
}
return TRUE;
}
// By default this uses the selected font (which is a bigger font)
CSize CGridCellBase::GetTextExtent(LPCTSTR szText, CDC* pDC /*= NULL*/)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
BOOL bReleaseDC = FALSE;
if (pDC == NULL || szText == NULL)
{
if (szText)
pDC = pGrid->GetDC();
if (pDC == NULL || szText == NULL)
{
CGridDefaultCell* pDefCell = (CGridDefaultCell*) GetDefaultCell();
ASSERT(pDefCell);
return CSize(pDefCell->GetWidth(), pDefCell->GetHeight());
}
bReleaseDC = TRUE;
}
CFont *pOldFont = NULL,
*pFont = GetFontObject();
if (pFont)
pOldFont = pDC->SelectObject(pFont);
CSize size;
int nFormat = GetFormat();
// If the cell is a multiline cell, then use the width of the cell
// to get the height
if ((nFormat & DT_WORDBREAK) && !(nFormat & DT_SINGLELINE))
{
CString str = szText;
int nMaxWidth = 0;
while (TRUE)
{
int nPos = str.Find(_T('\n'));
CString TempStr = (nPos < 0)? str : str.Left(nPos);
int nTempWidth = pDC->GetTextExtent(TempStr).cx;
if (nTempWidth > nMaxWidth)
nMaxWidth = nTempWidth;
if (nPos < 0)
break;
str = str.Mid(nPos + 1); // Bug fix by Thomas Steinborn
}
CRect rect;
rect.SetRect(0,0, nMaxWidth+1, 0);
pDC->DrawText(szText, -1, rect, nFormat | DT_CALCRECT);
size = rect.Size();
}
else
size = pDC->GetTextExtent(szText, (int)_tcslen(szText));
// Removed by Yogurt
//TEXTMETRIC tm;
//pDC->GetTextMetrics(&tm);
//size.cx += (tm.tmOverhang);
if (pOldFont)
pDC->SelectObject(pOldFont);
size += CSize(2*GetMargin(), 2*GetMargin());
// Kludge for vertical text
LOGFONT *pLF = GetFont();
if (pLF->lfEscapement == 900 || pLF->lfEscapement == -900)
{
int nTemp = size.cx;
size.cx = size.cy;
size.cy = nTemp;
size += CSize(0, 4*GetMargin());
}
if (bReleaseDC)
pGrid->ReleaseDC(pDC);
return size;
}
CSize CGridCellBase::GetCellExtent(CDC* pDC)
{
CSize size = GetTextExtent(GetText(), pDC);
CSize ImageSize(0,0);
int nImage = GetImage();
if (nImage >= 0)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
IMAGEINFO Info;
if (pGrid->GetImageList() && pGrid->GetImageList()->GetImageInfo(nImage, &Info))
{
ImageSize = CSize(Info.rcImage.right-Info.rcImage.left,
Info.rcImage.bottom-Info.rcImage.top);
if (size.cx > 2*(int)GetMargin ())
ImageSize.cx += GetMargin();
ImageSize.cy += 2*(int)GetMargin ();
}
}
size.cx += ImageSize.cx + 1;
size.cy = max(size.cy, ImageSize.cy) + 1;
if (IsFixed())
{
size.cx++;
size.cy++;
}
return size;
}
// EFW - Added to print cells so that grids that use different colors are
// printed correctly.
BOOL CGridCellBase::PrintCell(CDC* pDC, int /*nRow*/, int /*nCol*/, CRect rect)
{
#if defined(_WIN32_WCE_NO_PRINTING) || defined(GRIDCONTROL_NO_PRINTING)
return FALSE;
#else
COLORREF crFG, crBG;
GV_ITEM Item;
CGridCtrl* pGrid = GetGrid();
if (!pGrid || !pDC)
return FALSE;
if( rect.Width() <= 0
|| rect.Height() <= 0) // prevents imagelist item from drawing even
return FALSE; // though cell is hidden
int nSavedDC = pDC->SaveDC();
pDC->SetBkMode(TRANSPARENT);
if (pGrid->GetShadedPrintOut())
{
// Get the default cell implementation for this kind of cell. We use it if this cell
// has anything marked as "default"
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return FALSE;
// Use custom color if it doesn't match the default color and the
// default grid background color. If not, leave it alone.
if(IsFixed())
crBG = (GetBackClr() != CLR_DEFAULT) ? GetBackClr() : pDefaultCell->GetBackClr();
else
crBG = (GetBackClr() != CLR_DEFAULT && GetBackClr() != pDefaultCell->GetBackClr()) ?
GetBackClr() : CLR_DEFAULT;
// Use custom color if the background is different or if it doesn't
// match the default color and the default grid text color.
if(IsFixed())
crFG = (GetBackClr() != CLR_DEFAULT) ? GetTextClr() : pDefaultCell->GetTextClr();
else
crFG = (GetBackClr() != CLR_DEFAULT) ? GetTextClr() : pDefaultCell->GetTextClr();
// If not printing on a color printer, adjust the foreground color
// to a gray scale if the background color isn't used so that all
// colors will be visible. If not, some colors turn to solid black
// or white when printed and may not show up. This may be caused by
// coarse dithering by the printer driver too (see image note below).
if(pDC->GetDeviceCaps(NUMCOLORS) == 2 && crBG == CLR_DEFAULT)
crFG = RGB(GetRValue(crFG) * 0.30, GetGValue(crFG) * 0.59,
GetBValue(crFG) * 0.11);
// Only erase the background if the color is not the default
// grid background color.
if(crBG != CLR_DEFAULT)
{
CBrush brush(crBG);
rect.right++; rect.bottom++;
pDC->FillRect(rect, &brush);
rect.right--; rect.bottom--;
}
}
else
{
crBG = CLR_DEFAULT;
crFG = RGB(0, 0, 0);
}
pDC->SetTextColor(crFG);
CFont *pFont = GetFontObject();
if (pFont)
pDC->SelectObject(pFont);
/*
// ***************************************************
// Disabled - if you need this functionality then you'll need to rewrite.
// Create the appropriate font and select into DC.
CFont Font;
// Bold the fixed cells if not shading the print out. Use italic
// font it it is enabled.
const LOGFONT* plfFont = GetFont();
if(IsFixed() && !pGrid->GetShadedPrintOut())
{
Font.CreateFont(plfFont->lfHeight, 0, 0, 0, FW_BOLD, plfFont->lfItalic, 0, 0,
ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
#ifndef _WIN32_WCE
PROOF_QUALITY,
#else
DEFAULT_QUALITY,
#endif
VARIABLE_PITCH | FF_SWISS, plfFont->lfFaceName);
}
else
Font.CreateFontIndirect(plfFont);
pDC->SelectObject(&Font);
// ***************************************************
*/
// Draw lines only when wanted on fixed cells. Normal cell grid lines
// are handled in OnPrint.
if(pGrid->GetGridLines() != GVL_NONE && IsFixed())
{
CPen lightpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DHIGHLIGHT)),
darkpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DDKSHADOW)),
*pOldPen = pDC->GetCurrentPen();
pDC->SelectObject(&lightpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.left, rect.top);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(&darkpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->LineTo(rect.left, rect.bottom);
rect.DeflateRect(1,1);
pDC->SelectObject(pOldPen);
}
rect.DeflateRect(GetMargin(), 0);
if(pGrid->GetImageList() && GetImage() >= 0)
{
// NOTE: If your printed images look like fuzzy garbage, check the
// settings on your printer driver. If it's using coarse
// dithering and/or vector graphics, they may print wrong.
// Changing to fine dithering and raster graphics makes them
// print properly. My HP 4L had that problem.
IMAGEINFO Info;
if(pGrid->GetImageList()->GetImageInfo(GetImage(), &Info))
{
int nImageWidth = Info.rcImage.right-Info.rcImage.left;
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
rect.left += nImageWidth+GetMargin();
}
}
// Draw without clipping so as not to lose text when printed for real
// DT_NOCLIP removed 01.01.01. Slower, but who cares - we are printing!
DrawText(pDC->m_hDC, GetText(), -1, rect,
GetFormat() | /*DT_NOCLIP | */ DT_NOPREFIX);
pDC->RestoreDC(nSavedDC);
return TRUE;
#endif
}
/*****************************************************************************
Callable by derived classes, only
*****************************************************************************/
LRESULT CGridCellBase::SendMessageToParent(int nRow, int nCol, int nMessage)
{
CGridCtrl* pGrid = GetGrid();
if( pGrid)
return pGrid->SendMessageToParent(nRow, nCol, nMessage);
else
return 0;
} | [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
813
]
]
]
|
cd3e72f1b0cae772978b857c17f8e05e3313182c | dee66eacd9f9f7da38c1553db3c1d2c9ffe7d9ac | /src/drips.h | 32401b0797491216819012b585103728acc4bc54 | []
| no_license | Jerrem/LightGraff_BDO | 6ada3dd060b0c2eb3af70e17406339b801e92dbd | ee36e13c869eb73bd27bf92738f8ca51fa6ebf05 | refs/heads/master | 2021-01-16T21:06:38.096203 | 2011-04-05T10:11:19 | 2011-04-05T10:11:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | h | #ifndef _DRIP
#define _DRIP
#include "ofMain.h"
#define ONE_OVER_255 0.00392157
//--------------------------------------------------------
class Drips {
public:
void setup();
void update();
void draw();
unsigned char * getPixelData();
void drawDrip(int _d);
void clearScreen();
void addDrip(int _x, int _y);
unsigned char * pixels;
ofImage dripBrush;
ofImage IMG;
ofImage TMP;
int steps;
int red;
int green;
int blue;
int imageNumBytes;
int stride;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
3ae192748b07bffda706f36573984927b5981c38 | 0b55a33f4df7593378f58b60faff6bac01ec27f3 | /Konstruct/Common/Graphics/kpgShader.cpp | c7247e92291b4030dab87e41cff615f8c6cfa311 | []
| no_license | RonOHara-GG/dimgame | 8d149ffac1b1176432a3cae4643ba2d07011dd8e | bbde89435683244133dca9743d652dabb9edf1a4 | refs/heads/master | 2021-01-10T21:05:40.480392 | 2010-09-01T20:46:40 | 2010-09-01T20:46:40 | 32,113,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,250 | cpp | #include "StdAfx.h"
#include "Common\Graphics\kpgShader.h"
#include "Common\Graphics\kpgRenderer.h"
#include "Common\Graphics\kpgTexture.h"
#include "Common\Graphics\kpgLight.h"
#include "Common\Utility\kpuFileManager.h"
// Include the shader data here
#include "Common\Graphics\Shaders\DefaultShader.sh"
#include "Common\Graphics\Shaders\ImmediateMode.sh"
const u32 g_DefaultShaderShaderDataSize = sizeof(g_DefaultShaderShaderData);
const u32 g_ImmediateModeShaderDataSize = sizeof(g_ImmediateModeShaderData);
kpgShader::kpgShader(void)
{
m_pEffect = 0;
m_hDefaultTechnique = 0;
m_hWorldViewProj = 0;
m_hWorld = 0;
m_hLightCount = 0;
m_hLightType = 0;
m_hLightVector = 0;
m_hLightColor = 0;
m_hAmbientColor = 0;
m_hDefaultTexture = 0;
m_pDefaultTexture = 0;
m_hCurrentTechnique = 0;
m_bBound = false;
}
kpgShader::~kpgShader(void)
{
Unbind();
if( m_pEffect )
{
m_pEffect->Release();
}
}
void kpgShader::LoadFromFile(kpgRenderer* pRenderer, const char* pszFilename)
{
char szFullPath[2048];
kpuFileManager::GetFullFilePath(pszFilename, szFullPath, sizeof(szFullPath));
HRESULT result = D3DXCreateEffectFromFile(pRenderer->GetDevice(), szFullPath, 0, 0, 0, 0, &m_pEffect, 0);
if( result != D3D_OK )
{
assert(0);
}
else
{
// Get the default technique
m_hDefaultTechnique = m_pEffect->GetTechniqueByName("DefaultTechnique");
// Get Global Variables
m_hWorldViewProj = m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ");
m_hWorld = m_pEffect->GetParameterBySemantic(NULL, "WORLD");
// Get Lighting Variables
m_hLightCount = m_pEffect->GetParameterBySemantic(NULL, "LIGHTCOUNT");
m_hLightType = m_pEffect->GetParameterBySemantic(NULL, "LIGHTTYPE");
m_hLightVector = m_pEffect->GetParameterBySemantic(NULL, "LIGHTVECTOR");
m_hLightColor = m_pEffect->GetParameterBySemantic(NULL, "LIGHTCOLOR");
m_hAmbientColor = m_pEffect->GetParameterBySemantic(NULL, "AMBIENTCOLOR");
m_hSkinningMatricies = m_pEffect->GetParameterBySemantic(NULL, "SKINNINGMATRICIES");
// Get Default Texture Variable
m_hDefaultTexture = m_pEffect->GetParameterBySemantic(NULL, "DEFAULTTEXTURE");
m_hCurrentTechnique = m_hDefaultTechnique;
}
}
void kpgShader::LoadFromMemory(kpgRenderer* pRenderer, const BYTE* pShaderData, u32 nShaderDataSize )
{
if( D3DXCreateEffect(pRenderer->GetDevice(), pShaderData, nShaderDataSize, 0, 0, 0, 0, &m_pEffect, 0) != D3D_OK )
{
assert(0);
}
else
{
// Get the default technique
m_hDefaultTechnique = m_pEffect->GetTechniqueByName("DefaultTechnique");
// Get Global Variables
m_hWorldViewProj = m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ");
m_hWorld = m_pEffect->GetParameterBySemantic(NULL, "WORLD");
// Get Lighting Variables
m_hLightCount = m_pEffect->GetParameterBySemantic(NULL, "LIGHTCOUNT");
m_hLightType = m_pEffect->GetParameterBySemantic(NULL, "LIGHTTYPE");
m_hLightVector = m_pEffect->GetParameterBySemantic(NULL, "LIGHTVECTOR");
m_hLightColor = m_pEffect->GetParameterBySemantic(NULL, "LIGHTCOLOR");
m_hAmbientColor = m_pEffect->GetParameterBySemantic(NULL, "AMBIENTCOLOR");
m_hSkinningMatricies = m_pEffect->GetParameterBySemantic(NULL, "SKINNINGMATRICIES");
// Get Default Texture Variable
m_hDefaultTexture = m_pEffect->GetParameterBySemantic(NULL, "DEFAULTTEXTURE");
m_hCurrentTechnique = m_hDefaultTechnique;
}
}
void kpgShader::SetDefaultTexture(const kpgTexture* pTexture)
{
if( m_hDefaultTexture )
{
m_pDefaultTexture = (kpgTexture*)pTexture;
m_pEffect->SetTexture(m_hDefaultTexture, pTexture->GetDeviceTexture());
}
}
void kpgShader::SetTexture(const kpgTexture* pTexture)
{
m_pEffect->SetTexture(m_hDefaultTexture, pTexture->GetDeviceTexture());
}
void kpgShader::SetMatrices(const kpuMatrix& mTransform, const kpuMatrix& mWorld)
{
if( m_hWorldViewProj )
m_pEffect->SetMatrix(m_hWorldViewProj, (const D3DXMATRIX*)&mTransform);
if( m_hWorld )
m_pEffect->SetMatrix(m_hWorld, (const D3DXMATRIX*)&mWorld);
}
void kpgShader::SetMatrixParam(const char* szSemantic, const kpuMatrix& mMatrix)
{
D3DXHANDLE hMatrix = m_pEffect->GetParameterBySemantic(NULL, szSemantic);
if( hMatrix )
m_pEffect->SetMatrix(hMatrix, (const D3DXMATRIX*)&mMatrix);
}
void kpgShader::SetAmbientColor(const kpuVector& vAmbientColor)
{
if( m_hAmbientColor )
{
m_pEffect->SetFloatArray(m_hAmbientColor, (const float*)&vAmbientColor, 4);
}
}
void kpgShader::SetLights(const kpgLight** pLightArray)
{
int nLightCount = 0;
for( nLightCount; nLightCount < MAX_LIGHTS; nLightCount++ )
{
if( !pLightArray[nLightCount] )
break;
}
if( m_hLightCount )
m_pEffect->SetInt(m_hLightCount, nLightCount);
int nLightTypes[MAX_LIGHTS];
kpuVector vVectors[MAX_LIGHTS];
kpuVector vColors[MAX_LIGHTS];
for( int i = 0; i < nLightCount; i++ )
{
nLightTypes[i] = (int)pLightArray[i]->GetType();
vVectors[i] = pLightArray[i]->GetPositionDirection();
vColors[i] = pLightArray[i]->GetColor();
}
if( m_hLightType )
m_pEffect->SetIntArray(m_hLightType, &nLightTypes[0], MAX_LIGHTS);
if( m_hLightVector )
m_pEffect->SetFloatArray(m_hLightVector, (const float*)&vVectors[0], 4 * MAX_LIGHTS);
if( m_hLightColor)
m_pEffect->SetFloatArray(m_hLightColor, (const float*)&vColors[0], 4 * MAX_LIGHTS);
}
void kpgShader::SetSkinningMatricies(kpuFixedArray<kpuMatrix>* paMatricies)
{
if( m_hSkinningMatricies)
m_pEffect->SetMatrixArray(m_hSkinningMatricies, (D3DXMATRIX*)(&(*paMatricies)[0]), paMatricies->GetNumElements());
}
void kpgShader::Bind()
{
// Set the current technique
m_pEffect->SetTechnique(m_hCurrentTechnique);
HRESULT hRes = m_pEffect->Begin(&m_unPasses, 0);
m_bBound = true;
}
void kpgShader::Unbind()
{
if( m_bBound )
{
m_pEffect->End();
}
m_bBound = false;
}
void kpgShader::BeginPass(u32 unPass)
{
// Start the pass
m_pEffect->BeginPass(unPass);
// Update shader variables
m_pEffect->CommitChanges();
}
void kpgShader::EndPass()
{
m_pEffect->EndPass();
if(m_pDefaultTexture)
SetTexture(m_pDefaultTexture);
} | [
"acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e",
"bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e"
]
| [
[
[
1,
5
],
[
7,
26
],
[
28,
43
],
[
80,
92
],
[
94,
100
],
[
103,
114
],
[
116,
119
],
[
126,
177
],
[
184,
196
],
[
198,
198
],
[
201,
215
],
[
219,
219
]
],
[
[
6,
6
],
[
27,
27
],
[
44,
79
],
[
93,
93
],
[
101,
102
],
[
115,
115
],
[
120,
125
],
[
178,
183
],
[
197,
197
],
[
199,
200
],
[
216,
218
]
]
]
|
ee4cc22356dc51d392396558ac9b19468114f718 | c1c3866586c56ec921cd8c9a690e88ac471adfc8 | /Qt_Practise/MFC_CString_Test/MFC_CString_Test.cpp | 4f4af859983a9d91ddd2776879052748cec22f09 | []
| no_license | rtmpnewbie/lai3d | 0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f | b44c9edfb81fde2b40e180a651793fec7d0e617d | refs/heads/master | 2021-01-10T04:29:07.463289 | 2011-03-22T17:51:24 | 2011-03-22T17:51:24 | 36,842,700 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,079 | cpp | // MFC_CString_Test.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "MFC_CString_Test.h"
#include "MFC_CString_TestDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFC_CString_TestApp
BEGIN_MESSAGE_MAP(CMFC_CString_TestApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CMFC_CString_TestApp 构造
CMFC_CString_TestApp::CMFC_CString_TestApp()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CMFC_CString_TestApp 对象
CMFC_CString_TestApp theApp;
// CMFC_CString_TestApp 初始化
BOOL CMFC_CString_TestApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
CMFC_CString_TestDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此处放置处理何时用“确定”来关闭
// 对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用“取消”来关闭
// 对话框的代码
}
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
| [
"laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5"
]
| [
[
[
1,
78
]
]
]
|
e8c8eba5f5d7bec38f38be7caa4bdf561d2e52b3 | cecdfda53e1c15e7bd667440cf5bf8db4b3d3e55 | /Map Editor/Config.h | bad69f058c219dde3ebb78198ee8f2bcb6500623 | []
| no_license | omaskery/mini-stalker | f9f8713cf6547ccb9b5e51f78dfb65a4ae638cda | 954e8fce9e16740431743f020c6ddbc866e69002 | refs/heads/master | 2021-01-23T13:29:26.557156 | 2007-08-04T12:44:52 | 2007-08-04T12:44:52 | 33,090,577 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,151 | h | struct value
{
std::string name,val;
value()
{
}
value(const std::string &n, const std::string &v) : name(n), val(v)
{
}
void get(int *i)
{
*i = toInt(val);
}
void get(float *f)
{
*f = toFloat(val);
}
void get(double *d)
{
*d = toDouble(val);
}
void get(std::string *s)
{
*s = val;
}
};
struct block
{
std::vector<block> blocks;
std::vector<value> values;
std::string name;
value *get_value(const std::string &name)
{
for(unsigned int i = 0; i < values.size(); ++i)
{
if(values[i].name == name) return &values[i];
}
return NULL;
}
block *get_block(const std::string &name)
{
for(unsigned int i = 0; i < blocks.size(); ++i)
{
if(blocks[i].name == name) return &blocks[i];
}
return NULL;
}
};
#include <iostream>
class config
{
std::vector<block> blocks;
std::string filename;
void remove_outer_spaces(std::string &str)
{
unsigned int first = str.find_first_not_of(" ");
unsigned int last;
str.erase(0,first);
last = str.size()-1;
while(last >= 0 && str[last] == ' ')
{
--last;
}
str.erase(last);
}
int load_contents(std::string *str)
{
std::ifstream f(filename.c_str());
if(!f) return -1;
size_t size;
f.seekg(0,std::ios::end);
size = f.tellg();
f.seekg(0,std::ios::beg);
char *read = new char[size];
f.read(read,size);
*str = read;
delete read;
f.close();
return 0;
}
block load_block(const std::string &name, const std::string &Block)
{
block temp;
temp.name = name;
int pos = 0;
while(1)
{
int b_pos = pos;
pos = Block.find("block",pos);
if(pos == std::string::npos)
{
pos = b_pos;
break;
}
pos = Block.find("\"",pos);
int epos = Block.find("\"",pos+1);
++pos;
std::string Block_name = Block.substr(pos,epos-pos);
pos = Block.find("{",epos);
int scope = 1;
int start = pos;
while(pos < Block.size() && scope > 0)
{
if(scope > 0) ++pos;
if(Block[pos] == '{') ++scope;
if(Block[pos] == '}') --scope;
}
int end = pos;
if(Block[start] == '{') ++start;
if(Block[end] == '}') --end;
std::string Block_contents = Block.substr(start,end-start);
temp.blocks.push_back(load_block(Block_name,Block_contents));
}
while(1)
{
pos = Block.find(":",pos);
if(pos == std::string::npos) break;
int e_name = Block.find_last_not_of(" ",pos-1);
int s_name = Block.find_last_of(" ",e_name);
++s_name;
++e_name;
std::string value_name = Block.substr(s_name,e_name-s_name);
pos = Block.find_first_not_of(" ",pos+1);
int epos = Block.find(" ",pos);
if(Block.substr(pos,epos-pos).find("\n") != std::string::npos) epos = Block.find("\n",pos);
std::string val = Block.substr(pos,epos-pos);
value t;
t.name = value_name;
t.val = val;
temp.values.push_back(t);
pos = epos;
}
return temp;
}
public:
config(const std::string &file) : filename(file)
{
}
block *get_block(const std::string &name)
{
for(unsigned int i = 0; i < blocks.size(); ++i)
{
if(blocks[i].name == name) return &blocks[i];
}
return NULL;
}
int load()
{
blocks.clear();
std::string contents;
if(load_contents(&contents) == -1) return -1;
int pos = 0;
while(1)
{
pos = contents.find("block",pos);
if(pos == std::string::npos) break;
pos = contents.find("\"",pos);
int epos = contents.find("\"",pos+1);
++pos;
std::string block_name = contents.substr(pos,epos-pos);
pos = contents.find("{",epos);
int scope = 1;
int start = pos;
while(pos < contents.size() && scope > 0)
{
if(scope > 0) ++pos;
if(contents[pos] == '{') ++scope;
if(contents[pos] == '}') --scope;
}
int end = pos;
if(contents[start] == '{') ++start;
if(contents[end] == '}') --end;
std::string block_contents = contents.substr(start,end-start);
blocks.push_back(load_block(block_name,block_contents));
}
return 0;
}
};
| [
"ollie.the.pie.lord@823218a8-ad34-0410-91fc-f9441fec9dcb"
]
| [
[
[
1,
221
]
]
]
|
2f665432a48b3aeadde865b019eabf5eead563e0 | e09dfcc817c731587fd756f7611aacb19b17018a | /FilterLog/inc/FilterLogView.h | e938ec8dda60de0a75caa806c8768bbd8f95c852 | []
| no_license | jweitzen/analogqct | cb77f50f2682ee46325cafd738fcf1299d2710aa | 535bcf32fd615815d640b06c860cfec9acb7f983 | refs/heads/master | 2021-01-10T09:31:14.808743 | 2009-06-12T16:46:03 | 2009-06-12T16:46:03 | 50,674,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,590 | h | // FilterLogView.h : interface of the CFilterLogView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_FILTERLOGVIEW_H__95F45486_1274_4486_B0F4_888D46F1773F__INCLUDED_)
#define AFX_FILTERLOGVIEW_H__95F45486_1274_4486_B0F4_888D46F1773F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "InPlaceEdit.h"
#include "InPlaceList.h"
class CFilterLogView : public CListView
{
protected: // create from serialization only
CFilterLogView();
DECLARE_DYNCREATE(CFilterLogView)
// Attributes
public:
CFilterLogDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFilterLogView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void OnInitialUpdate(); // called first time after construct
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
// Implementation
public:
void UpdateView();
CComboBox* ShowInPlaceList(int nItem, int nCol, CStringList &lstItems, int nSel);
int HitTestEx(CPoint &point, int *col) const;
CEdit* EditSubLabel(int nItem, int nCol);
virtual ~CFilterLogView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CFilterLogView)
afx_msg void OnEndlabeledit(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnItemchanged(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnEditCheckall();
afx_msg void OnEditUncheckall();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in FilterLogView.cpp
inline CFilterLogDoc* CFilterLogView::GetDocument()
{ return (CFilterLogDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FILTERLOGVIEW_H__95F45486_1274_4486_B0F4_888D46F1773F__INCLUDED_)
| [
"giulio.inbox@6d061dfa-575b-11de-9a1b-6103e4980ab8"
]
| [
[
[
1,
80
]
]
]
|
b033692bd6dc997cf0134e4a254f9584e9c1a13f | 3a79a741fe799d531f363834255d1ce15a520258 | /artigos/arquiteturaDeJogos/programacao/animacao/VertexAnimation/main.cpp | 5be6e88acdc1e9e8759e4766ce1ad427bdf8c879 | []
| no_license | ViniGodoy/pontov | a8bd3485c53d5fc79312f175610a2962c420c40d | 01f8f82209ba10a57d9d220d838cbf00aede4cee | refs/heads/master | 2020-04-24T19:33:24.288796 | 2011-06-20T21:44:03 | 2011-06-20T21:44:03 | 32,488,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include "GameWindow.h"
#include "ModelViewer.h"
int main(int argc,char* argv[])
{
if(argc < 3)
{
printf("Usage: modelViewer <modelName> <textureName>\n");
return 0;
}
GameWindow &gw = GameWindow::getInstance();
gw.setup("Model Viewer", 800, 600);
gw.show(new ModelViewer(argv[1], argv[2]));
return 0;
}
| [
"bcsanches@7ec48984-19c3-11df-a513-1fc609e2573f"
]
| [
[
[
1,
19
]
]
]
|
c57936e5bea3f45af0617d8af8a081f9effb9640 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /GameSDK/GameCore/stdafx.h | d92786a97c7155a748d4d5ba1a660e8c8311833d | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 792 | h | // stdafx.h : 标准系统包含文件的包含文件,
// 或是常用但不常更改的项目特定的包含文件
//
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头中排除极少使用的资料
// Windows 头文件:
#include <windows.h>
// TODO: 在此处引用程序要求的附加头文件
// C 运行时头文件
#include <tchar.h>
#include <list>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <vector>
#include <complex>
#include "commonlib.h"
#include "AttribDef.h"
#include "DataHelper.h"
#include "XObject.h"
#include "XAction.h"
#include "XVector2.h"
#include "XVector3.h"
#include "GameCore.h"
using namespace XGC;
using namespace XGC::common;
// TODO: 在此处引用程序要求的附加头文件 | [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
33
]
]
]
|
14eb61df077afc879a8921b5ba894efa1b29eb09 | 75fe47eafcd866b1a1079ce476d5623b7f1cefe1 | /src/Graphic_OpenGL/Graphic_OpenGL.cpp | fa4c8cfd062d76c4b2cf1fa118cecbd95fd5d5ec | []
| no_license | Orchaldir/Engine | ae64d10c646303ea36ffa855b41de7d3555b2e22 | a7e4f177a455bc642e0d76b1f53b6227649f6bfe | refs/heads/master | 2021-01-22T17:47:56.531119 | 2010-11-21T11:11:28 | 2010-11-21T11:11:28 | 1,096,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,582 | cpp | #include "Graphic_OpenGL.hpp"
#include "Window/Window_OpenGL.hpp"
#include "SDL.h"
#include "SDL_opengl.h"
namespace Graphic
{
DLL iGraphic* createGraphic(const string& pTitle, uint32 pSizeX, uint32 pSizeY)
{
return new Graphic_OpenGL(pTitle, pSizeX, pSizeY);
}
DLL void destroyGraphic(iGraphic* pGraphic)
{
if(0 != pGraphic)
{
delete pGraphic;
}
}
Graphic_OpenGL::Graphic_OpenGL(const string& pTitle, uint32 pSizeX, uint32 pSizeY) :
mWindow(0)
{
mWindow = new Window_OpenGL(pTitle, pSizeX, pSizeY);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glShadeModel(GL_SMOOTH);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
}
Graphic_OpenGL::~Graphic_OpenGL()
{
if(0 != mWindow)
{
delete mWindow;
}
}
GraphicEvent Graphic_OpenGL::getEvent() const
{
SDL_Event fEvent;
while(SDL_PollEvent(&fEvent))
{
if(SDL_ACTIVEEVENT == fEvent.type)
{
if(fEvent.active.state & SDL_APPACTIVE)
{
if(1 == fEvent.active.gain)
{
return Focus;
}
}
}
else if(SDL_QUIT == fEvent.type)
{
return Close;
}
else if(SDL_MOUSEBUTTONDOWN == fEvent.type)
{
SDL_PushEvent(&fEvent);
return None;
}
else if(SDL_MOUSEBUTTONUP == fEvent.type)
{
SDL_PushEvent(&fEvent);
return None;
}
}
return None;
}
}
| [
"[email protected]"
]
| [
[
[
1,
86
]
]
]
|
cde05afd3bedda94a1b4a222fde00d48e433e1fd | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Applications/Physics/GelatinCube/PhysicsModule.cpp | 750074c97244ae27af10c75d4d728fdadf82c256 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,323 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Game Physics source code is supplied under the terms of the license
// agreement http://www.magic-software.com/License/GamePhysics.pdf and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
#include "PhysicsModule.h"
//----------------------------------------------------------------------------
PhysicsModule::PhysicsModule (int iSlices, int iRows, int iCols, float fStep,
float fViscosity)
:
MassSpringVolume3f(iSlices,iRows,iCols,fStep)
{
m_fViscosity = fViscosity;
}
//----------------------------------------------------------------------------
PhysicsModule::~PhysicsModule ()
{
}
//----------------------------------------------------------------------------
float& PhysicsModule::Viscosity ()
{
return m_fViscosity;
}
//----------------------------------------------------------------------------
Vector3f PhysicsModule::ExternalImpulse (int i, float fTime,
const Vector3f* akPosition, const Vector3f* akVelocity)
{
Vector3f kImpulse = -m_fViscosity*akVelocity[i];
return kImpulse;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
3ea983e85b3a35254c7da986b6279246fd52b2ac | 8a8c3d018f999f787a3751f32f24aca787bb05f8 | /ObjTable.h | a8f95b0efdc93b542595055c7e00d95e2da2ce44 | []
| no_license | daoopp/mse | fbc01193584400866b7516ecf24e6f0837443b87 | 2631ce8a7b5b225c9e4440aefdf12c2604846674 | refs/heads/master | 2021-01-18T07:19:20.025158 | 2011-03-17T15:36:02 | 2011-03-17T15:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #ifndef __OBJTABLE_H__
#define __OBJTABLE_H__
#include "clib.h"
#include "os/CSS_LOCKEX.h"
#include "ObjectInst.h"
#ifdef WIN32
using namespace stdext;
#else
#include <ext/hash_map>
#endif
class CObjTable
{
private:
std::vector<CObjectInst*> m_table;
CSS_MUTEX m_lock;
int hash_code;
public:
CObjectInst* createObjectInstance(CClass* c){
// lock table
m_lock.Lock();
// create instance
CObjectInst *obj = new CObjectInst(m_table.size(), c);
// add to table
m_table.push_back(obj);
// relase table;
m_lock.Unlock();
return obj;
};
public:
CObjTable(void);
public:
~CObjTable(void);
};
#endif //__OBJTABLE_H__ | [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
ed973129b9a43ad01f03e01b3224f046399ef0de | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlDistTri3Rct3.h | d4d14dd7326f8c68268fda70bef0e2efdfd478f7 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLDISTTRI3RCT3_H
#define WMLDISTTRI3RCT3_H
#include "WmlRectangle3.h"
#include "WmlTriangle3.h"
namespace Wml
{
// squared distance measurements
template <class Real>
WML_ITEM Real SqrDistance (const Triangle3<Real>& rkTri,
const Rectangle3<Real>& rkRct, Real* pfTriP0 = NULL, Real* pfTriP1 = NULL,
Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);
// distance measurements
template <class Real>
WML_ITEM Real Distance (const Triangle3<Real>& rkTri,
const Rectangle3<Real>& rkRct, Real* pfTriP0 = NULL, Real* pfTriP1 = NULL,
Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
02c90dad04c32f0656d43c9e9da5fa9252400060 | 4497c10f3b01b7ff259f3eb45d0c094c81337db6 | /Retargeting/Shifmap/Version01/GCScaleImage.cpp | f89ec16d8c6c65b83baf02dde09ff7726fb5784b | []
| no_license | liuguoyou/retarget-toolkit | ebda70ad13ab03a003b52bddce0313f0feb4b0d6 | d2d94653b66ea3d4fa4861e1bd8313b93cf4877a | refs/heads/master | 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | #include "StdAfx.h"
#include "GCScaleImage.h"
GCScaleImage::GCScaleImage(void)
{
}
GCScaleImage::~GCScaleImage(void)
{
}
void GCScaleImage::Initialize(int width, int height, int labelCount)
{
_gc = new GCoptimizationGridGraph(width, height, labelCount);
}
| [
"kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a"
]
| [
[
[
1,
15
]
]
]
|
7b36577392b739f92939ad30f2ceacaaf282503a | 347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1 | /addons/vaOpenal/src/Listener.cpp | 0414bb33dfc47cd7ac668d0d947ea2874668025f | []
| no_license | sanyaade/VirtualAwesome | 29688648aa3f191cdd756c826b5c84f6f841b93f | 05f3db98500366be1e79da16f5e353e366aed01f | refs/heads/master | 2020-12-01T03:03:51.561884 | 2010-11-08T00:17:44 | 2010-11-08T00:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,525 | cpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <vaOpenal/Listener.h>
#include <vaOpenal/OpenAL.h>
using namespace vaOpenal;
std::vector<Sound*> Listener::soundPool;
std::vector<SoundStream*> Listener::streamPool;
////////////////////////////////////////////////////////////
/// Change the global volume of all the sounds
////////////////////////////////////////////////////////////
void Listener::SetGlobalVolume(float Volume)
{
ALCheck(alListenerf(AL_GAIN, Volume * 0.01f));
}
////////////////////////////////////////////////////////////
/// Get the current value of the global volume of all the sounds
////////////////////////////////////////////////////////////
float Listener::GetGlobalVolume()
{
float Volume = 0.f;
ALCheck(alGetListenerf(AL_GAIN, &Volume));
return Volume;
}
////////////////////////////////////////////////////////////
/// Change the position of the listener (take 3 values)
////////////////////////////////////////////////////////////
void Listener::SetPosition(float X, float Y, float Z)
{
ALCheck(alListener3f(AL_POSITION, X, Y, Z));
}
////////////////////////////////////////////////////////////
/// Change the position of the listener (take a 3D vector)
////////////////////////////////////////////////////////////
void Listener::SetPosition(const osg::Vec3f& Position)
{
SetPosition(Position.x(), Position.y(), Position.z());
}
////////////////////////////////////////////////////////////
/// Get the current position of the listener
////////////////////////////////////////////////////////////
osg::Vec3f Listener::GetPosition()
{
osg::Vec3f Position;
ALCheck(alGetListener3f(AL_POSITION, &Position.x(), &Position.y(), &Position.z()));
return Position;
}
////////////////////////////////////////////////////////////
/// Change the orientation of the listener (the point
/// he must look at) (take 3 values)
////////////////////////////////////////////////////////////
void Listener::SetTarget(float X, float Y, float Z)
{
float Orientation[] = {X, Y, Z, 0.f, 1.f, 0.f};
ALCheck(alListenerfv(AL_ORIENTATION, Orientation));
}
////////////////////////////////////////////////////////////
/// Change the orientation of the listener (the point
/// he must look at) (take a 3D vector)
////////////////////////////////////////////////////////////
void Listener::SetTarget(const osg::Vec3f& Target)
{
SetTarget(Target.x(), Target.y(), Target.z());
}
////////////////////////////////////////////////////////////
/// Get the current orientation of the listener (the point
/// he's looking at)
////////////////////////////////////////////////////////////
osg::Vec3f Listener::GetTarget()
{
float Orientation[6];
ALCheck(alGetListenerfv(AL_ORIENTATION, Orientation));
return osg::Vec3f(Orientation[0], Orientation[1], Orientation[2]);
}
////////////////////////////////////////////////////////////
/// Add sound to the audio pool
////////////////////////////////////////////////////////////
void Listener::AddSound(Sound* sound)
{
soundPool.push_back(sound);
}
////////////////////////////////////////////////////////////
/// Add stream to the stream pool
////////////////////////////////////////////////////////////
void Listener::AddStream(SoundStream* stream)
{
streamPool.push_back(stream);
}
////////////////////////////////////////////////////////////
/// Remove all sounds from the audio pool
////////////////////////////////////////////////////////////
void Listener::RemoveAllSounds()
{
soundPool.clear();
}
////////////////////////////////////////////////////////////
/// Remove all streams from the stream pool
////////////////////////////////////////////////////////////
void Listener::RemoveAllStreams()
{
streamPool.clear();
}
////////////////////////////////////////////////////////////
/// Stop all sounds in the audio pool
////////////////////////////////////////////////////////////
void Listener::StopAllSounds()
{
std::vector<Sound*>::iterator itr;
for(itr = soundPool.begin() ; itr < soundPool.end(); itr++)
{
(*itr)->Stop();
}
}
////////////////////////////////////////////////////////////
/// Stop all streams in the stream pool
////////////////////////////////////////////////////////////
void Listener::StopAllStreams()
{
std::vector<SoundStream*>::iterator itr;
for(itr = streamPool.begin() ; itr < streamPool.end(); itr++)
{
(*itr)->Stop();
}
}
////////////////////////////////////////////////////////////
/// Play all sounds in the audio pool
////////////////////////////////////////////////////////////
void Listener::PlayAllSounds()
{
std::vector<Sound*>::iterator itr;
for(itr = soundPool.begin() ; itr < soundPool.end(); itr++)
{
(*itr)->Play();
}
}
////////////////////////////////////////////////////////////
/// Play all streams in the stream pool
////////////////////////////////////////////////////////////
void Listener::PlayAllStreams()
{
std::vector<SoundStream*>::iterator itr;
for(itr = streamPool.begin() ; itr < streamPool.end(); itr++)
{
(*itr)->Play();
}
}
| [
"[email protected]"
]
| [
[
[
1,
200
]
]
]
|
e13e9451fdf63ebb5f0e8956e31577247998712f | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib-test/af2-test/tutorial/tutorial_10.cpp | 2dcb44ad87453df802ffe95e6141f84a95fcda59 | []
| 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 | 1,396 | cpp | #include "mglaugust2.h"
// メインフレームクラス
class CMyFrame : public CAugustWindowFrame2
{
private:
CAugustKeyboardInput2 m_kb;
CAugustSoundManager2 m_soundMgr;
CAugustSound2 m_sound1;
CAugustSound2 m_sound2;
public:
// 初期化時に呼ばれる
bool OnGraphicInitEnded()
{
// コントロールクラスの登録
RegistControl(&m_kb);
RegistControl(&m_soundMgr);
m_soundMgr.RegistControl(&m_sound1);
m_soundMgr.RegistControl(&m_sound2);
// .wavファイルの読み込み
m_sound1.Load("hoge.wav");
m_sound2.Load("hoge2.wav");
// Zキーハンドラの登録
m_kb.RegistHandler(
CAugustKeyboardInput::EVTTYPE_ON_DOWN,
'Z',
(CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::OnZ,
this);
// Xキーハンドラの登録
m_kb.RegistHandler(
CAugustKeyboardInput::EVTTYPE_ON_DOWN,
'X',
(CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::OnX,
this);
return true;
}
// Zキーにて再生
bool OnZ(){
m_sound1.Play();
return true;
}
// Xキーにて再生
bool OnX(){
m_sound2.Play();
return true;
}
};
// WinMain
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
CMyFrame frame;
frame.Start();
return 0;
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
]
| [
[
[
1,
68
]
]
]
|
b6e8826f85399a39e8341c8e413e3d4286f7eb55 | f9351a01f0e2dec478e5b60c6ec6445dcd1421ec | /itl/src/itl/split_interval_map.hpp | 32b012a609226a64bdfd87eb1163a36a48d3dd0d | [
"BSL-1.0"
]
| permissive | WolfgangSt/itl | e43ed68933f554c952ddfadefef0e466612f542c | 6609324171a96565cabcf755154ed81943f07d36 | refs/heads/master | 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 35,358 | hpp | /*----------------------------------------------------------------------------+
Copyright (c) 2007-2008: Joachim Faulhaber
+-----------------------------------------------------------------------------+
Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin
+-----------------------------------------------------------------------------+
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+----------------------------------------------------------------------------*/
/* ------------------------------------------------------------------
class split_interval_map
--------------------------------------------------------------------*/
#ifndef __split_interval_map_h_JOFA_000706__
#define __split_interval_map_h_JOFA_000706__
#include <itl/interval_set.hpp>
#include <itl/interval_map.hpp>
//CL #include <itl/split_interval_map.hpp>
#include <itl/interval_base_map.hpp>
#include <itl/split_interval_set.hpp>
namespace itl
{
/// implements a map as a map of intervals - on insertion overlapping intervals are split and associated values are combined.
/**
Template-class <b>split_interval_map</b>
implements a map as a map of intervals - On insertion overlapping intervals are
<b>split</b> and associated values are combined.
Template parameter <b>DomainT</b>: Domain type of the map. Also type of the
map's keys.
Suitable as domain types are all datatypes that posess a partial order.
In particular all discrete atomic datatypes like <tt>int, short, long</tt> and
atomic pseudo-continuous datatypes <tt>float, double</tt> may be instantiated.
Datatypes for the codomain parameter have to <b>implement</b> operations
<tt>+=</tt>, <tt>-=</tt>, <tt>==</tt> (equality) and <tt>CodomainT()</tt> (default constructor).
The default constructor <tt>CodomainT()</tt> has to contruct a neutral element
such that the following holds:
If <tt>x = y; y += CodomainT();</tt> then <tt>x==y;</tt> and
If <tt>x = y; y -= CodomainT();</tt> then <tt>x==y;</tt>
Template parameter <b>Interval=itl::interval</b>: Template type of interval used
to implement the map. The default <b>itl::interval</b> uses the
interval class template that comes with this library. Own implementation of interval
classes are possible (but not trivial).
<b>split_interval_map</b> implements a map <tt>map<DomainT, CodomainT></tt> as a map
of intervals <tt>map<interval<DomainT>, CodomainT, ExclusiveLessT<Interval> ></tt>
Interval maps <tt>split_interval_map<DomainT,CodomainT></tt> can be used similar (and in many
aspects exactly like) common stl-maps. Unlike to stl-maps where you store
a value for every key an interval map stores a contents value for an interval of
keys. In it's degenerated form the key intervals contain a single element
only. Then the interval map works like a normal stl-map. But if you work in problem
domains where you associate values to large contiguous intervals, interval maps
are very useful and efficient.
Class <tt>interval_base_map</tt> yields the following benefits:
<ul>
<li> A set of intervals is conceived as the domain set of the map.
The complexity involved with
operations on intervals maps is encapsulated. The user of the class who
wants to perform operations on interval maps is no more concerned
with questions of overlapping, joining and bordering intervals.
<li>
<b>split_interval_map</b> gives an efficient implementation of maps consisting
of larger contiguous chunks. Very large, even uncountably infinite maps
can be represented in a compact way and handled efficiently.
<li>
<b>split_interval_map</b> serves as a overlay- or collision-computer.
</ul>
<b>split_interval_map as overlay computer</b>
An object <tt>split_interval_map<int,int> overlays;</tt> computes the overlays or
collisions of intervalls which have been inserted into it, if they are
associated with the <tt>int</tt>-value <tt>1</tt> as the codommain value.
If a newly inserted interval overlaps with intervals which are already in the
map, the interval is split up at the borders of the collisions. The assiciated
values of the overlapping intervals are incremented by 1, thus counting
the numbers of overlaps.
If sets are used as codomain types, interval_maps will compute unions of
associated maps in case of interval collisions.
<b>Restrictions: </b>
A small number of functions can only be used for <b>discrete</b> domain datatypes
(<tt>short, int, Date</tt> etc.) that implement operators <tt>++</tt> and <tt>--</tt>.
These functions are tagged in the documentation. Using such functions
for continuous domain datatypes yields compiletime errors. C.f. getting
the <tt>first()</tt> element of a left open interval makes sense for intervals of
int but not for intervals of double.
@author Joachim Faulhaber
*/
template
<
typename DomainT,
typename CodomainT,
class Traits = itl::neutron_absorber,
template<class>class Interval = itl::interval,
template<class>class Compare = std::less,
template<class>class Alloc = std::allocator
>
class split_interval_map:
public interval_base_map<split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>,
DomainT,CodomainT,Traits,Interval,Compare,Alloc>
{
public:
typedef Traits traits;
typedef split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc> type;
typedef interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc> joint_type;
typedef interval_base_map <split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>,
DomainT,CodomainT,Traits,Interval,Compare,Alloc> base_type;
typedef split_interval_map<DomainT,CodomainT,itl::neutron_absorber,Interval,Compare,Alloc>
neutron_absorber_type;
typedef Interval<DomainT> interval_type;
typedef typename base_type::iterator iterator;
typedef typename base_type::value_type value_type;
typedef typename base_type::ImplMapT ImplMapT;
typedef interval_set<DomainT,Interval,Compare,Alloc> interval_set_type;
typedef interval_set_type set_type;
/// Default constructor for the empty map
split_interval_map(): base_type() {}
/// Copy constructor
split_interval_map(const split_interval_map& src): base_type(src) {}
bool contains(const value_type& x)const;
template<template<class>class Combinator>
void add(const value_type&);
void add(const value_type& value)
{ add<inplace_plus>(value); }
template<template<class>class Combinator>
void subtract(const value_type&);
void subtract(const value_type& value)
{
if(Traits::emits_neutrons())
add<inplace_minus>(value);
else
subtract<inplace_minus>(value);
}
void insert(const value_type& value);
void erase(const value_type& value);
void handle_neighbours(const iterator& it){}
//TESTCODE
void getResiduals(const interval_type& x_itv, interval_type& leftResid, interval_type& rightResid);
private:
void fill(const value_type&);
template<template<class>class Combinator>
void fill_gap(const value_type&);
template<template<class>class Combinator>
void add_rest(const interval_type& x_itv, const CodomainT& x_val, iterator& it, iterator& end_it);
template<template<class>class Combinator>
void add_rear(const interval_type& x_itv, const CodomainT& x_val, iterator& it);
template<template<class>class Combinator>
void subtract_rest(const interval_type& x_itv, const CodomainT& x_val, iterator& it, iterator& end_it);
void insert_rest(const interval_type& x_itv, const CodomainT& x_val, iterator& it, iterator& end_it);
void insert_rear(const interval_type& x_itv, const CodomainT& x_val, iterator& it);
void erase_rest(const interval_type& x_itv, const CodomainT& x_val, iterator& it, iterator& end_it);
void matchMap(split_interval_map& matchMap, const value_type& x)const;
} ;
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::matchMap(split_interval_map& matchMap, const value_type& x_y)const
{
interval_type x = x_y.KEY_VALUE;
typename ImplMapT::const_iterator fst_it = this->_map.lower_bound(x);
typename ImplMapT::const_iterator end_it = this->_map.upper_bound(x);
for(typename ImplMapT::const_iterator it=fst_it; it!=end_it; it++)
matchMap.add(*it);
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
bool split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::contains(const value_type& x_y)const
{
interval_type x = x_y.KEY_VALUE;
if(x.empty()) return true;
split_interval_map match_map; //CL <DomainT,CodomainT,Traits,Interval,Compare,Alloc> match_map;
matchMap(match_map, x_y);
if(match_map.iterative_size() != 1) return false;
iterator match_it = match_map._map.find(x);
if(! x.contained_in((*match_it).KEY_VALUE) ) return false;
return (*match_it).CONT_VALUE==x_y.CONT_VALUE;
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>::getResiduals(const interval_type& x_itv, interval_type& leftResid, interval_type& rightResid)
{
iterator fst_it = this->_map.lower_bound(x_itv);
iterator end_it = this->_map.upper_bound(x_itv);
if(fst_it==end_it)
{
leftResid.clear();
rightResid.clear();
return;
}
(*fst_it).KEY_VALUE.left_surplus(leftResid, x_itv);
iterator lst_it = fst_it; lst_it++;
if(lst_it==end_it)
{
rightResid.clear();
return;
}
lst_it=end_it; lst_it--;
(*lst_it).KEY_VALUE.right_surplus(rightResid, x_itv);
}
template <typename DomainT, typename CodomainT, class Traits,
template<class>class Interval, template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::fill(const value_type& value)
{
//collision free insert is asserted
if(value.KEY_VALUE.empty())
return;
if(Traits::absorbs_neutrons() && value.CONT_VALUE == CodomainT())
return;
this->_map.insert(value);
}
template <typename DomainT, typename CodomainT, class Traits,
template<class>class Interval, template<class>class Compare, template<class>class Alloc>
template<template<class>class Combinator>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::fill_gap(const value_type& value)
{
//collision free insert is asserted
if(value.KEY_VALUE.empty())
return;
if(Traits::absorbs_neutrons() && value.CONT_VALUE == CodomainT())
return;
if(Traits::emits_neutrons())
{
CodomainT added_val = CodomainT();
Combinator<CodomainT>()(added_val, value.CONT_VALUE);
this->_map.insert(value_type(value.KEY_VALUE, added_val));
}
else
this->_map.insert(value);
}
//-----------------------------------------------------------------------------
// add<Combinator>(pair(interval,value)):
//-----------------------------------------------------------------------------
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
template<template<class>class Combinator>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::add(const value_type& x)
{
const interval_type& x_itv = x.KEY_VALUE;
if(x_itv.empty())
return;
const CodomainT& x_val = x.CONT_VALUE;
if(Traits::absorbs_neutrons() && x_val==CodomainT())
return;
std::pair<iterator,bool> insertion;
if(Traits::emits_neutrons())
{
CodomainT added_val = CodomainT();
Combinator<CodomainT>()(added_val, x_val);
insertion = this->_map.insert(value_type(x_itv, added_val));
}
else
insertion = this->_map.insert(x);
if(!insertion.WAS_SUCCESSFUL)
{
// Detect the first and the end iterator of the collision sequence
iterator fst_it = this->_map.lower_bound(x_itv);
iterator end_it = insertion.ITERATOR;
if(end_it != this->_map.end())
end_it++;
//assert(end_it == this->_map.upper_bound(x_itv));
interval_type fst_itv = (*fst_it).KEY_VALUE ;
CodomainT cur_val = (*fst_it).CONT_VALUE ;
interval_type leadGap; x_itv.left_surplus(leadGap, fst_itv);
// this is a new Interval that is a gap in the current map
fill_gap<Combinator>(value_type(leadGap, x_val));
// only for the first there can be a leftResid: a part of *it left of x
interval_type leftResid; fst_itv.left_surplus(leftResid, x_itv);
// handle special case for first
interval_type interSec;
fst_itv.intersect(interSec, x_itv);
CodomainT cmb_val = cur_val;
Combinator<CodomainT>()(cmb_val, x_val);
iterator snd_it = fst_it; snd_it++;
if(snd_it == end_it)
{
// first == last
interval_type endGap; x_itv.right_surplus(endGap, fst_itv);
// this is a new Interval that is a gap in the current map
fill_gap<Combinator>(value_type(endGap, x_val));
// only for the last there can be a rightResid: a part of *it right of x
interval_type rightResid; (*fst_it).KEY_VALUE.right_surplus(rightResid, x_itv);
this->_map.erase(fst_it);
fill(value_type(leftResid, cur_val));
fill(value_type(interSec, cmb_val));
fill(value_type(rightResid, cur_val));
}
else
{
this->_map.erase(fst_it);
fill(value_type(leftResid, cur_val));
fill(value_type(interSec, cmb_val));
// shrink interval
interval_type x_rest(x_itv);
x_rest.left_subtract(fst_itv);
add_rest<Combinator>(x_rest, x_val, snd_it, end_it);
}
}
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
template<template<class>class Combinator>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::add_rest(const interval_type& x_itv, const CodomainT& x_val, iterator& it, iterator& end_it)
{
iterator nxt_it = it; nxt_it++;
interval_type x_rest = x_itv, gap, common, cur_itv;
//CL for(; nxt_it!=end_it; ++it, ++nxt_it)
while(nxt_it!=end_it)
{
cur_itv = (*it).KEY_VALUE ;
x_rest.left_surplus(gap, cur_itv);
Combinator<CodomainT>()(it->CONT_VALUE, x_val);
fill_gap<Combinator>(value_type(gap, x_val));
if(Traits::absorbs_neutrons() && it->CONT_VALUE == CodomainT())
this->_map.erase(it++);
else it++;
// shrink interval
x_rest.left_subtract(cur_itv);
nxt_it++;
}
add_rear<Combinator>(x_rest, x_val, it);
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
template<template<class>class Combinator>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::add_rear(const interval_type& x_rest, const CodomainT& x_val, iterator& it)
{
interval_type cur_itv = (*it).KEY_VALUE ;
CodomainT cur_val = (*it).CONT_VALUE ;
interval_type left_gap;
x_rest.left_surplus(left_gap, cur_itv);
fill_gap<Combinator>(value_type(left_gap, x_val));
interval_type common;
cur_itv.intersect(common, x_rest);
CodomainT cmb_val = cur_val;
Combinator<CodomainT>()(cmb_val, x_val);
interval_type end_gap;
x_rest.right_surplus(end_gap, cur_itv);
fill_gap<Combinator>(value_type(end_gap, x_val));
// only for the last there can be a rightResid: a part of *it right of x
interval_type right_resid;
cur_itv.right_surplus(right_resid, x_rest);
this->_map.erase(it);
fill(value_type(common, cmb_val));
fill(value_type(right_resid, cur_val));
}
//-----------------------------------------------------------------------------
// subtract<Combinator>(pair(interval,value)):
//-----------------------------------------------------------------------------
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
template<template<class>class Combinator>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::subtract(const value_type& x)
{
const interval_type& x_itv = x.KEY_VALUE;
if(x_itv.empty())
return;
const CodomainT& x_val = x.CONT_VALUE;
if(Traits::absorbs_neutrons() && x_val==CodomainT())
return;
iterator fst_it = this->_map.lower_bound(x_itv);
if(fst_it==this->_map.end()) return;
iterator end_it = this->_map.upper_bound(x_itv);
if(fst_it==end_it) return;
interval_type fst_itv = (*fst_it).KEY_VALUE ;
// must be copies because fst_it will be erased
CodomainT fst_val = (*fst_it).CONT_VALUE ;
// only for the first there can be a leftResid: a part of *it left of x
interval_type leftResid;
fst_itv.left_surplus(leftResid, x_itv);
// handle special case for first
interval_type interSec;
fst_itv.intersect(interSec, x_itv);
CodomainT cmb_val = fst_val;
Combinator<CodomainT>()(cmb_val, x_val);
iterator snd_it = fst_it; snd_it++;
if(snd_it == end_it)
{
// only for the last there can be a rightResid: a part of *it right of x
interval_type rightResid; (*fst_it).KEY_VALUE.right_surplus(rightResid, x_itv);
this->_map.erase(fst_it);
fill(value_type(leftResid, fst_val));
fill(value_type(interSec, cmb_val));
fill(value_type(rightResid, fst_val));
}
else
{
// first AND NOT last
this->_map.erase(fst_it);
fill(value_type(leftResid, fst_val));
fill(value_type(interSec, cmb_val));
subtract_rest<Combinator>(x_itv, x_val, snd_it, end_it);
}
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
template<template<class>class Combinator>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::subtract_rest(const interval_type& x_itv, const CodomainT& x_val, iterator& it, iterator& end_it)
{
iterator nxt_it=it; nxt_it++;
while(nxt_it!=end_it)
{
CodomainT& cur_val = (*it).CONT_VALUE ;
Combinator<CodomainT>()(cur_val, x_val);
if(Traits::absorbs_neutrons() && cur_val==CodomainT())
this->_map.erase(it++);
else it++;
nxt_it=it; nxt_it++;
}
// it refers the last overlaying intervals of x_itv
const interval_type& cur_itv = (*it).KEY_VALUE ;
interval_type rightResid;
cur_itv.right_surplus(rightResid, x_itv);
if(rightResid.empty())
{
CodomainT& cur_val = (*it).CONT_VALUE ;
Combinator<CodomainT>()(cur_val, x_val);
if(Traits::absorbs_neutrons() && cur_val==CodomainT())
this->_map.erase(it);
}
else
{
CodomainT cur_val = (*it).CONT_VALUE ;
CodomainT cmb_val = cur_val ;
Combinator<CodomainT>()(cmb_val, x_val);
interval_type interSec;
cur_itv.intersect(interSec, x_itv);
this->_map.erase(it);
fill(value_type(interSec, cmb_val));
fill(value_type(rightResid, cur_val));
}
}
//-----------------------------------------------------------------------------
// insert(pair(interval,value)):
//-----------------------------------------------------------------------------
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::insert(const value_type& x)
{
const interval_type& x_itv = x.KEY_VALUE;
if(x_itv.empty())
return;
const CodomainT& x_val = x.CONT_VALUE;
if(Traits::absorbs_neutrons() && x_val==CodomainT())
return;
std::pair<typename ImplMapT::iterator,bool>
insertion = this->_map.insert(x);
if(!insertion.WAS_SUCCESSFUL)
{
// Detect the first and the end iterator of the collision sequence
iterator fst_it = this->_map.lower_bound(x_itv);
iterator end_it = insertion.ITERATOR;
if(end_it != this->_map.end())
end_it++;
//assert(end_it == this->_map.upper_bound(x_itv));
interval_type fst_itv = (*fst_it).KEY_VALUE ;
CodomainT cur_val = (*fst_it).CONT_VALUE ;
interval_type leadGap; x_itv.left_surplus(leadGap, fst_itv);
// this is a new Interval that is a gap in the current map
fill_gap<inplace_plus>(value_type(leadGap, x_val));
// only for the first there can be a leftResid: a part of *it left of x
interval_type leftResid; fst_itv.left_surplus(leftResid, x_itv);
// handle special case for first
interval_type interSec;
fst_itv.intersect(interSec, x_itv);
iterator snd_it = fst_it; snd_it++;
if(snd_it == end_it)
{
interval_type endGap; x_itv.right_surplus(endGap, fst_itv);
// this is a new Interval that is a gap in the current map
fill_gap<inplace_plus>(value_type(endGap, x_val));
}
else
{
// shrink interval
interval_type x_rest(x_itv);
x_rest.left_subtract(fst_itv);
insert_rest(x_rest, x_val, snd_it, end_it);
}
}
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::insert_rest(const interval_type& x_itv, const CodomainT& x_val,
iterator& it, iterator& end_it)
{
iterator nxt_it = it; nxt_it++;
interval_type x_rest = x_itv, gap, common, cur_itv;
for(; nxt_it!=end_it; ++it, ++nxt_it)
{
cur_itv = (*it).KEY_VALUE ;
x_rest.left_surplus(gap, cur_itv);
fill_gap<inplace_plus>(value_type(gap, x_val));
// shrink interval
x_rest.left_subtract(cur_itv);
}
insert_rear(x_rest, x_val, it);
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::insert_rear(const interval_type& x_rest, const CodomainT& x_val,
iterator& it)
{
interval_type cur_itv = (*it).KEY_VALUE ;
CodomainT cur_val = (*it).CONT_VALUE ;
interval_type left_gap;
x_rest.left_surplus(left_gap, cur_itv);
fill_gap<inplace_plus>(value_type(left_gap, x_val));
interval_type common;
cur_itv.intersect(common, x_rest);
interval_type end_gap;
x_rest.right_surplus(end_gap, cur_itv);
fill_gap<inplace_plus>(value_type(end_gap, x_val));
}
//-----------------------------------------------------------------------------
// erase(pair(interval,value)):
//-----------------------------------------------------------------------------
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::erase(const value_type& x)
{
const interval_type& x_itv = x.KEY_VALUE;
if(x_itv.empty())
return;
const CodomainT& x_val = x.CONT_VALUE;
if(Traits::absorbs_neutrons() && x_val==CodomainT())
return;
iterator fst_it = this->_map.lower_bound(x_itv);
if(fst_it==this->_map.end()) return;
iterator end_it = this->_map.upper_bound(x_itv);
if(fst_it==end_it) return;
interval_type fst_itv = (*fst_it).KEY_VALUE ;
// must be copies because fst_it will be erased
CodomainT fst_val = (*fst_it).CONT_VALUE ;
// only for the first there can be a leftResid: a part of *it left of x
interval_type leftResid;
fst_itv.left_surplus(leftResid, x_itv);
// handle special case for first
interval_type interSec;
fst_itv.intersect(interSec, x_itv);
iterator snd_it = fst_it; snd_it++;
if(snd_it == end_it)
{
// only for the last there can be a rightResid: a part of *it right of x
interval_type rightResid; (*fst_it).KEY_VALUE.right_surplus(rightResid, x_itv);
if(!interSec.empty() && fst_val == x_val)
{
this->_map.erase(fst_it);
fill(value_type(leftResid, fst_val));
// erased: fill(value_type(interSec, cmb_val));
fill(value_type(rightResid, fst_val));
}
}
else
{
// first AND NOT last
if(!interSec.empty() && fst_val == x_val)
{
this->_map.erase(fst_it);
fill(value_type(leftResid, fst_val));
// erased: fill(value_type(interSec, cmb_val));
}
erase_rest(x_itv, x_val, snd_it, end_it);
}
}
template <typename DomainT, typename CodomainT, class Traits, template<class>class Interval, template<class>class Compare, template<class>class Alloc>
void split_interval_map<DomainT,CodomainT,Traits,Interval,Compare,Alloc>
::erase_rest(const interval_type& x_itv, const CodomainT& x_val,
iterator& it, iterator& end_it)
{
iterator nxt_it=it; nxt_it++;
// For all intervals within loop: it->KEY_VALUE are contained_in x_itv
while(nxt_it!=end_it)
{
if((*it).CONT_VALUE == x_val)
this->_map.erase(it++);
else it++;
nxt_it=it; nxt_it++;
}
// it refers the last overlaying intervals of x_itv
interval_type cur_itv = (*it).KEY_VALUE ;
// Has to be a copy, cause 'it' will be erased
CodomainT cur_val = (*it).CONT_VALUE;
interval_type rightResid;
cur_itv.right_surplus(rightResid, x_itv);
if(rightResid.empty())
{
if(cur_val == x_val)
this->_map.erase(it);
}
else
{
interval_type interSec;
cur_itv.intersect(interSec, x_itv);
if(!interSec.empty() && cur_val == x_val)
{
this->_map.erase(it);
//erased: fill(value_type(interSec, cmb_val));
fill(value_type(rightResid, cur_val));
}
}
}
//-----------------------------------------------------------------------------
// addition += and subtraction -=
//-----------------------------------------------------------------------------
template
<
class SubType,
class DomainT, class CodomainT,
class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc
>
interval_base_map<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc>&
operator +=
(
interval_base_map<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& object,
const split_interval_map<DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& operand
)
{
typedef split_interval_map<DomainT,CodomainT,Traits,
Interval,Compare,Alloc> map_type;
const_FORALL(typename map_type, elem_, operand)
object.add(*elem_);
return object;
}
template
<
class SubType,
class DomainT, class CodomainT,
class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc
>
interval_base_map<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc>&
operator -=
(
interval_base_map<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& object,
const split_interval_map<DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& operand
)
{
typedef split_interval_map<DomainT,CodomainT,Traits,
Interval,Compare,Alloc> map_type;
const_FORALL(typename map_type, elem_, operand)
object.subtract(*elem_);
return object;
}
//-----------------------------------------------------------------------------
// erasure via keysets: map -= key_set
//-----------------------------------------------------------------------------
/*CL ??
template
<
class SetSubType,
class DomainT, class CodomainT,
class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc
>
split_interval_map<DomainT,CodomainT,
Traits,Interval,Compare,Alloc>&
operator -=
(
split_interval_map<DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& object,
const interval_base_set<SetSubType,DomainT,
Interval,Compare,Alloc>& erasure
)
{
typedef interval_base_set<SetSubType,DomainT,
Interval,Compare,Alloc> set_type;
typedef typename split_interval_map<DomainT,CodomainT,
Traits,Interval,Compare,Alloc>::base_type map_base;
const_FORALL(typename set_type, key_, erasure)
static_cast<map_base>(object).erase(*key_);
return object;
}
*/
//-----------------------------------------------------------------------------
// intersection *=
//-----------------------------------------------------------------------------
template
<
class SubType,
class DomainT, class CodomainT,
class Traits, template<class>class Interval,
template<class>class Compare, template<class>class Alloc
>
interval_base_map<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc>&
operator *=
(
interval_base_map<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& object,
const split_interval_map< DomainT,CodomainT,
Traits,Interval,Compare,Alloc>& operand
)
{
typedef interval_base_map
<SubType,DomainT,CodomainT,
Traits,Interval,Compare,Alloc> object_map_type;
typedef split_interval_map
<DomainT,CodomainT,
Traits,Interval,Compare,Alloc> operand_map_type;
if(Traits::emits_neutrons())
return object += operand;
else if(Traits::absorbs_neutrons() && !type<CodomainT>::is_set())
return object += operand;
else
{
object_map_type section;
object.map_intersect(section, operand);
object.swap(section);
return object;
}
}
//-----------------------------------------------------------------------------
// type traits
//-----------------------------------------------------------------------------
template <class KeyT, class DataT, class Traits>
struct type<itl::split_interval_map<KeyT,DataT,Traits> >
{
static bool is_set() { return true; }
static bool is_interval_container() { return true; }
static bool is_interval_splitter() { return true; }
static bool is_neutron_absorber() { return Traits::absorbs_neutrons(); }
static bool is_neutron_emitter() { return Traits::emits_neutrons(); }
static std::string to_string()
{
return "sp_itv_map<"+ type<KeyT>::to_string() + ","
+ type<DataT>::to_string() + ","
+ type<Traits>::to_string() +">";
}
};
} // namespace itl
#endif
| [
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
]
| [
[
[
1,
938
]
]
]
|
dd933f493dabd15f27c11b4992a266ccf8e29d4e | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/vcsintf.hpp | ac115b12079ff70418ba56b8270e5daed27df4bd | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,132 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'VcsIntf.pas' rev: 6.00
#ifndef VcsIntfHPP
#define VcsIntfHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <ToolIntf.hpp> // Pascal unit
#include <VirtIntf.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Vcsintf
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TIVCSClient;
class PASCALIMPLEMENTATION TIVCSClient : public Virtintf::TInterface
{
typedef Virtintf::TInterface inherited;
public:
virtual AnsiString __stdcall GetIDString(void) = 0 ;
virtual void __stdcall ExecuteVerb(int Index) = 0 ;
virtual AnsiString __stdcall GetMenuName(void) = 0 ;
virtual AnsiString __stdcall GetVerb(int Index) = 0 ;
virtual int __stdcall GetVerbCount(void) = 0 ;
virtual Word __stdcall GetVerbState(int Index) = 0 ;
virtual void __stdcall ProjectChange(void) = 0 ;
public:
#pragma option push -w-inl
/* TInterface.Create */ inline __fastcall TIVCSClient(void) : Virtintf::TInterface() { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~TIVCSClient(void) { }
#pragma option pop
};
typedef TIVCSClient* __stdcall (*TVCSManagerInitProc)(Toolintf::TIToolServices* VCSInterface);
//-- var, const, procedure ---------------------------------------------------
#define isVersionControl "Version Control"
#define ivVCSManager "VCSManager"
#define VCSManagerEntryPoint "INITVCS0014"
static const Shortint vsEnabled = 0x1;
static const Shortint vsChecked = 0x2;
} /* namespace Vcsintf */
using namespace Vcsintf;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // VcsIntf
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
66
]
]
]
|
dd4be41ecd4156b11de79125a6138a797df54af9 | f992ff7d77a993c11768dd509c0307f782a13af0 | /Projekt/src/gfx/Drawable.cpp | 374289ac06117b0926d7f111c6f313b9e3426665 | []
| no_license | mariojas/mariusz | 6b0889f3ae623400274ab9448ee8f93556336618 | 965209b0ae0400991b9ceab4c5177b63116302ca | refs/heads/master | 2021-01-23T03:13:01.384598 | 2010-05-03T10:27:47 | 2010-05-03T10:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cpp | #include <allegro.h>
#include "Drawable.h"
void Drawable::draw()
{
blit(me, *parent, x, y, 0, 0, w, h);//chyba starczy
} | [
"ryba@ryb-520fb58ee61.(none)",
"Mariusz@MariuszowyLaptop.(none)"
]
| [
[
[
1,
1
],
[
3,
3
]
],
[
[
2,
2
],
[
4,
7
]
]
]
|
6c974da40da992221f8108e4fbf9e95e33ab91b6 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/NetAccessors/libWWW/BinURLInputStream.hpp | 3c76ecdb65897621ad1c6fe5bb2c6530f2fb668d | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | hpp | /*
* Copyright 1999-2000,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.
*/
/*
* $Id: BinURLInputStream.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(BINURLINPUTSTREAM_HPP)
#define BINURLINPUTSTREAM_HPP
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/util/XMLExceptMsgs.hpp>
#include <xercesc/util/BinInputStream.hpp>
//
// Forward reference the libWWW constructs here, so as to avoid including
// any of the libWWW headers in this file. Just being careful in isolating
// the files that explicitly need to include the libWWW headers.
//
struct _HTAnchor;
XERCES_CPP_NAMESPACE_BEGIN
//
// This class implements the BinInputStream interface specified by the XML
// parser.
//
class XMLUTIL_EXPORT BinURLInputStream : public BinInputStream
{
public :
BinURLInputStream(const XMLURL& urlSource);
~BinURLInputStream();
unsigned int curPos() const;
unsigned int readBytes
(
XMLByte* const toFill
, const unsigned int maxToRead
);
void reset();
unsigned int bytesAvail() const;
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
BinURLInputStream(const BinURLInputStream&);
BinURLInputStream& operator=(const BinURLInputStream&);
// -----------------------------------------------------------------------
// Private data members
//
// fAnchor
// This is the handle that LibWWW returns for the remote file that
// is being addressed.
// fBuffer
// This is the array in which the data is stored after reading it
// of the network. The maximum size of this array is decided in the
// constructor via a file specific #define.
// fBufferIndex
// Its the index into fBuffer and points to the next unprocessed
// character. When the parser asks for more data to be read of the
// stream, then fBuffer[fBufferIndex] is the first byte returned,
// unless fBufferIndex equals fBufferSize indicating that all
// data in the fBuffer has been processed.
// fBufferSize
// This represents the extent of valid data in the fBuffer array.
// fRemoteFileSize
// This stores the size in bytes of the remote file addressed by
// this URL input stream.
// fBytesProcessed
// Its a rolling count of the number of bytes processed off this
// input stream. Its only reset back to zero, if the stream is
// reset. The maximum value this can have is fRemoteFileSize.
// -----------------------------------------------------------------------
struct _HTAnchor* fAnchor;
XMLByte* fBuffer;
unsigned int fBufferIndex;
unsigned int fBufferSize;
int fRemoteFileSize;
unsigned int fBytesProcessed;
MemoryManager* fMemoryManager;
};
XERCES_CPP_NAMESPACE_END
#endif // BINURLINPUTSTREAM_HPP
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
105
]
]
]
|
457a876158462e1471415e89b4f88022cc289a42 | 9891c65690bfc3d774285ccfbd4733c2ad249d5a | /ok/ok/ok.cpp | 7aaeb4130ea48261f616da39f2b8cd51f80ec968 | []
| no_license | saki21/saki21 | 55569cdebd012b861f7b0ca9843caf1a404df0cc | f50ef1b9c5ac305f4edce6a4502ecc6afd104a34 | refs/heads/master | 2021-01-19T07:53:59.989872 | 2010-10-09T15:22:16 | 2010-10-09T15:22:16 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,615 | cpp | // ok.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
#include "ok.h"
#include "MainForm.h"
#include "HistForm.h"
using namespace ok;
App::App() : form(dynamic_cast<Form^>(gcnew ok::MainForm(gcnew EnterPage()))){
form->Show();
form->Closed += gcnew EventHandler(this, &App::OnFormClosed);
}
App ^App::Cre() { app = gcnew App(); return app; }
HistListView ^App::create_hist_form(AuctionItem ^a) {
return (gcnew HistForm(a))->listView1;
}
void EnterPage::UpdateItems() {
if (need_read) go();
set_action_in_div_open_action();
need_read = true;
}
void EnterPage::setsub(String ^id, bool v) {
for (int i = 0; i < SubLength; i++) {
Janru ^j = dynamic_cast<Janru^>(sub[i]);
if (j->id == id) {
listview->off();
if (!v) {
Collections::IEnumerator ^ie = listview->Items->GetEnumerator();
while (ie->MoveNext()) {
AuctionItem^ a = safe_cast<AuctionItem^>(ie->Current);
if (a->SubItems[10]->Text == id)
listview->Items->Remove(a);
}
} else {
for (int i = 0; i < Length; i++) {
if (all[i]->SubItems[10]->Text == id)
listview->Items->Add(all[i]);
}
}
listview->on();
return;
}
}
if (SubLength < 10) {
sub[SubLength] = Janru::Cre(id);
SubLength++;
}
}
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// コントロールが作成される前に、Windows XP ビジュアル効果を有効にします
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(App::Cre());
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
56
]
]
]
|
24115967ba0945f3c5b9483e2de0bc35b18ae36d | a52ab677945cab174095a4f2315a63acf1903567 | /p438/srouter/trunk/.svn/text-base/hclass.hpp.svn-base | 6cc9fdd6993ab49e2f1b8e6972683a39eac8dc16 | []
| no_license | grpatter/iu_cs_jegm | fe5f499c79fbbb7e0cd3d954d4fac95d0a0f631e | 2a2d45eb4f7c5560a945d94a0e4e32f50ca46817 | refs/heads/master | 2021-01-19T18:30:34.722909 | 2009-12-30T02:51:20 | 2009-12-30T02:51:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 745 | #include <string>//to support strings
#include <iostream>
using namespace std;
class EndHosts{
public://vars
int eh_id;
string ext_ip;
string vir_ip;
public://methods
EndHosts();
EndHosts(int eh_id, string ext_ip, string vir_ip);
//destructor
//~EndHosts();
int get_eh_id();
string get_ext_ip();
string get_vir_ip();
};
EndHosts::EndHosts(){
this->eh_id = 0;
this->ext_ip = "";
this->vir_ip = "";
}
EndHosts::EndHosts(int ehid, string extip, string virip){
this->eh_id = ehid;
this->ext_ip = extip;
this->vir_ip = virip;
}
int EndHosts::get_eh_id(){
return this->eh_id;
}
string EndHosts::get_ext_ip(){
return this->ext_ip;
}
string EndHosts::get_vir_ip(){
return this->vir_ip;
}
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
|
893343623c533422b16b1ca0878b8b163bf7e9d7 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/multiplayer/ricochet/cl_dll/vgui_TeamFortressViewport.h | d3d8ad3f4dff9157e2c3d702daf0575bbf208bcc | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,960 | h |
#ifndef TEAMFORTRESSVIEWPORT_H
#define TEAMFORTRESSVIEWPORT_H
#include<VGUI_Panel.h>
#include<VGUI_Frame.h>
#include<VGUI_TextPanel.h>
#include<VGUI_Label.h>
#include<VGUI_Button.h>
#include<VGUI_ActionSignal.h>
#include<VGUI_InputSignal.h>
#include<VGUI_Scheme.h>
#include<VGUI_Image.h>
#include<VGUI_FileInputStream.h>
#include<VGUI_BitmapTGA.h>
#include<VGUI_DesktopIcon.h>
#include<VGUI_App.h>
#include<VGUI_MiniApp.h>
#include<VGUI_LineBorder.h>
#include<VGUI_String.h>
#include<VGUI_ScrollPanel.h>
#include<VGUI_ScrollBar.h>
#include<VGUI_Slider.h>
// custom scheme handling
#include "vgui_SchemeManager.h"
#define TF_DEFS_ONLY
#include "tf_defs.h"
#include "discwar.h"
using namespace vgui;
class Cursor;
class ScorePanel;
class CCommandMenu;
class CommandLabel;
class CommandButton;
class BuildButton;
class ClassButton;
class CMenuPanel;
class ServerBrowser;
class DragNDropPanel;
class CTransparentPanel;
class CDiscPanel;
class CDiscArena_RoundStart;
class CDiscArena_RoundEnd;
class CDiscPowerups;
class CDiscRewards;
char* GetVGUITGAName(const char *pszName);
BitmapTGA *LoadTGAForRes( const char* pImageName );
void ScaleColors( int &r, int &g, int &b, int a );
extern char *sTFClassSelection[];
extern int sTFValidClassInts[];
extern char *sLocalisedClasses[];
extern int iTeamColors[5][3];
#define MAX_SERVERNAME_LENGTH 32
// Use this to set any co-ords in 640x480 space
#define XRES(x) (x * ((float)ScreenWidth / 640))
#define YRES(y) (y * ((float)ScreenHeight / 480))
// Command Menu positions
#define MAX_MENUS 40
#define MAX_BUTTONS 100
#define BUTTON_SIZE_Y YRES(30)
#define CMENU_SIZE_X XRES(160)
#define SUBMENU_SIZE_X (CMENU_SIZE_X / 8)
#define SUBMENU_SIZE_Y (BUTTON_SIZE_Y / 6)
#define CMENU_TOP (BUTTON_SIZE_Y * 4)
#define MAX_TEAMNAME_SIZE 64
#define MAX_BUTTON_SIZE 32
// Map Briefing Window
#define MAPBRIEF_INDENT 30
// Team Menu
#define TMENU_INDENT_X (30 * ((float)ScreenHeight / 640))
#define TMENU_HEADER 100
#define TMENU_SIZE_X (ScreenWidth - (TMENU_INDENT_X * 2))
#define TMENU_SIZE_Y (TMENU_HEADER + BUTTON_SIZE_Y * 7)
#define TMENU_PLAYER_INDENT (((float)TMENU_SIZE_X / 3) * 2)
#define TMENU_INDENT_Y (((float)ScreenHeight - TMENU_SIZE_Y) / 2)
// Class Menu
#define CLMENU_INDENT_X (30 * ((float)ScreenHeight / 640))
#define CLMENU_HEADER 100
#define CLMENU_SIZE_X (ScreenWidth - (CLMENU_INDENT_X * 2))
#define CLMENU_SIZE_Y (CLMENU_HEADER + BUTTON_SIZE_Y * 11)
#define CLMENU_PLAYER_INDENT (((float)CLMENU_SIZE_X / 3) * 2)
#define CLMENU_INDENT_Y (((float)ScreenHeight - CLMENU_SIZE_Y) / 2)
// Discwar icons
#define DISC_ICON_WIDTH XRES(32)
#define DISC_ICON_SPACER XRES(72)
// Arrows
enum
{
ARROW_UP,
ARROW_DOWN,
ARROW_LEFT,
ARROW_RIGHT,
};
//==============================================================================
// VIEWPORT PIECES
//============================================================
// Wrapper for an Image Label without a background
class CImageLabel : public Label
{
public:
BitmapTGA *m_pTGA;
public:
void LoadImage(const char * pImageName);
CImageLabel( const char* pImageName,int x,int y );
CImageLabel( const char* pImageName,int x,int y,int wide,int tall );
virtual int getImageTall();
virtual int getImageWide();
virtual void paintBackground()
{
// Do nothing, so the background's left transparent.
}
};
// Command Label
// Overridden label so we can darken it when submenus open
class CommandLabel : public Label
{
private:
int m_iState;
public:
CommandLabel(const char* text,int x,int y,int wide,int tall) : Label(text,x,y,wide,tall)
{
m_iState = false;
}
void PushUp()
{
m_iState = false;
repaint();
}
void PushDown()
{
m_iState = true;
repaint();
}
};
//============================================================
// Command Buttons
class CommandButton : public Button
{
private:
int m_iPlayerClass;
// Submenus under this button
CCommandMenu *m_pSubMenu;
CCommandMenu *m_pParentMenu;
CommandLabel *m_pSubLabel;
char m_sMainText[MAX_BUTTON_SIZE];
char m_cBoundKey;
SchemeHandle_t m_hTextScheme;
void RecalculateText( void );
public:
bool m_bNoHighlight;
public:
// Constructors
CommandButton( const char* text,int x,int y,int wide,int tall, bool bNoHighlight = false);
CommandButton( int iPlayerClass, const char* text,int x,int y,int wide,int tall);
void Init( void );
// Menu Handling
void AddSubMenu( CCommandMenu *pNewMenu );
void AddSubLabel( CommandLabel *pSubLabel )
{
m_pSubLabel = pSubLabel;
}
virtual int IsNotValid( void )
{
return false;
}
void UpdateSubMenus( int iAdjustment );
int GetPlayerClass() { return m_iPlayerClass; };
CCommandMenu *GetSubMenu() { return m_pSubMenu; };
CCommandMenu *getParentMenu( void );
void setParentMenu( CCommandMenu *pParentMenu );
// Overloaded vgui functions
virtual void paint();
virtual void setText( const char *text );
virtual void paintBackground();
void cursorEntered( void );
void cursorExited( void );
void setBoundKey( char boundKey );
char getBoundKey( void );
};
//============================================================
// Command Menus
class CCommandMenu : public Panel
{
private:
CCommandMenu *m_pParentMenu;
int m_iXOffset;
int m_iYOffset;
// Buttons in this menu
CommandButton *m_aButtons[ MAX_BUTTONS ];
int m_iButtons;
public:
CCommandMenu( CCommandMenu *pParentMenu, int x,int y,int wide,int tall ) : Panel(x,y,wide,tall)
{
m_pParentMenu = pParentMenu;
m_iXOffset = x;
m_iYOffset = y;
m_iButtons = 0;
}
void AddButton( CommandButton *pButton );
bool RecalculateVisibles( int iNewYPos, bool bHideAll );
void RecalculatePositions( int iYOffset );
void MakeVisible( CCommandMenu *pChildMenu );
CCommandMenu *GetParentMenu() { return m_pParentMenu; };
int GetXOffset() { return m_iXOffset; };
int GetYOffset() { return m_iYOffset; };
int GetNumButtons() { return m_iButtons; };
CommandButton *FindButtonWithSubmenu( CCommandMenu *pSubMenu );
void ClearButtonsOfArmedState( void );
bool KeyInput( int keyNum );
virtual void paintBackground();
};
//==============================================================================
class TeamFortressViewport : public Panel
{
private:
vgui::Cursor* _cursorNone;
vgui::Cursor* _cursorArrow;
int m_iInitialized;
CCommandMenu *m_pCommandMenus[ MAX_MENUS ];
CCommandMenu *m_pCurrentCommandMenu;
float m_flMenuOpenTime;
float m_flScoreBoardLastUpdated;
int m_iNumMenus;
int m_iCurrentTeamNumber;
int m_iCurrentPlayerClass;
// VGUI Menus
void CreateSpectatorMenu( void );
// Scheme handler
CSchemeManager m_SchemeManager;
// MOTD
int m_iGotAllMOTD;
char m_szMOTD[ MAX_MOTD_LENGTH ];
// Command Menu Team buttons
CommandButton *m_pTeamButtons[6];
CommandButton *m_pDisguiseButtons[5];
BuildButton *m_pBuildButtons[3];
BuildButton *m_pBuildActiveButtons[3];
// Server Browser
ServerBrowser *m_pServerBrowser;
// Spectator "menu"
Label *m_pSpectatorLabel;
int m_iAllowSpectators;
// Data for specific sections of the Command Menu
int m_iValidClasses[5];
int m_iIsFeigning;
int m_iIsSettingDetpack;
int m_iNumberOfTeams;
int m_iBuildState;
int m_iRandomPC;
char m_sTeamNames[5][MAX_TEAMNAME_SIZE];
// Localisation strings
char m_sDetpackStrings[3][MAX_BUTTON_SIZE];
char m_sMapName[64];
public:
TeamFortressViewport(int x,int y,int wide,int tall);
void Initialize( void );
void CreateCommandMenu( void );
void CreateScoreBoard( void );
void CreateServerBrowser( void );
CommandButton *CreateCustomButton( char *pButtonText, char *pButtonName );
CCommandMenu *CreateDisguiseSubmenu( CommandButton *pButton, CCommandMenu *pParentMenu, const char *commandText );
void CreateDiscIcons( void );
void UpdateCursorState( void );
void UpdateCommandMenu( void );
void UpdateOnPlayerInfo( void );
void UpdateHighlights( void );
void UpdateSpectatorMenu( void );
int KeyInput( int down, int keynum, const char *pszCurrentBinding );
void InputPlayerSpecial( void );
void GetAllPlayersInfo( void );
void DeathMsg( int killer, int victim );
void ShowCommandMenu( void );
void InputSignalHideCommandMenu( void );
void HideCommandMenu( void );
void SetCurrentCommandMenu( CCommandMenu *pNewMenu );
void SetCurrentMenu( CMenuPanel *pMenu );
void ShowScoreBoard( void );
void HideScoreBoard( void );
bool IsScoreBoardVisible( void );
bool AllowedToPrintText( void );
void ShowVGUIMenu( int iMenu );
void HideVGUIMenu( void );
void HideTopMenu( void );
void ToggleServerBrowser( void );
CMenuPanel* CreateTextWindow( int iTextToShow );
CCommandMenu *CreateSubMenu( CommandButton *pButton, CCommandMenu *pParentMenu );
// Data Handlers
int GetValidClasses(int iTeam) { return m_iValidClasses[iTeam]; };
int GetNumberOfTeams() { return m_iNumberOfTeams; };
int GetIsFeigning() { return m_iIsFeigning; };
int GetIsSettingDetpack() { return m_iIsSettingDetpack; };
int GetBuildState() { return m_iBuildState; };
int IsRandomPC() { return m_iRandomPC; };
char *GetTeamName( int iTeam ) { return m_sTeamNames[iTeam]; };
int GetAllowSpectators() { return m_iAllowSpectators; };
// Message Handlers
int MsgFunc_ValClass(const char *pszName, int iSize, void *pbuf );
int MsgFunc_TeamNames(const char *pszName, int iSize, void *pbuf );
int MsgFunc_Feign(const char *pszName, int iSize, void *pbuf );
int MsgFunc_Detpack(const char *pszName, int iSize, void *pbuf );
int MsgFunc_VGUIMenu(const char *pszName, int iSize, void *pbuf );
int MsgFunc_MOTD( const char *pszName, int iSize, void *pbuf );
int MsgFunc_BuildSt( const char *pszName, int iSize, void *pbuf );
int MsgFunc_RandomPC( const char *pszName, int iSize, void *pbuf );
int MsgFunc_ServerName( const char *pszName, int iSize, void *pbuf );
int MsgFunc_ScoreInfo( const char *pszName, int iSize, void *pbuf );
int MsgFunc_TeamScore( const char *pszName, int iSize, void *pbuf );
int MsgFunc_TeamInfo( const char *pszName, int iSize, void *pbuf );
int MsgFunc_Spectator( const char *pszName, int iSize, void *pbuf );
int MsgFunc_AllowSpec( const char *pszName, int iSize, void *pbuf );
// Discwar
int MsgFunc_StartRnd(const char *pszName, int iSize, void *pbuf );
int MsgFunc_EndRnd(const char *pszName, int iSize, void *pbuf );
int MsgFunc_Powerup( const char *pszName, int iSize, void *pbuf );
int MsgFunc_Reward( const char *pszName, int iSize, void *pbuf );
int MsgFunc_Frozen( const char *pszName, int iSize, void *pbuf );
// Input
bool SlotInput( int iSlot );
virtual void paintBackground();
CSchemeManager *GetSchemeManager( void ) { return &m_SchemeManager; }
ScorePanel *GetScoreBoard( void ) { return m_pScoreBoard; }
void *operator new( size_t stAllocateBlock );
public:
// VGUI Menus
CMenuPanel *m_pCurrentMenu;
ScorePanel *m_pScoreBoard;
char m_szServerName[ MAX_SERVERNAME_LENGTH ];
CDiscPanel *m_pDiscIcons[MAX_DISCS];
CDiscArena_RoundStart *m_pDiscStartRound;
CDiscArena_RoundEnd *m_pDiscEndRound;
CDiscPowerups *m_pDiscPowerupWindow;
CDiscRewards *m_pDiscRewardWindow;
CTransparentPanel *m_pSpectatorMenu;
float m_flRewardOpenTime;
int m_iUser1;
int m_iUser2;
int m_iDiscPowerup;
};
//============================================================
// Command Menu Button Handlers
#define MAX_COMMAND_SIZE 256
class CMenuHandler_StringCommand : public ActionSignal
{
protected:
char m_pszCommand[MAX_COMMAND_SIZE];
int m_iCloseVGUIMenu;
public:
CMenuHandler_StringCommand( char *pszCommand )
{
strncpy( m_pszCommand, pszCommand, MAX_COMMAND_SIZE);
m_pszCommand[MAX_COMMAND_SIZE-1] = '\0';
m_iCloseVGUIMenu = false;
}
CMenuHandler_StringCommand( char *pszCommand, int iClose )
{
strncpy( m_pszCommand, pszCommand, MAX_COMMAND_SIZE);
m_pszCommand[MAX_COMMAND_SIZE-1] = '\0';
m_iCloseVGUIMenu = true;
}
virtual void actionPerformed(Panel* panel)
{
gEngfuncs.pfnClientCmd(m_pszCommand);
if (m_iCloseVGUIMenu)
gViewPort->HideTopMenu();
else
gViewPort->HideCommandMenu();
}
};
// This works the same as CMenuHandler_StringCommand, except it watches the string command
// for specific commands, and modifies client vars based upon them.
class CMenuHandler_StringCommandWatch : public CMenuHandler_StringCommand
{
private:
public:
CMenuHandler_StringCommandWatch( char *pszCommand ) : CMenuHandler_StringCommand( pszCommand )
{
}
CMenuHandler_StringCommandWatch( char *pszCommand, int iClose ) : CMenuHandler_StringCommand( pszCommand, iClose )
{
}
virtual void actionPerformed(Panel* panel)
{
CMenuHandler_StringCommand::actionPerformed( panel );
// Try to guess the player's new team (it'll be corrected if it's wrong)
if ( !strcmp( m_pszCommand, "jointeam 1" ) )
g_iTeamNumber = 1;
else if ( !strcmp( m_pszCommand, "jointeam 2" ) )
g_iTeamNumber = 2;
else if ( !strcmp( m_pszCommand, "jointeam 3" ) )
g_iTeamNumber = 3;
else if ( !strcmp( m_pszCommand, "jointeam 4" ) )
g_iTeamNumber = 4;
}
};
// Used instead of CMenuHandler_StringCommand for Class Selection buttons.
// Checks the state of hud_classautokill and kills the player if set
class CMenuHandler_StringCommandClassSelect : public CMenuHandler_StringCommand
{
private:
public:
CMenuHandler_StringCommandClassSelect( char *pszCommand ) : CMenuHandler_StringCommand( pszCommand )
{
}
CMenuHandler_StringCommandClassSelect( char *pszCommand, int iClose ) : CMenuHandler_StringCommand( pszCommand, iClose )
{
}
virtual void actionPerformed(Panel* panel);
};
class CMenuHandler_PopupSubMenuInput : public InputSignal
{
private:
CCommandMenu *m_pSubMenu;
Button *m_pButton;
public:
CMenuHandler_PopupSubMenuInput( Button *pButton, CCommandMenu *pSubMenu )
{
m_pSubMenu = pSubMenu;
m_pButton = pButton;
}
virtual void cursorMoved(int x,int y,Panel* panel)
{
//gViewPort->SetCurrentCommandMenu( m_pSubMenu );
}
virtual void cursorEntered(Panel* panel)
{
gViewPort->SetCurrentCommandMenu( m_pSubMenu );
if (m_pButton)
m_pButton->setArmed(true);
};
virtual void cursorExited(Panel* Panel) {};
virtual void mousePressed(MouseCode code,Panel* panel) {};
virtual void mouseDoublePressed(MouseCode code,Panel* panel) {};
virtual void mouseReleased(MouseCode code,Panel* panel) {};
virtual void mouseWheeled(int delta,Panel* panel) {};
virtual void keyPressed(KeyCode code,Panel* panel) {};
virtual void keyTyped(KeyCode code,Panel* panel) {};
virtual void keyReleased(KeyCode code,Panel* panel) {};
virtual void keyFocusTicked(Panel* panel) {};
};
class CMenuHandler_LabelInput : public InputSignal
{
private:
ActionSignal *m_pActionSignal;
public:
CMenuHandler_LabelInput( ActionSignal *pSignal )
{
m_pActionSignal = pSignal;
}
virtual void mousePressed(MouseCode code,Panel* panel)
{
m_pActionSignal->actionPerformed( panel );
}
virtual void mouseReleased(MouseCode code,Panel* panel) {};
virtual void cursorEntered(Panel* panel) {};
virtual void cursorExited(Panel* Panel) {};
virtual void cursorMoved(int x,int y,Panel* panel) {};
virtual void mouseDoublePressed(MouseCode code,Panel* panel) {};
virtual void mouseWheeled(int delta,Panel* panel) {};
virtual void keyPressed(KeyCode code,Panel* panel) {};
virtual void keyTyped(KeyCode code,Panel* panel) {};
virtual void keyReleased(KeyCode code,Panel* panel) {};
virtual void keyFocusTicked(Panel* panel) {};
};
#define HIDE_TEXTWINDOW 0
#define SHOW_MAPBRIEFING 1
#define SHOW_CLASSDESC 2
#define SHOW_MOTD 3
class CMenuHandler_TextWindow : public ActionSignal
{
private:
int m_iState;
public:
CMenuHandler_TextWindow( int iState )
{
m_iState = iState;
}
virtual void actionPerformed(Panel* panel)
{
if (m_iState == HIDE_TEXTWINDOW)
{
gViewPort->HideTopMenu();
}
else
{
gViewPort->HideCommandMenu();
gViewPort->ShowVGUIMenu( m_iState );
}
}
};
class CDragNDropHandler : public InputSignal
{
private:
DragNDropPanel* m_pPanel;
bool m_bDragging;
int m_iaDragOrgPos[2];
int m_iaDragStart[2];
public:
CDragNDropHandler(DragNDropPanel* pPanel)
{
m_pPanel = pPanel;
m_bDragging = false;
}
void cursorMoved(int x,int y,Panel* panel);
void mousePressed(MouseCode code,Panel* panel);
void mouseReleased(MouseCode code,Panel* panel);
void mouseDoublePressed(MouseCode code,Panel* panel) {};
void cursorEntered(Panel* panel) {};
void cursorExited(Panel* panel) {};
void mouseWheeled(int delta,Panel* panel) {};
void keyPressed(KeyCode code,Panel* panel) {};
void keyTyped(KeyCode code,Panel* panel) {};
void keyReleased(KeyCode code,Panel* panel) {};
void keyFocusTicked(Panel* panel) {};
};
class CHandler_MenuButtonOver : public InputSignal
{
private:
int m_iButton;
CMenuPanel *m_pMenuPanel;
public:
CHandler_MenuButtonOver( CMenuPanel *pPanel, int iButton )
{
m_iButton = iButton;
m_pMenuPanel = pPanel;
}
void cursorEntered(Panel *panel);
void cursorMoved(int x,int y,Panel* panel) {};
void mousePressed(MouseCode code,Panel* panel) {};
void mouseReleased(MouseCode code,Panel* panel) {};
void mouseDoublePressed(MouseCode code,Panel* panel) {};
void cursorExited(Panel* panel) {};
void mouseWheeled(int delta,Panel* panel) {};
void keyPressed(KeyCode code,Panel* panel) {};
void keyTyped(KeyCode code,Panel* panel) {};
void keyReleased(KeyCode code,Panel* panel) {};
void keyFocusTicked(Panel* panel) {};
};
class CHandler_ButtonHighlight : public InputSignal
{
private:
Button *m_pButton;
public:
CHandler_ButtonHighlight( Button *pButton )
{
m_pButton = pButton;
}
virtual void cursorEntered(Panel* panel)
{
m_pButton->setArmed(true);
};
virtual void cursorExited(Panel* Panel)
{
m_pButton->setArmed(false);
};
virtual void mousePressed(MouseCode code,Panel* panel) {};
virtual void mouseReleased(MouseCode code,Panel* panel) {};
virtual void cursorMoved(int x,int y,Panel* panel) {};
virtual void mouseDoublePressed(MouseCode code,Panel* panel) {};
virtual void mouseWheeled(int delta,Panel* panel) {};
virtual void keyPressed(KeyCode code,Panel* panel) {};
virtual void keyTyped(KeyCode code,Panel* panel) {};
virtual void keyReleased(KeyCode code,Panel* panel) {};
virtual void keyFocusTicked(Panel* panel) {};
};
//-----------------------------------------------------------------------------
// Purpose: Special handler for highlighting of command menu buttons
//-----------------------------------------------------------------------------
class CHandler_CommandButtonHighlight : public CHandler_ButtonHighlight
{
private:
CommandButton *m_pCommandButton;
public:
CHandler_CommandButtonHighlight( CommandButton *pButton ) : CHandler_ButtonHighlight( pButton )
{
m_pCommandButton = pButton;
}
virtual void cursorEntered( Panel *panel )
{
m_pCommandButton->cursorEntered();
}
virtual void cursorExited( Panel *panel )
{
m_pCommandButton->cursorExited();
}
};
//================================================================
// Overidden Command Buttons for special visibilities
class ClassButton : public CommandButton
{
protected:
int m_iPlayerClass;
public:
ClassButton( int iClass, const char* text,int x,int y,int wide,int tall, bool bNoHighlight ) : CommandButton( text,x,y,wide,tall, bNoHighlight)
{
m_iPlayerClass = iClass;
}
virtual int IsNotValid();
};
class TeamButton : public CommandButton
{
private:
int m_iTeamNumber;
public:
TeamButton( int iTeam, const char* text,int x,int y,int wide,int tall ) : CommandButton( text,x,y,wide,tall)
{
m_iTeamNumber = iTeam;
}
virtual int IsNotValid()
{
int iTeams = gViewPort->GetNumberOfTeams();
// Never valid if there's only 1 team
if (iTeams == 1)
return true;
// Auto Team's always visible
if (m_iTeamNumber == 5)
return false;
if (iTeams >= m_iTeamNumber && m_iTeamNumber != g_iTeamNumber)
return false;
return true;
}
};
class FeignButton : public CommandButton
{
private:
int m_iFeignState;
public:
FeignButton( int iState, const char* text,int x,int y,int wide,int tall ) : CommandButton( text,x,y,wide,tall)
{
m_iFeignState = iState;
}
virtual int IsNotValid()
{
// Only visible for spies
if (g_iPlayerClass != PC_SPY)
return true;
if (m_iFeignState == gViewPort->GetIsFeigning())
return false;
return true;
}
};
class SpectateButton : public CommandButton
{
public:
SpectateButton( const char* text,int x,int y,int wide,int tall, bool bNoHighlight ) : CommandButton( text,x,y,wide,tall, bNoHighlight)
{
}
virtual int IsNotValid()
{
// Only visible if the server allows it
if ( gViewPort->GetAllowSpectators() != 0 )
return false;
return true;
}
};
#define DISGUISE_TEAM1 (1<<0)
#define DISGUISE_TEAM2 (1<<1)
#define DISGUISE_TEAM3 (1<<2)
#define DISGUISE_TEAM4 (1<<3)
class DisguiseButton : public CommandButton
{
private:
int m_iValidTeamsBits;
int m_iThisTeam;
public:
DisguiseButton( int iValidTeamNumsBits, const char* text,int x,int y,int wide,int tall ) : CommandButton( text,x,y,wide,tall,false )
{
m_iValidTeamsBits = iValidTeamNumsBits;
}
virtual int IsNotValid()
{
// Only visible for spies
if ( g_iPlayerClass != PC_SPY )
return true;
// if it's not tied to a specific team, then always show (for spies)
if ( !m_iValidTeamsBits )
return false;
// if we're tied to a team make sure we can change to that team
int iTmp = 1 << (gViewPort->GetNumberOfTeams() - 1);
if ( m_iValidTeamsBits & iTmp )
return false;
return true;
}
};
class DetpackButton : public CommandButton
{
private:
int m_iDetpackState;
public:
DetpackButton( int iState, const char* text,int x,int y,int wide,int tall ) : CommandButton( text,x,y,wide,tall)
{
m_iDetpackState = iState;
}
virtual int IsNotValid()
{
// Only visible for demomen
if (g_iPlayerClass != PC_DEMOMAN)
return true;
if (m_iDetpackState == gViewPort->GetIsSettingDetpack())
return false;
return true;
}
};
extern int iBuildingCosts[];
#define BUILDSTATE_HASBUILDING (1<<0) // Data is building ID (1 = Dispenser, 2 = Sentry)
#define BUILDSTATE_BUILDING (1<<1)
#define BUILDSTATE_BASE (1<<2)
#define BUILDSTATE_CANBUILD (1<<3) // Data is building ID (0 = Dispenser, 1 = Sentry)
class BuildButton : public CommandButton
{
private:
int m_iBuildState;
int m_iBuildData;
public:
enum Buildings
{
DISPENSER = 0,
SENTRYGUN = 1,
};
BuildButton( int iState, int iData, const char* text,int x,int y,int wide,int tall ) : CommandButton( text,x,y,wide,tall)
{
m_iBuildState = iState;
m_iBuildData = iData;
}
virtual int IsNotValid()
{
// Only visible for engineers
if (g_iPlayerClass != PC_ENGINEER)
return true;
// If this isn't set, it's only active when they're not building
if (m_iBuildState & BUILDSTATE_BUILDING)
{
// Make sure the player's building
if ( !(gViewPort->GetBuildState() & BS_BUILDING) )
return true;
}
else
{
// Make sure the player's not building
if ( gViewPort->GetBuildState() & BS_BUILDING )
return true;
}
if (m_iBuildState & BUILDSTATE_BASE)
{
// Only appear if we've got enough metal to build something, or something already built
if ( gViewPort->GetBuildState() & (BS_HAS_SENTRYGUN | BS_HAS_DISPENSER | BS_CANB_SENTRYGUN | BS_CANB_DISPENSER) )
return false;
return true;
}
// Must have a building
if (m_iBuildState & BUILDSTATE_HASBUILDING)
{
if ( m_iBuildData == BuildButton::DISPENSER && !(gViewPort->GetBuildState() & BS_HAS_DISPENSER) )
return true;
if ( m_iBuildData == BuildButton::SENTRYGUN && !(gViewPort->GetBuildState() & BS_HAS_SENTRYGUN) )
return true;
}
// Can build something
if (m_iBuildState & BUILDSTATE_CANBUILD)
{
// Make sure they've got the ammo and don't have one already
if ( m_iBuildData == BuildButton::DISPENSER && (gViewPort->GetBuildState() & BS_CANB_DISPENSER) )
return false;
if ( m_iBuildData == BuildButton::SENTRYGUN && (gViewPort->GetBuildState() & BS_CANB_SENTRYGUN) )
return false;
return true;
}
return false;
}
};
#define MAX_MAPNAME 256
class MapButton : public CommandButton
{
private:
char m_szMapName[ MAX_MAPNAME ];
public:
MapButton( const char *pMapName, const char* text,int x,int y,int wide,int tall ) : CommandButton( text,x,y,wide,tall)
{
sprintf( m_szMapName, "maps/%s.bsp", pMapName );
}
virtual int IsNotValid()
{
const char *level = gEngfuncs.pfnGetLevelName();
if (!level)
return true;
// Does it match the current map name?
if ( strcmp(m_szMapName, level) )
return true;
return false;
}
};
//-----------------------------------------------------------------------------
// Purpose: CommandButton which is only displayed if the player is on team X
//-----------------------------------------------------------------------------
class TeamOnlyCommandButton : public CommandButton
{
private:
int m_iTeamNum;
public:
TeamOnlyCommandButton( int iTeamNum, const char* text,int x,int y,int wide,int tall ) :
CommandButton( text, x, y, wide, tall ), m_iTeamNum(iTeamNum) {}
virtual int IsNotValid()
{
if ( g_iTeamNumber != m_iTeamNum )
return true;
return CommandButton::IsNotValid();
}
};
//============================================================
// Panel that can be dragged around
class DragNDropPanel : public Panel
{
private:
bool m_bBeingDragged;
LineBorder *m_pBorder;
public:
DragNDropPanel(int x,int y,int wide,int tall) : Panel(x,y,wide,tall)
{
m_bBeingDragged = false;
// Create the Drag Handler
addInputSignal( new CDragNDropHandler(this) );
// Create the border (for dragging)
m_pBorder = new LineBorder();
}
virtual void setDragged( bool bState )
{
m_bBeingDragged = bState;
if (m_bBeingDragged)
setBorder(m_pBorder);
else
setBorder(NULL);
}
};
//================================================================
// Panel that draws itself with a transparent black background
class CTransparentPanel : public Panel
{
private:
int m_iTransparency;
public:
CTransparentPanel(int iTrans, int x,int y,int wide,int tall) : Panel(x,y,wide,tall)
{
m_iTransparency = iTrans;
}
virtual void paintBackground()
{
if (m_iTransparency)
{
// Transparent black background
drawSetColor( 0,0,0, m_iTransparency );
drawFilledRect(0,0,_size[0],_size[1]);
}
}
};
//================================================================
// Menu Panel that supports buffering of menus
class CMenuPanel : public CTransparentPanel
{
private:
CMenuPanel *m_pNextMenu;
int m_iMenuID;
int m_iRemoveMe;
int m_iIsActive;
float m_flOpenTime;
public:
CMenuPanel(int iRemoveMe, int x,int y,int wide,int tall) : CTransparentPanel(100, x,y,wide,tall)
{
Reset();
m_iRemoveMe = iRemoveMe;
}
CMenuPanel(int iTrans, int iRemoveMe, int x,int y,int wide,int tall) : CTransparentPanel(iTrans, x,y,wide,tall)
{
Reset();
m_iRemoveMe = iRemoveMe;
}
virtual void Reset( void )
{
m_pNextMenu = NULL;
m_iIsActive = false;
m_flOpenTime = 0;
}
void SetNextMenu( CMenuPanel *pNextPanel )
{
if (m_pNextMenu)
m_pNextMenu->SetNextMenu( pNextPanel );
else
m_pNextMenu = pNextPanel;
}
void SetMenuID( int iID )
{
m_iMenuID = iID;
}
void SetActive( int iState )
{
m_iIsActive = iState;
}
virtual void Open( void )
{
setVisible( true );
// Note the open time, so we can delay input for a bit
m_flOpenTime = gHUD.m_flTime;
}
virtual void Close( void )
{
setVisible( false );
m_iIsActive = false;
if ( m_iRemoveMe )
gViewPort->removeChild( this );
// This MenuPanel has now been deleted. Don't append code here.
}
int ShouldBeRemoved() { return m_iRemoveMe; };
CMenuPanel* GetNextMenu() { return m_pNextMenu; };
int GetMenuID() { return m_iMenuID; };
int IsActive() { return m_iIsActive; };
float GetOpenTime() { return m_flOpenTime; };
// Numeric input
virtual bool SlotInput( int iSlot ) { return false; };
virtual void SetActiveInfo( int iInput ) {};
};
//================================================================
// Custom drawn scroll bars
class CTFScrollButton : public CommandButton
{
private:
BitmapTGA *m_pTGA;
public:
CTFScrollButton(int iArrow, const char* text,int x,int y,int wide,int tall);
virtual void paint( void );
virtual void paintBackground( void );
};
// Custom drawn slider bar
class CTFSlider : public Slider
{
public:
CTFSlider(int x,int y,int wide,int tall,bool vertical) : Slider(x,y,wide,tall,vertical)
{
};
virtual void paintBackground( void );
};
// Custom drawn scrollpanel
class CTFScrollPanel : public ScrollPanel
{
public:
CTFScrollPanel(int x,int y,int wide,int tall);
};
//================================================================
// Specific Menus to handle old HUD sections
class CHealthPanel : public DragNDropPanel
{
private:
BitmapTGA *m_pHealthTGA;
Label *m_pHealthLabel;
public:
CHealthPanel(int x,int y,int wide,int tall) : DragNDropPanel(x,y,wide,tall)
{
// Load the Health icon
FileInputStream* fis = new FileInputStream( GetVGUITGAName("%d_hud_health"), false);
m_pHealthTGA = new BitmapTGA(fis,true);
fis->close();
// Create the Health Label
int iXSize,iYSize;
m_pHealthTGA->getSize(iXSize,iYSize);
m_pHealthLabel = new Label("",0,0,iXSize,iYSize);
m_pHealthLabel->setImage(m_pHealthTGA);
m_pHealthLabel->setParent(this);
// Set panel dimension
// Shouldn't be needed once Billy's fized setImage not recalculating the size
//setSize( iXSize + 100, gHUD.m_iFontHeight + 10 );
//m_pHealthLabel->setPos( 10, (getTall() - iYSize) / 2 );
}
virtual void paintBackground()
{
}
void paint()
{
// Get the paint color
int r,g,b,a;
// Has health changed? Flash the health #
if (gHUD.m_Health.m_fFade)
{
gHUD.m_Health.m_fFade -= (gHUD.m_flTimeDelta * 20);
if (gHUD.m_Health.m_fFade <= 0)
{
a = MIN_ALPHA;
gHUD.m_Health.m_fFade = 0;
}
// Fade the health number back to dim
a = MIN_ALPHA + (gHUD.m_Health.m_fFade/FADE_TIME) * 128;
}
else
a = MIN_ALPHA;
gHUD.m_Health.GetPainColor( r, g, b );
ScaleColors(r, g, b, a );
// If health is getting low, make it bright red
if (gHUD.m_Health.m_iHealth <= 15)
a = 255;
int iXSize,iYSize, iXPos, iYPos;
m_pHealthTGA->getSize(iXSize,iYSize);
m_pHealthTGA->getPos(iXPos, iYPos);
// Paint the player's health
int x = gHUD.DrawHudNumber( iXPos + iXSize + 5, iYPos + 5, DHN_3DIGITS | DHN_DRAWZERO, gHUD.m_Health.m_iHealth, r, g, b);
// Draw the vertical line
int HealthWidth = gHUD.GetSpriteRect(gHUD.m_HUD_number_0).right - gHUD.GetSpriteRect(gHUD.m_HUD_number_0).left;
x += HealthWidth / 2;
FillRGBA(x, iYPos + 5, HealthWidth / 10, gHUD.m_iFontHeight, 255, 160, 0, a);
}
};
#endif
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
1207
]
]
]
|
3ab7fae49dc475bd57b8435a2c844bfcf1de4c8b | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Utilities/include/BaseComponent.h | f56020394c34b567ab5735095427e6cffef4ecf1 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,485 | h | #pragma once
#ifndef __BASE_COMPONENT_H__
#define __BASE_COMPONENT_H__
// NO INCLOURE AQUEST ARXIU !!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!
// incloure "EntityDefines.h"
#include "base.h"
#ifndef __ENTITY_DEFINES_H__
#error S'ha d'incloure "EntityDefines.h" i no "BaseComponent.h"
#endif
#include "EntityDefines.h"
//---- forward declarations --
class CGameEntity;
class CRenderManager;
// ---------------------------
class CBaseComponent:
public CBaseControl
{
public:
enum Type {
ECT_OBJECT_3D,
ECT_MOVEMENT,
ECT_ROTATIVE,
ECT_PLAYER_CONTROLLER,
ECT_IA_WALK_TO_PLAYER,
ECT_PHYSX_CONTROLLER,
ECT_PHYSX_ACTOR,
ECT_ANIMATION,
ECT_RENDERABLE_OBJECT,
ECT_3RD_PERSON_SHOOTER_CAMERA,
ECT_TRIGGER,
ECT_ENERGY,
ECT_LASER,
ECT_IA_BRAIN,
ECT_IA_BRAIN_VIGIA,
ECT_VIDA,
ECT_DOOR,
ECT_INTERACTIVE,
ECT_DESTROYABLE,
ECT_SPAWNER,
ECT_STATE_MACHINE,
ECT_BGM,
ECT_SOUND,
ECT_RAGDOLL,
ECT_COVER,
ECT_MIRILLA,
ECT_SHIELD,
ECT_ARMA,
ECT_NAV_NODE,
ECT_EMITER,
ECT_BILLBOARD,
ECT_OMNI,
ECT_PARTICLE_SHOOT_PLAYER,
ECT_PARTICLE_SHOOT_MINER,
ECT_PARTICLE_SHOOT_MILITAR,
ECT_COLLISION_REPORT,
ECT_EXPLOSIVE,
ECT_LIFETIME,
ECT_DELAYED_SCRIPT,
ECT_SOUND_LISTENER,
ECT_PHYSXSPHERE,
ECT_CYNEMATIC_CAMERA
};
virtual Type GetType() = 0; //{return m_Type;};
bool IsType(Type _Type) {return GetType() == _Type;};
CGameEntity* GetEntity() const {return m_pEntity;};
virtual void ReceiveEvent(const SEvent& _Event) {};
void SetActive(bool _bActive);
bool IsActive() {return m_bActive;};
//updates
virtual void PreUpdate(float _fDeltaTime) {};
virtual void Update(float _fDeltaTime) {};
virtual void UpdatePrePhysX(float _fDeltaTime) {};
virtual void UpdatePostPhysX(float _fDeltaTime) {};
virtual void UpdatePostAnim(float _fDeltaTime) {};
virtual void PostUpdate(float _fDeltaTime) {};
virtual void DebugRender(CRenderManager*) {};
virtual bool UpdateInPause() const {return false;};
protected:
CBaseComponent():m_pEntity(0),m_bActive(true) {};
void SetEntity(CGameEntity* _pEntity);
virtual void Enable(void) {};
virtual void Disable(void) {};
private:
bool m_bActive;
//EComponentType m_Type;
CGameEntity* m_pEntity;
};
#endif | [
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485",
"mudarra@576ee6d0-068d-96d9-bff2-16229cd70485",
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485",
"galindix@576ee6d0-068d-96d9-bff2-16229cd70485",
"edual1985@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
29
],
[
31,
32
],
[
36,
38
],
[
40,
41
],
[
63,
63
],
[
70,
77
],
[
81,
92
],
[
95,
95
],
[
97,
98
],
[
102,
102
],
[
106,
110
]
],
[
[
30,
30
],
[
33,
34
],
[
44,
47
],
[
49,
50
],
[
53,
53
],
[
55,
55
],
[
64,
64
]
],
[
[
35,
35
],
[
39,
39
],
[
42,
43
],
[
48,
48
],
[
51,
51
],
[
59,
59
],
[
62,
62
],
[
67,
67
],
[
78,
80
],
[
96,
96
],
[
99,
101
],
[
103,
105
]
],
[
[
52,
52
],
[
54,
54
],
[
65,
65
]
],
[
[
56,
56
],
[
60,
61
]
],
[
[
57,
58
],
[
66,
66
],
[
68,
69
],
[
93,
94
]
]
]
|
18ff6117715f10174bcd4471ad24ea98d453d9a0 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_cwctype_fail.cpp | 17b1b164f10a9322cb539b35a1e3726b6d103e19 | []
| 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 | UTF-8 | C++ | false | false | 1,149 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to 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/config for the most recent version.
// Test file for macro BOOST_NO_CWCTYPE
// This file should not compile, if it does then
// BOOST_NO_CWCTYPE need not be defined.
// see boost_no_cwctype.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_cwctype.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_NO_CWCTYPE
#include "boost_no_cwctype.ipp"
#else
#error "this file should not compile"
#endif
int main( int, char *[] )
{
return boost_no_cwctype::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
39
]
]
]
|
55ebd7e32bda9be55e96f5da9dcc463da5991360 | 6cd6ceebdc936511db968770e3384a391e1c1072 | /GUI/systemTray.cpp | 633f94d8d4ae07c08850cda73dac8b62fb94c59e | []
| no_license | AngryPowman/smalltranslator | 1fb70adf2e814493854964bf1274cabf93a60b49 | 65b54c54b59538632c2eba677c13589e81d0e4e3 | refs/heads/master | 2021-01-13T00:52:35.200448 | 2009-02-17T01:42:21 | 2009-02-17T01:42:21 | 51,979,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,849 | cpp | #include "stdafx.h"
#include "systemTray.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNAMIC(CSystemTray, CObject)
/////////////////////////////////////////////////
// CSystemTray construction/creation/destruction
// systemtray.cpp
CSystemTray::CSystemTray()
{
memset(&m_tnd,0,sizeof(m_tnd));
m_bEnabled=FALSE;
m_bHidden=FALSE;
}
CSystemTray::CSystemTray(CWnd* pWnd,UINT uCallbackMessage,LPCTSTR szToolTip,HICON icon,UINT uID)
{
Create(pWnd,uCallbackMessage,szToolTip,icon,uID);
m_bHidden=FALSE;
}
BOOL CSystemTray::Create(CWnd* pWnd,UINT uCallbackMessage,LPCTSTR szToolTip,HICON icon,UINT uID)
{
// this is only for Windows 95 (or higher)
VERIFY(m_bEnabled=(GetVersion()&0xff)>=4);
if(!m_bEnabled)
return FALSE;
//Make sure Notification window is valid
VERIFY(m_bEnabled=(pWnd && ::IsWindow(pWnd->GetSafeHwnd())));
if (!m_bEnabled)
return FALSE;
//Make sure we avoid conflict with other messages
ASSERT(uCallbackMessage >= WM_USER);
//Tray only supports tooltip text up to 64 characters
ASSERT(_tcslen(szToolTip) <= 64);
// load up the NOTIFYICONDATA structure
m_tnd.cbSize = sizeof(NOTIFYICONDATA);
m_tnd.hWnd = pWnd->GetSafeHwnd();
m_tnd.uID = uID;
m_tnd.hIcon = icon;
m_tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
m_tnd.uCallbackMessage = uCallbackMessage;
strcpy(m_tnd.szTip,szToolTip);
// Set the tray icon
m_pFrame = (CFrameWnd*)pWnd;
VERIFY(m_bEnabled = Shell_NotifyIcon(NIM_ADD, &m_tnd));
return m_bEnabled;
}
CSystemTray::~CSystemTray()
{
RemoveIcon();
}
/////////////////////////////////////////////
// CSystemTray icon manipulation
void CSystemTray::MoveToRight()
{
HideIcon();
ShowIcon();
}
void CSystemTray::RemoveIcon()
{
if(!m_bEnabled)
return;
m_tnd.uFlags = 0;
Shell_NotifyIcon(NIM_DELETE, &m_tnd);
m_bEnabled = FALSE;
}
void CSystemTray::HideIcon()
{
if (m_bEnabled && !m_bHidden)
{
m_tnd.uFlags = NIF_ICON;
Shell_NotifyIcon(NIM_DELETE,&m_tnd);
m_bHidden = TRUE;
}
}
void CSystemTray::ShowIcon()
{
if (m_bEnabled && m_bHidden)
{
m_tnd.uFlags = NIF_MESSAGE|NIF_ICON|NIF_TIP;
Shell_NotifyIcon(NIM_ADD, &m_tnd);
m_bHidden = FALSE;
}
}
BOOL CSystemTray::SetIcon(HICON hIcon)
{
if (!m_bEnabled)
return FALSE;
m_tnd.uFlags = NIF_ICON;
m_tnd.hIcon = hIcon;
return Shell_NotifyIcon(NIM_MODIFY,&m_tnd);
}
BOOL CSystemTray::SetIcon(LPCTSTR lpszIconName)
{
HICON hIcon = AfxGetApp()->LoadIcon(lpszIconName);
return SetIcon(hIcon);
}
BOOL CSystemTray::SetIcon(UINT nIDResource)
{
HICON hIcon = AfxGetApp()->LoadIcon(nIDResource);
return SetIcon(hIcon);
}
BOOL CSystemTray::SetStandardIcon(LPCTSTR lpIconName)
{
HICON hIcon = LoadIcon(NULL, lpIconName);
return SetIcon(hIcon);
}
BOOL CSystemTray::SetStandardIcon(UINT nIDResource)
{
HICON hIcon = ::LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(nIDResource));
return SetIcon(hIcon);
}
HICON CSystemTray::GetIcon() const
{
HICON hIcon = NULL;
if (m_bEnabled)
hIcon = m_tnd.hIcon;
return hIcon;
}
//////////////////////////////////////////////////
// CSystemTray tooltip text manipulation
BOOL CSystemTray::SetTooltipText(LPCTSTR pszTip)
{
if (!m_bEnabled)
return FALSE;
m_tnd.uFlags = NIF_TIP;
_tcscpy(m_tnd.szTip, pszTip);
return Shell_NotifyIcon(NIM_MODIFY, &m_tnd);
}
BOOL CSystemTray::SetTooltipText(UINT nID)
{
CString strText;
VERIFY(strText.LoadString(nID));
return SetTooltipText(strText);
}
CString CSystemTray::GetTooltipText() const
{
CString strText;
if (m_bEnabled)
strText = m_tnd.szTip;
return strText;
}
////////////////////////////////////////////////
// CSystemTray notification window stuff
BOOL CSystemTray::SetNotificationWnd(CWnd* pWnd)
{
if (!m_bEnabled)
return FALSE;
//Make sure Notification window is valid
ASSERT(pWnd && ::IsWindow(pWnd->GetSafeHwnd()));
m_tnd.hWnd = pWnd->GetSafeHwnd();
m_tnd.uFlags = 0;
return Shell_NotifyIcon(NIM_MODIFY, &m_tnd);
}
CWnd* CSystemTray::GetNotificationWnd() const
{
return CWnd::FromHandle(m_tnd.hWnd);
} | [
"thewintersun@47b1f2b0-5e4c-0410-92d4-570404a9583c"
]
| [
[
[
1,
205
]
]
]
|
bbb955cfd72ab65635bee28831a1c29f5a4bae44 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib-test/mgl_test/AFチュートリアル/tutorial_2A.cpp | 8860ce3109e860c4f3016ef9cfa68159b7bb4045 | []
| 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 | 641 | cpp | #include "stdafx.h"
// メインフレームクラス
class CMglTestFrame : public CMglguiWindow
{
private:
CMglAghImage m_img;
public:
// 初期化時に呼ばれる
void OnInit(){
m_img.Load("test.jpg");
CMglguiWindow::RegistControl(&m_img);
}
// クリック時に呼ばれる
void OnLButtonDown(int x, int y){
::MessageBox(NULL,"test","test",NULL);
}
};
CMglTestFrame g_frame;
// WinMain
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
g_frame.Start();
return 0;
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
]
| [
[
[
1,
29
]
]
]
|
5b383bbf76b4ad76475904674531eac4d6f6858f | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/Explosion.cpp | 664942e13baf4529d8310cd3ea6efe3750d47e44 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,785 | cpp | // ----------------------------------------------------------------------- //
//
// MODULE : Explosion.cpp
//
// PURPOSE : Explosion - Definition
//
// CREATED : 11/25/97
//
// (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "Explosion.h"
#include "iltserver.h"
#include "ServerUtilities.h"
#include "WeaponFXTypes.h"
#include "ObjectMsgs.h"
#include "ParsedMsg.h"
#include "DamageTypes.h"
#include "SharedFXStructs.h"
#include "SFXMsgIds.h"
#include "Character.h"
#define MIN_RADIUS_PERCENT 0.25f
LINKFROM_MODULE( Explosion );
#pragma force_active on
BEGIN_CLASS(Explosion)
ADD_STRINGPROP_FLAG(ImpactFXName, "", PF_STATICLIST)
ADD_STRINGPROP_FLAG(DamageType, "EXPLODE", PF_STATICLIST)
ADD_REALPROP_FLAG(DamageRadius, 200.0f, PF_RADIUS)
ADD_REALPROP_FLAG(MaxDamage, 200.0f, 0)
ADD_BOOLPROP_FLAG(RemoveWhenDone, LTTRUE, 0)
END_CLASS_DEFAULT_FLAGS_PLUGIN(Explosion, GameBase, NULL, NULL, 0, CExplosionPlugin)
#pragma force_active off
CMDMGR_BEGIN_REGISTER_CLASS( Explosion )
CMDMGR_ADD_MSG( START, 1, NULL, "START" )
CMDMGR_ADD_MSG( ON, 1, NULL, "ON" )
CMDMGR_END_REGISTER_CLASS( Explosion, GameBase )
bool ExplosionFilterFn(HOBJECT hObj, void *pUserData)
{
uint32 dwFlags;
g_pCommonLT->GetObjectFlags(hObj, OFT_Flags, dwFlags);
if (!(dwFlags & FLAG_SOLID))
{
return false;
}
else if (IsMainWorld(hObj) || (OT_WORLDMODEL == GetObjectType(hObj)))
{
return true;
}
return false;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::Explosion()
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
Explosion::Explosion() : GameBase()
{
m_fDamageRadius = 200.0f;
m_fMaxDamage = 200.0f;
m_eDamageType = DT_UNSPECIFIED;
// For now these aren't used with DEdit created Explosions...
m_fProgDamage = 0.0f;
m_fProgDamageDuration = 0.0f;
m_fProgDamageRadius = 0.0f;
m_fProgDamageLifetime = 0.0f;
m_eProgDamageType = DT_UNSPECIFIED;
m_hFiredFrom = LTNULL;
m_bRemoveWhenDone = LTTRUE;
m_vPos.Init();
m_nImpactFXId = FXBMGR_INVALID_ID;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::Setup()
//
// PURPOSE: Setup the Explosion
//
// ----------------------------------------------------------------------- //
void Explosion::Setup(HOBJECT hFiredFrom, uint8 nAmmoId)
{
if (!hFiredFrom) return;
AMMO const *pAmmo = g_pWeaponMgr->GetAmmo(nAmmoId);
if (!pAmmo) return;
m_bRemoveWhenDone = LTTRUE;
m_fDamageRadius = (LTFLOAT) pAmmo->nAreaDamageRadius;
m_fMaxDamage = (LTFLOAT) pAmmo->nAreaDamage;
m_eDamageType = pAmmo->eAreaDamageType;
m_fProgDamageRadius = (LTFLOAT) pAmmo->fProgDamageRadius;
m_fProgDamageLifetime = pAmmo->fProgDamageLifetime;
m_fProgDamage = pAmmo->fProgDamage;
m_fProgDamageDuration = pAmmo->fProgDamageDuration;
m_eProgDamageType = pAmmo->eProgDamageType;
Start(hFiredFrom);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::Start()
//
// PURPOSE: Start the Explosion
//
// ----------------------------------------------------------------------- //
void Explosion::Start(HOBJECT hFiredFrom)
{
if (!m_hObject) return;
g_pLTServer->GetObjectPos(m_hObject, &m_vPos);
// Do special fx (on the client) if applicable...
if (m_nImpactFXId != FXBMGR_INVALID_ID)
{
LTRotation rRot;
g_pLTServer->GetObjectRotation(m_hObject, &rRot);
EXPLOSIONCREATESTRUCT cs;
cs.nImpactFX = m_nImpactFXId;
cs.rRot = rRot;
cs.vPos = m_vPos;
cs.fDamageRadius = m_fDamageRadius;
CAutoMessage cMsg;
cMsg.Writeuint8(SFX_EXPLOSION_ID);
cs.Write(cMsg);
g_pLTServer->SendSFXMessage(cMsg.Read(), m_vPos, 0);
}
m_hFiredFrom = hFiredFrom;
// Do Area damage to the objects caught in the blast...
if (m_fDamageRadius > 0.0f && m_fMaxDamage > 0.0f)
{
AreaDamageObjectsInSphere();
}
// Progressively damage the objects caught in the blast...
if (m_fProgDamageRadius > 0.0f)
{
ProgDamageObjectsInSphere();
}
if (m_fProgDamageLifetime > 0.0f && m_fProgDamageRadius > 0.0f)
{
// Process the progressive damage every frame...
m_ProgDamageTimer.Start(m_fProgDamageLifetime);
SetNextUpdate(UPDATE_NEXT_FRAME);
}
else
{
if (m_bRemoveWhenDone)
{
g_pLTServer->RemoveObject(m_hObject);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::DoDamage()
//
// PURPOSE: Do the damage...
//
// ----------------------------------------------------------------------- //
void Explosion::Update()
{
// Do progressive damage to the objects caught in the blast...
ProgDamageObjectsInSphere();
if (m_ProgDamageTimer.Stopped())
{
if (m_bRemoveWhenDone)
{
g_pLTServer->RemoveObject(m_hObject);
}
m_hFiredFrom = 0;
}
else
{
SetNextUpdate(UPDATE_NEXT_FRAME);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::EngineMessageFn
//
// PURPOSE: Handle engine messages
//
// ----------------------------------------------------------------------- //
uint32 Explosion::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData)
{
switch(messageID)
{
case MID_UPDATE :
{
Update();
}
break;
case MID_INITIALUPDATE:
{
if (fData != INITIALUPDATE_SAVEGAME)
{
SetNextUpdate(UPDATE_NEVER);
}
}
break;
case MID_PRECREATE :
{
if (fData == PRECREATE_WORLDFILE || fData == PRECREATE_STRINGPROP)
{
ReadProp();
}
}
break;
case MID_SAVEOBJECT:
{
Save((ILTMessage_Write*)pData, (uint32)fData);
}
break;
case MID_LOADOBJECT:
{
Load((ILTMessage_Read*)pData, (uint32)fData);
}
break;
default : break;
}
return GameBase::EngineMessageFn(messageID, pData, fData);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::OnTrigger
//
// PURPOSE: Handle trigger messages
//
// ----------------------------------------------------------------------- //
bool Explosion::OnTrigger(HOBJECT hSender, const CParsedMsg &cMsg)
{
static CParsedMsg::CToken s_cTok_Start("START");
static CParsedMsg::CToken s_cTok_On("ON");
if ((cMsg.GetArg(0) == s_cTok_Start) || (cMsg.GetArg(0) == s_cTok_On))
{
Start();
}
else
return GameBase::OnTrigger(hSender, cMsg);
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::ReadProp
//
// PURPOSE: Read object properties
//
// ----------------------------------------------------------------------- //
void Explosion::ReadProp()
{
GenericProp genProp;
if (g_pLTServer->GetPropGeneric("DamageRadius", &genProp) == LT_OK)
{
m_fDamageRadius = genProp.m_Float;
}
if (g_pLTServer->GetPropGeneric("MaxDamage", &genProp) == LT_OK)
{
m_fMaxDamage = genProp.m_Float;
}
if (g_pLTServer->GetPropGeneric("RemoveWhenDone", &genProp) == LT_OK)
{
m_bRemoveWhenDone = genProp.m_Bool;
}
g_pFXButeMgr->ReadImpactFXProp("ImpactFXName", m_nImpactFXId);
if (g_pLTServer->GetPropGeneric("DamageType", &genProp) == LT_OK)
{
if (genProp.m_String[0])
{
m_eDamageType = StringToDamageType((const char*)genProp.m_String);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::AreaDamageObject()
//
// PURPOSE: Damage the object...
//
// ----------------------------------------------------------------------- //
void Explosion::AreaDamageObject(HOBJECT hObj)
{
if (!hObj) return;
HOBJECT hDamager = m_hFiredFrom ? m_hFiredFrom : m_hObject;
LTVector vObjPos;
g_pLTServer->GetObjectPos(hObj, &vObjPos);
LTVector vDir = vObjPos - m_vPos;
LTFLOAT fDist = vDir.Mag();
if (fDist <= m_fDamageRadius)
{
// Make sure that Characters don't take damage if another object
// is blocking them from the explosion...
LTBOOL bIntersect1 = LTFALSE;
LTBOOL bIntersect2 = LTFALSE;
if (IsCharacter(hObj) || IsCharacterHitBox(hObj))
{
// To do this test, do an intersect segment both directions
// (from the object to the explosion and from the explosion
// to the object). This will ensure that neither point
// is inside a wall and that nothing is blocking the damage...
IntersectInfo iInfo;
IntersectQuery qInfo;
qInfo.m_Flags = INTERSECT_HPOLY | INTERSECT_OBJECTS | IGNORE_NONSOLID;
qInfo.m_FilterFn = ExplosionFilterFn;
qInfo.m_From = m_vPos + vDir/fDist;
qInfo.m_To = vObjPos;
bIntersect1 = g_pLTServer->IntersectSegment(&qInfo, &iInfo);
qInfo.m_From = vObjPos;
qInfo.m_To = m_vPos + vDir/fDist;
bIntersect2 = g_pLTServer->IntersectSegment(&qInfo, &iInfo);
}
if (!bIntersect1 && !bIntersect2)
{
DamageStruct damage;
damage.hDamager = hDamager;
damage.vDir = vDir;
LTFLOAT fMinRadius = m_fDamageRadius * MIN_RADIUS_PERCENT;
LTFLOAT fRange = m_fDamageRadius - fMinRadius;
// Scale damage if necessary...
LTFLOAT fMultiplier = 1.0f;
if (fDist > fMinRadius)
{
LTFLOAT fPercent = (fDist - fMinRadius) / (m_fDamageRadius - fMinRadius);
fPercent = fPercent > 1.0f ? 1.0f : (fPercent < 0.0f ? 0.0f : fPercent);
fMultiplier = (1.0f - fPercent);
}
damage.eType = m_eDamageType;
damage.fDamage = m_fMaxDamage;
damage.fDamage *= fMultiplier;
damage.DoDamage(this, hObj, m_hObject);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::ProgDamageObject()
//
// PURPOSE: Damage the object...
//
// ----------------------------------------------------------------------- //
void Explosion::ProgDamageObject(HOBJECT hObj)
{
if (!hObj) return;
HOBJECT hDamager = m_hFiredFrom ? m_hFiredFrom : m_hObject;
LTVector vObjPos;
g_pLTServer->GetObjectPos(hObj, &vObjPos);
LTVector vDir = vObjPos - m_vPos;
LTFLOAT fDist = vDir.Mag();
if (fDist <= m_fProgDamageRadius)
{
// Make sure that Characters don't take damage if another object
// is blocking them from the explosion...
LTBOOL bIntersect1 = LTFALSE;
LTBOOL bIntersect2 = LTFALSE;
if (IsCharacter(hObj) || IsCharacterHitBox(hObj))
{
// To do this test, do an intersect segment both directions
// (from the object to the explosion and from the explosion
// to the object). This will ensure that neither point
// is inside a wall and that nothing is blocking the damage...
IntersectInfo iInfo;
IntersectQuery qInfo;
qInfo.m_Flags = INTERSECT_HPOLY | INTERSECT_OBJECTS | IGNORE_NONSOLID;
qInfo.m_FilterFn = ExplosionFilterFn;
qInfo.m_From = m_vPos + vDir/fDist;
qInfo.m_To = vObjPos;
bIntersect1 = g_pLTServer->IntersectSegment(&qInfo, &iInfo);
qInfo.m_From = vObjPos;
qInfo.m_To = m_vPos + vDir/fDist;
bIntersect2 = g_pLTServer->IntersectSegment(&qInfo, &iInfo);
}
if (!bIntersect1 && !bIntersect2)
{
DamageStruct damage;
damage.hDamager = hDamager;
damage.vDir = vDir;
damage.eType = m_eProgDamageType;
damage.fDuration = m_fProgDamageDuration;
damage.fDamage = m_fProgDamage;
damage.hContainer = m_hObject;
damage.DoDamage(this, hObj, m_hObject);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::ProgDamageObjectsInSphere()
//
// PURPOSE: Progressively damage all the objects in our radius
//
// ----------------------------------------------------------------------- //
void Explosion::ProgDamageObjectsInSphere()
{
ObjectList* pList = g_pLTServer->FindObjectsTouchingSphere(&m_vPos,
m_fProgDamageRadius);
if (!pList) return;
ObjectLink* pLink = pList->m_pFirstLink;
while (pLink)
{
ProgDamageObject(pLink->m_hObject);
pLink = pLink->m_pNext;
}
g_pLTServer->RelinquishList(pList);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::AreaDamageObjectsInSphere()
//
// PURPOSE: Area damage all the objects in our radius
//
// ----------------------------------------------------------------------- //
void Explosion::AreaDamageObjectsInSphere()
{
ObjectList* pList = g_pLTServer->FindObjectsTouchingSphere(&m_vPos, m_fDamageRadius);
if (!pList) return;
ObjectLink* pLink = pList->m_pFirstLink;
while (pLink)
{
AreaDamageObject(pLink->m_hObject);
pLink = pLink->m_pNext;
}
g_pLTServer->RelinquishList(pList);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::GetBoundingBoxColor()
//
// PURPOSE: Get the color of the bounding box
//
// ----------------------------------------------------------------------- //
LTVector Explosion::GetBoundingBoxColor()
{
return LTVector(0, 0, 1);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::Save
//
// PURPOSE: Save the object
//
// ----------------------------------------------------------------------- //
void Explosion::Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags)
{
if (!pMsg) return;
SAVE_HOBJECT(m_hFiredFrom);
SAVE_VECTOR(m_vPos);
SAVE_FLOAT(m_fDamageRadius);
SAVE_FLOAT(m_fMaxDamage);
SAVE_BYTE(m_eDamageType);
SAVE_FLOAT(m_fProgDamage);
SAVE_FLOAT(m_fProgDamageRadius);
SAVE_FLOAT(m_fProgDamageDuration);
SAVE_FLOAT(m_fProgDamageLifetime);
SAVE_BYTE(m_eProgDamageType);
SAVE_BOOL(m_bRemoveWhenDone);
SAVE_BYTE(m_nImpactFXId);
m_ProgDamageTimer.Save(pMsg);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: Explosion::Load
//
// PURPOSE: Load the object
//
// ----------------------------------------------------------------------- //
void Explosion::Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags)
{
if (!pMsg) return;
LOAD_HOBJECT(m_hFiredFrom);
LOAD_VECTOR(m_vPos);
LOAD_FLOAT(m_fDamageRadius);
LOAD_FLOAT(m_fMaxDamage);
LOAD_BYTE_CAST(m_eDamageType, DamageType);
LOAD_FLOAT(m_fProgDamage);
LOAD_FLOAT(m_fProgDamageRadius);
LOAD_FLOAT(m_fProgDamageDuration);
LOAD_FLOAT(m_fProgDamageLifetime);
LOAD_BYTE_CAST(m_eProgDamageType, DamageType);
LOAD_BOOL(m_bRemoveWhenDone);
LOAD_BYTE(m_nImpactFXId);
m_ProgDamageTimer.Load(pMsg);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CExplosionPlugin::PreHook_EditStringList
//
// PURPOSE: Requests a state change
//
// ----------------------------------------------------------------------- //
#ifndef __PSX2
LTRESULT CExplosionPlugin::PreHook_EditStringList(const char* szRezPath,
const char* szPropName,
char** aszStrings,
uint32* pcStrings,
const uint32 cMaxStrings,
const uint32 cMaxStringLength)
{
// See if we can handle the property...
if (_strcmpi("ImpactFXName", szPropName) == 0)
{
m_FXButeMgrPlugin.PreHook_EditStringList(szRezPath, szPropName,
aszStrings, pcStrings, cMaxStrings, cMaxStringLength);
if (!m_FXButeMgrPlugin.PopulateStringList(aszStrings, pcStrings,
cMaxStrings, cMaxStringLength)) return LT_UNSUPPORTED;
return LT_OK;
}
else if (_strcmpi("DamageType", szPropName) == 0)
{
if (!aszStrings || !pcStrings) return LT_UNSUPPORTED;
_ASSERT(aszStrings && pcStrings);
// Add an entry for each supported damage type
for (int i=0; i < kNumDamageTypes; i++)
{
if (!DTInfoArray[i].bGadget)
{
_ASSERT(cMaxStrings > (*pcStrings) + 1);
uint32 dwNameLen = strlen(DTInfoArray[i].pName);
if (dwNameLen < cMaxStringLength &&
((*pcStrings) + 1) < cMaxStrings)
{
strcpy(aszStrings[(*pcStrings)++], DTInfoArray[i].pName);
}
}
}
return LT_OK;
}
return LT_UNSUPPORTED;
}
#endif | [
"[email protected]"
]
| [
[
[
1,
664
]
]
]
|
137bfafe5f256616a962efc335779735160dbdba | d08c381305e3e675c3f8253ce88fafd5111b103c | /8_8_2008/curve_-project/doc/arm_curve_going/arm_curve_3/display.cpp | 2fdf2ec5c53c8ef190006e936fd14a9f9a5f6693 | []
| no_license | happypeter/tinylion | 07ea77febf6dff84089eddd6e1e47cd2ae032eb2 | 2f802f291ff43c568f9ef5eb846719efca03cc80 | refs/heads/master | 2020-06-03T09:14:19.682005 | 2010-10-19T09:12:56 | 2010-10-19T09:12:56 | 914,128 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | #include "display.h"
#include "screen.h"
#include <qlayout.h>
#include <qtimer.h>
#include <qframe.h>
#include <qlineedit.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qpushbutton.h>
#include <qfile.h>
//#include <cstdlib>
#include <iostream>
using namespace std;
DisplayWidget::DisplayWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
timer = 0;
QVBoxLayout *vbox = new QVBoxLayout( this, 10 );
QHBoxLayout *hbox = new QHBoxLayout( vbox );
screen1 = new Screen( this );
screen2 = new Screen( this );
screen3 = new Screen( this );
vbox->addWidget( screen1 );
vbox->addWidget( screen2 );
vbox->addWidget( screen3 );
lineEdit = new QLineEdit(this);
lineEdit->setReadOnly( TRUE );
hbox->addWidget( lineEdit );
startButton = new QPushButton( this );
startButton->setText( tr( "&Start" ) );
stopButton = new QPushButton( this );
stopButton->setText( tr( "Sto&p" ) );
hbox->addWidget( startButton );
hbox->addWidget( stopButton );
connect( startButton, SIGNAL( clicked () ), SLOT( start() ) );
connect( stopButton, SIGNAL( clicked () ), SLOT( stop() ) );
time = 0;
yval = 0.0;
}
void DisplayWidget::start()
{
printf("run slot\n");
}
void DisplayWidget::stop()
{
printf("stop slot\n");
}
QSize DisplayWidget::sizeHint() const
{
return QSize( 16 * Margin, 12 * Margin );
}
| [
"[email protected]"
]
| [
[
[
1,
61
]
]
]
|
990b0d67f43f7b55b40f7ef9b622e9fb701b0d38 | 724cded0e31f5fd52296d516b4c3d496f930fd19 | /inc/jrtp/rtpsessionparams.h | 10e8d712bbe9a3a476f7624579c0657fbe11afd5 | []
| no_license | yubik9/p2pcenter | 0c85a38f2b3052adf90b113b2b8b5b312fefcb0a | fc4119f29625b1b1f4559ffbe81563e6fcd2b4ea | refs/heads/master | 2021-08-27T15:40:05.663872 | 2009-02-19T00:13:33 | 2009-02-19T00:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,199 | h | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2006 Jori Liesenborgs
Contact: [email protected]
This library was developed at the "Expertisecentrum Digitale Media"
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef RTPSESSIONPARAMS_H
#define RTPSESSIONPARAMS_H
#include "rtpconfig.h"
#include "rtptypes.h"
#include "rtptransmitter.h"
#include "rtptimeutilities.h"
#include "rtpsources.h"
class RTPSessionParams
{
public:
RTPSessionParams();
int SetUsePollThread(bool usethread);
bool IsUsingPollThread() const { return usepollthread; }
void SetMaximumPacketSize(size_t max) { maxpacksize = max; }
size_t GetMaximumPacketSize() const { return maxpacksize; }
void SetAcceptOwnPackets(bool accept) { acceptown = accept; }
bool AcceptOwnPackets() const { return acceptown; }
void SetReceiveMode(RTPTransmitter::ReceiveMode recvmode) { receivemode = recvmode; }
RTPTransmitter::ReceiveMode GetReceiveMode() const { return receivemode; }
void SetOwnTimestampUnit(double tsunit) { owntsunit = tsunit; }
double GetOwnTimestampUnit() const { return owntsunit; }
void SetResolveLocalHostname(bool v) { resolvehostname = v; }
bool GetResolveLocalHostname() const { return resolvehostname; }
#ifdef RTP_SUPPORT_PROBATION
void SetProbationType(RTPSources::ProbationType probtype) { probationtype = probtype; }
RTPSources::ProbationType GetProbationType() const { return probationtype; }
#endif // RTP_SUPPORT_PROBATION
void SetSessionBandwidth(double sessbw) { sessionbandwidth = sessbw; }
double GetSessionBandwidth() const { return sessionbandwidth; }
void SetControlTrafficFraction(double frac) { controlfrac = frac; }
double GetControlTrafficFraction() const { return controlfrac; }
void SetSenderControlBandwidthFraction(double frac) { senderfrac = frac; }
double GetSenderControlBandwidthFraction() const { return senderfrac; }
void SetMinimumRTCPTransmissionInterval(const RTPTime &t) { mininterval = t; }
RTPTime GetMinimumRTCPTransmissionInterval() const { return mininterval; }
void SetUseHalfRTCPIntervalAtStartup(bool usehalf) { usehalfatstartup = usehalf; }
bool GetUseHalfRTCPIntervalAtStartup() const { return usehalfatstartup; }
void SetRequestImmediateBYE(bool v) { immediatebye = v; }
bool GetRequestImmediateBYE() const { return immediatebye; }
void SetSenderReportForBYE(bool v) { SR_BYE = v; }
bool GetSenderReportForBYE() const { return SR_BYE; }
void SetSenderTimeoutMultiplier(double m) { sendermultiplier = m; }
double GetSenderTimeoutMultiplier() const { return sendermultiplier; }
void SetSourceTimeoutMultiplier(double m) { generaltimeoutmultiplier = m; }
double GetSourceTimeoutMultiplier() const { return generaltimeoutmultiplier; }
void SetBYETimeoutMultiplier(double m) { byetimeoutmultiplier = m; }
double GetBYETimeoutMultiplier() const { return byetimeoutmultiplier; }
void SetCollisionTimeoutMultiplier(double m) { collisionmultiplier = m; }
double GetCollisionTimeoutMultiplier() const { return collisionmultiplier; }
void SetNoteTimeoutMultiplier(double m) { notemultiplier = m; }
double GetNoteTimeoutMultiplier() const { return notemultiplier; }
private:
bool acceptown;
bool usepollthread;
int maxpacksize;
double owntsunit;
RTPTransmitter::ReceiveMode receivemode;
bool resolvehostname;
#ifdef RTP_SUPPORT_PROBATION
RTPSources::ProbationType probationtype;
#endif // RTP_SUPPORT_PROBATION
double sessionbandwidth;
double controlfrac;
double senderfrac;
RTPTime mininterval;
bool usehalfatstartup;
bool immediatebye;
bool SR_BYE;
double sendermultiplier;
double generaltimeoutmultiplier;
double byetimeoutmultiplier;
double collisionmultiplier;
double notemultiplier;
};
#endif // RTPSESSIONPARAMS_H
| [
"fuwenke@b5bb1052-fe17-11dd-bc25-5f29055a2a2d"
]
| [
[
[
1,
117
]
]
]
|
3b0b86653ab71ff4007204bfa8728261bee31b37 | ed2a1c83681d8ed2d08f8a74707536791e5cd057 | /Computron/Keytron.EXE v03/keytron.cpp | 8a7508794deabac5726da3bfe3fa2cc6a4b33a24 | [
"Apache-2.0"
]
| permissive | MartinMReed/XenDLL | e33d5c27187e58fd4401b2dbcaae3ebab8279bc2 | 51a05c3cec7b2142f704f2ea131202a72de843ec | refs/heads/master | 2021-01-10T19:10:40.492482 | 2007-10-31T16:38:00 | 2007-10-31T16:38:00 | 12,150,175 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,077 | cpp | // keytron.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "keytron.h"
#include "keytronDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CKeytronApp
BEGIN_MESSAGE_MAP(CKeytronApp, CWinApp)
//{{AFX_MSG_MAP(CKeytronApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CKeytronApp construction
CKeytronApp::CKeytronApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CKeytronApp object
CKeytronApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CKeytronApp initialization
BOOL CKeytronApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CKeytronDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
cbdb577fbab0e92307f2eaa2bc5c451ccf6f99c7 | 9ba08620ddc3579995435d6e0e9cabc436e1c88d | /src/logger.cpp | fee131b0065d1dacf181abc8eca7d1980735135c | [
"MIT"
]
| permissive | foxostro/CheeseTesseract | f5d6d7a280cbdddc94a5d57f32a50caf1f15e198 | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | refs/heads/master | 2021-01-01T17:31:27.189613 | 2009-08-02T13:27:20 | 2009-08-02T13:27:33 | 267,008 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,912 | cpp | #include "Core.h"
#include "FileFuncs.h"
#ifdef _WIN32
#include <windows.h>
#endif
void PrintStringToLog(const string &s) {
static bool firstTime = true;
static fstream stream;
if (firstTime) {
firstTime = false;
const FileName logFileName("log.txt");
stream.open(logFileName.c_str(), ios::out);
if (!stream) {
cerr << "Failed to create log file: " << logFileName.str() << endl;
} else {
cout << "Redirecting std::clog to file: "
<< logFileName.str()
<< endl;
clog.rdbuf(stream.rdbuf()); // redirect clog to file
cout << "Redirecting std::cerr to file: "
<< logFileName.str()
<< endl;
cerr.rdbuf(stream.rdbuf()); // redirect cerr to file
}
// Create a header for the log file
clog << "=============================================" << endl
<< "= =" << endl
#ifndef NDEBUG
<< "= Debug Build =" << endl
#else
<< "= Release Build =" << endl
#endif
<< "= =" << endl
<< "=============================================" << endl
<< endl;
}
#ifdef _WIN32
// Print message to debugger message window
OutputDebugString(string(s + "\n\n").c_str());
#else
cout << s << endl << endl;
#endif
clog << s << endl << endl;
}
void Log(const string &message,
const string &function,
const FileName &file,
const int line) {
// Format the time stamp.
time_t curTime = time(NULL);
char timestamp[32];
strftime(timestamp,
sizeof(timestamp),
"%Y.%m.%dT%H:%M:%S",
localtime(&curTime));
PrintStringToLog
(
function + " -> " + message +
"\n\t" + file.stripPath().str() + ":" + itos(line) +
"\n\t" + timestamp +
"\n"
);
}
| [
"arfox@arfox-desktop",
"[email protected]",
"arfox@bishop"
]
| [
[
[
1,
3
],
[
8,
50
],
[
52,
76
]
],
[
[
4,
7
]
],
[
[
51,
51
]
]
]
|
0938269b93461511e29a65db70377744e1594435 | 91ac219c4cde8c08a6b23ac3d207c1b21124b627 | /common/mlc/BitInterleaver.h | 2ccfd3caade5cbb7f6e15b05ee04d5a7fa2970bf | []
| no_license | DazDSP/hamdrm-dll | e41b78d5f5efb34f44eb3f0c366d7c1368acdbac | 287da5949fd927e1d3993706204fe4392c35b351 | refs/heads/master | 2023-04-03T16:21:12.206998 | 2008-01-05T19:48:59 | 2008-01-05T19:48:59 | 354,168,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | h | /******************************************************************************\
* Technische Universitaet Darmstadt, Institut fuer Nachrichtentechnik
* Copyright (c) 2001
*
* Author(s):
* Volker Fischer
*
* Description:
*
*
******************************************************************************
*
* 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
\******************************************************************************/
#if !defined(BIT_INTERLEAVER_H__3B0BA660_CA63_4344_BB2B_23E7A0D31912__INCLUDED_)
#define BIT_INTERLEAVER_H__3B0BA660_CA63_4344_BB2B_23E7A0D31912__INCLUDED_
#include "../GlobalDefinitions.h"
#include "../interleaver/BlockInterleaver.h"
#include "../Vector.h"
/* Classes ********************************************************************/
class CBitInterleaver: public CBlockInterleaver
{
public:
CBitInterleaver() {}
virtual ~CBitInterleaver() {}
void Init(int iNewx_in1, int iNewx_in2, int it_0);
void Interleave(CVector<_BINARY>& InputData);
protected:
int ix_in1;
int ix_in2;
CVector<int> veciIntTable1;
CVector<int> veciIntTable2;
CVector<_BINARY> vecbiInterlMemory1;
CVector<_BINARY> vecbiInterlMemory2;
};
class CBitDeinterleaver: public CBlockInterleaver
{
public:
CBitDeinterleaver() {}
virtual ~CBitDeinterleaver() {}
void Init(int iNewx_in1, int iNewx_in2, int it_0);
void Deinterleave(CVector<CDistance>& vecInput);
protected:
int ix_in1;
int ix_in2;
CVector<int> veciIntTable1;
CVector<int> veciIntTable2;
CVector<CDistance> vecDeinterlMemory1;
CVector<CDistance> vecDeinterlMemory2;
};
#endif // !defined(BIT_INTERLEAVER_H__3B0BA660_CA63_4344_BB2B_23E7A0D31912__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
75
]
]
]
|
f42189f59466b47333225de25b17b164685d68ca | a92598d0a8a2e92b424915d2944212f2f13e7506 | /PtRPG/PhotonLib/Common-cpp/inc/BaseCharString.h | 56d17471f5fddf8c797ad9af2d4165c3d1361e9d | [
"MIT"
]
| permissive | peteo/RPG_Learn | 0cc4facd639bd01d837ac56cf37a07fe22c59211 | 325fd1802b14e055732278f3d2d33a9577608c39 | refs/heads/master | 2021-01-23T11:07:05.050645 | 2011-12-12T08:47:27 | 2011-12-12T08:47:27 | 2,299,148 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,287 | h | /* Exit Games Common - C++ Client Lib
* Copyright (C) 2004-2011 by Exit Games GmbH. All rights reserved.
* http://www.exitgames.com
* mailto:[email protected]
*/
#ifndef __BASE_CHAR_STRING_H
#define __BASE_CHAR_STRING_H
#include "Base.h"
#ifndef _EG_BREW_PLATFORM
namespace ExitGames
{
#endif
class JString;
/* Summary
The BaseCharString class is the abstract base class for container classes,
holding char* strings.
Description
Subclasses of this class act as convenience classes for conversions between
instances of class <link JString> and char*'s.
The encoding of the char*'s is defines by the subclass. There should be one
subclass for every supported encoding.
Subclasses of this class should only be used to hold or pass strings and for
conversions between string encodings.
Please use class <link JString> for common string operations and modifications.*/
class BaseCharString : protected Base
{
public:
virtual operator const char* (void) const = 0;
virtual operator JString (void) const = 0;
virtual const char* cstr(void) const = 0;
virtual JString JStringRepresentation(void) const = 0;
protected:
char* mBuffer;
};
#ifndef _EG_BREW_PLATFORM
}
#endif
#endif | [
"[email protected]"
]
| [
[
[
1,
45
]
]
]
|
f534c0deae2cab79211d686bddba66f46cfc1688 | 999a45e54eaa7e2e2272f03845867b2a016cdf07 | /World.cpp | 14c829251f0e0b462f1ffeb9c07c42c6966b19dc | []
| no_license | jwagner/box2dlite | 9daa5a150a5b870f6b57dd23d3c65d7a1dfaf035 | 10e57830fdd5e8c445d81f1d0ee970cd93607926 | refs/heads/master | 2021-01-10T18:26:46.417513 | 2011-10-16T19:43:36 | 2011-10-16T19:43:36 | 2,587,719 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,820 | cpp | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies.
* Erin Catto makes no representations about the suitability
* of this software for any purpose.
* It is provided "as is" without express or implied warranty.
*/
#include "World.h"
#include "Body.h"
#include "Joint.h"
using std::vector;
using std::map;
using std::pair;
typedef map<ArbiterKey, Arbiter>::iterator ArbIter;
typedef pair<ArbiterKey, Arbiter> ArbPair;
bool World::accumulateImpulses = true;
bool World::warmStarting = true;
bool World::positionCorrection = true;
void World::Add(Body* body)
{
bodies.push_back(body);
}
void World::Add(Joint* joint)
{
joints.push_back(joint);
}
void World::Clear()
{
bodies.clear();
joints.clear();
arbiters.clear();
}
void World::BroadPhase()
{
// O(n^2) broad-phase
for (int i = 0; i < (int)bodies.size(); ++i)
{
Body* bi = bodies[i];
for (int j = i + 1; j < (int)bodies.size(); ++j)
{
Body* bj = bodies[j];
if (bi->invMass == 0.0f && bj->invMass == 0.0f)
continue;
Arbiter newArb(bi, bj);
ArbiterKey key(bi, bj);
if (newArb.numContacts > 0)
{
ArbIter iter = arbiters.find(key);
if (iter == arbiters.end())
{
arbiters.insert(ArbPair(key, newArb));
}
else
{
iter->second.Update(newArb.contacts, newArb.numContacts);
}
}
else
{
arbiters.erase(key);
}
}
}
}
void World::Step(float dt)
{
float inv_dt = dt > 0.0f ? 1.0f / dt : 0.0f;
// Determine overlapping bodies and update contact points.
BroadPhase();
// Integrate forces.
for (int i = 0; i < (int)bodies.size(); ++i)
{
Body* b = bodies[i];
if (b->invMass == 0.0f)
continue;
b->velocity += dt * (gravity + b->invMass * b->force);
b->angularVelocity += dt * b->invI * b->torque;
}
// Perform pre-steps.
for (ArbIter arb = arbiters.begin(); arb != arbiters.end(); ++arb)
{
arb->second.PreStep(inv_dt);
}
for (int i = 0; i < (int)joints.size(); ++i)
{
joints[i]->PreStep(inv_dt);
}
// Perform iterations
for (int i = 0; i < iterations; ++i)
{
for (ArbIter arb = arbiters.begin(); arb != arbiters.end(); ++arb)
{
arb->second.ApplyImpulse();
}
for (int j = 0; j < (int)joints.size(); ++j)
{
joints[j]->ApplyImpulse();
}
}
// Integrate Velocities
for (int i = 0; i < (int)bodies.size(); ++i)
{
Body* b = bodies[i];
b->position += dt * b->velocity;
b->rotation += dt * b->angularVelocity;
b->force.Set(0.0f, 0.0f);
b->torque = 0.0f;
}
}
| [
"[email protected]"
]
| [
[
[
1,
136
]
]
]
|
7b63aa3347db257b3558b136d956117f550b2a4e | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEIntersection/SEIntersector.h | 4db78e1cd8257c57b58ceada0859bcd7c73bcb0b | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,068 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_Intersector_H
#define Swing_Intersector_H
#include "SEFoundationLIB.h"
#include "SEPlatforms.h"
#include "SELinComp.h"
#include "SEVector2.h"
#include "SEVector3.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:
// Author:Sun Che
// Date:20081219
//----------------------------------------------------------------------------
template <class Real, class TVector>
class SE_FOUNDATION_API SEIntersector
{
public:
// 虚基类
virtual ~SEIntersector(void);
// 静态相交查询.默认实现返回false.
// Find查询返回一个相交集.派生类有责任提供访问该集合的功能,
// 因为该集合的性质由具体的对象类型所决定.
virtual bool Test(void);
virtual bool Find(void);
// 动态相交查询.默认实现返回false.
// Find查询返回一个first contact set.派生类有责任提供访问该集合的功能,
// 因为该集合的性质由具体的对象类型所决定.
virtual bool Test(Real fTMax, const TVector& rVelocity0,
const TVector& rVelocity1);
virtual bool Find(Real fTMax, const TVector& rVelocity0,
const TVector& rVelocity1);
// 动态相交查询时,两个对象第一次接触的时间.
Real GetContactTime(void) const;
// 相交集的信息.
enum
{
IT_EMPTY = SELinComp<Real>::CT_EMPTY,
IT_POINT = SELinComp<Real>::CT_POINT,
IT_SEGMENT = SELinComp<Real>::CT_SEGMENT,
IT_RAY = SELinComp<Real>::CT_RAY,
IT_LINE = SELinComp<Real>::CT_LINE,
IT_POLYGON,
IT_PLANE,
IT_POLYHEDRON,
IT_OTHER
};
int GetIntersectionType(void) const;
protected:
SEIntersector(void);
Real m_fContactTime;
int m_iIntersectionType;
};
typedef SEIntersector<float, SEVector2f> SEIntersector2f;
typedef SEIntersector<float, SEVector3f> SEIntersector3f;
typedef SEIntersector<double, SEVector2d> SEIntersector2d;
typedef SEIntersector<double, SEVector3d> SEIntersector3d;
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
91
]
]
]
|
8ef41a085ad021c8cd70b59435bd03bb02d2e597 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/inc/kernel/nipcminiserver.h | 0e703329fd0d07cfcffc0cc309c123c347089ca5 | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,153 | h | #ifndef N_IPCMINISERVER_H
#define N_IPCMINISERVER_H
//------------------------------------------------------------------------------
/**
A nIpcServer creates one nIpcMiniServer for each connecting client.
(C) 2002 RadonLabs GmbH
*/
#ifndef N_NODE_H
#include "util/nnode.h"
#endif
#include "kernel/nsession.h"
//------------------------------------------------------------------------------
class nIpcServer;
class nThread;
class nFile;
class nIpcMiniServer : public nNode
{
public:
/// constructor
nIpcMiniServer(nIpcServer* _server);
/// destructor
//virtual ~nIpcMiniServer();
/// listen on socket and wait for new client
bool Listen();
/// ignore the new client for any reason
void Ignore();
/// check for and pull incoming messages, call this frequently!
bool Poll();
/// send a string message to the client
bool Send(const char* msg, bool backline_only = false);
/// completely send a data buffer to the client
bool SendData(const char* buf, int sz, bool backline_only = false);
/// set script answering mode
void SetQuiet(bool b ) { this->quiet = b; }
/// get script answering mode
bool GetQuiet() const { return this->quiet; }
/// returns true in case socket is valid
bool IsValid() const { return (this->session.connected());}
/// return true if this server for a back line
bool IsBackLine() const { return this->backline; }
private: //
friend class nIpcServer;
private: // file operations
/// open file by command received over ip, returns handle if success, -1 if failed
char* ft_open(const char* fname, const char* mode);
/// close file by hanlde received over ip, returns FT_DONE if success, FT_FAIL if failed
char* ft_close(const char* handle);
/// write to nFile specified by handle size of bytes of data came overe ip
char* ft_write(const char* handle, int size);
/// read from nFile specified by handle size of bytes of data came overe ip
char* ft_read(const char* handle, int size);
/// check if file defined by hanlde is open, returns FT_TRUE if open, FT_FALSE if not and FT_FAIL if failed
char* ft_isopen(const char* handle);
/// set position in file defined by hanlde received over ip, returns FT_TRUE if done, FT_FALSE if not and FT_FAIL if protocol failed
char* ft_seek(const char* handle, int offset, const char* origin);
/// get position in file defined by hanlde received over ip, returns position in ASCII if done, FT_FAIL if failed
char* ft_tell(const char* handle);
/// check the existance of file with given name, returns FT_TRUE if exists, FT_FALSE if not
char* ft_exists(const char* name);
static nFile* strHandle2nFile(const char*);
nSession session;
nIpcServer* server; // my mother server
int id;
SOCKET srvrSocket;
struct sockaddr_in clientAddr;
char answer[N_MAXPATH*2];
bool quiet;
bool exit_on_disconnect;
public:
bool backline;
};
//------------------------------------------------------------------------------
#endif
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
91
]
]
]
|
a31f89e985580599ee4f0dd5be13a761ccde52ed | b22c254d7670522ec2caa61c998f8741b1da9388 | /common/DoorActor.cpp | d6047fe9d3b82abb473e89c3aa2293557f2ef03e | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,000 | cpp | /*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
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/>.
-----------------------------------------------------------------------------
*/
#include "DoorActor.h"
#include <math.h>
#ifndef _LBANET_SERVER_SIDE_
#include "ThreadSafeWorkpile.h"
#include "GameEvents.h"
#include "DataLoader.h"
#include "MusicHandler.h"
#include "PhysXPhysicHandler.h"
#include <windows.h> // Header File For Windows
#include <GL/gl.h> // Header File For The OpenGL32 Library
#endif
/***********************************************************
Constructor
***********************************************************/
DoorActor::DoorActor(float zoneSizeX, float zoneSizeY, float zoneSizeZ, bool Locked, long KeyId,
bool Hide, float OpenTransX, float OpenTransY, float OpenTransZ,
float OpenTransSpeedX, float OpenTransSpeedY, float OpenTransSpeedZ, bool destroykey)
: ZoneActor(zoneSizeX, zoneSizeY, zoneSizeZ), _locked(Locked), _KeyId(KeyId), _state(CLOSED),
_Hide(Hide),_OpenTransSpeedX(OpenTransSpeedX), _OpenTransSpeedY(OpenTransSpeedY),
_OpenTransSpeedZ(OpenTransSpeedZ), _opencounter(0), _signalon(false),
_OpenTransX(OpenTransX), _OpenTransY(OpenTransY), _OpenTransZ(OpenTransZ), _destroykey(destroykey)
{
}
/***********************************************************
Destructor
***********************************************************/
DoorActor::~DoorActor()
{
}
/***********************************************************
do all check to be done when idle
***********************************************************/
int DoorActor::Process(double tnow, float tdiff)
{
if(_Hide)
{
if(_state == OPENING)
{
Hide();
_state = OPENED;
}
if(_state == CLOSING)
{
Show();
_state = CLOSED;
}
}
else
{
if(_state == OPENING)
{
double stepX = (_OpenTransSpeedX * tdiff);
double stepY = (_OpenTransSpeedY * tdiff);
double stepZ = (_OpenTransSpeedZ * tdiff);
double diffX = _OpenedX - _posX;
double diffY = _OpenedY - _posY;
double diffZ = _OpenedZ - _posZ;
if(fabs(stepX) > fabs(diffX))
stepX = diffX;
if(fabs(stepY) > fabs(diffY))
stepY = diffY;
if(fabs(stepZ) > fabs(diffZ))
stepZ = diffZ;
if(stepX == 0 && stepY == 0 && stepZ == 0)
_state = OPENED;
else
{
_posX += (float)stepX;
_posY += (float)stepY;
_posZ += (float)stepZ;
#ifndef _LBANET_SERVER_SIDE_
if(_physposhandler)
_physposhandler->SetPosition(_posX, _posY+(_sizeY/2.0f), _posZ);
#endif
}
}
if(_state == CLOSING)
{
double stepX = (-_OpenTransSpeedX * tdiff);
double stepY = (-_OpenTransSpeedY * tdiff);
double stepZ = (-_OpenTransSpeedZ * tdiff);
double diffX = _ClosedX - _posX;
double diffY = _ClosedY - _posY;
double diffZ = _ClosedZ - _posZ;
if(fabs(stepX) > fabs(diffX))
stepX = diffX;
if(fabs(stepY) > fabs(diffY))
stepY = diffY;
if(fabs(stepZ) > fabs(diffZ))
stepZ = diffZ;
if(stepX == 0 && stepY == 0 && stepZ == 0)
_state = CLOSED;
else
{
_posX += (float)stepX;
_posY += (float)stepY;
_posZ += (float)stepZ;
#ifndef _LBANET_SERVER_SIDE_
if(_physposhandler)
_physposhandler->SetPosition(_posX, _posY+(_sizeY/2.0f), _posZ);
#endif
}
}
}
return Actor::Process(tnow, tdiff);
}
/***********************************************************
process zone activation
***********************************************************/
void DoorActor::ProcessActivation(float PlayerPosX, float PlayerPosY, float PlayerPosZ,
float PlayerRotation)
{
Open();
SendSignal(1, _targets);
}
/***********************************************************
process zone desactivation
***********************************************************/
void DoorActor::ProcessDesactivation(float PlayerPosX, float PlayerPosY, float PlayerPosZ,
float PlayerRotation)
{
Close();
SendSignal(2, _targets);
}
/***********************************************************
called on signal
***********************************************************/
bool DoorActor::OnSignal(long SignalNumber)
{
if(SignalNumber == 1) // open door signal
{
Open();
return true;
}
if(SignalNumber == 2) // close door signal
{
Close();
return true;
}
if(SignalNumber == 4) // switch open/close door signal
{
if(!_signalon)
{
_signalon = true;
Open();
}
else
{
_signalon = false;
Close();
}
return true;
}
return false;
}
/***********************************************************
open the door
***********************************************************/
bool DoorActor::Open()
{
if(_opencounter < 0)
_opencounter=0;
++_opencounter;
if(_state == CLOSED || _state == CLOSING)
{
#ifndef _LBANET_SERVER_SIDE_
if(_attachedsound >= 0)
{
std::string soundp = DataLoader::getInstance()->GetSoundPath(_attachedsound);
if(soundp != "")
MusicHandler::getInstance()->PlaySample(soundp, 0);
}
#endif
_state = OPENING;
return true;
}
return false;
}
/***********************************************************
open the door
***********************************************************/
bool DoorActor::Close()
{
if(_opencounter > 0)
--_opencounter;
if(_opencounter == 0)
if(_state == OPENED || _state == OPENING)
{
#ifndef _LBANET_SERVER_SIDE_
if(_attachedsound >= 0)
{
std::string soundp = DataLoader::getInstance()->GetSoundPath(_attachedsound);
if(soundp != "")
MusicHandler::getInstance()->PlaySample(soundp, 0);
}
#endif
_state = CLOSING;
return true;
}
return false;
}
/***********************************************************
set actor position in the scene
***********************************************************/
void DoorActor::SetPosition(float posX, float posY, float posZ, bool refreshPhysic)
{
Actor::SetPosition(posX, posY, posZ, refreshPhysic);
UpdateCLoseOpen();
}
/***********************************************************
update info
***********************************************************/
void DoorActor::UpdateCLoseOpen()
{
_OpenedX = _posX+_OpenTransX;
_OpenedY = _posY+_OpenTransY;
_OpenedZ = _posZ+_OpenTransZ;
_ClosedX = _posX;
_ClosedY = _posY;
_ClosedZ = _posZ;
}
/***********************************************************
render editor part
***********************************************************/
void DoorActor::RenderEditor()
{
#ifndef _LBANET_SERVER_SIDE_
glEnable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glLineWidth(2.0f);
glPushMatrix();
glTranslated(GetZoneCenterX(), GetZoneCenterY()/2. + 0.5, GetZoneCenterZ());
glColor4f(0.7f,0.7f,1.0f, 1.f);
glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(_OpenTransX,_OpenTransY,_OpenTransZ);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
ZoneActor::RenderEditor();
#endif
}
/***********************************************************
get current actor state
return false if the actor is stateless
***********************************************************/
bool DoorActor::Getstate(ActorStateInfo & currState)
{
currState.Open = (_state == OPENING) || (_state == OPENED);
currState.Counter = _opencounter;
currState.SignalOn = _signalon;
return true;
}
/***********************************************************
set the actor state
***********************************************************/
void DoorActor::Setstate(const ActorStateInfo & currState)
{
_state = (currState.Open ? OPENED : CLOSED);
_opencounter = currState.Counter;
_signalon = currState.SignalOn;
if(currState.Open)
{
if(_Hide)
{
Hide();
}
else
{
_posX = _OpenedX;
_posY = _OpenedY;
_posZ = _OpenedZ;
#ifndef _LBANET_SERVER_SIDE_
if(_physposhandler)
_physposhandler->SetPosition(_posX, _posY+(_sizeY/2.0f), _posZ);
#endif
}
}
} | [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
366
]
]
]
|
5efeb67dc21ba7cf806b9c3d9dc978a0cdb4a7b6 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/commdlg.hpp | d8a0d44d28994585f6887f48635f0cfc95945b9f | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,714 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'CommDlg.pas' rev: 6.00
#ifndef CommDlgHPP
#define CommDlgHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <ShlObj.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
#include <commdlg.h>
namespace Commdlg
{
//-- type declarations -------------------------------------------------------
typedef tagOFNA *POpenFilenameA;
typedef tagOFNW *POpenFilenameW;
typedef tagOFNA *POpenFilename;
typedef tagOFNA TOpenFilenameA;
typedef tagOFNW TOpenFilenameW;
typedef tagOFNA TOpenFilename;
typedef _OFNOTIFYA *POFNotifyA;
typedef _OFNOTIFYW *POFNotifyW;
typedef _OFNOTIFYA *POFNotify;
typedef _OFNOTIFYA TOFNotifyA;
typedef _OFNOTIFYW TOFNotifyW;
typedef _OFNOTIFYA TOFNotify;
typedef _OFNOTIFYEXA *POFNotifyExA;
typedef _OFNOTIFYEXW *POFNotifyExW;
typedef _OFNOTIFYEXA *POFNotifyEx;
typedef _OFNOTIFYEXA TOFNotifyExA;
typedef _OFNOTIFYEXW TOFNotifyExW;
typedef _OFNOTIFYEXA TOFNotifyEx;
typedef tagCHOOSECOLORA *PChooseColorA;
typedef tagCHOOSECOLORW *PChooseColorW;
typedef tagCHOOSECOLORA *PChooseColor;
typedef tagCHOOSECOLORA TChooseColorA;
typedef tagCHOOSECOLORW TChooseColorW;
typedef tagCHOOSECOLORA TChooseColor;
typedef tagFINDREPLACEA *PFindReplaceA;
typedef tagFINDREPLACEW *PFindReplaceW;
typedef tagFINDREPLACEA *PFindReplace;
typedef tagFINDREPLACEA TFindReplaceA;
typedef tagFINDREPLACEW TFindReplaceW;
typedef tagFINDREPLACEA TFindReplace;
typedef tagCHOOSEFONTA *PChooseFontA;
typedef tagCHOOSEFONTW *PChooseFontW;
typedef tagCHOOSEFONTA *PChooseFont;
typedef tagCHOOSEFONTA TChooseFontA;
typedef tagCHOOSEFONTW TChooseFontW;
typedef tagCHOOSEFONTA TChooseFont;
typedef tagDEVNAMES *PDevNames;
typedef tagDEVNAMES TDevNames;
typedef tagPSDA *PPageSetupDlgA;
typedef tagPSDW *PPageSetupDlgW;
typedef tagPSDA *PPageSetupDlg;
typedef tagPSDA TPageSetupDlgA;
typedef tagPSDW TPageSetupDlgW;
typedef tagPSDA TPageSetupDlg;
//-- var, const, procedure ---------------------------------------------------
} /* namespace Commdlg */
using namespace Commdlg;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // CommDlg
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
122
]
]
]
|
5451f0ba9ca8ef171e45f8e922abb3b2435400f0 | 28a56d127e0c18c6ba138348ffac61fa25742be1 | /BeloteClient/src/GUIManager.h | 75cfaf70c55e0cedbe62b362597cb5de4968cbb3 | []
| no_license | IrmatDen/fr-belote | 036f68966b6c8beb7ea1bb7a18aeac98bee30924 | c7dc68be4d8c18ad2905c59d6e13887c6a3c0b8d | refs/heads/master | 2020-05-17T11:07:42.910399 | 2011-07-21T14:40:26 | 2011-07-21T14:40:26 | 40,088,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,612 | h | #ifndef GUIManager_H
#define GUIManager_H
#include <CEGUI.h>
#include <SFML/Graphics/RenderWindow.hpp>
class ErrorRaisedArgs : public CEGUI::EventArgs
{
public:
std::string m_ErrorTxt;
};
// Based on SFML/CEGUI bridge available here:
// http://www.sfml-dev.org/wiki/fr/tutoriels/utilisercegui
class GUIManager : public CEGUI::EventSet
{
public:
static const CEGUI::String EventNamespace;
static const CEGUI::String EventErrorRaised;
static const std::string ErrorUnknown;
static const std::string ErrorLostConnection;
public:
GUIManager();
~GUIManager();
bool Initialize(sf::RenderWindow* win);
bool HandleEvent(sf::Event& event);
void UpdateAndDraw(float elapsedSeconds);
void SetRootWindow(CEGUI::Window* win) { CEGUI::System::getSingleton().setGUISheet(win); }
private:
sf::RenderWindow* m_Window;
const sf::Input* m_Input;
// SFML to CEGUI input mapping section
private:
void InitializeMaps();
struct MappingCompare
{
// Sorting func
template<typename T>
bool operator()(const T &lhs, const T &rhs) const
{ return keyLess<T>(lhs.first, rhs.first); }
// Look-up #1
template<typename T>
bool operator()(const T &lhs, typename const T::first_type &k) const
{ return keyLess<T>(lhs.first, k); }
// Look-up #2
template<typename T>
bool operator()(typename const T::first_type &k, const T &rhs) const
{ return keyLess<T>(k, rhs.first); }
private:
template<typename T>
bool keyLess(typename const T::first_type &k1, typename const T::first_type &k2) const
{ return k1 < k2; }
};
/**
* Look for a value in a \b sorted container of \b std::pairs.
* Sample use:
* \code
* const CEGUI::MouseButton mapped = getMapping<CEGUI::MouseButton, CEGUI::NoButton>(button, mouseMap);
* \endcode
* where mouseMap is a std::vector< std::pair<MouseButtonInput, CEGUI::MouseButton> >
*/
template <typename ResType, ResType failValue, typename KeyType, typename Dict>
inline ResType getMapping(KeyType k, const Dict &mapping) const
{
typename Dict::const_iterator i = std::lower_bound(mapping.begin(), mapping.end(), k, MappingCompare());
if (i != mapping.end() && !MappingCompare()(k, *i))
return i->second;
return failValue;
}
typedef std::pair<sf::Mouse::Button, CEGUI::MouseButton> MouseMapping;
typedef std::vector<MouseMapping> MouseMappings;
typedef std::pair<sf::Key::Code, CEGUI::Key::Scan> KeyMapping;
typedef std::vector<KeyMapping> KeyboardMappings;
MouseMappings mouseMap;
KeyboardMappings keyboardMap;
};
#endif
| [
"Denys@localhost"
]
| [
[
[
1,
93
]
]
]
|
10ab7832838f23112d4ee0d693500ba351a53f72 | 5df145c06c45a6181d7402279aabf7ce9376e75e | /src/bbsmenumodel.cpp | ee64e6088a53bab0935e5da5021a4cd9d160c8d2 | []
| no_license | plus7/openjohn | 89318163f42347bbac24e8272081d794449ab861 | 1ffdcc1ea3f0af43b9033b68e8eca048a229305f | refs/heads/master | 2021-03-12T22:55:57.315977 | 2009-05-15T11:30:00 | 2009-05-15T11:30:00 | 152,690 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,284 | cpp | /*
* Copyright 2009 NOSE Takafumi <[email protected]>
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include "bbsmenumgr.h"
#include "bbsmenumodel.h"
#include <QMessageBox>
BBSMenuModel::BBSMenuModel(BBSMenuManager *manager, QObject *parent)
: QAbstractItemModel(parent), m_manager(manager)
{
connect(manager, SIGNAL(itemAdded(BBSNode *)),
this, SLOT(itemAdded(BBSNode*)));
connect(manager, SIGNAL(itemRemoved(BBSNode*,int,BBSNode*)),
this, SLOT(itemRemoved(BBSNode*,int,BBSNode*)));
connect(manager, SIGNAL(itemChanged(BBSNode*)),
this, SLOT(itemChanged(BBSNode*)));
}
// QAbstractItemModel
int BBSMenuModel::columnCount(const QModelIndex &parent) const
{
return (parent.column() > 0) ? 0 : 1;
}
QVariant BBSMenuModel::data(const QModelIndex &index, int role) const
{
//QMessageBox::information(NULL, "", "aa");
if(!index.isValid()) return QVariant();
if(role != Qt::DisplayRole) return QVariant();
BBSNode *node = nodeByIndex(index);
switch(role){
case Qt::EditRole:
case Qt::DisplayRole:
return node->title;
break;
}
return QVariant();
}
Qt::ItemFlags BBSMenuModel::flags(const QModelIndex &index) const
{
if(!index.isValid()) return Qt::NoItemFlags;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
bool BBSMenuModel::hasChildren(const QModelIndex &parent) const
{
QMessageBox::information(NULL, "", "DD");
if (!parent.isValid()) return false;
BBSNode *parentItem = nodeByIndex(parent);
return (parentItem->type() == BBSNode::Folder || parentItem->type() == BBSNode::Root);
}
QVariant BBSMenuModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal && role == Qt::DisplayRole){
return tr("title");
}
return QAbstractItemModel::headerData(section, orientation, role);
}
QModelIndex BBSMenuModel::index(int row, int column, const QModelIndex &parent) const
{
QMessageBox::information(NULL, "wss", "oiu");
if(row < 0 || column < 0 || row >= rowCount(parent) || column >= columnCount(parent))
return QModelIndex();
BBSNode *parentItem, *childItem;
if(!parent.isValid()){ parentItem = m_manager->root(); }
else{ parentItem = (BBSNode*)(parent.internalPointer()); }
childItem = parentItem->children().at(row);
if(childItem){ return createIndex(row, column, childItem); }
else {return QModelIndex();}
}
QModelIndex BBSMenuModel::parent(const QModelIndex &index) const
{
if(!index.isValid()){return QModelIndex();};
BBSNode *parentItem, *childItem;
childItem = (BBSNode*)(index.internalPointer());
parentItem = childItem->parent();
if(parentItem == m_manager->root()){ return QModelIndex(); }
return createIndex(parentItem->row(), 0, parentItem);
}
bool BBSMenuModel::removeRows(int rows, int count, const QModelIndex& parent)
{
return false;
// if(row < 0 || count <= 0 || row + count > rowCount(parent)) return false;
// BBSNode *node = nodeByIndex(parent);
// for(int i = row +
}
int BBSMenuModel::rowCount(const QModelIndex &parent) const
{
if(parent.column() > 0) return 0;
QString str;
BBSNode *parentItem;
if(!parent.isValid()){ parentItem = m_manager->root(); }
else{ parentItem = (BBSNode*)(parent.internalPointer()); }
QMessageBox::information(NULL,"",str.sprintf("%d",parentItem->children().length()));
return parentItem->children().length();
}
BBSNode* BBSMenuModel::nodeByIndex(const QModelIndex& index) const
{
BBSNode *node = (BBSNode*)(index.internalPointer());
return node;
}
QModelIndex BBSMenuModel::indexOf(BBSNode *node) const
{
BBSNode *parent = node->parent();
if(!parent)
return QModelIndex();
return createIndex(parent->children().indexOf(node), 0, node);
}
void BBSMenuModel::itemAdded(BBSNode *item)
{
int row = item->parent()->children().indexOf(item);
BBSNode *parent = item->parent();
parent->removeNode(item);
beginInsertRows(indexOf(parent), row, row);
parent->addNode(item, row);
endInsertRows();
}
void BBSMenuModel::itemRemoved(BBSNode *parent, int row, BBSNode *item)
{
parent->addNode(item, row);
beginRemoveRows(indexOf(parent), row, row);
parent->removeNode(item);
endInsertRows();
}
void BBSMenuModel::itemChanged(BBSNode *item){
QModelIndex idx = indexOf(item);
emit dataChanged(idx, idx);
}
| [
"[email protected]"
]
| [
[
[
1,
159
]
]
]
|
f0457288a1e093c140ce1c332c31c3b20683c110 | 353bd39ba7ae46ed521936753176ed17ea8546b5 | /src/layer2_support/script/test/axsc_test.cpp | 319315878951cad334f61c188bf9ee3bc2922886 | []
| no_license | d0n3val/axe-engine | 1a13e8eee0da667ac40ac4d92b6a084ab8a910e8 | 320b08df3a1a5254b776c81775b28fa7004861dc | refs/heads/master | 2021-01-01T19:46:39.641648 | 2007-12-10T18:26:22 | 2007-12-10T18:26:22 | 32,251,179 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,317 | cpp | /**
* @file
* Axe 'script' test code
* @see axe_script.h
*/
#include "axsc_test.h"
#define AXSC_NO_AUTOLINK
#include "../src/axe_script.h"
/// Version of this test code
#define AXE_SCRIPT_TEST_VERSION 1
// Use proper library --------
#ifdef _DEBUG
#pragma comment( lib, "../../../output_debug/lib/axe_script.lib" )
#else
#pragma comment( lib, "../../../output_release/lib/axe_script.lib" )
#endif
/**
* Checks for the current 'error' state of the library
*/
void error( int num, const char* file, long line ) {
printf( "\n\n\n*** ERROR in %s(%u): %s\n", file, line, axsc_get_error_message(num) );
getchar();
}
/**
* Checks if this code and the lib have the same version
*/
int check_versions() {
printf( "\nGetting lib version ... " );
int lib_version = axsc_get( AXSC_VERSION );
if( lib_version != AXE_SCRIPT_TEST_VERSION ) {
printf(
"This test program and the library versions differ! Lib:%d Test:%d\n",
lib_version,
AXE_SCRIPT_TEST_VERSION );
getchar();
return( 0 );
}
printf( "Library Version: %d - This testing program: %d\n\n", lib_version, AXE_SCRIPT_TEST_VERSION );
return( 1 );
}
void print_text( int num ) {
printf( "FROM SCRIPT-> %d", num );
}
struct some_data
{
int a;
float b;
float c;
void some_method(int n) {
a = n;
}
};
/**
* Simple code to test all functionality of the library
*/
int main() {
printf( "Axe 'script' library test STARTED\n" );
// Check versions ------------------------------------
if( check_versions() == 0 ) {
return( 0 );
}
// Start ---------------------------------------------
int var_to_publish = 43;
int result;
int a = 1;
int b = 99;
int c = 1;
some_data test;
test.a = 5;
test.b = 23.221312f;
test.c = 89.0f;
// Init the engine ---
axsc_init();
// Configure the engine ---
axsc_register_variable( "int var", &var_to_publish );
axsc_register_function( "void print_text(int)", AXSC_FUNCTION(print_text) );
axsc_begin_register_class( "some_data", sizeof(some_data) );
axsc_register_property( "int a", AXSC_OFFSET(some_data, a) );
axsc_register_property( "float b", AXSC_OFFSET(some_data, b) );
axsc_register_property( "float c", AXSC_OFFSET(some_data, c) );
axsc_register_method("void some_method(int)", AXSC_METHOD(some_data, some_method));
axsc_end_register_class();
axsc_register_variable( "some_data test", &test );
// Load all scripts ---
axsc_load_file( "../layer2_support/script/test/test.axe" );
// Compile scripts ---
axsc_compile();
// Call a function ---
axsc_begin_call_function( "main" );
axsc_add_argument( &a, sizeof(a) );
axsc_add_argument( &b, sizeof(b) );
axsc_add_argument( &c, sizeof(c) );
axsc_set_return_value( &result, sizeof(result) );
axsc_end_call_function();
// End using the script engine ---
axsc_done();
// check data ---
printf( "\nVar now contains %d\n", var_to_publish );
printf( "\nScript returned %d\n", result );
// Finish --------------------------------------------
printf( "\nAxe 'script' library test FINISHED\n" );
getchar();
return( 1 );
}
/* $Id: axsc_test.cpp,v 1.2 2004/09/10 23:06:47 doneval Exp $ */
| [
"d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54"
]
| [
[
[
1,
135
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.