blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7fa06906d9c033489ea1b801f727a90cf4c6f42 | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/Controls/TreePropSheet/TreePropSheetSplitter.cpp | ebd7670da4ed6d2f22221714692cf52c2fbad3d3 | [] | no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,353 | cpp | // RealTimeSplitter.cpp
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2004 by Yves Tkaczyk
// (http://www.tkaczyk.net - [email protected])
//
// The contents of this file are subject to the Artistic License (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.opensource.org/licenses/artistic-license.html
//
// Documentation: http://www.codeproject.com/property/treepropsheetex.asp
// CVS tree: http://sourceforge.net/projects/treepropsheetex
//
// /********************************************************************
// *
// * This code is an update of SimpleSplitter written by Robert A. T. Kaldy and
// * published on code project at http://www.codeproject.com/splitter/kaldysimplesplitter.asp.
// *
// *********************************************************************/
//
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "TreePropSheetSplitter.h"
namespace TreePropSheet
{
#define FULL_SIZE 32768
inline int MulDivRound(int x, int mul, int div)
{
if(div == 0)
{
div = 1;
}
return (x * mul + div / 2) / div;
}
BEGIN_MESSAGE_MAP(CTreePropSheetSplitter, CWnd)
//{{AFX_MSG_MAP(CTreePropSheetSplitter)
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_SIZE()
ON_WM_NCCREATE()
ON_WM_WINDOWPOSCHANGING()
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CTreePropSheetSplitter::CTreePropSheetSplitter(const int nPanes, const UINT nOrientation, const int nMinSize, const int nBarThickness):
m_nPanes(nPanes),
m_nOrientation(nOrientation),
m_nBarThickness(nBarThickness),
m_nFrozenPaneCount(0),
m_bRealtimeUpdate(false),
m_bAllowUserResizing(true)
{
ASSERT(nMinSize >= 0);
// Common initialization
CommonInit();
// Set minimum pane sizes
for (int iPaneCnt = 0; iPaneCnt < m_nPanes; iPaneCnt++)
{
// Initialize minimum pane sizes.
m_pzMinSize[iPaneCnt] = nMinSize;
}
}
CTreePropSheetSplitter::CTreePropSheetSplitter(const int nPanes, const UINT nOrientation, const int* pzMinSize, const int nBarThickness):
m_nPanes(nPanes),
m_nOrientation(nOrientation),
m_nBarThickness(nBarThickness),
m_nFrozenPaneCount(0),
m_bRealtimeUpdate(false),
m_bAllowUserResizing(true)
{
// Common initialization
CommonInit();
// Set minimum pane sizes
for (int iPaneCnt = 0; iPaneCnt < m_nPanes; iPaneCnt++)
{
// Initialize minimum pane sizes.
m_pzMinSize[iPaneCnt] = pzMinSize[iPaneCnt];
}
}
CTreePropSheetSplitter::~CTreePropSheetSplitter()
{
delete[] m_pane;
delete[] m_size;
delete[] m_orig;
delete[] m_frozen;
delete[] m_pzMinSize;
}
///////////////////////////////////////////////////////////////////////////////
//
BOOL CTreePropSheetSplitter::Create(CWnd* pParent, const CRect& rect, UINT nID)
{
ASSERT(pParent);
BOOL bRet = CreateEx(0, AfxRegisterWndClass(CS_DBLCLKS, GetCursorHandle(), NULL, NULL), NULL, WS_CHILD | WS_VISIBLE, rect, pParent, nID, NULL);
return bRet;
}
///////////////////////////////////////////////////////////////////////////////
//
BOOL CTreePropSheetSplitter::Create(CWnd* pParent, UINT nID)
{
CRect rcOuter;
ASSERT(pParent);
pParent->GetClientRect(&rcOuter);
return Create( pParent, rcOuter, nID );
}
///////////////////////////////////////////////////////////////////////////////
//
BOOL CTreePropSheetSplitter::CreatePane(int nIndex, CWnd* pPaneWnd, DWORD dwStyle, DWORD dwExStyle, LPCTSTR lpszClassName)
{
CRect rcPane;
ASSERT((nIndex >= 0) && (nIndex < m_nPanes));
m_pane[nIndex] = pPaneWnd;
dwStyle |= WS_CHILD | WS_VISIBLE;
GetPaneRect(nIndex, rcPane);
return pPaneWnd->CreateEx(dwExStyle, lpszClassName, NULL, dwStyle, rcPane, this, AFX_IDW_PANE_FIRST + nIndex);
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::SetPane(int nIndex, CWnd* pPaneWnd)
{
CRect rcPane;
ASSERT((nIndex >= 0) && (nIndex < m_nPanes));
ASSERT(pPaneWnd);
ASSERT(pPaneWnd->m_hWnd);
m_pane[nIndex] = pPaneWnd;
GetPaneRect(nIndex, rcPane);
pPaneWnd->MoveWindow(rcPane, false);
}
void CTreePropSheetSplitter::SetPaneWidth(int nIndex,int nWidth)
{
ASSERT(nIndex >= 0 && nIndex < m_nPanes);
if (m_nOrientation == SSP_HORZ)
{
m_orig[nIndex + 1] = nWidth + m_nBarThickness ;
CRect rcClient;
int mouse_pos = nWidth;
for (m_nTrackIndex = 1; (m_nTrackIndex < m_nPanes && m_orig[m_nTrackIndex] < mouse_pos); m_nTrackIndex++);
m_nTracker = m_orig[m_nTrackIndex];
m_nTrackerMouseOffset = mouse_pos - m_nTracker;
GetWindowRect(&rcClient);
GetParent()->ScreenToClient(&rcClient);
m_nTrackerLength = rcClient.Height();
CRect rcOuter;
int size_sum;
GetAdjustedClientRect(&rcOuter);
size_sum = m_nOrientation == SSP_HORZ ? rcOuter.Width() : rcOuter.Height();
size_sum -= (m_nPanes - 1) * m_nBarThickness;
m_orig[m_nTrackIndex] = m_nTracker;
m_size[m_nTrackIndex - 1] = MulDivRound(m_orig[m_nTrackIndex] - m_orig[m_nTrackIndex - 1] - m_nBarThickness, FULL_SIZE, size_sum);
m_size[m_nTrackIndex] = MulDivRound(m_orig[m_nTrackIndex + 1] - m_orig[m_nTrackIndex] - m_nBarThickness, FULL_SIZE, size_sum);
ResizePanes();
}
}
void CTreePropSheetSplitter::SetPaneHeight(int nIndex,int nHeight)
{
ASSERT(nIndex >= 0 && nIndex < m_nPanes);
if (m_nOrientation == SSP_VERT)
{
m_orig[nIndex + 1] = nHeight + m_nBarThickness ;
CRect rcClient;
int mouse_pos = nHeight;
for (m_nTrackIndex = 1; (m_nTrackIndex < m_nPanes && m_orig[m_nTrackIndex] < mouse_pos); m_nTrackIndex++);
m_nTracker = m_orig[m_nTrackIndex];
m_nTrackerMouseOffset = mouse_pos - m_nTracker;
GetWindowRect(&rcClient);
GetParent()->ScreenToClient(&rcClient);
m_nTrackerLength = rcClient.Width();
CRect rcOuter;
int size_sum;
GetAdjustedClientRect(&rcOuter);
size_sum = m_nOrientation == SSP_HORZ ? rcOuter.Width() : rcOuter.Height();
size_sum -= (m_nPanes - 1) * m_nBarThickness;
m_orig[m_nTrackIndex] = m_nTracker;
m_size[m_nTrackIndex - 1] = MulDivRound(m_orig[m_nTrackIndex] - m_orig[m_nTrackIndex - 1] - m_nBarThickness, FULL_SIZE, size_sum);
m_size[m_nTrackIndex] = MulDivRound(m_orig[m_nTrackIndex + 1] - m_orig[m_nTrackIndex] - m_nBarThickness, FULL_SIZE, size_sum);
ResizePanes();
}
}
///////////////////////////////////////////////////////////////////////////////
//
CWnd* CTreePropSheetSplitter::GetPane(int nIndex) const
{
ASSERT((nIndex >= 0) && (nIndex < m_nPanes));
return m_pane[nIndex];
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::SetActivePane(int nIndex)
{
ASSERT((nIndex >= 0) && (nIndex < m_nPanes));
m_pane[nIndex]->SetFocus();
}
///////////////////////////////////////////////////////////////////////////////
//
CWnd* CTreePropSheetSplitter::GetActivePane(int& nIndex) const
{
for (int i = 0; i < m_nPanes; i++)
if (m_pane[i]->GetFocus())
{
nIndex = i;
return m_pane[i];
}
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::SetPaneSizes(const int* sizes)
{
int i, total = 0, total_in = 0;
for (i = 0; i < m_nPanes; i++)
{
ASSERT(sizes[i] >= 0);
total += sizes[i];
}
for (i = 0; i < m_nPanes - 1; i++)
{
m_size[i] = MulDivRound(sizes[i], FULL_SIZE, total);
total_in += m_size[i];
}
m_size[m_nPanes - 1] = FULL_SIZE - total_in;
RecalcLayout();
ResizePanes();
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::GetPaneRect(int nIndex, CRect& rcPane) const
{
ASSERT(nIndex >= 0 && nIndex < m_nPanes);
GetAdjustedClientRect(&rcPane);
if (m_nOrientation == SSP_HORZ)
{
rcPane.left = m_orig[nIndex];
rcPane.right = m_orig[nIndex + 1] - m_nBarThickness;
}
else
{
rcPane.top = m_orig[nIndex];
rcPane.bottom = m_orig[nIndex + 1] - m_nBarThickness;
}
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::GetBarRect(int nIndex, CRect& rcBar) const
{
ASSERT(nIndex > 0 && nIndex < m_nPanes - 1);
GetAdjustedClientRect(&rcBar);
if (m_nOrientation == SSP_HORZ)
{
rcBar.left = m_orig[nIndex];
rcBar.right = m_orig[nIndex + 1] - m_nBarThickness;
}
else
{
rcBar.top = m_orig[nIndex];
rcBar.bottom = m_orig[nIndex + 1] - m_nBarThickness;
}
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::SetFrozenPanes(const bool* frozenPanes)
{
m_nFrozenPaneCount = 0;
for( int i = 0; i < m_nPanes; ++i )
{
m_frozen[i] = frozenPanes[i];
if( frozenPanes[i] )
++m_nFrozenPaneCount;
}
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::ResetFrozenPanes()
{
for( int i = 0; i < m_nPanes; ++i )
{
m_frozen[i] = false;
}
m_nFrozenPaneCount = 0;
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::SetRealtimeUpdate(const bool bRealtime)
{
m_bRealtimeUpdate = bRealtime;
}
///////////////////////////////////////////////////////////////////////////////
//
bool CTreePropSheetSplitter::IsRealtimeUpdate() const
{
return m_bRealtimeUpdate;
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::SetAllowUserResizing(const bool bAllowUserResizing)
{
m_bAllowUserResizing = bAllowUserResizing;
// If the window exists, reset the cursor.
if( ::IsWindow( GetSafeHwnd() ) )
{
::SetClassLong( GetSafeHwnd(), GCL_HCURSOR, (LONG)GetCursorHandle() );
}
}
///////////////////////////////////////////////////////////////////////////////
//
bool CTreePropSheetSplitter::IsAllowUserResizing() const
{
return m_bAllowUserResizing;
}
///////////////////////////////////////////////////////////////////////////////
// Overridables
///////////////////////////////////////////////////////////////////////////////
void CTreePropSheetSplitter::UpdateParentRect(LPCRECT lpRectUpdate)
{
GetParent()->RedrawWindow( lpRectUpdate, NULL, RDW_UPDATENOW | RDW_INVALIDATE );
}
///////////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////////
HCURSOR CTreePropSheetSplitter::GetCursorHandle() const
{
HCURSOR hCursor;
LPCTSTR lpszCursor = IDC_ARROW;
if( m_bAllowUserResizing )
lpszCursor = m_nOrientation == SSP_HORZ ? IDC_SIZEWE : IDC_SIZENS;
hCursor = (HCURSOR)::LoadImage(0, lpszCursor, IMAGE_CURSOR, LR_DEFAULTSIZE, LR_DEFAULTSIZE, LR_SHARED );
return hCursor;
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::CommonInit()
{
ASSERT(m_nPanes > 0);
ASSERT(m_nOrientation == SSP_HORZ || m_nOrientation == SSP_VERT);
ASSERT(m_nBarThickness >= 0);
int total = 0;
m_pane = new CWnd*[m_nPanes];
m_size = new int[m_nPanes];
m_orig = new int[m_nPanes + 1];
m_pzMinSize = new int[m_nPanes];
m_frozen = new bool[m_nPanes];
::ZeroMemory(m_pane, m_nPanes * sizeof(CWnd*));
for (int i = 0; i < m_nPanes - 1; i++)
{
// Initialize sizes. Default, set equal size to all panes
m_size[i] = (FULL_SIZE + m_nPanes / 2) / m_nPanes;
total += m_size[i];
}
m_size[m_nPanes - 1] = FULL_SIZE - total;
ResetFrozenPanes();
}
///////////////////////////////////////////////////////////////////////////////
// CTreePropSheetSplitter protected
///////////////////////////////////////////////////////////////////////////////
void CTreePropSheetSplitter::RecalcLayout()
{
int i, size_sum, remain, remain_new = 0;
bool bGrow = true;
CRect rcOuter;
GetAdjustedClientRect(&rcOuter);
size_sum = m_nOrientation == SSP_HORZ ? rcOuter.Width() : rcOuter.Height();
size_sum -= (m_nPanes - 1) * m_nBarThickness;
// Frozen panes
/* Get the previous size and adjust the size of the frozen pane. We need to
do this as the size array contains ratio to FULL_SIZE. */
// If we have some frozen columns use this algorithm otherwise adjust for minimum sizes.
// If all the panes are frozen, do not use frozen pane algorithm.
bool bFrozenOnly = m_nFrozenPaneCount && m_nPanes - m_nFrozenPaneCount;
if( bFrozenOnly )
{
int prev_size_sum = m_orig[m_nPanes] - m_orig[0] - m_nBarThickness * m_nPanes;
int non_frozen_count = m_nPanes - m_nFrozenPaneCount;
int nTotalPanes = 0;
for( int i = 0; i < m_nPanes; ++i )
{
if( i + 1 == m_nPanes )
{
// Assigned all remaining value to the last pane without computation.
// This is done in order to prevent propagation of computation errors.
m_size[i] = FULL_SIZE - nTotalPanes;
}
else
{
if( m_frozen[i] )
{ // Frozen pane
m_size[i] = MulDivRound( m_size[i], prev_size_sum, size_sum);
}
else
{ // Non frozen pane
m_size[i] = MulDivRound( m_size[i], prev_size_sum, size_sum ) +
MulDivRound( size_sum - prev_size_sum, FULL_SIZE, size_sum * non_frozen_count );
}
}
// If a pane become to small, it will be adjusted with the proportional algorithm.
bFrozenOnly &= ( MulDivRound(m_size[i], size_sum, FULL_SIZE) <= m_pzMinSize[i] );
// Compute running sumof pane sizes.
nTotalPanes += m_size[i];
}
}
/* The previous section might set the flag bFrozenOnly in case a pane became too small.
In this case, we also want to execute this algorithm in order to respect the minimum
pane size constraint. */
if( !bFrozenOnly )
{
while (bGrow) // adjust sizes on the beginning
{ // and while we have growed something
bGrow = false;
remain = remain_new = FULL_SIZE;
for (i = 0; i < m_nPanes; i++) // grow small panes to minimal size
if ( MulDivRound(m_size[i], size_sum, FULL_SIZE) <= m_pzMinSize[i])
{
remain -= m_size[i];
if (MulDivRound(m_size[i], size_sum, FULL_SIZE) < m_pzMinSize[i])
{
if (m_pzMinSize[i] > size_sum)
m_size[i] = FULL_SIZE;
else
m_size[i] = MulDivRound(m_pzMinSize[i], FULL_SIZE, size_sum);
bGrow = true;
}
remain_new -= m_size[i];
}
if (remain_new <= 0) // if there isn't place to all panes
{ // set the minimal size to the leftmost/topmost
remain = FULL_SIZE; // and set zero size to the remainimg
for (i = 0; i < m_nPanes; i++)
{
if (size_sum == 0)
m_size[i] = 0;
else
m_size[i] = MulDivRound(m_pzMinSize[i], FULL_SIZE, size_sum);
if (m_size[i] > remain)
m_size[i] = remain;
remain -= m_size[i];
}
break;
}
if (remain_new != FULL_SIZE) // adjust other pane sizes, if we have growed some
for (i = 0; i < m_nPanes; i++)
if ( MulDivRound(m_size[i], size_sum, FULL_SIZE) != m_pzMinSize[i])
m_size[i] = MulDivRound(m_size[i], remain_new, remain);
}
}
// calculate positions (in pixels) from relative sizes
m_orig[0] = ( m_nOrientation == SSP_HORZ ? rcOuter.left:rcOuter.top );
for (i = 0; i < m_nPanes - 1; i++)
m_orig[i + 1] = m_orig[i] + MulDivRound(m_size[i], size_sum, FULL_SIZE) + m_nBarThickness;
m_orig[m_nPanes] = m_orig[0] + size_sum + m_nBarThickness * m_nPanes;
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::ResizePanes()
{
int i;
CRect rcOuter;
GetAdjustedClientRect(&rcOuter);
if (m_nOrientation == SSP_HORZ)
for (i = 0; i < m_nPanes; i++)
{
if (m_pane[i])
m_pane[i]->MoveWindow(m_orig[i], rcOuter.top, m_orig[i + 1] - m_orig[i] - m_nBarThickness, rcOuter.Height(), FALSE);
}
else
for (i = 0; i < m_nPanes; i++)
{
if (m_pane[i])
m_pane[i]->MoveWindow(rcOuter.left, m_orig[i], rcOuter.Width(), m_orig[i + 1] - m_orig[i] - m_nBarThickness, FALSE);
}
UpdateParentRect( &rcOuter );
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::InvertTracker()
{
CDC* pDC = GetDC();
CBrush* pBrush = CDC::GetHalftoneBrush();
HBRUSH hOldBrush;
CRect rcWnd;
GetAdjustedClientRect(&rcWnd);
hOldBrush = (HBRUSH)SelectObject(pDC->m_hDC, pBrush->m_hObject);
if (m_nOrientation == SSP_HORZ)
pDC->PatBlt(m_nTracker - m_nBarThickness - rcWnd.left, 0, m_nBarThickness, m_nTrackerLength, PATINVERT);
else
pDC->PatBlt(0, m_nTracker - m_nBarThickness - rcWnd.top, m_nTrackerLength, m_nBarThickness, PATINVERT);
if (hOldBrush != NULL)
SelectObject(pDC->m_hDC, hOldBrush);
ReleaseDC(pDC);
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::GetAdjustedClientRect(CRect* pRect) const
{
GetWindowRect(pRect);
GetParent()->ScreenToClient(pRect);
}
///////////////////////////////////////////////////////////////////////////////
// CTreePropSheetSplitter messages
///////////////////////////////////////////////////////////////////////////////
void CTreePropSheetSplitter::OnPaint()
{
CPaintDC dc(this);
CRect rcClip, rcClipPane;
int i;
// retrieve the background brush
HWND hWnd = GetParent()->GetSafeHwnd();
// send a message to the dialog box
HBRUSH hBrush = (HBRUSH)::SendMessage(hWnd, WM_CTLCOLORDLG, (WPARAM)dc.m_ps.hdc, (LPARAM)hWnd);
ASSERT( hBrush );
CRect rcWnd;
GetAdjustedClientRect(&rcWnd);
dc.GetClipBox(&rcClip);
CRect rect;
int top, left;
if (m_nOrientation == SSP_HORZ)
{
for (i = 1; i < m_nPanes; i++)
{
left = m_orig[i] - m_nBarThickness - rcWnd.left;
top = rcClip.top;
rect.SetRect( left, top, left + m_nBarThickness, top + rcClip.Height() );
dc.FillRect( &rect, CBrush::FromHandle(hBrush) );
}
}
else
{
for (i = 1; i < m_nPanes; i++)
{
left = rcClip.left;
top = m_orig[i] - m_nBarThickness - rcWnd.top;
rect.SetRect( left, top, left + rcClip.Width(), top + m_nBarThickness );
dc.FillRect( &rect, CBrush::FromHandle(hBrush) );
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
RecalcLayout();
ResizePanes();
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::OnLButtonDown(UINT nFlags, CPoint point)
{
UNREFERENCED_PARAMETER(nFlags);
// Must be in AllowUserResizing mode.
if( !m_bAllowUserResizing )
return;
CRect rcClient;
int mouse_pos = m_nOrientation == SSP_HORZ ? point.x : point.y;
SetCapture();
for (m_nTrackIndex = 1; (m_nTrackIndex < m_nPanes && m_orig[m_nTrackIndex] < mouse_pos); m_nTrackIndex++);
m_nTracker = m_orig[m_nTrackIndex];
m_nTrackerMouseOffset = mouse_pos - m_nTracker;
GetWindowRect(&rcClient);
GetParent()->ScreenToClient(&rcClient);
m_nTrackerLength = m_nOrientation == SSP_HORZ ? rcClient.Height() : rcClient.Width();
InvertTracker();
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::OnLButtonUp(UINT nFlags, CPoint point)
{
UNREFERENCED_PARAMETER(nFlags);
UNREFERENCED_PARAMETER(point);
if (GetCapture() != this)
return;
CRect rcOuter;
int size_sum;
GetAdjustedClientRect(&rcOuter);
size_sum = m_nOrientation == SSP_HORZ ? rcOuter.Width() : rcOuter.Height();
size_sum -= (m_nPanes - 1) * m_nBarThickness;
InvertTracker();
ReleaseCapture();
m_orig[m_nTrackIndex] = m_nTracker;
m_size[m_nTrackIndex - 1] = MulDivRound(m_orig[m_nTrackIndex] - m_orig[m_nTrackIndex - 1] - m_nBarThickness, FULL_SIZE, size_sum);
m_size[m_nTrackIndex] = MulDivRound(m_orig[m_nTrackIndex + 1] - m_orig[m_nTrackIndex] - m_nBarThickness, FULL_SIZE, size_sum);
ResizePanes();
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::OnMouseMove(UINT nFlags, CPoint point)
{
UNREFERENCED_PARAMETER(nFlags);
if (GetCapture() != this)
return;
InvertTracker();
m_nTracker = (m_nOrientation == SSP_HORZ ? point.x : point.y) - m_nTrackerMouseOffset;
ASSERT( m_nTrackIndex > 0 );
if (m_nTracker > m_orig[m_nTrackIndex + 1] - m_nBarThickness - m_pzMinSize[m_nTrackIndex])
{
m_nTracker = m_orig[m_nTrackIndex + 1] - m_nBarThickness - m_pzMinSize[m_nTrackIndex];
}
else if (m_nTracker < m_orig[m_nTrackIndex - 1] + m_nBarThickness + m_pzMinSize[m_nTrackIndex-1])
{
m_nTracker = m_orig[m_nTrackIndex - 1] + m_nBarThickness + m_pzMinSize[m_nTrackIndex-1];
}
InvertTracker();
CRect rcOuter;
GetAdjustedClientRect(&rcOuter);
// Real-time update.
if( m_bRealtimeUpdate )
{
m_orig[m_nTrackIndex] = m_nTracker;
ResizePanes();
}
}
///////////////////////////////////////////////////////////////////////////////
//
BOOL CTreePropSheetSplitter::OnNcCreate(LPCREATESTRUCT lpCreateStruct)
{
if (!CWnd::OnNcCreate(lpCreateStruct))
return FALSE;
CWnd* pParent = GetParent();
ASSERT_VALID(pParent);
pParent->ModifyStyleEx(WS_EX_CLIENTEDGE, 0, SWP_DRAWFRAME);
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
//
void CTreePropSheetSplitter::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos)
{
lpwndpos->flags |= SWP_NOCOPYBITS;
CWnd::OnWindowPosChanging(lpwndpos);
}
}; // namespace TreePropSheet
| [
"[email protected]"
] | [
[
[
1,
726
]
]
] |
f71afcf3cc8ecea77f36939915ff256f750f8820 | a36d7a42310a8351aa0d427fe38b4c6eece305ea | /render_win32/ReleasableEffectResourceDX9.h | 2e03d189689c5dac9fad3fb8e8263a5ee6a5e395 | [] | no_license | newpolaris/mybilliard01 | ca92888373c97606033c16c84a423de54146386a | dc3b21c63b5bfc762d6b1741b550021b347432e8 | refs/heads/master | 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | h | #pragma once
namespace my_render_win32_dx9 {
MY_INTERFACE ReleasableEffectResourceDX9 : EXTENDS_INTERFACE( ReleasableResourceDX9 ) {
virtual void setEffect( LPD3DXEFFECT effect ) PURE;
};
} | [
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
] | [
[
[
1,
12
]
]
] |
8c5f6fa0387bc8d715140a1f7e32cba39f2002fe | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/WorkLayer/NatTraversal/TraverseBySvr.h | 45629aa90f71b75473c6382a324f397d2197905c | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | h | #pragma once
#include "TraverseStrategy.h"
#include "ClientList.h"
#include "updownclient.h"
#include "ListenSocket.h"
#include "sockets.h"
class CTraverseBySvr : public CTraverseStrategy
{
public:
CTraverseBySvr(const uchar * uh, CTraverseStrategy * pNext);
virtual bool Initialize();
virtual void SendPacket();
virtual bool ProcessPacket(const uchar * data, int len, DWORD ip, WORD port);
private:
void StopTraverse();
int SendConnectReq();
int SendPingPacket();
void OnRecvSync(const uchar * data, int len, DWORD ip, WORD port);
void OnRecvPing(const uchar * data, int len, DWORD ip, WORD port);
DWORD m_dwTraverseIp;
WORD m_wTraversePort;
int m_nSendReqCount ,m_nSendPingCount , m_nSendConnAck;
int m_nPassivePing;
DWORD m_SendReqTime, m_SendPingTime, m_SendConnAckTime;
DWORD m_dwClientIp;
WORD m_wClientPort;
CAsyncSocketEx * m_Sock;
bool m_bAcceptor;
bool m_bByBuddy;
DWORD m_dwState;
DWORD m_dwConnAskNumber;
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
37
]
]
] |
044121ae7ccd6c060d96d6077470eabc035ef1b2 | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /inc/ListBox.h | 17e3be150a53847c07e72b6033262362365912ad | [] | no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,597 | h | /*
============================================================================
Name : TurkeyListBox.h
Author : 浮生若茶
Version :
Copyright : Your copyright notice
Description : CListBox declaration
说明:该类可以根据需要做修改,但不要添加与列表的显示无关的逻辑进来
待添加功能 : 添加选项,使得选项打开时,当前项展开,显示详细信息
在每一项的前面显示图标
添加对CSlide的使用
使文字居中显示(默认),尽量使此功能与CSlide整合
限制文字长度的选项,过长的文字用省略号代替
使图片上下居中
待改进 : 使数据与界面完全分离,即CListBox中不保存要显示的内容与每项的具体信息
使每一项与列表分离,以便定制列表
将此类再抽象(是否有必要)
考虑是否有需要简化接口
如何保证用户代码传入的CListBoxItem是同一种类型
============================================================================
*/
#ifndef __LISTBOX_H__
#define __LISTBOX_H__
#include "Control.h"
#include "ListBoxItem.h"
#include "PreDefine.h"
#include "ControlObserver.h"
class CScrollBar;
//////////////////////////////////////////////////////////////////////////
//CListBox
//////////////////////////////////////////////////////////////////////////
class CListBox : public CControl , public MDrawEventObserver
{
friend class CListBoxItem;
//private:
public: // Constructors and destructor
CListBox(MDrawEventObserver& aObserver,const TRect& aRect,const CFont* aFont,TInt aScrollWidth);
~CListBox();
public://From CControl
virtual void Draw(CGraphic& aGraphic)const;
virtual TBool KeyEventL(TInt aKeyCode);
virtual TBool HandleCommandL(TInt aCommand);
virtual void SizeChanged(const TRect& aScreenRect);
virtual void ActivateL();
virtual void Deactivate();
public://From MDrawEventObserver
virtual void ControlRequestDraw();
public:
//向ListBox中添加一个CListBoxItem类型的指针,
//同时把该指针的拥有权交给ListBox,当
//调用Remove、Reset等方法时,ListBox会删除这些实例
void AppendL(CListBoxItem* aItem);
void Remove(TInt aIndex);
void RemoveCurItem();
void Reset();
TInt Count()const; //返回项目的个数
TInt CurItemIndex()const;
CListBoxItem& GetItem(TInt aIndex) const; //获取指定项
CListBoxItem& CurItem() const; //获取当前列表项
CScrollBar* ScrollBar()const; //返回滚动条,以便自定义配置
void SetTextColor(const TRgb& aTextColor,const TRgb& aTextColorWhenFocus);
//void SetBackgroundColor(const)
void Layout();
void SetUseHotKey(TBool aUseHotKey);
//卞涛增加,获取当前界面可显示的行数,在外面调用判断是否需要翻屏
TInt GetScreenMaxLine(){ return iMaxLinePerPage; }
private:
void CalculateSize();
void ActiveCurItem();
void DeactivateCurItem();
void LayoutScrollBar();
void Assert()const;
private:
RPointerArray<CListBoxItem> iItemArray;
CScrollBar* iScrollBar;
const CFont* iFont;
TRect iClientRect;
TSize iItemSize;
//绘制文本的颜色,有待扩展,以便配置子项
TRgb iTextColor;
TRgb iTextColorWhenFocus;
TInt iCurScreenIndex; //相对索引
TInt iLineHeight; //行距
TInt iMaxLinePerPage;
TInt iScrollWidth;
TBool iAlreadyLayout; //在使用前必须调用Layout(),否则不能正常执行
TBool iUseHotKey;
};
#endif // __LISTBOX_H__
| [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
] | [
[
[
1,
125
]
]
] |
62fcc86e0cb6359f726347a1e8b8476f7d87379d | df070aa6eb5225412ebf0c3916b41449edfa16ac | /AVS_Transcoder_SDK/kernel/video/tavs/avs_enc/src/image.cpp | 7515202c393bec8f6c91fb399b6b54a21cf0dacd | [] | no_license | numericalBoy/avs-transcoder | 659b584cc5bbc4598a3ec9beb6e28801d3d33f8d | 56a3238b34ec4e0bf3a810cedc31284ac65361c5 | refs/heads/master | 2020-04-28T21:08:55.048442 | 2010-03-10T13:28:18 | 2010-03-10T13:28:18 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 115,296 | cpp | /*
*****************************************************************************
* COPYRIGHT AND WARRANTY INFORMATION
*
* Copyright 2003, Advanced Audio Video Coding Standard, Part II
*
* DISCLAIMER OF WARRANTY
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY.
* The AVS Working Group doesn't represent or warrant that the programs
* furnished here under are free of infringement of any third-party patents.
* Commercial implementations of AVS, including shareware, may be
* subject to royalty fees to patent holders. Information regarding
* the AVS patent policy for standardization procedure is available at
* AVS Web site http://www.avs.org.cn. Patent Licensing is outside
* of AVS Working Group.
*
* THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY.
************************************************************************
*/
/*
*************************************************************************************
* File name:
* Function:
*
*************************************************************************************
*/
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/timeb.h>
#include <string.h>
#include <memory.h>
#include <assert.h>
#include "global.h"
#include <xmmintrin.h>
#include <emmintrin.h>
#include "windows.h"
#define TO_SAVE 4711
#define FROM_SAVE 4712
#define Clip(min,max,val) (((val)<(min))?(min):(((val)>(max))?(max):(val)))
TLS static byte clip0c[16]={0,128,0,128,0,128,0,128,0,128,0,128,0,128,0,128};
TLS static byte clip255c[16]={0,127,0,127,0,127,0,127,0,127,0,127,0,127,0,127};
TLS static byte round1c[16]={1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0};
TLS static byte round4c[16]={4,0,4,0,4,0,4,0,4,0,4,0,4,0,4,0};
TLS static byte round8c[16]={8,0,8,0,8,0,8,0,8,0,8,0,8,0,8,0};
TLS static byte round16c[16]={16,0,16,0,16,0,16,0,16,0,16,0,16,0,16,0};
TLS static byte round32c[16]={32,0,32,0,32,0,32,0,32,0,32,0,32,0,32,0};
TLS static byte round64c[16]={64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0};
TLS static byte round512c[16]={0,2,0,0,0,2,0,0,0,2,0,0,0,2,0,0};
#define IClip( Min, Max, Val) (((Val)<(Min))? (Min):(((Val)>(Max))? (Max):(Val)))
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::picture_header()
{
int len;
img->cod_counter = 0;
if(img->type==INTRA_IMG)
len = IPictureHeader(img->number);
else
len = PBPictureHeader();
// Rate control
img->NumberofHeaderBits +=len;
if(img->BasicUnit<img->total_number_mb)
img->NumberofBasicUnitHeaderBits +=len;
// Update statistics
stat->bit_slice += len;
stat->bit_use_header[img->type] += len;
WriteFrameFieldMBInHeader = 0;
}
int c_avs_enc::encode_one_frame ()
{
time_t ltime1;
time_t ltime2;
#ifdef ROI_ENABLE
int_32_t erroCode;
#endif
#ifdef WIN32
struct _timeb tstruct1;
struct _timeb tstruct2;
#else
struct timeb tstruct1;
struct timeb tstruct2;
#endif
int_32_t tmp_time;
int_32_t bits_frm = 0, bits_fld = 0;
float dis_frm = 0, dis_frm_y = 0, dis_frm_u = 0, dis_frm_v = 0;
float dis_fld = 0, dis_fld_y = 0, dis_fld_u = 0, dis_fld_v = 0;
int_32_t bits = 0;
#ifdef WIN32
_ftime (&tstruct1); // start time ms
#else
ftime (&tstruct1);
#endif
time (<ime1); // start time s
init_frame(); // initial frame variables
CalculateFrameNumber();
ReadOneFrame ();
CopyFrameToOldImgOrgVariables();
#ifdef ROI_ENABLE
//detect roi
erroCode=detect_roi(YCbCr, w, h, ROIArray);
if (erroCode)
{
printf("error in detecting roi function\n");
}
#endif
//Rate control
img->FieldControl=0;
if(input->RCEnable == 1)
{
/*update the number of MBs in the basic unit for MB adaptive coding*/
img->BasicUnit = input->basicunit;
rc_init_pict(1,0,1);
img->qp = updateQuantizationParameter(0);
}
else if ( input->RCEnable == 3 )
{
img->qp = (img->type == B_IMG) ? i_QPb : i_QPip;
}
if (input->InterlaceCodingOption == FRAME_CODING) // !! frame coding or paff coding
{
put_buffer_frame (); //initialize frame buffer
//frame picture
img->progressive_frame = 1;
img->picture_structure = 1;
img->TopFieldFlag = 0;
if (img->type == B_IMG)
Bframe_ctr++; // Bframe_ctr only used for statistics, should go to stat->
// !! calculate the weighting parameter
if(img->type != INTRA_IMG && input->picture_weighting_flag == 1)
{
estimate_weighting_factor();
}
else
{
img->LumVarFlag = 0 ;
}
code_a_picture (frame_pic);
if (img->type!=B_IMG)
{
Update_Picture_Buffers();
}
stat->bit_ctr_emulationprevention += stat->em_prev_bits_frm;
if (img->type != B_IMG) //all I- and P-frames
{
#ifdef _FAST_INTERPOLATION_
UnifiedOneForthPix_sse (imgY);
#else
UnifiedOneForthPix_c_sse(imgY);
#endif
}
time (<ime2); // end time sec
#ifdef WIN32
_ftime (&tstruct2); // end time ms
#else
ftime (&tstruct2); // end time ms
#endif
tmp_time = (int)((ltime2 * 1000 + tstruct2.millitm) - (ltime1 * 1000 + tstruct1.millitm));
tot_time = tot_time + tmp_time;
}
writeout_picture ();
FreeBitstream();
find_snr ();
GBIM_value_frm = 0;//find_GBIM(imgY);
GBIM_value=0;
GBIM_value += GBIM_value_frm;
#ifdef _OUTPUT_RECON_IMG_
// Write reconstructed images
write_reconstructed_image ();
#endif
//Rate control
if(input->RCEnable == 1)
{
bits = stat->bit_ctr-stat->bit_ctr_n;
rc_update_pict_frame(bits);
}
goprate += (stat->bit_ctr-stat->bit_ctr_n);
#ifdef _DEBUG
if (img->number == 0)
ReportFirstframe(tmp_time);
else
{
//Rate control
if(input->RCEnable == 1)
{
if(input->InterlaceCodingOption == FRAME_CODING)
bits = stat->bit_ctr-stat->bit_ctr_n;
else
{
bits = stat->bit_ctr -Pprev_bits; // used for rate control update */
Pprev_bits = stat->bit_ctr;
}
}
switch (img->type)
{
case INTRA_IMG:
stat->bit_ctr_P += stat->bit_ctr - stat->bit_ctr_n;
ReportIntra(tmp_time);
break;
case B_IMG:
stat->bit_ctr_B += stat->bit_ctr - stat->bit_ctr_n;
ReportB(tmp_time);
break;
default: // P, P_MULTPRED?
stat->bit_ctr_P += stat->bit_ctr - stat->bit_ctr_n;
ReportP(tmp_time);
}
}
#endif
stat->bit_ctr_n = stat->bit_ctr;
//Rate control
if(input->RCEnable == 1)
{
rc_update_pict(bits);
/*update the parameters of quadratic R-D model*/
if (img->type == INTER_IMG)
{
if (input->InterlaceCodingOption == FRAME_CODING)
{
updateRCModel();
}
else if (img->IFLAG == 0)
{
updateRCModel();
}
}
}
return 1;
}
int c_avs_enc:: writeout_picture()
{
assert (currBitStream->bits_to_go == 8);
WriteBitstreamtoFile();
return 0;
}
void c_avs_enc::code_a_picture (Picture *frame)
{
stat->em_prev_bits_frm = 0;
stat->em_prev_bits = &stat->em_prev_bits_frm;
AllocateBitstream();
picture_header();
picture_data();
frame->bits_per_picture = 8 * (currBitStream->byte_pos);
if (input->InterlaceCodingOption != FRAME_CODING)
{
find_distortion ();
frame->distortion_y = snr->snr_y;
frame->distortion_u = snr->snr_u;
frame->distortion_v = snr->snr_v;
}
}
/*
*************************************************************************
* Function:Initializes the parameters for a new frame
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::init_frame ()
{
int i, j, k;
int prevP_no, nextP_no;
img->top_bot = -1;
img->current_mb_nr = 0;
img->current_slice_nr = 0;
img->coded_mb_nr = 0;
img->mb_y = img->mb_x = 0;
img->block_y = img->pix_y = img->pix_c_y = 0;
img->block_x = img->pix_x = img->block_c_x = img->pix_c_x = 0;
refFrArr = refFrArr_frm;
fw_refFrArr = fw_refFrArr_frm;
bw_refFrArr = bw_refFrArr_frm;
if (img->type != B_IMG)
{
if((gframe_no%input->GopLength)>=input->GopLength - input->successive_Bframe)
{
img->tr = gframe_no;
}
else if(img->type==INTRA_IMG)
{
img->tr = gframe_no;
}
else
{
img->tr = gframe_no + input->successive_Bframe;
}
if (img->imgtr_last_P_frm < 0)
img->imgtr_last_P_frm = 0;
img->imgtr_last_prev_P_frm = img->imgtr_last_P_frm;
img->imgtr_last_P_frm = img->imgtr_next_P_frm;
img->imgtr_next_P_frm = picture_distance;
if (img->number != 0 && input->successive_Bframe != 0) // B pictures to encode
nextP_tr_frm = picture_distance;
if(!input->RCEnable)
{
if (img->type == INTRA_IMG)
img->qp = input->qp0; // set quant. parameter for I-frame
else
{
img->qp = input->qpN;
}
}
}
else
{
img->p_interval = input->successive_Bframe + 1;
prevP_no = (img->number - 1) * img->p_interval;
nextP_no = (img->number) * img->p_interval;
img->b_interval = (int) ((float) (input->successive_Bframe + 1) / (input->successive_Bframe + 1.0) + 0.49999);
img->tr = gframe_no-1;
if (img->tr >= nextP_no)
img->tr = nextP_no - 1;
if(!input->RCEnable)
img->qp = input->qpB;
// initialize arrays
if(!img->picture_structure) //field coding
{
for (k = 0; k < 2; k++)
{
for (i = 0; i < img->height / BLOCK_SIZE; i++)
{
for (j = 0; j < img->width / BLOCK_SIZE + 4; j++)
{
tmp_fwMV[k][i][j] = 0;
tmp_bwMV[k][i][j] = 0;
dfMV[k][i][j] = 0;
dbMV[k][i][j] = 0;
}
}
}
for (i = 0; i < img->height / B8_SIZE; i++)
{
for (j = 0; j < img->width / BLOCK_SIZE; j++)
{
fw_refFrArr[i][j] = bw_refFrArr[i][j] = -1;
}
}
}
else
{
for (k = 0; k < 2; k++)
{
for (i = 0; i < img->height / BLOCK_SIZE; i++)
{
for (j = 0; j < img->width / BLOCK_SIZE + 4; j++)
{
tmp_fwMV[k][i][j] = 0;
tmp_bwMV[k][i][j] = 0;
dfMV[k][i][j] = 0;
dbMV[k][i][j] = 0;
}
}
}
for (i = 0; i < img->height / BLOCK_SIZE; i++)
{
for (j = 0; j < img->width / BLOCK_SIZE; j++)
{
fw_refFrArr[i][j] = bw_refFrArr[i][j] = -1;
}
}
}
}
stat->bit_slice = 0;
//for rm52j
picture_distance = img->tr;
}
void c_avs_enc::init_field ()
{
img->current_mb_nr = 0;
img->current_slice_nr = 0;
stat->bit_slice = 0;
img->coded_mb_nr = 0;
img->mb_y = img->mb_x = 0;
img->block_y = img->pix_y = img->pix_c_y = 0;
img->block_x = img->pix_x = img->block_c_x = img->pix_c_x = 0;
img->mb_no_currSliceLastMB = ( input->slice_row_nr != 0 )
? min(input->slice_row_nr * img->img_width_in_mb - 1, img->img_width_in_mb * img->img_height_in_mb - 1)
: img->img_width_in_mb * img->img_height_in_mb - 1 ;
}
/*
*************************************************************************
* Function:Writes reconstructed image(s) to file
This can be done more elegant!
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::write_reconstructed_image ()
{
int i, j, k;
if (p_rec != NULL)
{
if (img->type != B_IMG)
{
if (input->successive_Bframe == 0)
{
for (i = 0; i < img->height; i++)
for (j = 0; j < img->width; j++)
{
fputc (imgY[i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgY_org[i][j], p_org_dec);
#endif
}
for (k = 0; k < 2; ++k)
for (i = 0; i < img->height / 2; i++)
for (j = 0; j < img->width / 2; j++)
{
fputc (imgUV[k][i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgUV_org[k][i][j], p_org_dec);
#endif
}
}
else if ((gframe_no%input->GopLength) == 0)
{
for (i = 0; i < img->height; i++)
for (j = 0; j < img->width; j++)
{
fputc (imgY[i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgY_org[i][j], p_org_dec);
#endif
}
for (k = 0; k < 2; ++k)
for (i = 0; i < img->height / 2; i++)
for (j = 0; j < img->width / 2; j++)
{
fputc (imgUV[k][i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgUV_org[k][i][j], p_org_dec);
#endif
}
}
// next P picture. This is saved with recon B picture after B picture coding
if (img->number != 0 && input->successive_Bframe != 0)
{
if(((gframe_no%input->GopLength)>=input->GopLength - input->successive_Bframe))
{
for (i = 0; i < img->height; i++)
for (j = 0; j < img->width; j++)
{
fputc (imgY[i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgY_org[i][j], p_org_dec);
#endif
}
for (k = 0; k < 2; ++k)
for (i = 0; i < img->height / 2; i++)
for (j = 0; j < img->width / 2; j++)
{
fputc (imgUV[k][i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgUV_org[k][i][j], p_org_dec);
#endif
}
}
else
{
for (i = 0; i < img->height; i++)
for (j = 0; j < img->width; j++)
{
nextP_imgY[i][j] = imgY[i][j];
#ifdef _OUTPUT_DEC_IMG_
org_nextP_imgY[i][j] = imgY_org[i][j];
#endif
}
for (k = 0; k < 2; ++k)
for (i = 0; i < img->height / 2; i++)
for (j = 0; j < img->width / 2; j++)
{
nextP_imgUV[k][i][j] = imgUV[k][i][j];
#ifdef _OUTPUT_DEC_IMG_
org_nextP_imgUV[k][i][j] = imgUV_org[k][i][j];
#endif
}
}
}
}
else
{
for (i = 0; i < img->height; i++)
for (j = 0; j < img->width; j++)
{
fputc (imgY[i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgY_org[i][j], p_org_dec);
#endif
}
for (k = 0; k < 2; ++k)
for (i = 0; i < img->height / 2; i++)
for (j = 0; j < img->width / 2; j++)
{
fputc (imgUV[k][i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(imgUV_org[k][i][j], p_org_dec);
#endif
}
// If this is last B frame also store P frame
if (img->b_frame_to_code == input->successive_Bframe)
{
// save P picture
for (i = 0; i < img->height; i++)
for (j = 0; j < img->width; j++)
{
fputc (nextP_imgY[i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(org_nextP_imgY[i][j], p_org_dec);
#endif
}
for (k = 0; k < 2; ++k)
for (i = 0; i < img->height / 2; i++)
for (j = 0; j < img->width / 2; j++)
{
fputc (nextP_imgUV[k][i][j], p_rec);
#ifdef _OUTPUT_DEC_IMG_
fputc(org_nextP_imgUV[k][i][j], p_org_dec);
#endif
}
}
}
}
fflush(p_rec);
}
/*
*************************************************************************
* Function:Choose interpolation method depending on MV-resolution
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
__inline void c_avs_enc::avs_const_initialize()
{
clip0 = _mm_loadu_si128((const __m128i *)clip0c);
clip255 = _mm_loadu_si128((const __m128i *)clip255c);
round1 = _mm_loadu_si128((const __m128i *)round1c);
round4 = _mm_loadu_si128((const __m128i *)round4c);
round8 = _mm_loadu_si128((const __m128i *)round8c);
round16 = _mm_loadu_si128((const __m128i *)round16c);
round32 = _mm_loadu_si128((const __m128i *)round32c);
round64 = _mm_loadu_si128((const __m128i *)round64c);
round512 = _mm_loadu_si128((const __m128i *)round512c);
}
__inline __m128i c_avs_enc::avs_combine_w2b(__m128i xmm0, __m128i xmm1)
{
xmm0 = _mm_packus_epi16(xmm0,xmm1);
return xmm0;
}
__inline __m128i c_avs_enc::avs_combine_d2w(__m128i xmm0, __m128i xmm1)
{
xmm0 = _mm_packus_epi16(xmm0,xmm1);
xmm1 = _mm_xor_si128(xmm1,xmm1);
xmm0 = _mm_packus_epi16(xmm0,xmm1);
return xmm0;
}
__inline __m128i c_avs_enc::avs_filter_halfpel_w(__m128i xmm0, __m128i xmm1, __m128i xmm2)
{
xmm1 = _mm_add_epi16(xmm1,xmm2);
xmm2 = _mm_slli_epi16(xmm1,2);
xmm1 = _mm_add_epi16(xmm1,xmm2);
xmm2 = _mm_sub_epi16(xmm1,xmm0);
return xmm2;
}
__inline __m128i c_avs_enc::avs_filter_quaterpel_w(__m128i xmm0, __m128i xmm1, __m128i xmm2)
{
xmm1 = _mm_add_epi16(xmm1,xmm2);
xmm2 = _mm_slli_epi16(xmm1,3);
xmm1 = _mm_sub_epi16(xmm2,xmm1);
//xmm1 = _mm_add_epi16(xmm1,round1);
xmm1 = _mm_srai_epi16(xmm1,1); // bit width control
//xmm0 = _mm_add_epi16(xmm0,round1);
xmm0 = _mm_srai_epi16(xmm0,1); // bit width control
xmm2 = _mm_add_epi16(xmm1,xmm0);
return xmm2;
}
__inline __m128i c_avs_enc::avs_filter_quaterpel_d(__m128i xmm0, __m128i xmm1, __m128i xmm2)
{
xmm1 = _mm_add_epi32(xmm1,xmm2);
xmm2 = _mm_slli_epi32(xmm1,3);
xmm1 = _mm_sub_epi32(xmm2,xmm1);
xmm2 = _mm_add_epi32(xmm1,xmm0);
return xmm2;
}
__inline __m128i c_avs_enc::avs_clip_0_255_w(__m128i xmm0)
{
xmm0 = _mm_adds_epi16(xmm0,clip255);
xmm0 = _mm_subs_epi16(xmm0,clip255);
xmm0 = _mm_adds_epi16(xmm0,clip0);
xmm0 = _mm_subs_epi16(xmm0,clip0);
return xmm0;
}
__inline __m128i c_avs_enc::avs_zero(__m128i xmm0)
{
return _mm_xor_si128(xmm0,xmm0);
}
/*
*************************************************************************
* Function:Quarter Pel Intelpolation for SSE Optimization
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::UnifiedOneForthPix_sse (pel_t ** imgY)
{
int img_pad_width,img_pad_height;
int xx,yy;
double temp=0;
__int16 tmpw0;
__m128i xmm0,xmm1,xmm2,xmm3,xmm4,xmm5,xmm6,xmm7,xmm8,xmm9;
__m128i qtmp0,qtmp1;
/////////////////////////////将所有可对齐载入的数据对齐载入!!!!!!!!!
img_pad_width = (img->width + (IMG_PAD_SIZE<<1));
img_pad_height = (img->height + (IMG_PAD_SIZE<<1));
interpolation = mref[0];
// initialize
avs_const_initialize();
xmm0=_mm_setzero_si128();
/*************************************************************
// Basic Quater Pel Interpolation Unit
//
// ○ ==> Interger Pel Position
// □ ==> Half Pel Position
// △ ==> Quarter Pel Position
//************************************************************
// ○ △ □ △
//
// △ △ △ △
//
// □ △ □ △
//
// △ △ △ △
*************************************************************/
// Pre Stuffing for Marginal Conditions
// * * * *
// o * * o
// o * * o
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
// o o o o
// x x x x
// x x x x
// x x x x
tmpw0 = imgY[yy-IMG_PAD_SIZE][0];
xmm0 = _mm_insert_epi16(xmm0,(tmpw0<<3),0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)tmp02[yy] , xmm0);
_mm_store_si128((__m128i*)(tmp02[yy]+8), xmm0);
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i *)interpolation[0][0][yy] , xmm0);
_mm_store_si128((__m128i *)interpolation[0][1][yy] , xmm0);
_mm_store_si128((__m128i *)interpolation[0][2][yy] , xmm0);
_mm_store_si128((__m128i *)interpolation[0][3][yy] , xmm0);
tmpw0 = imgY[yy-IMG_PAD_SIZE][img->width-1];
xmm0 = _mm_insert_epi16(xmm0,(tmpw0<<3),0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i *)(tmp02[yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i *)(tmp02[yy]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i *)(interpolation[0][0][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i *)(interpolation[0][1][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i *)(interpolation[0][2][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i *)(interpolation[0][3][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
}
// * o o *
// * * * *
// * * * *
// * o o *
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// o x x x
// o x x x
// o x x x
// o x x x
xmm0 = _mm_loadu_si128((const __m128i*)(imgY[0]+xx-IMG_PAD_SIZE));
xmm2 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm3 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm2 = _mm_srli_epi16(xmm2,8);
xmm3 = _mm_srli_epi16(xmm3,8);
xmm2 = _mm_slli_epi16(xmm2,3);
xmm3 = _mm_slli_epi16(xmm3,3);
xmm1 = _mm_loadu_si128((const __m128i*)(imgY[img->height-1]+xx-IMG_PAD_SIZE));
xmm4 = _mm_unpackhi_epi8(xmm1,xmm1);
xmm5 = _mm_unpacklo_epi8(xmm1,xmm1);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm5 = _mm_srli_epi16(xmm5,8);
xmm4 = _mm_slli_epi16(xmm4,3);
xmm5 = _mm_slli_epi16(xmm5,3);
for(yy=0;yy<IMG_PAD_SIZE;yy++)
{
_mm_store_si128((__m128i *)(interpolation[0][0][yy]+xx), xmm0);
_mm_store_si128((__m128i *)(interpolation[1][0][yy]+xx), xmm0);
_mm_store_si128((__m128i *)(interpolation[2][0][yy]+xx), xmm0);
_mm_store_si128((__m128i *)(interpolation[3][0][yy]+xx), xmm0);
_mm_store_si128((__m128i *)(tmp20[yy]+xx), xmm2);
_mm_store_si128((__m128i *)(tmp20[yy]+xx+8), xmm3);
_mm_store_si128((__m128i *)(interpolation[0][0][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i *)(interpolation[1][0][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i *)(interpolation[2][0][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i *)(interpolation[3][0][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i *)(tmp20[img_pad_height-yy-1]+xx), xmm4);
_mm_store_si128((__m128i *)(tmp20[img_pad_height-yy-1]+xx+8), xmm5);
}
}
// o * * o
// * * * *
// * * * *
// o * * o
for(yy=0; yy<IMG_PAD_SIZE; yy++)
{
// ALL 16 Points Need to Be Stuffed at Corner Positions
// o o o o
// o o o o
// o o o o
// o o o o
tmpw0 = imgY[0][0];
xmm0 = _mm_insert_epi16(xmm0,(tmpw0<<3),0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i *)(tmp02[yy]), xmm0);
_mm_store_si128((__m128i *)(tmp02[yy]+8), xmm0);
_mm_store_si128((__m128i *)(tmp20[yy]), xmm0);
_mm_store_si128((__m128i *)(tmp20[yy]+8), xmm0);
xmm0 = _mm_slli_epi16(xmm0,3);
_mm_store_si128((__m128i*)(tmp22[yy]), xmm0);
_mm_store_si128((__m128i*)(tmp22[yy]+8), xmm0);
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[0][0][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][1][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][2][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][3][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][0][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][3][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][0][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][3][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][0][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][yy]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][3][yy]) , xmm0);
tmpw0 = imgY[0][img->width-1];
xmm0 = _mm_insert_epi16(xmm0,(tmpw0<<3),0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(tmp02[yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(tmp02[yy]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
_mm_store_si128((__m128i*)(tmp20[yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(tmp20[yy]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
xmm0 = _mm_slli_epi16(xmm0,3);
_mm_store_si128((__m128i*)(tmp22[yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(tmp22[yy]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[0][0][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][1][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][2][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][3][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][0][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][3][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][0][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][3][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][0][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][3][yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
tmpw0 = imgY[img->height-1][0];
xmm0 = _mm_insert_epi16(xmm0,(tmpw0<<3),0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(tmp02[img_pad_height-yy-1]), xmm0);
_mm_store_si128((__m128i*)(tmp02[img_pad_height-yy-1]+8), xmm0);
_mm_store_si128((__m128i*)(tmp20[img_pad_height-yy-1]), xmm0);
_mm_store_si128((__m128i*)(tmp20[img_pad_height-yy-1]+8), xmm0);
xmm0 = _mm_slli_epi16(xmm0,3);
_mm_store_si128((__m128i*)(tmp22[img_pad_height-yy-1]), xmm0);
_mm_store_si128((__m128i*)(tmp22[img_pad_height-yy-1]+8), xmm0);
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[0][0][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][1][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][2][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[0][3][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][0][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[1][3][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][0][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[2][3][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][0][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][img_pad_height-yy-1]) , xmm0);
_mm_store_si128((__m128i*)(interpolation[3][3][img_pad_height-yy-1]) , xmm0);
tmpw0 = imgY[img->height-1][img->width-1];
xmm0 = _mm_insert_epi16(xmm0,(tmpw0<<3),0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(tmp02[img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(tmp02[img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
_mm_store_si128((__m128i*)(tmp20[img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(tmp20[img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
xmm0 = _mm_slli_epi16(xmm0,3);
_mm_store_si128((__m128i*)(tmp22[img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(tmp22[img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[0][0][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[0][1][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[0][2][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[0][3][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][0][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][3][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][0][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][3][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][0][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][3][img_pad_height-yy-1]+img_pad_width-IMG_PAD_SIZE), xmm0);
}
// o x x x
// x x x x
// x x x x
// x x x x
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
xmm0 = _mm_loadu_si128((const __m128i*)(imgY[yy-IMG_PAD_SIZE]+xx-IMG_PAD_SIZE));
_mm_store_si128((__m128i*)(interpolation[0][0][yy]+xx) , xmm0);
}
}
// x x o x
// x x x x
// x x x x
// x x x x
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// loading
xmm0 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy]+xx-1));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm1 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm5 = _mm_unpackhi_epi8(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi8(xmm1,xmm1);
xmm5 = _mm_srli_epi16(xmm5,8);
xmm1 = _mm_srli_epi16(xmm1,8);
xmm2 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy]+xx+1));
xmm6 = _mm_unpackhi_epi8(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi8(xmm2,xmm2);
xmm6 = _mm_srli_epi16(xmm6,8);
xmm2 = _mm_srli_epi16(xmm2,8);
xmm3 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy]+xx+2));
xmm7 = _mm_unpackhi_epi8(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi8(xmm3,xmm3);
xmm7 = _mm_srli_epi16(xmm7,8);
xmm3 = _mm_srli_epi16(xmm3,8);
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_halfpel_w(xmm0,xmm1,xmm2);
_mm_store_si128((__m128i *)(tmp02[yy]+xx), xmm2);
// rounding & cliping
xmm2 = _mm_add_epi16(xmm2,round4);
xmm2 = _mm_srai_epi16(xmm2,3);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_halfpel_w(xmm4,xmm5,xmm6);
_mm_store_si128((__m128i*)(tmp02[yy]+xx+8), xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round4);
xmm6 = _mm_srai_epi16(xmm6,3);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i*)(interpolation[0][2][yy]+xx), xmm2);
}
}
// Stuffing Vertical Marginal Points for Half Pels
// * o o *
// * * * *
// * * * *
// * o o *
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// x x o x
// x x o x
// x x o x
// x x o x
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][2][IMG_PAD_SIZE]+xx));
xmm1 = _mm_load_si128((const __m128i*)(interpolation[0][2][img_pad_height-IMG_PAD_SIZE-1]+xx));
xmm2 = _mm_load_si128((const __m128i*)(tmp02[IMG_PAD_SIZE]+xx));
xmm3 = _mm_load_si128((const __m128i*)(tmp02[img_pad_height-IMG_PAD_SIZE-1]+xx));
xmm4 = _mm_load_si128((const __m128i*)(tmp02[IMG_PAD_SIZE]+xx+8));
xmm5 = _mm_load_si128((const __m128i*)(tmp02[img_pad_height-IMG_PAD_SIZE-1]+xx+8));
xmm6 = _mm_slli_epi16(xmm3,3);
xmm7 = _mm_slli_epi16(xmm5,3);
xmm8 = _mm_slli_epi16(xmm2,3);
xmm9 = _mm_slli_epi16(xmm4,3);
for(yy=0; yy<IMG_PAD_SIZE; yy++)
{
_mm_store_si128((__m128i*)(interpolation[0][2][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[0][2][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[1][2][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[2][2][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[3][2][img_pad_height-yy-1]+xx), xmm1);
_mm_store_si128((__m128i*)(tmp02[yy]+xx), xmm2);
_mm_store_si128((__m128i*)(tmp02[yy]+xx+8), xmm4);
_mm_store_si128((__m128i*)(tmp22[yy]+xx), xmm8);
_mm_store_si128((__m128i*)(tmp22[yy]+xx+8), xmm9);
_mm_store_si128((__m128i*)(tmp02[img_pad_height-yy-1]+xx), xmm3);
_mm_store_si128((__m128i*)(tmp02[img_pad_height-yy-1]+xx+8), xmm5);
_mm_store_si128((__m128i*)(tmp22[img_pad_height-yy-1]+xx), xmm6);
_mm_store_si128((__m128i*)(tmp22[img_pad_height-yy-1]+xx+8), xmm7);
}
}
// x x x x
// x x x x
// o x o x
// x x x x
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// x x x x
// x x x x
// o x x x
// x x x x
// loading
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy-1]+xx));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm1 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm5 = _mm_unpackhi_epi8(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi8(xmm1,xmm1);
xmm5 = _mm_srli_epi16(xmm5,8);
xmm1 = _mm_srli_epi16(xmm1,8);
xmm2 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy+1]+xx));
xmm6 = _mm_unpackhi_epi8(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi8(xmm2,xmm2);
xmm6 = _mm_srli_epi16(xmm6,8);
xmm2 = _mm_srli_epi16(xmm2,8);
xmm3 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy+2]+xx));
xmm7 = _mm_unpackhi_epi8(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi8(xmm3,xmm3);
xmm7 = _mm_srli_epi16(xmm7,8);
xmm3 = _mm_srli_epi16(xmm3,8);
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_halfpel_w(xmm0,xmm1,xmm2);
_mm_store_si128((__m128i*)(tmp20[yy]+xx), xmm2);
// cliping
xmm2 = _mm_add_epi16(xmm2,round4);
xmm2 = _mm_srai_epi16(xmm2,3);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_halfpel_w(xmm4,xmm5,xmm6);
_mm_store_si128((__m128i*)(tmp20[yy]+xx+8), xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round4);
xmm6 = _mm_srai_epi16(xmm6,3);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i *)(interpolation[2][0][yy]+xx), xmm2);
// x x x x
// x x x x
// x x o x
// x x x x
// loading
xmm0 = _mm_load_si128((const __m128i*)(tmp02[yy-1]+xx));
xmm1 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx));
xmm2 = _mm_load_si128((const __m128i*)(tmp02[yy+1]+xx));
xmm3 = _mm_load_si128((const __m128i*)(tmp02[yy+2]+xx));
xmm4 = _mm_load_si128((const __m128i*)(tmp02[yy-1]+xx+8));
xmm5 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx+8));
xmm6 = _mm_load_si128((const __m128i*)(tmp02[yy+1]+xx+8));
xmm7 = _mm_load_si128((const __m128i*)(tmp02[yy+2]+xx+8));
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_halfpel_w(xmm0,xmm1,xmm2);
_mm_store_si128((__m128i*)(tmp22[yy]+xx), xmm2);
// cliping
xmm2 = _mm_add_epi16(xmm2,round32);
xmm2 = _mm_srai_epi16(xmm2,6);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_halfpel_w(xmm4,xmm5,xmm6);
_mm_store_si128((__m128i*)(tmp22[yy]+xx+8), xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round32);
xmm6 = _mm_srai_epi16(xmm6,6);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i*)(interpolation[2][2][yy]+xx), xmm2);
}
}
// Stuffing Horizontal Marginal Points for Half Pels
// * * * *
// o * * o
// o * * o
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
// x x x x
// x x x x
// o o o o
// x x x x
tmpw0 = interpolation[2][0][yy][IMG_PAD_SIZE];
tmpw0 = tmpw0 + (tmpw0<<8);
xmm0 = _mm_insert_epi16 (xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0, 0);
xmm0 = _mm_shuffle_epi32 (xmm0, 0);
_mm_store_si128((__m128i*)(interpolation[2][0][yy]), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][yy]), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][yy]), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][3][yy]), xmm0);
tmpw0 = tmp20[yy][IMG_PAD_SIZE];
xmm0 = _mm_insert_epi16 (xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32 (xmm0,0);
_mm_store_si128((__m128i*)(tmp20[yy]), xmm0);
_mm_store_si128((__m128i*)(tmp20[yy]+8), xmm0);
xmm0 = _mm_slli_epi16(xmm0,3);
_mm_store_si128((__m128i*)(tmp22[yy]), xmm0);
_mm_store_si128((__m128i*)(tmp22[yy]+8), xmm0);
tmpw0 = interpolation[2][0][yy][img_pad_width-IMG_PAD_SIZE-1];
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[2][0][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][2][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][3][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
tmpw0 = tmp22[yy][img_pad_width-IMG_PAD_SIZE-1];
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(tmp22[yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(tmp22[yy]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
xmm0 = _mm_srai_epi16(xmm0,3);
_mm_store_si128((__m128i*)(tmp20[yy]+img_pad_width-IMG_PAD_SIZE) , xmm0);
_mm_store_si128((__m128i*)(tmp20[yy]+img_pad_width-IMG_PAD_SIZE+8), xmm0);
}
// x o x o
// x x x x
// x o x o
// x x x x
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// x o x x
// x x x x
// x x x x
// x x x x
// loading
xmm0 = _mm_loadu_si128((const __m128i*)(tmp02[yy]+xx-1));
xmm1 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm5 = _mm_unpackhi_epi8(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi8(xmm1,xmm1);
xmm5 = _mm_srli_epi16(xmm5,8);
xmm1 = _mm_srli_epi16(xmm1,8);
xmm5 = _mm_slli_epi16(xmm5,3);
xmm1 = _mm_slli_epi16(xmm1,3);
xmm2 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx));
xmm3 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy]+xx+1));
xmm7 = _mm_unpackhi_epi8(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi8(xmm3,xmm3);
xmm7 = _mm_srli_epi16(xmm7,8);
xmm3 = _mm_srli_epi16(xmm3,8);
xmm7 = _mm_slli_epi16(xmm7,3);
xmm3 = _mm_slli_epi16(xmm3,3);
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_w(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi16(xmm2,round32);
xmm2 = _mm_srai_epi16(xmm2,6);
xmm2 = avs_clip_0_255_w(xmm2);
// loading
xmm4 = _mm_loadu_si128((const __m128i*)(tmp02[yy]+xx+8-1));
xmm6 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx+8));
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_w(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round32);
xmm6 = _mm_srai_epi16(xmm6,6);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i*)(interpolation[0][1][yy]+xx), xmm2);
// x x x o
// x x x x
// x x x x
// x x x x
// loading
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm4 = _mm_slli_epi16(xmm4,3);
xmm0 = _mm_slli_epi16(xmm0,3);
xmm1 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx));
xmm2 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy]+xx+1));
xmm6 = _mm_unpackhi_epi8(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi8(xmm2,xmm2);
xmm6 = _mm_srli_epi16(xmm6,8);
xmm2 = _mm_srli_epi16(xmm2,8);
xmm6 = _mm_slli_epi16(xmm6,3);
xmm2 = _mm_slli_epi16(xmm2,3);
xmm3 = _mm_loadu_si128((const __m128i*)(tmp02[yy]+xx+1));
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_w(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi16(xmm2,round32);
xmm2 = _mm_srai_epi16(xmm2,6);
xmm2 = avs_clip_0_255_w(xmm2);
// loading
xmm5 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx+8));
xmm7 = _mm_loadu_si128((const __m128i*)(tmp02[yy]+xx+8+1));
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_w(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round32);
xmm6 = _mm_srai_epi16(xmm6,6);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i*)(interpolation[0][3][yy]+xx), xmm2);
// x x x x
// x x x x
// x o x x
// x x x x
//////////////////////////////////bit width in 32 bits
//loading
xmm0 = _mm_loadu_si128((const __m128i*)(tmp22[yy]+xx-1));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm1 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm5 = _mm_slli_epi32(xmm5,3);
xmm1 = _mm_slli_epi32(xmm1,3);
xmm2 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm3 = _mm_loadu_si128((const __m128i*)(tmp20[yy]+xx+1));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
xmm7 = _mm_slli_epi32(xmm7,3);
xmm3 = _mm_slli_epi32(xmm3,3);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp0 = avs_combine_d2w(xmm2,xmm6);
// low 8 results completed!
//loading
xmm0 = _mm_loadu_si128((const __m128i*)(tmp22[yy]+xx+8-1));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm1 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx+8));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm5 = _mm_slli_epi32(xmm5,3);
xmm1 = _mm_slli_epi32(xmm1,3);
xmm2 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx+8));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm3 = _mm_loadu_si128((const __m128i*)(tmp20[yy]+xx+8+1));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
xmm7 = _mm_slli_epi32(xmm7,3);
xmm3 = _mm_slli_epi32(xmm3,3);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp1 = avs_combine_d2w(xmm2,xmm6);
// high 8 results completed!
qtmp1 = _mm_shuffle_epi32(qtmp1,78); //[1,0,3,2]
qtmp0 = _mm_or_si128(qtmp0,qtmp1);
_mm_store_si128((__m128i*)(interpolation[2][1][yy]+xx), qtmp0);
// x x x x
// x x x x
// x x x o
// x x x x
//////////////////////////////////bit width in 32 bits
xmm0 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm4 = _mm_slli_epi32(xmm4,3);
xmm0 = _mm_slli_epi32(xmm0,3);
xmm1 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm2 = _mm_loadu_si128((const __m128i*)(tmp20[yy]+xx+1));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm6 = _mm_slli_epi32(xmm6,3);
xmm2 = _mm_slli_epi32(xmm2,3);
xmm3 = _mm_loadu_si128((const __m128i*)(tmp22[yy]+xx+1));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp0 = avs_combine_d2w(xmm2,xmm6);
// low 8 results completed!
//loading
xmm0 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx+8));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm4 = _mm_slli_epi32(xmm4,3);
xmm0 = _mm_slli_epi32(xmm0,3);
xmm1 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx+8));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm2 = _mm_loadu_si128((const __m128i*)(tmp20[yy]+xx+1+8));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm6 = _mm_slli_epi32(xmm6,3);
xmm2 = _mm_slli_epi32(xmm2,3);
xmm3 = _mm_loadu_si128((const __m128i*)(tmp22[yy]+xx+1+8));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp1 = avs_combine_d2w(xmm2,xmm6);
// high 8 results completed!
qtmp1 = _mm_shuffle_epi32(qtmp1,78); //[1,0,3,2]
qtmp0 = _mm_or_si128(qtmp0,qtmp1);
_mm_store_si128((__m128i*)(interpolation[2][3][yy]+xx), qtmp0);
}
}
// Stuffing Vertical Marginal Points for Quater Pels
// * o o *
// * * * *
// * * * *
// * o o *
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// x o x o
// x o x o
// x o x o
// x o x o
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][1][IMG_PAD_SIZE]+xx));
xmm1 = _mm_load_si128((const __m128i*)(interpolation[0][3][IMG_PAD_SIZE]+xx));
xmm2 = _mm_load_si128((const __m128i*)(interpolation[2][1][img_pad_height-IMG_PAD_SIZE-1]+xx));
xmm3 = _mm_load_si128((const __m128i*)(interpolation[2][3][img_pad_height-IMG_PAD_SIZE-1]+xx));
for(yy=0; yy<IMG_PAD_SIZE; yy++)
{
_mm_store_si128((__m128i*)(interpolation[0][1][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[2][1][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][yy]+xx), xmm0);
_mm_store_si128((__m128i*)(interpolation[0][3][yy]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[1][3][yy]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[2][3][yy]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[3][3][yy]+xx), xmm1);
_mm_store_si128((__m128i*)(interpolation[0][1][img_pad_height-yy-1]+xx), xmm2);
_mm_store_si128((__m128i*)(interpolation[1][1][img_pad_height-yy-1]+xx), xmm2);
_mm_store_si128((__m128i*)(interpolation[2][1][img_pad_height-yy-1]+xx), xmm2);
_mm_store_si128((__m128i*)(interpolation[3][1][img_pad_height-yy-1]+xx), xmm2);
_mm_store_si128((__m128i*)(interpolation[0][3][img_pad_height-yy-1]+xx), xmm3);
_mm_store_si128((__m128i*)(interpolation[1][3][img_pad_height-yy-1]+xx), xmm3);
_mm_store_si128((__m128i*)(interpolation[2][3][img_pad_height-yy-1]+xx), xmm3);
_mm_store_si128((__m128i*)(interpolation[3][3][img_pad_height-yy-1]+xx), xmm3);
}
}
// x x x x
// o x o x
// x x x x
// o x o x
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// x x x x
// o x x x
// x x x x
// x x x x
xmm0 = _mm_load_si128((const __m128i*)(tmp20[yy-1]+xx));
xmm1 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm5 = _mm_unpackhi_epi8(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi8(xmm1,xmm1);
xmm5 = _mm_srli_epi16(xmm5,8);
xmm1 = _mm_srli_epi16(xmm1,8);
xmm5 = _mm_slli_epi16(xmm5,3);
xmm1 = _mm_slli_epi16(xmm1,3);
xmm2 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx));
xmm3 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy+1]+xx));
xmm7 = _mm_unpackhi_epi8(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi8(xmm3,xmm3);
xmm7 = _mm_srli_epi16(xmm7,8);
xmm3 = _mm_srli_epi16(xmm3,8);
xmm7 = _mm_slli_epi16(xmm7,3);
xmm3 = _mm_slli_epi16(xmm3,3);
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_w(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi16(xmm2,round32);
xmm2 = _mm_srai_epi16(xmm2,6);
xmm2 = avs_clip_0_255_w(xmm2);
// loading
xmm4 = _mm_load_si128((const __m128i*)(tmp20[yy-1]+xx+8));
xmm6 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx+8));
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_w(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round32);
xmm6 = _mm_srai_epi16(xmm6,6);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i*)(interpolation[1][0][yy]+xx), xmm2);
// x x x x
// x x x x
// x x x x
// o x x x
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm4 = _mm_slli_epi16(xmm4,3);
xmm0 = _mm_slli_epi16(xmm0,3);
xmm1 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx));
xmm2 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy+1]+xx));
xmm6 = _mm_unpackhi_epi8(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi8(xmm2,xmm2);
xmm6 = _mm_srli_epi16(xmm6,8);
xmm2 = _mm_srli_epi16(xmm2,8);
xmm6 = _mm_slli_epi16(xmm6,3);
xmm2 = _mm_slli_epi16(xmm2,3);
xmm3 = _mm_load_si128((const __m128i*)(tmp20[yy+1]+xx));
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_w(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi16(xmm2,round32);
xmm2 = _mm_srai_epi16(xmm2,6);
xmm2 = avs_clip_0_255_w(xmm2);
// loading
xmm5 = _mm_load_si128((const __m128i*)(tmp20[yy]+xx+8));
xmm7 = _mm_load_si128((const __m128i*)(tmp20[yy+1]+xx+8));
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_w(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi16(xmm6,round32);
xmm6 = _mm_srai_epi16(xmm6,6);
xmm6 = avs_clip_0_255_w(xmm6);
xmm2 = avs_combine_w2b(xmm2,xmm6);
_mm_store_si128((__m128i*)(interpolation[3][0][yy]+xx), xmm2);
// x x x x
// x x o x
// x x x x
// x x x x
xmm0 = _mm_load_si128((const __m128i*)(tmp22[yy-1]+xx));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm1 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm5 = _mm_slli_epi32(xmm5,3);
xmm1 = _mm_slli_epi32(xmm1,3);
xmm2 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm3 = _mm_load_si128((const __m128i*)(tmp02[yy+1]+xx));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
xmm7 = _mm_slli_epi32(xmm7,3);
xmm3 = _mm_slli_epi32(xmm3,3);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp0 = avs_combine_d2w(xmm2,xmm6);
// low 8 results completed!
//loading
xmm0 = _mm_load_si128((const __m128i*)(tmp22[yy-1]+xx+8));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm1 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx+8));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm5 = _mm_slli_epi32(xmm5,3);
xmm1 = _mm_slli_epi32(xmm1,3);
xmm2 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx+8));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm3 = _mm_load_si128((const __m128i*)(tmp02[yy+1]+xx+8));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
xmm7 = _mm_slli_epi32(xmm7,3);
xmm3 = _mm_slli_epi32(xmm3,3);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp1 = avs_combine_d2w(xmm2,xmm6);
// high 8 results completed!
qtmp1 = _mm_shuffle_epi32(qtmp1,78); //[1,0,3,2]
qtmp0 = _mm_or_si128(qtmp0,qtmp1);
_mm_store_si128((__m128i*)(interpolation[1][2][yy]+xx), qtmp0);
// x x x x
// x x x x
// x x x x
// x x o x
//////////////////////////////////bit width in 32 bits
xmm0 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm4 = _mm_slli_epi32(xmm4,3);
xmm0 = _mm_slli_epi32(xmm0,3);
xmm1 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm2 = _mm_load_si128((const __m128i*)(tmp02[yy+1]+xx));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm6 = _mm_slli_epi32(xmm6,3);
xmm2 = _mm_slli_epi32(xmm2,3);
xmm3 = _mm_load_si128((const __m128i*)(tmp22[yy+1]+xx));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp0 = avs_combine_d2w(xmm2,xmm6);
// low 8 results completed!
//loading
xmm0 = _mm_load_si128((const __m128i*)(tmp02[yy]+xx+8));
xmm4 = _mm_unpackhi_epi16(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0,xmm0);
xmm4 = _mm_srai_epi32(xmm4,16);
xmm0 = _mm_srai_epi32(xmm0,16);
xmm4 = _mm_slli_epi32(xmm4,3);
xmm0 = _mm_slli_epi32(xmm0,3);
xmm1 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx+8));
xmm5 = _mm_unpackhi_epi16(xmm1,xmm1);
xmm1 = _mm_unpacklo_epi16(xmm1,xmm1);
xmm5 = _mm_srai_epi32(xmm5,16);
xmm1 = _mm_srai_epi32(xmm1,16);
xmm2 = _mm_load_si128((const __m128i*)(tmp02[yy+1]+xx+8));
xmm6 = _mm_unpackhi_epi16(xmm2,xmm2);
xmm2 = _mm_unpacklo_epi16(xmm2,xmm2);
xmm6 = _mm_srai_epi32(xmm6,16);
xmm2 = _mm_srai_epi32(xmm2,16);
xmm6 = _mm_slli_epi32(xmm6,3);
xmm2 = _mm_slli_epi32(xmm2,3);
xmm3 = _mm_load_si128((const __m128i*)(tmp22[yy+1]+xx+8));
xmm7 = _mm_unpackhi_epi16(xmm3,xmm3);
xmm3 = _mm_unpacklo_epi16(xmm3,xmm3);
xmm7 = _mm_srai_epi32(xmm7,16);
xmm3 = _mm_srai_epi32(xmm3,16);
// filtering
xmm0 = _mm_add_epi32(xmm0,xmm3);
xmm2 = avs_filter_quaterpel_d(xmm0,xmm1,xmm2);
// cliping
xmm2 = _mm_add_epi32(xmm2,round512);
xmm2 = _mm_srai_epi32(xmm2,10);
xmm2 = avs_clip_0_255_w(xmm2);
// filtering
xmm4 = _mm_add_epi32(xmm4,xmm7);
xmm6 = avs_filter_quaterpel_d(xmm4,xmm5,xmm6);
// cliping
xmm6 = _mm_add_epi32(xmm6,round512);
xmm6 = _mm_srai_epi32(xmm6,10);
xmm6 = avs_clip_0_255_w(xmm6);
// reorder
qtmp1 = avs_combine_d2w(xmm2,xmm6);
// high 8 results completed!
qtmp1 = _mm_shuffle_epi32(qtmp1,78); //[1,0,3,2]
qtmp0 = _mm_or_si128(qtmp0,qtmp1);
_mm_store_si128((__m128i*)(interpolation[3][2][yy]+xx), qtmp0);
}
}
// Stuffing Horizontal Marginal Points for Quater Pels
// * * * *
// o * * o
// o * * o
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
// x x x x
// o o o o
// x x x x
// o o o o
tmpw0 = interpolation[1][0][yy][IMG_PAD_SIZE];
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[1][0][yy] ), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][yy] ), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][yy] ), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][3][yy] ), xmm0);
tmpw0 = interpolation[3][0][yy][IMG_PAD_SIZE];
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[3][0][yy] ), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][yy] ), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][yy] ), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][3][yy] ), xmm0);
tmpw0 = interpolation[1][2][yy][img_pad_width-IMG_PAD_SIZE-1];
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[1][0][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][1][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][2][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[1][3][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
tmpw0 = interpolation[3][2][yy][img_pad_width-IMG_PAD_SIZE-1];
tmpw0 = tmpw0+(tmpw0<<8);
xmm0 = _mm_insert_epi16(xmm0,tmpw0,0);
xmm0 = _mm_shufflelo_epi16(xmm0,0);
xmm0 = _mm_shuffle_epi32(xmm0,0);
_mm_store_si128((__m128i*)(interpolation[3][0][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][1][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][2][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
_mm_store_si128((__m128i*)(interpolation[3][3][yy]+img_pad_width-IMG_PAD_SIZE), xmm0);
}
// x x x x
// x o x o
// x x x x
// x o x o
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx=xx+16)
{
// loading
xmm1 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx));
xmm1 = _mm_srai_epi16(xmm1,1); // bit width control
xmm2 = _mm_load_si128((const __m128i*)(tmp22[yy]+xx+8));
xmm2 = _mm_srai_epi16(xmm2,1); // bit width control
// x x x x
// x o x x
// x x x x
// x x x x
// loading
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy]+xx));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm4 = _mm_slli_epi16(xmm4,5); // shifting with bit width control
xmm0 = _mm_slli_epi16(xmm0,5); // shifting with bit width control
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm1);
// cliping
xmm0 = _mm_add_epi16(xmm0,round32);
xmm0 = _mm_srai_epi16(xmm0,6);
xmm0 = avs_clip_0_255_w(xmm0);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm2);
// cliping
xmm4 = _mm_add_epi16(xmm4,round32);
xmm4 = _mm_srai_epi16(xmm4,6);
xmm4 = avs_clip_0_255_w(xmm4);
xmm0 = avs_combine_w2b(xmm0,xmm4);
_mm_store_si128((__m128i*)(interpolation[1][1][yy]+xx), xmm0);
// x x x x
// x x x o
// x x x x
// x x x x
// loading
xmm0 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy]+xx+1));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm4 = _mm_slli_epi16(xmm4,5); // shifting with bit width control
xmm0 = _mm_slli_epi16(xmm0,5); // shifting with bit width control
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm1);
// cliping
xmm0 = _mm_add_epi16(xmm0,round32);
xmm0 = _mm_srai_epi16(xmm0,6);
xmm0 = avs_clip_0_255_w(xmm0);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm2);
// cliping
xmm4 = _mm_add_epi16(xmm4,round32);
xmm4 = _mm_srai_epi16(xmm4,6);
xmm4 = avs_clip_0_255_w(xmm4);
xmm0 = avs_combine_w2b(xmm0,xmm4);
_mm_store_si128((__m128i*)(interpolation[1][3][yy]+xx), xmm0);
// x x x x
// x x x x
// x x x x
// x o x x
// loading
xmm0 = _mm_load_si128((const __m128i*)(interpolation[0][0][yy+1]+xx));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm4 = _mm_slli_epi16(xmm4,5); // shifting with bit width control
xmm0 = _mm_slli_epi16(xmm0,5); // shifting with bit width control
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm1);
// cliping
xmm0 = _mm_add_epi16(xmm0,round32);
xmm0 = _mm_srai_epi16(xmm0,6);
xmm0 = avs_clip_0_255_w(xmm0);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm2);
// cliping
xmm4 = _mm_add_epi16(xmm4,round32);
xmm4 = _mm_srai_epi16(xmm4,6);
xmm4 = avs_clip_0_255_w(xmm4);
xmm0 = avs_combine_w2b(xmm0,xmm4);
_mm_store_si128((__m128i*)(interpolation[3][1][yy]+xx), xmm0);
// x x x x
// x x x x
// x x x x
// x x x o
// loading
xmm0 = _mm_loadu_si128((const __m128i*)(interpolation[0][0][yy+1]+xx+1));
xmm4 = _mm_unpackhi_epi8(xmm0,xmm0);
xmm0 = _mm_unpacklo_epi8(xmm0,xmm0);
xmm4 = _mm_srli_epi16(xmm4,8);
xmm0 = _mm_srli_epi16(xmm0,8);
xmm4 = _mm_slli_epi16(xmm4,5); // shifting with bit width control
xmm0 = _mm_slli_epi16(xmm0,5); // shifting with bit width control
// filtering
xmm0 = _mm_add_epi16(xmm0,xmm1);
// cliping
xmm0 = _mm_add_epi16(xmm0,round32);
xmm0 = _mm_srai_epi16(xmm0,6);
xmm0 = avs_clip_0_255_w(xmm0);
// filtering
xmm4 = _mm_add_epi16(xmm4,xmm2);
// cliping
xmm4 = _mm_add_epi16(xmm4,round32);
xmm4 = _mm_srai_epi16(xmm4,6);
xmm4 = avs_clip_0_255_w(xmm4);
xmm0 = avs_combine_w2b(xmm0,xmm4);
_mm_store_si128((__m128i*)(interpolation[3][3][yy]+xx), xmm0);
}
}
// test
//posy=3;posx=3;
/* for(posy=0;posy<4;posy++)
for(posx=0;posx<4;posx++)
for(yy=0; yy<img_pad_height; yy++)
{
for(xx=0; xx<img_pad_width; xx++)
if(interpolation[posy][posx][yy][xx] != mref[0][4*yy+posy][4*xx+posx])
//if(tmp20[yy][xx]*8 != img4Y_tmp[4*yy+2][4*xx+0])
//if(interpolation[posy][posx][yy][xx]-mref[0][4*yy+posy][4*xx+posx]>7)
temp=temp+abs(interpolation[posy][posx][yy][xx]-mref[0][4*yy+posy][4*xx+posx]);
}
temp=temp/(21504*16);
*/
}
// xzhao }
/*
*************************************************************************
* Function:Upsample 4 times, store them in out4x. Color is simply copied
* Input:srcy, srcu, srcv, out4y, out4u, out4v
* Output:
* Return:
* Attention:Side Effects_
Uses (writes) img4Y_tmp. This should be moved to a static variable
in this module
*************************************************************************
*/
#define IClip( Min, Max, Val) (((Val)<(Min))? (Min):(((Val)>(Max))? (Max):(Val)))
void c_avs_enc::find_snr ()
{
int i, j;
int diff_y, diff_u, diff_v;
int impix;
// Calculate PSNR for Y, U and V.
// Luma.
impix = img->height * img->width;
diff_y = 0;
for (i = 0; i < img->width; ++i)
{
for (j = 0; j < img->height; ++j)
{
diff_y += img->quad[imgY_org[j][i] - imgY[j][i]];
}
}
// Chroma.
diff_u = 0;
diff_v = 0;
for (i = 0; i < img->width_cr; i++)
{
for (j = 0; j < img->height_cr; j++)
{
diff_u += img->quad[imgUV_org[0][j][i] - imgUV[0][j][i]];
diff_v += img->quad[imgUV_org[1][j][i] - imgUV[1][j][i]];
}
}
// Collecting SNR statistics
if (diff_y != 0)
{
snr->snr_y = (float) (10 * log10 (65025 * (float) impix / (float) diff_y)); // luma snr for current frame
snr->snr_u = (float) (10 * log10 (65025 * (float) impix / (float) (4 * diff_u))); // u chroma snr for current frame, 1/4 of luma samples
snr->snr_v = (float) (10 * log10 (65025 * (float) impix / (float) (4 * diff_v))); // v chroma snr for current frame, 1/4 of luma samples
}
if (img->number == 0)
{
snr->snr_y1 = (float) (10 * log10 (65025 * (float) impix / (float) diff_y)); // keep luma snr for first frame
snr->snr_u1 = (float) (10 * log10 (65025 * (float) impix / (float) (4 * diff_u))); // keep chroma u snr for first frame
snr->snr_v1 = (float) (10 * log10 (65025 * (float) impix / (float) (4 * diff_v))); // keep chroma v snr for first frame
snr->snr_ya = snr->snr_y1;
snr->snr_ua = snr->snr_u1;
snr->snr_va = snr->snr_v1;
}
// B pictures
else
{
snr->snr_ya = (float) (snr->snr_ya * (img->number + Bframe_ctr) + snr->snr_y) / (img->number + Bframe_ctr + 1); // average snr lume for all frames inc. first
snr->snr_ua = (float) (snr->snr_ua * (img->number + Bframe_ctr) + snr->snr_u) / (img->number + Bframe_ctr + 1); // average snr u chroma for all frames inc. first
snr->snr_va = (float) (snr->snr_va * (img->number + Bframe_ctr) + snr->snr_v) / (img->number + Bframe_ctr + 1); // average snr v chroma for all frames inc. first
}
}
/*
*************************************************************************
* Function:GBIM方法估计块效应
* Input: imgY
* Output:
* Return: GBIM value
*************************************************************************
*/
double c_avs_enc::find_GBIM(byte **I)
{
int i,j,k,n;
byte **I_trans;
I_trans = new byte* [img->width];
for(i=0; i<img->width; i++)
{
I_trans[i] = new byte[img->height];
}
double Weighted_Value_v=0;
double Weighted_Value=0;
double Weighted_Value_interpixel=0;
double M_hor=0;
double M_ver=0;
double M_image=0;
//水平块效应估计
for (k=1;k<=img->width/8-1;k++)
{
for (i=0;i<img->height;i++)
{
double Local_mean=0;
double Local_mean_left=0;
double Local_mean_right=0;
double Local_activity=0;
double Local_activity_left=0;
double Local_activity_right=0;
double Weight;
//求左右临块的亮度均值
for(n=k*8-8;n<=k*8-1;n++)
{
Local_mean_left+=I[i][n]/8;
}
for(n=k*8;n<=k*8+7;n++)
{
Local_mean_right+=I[i][n]/8;
}
Local_mean=(Local_mean_left+Local_mean_right)/2;
//求左右临块的亮度变化值
for(n=k*8-8;n<=k*8-1;n++)
{
Local_activity_left+=(I[i][n]-Local_mean_left)*(I[i][n]-Local_mean_left)/8;
}
for(n=k*8;n<=k*8+7;n++)
{
Local_activity_right+=(I[i][n]-Local_mean_right)*(I[i][n]-Local_mean_right)/8;
}
Local_activity=(sqrt(Local_activity_left)+sqrt(Local_activity_right))/2;
//求权值系数
if (Local_mean<=81)
{
Weight=1.15201*log(1+(sqrt(Local_mean)/(1+Local_activity)));
}
else
{
Weight=log(1+(sqrt(255-Local_mean)/(1+Local_activity)));
}
Weighted_Value_v = Weight*(I[i][k*8-1]-I[i][k*8]);
Weighted_Value += Weighted_Value_v*Weighted_Value_v;
for(int m =1;m<=7;m++)
{Weighted_Value_interpixel += (Weight*(I[i][k*8+m-1]-I[i][k*8+m]))*(Weight*(I[i][k*8+m-1]-I[i][k*8+m]));}
}
}
M_hor=sqrt(Weighted_Value)/sqrt(Weighted_Value_interpixel)*7;
Weighted_Value=0;
Weighted_Value_interpixel=0;
//图像存储矩阵转置
for (j=0;j<img->height;j++)
{
for (i=0;i<img->width;i++)
{
I_trans[i][j]=I[j][i];
}
}
//竖直块效应估计
for (k=1;k<=img->height/8-1;k++)
{
for (i=0;i<img->width;i++)
{
double Local_mean=0;
double Local_mean_left=0;
double Local_mean_right=0;
double Local_activity=0;
double Local_activity_left=0;
double Local_activity_right=0;
double Weight=0;
//求左右临块的亮度均值
for(n=k*8-8;n<=k*8-1;n++)
{
Local_mean_left+=I_trans[i][n]/8;
}
for(n=k*8;n<=k*8+7;n++)
{
Local_mean_right+=I_trans[i][n]/8;
}
Local_mean=(Local_mean_left+Local_mean_right)/2;
//求左右临块的亮度变化值
for(n=k*8-8;n<=k*8-1;n++)
{
Local_activity_left+=(I_trans[i][n]-Local_mean_left)*(I_trans[i][n]-Local_mean_left)/8;
}
for(n=k*8;n<=k*8+7;n++)
{
Local_activity_right+=(I_trans[i][n]-Local_mean_right)*(I_trans[i][n]-Local_mean_right)/8;
}
Local_activity=(sqrt(Local_activity_left)+sqrt(Local_activity_right))/2;
//求权值系数
if (Local_mean<=81)
{
Weight=1.15201*log(1+(sqrt(Local_mean)/(1+Local_activity)));
}
else
{
Weight=log(1+(sqrt(255-Local_mean)/(1+Local_activity)));
}
Weighted_Value+=(Weight*(I_trans[i][k*8-1]-I_trans[i][k*8]))*(Weight*(I_trans[i][k*8-1]-I_trans[i][k*8]));
for(int m=1;m<=7;m++)
{Weighted_Value_interpixel+=(Weight*(I_trans[i][k*8+m-1]-I_trans[i][k*8+m]))*(Weight*(I_trans[i][k*8+m-1]-I_trans[i][k*8+m]));}
}
}
M_ver=sqrt(Weighted_Value)/sqrt(Weighted_Value_interpixel)*7;
for (i=0; i<img->width; i++)
{
delete [] I_trans[i];
}
delete I_trans;
//图像块效应估计值
M_image=(M_hor+M_ver)/2;
return (M_image);
}
/*
*************************************************************************
* Function:Find distortion for all three components
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::find_distortion ()
{
int i, j;
int diff_y, diff_u, diff_v;
int impix;
// Calculate PSNR for Y, U and V.
// Luma.
impix = img->height * img->width;
diff_y = 0;
for (i = 0; i < img->width; ++i)
{
for (j = 0; j < img->height; ++j)
{
diff_y += img->quad[abs(imgY_org[j][i] - imgY[j][i])];
}
}
// Chroma.
diff_u = 0;
diff_v = 0;
for (i = 0; i < img->width_cr; i++)
{
for (j = 0; j < img->height_cr; j++)
{
diff_u += img->quad[abs (imgUV_org[0][j][i] - imgUV[0][j][i])];
diff_v += img->quad[abs (imgUV_org[1][j][i] - imgUV[1][j][i])];
}
}
// Calculate real PSNR at find_snr_avg()
snr->snr_y = (float) diff_y;
snr->snr_u = (float) diff_u;
snr->snr_v = (float) diff_v;
}
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::ReportFirstframe(int tmp_time)
{
printf ("%3d(I) %8d %4d %7.4f %7.4f %7.4f %7.4f %5d %s \n",
frame_no, stat->bit_ctr - stat->bit_ctr_n,
img->qp, snr->snr_y, snr->snr_u, snr->snr_v, GBIM_value_frm, tmp_time, img->picture_structure ? "FRM":"FLD" );
//Rate control
if(input->RCEnable && input->InterlaceCodingOption != 0)
{
Iprev_bits = stat->bit_ctr;
}
stat->bitr0 = stat->bitr;
stat->bit_ctr_0 = stat->bit_ctr;
stat->bit_ctr = 0;
}
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::ReportIntra(int tmp_time)
{
//FILE *file = fopen("stat.dat","at");
//fprintf (file,"%3d(I) %8d %4d %7.4f %7.4f %7.4f %5d \n",
// frame_no, stat->bit_ctr - stat->bit_ctr_n,
// img->qp, snr->snr_y, snr->snr_u, snr->snr_v, tmp_time );
//
//fclose(file);
printf ("\n%3d(I) %8u %4d %7.4f %7.4f %7.4f %7.4f %5d %3s\n",
frame_no, stat->bit_ctr - stat->bit_ctr_n,
img->qp, snr->snr_y, snr->snr_u, snr->snr_v,GBIM_value_frm, tmp_time, img->picture_structure ? "FRM":"FLD");
}
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::ReportB(int tmp_time)
{
//FILE *file = fopen("stat.dat","at");
//fprintf (file,"%3d(B) %8d %4d %7.4f %7.4f %7.4f %5d \n",
// frame_no, stat->bit_ctr - stat->bit_ctr_n, img->qp,
// snr->snr_y, snr->snr_u, snr->snr_v, tmp_time);
//
//fclose(file);
printf ("%3d(B) %8u %4d %7.4f %7.4f %7.4f %7.4f %5d %3s %3d \n",
frame_no, stat->bit_ctr - stat->bit_ctr_n, img->qp,
snr->snr_y, snr->snr_u, snr->snr_v,GBIM_value_frm, tmp_time, img->picture_structure ? "FRM":"FLD",intras);
}
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::ReportP(int tmp_time)
{
//FILE *file = fopen("stat.dat","at");
//fprintf (file,"%3d(P) %8u %4d %7.4f %7.4f %7.4f %5d %3d\n",
// frame_no, stat->bit_ctr - stat->bit_ctr_n, img->qp, snr->snr_y,
// snr->snr_u, snr->snr_v, tmp_time,
// intras);
//fclose(file);
printf ("%3d(P) %8u %4d %7.4f %7.4f %7.4f %7.4f %5d %3s %3d \n",
frame_no, stat->bit_ctr - stat->bit_ctr_n, img->qp, snr->snr_y,
snr->snr_u, snr->snr_v, GBIM_value_frm, tmp_time,
img->picture_structure ? "FRM":"FLD",intras);
}
/*
*************************************************************************
* Function:Copies contents of a Source frame structure into the old-style
* variables imgY_org_frm and imgUV_org_frm. No other side effects
* Input: sf the source frame the frame is to be taken from
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::CopyFrameToOldImgOrgVariables ()
{
int x, y, xx, yy, adr;
byte *u_buffer,*v_buffer;
u_buffer = imgY_org_buffer + bytes_y;
v_buffer = imgY_org_buffer + bytes_y + bytes_uv;
for (y=0; y<img->height; y++)
{
for (x=0; x<img->width; x++)
{
imgY_org_frm [y][x] = imgY_org_buffer[y*img->width+x];
if (y&1 && x&1)
{
xx=x>>1;
yy=y>>1;
adr=yy*img->width/2+xx;
imgUV_org_frm[0][yy][xx] = u_buffer[adr];
imgUV_org_frm[1][yy][xx] = v_buffer[adr];
}
}
}
if(input->InterlaceCodingOption != FRAME_CODING)
{
// xzhao { 2007.7.14
for (y=0; y<img->height; y += 2)
{
for (x=0; x<img->width; x++)
{
imgY_org_top [y/2][x] = imgY_org_buffer[y*img->width +x]; // !! Lum component for top field
imgY_org_bot [y/2][x] = imgY_org_buffer[(y+1)*img->width+x]; // !! Lum component for bot field
xx=x>>2;
yy=y>>2;
adr=yy*img->width/2+xx;
imgUV_org_top[0][yy][xx] = u_buffer[adr]; // !! Cr and Cb component for top field
imgUV_org_top[1][yy][xx] = v_buffer[adr];
imgUV_org_bot[0][yy][xx] = u_buffer[adr-img->width/2]; // !! Cr and Cb component for bot field
imgUV_org_bot[1][yy][xx] = v_buffer[adr-img->width/2];
}
}
}
#ifdef ROI_ENABLE
memcpy(YCbCr[0], imgY_org_buffer, bytes_y *sizeof(byte));
memcpy(YCbCr[1], imgY_org_buffer+bytes_y, bytes_uv*sizeof(byte));
memcpy(YCbCr[2], imgY_org_buffer+bytes_y+bytes_uv, bytes_uv*sizeof(byte));
w[0] = img->width;
w[1] = w[2] = img->width_cr;
h[0] = img->height;
h[1] = h[2] = img->height_cr;
#endif
}
/*
*************************************************************************
* Function: Calculates the absolute frame number in the source file out
of various variables in img-> and input->
* Input:
* Output:
* Return: frame number in the file to be read
* Attention: \side effects
global variable frame_no updated -- dunno, for what this one is necessary
*************************************************************************
*/
void c_avs_enc::CalculateFrameNumber()
{
frame_no = picture_distance;
if (img->type == B_IMG)
{
// xzhao 20080329
//frame_no = (img->number - 1) * (input->successive_Bframe + 1) + img->b_interval * img->b_frame_to_code;
frame_no = gframe_no - 1;
}
else
{
if(img->type==INTRA_IMG)
{
frame_no = gframe_no;
}
// xzhao 20080329
else if((gframe_no%input->GopLength)>=input->GopLength - input->successive_Bframe)
{
frame_no = gframe_no;
}
else
{
//frame_no = img->number * (1 + input->successive_Bframe);
frame_no = gframe_no + input->successive_Bframe;
}
//frame_no = img->number * (input->successive_Bframe + 1);
}
}
void c_avs_enc::ReadOneFrame ()
{
int i, j;
int stuff_height_cr = (input->img_height-input->stuff_height)/2;
// xzhao { 2007.7.18
if(input->img_height != input->stuff_height)
{
//Y
memcpy(imgY_org_buffer, pInputImage, bytes_y);
for(j = input->stuff_height; j<input->img_height; j++)
{
for(i = 0; i <input->stuff_width; i++)
{
imgY_org_buffer[j*input->stuff_width + i] = imgY_org_buffer[input->stuff_height*input->stuff_width - input->stuff_width +i];
}
}
//U
memcpy( imgY_org_buffer + bytes_y, pInputImage + bytes_y, bytes_uv);
for(j = 0; j < stuff_height_cr; j++)
{
for(i = 0; i <input->stuff_width/2; i++)
{
imgY_org_buffer[bytes_y+ bytes_uv +j*input->stuff_width/2 + i] = imgY_org_buffer[bytes_y+ bytes_uv - input->stuff_width/2 +i];
}
}
//V
memcpy( imgY_org_buffer + bytes_y + bytes_uv, pInputImage + bytes_y + bytes_uv, bytes_uv);
for(j = 0; j < stuff_height_cr; j++)
{
for(i = 0; i <input->stuff_width/2; i++)
{
imgY_org_buffer[bytes_y + bytes_uv + bytes_uv + j*input->stuff_width/2 + i] = imgY_org_buffer[bytes_y+bytes_uv+bytes_uv - input->stuff_width/2 +i];
}
}
}
else
{
memcpy(imgY_org_buffer, pInputImage, bytes_y+2*bytes_uv);
}
// xzhao }
}
/*
*************************************************************************
* Function:point to frame coding variables
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::put_buffer_frame()
{
int i,j;
imgY_org = imgY_org_frm;
imgUV_org = imgUV_org_frm;
tmp_mv = tmp_mv_frm;
//initialize ref index 1/4 pixel
for(i=0;i<2;i++)
{
mref[i] = mref_frm[i];
}
//integer pixel for chroma
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
mcef[i][j] = ref_frm[i][j+1];
}
}
//integer pixel for luma
for(i=0;i<2;i++)
{
Refbuf11[i] = &ref_frm[i][0][0][0];
}
//current reconstructed image
imgY = imgY_frm = current_frame[0];
imgUV = imgUV_frm = ¤t_frame[1];
refFrArr = refFrArr_frm;
fw_refFrArr = fw_refFrArr_frm;
bw_refFrArr = bw_refFrArr_frm;
}
/*
*************************************************************************
* Function:update the decoder picture buffer
* Input:frame number in the bitstream and the video sequence
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::Update_Picture_Buffers()
{
unsigned char ***tmp;
byte ****tmp_y;
int i;
//update integer pixel reference buffer
tmp = ref_frm[1]; //ref_frm[ref_index][yuv][height][width] ref_index = 0,1 for P frame
ref_frm[1] = ref_frm[0]; // ref_index = 0, backward reference for B frame; 1: forward reference for B frame
ref_frm[0] = current_frame; // current_frame: current image under reconstruction
current_frame = tmp;
//update luma 1/4 pixel reference buffer mref[ref_index][height][width] ref_index = 0,1 for P frame
tmp_y = mref_frm[1]; // ref_index = 0, forward refernce for B frame ; 1: backward refernce for B frame
mref_frm[1] = mref_frm[0];
mref_frm[0] = tmp_y;
//initial reference index, and for coming interpolation in mref[0]
for(i=0;i<2;i++)
{
mref[i] = mref_frm[i];
}
}
int c_avs_enc::DetectLumVar()
{
int i , j ;
int Histogtam_Cur[256] ;
int Histogtam_Pre[256] ;
int temp = 0 ;
for( i = 0 ; i < 256 ; i++){
Histogtam_Cur[i] = 0 ;
Histogtam_Pre[i] = 0 ;
}
for(j = 0 ; j < img->height ; j++){
for( i = 0 ; i < img->width ; i++){
Histogtam_Cur[imgY_org[j][i]] += 1 ;
Histogtam_Pre[Refbuf11[0][j*img->width + i]] += 1 ;
}
}
for(i = 0 ; i < 256 ; i++){
temp += abs(Histogtam_Pre[i] - Histogtam_Cur[i]);
}
// if(temp >= ((img->height*img->width)*2)){
if(temp >= ((img->height*img->width)/4)){
return 1;
}
else
{
return 0;
}
}
void c_avs_enc::CalculateBrightnessPar(int currentblock[16][16] , int preblock[16][16] , float *c , float *d)
{
int N = 256 ;
int i , j ;
int m1,m2,m3,m4,m5,m6;
m1 = m2 = m3 = m4 = m5 = m6 = 0 ;
for(j = 0 ; j < 16 ; j++){
for(i = 0 ; i < 16 ; i++){
m1 += preblock[j][i]*preblock[j][i] ;
m2 += preblock[j][i];
m3 += preblock[j][i];
m4 += 1;
m5 += preblock[j][i]*currentblock[j][i] ;
m6 += currentblock[j][i];
}
}
*c = ((float)(m4*m5 - m2*m6)) / ((float)(m1*m4 - m2*m3));
*d = ((float)(m3*m5 - m6*m1)) / ((float)(m3*m2 - m1*m4));
return ;
}
void c_avs_enc::CalculatePar(int refnum)
{
int mbx , mby ;
int currmb[16][16] ;
int refmb[16][16] ;
float alpha ;
float belta ;
int i , j ;
int Alpha_His[256];
int Belta_His[256];
int max_num = 0 ;
int max_index = -1 ;
int belta_sum = 0 ;
for( i = 0 ; i < 256 ; i++){
Alpha_His[i] = 0 ;
Belta_His[i] = 0 ;
}
for(mby = 0 ; mby < img->height/16 ; mby++){
for(mbx = 0 ; mbx < img->width/16 ; mbx++){
for( j = 0 ; j < 16 ; j++){
for( i = 0 ; i < 16 ; i++){
currmb[j][i] = imgY_org[mby*16+j][mbx*16+i];
refmb [j][i] = Refbuf11[refnum][(mby*16+j)*img->width + mbx*16+i] ;
}
}
CalculateBrightnessPar(currmb,refmb,&alpha,&belta);
allalpha_lum[mby*(img->width/16)+mbx] = (int)(alpha*32);
allbelta_lum[mby*(img->width/16)+mbx] = (int)(belta);
}
}
for(i = 0 ; i < ((img->height/16)*(img->width/16)) ; i++)
{
if((allalpha_lum[i] < 256)&&(abs(allbelta_lum[i]) < 127))
{
Alpha_His[allalpha_lum[i]]++;
}
}
for( i = 4 ; i < 256 ; i++) // !! 4-256 shenyanfei
{
if(Alpha_His[i] > max_num)
{
max_num = Alpha_His[i] ;
max_index = i ;
}
}
for( i = 0 ; i < ((img->height/16)*(img->width/16)) ; i++){
if(allalpha_lum[i] == max_index){
belta_sum += allbelta_lum[i] ;
}
}
img->lum_scale[refnum] = max_index ;
img->lum_shift[refnum] = belta_sum/max_num ;
if(max_num > ((img->height/16)*(img->width/16) / 2))
img->allframeweight = 1 ;
else
img->allframeweight = 0 ;
img->chroma_scale[refnum] = 32 ; // !! default value
img->chroma_shift[refnum] = 0 ; // !! default value
return ;
}
void c_avs_enc::estimate_weighting_factor()
{
int bframe = (img->type==B_IMG);
int max_ref = img->nb_references;
int ref_num ;
if(max_ref > img->buf_cycle)
max_ref = img->buf_cycle;
// !! detection luminance variation
img->LumVarFlag = DetectLumVar();
if(img->LumVarFlag == 1){
for(ref_num = 0 ; ref_num < max_ref ; ref_num++){
CalculatePar(ref_num);
}
}
return;
}
void c_avs_enc::UnifiedOneForthPix_c_sse (pel_t ** imgY)
{
int img_pad_width,img_pad_height;
int xx,yy;
int temp=0;
int_16_t hh,hv;
int qh,qv; //qx for direction "\", qy for direction "/"
img_pad_width = (img->width + (IMG_PAD_SIZE<<1));
img_pad_height = (img->height + (IMG_PAD_SIZE<<1));
interpolation = mref[0];
/*************************************************************
// Basic Quater Pel Interpolation Unit
//
// ○ ==> Interger Pel Position
// □ ==> Half Pel Position
// △ ==> Quarter Pel Position
//************************************************************
// ○ △ □ △
//
// △ △ △ △
//
// □ △ □ △
//
// △ △ △ △
*************************************************************/
/*if(frame_no==6)
{
printf("interpolation debug:\n");
}*/
// o x x x
// x x x x
// x x x x
// x x x x
// * * * *
// * o o *
// * o o *
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx++)
interpolation[0][0][yy][xx] = imgY[yy-IMG_PAD_SIZE][xx-IMG_PAD_SIZE];
// * * * *
// o o o o
// o o o o
// * * * *
for(yy=IMG_PAD_SIZE; yy<img_pad_height-IMG_PAD_SIZE; yy++)
{
for(xx=0;xx<IMG_PAD_SIZE;xx++)
{
interpolation[0][0][yy][xx] = imgY[yy-IMG_PAD_SIZE][0];
interpolation[0][0][yy][img_pad_width-xx-1] = imgY[yy-IMG_PAD_SIZE][img->width-1];
}
}
// * o o *
// o o o o
// o o o o
// * o o *
for(xx=IMG_PAD_SIZE; xx<img_pad_width-IMG_PAD_SIZE; xx++)
{
for(yy=0;yy<IMG_PAD_SIZE;yy++)
{
interpolation[0][0][yy][xx] = imgY[0][xx-IMG_PAD_SIZE];
interpolation[0][0][img_pad_height-yy-1][xx] = imgY[img->height-1][xx-IMG_PAD_SIZE];
}
}
// o o o o
// o o o o
// o o o o
// o o o o
for(yy=0; yy<IMG_PAD_SIZE; yy++)
for(xx=0; xx<IMG_PAD_SIZE; xx++)
{
interpolation[0][0][yy][xx]=imgY[0][0];
interpolation[0][0][yy][img_pad_width-xx-1]=imgY[0][img->width-1];
interpolation[0][0][img_pad_height-yy-1][xx]=imgY[img->height-1][0];
interpolation[0][0][img_pad_height-yy-1][img_pad_width-xx-1]=imgY[img->height-1][img->width-1];
}
// x x o x
// x x x x
// x x x x
// x x x x
// * o * *
// * o * *
// * o * *
// * o * *
for(yy=0; yy<img_pad_height; yy++)
for(xx=1; xx<img_pad_width-2; xx++)
{
hh = 5 * (interpolation[0][0][yy][xx] + interpolation[0][0][yy][xx+1])
- (interpolation[0][0][yy][xx-1] + interpolation[0][0][yy][xx+2]);
interpolation[0][2][yy][xx] = IClip(0, 255,((hh+4)>>3));
tmp02[yy][xx] = hh;
}
// o o o o
// o o o o
// o o o o
// o o o o
for(yy=0; yy<img_pad_height; yy++)
{
// pos 02
hh = 5 * (interpolation[0][0][yy][0] + interpolation[0][0][yy][1])
- (interpolation[0][0][yy][0] + interpolation[0][0][yy][2]);
interpolation[0][2][yy][0] = IClip(0, 255,((hh+4)>>3));
tmp02[yy][0] = hh;
hh = 5 * (interpolation[0][0][yy][img_pad_width-2] + interpolation[0][0][yy][img_pad_width-1])
- (interpolation[0][0][yy][img_pad_width-3] + interpolation[0][0][yy][img_pad_width-1]);
interpolation[0][2][yy][img_pad_width-2] = IClip(0, 255,((hh+4)>>3));
tmp02[yy][img_pad_width-2] = hh;
hh = 5 * (interpolation[0][0][yy][img_pad_width-1] + interpolation[0][0][yy][img_pad_width-1])
- (interpolation[0][0][yy][img_pad_width-2] + interpolation[0][0][yy][img_pad_width-1]);
interpolation[0][2][yy][img_pad_width-1] = IClip(0, 255,((hh+4)>>3));
tmp02[yy][img_pad_width-1] = hh;
}
// x x x x
// x x x x
// o x o x
// x x x x
// * * * *
// o o o o
// * * * *
// * * * *
for(yy=1; yy<img_pad_height-2; yy++)
for(xx=0; xx<img_pad_width; xx++)
{
hv = 5 * (interpolation[0][0][yy][xx] + interpolation[0][0][yy+1][xx])
- (interpolation[0][0][yy-1][xx] + interpolation[0][0][yy+2][xx]);
interpolation[2][0][yy][xx] = IClip(0, 255,((hv+4)>>3));
tmp20[yy][xx] = (hv<<3);
hv = 5 * (tmp02[yy][xx] + tmp02[yy+1][xx])
- (tmp02[yy-1][xx] + tmp02[yy+2][xx]);
interpolation[2][2][yy][xx] = IClip(0, 255,((hv+32)>>6));
tmp22[yy][xx] = hv;
}
// o o o o
// o o o o
// o o o o
// o o o o
for(xx=0; xx<img_pad_width; xx++)
{
// pos 20
hv = 5 * (interpolation[0][0][0][xx] + interpolation[0][0][1][xx])
- (interpolation[0][0][0][xx] + interpolation[0][0][2][xx]);
interpolation[2][0][0][xx] = IClip(0, 255,((hv+4)>>3));
tmp20[0][xx] = (hv<<3);
hv = 5 * (interpolation[0][0][img_pad_height-2][xx] + interpolation[0][0][img_pad_height-1][xx])
- (interpolation[0][0][img_pad_height-3][xx] + interpolation[0][0][img_pad_height-1][xx]);
interpolation[2][0][img_pad_height-2][xx] = IClip(0, 255,((hv+4)>>3));
tmp20[img_pad_height-2][xx] = (hv<<3);
hv = 5 * (interpolation[0][0][img_pad_height-1][xx] + interpolation[0][0][img_pad_height-1][xx])
- (interpolation[0][0][img_pad_height-2][xx] + interpolation[0][0][img_pad_height-1][xx]);
interpolation[2][0][img_pad_height-1][xx] = IClip(0, 255,((hv+4)>>3));
tmp20[img_pad_height-1][xx] = (hv<<3);
// pos 22
hv = 5 * (tmp02[0][xx] + tmp02[1][xx])
- (tmp02[0][xx] + tmp02[2][xx]);
interpolation[2][2][0][xx] = IClip(0, 255,((hv+32)>>6));
tmp22[0][xx] = hv;
hv = 5 * (tmp02[img_pad_height-2][xx] + tmp02[img_pad_height-1][xx])
- (tmp02[img_pad_height-3][xx] + tmp02[img_pad_height-1][xx]);
interpolation[2][2][img_pad_height-2][xx] = IClip(0, 255,((hv+32)>>6));
tmp22[img_pad_height-2][xx] = hv;
hv = 5 * (tmp02[img_pad_height-1][xx] + tmp02[img_pad_height-1][xx])
- (tmp02[img_pad_height-2][xx] + tmp02[img_pad_height-1][xx]);
interpolation[2][2][img_pad_height-1][xx] = IClip(0, 255,((hv+32)>>6));
tmp22[img_pad_height-1][xx] = hv;
}
// x o x o
// x x x x
// x o x o
// x x x x
for(yy=0; yy<img_pad_height; yy++)
{
// o * * *
// o * * *
// o * * *
// o * * *
// pos 01 & 21
qh = 1* (interpolation[0][0][yy][0]<<3) +
7* (interpolation[0][0][yy][0]<<3) +
7* tmp02[yy][0] +
1* (interpolation[0][0][yy][1]<<3);
interpolation[0][1][yy][0] = IClip(0, 255,((qh+64)>>7));
qh = 1* tmp20[yy][0] +
7* tmp20[yy][0] +
7* tmp22[yy][0] +
1* tmp20[yy][1];
interpolation[2][1][yy][0] = IClip(0, 255,((qh+512)>>10));
// pos 03 & pos 23
qh = 1* (interpolation[0][0][yy][0]<<3) +
7* tmp02[yy][0] +
7* (interpolation[0][0][yy][1]<<3) +
1* tmp02[yy][1];
interpolation[0][3][yy][0] = IClip(0, 255,((qh+64)>>7));
qh = 1* tmp20[yy][0] +
7* tmp22[yy][0] +
7* tmp20[yy][1] +
1* tmp22[yy][1];
interpolation[2][3][yy][0] = IClip(0, 255,((qh+512)>>10));
// * o o *
// * o o *
// * o o *
// * o o *
for(xx=1; xx<img_pad_width-1; xx++)
{
// pos 01
qh = 1* tmp02[yy][xx-1] +
7* (interpolation[0][0][yy][xx]<<3) +
7* tmp02[yy][xx] +
1* (interpolation[0][0][yy][xx+1]<<3);
interpolation[0][1][yy][xx] = IClip(0, 255,((qh+64)>>7));
// pos 21
qh = 1* tmp22[yy][xx-1] +
7* tmp20[yy][xx] +
7* tmp22[yy][xx] +
1* tmp20[yy][xx+1];
interpolation[2][1][yy][xx] = IClip(0, 255,((qh+512)>>10));
// pos 03
qh = 1* (interpolation[0][0][yy][xx]<<3) +
7* tmp02[yy][xx] +
7* (interpolation[0][0][yy][xx+1]<<3) +
1* tmp02[yy][xx+1];
interpolation[0][3][yy][xx] = IClip(0, 255,((qh+64)>>7));
// pos 23
qh = 1* tmp20[yy][xx] +
7* tmp22[yy][xx] +
7* tmp20[yy][xx+1] +
1* tmp22[yy][xx+1];
interpolation[2][3][yy][xx] = IClip(0, 255,((qh+512)>>10));
}
// * * * o
// * * * o
// * * * o
// * * * o
// pos 01 & 21
qh = 1* tmp02[yy][img_pad_width-2] +
7* (interpolation[0][0][yy][img_pad_width-1]<<3) +
7* tmp02[yy][img_pad_width-1] +
1* tmp02[yy][img_pad_width-1];
interpolation[0][1][yy][img_pad_width-1] = IClip(0, 255,((qh+64)>>7));
qh = 1* tmp22[yy][img_pad_width-2] +
7* tmp20[yy][img_pad_width-1] +
7* tmp22[yy][img_pad_width-1] +
1* tmp22[yy][img_pad_width-1];
interpolation[2][1][yy][img_pad_width-1] = IClip(0, 255,((qh+512)>>10));
// pos 03 & pos 23
qh = 1* (interpolation[0][0][yy][img_pad_width-1]<<3) +
7* tmp02[yy][img_pad_width-1] +
7* tmp02[yy][img_pad_width-1] +
1* tmp02[yy][img_pad_width-1];
interpolation[0][3][yy][img_pad_width-1] = (IClip(0, 255,(qh+64)>>7));
qh = 1* tmp20[yy][img_pad_width-1] +
7* tmp22[yy][img_pad_width-1] +
7* tmp22[yy][img_pad_width-1] +
1* tmp22[yy][img_pad_width-1];
interpolation[2][3][yy][img_pad_width-1] = IClip(0, 255,((qh+512)>>10));
}
// x x x x
// o x o x
// x x x x
// o x o x
// o o o o
// * * * *
// * * * *
// * * * *
for(xx=0; xx<img_pad_width; xx++)
{
// pos 10 & 12
qv = 1* (interpolation[0][0][0][xx]<<6) +
7* (interpolation[0][0][0][xx]<<6) +
7* tmp20[0][xx] +
1* (interpolation[0][0][1][xx]<<6);
interpolation[1][0][0][xx] = IClip(0, 255,((qv+512)>>10));
qv = 1* (tmp02[0][xx]<<3) +
7* (tmp02[0][xx]<<3) +
7* tmp22[0][xx] +
1* (tmp02[1][xx]<<3);
interpolation[1][2][0][xx] = IClip(0, 255,((qv+512)>>10));
// pos 30 & pos 32
qv = 1* (interpolation[0][0][0][xx]<<6) +
7* tmp20[0][xx] +
7* (interpolation[0][0][1][xx]<<6) +
1* tmp20[1][xx];
interpolation[3][0][0][xx] = IClip(0, 255,((qv+512)>>10));
qv = 1* (tmp02[0][xx]<<3) +
7* tmp22[0][xx] +
7* (tmp02[1][xx]<<3) +
1* tmp22[1][xx];
interpolation[3][2][0][xx] = IClip(0, 255,((qv+512)>>10));
}
for(yy=1; yy<img_pad_height-1; yy++)
{
// * * * *
// o o o o
// o o o o
// * * * *
for(xx=0; xx<img_pad_width; xx++)
{
// pos 10
qv = 1* tmp20[yy-1][xx] +
7* (interpolation[0][0][yy][xx]<<6) +
7* tmp20[yy][xx] +
1* (interpolation[0][0][yy+1][xx]<<6);
interpolation[1][0][yy][xx] = IClip(0, 255,((qv+512)>>10));
// pos 12
qv = 1* tmp22[yy-1][xx] +
7* (tmp02[yy][xx]<<3) +
7* tmp22[yy][xx] +
1* (tmp02[yy+1][xx]<<3);
interpolation[1][2][yy][xx] = IClip(0, 255,((qv+512)>>10));
// pos 30
qv = 1* (interpolation[0][0][yy][xx]<<6) +
7* tmp20[yy][xx] +
7* (interpolation[0][0][yy+1][xx]<<6) +
1* tmp20[yy+1][xx];
interpolation[3][0][yy][xx] = IClip(0, 255,((qv+512)>>10));
// pos 32
qv = 1* (tmp02[yy][xx]<<3) +
7* tmp22[yy][xx] +
7* (tmp02[yy+1][xx]<<3) +
1* tmp22[yy+1][xx];
interpolation[3][2][yy][xx] = IClip(0, 255,((qv+512)>>10));
}
// * * * *
// * * * *
// * * * *
// o o o o
for(xx=0; xx<img_pad_width; xx++)
{
// pos 10 & 12
qv = 1* tmp20[img_pad_height-2][xx] +
7* (interpolation[0][0][img_pad_height-1][xx]<<6) +
7* tmp20[img_pad_height-1][xx] +
1* tmp20[img_pad_height-1][xx];
interpolation[1][0][img_pad_height-1][xx] = IClip(0, 255,((qv+512)>>10));
qv = 1* tmp22[img_pad_height-2][xx] +
7* (tmp02[img_pad_height-1][xx]<<3) +
7* tmp22[img_pad_height-1][xx] +
1* tmp22[img_pad_height-1][xx];
interpolation[1][2][img_pad_height-1][xx] = IClip(0, 255,((qv+512)>>10));
// pos 30 & 32
qv = 1* (interpolation[0][0][img_pad_height-1][xx]<<6) +
7* tmp20[img_pad_height-1][xx] +
7* tmp20[img_pad_height-1][xx] +
1* tmp20[img_pad_height-1][xx];
interpolation[3][0][img_pad_height-1][xx] = IClip(0, 255,((qv+512)>>10));
qv = 1* (tmp02[img_pad_height-1][xx]<<3) +
7* tmp22[img_pad_height-1][xx] +
7* tmp22[img_pad_height-1][xx] +
1* tmp22[img_pad_height-1][xx];
interpolation[3][2][img_pad_height-1][xx] = IClip(0, 255,((qv+512)>>10));
}
}
// x x x x
// x o x o
// x x x x
// x o x o
// o o o *
// o o o *
// o o o *
// * * * *
for(yy=0; yy<img_pad_height-1; yy++)
for(xx=0; xx<img_pad_width-1; xx++)
{
// "\"
// pos 11 & 33
interpolation[1][1][yy][xx]=IClip(0, 255,(((interpolation[0][0][yy][xx]<<6)+tmp22[yy][xx]+64)>>7));
interpolation[3][3][yy][xx]=IClip(0, 255,(((interpolation[0][0][yy+1][xx+1]<<6)+tmp22[yy][xx]+64)>>7));
// "/"
// pos 13 & 31
interpolation[1][3][yy][xx]=IClip(0, 255,(((interpolation[0][0][yy][xx+1]<<6)+tmp22[yy][xx]+64)>>7));
interpolation[3][1][yy][xx]=IClip(0, 255,(((interpolation[0][0][yy+1][xx]<<6)+tmp22[yy][xx]+64)>>7));
}
// o o o o
// o o o o
// o o o o
// * * * *
for(yy=0; yy<img_pad_height-1; yy++)
{
// pos 11 & 31
interpolation[1][1][yy][img_pad_width-1]=IClip(0, 255,(((interpolation[0][0][yy][img_pad_width-1]<<6)+tmp22[yy][img_pad_width-1]+64)>>7));
interpolation[3][1][yy][img_pad_width-1]=IClip(0, 255,(((interpolation[0][0][yy+1][img_pad_width-1]<<6)+tmp22[yy][img_pad_width-1]+64)>>7));
// pos 13 & 33
interpolation[1][3][yy][img_pad_width-1]=interpolation[1][1][yy][img_pad_width-1];
interpolation[3][3][yy][img_pad_width-1]=interpolation[3][1][yy][img_pad_width-1];
}
// o o o o
// o o o o
// o o o o
// o o o *
for(xx=0; xx<img_pad_width-1; xx++)
{
// pos 11 & 13
interpolation[1][1][img_pad_height-1][xx]=IClip(0, 255,(((interpolation[0][0][img_pad_height-1][xx]<<6)+tmp22[img_pad_height-1][xx]+64)>>7));
interpolation[1][3][img_pad_height-1][xx]=IClip(0, 255,(((interpolation[0][0][img_pad_height-1][xx+1]<<6)+tmp22[img_pad_height-1][xx]+64)>>7));
//pos 31 & 33
interpolation[3][1][img_pad_height-1][xx]=interpolation[1][1][img_pad_height-1][xx];
interpolation[3][3][img_pad_height-1][xx]=interpolation[1][3][img_pad_height-1][xx];
}
// o o o o
// o o o o
// o o o o
// o o o o
{
interpolation[1][1][img_pad_height-1][img_pad_width-1]=IClip(0, 255,(((interpolation[0][0][img_pad_height-1][img_pad_width-1]<<6)+tmp22[img_pad_height-1][img_pad_width-1]+64)>>7));
interpolation[1][3][img_pad_height-1][img_pad_width-1]=interpolation[1][1][img_pad_height-1][img_pad_width-1];
interpolation[3][1][img_pad_height-1][img_pad_width-1]=interpolation[1][1][img_pad_height-1][img_pad_width-1];
interpolation[3][3][img_pad_height-1][img_pad_width-1]=interpolation[1][1][img_pad_height-1][img_pad_width-1];
}
/* if(frame_no==6)
{
printf("interpolation:\n");
printf("%3d\n",interpolation[2][1][192][367]);
printf("%3d ",tmp22[192][img_pad_width-2]);
printf("%3d ",tmp20[192][img_pad_width-1]);
printf("%3d \n",tmp22[192][img_pad_width-1]);
printf("%3d ",interpolation[2][2][192][img_pad_width-2]);
printf("%3d ",interpolation[2][0][192][img_pad_width-1]);
printf("%3d ",interpolation[2][2][192][img_pad_width-1]);
for(yy=0;yy<8;yy++)
{
for(xx=0;xx<8;xx++)
{
//printf("%3d ",img->mpr[jj+mb_y][ii+mb_x]);
//printf("%d ",interpolation[2][1][192+yy][360+xx]);
}
printf("\n");
}
}*/
// for test
/*for(posy=0;posy<4;posy++)
for(posx=0;posx<4;posx++)
for(yy=0; yy<img_pad_height; yy++)
for(xx=0; xx<img_pad_width; xx++)
if(interpolation[posy][posx][yy][xx] != mref[0][4*yy+posy][4*xx+posx])
temp++;*/
}
| [
"zhihang.wang@6c8d3a4c-d4d5-11dd-b6b4-918b84bbd919",
"[email protected]@6c8d3a4c-d4d5-11dd-b6b4-918b84bbd919"
] | [
[
[
1,
144
],
[
146,
151
],
[
156,
214
],
[
216,
227
],
[
229,
257
],
[
259,
2772
],
[
2774,
3491
]
],
[
[
145,
145
],
[
152,
155
],
[
215,
215
],
[
228,
228
],
[
258,
258
],
[
2773,
2773
]
]
] |
0905b9bdd6ea425f52d30786c27c0b5900ec2390 | 979e53d80e9389bc8b750743a19651764f5c25bd | /baseport/syborg/svphostfs/fs/svphostmnt.cpp | 8d929eb5eb18ece71cd7cdfabc6cdd25891ad160 | [] | no_license | SymbianSource/oss.FCL.interim.QEMU | a46ab50b3c1783fbbbe21119d6ebb3268542d8c1 | 27314f44d508ef89270ca0f43a24a0e5e7fc047b | refs/heads/master | 2021-01-19T06:46:29.018585 | 2010-05-17T17:37:02 | 2010-05-17T17:37:02 | 65,377,884 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,497 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "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 <f32file.h>
#include <f32fsys.h>
#include <f32ver.h>
#include <e32uid.h>
#include "svphostfsy.h"
#define HOST_SVP_DRIVE_SIZE 1024*1024*1024
// Fixed low mass-memory warning at startup
//#define HOST_SVP_DRIVE_FREE_SIZE 10*1024*1024
#define HOST_SVP_DRIVE_FREE_SIZE 100*1024*1024
LOCAL_C TInt GetMediaSize(TInt /*aDriveNumber*/,TInt64& aSize,TInt64& aFree)
//
// Return the size and free space on a drive.
//
{
DP(_L("** (SVPHOSTMNT) GetMediaSize"));
aSize = HOST_SVP_DRIVE_SIZE;
aFree = HOST_SVP_DRIVE_FREE_SIZE;
return(KErrNone);
}
LOCAL_C TInt GetVolume(TInt /*aDriveNumber*/,TDes& aName,TUint& aUniqueID)
//
// Return the volume name and uniqueID.
//
{
DP(_L("** (SVPHOSTMNT) GetVolume"));
aUniqueID=1234;
aName=(_L("SVPHOSTDRV"));
return(KErrNone);
}
void CanonicalizePathname(const TDesC& aName, TInt aDrive, TDes& n, THostFileName& aHostName)
{
DP(_L("** (SVPHOSTMNT) CanonicalizePathname (%S)"), &aName);
n += TDriveUnit(aDrive).Name();
n += aName;
TParse parse;
parse.Set(n,NULL,NULL);
n=parse.FullName();
aHostName.Copy(n);
DP(_L("-> (%S)"), &aHostName);
}
void CanonicalizePathname(const TDesC& aName, TInt aDrive, THostFileName& aHostName)
{
TUint16 buf[KMaxPath];
TPtr n(buf, KMaxPath);
CanonicalizePathname(aName, aDrive, n, aHostName);
}
//////////////////////////////////////////////////////////////////////////
// CSVPHostMountCB //
//////////////////////////////////////////////////////////////////////////
CSVPHostMountCB::CSVPHostMountCB()
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::CSVPHostMountCB()"));
__DECLARE_NAME(_S("CSVPHostMountCB"));
}
CSVPHostMountCB::~CSVPHostMountCB()
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::~CSVPHostMountCB()"));
iDevice.Close();
}
void CSVPHostMountCB::MountL(TBool /*aForceMount*/)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::MountL()"));
TInt err = iDevice.Open();
User::LeaveIfError(err);
TFileName driveName;
TInt d=Drive().DriveNumber();
iSize=HOST_SVP_DRIVE_SIZE;
User::LeaveIfError(GetVolume(d,driveName,iUniqueID));
HBufC* pN=driveName.AllocL();
DP(_L("** (SVPHOSTMNT) ->SetVolumeName()"));
SetVolumeName(pN);
DP(_L("** (SVPHOSTMNT) <-SetVolumeName()"));
}
TInt CSVPHostMountCB::ReMount()
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::ReMount()"));
TFileName n;
TInt d=Drive().DriveNumber();
TUint uniqueID;
TInt r=GetVolume(d,n,uniqueID);
if (r!=KErrNone)
return(r);
if (n==VolumeName() && uniqueID==iUniqueID)
return(KErrNone);
return(KErrGeneral);
}
void CSVPHostMountCB::Dismounted()
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::Dismounted()"));
}
void CSVPHostMountCB::VolumeL(TVolumeInfo& aVolume) const
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::VolumeL()"));
TInt64 s,f(0);
TFileName n;
TInt d=Drive().DriveNumber();
User::LeaveIfError(GetMediaSize(d,s,f));
aVolume.iFree=f;
}
void CSVPHostMountCB::SetVolumeL(TDes& /*aName*/)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::SetVolumeL()"));
User::Leave(KErrNotSupported);
}
void CSVPHostMountCB::IsFileInRom(const TDesC& /*aName*/,TUint8*& /*aFileStart*/)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::IsFileInRom()"));
}
void CSVPHostMountCB::MkDirL(const TDesC& aName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::MkDirL()"));
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsMkDirInfo info(driveNumber, name, 0777);
User::LeaveIfError(SVP_HOST_FS_DEVICE().MkDir(info));
}
void CSVPHostMountCB::RmDirL(const TDesC& aName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::RmDirL()"));
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsRmDirInfo info(driveNumber, name);
User::LeaveIfError(SVP_HOST_FS_DEVICE().RmDir(info));
}
void CSVPHostMountCB::DeleteL(const TDesC& aName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::DeleteL()"));
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsDeleteInfo info(driveNumber, name);
User::LeaveIfError(SVP_HOST_FS_DEVICE().Delete(info));
}
void CSVPHostMountCB::RenameL(const TDesC& anOldName,const TDesC& aNewName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::RenameL()"));
// TODO: do we allow renaming across drives?
TBuf<KMaxPath> oldName, newName;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(anOldName, driveNumber, oldName);
CanonicalizePathname(aNewName, driveNumber, newName);
TSVPHostFsRenameInfo info(driveNumber, oldName, newName);
User::LeaveIfError(SVP_HOST_FS_DEVICE().Rename(info));
}
void CSVPHostMountCB::ReplaceL(const TDesC& anOldName,const TDesC& aNewName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::ReplaceL()"));
if(FileNamesIdentical(anOldName,aNewName))
{
return;
}
TBuf<KMaxPath> oldName, newName;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(anOldName, driveNumber, oldName);
CanonicalizePathname(aNewName, driveNumber, newName);
TSVPHostFsReplaceInfo info(driveNumber, oldName, newName);
User::LeaveIfError(SVP_HOST_FS_DEVICE().Replace(info));
}
void CSVPHostMountCB::ReadUidL(const TDesC& aName,TEntry& anEntry) const
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::ReadUidL()"));
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsFileOpenInfo fileOpenInfo(driveNumber, name,EFileRead,EFileOpen);
TInt err = SVP_HOST_FS_DEVICE().FileOpen(fileOpenInfo);
User::LeaveIfError(err);
TBuf8<sizeof(TCheckedUid)> uidBuf;
uidBuf.SetLength(sizeof(TCheckedUid));
TSVPHostFsFileReadInfo fileReadInfo(driveNumber, fileOpenInfo.iHandle,sizeof(TCheckedUid),0,(char*)uidBuf.Ptr());
if (KErrNone != SVP_HOST_FS_DEVICE().FileRead(fileReadInfo))
User::LeaveIfError(SVP_HOST_FS_DEVICE().FileClose(driveNumber, fileOpenInfo.iHandle));
DP(_L("** (SVPHOSTMNT) CSVPHostFileCB::ReadUidL sizeof(TCheckedUid) %d fileOpenInfo.iLength %d "), sizeof(TCheckedUid), fileReadInfo.iLength);
if (fileReadInfo.iLength!=sizeof(TCheckedUid))
User::LeaveIfError(SVP_HOST_FS_DEVICE().FileClose(driveNumber, fileOpenInfo.iHandle));
TCheckedUid uid(uidBuf);
anEntry.iType=uid.UidType();
User::LeaveIfError(SVP_HOST_FS_DEVICE().FileClose(driveNumber, fileOpenInfo.iHandle));
}
void CSVPHostMountCB::EntryL(const TDesC& aName,TEntry& anEntry) const
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::EntryL(%S)"), &aName);
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsEntryInfo info(driveNumber, name);
User::LeaveIfError(SVP_HOST_FS_DEVICE().Entry(info));
anEntry.iAtt=info.iAtt&KEntryAttMaskSupported;
anEntry.iSize=info.iSize;
fileTimeToTime(info.iModified,anEntry.iModified, info.iTimeType);
}
void timeToFileTime(TUint32& t,const TTime& aTime, TFileTimeType aType);
void CSVPHostMountCB::SetEntryL(const TDesC& aName,const TTime& aTime,TUint aSetAttMask,TUint aClearAttMask)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::SetEntryL()"));
//User::Leave(KErrNotSupported);
}
void CSVPHostMountCB::FileOpenL(const TDesC& aName,TUint aMode,TFileOpen anOpen,CFileCB* aFile)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::FileOpenL(%S)"), &aName);
CSVPHostFileCB& file=(*((CSVPHostFileCB*)aFile));
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsFileOpenInfo info(driveNumber, name,aMode,anOpen);
TInt err = SVP_HOST_FS_DEVICE().FileOpen(info);
User::LeaveIfError(err);
file.SetHandle(info.iHandle);
file.SetSize(info.iSize);
file.SetAtt(info.iAtt&KEntryAttMaskSupported);
TTime tempTime=file.Modified();
fileTimeToTime(info.iModified, tempTime, info.iTimeType);
file.SetModified(tempTime);
}
void CSVPHostMountCB::DirOpenL(const TDesC& aName ,CDirCB* aDir)
{
DP(_L("CFatMountCB::DirOpenL, drv:%d, %S"), DriveNumber(), &aName);
CSVPHostDirCB& dir=(*((CSVPHostDirCB*)aDir));
TBuf<KMaxPath> name;
TUint driveNumber = Drive().DriveNumber();
CanonicalizePathname(aName, driveNumber, name);
TSVPHostFsDirOpenInfo info(driveNumber, name);
TInt err = SVP_HOST_FS_DEVICE().DirOpen(info);
User::LeaveIfError(err);
dir.SetHandle(info.iHandle);
TFileName n(TDriveUnit(Drive().DriveNumber()).Name());
n.Append(aName);
dir.SetFullName(n);
}
void CSVPHostMountCB::RawReadL(TInt64 /*aPos*/,TInt /*aLength*/,const TAny* /*aTrg*/,TInt /*anOffset*/,const RMessagePtr2& /*aMessage*/) const
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::RawReadL()"));
User::Leave(KErrNotSupported);
}
void CSVPHostMountCB::RawWriteL(TInt64 /*aPos*/,TInt /*aLength*/,const TAny* /*aSrc*/,TInt /*anOffset*/,const RMessagePtr2& /*aMessage*/)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::RawWriteL()"));
User::Leave(KErrNotSupported);
}
void CSVPHostMountCB::GetShortNameL(const TDesC& aLongName,TDes& aShortName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::GetShortNameL(%S)"), &aLongName);
aShortName = aLongName;
}
void CSVPHostMountCB::GetLongNameL(const TDesC& aShortName,TDes& aLongName)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::GetLongNameL(%S)"), &aShortName);
aLongName = aShortName;
}
void CSVPHostMountCB::ReadSectionL(const TDesC& /*aName*/,TInt /*aPos*/,TAny* /*aTrg*/,TInt /*aLength*/,const RMessagePtr2& /*aMessage*/)
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::RawSectionL()"));
User::Leave(KErrNotSupported);
}
TBool CSVPHostMountCB::IsRomDrive() const
{
DP(_L("** (SVPHOSTMNT) CSVPHostMountCB::IsRomDrive()"));
return(EFalse);
}
| [
"[email protected]"
] | [
[
[
1,
339
]
]
] |
04ebe054e436c6060fc4c34154d0d39e5db57516 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Common/2DRender.h | c3882a150d48f84a998063c23a86ab5234fee557 | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 23,940 | h | #ifndef __2DRENDER_H
#define __2DRENDER_H
#ifdef __CLIENT
#include "mempooler.h"
#endif
#ifndef __WORLDSERVER
#include "EditString.h"
#endif // __CLEINT
#include "..\_UnhandledException\ExceptionHandler.h"
#include "xUtil.h"
struct IDeviceRes
{
virtual void Invalidate() = 0;
virtual BOOL SetInvalidate(LPDIRECT3DDEVICE9 pd3dDevice) = 0;
};
class CRectClip : public CRect
{
public:
CRectClip() { }
CRectClip(int l,int t,int r,int b) : CRect(l,t,r,b) { }
CRectClip(const RECT& srcRect) : CRect(srcRect) { }
CRectClip(LPCRECT lpSrcRect) : CRect(lpSrcRect) { }
CRectClip(POINT point,SIZE size) : CRect(point,size) { }
CRectClip(POINT topLeft,POINT bottomRight) : CRect(topLeft,bottomRight) { }
BOOL Clipping(CRect& rect) const;
//BOOL Clipping(CRect& os,Rect& is);
//BOOL Clipping(CPtSz& os,CPtSz& is) const;
//BOOL PtSzLapRect(CPtSz ptSz) const;
//BOOL PtSzInRect (CPtSz ptSz) const;
BOOL RectLapRect(CRect rect) const;
BOOL RectInRect (CRect rect) const;
};
#define D2DTEXRENDERFLAG_90 1
#define D2DTEXRENDERFLAG_180 2
#define D2DTEXRENDERFLAG_HFLIP 3
#define D2DTEXRENDERFLAG_VFLIP 4
struct DRAWVERTEX
{
D3DXVECTOR3 vec;//AT x, y, z;
FLOAT rhw;
DWORD color;
// FLOAT u, v;
};
struct TEXTUREVERTEX
{
D3DXVECTOR3 vec;//
//FLOAT x, y, z,
FLOAT rhw, u, v;
};
struct TEXTUREVERTEX2
{
D3DXVECTOR3 vec;//
//FLOAT x, y, z,
FLOAT rhw;
DWORD color;
FLOAT u, v;
};
#define D3DFVF_DRAWVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE/*|D3DFVF_TEX1*/) // FVF가 맞지않아 경고가 떠서 지웠음.-xuzhu-
#define D3DFVF_TEXTUREVERTEX (D3DFVF_XYZRHW|D3DFVF_TEX1)
#define D3DFVF_TEXTUREVERTEX2 (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)
inline void SetDrawVertex( DRAWVERTEX* pVertices, FLOAT x, FLOAT y, DWORD dwColor )
{
pVertices->vec = D3DXVECTOR3( x,y,0);
pVertices->rhw = 1.0f;
pVertices->color = dwColor;
}
inline void SetTextureVertex( TEXTUREVERTEX* pVertices, FLOAT x, FLOAT y, FLOAT u, FLOAT v )
{
//pVertices->x = (FLOAT)x - 0.5f;
//pVertices->y = (FLOAT)y - 0.5f;
//pVertices->z = 0.0f;
pVertices->vec = D3DXVECTOR3( x - 0.5f, y - 0.5f, 0 );
pVertices->rhw = 1.0f;
pVertices->u = u;
pVertices->v = v;
}
inline void SetTextureVertex2( TEXTUREVERTEX2* pVertices, FLOAT x, FLOAT y, FLOAT u, FLOAT v, DWORD dwColor )
{
//pVertices->x = (FLOAT)x - 0.5f;
//pVertices->y = (FLOAT)y - 0.5f;
//pVertices->z = 0.0f;
pVertices->vec = D3DXVECTOR3( x - 0.5f, y - 0.5f, 0 );
pVertices->rhw = 1.0f;
pVertices->u = u;
pVertices->v = v;
pVertices->color = dwColor;
}
class CTexture;
class CTexturePack;
class C2DRender
{
LPDIRECT3DVERTEXBUFFER9 m_pVBRect;
LPDIRECT3DVERTEXBUFFER9 m_pVBFillRect;
LPDIRECT3DVERTEXBUFFER9 m_pVBRoundRect;
LPDIRECT3DVERTEXBUFFER9 m_pVBFillTriangle;
LPDIRECT3DVERTEXBUFFER9 m_pVBTriangle;
LPDIRECT3DVERTEXBUFFER9 m_pVBLine;
LPDIRECT3DVERTEXBUFFER9 m_pVBPixel;
//LPDIRECT3DVERTEXBUFFER9 m_pVBTexture;
public:
LPDIRECT3DDEVICE9 m_pd3dDevice; // The D3D rendering device
DWORD m_dwTextColor;
CD3DFont* m_pFont;
CPoint m_ptOrigin ; // 뷰포트 시작 지점
CRectClip m_clipRect;
C2DRender();
~C2DRender();
CD3DFont* GetFont() { return m_pFont; }
void SetFont( CD3DFont* pFont ) { m_pFont = pFont; }
// 뷰포트 관련
CPoint GetViewportOrg() const { return m_ptOrigin; }
void SetViewportOrg(POINT pt) { m_ptOrigin = pt; }
void SetViewportOrg(int x,int y) { m_ptOrigin = CPoint(x,y); }
void SetViewport(CRect rect);
void SetViewport(int nLeft,int nTop,int nRight,int nBottom);
BOOL ResizeRectVB( CRect* pRect, DWORD dwColorLT, DWORD dwColorRT, DWORD dwColorLB, DWORD dwColorRB, LPDIRECT3DVERTEXBUFFER9 pVB );
BOOL RenderRect ( CRect rect, DWORD dwColorLT, DWORD dwColorRT, DWORD dwColorLB, DWORD dwColorRB );
BOOL RenderRect ( CRect rect, DWORD dwColor ) { return RenderRect( rect, dwColor, dwColor, dwColor, dwColor); }
BOOL RenderResizeRect( CRect rect, int nThick );
BOOL ResizeFillRectVB( CRect* pRect, DWORD dwColorLT, DWORD dwColorRT, DWORD dwColorLB, DWORD dwColorRB, LPDIRECT3DVERTEXBUFFER9 pVB, LPDIRECT3DTEXTURE9 m_pTexture = NULL );
BOOL RenderFillRect ( CRect rect, DWORD dwColorLT, DWORD dwColorRT, DWORD dwColorLB, DWORD dwColorRB, LPDIRECT3DTEXTURE9 m_pTexture = NULL );
BOOL RenderFillRect ( CRect rect, DWORD dwColor, LPDIRECT3DTEXTURE9 m_pTexture = NULL ) { return RenderFillRect( rect, dwColor, dwColor, dwColor, dwColor, m_pTexture); }
BOOL ResizeRoundRectVB( CRect* pRect, DWORD dwColorLT, DWORD dwColorRT, DWORD dwColorLB, DWORD dwColorRB, LPDIRECT3DVERTEXBUFFER9 pVB, LPDIRECT3DTEXTURE9 m_pTexture = NULL );
BOOL RenderRoundRect ( CRect rect, DWORD dwColorLT, DWORD dwColorRT, DWORD dwColorLB, DWORD dwColorRB, LPDIRECT3DTEXTURE9 m_pTexture = NULL );
BOOL RenderRoundRect ( CRect rect, DWORD dwColor, LPDIRECT3DTEXTURE9 m_pTexture = NULL ) { return RenderRoundRect( rect, dwColor, dwColor, dwColor, dwColor, m_pTexture ); }
BOOL RenderLine( CPoint pt1, CPoint pt2, DWORD dwColor1, DWORD dwColor2 );
BOOL RenderLine( CPoint pt1, CPoint pt2, DWORD dwColor ) { return RenderLine(pt1,pt2,dwColor,dwColor); }
BOOL RenderTriangle( CPoint pt1, CPoint pt2, CPoint pt3, DWORD dwColor1, DWORD dwColor2, DWORD dwColor3 );
BOOL RenderTriangle( CPoint pt1, CPoint pt2, CPoint pt3, DWORD dwColor ) { return RenderTriangle( pt1, pt2, pt3, dwColor, dwColor, dwColor ); }
BOOL RenderFillTriangle( CPoint pt1, CPoint pt2, CPoint pt3, DWORD dwColor1, DWORD dwColor2, DWORD dwColor3 );
BOOL RenderFillTriangle( CPoint pt1, CPoint pt2, CPoint pt3, DWORD dwColor ) { return RenderFillTriangle( pt1, pt2, pt3, dwColor, dwColor, dwColor ); }
BOOL RenderTextureEx( CPoint pt, CPoint pt2, CTexture* pTexture, DWORD dwBlendFactorAlhpa, FLOAT fScaleX , FLOAT fScaleY, BOOL bAnti = TRUE );
BOOL RenderTexture( CPoint pt, CTexture* pTexture, DWORD dwBlendFactorAlhpa = 255, FLOAT fScaleX=1.0 , FLOAT fScaleY=1.0 );
BOOL RenderTextureRotate( CPoint pt, CTexture* pTexture, DWORD dwBlendFactorAlhpa, FLOAT fScaleX , FLOAT fScaleY, FLOAT fRadian );
//added by gmpbigsun: 회전축 변경
BOOL RenderTextureRotate( CPoint pt, CTexture* pTexture, DWORD dwBlendFactorAlhpa, FLOAT fRadian, BOOL bCenter, FLOAT fScaleX, FLOAT fScaleY );
BOOL RenderTexture2( CPoint pt, CTexture* pTexture, FLOAT fScaleX = 1.0, FLOAT fScaleY = 1.0, D3DCOLOR coolor = 0xffffffff );
BOOL RenderTextureEx2( CPoint pt, CPoint pt2, CTexture* pTexture, DWORD dwBlendFactorAlhpa, FLOAT fScaleX , FLOAT fScaleY, D3DCOLOR color );
BOOL RenderTextureColor( CPoint pt, CTexture* pTexture, FLOAT fScaleX , FLOAT fScaleY, D3DCOLOR color );
void SetTextColor( DWORD dwColor ) { m_dwTextColor = dwColor; }
DWORD GetTextColor() { return m_dwTextColor; }
#ifdef __CLIENT
void TextOut_EditString( int x,int y, CEditString& strEditString, int nPos = 0, int nLines = 0, int nLineSpace = 0 );
void TextOut_EditString2( int x,int y, CEditString& strEditString, int nPos = 0, int nLines = 0, int nLineSpace = 0 );
bool DrawTextMotion(std::string& MotionCmd, CPoint pt, CPoint pt2);
#endif
void TextOut( int x,int y, LPCTSTR pszString, DWORD dwColor = 0xffffffff, DWORD dwShadowColor = 0x00000000 );
void TextOut( int x,int y, int nValue, DWORD dwColor = 0xffffffff, DWORD dwShadowColor = 0x00000000 );
void TextOut( int x,int y, FLOAT fXScale, FLOAT fYScale, LPCTSTR pszString, DWORD dwColor = 0xffffffff, DWORD dwShadowColor = 0x00000000 );
HRESULT InitDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice );
HRESULT RestoreDeviceObjects( D3DSURFACE_DESC* pd3dsdBackBuffer );
HRESULT InvalidateDeviceObjects();
HRESULT DeleteDeviceObjects();
};
class CTexture : public IDeviceRes
{
BOOL m_bAutoFree;
public:
SIZE m_sizePitch;
SIZE m_size;
FLOAT m_fuLT, m_fvLT;
FLOAT m_fuRT, m_fvRT;
FLOAT m_fuLB, m_fvLB;
FLOAT m_fuRB, m_fvRB;
POINT m_ptCenter;
LPDIRECT3DTEXTURE9 m_pTexture;
#ifdef _DEBUG
CString m_strFileName;
#endif
#ifdef __YDEBUG
CString m_strTexFileName;
D3DCOLOR m_d3dKeyColor;
UINT m_nLevels;
BOOL m_bMyLoader;
DWORD m_dwUsage;
D3DPOOL m_Pool;
D3DFORMAT m_Format;
#endif //__YDEBUG
CTexture();
~CTexture();
void Invalidate();
BOOL SetInvalidate(LPDIRECT3DDEVICE9 pd3dDevice);
BOOL DeleteDeviceObjects();
void SetAutoFree( BOOL bAuto ) { m_bAutoFree = bAuto; }
LPDIRECT3DTEXTURE9 GetTexture() { return m_pTexture; }
BOOL CreateTexture( LPDIRECT3DDEVICE9 pd3dDevice, int nWidth, int nHeight,
UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool = D3DPOOL_DEFAULT );
BOOL LoadTexture( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pFileName, D3DCOLOR d3dKeyColor, BOOL bMyLoader = FALSE );
//BOOL LoadTextureFromRes( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pFileName, D3DCOLOR d3dKeyColor, BOOL bMyLoader = FALSE );
void Render( C2DRender* p2DRender, CPoint pt, DWORD dwBlendFactorAlhpa = 255 ) {
p2DRender->RenderTexture( pt, this, dwBlendFactorAlhpa );
}
void Render( C2DRender* p2DRender, CPoint pt, CPoint pt2, DWORD dwBlendFactorAlhpa = 255, FLOAT fscalX = 1.0, FLOAT fscalY = 1.0 ) {
p2DRender->RenderTextureEx( pt, pt2, this, dwBlendFactorAlhpa, fscalX, fscalY );
}
void RenderEx2( C2DRender* p2DRender, CPoint pt, CPoint pt2, DWORD dwBlendFactorAlhpa = 255, FLOAT fscalX = 1.0, FLOAT fscalY = 1.0, D3DCOLOR color = 0 ) {
p2DRender->RenderTextureEx2( pt, pt2, this, dwBlendFactorAlhpa, fscalX, fscalY, color );
}
void RenderScal( C2DRender* p2DRender, CPoint pt, DWORD dwBlendFactorAlhpa = 255, FLOAT fscalX = 1.0, FLOAT fscalY = 1.0 ) {
p2DRender->RenderTexture( pt, this, dwBlendFactorAlhpa , fscalX, fscalY );
}
void RenderRotate( C2DRender* p2DRender, CPoint pt, FLOAT fRadian, DWORD dwBlendFactorAlhpa = 255, FLOAT fscalX = 1.0, FLOAT fscalY = 1.0 ) {
p2DRender->RenderTextureRotate( pt, this, dwBlendFactorAlhpa , fscalX, fscalY, fRadian );
}
//added by gmpbigsun : 회전축 변경가능 ( center or start point )
void RenderRotate( C2DRender* p2DRender, CPoint pt, FLOAT fRadian, BOOL bCenter, DWORD dwBlendFactorAlhpa = 255, FLOAT fscalX = 1.0, FLOAT fscalY = 1.0 ) {
p2DRender->RenderTextureRotate( pt, this, dwBlendFactorAlhpa, fRadian, bCenter, fscalX, fscalY );
}
void Render2( C2DRender* p2DRender, CPoint pt, D3DCOLOR color, float fscalX = 1.0f, float fscalY = 1.0f ) {
p2DRender->RenderTexture2( pt, this, fscalX, fscalY, color );
}
void RenderScal2( C2DRender* p2DRender, CPoint pt, DWORD dwBlendFactorAlhpa = 255, FLOAT fscalX = 1.0, FLOAT fscalY = 1.0, D3DCOLOR color = 0 ) {
p2DRender->RenderTextureColor( pt, this, fscalX, fscalY, color );
}
//CSize ComputeSize( CSize size );
};
//class CTextureMotion
//{
//public:
// DWORD m_dwNumber;
// CSize m_size;
// LPDIRECT3DTEXTURE9 m_pTexture;
// CTexture* m_ap2DTexture;
//
// BOOL LoadScript( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pszFileName )
// {
// CScanner scanner;
// if( scanner.Load( pszFileName ) == FALSE )
// {
// Error( "%s not found", pszFileName );
// return FALSE;
// }
//
// DWORD dwCount = 0;
// CTexture* pTexture;
// BOOL bMultiLang = FALSE;
//
// do {
// scanner.GetToken();
// if(scanner.Token == "number")
// {
// m_dwNumber = scanner.GetNumber();
// m_ap2DTexture = new CTexture[ m_dwNumber ];
// }
// else
// if( scanner.Token == "MULTI_LANGUAGE" )
// {
// bMultiLang = TRUE;
// }
// else
// if(scanner.Token == "texture")
// {
// scanner.GetToken();
//
// TCHAR strFileName[MAX_PATH];
// strcpy(strFileName,scanner.token);
// D3DCOLOR d3dKeyColor = scanner.GetHex();
// // 여기서 텍스춰 생성 (Create the texture using D3DX)
// D3DXIMAGE_INFO imageInfo;
//
// if( bMultiLang )
// {
// LoadTextureFromRes( pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), strFileName ),
// D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4,
// D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR,
// D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, d3dKeyColor, &imageInfo, NULL, &m_pTexture );
// }
// else
// {
// LoadTextureFromRes( pd3dDevice, strFileName,
// D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4,
// D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR,
// D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, d3dKeyColor, &imageInfo, NULL, &m_pTexture );
// }
//
// m_size.cx = imageInfo.Width;
// m_size.cy = imageInfo.Height;
// }
// else
// if(scanner.Token == "data") // 좌표와 사이즈
// {
// if( dwCount >= m_dwNumber )
// {
// }
// pTexture = &m_ap2DTexture[ dwCount++ ];
// pTexture->m_size.cx = scanner.GetNumber();
// pTexture->m_size.cy = scanner.GetNumber();
// pTexture->m_fuLT = (FLOAT)scanner.GetNumber() / m_size.cx;
// pTexture->m_fvLT = (FLOAT)scanner.GetNumber() / m_size.cy;
// pTexture->m_fuRT = (FLOAT)scanner.GetNumber() / m_size.cx;
// pTexture->m_fvRT = (FLOAT)scanner.GetNumber() / m_size.cy;
// pTexture->m_fuLB = (FLOAT)scanner.GetNumber() / m_size.cx;
// pTexture->m_fvLB = (FLOAT)scanner.GetNumber() / m_size.cy;
// pTexture->m_fuRB = (FLOAT)scanner.GetNumber() / m_size.cx;
// pTexture->m_fvRB = (FLOAT)scanner.GetNumber() / m_size.cy;
// pTexture->m_pTexture = m_pTexture;
// }
// else
// if( scanner.Token == "pos" ) // 좌표
// {
// if( dwCount >= m_dwNumber )
// {
// }
// pTexture = &m_ap2DTexture[ dwCount++ ];
// pTexture->m_size.cx = scanner.GetNumber();
// pTexture->m_size.cy = scanner.GetNumber();
// int x = scanner.GetNumber();
// int y = scanner.GetNumber();
// scanner.GetToken();
// if( scanner.Token == "h" )
// {
// pTexture->m_fuRT = (FLOAT) x / m_size.cx;
// pTexture->m_fvRT = (FLOAT) y / m_size.cy;
// pTexture->m_fuLT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvLT = (FLOAT) y / m_size.cy;
// pTexture->m_fuRB = (FLOAT) x / m_size.cx;
// pTexture->m_fvRB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// pTexture->m_fuLB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvLB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// }
// else
// if( scanner.Token == "v" )
// {
// pTexture->m_fuLB = (FLOAT) x / m_size.cx;
// pTexture->m_fvLB = (FLOAT) y / m_size.cy;
// pTexture->m_fuRB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvRB = (FLOAT) y / m_size.cy;
// pTexture->m_fuLT = (FLOAT) x / m_size.cx;
// pTexture->m_fvLT = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// pTexture->m_fuRT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvRT = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// }
// else
// if( scanner.Token == "hv" )
// {
// pTexture->m_fuRB = (FLOAT) x / m_size.cx;
// pTexture->m_fvRB = (FLOAT) y / m_size.cy;
// pTexture->m_fuLB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvLB = (FLOAT) y / m_size.cy;
// pTexture->m_fuRT = (FLOAT) x / m_size.cx;
// pTexture->m_fvRT = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// pTexture->m_fuLT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvLT = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// }
// else
// {
// pTexture->m_fuLT = (FLOAT) x / m_size.cx;
// pTexture->m_fvLT = (FLOAT) y / m_size.cy;
// pTexture->m_fuRT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvRT = (FLOAT) y / m_size.cy;
// pTexture->m_fuLB = (FLOAT) x / m_size.cx;
// pTexture->m_fvLB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// pTexture->m_fuRB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvRB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// }
// pTexture->m_pTexture = m_pTexture;
// }
// else
// if(scanner.Token == "datauv") // uv 상태로 입력
// {
// if( dwCount >= m_dwNumber )
// {
// }
// pTexture = &m_ap2DTexture[ dwCount++ ];
// pTexture->m_size.cx = scanner.GetNumber();
// pTexture->m_size.cy = scanner.GetNumber();
// pTexture->m_fuLT = scanner.GetFloat();
// pTexture->m_fvLT = scanner.GetFloat();
// pTexture->m_fuRT = scanner.GetFloat();
// pTexture->m_fvRT = scanner.GetFloat();
// pTexture->m_fuLB = scanner.GetFloat();
// pTexture->m_fvLB = scanner.GetFloat();
// pTexture->m_fuRB = scanner.GetFloat();
// pTexture->m_fvRB = scanner.GetFloat();
// pTexture->m_pTexture = m_pTexture;
// }
// else
// if(scanner.Token == "serialize")
// {
// if( dwCount >= m_dwNumber )
// {
// Error( "%s 에러, 할당 :%d, 실제갯수 : %d", pszFileName, m_dwNumber, dwCount );
// return FALSE;
// }
// int nCnt = 0;
// int nFrame = scanner.GetNumber();
// SIZE size;
// size.cx = scanner.GetNumber();
// size.cy = scanner.GetNumber();
// POINT start;
// start.x = scanner.GetNumber();
// start.y = scanner.GetNumber();
// POINT center;
// center.x = scanner.GetNumber();
// center.y = scanner.GetNumber();
//
// int i; for( i = start.y; i < m_size.cy; i += size.cy )
// {
// int j; for( j = start.x; j < m_size.cx; j += size.cx, nCnt++ )
// {
// if( nCnt < nFrame )
// {
//
// if( dwCount >= m_dwNumber )
// {
// Error( "%s 에러, 할당 :%d, 실제갯수 : %d", pszFileName, m_dwNumber, dwCount );
// return FALSE;
// }
//
// pTexture = &m_ap2DTexture[ dwCount ];
// dwCount++;
//
// pTexture->m_size = size;
// pTexture->m_ptCenter = center;
// int x = j;
// int y = i;
// pTexture->m_fuLT = (FLOAT) x / m_size.cx;
// pTexture->m_fvLT = (FLOAT) y / m_size.cy;
// pTexture->m_fuRT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvRT = (FLOAT) y / m_size.cy;
// pTexture->m_fuLB = (FLOAT) x / m_size.cx;
// pTexture->m_fvLB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// pTexture->m_fuRB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx;
// pTexture->m_fvRB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy;
// pTexture->m_pTexture = m_pTexture;
// }
// }
// }
// }
// } while(scanner.tok!=FINISHED);
// return TRUE;
// }
//
//
//};
class CTexturePack
{
public:
DWORD m_dwNumber;
CSize m_size;
LPDIRECT3DTEXTURE9 m_pTexture;
CTexture* m_ap2DTexture;
CTexturePack();
~CTexturePack();
HRESULT RestoreDeviceObjects(LPDIRECT3DDEVICE9 pd3dDevice);
HRESULT InvalidateDeviceObjects();
BOOL DeleteDeviceObjects();
DWORD GetNumber() { return m_dwNumber; }
void MakeVertex( C2DRender* p2DRender, CPoint point, int nIndex, TEXTUREVERTEX** ppVertices );
void MakeVertex( C2DRender* p2DRender, CPoint point, int nIndex, TEXTUREVERTEX2** ppVertices, DWORD dwColor );
void Render( LPDIRECT3DDEVICE9 pd3dDevice, TEXTUREVERTEX* pVertices, int nVertexNum );
void Render( LPDIRECT3DDEVICE9 pd3dDevice, TEXTUREVERTEX2* pVertices, int nVertexNum );
#if __VER >= 13 // __CSC_VER13_1
virtual BOOL LoadScript( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pFileName );
#else //__CSC_VER13_1
BOOL LoadScript( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pFileName );
#endif //__CSC_VER13_1
CTexture* LoadTexture( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pFileName, D3DCOLOR d3dKeyColor );
CTexture* GetAt( DWORD dwIndex ) {
return &m_ap2DTexture[ dwIndex ];
}
void Render( C2DRender* p2DRender, CPoint pt, DWORD dwIndex, DWORD dwBlendFactorAlhpa = 255, FLOAT fScaleX=1.0f , FLOAT fScaleY=1.0f )
{
if( ((int)dwIndex >= (int)m_dwNumber) || (int)dwIndex < 0 )
{
LPCTSTR szErr = Error( "CTexturePack::Render : 범위를 벗어남 %d", (int)dwIndex );
ADDERRORMSG( szErr );
int *p = NULL;
*p = 1;
}
p2DRender->RenderTexture( pt, &m_ap2DTexture[ dwIndex ], dwBlendFactorAlhpa, fScaleX , fScaleY );
}
};
typedef map< string, CTexture* > CMapTexture;
typedef CMapTexture::value_type MapTexType;
typedef CMapTexture::iterator MapTexItor;
class CTextureMng
{
public:
BOOL SetInvalidate(LPDIRECT3DDEVICE9 pd3dDevice);
void Invalidate();
CMapTexture m_mapTexture;
//CMapStringToPtr m_mapTexture;
CTextureMng();
~CTextureMng();
BOOL RemoveTexture( LPCTSTR pKey );
BOOL DeleteDeviceObjects();
CTexture* AddTexture( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pFileName, D3DCOLOR d3dKeyColor, BOOL bMyLoader = FALSE );
CTexture* AddTexture( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pKey, CTexture* pTexture );
CTexture* GetAt( LPCTSTR pFileName );
};
#ifdef __CLIENT
// 몹, 플레이어 데미지 출력
class CDamageNum
{
public:
DWORD m_nFrame;
DWORD m_nNumber;
DWORD m_nAttribute;
D3DXVECTOR3 m_vPos;
FLOAT m_fY, m_fDy;
int m_nState;
int m_nCnt;
CDamageNum(D3DXVECTOR3 vPos,DWORD nNumber,DWORD nAttribute)
{ m_nFrame=0; m_nNumber=nNumber; m_vPos=vPos; m_nAttribute=nAttribute; m_nState = 0; m_nCnt = 0; }
~CDamageNum() {};
void Process();
void Render(CTexturePack *textPackNum);
#ifdef __CLIENT
#ifndef __VM_0820
#ifndef __MEM_TRACE
static MemPooler<CDamageNum>* m_pPool;
void* operator new( size_t nSize ) { return CDamageNum::m_pPool->Alloc(); }
void* operator new( size_t nSize, LPCSTR lpszFileName, int nLine ) { return CDamageNum::m_pPool->Alloc(); }
void operator delete( void* lpMem ) { CDamageNum::m_pPool->Free( (CDamageNum*)lpMem ); }
void operator delete( void* lpMem, LPCSTR lpszFileName, int nLine ) { CDamageNum::m_pPool->Free( (CDamageNum*)lpMem ); }
#endif // __MEM_TRACE
#endif // __VM_0820
#endif // __CLIENT
};
// 데미지 숫자 관리자
class CDamageNumMng
{
public:
CPtrArray m_Array;
D3DXMATRIX m_matProj,m_matView,m_matWorld;
D3DVIEWPORT9 m_viewport;
CTexturePack m_textPackNum;
CDamageNumMng() { D3DXMatrixIdentity(&m_matWorld); };
~CDamageNumMng();
HRESULT RestoreDeviceObjects();
HRESULT InvalidateDeviceObjects();
BOOL DeleteDeviceObjects();
void LoadTexture(LPDIRECT3DDEVICE9 pd3dDevice);
void AddNumber(D3DXVECTOR3 vPos,DWORD nNumber,DWORD nAttribute); // 새로운 데미지 표시를 생성시킨다.
void Process(); // 현재 생성된 데미지 표시들을 처리한다.
void Render(); // 현재 생성된 데미지 표시들을 출력한다.
};
#endif
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
594
]
]
] |
271d7ed11568f6095e544254c90494fee0b72b1d | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/Code/Flosti Engine/PhysX/PhysicUserAllocator.cpp | 1b7ef45f14e6085e9d8606634b6d5d293e9837cc | [] | 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 | 8,448 | cpp | #include "__PCH_PhysX.h"
#ifdef WIN32
#define NOMINMAX
#include <windows.h>
#elif LINUX
#include "string.h"
#endif
#include <stdio.h>
#include "NxPhysics.h"
#include "PhysicUserAllocator.h"
#define MEMBLOCKSTART 64
static const size_t g_pointerMarker = (size_t)0xbadbad00deadbabeLL;
CPhysicUserAllocator::CPhysicUserAllocator()
: mNbAllocatedBytes(0)
, mHighWaterMark(0)
, mTotalNbAllocs(0)
, mNbAllocs(0)
, mNbReallocs(0)
{
//we need a lock so that block list handling etc is thread safe.
#if defined(WIN32) || defined(_XBOX)
InitializeCriticalSection(&allocatorLock);
#endif
mMemBlockList = NULL;
#ifdef _DEBUG
//Initialize the Memory blocks list (DEBUG mode only)
mMemBlockList = (size_t*)::malloc(MEMBLOCKSTART*sizeof(size_t));
memset(mMemBlockList, 0, MEMBLOCKSTART*sizeof(size_t));
mMemBlockListSize = MEMBLOCKSTART;
mMemBlockFirstFree = 0;
mMemBlockUsed = 0;
#endif
}
CPhysicUserAllocator::~CPhysicUserAllocator()
{
if(mNbAllocatedBytes) printf("Memory leak detected: %d bytes non released\n", mNbAllocatedBytes);
if(mNbAllocs) printf("Remaining allocs: %d\n", mNbAllocs);
printf("Nb alloc: %d\n", mTotalNbAllocs);
printf("Nb realloc: %d\n", mNbReallocs);
printf("High water mark: %d Kb\n", mHighWaterMark/1024);
#ifdef _DEBUG
// Scanning for memory leaks
if(mMemBlockList && mMemBlockUsed)
{
NxU32 NbLeaks = 0;
printf("\n\n ICE Message Memory leaks detected :\n\n");
NxU32 used = mMemBlockUsed;
for(NxU32 i=0, j=0; i<used; i++, j++)
{
while(!mMemBlockList[j]) j++;
size_t* cur = (size_t*)mMemBlockList[j];
//printf(" Address 0x%.8X, %d bytes (%s), allocated in: %s(%d):\n\n", cur+6, cur[1], (const char*)cur[5], (const char*)cur[2], cur[3]);
NbLeaks++;
// Free(cur+4);
}
//printf("\n Dump complete (%d leaks)\n\n", NbLeaks);
}
// Free the Memory Block list
::free(mMemBlockList);
mMemBlockList = NULL;
#endif
#if defined(WIN32) || defined(_XBOX)
DeleteCriticalSection(&allocatorLock);
#endif
}
void CPhysicUserAllocator::reset()
{
LockAlloc();
mNbAllocatedBytes = 0;
mHighWaterMark = 0;
mNbAllocs = 0;
UnlockAlloc();
}
void* CPhysicUserAllocator::malloc(size_t size)
{
printf("Obsolete code called!\n");
return NULL;
}
void* CPhysicUserAllocator::malloc(size_t size, NxMemoryType type)
{
#ifdef _DEBUG
return mallocDEBUG(size, NULL, 0, "Undefined", type);
#endif
if(size == 0)
{
printf("Warning: trying to allocate 0 bytes\n");
return NULL;
}
LockAlloc();
void* ptr = (void*)::malloc(size+2*sizeof(size_t));
mTotalNbAllocs++;
mNbAllocs++;
size_t* blockStart = (size_t*)ptr;
blockStart[0] = g_pointerMarker;
blockStart[1] = size;
mNbAllocatedBytes+=(NxI32)size;
if(mNbAllocatedBytes>mHighWaterMark) mHighWaterMark = mNbAllocatedBytes;
UnlockAlloc();
return ((size_t*)ptr)+2;
}
void* CPhysicUserAllocator::mallocDEBUG(size_t size, const char* file, int line)
{
printf("Obsolete code called!\n");
return NULL;
}
void* CPhysicUserAllocator::mallocDEBUG(size_t size, const char* file, int line, const char* className, NxMemoryType type)
{
#ifndef _DEBUG
return malloc(size, type);
#endif
if(size == 0)
{
printf("Warning: trying to allocate 0 bytes\n");
return NULL;
}
LockAlloc();
void* ptr = (void*)::malloc(size+6*sizeof(size_t));
mTotalNbAllocs++;
mNbAllocs++;
size_t* blockStart = (size_t*)ptr;
blockStart[0] = g_pointerMarker;
blockStart[1] = size;
blockStart[2] = (size_t)file;
blockStart[3] = line;
mNbAllocatedBytes+=(NxI32)size;
if(mNbAllocatedBytes>mHighWaterMark) mHighWaterMark = mNbAllocatedBytes;
// Insert the allocated block in the debug memory block list
if(mMemBlockList)
{
mMemBlockList[mMemBlockFirstFree] = (size_t)ptr;
blockStart[4] = mMemBlockFirstFree;
mMemBlockUsed++;
if(mMemBlockUsed==mMemBlockListSize)
{
size_t* tps = (size_t*)::malloc((mMemBlockListSize+MEMBLOCKSTART)*sizeof(size_t));
memcpy(tps, mMemBlockList, mMemBlockListSize*sizeof(size_t));
memset((tps+mMemBlockListSize), 0, MEMBLOCKSTART*sizeof(size_t));
::free(mMemBlockList);
mMemBlockList = tps;
mMemBlockFirstFree = mMemBlockListSize-1;
mMemBlockListSize += MEMBLOCKSTART;
}
while(mMemBlockList[++mMemBlockFirstFree] && (mMemBlockFirstFree<mMemBlockListSize));
if(mMemBlockFirstFree==mMemBlockListSize)
{
mMemBlockFirstFree = (size_t)-1;
while(mMemBlockList[++mMemBlockFirstFree] && (mMemBlockFirstFree<mMemBlockListSize));
}
}
else
{
blockStart[4] = 0;
}
blockStart[5] = (size_t)className;
UnlockAlloc();
return ((size_t*)ptr)+6;
}
void* CPhysicUserAllocator::realloc(void* memory, size_t size)
{
// return ::realloc(memory, size);
if(memory == NULL)
{
printf("Warning: trying to realloc null pointer\n");
return NULL;
}
if(size == 0)
{
printf("Warning: trying to realloc 0 bytes\n");
}
#ifdef _DEBUG
LockAlloc();
size_t* ptr = ((size_t*)memory)-6;
if(ptr[0]!=g_pointerMarker)
{
printf("Error: realloc unknown memory!!\n");
}
mNbAllocatedBytes -= (NxI32)ptr[1];
mNbAllocatedBytes += (NxI32)size;
if(mNbAllocatedBytes>mHighWaterMark) mHighWaterMark = mNbAllocatedBytes;
//need to store this for removal later
size_t oldMemBlockIndex = ptr[4];
void* ptr2 = ::realloc(ptr, size+6*sizeof(size_t));
mNbReallocs++;
*(((size_t*)ptr2)+1) = size;
if(ptr==ptr2)
{
UnlockAlloc();
return memory;
}
*(((size_t*)ptr2)) = g_pointerMarker;
*(((size_t*)ptr2)+1) = size;
*(((size_t*)ptr2)+2) = 0; // File
*(((size_t*)ptr2)+3) = 0; // Line
NxU32* blockStart = (NxU32*)ptr2;
// Remove the old allocated block from the debug memory block list
if(mMemBlockList)
{
mMemBlockList[oldMemBlockIndex] = 0;
mMemBlockUsed--;
}
// Insert the allocated block in the debug memory block list
if(mMemBlockList)
{
mMemBlockList[mMemBlockFirstFree] = (size_t)ptr;
blockStart[4] = mMemBlockFirstFree;
mMemBlockUsed++;
if(mMemBlockUsed==mMemBlockListSize)
{
size_t* tps = (size_t*)::malloc((mMemBlockListSize+MEMBLOCKSTART)*sizeof(size_t));
memcpy(tps, mMemBlockList, mMemBlockListSize*sizeof(size_t));
memset((tps+mMemBlockListSize), 0, MEMBLOCKSTART*sizeof(size_t));
::free(mMemBlockList);
mMemBlockList = tps;
mMemBlockFirstFree = mMemBlockListSize-1;
mMemBlockListSize += MEMBLOCKSTART;
}
while(mMemBlockList[++mMemBlockFirstFree] && (mMemBlockFirstFree<mMemBlockListSize));
if(mMemBlockFirstFree==mMemBlockListSize)
{
mMemBlockFirstFree = (size_t)-1;
while(mMemBlockList[++mMemBlockFirstFree] && (mMemBlockFirstFree<mMemBlockListSize));
}
}
else
{
blockStart[4] = 0;
}
blockStart[5] = 0; // Classname
UnlockAlloc();
return ((size_t*)ptr2)+6;
#else
LockAlloc();
size_t* ptr = ((size_t*)memory)-2;
if(ptr[0]!=g_pointerMarker)
{
printf("Error: realloc unknown memory!!\n");
}
mNbAllocatedBytes -= (NxI32)ptr[1];
mNbAllocatedBytes += (NxI32)size;
if(mNbAllocatedBytes>mHighWaterMark) mHighWaterMark = mNbAllocatedBytes;
void* ptr2 = ::realloc(ptr, size+2*sizeof(size_t));
mNbReallocs++;
*(((size_t*)ptr2)+1) = size;
if(ptr == ptr2)
{
UnlockAlloc();
return memory;
}
*(((size_t*)ptr2)) = g_pointerMarker;
UnlockAlloc();
return ((size_t*)ptr2)+2;
#endif
}
void CPhysicUserAllocator::free(void* memory)
{
if(memory == NULL)
{
printf("Warning: trying to free null pointer\n");
return;
}
LockAlloc();
#ifdef _DEBUG
size_t* ptr = ((size_t*)memory)-6;
if(ptr[0] != g_pointerMarker)
{
printf("Error: free unknown memory!!\n");
}
mNbAllocatedBytes -= (NxI32)ptr[1];
mNbAllocs--;
const char* File = (const char*)ptr[2];
size_t Line = ptr[3];
size_t MemBlockFirstFree = ptr[4];
// Remove the block from the Memory block list
if(mMemBlockList)
{
mMemBlockList[MemBlockFirstFree] = 0;
mMemBlockUsed--;
}
#else
size_t* ptr = ((size_t*)memory)-2;
if(ptr[0] != g_pointerMarker)
{
printf("Error: free unknown memory!!\n");
}
mNbAllocatedBytes -= (NxI32)ptr[1];
if(mNbAllocatedBytes < 0)
{
printf("Oops (%d)\n", ptr[1]);
}
mNbAllocs--;
#endif
ptr[0]=g_pointerMarker;
ptr[1]=0;
::free(ptr);
UnlockAlloc();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
376
]
]
] |
36b7f8fa37fe3d83bb342fb2c681e5a561779c30 | 29e87c19d99b77d379b2f9760f5e7afb3b3790fa | /src/audio/backend_portaudio.cpp | 6888e8ebb9961a094738469ecb8a0ae4007fb3d8 | [] | no_license | wilcobrouwer/dmplayer | c0c63d9b641a0f76e426ed30c3a83089166d0000 | 9f767a15e25016f6ada4eff6a1cdd881ad922915 | refs/heads/master | 2021-05-30T17:23:21.889844 | 2011-03-29T08:51:52 | 2011-03-29T08:51:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,911 | cpp | #include "backend_portaudio.h"
#include "../error-handling.h"
#include "../util/StrFormat.h"
#include <boost/thread/mutex.hpp>
boost::mutex pa_mutex; // PortAudio is not thread safe
#define BUFFER_SECONDS (1) // FIXME: This is really coarse grained
using namespace std;
int PortAudioBackend::pa_callback(const void *inputBuffer, void *outputBuffer,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
PortAudioBackend* be = (PortAudioBackend*)userData;
uint8* out = (uint8*)outputBuffer;
unsigned long byteCount = (frameCount * be->af.Channels * be->af.BitsPerSample) >> 3; // divide by 8 for bits->bytes
return be->data_callback(out, byteCount);
}
int PortAudioBackend::data_callback(uint8* out, unsigned long byteCount)
{
// FIXED: This callback runs with PRIO_REALTIME, but it doesn't do much so this won't cause problems
// only 1 mutex is locked, 1 memcpy call is made, and possibly 1 memset call
// in addition the mutex is not held by any other threads while they
// do anything taking more than a few cycles
size_t read = cbuf.read(out, byteCount);
if (read < byteCount)
memset(out+read, 0, byteCount-read);
return 0;
}
void PortAudioBackend::decodeloop()
{
try {
size_t decode = 0;
uint8* buf = NULL;
while (true) {
boost::this_thread::interruption_point();
cbuf.write(buf, decode, decode);
decode = dec->getData(buf, decode);
if (decode == 0) boost::this_thread::sleep(boost::posix_time::milliseconds(10));
}
} catch (boost::thread_interrupted& /*e*/) {
}
}
PortAudioBackend::PortAudioBackend(AudioController* _dec)
: IBackend(dec), dec(_dec)
{
boost::mutex::scoped_lock lock(pa_mutex);
PaError err = Pa_Initialize();
if (err != paNoError)
throw SoundException("PortAudioBackend initialisation failed");
int numDevices = Pa_GetDeviceCount();
if(numDevices < 0) {
throw SoundException(STRFORMAT("PortAudio backend: ERROR: Pa_GetDeviceCount returned 0x%x (%s)\n", numDevices, Pa_GetErrorText(numDevices)));
}
if(numDevices == 0) {
throw SoundException("PortAudio backend: ERROR: No output devices available");
}
int default_device = Pa_GetDefaultOutputDevice();
const PaDeviceInfo* deviceInfo = Pa_GetDeviceInfo( default_device );
int best_device = default_device;
string default_name = deviceInfo->name;
string device_name = deviceInfo->name;
int n_channels = deviceInfo->maxOutputChannels;
double samplerate = deviceInfo->defaultSampleRate;
double latency = deviceInfo->defaultHighOutputLatency;
PaStreamParameters outputParameters;
outputParameters.channelCount = deviceInfo->maxOutputChannels;
outputParameters.device = default_device;
outputParameters.hostApiSpecificStreamInfo = NULL;
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = deviceInfo->defaultHighOutputLatency;
bool supports_float = (Pa_IsFormatSupported(NULL, &outputParameters, deviceInfo->defaultSampleRate) == paFormatIsSupported);
for(int i=0; i<numDevices; i++) {
deviceInfo = Pa_GetDeviceInfo( i );
dcerr( "Found device #" << i << ": '" << deviceInfo->name << "'");
dcerr( "\tmaxInputChannels=" << deviceInfo->maxInputChannels);
dcerr( "\tmaxOutputChannels=" << deviceInfo->maxOutputChannels);
dcerr( "\tdefaultSampleRate=" << deviceInfo->defaultSampleRate);
outputParameters.channelCount = deviceInfo->maxOutputChannels;
outputParameters.device = i;
outputParameters.hostApiSpecificStreamInfo = NULL;
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = deviceInfo->defaultHighOutputLatency;
if(Pa_IsFormatSupported(NULL, &outputParameters, deviceInfo->defaultSampleRate) == paFormatIsSupported) {
if( ((deviceInfo->maxOutputChannels > n_channels) && (deviceInfo->defaultSampleRate >= samplerate)))
{
best_device = i;
n_channels = deviceInfo->maxOutputChannels;
samplerate = deviceInfo->defaultSampleRate;
latency = deviceInfo->defaultHighOutputLatency;
supports_float = true;
}
dcerr("device supports " << deviceInfo->maxOutputChannels << " channels, " << deviceInfo->defaultSampleRate << "Hz, Float32 output, with " << deviceInfo->defaultHighOutputLatency << "s latency");
}
else {
dcerr("device does not support " << deviceInfo->maxOutputChannels << " channels, " << deviceInfo->defaultSampleRate << "Hz, Float32 output, with " << deviceInfo->defaultHighOutputLatency << "s latency");
}
}
if(!supports_float) { // FIXME: try to set up default 16bit PCM output
cerr << "PortAudio: Error: Could not find a suitable device (missing float32 output support!). Expect Major Breakage!!" << endl;
}
if(fabs(samplerate - double(long(samplerate))) > 0.5)
cout << "PortAudio backend: WARNING: samplerate mismatch > 0.5!" << endl;
af.SampleRate = uint32(samplerate);
af.Channels = std::min(dec->get_preferred_output_channel_count(), n_channels);
af.BitsPerSample = 32;
af.SignedSample = true;
af.LittleEndian = true;
af.Float = true;
cbuf.reset(BUFFER_SECONDS * (af.BitsPerSample/8) * af.Channels * af.SampleRate);
outputParameters.channelCount = af.Channels;
outputParameters.device = best_device;
outputParameters.sampleFormat = paFloat32;
outputParameters.hostApiSpecificStreamInfo = NULL;
// Request 1/5 of a second output latency (should give us 'interactive enough'
// performance while still allowing some other tasks to interrupt playback
// momentarily)
outputParameters.suggestedLatency = 0.2;
if(Pa_IsFormatSupported(NULL, &outputParameters, samplerate) == paFormatIsSupported) {
if(Pa_OpenStream(
&stream,
NULL,
&outputParameters,
samplerate,
paFramesPerBufferUnspecified, // Let PortAudio decide the optimal number of frames per buffer
paClipOff, /* we won't output out of range samples so don't bother clipping them */
pa_callback,
(void*)this)
!= paNoError)
throw SoundException("PortAudio backend: ERROR: failed to open portaudio stream");
}
else {
throw SoundException("PortAudio backend: ERROR: Format not supported!");
}
cout << "PortAudio: Selected device '" << device_name << "', device #" << best_device << " (default is '" << default_name << "', device #" << default_device << ")." << endl;
cout << "PortAudio: Device supports " << n_channels << " channels (requested " << af.Channels << "), " << samplerate << "Hz, Float32 output, with " << latency << "s latency." << endl;
};
PortAudioBackend::~PortAudioBackend()
{
stop_output();
boost::mutex::scoped_lock lock(pa_mutex);
dcerr("shutting down");
Pa_StopStream(stream);
Pa_CloseStream(stream);
Pa_Terminate();
dcerr("shut down");
}
void PortAudioBackend::stop_output()
{
boost::mutex::scoped_lock lock(pa_mutex);
PaError err = Pa_StopStream( stream );
if((err != paNoError) && (err != paStreamIsStopped))
throw SoundException(STRFORMAT("failed to stop portaudio stream: %s", Pa_GetErrorText(err)));
decodethread.interrupt();
decodethread.join();
}
void PortAudioBackend::start_output()
{
boost::mutex::scoped_lock lock(pa_mutex);
PaError err = Pa_StartStream( stream );
if ((err != paNoError) && (err != paStreamIsNotStopped))
throw SoundException(STRFORMAT("failed to start portaudio stream: %s", Pa_GetErrorText(err)));
decodethread = boost::thread(&PortAudioBackend::decodeloop, this).move();
}
| [
"simon.sasburg@e69229e2-1541-0410-bedc-87cb2d1b0d4b",
"daniel.geelen@e69229e2-1541-0410-bedc-87cb2d1b0d4b",
"daan.wissing@e69229e2-1541-0410-bedc-87cb2d1b0d4b"
] | [
[
[
1,
2
],
[
6,
6
],
[
8,
10
],
[
15,
16
],
[
18,
55
],
[
57,
58
],
[
60,
60
],
[
92,
92
],
[
119,
119
],
[
128,
128
],
[
157,
161
],
[
164,
166
],
[
168,
169
],
[
177,
179
],
[
188,
189
]
],
[
[
3,
5
],
[
7,
7
],
[
11,
14
],
[
17,
17
],
[
56,
56
],
[
59,
59
],
[
61,
91
],
[
93,
118
],
[
120,
127
],
[
129,
155
],
[
162,
163
],
[
167,
167
],
[
170,
173
],
[
175,
176
],
[
180,
182
],
[
184,
184
],
[
186,
187
],
[
190,
190
]
],
[
[
156,
156
],
[
174,
174
],
[
183,
183
],
[
185,
185
]
]
] |
97672d368eebabd204a0538a1b4f7bad4466c258 | d60d14a507d9d20303821be3fd57eb5086d1eead | /PageCapture/CBho/stdafx.cpp | 7344624e73b4f75b8e9e1123d1cab7d7f0a33507 | [] | no_license | xmxjq/pagecapture | 292ffbecc921d143ae5ad16c1ba26d64b801786f | 468d6722e01dd7ffc50ce6025d5b78a509028e34 | refs/heads/master | 2021-01-09T21:52:22.397068 | 2010-05-05T09:45:30 | 2010-05-05T09:45:30 | 36,633,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | cpp | // stdafx.cpp : source file that includes just the standard includes
// CBho.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"imhmao@16b99238-1c9a-11df-9fc2-77fecae625a6"
] | [
[
[
1,
5
]
]
] |
b3fb53e271483262d157ee422b4b0f126e28e09d | 3b76b2980485417cb656215379b93b27d4444815 | /8.Nop KLTN/DIA/SCVOICECHAT/SOURCE/SC Voice Chat Server/about.h | f26ad1628f57d2792ec7a8e368c6f445791d1c3d | [] | no_license | hemprasad/lvmm-sc | 48d48625b467b3756aa510b5586af250c3a1664c | 7c68d1d3b1489787f5ec3d09bc15b4329b0c087a | refs/heads/master | 2016-09-06T11:05:32.770867 | 2011-07-25T01:09:07 | 2011-07-25T01:09:07 | 38,108,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | // about.h: interface for the about class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ABOUT_H__33737ACB_43C6_11D6_8886_F00753C10001__INCLUDED_)
#define AFX_ABOUT_H__33737ACB_43C6_11D6_8886_F00753C10001__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class about : public CDialog
{
public:
about(int n);
virtual ~about();
HBRUSH OnCtlColor(CDC *pdc,CWnd *pwnd,UINT ctrl);
void OnPaint();
DECLARE_MESSAGE_MAP()
};
#endif // !defined(AFX_ABOUT_H__33737ACB_43C6_11D6_8886_F00753C10001__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
660cdbdf02ee016525d0d3e613d0625ce91f93eb | b5ab57edece8c14a67cc98e745c7d51449defcff | /CD - Sprint 1/Captain's Log - Code/MainGame/Source/Managers/CCodeProfiler.h | c8fccce7de0e8711d471eb64cc33254a40d38451 | [] | no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 558 | h | #ifndef CCodeProfiler_h__
#define CCodeProfiler_h__
#include <vector>
#include <string>
using namespace std;
class CCodeProfiler
{
vector<string> strFunctionName;
vector<vector<float>> vTimes;
~CCodeProfiler();
CCodeProfiler();
CCodeProfiler(CCodeProfiler&);
CCodeProfiler& operator=(CCodeProfiler&);
public:
static CCodeProfiler* GetInstance();
void StartFunction(float fTime, char* szFunctionName);
void EndFunction(float fTime, char* szFunctionName);
void Output(char* szFileName);
};
#endif // CCodeProfiler_h__ | [
"dpmakin@34577012-8437-c882-6fb8-056151eb068d"
] | [
[
[
1,
26
]
]
] |
e6e8e6357c8e47e01fb292a8e800db449dc7cffa | db93a4d93dbeecef7a35d2b5c6833c1482b3fc63 | /OpenCV sample/OpenCV sample2/stdafx.cpp | 3fb01d5598b219304fbf79d702dab872e92c1f38 | [] | no_license | schiappino/my-masters-thesis | d71bed348cfcd5587b7cb5b29b825eee4570ca01 | b58c7e977c55ad90994d346cdbc23365c3439c9d | refs/heads/master | 2021-01-10T04:06:25.661663 | 2011-12-01T22:21:47 | 2011-12-01T22:21:47 | 50,738,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | // stdafx.cpp : source file that includes just the standard includes
// OpenCV sample2.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"netholik@d5417a9b-353e-50d0-132f-3a12f4a86f55"
] | [
[
[
1,
8
]
]
] |
60c267dc1bb955e3cb5cb65bbe58ebd2a69d23e8 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /branches/bokeoa-scons/pcbnew/gendrill.cpp | 6a31b85fa992bfb4af37dde84ef1d344ee502b0d | [] | no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 37,118 | cpp | /***********************************************/
/* Routine de Generation du fichier de percage */
/***********************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "plot_common.h"
#include "trigo.h"
#include "pcbnew.h"
#include "pcbplot.h"
#include "autorout.h"
#include "macros.h"
#include "protos.h"
/*
Generation du fichier de percage en format EXCELLON
Variantes supportees:
- Decimal : coord flottantes en pouces
- Metric : coord entieres en 1/10000 mm
format "Trailling Zero" ( TZ )
On peut aussi generer le plan de percage en format HPGL ou PS
*/
/* Routines importees */
class FORET
{
public:
int nb;
int diametre;
};
/* drill precision format */
class DrillPrecision
{
public:
int m_lhs;
int m_rhs;
public:
DrillPrecision(int l, int r) {m_lhs=l; m_rhs=r;}
};
/* zeros format */
enum zeros_fmt {
DECIMAL_FORMAT,
SUPPRESS_LEADING,
SUPPRESS_TRAILING
};
/* Routines Locales */
static void Fin_Drill(void);
static void PlotDrillSymbol(int x0,int y0,int diametre,int num_forme,int format);
/* Variables locales : */
static int DrillToolsCount; /* Nombre de forets a utiliser */
static float conv_unit; /* coeff de conversion des unites drill / pcb */
static bool Unit_Drill_is_Inch = TRUE; /* INCH,LZ (2:4) */
static int Zeros_Format = DECIMAL_FORMAT;
static DrillPrecision Precision(2,4);
static bool DrillOriginIsAuxAxis; // Axis selection (main / auxiliary) for Drill Origin coordinates
static wxPoint File_Drill_Offset; /* Offset des coord de percage pour le fichier généré */
static bool Minimal = false;
static bool Mirror = true;
// Keywords for read and write config
#define ZerosFormatKey wxT("DrillZerosFormat")
#define MirrorKey wxT("DrillMirrorYOpt")
#define MinimalKey wxT("DrillMinHeader")
#define UnitDrillInchKey wxT("DrillUnit")
#define DrillOriginIsAuxAxisKey wxT("DrillAuxAxis")
/****************************************/
/* Dialog box for drill file generation */
/****************************************/
enum id_drill {
ID_CREATE_DRILL_FILES = 1370,
ID_CLOSE_DRILL,
ID_SEL_DRILL_UNITS,
ID_SEL_DRILL_SHEET,
ID_SEL_ZEROS_FMT,
ID_SEL_PRECISION
};
class WinEDA_DrillFrame: public wxDialog
{
WinEDA_PcbFrame * m_Parent;
wxRadioBox * m_Choice_Drill_Plan;
wxRadioBox * m_Choice_Unit;
wxRadioBox * m_Choice_Drill_Offset;
WinEDA_EnterText * m_EnterFileNameDrill;
WinEDA_ValueCtrl * m_ViaDrillCtrl;
WinEDA_ValueCtrl * m_PenSpeed;
WinEDA_ValueCtrl * m_PenNum;
wxCheckBox * m_Check_Mirror;
wxCheckBox * m_Check_Minimal;
wxRadioBox * m_Choice_Zeros_Format;
wxRadioBox * m_Choice_Precision;
// Constructor and destructor
public:
WinEDA_DrillFrame(WinEDA_PcbFrame *parent);
~WinEDA_DrillFrame(void) {};
private:
void OnQuit(wxCommandEvent& event);
void SetParams(void);
void GenDrillFiles(wxCommandEvent& event);
void GenDrillMap(int format);
void UpdatePrecisionOptions(wxCommandEvent& event);
int Plot_Drill_PcbMap( FORET * buffer, int format);
int Gen_Liste_Forets( FORET * buffer,bool print_header);
int Gen_Drill_File_EXCELLON( FORET * buffer);
void Gen_Line_EXCELLON(char *line, float x, float y);
void Init_Drill(void);
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(WinEDA_DrillFrame, wxDialog)
EVT_BUTTON(ID_CLOSE_DRILL, WinEDA_DrillFrame::OnQuit)
EVT_BUTTON(ID_CREATE_DRILL_FILES, WinEDA_DrillFrame::GenDrillFiles)
EVT_RADIOBOX(ID_SEL_DRILL_UNITS, WinEDA_DrillFrame::UpdatePrecisionOptions)
EVT_RADIOBOX(ID_SEL_ZEROS_FMT, WinEDA_DrillFrame::UpdatePrecisionOptions)
END_EVENT_TABLE()
#define H_SIZE 550
#define V_SIZE 250
/*************************************************************************/
WinEDA_DrillFrame::WinEDA_DrillFrame(WinEDA_PcbFrame *parent):
wxDialog(parent, -1, _("Drill tools"), wxDefaultPosition, wxSize(H_SIZE, V_SIZE),
DIALOG_STYLE)
/*************************************************************************/
{
m_Parent = parent;
SetFont(*g_DialogFont);
SetReturnCode(1);
wxBoxSizer * MainBoxSizer = new wxBoxSizer(wxHORIZONTAL);
SetSizer(MainBoxSizer);
wxBoxSizer * LeftBoxSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer * MiddleBoxSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer * RightBoxSizer = new wxBoxSizer(wxVERTICAL);
MainBoxSizer->Add(LeftBoxSizer, 0, wxGROW|wxALL, 5);
MainBoxSizer->Add(MiddleBoxSizer, 0, wxGROW|wxALL, 5);
MainBoxSizer->Add(RightBoxSizer, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
/* first column, NC drill options */
wxString choice_unit_msg[] =
{_("millimeters"), _("inches") };
m_Choice_Unit = new wxRadioBox(this, ID_SEL_DRILL_UNITS,
_("Drill Units:"),
wxDefaultPosition,wxSize(-1,-1),
2,choice_unit_msg,1,wxRA_SPECIFY_COLS);
if ( Unit_Drill_is_Inch )m_Choice_Unit->SetSelection(1);
LeftBoxSizer->Add(m_Choice_Unit, 0, wxGROW|wxALL, 5);
wxString choice_zeros_format_msg[] = {
_("decimal format"), _("suppress leading zeros"), _("suppress trailing zeros")
};
m_Choice_Zeros_Format = new wxRadioBox(this, ID_SEL_ZEROS_FMT,
_("Zeros Format"),
wxDefaultPosition,wxSize(-1,-1),
3,choice_zeros_format_msg,1,wxRA_SPECIFY_COLS);
m_Choice_Zeros_Format->SetSelection(Zeros_Format);
LeftBoxSizer->Add(m_Choice_Zeros_Format, 0, wxGROW|wxALL, 5);
wxString *choice_precision_msg;
wxString choice_precision_inch_msg[] = { _("2:3"), _("2:4")};
wxString choice_precision_metric_msg[] = { _("3:2"), _("3:3")};
if (Unit_Drill_is_Inch)
choice_precision_msg = choice_precision_inch_msg;
else
choice_precision_msg = choice_precision_metric_msg;
m_Choice_Precision = new wxRadioBox(this, ID_SEL_PRECISION,
_("Precision"),
wxDefaultPosition, wxSize(-1,-1),
2,choice_precision_msg,1,wxRA_SPECIFY_COLS);
LeftBoxSizer->Add(m_Choice_Precision, 0, wxGROW|wxALL, 5);
wxString ps;
ps << Precision.m_lhs << wxT(":") << Precision.m_rhs;
m_Choice_Precision->SetStringSelection(ps);
if (Zeros_Format==DECIMAL_FORMAT) m_Choice_Precision->Enable(false);
wxString choice_drill_offset_msg[] =
{_("absolute"), _("auxiliary axis")};
m_Choice_Drill_Offset = new wxRadioBox(this, ID_SEL_DRILL_SHEET,
_("Drill Origine:"),
wxDefaultPosition,wxSize(-1,-1),
2,choice_drill_offset_msg,1,wxRA_SPECIFY_COLS);
if ( DrillOriginIsAuxAxis ) m_Choice_Drill_Offset->SetSelection(1);
LeftBoxSizer->Add(m_Choice_Drill_Offset, 0, wxGROW|wxALL, 5);
/* second column */
wxString choice_drill_plan_msg[] =
{_("none"), _("drill sheet (HPGL)"), _("drill sheet (Postscript)")};
m_Choice_Drill_Plan = new wxRadioBox(this, ID_SEL_DRILL_SHEET,
_("Drill Sheet:"),
wxDefaultPosition,wxSize(-1,-1),
3,choice_drill_plan_msg,1,wxRA_SPECIFY_COLS);
MiddleBoxSizer->Add(m_Choice_Drill_Plan, 0, wxGROW|wxALL, 5);
m_ViaDrillCtrl = new WinEDA_ValueCtrl(this, _("Via Drill"),
g_DesignSettings.m_ViaDrill, g_UnitMetric, MiddleBoxSizer,
m_Parent->m_InternalUnits);
m_PenNum = new WinEDA_ValueCtrl(this, _("Pen Number"),
g_HPGL_Pen_Num, 2, MiddleBoxSizer, 1);
m_PenSpeed = new WinEDA_ValueCtrl(this, _("Speed(cm/s)"),
g_HPGL_Pen_Speed, CENTIMETRE, MiddleBoxSizer, 1);
m_Check_Mirror = new wxCheckBox(this, -1, _("mirror y axis"));
m_Check_Mirror->SetValue(Mirror);
m_Check_Minimal = new wxCheckBox(this, -1, _("minimal header"));
m_Check_Minimal->SetValue(Minimal);
MiddleBoxSizer->Add(m_Check_Minimal, 0, wxGROW|wxALL, 5);
/* third column, buttons */
wxButton * Button = new wxButton(this, ID_CREATE_DRILL_FILES,
_("&Execute"));
Button->SetForegroundColour(*wxRED);
RightBoxSizer->Add(Button, 0, wxGROW|wxALL, 5);
Button = new wxButton(this, ID_CLOSE_DRILL, _("&Close"));
Button->SetForegroundColour(*wxBLUE);
RightBoxSizer->Add(Button, 0, wxGROW|wxALL, 5);
Centre();
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
}
/**************************************/
void WinEDA_DrillFrame::SetParams(void)
/**************************************/
{
Unit_Drill_is_Inch = (m_Choice_Unit->GetSelection() == 0) ? FALSE : TRUE;
Minimal = m_Check_Minimal->IsChecked();
Mirror = m_Check_Mirror->IsChecked();
Zeros_Format = m_Choice_Zeros_Format->GetSelection();
DrillOriginIsAuxAxis = m_Choice_Drill_Offset->GetSelection();
g_DesignSettings.m_ViaDrill = m_ViaDrillCtrl->GetValue();
Unit_Drill_is_Inch = m_Choice_Unit->GetSelection();
g_HPGL_Pen_Speed = m_PenSpeed->GetValue();
g_HPGL_Pen_Num = m_PenNum->GetValue();
if ( m_Choice_Drill_Offset->GetSelection() == 0)
File_Drill_Offset = wxPoint(0,0);
else
File_Drill_Offset = m_Parent->m_Auxiliary_Axe_Position;
/* get precision from radio box strings (this just makes it easier to
change options later)*/
wxString ps = m_Choice_Precision->GetStringSelection();
wxString l=ps.substr(0,1);
wxString r=ps.substr(2,1);
l.ToLong((long*)&Precision.m_lhs);
r.ToLong((long*)&Precision.m_rhs);
}
/*****************************************************************/
void WinEDA_PcbFrame::InstallDrillFrame(wxCommandEvent& event)
/*****************************************************************/
/* Thi function display and delete the dialog frame for drill tools
*/
{
wxConfig * Config = m_Parent->m_EDA_Config;
if( Config )
{
Config->Read(ZerosFormatKey, & Zeros_Format );
Config->Read(MirrorKey, &Mirror );
Config->Read(MinimalKey, &Minimal );
Config->Read(UnitDrillInchKey, &Unit_Drill_is_Inch );
Config->Read(DrillOriginIsAuxAxisKey, &DrillOriginIsAuxAxis );
}
WinEDA_DrillFrame * frame = new WinEDA_DrillFrame(this);
frame->ShowModal(); frame->Destroy();
}
/****************************************************************/
void WinEDA_DrillFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
/****************************************************************/
{
/* Save drill options: */
wxConfig * Config = m_Parent->m_Parent->m_EDA_Config;
SetParams();
if( Config )
{
Config->Write(ZerosFormatKey, Zeros_Format);
Config->Write(MirrorKey, Mirror);
Config->Write(MinimalKey, Minimal);
Config->Write(UnitDrillInchKey, Unit_Drill_is_Inch);
Config->Write(DrillOriginIsAuxAxisKey, DrillOriginIsAuxAxis);
}
Close(true); // true is to force the frame to close
}
/*************************************************************/
void WinEDA_DrillFrame::GenDrillFiles(wxCommandEvent& event)
/*************************************************************/
{
int ii;
wxString FullFileName;
wxString msg;
//<ryan's edit>
SetParams();
//</ryan's edit>
m_Parent->MsgPanel->EraseMsgBox();
/* Calcul des echelles de conversion */
conv_unit = 0.0001; /* unites = INCHES */
if( ! Unit_Drill_is_Inch) conv_unit = 0.000254; /* unites = mm */
/* Init nom fichier */
FullFileName = m_Parent->m_CurrentScreen->m_FileName;
ChangeFileNameExt(FullFileName, wxT(".drl") );
FullFileName = EDA_FileSelector(_("Drill file"),
wxEmptyString, /* Chemin par defaut */
FullFileName, /* nom fichier par defaut */
wxT(".drl"), /* extension par defaut */
wxT("*.drl"), /* Masque d'affichage */
this,
wxSAVE,
TRUE
);
if ( FullFileName != wxEmptyString )
{
dest = wxFopen(FullFileName, wxT("w") );
if (dest == 0)
{
msg = _("Unable to create file ") + FullFileName;
DisplayError(this, msg);
EndModal(0);
return ;
}
/* Init : */
Affiche_1_Parametre(m_Parent, 0,_("File"),FullFileName,BLUE) ;
Init_Drill();
ii = Gen_Liste_Forets( (FORET *) adr_lowmem,TRUE);
msg.Printf( wxT("%d"),ii);
Affiche_1_Parametre(m_Parent, 30,_("Tools"), msg, BROWN);
ii = Gen_Drill_File_EXCELLON( (FORET *) adr_lowmem);
msg.Printf( wxT("%d"),ii);
Affiche_1_Parametre(m_Parent, 45,_("Drill"), msg, GREEN);
Fin_Drill();
}
switch ( m_Choice_Drill_Plan->GetSelection() )
{
case 0: break;
case 1:
GenDrillMap(PLOT_FORMAT_HPGL);
break;
case 2:
GenDrillMap(PLOT_FORMAT_POST);
break;
}
EndModal(0);
}
/********************************************************************/
void WinEDA_DrillFrame::UpdatePrecisionOptions(wxCommandEvent& event)
/********************************************************************/
{
if (m_Choice_Unit->GetSelection()==1)
{ /* inch options */
m_Choice_Precision->SetString(0,_("2:3"));
m_Choice_Precision->SetString(1,_("2:4"));
}
else
{ /* metric options */
m_Choice_Precision->SetString(0,_("3:2"));
m_Choice_Precision->SetString(1,_("3:3"));
}
if (m_Choice_Zeros_Format->GetSelection()==DECIMAL_FORMAT)
m_Choice_Precision->Enable(false);
else
m_Choice_Precision->Enable(true);
}
/***************************************************************/
int WinEDA_DrillFrame::Gen_Drill_File_EXCELLON( FORET * buffer)
/***************************************************************/
/* Create the drill file in EXECELLON format
Return hole count
buffer: Drill tools list
*/
{
FORET * foret;
TRACK * pt_piste;
D_PAD * pt_pad;
MODULE * Module;
int ii, diam, nb_trous;
int x0, y0;
float xt,yt;
char line[1024];
/* Create the pad drill list : */
nb_trous = 0;
/* Examen de la liste des forets */
for(ii = 0, foret = buffer; ii < DrillToolsCount; ii++, foret++)
{
sprintf(line,"T%d\n",ii+1); fputs(line,dest);
/* Read the via list */
{
pt_piste = m_Parent->m_Pcb->m_Track;
for( ; pt_piste != NULL; pt_piste = (TRACK*) pt_piste->Pnext)
{
if(pt_piste->m_StructType != TYPEVIA) continue;
if ( pt_piste->m_Drill == 0 ) continue;
int via_drill = ( pt_piste->m_Drill < 0 ) ? g_DesignSettings.m_ViaDrill : pt_piste->m_Drill;
if ( foret->diametre != via_drill )
continue;
x0 = pt_piste->m_Start.x - File_Drill_Offset.x;
y0 = pt_piste->m_Start.y - File_Drill_Offset.y;
//<ryan's edit>
if (!Mirror) y0 *= -1;
xt = float(x0) * conv_unit; yt = float(y0) * conv_unit;
if(Unit_Drill_is_Inch)
{
Gen_Line_EXCELLON(line, xt, yt);
}
//</ryan's edit>
else
{ /* metric 3:3 */
Gen_Line_EXCELLON(line, xt*10, yt*10);
}
// si les flottants sont ecrits avec , au lieu de .
// conversion , -> . necessaire !
to_point( line );
fputs(line,dest);
nb_trous++;
}
}
/* Examen de la liste des pads : */
Module = m_Parent->m_Pcb->m_Modules;
for( ; Module != NULL; Module = (MODULE*)Module->Pnext )
{
/* Examen des pastilles */
pt_pad = (D_PAD*) Module->m_Pads;
for ( ; pt_pad != NULL; pt_pad = (D_PAD*)pt_pad->Pnext )
{
diam = pt_pad->m_Drill;
if(diam != foret->diametre) continue;
/* calcul de la position des trous: */
x0 = pt_pad->m_Pos.x - File_Drill_Offset.x;
y0 = pt_pad->m_Pos.y - File_Drill_Offset.y;
//<ryan's edit>
if (!Mirror) y0 *= -1;
xt = float(x0) * conv_unit; yt = float(y0) * conv_unit;
if(Unit_Drill_is_Inch)
Gen_Line_EXCELLON(line, xt, yt);
else
Gen_Line_EXCELLON(line, xt*10, yt*10);
// sprintf(line,"X%dY%d\n",
// (int)(float(x0) * conv_unit * 10000.0),
// (int)(float(y0) * conv_unit * 10000.0) );
// Si les flottants sont ecrits avec , au lieu de .
// conversion , -> . necessaire !
to_point( line );
fputs(line,dest);
nb_trous++;
} /* Fin examen 1 module */
} /* Fin 1 passe de foret */
} /* fin analyse des trous de modules */
return(nb_trous);
}
/**********************************************************************/
void WinEDA_DrillFrame::Gen_Line_EXCELLON(char *line, float x, float y)
/**********************************************************************/
{
wxString xs, ys;
int xpad=Precision.m_lhs + Precision.m_rhs;
int ypad=xpad;
/* I need to come up with an algorithm that handles any lhs:rhs format.*/
/* one idea is to take more inputs for xpad/ypad when metric is used. */
switch (Zeros_Format)
{
default:
case (DECIMAL_FORMAT):
sprintf(line,"X%.3fY%.3f\n", x, y);
break;
case (SUPPRESS_LEADING): /* that should work now */
for (int i=0;i<Precision.m_rhs;i++)
{ x*=10; y*=10; }
sprintf(line,"X%dY%d\n", (int) round(x), (int) round(y) );
break;
case (SUPPRESS_TRAILING):
for (int i=0;i<Precision.m_rhs;i++)
{ x *= 10; y*=10; }
if (x<0)xpad++;
if (y<0)ypad++;
xs.Printf( wxT("%0*d"), xpad, (int) round(x) );
ys.Printf( wxT("%0*d"), ypad, (int) round(y) );
size_t j=xs.Len()-1;
while (xs[j] == '0' && j) xs.Truncate(j--);
j=ys.Len()-1;
while (ys[j] == '0' && j) ys.Truncate(j--);
sprintf(line, "X%sY%s\n", CONV_TO_UTF8(xs), CONV_TO_UTF8(ys));
break;
};
}
/***************************************************/
/***************************************************/
FORET * GetOrAddForet( FORET * buffer, int diameter)
/***************************************************/
/* Search the drill tool for the diameter "diameter"
Create a new one if not found
*/
{
int ii;
FORET * foret;
if(diameter == 0) return NULL;
/* Search for an existing tool: */
for(ii = 0, foret = buffer ; ii < DrillToolsCount; ii++, foret++)
{
if(foret->diametre == diameter) /* found */
return foret;
}
/* No tool found, we must create a new one */
DrillToolsCount ++;
foret->nb = 0;
foret->diametre = diameter;
return foret;
}
/* Sort function by drill value */
int Sort_by_Drill_Value(void * foret1, void * foret2)
{
return( ((FORET*)foret1)->diametre - ((FORET*)foret2)->diametre);
}
/*********************************************************************/
int WinEDA_DrillFrame::Gen_Liste_Forets( FORET * buffer, bool print_header)
/**********************************************************************/
/* Etablit la liste des forets de percage, dans l'ordre croissant des
diametres
Retourne:
Nombre de Forets
Mise a jour: DrillToolsCount = nombre de forets differents
Genere une liste de DrillToolsCount structures FORET a partir de buffer
*/
{
FORET * foret;
D_PAD * pt_pad;
MODULE * Module;
int ii, diam;
char line[1024];
DrillToolsCount = 0; foret = buffer;
/* Create the via tools */
TRACK * pt_piste = m_Parent->m_Pcb->m_Track;
for( ; pt_piste != NULL; pt_piste = (TRACK*) pt_piste->Pnext )
{
if(pt_piste->m_StructType != TYPEVIA) continue;
if ( pt_piste->m_Drill == 0 ) continue;
int via_drill = g_DesignSettings.m_ViaDrill;
if ( pt_piste->m_Drill > 0 ) // Drill value is not the default value
via_drill = pt_piste->m_Drill;
foret = GetOrAddForet( buffer, via_drill);
if ( foret ) foret->nb++;
}
/* Create the pad tools : */
Module = m_Parent->m_Pcb->m_Modules;
for( ; Module != NULL; Module = (MODULE*)Module->Pnext )
{
/* Examen des pastilles */
pt_pad = (D_PAD*) Module->m_Pads;
for ( ; pt_pad != NULL; pt_pad = (D_PAD*)pt_pad->Pnext )
{
diam = pt_pad->m_Drill;
if(diam == 0) continue;
foret = GetOrAddForet( buffer, diam);
if ( foret ) foret->nb++;
} /* Fin examen 1 module */
}
/* tri des forets par ordre de diametre croissant */
qsort(buffer,DrillToolsCount,sizeof(FORET),
(int(*)(const void *, const void * ))Sort_by_Drill_Value);
/* Generation de la section liste des outils */
if (print_header)
{
for(ii = 0, foret = (FORET*) buffer ; ii < DrillToolsCount; ii++, foret++)
{
//<ryan's edit>
if (Unit_Drill_is_Inch) /* does it need T01, T02 or is T1,T2 ok?*/
sprintf(line,"T%dC%.3f\n", ii+1,
float(foret->diametre) * conv_unit);
else
sprintf(line,"T%dC%.3f\n", ii+1,
float(foret->diametre) * conv_unit * 10.0);
//</ryan's edit>
to_point( line );
fputs(line,dest);
}
fputs("%\n",dest);
if (!Minimal)
fputs("M47\nG05\n",dest);
if (Unit_Drill_is_Inch && !Minimal)
fputs("M72\n",dest);
else if (!Minimal)
fputs("M71\n",dest);
}
return(DrillToolsCount);
}
/***************************************/
void WinEDA_DrillFrame::Init_Drill(void)
/***************************************/
/* Print the DRILL file header */
{
char Line[256];
if (!Minimal)
{
DateAndTime(Line);
fprintf(dest,";DRILL file {%s} date %s\n",CONV_TO_UTF8(Main_Title),Line);
fputs(";FORMAT={",dest);
fprintf(dest,"%s / absolute / ",
CONV_TO_UTF8(m_Choice_Precision->GetStringSelection()));
fprintf(dest,"%s / ",CONV_TO_UTF8(m_Choice_Unit->GetStringSelection()));
fprintf(dest,"%s}\n",CONV_TO_UTF8(m_Choice_Zeros_Format->GetStringSelection()));
}
fputs("M48\n",dest);
if (!Minimal)
{
fputs("R,T\nVER,1\nFMAT,2\n",dest);
}
if(Unit_Drill_is_Inch) fputs("INCH,",dest); // Si unites en INCHES
else fputs("METRIC,",dest); // Si unites en mm
if(Zeros_Format==SUPPRESS_LEADING || Zeros_Format==DECIMAL_FORMAT)
fputs("TZ\n",dest);
else fputs("LZ\n",dest);
if (!Minimal)
fputs("TCST,OFF\nICI,OFF\nATC,ON\n",dest);
}
/************************/
void Fin_Drill(void)
/************************/
{
//add if minimal here
fputs("T0\nM30\n",dest) ; fclose(dest) ;
}
/***********************************************/
void WinEDA_DrillFrame::GenDrillMap(int format)
/***********************************************/
/* Genere le plan de percage (Drill map) format HPGL ou POSTSCRIPT
*/
{
int ii, x, y;
int plotX, plotY, TextWidth;
FORET * foret;
int intervalle = 0, CharSize = 0;
EDA_BaseStruct * PtStruct;
int old_g_PlotOrient = g_PlotOrient;
wxString FullFileName, Mask(wxT("*")), Ext;
char line[1024];
int dX, dY;
wxPoint BoardCentre;
int PlotMarge_in_mils = 400; // Margin in 1/1000 inch
int marge = PlotMarge_in_mils * U_PCB;
wxSize SheetSize;
float fTextScale = 1.0;
double scale_x = 1.0, scale_y = 1.0;
Ki_PageDescr * SheetPS = NULL;
wxString msg;
/* Init extension */
switch( format )
{
case PLOT_FORMAT_HPGL:
Ext = wxT("-drl.plt");
break;
case PLOT_FORMAT_POST:
Ext = wxT("-drl.ps");
break;
default:
DisplayError (this, wxT("WinEDA_DrillFrame::GenDrillMap() error"));
return;
}
/* Init file name */
FullFileName = m_Parent->m_CurrentScreen->m_FileName;
ChangeFileNameExt(FullFileName,Ext) ;
Mask += Ext;
FullFileName = EDA_FileSelector(_("Drill Map file"),
wxEmptyString, /* Chemin par defaut */
FullFileName, /* nom fichier par defaut */
Ext, /* extension par defaut */
Mask, /* Masque d'affichage */
this,
wxSAVE,
TRUE
);
if ( FullFileName.IsEmpty()) return;
g_PlotOrient = 0;
/* calcul des dimensions et centre du PCB */
m_Parent->m_Pcb->ComputeBoundaryBox();
dX = m_Parent->m_Pcb->m_BoundaryBox.GetWidth();
dY = m_Parent->m_Pcb->m_BoundaryBox.GetHeight();
BoardCentre = m_Parent->m_Pcb->m_BoundaryBox.Centre();
// Calcul de l'echelle du dessin du PCB,
// Echelle 1 en HPGL, dessin sur feuille A4 en PS, + texte description des symboles
switch( format )
{
case PLOT_FORMAT_HPGL: /* Calcul des echelles de conversion format HPGL */
Scale_X = Scale_Y = 1.0;
scale_x = Scale_X * SCALE_HPGL;
scale_y = Scale_Y * SCALE_HPGL;
fTextScale = SCALE_HPGL;
SheetSize = m_Parent->m_CurrentScreen->m_CurrentSheet->m_Size;
SheetSize.x *= U_PCB;
SheetSize.y *= U_PCB;
g_PlotOffset.x = 0;
g_PlotOffset.y = (int)(SheetSize.y * scale_y);
break;
case PLOT_FORMAT_POST:
{
// calcul en unites internes des dimensions de la feuille ( connues en 1/1000 pouce )
SheetPS = &g_Sheet_A4;
SheetSize.x = SheetPS->m_Size.x * U_PCB;
SheetSize.y = SheetPS->m_Size.y * U_PCB;
float Xscale = (float) (SheetSize.x - (marge*2)) / dX;
float Yscale = (float) (SheetSize.y * 0.6 - (marge*2)) / dY;
scale_x = scale_y = min(Xscale, Yscale);
g_PlotOffset.x = - (SheetSize.x/2) +
(int)(BoardCentre.x * scale_x) + marge;
g_PlotOffset.y = SheetSize.y/2 +
(int)(BoardCentre.y * scale_y) - marge;
g_PlotOffset.y += SheetSize.y / 8 ; /* decalage pour legende */
break;
}
}
dest = wxFopen(FullFileName, wxT("wt") );
if (dest == 0)
{
msg.Printf( _("Unable to create file <%s>"),FullFileName.GetData()) ;
DisplayError(this, msg); return ;
}
/* Init : */
m_Parent->MsgPanel->EraseMsgBox();
Affiche_1_Parametre(m_Parent, 0,_("File"), FullFileName, BLUE);
/* Calcul de la liste des diametres de percage (liste des forets) */
ii = Gen_Liste_Forets( (FORET *) adr_lowmem, FALSE);
msg.Printf( wxT("%d"),ii);
Affiche_1_Parametre(m_Parent, 48, _("Tools"), msg, BROWN);
switch( format )
{
case PLOT_FORMAT_HPGL:
InitPlotParametresHPGL(g_PlotOffset, scale_x, scale_y);
PrintHeaderHPGL(dest, g_HPGL_Pen_Speed,g_HPGL_Pen_Num);
break;
case PLOT_FORMAT_POST:
{
int BBox[4];
BBox[0] = BBox[1] = PlotMarge_in_mils;
BBox[2] = SheetPS->m_Size.x - PlotMarge_in_mils;
BBox[3] = SheetPS->m_Size.y - PlotMarge_in_mils;
InitPlotParametresPS(g_PlotOffset, SheetPS,
(double) 1.0 / PCB_INTERNAL_UNIT, (double) 1.0 / PCB_INTERNAL_UNIT);
SetDefaultLineWidthPS(10); // Set line with to 10/1000 inch
PrintHeaderPS(dest, wxT("PCBNEW-PS"), FullFileName, BBox);
InitPlotParametresPS(g_PlotOffset, SheetPS, scale_x, scale_y);
}
break;
default:
break;
}
/* Trace du contour ( couche EDGE ) */
PtStruct = m_Parent->m_Pcb->m_Drawings;
for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext )
{
switch( PtStruct->m_StructType )
{
case TYPEDRAWSEGMENT:
PlotDrawSegment( (DRAWSEGMENT*) PtStruct, format, EDGE_LAYER );
break;
case TYPETEXTE:
PlotTextePcb((TEXTE_PCB*) PtStruct, format, EDGE_LAYER);
break;
case TYPECOTATION:
PlotCotation((COTATION*) PtStruct, format, EDGE_LAYER);
break;
case TYPEMIRE:
PlotMirePcb((MIREPCB*) PtStruct, format, EDGE_LAYER);
break;
default:
DisplayError(this, wxT("WinEDA_DrillFrame::GenDrillMap() : Unexpected Draw Type") );
break;
}
}
TextWidth = (int)(50 * scale_x); // Set Drill Symbols width
if( format == PLOT_FORMAT_POST )
{
sprintf( line, "%d setlinewidth\n", TextWidth );
fputs(line,dest);
}
ii = Plot_Drill_PcbMap( (FORET *) adr_lowmem, format);
msg.Printf( wxT("%d"),ii);
Affiche_1_Parametre(m_Parent, 64, _("Drill"), msg,GREEN);
/* Impression de la liste des symboles utilises */
CharSize = 600; /* hauteur des textes en 1/10000 mils */
float CharScale = 1.0;
TextWidth = (int)(50 * CharScale); // Set text width
intervalle = (int)(CharSize * CharScale) + TextWidth;
switch( format)
{
case PLOT_FORMAT_HPGL:
{
/* generation des dim: commande SI x,y; x et y = dim en cm */
char csize[256];
sprintf(csize, "%2.3f", (float)CharSize * CharScale * 0.000254);
to_point(csize);
sprintf(line,"SI %s, %s;\n", csize, csize);
break;
}
case PLOT_FORMAT_POST:
/* Reglage de l'epaisseur de traits des textes */
sprintf( line,"%d setlinewidth\n", TextWidth );
break;
default: *line = 0;
break;
}
fputs(line,dest);
switch( format )
{
default:
case PLOT_FORMAT_POST:
g_PlotOffset.x = 0;
g_PlotOffset.y = 0;
InitPlotParametresPS(g_PlotOffset, SheetPS, scale_x, scale_x);
break;
case PLOT_FORMAT_HPGL:
InitPlotParametresHPGL(g_PlotOffset, scale_x, scale_x);
break;
}
/* Trace des informations */
/* Trace de "Infos" */
plotX = marge + 1000;
plotY = CharSize + 1000;
x = plotX ; y = plotY;
x = +g_PlotOffset.x + (int)(x * fTextScale);
y = g_PlotOffset.y - (int)(y * fTextScale);
switch( format )
{
case PLOT_FORMAT_HPGL:
sprintf(line,"PU %d, %d; LBInfos\03;\n",
x + (int)(intervalle * CharScale * fTextScale),
y - (int)(CharSize / 2 * CharScale * fTextScale) );
fputs(line,dest);
break;
case PLOT_FORMAT_POST:
wxString Text = wxT("Infos");
Plot_1_texte(format, Text, 0, TextWidth,
x, y,
(int) (CharSize * CharScale), (int) (CharSize * CharScale),
FALSE);
break;
}
plotY += (int)( intervalle * 1.2) + 200;
for(ii = 0, foret = (FORET*)adr_lowmem ; ii < DrillToolsCount; ii++, foret++)
{
int plot_diam;
if ( foret->nb == 0 ) continue;
plot_diam = (int)(foret->diametre * scale_x);
x = plotX; y = plotY;
x = -g_PlotOffset.x + (int)(x * fTextScale);
y = g_PlotOffset.y - (int)(y * fTextScale);
PlotDrillSymbol(x,y,plot_diam,ii, format);
intervalle = (int)(CharSize * CharScale) + TextWidth;
intervalle = (int)( intervalle * 1.2);
if ( intervalle < (plot_diam + 200 + TextWidth) ) intervalle = plot_diam + 200 + TextWidth;
int rayon = plot_diam/2;
x = plotX + rayon + (int)(CharSize * CharScale); y = plotY;
x = -g_PlotOffset.x + (int)(x * fTextScale);
y = g_PlotOffset.y - (int)(y * fTextScale);
/* Trace de la legende associee */
switch( format )
{
case PLOT_FORMAT_HPGL:
sprintf(line,"PU %d, %d; LB%2.2fmm / %2.3f\" (%d trous)\03;\n",
x + (int)(intervalle * CharScale * fTextScale),
y - (int)(CharSize / 2 * CharScale * fTextScale),
float(foret->diametre) * 0.00254,
float(foret->diametre) * 0.0001,
foret->nb );
fputs(line,dest);
break;
case PLOT_FORMAT_POST:
sprintf(line,"%2.2fmm / %2.3f\" (%d trous)",
float(foret->diametre) * 0.00254,
float(foret->diametre) * 0.0001,
foret->nb );
msg = CONV_FROM_UTF8(line);
Plot_1_texte(format, msg, 0, TextWidth,
x, y,
(int) (CharSize * CharScale),
(int) (CharSize * CharScale),
FALSE);
break;
}
plotY += intervalle;
}
switch( format )
{
case PLOT_FORMAT_HPGL:
CloseFileHPGL(dest);
break;
case PLOT_FORMAT_POST:
CloseFilePS(dest);
break;
}
g_PlotOrient = old_g_PlotOrient;
}
/********************************************************************/
int WinEDA_DrillFrame::Plot_Drill_PcbMap( FORET * buffer, int format)
/*********************************************************************/
/* Trace la liste des trous a percer en format HPGL ou POSTSCRIPT
Retourne:
Nombre de trous
Utilise:
liste des forets pointee par buffer
*/
{
FORET * foret;
TRACK * pt_piste;
D_PAD * pt_pad;
MODULE * Module;
int ii , diam, nb_trous;
wxPoint pos;
wxSize size;
/* Generation des trous des pastilles : */
nb_trous = 0;
/* Examen de la liste des vias */
for(ii = 0, foret = (FORET*)buffer ; ii < DrillToolsCount; ii++, foret++)
{
/* Generation de la liste des vias */
{
pt_piste = m_Parent->m_Pcb->m_Track;
for( ; pt_piste != NULL; pt_piste = (TRACK*) pt_piste->Pnext)
{
if(pt_piste->m_StructType != TYPEVIA) continue;
if(pt_piste->m_Drill == 0) continue;
int via_drill = g_DesignSettings.m_ViaDrill;
if (pt_piste->m_Drill >= 0) via_drill = pt_piste->m_Drill;
pos = pt_piste->m_Start;
PlotDrillSymbol(pos.x,pos.y, via_drill,ii, format);
nb_trous++;
}
}
/* Examen de la liste des pads : */
Module = m_Parent->m_Pcb->m_Modules;
for( ; Module != NULL; Module = (MODULE*)Module->Pnext )
{
/* Examen des pastilles */
pt_pad = (D_PAD*) Module->m_Pads;
for ( ; pt_pad != NULL; pt_pad = (D_PAD*)pt_pad->Pnext )
{
diam = pt_pad->m_Drill;
if(diam != foret->diametre) continue;
/* calcul de la position des trous: */
pos = pt_pad->m_Pos;
PlotDrillSymbol(pos.x,pos.y, diam,ii, format);
nb_trous++;
} /* Fin examen 1 module */
} /* Fin 1 passe de foret */
} /* fin analyse des trous de modules */
return(nb_trous);
}
/*************************************************************************/
void PlotDrillSymbol(int x0,int y0,int diametre,int num_forme, int format)
/*************************************************************************/
/* Trace un motif de numero de forme num_forme, aux coord x0, y0.
x0, y0 = coordonnees tables
diametre = diametre (coord table) du trou
num_forme = index ( permet de gererer des formes caract )
*/
{
int rayon = diametre / 2;
void (*FctPlume)(wxPoint pos, int state);
FctPlume = Move_Plume_HPGL;
if(format == PLOT_FORMAT_POST) FctPlume = LineTo_PS;
switch( num_forme)
{
case 0: /* vias : forme en X */
FctPlume( wxPoint(x0 - rayon, y0 - rayon), 'U');
FctPlume( wxPoint(x0 + rayon, y0 + rayon), 'D');
FctPlume( wxPoint(x0 + rayon, y0 - rayon), 'U');
FctPlume( wxPoint(x0 - rayon, y0 + rayon), 'D');
break;
case 1: /* Cercle */
if( format == PLOT_FORMAT_HPGL )
trace_1_pastille_RONDE_HPGL(wxPoint(x0, y0), diametre, FILAIRE);
if( format == PLOT_FORMAT_POST )
trace_1_pastille_RONDE_POST(wxPoint(x0, y0), diametre, FILAIRE);
break;
case 2: /* forme en + */
FctPlume( wxPoint(x0 , y0 - rayon),'U');
FctPlume( wxPoint(x0 , y0 + rayon),'D');
FctPlume( wxPoint(x0 + rayon, y0), 'U');
FctPlume( wxPoint(x0 - rayon, y0), 'D');
break;
case 3: /* forme en X cercle */
FctPlume( wxPoint(x0 - rayon, y0 - rayon),'U');
FctPlume( wxPoint(x0 + rayon, y0 + rayon),'D');
FctPlume( wxPoint(x0 + rayon, y0 - rayon),'U');
FctPlume( wxPoint(x0 - rayon, y0 + rayon),'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pastille_RONDE_HPGL(wxPoint(x0, y0), diametre, FILAIRE);
if( format == PLOT_FORMAT_POST )
trace_1_pastille_RONDE_POST(wxPoint(x0, y0), diametre, FILAIRE);
break;
case 4: /* forme en cercle barre de - */
FctPlume( wxPoint(x0 - rayon, y0), 'U');
FctPlume( wxPoint(x0 + rayon, y0), 'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pastille_RONDE_HPGL(wxPoint(x0, y0), diametre, FILAIRE);
if( format == PLOT_FORMAT_POST )
trace_1_pastille_RONDE_POST(wxPoint(x0, y0), diametre, FILAIRE);
break;
case 5: /* forme en cercle barre de | */
FctPlume( wxPoint(x0, y0 - rayon),'U');
FctPlume( wxPoint(x0, y0 + rayon),'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pastille_RONDE_HPGL(wxPoint(x0, y0), diametre, FILAIRE);
if( format == PLOT_FORMAT_POST )
trace_1_pastille_RONDE_POST(wxPoint(x0, y0), diametre, FILAIRE);
break;
case 6: /* forme en carre */
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 0, FILAIRE) ;
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 0, FILAIRE) ;
break;
case 7: /* forme en losange */
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE) ;
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE) ;
break;
case 8: /* forme en carre barre par un X*/
FctPlume( wxPoint(x0 - rayon, y0 - rayon),'U');
FctPlume( wxPoint(x0 + rayon, y0 + rayon),'D');
FctPlume( wxPoint(x0 + rayon, y0 - rayon),'U');
FctPlume( wxPoint(x0 - rayon, y0 + rayon),'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 0, FILAIRE) ;
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 0, FILAIRE) ;
break;
case 9: /* forme en losange barre par un +*/
FctPlume( wxPoint(x0, y0 - rayon),'U');
FctPlume( wxPoint(x0, y0 + rayon),'D');
FctPlume( wxPoint(x0 + rayon, y0), 'U');
FctPlume( wxPoint(x0 - rayon, y0), 'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE);
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE);
break;
case 10: /* forme en carre barre par un '/' */
FctPlume( wxPoint(x0 - rayon, y0 - rayon),'U');
FctPlume( wxPoint(x0 + rayon, y0 + rayon),'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 0, FILAIRE) ;
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 0, FILAIRE) ;
break;
case 11: /* forme en losange barre par un |*/
FctPlume( wxPoint(x0, y0 - rayon), 'U');
FctPlume( wxPoint(x0, y0 + rayon), 'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE) ;
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE) ;
break;
case 12: /* forme en losange barre par un -*/
FctPlume( wxPoint(x0 - rayon, y0), 'U');
FctPlume( wxPoint(x0 + rayon, y0), 'D');
if( format == PLOT_FORMAT_HPGL )
trace_1_pad_TRAPEZE_HPGL(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE) ;
if( format == PLOT_FORMAT_POST )
trace_1_pad_TRAPEZE_POST(wxPoint(x0,y0),wxSize(rayon, rayon),wxSize(0,0), 450, FILAIRE) ;
break;
default:
DisplayError(NULL, wxT(" Too many diameter values ( max 13)"), 10);
if( format == PLOT_FORMAT_HPGL )
trace_1_pastille_RONDE_HPGL(wxPoint(x0, y0), diametre, FILAIRE);
if( format == PLOT_FORMAT_POST )
trace_1_pastille_RONDE_POST(wxPoint(x0, y0), diametre, FILAIRE);
break;
}
if( format == PLOT_FORMAT_HPGL) Plume_HPGL('U');
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
1226
]
]
] |
30cdbc3a8efaa13dcc2880a2979db727857a4737 | 31009164b9c086f008b6196b0af0124c1a451f04 | /src/Test/TestLock.cpp | 6f5eb4e9153ccad5011fea3e0d2ccc206fe69f53 | [
"Apache-2.0"
] | permissive | duarten/slimthreading-windows | e8ca8c799e6506fc5c35c63b7e934037688fbcc2 | a685d14ca172856f5a329a93aee4d00a4d0dd879 | refs/heads/master | 2021-01-16T18:58:45.758109 | 2011-04-19T10:16:38 | 2011-04-19T10:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,957 | cpp | // Copyright 2011 Carlos Martins
//
// 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.
//
#include "stdafx.h"
//
// The number of acquirer/releaser threads.
//
#define THREADS 5
//
// The Lock
//
static StLock Lock(50);
//
// The alerter and the count down event used to synchronize shutdown.
//
static StAlerter Shutdown;
static StCountDownEvent Done(THREADS);
//
// The counters
//
static ULONG Loops[THREADS];
//
// Shared random
//
static LONG SharedSeed;
//
// Probability used to lock acquire/release.
//
#define S 100
//
// Random number generator
//
static
LONG
NextRandom (
LONG Seed
)
{
int t = (Seed % 1277773) * 16807 - (Seed / 127773) * 2836;
return (t > 0) ? t : t + 0x7fffffff;
}
//
// The acquire/releaser thread.
//
static
ULONG
WINAPI
AcquirerReleaser (
__in PVOID Argument
)
{
ULONG Id = (ULONG)Argument;
LONG LocalSeed, s;
LocalSeed = s = GetCurrentThreadId();
ULONG Timeouts = 0;
printf("+++ a/r #%d started...\n", Id);
do {
if ((s % 100) < S) {
//Lock.Enter();
while (!Lock.TryEnter(1)) {
Timeouts++;
}
s = SharedSeed = NextRandom(SharedSeed);
Lock.Exit();
} else {
s = LocalSeed = NextRandom(LocalSeed);
}
Loops[Id]++;
} while (!Shutdown.IsSet());
printf("+++a/r #%d exits: [%d/%d]\n", Id, Loops[Id], Timeouts);
Done.Signal();
return 0;
}
//
// The test function.
//
VOID
RunLockTest(
)
{
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_HIGHEST);
SharedSeed = GetTickCount();
for (int i = 0; i < THREADS; i++) {
//HANDLE ThreadHandle = CreateThread(NULL, 0, AcquirerReleaser, (PVOID)(i), 0, NULL);
HANDLE ThreadHandle = StUmsThread_Create(NULL, 0, AcquirerReleaser, (PVOID)(i), 0, NULL);
CloseHandle(ThreadHandle);
}
int start = GetTickCount();
getchar();
int elapsed = GetTickCount() - start;
//
// Alert all threads
//
Shutdown.Set();
Done.Wait();
ULONGLONG total = 0;
for (int i = 0; i < THREADS; i++) {
total += Loops[i];
}
printf("+++ Loops: %I64d, unit cost: %d ns\n", total,
(LONG)((elapsed * 1000000.0)/ total) - 20);
}
| [
"[email protected]"
] | [
[
[
1,
140
]
]
] |
847be039c106e3702b1148458fb573b0b3c52fcb | ea0f6859b1890d0050830f772eebeb2193c2c6eb | /kbot.h | 3ab2dc5074ca8da8a2c02e4eb2ab15b0e4f3f60b | [] | no_license | tjradcliffe/kbot2011 | 9086c1aca4c451bc2a9a79114741cb383f53d92e | 5dcd422927884b37ea840bfe49860c85169619af | refs/heads/master | 2016-09-11T02:25:57.314454 | 2011-04-26T00:59:50 | 2011-04-26T00:59:50 | 1,286,256 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,147 | h | #ifndef KBOT_H
#define KBOT_H
#define PID_ARM
// local includes
#include "mappings.h"
// Framework includes
#include "Gyro.h"
#include "WPILib.h"
// Standard includes old-style x.h files => cx files)
#include <map>
#include <cmath>
// local forward declarations
class AutonomousController;
class Controller;
//class I2C_Ultrasound;
class DistanceSensor;
class ProgrammedController;
class TeleopController;
class KbotPID;
/*!
The main robot class. This is where almost all of the work gets
done in the robot control framework. The idea in 2011 is to
make this class handled all of the robot control work in a
consistent, sequential form that is as close as possible identical
in autonomous and telepop.
The main clever feature of the design is to have autonomous
STRICTLY drive the robot via the same joystick controls that the
driver uses. The main loop for both autonomous and teleop is
therefore identical: get input from the joystick and put it
into the "current control state" vectors of the KBot object--with
the autonomous "joystick" being a pre-programmed sequence, and
the teleop joystick being the real things--and then read all
sensors, update all control logic, and finally controll all
motors and actuators.
*/
class KBot : public IterativeRobot
{
friend class ProgrammedController;
public:
//! Constructor builds the essentials
KBot(void);
//! Framework method to initialize robot
void RobotInit();
//! Framework method called at the start of disabled
void DisabledInit();
//! Framework method called at the start of autonomus
void AutonomousInit();
//! Framework method called at the start of teleop
void TeleopInit();
//! Framework method called on autonomous clock
void DisabledPeriodic();
//! Framework method called on autonomous clock
void AutonomousPeriodic();
//! Framework method called on teleop clock
void TeleopPeriodic();
protected:
//! Handle compressor functions
void ControlCompressor(void);
//! Reset the whole robot
void ResetRobot(bool bRecordTeleop = false);
//! Run the robot based on controller state
void RunRobot(Controller* pController);
//! Apply deadband and normalize all wheel speeds so max is 1.0
void DeadbandNormalize(double *pfWheelSpeeds);
//! Rotate a vecotr (fX, fY) through angle fAngle degrees
void RotateVector(double &fY, double &fX, double fAngle);
//! Read all the sensors into robot buffers
void ReadSensors();
//! Read the ultrasounds (takes some extra logic for cross-talk etc)
void ReadUltrasoundSensors();
//! Compute actuator inputs
void ComputeActuators(Controller* pController);
// Compute controller inputs and weight
void ComputeControllerXYR(Controller* pController);
// Compute gyro inputs and weight
void ComputeGyroXYR();
// Compute rotation etc for line following
void ComputeLineAndWallXYR();
// Compute the arm and deployer actuator outputs
void ComputeArmAndDeployer(Controller* pController);
// Compute the light states
void ComputeLights(Controller* pController);
//! Compute the weight given each of the inputs
void ComputeWeights(Controller* pController);
//! Actually update the actuators
void UpdateActuators();
//! Update the wheel speeds
void UpdateMotors();
//! Update the wrist position
void UpdateWrist();
//! Update the roller claw jaw position
void UpdateJaw();
//! Update the deployer position
void UpdateDeployer();
//! Update the driver station (extended IO)
void UpdateDriverStation();
//! Update the light relays
void UpdateLights();
protected:
static const int kPeriodicSpeed;
// PID constants for asymmetric PID controller
static const float k_posP;
static const float k_posI;
static const float k_posD;
static const float k_negP;
static const float k_negI;
static const float k_negD;
static const float kArmGain;
//! Estimated robot position, orienation and velocity
std::vector<float> m_vecPosition;
float m_fOrientation; // positive CCW, 0->360
std::vector<float> m_vecVelocity;
//! Digital sensor values
std::map<DigitalMapping, int> m_mapDigitalSensors;
//! Analog sensor values
std::map<AnalogMapping, float> m_mapAnalogSensors;
//! Body update values from various sources
//@{
std::map<CalculationMapping, float> m_mapX;
std::map<CalculationMapping, float> m_mapY;
std::map<CalculationMapping, float> m_mapR;
//@}
//! Weight vector (appliesto x/y/r from each source)
//@{
std::map<CalculationMapping, float> m_mapWeightX;
std::map<CalculationMapping, float> m_mapWeightY;
std::map<CalculationMapping, float> m_mapWeightR;
//@}
//! arm angle and speed we want
float m_fTargetArmAngle;
float m_fArmSpeed;
#ifdef PID_ARM
// Arm PID
KbotPID *m_pArmPID;
#endif
// Line following PID
KbotPID *m_pLinePID;
// Line following counter
int m_nLineCount;
//! wrist position we want (0 == in, 1 == out)
int m_nWristPosition;
//! jaw position we want (1 == open, 0 == closed)
int m_nJawPosition;
//! mini-bot deployer position we want (1 == out, 0 == in)
int m_nDeployerPosition;
int m_nReleasePosition;
//! jaw roller speeds
float m_fLowerJawRollerSpeed;
float m_fUpperJawRollerSpeed;
// Light state
LightState m_nLightState;
Relay *m_pBlueLightRelay;
Relay *m_pRedLightRelay;
Relay *m_pWhiteLightRelay;
// Light servos
Servo *m_pBlueLightServo;
Servo *m_pRedLightServo;
Servo *m_pWhiteLightServo;
///*************ACTUATORS******************
void BuildJags();
void InitJags();
//! Motor controllers for body
CANJaguar *m_pLeftFrontJaguar;
CANJaguar *m_pLeftBackJaguar;
CANJaguar *m_pRightFrontJaguar;
CANJaguar *m_pRightBackJaguar;
// convenience array of jags
std::vector<CANJaguar*> m_vecJags;
std::vector<int> m_vecJagErrors;
//! Motor controller for arm and roller claws
CANJaguar *m_pArmJaguar;
CANJaguar *m_pLowerRollerJaguar;
CANJaguar *m_pUpperRollerJaguar;
//! Solenoids to control wrist, jaw and swing-arm
Solenoid *m_pWristOutSolenoid;
Solenoid *m_pWristInSolenoid;
Solenoid *m_pJawOpenSolenoid;
Solenoid *m_pJawClosedSolenoid;
Solenoid *m_pDeployerSolenoid;
Solenoid *m_pReleaseMinibotSolenoid;
///*************SENSORS******************
// The gyro is used for maintaining orientation
Gyro *m_pGyro;
float m_fGyroSetPoint;
// I2C ultrasound sensors
//I2C_Ultrasound* m_pLeftUltrasound;
//I2C_Ultrasound* m_pRightUltrasound;
// Stopped count on line
int m_nStoppedCount;
// Analog distance sensors
DistanceSensor* m_pLeftIRSensor;
DistanceSensor* m_pRightIRSensor;
// Arm angle sensor
AnalogChannel* m_pArmAngle;
// Declare variables for the controllers
TeleopController *m_pTeleopController;
AutonomousController *m_pPlaybackController;
ProgrammedController *m_pProgrammedController;
// compressor control and sensor
Relay *m_pCompressorRelay;
DigitalInput *m_pCompressorLimit;
// line sensors
DigitalInput* m_pLineRight;
DigitalInput* m_pLineLeft;
DigitalInput* m_pLineBack;
// tube sensors
DigitalInput* m_pTubeLeft;
DigitalInput* m_pTubeRight;
AnalogChannel* m_pTubeIR;
// pole detect switch
DigitalInput* m_pPoleDetect;
// retro-reflector (if we use it)
DigitalInput* m_pRetroReflector;
// Switches
DigitalInput* m_pRecordSwitch; // 0 = record
DigitalInput* m_pRecoverSwitch; // 0 = recover
DigitalInput* m_pMirrorSwitch; // 0 = invert recorded rotations
DigitalInput* m_pOneTwoTubeSwitch; // 0 = one tube, 1 = two tubes
DigitalInput* m_pFifthSwitch; // "What is this quintesence of switch?"
// accelerometer
//ADXL345_I2C* m_pAccelerometer;
int m_autoMode; // not used
bool m_bMinibotDeployed;
bool m_bRecordOverride; // if true over-rides record/playback switch to record
bool m_bPreviousOverride; // true if on the last call to DisabledPeriodic we had an override
}; // class declaration
#endif // KBOT_H
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
3
],
[
11,
14
],
[
17,
21
],
[
24,
25
],
[
28,
48
],
[
50,
77
],
[
81,
86
],
[
89,
94
],
[
98,
101
],
[
120,
122
],
[
143,
143
],
[
160,
160
],
[
163,
163
],
[
243,
244
],
[
247,
248
],
[
250,
250
],
[
265,
266
],
[
268,
269
],
[
300,
301
],
[
304,
305
],
[
307,
309
]
],
[
[
4,
10
],
[
15,
16
],
[
22,
23
],
[
26,
27
],
[
49,
49
],
[
78,
80
],
[
87,
88
],
[
95,
97
],
[
102,
119
],
[
123,
142
],
[
144,
159
],
[
161,
162
],
[
164,
242
],
[
245,
246
],
[
249,
249
],
[
251,
264
],
[
267,
267
],
[
270,
299
],
[
302,
303
],
[
306,
306
]
]
] |
d0b315fe1d3add8e1fbce67c94d41d9e7f7ee9cc | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/AranGl/ArnTextureGl.h | 26f35bc0daf32741ae7c0ac75a44364f9c7d9e9c | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | h | #pragma once
#include "ArnRenderableObject.h"
class ArnTexture;
class ARANGL_API ArnTextureGl : public ArnRenderableObject
{
public:
~ArnTextureGl(void);
static ArnTextureGl* createFrom(const ArnTexture* tex);
virtual int render(bool bIncludeShadeless) const;
virtual void cleanup();
private:
ArnTextureGl(void);
int init();
GLuint getTextureId() const { return m_textureId; }
GLuint m_textureId;
const ArnTexture* m_target;
};
ARANGL_API void ConfigureRenderableObjectOf( ArnTexture* tex );
| [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
90dfbcce1420f842215a3edd3c9db238b02ec333 | aab4c401149d8cdee10094d4fb4de98f490be3b6 | /include/module.h | 1967324a672b750a4d7a07ceca64bf6420ae5af4 | [] | no_license | soulik/quads | a7a49e32dcd137fd32fd45b60fa26b5c0747bd03 | ce440c5d35448908fd936797bff0cb7a9ff78b6e | refs/heads/master | 2016-09-08T00:18:28.704939 | 2008-09-01T14:18:42 | 2008-09-01T14:18:42 | 32,122,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | h | #ifndef H_MODULE
#define H_MODULE
#include "thread.h"
#include "runnable.h"
#include "cChild.h"
#include "qDebug.h"
class cModule: public cThread, public qDebug, public cRunnable, public cChild {
protected:
int threaded;
SDL_mutex * mutex;
public:
cModule(cBase * parent): cChild(parent){
threaded=0;
#ifndef NO_MUTEX
mutex = SDL_CreateMutex();
#endif
}
~cModule();
inline int hasThread(){
return threaded;
}
inline void preRun(){
if (threaded) start();
}
virtual void postRun(){}
void sendMessage(char * msg);
void lockMutex();
void unlockMutex();
};
#endif | [
"soulik42@89f801e3-d555-0410-a9c1-35b9be595399"
] | [
[
[
1,
35
]
]
] |
fe42bee8fdfc5915fc52c2dc142d7576a30180a2 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkMPICommunicator.h | 67abfa643848d3cf6b19ebdc09f5b08275f8dcc3 | [
"BSD-3-Clause"
] | permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,012 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkMPICommunicator.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
// .NAME vtkMPICommunicator - Class for creating user defined MPI communicators.
// .SECTION Description
// This class can be used to create user defined MPI communicators.
// The actual creation (with MPI_Comm_create) occurs in Initialize
// which takes as arguments a super-communicator and a group of
// process ids. The new communicator is created by including the
// processes contained in the group. The global communicator
// (equivalent to MPI_COMM_WORLD) can be obtained using the class
// method GetWorldCommunicator. It is important to note that
// this communicator should not be used on the processes not contained
// in the group. For example, if the group contains processes 0 and 1,
// controller->SetCommunicator(communicator) would cause an MPI error
// on any other process.
// .SECTION See Also
// vtkMPIController vtkProcessGroup
#ifndef __vtkMPICommunicator_h
#define __vtkMPICommunicator_h
#include "vtkCommunicator.h"
class vtkMPIController;
class vtkProcessGroup;
class vtkMPICommunicatorOpaqueComm;
class vtkMPICommunicatorOpaqueRequest;
class vtkMPICommunicatorReceiveDataInfo;
class VTK_PARALLEL_EXPORT vtkMPICommunicator : public vtkCommunicator
{
public:
//BTX
class VTK_PARALLEL_EXPORT Request
{
public:
Request();
Request( const Request& );
~Request();
Request& operator = ( const Request& );
int Test();
void Cancel();
void Wait();
vtkMPICommunicatorOpaqueRequest* Req;
};
//ETX
vtkTypeMacro( vtkMPICommunicator,vtkCommunicator);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Creates an empty communicator.
static vtkMPICommunicator* New();
// Description:
// Returns the singleton which behaves as the global
// communicator (MPI_COMM_WORLD)
static vtkMPICommunicator* GetWorldCommunicator();
// Description:
// Used to initialize the communicator (i.e. create the underlying MPI_Comm).
// The group must be associated with a valid vtkMPICommunicator.
int Initialize(vtkProcessGroup *group);
// Description:
// Used to initialize the communicator (i.e. create the underlying MPI_Comm)
// using MPI_Comm_split on the given communicator.
int SplitInitialize(vtkCommunicator *oldcomm, int color, int key);
// Description:
// Performs the actual communication. You will usually use the convenience
// Send functions defined in the superclass.
virtual int SendVoidArray(const void *data, vtkIdType length, int type,
int remoteProcessId, int tag);
virtual int ReceiveVoidArray(void *data, vtkIdType length, int type,
int remoteProcessId, int tag);
// Description:
// This method sends data to another process (non-blocking).
// Tag eliminates ambiguity when multiple sends or receives
// exist in the same process. The last argument,
// vtkMPICommunicator::Request& req can later be used (with
// req.Test() ) to test the success of the message.
int NoBlockSend(const int* data, int length, int remoteProcessId, int tag,
Request& req);
int NoBlockSend(const unsigned long* data, int length, int remoteProcessId,
int tag, Request& req);
int NoBlockSend(const char* data, int length, int remoteProcessId,
int tag, Request& req);
int NoBlockSend(const float* data, int length, int remoteProcessId,
int tag, Request& req);
// Description:
// This method receives data from a corresponding send (non-blocking).
// The last argument,
// vtkMPICommunicator::Request& req can later be used (with
// req.Test() ) to test the success of the message.
int NoBlockReceive(int* data, int length, int remoteProcessId,
int tag, Request& req);
int NoBlockReceive(unsigned long* data, int length,
int remoteProcessId, int tag, Request& req);
int NoBlockReceive(char* data, int length, int remoteProcessId,
int tag, Request& req);
int NoBlockReceive(float* data, int length, int remoteProcessId,
int tag, Request& req);
#ifdef VTK_USE_64BIT_IDS
int NoBlockReceive(vtkIdType* data, int length, int remoteProcessId,
int tag, Request& req);
#endif
// Description:
// More efficient implementations of collective operations that use
// the equivalent MPI commands.
virtual void Barrier();
virtual int BroadcastVoidArray(void *data, vtkIdType length, int type,
int srcProcessId);
virtual int GatherVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type, int destProcessId);
virtual int GatherVVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType sendLength, vtkIdType *recvLengths,
vtkIdType *offsets, int type, int destProcessId);
virtual int ScatterVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type, int srcProcessId);
virtual int ScatterVVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType *sendLengths, vtkIdType *offsets,
vtkIdType recvLength, int type,
int srcProcessId);
virtual int AllGatherVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type);
virtual int AllGatherVVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType sendLength, vtkIdType *recvLengths,
vtkIdType *offsets, int type);
virtual int ReduceVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type,
int operation, int destProcessId);
virtual int ReduceVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type,
Operation *operation, int destProcessId);
virtual int AllReduceVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type,
int operation);
virtual int AllReduceVoidArray(const void *sendBuffer, void *recvBuffer,
vtkIdType length, int type,
Operation *operation);
//BTX
friend class vtkMPIController;
vtkMPICommunicatorOpaqueComm *GetMPIComm()
{
return this->MPIComm;
}
//ETX
static char* Allocate(size_t size);
static void Free(char* ptr);
// Description:
// When set to 1, all MPI_Send calls are replaced by MPI_Ssend calls.
// Default is 0.
vtkSetClampMacro(UseSsend, int, 0, 1);
vtkGetMacro(UseSsend, int);
vtkBooleanMacro(UseSsend, int);
// Description:
// Copies all the attributes of source, deleting previously
// stored data. The MPI communicator handle is also copied.
// Normally, this should not be needed. It is used during
// the construction of a new communicator for copying the
// world communicator, keeping the same context.
void CopyFrom(vtkMPICommunicator* source);
protected:
vtkMPICommunicator();
~vtkMPICommunicator();
// Obtain size and rank setting NumberOfProcesses and LocalProcessId Should
// not be called if the current communicator does not include this process
int InitializeNumberOfProcesses();
// Description:
// KeepHandle is normally off. This means that the MPI
// communicator handle will be freed at the destruction
// of the object. However, if the handle was copied from
// another object (via CopyFrom() not Duplicate()), this
// has to be turned on otherwise the handle will be freed
// multiple times causing MPI failure. The alternative to
// this is using reference counting but it is unnecessarily
// complicated for this case.
vtkSetMacro(KeepHandle, int);
vtkBooleanMacro(KeepHandle, int);
static vtkMPICommunicator* WorldCommunicator;
void InitializeCopy(vtkMPICommunicator* source);
// Description:
// Copies all the attributes of source, deleting previously
// stored data EXCEPT the MPI communicator handle which is
// duplicated with MPI_Comm_dup(). Therefore, although the
// processes in the communicator remain the same, a new context
// is created. This prevents the two communicators from
// intefering with each other during message send/receives even
// if the tags are the same.
void Duplicate(vtkMPICommunicator* source);
// Description:
// Implementation for receive data.
virtual int ReceiveDataInternal(
char* data, int length, int sizeoftype,
int remoteProcessId, int tag,
vtkMPICommunicatorReceiveDataInfo* info,
int useCopy, int& senderId);
vtkMPICommunicatorOpaqueComm* MPIComm;
int Initialized;
int KeepHandle;
int LastSenderId;
int UseSsend;
static int CheckForMPIError(int err);
private:
vtkMPICommunicator(const vtkMPICommunicator&); // Not implemented.
void operator=(const vtkMPICommunicator&); // Not implemented.
};
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
] | [
[
[
1,
250
]
]
] |
a7d214e90de23fd8a2d1c49c14f2dbe6eb70063e | 21fe9ddd8ba3a3798246be0f01a56a10e07acb2e | /v8/src/x64/assembler-x64.cc | 4ac346bbcbdecf870ce5851997e54cca83fe8240 | [
"bzip2-1.0.6",
"BSD-3-Clause"
] | permissive | yong/xruby2 | 5e2ed23574b8f9f790b7df2ab347acca4f651373 | ecc8fa062c30cb54ef41d2ccdbe46c6d5ffaa844 | refs/heads/master | 2021-01-20T11:26:04.196967 | 2011-12-02T17:40:48 | 2011-12-02T17:40:48 | 2,893,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,890 | cc | // Copyright 2011 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#if defined(V8_TARGET_ARCH_X64)
#include "macro-assembler.h"
#include "serialize.h"
namespace v8 {
namespace internal {
// -----------------------------------------------------------------------------
// Implementation of CpuFeatures
#ifdef DEBUG
bool CpuFeatures::initialized_ = false;
#endif
uint64_t CpuFeatures::supported_ = CpuFeatures::kDefaultCpuFeatures;
uint64_t CpuFeatures::found_by_runtime_probing_ = 0;
void CpuFeatures::Probe() {
ASSERT(supported_ == CpuFeatures::kDefaultCpuFeatures);
#ifdef DEBUG
initialized_ = true;
#endif
supported_ = kDefaultCpuFeatures;
if (Serializer::enabled()) {
supported_ |= OS::CpuFeaturesImpliedByPlatform();
return; // No features if we might serialize.
}
const int kBufferSize = 4 * KB;
VirtualMemory* memory = new VirtualMemory(kBufferSize);
if (!memory->IsReserved()) {
delete memory;
return;
}
ASSERT(memory->size() >= static_cast<size_t>(kBufferSize));
if (!memory->Commit(memory->address(), kBufferSize, true/*executable*/)) {
delete memory;
return;
}
Assembler assm(NULL, memory->address(), kBufferSize);
Label cpuid, done;
#define __ assm.
// Save old rsp, since we are going to modify the stack.
__ push(rbp);
__ pushfq();
__ push(rcx);
__ push(rbx);
__ movq(rbp, rsp);
// If we can modify bit 21 of the EFLAGS register, then CPUID is supported.
__ pushfq();
__ pop(rax);
__ movq(rdx, rax);
__ xor_(rax, Immediate(0x200000)); // Flip bit 21.
__ push(rax);
__ popfq();
__ pushfq();
__ pop(rax);
__ xor_(rax, rdx); // Different if CPUID is supported.
__ j(not_zero, &cpuid);
// CPUID not supported. Clear the supported features in rax.
__ xor_(rax, rax);
__ jmp(&done);
// Invoke CPUID with 1 in eax to get feature information in
// ecx:edx. Temporarily enable CPUID support because we know it's
// safe here.
__ bind(&cpuid);
__ movl(rax, Immediate(1));
supported_ = kDefaultCpuFeatures | (1 << CPUID);
{ Scope fscope(CPUID);
__ cpuid();
// Move the result from ecx:edx to rdi.
__ movl(rdi, rdx); // Zero-extended to 64 bits.
__ shl(rcx, Immediate(32));
__ or_(rdi, rcx);
// Get the sahf supported flag, from CPUID(0x80000001)
__ movq(rax, 0x80000001, RelocInfo::NONE);
__ cpuid();
}
supported_ = kDefaultCpuFeatures;
// Put the CPU flags in rax.
// rax = (rcx & 1) | (rdi & ~1) | (1 << CPUID).
__ movl(rax, Immediate(1));
__ and_(rcx, rax); // Bit 0 is set if SAHF instruction supported.
__ not_(rax);
__ and_(rax, rdi);
__ or_(rax, rcx);
__ or_(rax, Immediate(1 << CPUID));
// Done.
__ bind(&done);
__ movq(rsp, rbp);
__ pop(rbx);
__ pop(rcx);
__ popfq();
__ pop(rbp);
__ ret(0);
#undef __
typedef uint64_t (*F0)();
F0 probe = FUNCTION_CAST<F0>(reinterpret_cast<Address>(memory->address()));
supported_ = probe();
found_by_runtime_probing_ = supported_;
found_by_runtime_probing_ &= ~kDefaultCpuFeatures;
uint64_t os_guarantees = OS::CpuFeaturesImpliedByPlatform();
supported_ |= os_guarantees;
found_by_runtime_probing_ &= ~os_guarantees;
// SSE2 and CMOV must be available on an X64 CPU.
ASSERT(IsSupported(CPUID));
ASSERT(IsSupported(SSE2));
ASSERT(IsSupported(CMOV));
delete memory;
}
// -----------------------------------------------------------------------------
// Implementation of RelocInfo
// Patch the code at the current PC with a call to the target address.
// Additional guard int3 instructions can be added if required.
void RelocInfo::PatchCodeWithCall(Address target, int guard_bytes) {
// Load register with immediate 64 and call through a register instructions
// takes up 13 bytes and int3 takes up one byte.
static const int kCallCodeSize = 13;
int code_size = kCallCodeSize + guard_bytes;
// Create a code patcher.
CodePatcher patcher(pc_, code_size);
// Add a label for checking the size of the code used for returning.
#ifdef DEBUG
Label check_codesize;
patcher.masm()->bind(&check_codesize);
#endif
// Patch the code.
patcher.masm()->movq(r10, target, RelocInfo::NONE);
patcher.masm()->call(r10);
// Check that the size of the code generated is as expected.
ASSERT_EQ(kCallCodeSize,
patcher.masm()->SizeOfCodeGeneratedSince(&check_codesize));
// Add the requested number of int3 instructions after the call.
for (int i = 0; i < guard_bytes; i++) {
patcher.masm()->int3();
}
}
void RelocInfo::PatchCode(byte* instructions, int instruction_count) {
// Patch the code at the current address with the supplied instructions.
for (int i = 0; i < instruction_count; i++) {
*(pc_ + i) = *(instructions + i);
}
// Indicate that code has changed.
CPU::FlushICache(pc_, instruction_count);
}
// -----------------------------------------------------------------------------
// Register constants.
const int Register::kRegisterCodeByAllocationIndex[kNumAllocatableRegisters] = {
// rax, rbx, rdx, rcx, rdi, r8, r9, r11, r14, r15
0, 3, 2, 1, 7, 8, 9, 11, 14, 15
};
const int Register::kAllocationIndexByRegisterCode[kNumRegisters] = {
0, 3, 2, 1, -1, -1, -1, 4, 5, 6, -1, 7, -1, -1, 8, 9
};
// -----------------------------------------------------------------------------
// Implementation of Operand
Operand::Operand(Register base, int32_t disp) : rex_(0) {
len_ = 1;
if (base.is(rsp) || base.is(r12)) {
// SIB byte is needed to encode (rsp + offset) or (r12 + offset).
set_sib(times_1, rsp, base);
}
if (disp == 0 && !base.is(rbp) && !base.is(r13)) {
set_modrm(0, base);
} else if (is_int8(disp)) {
set_modrm(1, base);
set_disp8(disp);
} else {
set_modrm(2, base);
set_disp32(disp);
}
}
Operand::Operand(Register base,
Register index,
ScaleFactor scale,
int32_t disp) : rex_(0) {
ASSERT(!index.is(rsp));
len_ = 1;
set_sib(scale, index, base);
if (disp == 0 && !base.is(rbp) && !base.is(r13)) {
// This call to set_modrm doesn't overwrite the REX.B (or REX.X) bits
// possibly set by set_sib.
set_modrm(0, rsp);
} else if (is_int8(disp)) {
set_modrm(1, rsp);
set_disp8(disp);
} else {
set_modrm(2, rsp);
set_disp32(disp);
}
}
Operand::Operand(Register index,
ScaleFactor scale,
int32_t disp) : rex_(0) {
ASSERT(!index.is(rsp));
len_ = 1;
set_modrm(0, rsp);
set_sib(scale, index, rbp);
set_disp32(disp);
}
Operand::Operand(const Operand& operand, int32_t offset) {
ASSERT(operand.len_ >= 1);
// Operand encodes REX ModR/M [SIB] [Disp].
byte modrm = operand.buf_[0];
ASSERT(modrm < 0xC0); // Disallow mode 3 (register target).
bool has_sib = ((modrm & 0x07) == 0x04);
byte mode = modrm & 0xC0;
int disp_offset = has_sib ? 2 : 1;
int base_reg = (has_sib ? operand.buf_[1] : modrm) & 0x07;
// Mode 0 with rbp/r13 as ModR/M or SIB base register always has a 32-bit
// displacement.
bool is_baseless = (mode == 0) && (base_reg == 0x05); // No base or RIP base.
int32_t disp_value = 0;
if (mode == 0x80 || is_baseless) {
// Mode 2 or mode 0 with rbp/r13 as base: Word displacement.
disp_value = *BitCast<const int32_t*>(&operand.buf_[disp_offset]);
} else if (mode == 0x40) {
// Mode 1: Byte displacement.
disp_value = static_cast<signed char>(operand.buf_[disp_offset]);
}
// Write new operand with same registers, but with modified displacement.
ASSERT(offset >= 0 ? disp_value + offset > disp_value
: disp_value + offset < disp_value); // No overflow.
disp_value += offset;
rex_ = operand.rex_;
if (!is_int8(disp_value) || is_baseless) {
// Need 32 bits of displacement, mode 2 or mode 1 with register rbp/r13.
buf_[0] = (modrm & 0x3f) | (is_baseless ? 0x00 : 0x80);
len_ = disp_offset + 4;
Memory::int32_at(&buf_[disp_offset]) = disp_value;
} else if (disp_value != 0 || (base_reg == 0x05)) {
// Need 8 bits of displacement.
buf_[0] = (modrm & 0x3f) | 0x40; // Mode 1.
len_ = disp_offset + 1;
buf_[disp_offset] = static_cast<byte>(disp_value);
} else {
// Need no displacement.
buf_[0] = (modrm & 0x3f); // Mode 0.
len_ = disp_offset;
}
if (has_sib) {
buf_[1] = operand.buf_[1];
}
}
bool Operand::AddressUsesRegister(Register reg) const {
int code = reg.code();
ASSERT((buf_[0] & 0xC0) != 0xC0); // Always a memory operand.
// Start with only low three bits of base register. Initial decoding doesn't
// distinguish on the REX.B bit.
int base_code = buf_[0] & 0x07;
if (base_code == rsp.code()) {
// SIB byte present in buf_[1].
// Check the index register from the SIB byte + REX.X prefix.
int index_code = ((buf_[1] >> 3) & 0x07) | ((rex_ & 0x02) << 2);
// Index code (including REX.X) of 0x04 (rsp) means no index register.
if (index_code != rsp.code() && index_code == code) return true;
// Add REX.B to get the full base register code.
base_code = (buf_[1] & 0x07) | ((rex_ & 0x01) << 3);
// A base register of 0x05 (rbp) with mod = 0 means no base register.
if (base_code == rbp.code() && ((buf_[0] & 0xC0) == 0)) return false;
return code == base_code;
} else {
// A base register with low bits of 0x05 (rbp or r13) and mod = 0 means
// no base register.
if (base_code == rbp.code() && ((buf_[0] & 0xC0) == 0)) return false;
base_code |= ((rex_ & 0x01) << 3);
return code == base_code;
}
}
// -----------------------------------------------------------------------------
// Implementation of Assembler.
#ifdef GENERATED_CODE_COVERAGE
static void InitCoverageLog();
#endif
Assembler::Assembler(Isolate* arg_isolate, void* buffer, int buffer_size)
: AssemblerBase(arg_isolate),
code_targets_(100),
positions_recorder_(this),
emit_debug_code_(FLAG_debug_code) {
if (buffer == NULL) {
// Do our own buffer management.
if (buffer_size <= kMinimalBufferSize) {
buffer_size = kMinimalBufferSize;
if (isolate() != NULL && isolate()->assembler_spare_buffer() != NULL) {
buffer = isolate()->assembler_spare_buffer();
isolate()->set_assembler_spare_buffer(NULL);
}
}
if (buffer == NULL) {
buffer_ = NewArray<byte>(buffer_size);
} else {
buffer_ = static_cast<byte*>(buffer);
}
buffer_size_ = buffer_size;
own_buffer_ = true;
} else {
// Use externally provided buffer instead.
ASSERT(buffer_size > 0);
buffer_ = static_cast<byte*>(buffer);
buffer_size_ = buffer_size;
own_buffer_ = false;
}
// Clear the buffer in debug mode unless it was provided by the
// caller in which case we can't be sure it's okay to overwrite
// existing code in it.
#ifdef DEBUG
if (own_buffer_) {
memset(buffer_, 0xCC, buffer_size); // int3
}
#endif
// Setup buffer pointers.
ASSERT(buffer_ != NULL);
pc_ = buffer_;
reloc_info_writer.Reposition(buffer_ + buffer_size, pc_);
#ifdef GENERATED_CODE_COVERAGE
InitCoverageLog();
#endif
}
Assembler::~Assembler() {
if (own_buffer_) {
if (isolate() != NULL &&
isolate()->assembler_spare_buffer() == NULL &&
buffer_size_ == kMinimalBufferSize) {
isolate()->set_assembler_spare_buffer(buffer_);
} else {
DeleteArray(buffer_);
}
}
}
void Assembler::GetCode(CodeDesc* desc) {
// Finalize code (at this point overflow() may be true, but the gap ensures
// that we are still not overlapping instructions and relocation info).
ASSERT(pc_ <= reloc_info_writer.pos()); // No overlap.
// Setup code descriptor.
desc->buffer = buffer_;
desc->buffer_size = buffer_size_;
desc->instr_size = pc_offset();
ASSERT(desc->instr_size > 0); // Zero-size code objects upset the system.
desc->reloc_size =
static_cast<int>((buffer_ + buffer_size_) - reloc_info_writer.pos());
desc->origin = this;
}
void Assembler::Align(int m) {
ASSERT(IsPowerOf2(m));
int delta = (m - (pc_offset() & (m - 1))) & (m - 1);
while (delta >= 9) {
nop(9);
delta -= 9;
}
if (delta > 0) {
nop(delta);
}
}
void Assembler::CodeTargetAlign() {
Align(16); // Preferred alignment of jump targets on x64.
}
void Assembler::bind_to(Label* L, int pos) {
ASSERT(!L->is_bound()); // Label may only be bound once.
ASSERT(0 <= pos && pos <= pc_offset()); // Position must be valid.
if (L->is_linked()) {
int current = L->pos();
int next = long_at(current);
while (next != current) {
// Relative address, relative to point after address.
int imm32 = pos - (current + sizeof(int32_t));
long_at_put(current, imm32);
current = next;
next = long_at(next);
}
// Fix up last fixup on linked list.
int last_imm32 = pos - (current + sizeof(int32_t));
long_at_put(current, last_imm32);
}
while (L->is_near_linked()) {
int fixup_pos = L->near_link_pos();
int offset_to_next =
static_cast<int>(*reinterpret_cast<int8_t*>(addr_at(fixup_pos)));
ASSERT(offset_to_next <= 0);
int disp = pos - (fixup_pos + sizeof(int8_t));
ASSERT(is_int8(disp));
set_byte_at(fixup_pos, disp);
if (offset_to_next < 0) {
L->link_to(fixup_pos + offset_to_next, Label::kNear);
} else {
L->UnuseNear();
}
}
L->bind_to(pos);
}
void Assembler::bind(Label* L) {
bind_to(L, pc_offset());
}
void Assembler::GrowBuffer() {
ASSERT(buffer_overflow());
if (!own_buffer_) FATAL("external code buffer is too small");
// Compute new buffer size.
CodeDesc desc; // the new buffer
if (buffer_size_ < 4*KB) {
desc.buffer_size = 4*KB;
} else {
desc.buffer_size = 2*buffer_size_;
}
// Some internal data structures overflow for very large buffers,
// they must ensure that kMaximalBufferSize is not too large.
if ((desc.buffer_size > kMaximalBufferSize) ||
(desc.buffer_size > HEAP->MaxOldGenerationSize())) {
V8::FatalProcessOutOfMemory("Assembler::GrowBuffer");
}
// Setup new buffer.
desc.buffer = NewArray<byte>(desc.buffer_size);
desc.instr_size = pc_offset();
desc.reloc_size =
static_cast<int>((buffer_ + buffer_size_) - (reloc_info_writer.pos()));
// Clear the buffer in debug mode. Use 'int3' instructions to make
// sure to get into problems if we ever run uninitialized code.
#ifdef DEBUG
memset(desc.buffer, 0xCC, desc.buffer_size);
#endif
// Copy the data.
intptr_t pc_delta = desc.buffer - buffer_;
intptr_t rc_delta = (desc.buffer + desc.buffer_size) -
(buffer_ + buffer_size_);
memmove(desc.buffer, buffer_, desc.instr_size);
memmove(rc_delta + reloc_info_writer.pos(),
reloc_info_writer.pos(), desc.reloc_size);
// Switch buffers.
if (isolate() != NULL &&
isolate()->assembler_spare_buffer() == NULL &&
buffer_size_ == kMinimalBufferSize) {
isolate()->set_assembler_spare_buffer(buffer_);
} else {
DeleteArray(buffer_);
}
buffer_ = desc.buffer;
buffer_size_ = desc.buffer_size;
pc_ += pc_delta;
reloc_info_writer.Reposition(reloc_info_writer.pos() + rc_delta,
reloc_info_writer.last_pc() + pc_delta);
// Relocate runtime entries.
for (RelocIterator it(desc); !it.done(); it.next()) {
RelocInfo::Mode rmode = it.rinfo()->rmode();
if (rmode == RelocInfo::INTERNAL_REFERENCE) {
intptr_t* p = reinterpret_cast<intptr_t*>(it.rinfo()->pc());
if (*p != 0) { // 0 means uninitialized.
*p += pc_delta;
}
}
}
ASSERT(!buffer_overflow());
}
void Assembler::emit_operand(int code, const Operand& adr) {
ASSERT(is_uint3(code));
const unsigned length = adr.len_;
ASSERT(length > 0);
// Emit updated ModR/M byte containing the given register.
ASSERT((adr.buf_[0] & 0x38) == 0);
pc_[0] = adr.buf_[0] | code << 3;
// Emit the rest of the encoded operand.
for (unsigned i = 1; i < length; i++) pc_[i] = adr.buf_[i];
pc_ += length;
}
// Assembler Instruction implementations.
void Assembler::arithmetic_op(byte opcode, Register reg, const Operand& op) {
EnsureSpace ensure_space(this);
emit_rex_64(reg, op);
emit(opcode);
emit_operand(reg, op);
}
void Assembler::arithmetic_op(byte opcode, Register reg, Register rm_reg) {
EnsureSpace ensure_space(this);
ASSERT((opcode & 0xC6) == 2);
if (rm_reg.low_bits() == 4) { // Forces SIB byte.
// Swap reg and rm_reg and change opcode operand order.
emit_rex_64(rm_reg, reg);
emit(opcode ^ 0x02);
emit_modrm(rm_reg, reg);
} else {
emit_rex_64(reg, rm_reg);
emit(opcode);
emit_modrm(reg, rm_reg);
}
}
void Assembler::arithmetic_op_16(byte opcode, Register reg, Register rm_reg) {
EnsureSpace ensure_space(this);
ASSERT((opcode & 0xC6) == 2);
if (rm_reg.low_bits() == 4) { // Forces SIB byte.
// Swap reg and rm_reg and change opcode operand order.
emit(0x66);
emit_optional_rex_32(rm_reg, reg);
emit(opcode ^ 0x02);
emit_modrm(rm_reg, reg);
} else {
emit(0x66);
emit_optional_rex_32(reg, rm_reg);
emit(opcode);
emit_modrm(reg, rm_reg);
}
}
void Assembler::arithmetic_op_16(byte opcode,
Register reg,
const Operand& rm_reg) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(reg, rm_reg);
emit(opcode);
emit_operand(reg, rm_reg);
}
void Assembler::arithmetic_op_32(byte opcode, Register reg, Register rm_reg) {
EnsureSpace ensure_space(this);
ASSERT((opcode & 0xC6) == 2);
if (rm_reg.low_bits() == 4) { // Forces SIB byte.
// Swap reg and rm_reg and change opcode operand order.
emit_optional_rex_32(rm_reg, reg);
emit(opcode ^ 0x02); // E.g. 0x03 -> 0x01 for ADD.
emit_modrm(rm_reg, reg);
} else {
emit_optional_rex_32(reg, rm_reg);
emit(opcode);
emit_modrm(reg, rm_reg);
}
}
void Assembler::arithmetic_op_32(byte opcode,
Register reg,
const Operand& rm_reg) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(reg, rm_reg);
emit(opcode);
emit_operand(reg, rm_reg);
}
void Assembler::immediate_arithmetic_op(byte subcode,
Register dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
if (is_int8(src.value_)) {
emit(0x83);
emit_modrm(subcode, dst);
emit(src.value_);
} else if (dst.is(rax)) {
emit(0x05 | (subcode << 3));
emitl(src.value_);
} else {
emit(0x81);
emit_modrm(subcode, dst);
emitl(src.value_);
}
}
void Assembler::immediate_arithmetic_op(byte subcode,
const Operand& dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
if (is_int8(src.value_)) {
emit(0x83);
emit_operand(subcode, dst);
emit(src.value_);
} else {
emit(0x81);
emit_operand(subcode, dst);
emitl(src.value_);
}
}
void Assembler::immediate_arithmetic_op_16(byte subcode,
Register dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit(0x66); // Operand size override prefix.
emit_optional_rex_32(dst);
if (is_int8(src.value_)) {
emit(0x83);
emit_modrm(subcode, dst);
emit(src.value_);
} else if (dst.is(rax)) {
emit(0x05 | (subcode << 3));
emitw(src.value_);
} else {
emit(0x81);
emit_modrm(subcode, dst);
emitw(src.value_);
}
}
void Assembler::immediate_arithmetic_op_16(byte subcode,
const Operand& dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit(0x66); // Operand size override prefix.
emit_optional_rex_32(dst);
if (is_int8(src.value_)) {
emit(0x83);
emit_operand(subcode, dst);
emit(src.value_);
} else {
emit(0x81);
emit_operand(subcode, dst);
emitw(src.value_);
}
}
void Assembler::immediate_arithmetic_op_32(byte subcode,
Register dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
if (is_int8(src.value_)) {
emit(0x83);
emit_modrm(subcode, dst);
emit(src.value_);
} else if (dst.is(rax)) {
emit(0x05 | (subcode << 3));
emitl(src.value_);
} else {
emit(0x81);
emit_modrm(subcode, dst);
emitl(src.value_);
}
}
void Assembler::immediate_arithmetic_op_32(byte subcode,
const Operand& dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
if (is_int8(src.value_)) {
emit(0x83);
emit_operand(subcode, dst);
emit(src.value_);
} else {
emit(0x81);
emit_operand(subcode, dst);
emitl(src.value_);
}
}
void Assembler::immediate_arithmetic_op_8(byte subcode,
const Operand& dst,
Immediate src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
ASSERT(is_int8(src.value_) || is_uint8(src.value_));
emit(0x80);
emit_operand(subcode, dst);
emit(src.value_);
}
void Assembler::immediate_arithmetic_op_8(byte subcode,
Register dst,
Immediate src) {
EnsureSpace ensure_space(this);
if (dst.code() > 3) {
// Use 64-bit mode byte registers.
emit_rex_64(dst);
}
ASSERT(is_int8(src.value_) || is_uint8(src.value_));
emit(0x80);
emit_modrm(subcode, dst);
emit(src.value_);
}
void Assembler::shift(Register dst, Immediate shift_amount, int subcode) {
EnsureSpace ensure_space(this);
ASSERT(is_uint6(shift_amount.value_)); // illegal shift count
if (shift_amount.value_ == 1) {
emit_rex_64(dst);
emit(0xD1);
emit_modrm(subcode, dst);
} else {
emit_rex_64(dst);
emit(0xC1);
emit_modrm(subcode, dst);
emit(shift_amount.value_);
}
}
void Assembler::shift(Register dst, int subcode) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xD3);
emit_modrm(subcode, dst);
}
void Assembler::shift_32(Register dst, int subcode) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xD3);
emit_modrm(subcode, dst);
}
void Assembler::shift_32(Register dst, Immediate shift_amount, int subcode) {
EnsureSpace ensure_space(this);
ASSERT(is_uint5(shift_amount.value_)); // illegal shift count
if (shift_amount.value_ == 1) {
emit_optional_rex_32(dst);
emit(0xD1);
emit_modrm(subcode, dst);
} else {
emit_optional_rex_32(dst);
emit(0xC1);
emit_modrm(subcode, dst);
emit(shift_amount.value_);
}
}
void Assembler::bt(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src, dst);
emit(0x0F);
emit(0xA3);
emit_operand(src, dst);
}
void Assembler::bts(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src, dst);
emit(0x0F);
emit(0xAB);
emit_operand(src, dst);
}
void Assembler::call(Label* L) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
// 1110 1000 #32-bit disp.
emit(0xE8);
if (L->is_bound()) {
int offset = L->pos() - pc_offset() - sizeof(int32_t);
ASSERT(offset <= 0);
emitl(offset);
} else if (L->is_linked()) {
emitl(L->pos());
L->link_to(pc_offset() - sizeof(int32_t));
} else {
ASSERT(L->is_unused());
int32_t current = pc_offset();
emitl(current);
L->link_to(current);
}
}
void Assembler::call(Handle<Code> target,
RelocInfo::Mode rmode,
unsigned ast_id) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
// 1110 1000 #32-bit disp.
emit(0xE8);
emit_code_target(target, rmode, ast_id);
}
void Assembler::call(Register adr) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
// Opcode: FF /2 r64.
emit_optional_rex_32(adr);
emit(0xFF);
emit_modrm(0x2, adr);
}
void Assembler::call(const Operand& op) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
// Opcode: FF /2 m64.
emit_optional_rex_32(op);
emit(0xFF);
emit_operand(0x2, op);
}
// Calls directly to the given address using a relative offset.
// Should only ever be used in Code objects for calls within the
// same Code object. Should not be used when generating new code (use labels),
// but only when patching existing code.
void Assembler::call(Address target) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
// 1110 1000 #32-bit disp.
emit(0xE8);
Address source = pc_ + 4;
intptr_t displacement = target - source;
ASSERT(is_int32(displacement));
emitl(static_cast<int32_t>(displacement));
}
void Assembler::clc() {
EnsureSpace ensure_space(this);
emit(0xF8);
}
void Assembler::cld() {
EnsureSpace ensure_space(this);
emit(0xFC);
}
void Assembler::cdq() {
EnsureSpace ensure_space(this);
emit(0x99);
}
void Assembler::cmovq(Condition cc, Register dst, Register src) {
if (cc == always) {
movq(dst, src);
} else if (cc == never) {
return;
}
// No need to check CpuInfo for CMOV support, it's a required part of the
// 64-bit architecture.
ASSERT(cc >= 0); // Use mov for unconditional moves.
EnsureSpace ensure_space(this);
// Opcode: REX.W 0f 40 + cc /r.
emit_rex_64(dst, src);
emit(0x0f);
emit(0x40 + cc);
emit_modrm(dst, src);
}
void Assembler::cmovq(Condition cc, Register dst, const Operand& src) {
if (cc == always) {
movq(dst, src);
} else if (cc == never) {
return;
}
ASSERT(cc >= 0);
EnsureSpace ensure_space(this);
// Opcode: REX.W 0f 40 + cc /r.
emit_rex_64(dst, src);
emit(0x0f);
emit(0x40 + cc);
emit_operand(dst, src);
}
void Assembler::cmovl(Condition cc, Register dst, Register src) {
if (cc == always) {
movl(dst, src);
} else if (cc == never) {
return;
}
ASSERT(cc >= 0);
EnsureSpace ensure_space(this);
// Opcode: 0f 40 + cc /r.
emit_optional_rex_32(dst, src);
emit(0x0f);
emit(0x40 + cc);
emit_modrm(dst, src);
}
void Assembler::cmovl(Condition cc, Register dst, const Operand& src) {
if (cc == always) {
movl(dst, src);
} else if (cc == never) {
return;
}
ASSERT(cc >= 0);
EnsureSpace ensure_space(this);
// Opcode: 0f 40 + cc /r.
emit_optional_rex_32(dst, src);
emit(0x0f);
emit(0x40 + cc);
emit_operand(dst, src);
}
void Assembler::cmpb_al(Immediate imm8) {
ASSERT(is_int8(imm8.value_) || is_uint8(imm8.value_));
EnsureSpace ensure_space(this);
emit(0x3c);
emit(imm8.value_);
}
void Assembler::cpuid() {
ASSERT(CpuFeatures::IsEnabled(CPUID));
EnsureSpace ensure_space(this);
emit(0x0F);
emit(0xA2);
}
void Assembler::cqo() {
EnsureSpace ensure_space(this);
emit_rex_64();
emit(0x99);
}
void Assembler::decq(Register dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xFF);
emit_modrm(0x1, dst);
}
void Assembler::decq(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xFF);
emit_operand(1, dst);
}
void Assembler::decl(Register dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xFF);
emit_modrm(0x1, dst);
}
void Assembler::decl(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xFF);
emit_operand(1, dst);
}
void Assembler::decb(Register dst) {
EnsureSpace ensure_space(this);
if (dst.code() > 3) {
// Register is not one of al, bl, cl, dl. Its encoding needs REX.
emit_rex_32(dst);
}
emit(0xFE);
emit_modrm(0x1, dst);
}
void Assembler::decb(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xFE);
emit_operand(1, dst);
}
void Assembler::enter(Immediate size) {
EnsureSpace ensure_space(this);
emit(0xC8);
emitw(size.value_); // 16 bit operand, always.
emit(0);
}
void Assembler::hlt() {
EnsureSpace ensure_space(this);
emit(0xF4);
}
void Assembler::idivq(Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src);
emit(0xF7);
emit_modrm(0x7, src);
}
void Assembler::idivl(Register src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(src);
emit(0xF7);
emit_modrm(0x7, src);
}
void Assembler::imul(Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src);
emit(0xF7);
emit_modrm(0x5, src);
}
void Assembler::imul(Register dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x0F);
emit(0xAF);
emit_modrm(dst, src);
}
void Assembler::imul(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x0F);
emit(0xAF);
emit_operand(dst, src);
}
void Assembler::imul(Register dst, Register src, Immediate imm) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
if (is_int8(imm.value_)) {
emit(0x6B);
emit_modrm(dst, src);
emit(imm.value_);
} else {
emit(0x69);
emit_modrm(dst, src);
emitl(imm.value_);
}
}
void Assembler::imull(Register dst, Register src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0xAF);
emit_modrm(dst, src);
}
void Assembler::imull(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0xAF);
emit_operand(dst, src);
}
void Assembler::imull(Register dst, Register src, Immediate imm) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
if (is_int8(imm.value_)) {
emit(0x6B);
emit_modrm(dst, src);
emit(imm.value_);
} else {
emit(0x69);
emit_modrm(dst, src);
emitl(imm.value_);
}
}
void Assembler::incq(Register dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xFF);
emit_modrm(0x0, dst);
}
void Assembler::incq(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xFF);
emit_operand(0, dst);
}
void Assembler::incl(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xFF);
emit_operand(0, dst);
}
void Assembler::incl(Register dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xFF);
emit_modrm(0, dst);
}
void Assembler::int3() {
EnsureSpace ensure_space(this);
emit(0xCC);
}
void Assembler::j(Condition cc, Label* L, Label::Distance distance) {
if (cc == always) {
jmp(L);
return;
} else if (cc == never) {
return;
}
EnsureSpace ensure_space(this);
ASSERT(is_uint4(cc));
if (L->is_bound()) {
const int short_size = 2;
const int long_size = 6;
int offs = L->pos() - pc_offset();
ASSERT(offs <= 0);
if (is_int8(offs - short_size)) {
// 0111 tttn #8-bit disp.
emit(0x70 | cc);
emit((offs - short_size) & 0xFF);
} else {
// 0000 1111 1000 tttn #32-bit disp.
emit(0x0F);
emit(0x80 | cc);
emitl(offs - long_size);
}
} else if (distance == Label::kNear) {
// 0111 tttn #8-bit disp
emit(0x70 | cc);
byte disp = 0x00;
if (L->is_near_linked()) {
int offset = L->near_link_pos() - pc_offset();
ASSERT(is_int8(offset));
disp = static_cast<byte>(offset & 0xFF);
}
L->link_to(pc_offset(), Label::kNear);
emit(disp);
} else if (L->is_linked()) {
// 0000 1111 1000 tttn #32-bit disp.
emit(0x0F);
emit(0x80 | cc);
emitl(L->pos());
L->link_to(pc_offset() - sizeof(int32_t));
} else {
ASSERT(L->is_unused());
emit(0x0F);
emit(0x80 | cc);
int32_t current = pc_offset();
emitl(current);
L->link_to(current);
}
}
void Assembler::j(Condition cc,
Handle<Code> target,
RelocInfo::Mode rmode) {
EnsureSpace ensure_space(this);
ASSERT(is_uint4(cc));
// 0000 1111 1000 tttn #32-bit disp.
emit(0x0F);
emit(0x80 | cc);
emit_code_target(target, rmode);
}
void Assembler::jmp(Label* L, Label::Distance distance) {
EnsureSpace ensure_space(this);
const int short_size = sizeof(int8_t);
const int long_size = sizeof(int32_t);
if (L->is_bound()) {
int offs = L->pos() - pc_offset() - 1;
ASSERT(offs <= 0);
if (is_int8(offs - short_size)) {
// 1110 1011 #8-bit disp.
emit(0xEB);
emit((offs - short_size) & 0xFF);
} else {
// 1110 1001 #32-bit disp.
emit(0xE9);
emitl(offs - long_size);
}
} else if (distance == Label::kNear) {
emit(0xEB);
byte disp = 0x00;
if (L->is_near_linked()) {
int offset = L->near_link_pos() - pc_offset();
ASSERT(is_int8(offset));
disp = static_cast<byte>(offset & 0xFF);
}
L->link_to(pc_offset(), Label::kNear);
emit(disp);
} else if (L->is_linked()) {
// 1110 1001 #32-bit disp.
emit(0xE9);
emitl(L->pos());
L->link_to(pc_offset() - long_size);
} else {
// 1110 1001 #32-bit disp.
ASSERT(L->is_unused());
emit(0xE9);
int32_t current = pc_offset();
emitl(current);
L->link_to(current);
}
}
void Assembler::jmp(Handle<Code> target, RelocInfo::Mode rmode) {
EnsureSpace ensure_space(this);
// 1110 1001 #32-bit disp.
emit(0xE9);
emit_code_target(target, rmode);
}
void Assembler::jmp(Register target) {
EnsureSpace ensure_space(this);
// Opcode FF/4 r64.
emit_optional_rex_32(target);
emit(0xFF);
emit_modrm(0x4, target);
}
void Assembler::jmp(const Operand& src) {
EnsureSpace ensure_space(this);
// Opcode FF/4 m64.
emit_optional_rex_32(src);
emit(0xFF);
emit_operand(0x4, src);
}
void Assembler::lea(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x8D);
emit_operand(dst, src);
}
void Assembler::leal(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x8D);
emit_operand(dst, src);
}
void Assembler::load_rax(void* value, RelocInfo::Mode mode) {
EnsureSpace ensure_space(this);
emit(0x48); // REX.W
emit(0xA1);
emitq(reinterpret_cast<uintptr_t>(value), mode);
}
void Assembler::load_rax(ExternalReference ref) {
load_rax(ref.address(), RelocInfo::EXTERNAL_REFERENCE);
}
void Assembler::leave() {
EnsureSpace ensure_space(this);
emit(0xC9);
}
void Assembler::movb(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
if (dst.code() > 3) {
// Register is not one of al, bl, cl, dl. Its encoding needs REX.
emit_rex_32(dst, src);
} else {
emit_optional_rex_32(dst, src);
}
emit(0x8A);
emit_operand(dst, src);
}
void Assembler::movb(Register dst, Immediate imm) {
EnsureSpace ensure_space(this);
if (dst.code() > 3) {
emit_rex_32(dst);
}
emit(0xB0 + dst.low_bits());
emit(imm.value_);
}
void Assembler::movb(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
if (src.code() > 3) {
emit_rex_32(src, dst);
} else {
emit_optional_rex_32(src, dst);
}
emit(0x88);
emit_operand(src, dst);
}
void Assembler::movw(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(src, dst);
emit(0x89);
emit_operand(src, dst);
}
void Assembler::movl(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x8B);
emit_operand(dst, src);
}
void Assembler::movl(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
emit_optional_rex_32(src, dst);
emit(0x89);
emit_modrm(src, dst);
} else {
emit_optional_rex_32(dst, src);
emit(0x8B);
emit_modrm(dst, src);
}
}
void Assembler::movl(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(src, dst);
emit(0x89);
emit_operand(src, dst);
}
void Assembler::movl(const Operand& dst, Immediate value) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xC7);
emit_operand(0x0, dst);
emit(value);
}
void Assembler::movl(Register dst, Immediate value) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xB8 + dst.low_bits());
emit(value);
}
void Assembler::movq(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x8B);
emit_operand(dst, src);
}
void Assembler::movq(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
emit_rex_64(src, dst);
emit(0x89);
emit_modrm(src, dst);
} else {
emit_rex_64(dst, src);
emit(0x8B);
emit_modrm(dst, src);
}
}
void Assembler::movq(Register dst, Immediate value) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xC7);
emit_modrm(0x0, dst);
emit(value); // Only 32-bit immediates are possible, not 8-bit immediates.
}
void Assembler::movq(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src, dst);
emit(0x89);
emit_operand(src, dst);
}
void Assembler::movq(Register dst, void* value, RelocInfo::Mode rmode) {
// This method must not be used with heap object references. The stored
// address is not GC safe. Use the handle version instead.
ASSERT(rmode > RelocInfo::LAST_GCED_ENUM);
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xB8 | dst.low_bits());
emitq(reinterpret_cast<uintptr_t>(value), rmode);
}
void Assembler::movq(Register dst, int64_t value, RelocInfo::Mode rmode) {
// Non-relocatable values might not need a 64-bit representation.
if (rmode == RelocInfo::NONE) {
// Sadly, there is no zero or sign extending move for 8-bit immediates.
if (is_int32(value)) {
movq(dst, Immediate(static_cast<int32_t>(value)));
return;
} else if (is_uint32(value)) {
movl(dst, Immediate(static_cast<int32_t>(value)));
return;
}
// Value cannot be represented by 32 bits, so do a full 64 bit immediate
// value.
}
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xB8 | dst.low_bits());
emitq(value, rmode);
}
void Assembler::movq(Register dst, ExternalReference ref) {
int64_t value = reinterpret_cast<int64_t>(ref.address());
movq(dst, value, RelocInfo::EXTERNAL_REFERENCE);
}
void Assembler::movq(const Operand& dst, Immediate value) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xC7);
emit_operand(0, dst);
emit(value);
}
// Loads the ip-relative location of the src label into the target location
// (as a 32-bit offset sign extended to 64-bit).
void Assembler::movl(const Operand& dst, Label* src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xC7);
emit_operand(0, dst);
if (src->is_bound()) {
int offset = src->pos() - pc_offset() - sizeof(int32_t);
ASSERT(offset <= 0);
emitl(offset);
} else if (src->is_linked()) {
emitl(src->pos());
src->link_to(pc_offset() - sizeof(int32_t));
} else {
ASSERT(src->is_unused());
int32_t current = pc_offset();
emitl(current);
src->link_to(current);
}
}
void Assembler::movq(Register dst, Handle<Object> value, RelocInfo::Mode mode) {
// If there is no relocation info, emit the value of the handle efficiently
// (possibly using less that 8 bytes for the value).
if (mode == RelocInfo::NONE) {
// There is no possible reason to store a heap pointer without relocation
// info, so it must be a smi.
ASSERT(value->IsSmi());
movq(dst, reinterpret_cast<int64_t>(*value), RelocInfo::NONE);
} else {
EnsureSpace ensure_space(this);
ASSERT(value->IsHeapObject());
ASSERT(!HEAP->InNewSpace(*value));
emit_rex_64(dst);
emit(0xB8 | dst.low_bits());
emitq(reinterpret_cast<uintptr_t>(value.location()), mode);
}
}
void Assembler::movsxbq(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x0F);
emit(0xBE);
emit_operand(dst, src);
}
void Assembler::movsxwq(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x0F);
emit(0xBF);
emit_operand(dst, src);
}
void Assembler::movsxlq(Register dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x63);
emit_modrm(dst, src);
}
void Assembler::movsxlq(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_rex_64(dst, src);
emit(0x63);
emit_operand(dst, src);
}
void Assembler::movzxbq(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0xB6);
emit_operand(dst, src);
}
void Assembler::movzxbl(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0xB6);
emit_operand(dst, src);
}
void Assembler::movzxwq(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0xB7);
emit_operand(dst, src);
}
void Assembler::movzxwl(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0xB7);
emit_operand(dst, src);
}
void Assembler::repmovsb() {
EnsureSpace ensure_space(this);
emit(0xF3);
emit(0xA4);
}
void Assembler::repmovsw() {
EnsureSpace ensure_space(this);
emit(0x66); // Operand size override.
emit(0xF3);
emit(0xA4);
}
void Assembler::repmovsl() {
EnsureSpace ensure_space(this);
emit(0xF3);
emit(0xA5);
}
void Assembler::repmovsq() {
EnsureSpace ensure_space(this);
emit(0xF3);
emit_rex_64();
emit(0xA5);
}
void Assembler::mul(Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src);
emit(0xF7);
emit_modrm(0x4, src);
}
void Assembler::neg(Register dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xF7);
emit_modrm(0x3, dst);
}
void Assembler::negl(Register dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xF7);
emit_modrm(0x3, dst);
}
void Assembler::neg(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xF7);
emit_operand(3, dst);
}
void Assembler::nop() {
EnsureSpace ensure_space(this);
emit(0x90);
}
void Assembler::not_(Register dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xF7);
emit_modrm(0x2, dst);
}
void Assembler::not_(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_rex_64(dst);
emit(0xF7);
emit_operand(2, dst);
}
void Assembler::notl(Register dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0xF7);
emit_modrm(0x2, dst);
}
void Assembler::nop(int n) {
// The recommended muti-byte sequences of NOP instructions from the Intel 64
// and IA-32 Architectures Software Developer's Manual.
//
// Length Assembly Byte Sequence
// 2 bytes 66 NOP 66 90H
// 3 bytes NOP DWORD ptr [EAX] 0F 1F 00H
// 4 bytes NOP DWORD ptr [EAX + 00H] 0F 1F 40 00H
// 5 bytes NOP DWORD ptr [EAX + EAX*1 + 00H] 0F 1F 44 00 00H
// 6 bytes 66 NOP DWORD ptr [EAX + EAX*1 + 00H] 66 0F 1F 44 00 00H
// 7 bytes NOP DWORD ptr [EAX + 00000000H] 0F 1F 80 00 00 00 00H
// 8 bytes NOP DWORD ptr [EAX + EAX*1 + 00000000H] 0F 1F 84 00 00 00 00 00H
// 9 bytes 66 NOP DWORD ptr [EAX + EAX*1 + 66 0F 1F 84 00 00 00 00
// 00000000H] 00H
ASSERT(1 <= n);
ASSERT(n <= 9);
EnsureSpace ensure_space(this);
switch (n) {
case 1:
emit(0x90);
return;
case 2:
emit(0x66);
emit(0x90);
return;
case 3:
emit(0x0f);
emit(0x1f);
emit(0x00);
return;
case 4:
emit(0x0f);
emit(0x1f);
emit(0x40);
emit(0x00);
return;
case 5:
emit(0x0f);
emit(0x1f);
emit(0x44);
emit(0x00);
emit(0x00);
return;
case 6:
emit(0x66);
emit(0x0f);
emit(0x1f);
emit(0x44);
emit(0x00);
emit(0x00);
return;
case 7:
emit(0x0f);
emit(0x1f);
emit(0x80);
emit(0x00);
emit(0x00);
emit(0x00);
emit(0x00);
return;
case 8:
emit(0x0f);
emit(0x1f);
emit(0x84);
emit(0x00);
emit(0x00);
emit(0x00);
emit(0x00);
emit(0x00);
return;
case 9:
emit(0x66);
emit(0x0f);
emit(0x1f);
emit(0x84);
emit(0x00);
emit(0x00);
emit(0x00);
emit(0x00);
emit(0x00);
return;
}
}
void Assembler::pop(Register dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0x58 | dst.low_bits());
}
void Assembler::pop(const Operand& dst) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst);
emit(0x8F);
emit_operand(0, dst);
}
void Assembler::popfq() {
EnsureSpace ensure_space(this);
emit(0x9D);
}
void Assembler::push(Register src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(src);
emit(0x50 | src.low_bits());
}
void Assembler::push(const Operand& src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(src);
emit(0xFF);
emit_operand(6, src);
}
void Assembler::push(Immediate value) {
EnsureSpace ensure_space(this);
if (is_int8(value.value_)) {
emit(0x6A);
emit(value.value_); // Emit low byte of value.
} else {
emit(0x68);
emitl(value.value_);
}
}
void Assembler::push_imm32(int32_t imm32) {
EnsureSpace ensure_space(this);
emit(0x68);
emitl(imm32);
}
void Assembler::pushfq() {
EnsureSpace ensure_space(this);
emit(0x9C);
}
void Assembler::rdtsc() {
EnsureSpace ensure_space(this);
emit(0x0F);
emit(0x31);
}
void Assembler::ret(int imm16) {
EnsureSpace ensure_space(this);
ASSERT(is_uint16(imm16));
if (imm16 == 0) {
emit(0xC3);
} else {
emit(0xC2);
emit(imm16 & 0xFF);
emit((imm16 >> 8) & 0xFF);
}
}
void Assembler::setcc(Condition cc, Register reg) {
if (cc > last_condition) {
movb(reg, Immediate(cc == always ? 1 : 0));
return;
}
EnsureSpace ensure_space(this);
ASSERT(is_uint4(cc));
if (reg.code() > 3) { // Use x64 byte registers, where different.
emit_rex_32(reg);
}
emit(0x0F);
emit(0x90 | cc);
emit_modrm(0x0, reg);
}
void Assembler::shld(Register dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src, dst);
emit(0x0F);
emit(0xA5);
emit_modrm(src, dst);
}
void Assembler::shrd(Register dst, Register src) {
EnsureSpace ensure_space(this);
emit_rex_64(src, dst);
emit(0x0F);
emit(0xAD);
emit_modrm(src, dst);
}
void Assembler::xchg(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.is(rax) || dst.is(rax)) { // Single-byte encoding
Register other = src.is(rax) ? dst : src;
emit_rex_64(other);
emit(0x90 | other.low_bits());
} else if (dst.low_bits() == 4) {
emit_rex_64(dst, src);
emit(0x87);
emit_modrm(dst, src);
} else {
emit_rex_64(src, dst);
emit(0x87);
emit_modrm(src, dst);
}
}
void Assembler::store_rax(void* dst, RelocInfo::Mode mode) {
EnsureSpace ensure_space(this);
emit(0x48); // REX.W
emit(0xA3);
emitq(reinterpret_cast<uintptr_t>(dst), mode);
}
void Assembler::store_rax(ExternalReference ref) {
store_rax(ref.address(), RelocInfo::EXTERNAL_REFERENCE);
}
void Assembler::testb(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
emit_rex_32(src, dst);
emit(0x84);
emit_modrm(src, dst);
} else {
if (dst.code() > 3 || src.code() > 3) {
// Register is not one of al, bl, cl, dl. Its encoding needs REX.
emit_rex_32(dst, src);
}
emit(0x84);
emit_modrm(dst, src);
}
}
void Assembler::testb(Register reg, Immediate mask) {
ASSERT(is_int8(mask.value_) || is_uint8(mask.value_));
EnsureSpace ensure_space(this);
if (reg.is(rax)) {
emit(0xA8);
emit(mask.value_); // Low byte emitted.
} else {
if (reg.code() > 3) {
// Register is not one of al, bl, cl, dl. Its encoding needs REX.
emit_rex_32(reg);
}
emit(0xF6);
emit_modrm(0x0, reg);
emit(mask.value_); // Low byte emitted.
}
}
void Assembler::testb(const Operand& op, Immediate mask) {
ASSERT(is_int8(mask.value_) || is_uint8(mask.value_));
EnsureSpace ensure_space(this);
emit_optional_rex_32(rax, op);
emit(0xF6);
emit_operand(rax, op); // Operation code 0
emit(mask.value_); // Low byte emitted.
}
void Assembler::testb(const Operand& op, Register reg) {
EnsureSpace ensure_space(this);
if (reg.code() > 3) {
// Register is not one of al, bl, cl, dl. Its encoding needs REX.
emit_rex_32(reg, op);
} else {
emit_optional_rex_32(reg, op);
}
emit(0x84);
emit_operand(reg, op);
}
void Assembler::testl(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
emit_optional_rex_32(src, dst);
emit(0x85);
emit_modrm(src, dst);
} else {
emit_optional_rex_32(dst, src);
emit(0x85);
emit_modrm(dst, src);
}
}
void Assembler::testl(Register reg, Immediate mask) {
// testl with a mask that fits in the low byte is exactly testb.
if (is_uint8(mask.value_)) {
testb(reg, mask);
return;
}
EnsureSpace ensure_space(this);
if (reg.is(rax)) {
emit(0xA9);
emit(mask);
} else {
emit_optional_rex_32(rax, reg);
emit(0xF7);
emit_modrm(0x0, reg);
emit(mask);
}
}
void Assembler::testl(const Operand& op, Immediate mask) {
// testl with a mask that fits in the low byte is exactly testb.
if (is_uint8(mask.value_)) {
testb(op, mask);
return;
}
EnsureSpace ensure_space(this);
emit_optional_rex_32(rax, op);
emit(0xF7);
emit_operand(rax, op); // Operation code 0
emit(mask);
}
void Assembler::testq(const Operand& op, Register reg) {
EnsureSpace ensure_space(this);
emit_rex_64(reg, op);
emit(0x85);
emit_operand(reg, op);
}
void Assembler::testq(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
emit_rex_64(src, dst);
emit(0x85);
emit_modrm(src, dst);
} else {
emit_rex_64(dst, src);
emit(0x85);
emit_modrm(dst, src);
}
}
void Assembler::testq(Register dst, Immediate mask) {
EnsureSpace ensure_space(this);
if (dst.is(rax)) {
emit_rex_64();
emit(0xA9);
emit(mask);
} else {
emit_rex_64(dst);
emit(0xF7);
emit_modrm(0, dst);
emit(mask);
}
}
// FPU instructions.
void Assembler::fld(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD9, 0xC0, i);
}
void Assembler::fld1() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xE8);
}
void Assembler::fldz() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xEE);
}
void Assembler::fldpi() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xEB);
}
void Assembler::fldln2() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xED);
}
void Assembler::fld_s(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xD9);
emit_operand(0, adr);
}
void Assembler::fld_d(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDD);
emit_operand(0, adr);
}
void Assembler::fstp_s(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xD9);
emit_operand(3, adr);
}
void Assembler::fstp_d(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDD);
emit_operand(3, adr);
}
void Assembler::fstp(int index) {
ASSERT(is_uint3(index));
EnsureSpace ensure_space(this);
emit_farith(0xDD, 0xD8, index);
}
void Assembler::fild_s(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDB);
emit_operand(0, adr);
}
void Assembler::fild_d(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDF);
emit_operand(5, adr);
}
void Assembler::fistp_s(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDB);
emit_operand(3, adr);
}
void Assembler::fisttp_s(const Operand& adr) {
ASSERT(CpuFeatures::IsEnabled(SSE3));
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDB);
emit_operand(1, adr);
}
void Assembler::fisttp_d(const Operand& adr) {
ASSERT(CpuFeatures::IsEnabled(SSE3));
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDD);
emit_operand(1, adr);
}
void Assembler::fist_s(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDB);
emit_operand(2, adr);
}
void Assembler::fistp_d(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDF);
emit_operand(7, adr);
}
void Assembler::fabs() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xE1);
}
void Assembler::fchs() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xE0);
}
void Assembler::fcos() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xFF);
}
void Assembler::fsin() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xFE);
}
void Assembler::fptan() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xF2);
}
void Assembler::fyl2x() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xF1);
}
void Assembler::fadd(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xC0, i);
}
void Assembler::fsub(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xE8, i);
}
void Assembler::fisub_s(const Operand& adr) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(adr);
emit(0xDA);
emit_operand(4, adr);
}
void Assembler::fmul(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xC8, i);
}
void Assembler::fdiv(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xF8, i);
}
void Assembler::faddp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xC0, i);
}
void Assembler::fsubp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xE8, i);
}
void Assembler::fsubrp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xE0, i);
}
void Assembler::fmulp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xC8, i);
}
void Assembler::fdivp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xF8, i);
}
void Assembler::fprem() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xF8);
}
void Assembler::fprem1() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xF5);
}
void Assembler::fxch(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD9, 0xC8, i);
}
void Assembler::fincstp() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xF7);
}
void Assembler::ffree(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDD, 0xC0, i);
}
void Assembler::ftst() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xE4);
}
void Assembler::fucomp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDD, 0xE8, i);
}
void Assembler::fucompp() {
EnsureSpace ensure_space(this);
emit(0xDA);
emit(0xE9);
}
void Assembler::fucomi(int i) {
EnsureSpace ensure_space(this);
emit(0xDB);
emit(0xE8 + i);
}
void Assembler::fucomip() {
EnsureSpace ensure_space(this);
emit(0xDF);
emit(0xE9);
}
void Assembler::fcompp() {
EnsureSpace ensure_space(this);
emit(0xDE);
emit(0xD9);
}
void Assembler::fnstsw_ax() {
EnsureSpace ensure_space(this);
emit(0xDF);
emit(0xE0);
}
void Assembler::fwait() {
EnsureSpace ensure_space(this);
emit(0x9B);
}
void Assembler::frndint() {
EnsureSpace ensure_space(this);
emit(0xD9);
emit(0xFC);
}
void Assembler::fnclex() {
EnsureSpace ensure_space(this);
emit(0xDB);
emit(0xE2);
}
void Assembler::sahf() {
// TODO(X64): Test for presence. Not all 64-bit intel CPU's have sahf
// in 64-bit mode. Test CpuID.
EnsureSpace ensure_space(this);
emit(0x9E);
}
void Assembler::emit_farith(int b1, int b2, int i) {
ASSERT(is_uint8(b1) && is_uint8(b2)); // wrong opcode
ASSERT(is_uint3(i)); // illegal stack offset
emit(b1);
emit(b2 + i);
}
// SSE 2 operations.
void Assembler::movd(XMMRegister dst, Register src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x6E);
emit_sse_operand(dst, src);
}
void Assembler::movd(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(src, dst);
emit(0x0F);
emit(0x7E);
emit_sse_operand(src, dst);
}
void Assembler::movq(XMMRegister dst, Register src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_rex_64(dst, src);
emit(0x0F);
emit(0x6E);
emit_sse_operand(dst, src);
}
void Assembler::movq(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_rex_64(src, dst);
emit(0x0F);
emit(0x7E);
emit_sse_operand(src, dst);
}
void Assembler::movq(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
if (dst.low_bits() == 4) {
// Avoid unnecessary SIB byte.
emit(0xf3);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x7e);
emit_sse_operand(dst, src);
} else {
emit(0x66);
emit_optional_rex_32(src, dst);
emit(0x0F);
emit(0xD6);
emit_sse_operand(src, dst);
}
}
void Assembler::movdqa(const Operand& dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_rex_64(src, dst);
emit(0x0F);
emit(0x7F);
emit_sse_operand(src, dst);
}
void Assembler::movdqa(XMMRegister dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_rex_64(dst, src);
emit(0x0F);
emit(0x6F);
emit_sse_operand(dst, src);
}
void Assembler::extractps(Register dst, XMMRegister src, byte imm8) {
ASSERT(is_uint2(imm8));
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x3A);
emit(0x17);
emit_sse_operand(dst, src);
emit(imm8);
}
void Assembler::movsd(const Operand& dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2); // double
emit_optional_rex_32(src, dst);
emit(0x0F);
emit(0x11); // store
emit_sse_operand(src, dst);
}
void Assembler::movsd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2); // double
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x10); // load
emit_sse_operand(dst, src);
}
void Assembler::movsd(XMMRegister dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0xF2); // double
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x10); // load
emit_sse_operand(dst, src);
}
void Assembler::movaps(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
// Try to avoid an unnecessary SIB byte.
emit_optional_rex_32(src, dst);
emit(0x0F);
emit(0x29);
emit_sse_operand(src, dst);
} else {
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x28);
emit_sse_operand(dst, src);
}
}
void Assembler::movapd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
if (src.low_bits() == 4) {
// Try to avoid an unnecessary SIB byte.
emit(0x66);
emit_optional_rex_32(src, dst);
emit(0x0F);
emit(0x29);
emit_sse_operand(src, dst);
} else {
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x28);
emit_sse_operand(dst, src);
}
}
void Assembler::movss(XMMRegister dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0xF3); // single
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x10); // load
emit_sse_operand(dst, src);
}
void Assembler::movss(const Operand& src, XMMRegister dst) {
EnsureSpace ensure_space(this);
emit(0xF3); // single
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x11); // store
emit_sse_operand(dst, src);
}
void Assembler::cvttss2si(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0xF3);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2C);
emit_operand(dst, src);
}
void Assembler::cvttss2si(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF3);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2C);
emit_sse_operand(dst, src);
}
void Assembler::cvttsd2si(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2C);
emit_operand(dst, src);
}
void Assembler::cvttsd2si(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2C);
emit_sse_operand(dst, src);
}
void Assembler::cvttsd2siq(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_rex_64(dst, src);
emit(0x0F);
emit(0x2C);
emit_sse_operand(dst, src);
}
void Assembler::cvtlsi2sd(XMMRegister dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2A);
emit_sse_operand(dst, src);
}
void Assembler::cvtlsi2sd(XMMRegister dst, Register src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2A);
emit_sse_operand(dst, src);
}
void Assembler::cvtlsi2ss(XMMRegister dst, Register src) {
EnsureSpace ensure_space(this);
emit(0xF3);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2A);
emit_sse_operand(dst, src);
}
void Assembler::cvtqsi2sd(XMMRegister dst, Register src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_rex_64(dst, src);
emit(0x0F);
emit(0x2A);
emit_sse_operand(dst, src);
}
void Assembler::cvtss2sd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF3);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x5A);
emit_sse_operand(dst, src);
}
void Assembler::cvtss2sd(XMMRegister dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0xF3);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x5A);
emit_sse_operand(dst, src);
}
void Assembler::cvtsd2ss(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x5A);
emit_sse_operand(dst, src);
}
void Assembler::cvtsd2si(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x2D);
emit_sse_operand(dst, src);
}
void Assembler::cvtsd2siq(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_rex_64(dst, src);
emit(0x0F);
emit(0x2D);
emit_sse_operand(dst, src);
}
void Assembler::addsd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x58);
emit_sse_operand(dst, src);
}
void Assembler::mulsd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x59);
emit_sse_operand(dst, src);
}
void Assembler::subsd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x5C);
emit_sse_operand(dst, src);
}
void Assembler::divsd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x5E);
emit_sse_operand(dst, src);
}
void Assembler::andpd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x54);
emit_sse_operand(dst, src);
}
void Assembler::orpd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x56);
emit_sse_operand(dst, src);
}
void Assembler::xorpd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x57);
emit_sse_operand(dst, src);
}
void Assembler::xorps(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x57);
emit_sse_operand(dst, src);
}
void Assembler::sqrtsd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0xF2);
emit_optional_rex_32(dst, src);
emit(0x0F);
emit(0x51);
emit_sse_operand(dst, src);
}
void Assembler::ucomisd(XMMRegister dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0f);
emit(0x2e);
emit_sse_operand(dst, src);
}
void Assembler::ucomisd(XMMRegister dst, const Operand& src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0f);
emit(0x2e);
emit_sse_operand(dst, src);
}
void Assembler::roundsd(XMMRegister dst, XMMRegister src,
Assembler::RoundingMode mode) {
ASSERT(CpuFeatures::IsEnabled(SSE4_1));
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0f);
emit(0x3a);
emit(0x0b);
emit_sse_operand(dst, src);
// Mask precision exeption.
emit(static_cast<byte>(mode) | 0x8);
}
void Assembler::movmskpd(Register dst, XMMRegister src) {
EnsureSpace ensure_space(this);
emit(0x66);
emit_optional_rex_32(dst, src);
emit(0x0f);
emit(0x50);
emit_sse_operand(dst, src);
}
void Assembler::emit_sse_operand(XMMRegister reg, const Operand& adr) {
Register ireg = { reg.code() };
emit_operand(ireg, adr);
}
void Assembler::emit_sse_operand(XMMRegister dst, XMMRegister src) {
emit(0xC0 | (dst.low_bits() << 3) | src.low_bits());
}
void Assembler::emit_sse_operand(XMMRegister dst, Register src) {
emit(0xC0 | (dst.low_bits() << 3) | src.low_bits());
}
void Assembler::emit_sse_operand(Register dst, XMMRegister src) {
emit(0xC0 | (dst.low_bits() << 3) | src.low_bits());
}
void Assembler::db(uint8_t data) {
EnsureSpace ensure_space(this);
emit(data);
}
void Assembler::dd(uint32_t data) {
EnsureSpace ensure_space(this);
emitl(data);
}
// Relocation information implementations.
void Assembler::RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data) {
ASSERT(rmode != RelocInfo::NONE);
// Don't record external references unless the heap will be serialized.
if (rmode == RelocInfo::EXTERNAL_REFERENCE) {
#ifdef DEBUG
if (!Serializer::enabled()) {
Serializer::TooLateToEnableNow();
}
#endif
if (!Serializer::enabled() && !emit_debug_code()) {
return;
}
}
RelocInfo rinfo(pc_, rmode, data, NULL);
reloc_info_writer.Write(&rinfo);
}
void Assembler::RecordJSReturn() {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
RecordRelocInfo(RelocInfo::JS_RETURN);
}
void Assembler::RecordDebugBreakSlot() {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
RecordRelocInfo(RelocInfo::DEBUG_BREAK_SLOT);
}
void Assembler::RecordComment(const char* msg, bool force) {
if (FLAG_code_comments || force) {
EnsureSpace ensure_space(this);
RecordRelocInfo(RelocInfo::COMMENT, reinterpret_cast<intptr_t>(msg));
}
}
const int RelocInfo::kApplyMask = RelocInfo::kCodeTargetMask |
1 << RelocInfo::INTERNAL_REFERENCE;
bool RelocInfo::IsCodedSpecially() {
// The deserializer needs to know whether a pointer is specially coded. Being
// specially coded on x64 means that it is a relative 32 bit address, as used
// by branch instructions.
return (1 << rmode_) & kApplyMask;
}
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_X64
| [
"[email protected]"
] | [
[
[
1,
3034
]
]
] |
96167e53a115dd93f9e81639545c2d9bba514a16 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/Hunter/NewGameVedioUI/VedioUIComponent/include/VedioUIComponent.h | b654af5166f1793872830eab64fc74ba5d85e129 | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | h | #ifndef __Orz_VedioUIComponent__
#define __Orz_VedioUIComponent__
namespace Ogre
{
class SceneNode;
}
namespace CEGUI
{
class Window;
}
namespace Orz
{
class VedioUIInterface;
class VedioUIComponent: public Component
{
public :
VedioUIComponent(void);
virtual ~VedioUIComponent(void);
private:
virtual ComponentInterface * _queryInterface(const TypeInfo & info);
boost::scoped_ptr<VedioUIInterface> _vedioInterface;
bool load(const std::string & filename);
bool isEnd(void);
bool play(void);
void reset(void);
void createTexture(const std::string & filename);
CEGUI::Window * getWindow(void);
private:
CEGUI::Window * _window;
std::string _filename;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
3d41883159681beb47c7ed6255f12f0d920061e5 | 51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c | /FileAssistant++/Source/COptionsMenu.h | 3b3b6087bc1abdd043e07cb498d9c674b3cb2501 | [] | no_license | jdek/jim-pspware | c3e043b59a69cf5c28daf62dc9d8dca5daf87589 | fd779e1148caac2da4c590844db7235357b47f7e | refs/heads/master | 2021-05-31T06:45:03.953631 | 2007-06-25T22:45:26 | 2007-06-25T22:45:26 | 56,973,047 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,459 | h | /***********************************************************************************
Module : COptionsMenu.h
Description :
Last Modified $Date: $
$Revision: $
Copyright (C) 13 August 2005 71M
***********************************************************************************/
#ifndef COPTIONSMENU_H_
#define COPTIONSMENU_H_
//**********************************************************************************
// Include Files
//**********************************************************************************
#include "CWindow.h"
#include "CFileHandler.h"
//**********************************************************************************
// Macros
//**********************************************************************************
//**********************************************************************************
// Types
//**********************************************************************************
class CWindowTable;
class CWindowTableItem;
//**********************************************************************************
// Constants
//**********************************************************************************
//**********************************************************************************
// Class definitions
//**********************************************************************************
class COptionsMenu : public CWindow
{
public:
enum eOption
{
OPTION_MAKE_DIRECTORY,
OPTION_USB_CONNECTION,
OPTION_SKIN_SELECTION,
OPTION_HIDE_CORRUPT_FILES,
OPTION_STOP_MUSIC,
MAX_OPTIONS
};
public:
COptionsMenu();
~COptionsMenu();
virtual void Process();
virtual void ProcessInput();
virtual void SetFocus( bool focus );
protected:
void AddOptions();
static void OptionSelectedCallback( CWindowTableItem * p_item, u32 item_no );
protected:
CWindowTable * m_pOptions;
static const CString s_szOptionNames[ MAX_OPTIONS ];
};
//**********************************************************************************
// Externs
//**********************************************************************************
//**********************************************************************************
// Prototypes
//**********************************************************************************
#endif /* COPTIONSMENU_H_ */
| [
"71m@ff2c0c17-07fa-0310-a4bd-d48831021cb5"
] | [
[
[
1,
86
]
]
] |
ca6a6c2144059ae3da8e5c3572323f024f56d290 | 22575f4bfceb68b4ca9b5c1146dd86ca4bd5c4ed | /include/zamara/mpq/mpq_file.h | 48e880afd2ba78299b3911e290d40caa06f62712 | [
"BSD-2-Clause"
] | permissive | aphistic/zamara | b4ef491949c02b65b164a2bff3ea9d2f349457c6 | c2a587bd8281540b4083ec5bcc47d992f1e75bf7 | refs/heads/master | 2016-09-05T11:28:11.983667 | 2011-12-09T03:37:13 | 2011-12-09T03:37:13 | 2,944,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,348 | h | /* Zamara Library
* Copyright (c) 2011, Erik Davidson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ZAMARA_MPQ_MPQ_FILE_H_
#define ZAMARA_MPQ_MPQ_FILE_H_
#include <fstream>
#include <string>
#include "zamara/mpq/mpq_hash_entry.h"
#include "zamara/mpq/mpq_block_entry.h"
namespace zamara {
namespace mpq {
class MpqFile {
public:
~MpqFile();
void Load(std::string filename, MpqHashEntry* hash_entry,
MpqBlockEntry* block_entry);
void OpenFile();
bool IsOpen();
char* FileData();
void CloseFile();
std::string filename();
uint32_t file_size();
MpqHashEntry* hash_entry();
MpqBlockEntry* block_entry();
private:
friend class Mpq;
MpqFile(std::ifstream* archive, uint32_t archive_offset);
std::ifstream* archive_;
uint32_t archive_offset_;
std::string filename_;
MpqHashEntry* hash_entry_;
MpqBlockEntry* block_entry_;
bool is_open_;
char* file_data_;
};
}
}
#endif // ZAMARA_MPQ_MPQ_FILE_H_
| [
"[email protected]"
] | [
[
[
1,
78
]
]
] |
a3b2ac6616993b2d9feecff648d7305a470e62e4 | 927e18c69355c4bf87b59dffefe59c2974e86354 | /super-go-proj/SgArray.h | e777dd2bef94ad091531821d4d3e466595c31349 | [] | no_license | lqhl/iao-gim-ca | 6fc40adc91a615fa13b72e5b4016a8b154196b8f | f177268804d1ba6edfd407fa44a113a44203ec30 | refs/heads/master | 2020-05-18T17:07:17.972573 | 2011-06-17T03:54:51 | 2011-06-17T03:54:51 | 32,191,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,864 | h | //----------------------------------------------------------------------------
/** @file SgArray.h
Static array. */
//----------------------------------------------------------------------------
#ifndef SG_ARRAY_H
#define SG_ARRAY_H
#include <cstring>
#include <Poco/Debugger.h>
//----------------------------------------------------------------------------
template<typename T, int SIZE> class SgArray;
/** Helper class to allow partial specialization of SgArray::operator=.
Partial member function specialization is not yet supported by standard
C++. */
template<typename T, int SIZE>
class SgArrayAssign
{
public:
static void Assign(T* dest, const T* src);
};
template<int SIZE>
class SgArrayAssign<int,SIZE>
{
public:
static void Assign(int* dest, const int* src);
};
template<int SIZE>
class SgArrayAssign<bool,SIZE>
{
public:
static void Assign(bool* dest, const bool* src);
};
template<typename T,int SIZE>
class SgArrayAssign<T*,SIZE>
{
public:
static void Assign(T** dest, T* const * src);
};
template<typename T, int SIZE>
void SgArrayAssign<T,SIZE>::Assign(T* dest, const T* src)
{
poco_assert(dest != src); // self-assignment not supported for efficiency
T* p = dest;
const T* pp = src;
for (int i = SIZE; i--; ++p, ++pp)
*p = *pp;
}
template<int SIZE>
void SgArrayAssign<int,SIZE>::Assign(int* dest, const int* src)
{
poco_assert(dest != src); // self-assignment not supported for efficiency
std::memcpy(dest, src, SIZE * sizeof(int));
}
template<int SIZE>
void SgArrayAssign<bool,SIZE>::Assign(bool* dest, const bool* src)
{
poco_assert(dest != src); // self-assignment not supported for efficiency
std::memcpy(dest, src, SIZE * sizeof(bool));
}
template<typename T, int SIZE>
void SgArrayAssign<T*,SIZE>::Assign(T** dest, T* const * src)
{
poco_assert(dest != src); // self-assignment not supported for efficiency
std::memcpy(dest, src, SIZE * sizeof(T*));
}
//----------------------------------------------------------------------------
/** Static array.
Wrapper class around a C style array.
Uses assertions for indices in range in debug mode.
@deprecated Use boost::array instead */
template<typename T, int SIZE>
class SgArray
{
public:
/** Local const iterator */
class Iterator
{
public:
Iterator(const SgArray& array);
const T& operator*() const;
void operator++();
operator bool() const;
private:
const T* m_end;
const T* m_current;
};
/** Local non-const iterator */
class NonConstIterator
{
public:
NonConstIterator(SgArray& array);
T& operator*() const;
void operator++();
operator bool() const;
private:
const T* m_end;
T* m_current;
};
SgArray();
SgArray(const SgArray& array);
explicit SgArray(const T& val);
SgArray& operator=(const SgArray& array);
T& operator[](int index);
const T& operator[](int index) const;
SgArray& operator*=(T val);
void Fill(const T& val);
private:
friend class Iterator;
friend class NonConstIterator;
T m_array[SIZE];
};
template<typename T, int SIZE>
SgArray<T,SIZE>::Iterator::Iterator(const SgArray& array)
: m_end(array.m_array + SIZE),
m_current(array.m_array)
{
}
template<typename T, int SIZE>
const T& SgArray<T,SIZE>::Iterator::operator*() const
{
poco_assert(*this);
return *m_current;
}
template<typename T, int SIZE>
void SgArray<T,SIZE>::Iterator::operator++()
{
++m_current;
}
template<typename T, int SIZE>
SgArray<T,SIZE>::Iterator::operator bool() const
{
return m_current < m_end;
}
template<typename T, int SIZE>
SgArray<T,SIZE>::NonConstIterator::NonConstIterator(SgArray& array)
: m_end(array.m_array + SIZE),
m_current(array.m_array)
{ }
template<typename T, int SIZE>
T& SgArray<T,SIZE>::NonConstIterator::operator*() const
{
poco_assert(*this);
return *m_current;
}
template<typename T, int SIZE>
void SgArray<T,SIZE>::NonConstIterator::operator++()
{
++m_current;
}
template<typename T, int SIZE>
SgArray<T,SIZE>::NonConstIterator::operator bool() const
{
return m_current < m_end;
}
template<typename T, int SIZE>
SgArray<T,SIZE>::SgArray()
{
}
template<typename T, int SIZE>
SgArray<T,SIZE>::SgArray(const SgArray& array)
{
poco_assert(&array != this); // self-assignment not supported for efficiency
*this = array;
}
template<typename T, int SIZE>
SgArray<T,SIZE>::SgArray(const T& val)
{
Fill(val);
}
template<typename T, int SIZE>
SgArray<T,SIZE>& SgArray<T,SIZE>::operator=(const SgArray& array)
{
poco_assert(&array != this); // self-assignment not supported for efficiency
SgArrayAssign<T,SIZE>::Assign(m_array, array.m_array);
return *this;
}
template<typename T, int SIZE>
T& SgArray<T,SIZE>::operator[](int index)
{
poco_assert(index >= 0);
poco_assert(index < SIZE);
return m_array[index];
}
template<typename T, int SIZE>
const T& SgArray<T,SIZE>::operator[](int index) const
{
poco_assert(index >= 0);
poco_assert(index < SIZE);
return m_array[index];
}
template<typename T, int SIZE>
SgArray<T,SIZE>& SgArray<T,SIZE>::operator*=(T val)
{
T* p = m_array;
for (int i = SIZE; i--; ++p)
*p *= val;
return *this;
}
template<typename T, int SIZE>
void SgArray<T,SIZE>::Fill(const T& val)
{
T* v = m_array;
for (int i = SIZE; i--; ++v)
*v = val;
}
//----------------------------------------------------------------------------
#endif // SG_ARRAY_H
| [
"[email protected]"
] | [
[
[
1,
259
]
]
] |
713b1fe073b091ae73acb4bdc10c9aafdf62ebaf | 37c757f24b674f67edd87b75b996d8d5015455cb | /UI/WTL_lib/WTLApp.h | e1ed4c31c4ad6274c22a1db7a668926c3259d10d | [] | no_license | SakuraSinojun/cotalking | 1118602313f85d1c49d73e1603cf6642bc15f36d | 37354d99db6b7033019fd0aaccec84e68aee2adf | refs/heads/master | 2021-01-10T21:20:50.269547 | 2011-04-07T06:15:04 | 2011-04-07T06:15:04 | 32,323,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,070 | h | #ifndef _WTLAPP_H_
#define _WTLAPP_H_
#pragma once
#include <Windows.h>
#include <ATLHelper.h>
#include <GdiPlus.h>
#pragma comment(lib,"gdiplus.lib")
#if (_MSC_VER>=1600) //VC2010 or higher
#include <type_traits>
#endif
//Single instance application support
#pragma data_seg("Shared")
__declspec(selectany) volatile HWND _g_hMainWindow = NULL;
#pragma data_seg()
#pragma comment(linker,"/Section:Shared,RWS")
namespace WTL
{
//Get the global AppModule pointer
__declspec(selectany) CAppModule* _g_pAppModule = NULL;
inline CAppModule& AtlGetAppModule()
{
return *_g_pAppModule;
}
//////////////////////////////////////////////////////////////////////////
//
//CWTLAppTraits class
//
enum WTLAppInitOption
{
WTLAPP_INIT_NONE = 0x00,
WTLAPP_INIT_GDIPLUS = 0x01,
WTLAPP_INIT_COM = 0x02
};
template<DWORD t_InitOption>
class CWTLAppTraits
{
public:
static DWORD GetInitOption()
{
return t_InitOption;
}
};
typedef CWTLAppTraits<WTLAPP_INIT_NONE> CWTLAppTraitsInitNone;
typedef CWTLAppTraits<WTLAPP_INIT_GDIPLUS> CWTLAppTraitsInitGdiplus;
typedef CWTLAppTraits<WTLAPP_INIT_COM> CWTLAppTraitsInitCom;
typedef CWTLAppTraits<WTLAPP_INIT_GDIPLUS | WTLAPP_INIT_COM> CWTLAppTraitsInitGdiplusCom;
//////////////////////////////////////////////////////////////////////////
//
//CWTLApplicationImpl class
//
template<typename T, typename TMainWindow, typename TWTLAppTraits = CWTLAppTraitsInitNone>
class ATL_NO_VTABLE CWTLApplicationImpl :
public CAppModule
{
private:
ULONG_PTR m_GdiplusToken;
public:
//Call this method in the application's entry point[_tWinMain(...)]
int WinMain(HINSTANCE hInstance,LPTSTR lpCmdLine,int nShowCmd)
{
#if (_MSC_VER>=1600) //VC2010 or higher
//Ensure that TMainWindow is derived from CWindow
static_assert(std::is_base_of<CWindow,TMainWindow>::value,
"TMainWindow class needs to be CWindow based.");
#endif
UNREFERENCED_PARAMETER(lpCmdLine);
_g_pAppModule = this;
T* pT = static_cast<T*>(this);
//Do additional work on starting up, if any
if(!(pT->OnStartup()))
return 0;
//Initialize COM
BOOL initCom = TWTLAppTraits::GetInitOption() & WTLAPP_INIT_COM;
HRESULT hr = S_OK;
if (initCom)
{
// 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.
// hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
hr = ::CoInitialize(NULL);
CHECKHR(hr);
if (FAILED(hr))
return 0;
}
//Initialize GDI+
BOOL initGdiplus = TWTLAppTraits::GetInitOption() & WTLAPP_INIT_GDIPLUS;
if (initGdiplus)
{
Gdiplus::GdiplusStartupInput input;
Gdiplus::GdiplusStartupOutput output;
Gdiplus::GdiplusStartup(&m_GdiplusToken,&input,&output);
}
// This resolves ATL window thunking problem when Microsoft Layer
// for Unicode (MSLU) is used
::DefWindowProc(NULL, 0, 0, 0L);
pT->OnInitCommonControl();
//CAppModule::Init()
hr = Init(NULL, hInstance);
CHECKHR(hr);
int nRet = 0;
{
CMessageLoop msgLoop;
//CAppModule::AddMessageLoop()
AddMessageLoop(&msgLoop);
TMainWindow wndMain;
_g_hMainWindow = wndMain.Create(NULL,CWindow::rcDefault);
if(_g_hMainWindow == NULL)
{
ATLTRACE(_T("Failed to create Main window!\n"));
return 0;
}
wndMain.ShowWindow(nShowCmd);
wndMain.UpdateWindow();
nRet = msgLoop.Run();
//CAppModule::RemoveMessageLoop()
RemoveMessageLoop();
_g_hMainWindow = NULL;
}
//CAppModule::Term()
Term();
//Uninitialize GDI+
if (initGdiplus)
Gdiplus::GdiplusShutdown(m_GdiplusToken);
//Uninitialize COM
if (initCom)
::CoUninitialize();
//Do additional work on shutting down, if any
pT->OnShutdown();
_g_pAppModule = NULL;
return nRet;
}
protected:
//Override this method to do additional work on starting up
BOOL OnStartup()
{
return TRUE;
}
//Override this method to do additional work on shutting down
void OnShutdown()
{}
//Override this method to support other native controls
void OnInitCommonControl()
{
AtlInitCommonControls(ICC_STANDARD_CLASSES|ICC_COOL_CLASSES|ICC_BAR_CLASSES|ICC_WIN95_CLASSES);
}
protected:
//Single instance application support
BOOL IsAnotherInstanceRunning()
{
return (_g_hMainWindow!=NULL);
}
void TakeAnotherInstanceForeground()
{
if (_g_hMainWindow)
{
CWindow mainWnd(_g_hMainWindow);
if (mainWnd.IsIconic())
mainWnd.ShowWindow(SW_RESTORE);
mainWnd.SetForegroundWindow();
}
}
}; // class CWTLApplicationImpl
//////////////////////////////////////////////////////////////////////////
//
//CWTLApplicationT class
//
template<typename TMainWindow, typename TWTLAppTraits = CWTLAppTraitsInitNone>
class CWTLApplicationT :
public CWTLApplicationImpl<CWTLApplicationT<TMainWindow, TWTLAppTraits>, TMainWindow, TWTLAppTraits>
{};
} // namespace WTL
#endif | [
"SakuraSinojun@02eed91f-dd82-7cf9-bfd0-73567c4360d3"
] | [
[
[
1,
209
]
]
] |
52394cfd4d3231327a4ec06044f34e9b5be9ec46 | 16052d8fae72cecb6249372b80fe633251685e1d | /visualization/shape_vis.h | 8bb179b8c55bf9058cfdf51518e87b366ff6830a | [] | no_license | istrandjev/hierarhical-clustering | 7a9876c5c6124488162f4089d7888452a53595a6 | adad22cce42d68b04cca747352d94df039e614a2 | refs/heads/master | 2021-01-19T14:59:08.593414 | 2011-06-29T06:07:41 | 2011-06-29T06:07:41 | 32,250,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 555 | h | #ifndef SHAPE_VIS_H
#define SHAPE_VIS_H
class ShapeType {
public:
ShapeType(unsigned code);
void ChangeCurrentColor() const;
int GetType() const;
private:
int r, g, b;
int type;
private:
static void Initialize();
private:
static const unsigned size = 8*8*8*8;
static unsigned remap[size];
static bool initialized;
};
class Shape {
public:
Shape(double _x, double _y, double _z, double _r, int type_code);
void Display() const;
private:
double x,y,z;
double r;
ShapeType type;
};
#endif // SHAPE_VIS_H
| [
"[email protected]@c0cadd32-5dbd-3e50-b098-144b922aa411"
] | [
[
[
1,
33
]
]
] |
f27c9d6c706f80973271355a074970d0be6cf956 | 2d22825193eacf3669ac8bd7a857791745a9ead4 | /HairSimulation/HairSimulation/include/AppManHead.h | 5d039ff6dc84053094e29b731c80aca9b2b1de53 | [] | no_license | dtbinh/com-animation-classprojects | 557ba550b575c3d4efc248f7984a3faac8f052fd | 37dc800a6f2bac13f5aa4fc7e0e96aa8e9cec29e | refs/heads/master | 2021-01-06T20:45:42.613604 | 2009-01-20T00:23:11 | 2009-01-20T00:23:11 | 41,496,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | h | #ifndef _APP_MANHEAD_H_
#define _APP_MANHEAD_H_
#include "AppPrerequisites.h"
#include "ApplicationObject.h"
class ManHead : public ApplicationObject
{
protected:
void setUp(const String& name);
public:
ManHead(const String& name);
~ManHead();
};
#endif | [
"grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4"
] | [
[
[
1,
16
]
]
] |
4c16503b271b4b6a96c1dd292fd1bfbc109a6fa3 | 565d432f8223100873944cfa22b9d9b2f14575f1 | /WGClient/StdAfx.cpp | 84d382e0b1d3d73b407617645819c07eb3b7a262 | [] | no_license | glencui2015/tlautologin | ce029c688e0414497e91115a2ee19e7abcac56d2 | 6e825807e2523bf4e020d91f92d86ce194747d0d | refs/heads/master | 2021-01-10T10:50:34.139524 | 2010-12-17T17:43:33 | 2010-12-17T17:43:33 | 50,753,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | // stdafx.cpp : source file that includes just the standard includes
// WGClient.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"woaini4t@84d92313-99f8-b76f-20ef-0d116c1dc3bd"
] | [
[
[
1,
8
]
]
] |
d5ac7a75d68e63c275330de6e4b166b69560ae5f | 82e5361cc4ac3f14f1a1b0bb5076777f19856e3a | /win32/token.cpp | ca357c066e99570cf04280479669060f336d064d | [] | no_license | rakusai/buco | 7d8a1c96630594b3453183aaba86dc81b4ec9b87 | 23190751611ccb018abe59d8d3fac1af027a475d | refs/heads/master | 2020-04-25T20:36:19.940758 | 2008-02-07T15:33:05 | 2008-02-07T15:33:05 | 2,123,100 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,848 | cpp | #include "stdafx.h"
#include "inc.h"
#include "token.h"
#define TOKEN_ALLOC_SIZE (128)
//#ifdef SJIS
#define issjiskanji(c) ((0x81 <= (unsigned char)(c&0xff) && (unsigned char)(c&0xff) <= 0x9f) \
|| (0xe0 <= (unsigned char)(c&0xff) && (unsigned char)(c&0xff) <= 0xfc))
//#else
//#define issjiskanji(c) 0
//#endif
/* プロトタイプ */
static int AddToken(TOKEN *token,char *buf,int len);
/* トークンの切り出し */
int GetToken(char *buf,int len,TOKEN *token,char *token_separate)
{
int token_start,token_len;
int i;
token->token=NULL;
token->size=0;
token->no=0;
token_start=0;
for(i=0;i<len;i++){
/* SJIS漢字1バイト目 */
if(issjiskanji(buf[i])){
i++;
}
else if(strchr(token_separate,buf[i])!=NULL){ /* 分離文字 */
token_len=i-token_start;
if(token_len>0){
AddToken(token,&buf[token_start],token_len);
}
token_start=i+1;
}
}
token_len=i-token_start;
if(token_len>0){
AddToken(token,&buf[token_start],token_len);
}
return(0);
}
/* トークンデータ追加 */
static int AddToken(TOKEN *token,char *buf,int len)
{
int pack_flag;
pack_flag=0;
if(buf[0]=='"'&&buf[len-1]=='"'){
pack_flag=1;
}
else if(buf[0]=='\''&&buf[len-1]=='\''){
pack_flag=1;
}
if(token->size==0){
token->size=TOKEN_ALLOC_SIZE;
token->token=(char **)malloc(token->size*sizeof(char *));
token->token[token->no]=(char*)malloc(len+1);
if(pack_flag==0){
memcpy(token->token[token->no],buf,len);
token->token[token->no][len]='\0';
}
else{
memcpy(token->token[token->no],buf+1,len-2);
token->token[token->no][len-2]='\0';
}
token->no++;
}
else{
if(token->no+1>=token->size){
token->size=TOKEN_ALLOC_SIZE;
token->token=(char **)realloc((char *)token->token,token->size*sizeof(char *));
}
token->token[token->no]=(char*)malloc(len+1);
if(pack_flag==0){
memcpy(token->token[token->no],buf,len);
token->token[token->no][len]='\0';
}
else{
memcpy(token->token[token->no],buf+1,len-2);
token->token[token->no][len-2]='\0';
}
token->no++;
}
return(0);
}
/* トークンデータ解放 */
int FreeToken(TOKEN *token)
{
int i;
for(i=0;i<token->no;i++){
free(token->token[i]);
}
if(token->size>0){
free(token->token);
}
token->token=NULL;
token->size=0;
token->no=0;
return(0);
}
/* トークンデータデバッグ用 */
int DebugToken(FILE *fp,TOKEN *token)
{
int i;
char buf[512];
for(i=0;i<token->no;i++){
sprintf(buf,"[%s]",token->token[i]);
fprintf(fp,"%s",buf);
}
fprintf(fp,"\r\n");
return(0);
}
/* 名前:値 形式の切り出し */
int GetNameVal(char *buf,int len,char *name,char *val,char *sep)
{
int name_flag,i,next;
strcpy(name,"");
strcpy(val,"");
name_flag=0;
for(i=0;i<len;i++){
if(issjiskanji(buf[i])){
i++;
continue;
}
else if(strchr(sep,buf[i])!=NULL){
name_flag=1;
strncpy(name,buf,i);
name[i]='\0';
next=i+1;
break;
}
}
if(name_flag==0){
return(0);
}
for(i=next;i<len;i++){
if(!(isascii(buf[i])&&isspace(buf[i]))){
next=i;
break;
}
}
strcpy(val,&buf[next]);
return(1);
}
/* 文字列を小文字に */
int CharSmall(char *buf)
{
char *ptr;
for(ptr=buf;*ptr!='\0';ptr++){
*ptr=tolower(*ptr);
}
return(0);
}
/* 文字列CRLF削除 */
int CutCrLf(char *str)
{
char *ptr;
if((ptr=strchr(str,'\r'))!=NULL){
*ptr='\0';
}
else if((ptr=strchr(str,'\n'))!=NULL){
*ptr='\0';
}
return(0);
}
/* 大文字小文字無視文字列 */
int StrCmp(char *a,char *b)
{
char *aa,*bb;
int ret;
aa=strdup(a);
CharSmall(aa);
bb=strdup(b);
CharSmall(bb);
ret=strcmp(aa,bb);
free(aa);
free(bb);
return(ret);
}
| [
"rakusai@28e12d17-5845-0410-a0b5-dc453db87596"
] | [
[
[
1,
214
]
]
] |
a77c5859d5f59bca95890cf0be9d1ab168f00830 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/InfoView.cpp | 28bc69e46895e15cc80f455e2bd885ded03ca58a | [] | no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,314 | cpp | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of the author.
*/
#include "stdafx.h"
#include "HydraIRC.h"
// CInfoView
BOOL CInfoView::PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
LRESULT CInfoView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
SetAutoURLDetect(TRUE);
SetEventMask(ENM_MOUSEEVENTS | ENM_KEYEVENTS | ENM_SELCHANGE | ENM_LINK | ENM_SCROLL | ENM_SCROLLEVENTS);
UpdateSettings();
return 0;
}
void CInfoView::Put(CString Message)
{
SetSel(0,-1);
ReplaceSel(Message);
SetSel(-1,-1);
SendMessage(WM_VSCROLL, SB_TOP, NULL);
}
LRESULT CInfoView::OnMsgFilter(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
bHandled = FALSE;
MSGFILTER *MsgFilter = (MSGFILTER *)pnmh;
switch (MsgFilter->msg)
{
case WM_LBUTTONUP:
{
if (pnmh->hwndFrom == m_hWnd)
{
CHARRANGE cr;
GetSel(cr);
if (cr.cpMin != cr.cpMax)
{
SendMessage(WM_COPY,0,0);
}
SetSel(cr.cpMax,cr.cpMax);
Put("Copied selection to clipboard\n");
}
}
break;
#ifdef DEBUG
default:
{
CString Message;
Message.Format("child message: %d - %d\n",idCtrl,pnmh->code);
OutputDebugString(Message);
Message.Format("msg: %d - %x\n",MsgFilter->msg, MsgFilter->msg);
OutputDebugString(Message);
}
#endif
}
return 0;// TODO: Check
}
// Call this function after you create the window or after an prefs update
void CInfoView::UpdateSettings( void )
{
SetFont(GetAppFont(PREF_fInfoFont)); // TODO: new font pref needed
SetBackgroundColor(m_BackColor);
SetSel(0,-1);
CHARFORMAT2 fmt;
GetDefaultCharFormat(fmt);
fmt.dwEffects = 0;
fmt.dwMask = CFM_COLOR | CFM_BACKCOLOR;
fmt.crTextColor = m_TextColor;
fmt.crBackColor = m_BackColor;
fmt.cbSize = sizeof(CHARFORMAT2);
SetSelectionCharFormat(fmt);
}
// call UpdateSettings() to have the changes take effect.
void CInfoView::SetColors( COLORREF *pColors )
{
// extract just the colors we need from the array of colors.
m_TextColor = pColors[item_infotext - PREF_COLOR_FIRST];
m_BackColor = pColors[item_infobackground - PREF_COLOR_FIRST];
}
| [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
] | [
[
[
1,
119
]
]
] |
b12ccee37f2e55240cf8c0915a6135a38591b06b | 3977ae61b891f7e8ae7d75b8e22bcb63dedc3c1c | /Base/Gui/Source/Menu/Item.h | 4f83891a33818651cf5e3f4993d0d31798f01535 | [] | no_license | jayrulez/ourprs | 9734915b69207e7c3382412ca8647b051a787bb1 | 9d10f7a6edb06483015ed11dcfc9785f63b7204b | refs/heads/master | 2020-05-17T11:40:55.001049 | 2010-03-25T05:20:04 | 2010-03-25T05:20:04 | 40,554,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | 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>
</ul>
@
*/
#ifndef ITEM_H
#define ITEM_H
#ifdef _WIN32
#include "../../Win32/Core/Console.h"
#endif
#include <string>
using namespace std;
class Item
{
private:
/*name for the menu Item*/
string name;
/*x coordinate for the menu Item*/
int x;
/*y coordinate for the menu Item*/
int y;
/*code for the menu Item being used*/
int code;
Console ConsoleObj;
public:
Item();
Item(string,int,int ,int);
~Item();
bool SetItem(int,int,int,string);
int GetItemCode();
int GetItemX();
int GetItemY();
string GetItemName();
/*gets the lenght of each Item so as
to set the Frame around it*/
int GetItemLenght();
/*gives the Item life, that is, displays it on the Screen*/
void born();
bool operator==(Item);
};
#endif
| [
"portmore.representa@c48e7a12-1f02-11df-8982-67e453f37615"
] | [
[
[
1,
49
]
]
] |
9ca59c5c2287056bcd792a9c17a1953c2f4ca4f1 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/apps/mermaid/jpaintgame.cpp | e00a800b87479e857724acf04701a66afc2b8abc | [] | no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 1,737 | cpp | /***********************************************************************************/
/* File: JPaintGame.cpp
/* Date: 27.05.2006
/* Author: Ruslan Shestopalyuk
/***********************************************************************************/
#include "stdafx.h"
#include "JButton.h"
#include "JDialog.h"
#include "JLocation.h"
#include "JPaintArea.h"
#include "JPaintGame.h"
/***********************************************************************************/
/* JPaintGame implementation
/***********************************************************************************/
decl_class(JPaintGame);
JPaintGame::JPaintGame()
{
m_NPainted = 0;
m_NAreas = 0;
m_CurColor = 0;
} // JPaintGame::JPaintGame
void JPaintGame::Init()
{
m_NAreas = 0;
JObjectIterator it( this );
while (it)
{
if (dynamic_cast<JPaintArea*>( *it ))
{
m_NAreas++;
}
++it;
}
} // JPaintGame:Init
void JPaintGame::Reset()
{
JObjectIterator it( this );
while (it)
{
JPaintArea* pArea = dynamic_cast<JPaintArea*>( *it );
if (pArea)
{
pArea->SetBgColor( 0 );
}
++it;
}
} // JPaintGame::Reset
void JPaintGame::Render()
{
m_NPainted = 0;
JObjectIterator it( this );
while (it)
{
JPaintArea* pArea = dynamic_cast<JPaintArea*>( *it );
if (pArea)
{
if (pArea->GetColor() != 0)
{
m_NPainted++;
}
}
++it;
}
if (m_NPainted == m_NAreas)
{
OnSuccess();
SendSignal( "OnSuccess" );
}
} // JPaintGame::Render | [
"[email protected]"
] | [
[
[
1,
74
]
]
] |
b89b4e128898b97f0e16859a79be9efca1a2b454 | 85a9c10b0847d7e09c42b7c124722bd1d1b4ee1b | /Project1.cpp | a380cae4cd3e594cccf5ae5bb404a14f181b3404 | [] | no_license | abcolor/mean-shift-tracker | 7b1638fee9f33aa2b961859722c5618573ca2868 | 0ed134114733d61be28c65a3b19a55b37ef6aa7f | refs/heads/master | 2021-01-20T11:51:32.864853 | 2011-09-20T17:36:06 | 2011-09-20T17:36:06 | 2,423,960 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
USERES("Project1.res");
USEFORM("Unit1.cpp", Form1);
USEUNIT("VideoCapture.cpp");
USE("ImageProcess.h", File);
USEUNIT("MeanShiftTracker.cpp");
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}
//---------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
25
]
]
] |
7b1544897ea916d4e37fbc4f6cfe3016aec1157f | 3785a4fa521ee1f941980b9c2d397d9aa3622727 | /Goop/UI/Window.cpp | 82dbdf6ce94e90578a89d251d135dce4e3f49b2a | [] | no_license | Synth3tik0/goop-gui-library | 8b6e0d475c27e0213eb8449d8d38ccf18ce88b6e | 3c8f8eda4aa4d575f15ed8af174268e6e28dc6f3 | refs/heads/master | 2021-01-10T15:05:20.157645 | 2011-08-13T14:29:37 | 2011-08-13T14:29:37 | 49,666,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,352 | cpp | #include "Window.h"
#include "Menu.h"
using namespace Goop;
Window::Window(const wchar_t *title, Vector2D size) : m_menu(0)
{
DWORD ExStyle = NULL;
HINSTANCE instanceHandle = GetModuleHandle( NULL );
RegisterWindowClass();
m_handle = (HWND)CreateWindowEx(ExStyle, L"GoopWindow", L"", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, size.m_x, size.m_y, NULL, NULL, instanceHandle, NULL);
m_size = size;
InitializeBase();
SetTitle(title);
}
Window::~Window()
{
Destroy();
}
void Window::SetTitle(const wchar_t *title)
{
SetText(title);
}
const wchar_t *Window::GetTitle()
{
return GetText();
}
Vector2D Window::GetClientSize()
{
RECT rect;
GetClientRect(m_handle, &rect);
return Vector2D(rect.right - rect.left, rect.bottom - rect.top);
}
void Window::Maximize()
{
::ShowWindow(m_handle, SW_MAXIMIZE);
}
void Window::Minimize()
{
::ShowWindow(m_handle, SW_MINIMIZE);
}
void Window::Restore()
{
::ShowWindow(m_handle, SW_RESTORE);
}
Menu *Window::GetMenu()
{
return m_menu;
}
void Window::SetMenu(Menu *menu)
{
m_menu = menu;
::SetMenu(m_handle, m_menu->GetHandle());
}
void Window::ShowButton(WindowButton button, bool show)
{
if(show)
{
if((button & ::Minimize) > 0) RemoveStyle(WS_MINIMIZEBOX);
if((button & ::Maximize) > 0) RemoveStyle(WS_MAXIMIZEBOX);
if((button & ::Close) > 0) RemoveStyle(WS_SYSMENU);
}
else
{
if((button & ::Minimize) > 0) RemoveStyle(WS_MINIMIZEBOX);
if((button & ::Maximize) > 0) RemoveStyle(WS_MAXIMIZEBOX);
if((button & ::Close) > 0) RemoveStyle(WS_SYSMENU);
}
}
void Window::RegisterWindowClass()
{
static bool registered = false;
if(registered)
{
return;
}
HINSTANCE instanceHandle = GetModuleHandle( NULL );
WNDCLASSEX windowClass;
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = 0;
windowClass.lpfnWndProc = (WNDPROC)Base::Process;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = instanceHandle;
windowClass.hIcon = NULL;
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = L"GoopWindow";
windowClass.hIconSm = NULL;
RegisterClassEx( &windowClass );
registered = true;
} | [
"kiporshnikov@4a631193-2d15-b5e0-78eb-106c76b1a797",
"[email protected]"
] | [
[
[
1,
7
],
[
9,
10
],
[
12,
82
],
[
110,
110
]
],
[
[
8,
8
],
[
11,
11
],
[
83,
109
]
]
] |
c0bf341686c621c129215ee957d833b7644fb483 | 729f72df96cd6f816d3a100b8b1346c98ba72457 | /source/FlourTool.cpp | 9639f5b462d88aa6da7327f0986fd9864c908006 | [] | no_license | yhzhu/flour | e2459c10a05bbb8e03fa2b18b61116825f91f36b | 10424d1ec6490cf8a07705beb6507201c36dcfbc | refs/heads/master | 2021-01-18T03:13:40.892264 | 2010-04-11T17:11:17 | 2010-04-11T17:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,184 | cpp | /** File: FlourTool.cpp
Created on: 06-Sept-09
Author: Robin Southern "betajaen"
Copyright (c) 2009 Robin Southern
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "FlourTool.h"
#include "Flour.h"
#include <iostream>
FlourTool::FlourTool(const std::string& name, const std::string& description)
: mVariablesMap(), mOptionsDescription(description), mName(name), mDescription(description), mHasPositionalOptions(false)
{
}
FlourTool::~FlourTool()
{
}
void FlourTool::parse(int argc, char** argv)
{
// try
// {
boost::program_options::command_line_parser optionsParser(argc, argv);
optionsParser.options(mOptionsDescription);
optionsParser.allow_unregistered();
//if (mHasPositionalOptions)
optionsParser.positional(mPositionalOptions);
boost::program_options::parsed_options options = optionsParser.run();
boost::program_options::store(options, mVariablesMap);
/*
boost::program_options::command_line_parser parser(argc, argv);
parser.options(mOptionsDescription);
parser.allow_unregsitered
*/
//boost::program_options::parsed_options options = boost::program_options::command_line_parser(argc, argv).options(mOptionsDescription).allow_unregistered().run();
// boost::program_options::store(options, mVariablesMap);
if (mVariablesMap.count("help"))
{
std::cout << mOptionsDescription << std::endl;
return;
}
process();
// }
// catch(...)
// {
// std::cout << "AAA" << std::endl;
// }
}
void FlourTool::process()
{
std::cout << "Not Bound." << std::endl;
}
void FlourTool::add_error(unsigned int id, const std::string &description)
{
mErrors[id] = description;
}
void FlourTool::error(unsigned int id, bool aborted)
{
std::map<unsigned int, std::string>::iterator it = mErrors.find(id);
std::string error_string;
if (it == mErrors.end())
std::cout << "Error! " << "Unknown Error. (" << id << ")" << std::endl;
else
std::cout << "Error! " << (*it).second << " (" << id <<")" << std::endl;
if (aborted)
std::cout << "Aborted." << std::endl;
} | [
"[email protected]"
] | [
[
[
1,
102
]
]
] |
f56682479c06cf80d9355797ff863af8fd56dfa4 | 50f94444677eb6363f2965bc2a29c09f8da7e20d | /Src/EmptyProject/MainState.cpp | f9df3c83c2ce3948079dd995b94bb11621f46c14 | [] | no_license | gasbank/poolg | efd426db847150536eaa176d17dcddcf35e74e5d | e73221494c4a9fd29c3d75fb823c6fb1983d30e5 | refs/heads/master | 2020-04-10T11:56:52.033568 | 2010-11-04T19:31:00 | 2010-11-04T19:31:00 | 1,051,621 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | #include "EmptyProjectPCH.h"
#include "MainState.h"
#include "World.h"
#include "WorldManager.h"
#include "TopStateManager.h"
MainState::MainState(void)
{
}
MainState::~MainState(void)
{
}
HRESULT MainState::enter( double dStartTime )
{
return S_OK;
}
HRESULT MainState::leave()
{
return S_OK;
}
HRESULT MainState::frameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime )
{
getCurWorld()->frameRender( pd3dDevice, fTime, fElapsedTime );
return S_OK;
}
HRESULT MainState::frameMove( double fTime, float fElapsedTime )
{
getCurWorld()->frameMove( fTime, fElapsedTime );
return S_OK;
}
HRESULT MainState::handleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if ( uMsg == WM_KEYDOWN )
{
GetTopStateManager().setNextState( GAME_TOP_STATE_PLAY );
}
return S_OK;
}
HRESULT MainState::onCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
return S_OK;
}
HRESULT MainState::onResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
return S_OK;
}
void MainState::onLostDevice()
{
}
HRESULT MainState::release()
{
return S_OK;
} | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
14
],
[
16,
71
]
],
[
[
15,
15
]
]
] |
09cdac7297339e5c39ce042386f983d795cf6c49 | 5124e1a9d04312802e5f2bdb8bc83c9db09eb6aa | /Root/API/IndexedDatabase.cpp | f56635a6fdd166c312b50f8cbfa96fba81cc3d35 | [] | no_license | BrandonHaynes/indexeddb | 302f9cab90752758e02a7a49af0b35eda87d0c4a | 477ac611b11977c36a44506fa86430638f292426 | refs/heads/master | 2020-03-31T12:19:14.663625 | 2010-05-10T15:27:40 | 2010-05-10T15:27:40 | 32,110,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | /**********************************************************\
Copyright Brandon Haynes
http://code.google.com/p/indexeddb
GNU Lesser General Public License
\**********************************************************/
#include "IndexedDatabase.h"
#include "Synchronized/DatabaseSync.h"
#include "DatabaseException.h"
using std::string;
namespace BrandonHaynes {
namespace IndexedDB {
using Implementation::ImplementationException;
namespace API {
IndexedDatabase::IndexedDatabase(FB::BrowserHost host)
: host(host)
{ registerMethod("open", make_method(this, &IndexedDatabase::open)); }
FB::JSOutObject IndexedDatabase::open(const string& name, const string& description, const FB::CatchAll& args)
{
const FB::VariantList& values = args.value;
if(values.size() > 1)
throw FB::invalid_arguments();
else if(values.size() == 1 && !values[0].is_of_type<bool>())
throw FB::invalid_arguments();
bool modifyDatabase = values.size() == 1 ? values[0].cast<bool>() : true;
try
{ return new DatabaseSync(host, name, description, modifyDatabase); }
catch(ImplementationException& e)
{ throw DatabaseException(e); }
}
}
}
} | [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
f8e15cf293c823a4b3971654191130b5f78efbe8 | 8e4100ae6657d257df7750ffcffd05982e957c8c | /ClothAmortized/Server/Particle.hh | 3669a4c0eb94c277b4e915f15885fd67b9d715c9 | [] | no_license | onorinbejasus/CudaP7 | b49f6d1a106dd3d057961bb67f847f8ac3d17f6b | 8f213caba10d8502626eba6e582411cd1df31a3e | refs/heads/master | 2021-01-01T06:05:30.857673 | 2011-04-29T02:29:59 | 2011-04-29T02:29:59 | 1,579,758 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | hh | //
// Particle.hh
// Cloth Simulation
//
// Created by Timothy Luciani on 2011-03-11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#pragma once
#include "open_gl.hh"
#include "cuda_helpers.hh"
#define DAMPING 0.1 // how much to damp the cloth simulation each frame
struct Particle
{
__device__
Particle(){}
__device__
Particle(const float3 & ConstructPos, float mass, float *data_pointer, float *norms, int index, bool move) :
m_ConstructPos(ConstructPos), m_Position(ConstructPos), m_Old(ConstructPos),
m_normal(make_float3(0.0f)), m_forces(make_float3(0.0f)), m_mass(mass), m_index(index), m_movable(move) {
data_pointer[(index * 3) + 0] = m_ConstructPos.x;
data_pointer[(index * 3) + 1] = m_ConstructPos.y;
data_pointer[(index * 3) + 2] = m_ConstructPos.z;
norms[(index * 3) + 0] = 0.0f;
norms[(index * 3) + 1] = 0.0f;
norms[(index * 3) + 2] = 0.0f;
}
__device__ __host__
void reset()
{
m_Position = m_Old = m_ConstructPos;
m_normal = make_float3(0.0f);
m_forces = make_float3(0.0f);
} // resets the position, velocity, and force
// ===============================
// = Add a force to the particle =
// ===============================
__device__ __host__
void addForce(float3 force){
m_forces += force/m_mass;
}
__device__ __host__
void updateVector(float3 new_pos, float *data_pointer){ /* updates the vector position */
m_Position += new_pos;
data_pointer[(m_index *3) + 0] = m_Position.x;
data_pointer[(m_index *3) + 1] = m_Position.y;
data_pointer[(m_index *3) + 2] = m_Position.z;
} // set vector
__device__ __host__
void updateNormal(float3 normal){ /* updates the vector normal */
m_normal += normal;
}
__device__
void step(float time){
if(m_movable)
{
float3 temp = m_Position;
m_Position = m_Position + (m_Position - m_Old)*(1.0-DAMPING) + m_forces * time;
m_Old = temp;
m_forces = make_float3(0.0f);
} // end if
} // end step
uint m_index;
float3 m_ConstructPos; // original position
float3 m_Position; // current position
float3 m_Old; // previous integration position
float3 m_normal; // "normal" of point
float3 m_forces; // forces
float m_mass; // mass of particle
bool m_movable; // if movable or not
}; // end struct
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
21
],
[
23,
25
],
[
32,
92
]
],
[
[
22,
22
],
[
26,
31
]
]
] |
9fa7b2e936048a45a093eda98970c84dc65638f2 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Renderer/D3D10ShadowMap.cpp | 8fa21f37972ab8c014c234abf48dbe80aad50ce4 | [] | no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,001 | cpp | #include "D3D10ShadowMap.h"
#include "D3D10Renderer.h"
#include "D3D10RenderWindow.h"
#include "D3D10Texture.h"
#include "D3D10CubeTexture.h"
#include "../Main/Light.h"
#include "../Main/DataCenter.h"
#include "../Main/GlobalParam.h"
namespace Flagship
{
D3D10ShadowMap::D3D10ShadowMap()
{
m_pRenderTarget = NULL;
m_pDepthStencil = NULL;
m_pDepthSurface = NULL;
m_pRenderSurface = NULL;
m_pRenderer = new D3D10Renderer;
}
D3D10ShadowMap::~D3D10ShadowMap()
{
SAFE_RELEASE( m_pRenderSurface );
SAFE_RELEASE( m_pDepthSurface );
SAFE_DELETE( m_pRenderTarget );
SAFE_DELETE( m_pDepthStencil );
SAFE_DELETE( m_pRenderer );
}
bool D3D10ShadowMap::Initialize( UINT uiWidth, UINT uiHeight, DWORD dwFormat )
{
// 获取D3D10设备指针
ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
// 创建渲染贴图
m_pRenderTarget = new D3D10Texture;
if ( ! m_pRenderTarget->CreateRenderTarget( uiWidth, uiHeight, dwFormat ) )
{
return false;
}
// 获取渲染表面
D3D10Texture * pRenderTarget = (D3D10Texture *) m_pRenderTarget;
m_pRenderSurface = pRenderTarget->GetRenderTargetView();
// 创建渲染贴图
m_pDepthStencil = new D3D10Texture;
if ( ! m_pDepthStencil->CreateDepthStencil( uiWidth, uiHeight, DXGI_FORMAT_D24_UNORM_S8_UINT ) )
{
return false;
}
// 获取深度表面
D3D10Texture * pDepthStencil = (D3D10Texture *) m_pDepthStencil;
m_pDepthSurface = pDepthStencil->GetDepthStencilView();
return true;
}
void D3D10ShadowMap::UpdateShadow( Light * pLight, BYTE byShadowFace )
{
ShadowMap::UpdateShadow( pLight, byShadowFace );
// 获取D3D10设备指针
ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
// 获取旧的信息
ID3D10RenderTargetView * pOldRenderSurface;
ID3D10DepthStencilView * pOldDepthSurface;
pD3D10Device->OMGetRenderTargets( 1, &pOldRenderSurface, &pOldDepthSurface );
RenderTarget * pOldRenderTarget = GetActiveRenderTarget();
Camera * pOldCamera = GetActiveCamera();
// 设置渲染对象并渲染
GlobalParam::GetSingleton()->m_pGlobalMaterial = GlobalParam::GetSingleton()->m_pMakeShadow;
pD3D10Device->OMSetRenderTargets( 1, &m_pRenderSurface, m_pDepthSurface );
RenderTexture::Update();
GlobalParam::GetSingleton()->m_pGlobalMaterial = NULL;
// 恢复旧的渲染表面
pD3D10Device->OMSetRenderTargets( 1, &pOldRenderSurface, pOldDepthSurface );
SetActiveRenderTarget( pOldRenderTarget );
SetActiveCamera( pOldCamera );
SAFE_RELEASE( pOldRenderSurface );
SAFE_RELEASE( pOldDepthSurface );
}
void D3D10ShadowMap::SaveRenderTexture( wstring szPath )
{
D3D10Texture * pRenderTarget = (D3D10Texture *) m_pRenderTarget;
D3DX10SaveTextureToFile( pRenderTarget->GetImpliment(), D3DX10_IFF_DDS, szPath.c_str() );
}
} | [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
96
]
]
] |
66522df0b59591c2c3210d2aad4d212875122673 | 975d45994f670a7f284b0dc88d3a0ebe44458a82 | /cliente/Source/GameCore/CGameData.cpp | 707179729c35fe24f05d98b08319f42fef08135c | [] | no_license | phabh/warbugs | 2b616be17a54fbf46c78b576f17e702f6ddda1e6 | bf1def2f8b7d4267fb7af42df104e9cdbe0378f8 | refs/heads/master | 2020-12-25T08:51:02.308060 | 2010-11-15T00:37:38 | 2010-11-15T00:37:38 | 60,636,297 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,832 | cpp | #include "CGameData.h"
CGameData::CGameData(IrrlichtDevice *grafico)
{
_gameLoaded = false;
porcentagem = 0.0f;
_dataLoaded = 0;
_dispositivo = grafico;
_gerenciadorCena = _dispositivo->getSceneManager(); // Cria o gerenciador de cena
_gerenciadorVideo = _dispositivo->getVideoDriver(); // Cria o driver para o vídeo
_gerenciadorHud = _dispositivo->getGUIEnvironment(); // Cria o gerenciador de menu
_totalLoading = /*NUMCENARIOS*8 +*/ NUMMENUHUDS + NUM2DOBJS + NUM3DPERS*2 + NUM3DITENS*2;// + NUMPROPS*2;
}
bool CGameData::isDataLoaded()
{
return _gameLoaded;
}
void CGameData::loadStage(int stage)
{
switch (stage) // Estágios de carregamento do jogo
{
case 0: // Carrega malhas dos personagens 3D
for(int i=0; i<NUM3DPERS; i++)
{
dataGeometryChars[i] = _gerenciadorCena->getMesh(pathCharsModels[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.00f;
}
break;
case 1: // Carrega malhas dos itens 3D
for(int i=0; i<NUM3DITENS; i++)
{
dataGeometryItens[i] = _gerenciadorCena->getMesh(pathItensModels[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.00f;
}
break;
/*
case 2: // Carrega malhas dos props 3D
for(int i=0; i<NUMPROPS; i++)
{
dataGeometryProps[i] = _gerenciadorCena->getMesh(modelPropFile[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.0f;
}
break;*/
case 2: // Carrega texturas dos personagens 3D
for(int i=0; i<NUM3DPERS; i++)
{
dataTxChars[i] = _gerenciadorVideo->getTexture(pathTextureModels[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.00f;
}
break;
case 3: // Carrega texturas dos itens 3D
for(int i=0; i<NUM3DITENS; i++)
{
dataTxItens[i] = _gerenciadorVideo->getTexture(pathTextureItens[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.00f;
}
break;
/*
case 5: // Carrega texturas dos props 3D
for(int i=0; i<NUMPROPS; i++)
{
dataTxProps[i] = _gerenciadorVideo->getTexture(texturePropFile[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.0f;
}
break;*/
case 4: // Carrega texturas dos Huds
for(int i=0; i<NUM2DOBJS; i++)
{
dataTx2DItens[i] = _gerenciadorVideo->getTexture(pathTexture2D[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.00f;
}
break;
case 5: // Carrega as demais texturas dos Huds
for(int i=0; i<NUMMENUHUDS; i++)
{
dataTxHuds[i] = _gerenciadorVideo->getTexture(pathTextureHud[i]);
_dataLoaded++;
porcentagem = _dataLoaded/_totalLoading*100.00f;
}
_gameLoaded = true;
break;
};
cout << "\n" << porcentagem << endl;
} | [
"[email protected]"
] | [
[
[
1,
107
]
]
] |
b13ff511cab9fc0a294a48b86fe9655aee0779d3 | d3dd666a9823e0df316804b5422c10050e796a57 | /Client/src/MainWindow.cpp | be51c00c1c0d15a83adffdb82084b80b003d2a84 | [] | no_license | Surrog/airtipe | 0b1d3bc8a8705ef93af35b0b9ddfb72f3e938aa6 | a44043df83f8be3f5b116d262af9818fdadee562 | refs/heads/master | 2021-01-15T19:22:41.519880 | 2010-07-20T16:11:49 | 2010-07-20T16:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,340 | cpp | #include "MainWindow.hpp"
MainWindow::MainWindow(Client * client)
{
setWindowTitle("R-Type");
setFixedSize(428, 320);
setStyleSheet("QWidget { background-color: #000000; }"
" QLineEdit{ color: black; background-color: #FFFFFF; }"
" QPushButton { color: white; } "
" QCheckBox { color: white; } "
" QLabel { color: white; }"
);
this->_client = client;
this->_ipLabel = new QLabel("IP", this);
this->_ipLabel->move(120, 165);
this->_ip = new QLineEdit("", this);
this->_ip->move(160, 160);
this->_loginLabel = new QLabel("Login", this);
this->_loginLabel->move(120, 195);
this->_login = new QLineEdit(this);
this->_login->move(160, 190);
this->_fullScreen = new QCheckBox("Plein ecran", this);
this->_fullScreen->move(190, 220);
this->_start = new QPushButton("Commencer la partie", this);
this->_start->setCursor(Qt::PointingHandCursor);
this->_start->move(170, 250);
this->_warning = NULL;
this->_SplashImage = new QLabel(this);
this->_SplashImage->setPixmap(QPixmap("../ressources/rtype.png"));
this->_SplashImage->move(0, 0);
QObject::connect(this->_start, SIGNAL(clicked()), this, SLOT(formValidation()));
}
MainWindow::~MainWindow()
{
std::cout << "Appel du destructeur de MainWindow" << std::endl;
delete this->_start;
if (this->_warning != NULL)
delete this->_warning;
delete this->_ip;
delete this->_ipLabel;
delete this->_login;
delete this->_loginLabel;
delete this->_fullScreen;
delete this->_SplashImage;
}
void MainWindow::formValidation()
{
// std::cout << this->_ip->text().toStdString() << " port : " << this->_port->text().toUShort() << std::endl;
std::string ip(_ip->text().toStdString());
std::cout << ip << std::endl;
if (this->_ip->text().length() == 0 || this->_login->text().length() == 0)
{
_warning = new QMessageBox(QMessageBox::Warning, "Error", "Please enter login and ip first");
_warning->show();
}
else
{
if (_client->getNetwork().tryConnect(this->_ip->text().toStdString(), 22255))
{
_client->setLogin(this->_login->text().toStdString());
this->close();
}
else
{
_warning = new QMessageBox(QMessageBox::Warning, "Error", "Connection timed out");
_warning->show();
}
}
}
| [
"anat1337@32e6bcfa-9e84-7d95-9935-f22b4b10203c",
"florian.chanioux@32e6bcfa-9e84-7d95-9935-f22b4b10203c"
] | [
[
[
1,
5
],
[
14,
14
],
[
16,
19
],
[
22,
28
],
[
31,
35
],
[
37,
41
],
[
43,
83
]
],
[
[
6,
13
],
[
15,
15
],
[
20,
21
],
[
29,
30
],
[
36,
36
],
[
42,
42
],
[
84,
84
]
]
] |
29d64ccfe422ecd8f3d618efb6ea052ba6884c16 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/test/test_class_info_save.cpp | 874d607488296ab2eb9fb2321740fc6ecc4f2dd8 | [] | 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 | 2,962 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_class_info_save.cpp: test implementation level trait
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is 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)
// test implementation level "object_class_info"
// should pass compilation and execution
#include <fstream>
#include <string>
#include <boost/static_assert.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/archive/tmpdir.hpp>
#include <boost/preprocessor/stringize.hpp>
#include "test_tools.hpp"
// first case : serialize WITHOUT class information
class A
{
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & /*ar*/, const unsigned int file_version){
// class that don't save class info always have a version number of 0
BOOST_CHECK(file_version == 0);
BOOST_STATIC_ASSERT(0 == ::boost::serialization::version<A>::value);
++count;
}
public:
unsigned int count;
A() : count(0) {}
};
BOOST_CLASS_IMPLEMENTATION(A, ::boost::serialization::object_serializable)
BOOST_CLASS_TRACKING(A, ::boost::serialization::track_never)
// second case : serialize WITH class information
class B;
BOOST_CLASS_VERSION(B, 2)
class B
{
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & /*ar*/, const unsigned int file_version){
// verify at execution that correct version number is passed on save
BOOST_CHECK(file_version == ::boost::serialization::version<B>::value);
++count;
}
public:
unsigned int count;
B() : count(0) {}
};
BOOST_CLASS_IMPLEMENTATION(B, ::boost::serialization::object_class_info)
BOOST_CLASS_TRACKING(B, boost::serialization::track_always)
void out(const char *testfile, const A & a, const B & b)
{
test_ostream os(testfile, TEST_STREAM_FLAGS);
test_oarchive oa(os);
// write object twice to check tracking
oa << BOOST_SERIALIZATION_NVP(a);
oa << BOOST_SERIALIZATION_NVP(a);
BOOST_CHECK(a.count == 2); // no tracking => redundant saves
oa << BOOST_SERIALIZATION_NVP(b);
oa << BOOST_SERIALIZATION_NVP(b);
BOOST_CHECK(b.count == 1); // tracking => no redundant saves
}
int
test_main( int /* argc */, char* /* argv */[] )
{
A a;
B b;
std::string filename;
filename += boost::archive::tmpdir();
filename += '/';
filename += BOOST_PP_STRINGIZE(testfile_);
filename += BOOST_PP_STRINGIZE(BOOST_ARCHIVE_TEST);
out(filename.c_str(), a, b);
return boost::exit_success;
}
// EOF
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
92
]
]
] |
4827580112c2f782093096261f04a9021ba6eef0 | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmesh/raster/Raster.h | 9d0a25aacb65b458e78fc1ffabde649f2fa0da1e | [] | no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | h | // This code is in the public domain -- [email protected]
#ifndef NV_MESH_RASTER_H
#define NV_MESH_RASTER_H
/** @file Raster.h
* @brief Rasterization library.
*
* This is just a standard scanline rasterizer that I took from one of my old
* projects. The perspective correction wasn't necessary so I just removed it.
**/
#include <nvmesh/nvmesh.h>
#include <nvmath/Vector.h>
#define RASTER_ANTIALIAS true
#define RASTER_NOAA false
namespace nv
{
namespace Raster
{
/// A callback to sample the environment.
typedef void (NV_CDECL * SamplingCallback)(void * param, int x, int y, Vector3::Arg bar, Vector3::Arg dx, Vector3::Arg dy, float coverage);
// Process the given triangle.
NVMESH_API bool drawTriangle(bool antialias, Vector2::Arg extents, const Vector2 v[3], SamplingCallback cb, void * param);
// Process the given quad.
NVMESH_API bool drawQuad(bool antialias, Vector2::Arg extents, const Vector2 vertex[4], SamplingCallback, void * param);
}
}
#endif // NV_MESH_RASTER_H
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
] | [
[
[
1,
36
]
]
] |
cc9a2571b545875a41c7f3b35201d60c9b0bbf74 | 8b68ff41fd39c9cf20d27922bb9f8b9d2a1c68e9 | /TWL/include/buf.h | 83b56afcf741cc1f8f7a3d06757bf4faaf66aacc | [] | no_license | dandycheung/dandy-twl | 2ec6d500273b3cb7dd6ab9e5a3412740d73219ae | 991220b02f31e4ec82760ece9cd974103c7f9213 | refs/heads/master | 2020-12-24T15:06:06.260650 | 2009-05-20T14:46:07 | 2009-05-20T14:46:07 | 32,625,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,355 | h | //////////////////////////////////////////////////////////////////////////
// This is a part of the Tiny Window Library(TWL).
// Copyright (C) 2003-2005 Dandy Cheung
// [email protected]
// All rights reserved.
//
#ifndef __BUF_H__
#define __BUF_H__
#pragma once
#ifndef __cplusplus
#error TWL requires C++ compilation (use a .cpp suffix)
#endif
namespace TWL
{
template <typename _T, size_t sizDef>
class TDataBuffer
{
protected:
_T* _p;
size_t _size;
public:
TDataBuffer(size_t size = sizDef) : _p(NULL), _size(0)
{
GetBuffer(size);
}
~TDataBuffer()
{
ReleaseBuffer();
}
BOOL GetBuffer(size_t size)
{
if(_size >= size)
return TRUE;
_T* p = new _T[size];
if(!p)
return FALSE;
memset(p, 0, sizeof(_T) * size);
if(_p)
{
memcpy(p, _p, sizeof(_T) * _size);
delete[] _p;
_p = NULL;
_size = 0;
}
_p = p;
_size = size;
return TRUE;
}
void ReleaseBuffer()
{
if(_p)
{
delete[] _p;
_p = NULL;
_size = 0;
}
}
size_t GetSize() const
{
return _size;
}
operator const _T*() const
{
return _p;
}
operator _T*()
{
return _p;
}
};
typedef TDataBuffer<TCHAR, 128> CStringBuffer;
typedef TDataBuffer<BYTE, 512> CByteBuffer;
}; // namespace TWL
#endif // __BUF_H__
| [
"dandycheung@9b253700-4547-11de-82b9-170f4fd74ac7"
] | [
[
[
1,
95
]
]
] |
2bffd1d1411cf4989e1587792c4cf96edc292676 | bf19f77fdef85e76a7ebdedfa04a207ba7afcada | /NewAlpha/TMNT Tactics Tech Demo/Source/Player.cpp | 798a90f8689c0ef206c89237bb9602b26e779430 | [] | no_license | marvelman610/tmntactis | 2aa3176d913a72ed985709843634933b80d7cb4a | a4e290960510e5f23ff7dbc1e805e130ee9bb57d | refs/heads/master | 2020-12-24T13:36:54.332385 | 2010-07-12T08:08:12 | 2010-07-12T08:08:12 | 39,046,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,351 | cpp | ////////////////////////////////////////////////////////
// File Name : "CPlayer.cpp"
//
// Author : Matthew Di Matteo (MD)
//
// Purpose : To provide a game object to be used as the player
// being controlled by user during the game.
////////////////////////////////////////////////////////
#include "Player.h"
#include "Factory.h"
#include "tinyxml/tinyxml.h"
#include "CSGD_TextureManager.h"
#include "ObjectManager.h"
#include "Skill.h"
#include "Achievements.h"
#include "Game.h"
#include <string>
#include <fstream>
using namespace std;
#include "Animation.h"
CPlayer::CPlayer(void)
{
m_pTurtles[LEONARDO] = Factory::GetInstance()->CreateTurtle("Leonardo");
m_pTurtles[DONATELLO]= Factory::GetInstance()->CreateTurtle("Donatello");
m_pTurtles[RAPHAEL] = Factory::GetInstance()->CreateTurtle("Raphael");
m_pTurtles[MIKEY] = Factory::GetInstance()->CreateTurtle("Michelangelo");
//////////////////////////////////////////////////////////////////////////
// load animations...play starting idles
LoadAnimations();
m_pTurtles[LEONARDO]->GetCurrAnim()->Play();
m_pTurtles[DONATELLO]->GetCurrAnim()->Play();
m_pTurtles[RAPHAEL]->GetCurrAnim()->Play();
m_pTurtles[MIKEY]->GetCurrAnim()->Play();
m_nCurrStage = 0; m_nKillCount = 0;
m_pAcheivements = new CAchievements();
}
void CPlayer::Exit()
{
delete m_pAcheivements; m_pAcheivements = NULL;
for(int i = 0; i < 4; i++)
for(unsigned int j = 0; j < m_pTurtles[i]->GetAnimations().size(); j++)
m_pTurtles[i]->GetAnimations()[j].Unload();
}
CPlayer::~CPlayer(void)
{
}
CPlayer* CPlayer::GetInstance()
{
static CPlayer instance;
return &instance;
}
void CPlayer::NewGame()
{
m_sProfileName = "NONE"; m_sFileName = "NONE";
Exit();
ObjectManager::GetInstance()->RemoveAll();
m_pTurtles[LEONARDO] = Factory::GetInstance()->CreateTurtle("Leonardo");
m_pTurtles[DONATELLO]= Factory::GetInstance()->CreateTurtle("Donatello");
m_pTurtles[RAPHAEL] = Factory::GetInstance()->CreateTurtle("Raphael");
m_pTurtles[MIKEY] = Factory::GetInstance()->CreateTurtle("Michelangelo");
LoadAnimations();
m_sProfileName = "NONE"; m_sFileName = "NONE";
GetItems()->clear();
if(m_pAcheivements)
delete m_pAcheivements;
m_pAcheivements = new CAchievements();
for (int i = 1; i < NUM_MAPS; ++i) // lock all maps, except first one
m_bMapsUnlocked[i] = false;
m_bMapsUnlocked[0] = true;
//////////////////////////////////////////////////////////////////////////
// create and add starting weapons
for (int i = 0; i < 4; ++i)
{
m_pTurtles[i]->ClearWeapons();
m_pTurtles[i]->ClearActiveSkills();
m_pTurtles[i]->ClearInactiveSkills();
m_pTurtles[i]->GetCurrAnim()->Play();
}
CBase weapon;
weapon.SetWeapon("Bokken",6,0,-1,0);
m_pTurtles[LEONARDO]->AddWeapon( weapon );
weapon.SetWeapon("Oak Bo Staff",5,1,-1,7);
m_pTurtles[DONATELLO]->AddWeapon( weapon );
weapon.SetWeapon("Rusty Sais",6,0,-1,10);
m_pTurtles[RAPHAEL]->AddWeapon( weapon );
weapon.SetWeapon("Wooden Nunchaku",3,0,-1,4);
m_pTurtles[MIKEY]->AddWeapon( weapon );
//////////////////////////////////////////////////////////////////////////
m_nCurrStage = 0; // current stage starts at the first battle map
// set stats to starting values
LoadTurtleStats("Resources/XML/VG_TurtleStats.xml");
CGame::GetInstance()->LoadNewSkills("Resources/XML/VG_TurtleSkills.xml");
//////////////////////////////////////////////////////////////////////////
// TODO:: remove temp items before final build
// POINT pt; pt.x = 3; pt.y = 17;
// Factory::GetInstance()->CreateBattleItem(BLACK_EGGS, pt);
// Factory::GetInstance()->CreateBattleItem(GRENADO, pt);
// Factory::GetInstance()->CreateBattleItem(PIZZA, pt);
}
bool CPlayer::LoadTurtleStats(const char* szXmlFileName)
{
TiXmlDocument doc;
int ap = 0, hp = 0, strength = 0, defense = 0, accuracy = 0, speed = 0, level = 0, experience = 0, range = 0;
if(!doc.LoadFile(szXmlFileName))
{MessageBox(0, "Failed to load turtle stats.", "Error", MB_OK);return false;}
TiXmlElement* pRoot = doc.RootElement();
TiXmlElement* pLeo = pRoot->FirstChildElement("Leonardo");
if(pLeo)
{
pLeo->Attribute("AP", &ap);
pLeo->Attribute("HP", &hp);
pLeo->Attribute("strength", &strength);
pLeo->Attribute("defense", &defense);
pLeo->Attribute("accuracy", &accuracy);
pLeo->Attribute("speed", &speed);
pLeo->Attribute("level", &level);
pLeo->Attribute("exp", &experience);
pLeo->Attribute("range", &range);
m_pTurtles[LEONARDO]->SetAttributes(ap,hp,strength,defense,accuracy,speed,level,experience,range);
}
TiXmlElement* pRaph = pLeo->NextSiblingElement("Raphael");
if(pRaph)
{
pRaph->Attribute("AP", &ap);
pRaph->Attribute("HP", &hp);
pRaph->Attribute("strength", &strength);
pRaph->Attribute("defense", &defense);
pRaph->Attribute("accuracy", &accuracy);
pRaph->Attribute("speed", &speed);
pRaph->Attribute("level", &level);
pRaph->Attribute("exp", &experience);
pRaph->Attribute("range", &range);
m_pTurtles[RAPHAEL]->SetAttributes(ap,hp,strength,defense,accuracy,speed,level,experience,range);
}
TiXmlElement* pDon = pRaph->NextSiblingElement("Donatello");
if(pDon)
{
pDon->Attribute("AP", &ap);
pDon->Attribute("HP", &hp);
pDon->Attribute("strength", &strength);
pDon->Attribute("defense", &defense);
pDon->Attribute("accuracy", &accuracy);
pDon->Attribute("speed", &speed);
pDon->Attribute("level", &level);
pDon->Attribute("exp", &experience);
pDon->Attribute("range", &range);
m_pTurtles[DONATELLO]->SetAttributes(ap,hp,strength,defense,accuracy,speed,level,experience,range);
}
TiXmlElement* pMikey = pDon->NextSiblingElement("Michelangelo");
if(pMikey)
{
pMikey->Attribute("AP", &ap);
pMikey->Attribute("HP", &hp);
pMikey->Attribute("strength", &strength);
pMikey->Attribute("defense", &defense);
pMikey->Attribute("accuracy", &accuracy);
pMikey->Attribute("speed", &speed);
pMikey->Attribute("level", &level);
pMikey->Attribute("exp", &experience);
pMikey->Attribute("range", &range);
m_pTurtles[MIKEY]->SetAttributes(ap,hp,strength,defense,accuracy,speed,level,experience,range);
}
return true;
}
void CPlayer::LoadAnimations()
{
CAnimation anim;
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 1,0.25f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 2,0.15f, false);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 3,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 4,0.25f, false);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 5,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 6,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 7,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 8,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 9,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 10,1,false);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 11,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 12,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_leonardo3.dat", 13,0.15f);
m_pTurtles[LEONARDO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 1,0.25f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 2,0.15f, false);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 3,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 4,0.15f, false);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 5,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 6,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 7,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 8,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 9,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 10,1,false);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_donatello.dat", 11,0.15f);
m_pTurtles[DONATELLO]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 1,0.25f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 2,0.15f, false);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 3,0.15f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 4,0.15f, false);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 5,0.15f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 6,0.15f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 7,0.15f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 8,0.15f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 9,0.15f);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_raphael.dat", 10,1,false);
m_pTurtles[RAPHAEL]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 1,0.25f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 2,0.15f, false);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 3,0.15f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 4,0.15f, false);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 5,0.15f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 6,0.15f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 7,0.15f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 8,0.15f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 9,0.15f);
m_pTurtles[MIKEY]->AddAnim(anim);
anim.Load("Resources/AnimationInfo/VG_michelangelo.dat", 10,1,false);
m_pTurtles[MIKEY]->AddAnim(anim);
}
bool CPlayer::RemoveItem(int index)
{
vector<CBattleItem>::iterator iter = m_nInventory.begin();
unsigned int count = 0;
while(count < m_nInventory.size())
{
if (count == index)
{
iter = m_nInventory.erase(iter);
return true;
}
++count;
++iter;
}
return false;
}
| [
"AllThingsCandid@7dc79cba-3e6d-11de-b8bc-ddcf2599578a",
"marvelman610@7dc79cba-3e6d-11de-b8bc-ddcf2599578a"
] | [
[
[
1,
28
],
[
31,
31
],
[
37,
194
],
[
196,
196
],
[
220,
221
],
[
223,
223
],
[
243,
244
],
[
246,
246
],
[
264,
265
],
[
283,
283
],
[
285,
286
]
],
[
[
29,
30
],
[
32,
36
],
[
195,
195
],
[
197,
219
],
[
222,
222
],
[
224,
242
],
[
245,
245
],
[
247,
263
],
[
266,
282
],
[
284,
284
],
[
287,
302
]
]
] |
f3e62eb743a2917c72458ee203ac519d586a851c | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/Aran/ArnContainer.h | 35b5105e7c7287e9440b9ea06151e2fa5eacb14a | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 982 | h | /*!
* @file ArnContainer.h
* @author Geoyeob Kim
* @date 2009
*/
#pragma once
#include "ArnNode.h"
TYPEDEF_SHARED_PTR(ArnContainer)
/*!
* @brief ArnNode를 계층적으로 저장하고 싶을 때 사용하는 클래스
*
* ArnNode는 순수 가상 함수가 포함되어있기 때문에 instantiate를 할 수 없습니다.
* 이 클래스는 순수 가상 함수를 모두 구현하여 개체를 생성할 수 있습니다.
*/
class ArnContainer : public ArnNode
{
public:
~ArnContainer(void);
/*!
* @brief 빈 container를 생성하여 반환
*/
static ArnContainerPtr createFromEmpty();
/*!
* @name Internal use only methods
* These methods are exposed in order to make internal linkage between objects.
* You should aware that these are not for client-side APIs.
*/
//@{
virtual void interconnect(ArnNode* sceneRoot) { ArnNode::interconnect(sceneRoot); }
//@}
private:
ArnContainer(void);
};
| [
"[email protected]"
] | [
[
[
1,
38
]
]
] |
7de3a8a417a319a652fcd62b519101fa9d6c1b64 | 17083b919f058848c3eb038eae37effd1a5b0759 | /SimpleGL/sgl/GL/GLBlendState.h | ce4ad99c476ab5f84b658f991ac2f6dc173e4a03 | [] | no_license | BackupTheBerlios/sgl | e1ce68dfc2daa011bdcf018ddce744698cc7bc5f | 2ab6e770dfaf5268c1afa41a77c04ad7774a70ed | refs/heads/master | 2021-01-21T12:39:59.048415 | 2011-10-28T16:14:29 | 2011-10-28T16:14:29 | 39,894,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | h | #ifndef SIMPLE_GL_GL_BLEND_STATE_H
#define SIMPLE_GL_GL_BLEND_STATE_H
#include "GLForward.h"
#include "../BlendState.h"
namespace sgl {
#ifndef __ANDROID__
class GLBlendStateDisplayLists :
public ReferencedImpl<BlendState>
{
public:
GLBlendStateDisplayLists(GLDevice* device,
const BlendState::DESC& desc);
~GLBlendStateDisplayLists();
// Override BlendState
void SGL_DLLCALL Bind() const;
const BlendState::DESC& SGL_DLLCALL Desc() const { return desc; }
private:
GLDevice* device;
unsigned bindDisplayList;
BlendState::DESC desc;
};
#endif // !defined(__ANDROID__)
class GLBlendStateSeparate :
public ReferencedImpl<BlendState>
{
public:
GLBlendStateSeparate(GLDevice* device,
const BlendState::DESC& desc);
~GLBlendStateSeparate();
// Override BlendState
void SGL_DLLCALL Bind() const;
const BlendState::DESC& SGL_DLLCALL Desc() const { return desc; }
private:
GLDevice* device;
BlendState::DESC desc;
};
class GLBlendStateDefault :
public ReferencedImpl<BlendState>
{
public:
GLBlendStateDefault(GLDevice* device,
const BlendState::DESC& desc);
~GLBlendStateDefault();
// Override BlendState
void SGL_DLLCALL Bind() const;
const BlendState::DESC& SGL_DLLCALL Desc() const { return desc; }
private:
GLDevice* device;
BlendState::DESC desc;
// gl bindings
unsigned glSrcBlend;
unsigned glDestBlend;
unsigned glBlendOp;
};
} // namepsace sgl
#endif // SIMPLE_GL_GL_BLEND_STATE_H
| [
"devnull@localhost"
] | [
[
[
1,
72
]
]
] |
28aeb406d27bb1983f0f30ca472613dafe498bc2 | b09a4d24f49daac145a26c4e6b0dbd7749fb202b | /development/FileKeeper/Data/DataPool.h | 0f2b6c0de6746b65fe1e21d4e7b3928f7a935b22 | [] | no_license | buf1024/filekeeper | e4d6ead1413fa5c41e66f95d5a5df2b21f211b9f | cb52a3cb417a73535177658d7f83bf71c778a590 | refs/heads/master | 2021-01-10T12:55:16.930778 | 2010-12-23T15:10:26 | 2010-12-23T15:10:26 | 49,615,444 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,452 | h | //=============================================================================
/**
* @file DataPool.h
* @brief Basic database class
* @author heidong
* @version 1.0
* @date 2010-12-13 20:52:11
*/
//=============================================================================
#pragma once
#include <Singleton.h>
#include <stl.h>
#include "ForbidOpt.h"
#include "sqlite3.h"
using namespace lgc;
class UserObject;
class ProgObject;
class PersistObject;
class DataPool
: public Singleton<DataPool>
{
public:
DataPool(void);
~DataPool(void);
public:
/**@name DataPool basic function*/
/**@{*/
/** Method Empty
*
* Delete all data in the database
* @return true if successfully, false otherwise
*/
bool Empty();
/** Method Init
*
* Initialize the Database
* @param strFile The Database filename
* @return true if successfully, false otherwise
*/
bool Init(Std_String strFile);
/** Method ExecRawSql
*
* Execute the raw sql
* @param strSql The SQL
* @return true if succesfully, false otherwise
*/
bool ExecRawSql(string strSql);
/** Method SetDbFile
*
* Set an new database file and initialize it.
* @param strFile The Database filename
*/
void SetDbFile(Std_String strFile);
/** Method GetDbFile
*
* Get the current database filename
* @return The Database filename
*/
Std_String GetDbFile();
/**@}*/
/**@name Persist Object function*/
/**@{*/
/**Get user from database
*@param strUserName The User Name
*@return NULL if the user not found, othewise the user
*/
UserObject* GetUser(Std_String strUserName);
/**Get All users from the database
*@param rgpUsers The returned users in the database
*@return The count of the users
*/
int GetUser(list<UserObject*>& rgpUsers);
/** Method PersistUser
*
* Persist a userobject into the database. update or create new one.
* @param pUser The persist object
* @return true if succesfully, false otherwise
*/
bool PersistUser(UserObject* pUser);
/**Get program from the database
*@param strProg The program
*@return NULL if the program not found, othewise the program
*/
ProgObject* GetProg(Std_String strProg);
/**Get All programs from the database
*@param rgpProgs The returned programs in the database
*@return The count of the programs
*/
int GetProg(list<ProgObject*>& rgpProgs);
/** Method PersistProg
*
* Persist a programobject into the database. update or create new one.
* @param pProg The Program object
* @return true if succesfully, false otherwise
*/
bool PersistProg(ProgObject* pProg);
/**@}*/
/**@name Forbidden function*/
/**@{*/
/**Get the forbidden path the forbid all program access
*@param rgpPath The returned forbidden path
*@return the count of forbidden path
*/
int GetForbidPath(list<Std_String>& rgpPath);
/**Get the forbidden path of the specific program
*@param strProgPath The program path
*@param rgpPath The returned forbidden path
*@return the count of forbidden path
*/
int GetForbidPath(Std_String strProgPath, list<ForbidOpt>& rgpPath);
/**Add a new forbidden path
*@param strProgPath The program path
*@param strPath The new path
*@param nOpt The forbidden mask
*@return true if successfully add, othwerwise false
*/
bool AddForbidPath(Std_String strProgPath, Std_String strPath, int nOpt = 0x07);
/** Method AddForbidPath
*
* Add a new forbidden path the forbidden all program access
* @param strPath The new path
* @return true if successfully add, othwerwise false
*/
bool AddForbidPath(Std_String strPath);
/**Delete a forbidden path
*@param strProgPath The program path
*@param strPath The path
*@return true if successfully delete, othwerwise false
*/
bool DropForbidPath(Std_String strProgPath, Std_String strPath);
/** Method DropForbidPath
*
* Delete a forbidden path that forbid all program access
* @param strPath The path
* @return true if successfully delete, othwerwise false
*/
bool DropForbidPath(Std_String strPath);
/**Change the forbidden path forbidden mask
*@param strProgPath The program path
*@param strPath The path
*@param nOpt The forbidden mask
*@return true if successfully changed, othwerwise false
*/
bool ChangeForbidPathOpt(Std_String strProgPath, Std_String strPath, int nOpt);
/**Get the path forbidden option
*@param rgpProg the returned programs
*@return the count of the program
*/
int GetPathForbidProg(Std_String strPath, list<ProgObject*>& rgpProg);
/** Method AddPathForbidProg
*
* Set Path that forbid specific progragm to access
* @param strPath The Path
* @param strProgPath The program path
* @param nOpt The forbidden mask
* @return true if successfull add, false otherwise
*/
bool AddPathForbidProg(Std_String strPath, Std_String strProgPath, int nOpt = 0x07);
/**@}*/
/**@name Encryption function*/
/**@{*/
/**Get the encrypt path
*@param rgpPath the encrypt path by all user
*@return the count of the encrypt path
*/
int GetEncryptPath(list<Std_String>& rgpPath);
/**Get the encrypt path of some user
*@param strUser the user
*@param rgpPath the encrypt path
*@return the count of the encrypt path
*/
int GetEncryptPath(Std_String strUser, list<Std_String>& rgpPath);
/**Get the encrypt path of some user
*@param strUser the user
*@param strPath the new encrypt path
*@return true if successfully add, false otherwise
*/
/** Method: AddEncryptPath
*
*
* @param strUser
* @param strPath
* @return
* @date 2010-12-14 (21:52)
* @author heidong
*/
bool AddEncryptPath(Std_String strUser, Std_String strPath);
/**delete the encrypt path of some user
*@param strUser the user
*@param strPath the new encrypt path
*@return true if successfully add, false otherwise
*/
bool DropEncryptPath(Std_String strUser, Std_String strPath);
/**@}*/
private:
bool InitDBData();
UserObject* BuildUserObject(sqlite3_stmt* pStmt);
ProgObject* BuildProgObject(sqlite3_stmt* pStmt);
private:
sqlite3* m_pDB;
Std_String m_strDbFile;
bool m_bInit;
};
| [
"buf1024@9b6b46d4-6a51-a6c0-14c6-10956b729e0f"
] | [
[
[
1,
216
]
]
] |
e5eae3fb19a43aec57a1666bbdd4d719cb035055 | 8523123cacd378d808dbd3f02bbe0b66e2c69290 | /SC2 Multi Lossbot/SC2 Multi Lossbot/clsBot.h | cda96cf2f5915bdc4aa851a6f79b972fcf60580e | [] | no_license | shneezyn/sc2-multi-lossbot | 568194a12cba168b0bbac9ed046a2fb717cd6bb3 | 47ed28853067689679d7e189344599b716ae4c5f | refs/heads/master | 2016-08-09T07:33:50.243624 | 2010-11-30T20:32:22 | 2010-11-30T20:32:22 | 44,065,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | h | #include <string>
#include <atlstr.h>
using namespace std;
class clsBot
{
public:
static HWND hChat[2];
static HWND hAll[2];
static HWND hAllies[2];
static HWND hGameType[8];
static HWND hMultiplayer[8];
static HWND hCooperative[8];
static HWND hWindowStatus[8];
static HWND hVisible[8];
static HWND hPlayerName[8];
static HWND hHidden[8];
static HWND hDisabled[8];
static HWND hStatus[8];
static HWND hGameLimit[8];
static HWND hGames[8];
static HWND hWon[8];
static HWND hLoss[8];
static HWND h2ndChatDelay[8];
static HWND h1stChatDelay[8];
static HWND hLeaveDelay[8];
static HWND h1stChat;
static HWND h2ndChat;
static HWND hShow1stChat;
static HWND hShow2ndChat;
static HWND hScoreScreen;
static HWND hSurrender;
static HANDLE hStartBot;
static void SetupWarcraft(int instance);
static DWORD WINAPI StartBot(LPVOID lpParam);
static void MouseClick(int instance, double x, double y);
static BOOL SetupWindow(int instance, RECT rctClient, RECT rctWindow);
static BOOL SupportedResolution(int width, int height);
}; | [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
89c9c47c3f64cc216c861c2e5a22165b49e26371 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /apsim/Plant/source/Phenology/InductivePhase.h | 86714f80a525d3e68e1110a16297bb7d74b4887f | [] | no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | #ifndef InductivePhaseH
#define InductivePhaseH
#include "VernalPhase.h"
class InductivePhase : public VernalPhase
{
protected:
virtual float stress();
virtual void updateTTTargets();
public:
InductivePhase(ScienceAPI& scienceAPI, plantInterface& p, const string& stage_name)
: VernalPhase (scienceAPI, p, stage_name){};
};
#endif
| [
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] | [
[
[
1,
17
]
]
] |
656862a8125ea3328986a5d5f9a5a586eccca3f0 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkBoostBiconnectedComponents.h | 674bfd9c3de79092f498b29077e55d07cfb45bae | [
"BSD-3-Clause"
] | permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,029 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkBoostBiconnectedComponents.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkBoostBiconnectedComponents - Find the biconnected components of a graph
//
// .SECTION Description
// The biconnected components of a graph are maximal regions of the graph where
// the removal of any single vertex from the region will not disconnect the
// graph. Every edge belongs to exactly one biconnected component. The
// biconnected component of each edge is given in the edge array named
// "biconnected component". The biconnected component of each vertex is also
// given in the vertex array named "biconnected component". Cut vertices (or
// articulation points) belong to multiple biconnected components, and break
// the graph apart if removed. These are indicated by assigning a component
// value of -1. To get the biconnected components that a cut vertex belongs
// to, traverse its edge list and collect the distinct component ids for its
// incident edges.
//
// .SECTION Caveats
// The boost graph bindings currently only support boost version 1.33.1.
// There are apparently backwards-compatibility issues with later versions.
#ifndef __vtkBoostBiconnectedComponents_h
#define __vtkBoostBiconnectedComponents_h
#include "vtkUndirectedGraphAlgorithm.h"
class VTK_INFOVIS_EXPORT vtkBoostBiconnectedComponents : public vtkUndirectedGraphAlgorithm
{
public:
static vtkBoostBiconnectedComponents *New();
vtkTypeMacro(vtkBoostBiconnectedComponents, vtkUndirectedGraphAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Set the output array name. If no output array name is
// set then the name "biconnected component" is used.
vtkSetStringMacro(OutputArrayName);
protected:
vtkBoostBiconnectedComponents();
~vtkBoostBiconnectedComponents();
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
private:
char* OutputArrayName;
vtkBoostBiconnectedComponents(const vtkBoostBiconnectedComponents&); // Not implemented.
void operator=(const vtkBoostBiconnectedComponents&); // Not implemented.
};
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
] | [
[
[
1,
70
]
]
] |
b8e6715099075f9d6a3939b1c8b4b3eb25b39398 | d249c8f9920b1267752342f77d6f12592cb32636 | /mocap/src/MocapLoader.cpp | f9901d2b8e4cb6cf6e62107d042a23bce79cc689 | [] | no_license | jgraulle/stage-animation-physique | 4c9fb0f96b9f4626420046171ff60f23fe035d5d | f1b0c69c3ab48f256d5ac51b4ffdbd48b1c001ae | refs/heads/master | 2021-12-23T13:46:07.677761 | 2011-03-08T22:47:53 | 2011-03-08T22:47:53 | 33,616,188 | 0 | 0 | null | 2021-10-05T10:41:29 | 2015-04-08T15:41:32 | C++ | ISO-8859-1 | C++ | false | false | 1,495 | cpp | #include "MocapLoader.h"
#include "BvhLoader.h"
#include "SkinLoader.h"
MocapLoader::MocapLoader() {
mocapData = NULL;
skeletalData = NULL;
skinData = NULL;
}
MocapLoader::~MocapLoader() {
}
MocapData * MocapLoader::getMocapData() {
return mocapData;
}
SkeletalData * MocapLoader::getSkeletalData() {
return skeletalData;
}
SkinData * MocapLoader::getSkinData() {
return skinData;
}
void MocapLoader::setMocapData(MocapData * mocapData) {
this->mocapData = mocapData;
}
void MocapLoader::setSkeletalData(SkeletalData * skeletalData) {
this->skeletalData = skeletalData;
}
void MocapLoader::setSkinData(SkinData * skinData) {
this->skinData = skinData;
}
MocapLoader * MocapLoader::getInstanceOfAppriopriateLoader(string nomFichier) {
// Détermine l'extension du fichier
string extension = nomFichier.substr(nomFichier.find_last_of('.')+1);
std::transform( extension.begin(), extension.end(), extension.begin(), static_cast<int (*)(int)>(std::tolower) );
// Selection du loader selon l'extension du fichier à charger
if (extension == "bvh") {
return new BvhLoader();
} else if (extension == "smd") {
return new SkinLoader();
} else if (extension == "extensionDeFouPourPlusTard") {
// Pour extensions futures
return NULL;
} else {
// Extension non gérée
return NULL;
}
}
| [
"jgraulle@74bb1adf-7843-2a67-e58d-b22fe9da3ebb"
] | [
[
[
1,
58
]
]
] |
2465344526506a061b36e43f7eca1c2f9dbd88ce | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_1_013.cpp | aa0926cd4b665254beb6f72a44ceb480f65095a5 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// This sample is taken from the C++ standard 16.3.5.6 [cpp.scope] and was
// slightly modified (removed the '#include' directive)
#define str(s) # s
#define xstr(s) str(s)
#define debug(s, t) printf("x" # s "= %d, x" # t "= %s", \
x ## s, x ## t)
#define INCFILE(n) vers ## n /* from previous #include example */
#define glue(a, b) a ## b
#define xglue(a, b) glue(a, b)
#define HIGHLOW "hello"
#define LOW LOW ", world"
debug(1, 2);
fputs(str(strncmp("abc\0d?", "abc", '\4', "\u1234") /* this goes away */
== 0) str(: @\n), s);
/*#include*/ xstr(INCFILE(2).hpp)
glue(HIGH, LOW);
xglue(HIGH, LOW)
// should expand to
//R #line 22 "t_1_013.cpp"
//R printf("x" "1" "= %d, x" "2" "= %s", x1, x2);
//R fputs("strncmp(\"abc\\0d\?\", \"abc\", '\\4', \"\\u1234\") == 0" ": @\n", s);
//R "vers2.hpp"
//R "hello";
//R "hello" ", world"
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
35
]
]
] |
0a505a8e0020e100e1a0d83f1d5470ebe0dfaf00 | 4ab592fb354f75b42181d5375d485031960aaa7d | /DES_GOBSTG/DES_GOBSTG/Class/Player.cpp | 2a59e185a0d1e2d558f110407142b35f07c87400 | [] | no_license | CBE7F1F65/cca610e2e115c51cef211fafb0f66662 | 806ced886ed61762220b43300cb993ead00949dc | b3cdff63d689e2b1748e9cd93cedd7e8389a7057 | refs/heads/master | 2020-12-24T14:55:56.999923 | 2010-07-23T04:24:59 | 2010-07-23T04:24:59 | 32,192,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,505 | cpp | #include "../header/Player.h"
#include "../header/Process.h"
#include "../header/BGLayer.h"
#include "../header/SE.h"
#include "../header/PlayerBullet.h"
#include "../header/Item.h"
#include "../header/Enemy.h"
#include "../header/Bullet.h"
#include "../header/Chat.h"
#include "../header/BossInfo.h"
#include "../header/EffectIDDefine.h"
#include "../header/SpriteItemManager.h"
#include "../header/FrontDisplayName.h"
#include "../header/FrontDisplay.h"
#include "../header/EventZone.h"
#include "../header/BResource.h"
#include "../header/Scripter.h"
#include "../header/GameInput.h"
#include "../header/GameAI.h"
#define _GAMERANK_MIN 8
#define _GAMERANK_MAX 22
#define _GAMERANK_ADDINTERVAL 9000
#define _GAMERANK_STAGEOVERADD -8
#define _PL_SHOOTCHARGEINFI_1 8
#define _PL_SHOOTCHARGEINFI_2 47
#define _PL_SHOOTCHARGEINFI_3 63
#define _PL_SHOOTCHARGEINFI_4 127
#define _PLAYER_DEFAULETCARDLEVEL_(X) (X?9:8)
#define _PLAYER_DEFAULETBOSSLEVEL_(X) (X?9:8)
#define _CARDLEVEL_ADDINTERVAL 3600
#define _BOSSLEVEL_ADDINTERVAL 3600
#define _CARDLEVEL_MAX 16
#define _BOSSLEVEL_MAX 16
#define _PLAYER_LIFECOSTMAX 2880
#define _PLAYER_COMBOHITMAX 999
#define _PLAYER_SHOOTPUSHOVER 9
#define _PLAYER_SHOOTNOTPUSHOVER 9
#define _PL_SPELLBONUS_BOSS_1 100000
#define _PL_SPELLBONUS_BOSS_2 300000
#define _PL_SPELLBONUS_BOSS_3 500000
Player Player::p[M_PL_MATCHMAXPLAYER];
float Player::lostStack = 0;
bool Player::able = false;
BYTE Player::rank = _GAMERANK_MIN;
int Player::lilycount = 0;
DWORD Player::alltime = 0;
BYTE Player::raisespellstopplayerindex = 0;
BYTE Player::round = 0;
#define _PL_MERGETOPOS_X_(X) (M_GAMESQUARE_CENTER_X_(X))
#define _PL_MERGETOPOS_Y (M_GAMESQUARE_BOTTOM - 64)
#define _PL_SHOOTINGCHARGE_1 0x01
#define _PL_SHOOTINGCHARGE_2 0x02
#define _PL_SHOOTINGCHARGE_3 0x04
#define _PL_SHOOTINGCHARGE_4 0x08
#define _PL_CHARGEZONE_R_2 188.0f
#define _PL_CHARGEZONE_R_3 252.0f
#define _PL_CHARGEZONE_R_4 444.5f
#define _PL_CHARGEZONE_MAXTIME_2 49
#define _PL_CHARGEZONE_MAXTIME_3 65
#define _PL_CHARGEZONE_MAXTIME_4 129
Player::Player()
{
effGraze.exist = false;
effChange.exist = false;
effInfi.exist = false;
effCollapse.exist = false;
effMerge.exist = false;
effBorder.exist = false;
effBorderOn.exist = false;
effBorderOff.exist = false;
sprite = NULL;
spdrain = NULL;
nowID = 0;
ID_sub_1 = 0;
ID_sub_2 = 0;
}
Player::~Player()
{
SpriteItemManager::FreeSprite(&sprite);
SpriteItemManager::FreeSprite(&spdrain);
}
void Player::ClearSet(BYTE _round)
{
x = PL_MERGEPOS_X_(playerindex);
y = PL_MERGEPOS_Y;
round = _round;
for(int i=0;i<PL_SAVELASTMAX;i++)
{
lastx[i] = x;
lasty[i] = y;
lastmx[i] = x;
lastmy[i] = y;
}
timer = 0;
angle = 0;
flag = PLAYER_MERGE;
bSlow = false;
bCharge = false;
bDrain = false;
bInfi = true;
hscale = 1.0f;
vscale = 1.0f;
alpha = 0xff;
diffuse = 0xffffff;
mergetimer = 0;
shottimer = 0;
collapsetimer = 0;
shoottimer = 0;
draintimer = 0;
chargetimer = 0;
slowtimer = 0;
fasttimer = 0;
playerchangetimer = 0;
costlifetimer = 0;
shootchargetimer = 0;
shootingchargeflag = 0;
nowshootingcharge = 0;
fExPoint = 0;
nGhostPoint = 0;
nBulletPoint = 0;
nSpellPoint = 0;
nLifeCost = 0;
fCharge = 0;
if (_round == 0)
{
fChargeMax = PLAYER_CHARGEONE;
winflag = 0;
}
cardlevel = _PLAYER_DEFAULETCARDLEVEL_(_round);
bosslevel = _PLAYER_DEFAULETBOSSLEVEL_(_round);
nowcardlevel = cardlevel;
nowbosslevel = bosslevel;
infitimer = 0;
rechargedelaytimer = 0;
infireasonflag = 0;
shootpushtimer = 0;
shootnotpushtimer = 0;
spellstoptimer = 0;
speedfactor = 1.0f;
// add
// initlife = PLAYER_DEFAULTINITLIFE;
exist = true;
nComboHit = 0;
nComboHitOri = 0;
nComboGage = 0;
nBounceAngle = 0;
drainx = x;
drainy = y;
drainheadangle = 0;
draintimer = 0;
drainhscale = 1;
drainvscale = 0;
draincopyspriteangle = 0;
if (effGraze.exist)
{
effGraze.Stop(true);
effGraze.MoveTo(x, y, 0, true);
}
if (effChange.exist)
{
effChange.Stop(true);
effChange.MoveTo(x, y, 0, true);
}
if (effInfi.exist)
{
effInfi.Stop(true);
effInfi.MoveTo(x, y, 0, true);
}
if (effCollapse.exist)
{
effCollapse.Stop(true);
effCollapse.MoveTo(x, y, 0, true);
}
if (effMerge.exist)
{
effMerge.Stop(true);
effMerge.MoveTo(x, y, 0, true);
}
if (effBorder.exist)
{
effBorder.Stop(true);
effBorder.MoveTo(x, y, 0, true);
}
if (effBorderOn.exist)
{
effBorderOn.Stop(true);
effBorderOn.MoveTo(x, y, 0, true);
}
if (effBorderOff.exist)
{
effBorderOff.Stop(true);
effBorderOff.MoveTo(x, y, 0, true);
}
changePlayerID(nowID, true);
setShootingCharge(0);
esChange.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCHANGE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 3.0f);
esChange.colorSet(0x7fffffff, BLEND_ALPHAADD);
esChange.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esShot.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERSHOT, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 1.2f);
esShot.colorSet(0xccff0000);
esShot.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esPoint.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERPOINT, SpriteItemManager::GetIndexByName(SI_PLAYER_POINT), x, y);
esPoint.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esCollapse.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCOLLAPSE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y);
esCollapse.actionSet(0, 0, 160);
esCollapse.colorSet(0x80ffffff);
}
void Player::ClearRound(BYTE round/* =0 */)
{
raisespellstopplayerindex = 0xff;
if (round)
{
rank += _GAMERANK_STAGEOVERADD;
if (rank < _GAMERANK_MIN)
{
rank = _GAMERANK_MIN;
}
AddLilyCount(-1000);
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
p[i].valueSet(i, round);
}
}
else
{
rank = _GAMERANK_MIN;
lilycount = 0;
alltime = 0;
}
}
//add
void Player::valueSet(BYTE _playerindex, BYTE round)
{
playerindex = _playerindex;
nowID = ID;
ClearSet(round);
initFrameIndex();
UpdatePlayerData();
SetDrainSpriteInfo(x, y);
nLife = initlife;
if (round == 0)
{
lostStack = 0;
}
setFrame(PLAYER_FRAME_STAND);
effGraze.valueSet(EFF_PL_GRAZE, playerindex, *this);
effGraze.Stop();
effChange.valueSet(EFF_PL_CHANGE, playerindex, *this);
effChange.Stop();
effInfi.valueSet(EFF_PL_INFI, playerindex, *this);
effInfi.Stop();
effCollapse.valueSet(EFF_PL_COLLAPSE, playerindex, *this);
effCollapse.Stop();
effMerge.valueSet(EFF_PL_MERGE, playerindex, *this);
effMerge.Stop();
effBorder.valueSet(EFF_PL_BORDER, playerindex, *this);
effBorder.Stop();
effBorderOn.valueSet(EFF_PL_BORDERON, playerindex, *this);
effBorderOn.Stop();
effBorderOff.valueSet(EFF_PL_BORDEROFF, playerindex, *this);
effBorderOff.Stop();
SetAble(true);
}
bool Player::Action()
{
alltime++;
AddLostStack();
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
if (gametime % _CARDLEVEL_ADDINTERVAL == 0)
{
p[i].AddCardBossLevel(1, 0);
}
if (gametime % _BOSSLEVEL_ADDINTERVAL == 0)
{
p[i].AddCardBossLevel(0, 1);
}
DWORD stopflag = Process::mp.GetStopFlag();
bool binstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYER);
bool binspellstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYERSPELL);
GameInput::gameinput[i].updateActiveInput(binspellstop);
if (p[i].exist)
{
if (!binstop && !binspellstop)
{
p[i].action();
}
else if (binspellstop)
{
p[i].actionInSpellStop();
}
else
{
p[i].actionInStop();
}
if (!p[i].exist)
{
return false;
}
}
}
if (gametime % _GAMERANK_ADDINTERVAL == 0)
{
rank++;
if (rank > _GAMERANK_MAX)
{
rank = _GAMERANK_MAX;
}
}
AddLilyCount(0, true);
return true;
}
void Player::action()
{
float nowspeed = 0;
timer++;
alpha = 0xff;
if(timer == 1)
flag |= PLAYER_MERGE;
//savelast
if(lastmx[0] != x || lastmy[0] != y)
{
for(int i=PL_SAVELASTMAX-1;i>0;i--)
{
lastmx[i] = lastmx[i-1];
lastmy[i] = lastmy[i-1];
}
lastmx[0] = x;
lastmy[0] = y;
}
for(int i=PL_SAVELASTMAX-1;i>0;i--)
{
lastx[i] = lastx[i-1];
lasty[i] = lasty[i-1];
}
lastx[0] = x;
lasty[0] = y;
//AI
// GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed, slowspeed, BResource::bres.playerdata[nowID].collision_r);
GameAI::ai[playerindex].SetMove();
//
if(flag & PLAYER_MERGE)
{
if(Merge())
{
flag &= ~PLAYER_MERGE;
}
}
if(flag & PLAYER_SHOT)
{
if(Shot())
{
flag &= ~PLAYER_SHOT;
}
}
if (flag & PLAYER_COSTLIFE)
{
if (CostLife())
{
flag &= ~PLAYER_COSTLIFE;
}
}
if(flag & PLAYER_COLLAPSE)
{
if(Collapse())
{
flag &= ~PLAYER_COLLAPSE;
return;
}
}
if(flag & PLAYER_SLOWCHANGE)
{
if(SlowChange())
{
flag &= ~PLAYER_SLOWCHANGE;
}
}
if(flag & PLAYER_FASTCHANGE)
{
if(FastChange())
{
flag &= ~PLAYER_FASTCHANGE;
}
}
if(flag & PLAYER_PLAYERCHANGE)
{
if(PlayerChange())
{
flag &= ~PLAYER_PLAYERCHANGE;
}
}
if(flag & PLAYER_SHOOT)
{
if(Shoot())
{
flag &= ~PLAYER_SHOOT;
}
}
if(flag & PLAYER_BOMB)
{
if(Bomb())
{
flag &= ~PLAYER_BOMB;
}
}
if(flag & PLAYER_DRAIN)
{
if(Drain())
{
flag &= ~PLAYER_DRAIN;
}
}
if (flag & PLAYER_CHARGE)
{
if (Charge())
{
flag &= ~PLAYER_CHARGE;
}
}
if(flag & PLAYER_GRAZE)
{
if(Graze())
{
flag &= ~PLAYER_GRAZE;
}
}
nLifeCost++;
if (nLifeCost > _PLAYER_LIFECOSTMAX)
{
nLifeCost = _PLAYER_LIFECOSTMAX;
}
if (rechargedelaytimer)
{
rechargedelaytimer--;
}
if (shootchargetimer)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGEONE, playerindex);
PlayerBullet::BuildShoot(playerindex, nowID, shootchargetimer, true);
shootchargetimer--;
}
if (infitimer > 0)
{
infitimer--;
bInfi = true;
}
else if (infitimer == PLAYER_INFIMAX)
{
bInfi = true;
}
else
{
bInfi = false;
}
if (nComboGage)
{
nComboGage--;
if (nComboGage == PLAYER_COMBORESET)
{
AddComboHit(-1, true);
}
else if (!nComboGage)
{
AddSpellPoint(-1);
}
}
for (list<EventZone>::iterator it=EventZone::ezone[playerindex].begin(); it!=EventZone::ezone[playerindex].end(); it++)
{
if (it->timer < 0)
{
continue;
}
if ((it->type) & EVENTZONE_TYPEMASK_PLAYER)
{
if (it->isInRect(x, y, r))
{
if (it->type & EVENTZONE_TYPE_PLAYERDAMAGE)
{
DoShot();
}
if (it->type & EVENTZONE_TYPE_PLAYEREVENT)
{
}
if (it->type & EVENTZONE_TYPE_PLAYERSPEED)
{
speedfactor = it->power;
}
}
}
}
//input
if(!(flag & PLAYER_SHOT || flag & PLAYER_COLLAPSE))
{
if (GameInput::GetKey(playerindex, KSI_SLOW))
{
bSlow = true;
flag &= ~PLAYER_FASTCHANGE;
if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN))
{
if (!(flag & PLAYER_SLOWCHANGE))
{
slowtimer = 0;
flag |= PLAYER_SLOWCHANGE;
}
}
}
else
{
bSlow = false;
flag &= ~PLAYER_SLOWCHANGE;
if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP))
{
if (!(flag & PLAYER_FASTCHANGE))
{
fasttimer = 0;
flag |= PLAYER_FASTCHANGE;
}
}
}
if(bSlow)
{
nowspeed = slowspeed;
}
else
{
nowspeed = speed;
}
nowspeed *= speedfactor;
if(GameInput::GetKey(playerindex, KSI_FIRE))
{
if (!Chat::chatitem.IsChatting())
{
flag |= PLAYER_SHOOT;
}
shootnotpushtimer = 0;
}
else
{
if (shootnotpushtimer < 0xff)
{
shootnotpushtimer++;
}
}
if (shootpushtimer < _PLAYER_SHOOTPUSHOVER)
{
if (GameInput::GetKey(playerindex, KSI_FIRE))
{
shootpushtimer++;
}
else
{
shootpushtimer = 0;
}
}
else
{
if (!GameInput::GetKey(playerindex, KSI_FIRE))
{
bCharge = false;
flag &= ~PLAYER_CHARGE;
shootpushtimer = 0;
}
else
{
if (!rechargedelaytimer)
{
flag &= ~PLAYER_SHOOT;
bCharge = true;
if (shootpushtimer >= _PLAYER_SHOOTPUSHOVER && !(flag & PLAYER_CHARGE))
{
chargetimer = 0;
flag |= PLAYER_CHARGE;
shootpushtimer = 0xff;
}
}
}
}
if (GameInput::GetKey(playerindex, KSI_DRAIN))
{
bDrain = true;
if (GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN))
{
if (!(flag & PLAYER_DRAIN))
{
draintimer = 0;
SetDrainSpriteInfo(x, y, 0, 0);
}
}
flag |= PLAYER_DRAIN;
}
else
{
bDrain = false;
flag &= ~PLAYER_DRAIN;
}
if((GameInput::GetKey(playerindex, KSI_UP) ^ GameInput::GetKey(playerindex, KSI_DOWN)) &&
GameInput::GetKey(playerindex, KSI_LEFT) ^ GameInput::GetKey(playerindex, KSI_RIGHT))
nowspeed *= M_SQUARE_2;
if(GameInput::GetKey(playerindex, KSI_UP))
y -= nowspeed;
if(GameInput::GetKey(playerindex, KSI_DOWN))
y += nowspeed;
if(GameInput::GetKey(playerindex, KSI_LEFT))
{
updateFrame(PLAYER_FRAME_LEFTPRE);
x -= nowspeed;
}
if(GameInput::GetKey(playerindex, KSI_RIGHT))
{
if (!GameInput::GetKey(playerindex, KSI_LEFT))
{
updateFrame(PLAYER_FRAME_RIGHTPRE);
}
else
{
updateFrame(PLAYER_FRAME_STAND);
}
x += nowspeed;
}
if (!GameInput::GetKey(playerindex, KSI_LEFT) && !GameInput::GetKey(playerindex, KSI_RIGHT))
{
updateFrame(PLAYER_FRAME_STAND);
}
}
if(GameInput::GetKey(playerindex, KSI_QUICK) && !(flag & PLAYER_MERGE))
{
callBomb();
}
if (!(flag & PLAYER_MERGE) || mergetimer >= 32)
{
if(x > PL_MOVABLE_RIGHT_(playerindex))
x = PL_MOVABLE_RIGHT_(playerindex);
else if(x < PL_MOVABLE_LEFT_(playerindex))
x = PL_MOVABLE_LEFT_(playerindex);
if(y > PL_MOVABLE_BOTTOM)
y = PL_MOVABLE_BOTTOM;
else if(y < PL_MOVABLE_TOP)
y = PL_MOVABLE_TOP;
}
//AI
GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed*speedfactor, slowspeed*speedfactor, r, BResource::bres.playerdata[nowID].aidraintime);
float aiaimx = _PL_MERGETOPOS_X_(playerindex);
float aiaimy = _PL_MERGETOPOS_Y;
bool tobelow = false;
if (PlayerBullet::activelocked[playerindex] != PBLOCK_LOST)
{
aiaimx = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].x;
aiaimy = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].y + 120;
tobelow = true;
}
else if (PlayerBullet::locked[playerindex] != PBLOCK_LOST)
{
aiaimx = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].x;
aiaimy = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].y;
}
GameAI::ai[playerindex].SetAim(aiaimx, aiaimy, tobelow);
//
//
speedfactor = 1.0f;
if (bInfi && timer % 8 < 4)
{
diffuse = 0xff99ff;
}
else
diffuse = 0xffffff;
esChange.action();
esShot.action();
esPoint.action();
effGraze.MoveTo(x, y);
effGraze.action();
effCollapse.action();
effBorderOn.action();
effBorderOff.action();
if(!(flag & PLAYER_GRAZE))
effGraze.Stop();
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
if (pg[i].exist)
{
pg[i].action();
}
}
}
void Player::actionInSpellStop()
{
spellstoptimer++;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSPELLSTOP, playerindex);
}
void Player::actionInStop()
{
// Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSTOP, playerindex);
}
bool Player::Merge()
{
mergetimer++;
if(mergetimer == 1)
{
SetInfi(PLAYERINFI_MERGE, 60);
if(GameInput::GetKey(playerindex, KSI_SLOW))
{
flag |= PLAYER_SLOWCHANGE;
slowtimer = 0;
flag &= ~PLAYER_FASTCHANGE;
}
else
{
flag |= PLAYER_FASTCHANGE;
fasttimer = 0;
flag &= ~PLAYER_SLOWCHANGE;
}
}
else if (mergetimer <= 24)
{
float interval = mergetimer / 24.0f;
x = INTER(PL_MERGEPOS_X_(playerindex), _PL_MERGETOPOS_X_(playerindex), interval);
y = INTER(PL_MERGEPOS_Y, _PL_MERGETOPOS_Y, interval);
flag &= ~PLAYER_SHOOT;
alpha = INTER(0, 0xff, interval);
}
else if(mergetimer < 60)
{
alpha = 0xff;
}
else if(mergetimer == 60)
{
mergetimer = 0;
return true;
}
return false;
}
bool Player::Shot()
{
shottimer++;
// TODO:
if(bInfi)
{
shottimer = 0;
return true;
}
if(shottimer == 1)
{
// Item::undrainAll();
SE::push(SE_PLAYER_SHOT, x);
}
else if(shottimer == shotdelay)
{
shottimer = 0;
flag |= PLAYER_COSTLIFE;
return true;
}
esShot.hscale = (shotdelay - shottimer) * 4.0f / shotdelay;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOT, playerindex);
return false;
}
bool Player::CostLife()
{
costlifetimer++;
if (costlifetimer == 1)
{
AddLilyCount(-1500);
if (nLife == 1)
{
nLife = 0;
flag |= PLAYER_COLLAPSE;
costlifetimer = 0;
return true;
}
int nLifeCostNum = nLifeCost / 720 + 2;
if (nLife > nLifeCostNum+1)
{
nLife -= nLifeCostNum;
}
else
{
FrontDisplay::fdisp.gameinfodisplay.lastlifecountdown[playerindex] = FDISP_COUNTDOWNTIME;
SE::push(SE_PLAYER_ALERT, x);
nLife = 1;
}
nLifeCost -= 1440;
if (nLifeCost < 0)
{
nLifeCost = 0;
}
SetInfi(PLAYERINFI_COSTLIFE, 120);
if (nLife == 1)
{
AddCharge(0, PLAYER_CHARGEMAX);
}
else
{
AddCharge(0, 130-nLife * 10);
}
nBounceAngle = randt();
}
else if (costlifetimer == 50)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, 10, 0, 0, 10, EVENTZONE_EVENT_NULL, 15.6);
}
else if (costlifetimer == 60)
{
costlifetimer = 0;
return true;
}
else
{
GameInput::SetKey(playerindex, KSI_UP, false);
GameInput::SetKey(playerindex, KSI_DOWN, false);
GameInput::SetKey(playerindex, KSI_LEFT, false);
GameInput::SetKey(playerindex, KSI_RIGHT, false);
// GameInput::SetKey(playerindex, KSI_FIRE, false);
GameInput::SetKey(playerindex, KSI_QUICK, false);
GameInput::SetKey(playerindex, KSI_SLOW, false);
GameInput::SetKey(playerindex, KSI_DRAIN, false);
x += cost(nBounceAngle) * ((60-costlifetimer) / 20.0f);
y += sint(nBounceAngle) * ((60-costlifetimer) / 20.0f);
}
return false;
}
bool Player::Collapse()
{
collapsetimer++;
if(collapsetimer == 1)
{
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, i, p[i].x, p[i].y, 64, EVENTZONE_OVERZONE, 0, 1000, EVENTZONE_EVENT_NULL, 16);
p[i].SetInfi(PLAYERINFI_COLLAPSE, 64);
}
esCollapse.x = x;
esCollapse.y = y;
SE::push(SE_PLAYER_DEAD, x);
effCollapse.MoveTo(x, y , 0, true);
effCollapse.Fire();
p[1-playerindex].winflag |= 1<<round;
}
else if(collapsetimer == 64)
{
x = PL_MERGEPOS_X_(playerindex);
y = PL_MERGEPOS_Y;
for(int i=0;i<PL_SAVELASTMAX;i++)
{
lastx[i] = x;
lasty[i] = y;
lastmx[i] = x;
lastmy[i] = y;
}
timer = 0;
collapsetimer = 0;
vscale = 1.0f;
flag |= PLAYER_MERGE;
AddCharge(0, 130);
// SetInfi(PLAYERINFI_COLLAPSE);
exist = false;
if(GameInput::GetKey(playerindex, KSI_SLOW))
{
flag |= PLAYER_SLOWCHANGE;
slowtimer = 0;
flag &= ~PLAYER_FASTCHANGE;
}
else
{
flag |= PLAYER_FASTCHANGE;
fasttimer = 0;
flag &= ~PLAYER_SLOWCHANGE;
}
effCollapse.Stop();
return true;
}
esCollapse.hscale = collapsetimer / 1.5f;
esCollapse.alpha = (BYTE)((WORD)(0xff * collapsetimer) / 0x3f);
esCollapse.colorSet(0xff0000);
alpha = (0xff - collapsetimer * 4);
vscale = (float)(collapsetimer)/40.0f + 1.0f;
return false;
}
bool Player::Shoot()
{
if(Chat::chatitem.IsChatting())
{
shoottimer = 0;
return true;
}
if (!(flag & PLAYER_SHOT) && !(flag & PLAYER_COSTLIFE))
{
PlayerBullet::BuildShoot(playerindex, nowID, shoottimer);
}
shoottimer++;
//
if(shootnotpushtimer > _PLAYER_SHOOTNOTPUSHOVER)
{
shoottimer = 0;
return true;
}
return false;
}
bool Player::Drain()
{
draintimer++;
bDrain = true;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERDRAIN, playerindex);
return false;
}
bool Player::Bomb()
{
BYTE ncharge;
BYTE nchargemax;
GetNCharge(&ncharge, &nchargemax);
if (nchargemax > 1)
{
BYTE nChargeLevel = shootCharge(nchargemax, true);
if (nChargeLevel == nchargemax)
{
AddCharge(-PLAYER_CHARGEMAX, -PLAYER_CHARGEMAX);
}
else
{
AddCharge((nChargeLevel-nchargemax)*PLAYER_CHARGEONE, (nChargeLevel-nchargemax)*PLAYER_CHARGEONE);
}
}
return true;
}
bool Player::SlowChange()
{
if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN))
slowtimer = 0;
bSlow = true;
slowtimer++;
if(slowtimer == 1)
{
ResetPlayerGhost();
SE::push(SE_PLAYER_SLOWON, x);
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
pg[i].timer = 0;
}
}
else if(slowtimer == 16)
{
esPoint.colorSet(0xffffffff);
slowtimer = 0;
return true;
}
esPoint.actionSet(0, 0, (24 - slowtimer) * 25);
esPoint.colorSet(((slowtimer*16)<<24)+0xffffff);
return false;
}
bool Player::FastChange()
{
if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP))
fasttimer = 0;
bSlow = false;
fasttimer++;
if(fasttimer == 1)
{
ResetPlayerGhost();
SE::push(SE_PLAYER_SLOWOFF, x);
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
pg[i].timer = 0;
}
}
else if(fasttimer == 16)
{
esPoint.colorSet(0x00ffffff);
fasttimer = 0;
return true;
}
esPoint.colorSet(((0xff-fasttimer*16)<<24)+0xffffff);
return false;
}
bool Player::Charge()
{
chargetimer++;
if (chargetimer == 1)
{
SE::push(SE_PLAYER_CHARGEON, x);
}
BYTE nChargeLevel = AddCharge(chargespeed);
if (!GameInput::GetKey(playerindex, KSI_FIRE))
{
shootCharge(nChargeLevel);
chargetimer = 0;
fCharge = 0;
if (nChargeLevel > 0)
{
rechargedelaytimer = rechargedelay;
}
return true;
}
bCharge = true;
return false;
}
bool Player::PlayerChange()
{
if(GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN))
playerchangetimer = 0;
playerchangetimer++;
if(playerchangetimer == 1)
{
}
else if(playerchangetimer == 16)
{
playerchangetimer = 0;
return true;
}
esChange.colorSet(0x3030ff | (((16-playerchangetimer) * 16)<<16));
return false;
}
void Player::changePlayerID(WORD toID, bool moveghost/* =false */)
{
nowID = toID;
ResetPlayerGhost(moveghost);
UpdatePlayerData();
}
bool Player::Graze()
{
effGraze.Fire();
SE::push(SE_PLAYER_GRAZE, x);
return true;
}
void Player::DoEnemyCollapse(float x, float y, BYTE type)
{
float addcharge = nComboHitOri / 128.0f + 1.0f;
if (addcharge > 2.0f)
{
addcharge = 2.0f;
}
AddComboHit(1, true);
AddCharge(0, addcharge);
enemyData * edata = &(BResource::bres.enemydata[type]);
AddExPoint(edata->expoint, x, y);
int addghostpoint;
if (edata->ghostpoint < 0)
{
addghostpoint = nComboHitOri + 3;
if (addghostpoint > 28)
{
addghostpoint = 28;
}
}
else
{
addghostpoint = edata->ghostpoint;
}
AddGhostPoint(addghostpoint, x, y);
int addbulletpoint;
float _x = x + randtf(-4.0f, 4.0f);
float _y = y + randtf(-4.0f, 4.0f);
if (edata->bulletpoint < 0)
{
addbulletpoint = nComboHitOri * 3 + 27;
if (addbulletpoint > 60)
{
addbulletpoint = 60;
}
}
else
{
addbulletpoint = edata->bulletpoint;
}
AddBulletPoint(addbulletpoint, _x, _y);
int addspellpoint;
if (edata->spellpoint == -1)
{
if (nComboHitOri == 1)
{
addspellpoint = 20;
}
else
{
addspellpoint = nComboHitOri * 30 - 20;
if (addspellpoint > 3000)
{
addspellpoint = 3000;
}
}
}
else if (edata->spellpoint == -2)
{
if (nComboHitOri == 1)
{
addspellpoint = 2000;
}
else
{
addspellpoint = (nComboHitOri + 4) * 200;
if (addspellpoint > 11000)
{
addspellpoint = 11000;
}
}
}
else
{
addspellpoint = edata->spellpoint;
}
AddSpellPoint(addspellpoint);
}
void Player::DoGraze(float x, float y)
{
if(!(flag & (PLAYER_MERGE | PLAYER_SHOT | PLAYER_COLLAPSE)))
{
flag |= PLAYER_GRAZE;
}
}
void Player::DoPlayerBulletHit(int hitonfactor)
{
if (hitonfactor < 0)
{
AddComboHit(-1, true);
}
}
void Player::DoSendBullet(float x, float y, int sendbonus)
{
for (int i=0; i<sendbonus; i++)
{
AddComboHit(1, false);
AddGhostPoint(2, x, y);
AddBulletPoint(3, x, y);
int addspellpoint = nComboHitOri * 9;
if (addspellpoint > 1000)
{
addspellpoint = 1000;
}
AddSpellPoint(addspellpoint);
}
}
void Player::DoShot()
{
if (!bInfi && !(flag & (PLAYER_SHOT | PLAYER_COLLAPSE)))
{
flag |= PLAYER_SHOT;
AddComboHit(-1, true);
AddSpellPoint(-1);
}
}
void Player::DoItemGet(WORD itemtype, float _x, float _y)
{
switch (itemtype)
{
case ITEM_GAUGE:
AddCharge(0, PLAYER_CHARGEMAX);
break;
case ITEM_BULLET:
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDITEMBULLET, playerindex);
// Item::SendBullet(1-playerindex, _x, _y, EFFSPSET_SYSTEM_SENDITEMBULLET);
break;
case ITEM_EX:
AddBulletPoint(1, _x, _y);
AddExPoint(100, _x, _y);
break;
case ITEM_POINT:
AddSpellPoint(70000+rank*7000);
break;
}
}
void Player::GetNCharge(BYTE * ncharge, BYTE * nchargemax)
{
if (ncharge)
{
*ncharge = (BYTE)(fCharge/PLAYER_CHARGEONE);
}
if (nchargemax)
{
*nchargemax = (BYTE)(fChargeMax/PLAYER_CHARGEONE);
}
}
void Player::GetSpellClassAndLevel(BYTE * spellclass, BYTE * spelllevel, int _shootingchargeflag)
{
BYTE usingshootingchargeflag = shootingchargeflag;
if (_shootingchargeflag > 0)
{
usingshootingchargeflag = _shootingchargeflag;
}
if (spellclass)
{
if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
if ((usingshootingchargeflag & _PL_SHOOTINGCHARGE_3) || (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2))
{
*spellclass = 4;
}
else
{
*spellclass = 3;
}
}
else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_3)
{
*spellclass = 2;
}
else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2)
{
*spellclass = 1;
}
else
{
*spellclass = 0;
}
}
if (spelllevel)
{
if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
*spelllevel = nowbosslevel;
}
else if(usingshootingchargeflag)
{
*spelllevel = nowcardlevel;
}
else
{
*spelllevel = 0;
}
}
}
void Player::ResetPlayerGhost(bool move /* = false */)
{
int tid = nowID;
tid *= PLAYERGHOSTMAX * 2;
if (bSlow)
{
tid += PLAYERGHOSTMAX;
}
for (int i=0; i<PLAYERGHOSTMAX; i++)
{
pg[i].valueSet(playerindex, tid+i, move);
}
}
void Player::Render()
{
if (spdrain && bDrain)
{
SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle), drainhscale, drainvscale);
if (draincopyspriteangle)
{
SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle+draincopyspriteangle), drainhscale, drainvscale);
}
}
if (sprite)
{
sprite->SetColor(alpha<<24|diffuse);
SpriteItemManager::RenderSpriteEx(sprite, x, y, 0, hscale, vscale);
}
}
void Player::RenderEffect()
{
effGraze.Render();
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
if (pg[i].exist)
{
pg[i].Render();
}
}
if(flag & PLAYER_PLAYERCHANGE)
{
esChange.Render();
}
if(flag & PLAYER_SHOT)
esShot.Render();
effBorderOff.Render();
if(bSlow || flag & PLAYER_FASTCHANGE)
{
esPoint.Render();
esPoint.headangle = -esPoint.headangle;
esPoint.Render();
esPoint.headangle = -esPoint.headangle;
}
if(flag & PLAYER_COLLAPSE)
esCollapse.Render();
effCollapse.Render();
}
void Player::callCollapse()
{
if (flag & PLAYER_COLLAPSE)
{
return;
}
flag |= PLAYER_COLLAPSE;
collapsetimer = 0;
}
bool Player::callBomb()
{
if (Chat::chatitem.IsChatting() || (flag & PLAYER_COLLAPSE))
{
return false;
}
return Bomb();
}
void Player::callSlowFastChange(bool toslow)
{
if (toslow)
{
GameInput::SetKey(playerindex, KSI_SLOW);
}
else
{
GameInput::SetKey(playerindex, KSI_SLOW, false);
}
}
void Player::callPlayerChange()
{
flag |= PLAYER_PLAYERCHANGE;
playerchangetimer = 0;
}
void Player::setShootingCharge(BYTE _shootingchargeflag)
{
if (!_shootingchargeflag)
{
shootingchargeflag = 0;
}
else
{
shootingchargeflag |= _shootingchargeflag;
if (shootingchargeflag & _PL_SHOOTINGCHARGE_1)
{
shootchargetimer = BResource::bres.playerdata[nowID].shootchargetime;
}
if (_shootingchargeflag & ~_PL_SHOOTINGCHARGE_1)
{
nowshootingcharge = _shootingchargeflag;
if (_shootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
nowbosslevel = bosslevel;
}
else
{
nowcardlevel = cardlevel;
}
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGE, playerindex);
}
}
}
BYTE Player::shootCharge(BYTE nChargeLevel, bool nodelete)
{
if (flag & PLAYER_COLLAPSE)
{
return 0;
}
if (!nChargeLevel)
{
return 0;
}
if (nChargeLevel > 3 && nChargeLevel < 7 && Enemy::bossindex[1-playerindex] != 0xff)
{
if (nChargeLevel == 4)
{
return shootCharge(3, nodelete);
}
else if (nChargeLevel == 6)
{
return shootCharge(7, nodelete);
}
return 0;
}
setShootingCharge(0);
int chargezonemaxtime=1;
float chargezoner=0;
switch (nChargeLevel)
{
case 1:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_1);
setShootingCharge(_PL_SHOOTINGCHARGE_1);
// AddCardBossLevel(1, 0);
break;
case 2:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_2);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_2);
AddCardBossLevel(1, 0);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_2;
chargezoner = _PL_CHARGEZONE_R_2;
break;
case 3:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_3);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_3);
AddCardBossLevel(1, 0);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_3;
chargezoner = _PL_CHARGEZONE_R_3;
break;
case 4:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_4);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(0, 1);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_4;
chargezoner = _PL_CHARGEZONE_R_4;
break;
case 5:
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(0, 1);
break;
case 6:
setShootingCharge(_PL_SHOOTINGCHARGE_3);
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(1, 1);
break;
case 7:
setShootingCharge(_PL_SHOOTINGCHARGE_3);
AddCardBossLevel(1, 0);
break;
}
if (nChargeLevel > 1)
{
raisespellstopplayerindex = playerindex;
spellstoptimer = 0;
Process::mp.SetStop(FRAME_STOPFLAG_SPELLSET|FRAME_STOPFLAG_PLAYERINDEX_0|FRAME_STOPFLAG_PLAYERINDEX_1, PL_SHOOTINGCHARGE_STOPTIME);
if (chargezoner)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, chargezonemaxtime, 0, 0, 10, EVENTZONE_EVENT_NULL, chargezoner/chargezonemaxtime, -2, SpriteItemManager::GetIndexByName(SI_PLAYER_CHARGEZONE), 400);
}
if (nChargeLevel < 5)
{
AddCharge(-PLAYER_CHARGEONE*(nChargeLevel-1), -PLAYER_CHARGEONE*(nChargeLevel-1));
}
AddLilyCount(-500);
FrontDisplay::fdisp.OnShootCharge(playerindex, nowshootingcharge);
}
return nChargeLevel;
}
void Player::SendEx(BYTE playerindex, float x, float y)
{
int _esindex = EffectSp::Build(EFFSPSET_SYSTEM_SENDEXATTACK, playerindex, EffectSp::senditemexsiid, x, y);
if (_esindex >= 0)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDEX, playerindex);
SE::push(SE_BULLET_SENDEX, x);
}
}
void Player::AddExPoint(float expoint, float x, float y)
{
fExPoint += expoint;
float fexsend = fExSendParaB + fExSendParaA * rank;
if (fexsend < fExSendMax)
{
fexsend = fExSendMax;
}
if (fExPoint >= fexsend)
{
AddExPoint(-fexsend, x, y);
SendEx(1-playerindex, x, y);
}
}
void Player::AddGhostPoint(int ghostpoint, float x, float y)
{
nGhostPoint += ghostpoint;
if (nGhostPoint >= 60-rank*1.5f)
{
if (nBulletPoint >= 10)
{
AddGhostPoint(-(60-rank*2), x, y);
AddBulletPoint(-10, x, y);
Enemy::SendGhost(1-playerindex, x, y, EFFSPSET_SYSTEM_SENDGHOST);
}
}
}
void Player::AddBulletPoint(int bulletpoint, float x, float y)
{
nBulletPoint += bulletpoint * 4 / 3;
if (nBulletPoint >= 120-rank*4)
{
AddBulletPoint(-(120-rank*4), x, y);
BYTE setID = EFFSPSET_SYSTEM_SENDBLUEBULLET;
if (randt(0, 2) == 0)
{
setID = EFFSPSET_SYSTEM_SENDREDBULLET;
}
Bullet::SendBullet(1-playerindex, x, y, setID);
}
}
void Player::AddSpellPoint(int spellpoint)
{
if (spellpoint < 0)
{
nSpellPoint = 0;
return;
}
spellpoint = spellpoint * rank / 10 + spellpoint;
int spellpointone = spellpoint % 10;
if (spellpointone)
{
spellpoint += 10-spellpointone;
}
if (nSpellPoint < _PL_SPELLBONUS_BOSS_1 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_1 ||
nSpellPoint < _PL_SPELLBONUS_BOSS_2 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_2)
{
shootCharge(5);
}
else if (nSpellPoint < _PL_SPELLBONUS_BOSS_3 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_3)
{
shootCharge(6);
}
nSpellPoint += spellpoint;
if (nSpellPoint > PLAYER_NSPELLPOINTMAX)
{
nSpellPoint = PLAYER_NSPELLPOINTMAX;
}
}
void Player::AddComboHit(int combo, bool ori)
{
if (combo < 0)
{
nComboHit = 0;
nComboHitOri = 0;
return;
}
nComboHit += combo;
if (nComboHit > PLAYER_NCOMBOHITMAX)
{
nComboHit = PLAYER_NCOMBOHITMAX;
}
if (ori)
{
nComboHitOri += combo;
if (nComboHitOri > PLAYER_NCOMBOHITMAX)
{
nComboHitOri = PLAYER_NCOMBOHITMAX;
}
}
if (nComboGage < 74)
{
nComboGage += 30;
if (nComboGage < 74)
{
nComboGage = 74;
}
}
else if (nComboGage < 94)
{
nComboGage += 5;
}
else
{
nComboGage += 2;
}
if (nComboGage > PLAYER_COMBOGAGEMAX)
{
nComboGage = PLAYER_COMBOGAGEMAX;
}
}
BYTE Player::AddCharge(float addcharge, float addchargemax)
{
BYTE ncharge;
BYTE nchargemax;
GetNCharge(&ncharge, &nchargemax);
float addchargemaxval = addchargemax;
if (addchargemax > 0)
{
addchargemaxval = addchargemax * BResource::bres.playerdata[nowID].addchargerate;
}
fChargeMax += addchargemaxval;
if (fChargeMax > PLAYER_CHARGEMAX)
{
fChargeMax = PLAYER_CHARGEMAX;
}
if (fChargeMax < 0)
{
fChargeMax = 0;
}
fCharge += addcharge;
if (fCharge > fChargeMax)
{
fCharge = fChargeMax;
}
if (fCharge < 0)
{
fCharge = 0;
}
BYTE nchargenow;
BYTE nchargemaxnow;
GetNCharge(&nchargenow, &nchargemaxnow);
if (nchargenow > ncharge)
{
SE::push(SE_PLAYER_CHARGEUP);
}
if (nchargemaxnow > nchargemax)
{
FrontDisplay::fdisp.gameinfodisplay.gaugefilledcountdown[playerindex] = FDISP_COUNTDOWNTIME;
}
return nchargenow;
}
void Player::AddLilyCount(int addval, bool bytime/* =false */)
{
if (bytime)
{
if (gametime < 5400)
{
AddLilyCount(gametime/1800+3);
}
else
{
AddLilyCount(7);
}
}
lilycount += addval;
if (lilycount > 10000)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDLILY, rank);
AddLilyCount(-10000);
}
else if (lilycount < 0)
{
lilycount = 0;
}
}
void Player::AddCardBossLevel(int cardleveladd, int bossleveladd)
{
cardlevel += cardleveladd;
bosslevel += bossleveladd;
if (cardlevel > _CARDLEVEL_MAX)
{
cardlevel = _CARDLEVEL_MAX;
}
if (bosslevel > _BOSSLEVEL_MAX)
{
bosslevel = _BOSSLEVEL_MAX;
}
}
| [
"CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b"
] | [
[
[
1,
1759
]
]
] |
939fe39915c8932ccd85c4252e8311740ea7162f | 9b402d093b852a574dccb869fbe4bada1ef069c6 | /code/foundation/terrain/terrainSystem.cpp | f5da460263045675ba9d52c9878d9ec182760a7d | [] | no_license | wangscript007/foundation-engine | adb24d4ccc932d7a8f8238170029de6d2db0cbfb | 2982b06d8f6b69c0654e0c90671aaef9cfc6cc40 | refs/heads/master | 2021-05-27T17:26:15.178095 | 2010-06-30T22:06:45 | 2010-06-30T22:06:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,759 | cpp | #include "terrainSystem.h"
using namespace Foundation;
using namespace Foundation::Terrain;
using namespace ET;
Terrain::TerrainManager& Terrain::TerrainManager::getSingleton()
{
static Terrain::TerrainManager m_Singleton;
return m_Singleton;
}
void Terrain::TerrainManager::create(Ogre::SceneManager *_pSceneMgr, Ogre::Camera *_pCamera)
{
m_pSceneMgr = _pSceneMgr;
// create terrain manager
mTerrainMgr = new ET::TerrainManager(_pSceneMgr);
mTerrainMgr->setLODErrorMargin(1, _pCamera->getViewport()->getActualHeight());
mTerrainMgr->setUseLODMorphing(true, 0.1, "morphFactor");
// create a fresh, mid-high terrain for editing
ET::TerrainInfo terrainInfo(129, 129, vector<float>(129*129, 0.5f));
// set position and size of the terrain
terrainInfo.setExtents(Ogre::AxisAlignedBox(-750, 0, -750, 750, 0, 750));
// now render it
mTerrainMgr->createTerrain(terrainInfo);
// create the splatting manager
mSplatMgr = new ET::SplattingManager("ETSplatting", "ET", 128, 128, 3);
// specify number of splatting textures we need to handle
mSplatMgr->setNumTextures(6);
// create a manual lightmap texture
Ogre::TexturePtr lightmapTex = Ogre::TextureManager::getSingleton().createManual(
"ETLightmap", "ET", Ogre::TEX_TYPE_2D, 128, 128, 1, Ogre::PF_BYTE_RGB);
Ogre::Image lightmap;
ET::createTerrainLightmap(terrainInfo, lightmap, 128, 128, Ogre::Vector3(1, -1, 1), Ogre::ColourValue::White,
Ogre::ColourValue(0.3, 0.3, 0.3));
lightmapTex->getBuffer(0, 0)->blitFromMemory(lightmap.getPixelBox(0, 0));
// load the terrain material and assign it
Ogre::MaterialPtr material (Ogre::MaterialManager::getSingleton().getByName("ETTerrainMaterial"));
mTerrainMgr->setMaterial(material);
}
gmtl::Vec3f Terrain::TerrainManager::getRayIntersection(const char *sSceneManagerName, const char *sCameraName, gmtl::Vec2f _nWorldPoint, gmtl::Vec2f _nScreenWidth)
{
Ogre::Camera* pCamera;
Ogre::Ray uRayIntersection;
Ogre::RaySceneQuery* uRaySceneQuery;
Ogre::RaySceneQueryResult uResult;
Ogre::RaySceneQueryResult::iterator itrResult;
float nX, nY;
if (!m_pSceneMgr->hasCamera(sCameraName)) {
f_printf("[TerrainManager] Error: Camera %s not found.\n", sCameraName);
return gmtl::Vec3f(0, 0, 0);
}
pCamera = m_pSceneMgr->getCamera(sCameraName);
f_printf("[TerrainManager] DEBUG: Getting Ray Intersection (Screen = %f, %f), (Point = %f, %f)\n", _nScreenWidth[0], _nScreenWidth[1], _nWorldPoint[0], _nWorldPoint[1]);
nX = _nWorldPoint[0] / _nScreenWidth[0];
nY = _nWorldPoint[1] / _nScreenWidth[1];
uRayIntersection = pCamera->getCameraToViewportRay(nX, nY);
uRaySceneQuery = m_pSceneMgr->createRayQuery(uRayIntersection);
uRaySceneQuery->setRay(uRayIntersection);
uRaySceneQuery->setSortByDistance(true);
uRaySceneQuery->setQueryMask(TERRAIN_MASK);
uRaySceneQuery->setQueryTypeMask(Ogre::SceneManager::WORLD_GEOMETRY_TYPE_MASK);
uResult = uRaySceneQuery->execute();
for (itrResult = uResult.begin(); itrResult != uResult.end(); itrResult++) {
Ogre::Vector3 nIntersectionPoint = uRayIntersection.getPoint(itrResult->distance);
return gmtl::Vec3f(nIntersectionPoint[0], nIntersectionPoint[1], nIntersectionPoint[2]);
}
f_printf("[TerrainSystem] Warning: Ray Intersection didn't hit terrain.\n");
return gmtl::Vec3f(0, 0, 0);
}
Terrain::TerrainManager::TerrainManager()
{
}
Terrain::TerrainManager::~TerrainManager()
{
}
| [
"drivehappy@a5d1a9aa-f497-11dd-9d1a-b59b2e1864b6"
] | [
[
[
1,
96
]
]
] |
327935b96a30f24995f2a759044493ccafeb988d | 86bb1666e703b6be9896166d1b192a20f4a1009c | /source/bbn/BBN_Plot.cpp | 3da6e73ef3aefd8fcafe7b46974c882ab093126f | [] | no_license | aggronerd/Mystery-Game | 39f366e9b78b7558f5f9b462a45f499060c87d7f | dfd8220e03d552dc4e0b0f969e8be03cf67ba048 | refs/heads/master | 2021-01-10T21:15:15.318110 | 2010-08-22T09:16:08 | 2010-08-22T09:16:08 | 2,344,888 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,156 | cpp |
#include "../misc/logging.h"
#include "BBN_Plot.h"
#include "BBN_Option.h"
#include "BBN_Decision.h"
#include "BBN_Exception.h"
#include "BBN_Random.h"
/**
* Copies defined results from another bayes net.
*
* @param existing
*/
void BBN_Plot::clone_results(BBN_Plot* existing)
{
//Duplicate results
std::vector<BBN_Decision*>::iterator it_source;
for(it_source = existing->get_decisions()->begin(); it_source != existing->get_decisions()->end(); ++it_source)
{
if((*it_source)->has_generated_result())
{
//TODO: Change so it doesn't resolve bayesian net with each set command.
this->set_result((*it_source)->get_name(),(*it_source)->get_result()->get_name());
}
}
}
BBN_Plot::BBN_Plot(const CL_String8& file_name)
{
DEBUG_MSG("BBN_Plot::BBN_Plot(const CL_String8&) - Called.")
_bn_current_solution = 0x0;
_bn_join_tree = 0x0;
_bn = 0x0;
_next_decision_id = 0;
_file_name = file_name;
CL_File xmlFile(file_name); //TODO: Catch if cannot open
DEBUG_MSG("BBN_Plot::BBN_Plot(const char*) - Creating CL_DomDocument.")
CL_DomDocument document(xmlFile);
DEBUG_MSG("BBN_Plot::BBN_Plot(const char*) - Getting plot element.")
CL_DomElement root = document.get_document_element();
//Retrieve attributes
_name = root.get_attribute("name");
//Parse children:
DEBUG_MSG(CL_String8("BBN_Plot::BBN_Plot(const char*) - Processing children for '") + _name + "'.")
int decisions_element_count = 0;
int decision_element_count = 0;
CL_DomNode cur = root.get_first_child();
//TODO: Compare with XML schema definition.
/*
* Loop through first elements.
*/
while (!cur.is_null())
{
if (cur.get_node_name() == CL_String8("decisions"))
{
//'decisions' element encountered
decisions_element_count ++;
CL_DomNode cur2 = cur.get_first_child();
/*
* Look for 'decision elements.
*/
while (!cur2.is_null())
{
if (cur2.get_node_name() == CL_String8("decision"))
{
BBN_Decision* decision = new BBN_Decision(this);
CL_DomElement element = cur2.to_element();
decision->load_from_xml(element);
add_decision(decision);
decision_element_count++;
}
cur2 = cur2.get_next_sibling();
}
}
cur = cur.get_next_sibling();
}
/*
* Validation afterwards to report errors.
*/
if(decisions_element_count != 1)
{
throw CL_Exception("Invalid number of 'decisions' elements in plot XML.");
}
if(decision_element_count == 0)
{
throw CL_Exception("No 'decision' elements found in plot XML.");
}
}
BBN_Plot::~BBN_Plot()
{
DEBUG_MSG("BBN_Plot::~BBN_Plot() - Called.")
// Delete all decisions
std::vector<BBN_Decision*>::iterator it_de;
for(it_de = _decisions.begin(); it_de != _decisions.end(); ++it_de)
delete (*it_de);
_decisions.clear();
clear_bn();
BBN_Random::reset();
}
void BBN_Plot::set_name(CL_String8 new_name)
{
_name = new_name;
}
CL_String8 BBN_Plot::get_name()
{
return(_name);
}
/**
* Adds the pointer to an instance of BBN_Decision to _decisions.
*/
void BBN_Plot::add_decision(BBN_Decision* decision)
{
DEBUG_MSG("BBN_Plot::add_decision(BBN_Decision*) - Called.")
_decisions.push_back(decision);
}
/**
* Prepares dlib's bayes net by defining nodes and probabilities.
*/
void BBN_Plot::prepare_bn()
{
//Destroy existing bayes net.
clear_bn();
//Create the bayes net.
_bn = new dlib::directed_graph<dlib::bayes_node>::kernel_1a_c();
long number_of_decisions = decisions_count();
get_bn()->set_number_of_nodes(number_of_decisions);
std::vector<BBN_Decision*>::iterator it_de;
for(it_de = _decisions.begin(); it_de != _decisions.end(); ++it_de)
(*it_de) -> prepare_bn_node(get_bn());
for(it_de = _decisions.begin(); it_de != _decisions.end(); ++it_de)
(*it_de) -> load_bn_probabilities(get_bn());
_bn_join_tree = new join_tree_type();
// Populate the join_tree with data from the bayesian network.
dlib::create_moral_graph(*(_bn), *(_bn_join_tree));
create_join_tree( *(_bn_join_tree), *(_bn_join_tree));
update_bn_solution();
}
long BBN_Plot::decisions_count()
{
return(_decisions.size());
}
/**
* Returns a pointer to the decision object with the
* name specified in the parameter. If it cannot be
* found the function returns a null pointer (0x0).
*
* Currently only iterates through all decisions.
* Therefore is slow for instances when there are
* many decisions. However allows names to be
* changed. TODO: What is the value of this given
* that linkages between objects are still defined
* by string paths given in the XML file and not by
* pointers?
*/
BBN_Decision* BBN_Plot::get_decision(const CL_String8& name)
{
std::vector<BBN_Decision*>::iterator it_decision;
for(it_decision = _decisions.begin(); it_decision != _decisions.end(); ++it_decision)
if((*it_decision)->get_name() == name)
return(*it_decision);
return(0x0);
}
dlib::directed_graph<dlib::bayes_node>::kernel_1a_c* BBN_Plot::get_bn()
{
return(_bn);
}
/**
* Updates the Bayes Net solution to reflect changes in bn.
*/
void BBN_Plot::update_bn_solution()
{
if(_bn != 0x0 && _bn_join_tree != 0x0)
{
// Obtain a solution to the bayesian network.
if(_bn_current_solution != 0x0)
delete _bn_current_solution;
_bn_current_solution = new dlib::bayesian_network_join_tree(*(_bn), *(_bn_join_tree));
}
else
{
throw(BBN_Exception("BBN_Plot::update_bn_solution() called when _bn or _bn_join_tree is not defined."));
}
}
/**
* Destroys all bayes net objects.
*/
void BBN_Plot::clear_bn()
{
if(_bn_join_tree != 0x0)
{
_bn_join_tree->clear();
delete(_bn_join_tree);
_bn_join_tree = 0x0;
}
if(_bn_current_solution != 0x0)
{
delete(_bn_current_solution);
_bn_current_solution = 0x0;
}
if(_bn != 0x0)
{
_bn->clear();
delete(_bn);
_bn = 0x0;
}
}
/**
* Returns the result for the decision. Returns null (0x0) if the decision isn't found.
*/
BBN_Option* BBN_Plot::query_result(CL_String8 decision_name)
{
BBN_Decision* decision = get_decision(decision_name);
if(decision != 0x0)
{
BBN_Option* result = decision->get_result();
return(result);
}
else
{
return(0x0);
}
}
dlib::bayesian_network_join_tree* BBN_Plot::get_bn_current_solution()
{
return(_bn_current_solution);
}
std::vector<BBN_Decision*>* BBN_Plot::get_decisions()
{
return(&_decisions);
}
/**
* Returns a pointer to an option defined by path. If it
* cannot be found then the function returns null (0x0).
*/
BBN_Option* BBN_Plot::get_option(const CL_String8& path)
{
int n = path.find_first_of('.',0);
CL_String8 decision_name = path.substr(0,n);
CL_String8 option_name = path.substr(n+1,path.size()-n-1);
BBN_Decision* decision = get_decision(decision_name);
if(decision == 0x0)
{
DEBUG_MSG("BBN_Option* BBN_Plot::get_option(const CL_String8&) - Attempt to get decision '" + decision_name + "' failed." )
return(0x0);
}
else
{
BBN_Option* option = decision->get_option(option_name);
if(option == 0x0)
{
DEBUG_MSG("BBN_Option* BBN_Plot::get_option(const CL_String8&) - Attempt to get option '" + option_name + "' failed." )
return(0x0);
}
else
{
return(option);
}
}
}
/**
* Sets the value of a decision. Returns true if successful.
*/
bool BBN_Plot::set_result(const CL_String8& decision_path, const CL_String8& value)
{
bool result = false;
BBN_Decision* decision = get_decision(decision_path);
if(decision != 0x0)
{
result = decision->set_result(value);
}
return(result);
}
unsigned long BBN_Plot::get_next_decision_id()
{
unsigned long id = _next_decision_id;
_next_decision_id += 1;
return(id);
}
CL_String8 BBN_Plot::get_file_name()
{
return(_file_name);
}
| [
"[email protected]"
] | [
[
[
1,
330
]
]
] |
b72ea33cad98f94b0db721103736d40fdd955632 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/2560/2560.cpp | 0758e661937b31575cad4a6c088fb01bd43f1b1a | [] | no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | #include "iostream"
#include "stdio.h"
#include "math.h"
using namespace std;
struct point
{
double x,y;
int link;
};
double dis[101][101];
int comp(const void *a,const void *b)
{
point *pa,*pb;
pa=(point*)a;
pb=(point *)b;
if(pa->x>pb->x) return 1;
else if(pa->x==pb->x) return 0;
else return -1;
}
int main()
{
int n;
cin>>n;
double sum=0.0;
point *pt=new point[n];
memset(pt,0,n*sizeof(point));
int i,j;
for(i=0;i<n;i++)
cin>>pt[i].x>>pt[i].y;
qsort(pt,n,sizeof(point),comp);
pt[0].link=1;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++)
dis[i][j]=sqrt((pt[i].x-pt[j].x)*(pt[i].x-pt[j].x)+(pt[i].y-pt[j].y)
*(pt[i].y-pt[j].y));
}
for(i=1;i<n;i++){
double min=1234567890.0;
int a,b;
for(j=1;j<n;j++){
if(pt[j].link==1) continue;
for(int k=0;k<j;k++){
if(pt[k].link==0) continue;
if(dis[k][j]<min){
min=dis[k][j];
a=k;b=j;
}
}
for(int k=j+1;k<n;k++){
if(pt[k].link==0) continue;
if(dis[j][k]<min){
min=dis[j][k];
a=k;b=j;
}
}
}
sum+=min;
pt[b].link=1;
}
printf("%.2f\n",sum);
delete []pt;
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
67
]
]
] |
ca290c3ec9bfe134c37a62a526bf3fb300d6a283 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkBoostKruskalMinimumSpanningTree.h | 1218a701448e009ed5270292c7a06f74e6c71c15 | [
"BSD-3-Clause"
] | permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,597 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkBoostKruskalMinimumSpanningTree.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkBoostKruskalMinimumSpanningTree - Contructs a minimum spanning
// tree from a graph and the weighting array
//
// .SECTION Description
//
// This vtk class uses the Boost Kruskal Minimum Spanning Tree
// generic algorithm to perform a minimum spanning tree creation given
// a weighting value for each of the edges in the input graph.
//
// .SECTION See Also
// vtkGraph vtkBoostGraphAdapter
#ifndef __vtkBoostKruskalMinimumSpanningTree_h
#define __vtkBoostKruskalMinimumSpanningTree_h
#include "vtkStdString.h" // For string type
#include "vtkVariant.h" // For variant type
#include "vtkSelectionAlgorithm.h"
class VTK_INFOVIS_EXPORT vtkBoostKruskalMinimumSpanningTree : public vtkSelectionAlgorithm
{
public:
static vtkBoostKruskalMinimumSpanningTree *New();
vtkTypeMacro(vtkBoostKruskalMinimumSpanningTree, vtkSelectionAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Set the name of the edge-weight input array, which must name an
// array that is part of the edge data of the input graph and
// contains numeric data. If the edge-weight array is not of type
// vtkDoubleArray, the array will be copied into a temporary
// vtkDoubleArray.
vtkSetStringMacro(EdgeWeightArrayName);
// Description:
// Set the output selection type. The default is to use the
// the set of minimum spanning tree edges "MINIMUM_SPANNING_TREE_EDGES". No
// other options are defined.
vtkSetStringMacro(OutputSelectionType);
// Description:
// Whether to negate the edge weights. By negating the edge
// weights this algorithm will give you the 'maximal' spanning
// tree (i.e. the algorithm will try to create a spanning tree
// with the highest weighted edges). Defaulted to Off.
// FIXME: put a real definition in...
void SetNegateEdgeWeights(bool value);
vtkGetMacro(NegateEdgeWeights, bool);
vtkBooleanMacro(NegateEdgeWeights, bool);
protected:
vtkBoostKruskalMinimumSpanningTree();
~vtkBoostKruskalMinimumSpanningTree();
int RequestData(
vtkInformation *,
vtkInformationVector **,
vtkInformationVector *);
int FillInputPortInformation(
int port, vtkInformation* info);
int FillOutputPortInformation(
int port, vtkInformation* info);
private:
char* EdgeWeightArrayName;
char* OutputSelectionType;
bool NegateEdgeWeights;
float EdgeWeightMultiplier;
vtkBoostKruskalMinimumSpanningTree(const vtkBoostKruskalMinimumSpanningTree&); // Not implemented.
void operator=(const vtkBoostKruskalMinimumSpanningTree&); // Not implemented.
};
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
] | [
[
[
1,
96
]
]
] |
f517b5fa177c717b89a0ee4e1cdb3a8a9e7c02ba | 197ac28d1481843225f35aff4aa85f1909ef36bf | /examples/GPIO_IAR_STM32/main.cpp | 2c437e501d6900260eaec6e91a9edd04b11fb06c | [
"BSD-3-Clause"
] | permissive | xandroalmeida/Mcucpp | 831e1088eb38dfcf65bfb6fb3205d4448666983c | 6fc5c8d5b9839ade60b3f57acc78a0ed63995fca | refs/heads/master | 2020-12-24T12:13:53.497692 | 2011-11-21T15:36:03 | 2011-11-21T15:36:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,750 | cpp |
// list of used IO ports
#define USE_PORTA
#define USE_PORTB
#define USE_PORTC
// NOTE that you need to add library platform independent and platform specific
// folders to compiler include files search paths:
// '../../mcucpp' and '../../mcucpp/ARM/STM32' respectively for this example
// defination of TPin class
#include <iopins.h>
// defination of PinList class
#include <pinlist.h>
// all IO stuff are in namespce
using namespace IO;
// working with ports
void Ports()
{
// set all pins in port to output
Porta::SetConfiguration(0xff, Porta::Out);
// write a value to port
Porta::Write(0x55);
// set pins with mask
Porta::Set(0xAA);
// clear pins with mask
Porta::Clear(0xF0);
// togle pins with mask
Porta::Toggle(0xFF);
uint8_t clearMask = 0x0F;
uint8_t outputValue = 0x03;
Porta::ClearAndSet(clearMask, outputValue);
// read out register
// set all pins in port to input
Porta::SetConfiguration(0xff, Porta::In);
uint8_t value = Porta::Read();
// read input register
value = Porta::PinRead();
// template versions of port manipulations for writing constant values
// these functions are guaranteed to be inlined for maximum speed
Porta::SetConfiguration<0xff, Porta::Out>();
Porta::Set<0xAA>();
Porta::Clear<0xF0>();
Porta::Toggle<0xFF>();
const uint8_t clearMask2 = 0x0F;
const uint8_t outputValue2 = 0x03;
Porta::ClearAndSet<clearMask2, outputValue2>();
}
// working with individual pins
void IndividualPins()
{
// definition of one IO pin: pin 1 at port
typedef TPin<Porta, 1> Pin1;
// or you can use predefined short name
// typedef Pa1 Pin1;
// Configure pin as output
Pin1::SetConfiguration(Pin1::Port::Out);
// set pin to logical 1
Pin1::Set();
// set pin to logical 0
Pin1::Clear();
// toggle pin state
Pin1::Toggle();
// Configure pin as input
Pin1::SetConfiguration(Pin1::Port::In);
// check pin state
if(Pin1::IsSet())
{
// do something
}
// definition of one IO pin: pin 1 at PORTA with inverted logic
// ie. 'Set' will write logical 0 to pin and 'Clear' - logical 1.
// reading (IsSet) is not inverted
typedef InvertedPin<Porta, 1> Pin2;
// or you can use predefined short name
// typedef Pa1Inv Pin2;
// Configure pin as output
Pin2::SetConfiguration(Pin2::Port::Out);
// set pin to logical 1
Pin2::Set();
// set pin to logical 0
Pin2::Clear();
// toggle pin state
Pin2::Toggle();
// Configure pin as input
Pin2::SetConfiguration(Pin2::Port::In);
// check pin state
if(Pin2::IsSet())
{
// do something
}
}
// wotking with groups of pins - pin lists
void PinLists()
{
// Definition of group of IO pins which acts like a virtual IO port.
// One group can contain up to 32 pins from different ports.
// Pins in the group can have an arbitrary order.
typedef PinList<Pa1, Pb0, Pa2, Pb1, Pc3, Pc4, Pc5> Group1;
// You can include inverted pins to the group
typedef PinList<Pa1, Pb0Inv, Pa2, Pb1, Pc3Inv, Pc4, Pc5> Group2;
// PinList has interface similar to IO port interface,
// but is is a little simplified
Group1::SetConfiguration(Group1::Out);
// write a value to group
Group1::Write(0x55);
// set pins with mask
Group1::Set(0xAA);
// clear pins with mask
Group1::Clear(0xF0);
// set all pins in group to input
Group1::SetConfiguration(Group1::In);
// read input register
uint8_t value = Group1::PinRead();
// If you have a constant value to write to group,
// use template varsions of writing functions.
// They are much faster and smaller, since most of things are evaluated
// at compile time and only actual Read/Modify/Write operation will take place in runtime.
Group1::SetConfiguration<Group1::Out, 0xff>();
Group1::Write<0x55>();
Group1::Set<0xAA>();
Group1::Clear<0xF0>();
// Individual pins in group can be accessed in this way:
// Set pin 1 in group (indexing starts whith 0)
Group1::Pin<1>::Set();
// you can 'typdef' it for best readability
typedef Group1::Pin<1> Pin1;
Pin1::Clear();
// Toggle the last pin in the group
const int lastPinIndex = Group1::Length - 1;
Group1::Pin<lastPinIndex>::Toggle();
// You can take a slice of group, it will be another PinList
const int startingIndex = 4;
const int sliceLenth = 3;
typedef Group1::Slice<startingIndex, sliceLenth> LastTreePins;
// Note that sliced pins will have they origin bit position in the input value.
// ie. other pins in group will be just masked out
LastTreePins::Write(0x70);
}
int main()
{
// enable port clocking
Porta::Enable();
Portb::Enable();
Portc::Enable();
Ports();
IndividualPins();
PinLists();
}
| [
"[email protected]"
] | [
[
[
1,
175
]
]
] |
8741841dda6fc3b2c6d3d17d612d6d5628d5d109 | 1e299bdc79bdc75fc5039f4c7498d58f246ed197 | /App/ClientHandlerThread.cpp | a3b5b196f99b31aaf58242616e706c2855132826 | [] | no_license | moosethemooche/Certificate-Server | 5b066b5756fc44151b53841482b7fa603c26bf3e | 887578cc2126bae04c09b2a9499b88cb8c7419d4 | refs/heads/master | 2021-01-17T06:24:52.178106 | 2011-07-13T13:27:09 | 2011-07-13T13:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,855 | cpp | //--------------------------------------------------------------------------------
//
// Copyright (c) 2000 MarkCare Solutions
//
// Programming by Rich Schonthal
//
//--------------------------------------------------------------------------------
#include "stdafx.h"
#include <LockedSocket.h>
#include "SecurityServer.h"
#include "ClientSubSystem.h"
#include "SSIOSubSystem.h"
#include "DBSubSystem.h"
#include "SSConfigBackup.h"
#include "ClientHandlerThread.h"
#include "CertificateMaster.h"
#include "AccessToken.h"
#include "SSQuickMail.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#if 0
#define RECEIVECERTWAIT INFINITE
#define RECEIVEPORTCONFIRM INFINITE
#else
#define RECEIVECERTWAIT 6000
#define RECEIVEPORTCONFIRM 6000
#endif
//--------------------------------------------------------------------------------
LPCTSTR CClientHandlerThread::m_pMsgHello = "000 MCMS_SECSERV1000\n";
LPCTSTR CClientHandlerThread::m_pMsgServerDown = "999 SERVDWN\n";
// max clients that one client handler thread will support
int CClientHandlerThread::m_nMaxClients = 32;
// the max # of minutes a connection is allowed to be idle before its deleted
int CClientHandlerThread::m_nMaxIdleTime = 3;
//--------------------------------------------------------------------------------
CClientHandlerThread::CClientHandlerThread(CSystemObject* pParent)
: CSSThread(pParent)
{
}
//--------------------------------------------------------------------------------
CClientHandlerThread::~CClientHandlerThread()
{
MSG msg;
while(::PeekMessage(&msg, NULL, CClientSubSystem::MSG_NEWCONNECTION, CClientSubSystem::MSG_NEWCONNECTION, PM_REMOVE))
delete (CSmallSocket*) msg.wParam;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::Init()
{
SetThreadPriority(THREAD_PRIORITY_HIGHEST);
return true;
}
//--------------------------------------------------------------------------------
void CClientHandlerThread::OnMessage(UINT nMsg, WPARAM hSocket, LPARAM)
{
CSmallSocket socket;
socket.Attach((SOCKET) hSocket);
if(nMsg == WM_QUIT || nMsg != CClientSubSystem::MSG_NEWCONNECTION)
return;
ULONG nState = GetState();
// if we're not in a run state then tell the client that the server is down
bool bAccepting = (nState == STATE_RUN) && GetSystem()->IsServing() && GetSystem()->IsLicensed();
LPCTSTR pMsg = bAccepting ? m_pMsgHello : m_pMsgServerDown;
long nLen = strlen(pMsg);
// send the hello msg
if(! socket.Send(pMsg, CSmallSocket::WAITFORWOULDBLOCK, 2000))
{
GetIO()->FormatOutput(IOMASK_ERR, "1001 socket error %ld", ::WSAGetLastError());
return;
}
// we told the client that the server is down so exit
if(! bAccepting)
return;
CCertificate cert;
if(! ReceiveCertificate(cert, socket))
return;
int nCmd = cert.GetCommand();
switch(nCmd)
{
case CCertificateCommands::CMD_BACKUPCONNECT:
DoBackupServerConnect(cert, socket);
break;
case CCertificateCommands::CMD_NEW:
if(cert.GetId() == 0)
DoNewCertificate(cert, socket);
else
DoAquireToken(cert, socket);
break;
case CCertificateCommands::CMD_REFRESH:
DoRefreshCertificate(cert, socket);
break;
case CCertificateCommands::CMD_RELEASE:
DoReleaseCertificate(cert, socket);
break;
default:
GetIO()->Output(IOMASK_ERR|IOMASK_CONST, "Illegal command received");
break;
}
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::ReceiveCertificate(CCertificate& rCert, CSmallSocket& socket)
{
if(! socket.WaitForBytesAvail(RECEIVECERTWAIT))
return false;
char sTemp[4096];
int nLen = socket.Receive(sTemp, 4096, CSmallSocket::WAITFORDATA, RECEIVECERTWAIT);
if(nLen < 1)
return false;
sTemp[nLen] = 0;
rCert.Decode(sTemp, nLen);
return true;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::DoBackupServerConnect(const CCertificate& cert, CSmallSocket& socket)
{
CString sAddr;
UINT nPort;
if(! socket.GetPeerName(sAddr, nPort))
{
GetIO()->Output(IOMASK_ERR|IOMASK_CONST, "Error obtaining client IP address");
return false;
}
CSSConfigBackup config;
CString sTemp;
if(sAddr == config.m_sIP)
sTemp = "MainOk";
else
sTemp = "GoAway";
if(! socket.Send(sTemp, CSmallSocket::WAITFORWOULDBLOCK, 10000))
{
GetIO()->Output(IOMASK_ERR|IOMASK_CONST, "Send error DBCS 1");
return false;
}
if(! GetSystem()->IsBackupRunning())
{
CSSQuickMail* pMail = new CSSQuickMail;
pMail->m_sSubject = "IMP: Backup Connection Made";
pMail->m_sMsg.Format("%s %s\r\n", (LPCTSTR) sAddr, (LPCTSTR) CTime::GetCurrentTime().Format("%c"));
GetIO()->SendQuickMail(pMail);
}
GetSystem()->SetBackupIsRunning();
return true;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::DoNewCertificate(const CCertificate& cert, CSmallSocket& socket)
{
CString sAddr;
UINT nPort;
if(! socket.GetPeerName(sAddr, nPort))
{
GetIO()->Output(IOMASK_ERR|IOMASK_CONST, "Error obtaining client IP address");
return false;
}
CCertificateMaster* pCert = GetDB()->IssueCertificate(cert, sAddr);
if(pCert == NULL)
{
GetIO()->Output(IOMASK_1|IOMASK_DEBUG|IOMASK_CONST, "IssueCertificate returns NULL (1)");
return false;
}
char temp[4096];
int nLen = pCert->Encode(temp);
// send the new certificate
if(socket.Send(temp, nLen, CSmallSocket::WAITFORWOULDBLOCK, 10000) != nLen)
{
GetIO()->Output(IOMASK_1|IOMASK_DEBUG|IOMASK_CONST, "error certificate not sent");
return false;
}
GetIO()->FormatOutput(IOMASK_1|IOMASK_DEBUG, "issused certificate %ld", pCert->GetId());
return true;
}
//--------------------------------------------------------------------------------
using namespace CCertificateCommands;
//--------------------------------------------------------------------------------
bool CClientHandlerThread::DoAquireToken(CCertificate& cert, CSmallSocket& socket)
{
UINT nInPort;
CString sAddr;
if(! socket.GetPeerName(sAddr, nInPort))
{
GetIO()->Output(IOMASK_ERR, "Error obtaining client IP address");
return false;
}
CCertificateMaster* pCert = GetDB()->FindCertMaster(cert);
// only issue tokens when we are serving
if(GetSystem()->IsServing() && pCert != NULL)
GetDB()->IssueToken(pCert, cert.GetCommandParam());
char temp[4096];
int nLen = 0;
if(pCert == NULL)
{
cert.SetCommand(CMD_REFRESH, ERR_NO_SUCH_CERT);
nLen = cert.Encode(temp, false);
}
else
nLen = pCert->Encode(temp, true);
// send the new certificate
return socket.Send(temp, nLen, CSmallSocket::WAITFORWOULDBLOCK, 2000) == nLen;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::DoRefreshCertificate(const CCertificate& cert, CSmallSocket& socket)
{
UINT nInPort;
CString sAddr;
if(! socket.GetPeerName(sAddr, nInPort))
{
GetIO()->Output(IOMASK_ERR, "Error obtaining client IP address");
return false;
}
SetThreadPriority(THREAD_PRIORITY_TIME_CRITICAL);
CCertificateMaster* pCert = NULL;
// only refresh when we are serving
if(GetSystem()->IsServing())
pCert = GetDB()->RefreshCertificate(cert, sAddr);
char temp[4096];
int nLen = 0;
if(pCert == NULL)
{
CCertificateMaster cert;
cert.SetCommand(CMD_REFRESH, ERR_NO_SUCH_CERT);
nLen = cert.Encode(temp, false);
}
else
nLen = pCert->Encode(temp, false);
// send the new certificate
bool bRv = socket.Send(temp, nLen, CSmallSocket::WAITFORWOULDBLOCK, 2000) == nLen;
SetThreadPriority(THREAD_PRIORITY_HIGHEST);
return bRv;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::DoReleaseCertificate(const CCertificate& cert, CSmallSocket& socket)
{
int nTokenId = cert.GetCommandParam();
if(nTokenId == 0)
{
UINT nInPort;
CString sAddr;
if(! socket.GetPeerName(sAddr, nInPort))
{
GetIO()->Output(IOMASK_ERR, "Error obtaining client IP address");
return false;
}
GetDB()->ReleaseCertificate(cert, sAddr);
}
else
GetDB()->ReleaseToken(cert, nTokenId);
return true;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::OnActivate()
{
return true;
}
//--------------------------------------------------------------------------------
bool CClientHandlerThread::OnDeactivate()
{
CThreadObject::OnDeactivate();
return true;
}
| [
"[email protected]"
] | [
[
[
1,
321
]
]
] |
38e41beaf72a59fa0045a88491767ff989c573f2 | 583d876ec2e0577f03d27033c44a731cb5883219 | /Robot_Control/robot_control.cpp | 20d955b74630380a4146eedd62a36d0e9aadaa3d | [] | no_license | BGCX067/eyerobot-hg-to-git | 6950df8a76cd536682843eb6c1232833735be7ee | f25681efe96f205fb0dac74b0072a5ac08070467 | refs/heads/master | 2016-09-01T08:50:07.262989 | 2010-07-09T18:40:57 | 2010-07-09T18:40:57 | 48,706,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,935 | cpp | // Robot_Control.cpp: implementation of the Robot_Control class.
//
//////////////////////////////////////////////////////////////////////
#include "Robot_Control.h"
#include <stdio.h>
#include <math.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/* world position in mm*/
#define CENTERX 584.8
#define CENTERY 0.0
#define CENTERZ 508.0
#define CENTERROTX 0.0
#define CENTERROTY 0.0
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Robot_Control::Robot_Control()
{
}
Robot_Control::~Robot_Control()
{
//Robbie->LockAxes(alAllAxes);
Robbie->UnlockAxes(alAllAxes);
Robbie->ControlRelease();
}
int Robot_Control::Initialize()
{
counterX=0;
counterY=0;
counterZ=0;
toolX=0;
toolY=0;
toolZ=0;
current_xrotation = 0;
current_yrotation = 0;
if FAILED(CoInitialize (NULL))
{
MessageBoxA(NULL,(LPCSTR)"CoInitialize() failed.","Error", MB_OK);
fprintf(stderr,"CoInitialize() failed.");
exit(0);
}
try
{
// initialize robot pointer variables
Robbie = ICRSRobotPtr(__uuidof(CRSRobot));
TestV3 = ICRSV3FilePtr(__uuidof(CRSV3File));
Robbie->put_Units( utMetric );
//Robbie->put_Units( utEnglish );
TheSpeed = 80;
//get control of robot
Robbie->ControlGet();
// open V3File
TestV3->Open("reach_eye.v3", v3fReadOnly);
//TestV3->Open("metr.v3", v3fReadOnly);
//retrieve variables from V3 file
locationtemp = TestV3->GetLocation("initial", 0, 0);
// close file
TestV3->Close();
//Unlock all the axes...
Robbie->UnlockAxes(alAllAxes);
for (int i = 0;i<100;i++){
for (int j=0;j<100;j++){
for (int k=0;k<100;k++){
grid[i][j][k] = ICRSLocationPtr(__uuidof(CRSLocation));
grid[i][j][k] = locationtemp;
grid[i][j][k]->x=CENTERX;
grid[i][j][k]->y=CENTERY;
grid[i][j][k]->z=CENTERZ;
grid[i][j][k]->xrot=CENTERROTX;
grid[i][j][k]->yrot=CENTERROTY;
}}}
}
catch (_com_error MyError)
{
// display error message
sprintf(WorkString, "The following error occurred during initialization --\n%s", (LPCTSTR) MyError.Description());
fprintf(stderr,"%s",WorkString);
MessageBoxA(NULL,(LPCSTR) MyError.Description(),"The following error occurred during initialization --", MB_OK);
// MessageBox(NULL,WorkString,"Error", MB_OK);
//AfxMessageBox(WorkString);
//close the program of the parent...or let them try something else...
Robbie->UnlockAxes(alAllAxes);
Robbie->ControlRelease();
return 0;
}
return 1;
}
ICRSLocationPtr Robot_Control::GetLocation( _bstr_t V3FileName, _bstr_t Variable ){
TestV3->Open( V3FileName, v3fReadOnly);
//retrieve variables from V3 file
locationtemp = TestV3->GetLocation(Variable, 0, 0);
// close file
TestV3->Close();
return locationtemp;
}
int Robot_Control::Compute_Grid(int points,int pointsz, float x, float y, float z, float spacing)
{
int i, j, k; //counter variables temporary
//int validStatus;
//check the boundaries of the given world axis and the grid - is it in bounds?
//instantiate a v3 object, create a file, and let's add variables to it...
//transform the world coordinate to the given origin relative to the robot base...
//generate the grid...
FILE *fp1 = fopen("zztest.txt","wt");
/*in sensor coords: i = z, j = x, k = y*/
/*in robot coords: i = x, j = y, k = z*/
for (i=0;i<points;i++){
for (j=0;j<points;j++){
for (k=0;k<pointsz;k++){
mygrid[i][j][k].x = (float) (spacing*i+x);
mygrid[i][j][k].y = (float) (spacing*j+y);
mygrid[i][j][k].z = (float) (spacing*k+z);
mygrid[i][j][k].xrot = 0.0;
mygrid[i][j][k].yrot = 0.0;
printf("Vals: x: %f y: %f z: %f\n", mygrid[i][j][k].x,mygrid[i][j][k].y,mygrid[i][j][k].z);
fprintf(fp1,"%f\t%f\t%f\n", mygrid[i][j][k].x,mygrid[i][j][k].y,mygrid[i][j][k].z);
}
}
}
fprintf(fp1,"\nCorrected coordinates\n");
float lsens = 10.25; //length of sensor in in. 26cm or 10.25 in
for (int i=0;i<points;i++){
for (int j=0;j<points;j++){
for (int k=0;k<pointsz;k++){
float r1 = atan2(mygrid[i][j][k].y, mygrid[i][j][k].x);
float r2 = sqrt( pow(mygrid[i][j][k].x,2)+pow(mygrid[i][j][k].y,2)) - lsens;
float u = r2 * cos( r1 ) ;
float v = r2 * sin( r1 );
mygrid[i][j][k].x = u;
mygrid[i][j][k].y = v;
printf("New Vals: x: %f y: %f z: %f\n", mygrid[i][j][k].x,mygrid[i][j][k].y,mygrid[i][j][k].z);
fprintf(fp1,"%f\t%f\t%f\n", mygrid[i][j][k].x,mygrid[i][j][k].y,mygrid[i][j][k].z);
}}}
fclose(fp1);
return (points*3);
}
int Robot_Control::MoveToGridPoint(int xcounter, int ycounter, int zcounter)
{
//locationtemp->PutFlags( ACTIVEROBOTLib::locFlags(16) );
locationtemp->x = (float)mygrid[xcounter][ycounter][zcounter].x;
locationtemp->y = (float)mygrid[xcounter][ycounter][zcounter].y;
locationtemp->z = (float)mygrid[xcounter][ycounter][zcounter].z;
locationtemp->xrot = (float)mygrid[xcounter][ycounter][zcounter].xrot;
locationtemp->yrot = (float)mygrid[xcounter][ycounter][zcounter].yrot;
VARIANT_BOOL metr = locationtemp->IsMetric;
locFlags flags = locFlags();
locationtemp->get_Flags(&flags);
try
{
Robbie->PutSpeed(TheSpeed);
Robbie->Move(locationtemp);
//Robbie->Move(grid[xcounter][ycounter][zcounter]);
}
catch (_com_error MyError)
{
// display error message
sprintf(WorkString, "The following error occurred in MoveToGridPoint --\n%s", (LPCTSTR) MyError.Description());
fprintf(stderr,"%s",WorkString);
MessageBoxA(NULL,(LPCSTR) MyError.Description(),"The following error occurred in MoveToGridPoint", MB_OK);
//AfxMessageBox(WorkString);
return 0;
}
counterX = xcounter;
counterY = ycounter;
counterZ = zcounter;
return 1;
}
int Robot_Control::Get_X_Counter(void)
{
if (counterX<0 || counterX>1000)
{
fprintf(stderr,"CounterX is not initialized yet");
//AfxMessageBox("CounterX is not initialized yet", MB_OK, -1);
//MessageBox(NULL,"CounterX is not initialized yet","Error", MB_OK);
return -1;
}
else
return (counterX);
}
int Robot_Control::Get_Y_Counter()
{
if (counterY<0 || counterY>1000)
{
fprintf(stderr,"CounterY is not initialized yet");
//AfxMessageBox("CounterY is not initialized yet", MB_OK, -1);
// MessageBox(NULL,"CounterY is not initialized yet","Error", MB_OK);
return -1;
}
else
return (counterY);
}
int Robot_Control::Get_Z_Counter()
{
if (counterZ<0 || counterZ>1000)
{
fprintf(stderr,"CounterZ is not initialized yet");
//AfxMessageBox("CounterZ is not initialized yet", MB_OK, -1);
//MessageBox(NULL,"CounterZ is not initialized yet","Error", MB_OK);
return -1;
}
else
return (counterZ);
}
float Robot_Control::Get_X_Position()
{
return (grid[counterX][counterY][counterZ]->x);
}
float Robot_Control::Get_Y_Position()
{
return (grid[counterX][counterY][counterZ]->y);
}
float Robot_Control::Get_Z_Position()
{
return (grid[counterX][counterY][counterZ]->z);
}
int Robot_Control::MoveTo_Actual_Point(float x, float y, float z, float rotatex, float rotatey)
{
//locationtemp = ICRSLocationPtr(__uuidof(CRSLocation));
locationtemp->Putx(x);
locationtemp->Puty(y);
locationtemp->Putz(z);
locationtemp->Putxrot(rotatex);
locationtemp->Putyrot(rotatey);
float x1 = locationtemp->Getx();
float y1 = locationtemp->Gety();
float z1 = locationtemp->Getz();
float xr1 = locationtemp->Getxrot();
float xy1 = locationtemp->Getyrot();
locationtemp->GetIsValid();
/*locationtemp->x = (float)x;
locationtemp->y = (float)y;
locationtemp->z = (float)z;
locationtemp->xrot =(float)rotatex;
locationtemp->yrot =(float)rotatey;*/
VARIANT_BOOL validloc = false;
validloc = locationtemp->GetIsValid();
if( validloc ){
try
{
Robbie->PutSpeed(TheSpeed);
//Robbie->MoveStraight(locationtemp); //not interpolated movement?
//Robbie->raw_Move(locationtemp); //no error msgs
Robbie->Move(locationtemp);
//Robbie->Approach(locationtemp,10);
}
catch (_com_error MyError)
{
// display error message
sprintf(WorkString, "The following error occurred during movement to actual point --\n%s", (LPCTSTR) MyError.Description());
fprintf(stderr,"%s",(LPCTSTR) MyError.Description());
//fprintf(stderr,"%s",WorkString);
//AfxMessageBox(WorkString);
::MessageBoxA(NULL,(LPCSTR) MyError.Description(),"Error", MB_OK);
//close the program of the parent...or let them try something else...
return 0;
}
}
else{ //if invalid location
fprintf(stderr,"Point %f %f %f is invalid\n",x,y,z);
}
return 1;
}
void Robot_Control::Ready( void ){
Robbie->Ready();
}
int Robot_Control::GPIO(int pin, int onoff)
{
try
{ /* OR outputs and incoming pin for on*/
if( onoff ){
long out = Robbie->Outputs[1];
out = ((long) 1 << (pin - 1)) | out; //(long) pow( (float) 2, (pin-1) ) | out;
Robbie->PutOutputs(1, out);
}
/* NAND outputs and incoming pin for on*/
else{
long out = Robbie->Outputs[1];
out = out & (long)((long) 0xFFFF - (long) (1 << (pin - 1)));//((long) pow( (float) 2, (pin-1) ));
Robbie->PutOutputs(1, out);
}
}
catch (_com_error MyError)
{
// display error message
sprintf(WorkString, "The following error occurred during GPIO output change --\n%s", (LPCTSTR) MyError.Description());
fprintf(stderr,"%s",WorkString);
::MessageBoxA(NULL,(LPCSTR) MyError.Description(),"Error", MB_OK);
//AfxMessageBox(WorkString);
//MessageBox(NULL,WorkString,"Error", MB_OK);
//close the program of the parent...or let them try something else...
return 0;
}
return 1;
}
| [
"devnull@localhost"
] | [
[
[
1,
359
]
]
] |
a73a66d5db35a9b950f460f4ba45d050d788ae8e | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/gui/gl_widget_3/GL_widget_3.cpp | 6d3b66374ed3175f3636e8323c8303485c4e3d6c | [] | 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 | 14,858 | cpp | /* This source file is part of Mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* More info: http://www.agg.ethz.ch/~miklosb/mesecina
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: GL_widget_3.cpp 737 2009-05-16 15:40:46Z miklosb $
*/
#include <GL/glew.h>
#include <gui/gl_widget_3/GL_draw_layer_3.h>
#include <gui/gl_widget_3/GL_widget_3.h>
#include <gui/gl_widget/Visualization_layer.h>
#include <gui/app/static/Application_settings.h>
#include <constants.h>
//#include "../textfile.h"
#include <algorithm>
#include <iostream>
#include <math.h>
#include <GL/glut.h>
#include <QtXml/QDomElement>
//double round(double x) {
// if(x>=0.5){return ceil(x);}else{return floor(x);}
//}
GL_widget_3::GL_widget_3(QWidget * parent) : QGLViewer(parent), use_display_lists(true) {
QSettings settings;
if (!settings.contains("camera-projection-orthographic"))
settings.setValue("camera-projection-orthographic", false);
Application_settings::add_setting("camera-projection-orthographic", AS_BOOL);
if (!settings.contains("camera-projection-perspective-fieldofview"))
settings.setValue("camera-projection-perspective-fieldofview", M_PI/4);
Application_settings::add_setting("camera-projection-perspective-fieldofview", AS_DOUBLE);
if (!settings.contains("sphere-rendering-resolution"))
settings.setValue("sphere-rendering-resolution", SPHERE_RENDERING_RENDERING);
Application_settings::add_setting("sphere-rendering-resolution", AS_INTEGER);
layers.clear();
default_bounding_box = true;
bounding_xmin = bounding_xmax = bounding_ymin = bounding_ymax = bounding_zmin = bounding_zmax = 0;
want_repaint =false;
sphere_dl = 0;
sphere_wire_dl = 0;
}
void GL_widget_3::request_repaint() {
want_repaint = true;
}
void GL_widget_3::postSelection(const QPoint& point) {
// std::cout << "post selection" << std::endl;
bool found;
qglviewer::Vec selectedPoint = camera()->pointUnderPixel(point, found);
// std::cout << " The selected point is: (" << selectedPoint.x << "," << selectedPoint.y << "," << selectedPoint.z << ")" << std::endl;
std::vector<Visualization_layer *>::iterator it, end=layers.end();
for (it=layers.begin(); it!=end; it++) {
GL_draw_layer_3 *l = (GL_draw_layer_3*)*it;
if (l->is_active()) {
l->selection_at(selectedPoint.x, selectedPoint.y, selectedPoint.z);
}
}
}
//GL_widget_3::~GL_widget_3() {}
void GL_widget_3::update_bounding_box(const Box3D& r) {
if (default_bounding_box || r.xmin < bounding_xmin) bounding_xmin = r.xmin;
if (default_bounding_box || r.xmax > bounding_xmax) bounding_xmax = r.xmax;
if (default_bounding_box || r.ymin < bounding_ymin) bounding_ymin = r.ymin;
if (default_bounding_box || r.ymax > bounding_ymax) bounding_ymax = r.ymax;
if (default_bounding_box || r.zmin < bounding_zmin) bounding_zmin = r.zmin;
if (default_bounding_box || r.zmax > bounding_zmax) bounding_zmax = r.zmax;
default_bounding_box = false;
}
void GL_widget_3::set_window_to_boundingbox() {
showEntireScene();
}
void GL_widget_3::export_to_image(QString image_filepath) {
//setSnapshotFormat("PNG");
//saveSnapshot(image_filepath, true);
bool old_dlists = get_use_display_lists();
set_use_display_lists(false);
repaint();
QImage image = grabFrameBuffer();
set_use_display_lists(old_dlists);
repaint();
image.save(image_filepath,"PNG");
std::cout << "Image written to " << image_filepath.toStdString() << std::endl;
}
void GL_widget_3::export_to_vector(QString file_name) {
if (file_name.toUpper().endsWith(".PS")) setSnapshotFormat("PS");
if (file_name.toUpper().endsWith(".PDF")) setSnapshotFormat("PDF");
saveSnapshot(file_name, true);
// something different here
}
void GL_widget_3::print_to_printer() {
QPrinter printer;
QPrintDialog print_dialog(&printer/*, this*/);
if (print_dialog.exec() == QDialog::Accepted) {
//something different here
}
}
void GL_widget_3::attach(Visualization_layer *l) {
layers.push_back(l);
l->attach(this);
// l->activate();
}
void GL_widget_3::detach(Visualization_layer *l) {
std::vector<Visualization_layer*>::iterator to_delete = std::find(layers.begin(),layers.end(),l);
if (to_delete!=layers.end())
layers.erase(to_delete);
}
void GL_widget_3::repaintGL() {
updateGL();
emit repaitedGL();
}
void GL_widget_3::resizeGL( int w, int h ) {
emit widget_resized_to(QRect(0,0,w,h));
QGLViewer::resizeGL(w,h);
}
void GL_widget_3::init() {
setBackgroundColor(Qt::white);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND); // Enable Blending
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Type Of Blending To Use
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); // Make round points, not square points
// glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Antialias the lines
glDisable( GL_COLOR_MATERIAL );
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE);
glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE );
// glShadeModel(GL_FLAT);
glEnable(GL_NORMALIZE);
setMouseBinding(Qt::LeftButton, ZOOM_ON_PIXEL, true);
// setMouseBinding(Qt::LeftButton, RAP_FROM_PIXEL, true);
setMouseBinding(Qt::RightButton, ZOOM_TO_FIT, true);
setMouseBinding(Qt::ALT + Qt::LeftButton, ALIGN_CAMERA, true);
// setMouseBinding(Qt::RightButton, RAP_IS_CENTER, true);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50);
setManipulatedFrame(0);
set_camera_projection();
create_sphere_display_list();
}
void GL_widget_3::set_camera_projection() {
QSettings settings;
if (settings.value("camera-projection-orthographic").toBool())
camera()->setType(qglviewer::Camera::ORTHOGRAPHIC);
else camera()->setType(qglviewer::Camera::PERSPECTIVE);
camera()->setFieldOfView(settings.value("camera-projection-perspective-fieldofview").toDouble());
}
void GL_widget_3::add_point_to_selection(double x, double y, double z) {
emit s_add_point_to_selection(x,y,z);
}
void GL_widget_3::remove_point_from_selection(double x, double y, double z) {
emit s_remove_point_from_selection(x,y,z);
}
void GL_widget_3::clear_selection() {
emit s_clear_selection();
}
void GL_widget_3::create_sphere_display_list() {
// generate a display list for a sphere
if (sphere_dl!=0) glDeleteLists(sphere_dl,1);
sphere_dl = glGenLists(1);
QSettings settings;
glNewList(sphere_dl,GL_COMPILE);
glutSolidSphere(1, settings.value("sphere-rendering-resolution").toInt(), settings.value("sphere-rendering-resolution").toInt());
glEndList();
if (sphere_wire_dl!=0) glDeleteLists(sphere_wire_dl,1);
sphere_wire_dl = glGenLists(1);
glNewList(sphere_wire_dl,GL_COMPILE);
glutWireSphere(1, settings.value("sphere-rendering-resolution").toInt(), settings.value("sphere-rendering-resolution").toInt());
glEndList();
// std::cout << LOG_BLUE <<"new sphere rendering with " << settings.value("sphere-rendering-resolution").toInt() << " resolution: " << sphere_dl << std::endl;
}
void GL_widget_3::draw () {
default_bounding_box = true;
bool is_valid;
std::vector<Visualization_layer *>::iterator it, end=layers.end();
for (it=layers.begin(); it!=end; it++) {
GL_draw_layer_3 *l = (GL_draw_layer_3*)*it;
if (l->is_active()) {
l->draw();
Box3D bbox = l->get_3d_bounding_box(&is_valid);
if (is_valid)
update_bounding_box(bbox);
}
}
setSceneBoundingBox(qglviewer::Vec((float)bounding_xmin, (float)bounding_ymin, (float)bounding_zmin),
qglviewer::Vec((float)bounding_xmax, (float)bounding_ymax, (float)bounding_zmax));
// std::cout << "BBox: [" << bounding_xmin << ", " << bounding_ymin << ", " << bounding_zmin << "] - [" << bounding_xmax << ", " << bounding_ymax << ", " << bounding_zmax << "]" << std::endl;
glDisable(GL_CLIP_PLANE0);
glDisable(GL_CLIP_PLANE1);
}
//void GL_widget_3::paint_to_painter() {
// painter->setClipRegion(QRegion(0,0,width(), height()));
// std::vector<Visualization_layer *>::iterator it, end=layers.end();
// for (it=layers.begin(); it!=end; it++) {
// Visualization_layer *l = *it;
// if (l->is_active())
// l->draw();
// }
//}
void GL_widget_3::mousePressEvent(QMouseEvent *e)
{
// emit(s_mousePressEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mousePressEvent(e);
QGLViewer::mousePressEvent(e);
}
void GL_widget_3::mouseReleaseEvent(QMouseEvent *e)
{
// emit(s_mouseReleaseEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mouseReleaseEvent(e);
QGLViewer::mouseReleaseEvent(e);
}
void GL_widget_3::mouseMoveEvent(QMouseEvent *e)
{
// emit(s_mouseMoveEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mouseMoveEvent(e);
QGLViewer::mouseMoveEvent(e);
}
void GL_widget_3::wheelEvent(QWheelEvent *e)
{
// emit(s_wheelEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->wheelEvent(e);
QGLViewer::wheelEvent(e);
}
void GL_widget_3::mouseDoubleClickEvent(QMouseEvent *e)
{
// emit(s_mouseDoubleClickEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mouseDoubleClickEvent(e);
QGLViewer::mouseDoubleClickEvent(e);
}
void GL_widget_3::keyPressEvent(QKeyEvent *e)
{
// emit(s_keyPressEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->keyPressEvent(e);
if (e->key() == Qt::Key_V && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier)) {
qglviewer::ManipulatedCameraFrame* frame = camera()->frame();
QDomDocument doc;
QDomElement el = frame->domElement("qglview-camera",doc);
doc.appendChild(el);
QSettings settings;
settings.setValue("viewer-buffer-3d-view-state",doc.toString());
std::cout << "Camera view stored" << std::endl;
}
if (e->key() == Qt::Key_V && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier)) {
QSettings settings;
QString doc_text = settings.value("viewer-buffer-3d-view-state").toString();
QDomDocument doc;
doc.setContent(doc_text);
QDomElement camera_element = doc.documentElement();
camera()->frame()->initFromDOMElement(camera_element);
repaint();
std::cout << "Camera view reloaded" << std::endl;
}
if (e->key() == Qt::Key_O && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier)) {
}
if (e->key() == Qt::Key_O && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier)) {
}
QGLViewer::keyPressEvent(e);
}
void GL_widget_3::save_view(bool) {
qglviewer::ManipulatedCameraFrame* frame = camera()->frame();
QDomDocument doc;
QDomElement el = frame->domElement("qglview-camera",doc);
doc.appendChild(el);
QSettings settings;
QString file_name = QFileDialog::getSaveFileName(
this,
"Choose a filename to save view",
settings.value("last-view-directory",QString()).toString(),
"View files (*.3view)");
if (file_name=="") return;
if (!file_name.endsWith(".3view")) file_name += ".3view";
QString save_directory = file_name;
save_directory.truncate(file_name.lastIndexOf('/'));
settings.setValue("last-view-directory",save_directory);
QFile f(file_name);
if ( !f.open( QIODevice::WriteOnly ) ) {
std::cout << LOG_ERROR << tr("File `%1' could not be open for writing!").arg(file_name).toStdString() << std::endl;
return;
}
QTextStream fs( &f );
fs << doc.toString();
f.close();
std::cout << "Camera view stored in " << file_name.toStdString() << std::endl;
}
void GL_widget_3::load_view(bool) {
QSettings settings;
QString file_name = QFileDialog::getOpenFileName(
this,
"Choose a filename to load view",
settings.value("last-view-directory",QString()).toString(),
"View files (*.3view)");
if (file_name!="") {
if (!file_name.endsWith(".3view")) file_name += ".3view";
QString save_directory = file_name;
save_directory.truncate(file_name.lastIndexOf('/'));
settings.setValue("last-view-directory",save_directory);
QFile file(file_name);
if (!file.open(QIODevice::ReadOnly)) {
std::cout << LOG_ERROR << tr("File `%1' could not be open for reading!").arg(file_name).toStdString() << std::endl;
return;
}
QDomDocument doc;
if (!doc.setContent(&file)) {
std::cout << LOG_ERROR << tr("File `%1' can not be parsed to an xml").arg(file_name).toStdString() << std::endl;
file.close();
return;
}
file.close();
QDomElement camera_element = doc.documentElement();
camera()->frame()->initFromDOMElement(camera_element);
repaint();
std::cout << "Camera view reloaded from " << file_name.toStdString() << std::endl;
}
}
void GL_widget_3::keyReleaseEvent(QKeyEvent *e)
{
// emit(s_keyReleaseEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->keyReleaseEvent(e);
QGLViewer::keyReleaseEvent(e);
}
void GL_widget_3::enterEvent(QEvent *e)
{
// emit(s_enterEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->enterEvent(e);
QGLViewer::enterEvent(e);
}
void GL_widget_3::leaveEvent(QEvent *e)
{
// emit(s_leaveEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->leaveEvent(e);
QGLViewer::leaveEvent(e);
}
bool GL_widget_3::event(QEvent *e)
{
// emit(s_event(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->event(e);
return QGLViewer::event(e);
}
void GL_widget_3::application_settings_changed(const QString& settings_name) {
//send it to the layers
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
(*it)->application_settings_changed(settings_name);
if (settings_name == "sphere-rendering-resolution") {
create_sphere_display_list();
want_repaint = true;
}
if (settings_name.startsWith("camera-projection")) {
set_camera_projection();
want_repaint = true;
}
if (want_repaint) {
repaintGL();
want_repaint = false;
}
}
| [
"balint.miklos@localhost"
] | [
[
[
1,
467
]
]
] |
26374aaeb8044ca5356744af37a4d0281ba10106 | 16ba8e891c084c827148d9c6cd6981a29772cb29 | /KaraokeMachine/trunk/src/KMachine_Basic.cpp | 7367a54f415000b0e88cb5c8f61d0bc0fc624fa8 | [] | no_license | RangelReale/KaraokeMachine | efa1d5d23d0759762f3d6f590e114396eefdb28a | abd3b05d7af8ebe8ace15e888845f1ca8c5e481f | refs/heads/master | 2023-06-29T20:32:56.869393 | 2008-09-16T18:09:40 | 2008-09-16T18:09:40 | 37,156,415 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | cpp | #include "KMachine_Basic.h"
namespace KaraokeMachine {
class KMachinePlaySongProcess : public KMBackendThreadProcess
{
public:
KMachinePlaySongProcess(KMSong *song) : KMBackendThreadProcess(), song_(song) {};
protected:
virtual void Run();
private:
KMSong *song_;
};
void KMachinePlaySongProcess::Run()
{
song_->Play();
while (!IsCancel() && song_->Poll())
kmutil_usleep(100);
}
KMachine_Basic::KMachine_Basic(KMBackend &backend) :
KMachine(), backend_(&backend), songplayprocess_(NULL)
{
}
void KMachine_Basic::DoCommand(commant_t command, int param )
{
switch(command)
{
case KC_SKIPIMAGE:
backend_->SkipImage();
break;
default:
KMachine::DoCommand(command, param);
break;
}
}
void KMachine_Basic::DoRun()
{
//KMachine::DoRun();
while (backend_->Loop(*this))
{
Loop();
}
}
void KMachine_Basic::PlaySong(KMSong *song)
{
songplayprocess_=new KMachinePlaySongProcess(song);
backend_->CreateThread(songplayprocess_);
}
void KMachine_Basic::StopSong()
{
if (songplayprocess_)
{
songplayprocess_->Cancel();
songplayprocess_=NULL;
}
}
};
| [
"hitnrun@6277c508-b546-0410-9041-f9c9960c1249"
] | [
[
[
1,
68
]
]
] |
95c8ba18c318c5791336b69895dd3f7e32a0154c | 465943c5ffac075cd5a617c47fd25adfe496b8b4 | /FLIGHTPA.H | 6fc5233af77c986a8ccbdb702d61871abd1ff481 | [] | no_license | paulanthonywilson/airtrafficcontrol | 7467f9eb577b24b77306709d7b2bad77f1b231b7 | 6c579362f30ed5f81cabda27033f06e219796427 | refs/heads/master | 2016-08-08T00:43:32.006519 | 2009-04-09T21:33:22 | 2009-04-09T21:33:22 | 172,292 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | h | /*
Flight path class
Paul Wilson
ver 0.0
5/4/96
*/
# ifndef _FLIGHTPATH_H
# define _FLIGHTPATH_H
# include "position.h"
class FlightPath {
private :
Position Start_c;
Position Finish_c;
const int AngleToFinish_c;
const int DistToFinishSquared_c;
public :
FlightPath (Position, Position);
Position Start();
Position Finish();
Boolean OnFlightPath (Position);
};
# endif
| [
"[email protected]"
] | [
[
[
1,
41
]
]
] |
eeaace32ffcfcc75489f491245463979caf8ef83 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /maxsdk2008/include/shaders.h | 33931a414e83b94f52f5329f898b5932ce48a799 | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,812 | h | //////////////////////////////////////////////////////////////////////////////
//
// Shader plug-ins
//
// Created: 8/18/98 Kells Elmquist
//
#ifndef SHADERS_H
#define SHADERS_H
#include "iparamb2.h"
#include "stdmat.h"
#include "buildver.h"
//#define STD2_NMAX_TEXMAPS 24
#define N_ID_CHANNELS 16 // number of ids in stdMat
class Shader;
#define OPACITY_PARAM 0
#define DEFAULT_SOFTEN 0.1f
/////////////////////////////////////////////////////////////////////////////
//
// Shader param dialog
//
// Returned by a shader when it is asked to put up its rollup page.
/*! \sa Class ParamDlg, Class StdMat2, Class Shader.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
A pointer to an instance of this class is returned by a Shader when it is asked
to put up its rollup page. */
class ShaderParamDlg : public ParamDlg {
public:
/*! \remarks Returns the unique Class_ID of this object. */
virtual Class_ID ClassID()=0;
/*! \remarks This method sets the current shader being edited to the shader passed.
\par Parameters:
<b>ReferenceTarget *m</b>\n\n
The Shader to set as current. */
virtual void SetThing(ReferenceTarget *m)=0;
/*! \remarks This method sets the current Standard material (and its shader) being
edited to the ones passed.
\par Parameters:
<b>StdMtl2* pMtl</b>\n\n
The Standard material to set as current.\n\n
<b>Shader* pShader</b>\n\n
The Shader to set as current. */
virtual void SetThings( StdMat2* pMtl, Shader* pShader )=0;
/*! \remarks Returns the a pointer to the current <b>material</b>
being edited. Note that in most of the Get/SetThing() methods in the
SDK the 'Thing' is the actual plug-in. In this case it's not. It the
material which is using this Shader. */
virtual ReferenceTarget* GetThing()=0;
/*! \remarks This method returns a pointer to the current Shader. */
virtual Shader* GetShader()=0;
/*! \remarks This method is called when the current time has changed.
This gives the developer an opportunity to update any user interface
data that may need adjusting due to the change in time.
\par Parameters:
<b>TimeValue t</b>\n\n
The new current time.
\par Default Implementation:
<b>{}</b> */
virtual void SetTime(TimeValue t) {}
/*! \remarks This method is called to delete this instance of the class.\n\n
For dynamically created global utility plugins, this method has to be
implemented and should have a implementation like <b>{ delete this;
}</b> */
virtual void DeleteThis()=0;
/*! \remarks This is the dialog procedure for the user interface controls of the Shader.
\par Parameters:
<b>HWND hwndDlg</b>\n\n
The window handle of the rollup page.\n\n
<b>UINT msg</b>\n\n
The message to process.\n\n
<b>WPARAM wParam</b>\n\n
The first dialog parameter.\n\n
<b>LPARAM lParam</b>\n\n
The second dialog parameter.
\return Except in response to the WM_INITDIALOG message, the procedure should
return nonzero if it processes the message, and zero if it does not. In
response to a WM_INITDIALOG message, the dialog box procedure should return
zero if it calls the SetFocus function to set the focus to one of the controls
in the dialog. Otherwise, it should return nonzero, in which case the system
sets the focus to the first control in the dialog that can be given the focus.*/
virtual INT_PTR PanelProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam )=0;
/*! \remarks This method is used to load the user interface controls
with their current values.
\par Parameters:
<b>int draw</b>\n\n
This parameter is not currently used. */
virtual void LoadDialog( int draw )=0;
virtual void UpdateDialog( ParamID paramId )=0;
/*! \remarks This method returns the window handle of the rollup
panel. */
virtual HWND GetHWnd()=0;
/*! \remarks This method returns the index of the sub-texmap
corresponding to the window whose handle is passed. If the handle is
not valid return -1.
\par Parameters:
<b>HWND hw</b>\n\n
The window handle to check. */
virtual int FindSubTexFromHWND(HWND hw)=0;
/*! \remarks This method is called to update the opacity parameter of
the plug-in in the user interface. */
virtual void UpdateOpacity()=0;
/*! \remarks This method is called to update the map buttons in the
user interface. For example it can put a <b>" "</b> or <b>"m"</b> or
<b>"M"</b> on the button face based on the state of the map. */
virtual void UpdateMapButtons()=0;
};
///////////////////////////////////sh flags //////////////////////////////////////
#define SELFILLUM_CLR_ON (1<<16) // can be or'd w/ mtl, not sure it's necessary
/*********
// post mapping params for shader
class IllumParams {
public:
// these are the inputs to the shader, mostly textured channels
ULONG mtlFlags;
Shader* pShader; // for render elements to call the shader & mtl again, may be null
Mtl* pMtl; // max mtl being shaded, null if bgnd
// Point3 N, V;
Color channels[ STD2_NMAX_TEXMAPS ];
float falloffOpac; // textured opacity w/ stdfalloff (reg opac in channels)
float kR; // combined reflection.a * amt
ULONG hasComponents; // bits for active components(e.g.currently has active refl map)
ULONG stdParams;
int* stdIDToChannel; // combined shader & mtl
// these are the component-wise outputs from the shading process
Color ambIllumOut, diffIllumOut, transIllumOut, selfIllumOut; // the diffuse clrs
Color specIllumOut, reflIllumOut; // the specular colors
// User Illumination outputs for render elements, name matched
int nUserIllumOut; // one set of names for all illum params instances
TCHAR** userIllumNames; // we just keep ptr to shared name array, not destroyed
Color* userIllumOut; // the user illum color array, new'd & deleted w/ the class
float diffIllumIntens; // used only by reflection dimming, intensity of diffIllum prior to color multiply
float finalOpac; // for combining components
// these are the outputs of the combiner
Color finalC; // final clr: combiner composites into this value.
Color finalT; // shader transp clr out
public:
// Illum params are allocated by materials during shading process to
// communicate with shaders & render elements
// So materials need to know how many userIllum slots they will use
// most materials know this, but std2 will have to get it from the shader
IllumParams( int nUserOut = 0, TCHAR** pUserNames = NULL ){
nUserIllumOut = nUserOut;
userIllumOut = ( nUserOut )? new Color[ nUserOut ] : NULL;
userIllumNames = pUserNames;
}
// IllumParams(){
// nUserIllumOut = 0;
// userIllumOut = NULL;
// userIllumNames = NULL;
// }
~IllumParams(){
// We Dont destroy the name array as it's shared by all
if( userIllumOut )
delete [] userIllumOut;
}
// returns number of user illum channels for this material
int nUserIllumChannels(){ return nUserIllumOut; }
// returns null if no name array specified
TCHAR* GetUserIllumName( int n ) {
DbgAssert( n < nUserIllumOut );
if( userIllumNames )
return userIllumNames[n];
return NULL;
}
// render elements, mtls & shaders can use this to find the index associated with a name
// returns -1 if it can't find the name
int FindUserIllumName( TCHAR* name ){
int n = -1;
for( int i = 0; i < nUserIllumOut; ++i ){
DbgAssert( userIllumNames );
if( strcmp( name, userIllumNames[i] )){
n = i;
break;
}
}
return n;
}
// knowing the index, these set/get the user illum output color
void SetUserIllumOutput( int n, Color& out ){
DbgAssert( n < nUserIllumOut );
userIllumOut[n] = out;
}
void SetUserIllumOutput( TCHAR* name, Color& out ){
for( int i = 0; i < nUserIllumOut; ++i ){
DbgAssert( userIllumNames );
if( strcmp( name, userIllumNames[i] )){
userIllumOut[i] = out;
break;
}
}
DbgAssert( i < nUserIllumOut );
}
Color GetUserIllumOutput( int n ){
DbgAssert( n < nUserIllumOut );
return userIllumOut[n];
}
Color GetUserIllumOutput( TCHAR* name, int n ){
for( int i = 0; i < nUserIllumOut; ++i ){
DbgAssert( userIllumNames );
if( strcmp( name, userIllumNames[i] )){
return userIllumOut[i];
}
}
return Color(0,0,0);
}
void ClearOutputs() {
finalC = finalT = ambIllumOut=diffIllumOut=transIllumOut=selfIllumOut=
specIllumOut=reflIllumOut= Color( 0.0f, 0.0f, 0.0f );
finalOpac = diffIllumIntens = 0.0f;
for( int i=0; i < nUserIllumOut; ++i )
userIllumOut[i] = finalC;
}
void ClearInputs() {
mtlFlags = stdParams = hasComponents = 0;
pShader = NULL; pMtl = NULL;
stdIDToChannel = NULL;
kR = 0.0f;
for( int i=0; i < STD2_NMAX_TEXMAPS; ++i )
channels[ i ] = Color( 0, 0, 0 );
}
};
********/
/////////// Components defines
#define HAS_BUMPS 0x01L
#define HAS_REFLECT 0x02L
#define HAS_REFRACT 0x04L
#define HAS_OPACITY 0x08L
#define HAS_REFLECT_MAP 0x10L
#define HAS_REFRACT_MAP 0x20L
#define HAS_MATTE_MTL 0x40L
////////// Texture channel type flags
#define UNSUPPORTED_CHANNEL 0x01L
#define CLR_CHANNEL 0x02L
#define MONO_CHANNEL 0x04L
#define BUMP_CHANNEL 0x08L
#define REFL_CHANNEL 0x10L
#define REFR_CHANNEL 0x20L
#define DISP_CHANNEL 0x40L
#define SLEV_CHANNEL 0x80L
#define ELIMINATE_CHANNEL 0x8000L
#define SKIP_CHANNELS (UNSUPPORTED_CHANNEL+BUMP_CHANNEL+REFL_CHANNEL+REFR_CHANNEL)
/////////// Class Id upper half for loading the Pre 3.0 shaders
#define DEFAULT_SHADER_CLASS_ID BLINNClassID
#ifndef USE_LIMITED_STDMTL // orb 01-14-2002
#define PHONGClassID (STDSHADERS_CLASS_ID+2)
#define METALClassID (STDSHADERS_CLASS_ID+4)
#endif // USE_LIMITED_STDMTL
#define BLINNClassID (STDSHADERS_CLASS_ID+3)
class ParamBlockDescID;
class IParamBlock;
/*! \sa Class SpecialFX, Class ShaderParamDlg, Class ShadeContext, Class IllumParams, Class IMtlParams, Class StdMat2, Class Mtl, Class Color, Class ILoad, Class ISave.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
This is one of the base classes for the creation of Shaders which plug-in to
the Standard material. Note: Developers should derive their plug-in Shader from
Class Shader rather than this class directly
since otherwise the interactive renderer won't know how to render the Shader in
the viewports.\n\n
Developers of this plug-in type need to understand how the Standard material
and the Shader work together.\n\n
Every material has a Shader. The Shader is the piece of code which controls how
light is reflected off the surface. The Standard material is basically the
mapping mechanism. It handles all the texturing for the material. It also
manages the user interface. This simplifies things so the Shader plug-in only
needs to worry about the interaction of light on the surface.\n\n
Prior to release 3 developers could write Material plug-ins that performed
their own shading, however ths was usually a major programming task. Release 3
provides the simpler Shader plug-in that would benefit from sharing all the
common capabilities. The Standard material, with its 'blind' texturing
mechanism, makes this possible. It doesn't know what it is texturing -- it
simply texturing 'stuff'. The shader names the channels (map), fills in the
initial values, specifies if they are a single channel (mono) or a triple
channel (color). The Standard material handles the rest including managing the
user interface.\n\n
Most of the code in a Shader has to do with supplying this information to a
Standard material. The values are passed and received back in class
<b>IllumParams</b>. There is a single method in a shader which actually does
the shading. This is the <b>Illum()</b> method.
\par Plug-In Information:
Class Defined In SHADER.H\n\n
Super Class ID SHADER_CLASS_ID\n\n
Standard File Name Extension DLB\n\n
Extra Include File Needed SHADERS.H
\par Method Groups:
See Method Groups for Class BaseShader.
*/
class BaseShader : public SpecialFX {
public:
RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget,
PartID& partID, RefMessage message) {return REF_SUCCEED;}
SClass_ID SuperClassID() {return SHADER_CLASS_ID;}
BOOL BypassPropertyLevel() { return TRUE; } // want to promote shader props to material level
/*! \remarks Returns the requirements of the Shader for the specified
sub-material. Many objects in the rendering pipeline use the
requirements to tell the renderer what data needs to be available. The
Shader's requirements are OR'd with the combined map requirements and
returned to the renderer via the Stdmtl2's <b>GetRequirements()</b>
function.
\par Parameters:
<b>int subMtlNum</b>\n\n
This parameter is not used.
\return One or more of the following flags:\n\n
See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_material_requirement_flags.html">List of
Material Requirement Flags</a>. */
virtual ULONG GetRequirements(int subMtlNum)=0;
// Put up a dialog that lets the user edit the plug-ins parameters.
/*! \remarks This method creates and returns a pointer to a<b>ShaderParamDlg</b>
object and puts up the dialog which lets the user edit the Shader's parameters.
\par Parameters:
<b>HWND hOldRollup</b>\n\n
The window handle of the old rollup. If non-NULL the IMtlParams method
ReplaceRollup method is usually used instead of AddRollup() to present the
rollup.\n\n
<b>HWND hwMtlEdit</b>\n\n
The window handle of the material editor.\n\n
<b>IMtlParams *imp</b>\n\n
The interface pointer for calling methods in 3ds Max.\n\n
<b>StdMtl2* theMtl</b>\n\n
Points to the Standard material being edited.\n\n
<b>int rollupOpen</b>\n\n
TRUE to have the UI rollup open; FALSE if closed.\n\n
<b>int n=0</b>\n\n
This parameter is available in release 4.0 and later only.\n\n
Specifies the number of the rollup to create. Reserved for future use with multiple rollups. */
virtual ShaderParamDlg* CreateParamDialog(
HWND hOldRollup,
HWND hwMtlEdit,
IMtlParams *imp,
StdMat2* theMtl,
int rollupOpen,
int n=0) = 0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Returns the number of rollups this shader is requesting.
\par Default Implementation:
<b>{ return 1; }</b> */
virtual int NParamDlgs(){ return 1; }
/*! \remarks Returns a pointer to the <b>ShaderParamDlg</b> object
which manages the user interface.
\par Parameters:
<b>int n=0</b>\n\n
This parameter is available in release 4.0 and later only.\n\n
Specifies the rollup to get <b>ShaderParamDlg</b> for. Reserved for
future use with multiple rollups. */
virtual ShaderParamDlg* GetParamDlg(int n=0 )=0;
/*! \remarks Sets the <b>ShaderParamDlg</b> object which manages the
user interface to the one passed.
\par Parameters:
<b>ShaderParamDlg* newDlg</b>\n\n
Points to the new ShaderParamDlg object.\n\n
<b>int n=0</b>\n\n
This parameter is available in release 4.0 and later only.\n\n
Specifies the rollup to set <b>ShaderParamDlg</b> for. Reserved for
future use with multiple rollups.\n\n
*/
virtual void SetParamDlg( ShaderParamDlg* newDlg, int n=0 )=0;
// Saves and loads name. These should be called at the start of
// a plug-in's save and load methods.
/*! \remarks Saves the plug-in's name. This should be called at the
start of a plug-in's <b>Save()</b> method.
\par Parameters:
<b>ISave *isave</b>\n\n
An interface for saving data. */
IOResult Save(ISave *isave) { return SpecialFX::Save(isave); }
/*! \remarks Loads the plug-in's name. This should be called at the
start of a plug-in's <b>Load()</b> method.
\par Parameters:
<b>ILoad *iload</b>\n\n
An interface for loading data. */
IOResult Load(ILoad *iload) { return SpecialFX::Load(iload); }
// std parameter support
/*! \remarks Returns a value which indicates which of the standard
parameters are supported.
\return See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_shader_standard_parameter.html">List of Shader
Standard Parameter Flags</a>. */
virtual ULONG SupportStdParams()=0;
// this method only req'd for R2.5 shaders, to convert stdmtl1 paramblks to current
/*! \remarks This method is only required for R2.5 shaders to convert
the previous Standard material parameter blocks to the current version.
\par Parameters:
<b>ParamBlockDescID *descOld</b>\n\n
Points to the old parameter block descriptor.\n\n
<b>int oldCount</b>\n\n
The number in the array of parameters above.\n\n
<b>IParamBlock *oldPB</b>\n\n
Points to the old parameter block. */
virtual void ConvertParamBlk( ParamBlockDescID *descOld, int oldCount, IParamBlock *oldPB ){};
// LOCAL vars of mtl for possible mapping prior to being given to back to illum
/*! \remarks This method updates the <b>channels</b>(as well as other) data
member of the <b>IllumParams</b> object passed to it with the <b>local</b>
variables of the material for possible mapping prior to being given to the
Shader's <b>Illum()</b> method. The shader plug-in copies the state of all its
parameters (at their current animation state) into the data members of the
<b>IllumParams</b> passed.
\par Parameters:
<b>IllumParams* ip</b>\n\n
Points to the IllumParams to update. */
virtual void GetIllumParams( ShadeContext &sc, IllumParams& ip )=0;
// actual shader
/*! \remarks This is the illumination function for the Shader.\n\n
Developers will find it very helpful to review the <b>Mtl::Shade()</b>
method of the Standard material. This is the main method of the
material which computes the color of the point being rendered. This
code is available in <b>/MAXSDK/SAMPLES/MATERIALS/STDMTL2.CPP</b>. This
code shows how the Standard calls <b>Shader::GetIllumParams()</b>, sets
up mapping channels, calls this <b>Illum()</b> method, and calls the
<b>Shader::CombineComponents()</b> method when all done.
\par Parameters:
<b>ShadeContext \&sc</b>\n\n
The ShadeContext which provides information on the pixel being
shaded.\n\n
<b>IllumParams \&ip</b>\n\n
The object whose data members provide communication between 3ds Max and
the shader. Input values are read from here and output values are
stored here. Note that the <b>XOut</b> (<b>ambIllumout</b>, etc) data
members of this class are initialized to 0 before the first call to
this method.\n\n
The input to this method has the textured illumination parameters, the
bump perturbed normal, the view vector, the raw (unattenuated) colors
in the reflection and refraction directions, etc.
\par Sample Code:
Below is a brief analysis of the standard Blinn shader Illum() method.
This is the standard 'computer graphics look' type shader supplied with
3ds Max. The entire method follows:\n\n
\code
void Blinn2::Illum(ShadeContext &sc, IllumParams &ip)
{
LightDesc *l;
Color lightCol;
// Blinn style phong
BOOL is_shiny= (ip.channels[ID_SS].r > 0.0f) ? 1:0;
double phExp = pow(2.0, ip.channels[ID_SH].r * 10.0) * 4.0;
for (int i=0; i<sc.nLights; i++) {
l = sc.Light(i);
register float NL, diffCoef;
Point3 L;
if (l->Illuminate(sc,ip.N,lightCol,L,NL,diffCoef)) {
if (l->ambientOnly) {
ip.ambIllumOut += lightCol;
continue;
}
if (NL<=0.0f)
continue;
// diffuse
if (l->affectDiffuse)
ip.diffIllumOut += diffCoef * lightCol;
// specular (Phong2)
if (is_shiny&&l->affectSpecular) {
Point3 H = Normalize(L-ip.V);
float c = DotProd(ip.N,H);
if (c>0.0f) {
if (softThresh!=0.0 && diffCoef<softThresh) {
c *= Soften(diffCoef/softThresh);
}
c = (float)pow((double)c, phExp);
ip.specIllumOut += c * ip.channels[ID_SS].r * lightCol;
}
}
}
}
// Apply mono self illumination
if ( ! selfIllumClrOn ) {
float si = ip.channels[ID_SI].r;
ip.diffIllumOut = (si>=1.0f) ? Color(1.0f,1.0f,1.0f):ip.diffIllumOut * (1.0f-si) + si;
}
else {
// colored self illum,
ip.selfIllumOut += ip.channels[ID_SI];
}
// now we can multiply by the clrs,
ip.ambIllumOut *= ip.channels[ID_AM];
ip.diffIllumOut *= ip.channels[ID_DI];
ip.specIllumOut *= ip.channels[ID_SP];
// the following is applicable only in R4
int chan = ip.stdIDToChannel[ ID_RL ];
ShadeTransmission(sc, ip, ip.channels[chan], ip.refractAmt);
chan = ip.stdIDToChannel[ ID_RR ];
ShadeReflection( sc, ip, ip.channels[chan] );
CombineComponents( sc, ip );
}
\endcode
Some of the key parts of this method are discussed below:\n\n
The <b>is_shiny</b> line sets a boolean based on if the Shader has a
shininess setting \> 0. Note that the Blinn shader uses the same
channel ordering as the original Standard material so it can index its
channels using the standard ID <b>ID_SS</b>.\n\n
<b>BOOL is_shiny= (ip.channels[ID_SS].r \> 0.0f) ? 1:0;</b>\n\n
Next the 'Phong Exponent' is computed. This is just a function that is
used to give a certain look. It uses 2^(Shinniness *10) * 4. This
calculation simply 'feels right' and gives a good look.\n\n
<b>double phExp = pow(2.0, ip.channels[ID_SH].r * 10.0) * 4.0;</b>\n\n
The following loop sums up the effect of each light on this point on
surface.\n\n
<b>for (int i=0; i\<sc.nLights; i++) {</b>\n\n
Inside the loop, the light descriptor is grabbed from the
ShadeContext:\n\n
<b> l = sc.Light(i);</b>\n\n
The <b>LightDesc::Illuminate()</b> method is then called to compute
some data:\n\n
<b> if (l-\>Illuminate(sc,ip.N,lightCol,L,NL,diffCoef))
{</b>\n\n
To <b>Illuminate()</b> is passed the ShadeContext (<b>sc</b>), and the
normal to the surface (<b>ip.N</b>) (pointing away from the surface
point).\n\n
The method returns the light color (<b>lightCol</b>), light vector
(<b>L</b>) (which points from the surface point to the light), the dot
product of N and L (<b>NL</b>) and the diffuse coefficient
(<b>diffCoef</b>). The diffuse coefficient is similar to NL but has the
atmosphere between the light and surface point taken into account as
well.\n\n
The next piece of code checks if the light figures into the
computations:\n\n
<b> if (NL\<=0.0f)</b>\n\n
<b> continue;</b>\n\n
If NL\<0 then the cosine of the vectors is greater than 90 degrees.
This means the light is looking at the back of the surface and is
therefore not to be considered.\n\n
The next statement checks if the light affect the diffuse channel
(lights may toggle on or off their ability to affect the diffuse and
specular channels.)\n\n
<b> if (l-\>affectDiffuse)</b>\n\n
<b> ip.diffIllumOut += diffCoef *
lightCol;</b>\n\n
If the light affects the diffuse channel then the diffuse illumination
output component of the <b>IllumParams</b> is added to. This is done by
multiplying the diffuse coefficient (returned by
<b>LightDesc::Illuminate()</b>) times the light color (also returned by
<b>LightDesc::Illuminate()</b>). Notice that the <b>diffIllumOut</b> is
being accumulated with each pass of the light loop.\n\n
The next section of code involves the specular component. If the light
is shiny, and it affects the specular channel a vector <b>H</b> is
computed.\n\n
<b> if (is_shiny\&\&l-\>affectSpecular) {</b>\n\n
Note the following about this <b>H</b> vector computation. Most vectors
are considered pointing <b>from</b> the point on the surface. The view
vector (<b>IllumParams::V</b>) does not follow this convention. It
points from the 'eye' towards the surface. Thus it's reversed from the
usual convention.\n\n
<b>H</b> is computed to be the average of <b>L</b> and <b>V</b>. This
is <b>(L+V)/2</b>. Since we normalize this we don't have to divide by
the 2. So, if <b>V</b> followed the standard convention this would be
simply <b>L+V</b>. Since it doesn't it is <b>L+(-ip.V)</b> or
<b>L-ip.V</b>.\n\n
<b> Point3 H = Normalize(L-ip.V);</b>\n\n
Next the dot product of <b>N</b> and <b>H</b> is computed and stored in
<b>c</b>. When you take the dot product of two normalized vectors what
is returned is the cosine of the angle between the vectors.\n\n
<b> float c = DotProd(ip.N,H); </b>\n\n
If c\>0 and the diffuse coefficient is less than the soften threshold
then <b>c</b> is modified by a 'softening' curve.
\code
if (c>0.0f)
{
if (softThresh!=0.0 &&
diffCoef<softThresh) {
c *=
Soften(diffCoef/softThresh);
}
}
\endcode
Note that the <b>Soften()</b> function is defined in
<b>/MAXSDK/SAMPLES/MATERIALS/SHADERUTIL.CPP</b> and developers can copy
this code.
\code
c = (float)pow((double)c,phExp);
\endcode
Next, <b>c</b> is raised to the power of the Phong exponent. This is
effectively taking a cosine (a smooth S curve) and raising it to a
power. As it is raised to a power it becomes a sharper and sharper S
curve. This is where the shape of the highlight curve in the Materials
Editor UI comes from.\n\n
That completes the pre computations for the specular function. Then
<b>c</b> is multiplied by the specular strength
(<b>ip.channels[ID_SS].r</b>) times the light color (<b>lightCol</b>).
The result is summed in specular illumination out
(<b>ip.specIllumOut</b>).\n\n
\code
ip.specIllumOut += c * ip.channels[ID_SS].r * lightCol;
\endcode
That completes the light loop. It happens over and over for each
light.\n\n
Next the self illumunation is computed. If the Self Illumination Color
is not on, then the original code for doing mono self illumination is
used.
\code
// Apply mono self illumination
if ( ! selfIllumClrOn )
{
float si = ip.channels[ID_SI].r;
ip.diffIllumOut = (si>=1.0f) ? Color(1.0f,1.0f,1.0f)
:
ip.diffIllumOut * (1.0f-si) + si;
}
else
{
// Otherwise the self illumination color is summed in to the Self Illumination
Out (ip.selfIllumOut).
// colored self illum,
ip.selfIllumOut += ip.channels[ID_SI];
}
\endcode
Then, we multiply by the colors for ambient, diffuse and specular.\n\n
\code
ip.ambIllumOut *= ip.channels[ID_AM];
ip.diffIllumOut *= ip.channels[ID_DI];
ip.specIllumOut *= ip.channels[ID_SP];
\endcode
The results are <b>ambIllumOut</b>, <b>diffIllumOut</b>, and
<b>specIllumOut</b>. Note that these components are not summed. In R3
and earlier these results would be returned to the Standard material.
However, R4 introduces a couple extra steps.\n\n
Finally, we call <b>ShadeTransmission()</b> and
<b>ShadeReflection()</b> to apply the transmission/refraction and
reflection models. The core implementation of 3ds Max provides the
standard models, but the shader can override these methods to compute
its own models.\n\n
\code
int chan = ip.stdIDToChannel[ ID_RL ];
ShadeTransmission(sc, ip, ip.channels[chan],ip.refractAmt);
chan = ip.stdIDToChannel[ ID_RR ];
ShadeReflection( sc, ip, ip.channels[chan] );
\endcode
In R4, It is a shader's responsibility to combine the components of the
shading process prior to exiting <b>Illum()</b> (in R3, this was the
responsibility of the Standard material). In order to combine these
values together to produce the final color for that point on the
surface (<b>IllumParams.finalC</b>), the shader should call
<b>CombineComponents()</b> method. The Shader base class provides a
default implementation which simply sums everything together and
multiplies by the opacity.\n\n
\code
virtual void CombineComponents( IllumParams& ip )
{
ip.finalC = ip.finalOpac * (ip.ambIllumOut + ip.diffIllumOut + ip.selfIllumOut)
+ ip.specIllumOut + ip.reflIllumOut + ip.transIllumOut ;
}
\endcode */
virtual void Illum(ShadeContext &sc, IllumParams &ip)=0;
// begin - ke/mjm - 03.16.00 - merge reshading code
// these support the pre-shade/reshade protocol
// virtual void PreIllum(ShadeContext &sc, IReshadeFragment* pFrag){}
// virtual void PostIllum(ShadeContext &sc, IllumParams &ip, IReshadeFragment* pFrag ){ Illum(sc,ip); }
// >>>> new for V4, one call superceded, 2 new ones added
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Compute the reflected color from the <b>sc</b>, <b>ip</b>, and
reflection map (or ray) color. The core implementation of this provides
the standard 3ds Max reflection model. To support the standard
reflection model, a shader may call this default implementation.
\par Parameters:
<b>ShadeContext\& sc</b>\n\n
The context which provides information on the pixel being shaded.\n\n
<b>IllumParams\& ip</b>\n\n
The object whose data members provide communication between 3ds Max and
the shader.\n\n
<b>Color \&mapClr</b>\n\n
The input reflection (or ray) color is passed in here and the resulting
'affected' color is stored here. */
virtual void ShadeReflection(ShadeContext &sc, IllumParams &ip, Color &mapClr){}
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Compute the transmission/refraction color for the sample.. The core
implementation of this provides the standard 3ds Max reflection model.
To support the standard transmission/refraction model, a shader may
call this default implementation.
\par Parameters:
<b>ShadeContext\& sc</b>\n\n
The context which provides information on the pixel being shaded.\n\n
<b>IllumParams\& ip</b>\n\n
The object whose data members provide communication between 3ds Max and
the shader.\n\n
<b>Color \&mapClr</b>\n\n
The input refraction (or ray) color is passed in here and the resulting
'affected' color is stored here.\n\n
<b>float amount</b>\n\n
The level of the amount spinner for the refraction channel. */
virtual void ShadeTransmission(ShadeContext &sc, IllumParams &ip, Color &mapClr, float amount){}
// orphaned, replaced by ShadeReflection()
/*! \remarks Note: This method has been superceded by
<b>ShadeReflection()</b> and is <b>obsolete</b> in release 4.0 and
later.\n\n
This method provides the shader with an opportunity to affect the
reflection code.
\par Parameters:
<b>ShadeContext \&sc</b>\n\n
The ShadeContext which provides information on the pixel being
shaded.\n\n
<b>IllumParams \&ip</b>\n\n
The object whose data members provide communication between 3ds Max and
the shader.\n\n
<b>Color \&rcol</b>\n\n
The input reflection color is passed in here and the resulting
'affected' color is stored here.
\par Sample Code:
A simple example like Phong does the following:\n\n
\code
void AffectReflection(ShadeContext &sc, IllumParams &ip, Color &rcol)
{
rcol *= ip.channels[ID_SP];
};
\endcode
If a color can affect the reflection of light off a surface than it can
usually affect the reflection of other things off a surface. Thus some
shaders influence the reflection color using the specular color and
specular level. For instance the Multi Layer Shader does the
following:\n\n
\code
#define DEFAULT_GLOSS2 0.03f
void MultiLayerShader::AffectReflection(ShadeContext &sc, IllumParams &ip, Color &rcol)
{
float axy = DEFAULT_GLOSS2;
float norm = 1.0f / (4.0f * PI * axy );
rcol *= ip.channels[_SPECLEV1].r * ip.channels[_SPECCLR1] * norm;
}
\endcode */
virtual void AffectReflection(ShadeContext &sc, IllumParams &ip, Color &rcol){}
// end - ke/mjm - 03.16.00 - merge reshading code
/*! \remarks This method does the final compositing of the various
illumination components. A default implementation is provided which
simply adds the components together. Developers who want to do other
more specialized composition can override this method. For example, a
certain Shader might want to composited highlights over the underlying
diffuse component since the light is reflected and the diffuse color
wouldn't fully show through. Such a Shader would provide its own
version of this method.
\par Parameters:
<b>ShadeContext \&sc</b>\n\n
The ShadeContext which provides information on the pixel being
shaded.\n\n
<b>IllumParams\& ip</b>\n\n
The illumination parameters to composite and store.
\par Default Implementation:
\code
virtual void CombineComponents(IllumParams& ip)
{
ip.finalC = ip.finalOpac * (ip.ambIllumOut + ip.diffIllumOut + ip.selfIllumOut)
+ ip.specIllumOut + ip.reflIllumOut + ip.transIllumOut;
}
\endcode */
virtual void CombineComponents( ShadeContext &sc, IllumParams& ip ){};
// texture maps
/*! \remarks Returns the number of texture map map channels supported
by this Shader. */
virtual long nTexChannelsSupported()=0;
/*! \remarks Returns the name of the specified texture map channel.
\par Parameters:
<b>long nTextureChan</b>\n\n
The zero based index of the texture map channel whose name is returned.
*/
virtual MSTR GetTexChannelName( long nTextureChan )=0;
/*! \remarks Returns the internal name of the specified texture map.
The Standard material uses this to get the fixed, parsable internal
name for each texture channel it defines.
\par Parameters:
<b>long nTextureChan</b>\n\n
The zero based index of the texture map whose name is returned.
\par Default Implementation:
<b>{ return GetTexChannelName(nTextureChan); }</b> */
virtual MSTR GetTexChannelInternalName( long nTextureChan ) { return GetTexChannelName(nTextureChan); }
/*! \remarks Returns the channel type for the specified texture map
channel. There are four channels which are part of the Material which
are not specific to the Shader. All other channels are defined by the
Shader (what they are and what they are called.) The four which are not
the province of the Shader are Bump, Reflection, Refraction and
Displacement. For example, Displacement mapping is really a geometry
operation and not a shading one. The channel type returned from this
method indicates if the specified channel is one of these, or if it is
a monochrome channel, a color channel, or is not a supported channel.
\par Parameters:
<b>long nTextureChan</b>\n\n
The zero based index of the texture map whose name is returned.
\return Texture channel type flags. One or more of the following
values:\n\n
<b>UNSUPPORTED_CHANNEL</b>\n\n
Indicates the channel is not supported (is not used).\n\n
<b>CLR_CHANNEL</b>\n\n
A color channel. The <b>Color.r</b>, <b>Color.g</b> and <b>Color.b</b>
parameters are used.\n\n
<b>MONO_CHANNEL </b>\n\n
A monochrome channel. Only the <b>Color.r</b> is used.\n\n
<b>BUMP_CHANNEL</b>\n\n
The bump mapping channel.\n\n
<b>REFL_CHANNEL</b>\n\n
The reflection channel.\n\n
<b>REFR_CHANNEL</b>\n\n
The refraction channel.\n\n
<b>DISP_CHANNEL</b>\n\n
The displacement channel.\n\n
<b>ELIMINATE_CHANNEL</b>\n\n
Indicates that the channel is not supported. For example, a certain
Shader might not support displacement mapping for some reason. If it
didn't, it could use this channel type to eliminate the support of
displacement mapping for itself. It would be as if displacement mapping
was not included in the material. None of the 3ds Max shaders use
this.\n\n
<b>SKIP_CHANNELS</b>\n\n
This is used internally to indicate that the channels to be skipped. */
virtual long ChannelType( long nTextureChan )=0;
// map StdMat Channel ID's to the channel number
/*! \remarks Returns the index of this Shader's channels which
corresponds to the specified Standard materials texture map ID. This
allows the Shader to arrange its channels in any order it wants in the
<b>IllumParams::channels</b> array but enables the Standard material to
access specific ones it needs (for instance the Bump channel or
Reflection channel).
\par Parameters:
<b>long stdID</b>\n\n
The ID whose corresponding channel to return. See \ref Material_TextureMap_IDs "List of Material Texture Map Indices".
\return The zero based index of the channel. If there is not a
corresponding channel return -1.
\par Sample Code:
This can be handled similar to below where an array is initialized with
the values of this plug-in shader's channels that correspond to each of
the standard channels. Then this method just returns the correspond
index from the array.\n\n
\code
static int stdIDToChannel[N_ID_CHANNELS] =
{
0, 1, 2, 5, 4, -1, 7, 8, 9, 10, 11, 12
};
long StdIDToChannel(long stdID){ return stdIDToChannel[stdID]; }
\endcode
*/
virtual long StdIDToChannel( long stdID )=0;
// Shader Uses these UserIllum output channels
virtual long nUserIllumOut(){ return 0; } // number of channels it will use
// static name array for matching by render elements
virtual TCHAR** UserIllumNameArray(){ return NULL; } // static name of each channel
/*! \remarks This method is called when the Shader is first activated
in the dropdown list of Shader choices. The Shader should reset itself
to its default values. */
virtual void Reset()=0; //reset to default values
};
// Chunk IDs saved by base class
#define SHADERBASE_CHUNK 0x39bf
#define SHADERNAME_CHUNK 0x0100
/////////////////////////////////////////////////////////////////////////////
//
// Standard params for shaders
//
// combination of these is returned by Shader.SupportStdParams()
#define STD_PARAM_NONE (0)
#define STD_PARAM_ALL (0xffffffffL)
#define STD_PARAM_METAL (1)
#define STD_PARAM_LOCKDS (1<<1)
#define STD_PARAM_LOCKAD (1<<2)
#define STD_PARAM_LOCKADTEX (1<<3)
#define STD_PARAM_SELFILLUM (1<<4)
#define STD_PARAM_SELFILLUM_CLR (1<<5)
#define STD_PARAM_AMBIENT_CLR (1<<6)
#define STD_PARAM_DIFFUSE_CLR (1<<7)
#define STD_PARAM_SPECULAR_CLR (1<<8)
#define STD_PARAM_FILTER_CLR (1<<9)
#define STD_PARAM_GLOSSINESS (1<<10)
#define STD_PARAM_SOFTEN_LEV (1<<11)
#define STD_PARAM_SPECULAR_LEV (1<<12)
#define STD_PARAM_DIFFUSE_LEV (1<<13)
#define STD_PARAM_DIFFUSE_RHO (1<<14)
#define STD_PARAM_ANISO (1<<15)
#define STD_PARAM_ORIENTATION (1<<16)
#define STD_PARAM_REFL_LEV (1<<17)
#define STD_PARAM_SELFILLUM_CLR_ON (1<<18)
#define STD_BASIC2_DLG (1<<20)
#define STD_EXTRA_DLG (1<<21)
// not including these 3 in yr param string disables the relevant params
// in extra params dialog
#define STD_EXTRA_REFLECTION (1<<22)
#define STD_EXTRA_REFRACTION (1<<23)
#define STD_EXTRA_OPACITY (1<<24)
#define STD_EXTRA (STD_EXTRA_DLG \
+STD_EXTRA_REFLECTION+STD_EXTRA_REFRACTION \
+STD_EXTRA_OPACITY )
#define STD_BASIC (0x00021ffeL | STD_BASIC2_DLG)
#ifndef USE_LIMITED_STDMTL // orb 01-14-2002
#define STD_BASIC_METAL (0x00020fffL | STD_BASIC2_DLG)
#define STD_ANISO (0x0002cffe)
#define STD_MULTILAYER (0x0002fffe)
#define STD_ONB (0x00023ffe)
#define STD_WARD (0x00000bce)
#endif // USE_LIMITED_STDMTL
///////////////////////////////////////////////////////////////////////////////
/*! \sa Class BaseShader, Class MacroRecorder.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
This is the class that developers use to create Shader plug-ins. Developers
must implement the methods of this class to provide data to the 3ds Max
interactive renderer so it can properly reflect the look of the shader in the
viewports. The methods associated with the actual Shader illumination code are
from the base class <b>BaseShader</b>.\n\n
There are various Get and Set methods defined in this class. Plug-in developers
provide implementations for the 'Get' methods which are used by the interactive
renderer. The implementations of the 'Set' methods are used when switching
between shaders types in the Materials Editor. This is used to transfer the
corresponding colors between the old Shader and the new one.\n\n
Note that some shaders may not have the exact parameters as called for in the
methods. In those case an approximate value may be returned from the 'Get'
methods. For example, the Strauss Shader doesn't have an Ambient channel. In
that case the Diffuse color is taken and divided by 2 and returned as the
Ambient color. This gives the interactive renderer something to work with that
might not be exact but is somewhat representative. */
class Shader : public BaseShader, public IReshading {
public:
/*! \remarks This method copies the standard shader parameters from
<b>pFrom</b> to this object. Note that plug-ins typically disable the macro
recorder during this operation as the Get and Set methods are called. See
the sample code for examples.
\par Parameters:
<b>Shader* pFrom</b>\n\n
The source parameters. */
virtual void CopyStdParams( Shader* pFrom )=0;
// these are the standard shader params
/*! \remarks Sets the state of the Diffuse / Specular lock to on or off.
\par Parameters:
<b>BOOL lock</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetLockDS(BOOL lock)=0;
/*! \remarks Returns TRUE if the Diffuse / Specular lock is on; otherwise
FALSE. */
virtual BOOL GetLockDS()=0;
/*! \remarks Sets the state of the Ambient / Diffuse lock to on or off.
\par Parameters:
<b>BOOL lock</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetLockAD(BOOL lock)=0;
/*! \remarks Returns TRUE if the Ambient / Diffuse lock is on; otherwise
FALSE. */
virtual BOOL GetLockAD()=0;
/*! \remarks Sets the state of the Ambient / Diffuse Texture lock to on or
off.
\par Parameters:
<b>BOOL lock</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetLockADTex(BOOL lock)=0;
/*! \remarks Returns TRUE if the Ambient / Diffuse Texture lock is on;
otherwise FALSE. */
virtual BOOL GetLockADTex()=0;
/*! \remarks Sets the Self Illumination parameter to the specified value
at the time passed.
\par Parameters:
<b>float v</b>\n\n
The value to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the value. */
virtual void SetSelfIllum(float v, TimeValue t)=0;
/*! \remarks Sets the Self Illumination Color On/Off state.
\par Parameters:
<b>BOOL on</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetSelfIllumClrOn( BOOL on )=0;
/*! \remarks Sets the Self Illumination Color at the specified time.
\par Parameters:
<b>Color c</b>\n\n
The color to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the color. */
virtual void SetSelfIllumClr(Color c, TimeValue t)=0;
/*! \remarks Sets the Ambient Color at the specified time.
\par Parameters:
<b>Color c</b>\n\n
The color to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the color. */
virtual void SetAmbientClr(Color c, TimeValue t)=0;
/*! \remarks Sets the Diffuse Color at the specified time.
\par Parameters:
<b>Color c</b>\n\n
The color to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the color. */
virtual void SetDiffuseClr(Color c, TimeValue t)=0;
/*! \remarks Sets the Specular Color at the specified time.
\par Parameters:
<b>Color c</b>\n\n
The color to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the color. */
virtual void SetSpecularClr(Color c, TimeValue t)=0;
/*! \remarks Sets the Glossiness parameter to the specified value at the
time passed.
\par Parameters:
<b>float v</b>\n\n
The value to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the value. */
virtual void SetGlossiness(float v, TimeValue t)=0;
/*! \remarks Sets the Specular Level parameter to the specified value at
the time passed.
\par Parameters:
<b>float v</b>\n\n
The value to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the value. */
virtual void SetSpecularLevel(float v, TimeValue t)=0;
/*! \remarks Sets the Soften Specular Highlights Level to the specified
value at the time passed.
\par Parameters:
<b>float v</b>\n\n
The value to set.\n\n
<b>TimeValue t</b>\n\n
The time to set the value. */
virtual void SetSoftenLevel(float v, TimeValue t)=0;
/*! \remarks Returns TRUE if the Self Illumination Color setting is on
(checked); FALSE if off.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual BOOL IsSelfIllumClrOn(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Ambient Color.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual Color GetAmbientClr(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Diffuse Color.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual Color GetDiffuseClr(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Specular Color.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual Color GetSpecularClr(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Self Illumination Color.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual Color GetSelfIllumClr(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Self Illumination Amount.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual float GetSelfIllum(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Glossiness Level.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual float GetGlossiness(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Specular Level.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual float GetSpecularLevel(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns the Soften Level as a float.
\par Parameters:
The parameters to this method are not applicable and may safely be ignored.
*/
virtual float GetSoftenLevel(int mtlNum, BOOL backFace)=0;
/*! \remarks Returns TRUE if the Self Illumination Color setting is on
(checked); FALSE if off. */
virtual BOOL IsSelfIllumClrOn()=0;
/*! \remarks Returns the Ambient Color at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the color. */
virtual Color GetAmbientClr(TimeValue t)=0;
/*! \remarks Returns the Diffuse Color at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the color. */
virtual Color GetDiffuseClr(TimeValue t)=0;
/*! \remarks Returns the Specular Color at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the color. */
virtual Color GetSpecularClr(TimeValue t)=0;
/*! \remarks Returns the Glossiness value at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the value. */
virtual float GetGlossiness( TimeValue t)=0;
/*! \remarks Returns the Specular Level at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the value. */
virtual float GetSpecularLevel(TimeValue t)=0;
/*! \remarks Returns the Soften Specular Highlights setting at the
specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the value. */
virtual float GetSoftenLevel(TimeValue t)=0;
/*! \remarks Returns the Self Illumination Amount at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the value. */
virtual float GetSelfIllum(TimeValue t)=0;
/*! \remarks Returns the Self Illumination Color at the specified time.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to return the color. */
virtual Color GetSelfIllumClr(TimeValue t)=0;
/*! \remarks This method is called to evaluate the hightlight curve that
appears in the Shader user interface.\n\n
Note: This gets called from the <b>DrawHilite()</b> function which is
available to developers in
<b>/MAXSDK/SAMPLES/MATERIALS/SHADER/SHADERUTIL.CPP</b>. <b>DrawHilite()</b>
get called from the window proc <b>HiliteWndProc()</b> in the same file.
This code is available to developers to use in their Shader dialog procs.
\par Parameters:
<b>float x</b>\n\n
The input value.
\return The output value on the curve. A value of 1.0 represents the top
of the curve as it appears in the UI. Values greater than 1.0 are okay and
simply appear off the top of the graph.
\par Default Implementation:
<b>{ return 0.0f; }</b> */
virtual float EvalHiliteCurve(float x){ return 0.0f; }
/*! \remarks This is the highlight curve function for the two highlight
curves which intersect and appear in the UI, for instance in the Anistropic
shader.
\par Parameters:
<b>float x</b>\n\n
The x input value.\n\n
<b>float y</b>\n\n
The y input value.\n\n
<b>int level = 0</b>\n\n
This is used by multi-layer shaders to indicate which layer to draw. The
draw highlight curve routines use this when redrawing the graph.
\return The output value of the curve.
\par Default Implementation:
<b>{ return 0.0f; }</b> */
virtual float EvalHiliteCurve2(float x, float y, int level = 0 ){ return 0.0f; }
// the Max std way of handling reflection and Transmission is
// implemented here to provide the default implementation.
CoreExport void ShadeReflection(ShadeContext &sc, IllumParams &ip, Color &mapClr);
CoreExport void ShadeTransmission(ShadeContext &sc, IllumParams &ip, Color &mapClr, float amount);
// Reshading
void PreShade(ShadeContext& sc, IReshadeFragment* pFrag){}
void PostShade(ShadeContext& sc, IReshadeFragment* pFrag, int& nextTexIndex, IllumParams* ip){ Illum( sc, *ip ); }
// [dl | 13march2003] Adding this inlined definition to resolve compile errors
BaseInterface* GetInterface(Interface_ID id) { return BaseShader::GetInterface(id); }
void* GetInterface(ULONG id){
if( id == IID_IReshading )
return (IReshading*)( this );
// else if ( id == IID_IValidityToken )
// return (IValidityToken*)( this );
else
return BaseShader::GetInterface(id);
}
};
#endif | [
"[email protected]"
] | [
[
[
1,
1220
]
]
] |
f7c2d065fe58c8564dded0e73f1050e5d3c28682 | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/core/game_core.h | 24f213a6b8e8f22d89163dac4d0296478d7dc959 | [] | no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,129 | h | /***************************************************************************
* game_core.h - header for the corresponding cpp file
*
* Copyright (C) 2005 - 2009 Florian Richter
***************************************************************************/
/*
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SMC_GAME_CORE_H
#define SMC_GAME_CORE_H
#include "../objects/movingsprite.h"
#include "../core/camera.h"
namespace SMC
{
/* *** *** *** *** *** *** *** *** Variables *** *** *** *** *** *** *** *** *** */
// quit game if true
extern bool game_exit;
// current Game Mode
extern GameMode Game_Mode;
// current Game Mode Type
extern GameModeType Game_Mode_Type;
// next global Game Action
extern GameAction Game_Action;
// Game Action data
extern CEGUI::XMLAttributes Game_Action_Data;
// Game Action pointer
extern void *Game_Action_ptr;
// internal game resolution and is used for global scaling
extern int game_res_w;
extern int game_res_h;
// global debugging
extern bool game_debug, game_debug_performance;
// Game Input event
extern SDL_Event input_event;
// global up scale ( f.e. default image scale )
extern float global_upscalex, global_upscaley;
// global down scale ( f.e. mouse/CEGUI scale )
extern float global_downscalex, global_downscaley;
// The global editor enabled variables prevent including additional editor header files
// if editor is enabled for the current game mode
extern bool editor_enabled;
// if level editor is active
extern bool editor_level_enabled;
// if world editor is active
extern bool editor_world_enabled;
// Active sprite manager
extern cSprite_Manager *pActive_Sprite_Manager;
// Active camera class
extern cCamera *pActive_Camera;
// Active player
extern cSprite *pActive_Player;
/* *** *** *** *** *** *** *** *** DialogBox *** *** *** *** *** *** *** *** *** */
class cDialogBox
{
public:
cDialogBox( void );
virtual ~cDialogBox( void );
// initialize
void Init( void );
// exit
void Exit( void );
// draw
virtual void Draw( void );
// update
virtual void Update( void );
// if finished
bool finished;
// base window
CEGUI::Window *window;
// layout filename
std::string layout_file;
// hide mouse on exit
bool mouse_hide;
};
// CEGUI EditBox with header
class cDialogBox_Text : public cDialogBox
{
public:
cDialogBox_Text( void );
virtual ~cDialogBox_Text( void );
// initialize
void Init( std::string title_text );
// enter
std::string Enter( std::string default_text, std::string title_text, bool auto_no_text = 1 );
// CEGUI events
// window quit button clicked event
bool Button_window_quit_clicked( const CEGUI::EventArgs &event );
// editbox
CEGUI::Editbox *box_editbox;
};
// Button Question Box
class cDialogBox_Question : public cDialogBox
{
public:
cDialogBox_Question( void );
virtual ~cDialogBox_Question( void );
// initialize
void Init( bool with_cancel );
// enter
int Enter( std::string text, bool with_cancel = 0 );
// CEGUI events
bool Button_yes_clicked( const CEGUI::EventArgs &event ); // yes button
bool Button_no_clicked( const CEGUI::EventArgs &event ); // no button
bool Button_cancel_clicked( const CEGUI::EventArgs &event ); // cancel button
// box window
CEGUI::FrameWindow *box_window;
// return value
int return_value;
};
/* *** *** *** *** *** *** *** Functions *** *** *** *** *** *** *** *** *** *** */
/* Change the Game Mode to the given mode
* and disables or enables game mode specific objects
*/
void Change_Game_Mode( const GameMode new_mode );
// Return the given time as string
std::string Time_to_String( time_t t, const char *format );
// Clear the complete input event queue
void Clear_Input_Events( void );
// Return the opposite Direction
ObjectDirection Get_Opposite_Direction( const ObjectDirection direction );
// Return the Direction Name
std::string Get_Direction_Name( const ObjectDirection dir );
// Return the Direction identifier
ObjectDirection Get_Direction_Id( const std::string &str_direction );
// Return the SpriteType identifier
SpriteType Get_Sprite_Type_Id( const std::string &str_type );
/* Return the Color of the given Sprite
* based mostly on sprite array
*/
Color Get_Sprite_Color( const cSprite *sprite );
// Return the massive type Name
std::string Get_Massive_Type_Name( const MassiveType mtype );
// Return the massive type identifier
MassiveType Get_Massive_Type_Id( const std::string &str_massivetype );
// Return the Color of the given Massivetype
Color Get_Massive_Type_Color( const MassiveType mtype );
// Return the ground type name
std::string Get_Ground_Type_Name( const GroundType gtype );
// Return the ground type identifier
GroundType Get_Ground_Type_Id( const std::string &str_groundtype );
// Return the Color Name
std::string Get_Color_Name( const DefaultColor color );
// Return the Color identifier
DefaultColor Get_Color_Id( const std::string &str_color );
// Update The GUI time handler
void Gui_Handle_Time( void );
/* Draw a Statictext
* if wait_for_input is given draws the text until the user pressed a key
*/
void Draw_Static_Text( const std::string &text, const Color *color_text = &white, const Color *color_bg = NULL, bool wait_for_input = 1 );
/* CEGUI EditBox with header
*
* Parameters
* default_text : default text in the EditBox
* title_text : box header text
* auto_no_text : if true and any key is pressed the default text is cleared
*/
std::string Box_Text_Input( const std::string &default_text, const std::string &title_text, bool auto_no_text = 1 );
/* Button Question Box
* returns 1 for Yes, 0 for No and -1 if canceled
*
* text : box question text
* with_cancel : add the cancel button
*/
int Box_Question( const std::string &text, bool with_cancel = 0 );
/* Preload the common images into the image manager
* draw_gui : if set use the loading screen gui for drawing
*/
void Preload_Images( bool draw_gui = 0 );
/* Preload the common sounds into the sound manager
* draw_gui : if set use the loading screen gui for drawing
*/
void Preload_Sounds( bool draw_gui = 0 );
// Changes the image path in the given xml attributes to the new one
void Relocate_Image( CEGUI::XMLAttributes &xml_attributes, const std::string &filename_old, const std::string &filename_new, const CEGUI::String &attribute_name = "image" );
// Return the clipboard content
std::string Get_Clipboard_Content( void );
// Set the clipboard content
void Set_Clipboard_Content( std::string str );
/* Copy selected GUI text to the Clipboard
* cut: if set cut the text
*/
bool GUI_Copy_To_Clipboard( bool cut = 0 );
// Paste text from the clipboard to the GUI
bool GUI_Paste_From_Clipboard( void );
// Trim the string from the end with the given character
std::string string_trim_from_end( std::string str, const char c );
// Return the number as a string
std::string int_to_string( const int number );
/* Return the float as a string
* prec: the precision after the decimal point
*/
std::string float_to_string( const float number, int prec = 6 );
// Return the string as a float
float string_to_float( const std::string &str );
// Return the string as a number
int string_to_int( const std::string &str );
// Return the string as a double
double string_to_double( const std::string &str );
// Return a valid XML string
std::string string_to_xml_string( const std::string &str );
// Return the real string
std::string xml_string_to_string( std::string str );
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
#endif
| [
"[email protected]"
] | [
[
[
1,
261
]
]
] |
788e3dd4e91258e29b7b3ad2796648d218eb8c2c | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /demo/demo_bumpmap/BumpMapApp.h | 5ba33b43b343f5a723eb79b97e83db3c9deab0fb | [] | no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | h | /*!
* \file BumpMapApp.h
* \date 6-7-2009 9:23:04
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __BUMPMAPAPP_H__
#define __BUMPMAPAPP_H__
#include "../common/BaseApp.h"
#include "../common/SimpleShape.h"
#include <libOEMsg/OEMsgShaderParam.h>
#include <OECore/IOEModel.h>
class CBumpMapApp : public CBaseApp
{
public:
CBumpMapApp();
virtual ~CBumpMapApp();
virtual bool UserDataInit();
virtual void UserDataTerm();
virtual void Update(float fDetailTime);
private:
void Init();
void Destroy();
bool OnKeyDown(COEMsgKeyboard& msg);
bool OnSetupShaderParam(COEMsgShaderParam& msg);
private:
CSimpleShape* m_pSimpleShape;
CVector3 m_vLightPos;
IOEModel* m_pModel;
bool m_bTimeStop;
};
#endif // __BUMPMAPAPP_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
43
]
]
] |
be2d0917075e45ca6b7b832fea2830695a33593c | 968aa9bac548662b49af4e2b873b61873ba6f680 | /imgtools/romtools/rofsbuild/fsnode.h | 01598f00473d1567a887f0bd5a78089a60457b80 | [] | no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,847 | h | /*
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "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:
*
*/
#ifndef __FILE_SYSTEM_ITEM_HEADER__
#define __FILE_SYSTEM_ITEM_HEADER__
#include "fatdefines.h"
#include <time.h>
class UTF16String;
class TFSNode {
public :
TFSNode(TFSNode* aParent = 0 ,const char* aFileName = 0, TUint8 aAttrs = 0, const char* aPCSideName = 0);
~TFSNode() ;
#ifdef _DEBUG
void PrintTree(int nTab = 0);
#endif
inline TUint8 GetAttrs() const { return iAttrs ;}
inline const char* GetFileName() const { return (iFileName != 0) ? iFileName : "" ;}
inline const char* GetPCSideName() const { return (iPCSideName != 0) ? iPCSideName : "" ;}
inline TFSNode* GetParent() const { return iParent;}
inline TFSNode* GetFirstChild() const {return iFirstChild;}
inline TFSNode* GetSibling() const { return iSibling ;}
// return the size of memory needed to store this entry in a FAT system
// for a file entry, it's size of file
// for a directory entry, it's sumup of memory for subdir and files entry storage
TUint GetSize() const ;
bool IsDirectory() const ;
//Except for "." and "..", every direcoty/file entry in FAT filesystem are treated as with
//"long name", for the purpose of reserving case sensitive file name.
// This function is for GetLongEntries() to know length of long name .
int GetWideNameLength() const ;
// To init the entry,
// For a file entry, aSize is the known file size,
// For a directory entry, aSize is not cared.
void Init(time_t aCreateTime, time_t aAccessTime, time_t aWriteTime, TUint aSize );
//This function is used by TFatImgGenerator::PrepareClusters, to prepare the clusters
// aClusterData should points to a buffer which is at least the size returns by
// GetSize()
void WriteDirEntries(TUint aStartIndex, TUint8* aClusterData );
protected:
void GenerateBasicName();
void MakeUniqueShortName(char rShortName[12],TUint baseNameLength) const;
void GetShortEntry(TShortDirEntry* aEntry);
int GetLongEntries(TLongDirEntry* aEntries) ;
TFSNode* iParent ;
TFSNode* iFirstChild ;
TFSNode* iSibling ;
TUint8 iAttrs ;
char* iPCSideName;
char* iFileName;
char iShortName[12];
UTF16String* iWideName ;
TTimeInteger iCrtTime ;
TDateInteger iCrtDate ;
TUint8 iCrtTimeTenth ;
TDateInteger iLstAccDate ;
TTimeInteger iWrtTime ;
TDateInteger iWrtDate ;
TUint iFileSize ;
TShortDirEntry* iFATEntry ;
};
#endif
| [
"none@none",
"[email protected]"
] | [
[
[
1,
57
],
[
59,
83
]
],
[
[
58,
58
]
]
] |
c27134ec4ec3cc94d41d4a22a005fa76eab4494c | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/burn_ym2151.cpp | 33d929a333a1975e30e68e77d63e222b633f5097 | [] | no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,732 | cpp | #include "burnint.h"
#include "burn_sound.h"
#include "burn_ym2151.h"
void (*BurnYM2151Render)(short* pSoundBuf, int nSegmentLength);
unsigned char BurnYM2151Registers[0x0100];
unsigned int nBurnCurrentYM2151Register;
static int nBurnYM2151SoundRate;
static short* pBuffer = NULL;
static short* pYM2151Buffer[2];
static int nBurnPosition;
static unsigned int nSampleSize;
static unsigned int nFractionalPosition;
static unsigned int nSamplesRendered;
static int nYM2151Volume;
static void YM2151RenderResample(short* pSoundBuf, int nSegmentLength)
{
nBurnPosition += nSegmentLength;
if (nBurnPosition >= nBurnSoundRate) {
nBurnPosition = nSegmentLength;
pYM2151Buffer[0][1] = pYM2151Buffer[0][(nFractionalPosition >> 16) - 3];
pYM2151Buffer[0][2] = pYM2151Buffer[0][(nFractionalPosition >> 16) - 2];
pYM2151Buffer[0][3] = pYM2151Buffer[0][(nFractionalPosition >> 16) - 1];
pYM2151Buffer[1][1] = pYM2151Buffer[1][(nFractionalPosition >> 16) - 3];
pYM2151Buffer[1][2] = pYM2151Buffer[1][(nFractionalPosition >> 16) - 2];
pYM2151Buffer[1][3] = pYM2151Buffer[1][(nFractionalPosition >> 16) - 1];
nSamplesRendered -= (nFractionalPosition >> 16) - 4;
for (unsigned int i = 0; i <= nSamplesRendered; i++) {
pYM2151Buffer[0][4 + i] = pYM2151Buffer[0][(nFractionalPosition >> 16) + i];
pYM2151Buffer[1][4 + i] = pYM2151Buffer[1][(nFractionalPosition >> 16) + i];
}
nFractionalPosition &= 0x0000FFFF;
nFractionalPosition |= 4 << 16;
}
pYM2151Buffer[0] = pBuffer + 4 + nSamplesRendered;
pYM2151Buffer[1] = pBuffer + 4 + nSamplesRendered + 65536;
YM2151UpdateOne(0, pYM2151Buffer, (unsigned int)(nBurnPosition + 1) * nBurnYM2151SoundRate / nBurnSoundRate - nSamplesRendered);
nSamplesRendered += (unsigned int)(nBurnPosition + 1) * nBurnYM2151SoundRate / nBurnSoundRate - nSamplesRendered;
pYM2151Buffer[0] = pBuffer;
pYM2151Buffer[1] = pBuffer + 65536;
nSegmentLength <<= 1;
for (int i = 0; i < nSegmentLength; i += 2, nFractionalPosition += nSampleSize) {
// Left channel
pSoundBuf[i + 0] = INTERPOLATE4PS_CUSTOM((nFractionalPosition >> 4) & 0x0FFF,
pYM2151Buffer[0][(nFractionalPosition >> 16) - 3],
pYM2151Buffer[0][(nFractionalPosition >> 16) - 2],
pYM2151Buffer[0][(nFractionalPosition >> 16) - 1],
pYM2151Buffer[0][(nFractionalPosition >> 16) - 0],
nYM2151Volume);
// Right channel
pSoundBuf[i + 1] = INTERPOLATE4PS_CUSTOM((nFractionalPosition >> 4) & 0x0FFF,
pYM2151Buffer[1][(nFractionalPosition >> 16) - 3],
pYM2151Buffer[1][(nFractionalPosition >> 16) - 2],
pYM2151Buffer[1][(nFractionalPosition >> 16) - 1],
pYM2151Buffer[1][(nFractionalPosition >> 16) - 0],
nYM2151Volume);
}
}
static void YM2151RenderNormal(short* pSoundBuf, int nSegmentLength)
{
nBurnPosition += nSegmentLength;
pYM2151Buffer[0] = pBuffer;
pYM2151Buffer[1] = pBuffer + nSegmentLength;
YM2151UpdateOne(0, pYM2151Buffer, nSegmentLength);
BurnSoundCopy_FM_C(pYM2151Buffer[0], pYM2151Buffer[1], pSoundBuf, nSegmentLength, nYM2151Volume, nYM2151Volume);
}
void BurnYM2151Reset()
{
YM2151ResetChip(0);
}
void BurnYM2151Exit()
{
YM2151Shutdown();
if (pBuffer)
{
free(pBuffer);
pBuffer = NULL;
}
}
int BurnYM2151Init(int nClockFrequency, float nVolume)
{
if (nBurnSoundRate <= 0) {
YM2151Init(1, nClockFrequency, 11025);
return 0;
}
if (nFMInterpolation == 3) {
// Set YM2151 core samplerate to match the hardware
nBurnYM2151SoundRate = nClockFrequency >> 6;
// Bring YM2151 core samplerate within usable range
while (nBurnYM2151SoundRate > nBurnSoundRate * 3) {
nBurnYM2151SoundRate >>= 1;
}
BurnYM2151Render = YM2151RenderResample;
nYM2151Volume = (int)((double)16384.0 * 100.0 / nVolume);
} else {
nBurnYM2151SoundRate = nBurnSoundRate;
BurnYM2151Render = YM2151RenderNormal;
nYM2151Volume = (int)((double)65536.0 * 100.0 / nVolume);
}
YM2151Init(1, nClockFrequency, nBurnYM2151SoundRate);
pBuffer = (short*)malloc(65536 * 2 * sizeof(short));
memset(pBuffer, 0, 65536 * 2 * sizeof(short));
nSampleSize = (unsigned int)nBurnYM2151SoundRate * (1 << 16) / nBurnSoundRate;
nFractionalPosition = 4 << 16;
nSamplesRendered = 0;
nBurnPosition = 0;
return 0;
}
void BurnYM2151Scan(int nAction)
{
if ((nAction & ACB_DRIVER_DATA) == 0) {
return;
}
SCAN_VAR(nBurnCurrentYM2151Register);
SCAN_VAR(BurnYM2151Registers);
if (nAction & ACB_WRITE) {
for (int i = 0; i < 0x0100; i++) {
YM2151WriteReg(0, i, BurnYM2151Registers[i]);
}
}
}
| [
"[email protected]"
] | [
[
[
1,
158
]
]
] |
659b322c2b774a561b9a74959baeb28a036301ec | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlIntrPln3Cap3.h | ae68e401dc2886414fe214c92bcdfb1e8b04f06b | [
"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,232 | 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 WMLINTRPLN3CAP3_H
#define WMLINTRPLN3CAP3_H
#include "WmlCapsule3.h"
#include "WmlPlane3.h"
namespace Wml
{
// The boolean bUnitNormal is a hint about whether or not the plane normal
// is unit length. If it is not, the length must be calculated by these
// routines. For batch calls, the plane normal should be unitized in advance
// to avoid the expensive length calculation.
template <class Real>
WML_ITEM bool TestIntersection (const Plane3<Real>& rkPlane,
const Capsule3<Real>& rkCapsule, bool bUnitNormal);
// Culling support. View frustum is assumed to be on the positive side of
// the plane. Capsule is culled if it is on the negative side.
template <class Real>
WML_ITEM bool Culled (const Plane3<Real>& rkPlane,
const Capsule3<Real>& rkCapsule, bool bUnitNormal);
}
#endif
| [
"[email protected]"
] | [
[
[
1,
38
]
]
] |
6d0385496ea19a524873c0f323e1613028c4da07 | d3cb844b081b8a15157f114adee96bd15bfdb7c5 | /Camera.h | 3a7c3768d9a831fd5130a3e1b6e3f78d3c88fef9 | [] | no_license | lucaas/RayTracer | 423f1d0269ed0a9f3a16811f71b5e9e361d6046c | 7ec5b309c1cc34a88e1d6e14aebdba55e92976d0 | refs/heads/master | 2021-01-16T19:00:23.077240 | 2011-12-12T10:15:04 | 2011-12-12T10:15:04 | 2,695,114 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 912 | h | #ifndef CAMERA_H
#define CAMERA_H
#include "Vector3.h"
class Camera
{
public:
Camera();
Camera(int,int,double,double);
~Camera();
void LookAt(cbh::vec3 _position, cbh::vec3 _target, cbh::vec3 _updirection);
void SetFov(float degrees);
void SetImagePlaneWidthHeight(double width,double height);
void SetPixelWidthHeight(unsigned int width, unsigned int height);
void SetImagePlaneCoords();
const cbh::vec3 & getPosition() const;
const cbh::vec3 & getImagePlaneBL() const;
const cbh::vec3 & getImagePlaneBR() const;
const cbh::vec3 & getImagePlaneTL() const;
const cbh::vec3 & getImagePlaneTR() const;
const cbh::vec3 & getPixelDx() const;
const cbh::vec3 & getPixelDy() const;
private:
cbh::vec3 pixelDx,pixelDy;
cbh::vec3 planeBLeft,planeBRight,planeTLeft,planeTRight,position;
unsigned int pixelWidth,pixelHeight;
double planeWidth,planeHeight;
};
#endif | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
3
],
[
5,
9
],
[
11,
11
],
[
13,
13
],
[
15,
16
],
[
27,
33
]
],
[
[
4,
4
],
[
10,
10
],
[
12,
12
],
[
14,
14
],
[
17,
26
]
]
] |
c33200f300a94be6cf58ebd40639887b716844a1 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/Virtual Machine/Operations/Operators/CompoundOperator.h | e8d409e0be84f0fe838a90fc36094b538a720419 | [] | 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 | 917 | h | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Base class for operators that can act on arrays of parameters
//
#pragma once
// Dependencies
#include "Virtual Machine/Core Entities/Operation.h"
namespace VM
{
namespace Operations
{
//
// Operation for operators that can act on arrays of parameters
//
class CompoundOperator
{
// Destruction
public:
virtual ~CompoundOperator()
{
for(std::list<VM::Operation*>::iterator iter = SubOps.begin(); iter != SubOps.end(); ++iter)
delete *iter;
}
// Array support
public:
void AddOperation(VM::Operation* op);
void AddOperationToFront(VM::Operation* op);
// Additional queries
public:
const std::list<VM::Operation*>& GetSubOperations() const
{ return SubOps; }
// Internal tracking
protected:
std::list<VM::Operation*> SubOps;
};
}
}
| [
"[email protected]",
"don.apoch@localhost"
] | [
[
[
1,
4
],
[
6,
20
],
[
22,
32
],
[
34,
49
]
],
[
[
5,
5
],
[
21,
21
],
[
33,
33
]
]
] |
7a82427a4f5bfa19f24b3ffca2659ba1125c101e | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /LuaPlus/Src/Modules/Misc/DirectoryScanner.h | 7932f11c1a576308b527de15ce76c28c8f21ac0d | [
"MIT"
] | permissive | 15831944/bastionlandscape | e1acc932f6b5a452a3bd94471748b0436a96de5d | c8008384cf4e790400f9979b5818a5a3806bd1af | refs/heads/master | 2023-03-16T03:28:55.813938 | 2010-05-21T15:00:07 | 2010-05-21T15:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | h | #ifndef MISC_DIRECTORYSCANNER_H
#define MISC_DIRECTORYSCANNER_H
#include "Misc.h"
#include "AnsiString.h"
#include <time.h>
#include "List.h"
namespace Misc {
class DirectoryEntry
{
public:
DWORD isDirectory:1;
DWORD isReadOnly:1;
time_t creationTime;
time_t lastAccessTime;
time_t lastWriteTime;
ULONGLONG fileSize;
AnsiString name;
AnsiString path;
};
class DirectoryScanner : public List<DirectoryEntry>
{
public:
enum ScanType
{
SCAN_FILES,
SCAN_DIRECTORIES,
SCAN_BOTH,
};
DirectoryScanner();
DirectoryScanner(const AnsiString& path, const char* fileSpec = "*.*", ScanType scanType = SCAN_BOTH, bool recursive = false);
void Scan(const AnsiString& path, const char* fileSpec = "*.*", ScanType scanType = SCAN_BOTH, bool recursive = false);
protected:
void ScanHelper(const AnsiString& path, const char* fileSpec = "*.*", ScanType scanType = SCAN_BOTH, bool recursive = false);
};
} // namespace Misc
#endif // MISC_DIRECTORYSCANNER_H
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
] | [
[
[
1,
45
]
]
] |
709eb99bf3c3d8ba65a640e4a656b02ac97df4d5 | 07e88c109af86db6aa3194cbb71c41d449f1a805 | /Code/m3alpsshaping/robot.cpp | b26321510ac758a15779040926070b5b5c27c2f1 | [] | no_license | jbongard/ISCS | 2a7fe528140aa24631022807c5af34d7442a122d | a7f7196a2a729564bd033abc13cdf4acb172edfb | refs/heads/master | 2016-09-05T08:44:10.630025 | 2011-08-17T15:31:58 | 2011-08-17T15:31:58 | 2,222,304 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,671 | cpp | #include "stdio.h"
#ifndef _ROBOT_CPP
#define _ROBOT_CPP
#include "robot.h"
#include "matrix.h"
extern int ROBOT_STARFISH;
extern int SHAPE_CYLINDER;
extern int SHAPE_RECTANGLE;
extern double ROBOT_STARFISH_BODY_LENGTH;
extern double ROBOT_STARFISH_BODY_WIDTH;
extern double ROBOT_STARFISH_BODY_HEIGHT;
extern double ROBOT_STARFISH_LEG_RADIUS;
extern double ROBOT_STARFISH_LEG_LENGTH;
extern double ROBOT_STARFISH_JOINT_RANGE;
extern double WORST_FITNESS;
ROBOT::ROBOT(ENVIRONMENT *cE, int robotType) {
containerEnvironment = cE;
if ( robotType == ROBOT_STARFISH )
Create_Starfish();
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->containerRobot = this;
for (int j=0; j<numJoints; j++)
if ( joints[j] )
joints[j]->containerRobot = this;
hidden = false;
physicalized = false;
neuralNetwork = NULL;
sensorDifferences = 0.0;
}
ROBOT::ROBOT(ROBOT *other) {
containerEnvironment = other->containerEnvironment;
Initialize(other);
}
ROBOT::ROBOT(ENVIRONMENT *cE, ROBOT *other) {
containerEnvironment = cE;
Initialize(other);
}
ROBOT::ROBOT(ENVIRONMENT *cE, ifstream *inFile) {
containerEnvironment = cE;
Initialize(inFile);
}
ROBOT::~ROBOT(void) {
if ( containerEnvironment )
containerEnvironment = NULL;
if ( objects ) {
for (int i=0; i<numObjects; i++) {
if ( objects[i] ) {
delete objects[i];
objects[i] = NULL;
}
}
delete[] objects;
objects = NULL;
}
if ( joints ) {
for (int j=0; j<numJoints; j++) {
if ( joints[j] ) {
delete joints[j];
joints[j] = NULL;
}
}
delete[] joints;
joints = NULL;
}
if ( neuralNetwork ) {
delete neuralNetwork;
neuralNetwork = NULL;
}
}
void ROBOT::Activate(void) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Activate();
}
void ROBOT::Deactivate(void) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Deactivate();
}
void ROBOT::Draw(void) {
if ( hidden )
return;
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Draw();
}
double ROBOT::Fitness_Get(ROBOT *targetRobot) {
/*
// if ( neuralNetwork->inAFixedAttractor )
// return( WORST_FITNESS );
double fitness = 0.0;
double diff = Sensors_Get_Total_Differences(targetRobot);
//double diff = Sensors_Get_Largest_Difference(targetRobot);
fitness = -diff;
// fitness = Sensors_Get_Total();
return( fitness );
*/
return( -sensorDifferences );
}
int ROBOT::Has_Stopped(void) {
if ( !neuralNetwork )
return( true );
return( neuralNetwork->inAFixedAttractor );
}
void ROBOT::Hide(void) {
hidden = true;
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Hide();
}
int ROBOT::In_Simulator(void) {
return( physicalized );
}
void ROBOT::Label(NEURAL_NETWORK *genome, int environmentIndex) {
if ( neuralNetwork )
delete neuralNetwork;
neuralNetwork = new NEURAL_NETWORK(genome);
}
void ROBOT::Make_Incorporeal(void) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Make_Incorporeal();
for (int j=0; j<numJoints; j++)
if ( joints[j] )
joints[j]->Make_Incorporeal();
physicalized = false;
}
void ROBOT::Make_Physical(dWorldID world, dSpaceID space) {
// Add the robot to the physical simulator.
if ( physicalized )
return;
physicalized = true;
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Make_Physical(world,space);
for (int j=0; j<numJoints; j++)
if ( joints[j] )
joints[j]->Make_Physical(world);
}
int ROBOT::Motors_Number_Of(void) {
return( numJoints );
// Assumes all joints are motorized.
}
void ROBOT::Move(int timeStep) {
// The robot is moving itself.
// The robot cannot move itself it is not physical.
if ( !physicalized )
return;
// if ( timeStep==0 )
Neural_Network_Set_Sensors();
Neural_Network_Update(timeStep);
Actuate_Motors();
Sensors_Touch_Clear();
}
void ROBOT::Move(double x, double y, double z) {
// The robot is being moved by the user.
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Move(x,y,z);
for (int j=0; j<numJoints; j++)
if ( joints[j] )
joints[j]->Move(x,y,z);
}
void ROBOT::Save(ofstream *outFile) {
(*outFile) << numObjects << "\n";
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Save(outFile);
(*outFile) << numJoints << "\n";
for (int j=0; j<numJoints; j++)
if ( joints[j] )
joints[j]->Save(outFile);
}
double ROBOT::Sensor_Sum(void) {
return( Sensors_Get_Total() );
}
void ROBOT::Sensors_Add_Difference(ROBOT *other) {
sensorDifferences = sensorDifferences +
Sensors_In_Objects_Total_Differences(other);
}
int ROBOT::Sensors_Number_Of(void) {
int numSensors = 0;
for (int i=0; i<numObjects; i++)
if ( objects[i] )
numSensors = numSensors +
objects[i]->Sensors_Number_Of();
for (int j=0; j<numJoints; j++)
if ( joints[j] )
numSensors = numSensors +
joints[j]->Sensors_Number_Of();
return( numSensors );
}
void ROBOT::Sensors_Update(void) {
// Light sensors already updated during the
// last drawing of the robot.
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Sensors_Update();
// Touch sensors updated by nearCallback function.
// Update all of the proprioceptive sensors.
for (int j=0; j<numJoints; j++)
if ( joints[j] )
joints[j]->Sensors_Update();
}
void ROBOT::Sensors_Write(void) {
Sensors_In_Objects_Write();
Sensors_In_Joints_Write();
printf("\n");
}
void ROBOT::Set_Color(double r, double g, double b) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Set_Color(r,g,b);
}
void ROBOT::Unhide(void) {
hidden = false;
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Unhide();
}
// --------------------- Private methods ------------------------
void ROBOT::Actuate_Motors(void) {
for (int j=0; j<numJoints; j++) {
double motorNeuronValue =
neuralNetwork->Get_Motor_Neuron_Value(j);
if ( joints[j] )
joints[j]->Move(motorNeuronValue);
}
}
void ROBOT::Create_Starfish(void) {
Create_Starfish_Objects();
Create_Starfish_Joints();
}
void ROBOT::Create_Starfish_Joints(void) {
// Four joints connecting each lower and upper leg, and
// four joints connecting each leg to the main body.
numJoints = 4 + 4;
joints = new JOINT * [numJoints];
for (int j=0; j<numJoints; j++)
joints[j] = NULL;
// Attach the left upper and lower legs.
joints[0] = new JOINT(this,1,5,
-ROBOT_STARFISH_BODY_LENGTH/2.0
-ROBOT_STARFISH_LEG_LENGTH,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,1,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach the right upper and lower legs.
joints[1] = new JOINT(this,2,6,
+ROBOT_STARFISH_BODY_LENGTH/2.0
+ROBOT_STARFISH_LEG_LENGTH,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,-1,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach the forward upper and lower legs.
joints[2] = new JOINT(this,3,7,
0,
+ROBOT_STARFISH_BODY_LENGTH/2.0
+ROBOT_STARFISH_LEG_LENGTH,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
1,0,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach the back upper and lower legs.
joints[3] = new JOINT(this,4,8,
0,
-ROBOT_STARFISH_BODY_LENGTH/2.0
-ROBOT_STARFISH_LEG_LENGTH,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
-1,0,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach main body and the left upper leg.
joints[4] = new JOINT(this,0,1,
-ROBOT_STARFISH_BODY_LENGTH/2.0,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,1,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach main body and the right upper leg.
joints[5] = new JOINT(this,0,2,
+ROBOT_STARFISH_BODY_LENGTH/2.0,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,-1,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach main body and the forward upper leg.
joints[6] = new JOINT(this,0,3,
0,
+ROBOT_STARFISH_BODY_LENGTH/2.0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
1,0,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
// Attach main body and the back upper leg.
joints[7] = new JOINT(this,0,4,
0,
-ROBOT_STARFISH_BODY_LENGTH/2.0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
-1,0,0,
-ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE);
for (int j=0;j<numJoints;j++)
joints[j]->Sensor_Proprioceptive_Add();
}
void ROBOT::Create_Starfish_Objects(void) {
// One main body, four upper legs and four lower legs
numObjects = 1 + 4 + 4;
objects = new OBJECT * [numObjects];
for (int i=0; i<numObjects; i++)
objects[i] = NULL;
// Main body
objects[0] = new OBJECT(SHAPE_RECTANGLE,
ROBOT_STARFISH_BODY_LENGTH,
ROBOT_STARFISH_BODY_WIDTH,
ROBOT_STARFISH_BODY_HEIGHT,
0,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,0,1);
// Left upper leg
objects[1] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
-ROBOT_STARFISH_BODY_LENGTH/2.0
-ROBOT_STARFISH_LEG_LENGTH/2.0,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
-1,0,0);
// Right upper leg
objects[2] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
+ROBOT_STARFISH_BODY_LENGTH/2.0
+ROBOT_STARFISH_LEG_LENGTH/2.0,
0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
+1,0,0);
// Forward upper leg
objects[3] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
0,
+ROBOT_STARFISH_BODY_LENGTH/2.0
+ROBOT_STARFISH_LEG_LENGTH/2.0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,+1,0);
// Back upper leg
objects[4] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
0,
-ROBOT_STARFISH_BODY_LENGTH/2.0
-ROBOT_STARFISH_LEG_LENGTH/2.0,
ROBOT_STARFISH_LEG_LENGTH
+ROBOT_STARFISH_LEG_RADIUS,
0,-1,0);
// Left lower leg
objects[5] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
-ROBOT_STARFISH_BODY_LENGTH/2.0
-ROBOT_STARFISH_LEG_LENGTH,
0,
ROBOT_STARFISH_LEG_LENGTH/2.0
+ROBOT_STARFISH_LEG_RADIUS,
0,0,+1);
// Right lower leg
objects[6] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
+ROBOT_STARFISH_BODY_LENGTH/2.0
+ROBOT_STARFISH_LEG_LENGTH,
0,
ROBOT_STARFISH_LEG_LENGTH/2.0
+ROBOT_STARFISH_LEG_RADIUS,
0,0,+1);
// Forward lower leg
objects[7] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
0,
+ROBOT_STARFISH_BODY_LENGTH/2.0
+ROBOT_STARFISH_LEG_LENGTH,
ROBOT_STARFISH_LEG_LENGTH/2.0
+ROBOT_STARFISH_LEG_RADIUS,
0,0,+1);
// Back lower leg
objects[8] = new OBJECT(SHAPE_CYLINDER,
ROBOT_STARFISH_LEG_RADIUS,
ROBOT_STARFISH_LEG_LENGTH,
0,
-ROBOT_STARFISH_BODY_LENGTH/2.0
-ROBOT_STARFISH_LEG_LENGTH,
ROBOT_STARFISH_LEG_LENGTH/2.0
+ROBOT_STARFISH_LEG_RADIUS,
0,0,+1);
for (int i=0;i<numObjects;i++)
objects[i]->Sensor_Light_Add();
objects[5]->Sensor_Touch_Add();
objects[6]->Sensor_Touch_Add();
objects[7]->Sensor_Touch_Add();
objects[8]->Sensor_Touch_Add();
}
bool ROBOT::File_Exists(char *fileName) {
ifstream ifile(fileName);
return ifile;
}
int ROBOT::File_Index_Next_Available(void) {
int fileIndex = 0;
char fileName[100];
sprintf(fileName,"SavedFiles/robot%d.dat",fileIndex);
while ( File_Exists(fileName) ) {
fileIndex++;
sprintf(fileName,"SavedFiles/robot%d.dat",fileIndex);
}
return( fileIndex );
}
void ROBOT::Initialize(ifstream *inFile) {
(*inFile) >> numObjects;
objects = new OBJECT * [numObjects];
for (int i=0; i<numObjects; i++)
objects[i] = new OBJECT(this,inFile);
(*inFile) >> numJoints;
joints = new JOINT * [numJoints];
for (int j=0; j<numJoints; j++)
joints[j] = new JOINT(this,inFile);
hidden = false;
physicalized = false;
neuralNetwork = NULL;
sensorDifferences = 0.0;
}
void ROBOT::Initialize(ROBOT *other) {
numObjects = other->numObjects;
objects = new OBJECT * [numObjects];
for (int i=0; i<numObjects; i++)
objects[i] = new OBJECT(this,other->objects[i]);
numJoints = other->numJoints;
joints = new JOINT * [numJoints];
for (int j=0; j<numJoints; j++)
joints[j] = new JOINT(this,other->joints[j]);
hidden = false;
physicalized = false;
if ( other->neuralNetwork )
neuralNetwork = new NEURAL_NETWORK(other->neuralNetwork);
else
neuralNetwork = NULL;
sensorDifferences = 0.0;
}
void ROBOT::Neural_Network_Set_Sensors(void) {
int sensorIndex = 0;
double sensorValue = 0.0;
for (int i=0; i<numObjects; i++)
if ( objects[i] ) {
if ( objects[i]->lightSensor ) {
sensorValue = objects[i]->lightSensor->Get_Value();
neuralNetwork->Sensor_Set(sensorIndex,sensorValue);
sensorIndex++;
}
if ( objects[i]->touchSensor ) {
sensorValue = objects[i]->touchSensor->Get_Value();
//sensorValue = 0.0;
neuralNetwork->Sensor_Set(sensorIndex,sensorValue);
sensorIndex++;
}
}
for (int j=0; j<numJoints; j++)
if ( joints[j] ) {
if ( joints[j]->proprioceptiveSensor ) {
sensorValue = joints[j]->proprioceptiveSensor->Get_Value();
//sensorValue = 0.0;
neuralNetwork->Sensor_Set(sensorIndex,sensorValue);
sensorIndex++;
}
}
}
void ROBOT::Neural_Network_Update(int timeStep) {
if ( !neuralNetwork )
return;
neuralNetwork->Update(timeStep);
}
void ROBOT::Sensors_Touch_Print(void) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Sensor_Touch_Print();
printf("\n");
}
double ROBOT::Sensors_Get_Largest_Difference(ROBOT *other) {
double largestDifferenceInJoints =
Sensors_In_Joints_Largest_Difference(other);
double largestDifferenceInObjects =
Sensors_In_Objects_Largest_Difference(other);
if ( largestDifferenceInJoints > largestDifferenceInObjects )
return( largestDifferenceInJoints );
else
return( largestDifferenceInObjects );
}
double ROBOT::Sensors_Get_Total_Differences(ROBOT *other) {
// return( Sensors_In_Joints_Total_Differences(other) +
// Sensors_In_Objects_Total_Differences(other) );
return( Sensors_In_Objects_Total_Differences(other) );
}
double ROBOT::Sensors_Get_Total(void) {
double sum = 0.0;
for (int i=0; i<numObjects; i++)
if ( objects[i] )
if ( objects[i]->lightSensor ) {
sum = sum +
objects[i]->lightSensor->Get_Value();
}
return( sum );
}
double ROBOT::Sensors_In_Joints_Largest_Difference(ROBOT *other) {
double diff = -1000.0;
for (int j=0; j<numJoints; j++)
if ( joints[j] )
if ( joints[j]->proprioceptiveSensor ) {
/*
PROP_SENSOR *otherSensor =
other->joints[j]->proprioceptiveSensor;
if ( otherSensor ) {
double currDiff =
joints[j]->proprioceptiveSensor->
Difference(otherSensor);
if ( currDiff > diff )
diff = currDiff;
otherSensor = NULL;
}
*/
}
return( diff );
}
double ROBOT::Sensors_In_Joints_Total_Differences(ROBOT *other) {
double diff = 0.0;
double num = 1.0;
for (int j=0; j<numJoints; j++)
if ( joints[j] &&
joints[j]->proprioceptiveSensor &&
other->joints[j] &&
other->joints[j]->proprioceptiveSensor ) {
double myVal = joints[j]->proprioceptiveSensor->Get_Value();
double otherVal = other->joints[j]->proprioceptiveSensor->Get_Value();;
diff = diff + fabs(myVal - otherVal);
num++;
}
return( diff/num );
}
void ROBOT::Sensors_In_Joints_Write(void) {
for (int j=0; j<numJoints; j++)
if ( joints[j] )
if ( joints[j]->proprioceptiveSensor )
joints[j]->proprioceptiveSensor->Write();
}
double ROBOT::Sensors_In_Objects_Largest_Difference(ROBOT *other) {
double diff = -1000.0;
for (int i=0; i<numObjects; i++)
if ( objects[i] ) {
if ( objects[i]->lightSensor ) {
LIGHT_SENSOR *otherSensor =
other->objects[i]->lightSensor;
if ( otherSensor ) {
double currDiff =
objects[i]->lightSensor->
Difference(otherSensor);
if ( currDiff > diff )
diff = currDiff;
otherSensor = NULL;
}
}
/*
if ( objects[i]->touchSensor ) {
TOUCH_SENSOR *otherSensor =
other->objects[i]->touchSensor;
if ( otherSensor ) {
double currDiff =
objects[i]->touchSensor->
Difference(otherSensor);
if ( currDiff > diff )
diff = currDiff;
otherSensor = NULL;
}
}
*/
}
return( diff );
}
double ROBOT::Sensors_In_Objects_Total_Differences(ROBOT *other) {
double diff = 0.0;
double num = 1.0;
for (int i=0; i<numObjects; i++)
if ( objects[i] &&
objects[i]->lightSensor &&
other->objects[i] &&
other->objects[i]->lightSensor ) {
double myVal = objects[i]->lightSensor->Get_Value();
double otherVal = other->objects[i]->lightSensor->Get_Value();
diff = diff + fabs(myVal - otherVal);
num++;
}
return( diff/num );
}
void ROBOT::Sensors_In_Objects_Write(void) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
if ( objects[i]->lightSensor )
objects[i]->lightSensor->Write();
}
void ROBOT::Sensors_Touch_Clear(void) {
for (int i=0; i<numObjects; i++)
if ( objects[i] )
objects[i]->Sensor_Touch_Clear();
}
#endif
| [
"[email protected]"
] | [
[
[
1,
922
]
]
] |
0f351e034542f678069719317da375c8e7fa533d | 8f9358761aca3ef7c1069175ec1d18f009b81a61 | /CPP/xCalc/src/qextserialport/qextserialbase.h | 8036f37da47de254233da8eb9f251d295932e8b5 | [] | no_license | porfirioribeiro/resplacecode | 681d04151558445ed51c3c11f0ec9b7c626eba25 | c4c68ee40c0182bd7ce07a4c059300a0dfd62df4 | refs/heads/master | 2021-01-19T10:02:34.527605 | 2009-10-23T10:14:15 | 2009-10-23T10:14:15 | 32,256,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,828 | h | #ifndef _QEXTSERIALBASE_H_
#define _QEXTSERIALBASE_H_
#include <QIODevice>
#include <QFile>
#include <QThread>
#include <QMutex>
/*if all warning messages are turned off, flag portability warnings to be turned off as well*/
#ifdef _TTY_NOWARN_
#define _TTY_NOWARN_PORT_
#endif
/*macros for thread support*/
#define LOCK_MUTEX() mutex->lock()
#define UNLOCK_MUTEX() mutex->unlock()
/*macros for warning and debug messages*/
#ifdef _TTY_NOWARN_PORT_
#define TTY_PORTABILITY_WARNING(s)
#else
#define TTY_PORTABILITY_WARNING(s) qWarning(s)
#endif /*_TTY_NOWARN_PORT_*/
#ifdef _TTY_NOWARN_
#define TTY_WARNING(s)
#else
#define TTY_WARNING(s) qWarning(s)
#endif /*_TTY_NOWARN_*/
/*line status constants*/
#define LS_CTS 0x01
#define LS_DSR 0x02
#define LS_DCD 0x04
#define LS_RI 0x08
#define LS_RTS 0x10
#define LS_DTR 0x20
#define LS_ST 0x40
#define LS_SR 0x80
/*error constants*/
#define E_NO_ERROR 0
#define E_INVALID_FD 1
#define E_NO_MEMORY 2
#define E_CAUGHT_NON_BLOCKED_SIGNAL 3
#define E_PORT_TIMEOUT 4
#define E_INVALID_DEVICE 5
#define E_BREAK_CONDITION 6
#define E_FRAMING_ERROR 7
#define E_IO_ERROR 8
#define E_BUFFER_OVERRUN 9
#define E_RECEIVE_OVERFLOW 10
#define E_RECEIVE_PARITY_ERROR 11
#define E_TRANSMIT_OVERFLOW 12
#define E_READ_FAILED 13
#define E_WRITE_FAILED 14
/*!
* Enums for port settings.
*/
enum NamingConvention
{
WIN_NAMES,
IRIX_NAMES,
HPUX_NAMES,
SUN_NAMES,
DIGITAL_NAMES,
FREEBSD_NAMES,
OPENBSD_NAMES,
LINUX_NAMES
};
enum BaudRateType
{
BAUD50, //POSIX ONLY
BAUD75, //POSIX ONLY
BAUD110,
BAUD134, //POSIX ONLY
BAUD150, //POSIX ONLY
BAUD200, //POSIX ONLY
BAUD300,
BAUD600,
BAUD1200,
BAUD1800, //POSIX ONLY
BAUD2400,
BAUD4800,
BAUD9600,
BAUD14400, //WINDOWS ONLY
BAUD19200,
BAUD38400,
BAUD56000, //WINDOWS ONLY
BAUD57600,
BAUD76800, //POSIX ONLY
BAUD115200,
BAUD128000, //WINDOWS ONLY
BAUD256000 //WINDOWS ONLY
};
enum DataBitsType
{
DATA_5,
DATA_6,
DATA_7,
DATA_8
};
enum ParityType
{
PAR_NONE,
PAR_ODD,
PAR_EVEN,
PAR_MARK, //WINDOWS ONLY
PAR_SPACE
};
enum StopBitsType
{
STOP_1,
STOP_1_5, //WINDOWS ONLY
STOP_2
};
enum FlowType
{
FLOW_OFF,
FLOW_HARDWARE,
FLOW_XONXOFF
};
/**
* structure to contain port settings
*/
struct PortSettings
{
BaudRateType BaudRate;
DataBitsType DataBits;
ParityType Parity;
StopBitsType StopBits;
FlowType FlowControl;
long Timeout_Millisec;
};
/*!
* \author Stefan Sander
* \author Michal Policht
*
* A common base class for Win_QextSerialBase, Posix_QextSerialBase and QextSerialPort.
*/
class QextSerialBase : public QIODevice
{
Q_OBJECT
public:
enum QueryMode {
Polling,
EventDriven
};
protected:
QMutex* mutex;
QString port;
PortSettings Settings;
ulong lastErr;
QextSerialBase::QueryMode _queryMode;
virtual qint64 readData(char * data, qint64 maxSize)=0;
virtual qint64 writeData(const char * data, qint64 maxSize)=0;
public:
QextSerialBase();
QextSerialBase(const QString & name);
virtual ~QextSerialBase();
virtual void construct();
virtual void setPortName(const QString & name);
virtual QString portName() const;
/**!
* Get query mode.
* \return query mode.
*/
inline QextSerialBase::QueryMode queryMode() const { return _queryMode; };
/*!
* Set desired serial communication handling style. You may choose from polling
* or event driven approach. This function does nothing when port is open; to
* apply changes port must be reopened.
*
* In event driven approach read() and write() functions are acting
* asynchronously. They return immediately and the operation is performed in
* the background, so they doesn't freeze the calling thread.
* To determine when operation is finished, QextSerialPort runs separate thread
* and monitors serial port events. Whenever the event occurs, adequate signal
* is emitted.
*
* When polling is set, read() and write() are acting synchronously. Signals are
* not working in this mode and some functions may not be available. The advantage
* of polling is that it generates less overhead due to lack of signals emissions
* and it doesn't start separate thread to monitor events.
*
* Generally event driven approach is more capable and friendly, although some
* applications may need as low overhead as possible and then polling comes.
*
* \param mode query mode.
*/
virtual void setQueryMode(QueryMode mode);
virtual void setBaudRate(BaudRateType)=0;
virtual BaudRateType baudRate() const;
virtual void setDataBits(DataBitsType)=0;
virtual DataBitsType dataBits() const;
virtual void setParity(ParityType)=0;
virtual ParityType parity() const;
virtual void setStopBits(StopBitsType)=0;
virtual StopBitsType stopBits() const;
virtual void setFlowControl(FlowType)=0;
virtual FlowType flowControl() const;
virtual void setTimeout(long)=0;
virtual bool open(OpenMode mode)=0;
virtual bool isSequential() const;
virtual void close()=0;
virtual void flush()=0;
virtual qint64 size() const = 0;
virtual qint64 bytesAvailable() const = 0;
virtual bool atEnd() const;
virtual void ungetChar(char c)=0;
virtual qint64 readLine(char * data, qint64 maxSize);
virtual ulong lastError() const;
virtual void translateError(ulong error)=0;
virtual void setDtr(bool set=true)=0;
virtual void setRts(bool set=true)=0;
virtual ulong lineStatus()=0;
signals:
/**
* This signal is emitted whenever port settings are updated.
* \param valid \p true if settings are valid, \p false otherwise.
*
* @todo implement.
*/
// void validSettings(bool valid);
/*!
* This signal is emitted whenever dsr line has changed its state. You may
* use this signal to check if device is connected.
* \param status \p true when DSR signal is on, \p false otherwise.
*
* \see lineStatus().
*/
void dsrChanged(bool status);
};
#endif
| [
"porfirioribeiro@fe5bbf2e-9c30-0410-a8ad-a51b5c886b2f"
] | [
[
[
1,
257
]
]
] |
07148dc511facf963ec469b0f3ebac4f83c61915 | 1493997bb11718d3c18c6632b6dd010535f742f5 | /direct_ui/UIlib/UIAnim.h | 9063f249ff990233b6295937ba680cc062e9d79f | [] | no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | h | #if !defined(AFX_UIANIM_H__20050522_5560_2E48_0B2D_0080AD509054__INCLUDED_)
#define AFX_UIANIM_H__20050522_5560_2E48_0B2D_0080AD509054__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////////////
//
typedef enum
{
UIANIMTYPE_FLAT,
UIANIMTYPE_SWIPE,
} UITYPE_ANIM;
/////////////////////////////////////////////////////////////////////////////////////
//
class UILIB_API CAnimJobUI
{
public:
CAnimJobUI(const CAnimJobUI& src);
CAnimJobUI(UITYPE_ANIM AnimType, DWORD dwStartTick, DWORD dwDuration, COLORREF clrBack, COLORREF clrKey, RECT rcFrom, int xtrans, int ytrans, int ztrans, int alpha, float zrot);
typedef enum
{
INTERPOLATE_LINEAR,
INTERPOLATE_COS,
} INTERPOLATETYPE;
typedef struct PLOTMATRIX
{
int xtrans;
int ytrans;
int ztrans;
int alpha;
float zrot;
} PLOTMATRIX;
UITYPE_ANIM AnimType;
DWORD dwStartTick;
DWORD dwDuration;
int iBufferStart;
int iBufferEnd;
union
{
struct
{
COLORREF clrBack;
COLORREF clrKey;
RECT rcFrom;
PLOTMATRIX mFrom;
INTERPOLATETYPE iInterpolate;
} plot;
} data;
};
#endif // !defined(AFX_UIANIM_H__20050522_5560_2E48_0B2D_0080AD509054__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
64
]
]
] |
1312aae940ff8de249279ac94f17142a1731a074 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Scd/FlwLib/SparseSlv/Indirect/mv/src/mvvi.cc | f9c54b3e46ef55037ebff39a60013704b70ea6e1 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,820 | cc |
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* */
/* */
/* MV++ Numerical Matrix/Vector C++ Library */
/* MV++ Version 1.5 */
/* */
/* R. Pozo */
/* National Institute of Standards and Technology */
/* */
/* NOTICE */
/* */
/* Permission to use, copy, modify, and distribute this software and */
/* its documentation for any purpose and without fee is hereby granted */
/* provided that this permission notice appear in all copies and */
/* supporting documentation. */
/* */
/* Neither the Institution (National Institute of Standards and Technology) */
/* nor the author makes any representations about the suitability of this */
/* software for any purpose. This software is provided ``as is''without */
/* expressed or implied warranty. */
/* */
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
//
// Basic vector class (int precision)
//
#include <iostream>
#include "..\include\mvvi.h"
MV_Vector_int::MV_Vector_int() : p_(0), dim_(0) , ref_(0){};
MV_Vector_int::MV_Vector_int( int n) : p_(new int[n]), dim_(n),
ref_(0)
{
if (p_ == NULL)
{
std::cerr << "Error: NULL pointer in MV_Vector_int(int) constructor " << "\n";
std::cerr << " Most likely out of memory... " << "\n";
exit(1);
}
}
MV_Vector_int::MV_Vector_int( int n, const int& v) :
p_(new int[n]), dim_(n), ref_(0)
{
if (p_ == NULL)
{
std::cerr << "Error: NULL pointer in MV_Vector_int(int) constructor " << "\n";
std::cerr << " Most likely out of memory... " << "\n";
exit(1);
}
for (int i=0; i<n; i++)
p_[i] = v;
}
// operators and member functions
//
MV_Vector_int& MV_Vector_int::operator=(const int & m)
{
#ifdef TRACE_VEC
cout << "> MV_Vector_int::operator=(const int & m) " << "\n";
#endif
// unroll loops to depth of length 4
int N = size();
int Nminus4 = N-4;
int i;
for (i=0; i<Nminus4; )
{
p_[i++] = m;
p_[i++] = m;
p_[i++] = m;
p_[i++] = m;
}
for (; i<N; p_[i++] = m); // finish off last piece...
#ifdef TRACE_VEC
cout << "< MV_Vector_int::operator=(const int & m) " << "\n";
#endif
return *this;
}
MV_Vector_int& MV_Vector_int::newsize( int n)
{
#ifdef TRACE_VEC
cout << "> MV_Vector_int::newsize( int n) " << "\n";
#endif
if (ref_ ) // is this structure just a pointer?
{
{
std::cerr << "MV_Vector::newsize can't operator on references.\n";
exit(1);
}
}
else
if (dim_ != n ) // only delete and new if
{ // the size of memory is really
if (p_) delete [] p_; // changing, otherwise just
p_ = new int[n]; // copy in place.
if (p_ == NULL)
{
std::cerr << "Error : NULL pointer in operator= " << "\n";
exit(1);
}
dim_ = n;
}
#ifdef TRACE_VEC
cout << "< MV_Vector_int::newsize( int n) " << "\n";
#endif
return *this;
}
MV_Vector_int& MV_Vector_int::operator=(const MV_Vector_int & m)
{
int N = m.dim_;
int i;
if (ref_ ) // is this structure just a pointer?
{
if (dim_ != m.dim_) // check conformance,
{
std::cerr << "MV_VectorRef::operator= non-conformant assignment.\n";
exit(1);
}
// handle overlapping matrix references
if ((m.p_ + m.dim_) >= p_)
{
// overlap case, copy backwards to avoid overwriting results
for (i= N-1; i>=0; i--)
p_[i] = m.p_[i];
}
else
{
for (i=0; i<N; i++)
p_[i] = m.p_[i];
}
}
else
{
newsize(N);
// no need to test for overlap, since this region is new
for (i =0; i< N; i++) // careful not to use bcopy()
p_[i] = m.p_[i]; // here, but int::operator= int.
}
return *this;
}
MV_Vector_int::MV_Vector_int(const MV_Vector_int & m) : p_(new int[m.dim_]),
dim_(m.dim_) , ref_(0)
{
if (p_ == NULL)
{
std::cerr << "Error: Null pointer in MV_Vector_int(const MV_Vector&); " << "\n";
exit(1);
}
int N = m.dim_;
for (int i=0; i<N; i++)
p_[i] = m.p_[i];
}
MV_Vector_int::MV_Vector_int(int* d, int n) : p_(new int[n]),
dim_(n) , ref_(0)
{
if (p_ == NULL)
{
std::cerr << "Error: Null pointer in MV_Vector_int(int*, int) " << "\n";
exit(1);
}
for (int i=0; i<n; i++)
p_[i] = d[i];
}
MV_Vector_int::MV_Vector_int(const int* d, int n) : p_(new int[n]),
dim_(n) , ref_(0)
{
if (p_ == NULL)
{
std::cerr << "Error: Null pointer in MV_Vector_int(int*, int) " << "\n";
exit(1);
}
for (int i=0; i<n; i++)
p_[i] = d[i];
}
MV_Vector_int MV_Vector_int::operator()(void)
{
return MV_Vector_int(p_, dim_, MV_Vector_::ref);
}
const MV_Vector_int MV_Vector_int::operator()(void) const
{
return MV_Vector_int(p_, dim_, MV_Vector_::ref);
}
MV_Vector_int MV_Vector_int::operator()(const MV_VecIndex &I)
{
// default parameters
if (I.all())
return MV_Vector_int(p_, dim_, MV_Vector_::ref);
else
{
// check that index is not out of bounds
//
if ( I.end() >= dim_)
{
std::cerr << "MV_VecIndex: (" << I.start() << ":" << I.end() <<
") too big for matrix (0:" << dim_ - 1 << ") " << "\n";
exit(1);
}
return MV_Vector_int(p_+ I.start(), I.end() - I.start() + 1,
MV_Vector_::ref);
}
}
const MV_Vector_int MV_Vector_int::operator()(const MV_VecIndex &I) const
{
// check that index is not out of bounds
//
if (I.all())
return MV_Vector_int(p_, dim_, MV_Vector_::ref);
else
{
if ( I.end() >= dim_)
{
std::cerr << "MV_VecIndex: (" << I.start() << ":" << I.end() <<
") too big for matrix (0:" << dim_ - 1 << ") " << "\n";
exit(1);
}
return MV_Vector_int(p_+ I.start(), I.end() - I.start() + 1,
MV_Vector_::ref);
}
}
MV_Vector_int::~MV_Vector_int()
{
if (p_ && !ref_ ) delete [] p_;
}
std::ostream& operator<<(std::ostream& s, const MV_Vector_int& V)
{
int N = V.size();
for (int i=0; i< N; i++)
s << V(i) << "\n";
return s;
}
| [
"[email protected]"
] | [
[
[
1,
285
]
]
] |
df34bb6aa7756861d2b802ccffc9b2c9173fead7 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/Aran/ArnXmlLoader.cpp | b63da38e4da1f56aa6719b6c1760d1a8fc05d310 | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,533 | cpp | #include "AranPCH.h"
#include "ArnXmlLoader.h"
#include "ArnSceneGraph.h"
#include "ArnMesh.h"
#include "ArnCamera.h"
#include "ArnLight.h"
#include "ArnMaterial.h"
#include "ArnSkeleton.h"
#include "ArnBone.h"
#include "ArnIpo.h"
#include "ArnAction.h"
#include "ArnBinaryChunk.h"
#include "ArnMath.h"
#include "ArnTexture.h"
#include "ArnPathManager.h"
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
static bool gs_xmlInitialized = false;
ArnXmlLoader::ArnXmlLoader()
{
//ctor
}
ArnXmlLoader::~ArnXmlLoader()
{
//dtor
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static void
GetAttr(std::string& val, const TiXmlElement* elm, const char* attrName)
{
const char* str = elm->Attribute(attrName);
assert(str);
val = str;
}
static float
ParseFloatFromAttr(const TiXmlElement* elm, const char* attrName)
{
float f;
int ret = elm->QueryFloatAttribute(attrName, &f);
if (ret == TIXML_SUCCESS)
{
}
else if (ret == TIXML_NO_ATTRIBUTE)
{
f = 0;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
return f;
}
static int
ParseIntFromAttr(const TiXmlElement* elm, const char* attrName)
{
int i;
int ret = elm->QueryIntAttribute(attrName, &i);
if (ret == TIXML_SUCCESS)
{
}
else if (ret == TIXML_NO_ATTRIBUTE)
{
i = 0;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
return i;
}
static void
ParseRgbFromElementAttr(float* r, float* g, float* b, const TiXmlElement* elm)
{
*r = ParseFloatFromAttr(elm, "r");
*g = ParseFloatFromAttr(elm, "g");
*b = ParseFloatFromAttr(elm, "b");
}
static void
ParseRgbaFromElementAttr(float* r, float* g, float* b, float* a, const TiXmlElement* elm)
{
ParseRgbFromElementAttr(r, g, b, elm);
*a = ParseFloatFromAttr(elm, "a");
}
static void
ParseArnVec3FromElementAttr(ArnVec3* v, const TiXmlElement* elm)
{
v->x = ParseFloatFromAttr(elm, "x");
v->y = ParseFloatFromAttr(elm, "y");
v->z = ParseFloatFromAttr(elm, "z");
}
static void
ParseArnVec3FromElement(ArnVec3* v, const TiXmlElement* elm)
{
if (sscanf(elm->GetText(), "%f %f %f", &v->x, &v->y, &v->z) != 3)
ARN_THROW_UNEXPECTED_CASE_ERROR
}
static void
Parse2FloatsFromElement(float* f0, float* f1, const TiXmlElement* elm)
{
if (sscanf(elm->GetText(), "%f %f", f0, f1) != 2)
{
// NOTE: Microsoft Visual C++ link error if we use ARN_THROW_UNEXPECTED_CASE_ERROR
// instead of abort() on release build. Why???!!!
abort();
}
}
static void
AssertTagNameEquals(const TiXmlElement* elm, const char* tagName)
{
if (strcmp(elm->Value(), tagName) != 0)
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
}
static bool
AttrEquals(const TiXmlElement* elm, const char* attrName, const char* attrVal)
{
std::string val;
GetAttr(val, elm, attrName);
return strcmp(val.c_str(), attrVal) ? false : true;
}
static void
AssertAttrEquals(const TiXmlElement* elm, const char* attrName, const char* attrVal)
{
if (!AttrEquals(elm, attrName, attrVal))
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
}
static const TiXmlElement*
GetUniqueChildElement(const TiXmlElement* elm, const char* tagName)
{
int directChildrenCount = 0;
const TiXmlElement* uniqueChildren = 0;
for (const TiXmlElement* e = elm->FirstChildElement(tagName); e; e = e->NextSiblingElement(tagName))
{
assert(e->Parent() == elm);
++directChildrenCount;
uniqueChildren = e;
}
if (directChildrenCount == 1)
{
return uniqueChildren;
}
else if (directChildrenCount == 0)
{
return 0;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
}
static void
ParseTransformFromElement(ArnMatrix* mat, ArnVec3* scale, ArnQuat* rQuat, ArnVec3* trans,
const TiXmlElement* elm)
{
AssertTagNameEquals(elm, "transform");
if (AttrEquals(elm, "type", "srt"))
{
const TiXmlElement* scaling = GetUniqueChildElement(elm, "scaling");
const TiXmlElement* rotation = GetUniqueChildElement(elm, "rotation");
const TiXmlElement* translation = GetUniqueChildElement(elm, "translation");
ArnVec3 s(1,1,1);
ArnVec3 r(0,0,0);
ArnVec3 t(0,0,0);
if (scaling)
{
ParseArnVec3FromElementAttr(&s, scaling);
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
if (rotation)
{
AssertAttrEquals(rotation, "type", "euler");
AssertAttrEquals(rotation, "unit", "deg");
ParseArnVec3FromElementAttr(&r, rotation);
r.x = ArnToRadian(r.x);
r.y = ArnToRadian(r.y);
r.z = ArnToRadian(r.z);
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
if (translation)
{
ParseArnVec3FromElementAttr(&t, translation);
}
ArnQuat rQ;
rQ = ArnEulerToQuat(&r);
assert(rQuat && scale && trans);
*rQuat = rQ;
*scale = s;
*trans = t;
if (mat) // Matrix output is optional.
ArnMatrixTransformation(mat, 0, 0, &s, 0, &rQ, &t);
}
else
{
assert(!"Unsupported type.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static void
SetupArnNodeCommonPart(ArnNode* ret, const TiXmlElement* elm)
{
std::string name;
GetAttr(name, elm, "name");
ret->setName(name.c_str());
}
static void
SetupArnXformableCommonPart(ArnXformable* ret, const TiXmlElement* elm)
{
// Setup ArnXformable common part.
// This includes ArnNode part and
// 'transformation', and 'ipo'.
SetupArnNodeCommonPart(ret, elm);
ArnVec3 trans, scale;
ArnQuat rot;
const TiXmlElement* transformElm = GetUniqueChildElement(elm, "transform");
ParseTransformFromElement(0, &scale, &rot, &trans, transformElm);
ret->setLocalXform_Scale(scale);
ret->setLocalXform_Rot(rot);
ret->setLocalXform_Trans(trans);
ret->recalcLocalXform();
const TiXmlElement* ipoElm = GetUniqueChildElement(elm, "ipo");
if (ipoElm)
{
std::string ipoName;
GetAttr(ipoName, ipoElm, "name");
ret->setIpoName(ipoName.c_str());
}
else
{
ret->setIpoName("");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
template <typename T> void
parseFromToken(const char* targetConst, int& dataOffset, Tokenizer::const_iterator& it,
const int doCount, T func(const char*))
{
assert(doCount >= 1);
char* target = const_cast<char*>(targetConst); // TODO: const_cast used.
for (int i = 0; i < doCount; ++i)
{
*(T*)(target + i*sizeof(T)) = func((*it).c_str());
++it;
dataOffset += sizeof(T);
}
}
inline float
atof2(const char* c)
{
return (float)atof(c);
}
ArnBinaryChunk*
ArnBinaryChunk::createFrom(const TiXmlElement* elm, const char* binaryChunkBasePtr)
{
ArnBinaryChunk* ret = new ArnBinaryChunk();
const TiXmlElement* templ = elm->FirstChildElement("template");
assert(templ);
for (const TiXmlElement* e = templ->FirstChildElement("field"); e; e = e->NextSiblingElement("field"))
{
std::string typeStr, usageStr;
GetAttr(typeStr, e, "type");
GetAttr(usageStr, e, "usage");
ret->addField( typeStr.c_str(), usageStr.c_str() );
}
assert(ret->getFieldCount());
std::string placeStr;
GetAttr(placeStr, elm, "place");
if (strcmp(placeStr.c_str(), "xml") == 0)
{
const TiXmlElement* arraydata = elm->FirstChildElement("arraydata");
ret->m_recordCount = 0;
for (const TiXmlElement* e = arraydata->FirstChildElement("data"); e; e = e->NextSiblingElement("data"))
{
++ret->m_recordCount;
}
if (ret->m_recordCount > 0)
{
ret->m_data = new char[ ret->m_recordCount * ret->m_recordSize ];
}
else if (ret->m_recordCount == 0)
{
ret->m_data = 0;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
ret->m_deallocateData = true;
int dataOffset = 0;
for (const TiXmlElement* e = arraydata->FirstChildElement("data"); e; e = e->NextSiblingElement("data"))
{
std::string attrStr;
GetAttr(attrStr, e, "value");
boost::char_separator<char> sep(";");
Tokenizer tok(attrStr, sep);
Tokenizer::const_iterator it = tok.begin();
foreach (const Field& field, ret->m_recordDef)
{
switch (field.type)
{
case ACFT_FLOAT:
parseFromToken<float>(ret->m_data + dataOffset, dataOffset, it, 1, atof2);
break;
case ACFT_FLOAT2:
parseFromToken<float>(ret->m_data + dataOffset, dataOffset, it, 2, atof2);
break;
case ACFT_FLOAT3:
parseFromToken<float>(ret->m_data + dataOffset, dataOffset, it, 3, atof2);
break;
case ACFT_FLOAT8:
parseFromToken<float>(ret->m_data + dataOffset, dataOffset, it, 8, atof2);
break;
case ACFT_INT:
parseFromToken<int>(ret->m_data + dataOffset, dataOffset, it, 1, atoi);
break;
case ACFT_INT3:
parseFromToken<int>(ret->m_data + dataOffset, dataOffset, it, 3, atoi);
break;
case ACFT_INT4:
parseFromToken<int>(ret->m_data + dataOffset, dataOffset, it, 4, atoi);
break;
default:
assert(!"Should not reach here!");
break;
}
}
assert(dataOffset % ret->m_recordSize == 0);
}
assert(dataOffset == ret->m_recordCount * ret->m_recordSize);
}
else if (strcmp(placeStr.c_str(), "bin") == 0)
{
const int startOffset = ParseIntFromAttr(elm, "startoffset");
const int endOffset = ParseIntFromAttr(elm, "endoffset");
const int dataSize = endOffset - startOffset;
const int recordCount = dataSize / ret->m_recordSize;
assert(dataSize % ret->m_recordSize == 0);
if (recordCount)
ret->m_data = binaryChunkBasePtr + startOffset;
else
ret->m_data = 0;
ret->m_deallocateData = false;
ret->m_recordCount = recordCount;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
return ret;
}
void ArnxCreateArnNodeFromChildObjects(ArnNode* parentNode, const TiXmlElement* parentElm, ArnSceneGraph* sg, const char* binDataPtr)
{
for (const TiXmlElement* e = parentElm->FirstChildElement("object"); e; e = e->NextSiblingElement("object"))
{
const TiXmlElement* childElm = e;
assert(childElm);
ArnNode* childObj = CreateArnNodeFromXmlElement(childElm, binDataPtr);
parentNode->attachChild(childObj);
// 카메라는 별도의 리스트를 만들어서 쉽게 탐색할 수 있도록 한다.
if (childObj->getType() == NDT_RT_CAMERA)
{
sg->registerToCameraList(static_cast<ArnCamera*>(childObj));
}
ArnxCreateArnNodeFromChildObjects(childObj, childElm, sg, binDataPtr);
}
}
ArnSceneGraph*
ArnSceneGraph::createFrom(const char* xmlFile)
{
// File extension assertion
assert(xmlFile);
if (strlen(xmlFile) == 0)
return 0;
assert(strcmp(xmlFile + strlen(xmlFile) - 4, ".xml") == 0);
assert(gs_xmlInitialized);
//// 경로명에 포함된 특정한 심볼을
//// 찾아서 원래 값으로 찾아 바꾸기를 한다.
//// 현재는 임시로 구현되어 있는 상태.
//std::string xmlFileStr = xmlFile;
// std::string working;
// if (getenv("WORKING")) {
// working = getenv("WORKING");
// std::cout << "Working directory set from the environment variable WORKING.\n";
// } else {
// char *workingCstr = GetCurrentDir (0, 0);
// working = workingCstr;
// std::cout << "Working directory set from the function getcwd().\n";
// free(workingCstr);
// }
//const std::string mp("{ModelPath}");
//const std::string modelPath(working + "/models/");
//if (xmlFileStr.find(mp) != -1)
// xmlFileStr.replace(xmlFileStr.find(mp), mp.length(), modelPath);
//xmlFile = xmlFileStr.c_str();
std::string full_path = aran::core::PathManager::getSingleton().get_model_path() + xmlFile;
xmlFile = full_path.c_str();
// XML file loading
TiXmlDocument xmlDoc(xmlFile);
if (!xmlDoc.LoadFile())
{
std::cerr << "Scene file " << xmlFile << " not found." << std::endl;
return 0;
}
const TiXmlElement* elm = xmlDoc.RootElement();
AssertTagNameEquals(elm, "object");
std::string sceneNameStr;
GetAttr(sceneNameStr, elm, "name");
std::cout << " - Root scene name: " << sceneNameStr.c_str() << std::endl;
AssertAttrEquals(elm, "rtclass", "ArnSceneGraph");
ArnSceneGraph* ret = ArnSceneGraph::createFromEmptySceneGraph();
SetupArnNodeCommonPart(ret, elm);
std::string binaryFileName(xmlFile);
// Only the extension is differ from 'xml' to 'bin'.
binaryFileName[binaryFileName.size() - 3] = 'b';
binaryFileName[binaryFileName.size() - 2] = 'i';
binaryFileName[binaryFileName.size() - 1] = 'n';
unsigned int binUncompressedSize = (unsigned int)ParseIntFromAttr(elm, "binuncompressedsize");
ret->m_binaryChunk = ArnBinaryChunk::createFrom(binaryFileName.c_str(), true, binUncompressedSize);
const char* binDataPtr = ret->m_binaryChunk->getConstRawDataPtr();
ArnxCreateArnNodeFromChildObjects(ret, elm, ret, binDataPtr);
return ret;
}
ArnMesh*
ArnMesh::createFrom(const TiXmlElement* elm, const char* binaryChunkBasePtr)
{
AssertAttrEquals(elm, "rtclass", "ArnMesh");
ArnMesh* ret = new ArnMesh();
SetupArnXformableCommonPart(ret, elm);
const TiXmlElement* meshElm = GetUniqueChildElement(elm, "mesh");
const TiXmlElement* vertexElm = GetUniqueChildElement(meshElm, "vertex");
const TiXmlElement* faceElm = GetUniqueChildElement(meshElm, "face");
assert(vertexElm && faceElm);
if (ParseIntFromAttr(meshElm, "twosided"))
{
ret->setTwoSided(true);
}
// vertex-chunk element (contains the whole vertices of this mesh)
const TiXmlElement* vertexChunkElm = GetUniqueChildElement(vertexElm, "chunk");
ret->m_vertexChunk = ArnBinaryChunk::createFrom(vertexChunkElm, binaryChunkBasePtr);
// Process vertex groups
// Note: There is an implicitly created vertex group 0 which includes
// the entire vertices having material 0 and unit-weights.
VertexGroup vg0;
vg0.name = "Vertex Group 0";
vg0.mtrlIndex = 0;
vg0.vertGroupChunk = 0;
ret->m_vertexGroup.push_back(vg0);
for (const TiXmlElement* e = meshElm->FirstChildElement("vertgroup"); e; e = e->NextSiblingElement("vertgroup"))
{
VertexGroup vg;
GetAttr(vg.name, e, "name");
vg.mtrlIndex = 0; // TODO: Vertex group mtrl
vg.vertGroupChunk = ArnBinaryChunk::createFrom(GetUniqueChildElement(e, "chunk"), binaryChunkBasePtr);
assert(vg.vertGroupChunk->getRecordCount());
ret->m_vertexGroup.push_back(vg);
}
// Process face groups
for (const TiXmlElement* e = faceElm->FirstChildElement("facegroup"); e; e = e->NextSiblingElement("facegroup"))
{
const TiXmlElement* faceGroupElm = e;
std::string ssMtrl;
GetAttr(ssMtrl, faceGroupElm, "mtrl");
ArnMesh::FaceGroup fg;
fg.mtrlIndex = atoi(ssMtrl.c_str());
fg.triFaceChunk = 0;
fg.quadFaceChunk = 0;
assert(fg.mtrlIndex >= 0);
int chunkCount = 0;
for (const TiXmlElement* e2 = faceGroupElm->FirstChildElement("chunk"); e2; e2 = e2->NextSiblingElement("chunk"))
{
switch (chunkCount)
{
case 0:
fg.triFaceChunk = ArnBinaryChunk::createFrom(e2, binaryChunkBasePtr);
break;
case 1:
fg.quadFaceChunk = ArnBinaryChunk::createFrom(e2, binaryChunkBasePtr);
break;
default:
ARN_THROW_UNEXPECTED_CASE_ERROR
}
++chunkCount;
}
assert(chunkCount == 2);
assert(fg.triFaceChunk && fg.quadFaceChunk);
ret->m_faceGroup.push_back(fg);
}
// Process materials
for (const TiXmlElement* e = meshElm->FirstChildElement("material"); e; e = e->NextSiblingElement("material"))
{
std::string ss;
GetAttr(ss, e, "name");
ret->m_mtrlRefNameList.push_back(ss.c_str());
}
// Process UV coordinates
ret->m_triquadUvChunk = 0;
for (const TiXmlElement* e = meshElm->FirstChildElement("uv"); e; e = e->NextSiblingElement("uv"))
{
const TiXmlElement* triquadUvElm = e->FirstChildElement("chunk");
assert(triquadUvElm);
ret->m_triquadUvChunk = ArnBinaryChunk::createFrom(triquadUvElm, binaryChunkBasePtr);
}
// Process physics-related
const TiXmlElement* bbElm = GetUniqueChildElement(elm, "boundingbox");
if (bbElm)
{
const TiXmlElement* bbChunkElm = GetUniqueChildElement(bbElm, "chunk");
assert(bbChunkElm);
std::auto_ptr<ArnBinaryChunk> abc(ArnBinaryChunk::createFrom(bbChunkElm, binaryChunkBasePtr));
assert(abc->getRecordCount() == 8); // Should have 8 corner points of bounding box
ArnVec3 bb[8];
for (int i = 0; i < 8; ++i)
bb[i] = *reinterpret_cast<const ArnVec3*>(abc->getRecordAt(i));
ret->setBoundingBoxPoints(bb);
}
const TiXmlElement* actorElm = GetUniqueChildElement(elm, "actor");
if (actorElm)
{
assert(ret->m_bPhyActor == false);
ret->m_bPhyActor = true;
std::string s;
GetAttr(s, actorElm, "bounds");
if (s == "box")
{
ret->m_abbt = ABBT_BOX;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
const TiXmlElement* rigidbodyElm = GetUniqueChildElement(actorElm, "rigidbody");
if (rigidbodyElm)
{
ret->m_mass = ParseFloatFromAttr(rigidbodyElm, "mass"); // Have dynamics property
}
else
{
ret->m_mass = 0; // This object will be completely fixed in dynamics environment.
}
if (ret->getLocalXform_Scale().compare(ArnConsts::ARNVEC3_ONE) > 0.001)
{
// When a mesh is governed by dynamics, there is no scaling to make valid bounding volume.
ARN_THROW_UNEXPECTED_CASE_ERROR
}
}
// Process constraints
for (const TiXmlElement* e = elm->FirstChildElement("constraint"); e; e = e->NextSiblingElement("constraint"))
{
const char* type = e->Attribute("type");
if (strcmp(type, "rigidbodyjoint") == 0)
{
const TiXmlElement* targetElm = e->FirstChildElement("target");
const TiXmlElement* pivotElm = e->FirstChildElement("pivot");
const TiXmlElement* axElm = e->FirstChildElement("ax");
assert(targetElm && pivotElm && axElm);
ArnJointData ajd;
ajd.target = targetElm->GetText();
ParseArnVec3FromElement(&ajd.pivot, pivotElm);
ParseArnVec3FromElement(&ajd.ax, axElm);
for (const TiXmlElement* ee = e->FirstChildElement("limit"); ee; ee = ee->NextSiblingElement("limit"))
{
const char* limitType = ee->Attribute("type");
ArnJointData::ArnJointLimit ajl;
ajl.type = limitType;
Parse2FloatsFromElement(&ajl.minimum, &ajl.maximum, ee);
ajd.limits.push_back(ajl);
}
ret->addJointData(ajd);
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
}
ret->m_data.materialCount = ret->m_mtrlRefNameList.size();
return ret;
}
ArnMaterial*
ArnMaterial::createFrom(const TiXmlElement* elm)
{
AssertAttrEquals(elm, "rtclass", "ArnMaterial");
ArnMaterial* ret = new ArnMaterial();
SetupArnNodeCommonPart(ret, elm);
const TiXmlElement* materialElm = GetUniqueChildElement(elm, "material");
const TiXmlElement* diffuseElm = GetUniqueChildElement(materialElm, "diffuse");
const TiXmlElement* ambientElm = GetUniqueChildElement(materialElm, "ambient");
const TiXmlElement* specularElm = GetUniqueChildElement(materialElm, "specular");
const TiXmlElement* emissiveElm = GetUniqueChildElement(materialElm, "emissive");
const TiXmlElement* powerElm = GetUniqueChildElement(materialElm, "power");
assert(diffuseElm && ambientElm && specularElm && emissiveElm && powerElm);
int shadeless = ParseIntFromAttr(materialElm, "shadeless");
if (shadeless)
ret->m_bShadeless = true;
float r, g, b, a;
// TODO: Light colors...
std::string mtrlName;
GetAttr(mtrlName, elm, "name");
ret->m_data.m_materialName = mtrlName.c_str();
ParseRgbaFromElementAttr(&r, &g, &b, &a, diffuseElm);
ret->m_data.m_d3dMaterial.Diffuse = ArnColorValue4f(r, g, b, a);
if (a == 0)
std::cerr << " *** Warning: material " << mtrlName.c_str() << " diffuse alpha is zero." << std::endl;
ParseRgbaFromElementAttr(&r, &g, &b, &a, ambientElm);
ret->m_data.m_d3dMaterial.Ambient = ArnColorValue4f(r, g, b, a);
if (a == 0)
std::cerr << " *** Warning: material " << mtrlName.c_str() << " ambient alpha is zero." << std::endl;
ParseRgbaFromElementAttr(&r, &g, &b, &a, specularElm);
ret->m_data.m_d3dMaterial.Specular = ArnColorValue4f(r, g, b, a);
if (a == 0)
std::cerr << " *** Warning: material " << mtrlName.c_str() << " specular alpha is zero." << std::endl;
ParseRgbaFromElementAttr(&r, &g, &b, &a, emissiveElm);
ret->m_data.m_d3dMaterial.Emissive = ArnColorValue4f(r, g, b, 1);
// Don't care emissive alpha.
/*
if (a == 0)
std::cerr << " *** Warning: material " << mtrlName.c_str() << " emissive alpha is zero." << std::endl;
*/
ret->m_data.m_d3dMaterial.Power = ParseFloatFromAttr(powerElm, "value");
for (const TiXmlElement* e = materialElm->FirstChildElement("texture"); e; e = e->NextSiblingElement("texture"))
{
const TiXmlElement* textureElm = e;
if (AttrEquals(textureElm, "type", "image"))
{
std::string texImageFileName;
GetAttr(texImageFileName, textureElm, "path");
// Preceding two slashes of file path indicate
// the present working directory; should be removed first.
if (strcmp(texImageFileName.substr(0, 2).c_str(), "//") == 0)
{
texImageFileName = texImageFileName.substr(2, texImageFileName.length() - 2);
}
ArnTexture* tex = ArnTexture::createFrom(texImageFileName.c_str());
ret->attachTexture(tex);
}
else
{
ARN_THROW_NOT_IMPLEMENTED_ERROR
}
}
return ret;
}
ArnCamera*
ArnCamera::createFrom(const TiXmlElement* elm)
{
AssertAttrEquals(elm, "rtclass", "ArnCamera");
ArnCamera* ret = new ArnCamera();
SetupArnXformableCommonPart(ret, elm);
const TiXmlElement* cameraElm = GetUniqueChildElement(elm, "camera");
float farClip = ParseFloatFromAttr(cameraElm, "farclip");
float nearClip = ParseFloatFromAttr(cameraElm, "nearclip");
float fovdeg = ParseFloatFromAttr(cameraElm, "fovdeg");
float scale = ParseFloatFromAttr(cameraElm, "scale");
ret->setFarClip(farClip);
ret->setNearClip(nearClip);
ret->setFov(ArnToRadian(fovdeg));
ret->setOrthoScale(scale);
std::string typeStr;
GetAttr(typeStr, cameraElm, "type");
if (strcmp(typeStr.c_str(), "persp") == 0)
{
ret->setOrtho(false);
}
else if (strcmp(typeStr.c_str(), "ortho") == 0)
{
ret->setOrtho(true);
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
return ret;
}
ArnLight*
ArnLight::createFrom( const TiXmlElement* elm )
{
AssertAttrEquals(elm, "rtclass", "ArnLight");
ArnLight* ret = new ArnLight();
SetupArnXformableCommonPart(ret, elm);
const TiXmlElement* lightElm = GetUniqueChildElement(elm, "light");
float r, g, b;
ParseRgbFromElementAttr(&r, &g, &b, lightElm);
ret->m_d3dLight.Ambient = ArnColorValue4f(r, g, b, 1);
ret->m_d3dLight.Diffuse = ArnColorValue4f(r, g, b, 1);
ret->m_d3dLight.Specular = ArnColorValue4f(r, g, b, 1);
std::string lightTypeStr;
GetAttr(lightTypeStr, lightElm, "type");
if (strcmp(lightTypeStr.c_str(), "point") == 0)
{
// Point light
ret->m_d3dLight.Type = ARNLIGHT_POINT;
ret->m_d3dLight.Position = ret->getLocalXform_Trans();
}
else if (strcmp(lightTypeStr.c_str(), "spot") == 0)
{
// Spot light
ret->m_d3dLight.Type = ARNLIGHT_SPOT;
ARN_THROW_NOT_IMPLEMENTED_ERROR
}
else if (strcmp(lightTypeStr.c_str(), "directional") == 0)
{
// Directional light
ret->m_d3dLight.Type = ARNLIGHT_DIRECTIONAL;
ArnVec3 negZ(0, 0, 1);
ArnVec3 dir;
ArnMatrix rot;
ret->getLocalXform_Rot().getRotationMatrix(&rot);
ArnVec3TransformCoord(&dir, &negZ, &rot);
ret->m_d3dLight.Direction = dir;
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
return ret;
}
ArnSkeleton*
ArnSkeleton::createFrom( const TiXmlElement* elm )
{
AssertAttrEquals(elm, "rtclass", "ArnSkeleton");
ArnSkeleton* ret = new ArnSkeleton();
SetupArnXformableCommonPart(ret, elm);
for (const TiXmlElement* e = elm->FirstChildElement("actionstrip"); e; e = e->NextSiblingElement("actionstrip"))
{
const TiXmlElement* actStripElm = e;
std::string asName;
GetAttr(asName, actStripElm, "name");
ret->m_actionStripNames.push_back(asName);
}
const TiXmlElement* actionElm = GetUniqueChildElement(elm, "action");
if (actionElm)
{
std::string defActName;
GetAttr(defActName, actionElm, "name");
ret->setDefaultActionName(defActName.c_str());
}
else
{
ret->setDefaultActionName("");
}
const TiXmlElement* skelElm = GetUniqueChildElement(elm, "skeleton");
for (const TiXmlElement* e = skelElm->FirstChildElement("object"); e; e = e->NextSiblingElement("object"))
{
const TiXmlElement* boneElm = e;
if (boneElm->Parent() == skelElm)
{
ArnNode* bone = CreateArnNodeFromXmlElement(boneElm, 0);
ret->attachChild(bone);
}
}
for (const TiXmlElement* e = skelElm->FirstChildElement("constraint"); e; e = e->NextSiblingElement("constraint"))
{
if (e->Parent() == skelElm)
{
const char* type = e->Attribute("type");
if (strcmp(type, "limitrot") == 0)
{
const TiXmlElement* targetElm = e->FirstChildElement("target");
assert(targetElm);
const char* targetBoneName = targetElm->GetText();
ArnNode* boneNode = ret->getNodeByName(targetBoneName);
ArnBone* bone = dynamic_cast<ArnBone*>(boneNode);
assert(bone);
for (const TiXmlElement* ee = e->FirstChildElement("limit"); ee; ee = ee->NextSiblingElement("limit"))
{
const char* limitType = ee->Attribute("type");
const char* unit = ee->Attribute("unit");
AxisEnum axis;
float minimum, maximum;
Parse2FloatsFromElement(&minimum, &maximum, ee);
if (strcmp(unit, "deg") == 0)
{
minimum = ArnToRadian(minimum);
maximum = ArnToRadian(maximum);
}
if (strcmp(limitType, "AngX") == 0)
axis = AXIS_X;
else if (strcmp(limitType, "AngY") == 0)
axis = AXIS_Y;
else if (strcmp(limitType, "AngZ") == 0)
axis = AXIS_Z;
else
ARN_THROW_UNEXPECTED_CASE_ERROR
bone->setRotLimit(axis, minimum, maximum);
}
}
else
{
ARN_THROW_UNEXPECTED_CASE_ERROR
}
}
}
return ret;
}
ArnBone*
ArnBone::createFrom( const TiXmlElement* elm )
{
AssertAttrEquals(elm, "rtclass", "ArnBone");
const TiXmlElement* boneElm = GetUniqueChildElement(elm, "bone");
const TiXmlElement* headElm = GetUniqueChildElement(boneElm, "head");
const TiXmlElement* tailElm = GetUniqueChildElement(boneElm, "tail");
const TiXmlElement* rollElm = GetUniqueChildElement(boneElm, "roll");
ArnVec3 headPos, tailPos;
ParseArnVec3FromElementAttr(&headPos, headElm);
ParseArnVec3FromElementAttr(&tailPos, tailElm);
ArnVec3 boneDir(tailPos - headPos);
float length = ArnVec3Length(boneDir);
float roll = ParseFloatFromAttr(rollElm, "value");
ArnBone* ret = ArnBone::createFrom(length, ArnToRadian(roll));
SetupArnXformableCommonPart(ret, elm);
// This assures that the object is locally transformed
// by local xform in t=0.
ret->setAnimLocalXform (ret->getLocalXform ());
for (const TiXmlElement* e = elm->FirstChildElement("object"); e; e = e->NextSiblingElement("object"))
{
const TiXmlElement* boneElm = e;
if (boneElm->Parent() == elm)
{
ArnNode* bone = CreateArnNodeFromXmlElement(boneElm, 0);
ret->attachChild(bone);
}
}
return ret;
}
ArnIpo*
ArnIpo::createFrom(const TiXmlElement* elm, const char* binaryChunkBasePtr)
{
AssertAttrEquals(elm, "rtclass", "ArnIpo");
ArnIpo* ret = new ArnIpo();
SetupArnNodeCommonPart(ret, elm);
const TiXmlElement* ipoElm = elm->FirstChildElement("ipo");
assert(ipoElm);
unsigned int curveListSize = 0;
for (const TiXmlElement* e = ipoElm->FirstChildElement("curve"); e; e = e->NextSiblingElement("curve"))
{
const TiXmlElement* curveElm = e;
std::string curveTypeStr;
GetAttr(curveTypeStr, curveElm, "type");
std::string curveNameStr;
GetAttr(curveNameStr, curveElm, "name");
const TiXmlElement* controlPointElm = GetUniqueChildElement(curveElm, "controlpoint");
ret->m_curves.push_back(CurveData());
CurveData& cd = ret->m_curves.back();
cd.nameStr = curveNameStr.c_str();
cd.name = ArnIpo::CurveNameStrToEnum(cd.nameStr.c_str());
if (strcmp(curveTypeStr.c_str(), "const") == 0)
cd.type = IPO_CONST;
else if (strcmp(curveTypeStr.c_str(), "linear") == 0)
cd.type = IPO_LIN;
else if (strcmp(curveTypeStr.c_str(), "bezier") == 0)
cd.type = IPO_BEZ;
else
ARN_THROW_UNEXPECTED_CASE_ERROR
const TiXmlElement* cpChunk = GetUniqueChildElement(controlPointElm, "chunk");
ArnBinaryChunk* controlPointChunk = ArnBinaryChunk::createFrom(cpChunk, binaryChunkBasePtr);
assert(controlPointChunk->getRecordSize() == sizeof(BezTripleData));
cd.pointCount = controlPointChunk->getRecordCount();
cd.points.resize(cd.pointCount);
memcpy(&cd.points[0], controlPointChunk->getConstRawDataPtr(), sizeof(BezTripleData) * cd.pointCount);
foreach (const BezTripleData& btd, cd.points)
{
if ( ret->getEndKeyframe() < (int)btd.vec[1][0] )
ret->setEndKeyframe((int)btd.vec[1][0]);
}
delete controlPointChunk;
++curveListSize;
}
ret->m_curveCount = curveListSize;
ret->m_ipoCount = 1; // TODO: Is semantically correct one?
return ret;
}
ArnAction*
ArnAction::createFrom(const TiXmlElement* elm)
{
AssertAttrEquals(elm, "rtclass", "ArnAction");
ArnAction* ret = new ArnAction();
SetupArnNodeCommonPart(ret, elm);
const TiXmlElement* actionElm = GetUniqueChildElement(elm, "action");
for (const TiXmlElement* e = actionElm->FirstChildElement("objectipomap"); e; e = e->NextSiblingElement("objectipomap"))
{
const TiXmlElement* mapElm = e;
std::string ssObjName;
GetAttr(ssObjName, mapElm, "obj");
std::string ssIpoName;
GetAttr(ssIpoName, mapElm, "ipo");
ret->addMap(ssObjName.c_str(), ssIpoName.c_str());
}
return ret;
}
ArnNode*
CreateArnNodeFromXmlElement(const TiXmlElement* elm, const char* binaryChunkBasePtr)
{
std::string rtclassStr;
GetAttr(rtclassStr, elm, "rtclass");
ArnNode* ret = 0;
if (strcmp(rtclassStr.c_str(), "ArnMesh") == 0)
{
ret = ArnMesh::createFrom(elm, binaryChunkBasePtr);
}
else if (strcmp(rtclassStr.c_str(), "ArnCamera") == 0)
{
ret = ArnCamera::createFrom(elm);
}
else if (strcmp(rtclassStr.c_str(), "ArnMaterial") == 0)
{
ret = ArnMaterial::createFrom(elm);
}
else if (strcmp(rtclassStr.c_str(), "ArnSkeleton") == 0)
{
ret = ArnSkeleton::createFrom(elm);
}
else if (strcmp(rtclassStr.c_str(), "ArnIpo") == 0)
{
ret = ArnIpo::createFrom(elm, binaryChunkBasePtr);
}
else if (strcmp(rtclassStr.c_str(), "ArnAction") == 0)
{
ret = ArnAction::createFrom(elm);
}
else if (strcmp(rtclassStr.c_str(), "ArnLight") == 0)
{
ret = ArnLight::createFrom(elm);
}
else if (strcmp(rtclassStr.c_str(), "ArnBone") == 0)
{
ret = ArnBone::createFrom(elm);
}
else
{
assert(!"Unknown runtime class identifier (rtclass) attribute!");
}
assert(ret);
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int ArnInitializeXmlParser()
{
if (gs_xmlInitialized == false)
{
gs_xmlInitialized = true;
return 0;
}
else
{
return -1;
}
}
int ArnCleanupXmlParser()
{
if (gs_xmlInitialized)
{
gs_xmlInitialized = false;
return 0;
}
else
{
return -1;
}
}
| [
"[email protected]"
] | [
[
[
1,
1065
]
]
] |
cbcfe3f4a3c4df58b53085c5ceadbb48b9a24091 | df5277b77ad258cc5d3da348b5986294b055a2be | /Spaceships/Weapon.cpp | cace3723256237d8edb0694308d529e02d5b9d06 | [] | no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | #include "precompiled.h"
#include "Weapon.h"
Weapon::Weapon(BulletFactory* factory, GameObject* owner)
{
this->factory = factory;
fireDuration = 0;
this->owner = owner;
lastTimeFired = GetTickCount() - 1;
}
Weapon::~Weapon(void)
{
}
bool Weapon::IsFiring()
{
bool retvalue = (GetTickCount() - lastTimeFired) < fireDuration;
return retvalue;
}
void Weapon::Fire(const float x, const float y, const float rotation, Controller* controller)
{
if(!this->IsFiring())
{
lastTimeFired = GetTickCount();
GameObject* bullet = Fire(x, y, rotation);
if(bullet != NULL)
{
bullet->SetController(controller);
Message* message =
new Message(MessageType::GAME_OBJECT_ACTION, MessageContent::CREATE_OBJECT, (void*)bullet);
controller->PassMessage(message);
}
}
}
void Weapon::SetFireDuration(int duration)
{
this->fireDuration = duration;
}
void Weapon::Update()
{
} | [
"ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
] | [
[
[
1,
46
]
]
] |
4b73e796fc2675cb0a65b1b06fe262013eb121cd | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/include/Simulation.h | 5e87680431ec6578971b2ab89818841e0d3bad1c | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,110 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** A module to decode simulation data and feed it to the respective
* protocols.
*/
#ifndef MODULES_Simulation_H
#define MODULES_Simulation_H
#include <list>
#include <queue>
/// Makes the simulation module read simulation data from a file.
#define SIM_DATA_FROM_FILE
namespace isab {
class Simulation : public Module, public SerialConsumerInterface,
public SerialProviderInterface {
public:
#ifdef SIM_DATA_FROM_FILE
Simulation(SerialProviderPublic *p, const char* simFile = NULL);
#else
Simulation(SerialProviderPublic *p);
#endif
~Simulation(){
delete decoder.cmdBeingAssembled;
#ifdef SIM_DATA_FROM_FILE
delete[] m_simDataFile;
#endif
}
/** Creates a new SerialProviderPublic object used to reach this
* module. This gets connected to the trimble decoder.
* @return a new SerialProviderPublic object connected to the queue.
*/
SerialProviderPublic * newPublicSerial();
#ifndef _MSC_VER
static const int MaxMsgSize = 50;
#else
enum { MaxMsgSize = 50 } ;
#endif
protected:
/* Maximum size of various messages. Arbitarily chosen to be large enough
* for all messages to/from the trimble */
SerialProviderPublic * m_provider;
virtual MsgBuffer * dispatch(MsgBuffer *buf);
virtual void decodedReceiveData(int length, const uint8 *data, uint32 src);
virtual void decodedSendData(int inlen, const uint8 *data, uint32 src);
SerialConsumerPublic * rootPublic();
virtual void decodedShutdownPrepare(int16 upperTimeout);
virtual void decodedStartupComplete();
/** Set after shutdownPrepare() */
bool m_shutdown;
/** Decoder for SerialConsumer-messages */
SerialConsumerDecoder m_consumerDecoder;
/** Decoder for SerialProvider-messages */
SerialProviderDecoder m_serialProviderDecoder;
#ifdef SIM_DATA_FROM_FILE
/**
* Reads a file with sim data and stores it in a buffer.
*
*
*/
void simDataFromFileToDecoding();
Buffer* m_fileSimData;
bool m_alreadyTriedToOpenFile;
char* m_simDataFile;
#endif
enum driv_new_sim_states {
decoder_idle,
decoder_idle_got_escape,
decoder_in_packet,
decoder_in_packet_got_escape
};
struct SimCommand {
isabTime rxTime;
int8 pktType;
bool reconnect;
uint8 buf[MaxMsgSize];
int numBytes;
};
struct driv_new_sim_decoder {
enum driv_new_sim_states state;
struct SimCommand *cmdBeingAssembled;
uint8 reconnected;
};
enum driv_new_sim_trimble_state {
state_idle, state_in_packet_after_dle,
state_after_initial_dle,
state_in_packet
};
struct driv_new_sim_trimble_emulator {
float base_time;
uint8 reassmebled_pkt[MaxMsgSize];
uint8 *outpos;
int outlen;
enum driv_new_sim_trimble_state state;
};
struct driv_new_sim_dispatcher {
struct SimCommand *next_command;
std::queue< struct SimCommand *> cmdQueue;
isabTime last_exec_time;
uint16 timerId;
};
struct driv_new_sim_decoder decoder;
struct driv_new_sim_dispatcher dispatcher;
struct driv_new_sim_trimble_emulator trimble;
uint32 elapsed_simulation_time;
/* Standard replies used by the trimble smulator. The actual data
* is supplied in Simulation.cpp. */
/** Software version */
static const uint8 simulated_pkt45[];
/** Helth of receiver */
static const uint8 simulated_pkt46[];
/** Differential fix mode */
static const uint8 simulated_pkt82[];
/*+*******************************************************
* Setup the timers etc for the next command.
*
* This function should only ever be called when no
* packet is awaiting execution.
********************************************************+*/
void setupForNextCommand();
/*+*******************************************************
* Actually dispatch the simulated data to the various
* protocol drivers. These can either loop the data
* locally or send it out to another navigator.
*
* This functions draws the actual data from the list
* prepared by decode_data().
* The list is already ordered by the simulation source.
********************************************************+*/
void decodedExpiredTimer(uint16 timerno);
/*+*******************************************************
* Insert data byte into reassembly buffer (helper)
*
* This small function breaks out some common code for the
* decoder_in_packet and decoder_in_packet_got_escape
* states. It is expecet that this function is inlined.
*
* Append one data byte to the reassembly buffer while
* checking for too large packets.
********************************************************+*/
void append_data(uint8 data);
/*+*******************************************************
* Decode simulation data
*
* uint8 data_stream
* The raw stream of bytes. See "ISos Simulation
* Protocol v 1.01" for more information.
*
* int data_size
* Number of bytes in data_stream
*
* int blocking
* Zero to return when unable to process more data
* or non-zero to block until all data is processed.
*
* This function operates in two modes: blocking and
* non-blocking. Non-blocking operation is strongly
* recommended for serial connections while blocking
* operation normally is used when reading from rom/ram.
*
* Details: a buffer is held in self->decoder.buf whenever
* the state is not one of the idle ones (idle or
* idle_got_escape).
********************************************************+*/
void decode_data(
const uint8 * data_stream,
int32 data_size,
int reconnect,
int blocking);
void trimble_interpret_packet(uint8 *bufptr, int size);
};
} /* namespace isab */
#endif /* MODULES_GpsTrimble_H */
| [
"[email protected]"
] | [
[
[
1,
215
]
]
] |
d4a885f3785f9dec5d21702e2c2e6cd130a4b88b | 9566086d262936000a914c5dc31cb4e8aa8c461c | /EnigmaCommon/boost_foreach.hpp | 64dff24800a31f367cc559df01df94e46f1fca43 | [] | no_license | pazuzu156/Enigma | 9a0aaf0cd426607bb981eb46f5baa7f05b66c21f | b8a4dfbd0df206e48072259dbbfcc85845caad76 | refs/heads/master | 2020-06-06T07:33:46.385396 | 2011-12-19T03:14:15 | 2011-12-19T03:14:15 | 3,023,618 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,237 | hpp | #ifndef BOOST_FOREACH_HPP_INCLUDED
#define BOOST_FOREACH_HPP_INCLUDED
/*
Copyright © 2009 Christopher Joseph Dean Schaefer (disks86)
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.
*/
#ifdef ENIGMA_PLATFORM_WINDOWS
#pragma warning( push )
#pragma warning( disable : 4061 )
#pragma warning( disable : 4100 )
#pragma warning( disable : 4127 )
#pragma warning( disable : 4217 )
#pragma warning( disable : 4242 )
#pragma warning( disable : 4244 )
#pragma warning( disable : 4280 )
#pragma warning( disable : 4513 )
#pragma warning( disable : 4514 )
#pragma warning( disable : 4619 )
#pragma warning( disable : 4668 )
#pragma warning( disable : 4710 )
#pragma warning( disable : 4820 )
#include <boost/foreach.hpp>
#pragma warning( pop )
#define BOOST_FOREACH_LOADED 1
#endif
#ifdef ENIGMA_PLATFORM_LINUX
#include <boost/foreach.hpp>
#define BOOST_FOREACH_LOADED 2
#endif
#ifdef ENIGMA_PLATFORM_MAC
#include <boost/foreach.hpp>
#define BOOST_FOREACH_LOADED 3
#endif
#ifdef ENIGMA_PLATFORM_BSD
#include <boost/foreach.hpp>
#define BOOST_FOREACH_LOADED 4
#endif
#ifdef ENIGMA_PLATFORM_OPENSOLARIS
#include <boost/foreach.hpp>
#define BOOST_FOREACH_LOADED 5
#endif
#ifndef BOOST_FOREACH_LOADED
#include <boost/foreach.hpp>
#define BOOST_FOREACH_LOADED 6
#endif
#endif // BOOST_FOREACH_HPP_INCLUDED
| [
"[email protected]"
] | [
[
[
1,
61
]
]
] |
de6019e4c6a0f51669f44d22e5cd9d4f17220500 | faacd0003e0c749daea18398b064e16363ea8340 | /modules/mp3player/playerdisplay.h | 06a5e36eb6df693554d8da9e5289bedfe2b8855a | [] | no_license | yjfcool/lyxcar | 355f7a4df7e4f19fea733d2cd4fee968ffdf65af | 750be6c984de694d7c60b5a515c4eb02c3e8c723 | refs/heads/master | 2016-09-10T10:18:56.638922 | 2009-09-29T06:03:19 | 2009-09-29T06:03:19 | 42,575,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | h | /*
* Copyright (C) 2008-2009 Pavlov Denis
*
* Comments unavailable.
*
* 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 any later version.
*
*/
#ifndef AMP3PLAYERDISPLAY_H
#define AMP3PLAYERDISPLAY_H
#include <QtXml>
#include "display.h"
#include "scrolllabel.h"
#include "skinner.h"
class AMp3PlayerDisplay : public QWidget
{
Q_OBJECT
public:
AMp3PlayerDisplay(QWidget *parent = 0, ASkinner *skinner = 0);
~AMp3PlayerDisplay();
void setSongTitle(QString title);
void setSongDuration(QString duration);
void setPlaying(bool isPlaying);
void setPaused(bool isPaused);
void setRepeat(bool repeat);
private:
ALyxScrollLabel *songTitleLbl;
QLabel *songDurationLbl;
QLabel *playIcon;
QLabel *pausedIcon;
QLabel *repeatIcon;
};
#endif // AMP3PLAYERDISPLAY_H
| [
"futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9"
] | [
[
[
1,
45
]
]
] |
22679e9555033648c8d63e68ed9bb694fbbba80c | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/theme/Default/MenuItemTheme.h | 1e3df2cb4b6989905966151685bcc9956f99e211 | [
"BSD-3-Clause"
] | permissive | gui-works/ui | 3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b | 023faf07ff7f11aa7d35c7849b669d18f8911cc6 | refs/heads/master | 2020-07-18T00:46:37.172575 | 2009-11-18T22:05:25 | 2009-11-18T22:05:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,833 | h | /*
* Copyright (c) 2003-2006, Bram Stein
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MENUITEMTHEME_H
#define MENUITEMTHEME_H
#include "./ComponentTheme.h"
#include "../../event/MouseListener.h"
#include "../../event/FocusListener.h"
#include "../../event/PropertyListener.h"
#include "../../event/KeyListener.h"
namespace ui
{
namespace theme
{
namespace defaulttheme
{
class MenuItemTheme : public ComponentTheme, public event::PropertyListener, public event::KeyListener//, public event::MouseAdapter, public event::FocusListener
{
public:
MenuItemTheme();
void installTheme(Component *comp);
void deinstallTheme(Component *comp);
void paint(Graphics& g,const Component *comp) const;
const util::Dimension getPreferredSize(const Component *comp) const;
private:
util::Color background;
util::Color highlight;
util::Color foreground;
void propertyChanged(const event::PropertyEvent &e);
void keyTyped(const event::KeyEvent &e);
void keyPressed(const event::KeyEvent &e);
void keyReleased(const event::KeyEvent &e);
// void mouseEntered(const event::MouseEvent &e);
// void mouseExited(const event::MouseEvent &e);
// void focusGained(const event::FocusEvent &e);
// void focusLost(const event::FocusEvent &e);
};
}
}
}
#endif | [
"bs@bram.(none)"
] | [
[
[
1,
70
]
]
] |
efeef57f16fa552e087b8a567b74085f5844ef30 | 9fb229975cc6bd01eb38c3e96849d0c36985fa1e | /src/iPhone/File_iPhone.h | 6f24a7d9113cbce25fb2ee25b3009296d55f2113 | [] | no_license | Danewalker/ahr | 3758bf3219f407ed813c2bbed5d1d86291b9237d | 2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6 | refs/heads/master | 2016-09-13T08:03:43.040624 | 2010-07-21T15:44:41 | 2010-07-21T15:44:41 | 56,323,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,772 | h |
#ifndef _File_Iphone_H_
#define _File_Iphone_H_
#include <stdio.h>
////////////////////////////////////////////////////////////////////////////////////////
//@Class A_IFile
////////////////////////////////////////////////////////////////////////////////////////
class A_IFile
{
public:
enum EOpenFlags
{
OPEN_BINARY_TEXT = 0x01,
OPEN_BINARY = OPEN_BINARY_TEXT,
OPEN_TEXT = 0,
OPEN_READ = 0x02,
OPEN_WRITE = 0x04,
OPEN_READ_WRITE = OPEN_READ | OPEN_WRITE,
OPEN_APPEND = 0x08,
OPEN_STANDALONE = 0x10,
OPEN_CACHE = 0x20,
OPEN_WRITECACHE = 0x40,
OPEN_CHECKSUM = 0x80,
OPEN_USER_DATA = 0x100,
};
enum {k_nWriteCacheSize=4096};
// static A_IFile* OpenECP(ECPFileId);
static A_IFile* Open(const char* in_pFilePath, int in_nFlags, bool nofail = true, bool in_bDataPath = true);
static A_IFile* CreateStreamBuffer();
static void Close(A_IFile*& io_pFile);
static bool Delete(const char* in_pFilePath, bool in_bDataPath);
static bool ExistInPath(const char * in_pFilePath, bool in_bIsDataPath = false);
virtual void HandleReadError();
A_IFile(bool noFail):m_noFail(noFail),m_pCache(0),m_nCacheSize(0),m_nCachePosition(0),m_pWriteCache(0),m_nWriteSize(0),m_Checksum(0),m_UseChecksum(false){};
virtual ~A_IFile();
const char* ReadString();
void WriteString(const char*);
unsigned int Read(void * out_pData, unsigned int in_nSize);
inline int ReadInt() {int val; Read(&val,sizeof(int));return val;}
unsigned int Write(const void * in_pData, unsigned int in_nSize);
long GetSize();
bool Seek(unsigned int nOffsetFromStart);
char GetChar();
short GetShort();
int GetInt();
long GetLong();
void SkipLine();
int GetCurrentOffset();
virtual void Flush() = 0;
// If the file is all allocated in a buffer
// it returns directly this buffer
virtual void* GetBuffer();
protected:
void CacheFile();
protected:
virtual unsigned int SpecificRead(void * out_pData, unsigned int in_nSize)=0;
virtual unsigned int SpecificWrite(const void * in_pData, unsigned int in_nSize)=0;
virtual long SpecificGetSize()=0;
virtual bool SpecificSeek(unsigned int nOffsetFromStart)=0;
virtual void SpecificClose()=0;
protected:
const bool m_noFail;
bool m_UseChecksum;
unsigned char * m_pCache;
unsigned int m_nCacheSize;
unsigned char * m_pWriteCache;
unsigned int m_nWriteSize;
unsigned int m_nCachePosition;
unsigned int m_Checksum;
char m_tmpString[128];
};
////////////////////////////////////////////////////////////////////////////////////////
//@Class CCachedFile
////////////////////////////////////////////////////////////////////////////////////////
//#define CHUNK_SIZE (65535)
class CCachedFile
{
public:
char* content;
long crtPos, fileSize;
CCachedFile(const char* sourceFile);
int Read(void * out_pData, unsigned int in_nSize);
int GetInt();
bool Seek(unsigned int nOffsetFromStart);
~CCachedFile();
};
////////////////////////////////////////////////////////////////////////////////////////
//@Class CStreamBuffer
////////////////////////////////////////////////////////////////////////////////////////
class CStreamBuffer :
public A_IFile
{
public:
CStreamBuffer();
virtual ~CStreamBuffer();
virtual unsigned int SpecificRead(void * out_pData, unsigned int in_nSize);
virtual unsigned int SpecificWrite(const void * out_pData, unsigned int in_nSize);
virtual bool SpecificSeek(unsigned int nOffsetFromStart);
virtual long SpecificGetSize(){return m_nCreatedBufferSize;}
virtual void SpecificClose(){}
virtual void Flush(){}
virtual void* GetBuffer(){return m_pCreatedBuffer;}
virtual int Tell() {return 0;}// TODO; there seem to be some bugs in this class: if in_pBuffer (in ctor) is null,m_pReadPos will be null also
protected:
unsigned char * m_pCreatedBuffer;
unsigned int m_nCreatedBufferSize;
const unsigned char * m_pReadPos;
};
////////////////////////////////////////////////////////////////////////////////////////
//@Class File
////////////////////////////////////////////////////////////////////////////////////////
class File
{
public:
File(const char* fileName)
{
m_file = A_IFile::Open( fileName, A_IFile::OPEN_READ | A_IFile::OPEN_BINARY | A_IFile::OPEN_CACHE);
}
~File()
{
if(m_file)
A_IFile::Close(m_file);
}
long ReadInt()
{
long i;
m_file->Read(&i,sizeof(i));
return i;
}
char ReadChar()
{
char i;
m_file->Read(&i,sizeof(i));
return i;
}
void Close()
{
if(m_file)
A_IFile::Close(m_file);
m_file = 0; //NULL;
}
private:
A_IFile* m_file;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//@Class CWinFile
////////////////////////////////////////////////////////////////////////////////////////////////////
class CWinFile :
public A_IFile
{
public:
CWinFile(bool noFail);
bool Create(const char* in_pFileName, int in_nFlags);
virtual ~CWinFile();
virtual unsigned int SpecificRead(void * out_pData, unsigned int in_nSize);
virtual unsigned int SpecificWrite(const void * out_pData, unsigned int in_nSize);
virtual bool SpecificSeek(unsigned int nOffsetFromStart);
virtual long SpecificGetSize();
virtual void SpecificClose();
virtual void Flush();
protected:
FILE* m_pFile;
};
#endif /* _File_Iphone_H_ */
| [
"jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae"
] | [
[
[
1,
211
]
]
] |
9cde0dc3171c0afe7a5aa77d285f5cd1f8c64576 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/dialog/CommandSelectDialog.h | ee84c2c1dd20ccb609afd0f33ebff3c708ce5f71 | [] | no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,318 | h | /**
* @file CommandSelectDialog.h
* @brief "コマンドを選ぶ"ダイアログ
*/
#pragma once
#include "../resource.h"
class CCommandSelectDialog
: public CDialogImpl<CCommandSelectDialog >
, public CWinDataExchange<CCommandSelectDialog >
{
public:
enum { IDD = IDD_DIALOG_CMD_SELECT };
private:
// Data members
HMENU m_hMenu;
CComboBox m_cmbCategory;
CComboBox m_cmbCommand;
DWORD_PTR m_dwCommandID;
public:
CCommandSelectDialog(HMENU hMenu);
DWORD_PTR GetCommandID();
#if 1 //*+++ 抜けを追加.
BEGIN_DDX_MAP( CCommandSelectDialog )
END_DDX_MAP()
#endif
// Message map and handlers
BEGIN_MSG_MAP(CCommandSelectDialog)
MESSAGE_HANDLER (WM_INITDIALOG , OnInitDialog)
COMMAND_HANDLER_EX (IDC_CMB_CATEGORY, CBN_SELCHANGE, OnSelChangeCate)
COMMAND_HANDLER_EX (IDC_CMB_COMMAND , CBN_SELCHANGE, OnSelChangeCmd )
COMMAND_ID_HANDLER (IDOK , OnCloseCmd)
COMMAND_ID_HANDLER (IDCANCEL , OnCloseCmd)
END_MSG_MAP()
private:
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled);
LRESULT OnCloseCmd(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL &bHandled);
void OnSelChangeCate(UINT code, int id, HWND hWnd);
void OnSelChangeCmd(UINT code, int id, HWND hWnd);
private:
void SetGuideMsg();
};
| [
"[email protected]"
] | [
[
[
1,
52
]
]
] |
2124bb6cfba57999b58446dcfe9e438df15b9eef | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_particle/psselector.h | 57725b8c2e1a2b9231273ea27e4382fb25754e50 | [] | no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 936 | h | //****************************************************************************/
// File: PSSelector.h
// Date: 18.10.2006
// Author: Ruslan Shestopalyuk
//****************************************************************************/
#ifndef __PSSELECTOR_H__
#define __PSSELECTOR_H__
class ParticleServer;
//****************************************************************************/
// Class: PSSelector
// Desc: Performs selective firing of child emitters
//****************************************************************************/
class PSSelector : public PSEmitter
{
JFloatList m_Chances;
public:
PSSelector();
expose( PSSelector )
{
parent(PSEmitter)
field( "Chances", m_Chances );
}
private:
virtual PSEmitter* AssignEmitter( EmitterInstance* pInst, Particle* pHostParticle );
}; // class PSSelector
#endif // __PSSELECTOR_H__
| [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
087891899b6381df8f38d100e147cf7b1652fda2 | 5210c96be32e904a51a0f32019d6be4abdb62a6d | /Model.h | 3875cf5626f6840229ffd45dab08a635f50004ab | [] | no_license | Russel-Root/knot-trying-FTL | 699cec27fcf3f2b766a4beef6a58176c3cbab33e | 2c1a7992855927689ad1570dd7c5998a73728504 | refs/heads/master | 2021-01-15T13:18:35.661929 | 2011-04-02T07:51:51 | 2011-04-02T07:51:51 | 1,554,271 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 76 | h | #pragma once
class Model{
private:
float k, m, time_step;
public:
}; | [
"[email protected]"
] | [
[
[
1,
7
]
]
] |
334a673fdbb27a700a37b0abcb46eddf41ce0e55 | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/vis/properties/double/vis_property_smooth_double.cpp | 90398e8fa1fef423654237709b44c66ebd486c61 | [
"MIT",
"BSD-3-Clause"
] | permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,642 | cpp | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include "apps/vis/properties/double/vis_property_smooth_double.h"
using namespace shawn;
namespace vis
{
PropertySmoothDoubleTask::PropertySmoothDouble::
PropertySmoothDouble( double v1, double v2, double tmid, Transition tr )
: v1_(v1), v2_(v2), tmid_(tmid), trans_(tr)
{}
// ----------------------------------------------------------------------
PropertySmoothDoubleTask::PropertySmoothDouble::
~PropertySmoothDouble()
{}
// ----------------------------------------------------------------------
double
PropertySmoothDoubleTask::PropertySmoothDouble::
value( double t,
const PropertyStack<double>&,
const Element& )
const throw()
{
if( t>tmid_ )
return v2_;
else
return transition_between( trans_,v1_,v2_, start_time(),tmid_, t );
}
// ----------------------------------------------------------------------
PropertySmoothDoubleTask::
PropertySmoothDoubleTask()
{}
// ----------------------------------------------------------------------
PropertySmoothDoubleTask::
~PropertySmoothDoubleTask()
{}
// ----------------------------------------------------------------------
std::string
PropertySmoothDoubleTask::
name( void )
const throw()
{
return "vis_smooth_double";
}
// ----------------------------------------------------------------------
std::string
PropertySmoothDoubleTask::
description( void )
const throw()
{
return "create a smooth value property";
}
// ----------------------------------------------------------------------
ConstPropertyHandle
PropertySmoothDoubleTask::
create_property( shawn::SimulationController& sc )
throw( std::runtime_error )
{
double val1 = sc.environment().required_double_param("start_value");
double val2 = sc.environment().required_double_param("end_value");
double tim1 = param_start(sc);
double tim3 = param_end(sc);
double tim2 = sc.environment().optional_double_param("reach_time",tim3);
Transition tr = transition(sc.environment().required_string_param("transition"));
PropertySmoothDouble* pc = new PropertySmoothDouble(val1,val2,tim2,tr);
pc->set_start( tim1 );
pc->set_end( tim3 );
pc->set_priority( param_prio(sc) );
return pc;
}
}
#endif
/*-----------------------------------------------------------------------
* Source $Source: /cvs/shawn/shawn/tubsapps/vis/properties/double/vis_property_smooth_double.cpp,v $
* Version $Revision: 1.2 $
* Date $Date: 2006/02/04 20:19:46 $
*-----------------------------------------------------------------------
* $Log: vis_property_smooth_double.cpp,v $
* Revision 1.2 2006/02/04 20:19:46 ali
* *** empty log message ***
*
* Revision 1.1 2006/02/01 17:07:29 ali
* *** empty log message ***
*
*-----------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
98
]
]
] |
0dabbd5302f2eda545998b4465323d8c374e4475 | e5f7a02c92c5a60c924e07813bc0b7b8944c2ce8 | /7-continuation/7.5.1/test.cpp | a934d5b52b1e70514564c197e08122a407124baa | [] | no_license | 7shi/thunkben | b8fe8f29b43c030721e8a08290c91275c9f455fe | 9bc99c5a957e087bb41bd6f87cf7dfa44e7b55f6 | refs/heads/main | 2022-12-27T19:53:39.322464 | 2011-11-30T16:57:45 | 2011-11-30T16:57:45 | 303,163,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | #include <stdio.h>
void test() {
int a;
printf("\r&a: %p ", &a);
fflush(stdout);
test();
}
int main() {
int a;
printf("&a: %p\n", &a);
test();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
15
]
]
] |
fdbad610b2476c9cda29e5fc6cebdbf2ab5f31a4 | 1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3 | /branches/mapmodule/libsonetto/src/SonettoFontManager.cpp | 7d48dcb73455f9316b04ca1dbaf9fcffe3a54f6f | [] | no_license | sonetto/legacy | 46bb60ef8641af618d22c08ea198195fd597240b | e94a91950c309fc03f9f52e6bc3293007c3a0bd1 | refs/heads/master | 2021-01-01T16:45:02.531831 | 2009-09-10T21:50:42 | 2009-09-10T21:50:42 | 32,183,635 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,621 | cpp | /*-----------------------------------------------------------------------------
Copyright (c) 2009, Sonetto Project Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the Sonetto Project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------*/
#include "SonettoFontManager.h"
namespace Sonetto
{
// ----------------------------------------------------------------------
// Sonetto::FontManager implementation.
// ----------------------------------------------------------------------
SONETTO_SINGLETON_IMPLEMENT(SONETTO_API,FontManager);
// ----------------------------------------------------------------------
FontManager::FontManager()
{
mResourceType = "SFont";
// low, because it will likely reference other resources
mLoadOrder = 30.0f;
// Register the resorce manager with Ogre.
Ogre::ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this);
}
// ----------------------------------------------------------------------
FontManager::~FontManager()
{
// unregister the resource manager.
Ogre::ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType);
}
// ----------------------------------------------------------------------
FontPtr FontManager::load(const Ogre::String &name, const Ogre::String &group)
{
FontPtr fontf = getByName(name);
if (fontf.isNull())
fontf = create(name, group);
fontf->load();
return fontf;
}
// ----------------------------------------------------------------------
Ogre::Resource *FontManager::createImpl(const Ogre::String &name, Ogre::ResourceHandle handle,
const Ogre::String &group, bool isManual, Ogre::ManualResourceLoader *loader,
const Ogre::NameValuePairList *createParams)
{
return new Font(this, name, handle, group, isManual, loader);
}
// ----------------------------------------------------------------------
} // namespace
| [
"[email protected]"
] | [
[
[
1,
74
]
]
] |
ab5a2a6b4bf8db2a6ff0ec7991a75d3d9a27aa62 | 96485d6370f5fe919697efae3fbadab4bd2ec4b7 | /first.cpp | 588b40c49a5cb3bba5032505a03f36124ea6c948 | [] | no_license | Erop147/OS | befd9a64f3e5a2579412ff131237cad03798bf7e | 79a5047ef31f5a64f3e623134a19450a90e70c86 | refs/heads/master | 2020-06-01T16:50:21.577043 | 2011-12-13T16:38:01 | 2011-12-13T16:38:01 | 2,477,275 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cpp | #include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
void add(char *name, vector<int> &res)
{
FILE *in = fopen(name, "r");
if (in == NULL)
{
fprintf(stderr, "file %s dosn't exist\n", name);
return;
}
int num;
while (!feof(in))
{
if (fscanf (in, "%d", &num) <= 0)
{
fprintf(stderr, "file %s contains non digit\n", name);
break;
}
try
{
res.push_back(num);
}
catch (exception e)
{
fprintf(stderr, "something wrong with vectors");
break;
}
}
fclose(in);
}
int main(int argv, char* args[])
{
vector<int> numbers;
for (int i = 1; i < argv; ++i)
{
add(args[i], numbers);
}
sort(numbers.begin(), numbers.end());
for (int i = 0; i < (int)numbers.size(); ++i)
{
printf ("%d ", numbers[i]);
}
return 0;
} | [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
495c6055ba8c10463bbe0180019ea8a8fd99edb6 | da49fe5fb9fc91dba1f0236411de3021e1e25348 | /RNG.cpp | 969a55177f530b424a7aae18dd78a720b84ca8f0 | [] | no_license | imbaczek/baczek-kpai | 7f84d83ba395c2e5b5d85c10c14072049b4830ab | 4291ec37f49fc8cb4a643133ed5f3024264e1e27 | refs/heads/master | 2020-03-28T19:13:42.841144 | 2009-10-29T21:39:02 | 2009-10-29T21:39:02 | 151,447 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,480 | cpp | #include <cmath>
#include <ctime>
#include <boost/random.hpp>
#include <boost/math/constants/constants.hpp>
#include "float3.h"
#include "RNG.h"
using namespace std;
static boost::mt19937 rng;
static bool is_initialized = false;
void init_rng()
{
if (is_initialized)
return;
is_initialized = true;
rng.seed(time(NULL));
}
void init_rng(boost::uint32_t seed)
{
is_initialized = true;
rng.seed(seed);
}
// thanks http://www.bnikolic.co.uk/blog/cpp-boost-uniform01.html for pitfall warning
float randfloat()
{
static boost::uniform_01<boost::mt19937> zeroone(rng);
return zeroone();
}
float randfloat(float start, float end)
{
boost::uniform_real<float> rnd(start, end);
boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >
gimme_random(rng, rnd);
return gimme_random();
}
int randint(int start, int end)
{
boost::uniform_int<> rnd(start, end);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
gimme_random(rng, rnd);
return gimme_random();
}
float3 random_direction()
{
float x = randfloat(0, 2*boost::math::constants::pi<float>());
return float3(sin(x), 0, cos(x));
}
float3 random_offset_pos(const float3& basePos, float minoffset, float maxoffset)
{
float3 dest;
do {
float r = randfloat(minoffset, maxoffset);
float3 modDir = random_direction();
dest = basePos + modDir * r;
} while (!dest.IsInBounds());
return dest;
}
| [
"[email protected]"
] | [
[
[
1,
72
]
]
] |
88a4e1d2cc2fad5f50f385c6a4eec17fecc23e1f | 0b5026bf5e6738d691c917e7d5cd415efd6ed0e6 | /tags/mapgenerator-0.2.0/src/tracelogwriter.h | 3d8e6607d1423d3ade699e59181cb78680e22adf | [
"AFL-2.1"
] | permissive | BackupTheBerlios/mapgeneration-svn | 585763838691e898cb235c57146310a1c7e500bd | 46ead8b34da12fbb1aab8585e6b974e441b5ec61 | refs/heads/master | 2020-12-25T18:16:56.114314 | 2006-11-01T17:51:50 | 2006-11-01T17:51:50 | 40,822,922 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,761 | h | /*******************************************************************************
* MapGeneration Project - Creating a road map for the world. *
* *
* Copyright (C) 2004-2005 by Rene Bruentrup and Bjoern Scholz *
* Licensed under the Academic Free License version 2.1 *
*******************************************************************************/
#ifndef TRACELOGWRITER_H
#define TRACELOGWRITER_H
#include <fstream>
#include <ostream>
namespace mapgeneration
{
class TraceLogWriter;
}
#include "tilemanager.h"
#include "tracelog.h"
namespace mapgeneration
{
/**
* Class TraceLogWriter
*/
class TraceLogWriter
{
public:
/**
* Standard constructor.
*/
TraceLogWriter (TileManager* tile_manager, const std::string file_name,
const FilteredTrace& filtered_trace);
~TraceLogWriter();
void
add_tile(const Tile& tile, bool created = false);
void
changed_trace(const GPSPoint& new_start, const int removed_gps_points);
void
merge_node(const std::pair<unsigned int, unsigned int>& node_id,
const GPSPoint& gps_point, const Node& new_node);
void
new_node(const std::pair<unsigned int, unsigned int>& node_id,
const Node& node);
void
next_step();
private:
std::ofstream* _log_stream;
TileCache* _tile_cache;
void
end_of_tracelog();
void
write_command(const std::string& command_string);
void
write_header(const FilteredTrace& filtered_trace);
};
} // namespace mapgeneration
#endif //TRACELOGWRITER_H
| [
"sihar@8a73a7ee-ebeb-0310-8c2f-b847a91f6bfa"
] | [
[
[
1,
95
]
]
] |
903fe4937d701f4b0a8e9a47b90d0c45262aeb1b | 71ffdff29137de6bda23f02c9e22a45fe94e7910 | /LevelEditor/src/gui/CControlPanel.cpp | a7f11054c6bdb632dd3cba99a044c4527c815734 | [] | no_license | anhoppe/killakoptuz3000 | f2b6ecca308c1d6ebee9f43a1632a2051f321272 | fbf2e77d16c11abdadf45a88e1c747fa86517c59 | refs/heads/master | 2021-01-02T22:19:10.695739 | 2009-03-15T21:22:31 | 2009-03-15T21:22:31 | 35,839,301 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,845 | cpp | // ***************************************************************
// CControlPanel version: 1.0 · date: 06/18/2007
// -------------------------------------------------------------
//
// -------------------------------------------------------------
// Copyright (C) 2007 - All Rights Reserved
// ***************************************************************
//
// ***************************************************************
#include "CControlPanel.h"
#include "../KillaCoptuz3000/src/Objects/CObject.h"
#include "../data/CDataStorage.h"
#include "../data/CUpdateContainer.h"
#include "CLayerControl.h"
#include "CPropertyPanel.h"
//////////////////////////////////////////////////////////////////////////
// Definitions
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Event Table
//////////////////////////////////////////////////////////////////////////
BEGIN_EVENT_TABLE(CControlPanel, wxPanel)
END_EVENT_TABLE()
//////////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////////
CControlPanel::CControlPanel(wxWindow* t_parentPtr)
: wxPanel(t_parentPtr, wxID_ANY, wxDefaultPosition, wxSize(200, 360))
{
wxBoxSizer* a_sizerPtr = 0;
//////////////////////////////////////////////////////////////////////////
// Register listener
CUpdateContainer::getInstance().add((ISetObject*)this);
//////////////////////////////////////////////////////////////////////////
// create GUI
a_sizerPtr = new wxBoxSizer(wxVERTICAL);
//////////////////////////////////////////////////////////////////////////
// set the layer control panel
m_panelLayerControlPtr = new CLayerControl(this);
a_sizerPtr->Add(m_panelLayerControlPtr, 1, wxEXPAND);
//////////////////////////////////////////////////////////////////////////
// read property sheet
m_panelPropertyPtr = new CPropertyPanel(this);
a_sizerPtr->Add(m_panelPropertyPtr, 1, wxEXPAND|wxALIGN_BOTTOM);
//////////////////////////////////////////////////////////////////////////
// Register sizer
SetSizer(a_sizerPtr);
}
CControlPanel::~CControlPanel()
{
CUpdateContainer::getInstance().remove((ISetObject*)this);
}
void CControlPanel::setObject(int t_index)
{
CDataStorage::getInstance().setActiveObjectByIndex(t_index);
}
void CControlPanel::insertLayers(std::vector<int>& t_layerIndices)
{
m_panelLayerControlPtr->insertLayers(t_layerIndices);
}
//////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////
| [
"anhoppe@9386d06f-8230-0410-af72-8d16ca8b68df"
] | [
[
[
1,
81
]
]
] |
771024e9568304f6e67caf08ab33f0613f33e74c | 563e71cceb33a518f53326838a595c0f23d9b8f3 | /v3/ProcGUI/GLCanvas.cpp | 819aeee37af1c58e3d1e23caf19c1f1f96d78646 | [] | no_license | fabio-miranda/procedural | 3d937037d63dd16cd6d9e68fe17efde0688b5a0a | e2f4b9d34baa1315e258613fb0ea66d1235a63f0 | refs/heads/master | 2021-05-28T18:13:57.833985 | 2009-10-07T21:09:13 | 2009-10-07T21:09:13 | 39,636,279 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 523 | cpp | #include "GLCanvas.h"
GLCanvas::GLCanvas( QWidget *parent )
: QGLWidget(parent)
{
m_window = WindowMng(1280,720);
//m_terrainMng = new TerrainMng();
m_cityMng = new CityMng();
}
GLCanvas::~GLCanvas()
{}
void GLCanvas::initializeGL()
{
m_window.GLInit();
}
void GLCanvas::paintGL()
{
m_window.GLConfig();
m_window.UpdateKeyboard();
m_window.UpdateMouse();
m_cityMng->Update(m_window.GetCameraPosition());
m_cityMng->Render(0);
}
void GLCanvas::resizeGL()
{
paintGL();
}
| [
"fabiom@01b71de8-32d4-11de-96ab-f16d9912eac9"
] | [
[
[
1,
35
]
]
] |
510a325a2877f873e7e61f40c69e4b9d4cbcaa1b | b5ab57edece8c14a67cc98e745c7d51449defcff | /Captain's Log/MainGame/Source/States/CPauseMenuState.cpp | 4048a66e70500d11bf347a8dbbe09aec77e1df43 | [] | no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,079 | cpp | #include "precompiled_header.h"
#include "CPauseMenuState.h"
#include "COptionsMenuState.h"
#include "CMainMenuState.h"
#include "CHelpState.h"
#include "CLoadState.h"
#include "CSaveState.h"
#include "../SGD Wrappers/CSGD_TextureManager.h"
#include "../SGD Wrappers/CSGD_DirectInput.h"
#include "../CGame.h"
#include "../Managers/MovementControl.h"
CPauseMenuState::CPauseMenuState(void)
{
}
CPauseMenuState::~CPauseMenuState(void)
{
}
CPauseMenuState* CPauseMenuState::GetInstance()
{
static CPauseMenuState instance;
return &instance;
}
void CPauseMenuState::Enter(void)
{
m_nBGImageID = CSGD_TextureManager::GetInstance()->LoadTexture(CGame::GetInstance()->GraphicsPath("HUD\\pauseMenu.png").c_str());
m_nSelectorImageID = CSGD_TextureManager::GetInstance()->LoadTexture(CGame::GetInstance()->GraphicsPath("HUD\\menuSelector.png").c_str());
m_bfFont.Initialize(CGame::GetInstance()->FontPath("Font - Orbitron.bmp").c_str(), 1.0f, 1.0f, 2, 0xFF000000, 0xFF00CC00);
m_bfFont.LoadLetterRects(CGame::GetInstance()->FontPath("FontData.txt").c_str());
m_sCurrentChoice = 0;
}
bool CPauseMenuState::Input(void)
{
m_nMouseX = CMovementControl::GetInstance()->MousePosX();
m_nMouseY = CMovementControl::GetInstance()->MousePosY();
if(CSGD_DirectInput::GetInstance()->KeyPressed(DIK_ESCAPE))
{
CGame::GetInstance()->PopState();
}
if(CSGD_DirectInput::GetInstance()->KeyPressed(DIK_UP))
{
if(m_sCurrentChoice==0)
m_sCurrentChoice=5;
else
m_sCurrentChoice--;
}
if(CSGD_DirectInput::GetInstance()->KeyPressed(DIK_DOWN))
{
if(m_sCurrentChoice==5)
m_sCurrentChoice=0;
else
m_sCurrentChoice++;
}
if(CSGD_DirectInput::GetInstance()->KeyPressed(DIK_RETURN) || CSGD_DirectInput::GetInstance()->MouseButtonPressed(0))
{
switch(m_sCurrentChoice)
{
case 0: //resume
CGame::GetInstance()->PopState();
break;
case 1: //save
CGame::GetInstance()->PushState(CSaveState::GetInstance());
break;
case 2: //load
CGame::GetInstance()->PushState(CLoadState::GetInstance());
break;
case 3: //options
CGame::GetInstance()->PushState(COptionsMenuState::GetInstance());
break;
case 4: //help
CGame::GetInstance()->PushState(CHelpState::GetInstance());
break;
case 5: //main menu
CGame::GetInstance()->ChangeState(CMainMenuState::GetInstance());
break;
}
}
if(m_nMousePrevX!=m_nMouseX || m_nMousePrevY!=m_nMouseY)
{
POINT ptMouse = {m_nMouseX, m_nMouseY};
RECT rMenu = {CGame::GetInstance()->GetScreenWidth()/3,
CGame::GetInstance()->GetScreenHeight()/3,
2*CGame::GetInstance()->GetScreenWidth()/3,
CGame::GetInstance()->GetScreenHeight()/3+192};
if(PtInRect(&rMenu, ptMouse))
{
m_sCurrentChoice = (m_nMouseY - CGame::GetInstance()->GetScreenHeight()/3) / 32;
}
}
m_nMousePrevX = m_nMouseX;
m_nMousePrevY = m_nMouseY;
return true;
}
void CPauseMenuState::Update(float fElapsedTime)
{
if(m_nMouseX < 0)
CSGD_DirectInput::GetInstance()->MouseSetPosX(0);
if(m_nMouseX > CGame::GetInstance()->GetScreenWidth())
CSGD_DirectInput::GetInstance()->MouseSetPosX(CGame::GetInstance()->GetScreenWidth());
if(m_nMouseY < 0)
CSGD_DirectInput::GetInstance()->MouseSetPosY(0);
if(m_nMouseY > CGame::GetInstance()->GetScreenHeight())
CSGD_DirectInput::GetInstance()->MouseSetPosY(CGame::GetInstance()->GetScreenHeight());
}
void CPauseMenuState::Render(void)
{
CSGD_TextureManager::GetInstance()->Draw(m_nBGImageID, 0, 0, 0.75f, 0.75f);
int nAdd = 0;
CSGD_TextureManager::GetInstance()->Draw(m_nSelectorImageID, CGame::GetInstance()->GetScreenWidth()/3 - 20, CGame::GetInstance()->GetScreenHeight()/3+(32*m_sCurrentChoice)+8);
nAdd = (m_sCurrentChoice==0) ? 0 : 23;
m_bfFont.RenderText("Resume", nAdd+CGame::GetInstance()->GetScreenWidth()/3, CGame::GetInstance()->GetScreenHeight()/3);
nAdd = (m_sCurrentChoice==1) ? 0 : 23;
m_bfFont.RenderText("Save Progress", nAdd+CGame::GetInstance()->GetScreenWidth()/3, CGame::GetInstance()->GetScreenHeight()/3+32);
nAdd = (m_sCurrentChoice==2) ? 0 : 23;
m_bfFont.RenderText("Load Previous Sequence", nAdd+CGame::GetInstance()->GetScreenWidth()/3, CGame::GetInstance()->GetScreenHeight()/3+64);
nAdd = (m_sCurrentChoice==3) ? 0 : 23;
m_bfFont.RenderText("Adjust Parameters", nAdd+CGame::GetInstance()->GetScreenWidth()/3, CGame::GetInstance()->GetScreenHeight()/3+96);
nAdd = (m_sCurrentChoice==4) ? 0 : 23;
m_bfFont.RenderText("Reference Operation's Manual", nAdd+CGame::GetInstance()->GetScreenWidth()/3, CGame::GetInstance()->GetScreenHeight()/3+128);
nAdd = (m_sCurrentChoice==5) ? 0 : 23;
m_bfFont.RenderText("Exit to Main Menu", nAdd+CGame::GetInstance()->GetScreenWidth()/3, CGame::GetInstance()->GetScreenHeight()/3+160);
CMovementControl::GetInstance()->RenderCursor();
}
void CPauseMenuState::Exit(void)
{
CSGD_TextureManager::GetInstance()->UnloadTexture(m_nBGImageID);
CSGD_TextureManager::GetInstance()->UnloadTexture(m_nSelectorImageID);
} | [
"notserp007@34577012-8437-c882-6fb8-056151eb068d",
"[email protected]@34577012-8437-c882-6fb8-056151eb068d"
] | [
[
[
1,
2
],
[
12,
14
],
[
16,
19
],
[
21,
30
],
[
33,
33
],
[
37,
40
],
[
105,
109
],
[
121,
124
],
[
147,
150
],
[
153,
153
]
],
[
[
3,
11
],
[
15,
15
],
[
20,
20
],
[
31,
32
],
[
34,
36
],
[
41,
104
],
[
110,
120
],
[
125,
146
],
[
151,
152
]
]
] |
c7281f6e993adba5d9ced4766ae47d59488eef42 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch24/Fig24_5/RegexSubstitution.cpp | d3f2903574809458549caed1b26d65a7c51cd035 | [] | no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,248 | cpp | // Fig. 24.5: RegexSubstitution.cpp
// Using regex_replace algorithm.
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include "boost/regex.hpp"
int main()
{
// create the test strings
string testString1 = "This sentence ends in 5 stars *****";
string testString2 = "1, 2, 3, 4, 5, 6, 7, 8";
string output;
cout << "Original string: " << testString1 << endl;
// replace every * with a ^
testString1 =
boost::regex_replace( testString1, boost::regex( "\\*" ), "^" );
cout << "^ substituted for *: " << testString1 << endl;
// replace "stars" with "carets"
testString1 = boost::regex_replace(
testString1, boost::regex( "stars" ), "carets" );
cout << "\"carets\" substituted for \"stars\": "
<< testString1 << endl;
// replace every word with "word"
testString1 = boost::regex_replace(
testString1, boost::regex( "\\w+" ), "word" );
cout << "Every word replaced by \"word\": " << testString1 << endl;
// replace the first three digits with "digit"
cout << "\nOriginal string: " << testString2 << endl;
string testString2Copy = testString2;
for ( int i = 0; i < 3; i++ ) // loop three times
{
testString2Copy = boost::regex_replace( testString2Copy,
boost::regex( "\\d" ), "digit", boost::format_first_only );
} // end for
cout << "Replace first 3 digits by \"digit\": "
<< testString2Copy << endl;
// split the string at the commas
cout << "string split at commas [";
boost::sregex_token_iterator tokenIterator( testString2.begin(),
testString2.end(), boost::regex( ",\\s" ), -1 ); // token iterator
boost::sregex_token_iterator end; // empty iterator
while ( tokenIterator != end ) // tokenIterator isn't empty
{
output += "\"" + *tokenIterator + "\", "; // add the token to output
tokenIterator++; // advance the iterator
} // end while
// delete the ", " at the end of output string
cout << output.substr( 0, output.length() - 2 ) << "]" << endl;
return 0;
} // end of function main
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/ | [
"[email protected]"
] | [
[
[
1,
82
]
]
] |
f98588a821c630313f33d52a3fe7324374240be4 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_ui/jscrollbar.h | 5a16c5da7c67145093d394aab7bae5a7e95430be | [] | no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 1,061 | h | /***********************************************************************************/
// File: JScrollBar.h
// Date: 23.09.2005
// Author: Ruslan Shestopalyuk
/***********************************************************************************/
#ifndef __JSCROLLBAR_H__
#define __JSCROLLBAR_H__
class JButton;
class JSlider;
/***********************************************************************************/
// Class: JScrollBar
// Desc:
/***********************************************************************************/
class JScrollBar : public JWidget
{
JButton* m_pUp;
JButton* m_pDown;
JButton* m_pSlider;
JButton* m_pPage;
bool m_bVertical;
public:
JScrollBar ();
virtual void Init ();
virtual void OnSize ();
expose(JScrollBar)
{
parent(JWidget);
field( "Vertical", m_bVertical );
}
}; // class JScrollBar
#endif //__JSCROLLBAR_H__ | [
"[email protected]"
] | [
[
[
1,
36
]
]
] |
01e8ec44b80deffdd92d33706685a9deabbffac3 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nscene/src/nscene/nsurfacenode_main.cc | 74d5e83ef12b4c20b501095b24518e59c6cfe3b1 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,575 | cc | #include "precompiled/pchnscene.h"
//------------------------------------------------------------------------------
// nsurfacenode_main.cc
// (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "nscene/nsurfacenode.h"
#include "nscene/nsceneshader.h"
#include "nscene/nscenegraph.h"
#include "nscene/nshadertree.h"
#include "gfx2/ngfxserver2.h"
#include "gfx2/nshader2.h"
#include "gfx2/ntexture2.h"
#include "kernel/ntimeserver.h"
#include "nscene/ncscene.h"
#include "entity/nentity.h"
#include "kernel/ndebug.h"
#include "nscene/nanimator.h"
nNebulaScriptClass(nSurfaceNode, "nabstractshadernode");
//------------------------------------------------------------------------------
/**
*/
nSurfaceNode::nSurfaceNode() :
shaderArray(4, 4)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nSurfaceNode::~nSurfaceNode()
{
this->UnloadResources();
}
//------------------------------------------------------------------------------
/**
Unload all shaders.
*/
void
nSurfaceNode::UnloadShaders()
{
int i;
for (i = 0; i < this->shaderArray.Size(); i++)
{
if (this->shaderArray[i].IsShaderValid())
{
this->shaderArray[i].GetShader()->Release();
this->shaderArray[i].Invalidate();
}
}
for (i = 0; i < this->shaderTreeArray.Size(); ++i)
{
if (this->shaderTreeArray[i].isvalid())
{
this->shaderTreeArray[i]->Release();
this->shaderTreeArray[i].invalidate();
}
}
}
//------------------------------------------------------------------------------
/**
Load shader resources.
*/
bool
nSurfaceNode::LoadShaders()
{
// load shaders
int i;
for (i = 0; i < this->shaderArray.Size(); i++)
{
ShaderEntry& shaderEntry = this->shaderArray[i];
if (!shaderEntry.IsShaderValid() && shaderEntry.GetName())
{
#if 0 // keep this commented while the shader database is not used
// try to get shader by name from shader repository
int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName());
if (shaderIndex != -1)
{
nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex);
if (!sceneShader.IsValid())
{
sceneShader.Validate();
n_assert(sceneShader.IsValid());
}
sceneShader.GetShaderObject()->AddRef();
shaderEntry.SetShaderIndex(shaderIndex);
shaderEntry.SetShader(sceneShader.GetShaderObject());
}
else
#endif
{
// create a new empty shader object
nShader2* shd = nGfxServer2::Instance()->NewShader(shaderEntry.GetName());
n_assert(shd);
if (!shd->IsLoaded())
{
// load shader resource file
shd->SetFilename(shaderEntry.GetName());
}
if (shd)
{
// register shader object in scene shader database
nSceneShader sceneShader;
sceneShader.SetShader(shaderEntry.GetName());// filename
sceneShader.SetShaderName(shaderEntry.GetName());// shader name
int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName());
if (shaderIndex == -1)
{
shaderIndex = nSceneServer::Instance()->AddShader(sceneShader);
n_assert(shaderIndex != -1);
}
// set shader object and index for local entry
shaderEntry.SetShader(shd);
shaderEntry.shaderIndex = shaderIndex;
// create a degenerate decision tree for use in the render path
nShaderTree* shaderTree = static_cast<nShaderTree*>( kernelServer->New("nshadertree") );
n_assert( shaderTree );
shaderTree->BeginNode( nVariable::InvalidHandle, 0 );
shaderTree->SetShaderObject( shd );
shaderTree->SetShaderIndexAt( 0, shaderIndex );
shaderTree->EndNode();
this->shaderTreeArray.Set( shaderEntry.GetPassIndex(), shaderTree );
}
}
}
}
return true;
}
//------------------------------------------------------------------------------
/**
Load the resources needed by this object.
*/
bool
nSurfaceNode::LoadResources()
{
if (this->LoadShaders())
{
if (nAbstractShaderNode::LoadResources())
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
/**
Unload the resources if refcount has reached zero.
*/
void
nSurfaceNode::UnloadResources()
{
nAbstractShaderNode::UnloadResources();
this->UnloadShaders();
}
//------------------------------------------------------------------------------
/**
Find shader object associated with fourcc code.
*/
nSurfaceNode::ShaderEntry*
nSurfaceNode::FindShaderEntry(nFourCC fourcc) const
{
int i;
int numShaders = this->shaderArray.Size();
for (i = 0; i < numShaders; i++)
{
ShaderEntry& shaderEntry = this->shaderArray[i];
if (shaderEntry.GetFourCC() == fourcc)
{
return &shaderEntry;
}
}
// fallthrough: no loaded shader matches this fourcc code
return 0;
}
//------------------------------------------------------------------------------
/**
Return number of levels.
*/
int
nSurfaceNode::GetNumLevels()
{
return (this->shaderArray.Size() > 0) ? 1 : 0;
}
//------------------------------------------------------------------------------
/**
Return number of passes for a level
*/
int
nSurfaceNode::GetNumLevelPasses(int /*level*/)
{
return this->shaderArray.Size();
}
//------------------------------------------------------------------------------
/**
Return number of passes for a level
*/
int
nSurfaceNode::GetLevelPassIndex(int level, int pass)
{
n_assert_return((level == 0) && (pass < this->shaderArray.Size()), -1);
return this->shaderArray[pass].GetPassIndex();
}
//------------------------------------------------------------------------------
/**
*/
nShaderTree*
nSurfaceNode::GetShaderTree(int /*level*/, int passIndex)
{
n_assert(passIndex < this->shaderTreeArray.Size());
return this->shaderTreeArray[passIndex];
}
//------------------------------------------------------------------------------
/**
*/
void
nSurfaceNode::SetShader(nFourCC fourcc, const char* name)
{
n_assert(name);
ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc);
if (shaderEntry)
{
shaderEntry->Invalidate();
shaderEntry->SetName(name);
}
else
{
ShaderEntry newShaderEntry(fourcc, name);
this->shaderArray.Append(newShaderEntry);
}
}
//------------------------------------------------------------------------------
/**
*/
const char*
nSurfaceNode::GetShader(nFourCC fourcc) const
{
ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc);
if (shaderEntry)
{
return shaderEntry->GetName();
}
else
{
return 0;
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nSurfaceNode::IsTextureUsed(nShaderState::Param /*param*/)
{
#if 0
// check in all shaders if anywhere the texture specified by param is used
int i;
int numShaders = this->shaderArray.Size();
for (i = 0; i < numShaders; i++)
{
const ShaderEntry& shaderEntry = this->shaderArray[i];
// first be sure that the shader entry could be loaded
if (shaderEntry.IsShaderValid())
{
nShader2* shader = shaderEntry.GetShader();
if (shader->IsParameterUsed(param))
{
return true;
}
}
}
// fallthrough: texture not used by any shader
return false;
#else
return true;
#endif
}
//------------------------------------------------------------------------------
/**
Setup shader attributes before rendering instances of this scene node.
FIXME
*/
bool
nSurfaceNode::Apply(nSceneGraph* sceneGraph)
{
n_assert(sceneGraph);
int shaderIndex = sceneGraph->GetShaderIndex();
if (shaderIndex != -1)
{
nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex);
nGfxServer2::Instance()->SetShader(sceneShader.GetShaderObject());
nAbstractShaderNode::Apply(sceneGraph);
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
Update shader and set as current shader in the gfx server.
- 15-Jan-04 floh AreResourcesValid()/LoadResources() moved to scene server
*/
bool
nSurfaceNode::Render(nSceneGraph* sceneGraph, nEntityObject* entityObject)
{
n_assert(sceneGraph);
n_assert(entityObject);
//nShader2* shader = nSceneServer::Instance()->GetShaderAt(sceneGraph->GetShaderIndex()).GetShaderObject();
// invoke shader manipulators
this->InvokeAnimators(entityObject);
/*
//nGfxServer2* gfxServer = nGfxServer2::Instance();
// set texture transforms (that can be animated)
//n_assert(nGfxServer2::MaxTextureStages >= 4);
static matrix44 m;
this->textureTransform[0].getmatrix44(m);
gfxServer->SetTransform(nGfxServer2::Texture0, m);
this->textureTransform[1].getmatrix44(m);
gfxServer->SetTransform(nGfxServer2::Texture1, m);
*/
// transfer the rest of per-instance (animated, overriden) parameters
// per instance-set parameters are handled at Apply()
// also, shader overrides are handled at nGeometryNode::Render()
nAbstractShaderNode::Render(sceneGraph, entityObject);
return true;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
353
]
]
] |
d7091372b137db38ad540b4d23ba8733d6f13961 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/scene/nintanimator_main.cc | e65b27d478712e75f63d337ed1a0b66ba340ce78 | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,348 | cc | //------------------------------------------------------------------------------
// nintanimator_main.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "scene/nintanimator.h"
#include "scene/nabstractshadernode.h"
#include "scene/nrendercontext.h"
nNebulaScriptClass(nIntAnimator, "nshaderanimator");
//------------------------------------------------------------------------------
/**
*/
nIntAnimator::nIntAnimator() :
keyArray(0, 4)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nIntAnimator::~nIntAnimator()
{
// empty
}
//------------------------------------------------------------------------------
/**
Add a key to the animation key array.
*/
void
nIntAnimator::AddKey(float time, int key)
{
nAnimKey<int> newKey(time, key);
this->keyArray.Append(newKey);
}
//------------------------------------------------------------------------------
/**
Return the number of keys in the animation key array.
*/
int
nIntAnimator::GetNumKeys() const
{
return this->keyArray.Size();
}
//------------------------------------------------------------------------------
/**
Return information for a key index.
*/
void
nIntAnimator::GetKeyAt(int index, float& time, int& key) const
{
const nAnimKey<int>& animKey = this->keyArray[index];
time = animKey.GetTime();
key = animKey.GetValue();
}
//------------------------------------------------------------------------------
/**
*/
void
nIntAnimator::Animate(nSceneNode* sceneNode, nRenderContext* renderContext)
{
n_assert(sceneNode);
n_assert(renderContext);
n_assert(nVariable::InvalidHandle != this->channelVarHandle);
// FIXME: dirty cast, make sure that it is a nAbstractShaderNode!
nAbstractShaderNode* targetNode = (nAbstractShaderNode*)sceneNode;
// get the sample time from the render context
nVariable* var = renderContext->GetVariable(this->channelVarHandle);
n_assert(var);
float curTime = var->GetFloat();
// get sampled key
static nAnimKey<int> key;
if (this->keyArray.Sample(curTime, this->loopType, key))
{
targetNode->SetInt(this->param, key.GetValue());
}
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
85
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.