blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ad2c2a883955c2e7ffd664cde1f977d226e2233b | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Scada/ScdOPC/opcbase/OPCServerBase.h | 3d642e9ef543526368ba694c254595b3b1326661 | []
| 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 | 10,653 | h | //**************************************************************************
//**************************************************************************
//
// Copyright (c) FactorySoft, INC. 1997, All Rights Reserved
//
//**************************************************************************
//
// Filename : OPCServerBase.h
// $Author : Jim Hansen
//
// Subsystem : OPC
// Version : 2.04
//
// Description: OPC Server and String Enumerator. See OPC Spec for details.
// String Enumerator is used in Browse interface.
//
//**************************************************************************
#ifndef __OPCSERVERBASE_H__ // Only Include Once
#define __OPCSERVERBASE_H__
#pragma warning( disable : 4786 )
#ifndef OPC_ATL_INCLUDED // if ATL hasn't been included already...
#define _ATL_STATIC_REGISTRY
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#include <atlcom.h>
#include <statreg.h>
#endif // OPC_ATL_INCLUDED
#include "OPCDa.h"
#include "OPCComn.h"
#include "OPCError.h"
extern UINT OPCSTMFORMATDATA;
extern UINT OPCSTMFORMATDATATIME;
extern UINT OPCSTMFORMATWRITECOMPLETE;
extern LPWSTR empty;
extern CComBSTR emptyString;
extern CDWordArray LCIDs;
//*******************************************************************
#include "OPCGroup.h"
extern "C" CLSID CLSID_OPCServer;
// The "standard" OPC pattern match function (used in browsing)
BOOL MatchPattern( LPCTSTR String, LPCTSTR Pattern, BOOL bCaseSensitive );
//*******************************************************************
class ATL_NO_VTABLE OPCServerBase :
public IOPCServer,
public IOPCCommon,
public IOPCBrowseServerAddressSpace,
public IOPCItemProperties,
public IConnectionPointContainerImpl<OPCServerBase>,
public IConnectionPointImpl<OPCServerBase, &IID_IOPCShutdown, CComDynamicUnkArray>,
public CComObjectRootEx<CComMultiThreadModel>,
public CComCoClass<OPCServerBase,&CLSID_OPCServer>
{
public:
OPCServerBase();
virtual ~OPCServerBase();
OPCGroupObject* FindNamedGroup( LPCWSTR name );
void UpdateTime();
void ServerShutdown( LPTSTR reason );
void GetUnkGroupList( OPCENUMSCOPE dwScope, LPUNKNOWN** GroupList, int &Count);
void GetStrGroupList( OPCENUMSCOPE dwScope, CStringList &StringList );
BEGIN_COM_MAP(OPCServerBase)
COM_INTERFACE_ENTRY(IOPCServer)
COM_INTERFACE_ENTRY(IOPCCommon)
COM_INTERFACE_ENTRY(IOPCBrowseServerAddressSpace)
COM_INTERFACE_ENTRY(IOPCItemProperties)
COM_INTERFACE_ENTRY_IMPL(IConnectionPointContainer)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(OPCServer)
// Connection Point
BEGIN_CONNECTION_POINT_MAP(OPCServerBase)
CONNECTION_POINT_ENTRY(IID_IOPCShutdown)
END_CONNECTION_POINT_MAP()
// IOPCServer
STDMETHODIMP AddGroup(
LPCWSTR szName,
BOOL bActive,
DWORD dwRequestedUpdateRate,
OPCHANDLE hClientGroup,
LONG * pTimeBias,
FLOAT * pPercentDeadband,
DWORD dwLCID,
OPCHANDLE * phServerGroup,
DWORD * pRevisedUpdateRate,
REFIID riid,
LPUNKNOWN * ppUnk);
STDMETHODIMP GetErrorString(
HRESULT dwError,
LCID dwLocale,
LPWSTR * ppString);
STDMETHODIMP GetGroupByName(
LPCWSTR szName,
REFIID riid,
LPUNKNOWN * ppUnk);
STDMETHODIMP GetStatus(
OPCSERVERSTATUS **ppServerStatus);
STDMETHODIMP RemoveGroup(
OPCHANDLE hServerGroup,
BOOL bForce);
STDMETHODIMP CreateGroupEnumerator(
OPCENUMSCOPE dwScope,
REFIID riid,
LPUNKNOWN * ppUnk);
// IOPCCommon
STDMETHODIMP SetLocaleID(LCID dwLcid);
STDMETHODIMP GetLocaleID(LCID * pdwLcid);
STDMETHODIMP QueryAvailableLocaleIDs(
DWORD * pdwCount,
LCID ** pdwLcid);
STDMETHODIMP GetErrorString(
HRESULT dwError,
LPWSTR * ppString);
STDMETHODIMP SetClientName(LPCWSTR szName);
// IOPCBrowseServerAddressSpace
STDMETHODIMP QueryOrganization(
OPCNAMESPACETYPE * pNameSpaceType);
STDMETHODIMP ChangeBrowsePosition(
OPCBROWSEDIRECTION dwBrowseDirection,
LPCWSTR szString);
STDMETHODIMP BrowseOPCItemIDs(
OPCBROWSETYPE dwBrowseFilterType,
LPCWSTR szFilterCriteria,
VARTYPE vtDataTypeFilter,
DWORD dwAccessRightsFilter,
LPENUMSTRING * ppIEnumString);
STDMETHODIMP GetItemID(
LPWSTR szItemDataID,
LPWSTR * szItemID);
STDMETHODIMP BrowseAccessPaths(
LPCWSTR szItemID,
LPENUMSTRING * ppIEnumString);
// IOPCItemProperties
STDMETHODIMP QueryAvailableProperties(
LPWSTR szItemID,
DWORD * pdwCount,
DWORD ** ppPropertyIDs,
LPWSTR ** ppDescriptions,
VARTYPE ** ppvtDataTypes);
STDMETHODIMP GetItemProperties(
LPWSTR szItemID,
DWORD dwCount,
DWORD * pdwPropertyIDs,
VARIANT ** ppvData,
HRESULT ** ppErrors);
STDMETHODIMP LookupItemIDs(
LPWSTR szItemID,
DWORD dwCount,
DWORD * pdwPropertyIDs,
LPWSTR ** ppszNewItemIDs,
HRESULT ** ppErrors);
// Overrides
virtual HRESULT DoQueryNumProperties(
LPWSTR szItemID,
DWORD * pdwNumItems,
LPVOID * ppVoid);
virtual HRESULT DoQueryAvailableProperties(
LPWSTR szItemID,
DWORD dwNumItems,
LPVOID pVoid,
DWORD * pPropertyIDs,
LPWSTR * pDescriptions,
VARTYPE * pvtDataTypes);
virtual HRESULT DoGetItemProperties(
LPWSTR szItemID,
DWORD dwNumItems,
DWORD * pPropertyIDs,
VARIANT * pData,
HRESULT * pErrors);
virtual HRESULT DoLookupItemIDs(
LPWSTR szItemID,
DWORD dwNumItems,
DWORD * pPropertyIDs,
LPWSTR * pszNewItemIDs,
HRESULT * pErrors);
virtual HRESULT DoGetStatus( OPCSERVERSTATUS *pServerStatus);
virtual HRESULT DoGetErrorString(
HRESULT dwError,
LCID dwLocale,
LPWSTR pString);
virtual OPCGroupObject* DoAddGroup(
LPCWSTR szName,
BOOL bActive,
DWORD dwRequestedUpdateRate,
OPCHANDLE hClientGroup,
LONG * pTimeBias,
FLOAT * pPercentDeadband,
DWORD dwLCID,
OPCHANDLE * phServerGroup,
DWORD * pRevisedUpdateRate);
virtual OPCNAMESPACETYPE DoQueryOrganization()=0;
virtual HRESULT DoChangeBrowsePosition(
OPCBROWSEDIRECTION dwBrowseDirection,
LPCWSTR szString)=0;
virtual HRESULT DoBrowseOPCItemIDs(
OPCBROWSETYPE dwBrowseFilterType,
LPCWSTR szFilterCriteria,
VARTYPE vtDataTypeFilter,
DWORD dwAccessRightsFilter,
LPENUMSTRING * ppIEnumString)=0;
virtual HRESULT DoGetItemID(
LPWSTR szItemDataID,
LPWSTR * szItemID)=0;
virtual HRESULT DoBrowseAccessPaths(
LPCWSTR szItemID,
LPENUMSTRING * ppIEnumString);
virtual HRESULT DoCreateGroupEnumerator(OPCENUMSCOPE dwScope, REFIID riid, LPUNKNOWN* ppUnk);
//protected:
CRITICAL_SECTION m_cs;
GroupMap m_groupMap;
FILETIME m_lastUpdateTime;
LCID m_localeID;
CString m_client;
};
typedef CTypedPtrList<CPtrList, OPCServerBase*> ServerList;
//*******************************************************************
// An Unknown enumerator for OPC Groups - used for enumerating the groups
class CEnumUnkGroups :
public IEnumUnknown,
public CComObjectRoot
{
friend CEnumUnkGroups;
public:
CEnumUnkGroups();
~CEnumUnkGroups();
void Initialize( LPUNKNOWN* ppUnkGroupList, ULONG iTotal );
BEGIN_COM_MAP(CEnumUnkGroups)
COM_INTERFACE_ENTRY(IEnumUnknown)
END_COM_MAP()
STDMETHODIMP Next( ULONG celt,
IUnknown ** pUnk,
ULONG * pceltFetched );
STDMETHODIMP Skip( ULONG celt );
STDMETHODIMP Reset( void );
STDMETHODIMP Clone( IEnumUnknown ** ppEnumUnknown );
private:
ULONG m_current;
ULONG m_totalCount;
LPUNKNOWN* m_Groups;
OPCENUMSCOPE m_Scope;
};
typedef CComObject<CEnumUnkGroups> CComEnumUnkGroups;
//*********************************************************************
// A String enumerator for OPC Groups - used for enumerating the groups
class CEnumStrGroups :
public IEnumString,
public CComObjectRoot
{
friend CEnumStrGroups;
public:
CEnumStrGroups();
~CEnumStrGroups();
void Initialize( CStringList &StringList );
BEGIN_COM_MAP(CEnumStrGroups)
COM_INTERFACE_ENTRY(IEnumString)
END_COM_MAP()
STDMETHODIMP Next( ULONG celt,
LPOLESTR * ppStrings,
ULONG * pceltFetched );
STDMETHODIMP Skip( ULONG celt );
STDMETHODIMP Reset( void );
STDMETHODIMP Clone( IEnumString ** ppEnunString );
private:
POSITION m_pos;
CStringList m_strings;
};
typedef CComObject<CEnumStrGroups> CComEnumStrGroups;
#endif | [
"[email protected]"
]
| [
[
[
1,
327
]
]
]
|
4a1f29ae47632ed58e6c553ab78b61050ba65ea8 | 3276915b349aec4d26b466d48d9c8022a909ec16 | /数据结构/查找/哈希表--链表存储.cpp | 6885dcd4c8ec45f58b768c80f717612790d3d70a | []
| no_license | flyskyosg/3dvc | c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82 | 0279b1a7ae097b9028cc7e4aa2dcb67025f096b9 | refs/heads/master | 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,294 | cpp | #include<iostream.h>
#include<iostream>
#define max 50
typedef struct lnode
{
int key;
char data;
struct lnode * next;
}lnode;
lnode * st[max];
//***哈希函数******************//
int hax(int key)
{
return key%45;
}
//**********创建表******************//
void creat()
{
int i=0;
for(i;i<max;i++)
st[i]=NULL;
int key,n;char data='\0';lnode * p=NULL,*q=NULL;
cout<<"输入关键字与数据(key_data),输入0_0结束操作:";
cin>>key>>data;
while(data!='0')
{
if(key>max||key<0) cout<<"关键字超出范围."<<endl;
else
{
p=(lnode *)malloc(sizeof(lnode));
p->data=data;
p->key=key;
p->next=NULL;
n=hax(key);
if(st[n]!=NULL) p->next=q;
st[n]=p;q=p;
}
cout<<"输入关键字与数据(key_data):";
cin>>key>>data;
}
}
//*************输出函数******************//
void disp()
{
lnode * p=NULL;int i=0;
cout<<"输出如下:";
for( i=0;i<max;i++)
{
p=st[i];
while(p!=NULL)
{
cout<<p->key<<"_"<<p->data<<" ";
p=p->next;
}
cout<<" ";
}
}
//*************查找表元素*****************//
void search()
{
int key;
cout<<"输入查找的关键字:";
cin>>key;
int n=0;lnode * p=NULL;
n=hax(key);
p=st[n];
while(p->key!=key) p=p->next;
cout<<"要查找的元素是:";
cout<<p->key<<"_"<<p->data<<endl;
}
//*************插入元素****************//
void insert()
{
int key,n;char data='\0';lnode * p=NULL,*q=NULL;
cout<<"输入要插入的关键字与数据(key_data):";
cin>>key>>data;
if(key>max||key<0) cout<<"关键字超出范围."<<endl;
else
{
n=hax(key);
p=(lnode *)malloc(sizeof(lnode));
p->data=data;
p->key=key;
p->next=NULL;
if(st[n]!=NULL) p->next=q;
st[n]=p;q=p;
}
}
//************删除元素***********************//
void delelem()
{
int key=0,n=0;
cout<<"输入删除的关键字:";
cin>>key;
n=hax(key);
lnode * p=NULL,*q=NULL;
p=st[n];
while(p->key!=key)
{
q=p;
p=p->next;
}
if(q==NULL) st[n]=p->next;
else q=p->next;
delete p;
}
//**********主函数*****//
void main()
{
creat();
disp();
insert();
disp();
search();
delelem();
disp();
}
| [
"[email protected]"
]
| [
[
[
1,
151
]
]
]
|
c75a5bcea4fbe2b4dcfd9be32e22cb262882b06f | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/netsdk/NetPlayBack/NetPlayBackBuffer.cpp | f21799715f8e3519a7b287039179e69e2fea1cab | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,912 | cpp | #include "NetPlayBackBuffer.h"
CNetPlayBackBuffer::CNetPlayBackBuffer()
{
m_pData = 0;
m_nTotalSize = m_nMaxWriteSize = m_nMinWriteSize = 0;
m_nReadPos = m_nWritePos = 0;
m_pPauseFunc = 0;
m_userdata = 0;
m_bWriteFlag = true;
m_iPauseFlag = 0;
// InitializeCriticalSection(&m_csBuf);
}
CNetPlayBackBuffer::~CNetPlayBackBuffer()
{
if (m_pData)
{
delete[] m_pData;
}
// DeleteCriticalSection(&m_csBuf);
}
bool CNetPlayBackBuffer::init(int nTotalSize, int nMaxWriteSize, int nMinWriteSize,
NetPlayBackBufferPause pPauseFunc, void *userdata)
{
bool bRet = false;
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
m_iPauseFlag = 0;
if (nTotalSize > 0 && pPauseFunc != 0)
{
m_nTotalSize = nTotalSize;
m_nMaxWriteSize = nMaxWriteSize;
m_nMinWriteSize = nMinWriteSize;
if (m_pData)
{
delete[] m_pData;
}
m_pData = new unsigned char[nTotalSize];
m_nReadPos = m_nWritePos = 0;
m_pPauseFunc = pPauseFunc;
m_userdata = userdata;
m_bWriteFlag = true;
bRet = true;
}
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
return bRet;
}
bool CNetPlayBackBuffer::IsInited()
{
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
bool bRet = m_pData!=NULL ? true : false;
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
return bRet;
}
bool CNetPlayBackBuffer::AddData(unsigned char *data, int datalen)
{
if (!data || datalen <= 0)
{
return false;
}
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
/***********************缓冲数据***********************/
//现在当包长大于存储空间时采取丢包的原则
//如果不是中断过长时间的话不应有包过长的情况发生
int totalSize = datalen + m_nWritePos;
//如果缓冲区足够缓冲数据
if (totalSize <= m_nTotalSize)
{
memcpy(m_pData + m_nWritePos, data, datalen);
m_nWritePos += datalen;
}
//如果缓冲区不足以缓冲数据,从头再来
else
{
if ((totalSize >= m_nTotalSize)
&& m_nReadPos == 0)
{
OutputState();
goto e_exit;
}
memmove(m_pData, m_pData + m_nReadPos, m_nWritePos - m_nReadPos);
m_nWritePos -= m_nReadPos;
m_nReadPos = 0;
if ((datalen + m_nWritePos >= m_nTotalSize))
{
OutputState();
goto e_exit;
}
memcpy(m_pData + m_nWritePos, data, datalen);
m_nWritePos += datalen;
}
if (m_nWritePos >= m_nMaxWriteSize && m_nReadPos != 0)
{
memmove(m_pData, m_pData + m_nReadPos, m_nWritePos - m_nReadPos);
m_nWritePos -= m_nReadPos;
m_nReadPos = 0;
}
OutputState();
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
return true;
e_exit:
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
return false;
}
int CNetPlayBackBuffer::GetData(unsigned char *data, int datalen)
{
if (!data || datalen <= 0)
{
return 0;
}
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
int nRet = 0;
int size = m_nWritePos - m_nReadPos;
if (size > 0)
{
int readlen = 0;
if (size >= datalen)
{
readlen = datalen;
}
else
{
readlen = size;
}
memcpy(data, m_pData + m_nReadPos, datalen);
// OutputState();
nRet = readlen;
}
OutputState();
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
return nRet;
}
void CNetPlayBackBuffer::DecDataLength(int datalen)
{
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
m_nReadPos += datalen;
OutputState();
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
}
void CNetPlayBackBuffer::Reset()
{
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
m_nWritePos = m_nReadPos = 0;
if (IsPaused(BUFFER_SHORT))
{
Resume(BUFFER_SHORT);
}
OutputState();
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
}
int CNetPlayBackBuffer::OutputState()
{
if (!IsPaused(BUFFER_SHORT))
{
if (m_nWritePos >= m_nMaxWriteSize)
{
this->Pause(BUFFER_SHORT);
}
}
else
{
if (m_nWritePos - m_nReadPos <= m_nMinWriteSize/* && m_nWritePos >= m_nMaxWriteSize*/)
{
memmove(m_pData, m_pData + m_nReadPos, m_nWritePos - m_nReadPos);
m_nWritePos -= m_nReadPos;
m_nReadPos = 0;
if (IsPaused(BUFFER_SHORT))
{
Resume(BUFFER_SHORT);
}
return 1;
}
}
return 0;
}
void CNetPlayBackBuffer::Pause(enum PauseResumeID id)
{
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
if (0 == m_iPauseFlag)
{
if (m_pPauseFunc)
{
m_pPauseFunc(true, m_userdata);
}
}
m_iPauseFlag |= (1<<id);
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
}
void CNetPlayBackBuffer::Resume(enum PauseResumeID id)
{
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
m_iPauseFlag &= ~(1<<id);
if (0 == m_iPauseFlag)
{
if (m_pPauseFunc)
{
m_pPauseFunc(false, m_userdata);
}
}
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
}
BOOL CNetPlayBackBuffer::IsPaused(enum PauseResumeID id)
{
// EnterCriticalSection(&m_csBuf);
m_csBuf.Lock();
BOOL bRet = FALSE;
if (m_iPauseFlag & (1<<id))
{
bRet = TRUE;
}
else
{
bRet = FALSE;
}
// LeaveCriticalSection(&m_csBuf);
m_csBuf.UnLock();
return bRet;
}
void CNetPlayBackBuffer::IsRePause()
{
m_csBuf.Lock();
if (m_nWritePos - m_nReadPos >= m_nMaxWriteSize)
{
this->Pause(BUFFER_SHORT);
}
m_csBuf.UnLock();
}
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
291
]
]
]
|
da2d6e26abd1d7a7dd06035a13e9f28ddd001c3e | bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918 | /TPs CPOO/Gareth & Maxime/Projet/Ressources Projet/DLL WPF/CoursPOOWpf/mWrapper/AssemblyInfo.cpp | e5bfd96f7c42078580f0081eb409aecd1e176a3e | []
| no_license | Issam-Engineer/tp4infoinsa | 3538644b40d19375b6bb25f030580004ed4a056d | 1576c31862ffbc048890e72a81efa11dba16338b | refs/heads/master | 2021-01-10T17:53:31.102683 | 2011-01-27T07:46:51 | 2011-01-27T07:46:51 | 55,446,817 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,427 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
//
[assembly:AssemblyTitleAttribute("mWrapper")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("IRISA")];
[assembly:AssemblyProductAttribute("mWrapper")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) IRISA 2010")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de révision et de build par défaut
// en utilisant '*', comme indiqué ci-dessous :
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6"
]
| [
[
[
1,
40
]
]
]
|
6ba0a22eaf91202e33dbd02e26eda848612007f4 | b1093f654e78210a00e6ca561c1a8f8f108f543e | /include/processor/StarProcessor.h | 2690b599dbf129ed04ed2263cc5d1211f413b69f | []
| no_license | childhood/libAiml | bc82b7cd8859aa6fe0a7a3c42ffe4591438ae329 | 7954dc347463bcb4ab0070af87b9cbd421b08acc | refs/heads/master | 2021-01-18T10:07:02.407246 | 2010-09-20T04:40:34 | 2010-09-20T04:40:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | h | /**
* StarProcessor - Retrieves value of the wildcard in the
* input pattern
*
* @author Jonathan Roewen
*/
#ifndef STAR_PROCESSOR_H
#define STAR_PROCESSOR_H
#include "AimlProcessor.h"
#include <string>
using namespace std;
#include "Utils.h"
class StarProcessor : public AimlProcessor
{
public:
~StarProcessor() { }
string process(Match *m, PElement e, Responder *, const string &) {
string index = e->getAttribute("index");
if (index.empty()) {
index = "1";
}
return m->getInputStar(atoi(index.c_str()));
}
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
967da49ea3c5f0d0d9e1eec256171d66093ec40d | 59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02 | /publish/ksguicommon/drawer/KFormatDrawer.h | e82632363b7b8e6ac1fe6d0b1d0fe4db18270fd2 | []
| no_license | fingomajom/skinengine | 444a89955046a6f2c7be49012ff501dc465f019e | 6bb26a46a7edac88b613ea9a124abeb8a1694868 | refs/heads/master | 2021-01-10T11:30:51.541442 | 2008-07-30T07:13:11 | 2008-07-30T07:13:11 | 47,892,418 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,461 | h | /* -------------------------------------------------------------------------
// 文件名 : KFormatDrawer.h
// 创建人 : 冰峰
// 创建时间 : 2008-4-16 9:37:00
// 功能描述 :
//
// $Id: $
// -----------------------------------------------------------------------*/
#ifndef __KFORMATDRAWER_H__
#define __KFORMATDRAWER_H__
#include "KStreamPage.h"
// -------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////
// Control动作基类
class Action
{
public:
typedef enum
{
OMR_NoDeal = 0x00000000, //未处理
OMR_HasDeal = 0x00000001, //处理了
OMR_NeedRedraw = 0x00000002, //需要重绘
};
HWND SetMsgReviecer(HWND hWndReviecer)
{
ASSERT(!_T("应该在派生类中实现!"));
return NULL;
}
int OnMouse(int nCode, const POINT &pt, WPARAM wParam, LPARAM lParam)
{
ASSERT(!_T("应该在派生类中实现!"));
return OMR_NoDeal;
}
};
//////////////////////////////////////////////////////////////////////////
// KFormatControl 给外面使用的,所谓Control是包括了Draw和Action
template<class TDrawHelper = KSingleLineDrawer, class TPolicy = KDefaultPolicy<TDrawHelper> >
class KFormatControl: public TDrawHelper, public Action
{
public:
typedef TDrawHelper TDrawHelper;
typedef TPolicy TPolicy;
public:
KFormatControl()
{
m_Policy.SetDrawHelper(this);
}
virtual ~KFormatControl()
{
}
//////////////////////////////////////////////////////////////////////////
// 导出函数
public:
// 设置显示内容
BOOL SetRichText(LPCTSTR szContent)
{
return m_Policy.SetContent(szContent);
}
// Action
HWND SetMsgReviecer(HWND hWndReviecer)
{
return m_Policy.SetMsgReviecer(hWndReviecer);
}
int OnMouse(int nCode, const POINT &pt, WPARAM wParam, LPARAM lParam)
{
return m_Policy.OnMouse(nCode, pt, wParam, lParam);
}
// HitTestEx
int HitTestEx(const POINT &pt, LPARAM lParam, RECT* lprc = NULL) //外面不需要放lParam的内存!
{
return m_Policy.HitTestEx(pt, lParam, lprc);
}
private:
TPolicy m_Policy;
};
//////////////////////////////////////////////////////////////////////////
// 默认的文字解释类,需要实现Action
template<class TDrawHelper>
class KDefaultPolicy : public Action
{
public:
inline BOOL SetDrawHelper(TDrawHelper *pDrawHelper)
{
m_pDrawHelper = pDrawHelper;
return TRUE;
}
inline BOOL SetContent(LPCTSTR szContent)
{
int nIndex = m_pDrawHelper->AddTextSpan(szContent);
ASSERT(nIndex != -1);
return nIndex != -1;
}
//////////////////////////////////////////////////////////////////////////
// HitTestEx
inline int HitTestEx(POINT pt, LPARAM lParam, RECT* lprc = NULL)
{
ASSERT(!_T("未实现!"));
return ST_NONE;
}
private:
TDrawHelper* m_pDrawHelper;
};
//////////////////////////////////////////////////////////////////////////
// 简单的HTML解析类
#define _SAFE_FIND(exp) \
{ \
if ((exp) == -1) \
goto Exit0; \
}
#define _SAFE_FIND2(exp1, exp2) \
{ \
if ((exp1) == -1) \
{ \
exp2; \
goto Exit0; \
} \
}
//-------------------------------------------------------------------------
typedef enum
{
ST_HYPERLINK = ST_USER_BASE + 1, //超链接
};
#define WM_USER_HYPERLINK (WM_USER + 0xFFFE) //超链接发送的消息id
//////////////////////////////////////////////////////////////////////////
// Html Policy
template<class TDrawHelper = KSingleLineDrawer>
class KSimpleHTMLPolicy : public Action
{
public:
typedef TDrawHelper TDrawHelper;
//////////////////////////////////////////////////////////////////////////
// 私有变量
private:
typedef struct tagItem
{
int nType;
WTL::CString strName;
} _Item;
typedef std::map<UINT, _Item> _Container;
typedef typename _Container::iterator _Iter;
_Container m_Container;
TDrawHelper* m_pDrawHelper;
HWND m_MsgReceiver; //消息接收者
HCURSOR m_OldCursor;
HCURSOR m_HandCursor;
INT m_bPress : 1;
public:
KSimpleHTMLPolicy()
{
m_MsgReceiver = NULL;
m_OldCursor = NULL;
m_HandCursor = ::LoadCursor(NULL, IDC_HAND);
m_bPress = FALSE;
}
//////////////////////////////////////////////////////////////////////////
// 导出函数
public:
inline BOOL SetDrawHelper(TDrawHelper *pDrawHelper)
{
m_pDrawHelper = pDrawHelper;
return TRUE;
}
inline BOOL SetContent(LPCTSTR szContent)
{
m_pDrawHelper->Clear();
return _Parse(szContent);
}
//////////////////////////////////////////////////////////////////////////
// HitTestEx
inline int HitTestEx(POINT pt, void **ppParam = NULL, RECT* lprc = NULL)
{
int nIndex = 0;
HT_TYPE ht = m_pDrawHelper->HitTest(pt, &nIndex, lprc);
if (ht != ST_NONE)
{
// 给附上元素名称
_Container::iterator it = m_Container.find(nIndex);
if (it != m_Container.end())
{
if (ppParam)
*ppParam = (void*)(LPCTSTR)it->second.strName;
if (it->second.nType == ST_HYPERLINK)
return ST_HYPERLINK;
}
}
return ht;
}
//////////////////////////////////////////////////////////////////////////
// Action
HWND SetMsgReviecer(HWND hWndReviecer)
{
HWND hOld = m_MsgReceiver;
m_MsgReceiver = hWndReviecer;
return hOld;
}
int OnMouse(int nCode, const POINT &pt, WPARAM wParam, LPARAM lParam)
{
switch(nCode)
{
case WM_MOUSEMOVE:
return _OnMouseMove(pt, wParam, lParam);
case WM_LBUTTONDOWN:
return _OnLButtonDown(pt, wParam, lParam);
case WM_LBUTTONUP:
return _OnLButtonUp(pt, wParam, lParam);
}
return OMR_NoDeal;
}
//////////////////////////////////////////////////////////////////////////
// Helper
private:
BOOL _Parse(LPCTSTR szText)
{
WTL::CString strText = szText;
WTL::CString strTemp;
const int nEnd = strText.GetLength();
int nElementStart = 0;
int nPos1 = 0, nPos2 = 0;
//Start
while (nPos1 < nEnd)
{
if (strText.GetAt(nPos1) != '<') //裸文本
{
nPos1 = _ParseText(strText, nPos1);
}
else //HTML元素
{
nPos2 = strText.Find(' ', nPos1); //若一个属性都没有,本句会有问题,先不管,到时改成标准XML
strTemp = strText.Mid(nPos1 + 1, nPos2 - nPos1 - 1);
if (strTemp.CompareNoCase(_T("font")) == 0)
nPos1 = _ParseFont(strText, nPos1);
else if (strTemp.CompareNoCase(_T("img")) == 0)
nPos1 = _ParseImage(strText, nPos1);
else if (strTemp.CompareNoCase(_T("a")) == 0)
nPos1 = _ParseHyperLink(strText, nPos1);
}
++nPos1; //Next
}
return TRUE;
};
inline int _ParseText(const WTL::CString& strText, int nStart)
{
int nPos1, nPos2;
nPos1 = nStart;
nPos2 = strText.Find('<', nPos1);
if (nPos2 == -1) //纯文本
nPos2 = strText.GetLength();
m_pDrawHelper->AddTextSpan(strText.Mid(nPos1, nPos2 - nPos1));
return nPos2 - 1;
}
inline int _ParseFont(const WTL::CString &strText, int nStart)
{
WTL::CString strElement, strTemp;
int nElementEnd;
int nPos1, nPos2;
COLORREF rColor = Undefine;
int nSize = Undefine;
UINT bBold = Undefine;
UINT bItalic = Undefine;
UINT bUnderLine = Undefine;
WTL::CString strID; //元素的ID
//属性表
_SAFE_FIND(nPos1 = strText.Find(' ', nStart));
_SAFE_FIND(nElementEnd = strText.Find('>', nStart));
strElement = strText.Mid(nPos1 + 1, nElementEnd - nPos1 - 1);
nPos1 = 0;
while (nPos1 != -1)
{
nPos2 = strElement.Find('=', nPos1);
strTemp = strElement.Mid(nPos1, nPos2 - nPos1);
if (strTemp.CompareNoCase(_T("name")) == 0)
strID = _GetAttributeString(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("color")) == 0)
rColor = _GetAttributeInt(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("size")) == 0)
nSize = _GetAttributeInt(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("bold")) == 0)
bBold = _GetAttributeInt(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("italic")) == 0)
bItalic = _GetAttributeInt(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("underline")) == 0)
bUnderLine = _GetAttributeInt(strElement, nPos1);
else
ASSERT(FALSE);
nPos1 = _FindFirstNotChar(strElement, ' ', nPos1);
}
//Content
nPos1 = nElementEnd + 1;
nPos2 = strText.Find('<', nPos1);
int nIndex = m_pDrawHelper->AddTextSpan(strText.Mid(nPos1, nPos2 - nPos1),
rColor, nSize, bBold, bItalic, bUnderLine);
if (!strID.IsEmpty()) //元素id对应表
{
m_Container[nIndex].nType = 0;
m_Container[nIndex].strName = strID;
}
return strText.Find('>', nPos2);
Exit0:
return -1;
};
inline int _ParseImage(const WTL::CString &strText, int nStart)
{
WTL::CString strElement, strTemp;
int nElementEnd;
int nPos1, nPos2;
WTL::CString strID, strImage;
INT nImageListIndex = -1;
//属性表
_SAFE_FIND(nPos1 = strText.Find(' ', nStart));
_SAFE_FIND(nElementEnd = strText.Find(_T("/>"), nStart));
strElement = strText.Mid(nPos1 + 1, nElementEnd - nPos1 - 1);
nPos1 = 0;
while (nPos1 != -1)
{
nPos2 = strElement.Find('=', nPos1);
strTemp = strElement.Mid(nPos1, nPos2 - nPos1);
if (strTemp.CompareNoCase(_T("name")) == 0)
strID = _GetAttributeString(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("srcid")) == 0)
strImage = _GetAttributeString(strElement, nPos1);
else if (strTemp.CompareNoCase(_T("index")) == 0)
nImageListIndex = _GetAttributeInt(strElement, nPos1);
else
ASSERT(FALSE);
nPos1 = _FindFirstNotChar(strElement, ' ', nPos1);
}
ASSERT(!strImage.IsEmpty());
if (nImageListIndex == -1) //单个Bitmap
{
LPCTSTR szImageListName;
KImageListManager *pImageListMgr = KImageListManager::Instance();
nImageListIndex = pImageListMgr->GetImageListByBitmapName(strImage, &szImageListName);
ASSERT(nImageListIndex != -1);
strImage = szImageListName;
}
if (nImageListIndex != -1)
{
int nIndex = m_pDrawHelper->AddImageSpan(strImage, nImageListIndex);
if (!strID.IsEmpty()) //元素id对应表
{
m_Container[nIndex].nType = 0;
m_Container[nIndex].strName = strID;
}
}
return nElementEnd + 1;
Exit0:
return -1;
}
inline int _ParseHyperLink(const WTL::CString &strText, int nStart)
{
WTL::CString strElement, strTemp;
int nElementEnd;
int nPos1, nPos2;
COLORREF rColor = RGB(0, 0, 255); //蓝色
WTL::CString strID; //元素的ID
//属性表
_SAFE_FIND(nPos1 = strText.Find(' ', nStart));
_SAFE_FIND(nElementEnd = strText.Find('>', nStart));
strElement = strText.Mid(nPos1 + 1, nElementEnd - nPos1 - 1);
nPos1 = 0;
while (nPos1 != -1)
{
nPos2 = strElement.Find('=', nPos1);
strTemp = strElement.Mid(nPos1, nPos2 - nPos1);
if (strTemp.CompareNoCase(_T("name")) == 0)
strID = _GetAttributeString(strElement, nPos1);
else
ASSERT(FALSE);
nPos1 = _FindFirstNotChar(strElement, ' ', nPos1);
}
//Content
nPos1 = nElementEnd + 1;
nPos2 = strText.Find('<', nPos1);
int nIndex = m_pDrawHelper->AddTextSpan(strText.Mid(nPos1, nPos2 - nPos1), rColor);
m_Container[nIndex].nType = ST_HYPERLINK;
if (!strID.IsEmpty()) //元素id对应表
m_Container[nIndex].strName = strID;
return strText.Find('>', nPos2);
Exit0:
return -1;
}
inline int _GetAttributeInt(const WTL::CString &strText, int &nStart)
{
WTL::CString strTemp;
int nPos1, nPos2;
nPos1 = nStart;
_SAFE_FIND2(nPos1 = strText.Find('=', nPos1), nStart = -1);
_SAFE_FIND2(nPos1 = strText.Find('\'', nPos1), nStart = -1);
_SAFE_FIND2(nPos2 = strText.Find('\'', nPos1 + 1), nStart = -1);
strTemp = strText.Mid(nPos1 + 1, nPos2 - nPos1 -1);
nStart = nPos2 + 1;
if (strTemp.Find(_T("0x")) != -1)
{
int nRes = 0;
_stscanf_s(strText.Mid(nPos1 + 1, nPos2 - nPos1 -1), _T("%x"), &nRes);
return RGB(GetBValue(nRes), GetGValue(nRes), GetRValue(nRes)); //把GRB反为RGB
}
else
return _ttoi(strTemp);
Exit0:
return -1;
};
WTL::CString _GetAttributeString(WTL::CString &strText, int &nStart)
{
int nPos1, nPos2;
nPos1 = nStart;
_SAFE_FIND2(nPos1 = strText.Find('=', nPos1), nStart = -1);
_SAFE_FIND2(nPos1 = strText.Find('\'', nPos1), nStart = -1);
_SAFE_FIND2(nPos2 = strText.Find('\'', nPos1 + 1), nStart = -1);
nStart = nPos2 + 1;
return strText.Mid(nPos1 + 1, nPos2 - nPos1 -1);
Exit0:
return _T("");
};
inline int _FindFirstNotChar(WTL::CString& strText, TCHAR c, int nStart)
{
for (int i = nStart; i < strText.GetLength(); ++i)
{
if (strText.GetAt(i) != c)
return i;
}
return -1;
};
inline int _OnMouseMove(const POINT &pt, WPARAM wParam, LPARAM lParam)
{
static int s_nLastHyperLink = -1;
int nRet = OMR_NoDeal;
CRect rc;
int ht = HitTestEx(pt, NULL, &rc);
if (ht == ST_HYPERLINK)
{
m_OldCursor = ::SetCursor(m_HandCursor);
//Add Underline
int nIndex = 0;
m_pDrawHelper->HitTest(pt, &nIndex);
m_pDrawHelper->ChangeTextPiece(nIndex, NULL, Undefine, Undefine, Undefine, Undefine, TRUE);
s_nLastHyperLink = nIndex;
nRet = OMR_HasDeal | OMR_NeedRedraw;
}
else if (m_OldCursor != NULL)
{
::SetCursor(m_OldCursor);
// Remove underline
if (s_nLastHyperLink != -1)
{
m_pDrawHelper->ChangeTextPiece(s_nLastHyperLink, NULL, Undefine, Undefine, Undefine, Undefine, FALSE);
s_nLastHyperLink = -1;
nRet = OMR_HasDeal | OMR_NeedRedraw;
}
}
return nRet;
}
inline int _OnLButtonDown(const POINT &pt, WPARAM wParam, LPARAM lParam)
{
if (!m_MsgReceiver)
return OMR_NoDeal;
m_bPress = TRUE;
return OMR_HasDeal;
}
inline int _OnLButtonUp(const POINT &pt, WPARAM wParam, LPARAM lParam)
{
if (!m_MsgReceiver)
return OMR_NoDeal;
// if (!m_bPress)
// return OMR_NoDeal;
// m_bPress = FALSE;
// Normal
CRect rc;
LPCTSTR szName = NULL;
int ht;
if (lParam)
ht = HitTestEx(pt);
else
{
ht = HitTestEx(pt, (void**)&szName);
lParam = (LPARAM)szName;
}
if (ht == ST_HYPERLINK)
{
::SendMessage(m_MsgReceiver, WM_USER_HYPERLINK, wParam, lParam);
// 要不要变色?to do...
return OMR_HasDeal;
}
return OMR_NoDeal;
}
};
//////////////////////////////////////////////////////////////////////////
// Typedef
typedef KFormatControl<KSingleLineDrawer, KDefaultPolicy<KSingleLineDrawer> > KDefaultControl;
typedef KFormatControl<KSingleLineDrawer, KSimpleHTMLPolicy<KSingleLineDrawer> > KSingleLineHTMLControl; //单行
typedef KFormatControl<KMutiLineDrawer, KSimpleHTMLPolicy<KMutiLineDrawer> > KMutilineHTMLControl; //支持折行
// -------------------------------------------------------------------------
// $Log: $
#endif /* __KFORMATDRAWER_H__ */
| [
"[email protected]"
]
| [
[
[
1,
588
]
]
]
|
efbfb5cad93873b8717b2b29865981ed87e2a65a | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Tactical/Morale.cpp | ca29fd508fa67647d34ac3a79105c186118e8a5c | []
| no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,881 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Tactical All.h"
#else
#include <stdlib.h>
#include "Morale.h"
#include "Overhead.h"
#include "Soldier Profile.h"
#include "dialogue control.h"
#include "Map Screen Interface.h"
#include "message.h"
#include "assignments.h"
#include "Strategic Movement.h"
#include "Strategic Status.h"
#include "SkillCheck.h"
#include "drugs and alcohol.h"
#include "StrategicMap.h"
#include "Debug.h"
#include "Squads.h"
#include "ai.h"
#include "Campaign.h"
#include "mapscreen.h"
#include "Soldier macros.h"
#include "Event Pump.h"
// HEADROCK HAM 3.5: Added for facility effect on morale
#include "Facilities.h"
// addedd by SANDRO
#include "GameSettings.h"
#include "Isometric Utils.h"
#endif
#include "connect.h"
#include "fresh_header.h"
#define MORALE_MOD_MAX 50 // morale *mod* range is -50 to 50, if you change this, check the decay formulas!
#define DRUG_EFFECT_MORALE_MOD 150
#define ALCOHOL_EFFECT_MORALE_MOD 160
#define HOURS_BETWEEN_STRATEGIC_DECAY 3
#define PHOBIC_LIMIT -20
// macros
#define SOLDIER_IN_SECTOR( pSoldier, sX, sY, bZ ) ( !pSoldier->flags.fBetweenSectors && ( pSoldier->sSectorX == sX ) && ( pSoldier->sSectorY == sY ) && ( pSoldier->bSectorZ == bZ ) )
MoraleEvent gbMoraleEvent[NUM_MORALE_EVENTS] =
{
// TACTICAL = Short Term Effect, STRATEGIC = Long Term Effect
{ TACTICAL_MORALE_EVENT, +4}, // MORALE_KILLED_ENEMY
{ TACTICAL_MORALE_EVENT, -5}, // MORALE_SQUADMATE_DIED, // in same sector (not really squad)... IN ADDITION to strategic loss of morale
{ TACTICAL_MORALE_EVENT, -1}, // MORALE_SUPPRESSED, // up to 4 times per turn
{ TACTICAL_MORALE_EVENT, -2}, // MORALE_AIRSTRIKE,
{ TACTICAL_MORALE_EVENT, +2}, // MORALE_DID_LOTS_OF_DAMAGE,
{ TACTICAL_MORALE_EVENT, -3}, // MORALE_TOOK_LOTS_OF_DAMAGE,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_KILLED_CIVILIAN,
{ STRATEGIC_MORALE_EVENT, +4}, // MORALE_BATTLE_WON,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_RAN_AWAY,
{ STRATEGIC_MORALE_EVENT, +2}, // MORALE_HEARD_BATTLE_WON,
{ STRATEGIC_MORALE_EVENT, -2}, // MORALE_HEARD_BATTLE_LOST,
{ STRATEGIC_MORALE_EVENT, +5}, // MORALE_TOWN_LIBERATED,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_TOWN_LOST,
{ STRATEGIC_MORALE_EVENT, +8}, // MORALE_MINE_LIBERATED,
{ STRATEGIC_MORALE_EVENT, -8}, // MORALE_MINE_LOST,
{ STRATEGIC_MORALE_EVENT, +3}, // MORALE_SAM_SITE_LIBERATED,
{ STRATEGIC_MORALE_EVENT, -3}, // MORALE_SAM_SITE_LOST,
{ STRATEGIC_MORALE_EVENT, -15}, // MORALE_BUDDY_DIED,
{ STRATEGIC_MORALE_EVENT, +5}, // MORALE_HATED_DIED,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_TEAMMATE_DIED, // not in same sector
{ STRATEGIC_MORALE_EVENT, +5}, // MORALE_LOW_DEATHRATE,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_HIGH_DEATHRATE,
{ STRATEGIC_MORALE_EVENT, +2}, // MORALE_GREAT_MORALE,
{ STRATEGIC_MORALE_EVENT, -2}, // MORALE_POOR_MORALE,
{ TACTICAL_MORALE_EVENT, -10}, // MORALE_DRUGS_CRASH
{ TACTICAL_MORALE_EVENT, -10}, // MORALE_ALCOHOL_CRASH
{ STRATEGIC_MORALE_EVENT, +15}, // MORALE_MONSTER_QUEEN_KILLED
{ STRATEGIC_MORALE_EVENT, +25}, // MORALE_DEIDRANNA_KILLED
{ TACTICAL_MORALE_EVENT, -1}, // MORALE_CLAUSTROPHOBE_UNDERGROUND,
{ TACTICAL_MORALE_EVENT, -5}, // MORALE_INSECT_PHOBIC_SEES_CREATURE,
{ TACTICAL_MORALE_EVENT, -1}, // MORALE_NERVOUS_ALONE,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_MERC_CAPTURED,
{ STRATEGIC_MORALE_EVENT, -5}, // MORALE_MERC_MARRIED,
{ STRATEGIC_MORALE_EVENT, +8}, // MORALE_QUEEN_BATTLE_WON,
{ STRATEGIC_MORALE_EVENT, +5}, // MORALE_SEX,
// added by SANDRO
{ STRATEGIC_MORALE_EVENT, -1}, // MORALE_HEAT_INTOLERANT_IN_DESERT,
{ TACTICAL_MORALE_EVENT, -1}, // MORALE_PSYCHO_UNABLE_TO_PSYCHO,
{ STRATEGIC_MORALE_EVENT, +1}, // MORALE_PACIFIST_GAIN_NONCOMBAT,
{ TACTICAL_MORALE_EVENT, +1}, // MORALE_MALICIOUS_HIT,
};
BOOLEAN gfSomeoneSaidMoraleQuote = FALSE;
BOOLEAN IsShowOffNearBy( SOLDIERTYPE * pSoldier ); // Added by SANDRO
INT8 GetMoraleModifier( SOLDIERTYPE * pSoldier )
{
if (pSoldier->flags.uiStatusFlags & SOLDIER_PC)
{
if (pSoldier->aiData.bMorale > 50)
{
// give +1 at 55, +3 at 65, up to +5 at 95 and above
return( (pSoldier->aiData.bMorale - 45) / 10 );
}
else
{
// give penalties down to -20 at 0 (-2 at 45, -4 by 40...)
return( (pSoldier->aiData.bMorale - 50) * 2 / 5 );
}
}
else
{
// use AI morale
switch( pSoldier->aiData.bAIMorale )
{
case MORALE_HOPELESS:
return( -15 );
case MORALE_WORRIED:
return( -7 );
case MORALE_CONFIDENT:
return( 2 );
case MORALE_FEARLESS:
return( 5 );
default:
return( 0 );
}
}
}
void DecayTacticalMorale( SOLDIERTYPE * pSoldier )
{
// decay the tactical morale modifier
if (pSoldier->aiData.bTacticalMoraleMod != 0)
{
// decay the modifier!
if (pSoldier->aiData.bTacticalMoraleMod > 0)
{
pSoldier->aiData.bTacticalMoraleMod = __max( 0, pSoldier->aiData.bTacticalMoraleMod - (8 - pSoldier->aiData.bTacticalMoraleMod / 10) );
}
else
{
pSoldier->aiData.bTacticalMoraleMod = __min( 0, pSoldier->aiData.bTacticalMoraleMod + (6 + pSoldier->aiData.bTacticalMoraleMod / 10) );
}
}
}
void DecayStrategicMorale( SOLDIERTYPE * pSoldier )
{
// HEADROCK HAM 3.5: Strategic Morale Mod no longer normalizes to 0 by default. In fact, a local facility can
// cause normalization to another value (positive or negative!), based on the activity that the character is
// currently performing. It can literally reduce morale to ridiculously low amounts if you don't watch your
// assignments in some sectors.
// decay the modifier!
if (pSoldier->aiData.bStrategicMoraleMod > 0)
{
pSoldier->aiData.bStrategicMoraleMod = __max( 0, pSoldier->aiData.bStrategicMoraleMod - (8 - (pSoldier->aiData.bStrategicMoraleMod / 10)) );
}
else
{
pSoldier->aiData.bStrategicMoraleMod = __min( 0, pSoldier->aiData.bStrategicMoraleMod + (6 + (pSoldier->aiData.bStrategicMoraleMod / 10)) );
}
}
void DecayTacticalMoraleModifiers( void )
{
SOLDIERTYPE * pSoldier;
UINT8 ubLoop, ubLoop2;
BOOLEAN fHandleNervous;
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pSoldier++ )
{
//if the merc is active, in Arulco
// CJC: decay modifiers while asleep! or POW!
if ( pSoldier->bActive && pSoldier->ubProfile != NO_PROFILE &&
!(pSoldier->bAssignment == IN_TRANSIT ||
pSoldier->bAssignment == ASSIGNMENT_DEAD ) )
{
// only let morale mod decay if it is positive while merc is a POW
if ( pSoldier->bAssignment == ASSIGNMENT_POW && pSoldier->aiData.bTacticalMoraleMod < 0 )
{
continue;
}
switch( gMercProfiles[ pSoldier->ubProfile ].bDisability )
{
case CLAUSTROPHOBIC:
if ( pSoldier->bSectorZ > 0 )
{
// underground, no recovery... in fact, if tact morale is high, decay
if ( pSoldier->aiData.bTacticalMoraleMod > PHOBIC_LIMIT )
{
HandleMoraleEvent( pSoldier, MORALE_CLAUSTROPHOBE_UNDERGROUND, pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ );
}
continue;
}
break;
case NERVOUS:
if ( pSoldier->aiData.bMorale < 50 )
{
if (pSoldier->ubGroupID != 0 && PlayerIDGroupInMotion( pSoldier->ubGroupID ))
{
if ( NumberOfPeopleInSquad( pSoldier->bAssignment ) == 1 )
{
fHandleNervous = TRUE;
}
else
{
fHandleNervous = FALSE;
}
}
else if ( pSoldier->bActive && pSoldier->bInSector )
{
if ( DistanceToClosestFriend( pSoldier ) > NERVOUS_RADIUS )
{
fHandleNervous = TRUE;
}
else
{
fHandleNervous = FALSE;
}
}
else
{
// look for anyone else in same sector
fHandleNervous = TRUE;
for ( ubLoop2 = gTacticalStatus.Team[ gbPlayerNum ].bFirstID; ubLoop2 <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop2++ )
{
if ( MercPtrs[ ubLoop2 ] != pSoldier && MercPtrs[ ubLoop2 ]->bActive && MercPtrs[ ubLoop2 ]->sSectorX == pSoldier->sSectorX && MercPtrs[ ubLoop2 ]->sSectorY == pSoldier->sSectorY && MercPtrs[ ubLoop2 ]->bSectorZ == pSoldier->bSectorZ )
{
// found someone!
fHandleNervous = FALSE;
break;
}
}
}
if ( fHandleNervous )
{
if ( pSoldier->aiData.bTacticalMoraleMod == PHOBIC_LIMIT )
{
// don't change morale
continue;
}
// alone, no recovery... in fact, if tact morale is high, decay
if ( !(pSoldier->usQuoteSaidFlags & SOLDIER_QUOTE_SAID_PERSONALITY) )
{
TacticalCharacterDialogue( pSoldier, QUOTE_PERSONALITY_TRAIT );
pSoldier->usQuoteSaidFlags |= SOLDIER_QUOTE_SAID_PERSONALITY;
}
HandleMoraleEvent( pSoldier, MORALE_NERVOUS_ALONE, pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ );
continue;
}
}
}
DecayTacticalMorale( pSoldier );
RefreshSoldierMorale( pSoldier );
}
}
}
void DecayStrategicMoraleModifiers( void )
{
SOLDIERTYPE * pSoldier;
UINT8 ubLoop;
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pSoldier++ )
{
//if the merc is active, in Arulco
// CJC: decay modifiers while asleep! or POW!
if ( pSoldier->bActive && pSoldier->ubProfile != NO_PROFILE &&
!(pSoldier->bAssignment == IN_TRANSIT ||
pSoldier->bAssignment == ASSIGNMENT_DEAD ) )
{
// only let morale mod decay if it is positive while merc is a POW
if ( pSoldier->bAssignment == ASSIGNMENT_POW && pSoldier->aiData.bStrategicMoraleMod < 0 )
{
continue;
}
DecayStrategicMorale( pSoldier );
RefreshSoldierMorale( pSoldier );
}
}
}
void RefreshSoldierMorale( SOLDIERTYPE * pSoldier )
{
INT32 iActualMorale;
if ( pSoldier->flags.fMercAsleep )
{
// delay this till later!
return;
}
// CJC, April 19, 1999: added up to 20% morale boost according to progress
iActualMorale = DEFAULT_MORALE + (INT32) pSoldier->aiData.bTeamMoraleMod + (INT32) pSoldier->aiData.bTacticalMoraleMod + (INT32) pSoldier->aiData.bStrategicMoraleMod + (INT32) (CurrentPlayerProgressPercentage() / 5);
// ATE: Modify morale based on drugs....
iActualMorale += ( ( pSoldier->drugs.bDrugEffect[ DRUG_TYPE_ADRENALINE ] * DRUG_EFFECT_MORALE_MOD ) / 100 );
iActualMorale += ( ( pSoldier->drugs.bDrugEffect[ DRUG_TYPE_ALCOHOL ] * ALCOHOL_EFFECT_MORALE_MOD ) / 100 );
iActualMorale = __min( 100, iActualMorale );
iActualMorale = __max( 0, iActualMorale );
UINT8 ubMaxMorale = 100;
// HEADROCK HAM 3.5: Local facilities may decrease the total morale allowed.
for (UINT16 cnt = 0; cnt < NUM_FACILITY_TYPES; cnt++)
{
if (gFacilityLocations[SECTOR(pSoldier->sSectorX, pSoldier->sSectorY)][cnt].fFacilityHere)
{
if (cnt == (UINT16)pSoldier->sFacilityTypeOperated && // Soldier is operating this facility
GetSoldierFacilityAssignmentIndex( pSoldier ) != -1)
{
UINT8 ubFacilityType = (UINT8)cnt;
UINT8 ubAssignmentType = (UINT8)GetSoldierFacilityAssignmentIndex( pSoldier );
// Check this facility both for an assignment-specific AND ambient value. Use it if it's the lowest
// encountered yet.
ubMaxMorale = __min(ubMaxMorale, (UINT8)GetFacilityModifier(FACILITY_MAX_MORALE, ubFacilityType, ubAssignmentType ));
}
else // Soldier is not operating this facility
{
// Check this facility for an AMBIENT Maximum Morale limit. Use it if it's the lowest encountered yet.
ubMaxMorale = __min(ubMaxMorale, (UINT8)GetFacilityModifier(FACILITY_MAX_MORALE, (UINT8)cnt, FAC_AMBIENT));
}
}
}
if (ubMaxMorale > 0 && iActualMorale > ubMaxMorale)
{
// Normalize to Max Morale
iActualMorale = (iActualMorale + ubMaxMorale) / 2;
}
pSoldier->aiData.bMorale = (INT8) iActualMorale;
// update mapscreen as needed
fCharacterInfoPanelDirty = TRUE;
}
// SANDRO - changed this a bit
void UpdateSoldierMorale( SOLDIERTYPE * pSoldier, INT8 bMoraleEvent )
{
MERCPROFILESTRUCT * pProfile;
INT32 iMoraleModTotal;
UINT8 ubType;
INT8 bMoraleMod = 0;
if ( !pSoldier->bActive || ( pSoldier->stats.bLife < CONSCIOUSNESS ) ||
( pSoldier->flags.uiStatusFlags & SOLDIER_VEHICLE ) || AM_A_ROBOT( pSoldier ) || AM_AN_EPC( pSoldier ) )
{
return;
}
if ( ( pSoldier->bAssignment == ASSIGNMENT_DEAD ) ||
( pSoldier->bAssignment == ASSIGNMENT_POW ) ||
( pSoldier->bAssignment == IN_TRANSIT ) )
{
return;
}
if ( pSoldier->ubProfile == NO_PROFILE )
{
return;
}
if(cDisableMorale && is_networked)
{
return;
}//hayden
ubType = gbMoraleEvent[bMoraleEvent].ubType;
bMoraleMod = gbMoraleEvent[bMoraleEvent].bChange;
pProfile = &(gMercProfiles[ pSoldier->ubProfile ]);
if (bMoraleMod > 0)
{
if ( gGameOptions.fNewTraitSystem )
{
// SANDRO - STOMP traits
// Squadleader's bonus to morale
if ( IS_MERC_BODY_TYPE( pSoldier ) && (pSoldier->bTeam == ENEMY_TEAM || pSoldier->bTeam == MILITIA_TEAM || pSoldier->bTeam == gbPlayerNum) )
{
bMoraleMod += (gSkillTraitValues.ubSLMoraleGainBonus * GetSquadleadersCountInVicinity( pSoldier, FALSE, FALSE ));
}
// Check for character traits
INT8 bNumMercs = 0;
switch( pProfile->bCharacterTrait )
{
case CHAR_TRAIT_SOCIABLE:
bNumMercs = CheckMercsNearForCharTraits( pSoldier->ubProfile, CHAR_TRAIT_SOCIABLE );
if ( bNumMercs == 0 )
bMoraleMod -= 5;
else if ( bNumMercs == 1 )
bMoraleMod -= 2;
break;
case CHAR_TRAIT_LONER:
bNumMercs = CheckMercsNearForCharTraits( pSoldier->ubProfile, CHAR_TRAIT_LONER );
if ( bNumMercs > 1 )
bMoraleMod -= 5;
else if ( bNumMercs == 1 )
bMoraleMod -= 2;
break;
case CHAR_TRAIT_OPTIMIST:
bMoraleMod += 1;
break;
case CHAR_TRAIT_AGGRESSIVE:
switch ( bMoraleEvent )
{
case MORALE_KILLED_ENEMY:
case MORALE_DID_LOTS_OF_DAMAGE:
case MORALE_MONSTER_QUEEN_KILLED:
case MORALE_DEIDRANNA_KILLED:
bMoraleMod += 1;
break;
}
break;
case CHAR_TRAIT_PACIFIST:
switch ( bMoraleEvent )
{
case MORALE_KILLED_ENEMY:
case MORALE_DID_LOTS_OF_DAMAGE:
case MORALE_BATTLE_WON:
case MORALE_HEARD_BATTLE_WON:
case MORALE_HATED_DIED:
case MORALE_MONSTER_QUEEN_KILLED:
case MORALE_DEIDRANNA_KILLED:
case MORALE_QUEEN_BATTLE_WON:
bMoraleMod -= 5;
break;
}
break;
}
if ( IsShowOffNearBy( pSoldier ) )
{
bMoraleMod -= 2;
}
}
else if ( bMoraleMod != MORALE_PSYCHO_UNABLE_TO_PSYCHO && bMoraleMod != MORALE_MALICIOUS_HIT)
{
switch( pProfile->bAttitude )
{
case ATT_OPTIMIST:
case ATT_AGGRESSIVE:
bMoraleMod += 1;
break;
case ATT_PESSIMIST:
bMoraleMod -= 1;
break;
default:
break;
}
}
if (bMoraleMod < 0)
{
// can't change a positive event into a negative one!
bMoraleMod = 0;
}
}
else
{
if ( gGameOptions.fNewTraitSystem )
{
// SANDRO - STOMP traits - squadleader's bonus to morale
if ( IS_MERC_BODY_TYPE( pSoldier ) && (pSoldier->bTeam == ENEMY_TEAM || pSoldier->bTeam == MILITIA_TEAM || pSoldier->bTeam == gbPlayerNum) )
{
switch ( bMoraleEvent ) // certain thing are not supported by our squadleader
{
case MORALE_HATED_DIED:
case MORALE_MERC_MARRIED:
case MORALE_SEX:
case MORALE_PSYCHO_UNABLE_TO_PSYCHO:
case MORALE_MALICIOUS_HIT:
break;
default:
bMoraleMod += (gSkillTraitValues.ubSLMoraleLossReduction * GetSquadleadersCountInVicinity( pSoldier, FALSE, FALSE ));
break;
}
}
// Check for character traits
if ( pProfile->bCharacterTrait == CHAR_TRAIT_OPTIMIST )
{
bMoraleMod += 1;
}
// Fearless character does not suffer morale loss for these so much
else if( pProfile->bCharacterTrait == CHAR_TRAIT_DAUNTLESS )
{
switch ( bMoraleEvent )
{
case MORALE_SQUADMATE_DIED:
case MORALE_SUPPRESSED:
case MORALE_TOOK_LOTS_OF_DAMAGE:
bMoraleMod += 3;
break;
case MORALE_TEAMMATE_DIED:
bMoraleMod += 2;
break;
}
}
}
else if ( bMoraleMod != MORALE_PSYCHO_UNABLE_TO_PSYCHO)
{
switch( pProfile->bAttitude )
{
case ATT_OPTIMIST:
bMoraleMod += 1;
break;
case ATT_PESSIMIST:
bMoraleMod -= 1;
break;
case ATT_COWARD:
bMoraleMod -= 2;
default:
break;
}
}
if (pSoldier->pathing.bLevel == 1)
{
bMoraleMod--;
}
else if (pSoldier->pathing.bLevel > 5)
{
bMoraleMod++;
}
if (bMoraleMod > 0)
{
// can't change a negative event into a positive one!
bMoraleMod = 0;
}
}
// apply change!
if (ubType == TACTICAL_MORALE_EVENT)
{
iMoraleModTotal = (INT32) pSoldier->aiData.bTacticalMoraleMod + (INT32) bMoraleMod;
iMoraleModTotal = __min( iMoraleModTotal, MORALE_MOD_MAX );
iMoraleModTotal = __max( iMoraleModTotal, -MORALE_MOD_MAX );
pSoldier->aiData.bTacticalMoraleMod = (INT8) iMoraleModTotal;
}
else if ( gTacticalStatus.fEnemyInSector && !pSoldier->bInSector ) // delayed strategic
{
iMoraleModTotal = (INT32) pSoldier->bDelayedStrategicMoraleMod + (INT32) bMoraleMod;
iMoraleModTotal = __min( iMoraleModTotal, MORALE_MOD_MAX );
iMoraleModTotal = __max( iMoraleModTotal, -MORALE_MOD_MAX );
pSoldier->bDelayedStrategicMoraleMod = (INT8) iMoraleModTotal;
}
else // strategic
{
iMoraleModTotal = (INT32) pSoldier->aiData.bStrategicMoraleMod + (INT32) bMoraleMod;
iMoraleModTotal = __min( iMoraleModTotal, MORALE_MOD_MAX );
iMoraleModTotal = __max( iMoraleModTotal, -MORALE_MOD_MAX );
pSoldier->aiData.bStrategicMoraleMod = (INT8) iMoraleModTotal;
}
RefreshSoldierMorale( pSoldier );
if ( !pSoldier->flags.fMercAsleep )
{
if ( !gfSomeoneSaidMoraleQuote )
{
// Check if we're below a certain value and warn
if ( pSoldier->aiData.bMorale < 35 )
{
// Have we said this quote yet?
if ( !( pSoldier->usQuoteSaidFlags & SOLDIER_QUOTE_SAID_LOW_MORAL ) )
{
gfSomeoneSaidMoraleQuote = TRUE;
// ATE: Amde it a DELAYED QUOTE - will be delayed by the dialogue Q until it's our turn...
DelayedTacticalCharacterDialogue( pSoldier, QUOTE_STARTING_TO_WHINE );
pSoldier->usQuoteSaidFlags |= SOLDIER_QUOTE_SAID_LOW_MORAL;
}
}
}
}
// Reset flag!
if ( pSoldier->aiData.bMorale > 65 )
{
pSoldier->usQuoteSaidFlags &= (~SOLDIER_QUOTE_SAID_LOW_MORAL );
}
}
void HandleMoraleEventForSoldier( SOLDIERTYPE * pSoldier, INT8 bMoraleEvent )
{
// SANDRO - changed this to send the event forward
UpdateSoldierMorale( pSoldier, bMoraleEvent ); //, gbMoraleEvent[bMoraleEvent].ubType, gbMoraleEvent[bMoraleEvent].bChange );
}
void HandleMoraleEvent( SOLDIERTYPE *pSoldier, INT8 bMoraleEvent, INT16 sMapX, INT16 sMapY, INT8 bMapZ )
{
UINT8 ubLoop;
SOLDIERTYPE * pTeamSoldier;
MERCPROFILESTRUCT * pProfile;
gfSomeoneSaidMoraleQuote = FALSE;
// NOTE: Many morale events are NOT attached to a specific player soldier at all!
// Those that do need it have Asserts on a case by case basis below
if (pSoldier == NULL)
{
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Handling morale event %d at X=%d, Y=%d,Z=%d", bMoraleEvent, sMapX, sMapY, bMapZ ) );
}
else
{
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Handling morale event %d for %S at X=%d, Y=%d, Z=%d", bMoraleEvent, pSoldier->name, sMapX, sMapY, bMapZ ) );
}
switch( bMoraleEvent )
{
case MORALE_KILLED_ENEMY:
case MORALE_DID_LOTS_OF_DAMAGE:
case MORALE_DRUGS_CRASH:
case MORALE_ALCOHOL_CRASH:
case MORALE_SUPPRESSED:
case MORALE_TOOK_LOTS_OF_DAMAGE:
case MORALE_HIGH_DEATHRATE:
case MORALE_SEX:
// needs specific soldier!
Assert( pSoldier );
// affects the soldier only
HandleMoraleEventForSoldier( pSoldier, bMoraleEvent );
break;
case MORALE_CLAUSTROPHOBE_UNDERGROUND:
case MORALE_INSECT_PHOBIC_SEES_CREATURE:
case MORALE_NERVOUS_ALONE:
case MORALE_HEAT_INTOLERANT_IN_DESERT: // SANDRO added this one
// needs specific soldier!
Assert( pSoldier );
// affects the soldier only, should be ignored if tactical morale mod is -20 or less
// SANDRO - really?? I think it also shouldn't go lower if strategic morale mod is less than -20
if ( pSoldier->aiData.bTacticalMoraleMod > PHOBIC_LIMIT && pSoldier->aiData.bStrategicMoraleMod > PHOBIC_LIMIT )
{
HandleMoraleEventForSoldier( pSoldier, bMoraleEvent );
}
break;
case MORALE_BATTLE_WON:
// affects everyone to varying degrees
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive )
{
if ( SOLDIER_IN_SECTOR( pTeamSoldier, sMapX, sMapY, bMapZ ) )
{
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_BATTLE_WON );
}
// SANDRO - Assertive people don't care about actions of others
else if ( !gGameOptions.fNewTraitSystem || gMercProfiles[pTeamSoldier->ubProfile].bCharacterTrait != CHAR_TRAIT_ASSERTIVE )
{
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_HEARD_BATTLE_WON );
}
}
}
break;
case MORALE_RAN_AWAY:
// affects everyone to varying degrees
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive )
{
// CJC: adding to SOLDIER_IN_SECTOR check special stuff because the old sector values might
// be appropriate (because in transit going out of that sector!)
if ( SOLDIER_IN_SECTOR( pTeamSoldier, sMapX, sMapY, bMapZ ) || ( pTeamSoldier->flags.fBetweenSectors && ((pTeamSoldier->ubPrevSectorID % 16) + 1) == sMapX && ((pTeamSoldier->ubPrevSectorID / 16) + 1) == sMapY && ( pTeamSoldier->bSectorZ == bMapZ ) ) )
{
if ( gGameOptions.fNewTraitSystem )
{
// SANDRO - no penalty for pacifists to run away
if ( gMercProfiles[pTeamSoldier->ubProfile].bCharacterTrait != CHAR_TRAIT_PACIFIST )
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_RAN_AWAY );
// Double morale drop for aggressive people
if ( gMercProfiles[pTeamSoldier->ubProfile].bCharacterTrait == CHAR_TRAIT_AGGRESSIVE )
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_RAN_AWAY );
}
else
{
switch ( gMercProfiles[ pTeamSoldier->ubProfile ].bAttitude )
{
case ATT_AGGRESSIVE:
// double the penalty - these guys REALLY hate running away
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_RAN_AWAY );
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_RAN_AWAY );
break;
case ATT_COWARD:
// no penalty - cowards are perfectly happy to avoid fights!
break;
default:
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_RAN_AWAY );
break;
}
}
}
// SANDRO - Assertive people don't care about actions of others
else if ( !gGameOptions.fNewTraitSystem || gMercProfiles[pTeamSoldier->ubProfile].bCharacterTrait != CHAR_TRAIT_ASSERTIVE )
{
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_HEARD_BATTLE_LOST );
}
}
}
break;
case MORALE_TOWN_LIBERATED:
case MORALE_TOWN_LOST:
case MORALE_MINE_LIBERATED:
case MORALE_MINE_LOST:
case MORALE_SAM_SITE_LIBERATED:
case MORALE_SAM_SITE_LOST:
case MORALE_KILLED_CIVILIAN:
case MORALE_LOW_DEATHRATE:
case MORALE_HEARD_BATTLE_WON:
case MORALE_HEARD_BATTLE_LOST:
case MORALE_MONSTER_QUEEN_KILLED:
case MORALE_DEIDRANNA_KILLED:
// affects everyone, everywhere
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive )
{
if ( gGameOptions.fNewTraitSystem && bMoraleEvent != MORALE_DEIDRANNA_KILLED)
{
if ( !SOLDIER_IN_SECTOR( pTeamSoldier, sMapX, sMapY, bMapZ ) && ( gbMoraleEvent[bMoraleEvent].bChange > 0 ) &&
gMercProfiles[pTeamSoldier->ubProfile].bCharacterTrait == CHAR_TRAIT_ASSERTIVE )
{
// No morale gain for assertive people from actions of others
}
else
{
HandleMoraleEventForSoldier( pTeamSoldier, bMoraleEvent );
}
}
else
{
HandleMoraleEventForSoldier( pTeamSoldier, bMoraleEvent );
}
}
}
break;
case MORALE_POOR_MORALE:
case MORALE_GREAT_MORALE:
case MORALE_AIRSTRIKE:
// affects every in sector
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive && SOLDIER_IN_SECTOR( pTeamSoldier, sMapX, sMapY, bMapZ ) )
{
HandleMoraleEventForSoldier( pTeamSoldier, bMoraleEvent );
}
}
break;
case MORALE_MERC_CAPTURED:
// needs specific soldier! (for reputation, not here)
Assert( pSoldier );
// affects everyone
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive )
{
HandleMoraleEventForSoldier( pTeamSoldier, bMoraleEvent );
}
}
break;
case MORALE_TEAMMATE_DIED:
// needs specific soldier!
Assert( pSoldier );
// affects everyone, in sector differently than not, extra bonuses if it's a buddy or hated merc
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive && pTeamSoldier->ubProfile != NO_PROFILE)
{
pProfile = &(gMercProfiles[ pTeamSoldier->ubProfile ]);
if (HATED_MERC( pProfile, pSoldier->ubProfile ))
{
// yesss!
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_HATED_DIED );
}
else
{
if ( SOLDIER_IN_SECTOR( pTeamSoldier, sMapX, sMapY, bMapZ ) )
{
// mate died in my sector! tactical morale mod
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_SQUADMATE_DIED );
// SANDRO - Squadleaders death cost a lot of morale
if( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SQUADLEADER_NT ))
{
for ( UINT8 i = 0; i < (gSkillTraitValues.ubSLDeathMoralelossMultiplier * NUM_SKILL_TRAITS( pSoldier, SQUADLEADER_NT )); i++ )
{
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_SQUADMATE_DIED );
}
}
}
// this is handled for everyone even if in sector, as it's a strategic morale mod
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_TEAMMATE_DIED );
// SANDRO - Squadleaders death cost a lot of morale
if( gGameOptions.fNewTraitSystem && (NUM_SKILL_TRAITS( pSoldier, SQUADLEADER_NT ) > 1))
{
for ( UINT8 i = 0; i < gSkillTraitValues.ubSLDeathMoralelossMultiplier; i++ )
{
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_SQUADMATE_DIED );
}
}
if (BUDDY_MERC( pProfile, pSoldier->ubProfile ))
{
// oh no! buddy died!
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_BUDDY_DIED );
}
}
}
}
break;
case MORALE_MERC_MARRIED:
// female mercs get unhappy based on how sexist they are (=hate men)
// gentlemen males get unhappy too
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive && pTeamSoldier->ubProfile != NO_PROFILE )
{
if ( WhichHated( pTeamSoldier->ubProfile, pSoldier->ubProfile ) != -1 )
{
// we hate 'em anyways
continue;
}
if ( gMercProfiles[ pTeamSoldier->ubProfile ].bSex == FEMALE )
{
switch( gMercProfiles[ pTeamSoldier->ubProfile ].bSexist )
{
case SOMEWHAT_SEXIST:
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_MERC_MARRIED );
break;
case VERY_SEXIST:
// handle TWICE!
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_MERC_MARRIED );
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_MERC_MARRIED );
break;
default:
break;
}
}
else
{
switch( gMercProfiles[ pTeamSoldier->ubProfile ].bSexist )
{
case GENTLEMAN:
HandleMoraleEventForSoldier( pTeamSoldier, MORALE_MERC_MARRIED );
break;
default:
break;
}
}
}
}
break;
// added by SANDRO
case MORALE_PSYCHO_UNABLE_TO_PSYCHO:
case MORALE_PACIFIST_GAIN_NONCOMBAT: // added by SANDRO
case MORALE_MALICIOUS_HIT: // added by SANDRO
Assert( pSoldier );
HandleMoraleEventForSoldier( pSoldier, bMoraleEvent );
break;
default:
// debug message
ScreenMsg( MSG_FONT_RED, MSG_BETAVERSION, L"Invalid morale event type = %d. AM/CC-1", bMoraleEvent );
break;
}
// some morale events also impact the player's reputation with the mercs back home
switch( bMoraleEvent )
{
case MORALE_HIGH_DEATHRATE:
ModifyPlayerReputation(REPUTATION_HIGH_DEATHRATE);
break;
case MORALE_LOW_DEATHRATE:
ModifyPlayerReputation(REPUTATION_LOW_DEATHRATE);
break;
case MORALE_POOR_MORALE:
ModifyPlayerReputation(REPUTATION_POOR_MORALE);
break;
case MORALE_GREAT_MORALE:
ModifyPlayerReputation(REPUTATION_GREAT_MORALE);
break;
case MORALE_BATTLE_WON:
ModifyPlayerReputation(REPUTATION_BATTLE_WON);
break;
case MORALE_RAN_AWAY:
case MORALE_HEARD_BATTLE_LOST:
ModifyPlayerReputation(REPUTATION_BATTLE_LOST);
break;
case MORALE_TOWN_LIBERATED:
ModifyPlayerReputation(REPUTATION_TOWN_WON);
break;
case MORALE_TOWN_LOST:
ModifyPlayerReputation(REPUTATION_TOWN_LOST);
break;
case MORALE_TEAMMATE_DIED:
// impact depends on that dude's level of experience
ModifyPlayerReputation((UINT8) (pSoldier->stats.bExpLevel * REPUTATION_SOLDIER_DIED));
break;
case MORALE_MERC_CAPTURED:
// impact depends on that dude's level of experience
ModifyPlayerReputation((UINT8) (pSoldier->stats.bExpLevel * REPUTATION_SOLDIER_CAPTURED));
break;
case MORALE_KILLED_CIVILIAN:
ModifyPlayerReputation(REPUTATION_KILLED_CIVILIAN);
break;
case MORALE_MONSTER_QUEEN_KILLED:
ModifyPlayerReputation(REPUTATION_KILLED_MONSTER_QUEEN);
break;
case MORALE_DEIDRANNA_KILLED:
ModifyPlayerReputation(REPUTATION_KILLED_DEIDRANNA);
break;
default:
// no reputation impact
break;
}
}
void HourlyMoraleUpdate( void )
{
INT8 bMercID, bOtherID;
INT8 bActualTeamOpinion;
INT8 bTeamMoraleModChange, bTeamMoraleModDiff;
INT8 bOpinion=-1;
INT32 iTotalOpinions;
INT8 bNumTeamMembers;
INT8 bHighestTeamLeadership = 0;
INT8 bLastTeamID;
SOLDIERTYPE * pSoldier;
SOLDIERTYPE * pOtherSoldier;
MERCPROFILESTRUCT * pProfile;
BOOLEAN fSameGroupOnly;
static INT8 bStrategicMoraleUpdateCounter = 0;
BOOLEAN fFoundHated = FALSE;
INT8 bHated;
bMercID = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
bLastTeamID = gTacticalStatus.Team[ gbPlayerNum ].bLastID;
// loop through all mercs to calculate their morale
for ( pSoldier = MercPtrs[ bMercID ]; bMercID <= bLastTeamID; bMercID++,pSoldier++)
{
//if the merc is active, in Arulco, and conscious, not POW
if ( pSoldier->bActive && pSoldier->ubProfile != NO_PROFILE &&
!(pSoldier->bAssignment == IN_TRANSIT ||
pSoldier->flags.fMercAsleep == TRUE ||
pSoldier->bAssignment == ASSIGNMENT_DEAD ||
pSoldier->bAssignment == ASSIGNMENT_POW) )
{
// calculate the guy's opinion of the people he is with
pProfile = &(gMercProfiles[ pSoldier->ubProfile ]);
// if we're moving
if (pSoldier->ubGroupID != 0 && PlayerIDGroupInMotion( pSoldier->ubGroupID ))
{
// we only check our opinions of people in our squad
fSameGroupOnly = TRUE;
}
else
{
fSameGroupOnly = FALSE;
}
fFoundHated = FALSE;
// reset counts to calculate average opinion
iTotalOpinions = 0;
bNumTeamMembers = 0;
// let people with high leadership affect their own morale
bHighestTeamLeadership = EffectiveLeadership( pSoldier );
// loop through all other mercs
bOtherID = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pOtherSoldier = MercPtrs[ bOtherID ]; bOtherID <= bLastTeamID; bOtherID++,pOtherSoldier++)
{
// skip past ourselves and all inactive mercs
if (bOtherID != bMercID && pOtherSoldier->bActive && pOtherSoldier->ubProfile != NO_PROFILE &&
!(pOtherSoldier->bAssignment == IN_TRANSIT ||
pOtherSoldier->flags.fMercAsleep == TRUE ||
pOtherSoldier->bAssignment == ASSIGNMENT_DEAD ||
pOtherSoldier->bAssignment == ASSIGNMENT_POW))
{
if (fSameGroupOnly)
{
// all we have to check is the group ID
if (pSoldier->ubGroupID != pOtherSoldier->ubGroupID)
{
continue;
}
}
else
{
// check to see if the location is the same
if (pOtherSoldier->sSectorX != pSoldier->sSectorX ||
pOtherSoldier->sSectorY != pSoldier->sSectorY ||
pOtherSoldier->bSectorZ != pSoldier->bSectorZ)
{
continue;
}
// if the OTHER soldier is in motion then we don't do anything!
if (pOtherSoldier->ubGroupID != 0 && PlayerIDGroupInMotion( pOtherSoldier->ubGroupID ))
{
continue;
}
}
// WANNE: Fix by Headrock: Morale and the ice-cream truck.
if (OKToCheckOpinion(pOtherSoldier->ubProfile))
{
bOpinion = pProfile->bMercOpinion[ pOtherSoldier->ubProfile ];
}
else
{
bOpinion = 0;
}
if (bOpinion == HATED_OPINION)
{
bHated = WhichHated( pSoldier->ubProfile, pOtherSoldier->ubProfile );
if ( bHated >= 2 )
{
// learn to hate which has become full-blown hatred, full strength
fFoundHated = TRUE;
break;
}
else
{
// scale according to how close to we are to snapping
//KM : Divide by 0 error found. Wrapped into an if statement.
if( pProfile->bHatedTime[ bHated ] )
{
bOpinion = ((INT32) bOpinion) * (pProfile->bHatedTime[ bHated ] - pProfile->bHatedCount[ bHated ]) / pProfile->bHatedTime[ bHated ];
}
if ( pProfile->bHatedCount[ bHated ] <= pProfile->bHatedTime[ bHated ] / 2 )
{
// Augh, we're teamed with someone we hate! We HATE this!! Ignore everyone else!
fFoundHated = TRUE;
break;
}
// otherwise just mix this opinion in with everyone else...
}
}
iTotalOpinions += bOpinion;
bNumTeamMembers++;
if ( EffectiveLeadership( pOtherSoldier ) > bHighestTeamLeadership)
{
bHighestTeamLeadership = EffectiveLeadership( pOtherSoldier );
}
}
}
if (fFoundHated)
{
// If teamed with someone we hated, team opinion is automatically minimum
bActualTeamOpinion = HATED_OPINION;
}
else if (bNumTeamMembers > 0)
{
bActualTeamOpinion = (INT8) (iTotalOpinions / bNumTeamMembers);
// give bonus/penalty for highest leadership value on team
bActualTeamOpinion += (bHighestTeamLeadership - 50) / 10;
}
else // alone
{
bActualTeamOpinion = 0;
}
// reduce to a range of HATED through BUDDY
if (bActualTeamOpinion > BUDDY_OPINION)
{
bActualTeamOpinion = BUDDY_OPINION;
}
else if (bActualTeamOpinion < HATED_OPINION)
{
bActualTeamOpinion = HATED_OPINION;
}
// shift morale from team by ~10%
// this should range between -75 and +75
bTeamMoraleModDiff = bActualTeamOpinion - pSoldier->aiData.bTeamMoraleMod;
if (bTeamMoraleModDiff > 0)
{
bTeamMoraleModChange = 1 + bTeamMoraleModDiff / 10;
}
else if (bTeamMoraleModDiff < 0)
{
bTeamMoraleModChange = -1 + bTeamMoraleModDiff / 10;
}
else
{
bTeamMoraleModChange = 0;
}
// SANDRO - morale is going down faster if not fighting for malicious characters
if ( gGameOptions.fNewTraitSystem && pProfile->bCharacterTrait == CHAR_TRAIT_MALICIOUS )
{
bTeamMoraleModChange -= 1;
}
pSoldier->aiData.bTeamMoraleMod += bTeamMoraleModChange;
pSoldier->aiData.bTeamMoraleMod = __min( pSoldier->aiData.bTeamMoraleMod, MORALE_MOD_MAX );
pSoldier->aiData.bTeamMoraleMod = __max( pSoldier->aiData.bTeamMoraleMod, -MORALE_MOD_MAX );
// New, December 3rd, 1998, by CJC --
// If delayed strategic modifier exists then incorporate it in strategic mod
if ( pSoldier->bDelayedStrategicMoraleMod )
{
pSoldier->aiData.bStrategicMoraleMod += pSoldier->bDelayedStrategicMoraleMod;
pSoldier->bDelayedStrategicMoraleMod = 0;
pSoldier->aiData.bStrategicMoraleMod = __min( pSoldier->aiData.bStrategicMoraleMod, MORALE_MOD_MAX );
pSoldier->aiData.bStrategicMoraleMod = __max( pSoldier->aiData.bStrategicMoraleMod, -MORALE_MOD_MAX );
}
// refresh the morale value for the soldier based on the recalculated team modifier
RefreshSoldierMorale( pSoldier );
}
}
bStrategicMoraleUpdateCounter++;
if ( bStrategicMoraleUpdateCounter == HOURS_BETWEEN_STRATEGIC_DECAY )
{
DecayStrategicMoraleModifiers();
bStrategicMoraleUpdateCounter = 0;
}
}
void DailyMoraleUpdate(SOLDIERTYPE *pSoldier)
{
if ( pSoldier->ubProfile == NO_PROFILE )
{
return;
}
// CJC: made per hour now
/*
// decay the merc's strategic morale modifier
if (pSoldier->aiData.bStrategicMoraleMod != 0)
{
// decay the modifier!
DecayStrategicMorale( pSoldier );
// refresh the morale value for the soldier based on the recalculated modifier
RefreshSoldierMorale( pSoldier );
}
*/
// check death rate vs. merc's tolerance once/day (ignores buddies!)
if ( MercThinksDeathRateTooHigh( pSoldier->ubProfile ) )
{
// too high, morale takes a hit
HandleMoraleEvent( pSoldier, MORALE_HIGH_DEATHRATE, pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ );
}
// check his morale vs. his morale tolerance once/day (ignores buddies!)
if ( MercThinksHisMoraleIsTooLow( pSoldier ) )
{
// too low, morale sinks further (merc's in a funk and things aren't getting better)
HandleMoraleEvent( pSoldier, MORALE_POOR_MORALE, pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ );
}
else if ( pSoldier->aiData.bMorale >= 75 )
{
// very high morale, merc is cheerleading others
HandleMoraleEvent( pSoldier, MORALE_GREAT_MORALE, pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ );
}
}
// Added by SANDRO
BOOLEAN IsShowOffNearBy( SOLDIERTYPE * pSoldier )
{
UINT32 uiLoop;
SOLDIERTYPE * pTeammate;
BOOLEAN fOneException = FALSE;
BOOLEAN fYesHeIs = FALSE;
if (!pSoldier)
{
return( FALSE );
}
if( !(pSoldier->bActive) || !(pSoldier->bInSector) )
{
return( FALSE );
}
for ( uiLoop = gTacticalStatus.Team[ pSoldier->bTeam ].bFirstID; uiLoop < gTacticalStatus.Team[ pSoldier->bTeam ].bLastID; uiLoop++)
{
pTeammate = MercPtrs[ uiLoop ];
if ( pTeammate == NULL )
{
continue;
}
if ( pTeammate == pSoldier )
{
continue;
}
// Are we actually here?
if ( !(pTeammate->bActive) || !(pTeammate->bInSector) || ( pTeammate->flags.uiStatusFlags & SOLDIER_VEHICLE ) || (pTeammate->bAssignment == VEHICLE ) )
{
// is nowhere around!
continue;
}
// Are we from our team an dalive?
if ( pTeammate->bTeam == pSoldier->bTeam && pTeammate->stats.bLife >= OKLIFE &&
gMercProfiles[ pTeammate->ubProfile ].bCharacterTrait == CHAR_TRAIT_SHOWOFF && PythSpacesAway( pSoldier->sGridNo, pTeammate->sGridNo ) <= 15)
{
if ( (pSoldier->ubBodyType <= STOCKYMALE && pTeammate->ubBodyType <= STOCKYMALE) ||
(pSoldier->ubBodyType == REGFEMALE && pTeammate->ubBodyType == REGFEMALE) )
{
// phlegmatic character can ignore one
if ( gMercProfiles[ pSoldier->ubProfile ].bCharacterTrait == CHAR_TRAIT_PHLEGMATIC && !fOneException)
{
fOneException = TRUE;
}
else
{
fYesHeIs = TRUE;
}
}
}
}
return( fYesHeIs );
} | [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
1269
]
]
]
|
8e5b05bad9fb09c22dac270b40e02df4d4b1f588 | 789bfae90cbb728db537b24eb9ab21c88bda2786 | /source/StateClass.h | 6c9f0071e39d3e4652324fa92adec6ac89ba094c | [
"MIT"
]
| permissive | Izhido/bitsweeper | b89db2c2050cbc82ea60d31d2f31b041a1e913a3 | a37902c5b9ae9c25ee30694c2ba0974fd235090e | refs/heads/master | 2021-01-23T11:49:21.723909 | 2011-12-24T22:43:30 | 2011-12-24T22:43:30 | 34,614,275 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 321 | h | #ifndef STATECLASS_H
#define STATECLASS_H
class StateClass
{
public:
virtual void Start(class CommonDataClass* CommonData) = 0;
virtual void Run(CommonDataClass* CommonData) = 0;
virtual void Draw(CommonDataClass* CommonData) = 0;
virtual ~StateClass();
protected:
StateClass();
};
#endif
| [
"[email protected]@66f87ebb-1a6f-337b-3a26-6cadc16acdcf"
]
| [
[
[
1,
20
]
]
]
|
3a5b023ca0b96d11171f724a5dafa213af09e0f2 | d95931daeed5ed4226a5c93e110490f6f9d4030b | /include/types/list.h | ebb0884fcebfe5fb8798e73ebc6dc9d963145986 | []
| no_license | halberd-project/Poleaxe | 9ee4abcebcf153137ef2a5bedd62a2582b087243 | cf2c9036a9cef5696d843634ae9e8ad2664fdbbe | refs/heads/master | 2020-04-05T20:16:32.376607 | 2010-02-10T01:06:52 | 2010-02-10T01:06:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | h | /*
*
* The Poleaxe Graphics and Windowing system.
*
* Jeff Shoulders and Robert Butler
* hx86 working group
* [email protected]
* [email protected]
*
* (c) 2010
*
*/
#ifndef __POL_LIST__
#define __POL_LIST__
#include "../../poleaxe.h"
class list //: public object //for later...
{
//protected:
public:
node *base, *i, *end; //pointers to the start of the nodes, the iterator (i), and the end of the nodes.
int num_nodes;
//public:
list();
virtual ~list();
virtual bool AddNode(Node *_node);
virtual bool DeleteNode();
virtual int NumberOfNodes();
virtual void Clear();
virtual bool Empty();
virtual node *Iterator();
virtual node *Base();
virtual node *End();
};
#endif //__POL_LIST__
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
a84e1d1ca2114a5314c4e61701cf89090a2b868e | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/ptr_container/test/ptr_map_adapter.cpp | 033379ddd0213b4050f47fd546fd2238bae2987f | [
"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,716 | cpp | //
// Boost.Pointer Container
//
// Copyright Thorsten Ottosen 2003-2005. 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)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//
#include <boost/ptr_container/ptr_map.hpp>
#include <string>
using namespace std;
int test_main( int, char*[] )
{
typedef_test< ptr_map<int, Base>, Derived >();
typedef_test< ptr_map<int, Value>, Value >();
associative_container_test< ptr_map<int, Base>, Base, Derived >();
associative_container_test< ptr_map<int, Value>, Value, Value >();
typedef_test< ptr_multimap<int, Base>, Derived >();
typedef_test< ptr_multimap<int, Value>, Value >();
associative_container_test< ptr_multimap<int, Base>, Base, Derived >();
associative_container_test< ptr_multimap<int, Value>, Value, Value >();
string joe = "joe";
string brian = "brian";
ptr_map<string,int> m;
m.insert( joe, new int( 4 ) );
m.insert( brian, std::auto_ptr<int>( new int( 6 ) ) );
m[ joe ] += 56;
m[ brian ] += 10;
try
{
m[ "hans" ] = 4;
}
catch( const bad_ptr_container_operation& )
{ }
return 0;
}
#include <boost/test/included/unit_test_framework.hpp>
using boost::unit_test_framework::test_suite;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" );
test->add( BOOST_TEST_CASE( &test_container_adapter ) );
return test;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
67
]
]
]
|
712d61cb0999780a60b35fcd6da87ba37933f48f | 584d088c264ac58050ed0757b08d032b6c7fc83b | /oldGUI/Gui_ListBox.h | 3d8b170b0d1cc544485ae7f86357109e6bb6e0bd | []
| no_license | littlewingsoft/lunaproject | a843ca37c04bdc4e1e4e706381043def1789ab39 | 9102a39deaad74b2d73ee0ec3354f37f6f85702f | refs/heads/master | 2020-05-30T15:21:20.515967 | 2011-02-04T18:41:43 | 2011-02-04T18:41:43 | 32,302,109 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,244 | h |
#pragma once
////////////////////////////////////////
// 스크롤을 담당해주는 기본적으로 우측에 달리는 상,바,하 의 버튼역활
class CGUI_ListBox;
class CGUI_ListBox_SCROLL : public IGUI_Object
{
CGUI_Ani* m_pBack; // 한개를 로드해서 횟수만큼 포문돌아서 찍어요.
CGUI_Button* m_pUp; // 클릭이벤트 발생시 가상 기준값을 제어함
CGUI_Button* m_pBar; // 가상 기준값에 따라 현재 위치를 정하기도 하고 가상기준값을 변경하기도함.
CGUI_Button* m_pDn; // 클릭 이벤트 발생시 가상 기준값을 제어함
DWORD m_PointPos; // 0~100 까지의 가상기준값 스크롤 뷰와 바에 모두 적용될 기준입니다.
float _localx; // 직계 부모와 나의 상대적 위치
float _localy; // 직계 부모와 나의 상대적 위치
bool _IsDown;
public:
DECL_CREATE( CGUI_ListBox_SCROLL );
CGUI_ListBox_SCROLL();
CGUI_ListBox_SCROLL(CGUI_ListBox* pObj);
~CGUI_ListBox_SCROLL();
void HEAD();
void OnUP();
void OnDown();
void TAIL();
void Process();
void Render();
bool ProcMessage(GUIMSG& pMsg);
};
////////////////////////////////////////
// 리스트에 Contents 추가
// 실제 영역은 컨텐츠가 하나도 없을땐 0
// 계속 추가될때마다 + 컨텐츠 크기
// 추가된 컨텐츠 만큼 실제 사각형에 크기가 더 추가됨
class CGUI_ListBox : public IGUI_Object
{
CGUI_ListBox_SCROLL* m_pScroll;
std::string _ScrollName;
int m_LastScrollPos;
RECT m_ContentsRect; // 리스트박스 내에서 콘테츠들이 화면에 보이는 영역, 클리핑시쓰임..*/
int m_FocusIndex;
float m_Interval_ToHEAD;
float m_Interval_ToTAIL;
float m_Interval_ToBODY;
std::string m_UpButtonImgFileName;
std::string m_DnButtonImgFileName;
public:
DECL_CREATE(CGUI_ListBox )
void SetScrollName(const char* szName){ _ScrollName= szName;}
void SetFocusContentsIndex(int Index ); // 현재 선택된것의 인덱스를 반환한다.
int GetFocusContentsIndex( void ); // 현재 선택된것의 인덱스를 반환한다.
// 바운드박스를 셋팅해주면 한라인의 크기와..
void SetLineCnt( UINT LineCnt = 32 ); // 현재 정해준대로 컨텐츠 버퍼가 생성됩니다.
void AddString( TCHAR *szStr,DWORD OutClr,DWORD FontClr,bool bFocusString = false); // 스트링 잘라 붙이기 추가
void AddContents( IGUI_Object* pObj ); // 외부에서 추가할때는 이것으로 추가함
void RemoveAllContents(void);
void HEAD();
void TAIL();
CGUI_ListBox();
~CGUI_ListBox();
void Process();
void Render();
bool ProcMessage(GUIMSG& pMsg);
// 리스트 박스와 스크롤바의 위치를 지정해줄 메소드가 필요함.
// 아래는 스크롤 바가 상하좌우중 우에 붙었을때를 가정함
// 모든값은 + 일수록 리스트 박스와 멀어짐
// 수치는 상대적이다.현재 리스트 박스의 위치에서 상대적인 값임.
// 수치의 종류는 세가지.
// 1. 리스트 박스 와 스크롤바의 몸통의 거리
// 2. 스크롤 바의 몸통은 기본적으로 리스트 박스의 가로(or 세로) 폭과 길이가 같으며
// 헤드 테일 버튼을 각각 뺀만큼이다 .
// 헤드와 테일을
// 스크롤 바가 생성될때만 아래 메소드를 쓴다.
// 스크롤 바가 생성되고 나면 더이상 필요가 없음.
const char* GetUPButtonImgFileName(void){return m_UpButtonImgFileName.c_str(); }
const char* GetDNButtonImgFileName(void){return m_DnButtonImgFileName.c_str(); }
void SetUPButtonImgFileName(const char* fName=_T("data\\IMG\\GUI\\Scroll_Up.ani"))
{ if(strlen(fName)<=0)return; m_UpButtonImgFileName = fName; }
void SetDNButtonImgFileName(const char* fName=_T("data\\IMG\\GUI\\Scroll_Dn.ani"))
{ if(strlen(fName)<=0)return; m_DnButtonImgFileName = fName; }
void SetInterval_ToHEAD( float Interval =0.0f );
void SetInterval_ToTAIL( float Interval =0.0f );
void SetInterval_ToBODY( float Interval =0.0f );
void GetInterval_ToHEAD( float& Interval );
void GetInterval_ToTAIL( float& Interval );
void GetInterval_ToBODY( float& Interval );
};
| [
"jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9"
]
| [
[
[
1,
101
]
]
]
|
8c7c5b59222e78f787e64b75c3a75424535fb75f | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/level/bounds/AABBBounds.cpp | 446bf9ed21fca06c82fb6dce42b5e6aca3316cb5 | []
| no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,858 | cpp | /***
* hesperus: AABBBounds.cpp
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#include "AABBBounds.h"
#include <source/ogl/WrappedGL.h>
#include <source/math/geom/GeomUtil.h>
namespace hesp {
//#################### CONSTRUCTORS ####################
AABBBounds::AABBBounds(const Vector3d& scale)
: m_scale(scale)
{}
//#################### PUBLIC METHODS ####################
double AABBBounds::brush_expansion_distance(const Vector3d& n) const
{
Vector3d v = support_point(-n);
// v . -n = |v| cos theta (see p.26 of J.M.P. van Waveren's thesis on the Q3 bot for a diagram)
return v.dot(-n);
}
boost::optional<std::pair<Vector3d,Vector3d> > AABBBounds::determine_halfray_intersection(const Vector3d& s, const Vector3d& v) const
{
AABB3d aabb(-m_scale, m_scale);
return determine_halfray_intersection_with_shape(s, v, aabb);
}
Vector3d AABBBounds::half_dimensions() const
{
return m_scale;
}
double AABBBounds::height() const
{
return m_scale.z * 2;
}
void AABBBounds::render(const Vector3d& pos) const
{
Vector3d mins = pos - m_scale, maxs = pos + m_scale;
glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_CULL_FACE);
glColor3d(1,1,0);
glBegin(GL_QUADS);
// Front
glVertex3d(mins.x, mins.y, mins.z);
glVertex3d(maxs.x, mins.y, mins.z);
glVertex3d(maxs.x, mins.y, maxs.z);
glVertex3d(mins.x, mins.y, maxs.z);
// Right
glVertex3d(maxs.x, mins.y, mins.z);
glVertex3d(maxs.x, maxs.y, mins.z);
glVertex3d(maxs.x, maxs.y, maxs.z);
glVertex3d(maxs.x, mins.y, maxs.z);
// Back
glVertex3d(maxs.x, maxs.y, mins.z);
glVertex3d(mins.x, maxs.y, mins.z);
glVertex3d(mins.x, maxs.y, maxs.z);
glVertex3d(maxs.x, maxs.y, maxs.z);
// Left
glVertex3d(mins.x, maxs.y, mins.z);
glVertex3d(mins.x, mins.y, mins.z);
glVertex3d(mins.x, mins.y, maxs.z);
glVertex3d(mins.x, maxs.y, maxs.z);
glEnd();
glPopAttrib();
}
Vector3d AABBBounds::support_point(const Vector3d& n) const
{
double sx = m_scale.x, sy = m_scale.y, sz = m_scale.z;
int xCode = n.x > 0 ? 4 : 0;
int yCode = n.y > 0 ? 2 : 0;
int zCode = n.z > 0 ? 1 : 0;
int fullCode = xCode + yCode + zCode;
Vector3d v;
switch(fullCode)
{
case 0: v = Vector3d(-sx, -sy, -sz); break; // n: x-, y-, z-
case 1: v = Vector3d(-sx, -sy, sz); break; // n: x-, y-, z+
case 2: v = Vector3d(-sx, sy, -sz); break; // n: x-, y+, z-
case 3: v = Vector3d(-sx, sy, sz); break; // n: x-, y+, z+
case 4: v = Vector3d(sx, -sy, -sz); break; // n: x+, y-, z-
case 5: v = Vector3d(sx, -sy, sz); break; // n: x+, y-, z+
case 6: v = Vector3d(sx, sy, -sz); break; // n: x+, y+, z-
default: v = Vector3d(sx, sy, sz); break; // n: x+, y+, z+ (case 7)
}
return v;
}
}
| [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
8172ab57b2bb77c142b835b7cd48e091cbfb71bd | 314fa4d6839de9abfdedb72a521a156c06522761 | /Torso/include/Nurbs.cpp | 7c5fbeb5028b163c392f01dd3d31b286fc84872d | []
| no_license | moonjuice/moonjuice | 7b87f5a36cc696dc232cb8257e91aa60a0b5cca8 | 262bbf8e3e487191160566adf0f28771bccb375e | refs/heads/master | 2021-01-10T20:33:50.474152 | 2011-11-24T00:52:29 | 2011-11-24T00:52:29 | 32,118,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,408 | cpp | #include "StdAfx.h"
#include <Nurbs.h>
#include <cmath>
#include <fstream>
#include <string>
#include <CubicSolver.h>
using std::string;
IMPLEMENT_SERIAL(CNurbs, CObject, 1)
CNurbs::CNurbs(void): m_bUClosed(false), m_bVClosed(false)
{
m_Diffuse[0] = m_Diffuse[1] = m_Diffuse[2] = m_Diffuse[3] = 1.0;
}
CNurbs::~CNurbs(void)
{}
void CNurbs::Clear()
{
m_CtrlPts.clear();
m_uDirection = CBlend();
m_vDirection = CBlend();
}
CVector CNurbs::Position( double u, double v ) const
{
if ( m_CtrlPts.size() == 0 )
return CVector();
CVector Pos;
CMatrix uBasis( m_uDirection.GetOrder() );
CMatrix vBasis( m_vDirection.GetOrder() );
int uSpan = m_uDirection.BlendSlim( u, uBasis );
int vSpan = m_vDirection.BlendSlim( v, vBasis );
int k;
Pos(3) = 0;
for ( int i=0; i<m_uDirection.GetOrder(); i++ )
{
for ( int j=0; j<m_vDirection.GetOrder(); j++ )
{
Pos(0) += uBasis(i)*vBasis(j)*m_CtrlPts[i+uSpan][j+vSpan](0)*m_CtrlPts[i+uSpan][j+vSpan](3);
Pos(1) += uBasis(i)*vBasis(j)*m_CtrlPts[i+uSpan][j+vSpan](1)*m_CtrlPts[i+uSpan][j+vSpan](3);
Pos(2) += uBasis(i)*vBasis(j)*m_CtrlPts[i+uSpan][j+vSpan](2)*m_CtrlPts[i+uSpan][j+vSpan](3);
Pos(3) += uBasis(i)*vBasis(j)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
}
for ( k=0; k<4; k++ )
Pos(k) /= Pos(3);
return Pos;
}
void CNurbs::d1Position( double u, double v, CVector& Pos, CVector& uPos, CVector& vPos ) const
{
if ( m_CtrlPts.size()==0 )
return ;
Pos(0) = Pos(1) = Pos(2) = Pos(3) = 0.0;
uPos(0) = uPos(1) = uPos(2) = uPos(3) = 0.0;
vPos(0) = vPos(1) = vPos(2) = vPos(3) = 0.0;
if ( m_CtrlPts.size()==1 ) // curve
{
CMatrix uBasis( m_uDirection.GetOrder() ), vBasis(2,m_vDirection.GetOrder());
int uSpan = m_uDirection.BlendSlim( u, uBasis );
int vSpan = m_vDirection.dBlendSlim( v, 1, vBasis );
int k=0;
for ( int i=0; i<m_uDirection.GetOrder(); i++ )
{
for ( int j=0; j<m_vDirection.GetOrder(); j++ )
{
for ( k=0; k<3;k++ )
{
Pos(k) += uBasis(i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(k) += uBasis(i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
Pos(3) += uBasis(i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(3) += uBasis(i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
}
for ( k=0; k<3; k++ )
vPos(k) = vPos(k)*Pos(3) - Pos(k)*vPos(3);
for ( k=0; k<4;k++ )
{
if ( Pos(3) != 0.0 )
{
uPos(k) /= Pos(3)*Pos(3);
vPos(k) /= Pos(3)*Pos(3);
Pos(k) /= Pos(3);
}
else
Pos(k) = uPos(k) = vPos(k) = 0;
}
Pos(3) = uPos(3) = vPos(3) = 1.0;
}
else // surface
{
CMatrix uBasis(2,m_uDirection.GetOrder()), vBasis(2,m_vDirection.GetOrder());
int uSpan = m_uDirection.dBlendSlim( u, 1, uBasis );
int vSpan = m_vDirection.dBlendSlim( v, 1, vBasis );
int k=0;
for ( int i=0; i<m_uDirection.GetOrder(); i++ )
{
for ( int j=0; j<m_vDirection.GetOrder(); j++ )
{
for ( k=0; k<3;k++ )
{
Pos(k) += uBasis(0,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
uPos(k) += uBasis(1,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(k) += uBasis(0,i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
Pos(3) += uBasis(0,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
uPos(3) += uBasis(1,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(3) += uBasis(0,i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
}
for ( k=0; k<3; k++ )
{
uPos(k) = uPos(k)*Pos(3) - Pos(k)*uPos(3);
vPos(k) = vPos(k)*Pos(3) - Pos(k)*vPos(3);
}
for ( k=0; k<4;k++ )
{
if ( Pos(3) != 0.0 )
{
Pos(k) /= Pos(3);
uPos(k) /= Pos(3)*Pos(3);
vPos(k) /= Pos(3)*Pos(3);
}
else
Pos(k) = uPos(k) = vPos(k) = 0;
}
Pos(3) = uPos(3) = vPos(3) = 1.0;
}
}
void CNurbs::d2Position( double u, double v, CVector& Pos, CVector& uPos, CVector& vPos, CVector& uuPos, CVector& uvPos, CVector& vvPos ) const
{
if ( m_CtrlPts.size() == 0 )
return ;
CMatrix uBasis(3,m_uDirection.GetOrder()), vBasis(3,m_vDirection.GetOrder());
int uSpan = m_uDirection.dBlendSlim( u, 2, uBasis );
int vSpan = m_vDirection.dBlendSlim( v, 2, vBasis );
Pos(0) = uPos(0) = vPos(0) = uuPos(0) = uvPos(0) = vvPos(0) = 0.0;
Pos(1) = uPos(1) = vPos(1) = uuPos(1) = uvPos(1) = vvPos(1) = 0.0;
Pos(2) = uPos(2) = vPos(2) = uuPos(2) = uvPos(2) = vvPos(2) = 0.0;
Pos(3) = uPos(3) = vPos(3) = uuPos(3) = uvPos(3) = vvPos(3) = 0.0;
int k;
for ( int i=0; i<m_uDirection.GetOrder(); i++ )
{
for ( int j=0; j<m_vDirection.GetOrder(); j++ )
{
for ( k=0; k<3; k++ )
{
Pos(k) += uBasis(0,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
uPos(k) += uBasis(1,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(k) += uBasis(0,i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
uuPos(k) += uBasis(2,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
uvPos(k) += uBasis(1,i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
vvPos(k) += uBasis(0,i)*vBasis(2,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
Pos(3) += uBasis(0,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
uPos(3) += uBasis(1,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(3) += uBasis(0,i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
uuPos(3) += uBasis(2,i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
uvPos(3) += uBasis(1,i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
vvPos(3) += uBasis(0,i)*vBasis(2,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
}
for ( k=0; k<3; k++ )
{
uuPos(k) = uuPos(k)*Pos(3)*Pos(3) - ( 2*uPos(k)*uPos(3) + Pos(k)*uuPos(3) )*Pos(3) + 2.0*uPos(k)*uPos(3)*uPos(3);
uvPos(k) = uvPos(k)*Pos(3)*Pos(3) - ( vPos(k)*uPos(3) + uPos(k)*vPos(3) + Pos(k)*uvPos(3) )*Pos(3) + 2.0*Pos(k)*uPos(3)*vPos(3);
vvPos(k) = vvPos(k)*Pos(3)*Pos(3) - ( 2*vPos(k)*vPos(3) + Pos(k)*vvPos(3) )*Pos(3) + 2.0*vPos(k)*vPos(3)*vPos(3);
uPos(k) = uPos(k)*Pos(3) - Pos(k)*uPos(3);
vPos(k) = vPos(k)*Pos(3) - Pos(k)*vPos(3);
}
for ( k=0; k<4;k++ )
{
if ( Pos(3) != 0.0 )
{
Pos(k) /= Pos(3);
uPos(k) /= Pos(3)*Pos(3);
vPos(k) /= Pos(3)*Pos(3);
uuPos(k) /= pow( Pos(3), 3 );
uvPos(k) /= pow( Pos(3), 3 );
vvPos(k) /= pow( Pos(3), 3 );
}
else
{
Pos(k) = 0;
uPos(k) = 0;
vPos(k) = 0;
uuPos(k) = 0;
uvPos(k) = 0;
vvPos(k) = 0;
}
}
Pos(3) = uPos(3) = vPos(3) = uuPos(3) = uvPos(3) = vvPos(3) = 1.0;
}
double CNurbs::Distance( const CVector& pos, double& u, double& v ) const
{
double Dist = 1e10;
if ( m_CtrlPts.size() < 1 )
return 1.;
int Res = 50;
if ( m_CtrlPts.size() > 1 )
{
double MinU, MinV;
CVector P;
for ( int i=0; i<=Res; i++ )
{
for ( int j=0; j<=Res; j++ )
{
P = Position( i/float(Res), j/float(Res) );
if ( Dist > Mag( P-pos ) )
{
Dist = Mag( P-pos );
MinU = i/float(Res);
MinV = j/float(Res);
}
}
}
u = MinU;
v = MinV;
return 1.;
double Product;
do
{
CMatrix A(2,2), dX(2);
CVector P, vP, vvP, uP, uuP, uvP;
d2Position( u, v, P, uP, vP, uuP, uvP, vvP );
dX(0) = (pos-P)*uP; A(0,0) = -uP*uP + (pos-P)*uuP; A(0,1) = -vP*uP + (pos-P)*uvP;
dX(1) = (pos-P)*vP; A(1,0) = -uP*vP + (pos-P)*uvP; A(1,1) = -vP*vP + (pos-P)*vvP;
Product = fabs( dX(0) ) + fabs( dX(1) );
dX = Inv(A)*dX;
if ( m_bUClosed )
{
u -= dX(0);
if ( u >= 1.0 )
u -= 1.0;
else if ( u<0 )
u += 1.0;
}
else
{
if ( u-dX(0) >= 1.0 )
{
if ( u == 1.0-1e-6 )
break;
else
u = 1.0-1e-6;
}
else if ( u-dX(0)<0.0 )
{
if ( u == 0.0 )
break;
else
u = 0.0;
}
else
u -= dX(0);
}
if ( m_bVClosed )
{
v -= dX(1);
if ( v >= 1.0 )
v -= 1.0;
else if ( v<0 )
v += 1.0;
}
else
{
if ( v-dX(1) >= 1.0 )
{
if ( v == 1.0-1e-6 )
break;
else
v = 1.0-1e-6;
}
else if ( v-dX(1)<0.0 )
{
if ( v == 0.0 )
break;
else
v = 0.0;
}
else
v -= dX(1);
}
} while ( fabs( Product ) > 1e-6 );
}
else // Curve
{
u = 0.0;
CVector P;
double MinV;
for ( int i=0; i<20; i++ )
{
P = Position( 0, i/20.0 );
if ( Dist > Mag( P-pos ) )
{
Dist = Mag( P-pos );
MinV = i/20.0;
}
}
v = MinV;
// Newton method
double Product;
do
{
double A;
CVector P, dP, ddP, uP, uuP, uvP;
d2Position( u, v, P, uP, dP, uuP, uvP, ddP );
Product = (pos - P)*dP;
A = -dP*dP + (pos - P)*ddP;
Dist = Mag( pos - P );
double DeltaV;
if ( A!= 0.0 )
{
DeltaV =-Product/A;
}
if ( m_bVClosed )
{
v += DeltaV;
if ( v >= 1.0 )
v -= 1.0;
else if ( v<0 )
v += 1.0;
}
else
{
if ( v+DeltaV >= 1.0 )
{
if ( v == 1.0-1e-6 )
break;
else
v = 1.0-1e-6;
}
else if ( v+DeltaV<0.0 )
{
if ( v == 0.0 )
break;
else
v = 0.0;
}
else
v += DeltaV;
}
} while ( fabs( Product ) > 1e-6 );//( Upper-Lower> 0.001 );
}
return Dist;
}
float CNurbs::LineApproximate( size_t n, int nOpen, vector<CVector>& pData, vector<double>* pParam/*=NULL*/,
double Eps /*= 1.*/, bool bCull /*= false*/, int nRepeat/*=100000*/ )
{
{
m_uDirection.SetCtrlPts(1);
m_uDirection.SetOrder(1);
double uKnots[2] = {0.,1.};
m_uDirection.SetKnot( uKnots );
}
m_CtrlPts.resize( 1 );
m_bUClosed = false;
m_bVClosed =!nOpen;
return LocalAppro( n, nOpen, pData, m_CtrlPts[0], m_vDirection, pParam, Eps, bCull, nRepeat );
}
#ifdef _DEBUG
CDumpContext& operator<<( CDumpContext& dump, const std::vector<double>& V1 )
{
dump << "size = " << V1.size() << "\n";
for ( int i=0; i<V1.size(); i++ )
dump << V1[i] << ", " ;
return dump;
}
#endif
float CNurbs::LocalAppro( size_t n, int nOpen, vector<CVector>& pData, vector<CVector>& CtrlPts, CBlend& Blend,
vector<double>* pParam, double Eps /*= 1.*/, bool bCull /*= false*/, int nRepeat/*=100000*/ )
{
float Dist = 1e10;
if ( pData.size() < n )
n = pData.size();
bool bNew = true;
if ( pParam!=NULL )
bNew = false;
double StdDev = 0;
int CC = 1;
if ( nOpen==0 )
{
vector<bool> bActive;
vector<double> Param, fError;
if ( pParam==NULL )
{
pParam = &Param;
Param.resize( pData.size()+1 );
}
fError.resize( pData.size()+1 );
bActive.resize( pData.size()+1 );
double Len = 0;
int nActive = 0;
double MaxErr =-1e10;
int nCount = 0;
//int i;
for ( size_t i=0; i<pData.size()+1; i++ )
{
bActive[i] = true;
}
float Error=0.0;
CtrlPts.resize( n+3 );
Blend = CBlend();
Blend.SetCtrlPts( n+3 );
Blend.SetOrder( 4 );
vector<double> pKnots;
pKnots.resize(n+3+4);
double dStep = 1.0/(n+3.-(4-1.));
for ( size_t i=4-1; i<=n+3; i++ )
{
pKnots[i] = (i-(4-1))*dStep;
}
for ( int i=1; i<4; i++ )
{
pKnots[ 3-i ] =-i*dStep;
pKnots[ n+3+i ] = pKnots[n+3] + i*dStep;
}
Blend.SetKnot( pKnots );
bool bChanged;
bool bHead, bTail;
double LastError = 1e10;
do
{
bHead = bTail = false;
bChanged = false;
MaxErr =-1e10;
CVector Last;
Len = 0;
CVector First;
size_t i;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] )
{
First = pData[i];
Last = pData[i];
if ( bNew )
Param[i] = 0;
break;
}
}
for ( i+=1; i<pData.size()+1; i++ )
{
if ( bActive[i] && bNew )
{
double tmp;
if ( i!=pData.size() )
tmp = Mag( pData[i] - Last );
else
tmp = Mag( First - Last );
Len += tmp;
Param[i] = Len;
Last = pData[i%pData.size()];
}
}
for ( i=0; i<pData.size()+1; i++ )
{
if ( bActive[i] && bNew )
{
Param[i] /= Len;
}
}
//bNew = false;
FitCurve( n, nOpen, pData, CtrlPts, Blend, *pParam, bActive );
if ( CC>=nRepeat )
break;
CC++;
//Error=0.0;
int j=pData.size()-1;
Dist = 0;
StdDev = 0;
nActive = 0;
double K1, K2;
K1 = Blend.Knots(4-1);
K2 = Blend.Knots( Blend.GetCtrlPt() );
// for each segment calculate error, cull noise
for ( i=n+3-1/*-3-1*/; i>=4-1; i-- )
{
double u1, u2;
u1 = Blend.Knots( i );
u2 = Blend.Knots( i+1 );
Error=0.0;
StdDev = 0.0;
int nCount = 0;
int Start = j, End;
for ( ; j>=0; j-- )
{
if ( (*pParam)[j]*(K2-K1) + K1<u1 )
break;
if ( bActive[j] == false )
continue;
End = j;
double u = (*pParam)[j];
//if ( u == 1.0 )
// u = 1.0-1e-6;
double Basis[4];
int nSpan = Blend.BlendSlim( u, Basis );
CVector Pos;
for ( int k=0; k<4; k++ )
{
Pos = Pos + Basis[k]*CtrlPts[k+nSpan];
}
double err;
if ( j==pData.size() )
err = Mag( First - Pos );
else
err = Mag( pData[j] - Pos );
Error += err;
Dist += err;
fError[j] = err;
nCount++;
nActive++;
if ( err > MaxErr )
MaxErr = err;
}
//afxDump << "Count = " << nCount << "\n";
if ( nCount<=3 )
continue;
Error /= nCount;
if ( Error>Eps && i==n+3-1 ) // Last span
{
bTail = true;
bChanged = true;
}
else if ( Error>Eps && i==4-1 ) // First span
{
bHead = true;
bChanged = true;
}
else if ( Error>Eps )
{
pKnots.insert( pKnots.begin()+i+1, (u1+u2)/2.0 );
bChanged = true;
}
}
Dist /= nActive;
for ( i=0; i<pData.size()/*+1*/; i++ )
{
if ( bActive[i] == false )
continue;
StdDev += (fError[i]-Dist)*(fError[i]-Dist);
}
StdDev = sqrt( StdDev/(nActive-1) );
if ( bCull )
{
for ( int KK = 0; KK<pData.size()+1; KK++ )
{
if ( bActive[KK] == false )
continue;
if ( fError[KK] > Error+3*StdDev )
bActive[KK] = false;
}
}
if ( bChanged==false || nCount>=2/* || Dist<Eps */)
break;
if ( LastError/Dist>2 )
nCount = 0;
else
nCount++;
//if ( bChanged == true && LastError/Dist>2 )// && ZZ<T-1)
{
if ( bHead || bTail )
{
int Si = pKnots.size();
double dStep = ( pKnots[4] - pKnots[3] )/2.0;
pKnots.insert( pKnots.begin()+Si-4, -10. );
//afxDump << pKnots << "\n";
for ( int kk=0; kk<5; kk++ )
{
//pKnots[ Si-5+kk ] = pKnots[Si-5] + kk*(pKnots[pKnots.size()-1] - pKnots[Si-5])/5.0;
pKnots[ Si-4+kk ] = pKnots[ Si-5 ] + (kk+1)*dStep;
}
// add head
pKnots.insert( pKnots.begin()+4-1, 0 );
for ( int kk=0; kk<5; kk++ )
{
//pKnots[ kk ] = kk*pKnots[5]/(5.0);
pKnots[ 4-kk ] = pKnots[5] - (kk+1)*dStep;
}
//afxDump << "Add Head and Tail, " << "\t";
}
n = pKnots.size() - 3 - 4;
CtrlPts.resize( n+3 );
Blend.SetCtrlPts( n+3 );
Blend.SetKnot( pKnots );
//nCount = 0;
}
//else if ( bChange == true && nCount>=5 )
//{
// afxDump << "Ooops...\n";
// bChange = false;
//}
LastError = Dist;
} while ( bChanged );
if ( bCull )
FitCurve( Blend.GetCtrlPt()-3, nOpen, pData, CtrlPts, Blend, *pParam, bActive );
return Dist;
}
else
{
vector<double> Param, fError;
vector<bool> bActive;
int nActive = 0;
int i;
if ( pParam==NULL )
{
{
double AvgDist = 0;
for ( int i=1; i<pData.size(); i++ )
AvgDist += Mag( pData[i]-pData[i-1] );
AvgDist /= pData.size();
vector<CVector> Data;
Data.push_back( pData[0] );
for ( int k=1; k<pData.size(); k++ )
{
if ( Mag(pData[k]-pData[k-1])>=AvgDist*2 )
{
int Seg = Mag(pData[k]-pData[k-1])/AvgDist + 1;
for ( int c = 1; c<Seg; c++ )
{
CVector tmp = pData[k-1] + (pData[k]-pData[k-1])*c/Seg;
Data.push_back( tmp );
}
}
Data.push_back( pData[k] );
}
pData.clear();
pData = Data;
}
pParam = &Param;
Param.resize( pData.size() );
Param[0] = 0;
}
fError.resize( pData.size() );
bActive.resize( pData.size() );
for ( i=0; i<pData.size(); i++ )
bActive[i] = true;
double Len = 0;
float Error=0.0;
CtrlPts.resize( n );
Blend = CBlend();
Blend.SetCtrlPts( n );
Blend.SetOrder( 4 );
vector<double> pKnots;
pKnots.resize( n+4 );
for ( i=0; i<n+4; i++ )
{ //n+4 == 10 [0,0,0,0, 0.333, 0.667, 1,1,1,1]
if ( i<4 ) pKnots[i] = 0;
else if ( i>=n ) pKnots[i] = 1.0;
else pKnots[i] = (i-3.0)/(n-3.0);
}
Blend.SetKnot( pKnots );
bool bChange = false;
double LastError = 1e10;
int nCount = 0;
double Max =-1e10;
do
{
//afxDump << "LastError = " << LastError << "\n";
Max =-1e10;
bChange = false;
int nLast;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == true )
{
nLast = i;
break;
}
}
Len = 0;
if ( bNew )
Param[nLast] = 0;
for ( i=nLast+1; i<pData.size(); i++ )
{
double tmp;
if ( bActive[i] && bNew )
{
tmp = Mag( pData[i] - pData[nLast] );
Param[i] = tmp + Len;
Len += tmp;
nLast = i;
}
}
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] && bNew )
{
Param[i] /= Len;
}
}
//bNew = false;
FitCurve( n, nOpen, pData, CtrlPts, Blend, *pParam, bActive );
if ( CC>=nRepeat )
break;
CC++;
int j=pData.size()-1;
Dist = 0;
nActive = 0;
for ( i=n/*-3*/-1; i>=0; i-- )
{
double u1, u2;
u1 = Blend.Knots( i );
u2 = Blend.Knots( i+1 );
Error=0.0;
int Count = 0;
for ( ; j>=0; j-- )
{
if ((*pParam)[j]<u1)
break;
if ( bActive[j] == false )
continue;
double u = (*pParam)[j];///Len;
//if ( u == 1.0 )
// u = 1.0-1e-6;
double Basis[4];
int nSpan = Blend.BlendSlim( u, Basis );
CVector Pos;
for ( int k=0; k<4; k++ )
{
Pos = Pos + Basis[k]*CtrlPts[k+nSpan];
}
double err = Mag( pData[j] - Pos );
Error += err;
Dist += err;
fError[j] = err;
Count++;
nActive++;
if ( err > Max )
Max = err;
}
if ( Count<=3 )
continue;
Error /= Count;
if ( Error>Eps )
{
n += 1;
pKnots.insert( pKnots.begin()+i+1, (u1+u2)/2.0 );
bChange = true;
}
}
Dist /= nActive;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
StdDev += (fError[i]-Dist)*(fError[i]-Dist);
}
StdDev = sqrt( StdDev/(nActive-1) );
if ( bCull )
{
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
if ( fError[i] > Dist+3*StdDev )
bActive[i] = false;
}
}
if ( bChange==false || nCount>=2 || Dist<Eps )
break;
if ( LastError/Dist>2 )
nCount = 0;
else
nCount++;
//if ( bChange == true && LastError/Dist>2 )
{
CtrlPts.resize( n );
Blend.SetCtrlPts( n );
Blend.SetKnot( pKnots );
//nCount = 0;
}
//else if ( bChange == true && nCount<=5 )
//{
// CtrlPts.resize( n );
// Blend.SetCtrlPts( n );
// Blend.SetKnot( pKnots );
// nCount++;
//}
//else if ( bChange == true && nCount>=5 )
//{
// afxDump << "Ooops...\n";
// bChange = false;
//}
//afxDump << "Dist = " << Dist << "\n";
LastError = Dist;
} while ( bChange );
if ( bCull )
FitCurve( Blend.GetCtrlPt(), nOpen, pData, CtrlPts, Blend, *pParam, bActive );
return Dist;
}
}
void CNurbs::Draw( CDC* pDC, int T, CSize& size )
{
if ( m_CtrlPts.size() == 0 )
return;
CBrush Red( RGB(255,0,0) );
pDC->SelectObject( &Red );
CPen Green( PS_SOLID, 1, RGB(0,255,0) ), RenPen( PS_SOLID, 1, RGB(255,0,0) ), *pOriginal;
pOriginal = pDC->SelectObject( &Green );
pDC->SelectObject( pOriginal );
for ( int j=0; j<=200; j++ )
{
CVector tmp = Position(0,j/200.0);
if ( j==0 )
pDC->MoveTo( size.cx+tmp(0), size.cy-tmp(1) );
else
pDC->LineTo( size.cx+tmp(0), size.cy-tmp(1) );
}
pDC->SetBkMode( TRANSPARENT );
pDC->SetTextAlign( TA_CENTER|TA_BASELINE );
return;
int j;
for ( int i=3; i<m_vDirection.m_Knot.size()-3; i++ )
{
CVector tmp, uTmp, vTmp;
d1Position( 0, m_vDirection.m_Knot[i], tmp, uTmp, vTmp );
pDC->SelectObject( &Green );
vTmp = Normalize( vTmp );
pDC->MoveTo( size.cx+(tmp(0)/*-vTmp(0)*/), size.cy-(tmp(1)/*-vTmp(1)*/) );
pDC->LineTo( size.cx+(tmp(0)+vTmp(0)*20), size.cy-(tmp(1)+vTmp(1)*20) );
pDC->SelectObject( &RenPen );
pDC->MoveTo( size.cx+(tmp(0)-vTmp(1)*10), size.cy-(tmp(1)+vTmp(0)*10) );
pDC->LineTo( size.cx+(tmp(0)+vTmp(1)*10), size.cy-(tmp(1)-vTmp(0)*10) );
}
for ( j=0; j<m_vDirection.GetCtrlPt(); j++ )
{
CBrush Green( RGB(0,255,255) );
pDC->SelectObject( &Green );
pDC->Ellipse( size.cx+m_CtrlPts[0][j](0)-4, size.cy - (m_CtrlPts[0][j](1)-4),
size.cx+m_CtrlPts[0][j](0)+4, size.cy - (m_CtrlPts[0][j](1)+4) );
CString msg;
msg.Format( "%d", j );
pDC->TextOutA( size.cx+m_CtrlPts[0][j](0), size.cy - m_CtrlPts[0][j](1), msg );
}
CVector P, uP, vP;
d1Position( 0, T/100.0, P, uP, vP );
int iSpan = m_vDirection.GetSpan( T/100.0 );
pDC->MoveTo( size.cx+P(0), size.cy - P(1) );
pDC->LineTo( size.cx+P(0)+vP(0)/5, size.cy - (P(1)+vP(1)/5) );
pDC->Ellipse( size.cx+P(0)-2, size.cy - (P(1)-2), size.cx+P(0)+2, size.cy - (P(1)+2) );
}
float CNurbs::FitCurve( int n, int nOpen, vector<CVector>& pData, vector<CVector>& CtrlPts, CBlend& Blend,
vector<double>& uParam, vector<bool>& bActive )
{
double *pKnots = new double[ CtrlPts.size() ];
if ( nOpen==false )
{
int nFirst;
unsigned int i;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == true )
{
nFirst = i;
break;
}
}
CMatrix A(n,n), X(n), Y(n), Z(n);
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
CVector Sample;
double u = uParam[i%pData.size()];//uParam[ uParam.size()-1 ];
if ( i == pData.size() )
{
u = 1.0;
Sample = pData[nFirst];
}
else
{
u = uParam[i];
Sample = pData[i];
}
Blend.Blend( u, pKnots );
for ( int j=0; j<n; j++ )
{
double Nj;
if ( j==0 )
Nj = pKnots[j]+pKnots[n];
else if ( j==1 )
Nj = pKnots[j]+pKnots[n+1];
else if ( j==2 )
Nj = pKnots[j]+pKnots[n+2];
else
Nj = pKnots[j];
for ( int k=0; k<n; k++ )
{
double Nk;
if ( k==0 )
Nk = pKnots[0]+pKnots[n];
else if ( k==1 )
Nk = pKnots[1]+pKnots[n+1];
else if ( k==2 )
Nk = pKnots[2]+pKnots[n+2];
else
Nk = pKnots[k];
A(j,k) += Nj*Nk;
}
X(j) += Nj*Sample(0);
Y(j) += Nj*Sample(1);
Z(j) += Nj*Sample(2);
}
}
A = Inv(A);
X = A*X;
Y = A*Y;
Z = A*Z;
for ( i=0; i<CtrlPts.size(); i++ )
{
CtrlPts[i](0) = X(i%n);
CtrlPts[i](1) = Y(i%n);
CtrlPts[i](2) = Z(i%n);
}
}
else if ( nOpen==1 )
{
CMatrix A(n,n), X(n), Y(n), Z(n);
for ( int i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
double u = uParam[i];
Blend.Blend( u, pKnots );
for ( int j=0; j<n; j++ )
{
for ( int k=0; k<n; k++ )
A(j,k) += pKnots[j]*pKnots[k];
X(j) += pKnots[j]*pData[i](0);
Y(j) += pKnots[j]*pData[i](1);
Z(j) += pKnots[j]*pData[i](2);
}
}
A = Inv(A);
X = A*X;
Y = A*Y;
Z = A*Z;
for ( int i=0; i<n; i++ )
{
CtrlPts[i](0) = X(i);
CtrlPts[i](1) = Y(i);
CtrlPts[i](2) = Z(i);
}
}
else if ( nOpen==2 )
{
CMatrix A(n-2,n-2), X(n-2), Y(n-2), Z(n-2);
for ( int i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
double u = uParam[i];
CtrlPts[0] = pData[0];
CtrlPts[n-1] = pData[pData.size()-1];
Blend.Blend( u, pKnots );
for ( int j=1; j<n-1; j++ )
{
for ( int k=1; k<n-1; k++ )
A(j-1,k-1) += pKnots[j]*pKnots[k];
X(j-1) += ( pData[i](0)-pKnots[0]*CtrlPts[0](0)-pKnots[n-1]*CtrlPts[n-1](0) )*pKnots[j];
Y(j-1) += ( pData[i](1)-pKnots[0]*CtrlPts[0](1)-pKnots[n-1]*CtrlPts[n-1](1) )*pKnots[j];
Z(j-1) += ( pData[i](2)-pKnots[0]*CtrlPts[0](2)-pKnots[n-1]*CtrlPts[n-1](2) )*pKnots[j];
}
}
A = Inv(A);
X = A*X;
Y = A*Y;
Z = A*Z;
for ( int i=1; i<n-1; i++ )
{
CtrlPts[i](0) = X(i-1);
CtrlPts[i](1) = Y(i-1);
CtrlPts[i](2) = Z(i-1);
}
}
delete [] pKnots;
return 1;
}
float CNurbs::Approximate( size_t n, int nOpen, vector<CVector>& pData, vector<CVector>& CtrlPts, CBlend& Blend, double Eps /*= 1e-3*/, bool bCull /*= false*/ )
{
if ( pData.size() < 4 )
return 0;
int i;
if ( nOpen==0 )
{
vector<bool> bActive;
vector<double> pDist, fError;
pDist.resize( pData.size()+1 );
fError.resize( pData.size()+1 );
bActive.resize( pData.size()+1 );
double Len = 0;
for ( i=0; i<pData.size()+1; i++ )
{
bActive[i] = true;
}
float Error=0.0;
do
{
CVector Last = pData[0];
Len = 0;
pDist[0] = 0;
for ( i=1; i<pData.size()+1; i++ )
{
double tmp;
if ( bActive[i] )
{
if ( i!=pData.size() )
tmp = Mag( pData[i] - Last );
else
tmp = Mag( pData[0] - Last );
pDist[i] = tmp + Len;
Len += tmp;
Last = pData[i];
}
}
for ( i=1; i<pData.size()+1; i++ )
{
if ( bActive[i] )
{
pDist[i] /= Len;
}
}
CtrlPts.resize( n+3 );
Blend = CBlend();
Blend.SetCtrlPts( n+3 );
Blend.SetOrder( 4 );
double *pKnots = new double[ n+3+4 ];
for ( i=0; i<n+4+3; i++ )
{
pKnots[i] = (i)/(n-1.0);
}
Blend.SetKnot( pKnots );
FitCurve( n, nOpen, pData, CtrlPts, Blend, pDist, bActive );
Error=0.0;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
double u = pDist[i];///Len;
//if ( u == 1.0 )
// u = 1.0-1e-6;
int nSpan = Blend.BlendSlim( u, pKnots );
CVector Pos;
for ( int j=0; j<4; j++ )
{
Pos = Pos + pKnots[j]*CtrlPts[j+nSpan];
}
double err = Mag( Pos-pData[i] );
Error += err;
fError[i] = err;
}
Error /= pData.size();
if ( bCull )
{
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
if ( fError[i] > 2.5*Error )
bActive[i] = false;
}
}
delete [] pKnots;
n*=2;
} while ( Error > Eps );
return Error;
}
else
{
vector<double> pDist, fError;
vector<bool> bActive;
pDist.resize( pData.size() );
fError.resize( pData.size() );
bActive.resize( pData.size() );
for ( i=0; i<pData.size(); i++ )
bActive[i] = true;
double Len = 0;
pDist[0] = 0;
float Error=0.0;
double Max =-1e10;
do
{
Max =-1e10;
int nLast;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == true )
{
nLast = i;
break;
}
}
Len = 0;
pDist[0] = 0;
for ( i=nLast+1; i<pData.size(); i++ )
{
double tmp;
if ( bActive[i] )
{
tmp = Mag( pData[i] - pData[nLast] );
pDist[i] = tmp + Len;
Len += tmp;
nLast = i;
}
}
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] )
{
pDist[i] /= Len;
}
}
CtrlPts.resize( n );
Blend = CBlend();
Blend.SetCtrlPts( n );
Blend.SetOrder( 4 );
double *pKnots = new double[ n+4 ];
for ( i=0; i<n+4; i++ )
{ //n+4 == 10 0,0,0,0, 0.333, 0.667, 1,1,1,1
if ( i<4 ) pKnots[i] = 0;
else if ( i>=n ) pKnots[i] = 1.0;
else pKnots[i] = (i-3.0)/(n-3.0);
}
Blend.SetKnot( pKnots );
FitCurve( n, nOpen, pData, CtrlPts, Blend, pDist, bActive );
Error=0.0;
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
double u = pDist[i];///Len;
//if ( u == 1.0 )
// u = 1.0-1e-6;
int nSpan = Blend.BlendSlim( u, pKnots );
CVector Pos;
for ( int j=0; j<4; j++ )
{
Pos = Pos + pKnots[j]*CtrlPts[j+nSpan];
}
double err = Mag( pData[i] - Pos );
Error += err;
fError[i] = err;
if ( Max < err )
Max = err;
}
Error /= pData.size();
if ( bCull )
{
for ( i=0; i<pData.size(); i++ )
{
if ( bActive[i] == false )
continue;
if ( fError[i] > 2.5*Error )
bActive[i] = false;
}
}
delete [] pKnots;
n*=2;
} while ( Error > Eps );
n /= 2;
return Error;
}
}
CVector CNurbs::Normal(double u, double v) const
{
CVector P, Pu, Pv;
d1Position( u, v, P, Pu, Pv );
double A, B, C;
A = Pu(1)*Pv(2) - Pv(1)*Pu(2);
B = Pv(0)*Pu(2) - Pu(0)*Pv(2);
C = Pu(0)*Pv(1) - Pv(0)*Pu(1);
double Len = sqrt( A*A + B*B + C*C );
return CVector( A/Len, B/Len, C/Len );
}
bool CNurbs::dNormal(double u, double v, CVector& Nor, CVector& Nu, CVector& Nv) const
{
CVector P, Pu, Pv, Puu, Puv, Pvv;
d2Position( u, v, P, Pu, Pv, Puu, Puv, Pvv );
double A, B, C, Au, Av, Bu, Bv, Cu, Cv;
A = Pu(1)*Pv(2) - Pv(1)*Pu(2);
B = Pv(0)*Pu(2) - Pu(0)*Pv(2);
C = Pu(0)*Pv(1) - Pv(0)*Pu(1);
double Len, LenU, LenV;
Len = sqrt( A*A + B*B + C*C );
Nor(0) = A/Len;
Nor(1) = B/Len;
Nor(2) = C/Len;
Au = Puu(1)*Pv(2) + Pu(1)*Puv(2) - Puv(1)*Pu(2) - Pv(1)*Puu(2);
Bu = Puv(0)*Pu(2) + Pv(0)*Puu(2) - Puu(0)*Pv(2) - Pu(0)*Puv(2);
Cu = Puu(0)*Pv(1) + Pu(0)*Puv(1) - Puv(0)*Pu(1) - Pv(0)*Puu(1);
Av = Puv(1)*Pv(2) + Pu(1)*Pvv(2) - Pvv(1)*Pu(2) - Pv(1)*Puv(2);
Bv = Pvv(0)*Pu(2) + Pv(0)*Puv(2) - Puv(0)*Pv(2) - Pu(0)*Pvv(2);
Cv = Puv(0)*Pv(1) + Pu(0)*Pvv(1) - Pvv(0)*Pu(1) - Pv(0)*Puv(1);
LenU = (A*Au + B*Bu + C*Cu)/Len;
LenV = (A*Av + B*Bv + C*Cv)/Len;
Nu(0) = ( Au*Len - A*LenU )/(Len*Len);
Nu(1) = ( Bu*Len - B*LenU )/(Len*Len);
Nu(2) = ( Cu*Len - C*LenU )/(Len*Len);
Nv(0) = ( Av*Len - A*LenV )/(Len*Len);
Nv(1) = ( Bv*Len - B*LenV )/(Len*Len);
Nv(2) = ( Cv*Len - C*LenV )/(Len*Len);
return true;
}
void CNurbs::Serialize( CArchive& ar )
{
CObject::Serialize( ar );
if ( ar.IsLoading() ) // loading code
{
CFile *pFile = ar.GetFile();
//string pathname = pFile->GetFilePath();
using std::ifstream;
//using std::getline;
std::ifstream fin;
fin.open( pFile->GetFilePath() );
//afxDump << pFile->GetFilePath() << "\n";
string Tag;
bool bRead[7] = { false, false, false, false, false, false, false};
double *pUknots, *pVknots;
while ( fin >> Tag && fin )
{
if ( Tag == "Order" )
{
getline( fin, Tag, '[' );
int UK, VK;
fin >> UK;
getline( fin, Tag, ',' );
fin >> VK;
m_uDirection.SetOrder( UK );
m_vDirection.SetOrder( VK );
bRead[0] = true;
getline( fin, Tag );
//afxDump << "read order " << m_uDirection.GetOrder() << ", " << m_vDirection.GetOrder() << "\n";
}
else if ( Tag == "Grid_size" )
{
bRead[1] = true;
int M, N;
getline( fin, Tag, '[' );
fin >> M;
getline( fin, Tag, ',' );
fin >> N;
getline( fin, Tag );
m_uDirection.SetCtrlPts( M );
m_vDirection.SetCtrlPts( N );
m_CtrlPts.resize( M );
for ( int i=0; i<M; i++ )
m_CtrlPts[i].resize( N );
}
else if ( Tag == "Ctrl_pts" )
{
if ( !bRead[1] )
return; // fail
getline( fin, Tag, '[' );
//m_CtrlPts = new CVector*[m_m];
for ( int i=0; i<m_uDirection.GetCtrlPt(); i++ )
{
//m_CtrlPts[i] = new CVector[m_n];
for ( int j=0; j<m_vDirection.GetCtrlPt(); j++ )
{
getline( fin, Tag, '[' );
fin >> m_CtrlPts[i][j](0); getline( fin, Tag, ',' );
fin >> m_CtrlPts[i][j](1); getline( fin, Tag, ',' );
fin >> m_CtrlPts[i][j](2);
// //afxDump << "[" << m_CtrlPts[i][j](0) << ", "<< m_CtrlPts[i][j](1) << ", "<< m_CtrlPts[i][j](2) << "], ";
}
}
getline( fin, Tag );
bRead[2] = true; // CtrlPts read
//afxDump << "Ctrl_pts\n";
}
else if ( Tag == "Weights" )
{
if ( !bRead[1] )
return; // fail
getline( fin, Tag, '[' );
// m_Weight = CMatrix( m_uDirection.GetCtrlPt(), m_vDirection.GetCtrlPt() );
for ( int i=0; i<m_uDirection.GetCtrlPt(); i++ )
{
getline( fin, Tag, '[' );
for ( int j=0; j<m_vDirection.GetCtrlPt(); j++ )
{
fin >> m_CtrlPts[i][j](3);
if ( j!=m_vDirection.GetCtrlPt()-1 )
getline( fin, Tag, ',' );
}
}
getline( fin, Tag );
}
else if ( Tag == "U_knots" )
{
if ( !bRead[0] || !bRead[1] )
return; // fail
pUknots = new double[ m_uDirection.GetOrder()+m_uDirection.GetCtrlPt() ];
getline( fin, Tag, '[' );
for ( int i=0; i<m_uDirection.GetOrder()+m_uDirection.GetCtrlPt(); i++ )
{
fin >> pUknots[i];
if ( i != m_uDirection.GetCtrlPt()+m_uDirection.GetOrder()-1 )
getline( fin, Tag, ',' );
}
getline( fin, Tag );
m_uDirection.SetKnot( pUknots ); delete [] pUknots;
bRead[3] = true;
//afxDump << "U_knots, ";
}
else if ( Tag == "V_knots" )
{
if ( !bRead[0] || !bRead[1] )
return; // fail
pVknots = new double[ m_vDirection.GetOrder()+m_vDirection.GetCtrlPt() ];
getline( fin, Tag, '[' );
for ( int i=0; i<m_vDirection.GetOrder()+m_vDirection.GetCtrlPt(); i++ )
{
fin >> pVknots[i];
if ( i != m_vDirection.GetOrder()+m_vDirection.GetCtrlPt()-1 )
getline( fin, Tag, ',' );
////afxDump << pVknots[i] << ", ";
}
getline( fin, Tag );
m_vDirection.SetKnot( pVknots ); delete [] pVknots;
bRead[4] = true;
//afxDump << "V_knots\n";
}
else if ( Tag == "Material" )
{
getline( fin, Tag, '[' );
fin >> m_Diffuse[0]; getline( fin, Tag, ',' );
fin >> m_Diffuse[1]; getline( fin, Tag, ',' );
fin >> m_Diffuse[2]; getline( fin, Tag, ',' );
fin >> m_Diffuse[3];
getline( fin, Tag );
}
else if ( Tag == "UClosed" )
{
getline( fin, Tag, '[' );
fin >> m_bUClosed;
getline( fin, Tag );
bRead[5] = true;
}
else if ( Tag == "VClosed" )
{
getline( fin, Tag, '[' );
fin >> m_bVClosed;
getline( fin, Tag );
bRead[6] = true;
}
} // end of while ( fin >> Tag && fin )
if ( !(bRead[0] && bRead[1] && bRead[2] && bRead[3] && bRead[4]) )
{
} // file is not complete
else
{
}
} // end of loading code
else // storing code
{
int i, j;
CString Str;
Str.Format( "Order\t\t[ %d, %d ]\n", m_uDirection.GetOrder(), m_vDirection.GetOrder() );
ar.WriteString( Str );
Str.Format( "Grid_size\t\t[ %d, %d ]\n", m_uDirection.GetCtrlPt(), m_vDirection.GetCtrlPt() );
ar.WriteString( Str );
ar.WriteString( "Ctrl_pts [ " );
for ( int i=0; i<m_uDirection.GetCtrlPt(); i++ )
{
for ( int j=0; j<m_vDirection.GetCtrlPt(); j++ )
{
if ( j==m_vDirection.GetCtrlPt()-1 && i==m_uDirection.GetCtrlPt()-1 )
Str.Format( "[%f, %f, %f]", m_CtrlPts[i][j](0), m_CtrlPts[i][j](1), m_CtrlPts[i][j](2) );
else
Str.Format( "[%f, %f, %f], ", m_CtrlPts[i][j](0), m_CtrlPts[i][j](1), m_CtrlPts[i][j](2) );
ar.WriteString( Str );
}
if ( i!=m_uDirection.GetCtrlPt()-1 )
ar.WriteString( "\n\t" );
}
ar.WriteString( " ]\n" );
//if ( m_Weight.m()*m_Weight.n() > 0 )
{
ar.WriteString( "Weights [ " );
for ( i=0; i<m_uDirection.GetCtrlPt(); i++ )
{
ar.WriteString( "[ " );
for ( j=0; j<m_vDirection.GetCtrlPt(); j++ )
{
if ( j!=m_vDirection.GetCtrlPt()-1 )
Str.Format( "%f, ", m_CtrlPts[i][j](3) );
else
Str.Format( "%f ]", m_CtrlPts[i][j](3) );
ar.WriteString( Str );
}
if ( i!=m_uDirection.GetCtrlPt()-1 )
ar.WriteString( "\n\t" );
}
ar.WriteString( " ]\n" );
}
ar.WriteString( "U_knots [ " );
for ( i=0; i<m_uDirection.GetCtrlPt()+m_uDirection.GetOrder(); i++ )
{
if ( i==m_uDirection.GetCtrlPt()+m_uDirection.GetOrder()-1 )
Str.Format( "%f", m_uDirection.Knots(i) );
else
Str.Format( "%f, ", m_uDirection.Knots(i) );
ar.WriteString( Str );
}
ar.WriteString( " ]\n" );
ar.WriteString( "V_knots [ " );
for ( i=0; i<m_vDirection.GetCtrlPt()+m_vDirection.GetOrder(); i++ )
{
if ( i==m_vDirection.GetCtrlPt()+m_vDirection.GetOrder()-1 )
Str.Format( "%f", m_vDirection.Knots(i) );
else
Str.Format( "%f, ", m_vDirection.Knots(i) );
ar.WriteString( Str );
}
ar.WriteString( " ]\n" );
Str.Format( "Material [ %.3f, %.3f, %.3f, %.2f ]\n", m_Diffuse[0], m_Diffuse[1], m_Diffuse[2], m_Diffuse[3] );
ar.WriteString( Str );
} // end of storing code
}
double CNurbs::Curvature( double u , double v , double du , double dv) const
{
if ( m_CtrlPts.size() == 1 )
{
CVector Pos, vPos, vvPos;
{
CMatrix uBasis(m_uDirection.GetOrder()), vBasis(3,m_vDirection.GetOrder());
int uSpan = m_uDirection.BlendSlim( 0, uBasis );
int vSpan = m_vDirection.dBlendSlim( v, 2, vBasis );
Pos(3) = vPos(3) = vvPos(3) = 0.0;
int k;
for ( int i=0; i<m_uDirection.GetOrder(); i++ )
{
for ( int j=0; j<m_vDirection.GetOrder(); j++ )
{
for ( k=0; k<3; k++ )
{
Pos(k) += uBasis(i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(k) += uBasis(i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
vvPos(k) += uBasis(i)*vBasis(2,j)*m_CtrlPts[i+uSpan][j+vSpan](k)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
Pos(3) += uBasis(i)*vBasis(0,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
vPos(3) += uBasis(i)*vBasis(1,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
vvPos(3) += uBasis(i)*vBasis(2,j)*m_CtrlPts[i+uSpan][j+vSpan](3);
}
}
for ( k=0; k<3; k++ )
{
vvPos(k) = vvPos(k)*Pos(3)*Pos(3) - ( 2*vPos(k)*vPos(3) + Pos(k)*vvPos(3) )*Pos(3) + 2.0*vPos(k)*vPos(3)*vPos(3);
vPos(k) = vPos(k)*Pos(3) - Pos(k)*vPos(3);
}
for ( k=0; k<4;k++ )
{
if ( Pos(3) != 0.0 )
{
Pos(k) /= Pos(3);
vPos(k) /= Pos(3)*Pos(3);
vvPos(k) /= pow( Pos(3), 3 );
}
else
Pos(k) = vPos(k) = vvPos(k) = 0;
}
Pos(3) = vPos(3) = vvPos(3) = 1.0;
}
double Len, LenV;
Len = Mag( vPos );
double Av, Bv, Cv;
Av = vPos(0)*vvPos(0)/Len;
Bv = vPos(1)*vvPos(1)/Len;
Cv = vPos(2)*vvPos(2)/Len;
LenV = Av + Bv + Cv;
CVector Tv = ( vvPos*Len - vPos*LenV )/(Len*Len);
return Mag( Tv )/Len;
}
else
{
double len = sqrt( du*du + dv*dv );
du /= len;
dv /= len;
CVector P, Pu, Pv, Puu, Puv, Pvv;
d2Position( u, v, P, Pu, Pv, Puu, Puv, Pvv );
CVector vr = du*Pu + dv*Pv;
CVector ar = Puu*(du*du) + 2*Puv*du*dv + Pvv*dv*dv, nor = Normal(u, v);
return ar*nor/(vr*vr);
}
}
double CNurbs::PrincipalCurvature( double u, double v, double& R1, double& R2, double& K1, double& K2 ) const
{
if ( m_CtrlPts.size() == 1 )
return 0;
CVector P, Pu, Pv, Nor, Nu, Nv;
d1Position( u, v, P, Pu, Pv );
dNormal( u, v, Nor, Nu, Nv);
double A, B, C;
A = Nu(0)*Pu(1) - Nu(1)*Pu(0);
B = Nv(0)*Pu(1) + Nu(0)*Pv(1) - Nu(1)*Pv(0) - Nv(1)*Pu(0);
C = Nv(0)*Pv(1) - Nv(1)*Pv(0);
double Tmp = B*B - 4.0*A*C;
if ( Tmp < 0 )
{
return 0;
}
R1 = (-B+sqrt(Tmp))/(2.0*A);
R2 = (-B-sqrt(Tmp))/(2.0*A);
K1 =-( Pu(2)*R1 + Pv(2) )/( Nu(2)*R1 + Nv(2) );
K2 =-( Pu(2)*R2 + Pv(2) )/( Nu(2)*R2 + Nv(2) );
return K1*K2;
}
CMatrix PrincipalAxis( vector<CVector>& pData )
{
CVector Center;
int iCount = 0;
Center(0) = Center(1) = Center(2) = 0.0f;
for ( int j=0; j<pData.size(); j++ )
{
Center(0) += pData[j](0);
Center(1) += pData[j](1);
Center(2) += pData[j](2);
iCount++;
}
Center(0) /= iCount;
Center(1) /= iCount;
Center(2) /= iCount;
MyMath::CMatrix C(3,3);
for ( int j=0; j<3; j++ )
{
for ( int k=0; k<3; k++ )
{
for ( int l=0; l<pData.size(); l++ )
C(j,k) += (pData[l](j)-Center(j))*(pData[l](k)-Center(k));
C(j,k) /= iCount;
}
}
double v[3];
MyMath::CMatrix A(3,3);
EigenValue( C, v, A );
A = Transpose(A);
return A;
}
float CNurbs::SurfaceApproximate( int m, int n, int uOpen, int vOpen, vector<CVector>& pData, vector<bool>& bActive
, vector<double>* pUParam/*=NULL*/, vector<double>* pVParam/*=NULL*/, double Eps/* = 1.*/, bool bCull/* = false*/, int nRepeat/*=100000*/ )
{
vector<double> UParam, VParam;
int i, l;
if ( pUParam==NULL || pVParam==NULL )
{
pUParam = &UParam;
UParam.resize( pData.size() );
pVParam = &VParam;
VParam.resize( pData.size() );
CMatrix A = PrincipalAxis( pData );
double Ext[2][3] = { {1e10,1e10,1e10}, {-1e10,-1e10,-1e10} };
for ( l=0; l<pData.size(); l++ )
{
CVector tmp;
tmp(0) = A(0,0)*pData[l](0) + A(0,1)*pData[l](1) + A(0,2)*pData[l](2);
tmp(1) = A(1,0)*pData[l](0) + A(1,1)*pData[l](1) + A(1,2)*pData[l](2);
tmp(2) = A(2,0)*pData[l](0) + A(2,1)*pData[l](1) + A(2,2)*pData[l](2);
if ( Ext[0][0] > tmp(0) ) Ext[0][0] = tmp(0);
if ( Ext[1][0] < tmp(0) ) Ext[1][0] = tmp(0);
if ( Ext[0][1] > tmp(1) ) Ext[0][1] = tmp(1);
if ( Ext[1][1] < tmp(1) ) Ext[1][1] = tmp(1);
if ( Ext[0][2] > tmp(2) ) Ext[0][2] = tmp(2);
if ( Ext[1][2] < tmp(2) ) Ext[1][2] = tmp(2);
}
double UMax = Ext[1][0], UMin = Ext[0][0];
double VMax = Ext[1][1], VMin = Ext[0][1];
for ( int l=0; l<pData.size(); l++ )
{
CVector tmp;
tmp(0) = A(0,0)*pData[l](0) + A(0,1)*pData[l](1) + A(0,2)*pData[l](2);
tmp(1) = A(1,0)*pData[l](0) + A(1,1)*pData[l](1) + A(1,2)*pData[l](2);
(*pUParam)[l] = (tmp(0)-UMin)/(UMax-UMin);
(*pVParam)[l] = (tmp(1)-VMin)/(VMax-VMin);
}
}
this->m_uDirection.SetCtrlPts( m ); // should be n
this->m_vDirection.SetCtrlPts( n ); // should be m
m_uDirection.SetOrder( 4 );
m_vDirection.SetOrder( 4 );
vector<double> UKnots(m+4);
vector<double> VKnots(n+4);
for ( i=0; i<m+4; i++ )
{ //m+4 == 10 0,0,0,0, 0.333, 0.667, 1,1,1,1
if ( i<4 ) UKnots[i] = 0;
else if ( i>=m ) UKnots[i] = 1.0;
else UKnots[i] = (i-3.0)/(m-3.0);
}
for ( i=0; i<n+4; i++ )
{ //n+4 == 10 0,0,0,0, 0.333, 0.667, 1,1,1,1
if ( i<4 ) VKnots[i] = 0;
else if ( i>=n ) VKnots[i] = 1.0;
else VKnots[i] = (i-3.0)/(n-3.0);
}
m_uDirection.SetKnot( UKnots );
m_vDirection.SetKnot( VKnots );
if ( m_CtrlPts.size()!=m )
m_CtrlPts.resize( m );
for ( i=0; i<m; i++ )
{
if ( m_CtrlPts[i].size()!=n )
m_CtrlPts[i].resize( n );
}
FitSurface( m, n, uOpen, vOpen, pData, bActive, *pUParam, *pVParam );
return 0;
}
float CNurbs::FitSurface( int m, int n, int uOpen, int vOpen, vector<CVector>& Data, vector<bool>& bActive,
vector<double>& uParam, vector<double>& vParam )
{
double *pUKnots = new double[ m ];
double *pVKnots = new double[ n ];
if ( uOpen==1 && vOpen==1 )
{
CMatrix A(m*n,m*n), X(m*n), Y(m*n), Z(m*n);
for ( int i=0; i<Data.size(); i++ )
{
if ( bActive[i] == false )
continue;
double u = uParam[i];
double v = vParam[i];
m_uDirection.Blend( u, pUKnots );
m_vDirection.Blend( v, pVKnots );
for ( int j=0; j<m*n; j++ )
{
int ju, jv;
ju = j/n;
jv = j%n;
for ( int k=0; k<m*n; k++ )
{
int ku, kv;
ku = k/n;
kv = k%n;
A(j,k) += (pUKnots[ju]*pVKnots[jv])*(pUKnots[ku]*pVKnots[kv]);
}
X(j) += pUKnots[ju]*pVKnots[jv]*Data[i](0);
Y(j) += pUKnots[ju]*pVKnots[jv]*Data[i](1);
Z(j) += pUKnots[ju]*pVKnots[jv]*Data[i](2);
}
}
A = Inv(A);
X = A*X;
Y = A*Y;
Z = A*Z;
for ( int i=0; i<m*n; i++ )
{
int iu, iv;
iu = i/n;
iv = i%n;
m_CtrlPts[iu][iv](0) = X(i);
m_CtrlPts[iu][iv](1) = Y(i);
m_CtrlPts[iu][iv](2) = Z(i);
}
}
else if ( uOpen==2 && vOpen==2 )
{
CMatrix A((m-2)*(n-2),(m-2)*(n-2)), X((m-2)*(n-2)), Y((m-2)*(n-2)), Z((m-2)*(n-2));
for ( int i=0; i<Data.size(); i++ )
{
if ( bActive[i] == false )
continue;
double u = uParam[i];
double v = vParam[i];
m_uDirection.Blend( u, pUKnots );
m_vDirection.Blend( v, pVKnots );
for ( int j=0; j<m*n; j++ )
{
int ju, jv;
ju = j/n;
jv = j%n;
if ( ju==0 || ju==m-1 )
continue;
if ( jv==0 || jv==n-1 )
continue;
int J = (ju-1)*(n-2) + (jv-1);
for ( int k=0; k<m*n; k++ )
{
int ku, kv;
ku = k/n;
kv = k%n;
if ( ku==0 || ku==m-1 )
continue;
if ( kv==0 || kv==n-1 )
continue;
int K = (ku-1)*(n-2) + (kv-1);
A(J,K) += (pUKnots[ju]*pVKnots[jv])*(pUKnots[ku]*pVKnots[kv]);
}
{
double x=0, y=0, z=0;
for ( int ii=0; ii<m; ii++ )
{
for ( int jj=0; jj<n; jj++ )
{
if ( ( ii!=0 && ii!=m-1 ) && ( jj!=0 && jj!=n-1 ))
continue;
x += pUKnots[ii]*pVKnots[jj]*m_CtrlPts[ii][jj](0);
y += pUKnots[ii]*pVKnots[jj]*m_CtrlPts[ii][jj](1);
z += pUKnots[ii]*pVKnots[jj]*m_CtrlPts[ii][jj](2);
}
}
X(J) += pUKnots[ju]*pVKnots[jv]*(Data[i](0)-x);
Y(J) += pUKnots[ju]*pVKnots[jv]*(Data[i](1)-y);
Z(J) += pUKnots[ju]*pVKnots[jv]*(Data[i](2)-z);
}
}
}
A = Inv(A);
X = A*X;
Y = A*Y;
Z = A*Z;
for ( int i=0; i<m*n; i++ )
{
int iu, iv;
iu = i/n;
iv = i%n;
if ( iu==0 || iu==m-1 )
continue;
if ( iv==0 || iv==n-1 )
continue;
int I = (iu-1)*(n-2) + (iv-1);
m_CtrlPts[iu][iv](0) = X(I);
m_CtrlPts[iu][iv](1) = Y(I);
m_CtrlPts[iu][iv](2) = Z(I);
}
}
delete[] pUKnots;
delete[] pVKnots;
return 0;
}
double CNurbs::Length( double v0/*=0*/, double v1/*=1*/ ) const
{
double Len = 0;
if ( v0<0 )
v0 = 0;
if ( v1>1 )
v1 = 0;
CVector P0=Position(0,v0), P1=Position(0,v1);
return Length( v0, v1, P0, P1 );
}
double CNurbs::Length( double v0, double v1, CVector& P0, CVector& P1 ) const
{
CVector P05=Position(0,(v0+v1)/2.0);
double l1 = Mag( P0-P1 ), l2 = Mag(P0-P05)+Mag(P05-P1);
if ( l1/l2>0.9999 )
return l2;
if ( fabs(v0-v1)<1e-6 )
return l2;
return Length( v0, (v0+v1)/2., P0, P05 ) + Length( (v0+v1)/2., v1, P05, P1 );
}
bool CNurbs::SetControlGridSize( int m, int n )
{
if ( m_CtrlPts.size()!=m )
m_CtrlPts.resize( m );
for ( int i=0; i<m; i++ )
{
if ( m_CtrlPts[i].size()!=n )
m_CtrlPts[i].resize( n );
}
return true;
}
int CNurbs::CurveKnotInsert( double Knot, int nRepeat/*+1*/ )
{
vector<double> UP( m_vDirection.m_Knot );
int k = m_vDirection.KnotInsert( Knot, nRepeat );
vector<CVector> Qw( m_CtrlPts[0].size()+nRepeat );
int r = nRepeat;
int np = m_CtrlPts[0].size(), nq = m_CtrlPts[0].size()+r;
int p = m_vDirection.GetOrder()-1;
vector<CVector> Rw( p+1 );
int s = 0;
int L;
for ( int i=0; i<=k-p; i++ ) Qw[i] = m_CtrlPts[0][i];
for ( int i=k-s; i<np; i++ ) Qw[i+r] = m_CtrlPts[0][i];
for ( int i=0; i<=p-s; i++ ) Rw[i] = m_CtrlPts[0][k-p+i];
for ( int j=1; j<=r; j++ )
{
L = k-p+j;
for ( int i=0; i<=p-j-s; i++ )
{
double alpha = (Knot - UP[L+i])/(UP[i+k+1]-UP[L+i]);
Rw[i] = alpha*Rw[i+1] + (1.0-alpha)*Rw[i];
}
Qw[L] = Rw[0];
Qw[k+r-j-s] = Rw[p-j-s];
}
for ( int i=L+1; i<k-s; i++ )
Qw[i] = Rw[i-L];
m_CtrlPts[0] = Qw;
return 0;
}
| [
"[email protected]@8026b7c3-d9ae-87c5-0fde-12bd377d1155"
]
| [
[
[
1,
1948
]
]
]
|
906ca23e41fa2deb50565da2c7fbf2a0bb51d625 | b22c254d7670522ec2caa61c998f8741b1da9388 | /physXtest/Camera.cpp | 8fb2fdd9f9155c5356dcca593bac297ecaad52f3 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,157 | cpp | /*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#include "Camera.h"
#include <iostream>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846f
#endif
/***********************************************************
constructor
***********************************************************/
Camera::Camera()
: _size(80.), _perpective(true), _attached_actor(NULL), _movecamera(false)
{
SetTarget(32., 0, 32.);
SetDistance(30);
SetZenit(30);
SetAzimut(0);
}
/***********************************************************
reset camera position
***********************************************************/
void Camera::ResetPosition()
{
//if(_attached_actor)
//{
// SetTarget(_attached_actor->GetPosX(), _attached_actor->GetPosY(), _attached_actor->GetPosZ());
//}
}
/***********************************************************
set actor attached to the camera
***********************************************************/
void Camera::SetAttachedActor(Actor * act)
{
_attached_actor = act;
}
/***********************************************************
process
***********************************************************/
void Camera::Process()
{
//if(_attached_actor)
//{
// double actX = _attached_actor->GetPosX();
// double actY = _attached_actor->GetPosY();
// double actZ = _attached_actor->GetPosZ();
// // start to move camera only when actor moves a certain distance
// if(abs(actX - _targetx) > 3 || abs(actY - _targety) > 3 || abs(actZ - _targetz) > 3)
// _movecamera = true;
// if(abs(actX - _targetx) > 5 || abs(actY - _targety) > 5 || abs(actZ - _targetz) > 5)
// {
// ResetPosition();
// _movecamera = false;
// return;
// }
// if(_movecamera)
// {
// double speedX = (actX - _lastactX);
// double speedY = (actY - _lastactY);
// double speedZ = (actZ - _lastactZ);
// SetTarget(_targetx+speedX, _targety+speedY, _targetz+speedZ);
// double deltaX = (actX - _targetx);
// double deltaY = (actY - _targety);
// double deltaZ = (actZ - _targetz);
// if(abs(deltaX) > 0.1)
// _targetx+=deltaX/100;
// if(abs(deltaY) > 0.1)
// _targety+=deltaY/100;
// if(abs(deltaZ) > 0.1)
// _targetz+=deltaZ/100;
// if(actX == _lastactX && actY == _lastactY && actZ == _lastactZ)
// {
// _movecamera = false;
// }
// }
// _lastactX = actX;
// _lastactY = actY;
// _lastactZ = actZ;
//}
}
/***********************************************************
accessors
***********************************************************/
void Camera::SetTarget(double x, double y, double z)
{
_targetx = x;
_targety = y;
_targetz = z;
}
void Camera::SetDistance(double dist)
{
_distance = dist;
int maxdistance = 150;
if(!IsPerspective())
maxdistance = 1000;
if(_distance < 10)
_distance = 10;
if(_distance > maxdistance)
_distance = maxdistance;
_fov=atan(_size/2./_distance)*180./M_PI;
}
void Camera::SetZenit(double zenit)
{
_zenit = zenit;
if(_zenit < 10)
_zenit = 10;
if(_zenit > 70)
_zenit = 70;
}
void Camera::SetAzimut(double azimut)
{
_azimut = azimut;
if(_azimut < -45)
_azimut = -45;
if(_azimut > 90)
_azimut = 90;
}
void Camera::DeltaUpdateTarget(double x, double y, double z)
{
SetTarget(_targetx+x, _targety+y,_targetz+z);
}
void Camera::DeltaUpdateDistance(double dist)
{
SetDistance(_distance+dist);
}
void Camera::DeltaUpdateZenit(double zenit)
{
SetZenit(_zenit+zenit);
}
void Camera::DeltaUpdateAzimut(double azimut)
{
SetAzimut(_azimut+azimut);
}
double Camera::GetTargetX()
{
return _targetx;
}
double Camera::GetTargetY()
{
return _targety;
}
double Camera::GetTargetZ()
{
return _targetz;
}
double Camera::GetFOV()
{
return _fov;
}
double Camera::GetDistance()
{
return _distance;
}
double Camera::GetZenit()
{
return _zenit;
}
double Camera::GetAzimut()
{
return _azimut;
}
// tell if it is a perspective view or not
bool Camera::IsPerspective()
{
return _perpective;
}
// set perspective
void Camera::SetPerspective(bool Perspective)
{
_perpective = Perspective;
} | [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
242
]
]
]
|
0941c144c08a16386d2391fdd05693c9ff2b3465 | 28476e6f67b37670a87bfaed30fbeabaa5f773a2 | /src/autumnframework/ConsoleLogger.h | d2c705e65ffe28a722f72ef0fc89fe2dadc3920c | []
| no_license | rdmenezes/autumnframework | d1aeb657cd470b67616dfcf0aacdb173ac1e96e1 | d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d | refs/heads/master | 2021-01-20T13:48:52.187425 | 2008-07-17T18:25:19 | 2008-07-17T18:25:19 | 32,969,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | h | /*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AUTUMN_CONSOLELOGGER_H
#define AUTUMN_CONSOLELOGGER_H
#include <string>
#include <iostream>
#include "ILogAdapter.h"
using namespace std;
namespace Autumn{
/**
* Adapter for external log implementation
* @version 0.1.0
* @since 2006-11-30
*/
class ConsoleLogger: public ILogAdapter {
/** Log level */
int Level;
public:
ConsoleLogger(int level):Level(level){}
void debug(const string& msg){
this->log(0, "DEBUG: " + msg);
}
void info(const string& msg){
this->log(1, "INFO: " + msg);
}
void warn(const string& msg){
this->log(2, "WARN: " + msg);
}
void error(const string& msg){
this->log(3, "ERROR: " + msg);
}
void fatal(const string& msg){
this->log(4, "FATAL: " + msg);
}
void log(int level, const string& msg){
if( level >= this->Level )
cout<<msg<<endl;
}
};
} // End namespace Autumn
#endif
| [
"sharplog@c16174ff-a625-0410-88e5-87db5789ed7d"
]
| [
[
[
1,
88
]
]
]
|
57414c5bb1e761299cc0e8e2d650c8228b59dcae | ed2a1c83681d8ed2d08f8a74707536791e5cd057 | /Extensions/ItemImager.DLL/HG_SDK Files/HG_SDK.h | d9727e31278db95b0a7629dfd8e1726c328b4f2d | [
"Apache-2.0"
]
| permissive | MartinMReed/XenDLL | e33d5c27187e58fd4401b2dbcaae3ebab8279bc2 | 51a05c3cec7b2142f704f2ea131202a72de843ec | refs/heads/master | 2021-01-10T19:10:40.492482 | 2007-10-31T16:38:00 | 2007-10-31T16:38:00 | 12,150,175 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,223 | h | #ifndef HG_SDK_H
#define HG_SDK_H
#pragma once
#include "..\..\HGooey.DLL\HGooey Files\HGIncDef_Public.h"
#include "Capture Files\blit.h"
#include "Capture Files\BMP Functions.h"
//#include "Capture Files\DIB Functions.h"
#include "Capture Files\JPG Functions.h"
#include <iostream>
bool configOpen;
HGNodeList* ext_ItemImager;
int thumbnail;
int port;
int itemID;
int minID;
int maxID;
DWORD* g_page;
WORD* g_dropSlotMouseOver;
WORD* g_dropSlotImage;
char* g_mouseOverName;
char* g_mouseOverDescription;
WORD* g_descriptionLineCount;
RECT image;
BYTE startStopKey;
char* filePath;
int screenshotQuality;
UINT screenshotWidth;
UINT screenshotHeight;
IDirect3DTexture8* screenshotCopyTexture;
IDirect3DSurface8* screenshotRenderSurface;
IDirect3DSurface8* screenshotFinalSurface;
bool initialized;
void Initialize(void);
void CaptureScreen(void);
void LostDevice(void);
void ResetDevice(void);
void PreRender(void);
void Render(void);
bool HandleKeyboard(void);
void ResetImages(void);
void ResetImages(int _port);
void ClearScreenshot(void);
bool SetupScreenshot(void);
void DrawCursor(void);
bool Uninitialize(void);
#endif
| [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
93b6ee2c115eeedfeb67d8092cb9e45ee2f10625 | 1e01b697191a910a872e95ddfce27a91cebc57dd | /GrfTraceStack.cpp | 74e134cd5e6ea292bde96d288bec2c405ea40080 | []
| no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 1,464 | cpp | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2010 CÚdric Lemaire
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
To contact the author: [email protected]
*/
#ifdef WIN32
#pragma warning (disable : 4786)
#endif
#include "ScpStream.h"
#include "CppCompilerEnvironment.h"
#include "CGRuntime.h"
#include "GrfTraceStack.h"
namespace CodeWorker {
GrfTraceStack::~GrfTraceStack() {
}
SEQUENCE_INTERRUPTION_LIST GrfTraceStack::executeInternal(DtaScriptVariable& visibility) {
return CGRuntime::traceStack(visibility);
}
void GrfTraceStack::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const {
CW_BODY_INDENT << "// procedure 'traceStack' cannot be translated to C++";
CW_BODY_ENDL;
}
}
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
]
| [
[
[
1,
43
]
]
]
|
4d196deaa562bc1fff793223ca4c3067f0483e1e | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/dingus/gfx/gui/Gui.h | eb2429f4fd0d60e0438d5fad14784ba58dee2a02 | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,450 | h | // --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#ifndef __DINGUS_GUI_H
#define __DINGUS_GUI_H
#include "../../kernel/D3DDevice.h"
#include "../../kernel/Proxies.h"
#include "../../resource/DeviceResource.h"
#include "../../math/FPU.h"
namespace dingus {
// --------------------------------------------------------------------------
// Constants
const int UI_MAX_CTRL_STATES = 16;
#define UIEVENT_BUTTON_CLICKED 0x0101
#define UIEVENT_COMBOBOX_SELECTION_CHANGED 0x0201
#define UIEVENT_RADIOBUTTON_CHANGED 0x0301
#define UIEVENT_CHECKBOX_CHANGED 0x0401
#define UIEVENT_SLIDER_VALUE_CHANGED 0x0501
// UIEVENT_EDITBOX_CHANGE is sent when the listbox content changes
// due to user input.
#define UIEVENT_EDITBOX_CHANGE 0x0602
#define UIEVENT_LISTBOX_ITEM_DBLCLK 0x0701
// UIEVENT_LISTBOX_SELECTION is fired off when the selection changes in
// a single selection list box.
#define UIEVENT_LISTBOX_SELECTION 0x0702
// --------------------------------------------------------------------------
// Forward declarations
class CUIDialog;
class CUIControl;
class CUIButton;
class CUIStatic;
class CUIImage;
class CUICheckBox;
class CUIRadioButton;
class CUIComboBox;
class CUISlider;
class CUIListBox;
class CUIScrollBar;
class CUIRollout;
class SUIElement;
struct SUIFontNode;
typedef void (CALLBACK *TUICallbackEvent)( UINT evt, int ctrlID, CUIControl* ctrl );
typedef void (CALLBACK *TUICallbackRender)( CUIDialog& dlg );
// --------------------------------------------------------------------------
// Enums for pre-defined control types
enum eUIControlType {
UICTRL_BUTTON,
UICTRL_STATIC,
UICTRL_CHECKBOX,
UICTRL_RADIOBUTTON,
UICTRL_COMBOBOX,
UICTRL_SLIDER,
UICTRL_LISTBOX,
UICTRL_SCROLLBAR,
UICTRL_ROLLOUT,
UICTRL_IMAGE,
};
enum eUIControlState {
UISTATE_NORMAL,
UISTATE_DISABLED,
UISTATE_HIDDEN,
UISTATE_FOCUS,
UISTATE_MOUSEOVER,
UISTATE_PRESSED,
};
// --------------------------------------------------------------------------
static inline RECT makeRECT( int l, int t, int r, int b )
{
RECT rc = { l, t, r, b };
return rc;
}
struct SFPoint {
float x;
float y;
};
struct SFRect {
public:
SFRect() { } // empty constructor
SFRect( float l, float t, float r, float b )
: left(l), top(t), right(r), bottom(b) { }
float left;
float top;
float right;
float bottom;
public:
void set( float l, float t, float r, float b ) {
left = l; top = t; right = r; bottom = b;
}
bool containsPoint( const POINT& pt ) const {
return pt.x >= left && pt.y >= top && pt.x < right && pt.y < bottom;
}
bool containsPoint( float x, float y ) const {
return x >= left && y >= top && x < right && y < bottom;
}
void offset( float dx, float dy ) {
left += dx; top += dy;
right += dx; bottom += dy;
}
void inflate( float dx, float dy ) {
left -= dx; top -= dy;
right += dx; bottom += dy;
if( left > right )
left = right = (left+right)*0.5f;
if( top > bottom )
top = bottom = (top+bottom)*0.5f;
}
void toRect( RECT& rc ) const {
rc.left = dingus::round( left );
rc.top = dingus::round( top );
rc.right = dingus::round( right );
rc.bottom = dingus::round( bottom );
}
float getWidth() const { return right - left; }
float getHeight() const { return bottom - top; }
};
// --------------------------------------------------------------------------
struct SBlendColor {
void init( bool font, bool darkFont = false );
void blend( UINT state, float dt, float rate = 0.7f );
D3DCOLOR colors[ UI_MAX_CTRL_STATES ]; // Modulate colors for all possible control states
D3DXCOLOR current;
};
// --------------------------------------------------------------------------
/// Contains all the display tweakables for a sub-control
class SUIElement {
public:
void setTexture( CD3DTexture* tex, const RECT* texRect );
void setFont( size_t font, bool dark, DWORD textFmt = DT_CENTER | DT_VCENTER );
void refresh();
SBlendColor colorTexture;
SBlendColor colorFont;
RECT textureRect; // Bounding rect of this element on the composite texture
CD3DTexture* texture; // Texture for this element
size_t fontIdx; // Index of the font for this element
DWORD textFormat; // The format argument to drawText
bool darkFont; // Is the text dark (no need for the shadow)?
};
// --------------------------------------------------------------------------
/// All controls must be assigned to a dialog, which handles input and rendering for the controls.
class CUIDialog : public boost::noncopyable {
public:
CUIDialog();
~CUIDialog();
// Windows message handler
bool msgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );
// Control creation
HRESULT addStatic( int cid, const char* text, int x, int y, int width, int height, bool isDefault=false, CUIStatic** created=NULL );
HRESULT addButton( int cid, const char* text, int x, int y, int width, int height, UINT hotkey=0, bool isDefault=false, CUIButton** created=NULL );
HRESULT addCheckBox( int cid, const char* text, int x, int y, int width, int height, bool chk=false, UINT hotkey=0, bool isDefault=false, CUICheckBox** created=NULL );
HRESULT addRadioButton( int cid, UINT group, const char* text, int x, int y, int width, int height, bool chk=false, UINT hotkey=0, bool isDefault=false, CUIRadioButton** created=NULL );
HRESULT addComboBox( int cid, int x, int y, int width, int height, UINT nHotKey=0, bool isDefault=false, CUIComboBox** created=NULL );
HRESULT addSlider( int cid, int x, int y, int width, int height, int min=0, int max=100, int value=50, bool isDefault=false, CUISlider** created=NULL );
HRESULT addListBox( int cid, int x, int y, int width, int height, DWORD style=0, CUIListBox** created=NULL );
HRESULT addRollout( int cid, const char* text, int x, int y, int width, int height, int rollHeight, bool expanded=false, UINT hotkey=0, bool isDefault=false, CUIRollout** created=NULL );
HRESULT addImage( int cid, int x, int y, int width, int height, CD3DTexture& tex, int u0, int v0, int u1, int v1, CUIImage** created=NULL );
HRESULT addControl( CUIControl* ctrl );
HRESULT initControl( CUIControl* ctrl );
// Control retrieval
CUIStatic* getStatic( int cid ) { return (CUIStatic*) getControl( cid, UICTRL_STATIC ); }
CUIButton* getButton( int cid ) { return (CUIButton*) getControl( cid, UICTRL_BUTTON ); }
CUICheckBox* getCheckBox( int cid ) { return (CUICheckBox*) getControl( cid, UICTRL_CHECKBOX ); }
CUIRadioButton* getRadioButton( int cid ) { return (CUIRadioButton*) getControl( cid, UICTRL_RADIOBUTTON ); }
CUIComboBox* getComboBox( int cid ) { return (CUIComboBox*) getControl( cid, UICTRL_COMBOBOX ); }
CUISlider* getSlider( int cid ) { return (CUISlider*) getControl( cid, UICTRL_SLIDER ); }
CUIListBox* getListBox( int cid ) { return (CUIListBox*) getControl( cid, UICTRL_LISTBOX ); }
CUIRollout* getRollout( int cid ) { return (CUIRollout*) getControl( cid, UICTRL_ROLLOUT ); }
CUIImage* getImage( int cid ) { return (CUIImage*) getControl( cid, UICTRL_IMAGE ); }
CUIControl* getControl( int cid );
CUIControl* getControl( int cid, eUIControlType ctrlType );
CUIControl* getControlAtPoint( POINT pt );
bool isControlEnabled( int cid );
void setControlEnabled( int cid, bool enabled );
void clearRadioButtonGroup( int nGroup );
void clearComboBox( int cid );
// Access the default display Elements used when adding new controls
HRESULT setDefaultElement( eUIControlType ctrlType, size_t index, SUIElement* element );
SUIElement* getDefaultElement( eUIControlType ctrlType, size_t index );
// Methods called by controls
void sendEvent( UINT evt, bool userTriggered, CUIControl* ctrl );
void requestFocus( CUIControl* ctrl );
// render helpers
HRESULT drawRect( const SFRect* rect, D3DCOLOR color );
//HRESULT drawPolyLine( const POINT* points, size_t pointCount, D3DCOLOR color );
HRESULT drawSprite( SUIElement* element, const SFRect* dest );
//HRESULT calcTextRect( const char* text, SUIElement* element, SFRect* dest, int count = -1 );
HRESULT drawText( const char* text, SUIElement* element, const SFRect* dest, bool shadow = false, int count = -1 );
HRESULT drawText( const wchar_t* text, SUIElement* element, const SFRect* dest, bool shadow = false, int count = -1 );
// immediate mode renderers
HRESULT imDrawSprite( const D3DXCOLOR& color, const RECT& texRect, CD3DTexture* tex, const SFRect& destScr );
HRESULT imDrawText( const char* text, size_t fontIdx, DWORD format, const D3DXCOLOR& color, const SFRect& destScr, bool shadow = false, int count = -1 );
HRESULT imDrawText( const wchar_t* text, size_t fontIdx, DWORD format, const D3DXCOLOR& color, const SFRect& destScr, bool shadow = false, int count = -1 );
// Attributes
bool isMinimized() const { return mMinimized; }
void setMinimized( bool minimized ) { mMinimized = minimized; }
void setBackgroundColors( D3DCOLOR colorAllCorners ) { setBackgroundColors( colorAllCorners, colorAllCorners, colorAllCorners, colorAllCorners ); }
void setBackgroundColors( D3DCOLOR colorUL, D3DCOLOR colorUR, D3DCOLOR colorDL, D3DCOLOR colorDR );
void enableCaption( bool benable ) { mHasCaption = benable; }
float getCaptionHeight() const { return mCaptionHeight; }
void setCaptionHeight( float height ) { mCaptionHeight = height; }
void setCaptionText( const char *text ) { strncpy( mCaption, text, sizeof(mCaption)/sizeof(mCaption[0]) ); mCaption[sizeof(mCaption)/sizeof(mCaption[0])-1] = 0; }
//void getLocation( POINT& pt ) const { pt.x = mX; pt.y = mY; }
void setLocation( float x, float y ) { mX = x; mY = y; }
void setSize( float width, float height ) { mWidth = width; mHeight = height; }
float getX() const { return mX; }
float getY() const { return mY; }
float getWidth() const { return mWidth; }
float getHeight() const { return mHeight; }
void setNextDialog( CUIDialog* nextDlg );
static void setRefreshTime( float fTime ) { sTimeRefresh = fTime; }
static CUIControl* getNextControl( CUIControl* ctrl );
static CUIControl* getPrevControl( CUIControl* ctrl );
void removeControl( int cid );
void removeAllControls();
// sets the callback used to notify the app of control events
void setCallback( TUICallbackEvent pCallback ) { mCallbackEvent = pCallback; }
void enableNonUserEvents( bool benable ) { mDoNonUserEvents = benable; }
void enableKeyboardInput( bool benable ) { mDoKeyboardInput = benable; }
void enableMouseInput( bool benable ) { mDoMouseInput = benable; }
void refresh();
/**
* Render whole dialog and controls. This calls renderBegin() and
* renderEnd() internally; also calls render callback if any.
*/
void onRender( float dt );
/**
* Manually prepare for dialog rendering. This sets all required
* rendering state; after this call drawYYY and imDrawYYY methods can
* be used. Use in cases where you want to render something UI-related,
* but probably don't want to draw controls, etc.
*/
void renderBegin( bool renderDlgBackground = false );
/**
* End manual dialog rendering.
*/
void renderEnd();
void setRenderCallback( TUICallbackRender renderCb ) { mRenderCallback = renderCb; }
// Shared resource access.
void setFont( size_t index, const char* facename, LONG height, LONG weight );
SUIFontNode* getFont( size_t index ) const;
void setDefaultTexture( CD3DTexture& texture ) { mDefaultTexture = &texture; }
static void clearFocus();
void focusDefaultControl();
/// True if there is a control is in focus, belongs to this dialog, and is enabled.
bool hasFocusControl() const;
bool mDoNonUserEvents;
bool mDoKeyboardInput;
bool mDoMouseInput;
private:
// initialize default Elements
void initDefaultElements();
// Windows message handlers
void onMouseMove( POINT pt );
void onMouseUp( POINT pt );
// Control events
void onCycleFocus( bool forward );
void onMouseEnter( CUIControl* ctrl );
void onMouseLeave( CUIControl* ctrl );
private:
struct SElementHolder {
SUIElement element;
eUIControlType ctrlType;
size_t index;
};
private:
static CUIControl* sCtrlFocus; // The control which has focus
static CUIControl* sCtrlPressed; // The control currently pressed
char mCaption[256];
bool mHasCaption;
bool mMinimized;
bool mDragging;
float mX;
float mY;
float mWidth;
float mHeight;
float mCaptionHeight;
D3DCOLOR mColorUL;
D3DCOLOR mColorUR;
D3DCOLOR mColorDL;
D3DCOLOR mColorDR;
TUICallbackEvent mCallbackEvent;
CD3DTexture* mDefaultTexture;
std::vector< size_t > mFonts; // Index into mFontCache;
std::vector< CUIControl* > mControls;
std::vector< SElementHolder* > mDefaultElements;
SUIElement mCaptionElement; // element for the caption
/**
* Callback called inside rendering (before rendering controls), when
* all dialog render states are applied. Here one can arbitrarily
* call dialog's draw* functions (but otherwise don't mess with device state).
*/
TUICallbackRender mRenderCallback;
CUIDialog* mNextDlg;
CUIDialog* mPrevDlg;
int mDefaultCtrlID;
static double sTimeRefresh;
double mTimeLastRefresh;
CUIControl* mCtrlMouseOver; // The control which is hovered over
};
// --------------------------------------------------------------------------
struct SUIFontNode {
char facename[MAX_PATH];
ID3DXFont* font;
LONG height;
LONG weight;
};
// Manages shared resources of dialogs.
class CUIResourceManager : public IDeviceResource {
public:
static void initialize( int screenX, int screenY ) { assert(!mSingleInstance); mSingleInstance = new CUIResourceManager(screenX,screenY); }
static void finalize() { delete mSingleInstance; }
static CUIResourceManager& getInstance() { assert(mSingleInstance); return *mSingleInstance; }
public:
int addFont( const char* facename, LONG height, LONG weight );
SUIFontNode* getFontNode( size_t index ) { return mFontCache[ index ]; }
float xToBB( float x, int bbx ) const { return x * mInvScreenX * bbx; }
float yToBB( float y, int bby ) const { return y * mInvScreenY * bby; }
int bbToX( int bb, int bbx ) const { return bb * mScreenX / bbx; }
int bbToY( int bb, int bby ) const { return bb * mScreenY / bby; }
// IDeviceResource
virtual void createResource();
virtual void activateResource();
virtual void passivateResource();
virtual void deleteResource();
// Shared between all dialogs
IDirect3DStateBlock9* mStateBlock;
ID3DXSprite* mSprite; // Sprite used for drawing
protected:
static CUIResourceManager* mSingleInstance;
CUIResourceManager( int screenX, int screenY );
~CUIResourceManager();
HRESULT createFont( size_t index );
private:
std::vector< SUIFontNode* > mFontCache; // Shared fonts
int mScreenX;
int mScreenY;
float mInvScreenX;
float mInvScreenY;
};
// --------------------------------------------------------------------------
// Base class for controls
class CUIControl : public boost::noncopyable {
public:
CUIControl( CUIDialog *dialog = NULL );
virtual ~CUIControl();
//
// Overridables
virtual HRESULT onInit() { return S_OK; }
virtual void refresh();
virtual void render( IDirect3DDevice9* device, float dt ) { };
virtual bool msgProc( UINT msg, WPARAM wParam, LPARAM lParam ) { return false; }
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam ) { return false; }
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam ) { return false; }
virtual bool canHaveFocus() const { return false; }
virtual void onFocusIn() { mHasFocus = true; }
virtual void onFocusOut() { mHasFocus = false; }
virtual void onMouseEnter() { mMouseOver = true; }
virtual void onMouseLeave() { mMouseOver = false; }
virtual void onHotkey() {}
virtual bool containsPoint( const POINT& pt ) const { return mBBox.containsPoint( pt ); }
virtual void setEnabled( bool enabled ) { mEnabled = enabled; }
virtual bool isEnabled() const { return mEnabled; }
virtual void setVisible( bool vis ) { mVisible = vis; }
virtual bool isVisible() const { return mVisible; }
virtual void setTextColor( D3DCOLOR color );
//
// Getters/setters
eUIControlType getType() const { return mType; }
int getID() const { return mID; }
void setID( int cid ) { mID = cid; }
void setLocation( float x, float y ) { mX = x; mY = y; updateRects(); }
void setSize( float width, float height ) { mWidth = width; mHeight = height; updateRects(); }
void setHotkey( UINT hotkey ) { mHotkey = hotkey; }
UINT getHotkey() const { return mHotkey; }
void setUserData( void *userdata ) { mUserData = userdata; }
void *getUserData() const { return mUserData; }
SUIElement* getElement( size_t index ) { return mElements[ index ]; }
HRESULT setElement( size_t index, SUIElement* element );
//
// Public members
bool mVisible; // Shown/hidden flag
bool mMouseOver; // Mouse pointer is above control
bool mHasFocus; // Control has input focus
bool mDefault; // Is the default control
// Size, scale, and positioning members
float mX, mY;
float mWidth, mHeight;
// These members are set by the container
CUIDialog* mDialog; // Parent container
size_t mIndex; // Index within the control list
std::vector< SUIElement* > mElements; // Display elements
protected:
virtual void updateRects();
SFRect mBBox; // Rectangle defining the active region of the control
int mID; // Control ID number
eUIControlType mType; // Control type, set once in constructor
UINT mHotkey; // Virtual key code for this control's hotkey
void* mUserData; // Data associated with this control that is set by user.
bool mEnabled; // enabled/disabled flag
};
// --------------------------------------------------------------------------
/// Static control
class CUIStatic : public CUIControl {
public:
CUIStatic( CUIDialog *dialog = NULL );
// CUIControl
virtual void render( IDirect3DDevice9* device, float dt );
virtual bool containsPoint( const POINT& pt ) const { return false; }
HRESULT getTextCopy( char* strDest, size_t bufferCount );
const char* getText() const { return mText; }
HRESULT setText( const char* text );
protected:
char mText[MAX_PATH]; // Window text
};
// --------------------------------------------------------------------------
/// Image control
class CUIImage : public CUIControl {
public:
CUIImage( CUIDialog *dialog = NULL );
void setTexture( CD3DTexture& tex, int u0, int v0, int u1, int v1 ) {
RECT rc;
rc.left = u0; rc.right = u1;
rc.top = v0; rc.bottom = v1;
getElement(0)->setTexture( &tex, &rc );
}
// CUIControl
virtual void render( IDirect3DDevice9* device, float dt );
virtual bool containsPoint( const POINT& pt ) const { return false; }
};
// --------------------------------------------------------------------------
/// Button control
class CUIButton : public CUIStatic {
public:
CUIButton( CUIDialog *dialog = NULL );
// CUIControl
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void onHotkey() { mDialog->sendEvent( UIEVENT_BUTTON_CLICKED, true, this ); }
virtual bool containsPoint( const POINT& pt ) const { return mBBox.containsPoint( pt ); }
virtual bool canHaveFocus() const { return (mVisible && mEnabled); }
virtual void render( IDirect3DDevice9* device, float dt );
bool isPressed() const { return mPressed; }
protected:
eUIControlState getState() const;
bool mPressed;
};
// --------------------------------------------------------------------------
/// Check box control
class CUICheckBox : public CUIButton {
public:
CUICheckBox( CUIDialog *dialog = NULL );
// CUIControl
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void onHotkey() { setCheckedInternal( !mChecked, true ); }
virtual bool containsPoint( const POINT& pt ) const;
virtual void updateRects();
virtual void render( IDirect3DDevice9* device, float dt );
bool isChecked() const { return mChecked; }
void setChecked( bool chk ) { setCheckedInternal( chk, false ); }
protected:
virtual void setCheckedInternal( bool chk, bool fromInput );
bool mChecked;
SFRect mRectButton;
SFRect mRectText;
};
// --------------------------------------------------------------------------
/// Roll-out control
class CUIRollout : public CUICheckBox {
public:
CUIRollout( CUIDialog *dialog = NULL );
// CUIControl
//virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
//virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
//virtual void onHotkey() { setCheckedInternal( !mChecked, true ); }
virtual bool containsPoint( const POINT& pt ) const;
virtual void updateRects();
virtual void render( IDirect3DDevice9* device, float dt );
bool isExpanded() const { return isChecked(); }
void setExpanded( bool expanded ) { setChecked(expanded); }
float getRolloutHeight() const { return mRolloutHeight; }
void setRolloutHeight( float rh ) { mRolloutHeight = rh; }
void addChildControl( CUIControl& ctrl ) { mChildControls.push_back( &ctrl ); }
/**
* Offset location of the rollout and all child controls.
*/
void offsetPos( float dx, float dy );
protected:
virtual void setCheckedInternal( bool chk, bool fromInput );
float mRolloutHeight;
std::vector<CUIControl*> mChildControls;
};
// --------------------------------------------------------------------------
/// Radio button control
class CUIRadioButton : public CUICheckBox {
public:
CUIRadioButton( CUIDialog *dialog = NULL );
// CUIControl
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void onHotkey() { setCheckedInternal( true, true, true ); }
void setChecked( bool chk, bool clearGroup = true ) { setCheckedInternal( chk, clearGroup, false ); }
void setButtonGroup( int group ) { mButtonGroup = group; }
int getButtonGroup() const { return mButtonGroup; }
protected:
virtual void setCheckedInternal( bool chk, bool clearGroup, bool fromInput );
int mButtonGroup;
};
// --------------------------------------------------------------------------
/// Scrollbar control
class CUIScrollBar : public CUIControl {
public:
CUIScrollBar( CUIDialog *dialog = NULL );
virtual ~CUIScrollBar();
// CUIControl
virtual bool msgProc( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void render( IDirect3DDevice9* device, float dt );
virtual void updateRects();
void setTrackRange( int start, int end );
int getTrackPos() const { return mPosition; }
void setTrackPos( int pos ) { mPosition = pos; capPosition(); updateThumbRect(); }
int getPageSize() const { return mPageSize; }
void setPageSize( int pageSize ) { mPageSize = pageSize; capPosition(); updateThumbRect(); }
void scroll( int delta ); // scroll by delta items (plus or minus)
void showItem( int index ); // Ensure that item index is displayed, scroll if necessary
protected:
/// Indicates the state of the arrow buttons.
enum eArrowState {
CLEAR, ///< No arrow is down
CLICKED_UP, ///< Up arrow clicked
CLICKED_DOWN, ///< Down arrow clicked
HELD_UP, ///< Up arrow is held down for sustained period
HELD_DOWN ///< Down arrow is held down for sustained period
};
void updateThumbRect();
void capPosition(); ///< Clips position at boundaries. Ensures it stays within legal range.
bool mShowThumb;
bool mDragging;
SFRect mRectUp;
SFRect mRectDown;
SFRect mRectTrack;
SFRect mRectThumb;
int mPosition; // Position of the first displayed item
int mPageSize; // How many items are displayable in one page
int mStart; // First item
int mEnd; // The index after the last item
POINT mLastMouse; // Last mouse position
eArrowState mArrows; // State of the arrows
double mLastArrowTime; // Timestamp of last arrow event.
};
// --------------------------------------------------------------------------
struct SUIListItem {
char text[256];
const void* data;
SFRect activeRect;
bool selected;
};
/// List box control
class CUIListBox : public CUIControl {
public:
enum eStyle {
MULTISELECTION = 1,
};
public:
CUIListBox( CUIDialog *dialog = NULL );
virtual ~CUIListBox();
// CUIControl
virtual bool msgProc( UINT msg, WPARAM wParam, LPARAM lParam );
virtual HRESULT onInit() { return mDialog->initControl( &mScrollBar ); }
virtual bool canHaveFocus() const { return (mVisible && mEnabled); }
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void render( IDirect3DDevice9* device, float dt );
virtual void updateRects();
DWORD getStyle() const { return mStyle; }
void setStyle( DWORD style ) { mStyle = style; }
void setScrollBarWidth( float width ) { mSBWidth = width; updateRects(); }
void setBorder( float border, float margin ) { mBorder = border; mMargin = margin; }
HRESULT addItem( const char *text, const void *data );
HRESULT insertItem( int index, const char *text, const void *data );
void removeItem( int index );
void removeItemByText( const char *text );
void removeItemByData( const void *data );
void removeAllItems();
size_t getItemCount() const { return mItems.size(); }
SUIListItem* getItem( int index );
int getSelectedIndex( int prevSelected = -1 ) const;
SUIListItem* getSelectedItem( int prevSelected = -1 ) { return getItem( getSelectedIndex( prevSelected ) ); }
void selectItem( int newIndex );
protected:
CUIScrollBar mScrollBar;
SFRect mRectText; // Text rendering bound
SFRect mRectSelection; // Selection box bound
float mSBWidth;
float mBorder;
float mMargin;
float mTextHeight;// Height of a single line of text
DWORD mStyle; // List box style
int mSelected; // Index of the selected item for single selection list box
int mSelStart; // Index of the item where selection starts (for handling multi-selection)
bool mDragging; // Whether the user is dragging the mouse to select
std::vector< SUIListItem* > mItems;
};
// --------------------------------------------------------------------------
struct SUIComboItem {
char text[256];
const void* data;
SFRect activeRect;
bool vis;
};
/// ComboBox control
class CUIComboBox : public CUIButton {
public:
CUIComboBox( CUIDialog *dialog = NULL );
virtual ~CUIComboBox();
// CUIControl
virtual void setTextColor( D3DCOLOR color );
virtual HRESULT onInit() { return mDialog->initControl( &mScrollBar ); }
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void onHotkey();
virtual bool canHaveFocus() const { return (mVisible && mEnabled); }
virtual void onFocusOut();
virtual void render( IDirect3DDevice9* device, float dt );
virtual void updateRects();
HRESULT addItem( const char* text, const void* data, bool updateSelectionIf1st );
void removeAllItems();
void removeItem( size_t index );
bool containsItem( const char* text, size_t start=0 ) const;
int findItem( const char* text, size_t start=0 ) const;
const void* getItemData( const char* text );
void setDropHeight( float height ) { mDropHeight = height; updateRects(); }
void setScrollBarWidth( float width ) { mSBWidth = width; updateRects(); }
const void* getSelectedData();
SUIComboItem* getSelectedItem();
size_t getItemCount() const { return mItems.size(); }
SUIComboItem* getItem( size_t index ) { return mItems[ index ]; }
HRESULT setSelectedByIndex( int index );
HRESULT setSelectedByText( const char* text );
HRESULT setSelectedByData( const void* data );
protected:
CUIScrollBar mScrollBar;
SFRect mRectText;
SFRect mRectButton;
SFRect mRectDropdown;
SFRect mRectDropdownText;
int mSelected;
int mFocused;
float mDropHeight;
float mSBWidth;
bool mOpened;
std::vector< SUIComboItem* > mItems;
};
// --------------------------------------------------------------------------
/// Slider control
class CUISlider : public CUIControl {
public:
CUISlider( CUIDialog *dialog = NULL );
// CUIControl
virtual bool containsPoint( const POINT& pt ) const;
virtual bool canHaveFocus() const { return (mVisible && mEnabled); }
virtual bool handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam );
virtual bool handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam );
virtual void updateRects();
virtual void render( IDirect3DDevice9* device, float dt );
void setValue( int value ) { setValueInternal( value, false ); }
int getValue() const { return mValue; };
void setRange( int vmin, int vmax );
protected:
void setValueInternal( int value, bool fromInput );
int getValueFromPos( int x );
SFRect mRectButton;
int mValue;
int mMin;
int mMax;
int mDragStartX; // Mouse position at start of drag
int mDragOffset; // Drag offset from the center of the button
float mButtonX;
bool mPressed;
};
// --------------------------------------------------------------------------
// INLINE FUNCTIONS
inline bool CUIDialog::hasFocusControl() const
{
return sCtrlFocus && sCtrlFocus->mDialog == this && sCtrlFocus->isEnabled();
}
}; // namespace dingus
#endif // DXUT_GUI_H
| [
"[email protected]"
]
| [
[
[
1,
903
]
]
]
|
d7edc6b2fd5521021827d94df260c5eb191f55c5 | 333b818a4cb8e9dc3ddcbdac65a11f1c52cd2985 | /Mobile.h | 3610b34ca29b1767f350de73bb0f1ff822b8f721 | []
| no_license | noullet/firesimulation | 5ee51c0ed88d4807ad0fd3220b09d39324774be0 | 0a1e9dd7eaff3f20f01b8c97090fd12a3efcca82 | refs/heads/master | 2016-09-03T06:38:11.473207 | 2010-03-25T07:44:33 | 2010-03-25T07:44:33 | 32,204,918 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 303 | h | /////////////////////
// Fire Simulation //
// Nicolas Noullet //
// Bertrand Pagès //
/////////////////////
#if !defined(_MOBILE_H)
#define _MOBILE_H
class Mobile
{
public:
virtual void seDeplacer(string direction) = 0;
virtual string getDirection() = 0;
};
#endif //_MOBILE_H
| [
"pages.bertrand@6307593a-2cef-11df-aeb3-278f4910c8cc",
"nicolas.noullet@6307593a-2cef-11df-aeb3-278f4910c8cc"
]
| [
[
[
1,
9
],
[
11,
17
]
],
[
[
10,
10
]
]
]
|
b6bf3d88fdbbdeae98668dbfb022f08ff030cdd8 | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/SelectionManager.cpp | 4f66cfcc92670a095a43267d3128a5c0d185e96c | [
"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 | 10,693 | cpp | /*
* 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.
*/
#include "./SelectionManager.h"
#include "./Graphics.h"
#include "./Component.h"
#include "./event/MouseEvent.h"
#include "./FocusManager.h"
namespace ui
{
int SelectionManager::getRenderMode() const
{
return mode;
}
void SelectionManager::setRenderMode(int m)
{
// you have specified an invalid render mode.
assert(m == NORMAL || m == SELECTION);
mode = m;
}
void SelectionManager::beginUpdate(int x, int y)
{
mouseX = x;
mouseY = y;
// if(tempComponent != 0)
// {
// if(!tempComponent->getBounds().contains(x,y))
// {
tempComponent = getComponentAt(x,y);
// }
// }
// else
// {
// tempComponent = getComponentAt(x,y);
// }
}
SelectionManager::SelectionManager()
: mouseX(0),
mouseY(0),
lastX(0),
lastY(0),
foundComponent(0),
tempComponent(0),
hoverOverComponent(0),
pressed(false)
{
glGenTextures(1,&textureId);
glBindTexture(GL_TEXTURE_2D,textureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
SelectionManager::~SelectionManager()
{
}
Component* SelectionManager::getComponentAt(int x, int y) const
{
GLint viewport[4];
GLubyte pixel[3];
glGetIntegerv(GL_VIEWPORT,viewport);
glReadPixels(x,viewport[3]-y,1,1,GL_RGB,GL_UNSIGNED_BYTE,static_cast<void *>(pixel));
std::vector<ColorRegisterValue>::const_iterator iter;
for(iter = colorRegister.begin(); iter != colorRegister.end(); ++iter)
{
if(((*iter).color.red == pixel[0] && (*iter).color.green == pixel[1] && (*iter).color.blue == pixel[2]) ||
((*iter).textureColor.red == pixel[0] && (*iter).textureColor.green == pixel[1] && (*iter).textureColor.blue == pixel[2]))
{
//colorRegister.erase((*iter));
//break;
return (*iter).comp;
}
}
/*
for(int i = 0; i < static_cast<int>(pickingList.size()); ++i)
{
int index = pickingList[i].first;
// set seed, and check with the found colors
srand(index*2);
int red = (rand() % 255);
int green = (rand() % 255);
int blue = (rand() % 255);
if((pixel[0] == red) && (pixel[1] == green) && (pixel[2] == blue))
{
return pickingList[i].second;
}
//if(((pixel[0] - 3) == red) && (pixel[1] == green) && ((pixel[2] - 3) == blue))
//{
// return pickingList[i].second;
//}
}
*/
// fprintf(stderr,"%d %d %d\n",pixel[0],pixel[1],pixel[2]);
return 0;
}
void SelectionManager::mouseMotion(int x, int y)
{
if(foundComponent != 0 && pressed)
{
if(lastX == 0 && lastY == 0)
{
lastX = x;
lastY = y;
}
int draggedX = x - lastX;
int draggedY = y - lastY;
event::MouseEvent dragEvent(foundComponent,event::MouseEvent::MOUSE_DRAGGED,draggedX,draggedY,buttonPressed);
foundComponent->processMouseEvent(dragEvent);
lastX = x;
lastY = y;
}
if(foundComponent != 0)
{
event::MouseEvent motionEvent(foundComponent,event::MouseEvent::MOUSE_MOTION,x,y,0);
foundComponent->processMouseEvent(motionEvent);
}
if(tempComponent != hoverOverComponent)
{
if(hoverOverComponent != 0)
{
event::MouseEvent exitEvent(hoverOverComponent,event::MouseEvent::MOUSE_EXITED,mouseX,mouseY,0);
hoverOverComponent->processMouseEvent(exitEvent);
}
if(tempComponent != 0)
{
// send enter to f
event::MouseEvent enterEvent(tempComponent,event::MouseEvent::MOUSE_ENTERED,mouseX,mouseY,0);
tempComponent->processMouseEvent(enterEvent);
}
hoverOverComponent = tempComponent;
}
else if(tempComponent == 0)
{
if(hoverOverComponent != 0)
{
event::MouseEvent exitEvent(hoverOverComponent,event::MouseEvent::MOUSE_EXITED,mouseX,mouseY,0);
hoverOverComponent->processMouseEvent(exitEvent);
}
}
}
void SelectionManager::mousePressed(int button)
{
foundComponent = tempComponent;
if(foundComponent != 0)
{
event::MouseEvent event(foundComponent,event::MouseEvent::MOUSE_PRESSED,mouseX,mouseY,button);
foundComponent->processMouseEvent(event);
// also set focus
if(foundComponent->hasFocusListener())
FocusManager::getInstance().setPermanentFocusOwner(foundComponent);
}
else
{
FocusManager::getInstance().setPermanentFocusOwner(0);
}
pressed = true;
buttonPressed = button;
}
void SelectionManager::mouseReleased(int button)
{
if(foundComponent != 0)
{
event::MouseEvent event(foundComponent,event::MouseEvent::MOUSE_RELEASED,mouseX,mouseY,button);
foundComponent->processMouseEvent(event);
// check if we're still in the Component by comparing the hoverOverComponent with foundComponent.
if(foundComponent == hoverOverComponent)
{
// yes, we count this as an official click!
event::MouseEvent mouseClickEvent(foundComponent,event::MouseEvent::MOUSE_CLICKED,mouseX,mouseY,button);
foundComponent->processMouseEvent(mouseClickEvent);
}
}
pressed = false;
lastX = 0;
lastY = 0;
buttonPressed = -1;
}
void SelectionManager::addComponent(Component* comp)
{
// check to see if it's already here
if(getComponentId(comp) == -1)
{
ColorRegisterValue val;
val.index = idCounter;
val.comp = comp;
// pickingList.push_back(std::make_pair<int, Component*>(idCounter,comp));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushAttrib(GL_ALL_ATTRIB_BITS);
glViewport(0,0,64,64);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0,64,64,0);
//gluOrtho2D(0,800,600,0);
srand(idCounter*2);
GLubyte red = rand() % 255;
GLubyte green = rand() % 255;
GLubyte blue = rand() % 255;
glColor3ub(red,green,blue);
//glColor3f(1.0f,1.0f,0.0f);
glBegin(GL_QUADS);
glVertex3f(0, 0, 0.0f); // Top Left
glVertex3f(64, 0, 0.0f); // Top Right
glVertex3f(64, 64, 0.0f); // Bottom Right
glVertex3f(0,64, 0.0f); // Bottom Left
glEnd();
//ui::Frame::paint(g);
GLubyte pixel[3];
glReadPixels(10,10,1,1,GL_RGB,GL_UNSIGNED_BYTE,static_cast<void *>(pixel));
IntegerColor color(pixel[0],pixel[1],pixel[2]);
val.color = color;
//fprintf(stderr,"glColor: %d %d %d\n",pixel[0],pixel[1],pixel[2]);
glBindTexture(GL_TEXTURE_2D,textureId);
glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,64,64);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,textureId);
glBegin(GL_QUADS);
glTexCoord2f(0.0f,0.0f);
glVertex3f(0.0f,0.0f,0.0f);
glTexCoord2f(1.0f,0.0f);
glVertex3f(64.0f,0.0f,0.0f);
glTexCoord2f(1.0f,1.0f);
glVertex3f(64.0f,64.0f,0.0f);
glTexCoord2f(0.0f,1.0f);
glVertex3f(0.0f,64.0f,0.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
glReadPixels(10,10,1,1,GL_RGB,GL_UNSIGNED_BYTE,static_cast<void *>(pixel));
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
IntegerColor textureColor(pixel[0],pixel[1],pixel[2]);
val.textureColor = textureColor;
//colorRegister[idCounter] = std::make_pair<color,textureColor>;
//colorRegister.assign(idCounter,std::make_pair<IntegerColor,util::Color>(color,textureColor));
//fprintf(stderr,"texture: %d %d %d\n\n",pixel[0],pixel[1],pixel[2]);
//glClear(
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPopMatrix();
glPopAttrib();
colorRegister.push_back(val);
idCounter++;
}
}
void SelectionManager::removeComponent(Component* comp)
{
std::vector<ColorRegisterValue>::iterator iter;
for(iter = colorRegister.begin(); iter != colorRegister.end(); ++iter)
{
if((*iter).comp == comp)
{
colorRegister.erase(iter);
break;
}
}
/*
std::vector< std::pair<int, Component *> >::iterator iter;
for(iter = pickingList.begin(); iter != pickingList.end(); ++iter)
{
if((*iter).second == comp)
{
pickingList.erase(iter);
break;
}
}
*/
}
int SelectionManager::getComponentId(const Component* comp) const
{
/*
for(int i = 0; i < static_cast<int>(pickingList.size()); ++i)
{
if(comp == pickingList[i].second)
return pickingList[i].first;
}
*/
std::vector<ColorRegisterValue>::const_iterator iter;
for(iter = colorRegister.begin(); iter != colorRegister.end(); ++iter)
{
if((*iter).comp == comp)
{
return (*iter).index;
}
}
return -1;
}
} | [
"bs@bram.(none)"
]
| [
[
[
1,
398
]
]
]
|
ce9221e86ccc0888e6c5d7f867668b8fb2412b24 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testmisc/spawnchild/src/TPopen3FdTransfer.cpp | 8b9a9546e9eddb2d1cc8e674ba47ce7fa320855e | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | 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 "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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
int main()
{
char buf[20];
int fd1 = open("C:\\SharedFile.txt",O_RDWR);
if(fd1 <= 0)
{
return -1 ;
}
int i = 0 ;
do
{
if(read(fd1,&buf[i],1) == -1)
return -1;
}while(buf[i++]);
int fd = atoi(buf);
if(write(fd,"testing",7) == -1)
{
return -1;
}
if(read(fd,buf,7) == -1)
{
return -1;
}
close(fd1);
close(fd);
return 0;
}
| [
"none@none"
]
| [
[
[
1,
59
]
]
]
|
a01e414fd0ebf3a36778ba2e98460d37a2678415 | bb3a97270bfef3df38aeaf17b4d6a8e33bef3032 | /kinect_headtracking/KVertex.h | 1850452e7293e4baed7b58da0d8fa03f9ccfbd09 | []
| no_license | amrzagloul/kinect_lab | b10514ccabca4800bcaa9ae45df5c47bc423f5f7 | 871e3ec00ee035d7d8ad5074d92a63856b20a834 | refs/heads/master | 2021-01-21T01:33:49.469635 | 2011-03-22T15:46:47 | 2011-03-22T15:46:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | h | #pragma once
#include <cstdlib>
//#include <gl/glut.h>
#ifdef USE_GLUT
#if (XN_PLATFORM == XN_PLATFORM_MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#else
#include "opengles.h"
#endif
// Helper-struct
struct KRGBColor
{
KRGBColor(float _r, float _g, float _b){
r = _r;
g = _g;
b = _b;
}
KRGBColor(){
r = 0;
g = 0;
b = 0;
}
float r;
float g;
float b;
};
class KVertex
{
public:
KVertex(void);
KVertex(float x, float y, float z, KRGBColor color);
~KVertex(void);
// Makes glVertex3f and glColor3f
void paintVertex(void);
// sets the color
void setColor(float r, float g, float b);
// Saves the coordinates of the vertex
float mX,mY,mZ;
//Saves the color of the
KRGBColor mColor;
};
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
adecbcd66d0a86cad17408b6d3472b71a3bac5b3 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/audio/MglDirectShowBase.cpp | e43dcfceec5887f7d4ac48e9a7f44d295ba709ee | []
| no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 10,499 | cpp | //////////////////////////////////////////////////////////
//
// MglDirectShowBase
// - DirectMusicクラス
//
//////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MglDirectShowBase.h"
/*
#ifdef _DEBUG
#pragma comment(lib, "Strmbasd.lib")
#else
#pragma comment(lib, "Strmbase.lib")
#endif//_DEBUG
*/
//template class DLL_EXP std::map<std::string,IDirectMusicSegment8*>;
#define ENBL_CHK() if(m_flgEnable!=TRUE)return;
/* log2(x)の計算を行う */
double _MGL_log2(double x)
{
const double y=1;
__asm {
; st(0)=x, st(1)=y と入れておく
; exp(y * log(x))を求める
fld y;
fld x;
fyl2x;
fstp x;
}
return x;
}
// コンストラクタ
CMglDirectShowBase::CMglDirectShowBase()
{
m_pGraph = NULL;
m_pControl = NULL;
m_pEvent = NULL;
m_pSeeking = NULL;
m_pAudioRendererFilter = NULL;
m_pBasicAudio = NULL;
m_bRunReady = FALSE;
//m_bPausing = TRUE; TRUEにすると初期でPause()押しても再生される。・・・まぁ普通は再生されてないのにPauseで再生されるのはちょっと違うだろう・・・
m_bPausing = FALSE;
m_hWnd = NULL;
}
// デストラクタ
CMglDirectShowBase::~CMglDirectShowBase()
{
Release();
}
// 開放
void CMglDirectShowBase::Release()
{
SAFE_RELEASE(m_pGraph);
SAFE_RELEASE(m_pControl);
SAFE_RELEASE(m_pEvent);
SAFE_RELEASE(m_pSeeking);
SAFE_RELEASE(m_pAudioRendererFilter);
SAFE_RELEASE(m_pBasicAudio);
}
// 初期化
void CMglDirectShowBase::Init( HWND hWnd )
{
CMglStackInstance("CMglDirectShowBase::Init");
if ( hWnd == NULL )
hWnd = GetDefaultHwnd();
m_hWnd = hWnd;
// フィルタグラフのインスタンスを生成
MyuAssert( CoCreateInstance(CLSID_FilterGraph, NULL,
CLSCTX_INPROC_SERVER, IID_IGraphBuilder,
(void**)&m_pGraph), S_OK,
"CMglDirectShowBase::Init() CoCreateInstance(IGraphBuilder)に失敗。" );
// フィルタグラフからIMediaControlを取得する
MGL_H_ASSERT( m_pGraph->QueryInterface(IID_IMediaControl, (void **)&m_pControl) );
// MyuAssert( m_pGraph->QueryInterface(IID_IMediaControl, (void **)&m_pControl), S_OK,
// "CMglDirectShowBase::Init() QueryInterface(IMediaControl)に失敗。" );
// フィルタグラフからIMediaEventを取得する
MyuAssert( m_pGraph->QueryInterface(IID_IMediaEvent, (void **)&m_pEvent), S_OK,
"CMglDirectShowBase::Init() QueryInterface(IMediaEvent)に失敗。" );
// フィルタグラフからIMediaSeekingを取得する
MyuAssert( m_pGraph->QueryInterface(IID_IMediaSeeking, (void **)&m_pSeeking), S_OK,
"CMglDirectShowBase::Init() QueryInterface(IMediaSeeking)に失敗。" );
EnableAudioExControl();
}
// 読み込み
void CMglDirectShowBase::Load( const char* szMediaFile )
{
InitCheck();
WCHAR wstrFileName[32000*2+1];
ZeroMemory( wstrFileName, sizeof(wstrFileName) );
MultiByteToWideChar(CP_ACP, 0, szMediaFile, strlen(szMediaFile), wstrFileName, sizeof(wstrFileName));
// 再生するファイルを指定する
HRESULT hRet = m_pGraph->RenderFile(wstrFileName, NULL);
switch( hRet )
{
case S_OK:
break;
case VFW_S_AUDIO_NOT_RENDERED: // オーディオ ストリームを再生できない。適切なレンダラが見つからなかった。
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" はサポートしていないオーディオストリームです。", szMediaFile );
case VFW_S_VIDEO_NOT_RENDERED: // ビデオ ストリームを再生できない。適切なレンダラが見つからなかった。
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" はサポートしていないビデオストリームです。", szMediaFile );
case VFW_S_PARTIAL_RENDER: // このムービーにサポートされないフォーマットのストリームが含まれている。
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" はサポートしていないムービーストリームを含みます。", szMediaFile );
case E_INVALIDARG:
MyuThrow( hRet, "CMglDirectShowBase::Load() 引数が異常です。" );
case E_OUTOFMEMORY:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" を再生するのに十分なメモリがありません。", szMediaFile );
case VFW_E_CANNOT_CONNECT:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" 接続を確立する中間フィルタの組み合わせが見つからなかった。", szMediaFile );
case VFW_E_CANNOT_LOAD_SOURCE_FILTER:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" のソース フィルタをロードできない。", szMediaFile );
case VFW_E_CANNOT_RENDER:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" ストリームをレンダリングするフィルタの組み合わせが見つからなかった。", szMediaFile );
case VFW_E_INVALID_FILE_FORMAT:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイルフォーマットが無効です。 %s", szMediaFile );
case VFW_E_NOT_FOUND:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" が見つかりません。", szMediaFile );
case VFW_E_NOT_IN_GRAPH:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" フィルタ グラフに存在しないオブジェクトに要求された関数を実行できない。", szMediaFile );
case VFW_E_UNKNOWN_FILE_TYPE:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" のメディアタイプが認識出来ません。", szMediaFile );
case VFW_E_UNSUPPORTED_STREAM:
MyuThrow( hRet, "CMglDirectShowBase::Load() ファイル \"%s\" はサポートされていないメディア形式です。", szMediaFile );
default:
MyuThrow( hRet, "ファイル \"%s\" の読み込みに失敗。", szMediaFile );
}
SetVolume(100);
}
// 読み込んだのを破棄
void CMglDirectShowBase::Unload()
{
InitCheck();
//ENBL_CHK();
Release();
Init(m_hWnd);
#if 1 == 0
//IEnumFilters *pEnumFilters = NULL;
auto_release<IEnumFilters*> pEnumFilters = NULL;
MGL_H_ASSERT( m_pGraph->EnumFilters(&pEnumFilters) );
//ULONG ulFetched; NULLでいけるらしい
IBaseFilter *pFilter = NULL;
MGL_H_ASSERT( pEnumFilters->Next(1, &pFilter, NULL) );
MGL_H_ASSERT( m_pGraph->RemoveFilter(pFilter) );
// MGL_H_ASSERT2( m_pGraph->RemoveFilter(NULL), "CMglDirectShowBase::Unload()" );
// MyuAssert( m_pGraph->RemoveFilter(m_pGraph), S_OK,
// "CMglDirectShowBase::Unload() m_pGraph->RemoveFilter()に失敗。" );
pFilter->Release();
#endif
}
// 再生
inline void CMglDirectShowBase::Play()
{
InitCheck();
//ENBL_CHK();
if ( m_bPausing == FALSE )
{
/* 2009/09/13 まぁ、再生を押したらもう一回最初っから、が普通かねぇ? */
Stop();
}
/*MyuAssert( m_pControl->Run(), S_OK,
"CMglDirectShowBase::Play() m_pControl->Run()に失敗。" );*/
if ( m_pControl->Run() != S_OK ){
/*OAFilterState fs;
HRESULT hRet = S_FALSE;
for(int i=0; i<50; i++, Sleep(100)){
hRet = m_pControl->GetState(200,&fs);
if ( hRet != S_OK )
continue;
}
if ( hRet != S_OK ){
MyuThrow( hRet, "CMglDirectShowBase::Play() m_pControl->Run()に失敗。(GetState() failed.)" );
}*/
/*MyuAssert( m_pControl->GetState(1000,&fs), S_OK,
"CMglDirectShowBase::Play() m_pControl->GetState()に失敗。" );*/
//MyuThrow( 0, "CMglDirectShowBase::Play() m_pControl->Run()に失敗。" );
}
m_bPausing = FALSE;
}
// 停止
inline void CMglDirectShowBase::Stop()
{
InitCheck();
//ENBL_CHK();
MyuAssert( m_pControl->Stop(), S_OK,
"CMglDirectShowBase::Stop() m_pControl->Stop()に失敗。" );
SeekToHead();
}
// 一時停止
inline void CMglDirectShowBase::Pause()
{
InitCheck();
//ENBL_CHK();
if ( m_bPausing == TRUE )
Play();
else
{
//MyuAssert( m_pControl->Pause(), S_OK, // 再生してないとコケるっぽい。いっそそんならStopでいいじゃん(何
MyuAssert( m_pControl->Stop(), S_OK,
"CMglDirectShowBase::Pause() m_pControl->Pause()に失敗。" );
m_bPausing = TRUE;
}
}
// ボリュームの設定
inline void CMglDirectShowBase::SetVolume( int nVolume )
{
//EnableAudioExControl();
//m_pBasicAudio->put_Volume(nVolume*100-10000);
//long nVol = ( nVolume == -10000 ? 0 : _MGL_log2(100.0f/nVolume) * -1000 );
long nPutVol = -10000;
if ( nVolume != 0 )
nPutVol = _MGL_log2(100.0/nVolume) * -1000;
if ( nPutVol < -10000 )
nPutVol = -10000;
m_pBasicAudio->put_Volume( nPutVol );
}
// パン設定
inline void CMglDirectShowBase::SetBalance( int nBalance )
{
//EnableAudioExControl();
//m_pBasicAudio->put_Balance(nBalance*100);
long nPutPan = 0;
if ( nBalance != 0 )
nPutPan = _MGL_log2(100.0/ (100-( nBalance < 0 ? nBalance*-1 : nBalance)) ) * 1000;
if ( nBalance < 0 )
nPutPan *= -1;
m_pBasicAudio->put_Balance( nPutPan );
}
inline void CMglDirectShowBase::EnableAudioExControl()
{
if ( m_pAudioRendererFilter == NULL )
// 音声レンダラフィルター所得
MyuAssert( CoCreateInstance(CLSID_AudioRender, NULL,
CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&m_pAudioRendererFilter), S_OK,
"CMglDirectShowBase::EnableAudioExControl() CoCreateInstance(IBaseFilter)に失敗。" );
if ( m_pBasicAudio == NULL )
// IBasicAudioインターフェースの所得
MyuAssert( m_pAudioRendererFilter->QueryInterface(IID_IBasicAudio, (void**)&m_pBasicAudio), S_OK,
"CMglDirectShowBase::EnableAudioExControl() QueryInterface(IID_IBasicAudio)に失敗。" );
m_pGraph->AddFilter(m_pAudioRendererFilter, NULL);
}
// 位置変更
void CMglDirectShowBase::SeekTo( long nSeekTime, DWORD dwFlg )
{
InitCheck();
LONGLONG llSeekTime = nSeekTime;
DWORD dwCurrentFlags = 0;
switch(dwFlg)
{
case SEEK_SET: dwCurrentFlags = AM_SEEKING_AbsolutePositioning; break;
case SEEK_CUR: dwCurrentFlags = AM_SEEKING_RelativePositioning; break;
default:
MyuThrow(41166, "CMglDirectShowBase::SeekTo() dwFlg = %d は不明です。", dwFlg);
}
//先頭位置に設定する
MyuAssert( m_pSeeking->SetPositions(&llSeekTime,
dwCurrentFlags, NULL, AM_SEEKING_NoPositioning), S_OK,
"CMglDirectShowBase::SeekTo() m_pSeeking->SetPositions()に失敗。" );
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
]
| [
[
[
1,
320
]
]
]
|
b9b706d462a4277fae442c6a5be11309af8d743d | 847cccd728e768dc801d541a2d1169ef562311cd | /src/ResourceSystem/XMLOutput.cpp | 0ab5b42933242212dac735d149e78e61a6d718dc | []
| no_license | aadarshasubedi/Ocerus | 1bea105de9c78b741f3de445601f7dee07987b96 | 4920b99a89f52f991125c9ecfa7353925ea9603c | refs/heads/master | 2021-01-17T17:50:00.472657 | 2011-03-25T13:26:12 | 2011-03-25T13:26:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,655 | cpp | #include "Common.h"
#include "XMLOutput.h"
using namespace ResourceSystem;
XMLOutput::XMLOutput(const string& fileName, const string& indentStr)
: mOutStream(), mElementStack(), mElementOpen(false), mElementLast(false), mIndentStr(indentStr)
{
mOutStream.open(fileName.c_str());
mOutStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
}
XMLOutput::~XMLOutput()
{
CloseAndReport();
}
bool XMLOutput::CloseAndReport()
{
if (!mOutStream.is_open()) { return false; }
while (!mElementStack.empty()) { EndElement(); }
bool result = mOutStream.good();
mOutStream.clear();
mOutStream.close();
return result && mOutStream.good();
}
void XMLOutput::BeginElementStart(const string& name)
{
OC_ASSERT(!mElementOpen);
WriteNewLine();
mOutStream << "<" << name;
mElementOpen = true;
mElementStack.push(name);
}
void XMLOutput::AddAttribute(const string& key, const string& value)
{
OC_ASSERT(mElementOpen);
mOutStream << " " << key << "=\"" << value << "\"";
}
void XMLOutput::BeginElementFinish()
{
OC_ASSERT(mElementOpen);
mOutStream << ">";
mElementOpen = false;
mElementLast = true;
}
void XMLOutput::EndElement()
{
OC_ASSERT(!mElementOpen && !mElementStack.empty());
string name = mElementStack.top();
mElementStack.pop();
if (!mElementLast) { WriteNewLine(); }
mOutStream << "</" << name << ">";
mElementLast = false;
}
void XMLOutput::WriteNewLine()
{
mOutStream << std::endl;
for (uint32 i = 0; i < mElementStack.size(); ++i)
{
mOutStream << mIndentStr;
}
}
void XMLOutput::WriteString(const string &str)
{
mOutStream << str;
} | [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
dbda09ee06ed46f6ca2e7960c9ba0c95fbcda83d | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Scd/ScHist/HSTSLOTS.CPP | 90b063e9a16f2e12ad81521e71eaa098444aa0df | []
| 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 | 26,553 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#if ForSysCAD
#include "sc_defs.h"
#include "errorlog.h"
#else
#include <math.h>
#endif
#include "hstblks.h"
#include "hstslots.h"
#ifndef __AFXTEMPL_H__
#include <afxtempl.h> // "xafxtempl.h"
#endif
#include "hstmain.h"
#define dbgHistorian 1
#if dbgHistorian
#include "dbgmngr.h"
static CDbgMngr dbgHistTag("Historian", "HistTag");
#endif
//===========================================================================
IMPLEMENT_MEMSTATS(CFilter)
IMPLEMENT_MEMSTATS(CBoxcar)
IMPLEMENT_MEMSTATS(CSlot)
//===========================================================================
CFilter::CFilter()
{
memset(&Data, 0, sizeof(Data));
iSampleNo = 0;
iNSamples = 0;
pList = NULL;
iListLen = 0;
dSigma = 1.0;
pSlot = NULL;
}
//---------------------------------------------------------------------------
CFilter::~CFilter()
{
if (pList)
delete []pList;
}
//---------------------------------------------------------------------------
void CFilter::Cfg(pSlotCfgInfo pSCI, pCSlot Slot)
{
pSlot = Slot;
if (pSCI)
{
Data.dFilterTau = pSCI->mFilterTau;
Data.dWinFltPeriod = pSCI->mWinFltPeriod;
Data.iWinFltCount = pSCI->mWinFltCount;
Data.iFilterAlg = pSCI->mFilterAlg;
Data.FltDeltaVal.SetTypeDouble(pSlot->Data.VarTyp, pSCI->mFltDelta);
}
if ( (Data.dWinFltPeriod > 0) &&
(Data.dFilterTau >= Data.dWinFltPeriod) )
dAlpha = Data.dWinFltPeriod / Data.dFilterTau;
else
dAlpha = 1.0;
FixList();
}
//---------------------------------------------------------------------------
void CFilter::FixList()
{
Data.iWinFltCount = Range((short)0, Data.iWinFltCount, (short)100);
if (Data.iWinFltCount != iListLen)
{
iListLen = Data.iWinFltCount;
if (pList)
delete[] pList;
pList = NULL;
iNSamples = 0;
iSampleNo = 0;
if (iListLen > 0)
{
pList = new DataUnion[iListLen];
for (int i=0; i<iListLen; i++)
pList[i].SetTypeDouble(pSlot->Data.VarTyp, 0.0);
}
}
}
//---------------------------------------------------------------------------
void CFilter::DoFilter()
{
flag IsFirst = pSlot->bFirstValue;
if (pSlot->Data.iPrevStatus == TS_STATUS_INVALID)
{
iNSamples = 0;
iSampleNo = 0;
IsFirst = true;
}
if ((Data.iFilterAlg & HSFA_MovingAve) != 0)
{
if (Data.iWinFltCount > 1)
{
switch (pSlot->TSFlag)
{
case TS_BIT : break; //meaningless to filter it
case TS_DOUBLE:
case TS_FLOAT :
case TS_BYTE :
case TS_WORD :
case TS_DWORD :
case TS_INT16 :
case TS_LONG :
case TS_FLT16 :
{
long diff = pHistory->lScanNo - pSlot->lScanOfLastChange;
flag ForceCalc = (diff>1);
if (ForceCalc && !IsFirst)
{//value did not change between two consecutive iterations...
diff = min(Data.iWinFltCount, (short)diff) - 1;
short PrevNo = (iSampleNo + Data.iWinFltCount - 1) % Data.iWinFltCount;
for (short i=0; i<diff; i++)
{
if (iNSamples < Data.iWinFltCount)
iNSamples++;
pList[iSampleNo] = pList[PrevNo];
iSampleNo = (iSampleNo+1) % Data.iWinFltCount;
}
}
if (iNSamples < Data.iWinFltCount)
iNSamples++;
if (ForceCalc || iNSamples < Data.iWinFltCount || iSampleNo==0) // To Prevent Rounding Errors Accumulating
{
pList[iSampleNo] = pSlot->MeasVal;
dSigma = 0.0;
for (int i=0; i<iNSamples; i++)
dSigma += pList[i].GetDouble();
}
else
{
dSigma -= pList[iSampleNo].GetDouble();
pList[iSampleNo] = pSlot->MeasVal;
dSigma += pList[iSampleNo].GetDouble();
}
iSampleNo = (iSampleNo+1) % Data.iWinFltCount;
pSlot->MeasVal.SetTypeDouble(pSlot->Data.VarTyp, dSigma / iNSamples);
break;
}
default: ASSERT(FALSE);
}
}
}
if ((Data.iFilterAlg & HSFA_Tau)!=0)
{
if (dAlpha < 1.0 && !IsFirst)
{
switch (pSlot->TSFlag)
{
case TS_BIT : break; //meaningless to filter it
case TS_DOUBLE:
case TS_FLOAT :
case TS_BYTE :
case TS_WORD :
case TS_DWORD :
case TS_INT16 :
case TS_LONG :
case TS_FLT16 :
{
double Mv = pSlot->Data.PrevMeasVal.GetDouble();
double Nv = pSlot->MeasVal.GetDouble();
if (fabs(Nv-Mv) < Data.FltDeltaVal.GetDouble())
{
Nv = dAlpha * Nv + (1.0 - dAlpha) * Mv;
pSlot->MeasVal.SetTypeDouble(pSlot->Data.VarTyp, Nv);
}
}
break;
default : ASSERT(FALSE);
break;
}
}
}
}
//---------------------------------------------------------------------------
flag CFilter::Save(CFile & F)
{
F.Write((void*)&(Data), sizeof(HD_FilterInfo));
return true;
}
//---------------------------------------------------------------------------
flag CFilter::Load(CFile & F)
{
F.Read((void*)&(Data), sizeof(HD_FilterInfo));
return true;
}
//===========================================================================
CBoxcar::CBoxcar()
{
memset(&Data, 0, sizeof(Data));
pSlot = NULL;
}
//---------------------------------------------------------------------------
void CBoxcar::Cfg(pSlotCfgInfo pSCI, pCSlot Slot)
{
pSlot = Slot;
if (pSCI)
{
Data.dDeltaLo = pSCI->mDeltaLo;
Data.dDeltaHi = Max(pSCI->mDeltaHi, Data.dDeltaLo);
Data.dChange = pSCI->mChange;
Data.iNoRec = pSCI->mNoRec;
Data.iNoNotRec = pSCI->mNoNotRec;
Data.iBoxcarAlg = pSCI->mBoxcarAlg;
}
AveVal = 0.0;
AveCnt = 0L;
NoRec = 0;
NoNotRec = 0;
Data.dDeltaVal = (Data.dDeltaLo + Data.dDeltaHi) / 2.0;
}
//---------------------------------------------------------------------------
flag CBoxcar::CheckChanges()
{
AveVal = (AveVal * AveCnt);
long diff = pHistory->lScanNo - pSlot->lScanOfLastChange;
AveCnt += diff;
AveVal = (AveVal + (pSlot->MeasVal.GetDouble() * diff)) / AveCnt;
flag Changed = false;
switch(Data.iBoxcarAlg)
{
case HSA_Boxcar:
switch (pSlot->TSFlag)
{
case TS_DOUBLE:
case TS_FLOAT :
case TS_BYTE :
case TS_WORD :
case TS_DWORD :
case TS_INT16 :
case TS_LONG :
case TS_FLT16 :
{
if (fabs(pSlot->Data.PrevSaveVal.GetDouble() - AveVal) > Data.dDeltaLo)
Changed = true;
break;
}
case TS_BIT:
if (pSlot->MeasVal.GetLong() != pSlot->Data.PrevSaveVal.GetLong())
Changed = true;
default: ASSERT(FALSE); //type not supported ???
}
break;
case HSA_AdaptiveBoxcar:
switch (pSlot->TSFlag)
{
case TS_DOUBLE:
case TS_FLOAT :
case TS_BYTE :
case TS_WORD :
case TS_DWORD :
case TS_INT16 :
case TS_LONG :
case TS_FLT16 :
{
if (fabs(pSlot->Data.PrevSaveVal.GetDouble() - AveVal) > Data.dDeltaVal)
Changed = true;
break;
}
case TS_BIT:
if (pSlot->MeasVal.GetLong() != pSlot->Data.PrevSaveVal.GetLong())
Changed = true;
default: ASSERT(FALSE); //type not supported ???
}
if (Changed)
{
NoRec++;
if (NoRec>Data.iNoRec)
{
Data.dDeltaVal = Min(Data.dDeltaVal+Data.dChange, Data.dDeltaHi);
NoRec = 1;
}
NoNotRec = 0;
}
else
{
NoNotRec++;
if (NoNotRec>Data.iNoNotRec)
{
Data.dDeltaVal = Max(Data.dDeltaVal-Data.dChange, Data.dDeltaLo);
NoNotRec = 1;
}
NoRec = 0;
}
break;
case HSA_None:
break;
}
return Changed;
}
//---------------------------------------------------------------------------
flag CBoxcar::Save(CFile & F)
{
F.Write((void*)&(Data), sizeof(HD_BoxcarInfo));
return true;
}
//---------------------------------------------------------------------------
flag CBoxcar::Load(CFile & F)
{
F.Read((void*)&(Data), sizeof(HD_BoxcarInfo));
return true;
}
//===========================================================================
CSlot::CSlot()
{
Initialise();
}
//---------------------------------------------------------------------------
CSlot::~CSlot()
{
if (pFilter)
delete pFilter;
if (pBoxcar)
delete pBoxcar;
}
//---------------------------------------------------------------------------
void CSlot::Initialise()
{
memset(&Data, 0, sizeof(Data));
Data.lSlotID = 0xFFFFFFFF;
lSNo = -1;
iStatus = 0;
TSFlag = 0;
bFirstValue = false;
bIsRecording = false;
m_bVariesWithinTol=false;
m_bChangedDuringPause=false;
pFilter = NULL;
pBoxcar = NULL;
lScanOfLastSave = pHistory->lScanNo;
lScanOfLastChange = pHistory->lScanNo;
dwWriteCnt = 0;
dwChangeCnt = 0;
iCnvNo = 0;
}
//---------------------------------------------------------------------------
void CSlot::Configure(DWORD SlotID, long SNo)
{//configures NEW slot
bWriteMidTime = 1;
bFirstValue = 1;
m_bVariesWithinTol=false;
m_bChangedDuringPause=false;
Data.lSlotID = SlotID;
lSNo = SNo;
}
//---------------------------------------------------------------------------
void CSlot::Configure(long SNo)
{//configures OLD slot
bFirstValue = false;
m_bVariesWithinTol=false;
m_bChangedDuringPause=false;
lSNo = SNo;
switch (Data.VarTyp)
{
case tt_Bool :
case tt_Bit : TSFlag = TS_BIT; break;
case tt_Char :
case tt_Byte : TSFlag = TS_BYTE; break;
case tt_Short : TSFlag = TS_INT16; break;
case tt_Word : TSFlag = TS_WORD; break;
case tt_DWord : TSFlag = TS_DWORD; break;
case tt_Long : TSFlag = TS_LONG; break;
case tt_Float : TSFlag = TS_FLOAT; break;
case tt_Double : TSFlag = TS_DOUBLE; break;
case tt_Flt16 : TSFlag = TS_FLT16; break;
case tt_Int : TSFlag = TS_LONG; break;
case tt_Strng : TSFlag = TS_STR; break;
default: ASSERT(FALSE); //data type not supported
}
}
//---------------------------------------------------------------------------
void CSlot::Cfg(pSlotCfgInfo pSCI, flag NewSlot)
{
#if dbgHistorian && DBGMANAGER
if (dbgHistTag())
{
if (dbgHistTag.Items.Length()>0 && dbgHistTag.Items.Find(Data.sTag)!=NULL)
{ //place breakpoint here to see what is happening with a specific tag specified in syscad.dmf
dbgpln("Historian: tag %s configure", Data.sTag);
}
}
#endif
ASSERT(IsNumData(pSCI->mTyp) || (/*AllowHistStr &&*/ IsStrng(pSCI->mTyp)));
if (NewSlot)
{
Data.VarTyp = pSCI->mTyp;
Data.SetTag(pSCI->mTag);
bFirstValue = true;
m_bVariesWithinTol=false;
m_bChangedDuringPause=false;
Data.PrevMeasVal.SetTypeDouble(Data.VarTyp, 0.0);
Data.PrevMeasVal.SetStatus(ds_NAN);
Data.PrevSaveVal.SetTypeDouble(Data.VarTyp, 0.0);
Data.PrevSaveVal.SetStatus(ds_NAN);
Data.PrevActualVal.SetTypeDouble(Data.VarTyp, 0.0);
Data.PrevActualVal.SetStatus(ds_NAN);
Data.dPrevTime = 0.0;
Data.iPrevStatus = TS_STATUS_INVALID;
MeasVal.SetTypeDouble(Data.VarTyp, 0.0);
MeasVal.SetStatus(ds_NAN);
switch (Data.VarTyp)
{
case tt_Bool :
case tt_Bit : TSFlag = TS_BIT; break;
case tt_Char :
case tt_Byte : TSFlag = TS_BYTE; break;
case tt_Short : TSFlag = TS_INT16; break;
case tt_Word : TSFlag = TS_WORD; break;
case tt_DWord : TSFlag = TS_DWORD; break;
case tt_Long : TSFlag = TS_LONG; break;
case tt_Float : TSFlag = TS_FLOAT; break;
case tt_Double : TSFlag = TS_DOUBLE; break;
case tt_Flt16 : TSFlag = TS_FLT16; break;
case tt_Int : TSFlag = TS_LONG; break;
case tt_Strng : TSFlag = TS_STR; break;
default: ASSERT(FALSE); //data type not supported
}
}
else
{
//ASSERT(Data.VarTyp==pSCI->mTyp); //cannot change data type !!!
if (Data.VarTyp != pSCI->mTyp)
{
LogWarning("History", 0, "Tag '%s' changing data type!", pSCI->mTag);
Data.VarTyp = pSCI->mTyp;
switch (Data.VarTyp)
{
case tt_Bool :
case tt_Bit : TSFlag = TS_BIT; break;
case tt_Char :
case tt_Byte : TSFlag = TS_BYTE; break;
case tt_Short : TSFlag = TS_INT16; break;
case tt_Word : TSFlag = TS_WORD; break;
case tt_DWord : TSFlag = TS_DWORD; break;
case tt_Long : TSFlag = TS_LONG; break;
case tt_Float : TSFlag = TS_FLOAT; break;
case tt_Double : TSFlag = TS_DOUBLE; break;
case tt_Flt16 : TSFlag = TS_FLT16; break;
case tt_Int : TSFlag = TS_LONG; break;
case tt_Strng : TSFlag = TS_STR; break;
default: ASSERT(FALSE); //data type not supported
}
FixTyp();
}
}
//general stuff...
strncpy(Data.sEng, pSCI->mEng, sizeof(Data.sEng));
strncpy(Data.sCnvFam, pSCI->mCnvFam, sizeof(Data.sCnvFam));
strncpy(Data.sDesc, pSCI->mDesc, sizeof(Data.sDesc));
Data.bDriver = pSCI->mDriver;
Data.bRecordIt = pSCI->mRecordIt;
//filter stuff...
Data.bUseFilter = pSCI->mUseFilter;
if (Data.bUseFilter)
{
if (pFilter==NULL)
pFilter = new CFilter();
pFilter->Cfg(pSCI, this);
}
else
{
if (pFilter)
{
delete pFilter;
pFilter = NULL;
}
}
//boxcar stuff...
Data.bUseBoxcar = pSCI->mUseBoxcar;
if (Data.bUseBoxcar)
{
if (pBoxcar==NULL)
pBoxcar = new CBoxcar();
pBoxcar->Cfg(pSCI, this);
}
else
{
if (pBoxcar)
{
delete pBoxcar;
pBoxcar = NULL;
}
}
MeasVal = Data.PrevMeasVal;
if (NewSlot)
{
lScanOfLastChange = pHistory->lScanNo;
lScanOfLastSave = pHistory->lScanNo;
}
else
{
lScanOfLastChange = pHistory->lScanNo - 2;
lScanOfLastSave = pHistory->lScanNo - 2;
}
#if ForSysCAD
iCnvNo = gs_CnvsMngr.FindCnv(Data.sCnvFam);
#endif
if (iCnvNo<0)
iCnvNo = 0;
FixTyp(); //might as well check it
}
//---------------------------------------------------------------------------
void CSlot::GetCfg(SlotCfgInfo& SCI)
{
SCI.mTag = Data.sTag;
SCI.mTyp = Data.VarTyp;
SCI.mEng = Data.sEng;
SCI.mCnvFam = Data.sCnvFam;
SCI.mDesc = Data.sDesc;
SCI.mDriver = Data.bDriver;
SCI.mRecordIt = Data.bRecordIt;
SCI.mUseFilter = Data.bUseFilter;
if (Data.bUseFilter)
{
ASSERT(pFilter);
SCI.mFilterAlg = pFilter->Data.iFilterAlg;
SCI.mFilterTau = pFilter->Data.dFilterTau;
SCI.mWinFltPeriod = pFilter->Data.dWinFltPeriod;
SCI.mWinFltCount = pFilter->Data.iWinFltCount;
SCI.mFltDelta = pFilter->Data.FltDeltaVal.GetDouble();
}
else
{
SCI.mFilterAlg = 0;
SCI.mFilterTau= 0.0;
SCI.mWinFltPeriod = 0.0;
SCI.mWinFltCount = 0;
SCI.mFltDelta = 0.0;
}
SCI.mUseBoxcar = Data.bUseBoxcar;
if (Data.bUseBoxcar)
{
ASSERT(pBoxcar);
SCI.mBoxcarAlg = pBoxcar->Data.iBoxcarAlg;
SCI.mDeltaLo = pBoxcar->Data.dDeltaLo;
SCI.mDeltaHi = pBoxcar->Data.dDeltaHi;
SCI.mNoRec = pBoxcar->Data.iNoRec;
SCI.mNoNotRec = pBoxcar->Data.iNoNotRec;
SCI.mChange = pBoxcar->Data.dChange;
}
else
{
SCI.mBoxcarAlg = 0;
SCI.mDeltaLo = 0.0;
SCI.mDeltaHi = 0.0;
SCI.mNoRec = 0;
SCI.mNoNotRec = 0;
SCI.mChange = 0.0;
}
}
//---------------------------------------------------------------------------
/*void CSlot::ChangeBoxcar(byte BoxcarAlg, double DeltaLo, double DeltaHi, WORD NoRec, WORD NoNotRec, double Change)
{
Data.bUseBoxcar = (m_BoxcarAlg>0);
if (Data.bUseBoxcar)
{
if (pBoxcar==NULL)
pBoxcar = new CBoxcar();
pBoxcar->Data.iBoxcarAlg = BoxcarAlg;
pBoxcar->Data.dDeltaLo = DeltaLo;
pBoxcar->Data.dDeltaHi = DeltaHi;
pBoxcar->Data.dChange = Change;
pBoxcar->Data.iNoNotRec = NoNotRec;
pBoxcar->Data.iNoRec = NoRec;
}
}*/
//---------------------------------------------------------------------------
flag CSlot::Save(CFile & F, long SlotNo)
{
ASSERT(HD_SlotSpace >= sizeof(HD_FilterInfo) + sizeof(HD_BoxcarInfo) + sizeof(HD_SlotInfo));
unsigned long Pos=sizeof(HD_Hist) + SlotNo * HD_SlotSpace;
if (F.GetLength() < Pos)
F.SetLength(Pos);
F.Seek(Pos, CFile::begin);
// cnm a KLUDGE the contents of these do not get saved correctly if they are strings.
LPTSTR p0=Data.PrevActualVal.pChar;
LPTSTR p1=Data.PrevMeasVal.pChar;
LPTSTR p2=Data.PrevSaveVal.pChar;
if (IsStrng(Data.VarTyp))
{
Data.PrevActualVal.pChar=NULL;
Data.PrevMeasVal.pChar=NULL;
Data.PrevSaveVal.pChar=NULL;
}
F.Write((void*)&(Data), sizeof(HD_SlotInfo));
// cnm a KLUDGE the contents of these do not get saved correctly if they are strings.
if (IsStrng(Data.VarTyp))
{
Data.PrevActualVal.pChar=p0;
Data.PrevMeasVal.pChar=p1;
Data.PrevSaveVal.pChar=p2;
}
if (Data.bUseFilter)
pFilter->Save(F);
if (Data.bUseBoxcar)
pBoxcar->Save(F);
return true;
};
//---------------------------------------------------------------------------
static void FixDataUnion(DataUnion & Val)
{
byte iType = Val.iType;
byte iStat = Val.iStatus;
Val.iType = iType & 0x01f; // only the lowest 5 bits
Val.iStatus = ((iType & 0x020) >> 5) | (iStat << 1) ; // top bit of iType shifted into lowest bit pos and iSTat
}
flag CSlot::Load(CFile & F, long SlotNo)
{
unsigned long Pos=sizeof(HD_Hist) + SlotNo * HD_SlotSpace;
if (F.GetLength() < Pos)
{
dbgpln("History Desc File too short");
ASSERT(FALSE);
return false;
}
F.Seek(Pos, CFile::begin);
F.Read((void*)&(Data), sizeof(HD_SlotInfo));
// Fix for changes made to layout of DataUnion
if (PrjFileVerNo()<106)
{
FixDataUnion(Data.PrevActualVal);
FixDataUnion(Data.PrevMeasVal);
FixDataUnion(Data.PrevSaveVal);
}
// cnm a KLUDGE the contents of these do not get saved correctly if they are strings.
if (IsStrng(Data.VarTyp))
{
Data.PrevActualVal.pChar=NULL;
Data.PrevMeasVal.pChar=NULL;
Data.PrevSaveVal.pChar=NULL;
Data.PrevActualVal.Set("");
Data.PrevMeasVal.Set("");
Data.PrevSaveVal.Set("");
}
Configure(SlotNo);
if (Data.bUseFilter)
{
pFilter = new CFilter();
pFilter->Load(F);
pFilter->Cfg(NULL, this);
}
if (Data.bUseBoxcar)
{
pBoxcar = new CBoxcar();
pBoxcar->Load(F);
pBoxcar->Cfg(NULL, this);
}
#if ForSysCAD
iCnvNo = gs_CnvsMngr.FindCnv(Data.sCnvFam);
#endif
if (iCnvNo<0)
iCnvNo = 0;
return true;
}
//---------------------------------------------------------------------------
void CSlot::Changed(flag Force)
{
#if dbgHistorian && DBGMANAGER
if (dbgHistTag())
{
if (dbgHistTag.Items.Length()>0 && dbgHistTag.Items.Find(Data.sTag)!=NULL)
{ //place breakpoint here to see what is happening with a specific tag specified in syscad.dmf
dbgpln("Historian: tag %s [%8i] changed:%12.3f time:%15.3f", Data.sTag, pHistory->lScanNo, MeasVal.GetDouble(), pHistory->dTime);
}
}
#endif
ActualVal = MeasVal; //remember value before it gets changed by filtering
if (pFilter)
{
if (iStatus != TS_STATUS_INVALID)
pFilter->DoFilter();
}
flag Do = (Force || bFirstValue || (Data.iPrevStatus!=iStatus)); //always save for change of status
if (pBoxcar)
{
if (bFirstValue)
{
pBoxcar->AveVal = 0.0;
pBoxcar->AveCnt = 0L;
pBoxcar->NoRec = 0;
pBoxcar->NoNotRec = 0;
pBoxcar->Data.dDeltaVal = Max(pBoxcar->Data.dDeltaLo, pBoxcar->Data.dDeltaVal);
pBoxcar->Data.dDeltaVal = Min(pBoxcar->Data.dDeltaHi, pBoxcar->Data.dDeltaVal);
}
if (!Do)
Do = pBoxcar->CheckChanges(); //because of boxcar compression, save may not be required
}
else
{
if (!Do && pHistory->bUseTolerance)
{
if (IsStrng(MeasVal.Type()))
{
//Do = (fabs((Data.PrevSaveVal.GetDouble()-MeasVal.GetDouble())/Data.PrevSaveVal.GetDouble())>pHistory->dRecordATol);
Do = _stricmp(Data.PrevSaveVal.GetString(), MeasVal.GetString())!=0;
}
else
{
double Err;
Do = !ConvergedVV_NANOK(Data.PrevSaveVal.GetDouble(), MeasVal.GetDouble(), pHistory->dRecordATol, pHistory->dRecordRTol, Err);
}
}
else
Do = true;
}
if (!Do)
{
// CNM Should the logic bracketted AAAA below not maybe be moved here ??
// and instead of PrevSaveVal the Current value should be used
}
if (pHistory->bUseTolerance && !IsStrng(Data.VarTyp))
{
m_bVariesWithinTol=m_bVariesWithinTol || (Data.PrevSaveVal.EqualNANOK(MeasVal)==0);
}
if (Do)
{
SaveEvent();
bFirstValue = false;
m_bVariesWithinTol=false;
}
Data.PrevActualVal = ActualVal;
Data.PrevMeasVal = MeasVal;
Data.iPrevStatus = iStatus;
Data.dPrevTime = pHistory->dTime;
lScanOfLastChange = pHistory->lScanNo;
}
//---------------------------------------------------------------------------
void CSlot::SaveEvent()
{
dwWriteCnt++;
long diff = pHistory->lScanNo - lScanOfLastSave;
if (pHistory->bUseTolerance && m_bVariesWithinTol)
{
if (diff>1 && !bFirstValue && bWriteMidTime && TSFlag!=TS_STR)
{//value has remained "unchanged" for some time, previous value (except for strings) must be stored first
// also what does 'some time' mean ? CNM
byte TempStatus = iStatus;
iStatus = Data.iPrevStatus;
if (!pHistory->pCurEvBlk->AddEv(pHistory->dMidTime, lSNo, Data.PrevMeasVal))
{
// if (pHistory->bSwitchedOff)
// return;
if (!pHistory->pCurEvBlk->AddEv(pHistory->dMidTime, lSNo, Data.PrevMeasVal)) //try again
{ int xxx=0; };//return;
}
iStatus = TempStatus;
#if dbgHistorian && DBGMANAGER
if (dbgHistTag())
{
if (dbgHistTag.Items.Length()>0 && dbgHistTag.Items.Find(Data.sTag)!=NULL)
{ //place breakpoint here to see what is happening with a specific tag specified in syscad.dmf
dbgpln("Historian: tag %s [%8i] saved:%12.3f", Data.sTag, pHistory->lScanNo, Data.PrevMeasVal.GetDouble());
}
}
#endif
}
}
// bool AllowSavePrev=true;
// if ((pHistory->bUseTolerance || pBoxcar) && m_bVariesWithinTol)
// AllowSavePrev=false;
//
// //AAAA<<<<<<<<<<<<<<<<<<<<<<<<<
// //note, trend has steps (eg a level) instead of being smooth if tolerance is used so that not all points are saved
// // CNM the addition of 'pHistory->bUseTolerance' removes steps in the trends
// if (AllowSavePrev && diff>1 && !bFirstValue && bWriteMidTime && TSFlag!=TS_STR)
// {//value has remained "unchanged" for some time, previous value (except for strings) must be stored first
// // also what does 'some time' mean ? CNM
// byte TempStatus = iStatus;
// iStatus = Data.iPrevStatus;
// if (!pHistory->pCurEvBlk->AddEv(pHistory->dMidTime, lSNo, Data.PrevSaveVal))
// {
// if (pHistory->bSwitchedOff)
// return;
// if (!pHistory->pCurEvBlk->AddEv(pHistory->dMidTime, lSNo, Data.PrevSaveVal)) //try again
// return;
// }
// iStatus = TempStatus;
// }
// //AAAA<<<<<<<<<<<<<<<<<<<<<<
bWriteMidTime = 1;
pHistory->AddEv(lSNo);
Data.PrevSaveVal = MeasVal;
lScanOfLastSave = pHistory->lScanNo;
if (pBoxcar)
{
pBoxcar->AveVal = MeasVal.GetDouble();
pBoxcar->AveCnt = 1L;
}
#if dbgHistorian && DBGMANAGER
if (dbgHistTag())
{
if (dbgHistTag.Items.Length()>0 && dbgHistTag.Items.Find(Data.sTag)!=NULL)
{ //place breakpoint here to see what is happening with a specific tag specified in syscad.dmf
dbgpln("Historian: tag %s [%8i] saved:%12.3f", Data.sTag, pHistory->lScanNo, MeasVal.GetDouble());
}
}
#endif
}
//---------------------------------------------------------------------------
void CSlot::FixTyp()
{
if (IsNumData(Data.VarTyp))
{
if (MeasVal.Type() != Data.VarTyp)
MeasVal.SetTypeDouble(Data.VarTyp, (IsNumData(MeasVal.Type()) ? MeasVal.GetDouble() : 0.0));
if (ActualVal.Type() != Data.VarTyp)
ActualVal.SetTypeDouble(Data.VarTyp, (IsNumData(ActualVal.Type()) ? ActualVal.GetDouble() : 0.0));
if (Data.PrevSaveVal.Type() != Data.VarTyp)
Data.PrevSaveVal.SetTypeDouble(Data.VarTyp, (IsNumData(Data.PrevSaveVal.Type()) ? Data.PrevSaveVal.GetDouble() : 0.0));
if (Data.PrevMeasVal.Type() != Data.VarTyp)
Data.PrevMeasVal.SetTypeDouble(Data.VarTyp, (IsNumData(Data.PrevMeasVal.Type()) ? Data.PrevMeasVal.GetDouble() : 0.0));
if (Data.PrevActualVal.Type() != Data.VarTyp)
Data.PrevActualVal.SetTypeDouble(Data.VarTyp, (IsNumData(Data.PrevActualVal.Type()) ? Data.PrevActualVal.GetDouble() : 0.0));
}
}
//---------------------------------------------------------------------------
void CSlot::dbgDump(char* p)
{
dbgpln("Historian slot:[%s]", p);
dbgpln("Slot number :%d", lSNo);
dbgpln("TS flag :%d", TSFlag);
Data.dbgDump();
}
//===========================================================================
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
556
],
[
558,
664
],
[
673,
684
],
[
693,
769
],
[
771,
917
]
],
[
[
557,
557
],
[
665,
672
],
[
685,
692
],
[
770,
770
]
]
]
|
2aca02a91804e22522dd7ced4c75532cfc9407bd | 4dd5d3f7b913f2ccf62b01b45b8d13e01fba4135 | /BMPLoader.h | 268e3cf214685eb99f8095341fc3586d82723452 | []
| no_license | jsj2008/Pirates-VS-Ninja | bbba214da83646c5cf2edfe0bc6a0c8e7d281107 | d72acd37c022f4971ff441c377fb978ee07058df | refs/heads/master | 2021-01-21T00:00:33.250668 | 2011-10-28T03:36:47 | 2011-10-28T03:36:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,369 | h | /*BMPLoader - loads Microsoft .bmp format
Copyright (C) 2006 Chris Backhouse
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
[email protected] www.backhouse.tk
I would appreciate it if anyone using this in something cool would tell me
so I can see where it ends up.
Takes a filename, returns an array of RGB pixel data
Loads:
24bit bitmaps
256 colour bitmaps
16 colour bitmaps
2 colour bitmaps (Thanks to Charles Rabier)
This code is designed for use in openGL programs, so bitmaps not correctly padded will not
load properly, I believe this only applies to:
256cols if width is not a multiple of 4
16cols if width is not a multiple of 8
2cols if width is not a multiple of 32
Sample code:
BMPClass bmp;
BMPLoad(fname,bmp);
glTexImage2D(GL_TEXTURE_2D,0,3,bmp.width,bmp.height,0,GL_RGB,GL_UNSIGNED_BYTE,bmp.bytes);
*/
#ifndef BMPLOADER_H
#define BMPLOADER_H
#include <cstdio>
#include <string>
typedef unsigned char BYTE;
class BMPClass
{
public:
BMPClass();
~BMPClass();
BYTE& pixel(int x,int y,int c);
void allocateMem();
int width,height;
BYTE* bytes; //OpenGL formatted pixels
};
#define BMPError char
#define BMPNOTABITMAP 'b' //Possible error flags
#define BMPNOOPEN 'o'
#define BMPFILEERROR 'f'
#define BMPBADINT 'i'
#define BMPNOERROR '\0'
#define BMPUNKNOWNFORMAT 'u'
//Loads the bmp in fname, and puts the data in bmp
BMPError BMPLoad(std::string fname,BMPClass& bmp);
//Translates my error codes into English
std::string TranslateBMPError(BMPError err);
//Load and select in OpenGL
BMPError BMPLoadGL(std::string fname);
#endif
| [
"pkonrad@459-konnekerp-mav.(none)"
]
| [
[
[
1,
79
]
]
]
|
bfcfb08d8985a048a5832520673e68dbc0ac0597 | c495b752e23e5879cddd6714a015aab5c67f09e0 | /ProjectSin/DXProject/gocVisual.cpp | 3b86984aeabe9a80934d8cdfa178d20a6e834c5f | []
| no_license | zeno60/projectsin | 2c0d136995388de014ebaa6d70c0136b6ab43327 | a0d80a3da85cfeb683891eec0c9515a664cb4ce0 | refs/heads/master | 2021-01-02T23:06:37.648101 | 2008-08-09T07:39:51 | 2008-08-09T07:39:51 | 40,305,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 86 | cpp | #include "gocVisual.h"
GOComponent::goc_id_type gocVisual::mFamilyId = "gocVisual"; | [
"zeno60@5ee530d3-e753-0410-9a95-d5c3cf57bbea"
]
| [
[
[
1,
3
]
]
]
|
26e556fd12fda1ee7d92713dfbd97f2d92fddc59 | 6f7850c90ed97967998033df615d06eacfabd5fa | /whoisalive/tiler.cpp | f73b13043fa12328fb4e32625c4afbca8067e240 | []
| no_license | vi-k/whoisalive | 1145b0af6a2a18e951533b00a2103b000abd570a | ae86c1982c1e97eeebc50ba54bf53b9b694078b6 | refs/heads/master | 2021-01-10T02:00:28.585126 | 2010-08-23T01:58:45 | 2010-08-23T01:58:45 | 44,526,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,546 | cpp | #include "stdafx.h"
#include "tiler.h"
#include "server.h"
//#include "log.h"
//extern my::log main_log;
#include <sstream>
using namespace std;
#include <boost/bind.hpp>
namespace who { namespace tiler {
#pragma warning(disable:4355) /* 'this' : used in base member initializer list */
server::server(who::server &server, size_t max_tiles, boost::function<void ()> on_update_proc)
: server_(server)
, tiles_(max_tiles)
, on_update_(on_update_proc)
{
/* Запускаем после инициализации */
tiler_worker_ = new_worker("tiler_thread");
boost::thread( boost::bind(
&server::thread_proc, this, tiler_worker_) );
}
server::~server()
{
/* Оповещаем о завершении работы */
lets_finish();
/* "Увольняем" все ссылки на "работников" */
dismiss(tiler_worker_);
/* Ждём завершения */
#if 0
while (!check_for_finish())
{
vector<std::string> v;
workers_state(v);
size_t n = v.size();
}
#endif
wait_for_finish();
}
void server::thread_proc(my::worker::ptr this_worker)
{
while (!finish())
{
tiler::tile_id tile_id;
/* Ищем первый попавшийся незагруженный тайл */
{
shared_lock<shared_mutex> l(tiles_mutex_);
int map_id = server_.active_map_id();
for (tiles_list::iterator it = tiles_.begin();
it != tiles_.end(); it++)
{
if (!it->value() && it->key().map_id == map_id)
{
tile_id = it->key();
break;
}
}
}
/* Если нет такого - засыпаем */
if (!tile_id)
{
sleep(this_worker);
continue;
}
/* Загружаем тайл с диска */
wstringstream filename;
tiler::map *map;
{
unique_lock<recursive_mutex> l(maps_mutex_);
map = &maps_[ tile_id.map_id ];
}
filename << L"maps/" << map->id
<< L"/z" << tile_id.z
<< L"/" << (tile_id.x >> 10)
<< L"/x" << tile_id.x
<< L"/" << (tile_id.y >> 10)
<< L"/y" << tile_id.y
<< L"." << map->ext;
tiler::tile::ptr ptr( new tile(filename.str()) );
/* Если загрузить с диска не удалось - загружаем с сервера */
if (!ptr->loaded)
{
wstringstream request;
request << L"/maps/gettile?map=" << map->id
<< L"&z=" << tile_id.z
<< L"&x=" << tile_id.x
<< L"&y=" << tile_id.y;
try
{
server_.load_file(request.str(), filename.str());
ptr.reset( new tile(filename.str()) );
}
catch (...)
{
//
}
}
/* Вносим изменения в список загруженных тайлов */
{
shared_lock<shared_mutex> l(tiles_mutex_);
tiles_list::iterator it = tiles_.find(tile_id);
if (it != tiles_.end())
it->value() = ptr;
}
if (on_update_)
on_update_();
} /* while (true) */
}
int server::add_map(const tiler::map &map)
{
unique_lock<recursive_mutex> l(maps_mutex_);
int id = get_new_map_id_();
maps_[id] = map;
return id;
}
tile::ptr server::get_tile(int map_id, int z, int x, int y)
{
tile_id id(map_id, z, x, y);
{
shared_lock<shared_mutex> l(tiles_mutex_);
tiles_list::iterator it = tiles_.find(id);
if (it != tiles_.end())
return it->value();
}
{
unique_lock<shared_mutex> l(tiles_mutex_);
tile::ptr ptr = tiles_[id];
wake_up(tiler_worker_);
return ptr;
}
}
} }
| [
"victor dunaev ([email protected])",
"[email protected]"
]
| [
[
[
1,
83
],
[
85,
134
],
[
136,
163
]
],
[
[
84,
84
],
[
135,
135
]
]
]
|
1de4bb45e6abcea88a846718305d4def601616a8 | 1114bc4d985267910b21707c5a2e44dd580a1c6b | /workinprogressMain.h | 80b618fbe3b936ba640321295ec1fe157fe0aa74 | []
| no_license | patricksebastien/yuka | 1a1075a537e6e6508322e623c3a9236307ff5abe | 100380d47b2aad6ac7732843657bea30cbd94bdc | refs/heads/master | 2020-05-18T20:09:37.155608 | 2010-11-01T15:41:21 | 2010-11-01T15:41:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,288 | h | /***************************************************************
* Name: workinprogressMain.h
* Purpose: Defines Application Frame
* Author: Patrick Sébastien ([email protected])
* Created: 2010-10-11
* Copyright: Patrick Sébastien (www.workinprogress.ca)
* License:
**************************************************************/
#ifndef WORKINPROGRESSMAIN_H
#define WORKINPROGRESSMAIN_H
//(*Headers(workinprogressFrame)
#include <wx/notebook.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include <wx/listbox.h>
#include <wx/toolbar.h>
#include <wx/panel.h>
#include <wx/filedlg.h>
#include <wx/choice.h>
#include <wx/statbmp.h>
#include <wx/button.h>
#include <wx/frame.h>
#include <wx/html/htmlwin.h>
//*)
//CUSTOM
#include <wx/socket.h>
#include <wx/filename.h>
#include <wx/msgdlg.h>
#include <wx/dir.h>
#include <wx/file.h>
#include <wx/progdlg.h>
#include <wx/textfile.h>
#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
//ETHERNET
#define PROGMEM_SIZE 61440 // 4096-bytes reserve for bootloader
WX_DECLARE_STRING_HASH_MAP( wxString, DeviceHash );
class wxDirTraverserSimple : public wxDirTraverser
{
public:
wxDirTraverserSimple(wxArrayString& files) : m_files(files) { }
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
m_files.Add(filename);
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{
return wxDIR_CONTINUE;
}
private:
wxArrayString& m_files;
};
class workinprogressFrame: public wxFrame
{
public:
workinprogressFrame(wxWindow* parent,wxWindowID id = -1);
virtual ~workinprogressFrame();
private:
//(*Handlers(workinprogressFrame)
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void Ontb_helpClicked(wxCommandEvent& event);
void Ontb_updateClicked(wxCommandEvent& event);
void Ontb_shareClicked(wxCommandEvent& event);
void OnPanel1Paint(wxPaintEvent& event);
void usb_program(wxCommandEvent& event);
void Onb_openClick(wxCommandEvent& event);
void Onb_infoClick(wxCommandEvent& event);
void Onc_microcontrollerSelect(wxCommandEvent& event);
void Onc_categorySelect(wxCommandEvent& event);
void Onc_firmwareSelect(wxCommandEvent& event);
void Onb_sourceClick(wxCommandEvent& event);
void Onb_makeClick(wxCommandEvent& event);
void Onb_cleanClick(wxCommandEvent& event);
void Onb_open_bootloaderClick(wxCommandEvent& event);
void Onb_program_bootloaderClick(wxCommandEvent& event);
void Onc_bootloaderSelect(wxCommandEvent& event);
void Onc_microcontroller_bootloaderSelect(wxCommandEvent& event);
void Onb_clean_bootloaderClick(wxCommandEvent& event);
void Onb_make_bootloaderClick(wxCommandEvent& event);
void Onb_source_bootloaderClick(wxCommandEvent& event);
void Onb_ad_flashClick(wxCommandEvent& event);
void Onb_ad_eepromClick(wxCommandEvent& event);
void Onb_ad_executeClick(wxCommandEvent& event);
void Onb_fetchClick(wxCommandEvent& event);
void Onc_ad_deviceSelect(wxCommandEvent& event);
void Onc_ad_programmerSelect(wxCommandEvent& event);
void Onc_ad_portSelect(wxCommandEvent& event);
void Onb_fusesClick(wxCommandEvent& event);
void Ontc_lowText(wxCommandEvent& event);
void Ontc_highText(wxCommandEvent& event);
void Ontc_extendedText(wxCommandEvent& event);
void Onb_fuse_calculatorClick(wxCommandEvent& event);
void Oncb_dClick(wxCommandEvent& event);
void Oncb_eClick(wxCommandEvent& event);
void Oncb_vClick(wxCommandEvent& event);
void Onnb_viaPageChanged(wxNotebookEvent& event);
void Onnb_mainPageChanged(wxNotebookEvent& event);
//*)
//(*Identifiers(workinprogressFrame)
static const long ID_STATICTEXT37;
static const long ID_STATICBITMAP1;
static const long ID_HTMLWINDOW3;
static const long ID_PANEL8;
static const long ID_PANEL2;
static const long ID_TEXTCTRL10;
static const long ID_BUTTON13;
static const long ID_TEXTCTRL11;
static const long ID_BUTTON14;
static const long ID_STATICTEXT27;
static const long ID_CHOICE6;
static const long ID_STATICTEXT28;
static const long ID_CHOICE7;
static const long ID_STATICTEXT29;
static const long ID_CHOICE8;
static const long ID_STATICTEXT30;
static const long ID_TEXTCTRL12;
static const long ID_STATICTEXT31;
static const long ID_TEXTCTRL13;
static const long ID_STATICTEXT32;
static const long ID_TEXTCTRL14;
static const long ID_BUTTON17;
static const long ID_BUTTON18;
static const long ID_CHECKBOX3;
static const long ID_CHECKBOX4;
static const long ID_CHECKBOX5;
static const long ID_STATICTEXT33;
static const long ID_TEXTCTRL15;
static const long ID_STATICTEXT34;
static const long ID_LISTBOX3;
static const long ID_STATICTEXT36;
static const long ID_BUTTON16;
static const long ID_BUTTON15;
static const long ID_PANEL16;
static const long ID_PANEL3;
static const long ID_STATICTEXT2;
static const long ID_TEXTCTRL1;
static const long ID_STATICTEXT3;
static const long ID_TEXTCTRL2;
static const long ID_STATICTEXT4;
static const long ID_TEXTCTRL3;
static const long ID_STATICTEXT5;
static const long ID_TEXTCTRL4;
static const long ID_PANEL11;
static const long ID_PANEL5;
static const long ID_STATICTEXT15;
static const long ID_TEXTCTRL6;
static const long ID_STATICTEXT16;
static const long ID_TEXTCTRL7;
static const long ID_STATICTEXT17;
static const long ID_TEXTCTRL8;
static const long ID_PANEL12;
static const long ID_PANEL10;
static const long ID_STATICTEXT35;
static const long ID_CHECKBOX6;
static const long ID_PANEL14;
static const long ID_PANEL13;
static const long ID_NOTEBOOK_FIRM;
static const long ID_STATICTEXT6;
static const long ID_TEXTCTRL5;
static const long ID_BUTTON2;
static const long ID_STATICTEXT7;
static const long ID_STATICTEXT8;
static const long ID_CHOICE1;
static const long ID_STATICTEXT9;
static const long ID_CHOICE2;
static const long ID_STATICTEXT10;
static const long ID_CHOICE3;
static const long ID_STATICTEXT11;
static const long ID_HTMLWINDOW1;
static const long ID_BUTTON1;
static const long ID_BUTTON4;
static const long ID_BUTTON6;
static const long ID_BUTTON5;
static const long ID_STATICTEXT12;
static const long ID_LISTBOX1;
static const long ID_CHECKBOX2;
static const long ID_CHECKBOX1;
static const long ID_BUTTON3;
static const long ID_PANEL7;
static const long ID_PANEL4;
static const long ID_STATICTEXT24;
static const long ID_TEXTCTRL9;
static const long ID_BUTTON7;
static const long ID_STATICTEXT23;
static const long ID_STATICTEXT21;
static const long ID_CHOICE4;
static const long ID_STATICTEXT22;
static const long ID_CHOICE5;
static const long ID_STATICTEXT25;
static const long ID_HTMLWINDOW2;
static const long ID_STATICTEXT26;
static const long ID_LISTBOX2;
static const long ID_BUTTON8;
static const long ID_BUTTON9;
static const long ID_BUTTON10;
static const long ID_BUTTON11;
static const long ID_BUTTON12;
static const long ID_PANEL15;
static const long ID_PANEL6;
static const long ID_NOTEBOOK1;
static const long ID_PANEL1;
static const long tb_submit;
static const long tb_update;
static const long tb_help;
static const long tb_quit;
static const long ID_TOOLBAR1;
//*)
//(*Declarations(workinprogressFrame)
wxStaticText* StaticText10;
wxStaticText* StaticText22;
wxHtmlWindow* html_description;
wxStaticText* StaticText9;
wxCheckBox* cb_e;
wxToolBarToolBase* ToolBarItem4;
wxStaticText* st_note;
wxTextCtrl* tc_local_port;
wxPanel* Panel5;
wxToolBar* ToolBar1;
wxPanel* pl_avrdude;
wxButton* b_ad_eeprom;
wxTextCtrl* tc_file;
wxStaticText* StaticText29;
wxListBox* m_lbox_ad;
wxToolBarToolBase* ToolBarItem3;
wxTextCtrl* tc_high;
wxListBox* m_lbox_bootloader;
wxStaticText* StaticText33;
wxStaticText* StaticText2;
wxPanel* Panel4;
wxStaticText* StaticText30;
wxButton* b_open;
wxTextCtrl* tc_file_bootloader;
wxChoice* c_ad_device;
wxStaticText* StaticText26;
wxStaticText* StaticText6;
wxPanel* pn_usb;
wxStaticBitmap* StaticBitmap1;
wxButton* b_source_bootloader;
wxButton* b_clean;
wxTextCtrl* tc_product_string;
wxChoice* c_microcontroller_bootloader;
wxPanel* pl_welcome;
wxButton* b_info_bootloader;
wxButton* b_make;
wxStaticText* StaticText32;
wxStaticText* StaticText8;
wxStaticText* StaticText11;
wxPanel* pl_bootloader;
wxButton* b_ad_flash;
wxChoice* c_ad_port;
wxCheckBox* cb_restart;
wxPanel* Panel1;
wxStaticText* StaticText31;
wxNotebook* nb_main;
wxButton* b_fuses;
wxCheckBox* cb_bootloader;
wxStaticText* StaticText27;
wxFileDialog* FileDialog1;
wxPanel* pn_avrdude;
wxTextCtrl* tc_device_port;
wxHtmlWindow* html_description_bootloader;
wxStaticText* StaticText3;
wxButton* b_source;
wxButton* b_fetch;
wxListBox* m_lbox;
wxPanel* Panel6;
wxPanel* Panel3;
wxStaticText* StaticText21;
wxCheckBox* cb_d;
wxTextCtrl* tc_extended;
wxStaticText* StaticText23;
wxStaticText* StaticText24;
wxPanel* pn_ethernet;
wxToolBarToolBase* ToolBarItem1;
wxButton* b_open_bootloader;
wxChoice* c_category;
wxButton* b_fuse_calculator;
wxChoice* c_microcontroller;
wxTextCtrl* tc_ad_flash;
wxTextCtrl* tc_vendor_string;
wxStaticText* StaticText5;
wxStaticText* StaticText34;
wxStaticText* StaticText7;
wxTextCtrl* tc_low;
wxPanel* Panel7;
wxTextCtrl* tc_product_id;
wxHtmlWindow* HtmlWindow1;
wxTextCtrl* tc_vendor_id;
wxTextCtrl* tc_ip;
wxButton* b_clean_bootloader;
wxStaticText* StaticText28;
wxButton* b_info;
wxStaticText* StaticText15;
wxStaticText* StaticText12;
wxStaticText* StaticText35;
wxTextCtrl* tc_ad_eeprom;
wxCheckBox* cb_v;
wxChoice* c_ad_programmer;
wxPanel* Panel2;
wxButton* b_program_bootloader;
wxNotebook* nb_via;
wxStaticText* StaticText25;
wxButton* b_program;
wxStaticText* StaticText17;
wxStaticText* StaticText4;
wxStaticText* StaticText36;
wxChoice* c_firmware;
wxButton* b_ad_execute;
wxPanel* pl_firmware;
wxCheckBox* cb_asp;
wxToolBarToolBase* ToolBarItem2;
wxStaticText* StaticText16;
wxChoice* c_bootloader;
wxPanel* fm_panel;
wxButton* b_make_bootloader;
wxTextCtrl* tc_ad_command;
//*)
//CUSTOM
wxString GetCurrentWorkingDirectory();
wxString g_application_dir;
wxString avrdudepath;
void ShowOutput(const wxString& cmd, const wxArrayString& output, const wxString& title, wxListBox* box);
wxString g_help;
DeviceHash device;
void buildcommand();
wxString PathGTK(wxString thepath);
//AVAILABLE FIRMWARE
wxString g_microcontroller;
wxString g_microcontroller_bootloader;
wxString g_category;
wxString g_firmware;
wxString g_bootloader;
DECLARE_EVENT_TABLE()
//ETHERNET
unsigned int HexConverter(unsigned char *hex, unsigned char *buff);
unsigned char Ascii2Hex(unsigned char ascii);
wxDatagramSocket *pSocket;
wxChar progmem[PROGMEM_SIZE];// = new wxChar[57344];
wxUint32 progaddr;
bool local_port;
};
#endif // WORKINPROGRESSMAIN_H
| [
"[email protected]"
]
| [
[
[
1,
368
]
]
]
|
9439b33bd6b1a5ab7a5a7ed9f517ab7265248ca2 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/dingus/input/DIMouse.cpp | 29172d9e00b6cb57af2f7e0887f2bb6e1b077382 | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,051 | cpp | // --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#include "stdafx.h"
#include "DIMouse.h"
using namespace dingus;
struct SDIMToButtonMap
{
int dim;
CMouseEvent::eMouseButton button;
};
SDIMToButtonMap gDim2Button [] =
{ { 0, CMouseEvent::LEFT_BTN },
{ 1, CMouseEvent::RIGHT_BTN },
{ 2, CMouseEvent::MIDDLE_BTN }
};
int gDim2ButtonCount = sizeof(gDim2Button) / sizeof(gDim2Button[0]);
CDIMouse::CDIMouse( HWND hwnd, IDirectInput8& di8 )
: mDIMouse( NULL )
{
HRESULT hRes;
DWORD dwCoopFlags;
dwCoopFlags = DISCL_NONEXCLUSIVE | DISCL_FOREGROUND;
// dwCoopFlags = DISCL_EXCLUSIVE | DISCL_FOREGROUND;
// Obtain an interface to the system mouse device.
hRes = di8.CreateDevice(
GUID_SysMouse,
&mDIMouse,
NULL );
assert( SUCCEEDED( hRes ) );
assert( mDIMouse );
// Set the data format to "mouse format" - a predefined data format
//
// A data format specifies which controls on a device we
// are interested in, and how they should be reported.
//
// This tells DirectInput that we will be passing a
// DIMOUSESTATE2 structure to IDirectInputDevice::GetDeviceState.
hRes = mDIMouse->SetDataFormat( &c_dfDIMouse );
assert( SUCCEEDED( hRes ) );
// Set the mouse axis mode to relative
// See "Interpreting Mouse Axis Data" topic
DIPROPDWORD diprop;
diprop.diph.dwSize = sizeof( diprop );
diprop.diph.dwHeaderSize = sizeof( diprop.diph );
diprop.diph.dwObj = 0;
diprop.diph.dwHow = DIPH_DEVICE;
diprop.dwData = DIPROPAXISMODE_REL;
hRes = mDIMouse->SetProperty( DIPROP_AXISMODE, &diprop.diph );
assert( SUCCEEDED( hRes ) );
// Set the cooperativity level to let DirectInput know how
// this device should interact with the system and with other
// DirectInput applications.
hRes = mDIMouse->SetCooperativeLevel( hwnd, dwCoopFlags );
assert( SUCCEEDED( hRes ) );
for( int q = 0; q < gDim2ButtonCount; q++ )
{
int index = ::gDim2Button[q].dim;
assert( index >= 0 && index < BUTTON_COUNT );
mButtonByDim[ index ] = ::gDim2Button[q].button;
}
/* // IMPORTANT STEP TO USE BUFFERED DEVICE DATA!
//
// DirectInput uses unbuffered I/O (buffer size = 0) by default.
// If you want to read buffered data, you need to set a nonzero
// buffer size.
//
// Set the buffer size to DINPUT_BUFFERSIZE (defined above) elements.
//
// The buffer size is a DWORD property associated with the device.
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = SAMPLE_BUFFER_SIZE; // Arbitary buffer size
if( FAILED( hr = mDirectInput8Keyboard->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
throw EError( "keyboard device buffer size setting failed" );
*/
// Acquire the newly created device
mDIMouse->Acquire();
}
CMouseEvent::eMouseButton CDIMouse::dim2button( int dim )
{
return mButtonByDim[ dim ];
}
CInputEvents CDIMouse::poll()
{
HRESULT hr;
DIMOUSESTATE dims; // DirectInput mouse state structure
CInputEvents events;
// Get the input's device state, and put the state in dims
ZeroMemory( &dims, sizeof(dims) );
if( FAILED( hr = mDIMouse->GetDeviceState( sizeof(dims), &dims ) ) )
{
// DirectInput may be telling us that the input stream has been
// interrupted. We aren't tracking any state between polls, so
// we don't have any special reset that needs to be done.
// We just re-acquire and try again.
// If input is lost then acquire and keep trying
hr = mDIMouse->Acquire();
while( hr == DIERR_INPUTLOST )
hr = mDIMouse->Acquire();
//if( hr == DIERR_OTHERAPPHASPRIO ||
// hr == DIERR_NOTACQUIRED )
// hr may be DIERR_OTHERAPPHASPRIO or other errors. This
// may occur when the app is minimized or in the process of
// switching, so just try again later
return events;
}
long x = dims.lX;
long y = dims.lY;
long ox = mOldDims.lX;
long oy = mOldDims.lY;
for( int i = 0; i < BUTTON_COUNT; i++ ) {
CMouseEvent::eMouseButton btn = dim2button(i);
CMouseEvent::eMode mode;
if( dims.rgbButtons[i] != mOldDims.rgbButtons[i] ) {
mode = (dims.rgbButtons[i]&0x80) ? (CMouseEvent::MOUSE_PRESSED) : (CMouseEvent::MOUSE_RELEASED);
} else {
if( dims.rgbButtons[i] & 0x80 ) {
mode = (ox!=x || oy!=y) ? (CMouseEvent::MOUSE_DRAGGED) : (CMouseEvent::MOUSE_DOWN);
} else {
mode = (ox!=x || oy!=y) ? (CMouseEvent::MOUSE_MOVE) : (CMouseEvent::MOUSE_NO_ACTION);
}
events.addEvent( new CMouseEvent(mode,btn,x,y,1) );
}
}
mOldDims = dims;
return events;
} | [
"[email protected]"
]
| [
[
[
1,
164
]
]
]
|
1b77df1000b84dba63dc10b33dec239fb369c811 | ab2777854d7040cc4029edcd1eccc6d48ca55b29 | /Algorithm/ATCode/ATCodeMgr.cpp | 55fbd05c8b48b46be74c094ab224d1c9563fba4b | []
| no_license | adrix89/araltrans03 | f9c79f8e5e62a23bbbd41f1cdbcaf43b3124719b | 6aa944d1829006a59d0f7e4cf2fef83e3f256481 | refs/heads/master | 2021-01-10T19:56:34.730964 | 2009-12-21T16:21:45 | 2009-12-21T16:21:45 | 38,417,581 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 19,190 | cpp |
#pragma warning(disable:4312)
#pragma warning(disable:4313)
#pragma warning(disable:4996)
#include <process.h>
#include "stdafx.h"
#include "ATCodeMgr.h"
#include "HookPoint.h"
//#include "RegistryMgr/cRegistryMgr.h"
//#include "CharacterMapper.h"
#include "OptionDlg.h"
CATCodeMgr* CATCodeMgr::_Inst = NULL;
CATCodeMgr* CATCodeMgr::GetInstance()
{
return _Inst;
}
CATCodeMgr::CATCodeMgr(void)
: m_hContainer(NULL),
m_hContainerWnd(NULL),
m_wszOptionString(NULL),
m_bRunClipboardThread(FALSE),
m_hClipboardThread(NULL),
m_hClipTextChangeEvent(NULL)
//m_pfnLoadLibraryA(NULL),
//m_pfnLoadLibraryW(NULL)
{
_Inst = this;
ZeroMemory(&m_sContainerFunc, sizeof(CONTAINER_PROC_ENTRY));
InitializeCriticalSection(&m_csClipText);
}
CATCodeMgr::~CATCodeMgr(void)
{
DeleteCriticalSection(&m_csClipText);
Close();
_Inst = NULL;
}
BOOL CATCodeMgr::Init( HWND hAralWnd, LPWSTR wszPluginOption )
{
Close();
BOOL bRetVal = FALSE;
// 부모 윈도우 핸들 저장
if(NULL==hAralWnd) return FALSE;
m_hContainerWnd = hAralWnd;
// 컨테이너 함수 포인터 얻어오기
m_hContainer = GetModuleHandle(_T("ATCTNR3.DLL"));
if(m_hContainer && INVALID_HANDLE_VALUE != m_hContainer)
{
ZeroMemory(&m_sContainerFunc, sizeof(CONTAINER_PROC_ENTRY));
m_sContainerFunc.procHookWin32Api = (PROC_HookWin32Api) GetProcAddress(m_hContainer, "HookWin32Api");
m_sContainerFunc.procUnhookWin32Api = (PROC_UnhookWin32Api) GetProcAddress(m_hContainer, "UnhookWin32Api");
m_sContainerFunc.procHookCodePoint = (PROC_HookCodePoint) GetProcAddress(m_hContainer, "HookCodePoint");
m_sContainerFunc.procUnhookCodePoint = (PROC_UnhookCodePoint) GetProcAddress(m_hContainer, "UnhookCodePoint");
m_sContainerFunc.procCreateTransCtx = (PROC_CreateTransCtx) GetProcAddress(m_hContainer, "CreateTransCtx");
m_sContainerFunc.procDeleteTransCtx = (PROC_DeleteTransCtx) GetProcAddress(m_hContainer, "DeleteTransCtx");
m_sContainerFunc.procTranslateUsingCtx = (PROC_TranslateUsingCtx) GetProcAddress(m_hContainer, "TranslateUsingCtx");
m_sContainerFunc.procIsAppLocaleLoaded = (PROC_IsAppLocaleLoaded) GetProcAddress(m_hContainer, "IsAppLocaleLoaded");
m_sContainerFunc.procSuspendAllThread = (PROC_SuspendAllThread) GetProcAddress(m_hContainer, "SuspendAllThread");
m_sContainerFunc.procResumeAllThread = (PROC_ResumeAllThread) GetProcAddress(m_hContainer, "ResumeAllThread");
m_sContainerFunc.procIsAllThreadSuspended = (PROC_IsAllThreadSuspended) GetProcAddress(m_hContainer, "IsAllThreadSuspended");
}
if( m_sContainerFunc.procHookWin32Api && m_sContainerFunc.procUnhookWin32Api
&& m_sContainerFunc.procHookCodePoint && m_sContainerFunc.procUnhookCodePoint
&& m_sContainerFunc.procCreateTransCtx && m_sContainerFunc.procDeleteTransCtx
&& m_sContainerFunc.procTranslateUsingCtx && m_sContainerFunc.procIsAppLocaleLoaded
&& m_sContainerFunc.procSuspendAllThread && m_sContainerFunc.procResumeAllThread
&& m_sContainerFunc.procIsAllThreadSuspended)
{
// 모든 쓰레드 정지
m_sContainerFunc.procSuspendAllThread();
// LoadLibrary 함수 후킹
if( m_sContainerFunc.procHookWin32Api( L"kernel32.dll", L"LoadLibraryA", NewLoadLibraryA, 1 ) )
{
//m_pfnLoadLibraryA = (PROC_LoadLibrary) m_sContainerFunc.pfnGetOrigDllFunction("kernel32.dll", "LoadLibraryA");
}
if( m_sContainerFunc.procHookWin32Api( L"kernel32.dll", L"LoadLibraryW", NewLoadLibraryW, 1 ) )
{
//m_pfnLoadLibraryW = (PROC_LoadLibrary) m_sContainerFunc.pfnGetOrigDllFunction("kernel32.dll", "LoadLibraryW");
}
// 클립보드 관련
m_bRunClipboardThread = TRUE;
m_hClipTextChangeEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
m_hClipboardThread = (HANDLE)_beginthreadex(NULL, 0, ClipboardThreadFunc, NULL, 0, NULL);
// 옵션 스트링 파싱
m_wszOptionString = wszPluginOption;
if(m_wszOptionString == NULL)
{
m_wszOptionString = new wchar_t[MAX_OPTION_LEN];
ZeroMemory(m_wszOptionString, MAX_OPTION_LEN);
}
#ifdef UNICODE
CString strOptionString = m_wszOptionString;
#else
CString strOptionString;
WideCharToMultiByte(CP_ACP, 0, m_wszOptionString, -1, strOptionString.GetBufferSetLength(MAX_OPTION_LEN), MAX_OPTION_LEN, NULL, NULL);
#endif
if( m_optionRoot.ParseChildren(strOptionString) )
{
bRetVal = TRUE;
}
// 모든 쓰레드 재가동
m_sContainerFunc.procResumeAllThread();
}
if( bRetVal == TRUE )
{
// 옵션 적용
AdjustOption(&m_optionRoot);
}
else
{
Close();
}
return bRetVal;
}
BOOL CATCodeMgr::Close()
{
if(NULL==m_hContainerWnd) return FALSE;
// 클립보드 쓰레드 정지
m_bRunClipboardThread = FALSE;
if(m_hClipboardThread && m_hClipTextChangeEvent)
{
::SetEvent(m_hClipTextChangeEvent);
//::WaitForSingleObject(m_hClipboardThread, 3000);
::CloseHandle(m_hClipboardThread);
::CloseHandle(m_hClipTextChangeEvent);
}
// 모든 쓰레드 정지
m_sContainerFunc.procSuspendAllThread();
ResetOption();
m_hClipboardThread = NULL;
m_hClipTextChangeEvent = NULL;
// 옵션 객체 초기화
m_optionRoot.ClearChildren();
// LoadLibrary 언훅
TRACE(_T("kernel32.DLL!LoadLibraryA Unhook... \n"));
m_sContainerFunc.procUnhookWin32Api( L"kernel32.dll", L"LoadLibraryA", NewLoadLibraryA );
TRACE(_T("kernel32.DLL!LoadLibraryW Unhook... \n"));
m_sContainerFunc.procUnhookWin32Api( L"kernel32.dll", L"LoadLibraryW", NewLoadLibraryW );
// 기타 변수 리셋
m_hContainerWnd = NULL;
m_wszOptionString = NULL;
// 모든 쓰레드 재가동
m_sContainerFunc.procResumeAllThread();
return TRUE;
}
BOOL CATCodeMgr::Option()
{
BOOL bRetVal = TRUE;
CString strCurOptionString = m_optionRoot.ChildrenToString();
COptionNode tmpRoot;
if( tmpRoot.ParseChildren(strCurOptionString) == FALSE ) return FALSE;
COptionDlg od;
od.SetRootOptionNode(&tmpRoot);
if( od.DoModal() == IDOK )
{
ApplyOption(&tmpRoot);
}
return bRetVal;
}
BOOL CATCodeMgr::ApplyOption( COptionNode* pRootNode )
{
BOOL bRetVal = FALSE;
CString strCurOptionString = m_optionRoot.ChildrenToString();
// 적용시켜보고
if( AdjustOption(pRootNode) == FALSE || m_optionRoot.ParseChildren( pRootNode->ChildrenToString() ) == FALSE )
{
// 실패면 원상복구
m_optionRoot.ParseChildren( strCurOptionString );
AdjustOption(&m_optionRoot);
}
else
{
// 적용 성공이면
CString strOptionString = m_optionRoot.ChildrenToString();
#ifdef UNICODE
wcscpy_s(m_wszOptionString, MAX_OPTION_LEN, strOptionString);
#else
CString strOptionString;
WideCharToMultiByte(CP_ACP, 0, strOptionString, -1, m_wszOptionString, MAX_OPTION_LEN, NULL, NULL);
#endif
bRetVal = TRUE;
}
return bRetVal;
}
//////////////////////////////////////////////////////////////////////////
//
// 새 옵션 적용 직전에 현재 옵션들을 모두 초기화해주는 함수
//
//////////////////////////////////////////////////////////////////////////
void CATCodeMgr::ResetOption()
{
// 후킹 재시도 중인 목록을 클리어
m_listRetryHook.clear();
// 후킹한 ATCode들 해제
for(list<CHookPoint*>::iterator iter = m_listHookPoint.begin();
iter != m_listHookPoint.end();
iter++)
{
CHookPoint* pPoint = (*iter);
delete pPoint;
}
m_listHookPoint.clear();
}
//////////////////////////////////////////////////////////////////////////
//
// 이전 버전과의 호환을 위한 옵션 마이그레이션
//
//////////////////////////////////////////////////////////////////////////
BOOL CATCodeMgr::MigrateOption(COptionNode* pRootNode)
{
if(NULL == pRootNode) return FALSE;
BOOL bRetVal = TRUE;
BOOL bNeedMigration = FALSE;
BOOL bPtrCheat = FALSE;
BOOL bSOW = FALSE;
BOOL bRemoveSpace = FALSE;
BOOL bTwoByte = FALSE;
int cnt = pRootNode->GetChildCount();
for(int i=0; i<cnt; i++)
{
COptionNode* pNode = pRootNode->GetChild(i);
CString strValue = pNode->GetValue().MakeUpper();
// FORCEFONT 옵션
if(strValue == _T("FORCEFONT"))
{
COptionNode* pLevelNode = pNode->GetChild(0);
// 과거 형식과 호환을 위해
if(NULL==pLevelNode)
{
pLevelNode = pNode->CreateChild();
pLevelNode->SetValue(_T("10"));
}
}
// PTRCHEAT 옵션
else if(strValue == _T("PTRCHEAT"))
{
bNeedMigration = TRUE;
bPtrCheat = TRUE;
}
// SOW 옵션
else if(strValue == _T("SOW"))
{
bNeedMigration = TRUE;
bSOW = TRUE;
}
// REMOVESPACE 옵션
else if(strValue == _T("REMOVESPACE"))
{
bNeedMigration = TRUE;
bRemoveSpace = TRUE;
}
// TWOBYTE 옵션
else if(strValue == _T("TWOBYTE"))
{
bNeedMigration = TRUE;
bTwoByte = TRUE;
}
}
// 마이그레이션이 필요하면
if(bNeedMigration)
{
// 텍스트 조작 방식 결정
CString strTransMethod;
if(bPtrCheat) strTransMethod = _T("PTRCHEAT");
else if (bSOW) strTransMethod = _T("SOW");
else strTransMethod = _T("OVERWRITE");
// 필요없는 노드 삭제
pRootNode->DeleteChild(_T("PTRCHEAT"));
pRootNode->DeleteChild(_T("SOW"));
pRootNode->DeleteChild(_T("REMOVESPACE"));
pRootNode->DeleteChild(_T("TWOBYTE"));
// 루프를 돌며 모든 HOOK 노드에 적용
cnt = pRootNode->GetChildCount();
for(int i=0; i<cnt; i++)
{
COptionNode* pNode = pRootNode->GetChild(i);
CString strValue = pNode->GetValue().MakeUpper();
// HOOK 노드
if(strValue == _T("HOOK"))
{
int cnt2 = pNode->GetChildCount();
for(int j=0; j<cnt2; j++)
{
COptionNode* pTransNode = pNode->GetChild(j);
strValue = pTransNode->GetValue().MakeUpper();
// TRANS 노드
if(strValue == _T("TRANS"))
{
pTransNode->DeleteChild(_T("NOP"));
pTransNode->DeleteChild(_T("PTRCHEAT"));
pTransNode->DeleteChild(_T("OVERWRITE"));
pTransNode->DeleteChild(_T("SOW"));
pTransNode->DeleteChild(_T("REMOVESPACE"));
pTransNode->DeleteChild(_T("TWOBYTE"));
COptionNode* pChildNode = NULL;
// 번역작업 방식
pChildNode = pTransNode->CreateChild();
pChildNode->SetValue(strTransMethod);
// 공백제거
if(bRemoveSpace)
{
pChildNode = pTransNode->CreateChild();
pChildNode->SetValue(_T("REMOVESPACE"));
}
// 1바이트를 2바이트로 변환
if(bTwoByte)
{
pChildNode = pTransNode->CreateChild();
pChildNode->SetValue(_T("TWOBYTE"));
}
}
}
} // HOOK 노드 끝
}
}
return bRetVal;
}
//////////////////////////////////////////////////////////////////////////
//
// 옵션을 실제 프로그램에 적용
//
//////////////////////////////////////////////////////////////////////////
BOOL CATCodeMgr::AdjustOption(COptionNode* pRootNode)
{
if(NULL == pRootNode) return FALSE;
ResetOption();
MigrateOption(pRootNode);
//FORCEFONT,HOOK(0x00434343,TRANS([ESP+0x4],ANSI,ALLSAMETEXT))
BOOL bRetVal = TRUE;
int cnt = pRootNode->GetChildCount();
for(int i=0; i<cnt; i++)
{
COptionNode* pNode = pRootNode->GetChild(i);
CString strValue = pNode->GetValue().MakeUpper();
// HOOK 노드
if(strValue == _T("HOOK"))
{
BOOL bHookRes = HookFromOptionNode(pNode);
if(FALSE == bHookRes) m_listRetryHook.push_back(pNode);
} // HOOK 노드 끝
}
return bRetVal;
}
//////////////////////////////////////////////////////////////////////////
//
// 위의 AdjustOption 에서 HOOK 노드를 만날경우 이 함수를 호출해서 적용한다.
//
//////////////////////////////////////////////////////////////////////////
BOOL CATCodeMgr::HookFromOptionNode(COptionNode* pNode)
{
BOOL bRetVal = FALSE;
try
{
// 후킹할 주소
COptionNode* pAddrNode = pNode->GetChild(0);
if(pAddrNode==NULL) throw -1;
CHookPoint* pHookPoint = CHookPoint::CreateInstance(pAddrNode->GetValue());
if(pHookPoint==NULL)
{
//MessageBox(m_hContainerWnd, _T("다음의 주소를 후킹하는데 실패했습니다 : ") + pAddrNode->GetValue(), _T("Hook error"), MB_OK);
//continue;
throw -2;
}
m_listHookPoint.push_back(pHookPoint);
// 이 주소에 대한 후킹 명령들 수집
int cnt2 = pNode->GetChildCount();
for(int j=1; j<cnt2; j++)
{
COptionNode* pNode2 = pNode->GetChild(j);
CString strHookValue = pNode2->GetValue();
// 번역 명령
if(strHookValue.CompareNoCase(_T("TRANS"))==0)
{
int cnt3 = pNode2->GetChildCount();
if(cnt3 < 2) continue;
// 인자
//COptionNode* pDistNode = pNode2->GetChild(0);
//if(pDistNode==NULL)
CString strArgScript = pNode2->GetChild(0)->GetValue();
CString strContextName = pNode2->GetChild(1)->GetValue();
CTransCommand* pTransCmd = pHookPoint->AddTransCmd(strArgScript, strContextName);
// 번역 옵션들 수집
for(int k=2; k<cnt3; k++)
{
COptionNode* pNode3 = pNode2->GetChild(k);
CString strTransOption = pNode3->GetValue().MakeUpper();
// 번역방식
if(strTransOption == _T("NOP"))
{
pTransCmd->SetTransMethod(0);
}
else if(strTransOption == _T("PTRCHEAT"))
{
pTransCmd->SetTransMethod(1);
}
else if(strTransOption == _T("OVERWRITE"))
{
pTransCmd->SetTransMethod(2);
if(pNode3->GetChild(_T("IGNORE")) != NULL)
{
pTransCmd->SetIgnoreBufLen(TRUE);
}
}
else if(strTransOption == _T("SOW"))
{
pTransCmd->SetTransMethod(3);
}
// 멀티바이트 / 유니코드 지정
else if(strTransOption == _T("ANSI"))
{
pTransCmd->SetUnicode(FALSE);
}
else if(strTransOption == _T("UNICODE"))
{
pTransCmd->SetUnicode(TRUE);
}
// 모든 일치하는 텍스트 번역
else if(strTransOption == _T("ALLSAMETEXT"))
{
pTransCmd->SetAllSameText(TRUE);
}
// CLIPKOR 옵션
else if(strTransOption == _T("CLIPKOR"))
{
pTransCmd->SetClipKor(TRUE);
}
// CLIPJPN 옵션
else if(strTransOption == _T("CLIPJPN"))
{
pTransCmd->SetClipJpn(TRUE);
}
}
}
} // end of for ( 이 주소에 대한 후킹 명령들 수집 )
bRetVal = TRUE;
}
catch (int nErrCode)
{
nErrCode = nErrCode;
}
return bRetVal;
}
//////////////////////////////////////////////////////////////////////////
//
// 클립보드에 텍스트 세팅 작업만 하는 쓰레드
//
//////////////////////////////////////////////////////////////////////////
UINT __stdcall CATCodeMgr::ClipboardThreadFunc(LPVOID pParam)
{
while(_Inst && _Inst->m_bRunClipboardThread)
{
DWORD dwRes = WaitForSingleObject(_Inst->m_hClipTextChangeEvent, 300);
// 기다려도 변동 없을 때
if(WAIT_TIMEOUT == dwRes)
{
EnterCriticalSection(&_Inst->m_csClipText);
// 클립보드로 보내야 할 데이터가 있다면
if(_Inst->m_strClipText.IsEmpty() == FALSE)
{
HGLOBAL hGlobal = GlobalAlloc(GHND | GMEM_SHARE, (_Inst->m_strClipText.GetLength() + 1) * sizeof(TCHAR));
LPTSTR pGlobal = (LPTSTR)GlobalLock(hGlobal);
if(pGlobal)
{
_tcscpy(pGlobal, (LPCTSTR)_Inst->m_strClipText);
GlobalUnlock(hGlobal);
OpenClipboard(NULL);
EmptyClipboard();
#ifdef UNICODE
SetClipboardData(CF_UNICODETEXT, hGlobal);
#else
SetClipboardData(CF_TEXT, hGlobal);
#endif
CloseClipboard();
//GlobalFree(hGlobal);
}
_Inst->m_strClipText.Empty();
}
LeaveCriticalSection(&_Inst->m_csClipText);
}
// 기다리는 중 텍스트가 추가 되었을 때
else if(WAIT_OBJECT_0 == dwRes)
{
}
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
//
// 클립보드에 텍스트 세팅
//
//////////////////////////////////////////////////////////////////////////
BOOL CATCodeMgr::SetClipboardText(LPCTSTR cszText)
{
BOOL bRetVal = FALSE;
EnterCriticalSection(&m_csClipText);
m_strClipText += cszText;
LeaveCriticalSection(&m_csClipText);
::SetEvent(m_hClipTextChangeEvent);
return bRetVal;
}
//////////////////////////////////////////////////////////////////////////
//
// 새로운 로드 라이브러리 함수 (A)
// AT코드가 DLL 영역인 경우, 그 DLL이 언제 로드될 지 모르므로
// 이곳에서 감시하고 있다가 로드되는 순간 후킹한다.
//
//////////////////////////////////////////////////////////////////////////
HMODULE __stdcall CATCodeMgr::NewLoadLibraryA(LPCSTR lpFileName)
{
wchar_t wszTmp[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, lpFileName, -1, wszTmp, MAX_PATH);
TRACE(_T("[aral1] NewLoadLibraryA('%s') \n"), wszTmp);
HMODULE hModule = NULL;
if(CATCodeMgr::_Inst)
{
hModule = LoadLibraryA(lpFileName);
// 실패했던 후킹들을 재시도
for(list<COptionNode*>::iterator iter = _Inst->m_listRetryHook.begin();
iter != _Inst->m_listRetryHook.end();)
{
BOOL bHookRes = _Inst->HookFromOptionNode( (*iter) );
if(bHookRes) iter = _Inst->m_listRetryHook.erase(iter);
else iter++;
}
}
return hModule;
}
//////////////////////////////////////////////////////////////////////////
//
// 새로운 로드 라이브러리 함수 (W)
// AT코드가 DLL 영역인 경우, 그 DLL이 언제 로드될 지 모르므로
// 이곳에서 감시하고 있다가 로드되는 순간 후킹한다.
//
//////////////////////////////////////////////////////////////////////////
HMODULE __stdcall CATCodeMgr::NewLoadLibraryW(LPCWSTR lpFileName)
{
TRACE(_T("[aral1] NewLoadLibraryW('%s') \n"), lpFileName);
HMODULE hModule = NULL;
if(CATCodeMgr::_Inst)
{
hModule = LoadLibraryW(lpFileName);
// 실패했던 후킹들을 재시도
for(list<COptionNode*>::iterator iter = _Inst->m_listRetryHook.begin();
iter != _Inst->m_listRetryHook.end();)
{
BOOL bHookRes = _Inst->HookFromOptionNode( (*iter) );
if(bHookRes) iter = _Inst->m_listRetryHook.erase(iter);
else iter++;
}
}
return hModule;
}
int CATCodeMgr::GetAllLoadedModules( PMODULEENTRY32 pRetBuf, int maxCnt )
{
int curCnt = 0;
// 반환 버퍼 초기화
ZeroMemory(pRetBuf, sizeof(PMODULEENTRY32)*maxCnt);
// 프로세스 스냅샷 핸들을 생성
HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if(INVALID_HANDLE_VALUE == hModuleSnap) return 0;
pRetBuf[curCnt].dwSize = sizeof(MODULEENTRY32);
BOOL bExist = Module32First(hModuleSnap, &pRetBuf[curCnt]);
while( bExist == TRUE && curCnt < maxCnt )
{
curCnt++;
pRetBuf[curCnt].dwSize = sizeof(MODULEENTRY32);
bExist = Module32Next(hModuleSnap, &pRetBuf[curCnt]);
}
CloseHandle (hModuleSnap);
return curCnt;
}
| [
"arallab3@883913d8-bf2b-11de-8cd0-f941f5a20a08"
]
| [
[
[
1,
712
]
]
]
|
d847597a0fe7c0c38c1c8342433ea5cd176b693d | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/third_party/WebKit/WebCore/platform/image-decoders/skia/ImageDecoder.h | 003ead907f70283ebcfec911778a2335c597ec2a | [
"Apache-2.0"
]
| permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,660 | h | /*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
* Copyright (C) 2008, 2009 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ImageDecoder_h
#define ImageDecoder_h
#include "IntRect.h"
#include "ImageSource.h"
#include "NativeImageSkia.h"
#include "PlatformString.h"
#include "SharedBuffer.h"
#include <wtf/Assertions.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include "SkBitmap.h"
namespace WebCore {
class RefCountedNativeImageSkia : public RefCounted<RefCountedNativeImageSkia> {
public:
static PassRefPtr<RefCountedNativeImageSkia> create()
{
return adoptRef(new RefCountedNativeImageSkia);
}
const NativeImageSkia& bitmap() const { return m_bitmap; }
NativeImageSkia& bitmap() { return m_bitmap; }
private:
RefCountedNativeImageSkia() {}
NativeImageSkia m_bitmap;
};
// The RGBA32Buffer object represents the decoded image data in RGBA32 format.
// This buffer is what all decoders write a single frame into. Frames are then
// instantiated for drawing by being handed this buffer.
//
// The image data of an RGBA32Buffer is kept in an SkBitmapRef, a refcounting
// container for an SkBitmap. In all normal cases, the refcount should be
// exactly one. The exception happens when resizing the vector<RGBA32Buffer> in
// ImageDecoder::m_frameBufferCache, which copies all the buffers to the new
// vector, thus transiently incrementing the refcount to two.
//
// The choice to use an SkBitmapRef instead of an SkBitmap is not because of
// performance concerns -- SkBitmap refcounts its internal data anyway. Rather,
// we need the aforementioned vector resize to preserve the exact underlying
// SkBitmap object, since we may have already given its address to
// BitmapImage::m_frames. Using an SkBitmap would mean that after ImageDecoder
// resizes its vector, BitmapImage would be holding a pointer to garbage.
class RGBA32Buffer {
public:
enum FrameStatus { FrameEmpty, FramePartial, FrameComplete };
enum FrameDisposalMethod {
// If you change the numeric values of these, make sure you audit all
// users, as some users may cast raw values to/from these constants.
DisposeNotSpecified, // Leave frame in framebuffer
DisposeKeep, // Leave frame in framebuffer
DisposeOverwriteBgcolor, // Clear frame to transparent
DisposeOverwritePrevious, // Clear frame to previous framebuffer contents
};
RGBA32Buffer()
: m_status(FrameEmpty)
, m_duration(0)
, m_disposalMethod(DisposeNotSpecified)
{
m_bitmapRef = RefCountedNativeImageSkia::create();
}
// This constructor doesn't create a new copy of the image data, it only
// increases the ref count of the existing bitmap.
RGBA32Buffer(const RGBA32Buffer& other)
{
m_bitmapRef = RefCountedNativeImageSkia::create();
operator=(other);
}
~RGBA32Buffer()
{
}
// Initialize with another buffer. This function doesn't create a new copy
// of the image data, it only increases the refcount of the existing bitmap.
//
// Normal callers should not generally be using this function. If you want
// to create a copy on which you can modify the image data independently,
// use copyBitmapData() instead.
RGBA32Buffer& operator=(const RGBA32Buffer& other)
{
if (this == &other)
return *this;
m_bitmapRef = other.m_bitmapRef;
setRect(other.rect());
setStatus(other.status());
setDuration(other.duration());
setDisposalMethod(other.disposalMethod());
setHasAlpha(other.hasAlpha());
return *this;
}
void clear()
{
m_bitmapRef = RefCountedNativeImageSkia::create();
m_status = FrameEmpty;
// NOTE: Do not reset other members here; clearFrameBufferCache()
// calls this to free the bitmap data, but other functions like
// initFrameBuffer() and frameComplete() may still need to read
// other metadata out of this frame later.
}
// This function creates a new copy of the image data in |other|, so the
// two images can be modified independently.
void copyBitmapData(const RGBA32Buffer& other)
{
if (this == &other)
return;
m_bitmapRef = RefCountedNativeImageSkia::create();
SkBitmap& bmp = bitmap();
const SkBitmap& otherBmp = other.bitmap();
bmp.setConfig(SkBitmap::kARGB_8888_Config, other.width(),
other.height(), otherBmp.rowBytes());
bmp.allocPixels();
if (width() > 0 && height() > 0) {
memcpy(bmp.getAddr32(0, 0),
otherBmp.getAddr32(0, 0),
otherBmp.rowBytes() * height());
}
}
NativeImageSkia& bitmap() { return m_bitmapRef->bitmap(); }
const NativeImageSkia& bitmap() const { return m_bitmapRef->bitmap(); }
// Must be called before any pixels are written. Will return true on
// success, false if the memory allocation fails.
bool setSize(int width, int height)
{
// This function should only be called once, it will leak memory
// otherwise.
SkBitmap& bmp = bitmap();
ASSERT(bmp.width() == 0 && bmp.height() == 0);
bmp.setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (!bmp.allocPixels())
return false; // Allocation failure, maybe the bitmap was too big.
// Clear the image.
bmp.eraseARGB(0, 0, 0, 0);
return true;
}
int width() const { return bitmap().width(); }
int height() const { return bitmap().height(); }
const IntRect& rect() const { return m_rect; }
FrameStatus status() const { return m_status; }
unsigned duration() const { return m_duration; }
FrameDisposalMethod disposalMethod() const { return m_disposalMethod; }
bool hasAlpha() const { return !bitmap().isOpaque(); }
void setRect(const IntRect& r) { m_rect = r; }
void setStatus(FrameStatus s)
{
if (s == FrameComplete)
m_bitmapRef->bitmap().setDataComplete(); // Tell the bitmap it's done.
m_status = s;
}
void setDuration(unsigned duration) { m_duration = duration; }
void setDisposalMethod(FrameDisposalMethod method) { m_disposalMethod = method; }
void setHasAlpha(bool alpha) { bitmap().setIsOpaque(!alpha); }
static void setRGBA(uint32_t* dest, uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
// We store this data pre-multiplied.
if (a == 0)
*dest = 0;
else {
if (a < 255) {
float alphaPercent = a / 255.0f;
r = static_cast<unsigned>(r * alphaPercent);
g = static_cast<unsigned>(g * alphaPercent);
b = static_cast<unsigned>(b * alphaPercent);
}
*dest = (a << 24 | r << 16 | g << 8 | b);
}
}
void setRGBA(int x, int y, uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
setRGBA(bitmap().getAddr32(x, y), r, g, b, a);
}
private:
RefPtr<RefCountedNativeImageSkia> m_bitmapRef;
IntRect m_rect; // The rect of the original specified frame within the overall buffer.
// This will always just be the entire buffer except for GIF frames
// whose original rect was smaller than the overall image size.
FrameStatus m_status; // Whether or not this frame is completely finished decoding.
unsigned m_duration; // The animation delay.
FrameDisposalMethod m_disposalMethod; // What to do with this frame's data when initializing the next frame.
};
// The ImageDecoder class represents a base class for specific image format decoders
// (e.g., GIF, JPG, PNG, ICO) to derive from. All decoders decode into RGBA32 format
// and the base class manages the RGBA32 frame cache.
class ImageDecoder {
public:
ImageDecoder() : m_failed(false), m_sizeAvailable(false) {}
virtual ~ImageDecoder() {}
// The the filename extension usually associated with an undecoded image of this type.
virtual String filenameExtension() const = 0;
// All specific decoder plugins must do something with the data they are given.
virtual void setData(SharedBuffer* data, bool allDataReceived) { m_data = data; }
// Whether or not the size information has been decoded yet. This default
// implementation just returns true if the size has been set and we have not
// seen a failure. Decoders may want to override this to lazily decode
// enough of the image to get the size.
virtual bool isSizeAvailable() const
{
return !m_failed && m_sizeAvailable;
}
// Requests the size.
virtual IntSize size() const
{
// Requesting the size of an invalid bitmap is meaningless.
ASSERT(!m_failed);
return m_size;
}
// The total number of frames for the image. Classes that support multiple frames
// will scan the image data for the answer if they need to (without necessarily
// decoding all of the individual frames).
virtual int frameCount() { return 1; }
// The number of repetitions to perform for an animation loop.
virtual int repetitionCount() const { return cAnimationNone; }
// Called to obtain the RGBA32Buffer full of decoded data for rendering. The
// decoder plugin will decode as much of the frame as it can before handing
// back the buffer.
virtual RGBA32Buffer* frameBufferAtIndex(size_t index) = 0;
// Whether or not the underlying image format even supports alpha transparency.
virtual bool supportsAlpha() const { return true; }
bool failed() const { return m_failed; }
void setFailed() { m_failed = true; }
// Wipe out frames in the frame buffer cache before |clearBeforeFrame|,
// assuming this can be done without breaking decoding. Different decoders
// place different restrictions on what frames are safe to destroy, so this
// is left to them to implement.
// For convenience's sake, we provide a default (empty) implementation,
// since in practice only GIFs will ever use this.
virtual void clearFrameBufferCache(size_t clearBeforeFrame) { }
protected:
// Called by the image decoders to set their decoded size, this also check
// the size for validity. It will return true if the size was set, or false
// if there is an error. On error, the m_failed flag will be set and the
// caller should immediately stop decoding.
bool setSize(unsigned width, unsigned height)
{
if (isOverSize(width, height)) {
m_failed = true;
return false;
}
m_size = IntSize(width, height);
m_sizeAvailable = true;
return true;
}
RefPtr<SharedBuffer> m_data; // The encoded data.
Vector<RGBA32Buffer> m_frameBufferCache;
mutable bool m_failed;
private:
// This function allows us to make sure the image is not too large. Very
// large images, even if the allocation succeeds, can take a very long time
// to process, giving the appearance of a DoS.
//
// WebKit also seems to like to ask for the size before data is available
// and in some cases when the failed flag is set. Some of these code paths
// such as BitmapImage::resetAnimation then compute the size of the image
// based on the width and height. Because of this, our total computed image
// byte size must never overflow an int.
static bool isOverSize(unsigned width, unsigned height)
{
unsigned long long total_size = static_cast<unsigned long long>(width)
* static_cast<unsigned long long>(height);
if (total_size > 32 * 1024 * 1024) // 32M = 128MB memory total (32 bpp).
return true;
return false;
}
IntSize m_size;
bool m_sizeAvailable;
};
} // namespace WebCore
#endif
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
]
| [
[
[
1,
334
]
]
]
|
18a89ce60eb63b097f282466eb6d04d0f1926a6d | e31046aee3ad2d4600c7f35aaeeba76ee2b99039 | /trunk/libs/bullet/includes/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h | 3dd0a5e25a068e77972f0ccc3774dbb61c673734 | []
| no_license | BackupTheBerlios/trinitas-svn | ddea265cf47aff3e8853bf6d46861e0ed3031ea1 | 7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca | refs/heads/master | 2021-01-23T08:14:44.215249 | 2009-02-18T19:37:51 | 2009-02-18T19:37:51 | 40,749,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,747 | h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
*/
#ifndef BROADPHASE_PROXY_H
#define BROADPHASE_PROXY_H
#include "LinearMath/btScalar.h" //for SIMD_FORCE_INLINE
#include "LinearMath/btAlignedAllocator.h"
/// btDispatcher uses these types
/// IMPORTANT NOTE:The types are ordered polyhedral, implicit convex and concave
/// to facilitate type checking
enum BroadphaseNativeTypes
{
// polyhedral convex shapes
BOX_SHAPE_PROXYTYPE,
TRIANGLE_SHAPE_PROXYTYPE,
TETRAHEDRAL_SHAPE_PROXYTYPE,
CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE,
CONVEX_HULL_SHAPE_PROXYTYPE,
CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE,
//implicit convex shapes
IMPLICIT_CONVEX_SHAPES_START_HERE,
SPHERE_SHAPE_PROXYTYPE,
MULTI_SPHERE_SHAPE_PROXYTYPE,
CAPSULE_SHAPE_PROXYTYPE,
CONE_SHAPE_PROXYTYPE,
CONVEX_SHAPE_PROXYTYPE,
CYLINDER_SHAPE_PROXYTYPE,
UNIFORM_SCALING_SHAPE_PROXYTYPE,
MINKOWSKI_SUM_SHAPE_PROXYTYPE,
MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE,
//concave shapes
CONCAVE_SHAPES_START_HERE,
//keep all the convex shapetype below here, for the check IsConvexShape in broadphase proxy!
TRIANGLE_MESH_SHAPE_PROXYTYPE,
SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE,
///used for demo integration FAST/Swift collision library and Bullet
FAST_CONCAVE_MESH_PROXYTYPE,
//terrain
TERRAIN_SHAPE_PROXYTYPE,
///Used for GIMPACT Trimesh integration
GIMPACT_SHAPE_PROXYTYPE,
///Multimaterial mesh
MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE,
EMPTY_SHAPE_PROXYTYPE,
STATIC_PLANE_PROXYTYPE,
CONCAVE_SHAPES_END_HERE,
COMPOUND_SHAPE_PROXYTYPE,
SOFTBODY_SHAPE_PROXYTYPE,
INVALID_SHAPE_PROXYTYPE,
MAX_BROADPHASE_COLLISION_TYPES
};
///The btBroadphaseProxy is the main class that can be used with the Bullet broadphases.
///It stores collision shape type information, collision filter information and a client object, typically a btCollisionObject or btRigidBody.
ATTRIBUTE_ALIGNED16(struct) btBroadphaseProxy
{
BT_DECLARE_ALIGNED_ALLOCATOR();
///optional filtering to cull potential collisions
enum CollisionFilterGroups
{
DefaultFilter = 1,
StaticFilter = 2,
KinematicFilter = 4,
DebrisFilter = 8,
SensorTrigger = 16,
AllFilter = -1 //all bits sets: DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorTrigger
};
//Usually the client btCollisionObject or Rigidbody class
void* m_clientObject;
short int m_collisionFilterGroup;
short int m_collisionFilterMask;
void* m_multiSapParentProxy;
int m_uniqueId;//m_uniqueId is introduced for paircache. could get rid of this, by calculating the address offset etc.
SIMD_FORCE_INLINE int getUid() const
{
return m_uniqueId;
}
//used for memory pools
btBroadphaseProxy() :m_clientObject(0),m_multiSapParentProxy(0)
{
}
btBroadphaseProxy(void* userPtr,short int collisionFilterGroup, short int collisionFilterMask,void* multiSapParentProxy=0)
:m_clientObject(userPtr),
m_collisionFilterGroup(collisionFilterGroup),
m_collisionFilterMask(collisionFilterMask)
{
m_multiSapParentProxy = multiSapParentProxy;
}
static SIMD_FORCE_INLINE bool isPolyhedral(int proxyType)
{
return (proxyType < IMPLICIT_CONVEX_SHAPES_START_HERE);
}
static SIMD_FORCE_INLINE bool isConvex(int proxyType)
{
return (proxyType < CONCAVE_SHAPES_START_HERE);
}
static SIMD_FORCE_INLINE bool isConcave(int proxyType)
{
return ((proxyType > CONCAVE_SHAPES_START_HERE) &&
(proxyType < CONCAVE_SHAPES_END_HERE));
}
static SIMD_FORCE_INLINE bool isCompound(int proxyType)
{
return (proxyType == COMPOUND_SHAPE_PROXYTYPE);
}
static SIMD_FORCE_INLINE bool isInfinite(int proxyType)
{
return (proxyType == STATIC_PLANE_PROXYTYPE);
}
}
;
class btCollisionAlgorithm;
struct btBroadphaseProxy;
///The btBroadphasePair class contains a pair of aabb-overlapping objects.
///A btDispatcher can search a btCollisionAlgorithm that performs exact/narrowphase collision detection on the actual collision shapes.
ATTRIBUTE_ALIGNED16(struct) btBroadphasePair
{
btBroadphasePair ()
:
m_pProxy0(0),
m_pProxy1(0),
m_algorithm(0),
m_userInfo(0)
{
}
BT_DECLARE_ALIGNED_ALLOCATOR();
btBroadphasePair(const btBroadphasePair& other)
: m_pProxy0(other.m_pProxy0),
m_pProxy1(other.m_pProxy1),
m_algorithm(other.m_algorithm),
m_userInfo(other.m_userInfo)
{
}
btBroadphasePair(btBroadphaseProxy& proxy0,btBroadphaseProxy& proxy1)
{
//keep them sorted, so the std::set operations work
if (&proxy0 < &proxy1)
{
m_pProxy0 = &proxy0;
m_pProxy1 = &proxy1;
}
else
{
m_pProxy0 = &proxy1;
m_pProxy1 = &proxy0;
}
m_algorithm = 0;
m_userInfo = 0;
}
btBroadphaseProxy* m_pProxy0;
btBroadphaseProxy* m_pProxy1;
mutable btCollisionAlgorithm* m_algorithm;
mutable void* m_userInfo;
};
/*
//comparison for set operation, see Solid DT_Encounter
SIMD_FORCE_INLINE bool operator<(const btBroadphasePair& a, const btBroadphasePair& b)
{
return a.m_pProxy0 < b.m_pProxy0 ||
(a.m_pProxy0 == b.m_pProxy0 && a.m_pProxy1 < b.m_pProxy1);
}
*/
class btBroadphasePairSortPredicate
{
public:
bool operator() ( const btBroadphasePair& a, const btBroadphasePair& b )
{
return a.m_pProxy0 > b.m_pProxy0 ||
(a.m_pProxy0 == b.m_pProxy0 && a.m_pProxy1 > b.m_pProxy1) ||
(a.m_pProxy0 == b.m_pProxy0 && a.m_pProxy1 == b.m_pProxy1 && a.m_algorithm > b.m_algorithm);
}
};
SIMD_FORCE_INLINE bool operator==(const btBroadphasePair& a, const btBroadphasePair& b)
{
return (a.m_pProxy0 == b.m_pProxy0) && (a.m_pProxy1 == b.m_pProxy1);
}
#endif //BROADPHASE_PROXY_H
| [
"paradoxon@ab3bda7c-5b37-0410-9911-e7f4556ba333"
]
| [
[
[
1,
238
]
]
]
|
277e8dea19694c7938b3d26116e13bc63b1dce31 | 3949b4be60bfcb67541cc24ee079c969a877d6c9 | /InstallDialog.cpp | 9cb54fba31906b136416f9aec0b045b54655b6f5 | []
| no_license | Spidey01/l4d-maps-manager | 5d4e802f983236419d37f2de2d3fad9000bb60f1 | 24e6ec63fcd3467eb856d473fd619ddb090ce583 | refs/heads/master | 2021-01-19T14:29:40.299860 | 2011-05-28T14:03:04 | 2011-05-28T14:03:04 | 1,813,900 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | #include "InstallDialog.hpp"
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
InstallDialog::InstallDialog(QWidget *parent) :
QDialog(parent)
{
mLayout = new QFormLayout();
instructions = new QLabel(tr("<p>Copy the URL from the details page on"
" l4dmaps.com (in your web browser) and"
" paste it into the box below.</p>"));
mLayout->addWidget(instructions);
mapUrl = new QLineEdit();
mLayout->addRow(tr("Map URL"), mapUrl);
buttons = new QDialogButtonBox(QDialogButtonBox::Ok |
QDialogButtonBox::Cancel);
connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
mLayout->addWidget(buttons);
setLayout(mLayout);
}
| [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
a21619391f16fc2150a0153655bfa744b2f7f188 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/impl/DOMLocatorImpl.hpp | 9fe5b672cef533e88a051d4f00aa6a93f63c603b | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,304 | hpp | /*
* Copyright 2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: DOMLocatorImpl.hpp,v $
* Revision 1.6 2004/09/08 13:55:51 peiyongz
* Apache License Version 2.0
*
* Revision 1.5 2003/03/07 18:07:17 tng
* Return a reference instead of void for operator=
*
* Revision 1.4 2002/11/04 15:07:34 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/05/30 19:26:00 knoaman
* documentation update
*
* Revision 1.2 2002/05/27 18:25:41 tng
* To get ready for 64 bit large file, use XMLSSize_t to represent line and column number.
*
* Revision 1.1 2002/05/23 15:47:24 knoaman
* DOM L3 core - support for DOMError, DOMErrorHandler and DOMLocator
*
*/
#ifndef DOMLOCATORIMPL_HPP
#define DOMLOCATORIMPL_HPP
#include <xercesc/dom/DOMLocator.hpp>
XERCES_CPP_NAMESPACE_BEGIN
/**
* Introduced in DOM Level 3
*
* Implementation of a DOMLocator interface.
*
* @see DOMLocator#DOMLocator
*/
class CDOM_EXPORT DOMLocatorImpl : public DOMLocator
{
public:
/** @name Constructors and Destructor */
//@{
/** Constructor */
DOMLocatorImpl();
DOMLocatorImpl
(
const XMLSSize_t lineNum
, const XMLSSize_t columnNum
, DOMNode* const errorNode
, const XMLCh* const uri
, const XMLSSize_t offset = -1
);
/** Desctructor */
virtual ~DOMLocatorImpl();
//@}
/** @name Get function */
//@{
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Get the line number where the error occured. The value is -1 if there is
* no line number available.
*
* @see #setLineNumber
*/
virtual XMLSSize_t getLineNumber() const;
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Get the column number where the error occured. The value is -1 if there
* is no column number available.
*
* @see #setColumnNumber
*/
virtual XMLSSize_t getColumnNumber() const;
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Get the byte or character offset into the input source, if we're parsing
* a file or a byte stream then this will be the byte offset into that
* stream, but if a character media is parsed then the offset will be the
* character offset. The value is -1 if there is no offset available.
*
* @see #setOffset
*/
virtual XMLSSize_t getOffset() const;
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Get the DOM Node where the error occured, or <code>null</code> if there
* is no node available.
*
* @see #setErrorNode
*/
virtual DOMNode* getErrorNode() const;
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Get the URI where the error occured, or <code>null</code> if there is no
* URI available.
*
* @see #setURI
*/
virtual const XMLCh* getURI() const;
//@}
/** @name Set function */
//@{
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Set the line number of the error
*
* @param lineNumber the line number to set
*
* @see #getLinNumner
*/
virtual void setLineNumber(const XMLSSize_t lineNumber);
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Set the column number of the error
*
* @param columnNumber the column number to set.
*
* @see #getColumnNumner
*/
virtual void setColumnNumber(const XMLSSize_t columnNumber);
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Set the byte/character offset.
*
* @param offset the byte/characte offset to set.
*
* @see #getOffset
*/
virtual void setOffset(const XMLSSize_t offset);
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Set the DOM Node where the error occured
*
* @param errorNode the DOM Node to set
*
* @see #getErrorNode
*/
virtual void setErrorNode(DOMNode* const errorNode);
/**
* <p><b>"Experimental - subject to change"</b></p>
*
* Set the URI where the error occured
*
* @param uri the URI to set.
*
* @see #getURI
*/
virtual void setURI(const XMLCh* const uri);
//@}
private :
/* Unimplemented constructors and operators */
/* Copy constructor */
DOMLocatorImpl(const DOMLocatorImpl&);
/* Assignment operator */
DOMLocatorImpl& operator=(const DOMLocatorImpl&);
// -----------------------------------------------------------------------
// Private data members
//
// fLineNum
// fColumnNum
// Track line/column number of where the error occured
//
// fOffset
// Track character/byte offset in the input source where the error
// occured
//
// fErrorNode
// Current error node where the error occured
//
// fURI
// The uri where the error occured
// -----------------------------------------------------------------------
XMLSSize_t fLineNum;
XMLSSize_t fColumnNum;
XMLSSize_t fOffset;
DOMNode* fErrorNode;
const XMLCh* fURI;
};
// ---------------------------------------------------------------------------
// DOMLocatorImpl: Getter methods
// ---------------------------------------------------------------------------
inline XMLSSize_t DOMLocatorImpl::getLineNumber() const
{
return fLineNum;
}
inline XMLSSize_t DOMLocatorImpl::getColumnNumber() const
{
return fColumnNum;
}
inline XMLSSize_t DOMLocatorImpl::getOffset() const
{
return fOffset;
}
inline DOMNode* DOMLocatorImpl::getErrorNode() const
{
return fErrorNode;
}
inline const XMLCh* DOMLocatorImpl::getURI() const
{
return fURI;
}
// ---------------------------------------------------------------------------
// DOMLocatorImpl: Setter methods
// ---------------------------------------------------------------------------
inline void DOMLocatorImpl::setLineNumber(const XMLSSize_t lineNumber)
{
fLineNum = lineNumber;
}
inline void DOMLocatorImpl::setColumnNumber(const XMLSSize_t columnNumber)
{
fColumnNum = columnNumber;
}
inline void DOMLocatorImpl::setOffset(const XMLSSize_t offset)
{
fOffset = offset;
}
inline void DOMLocatorImpl::setErrorNode(DOMNode* const errorNode)
{
fErrorNode = errorNode;
}
inline void DOMLocatorImpl::setURI(const XMLCh* const uri)
{
fURI = uri;
}
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
292
]
]
]
|
46b3b685033c10db0953d67093d5aa4a3bf67d5b | 0a340b0f117dd183a3ebe774f3e9e5cee821bd64 | /cob_driver/cob_canopen_motor/common/include/cob_canopen_motor/CanDummy.h | 2e9ee79b1e6c12f8aec6e502d9d0a3f5f1e77e40 | []
| no_license | ipa-grg/care-o-bot | f8374381b7b14848794a5c9b273133c3cf74bb9c | c937984d7c00db688f830980576a698d1509f965 | refs/heads/master | 2021-01-16T20:56:20.302177 | 2010-04-23T14:21:57 | 2010-04-23T14:21:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,926 | h | /****************************************************************
*
* Copyright (c) 2010
*
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA)
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: care-o-bot
* ROS stack name: cob3_common
* ROS package name: canopen_motor
* Description:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author: Christian Connette, email:[email protected]
* Supervised by: Christian Connette, email:[email protected]
*
* Date of creation: Feb 2009
* ToDo:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
#ifndef CAN_DUMMY_INCLUDEDEF_H
#define CAN_DUMMY_INCLUDEDEF_H
//-----------------------------------------------
#include <generic_can/CanMsg.h>
//-----------------------------------------------
/**
* Dummy interface of the CAN bus.
* \ingroup DriversCanModul
*/
class CanDummy : public CanItf
{
public:
~CanDummy();
void init(){};
bool transmitMsg(CanMsg CMsg, bool bBlocking){ return true; }
bool receiveMsg(CanMsg* pCMsg){ return false; }
bool receiveMsgRetry(CanMsg* pCMsg, int iNrOfRetry){ return false; }
bool isObjectMode() { return false; }
};
//-----------------------------------------------
#endif
| [
"cpc@okeanos.(none)",
"[email protected]"
]
| [
[
[
1,
58
],
[
60,
83
]
],
[
[
59,
59
]
]
]
|
a8fe8b61447699560577b1da3c256e2fd0c63284 | dbdd79d28ebe34de3aa6d2cedf0d24310b3d8f9a | /ogre-npr/src/OgreApplication.cpp | 61e0be0cc607d8c6edaccc7959bf23b00618d08b | [
"WTFPL"
]
| permissive | sevas/ogre-npr | 5ade1846ca26ed5d0f9a78eb7e7356d1c2a69543 | b3e1219ac4ec3ad63ae9c7e4b4118bfc59c72c2b | refs/heads/master | 2021-01-20T23:17:11.678766 | 2010-01-24T17:22:10 | 2010-01-24T17:22:10 | 400,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,960 | cpp | /* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
//#include "precompiled.h"
#include "OgreApplication.h"
using namespace Ogre;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
// This function will locate the path to our application on OS X,
// unlike windows you can not rely on the curent working directory
// for locating your configuration files and resources.
inline std::string macBundlePath()
{
char path[1024];
CFBundleRef mainBundle = CFBundleGetMainBundle();
assert(mainBundle);
CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
assert(mainBundleURL);
CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);
assert(cfStringRef);
CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
CFRelease(mainBundleURL);
CFRelease(cfStringRef);
return std::string(path);
}
#endif
//-----------------------------------------------------------------------------
OgreApplication::OgreApplication(const String &_title)
:mRoot(NULL)
,mCamera(NULL)
,mSceneMgr(NULL)
,mWindow(NULL)
,mInputManager(NULL)
,mKeyboard(NULL)
,mMouse(NULL)
,mRotateSpeed(0.5)
,mTitle(_title)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
mResourcePath = macBundlePath() + "/Contents/Resources/";
#else
mResourcePath = "";
#endif
}
//-----------------------------------------------------------------------------
OgreApplication::~OgreApplication()
{
delete mRoot;
}
//-----------------------------------------------------------------------------
void OgreApplication::go()
{
if (!initialise())
return;
mRoot->startRendering();
// clean up
destroyScene();
}
//-----------------------------------------------------------------------------
bool OgreApplication::initialise()
{
String pluginsPath;
#ifndef OGRE_STATIC_LIB
pluginsPath = mResourcePath + "plugins.cfg";
#endif
mRoot = new Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");
// add resource locations
addResourceLocations();
// if we cannot initialise Ogre, just abandon the whole deal
if ( !initOgreCore() ) return false;
createSceneManager();
createCamera();
createViewports();
// Set default mipmap level (NB some APIs ignore this)
TextureManager::getSingleton().setDefaultNumMipmaps(5);
// Create any resource listeners (for loading screens)
createResourceListener();
// Initialise resources
initResources();
// Create the scene
createScene();
createInputSystem();
createFrameListener();
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::initOgreCore()
{
// Show the configuration dialog and initialise the system
// You can skip this and use root.restoreConfig() to load configuration
// settings if you were sure there are valid ones saved in ogre.cfg
if(mRoot->restoreConfig() || mRoot->showConfigDialog())
{
// If returned true, user clicked OK so initialise
// Here we choose to let the system create a default rendering window by passing 'true'
mWindow = mRoot->initialise(true, mTitle);
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
void OgreApplication::createSceneManager()
{
mSceneMgr = mRoot->createSceneManager(ST_GENERIC);
}
//-----------------------------------------------------------------------------
void OgreApplication::createCamera()
{
// Create the camera
mCamera = mSceneMgr->createCamera("PlayerCam");
mCamera->setNearClipDistance(1);
mCameraBaseNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("Camera Base Node");
mCameraTargetNode = mCameraBaseNode->createChildSceneNode("Camera Target Node");
mCameraNode = mCameraTargetNode->createChildSceneNode("Camera Node");
mCameraNode->attachObject(mCamera);
mCameraNode->translate(Vector3(0, 0, 200));
}
//-----------------------------------------------------------------------------
void OgreApplication::createViewports()
{
// Create one viewport, entire window
Viewport* vp = mWindow->addViewport(mCamera);
vp->setBackgroundColour(ColourValue(0.5,0.5,0.5));
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
mCamera->setQueryFlags(0);
}
//-----------------------------------------------------------------------------
void OgreApplication::createResourceListener(){}
//-----------------------------------------------------------------------------
void OgreApplication::createFrameListener()
{
mRoot->addFrameListener(this);
}
//-----------------------------------------------------------------------------
void OgreApplication::createInputSystem()
{
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
mWindow->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
unsigned int width, height, depth;
int top, left;
mWindow->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
mMouse->setEventCallback(this);
mKeyboard->setEventCallback(this);
}
//-----------------------------------------------------------------------------
void OgreApplication::addResourceLocations()
{
// Load resource paths from config file
ConfigFile cf;
cf.load(mResourcePath+"resources.cfg");
// Go through all sections & settings in the file
ConfigFile::SectionIterator seci = cf.getSectionIterator();
String secName, typeName, archName;
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
ConfigFile::SettingsMultiMap *settings = seci.getNext();
ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
// OS X does not set the working directory relative to the app,
// In order to make things portable on OS X we need to provide
// the loading with it's own bundle path location
ResourceGroupManager::getSingleton().addResourceLocation(
String(macBundlePath() + "/" + archName), typeName, secName);
#else
ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
#endif
//ResourceGroupManager::getSingleton().addResourceLocation(macBundlePath()+archName, typeName, secName);
}
}
}
//-----------------------------------------------------------------------------
void OgreApplication::initResources()
{
// Initialise, parse scripts etc
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
//-----------------------------------------------------------------------------
void OgreApplication::destroyScene()
{
// mInputManager->destroyInputObject(mMouse);
// mInputManager->destroyInputObject(mKeyboard);
// OIS::InputManager::destroyInputSystem(mInputManager);
mSceneMgr->destroyAllEntities();
}
//-----------------------------------------------------------------------------
//Adjust mouse clipping area
void OgreApplication::windowResized(RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
}
//-----------------------------------------------------------------------------
//Unattach OIS before window shutdown (very important under Linux)
void OgreApplication::windowClosed(RenderWindow* rw)
{
//Only close for window that created OIS (the main window in these demos)
if( rw == mWindow )
{
if( mInputManager )
{
mInputManager->destroyInputObject( mMouse );
mInputManager->destroyInputObject( mKeyboard );
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = 0;
}
}
}
//-----------------------------------------------------------------------------
bool OgreApplication::frameStarted(const FrameEvent& evt)
{
mKeyboard->capture();
mMouse->capture();
if (mKeyboard->isKeyDown(OIS::KC_ESCAPE))
return false;
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::frameEnded(const FrameEvent& evt)
{
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::keyPressed( const OIS::KeyEvent &e )
{
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::keyReleased( const OIS::KeyEvent &e )
{
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::mouseMoved( const OIS::MouseEvent &e )
{
if (e.state.buttonDown(OIS::MB_Right))
{
int dx = e.state.X.rel * mRotateSpeed;
int dy = e.state.Y.rel * mRotateSpeed;
mCameraTargetNode->yaw(Degree(dx), SceneNode::TS_PARENT);
mCameraTargetNode->pitch(Degree(dy));
}
else if (e.state.buttonDown(OIS::MB_Middle))
{
int dy = e.state.Y.rel;
mCameraNode->translate(Vector3(0.0, 0.0, dy));
}
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::mousePressed( const OIS::MouseEvent &e, OIS::MouseButtonID id )
{
return true;
}
//-----------------------------------------------------------------------------
bool OgreApplication::mouseReleased( const OIS::MouseEvent &e, OIS::MouseButtonID id )
{
return true;
}
//-----------------------------------------------------------------------------
void OgreApplication::_createGrid(int _units)
{
SceneNode *gridNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("WorldGrid Node");
ManualObject *axes = mSceneMgr->createManualObject("AXES");
axes->begin("WorldGrid/Axes", RenderOperation::OT_LINE_LIST);
// X axis
axes->position(-_units, 0.0, 0.0);
axes->colour(0.1, 0.0, 0.0);
axes->position( _units, 0.0, 0.0);
axes->colour(1.0, 0.0, 0.0);
// Y Axis
axes->position(0.0, -_units, 0.0);
axes->colour(0.0, 0.1, 0.0);
axes->position(0.0, _units, 0.0);
axes->colour(0.0, 1.0, 0.0);
// Z axis
axes->position( 0.0, 0.0, -_units);
axes->colour(0.0, 0.0, 0.1);
axes->position( 0.0, 0.0, _units);
axes->colour(0.0, 0.0, 1.0);
axes->end();
gridNode->attachObject(axes);
axes->setQueryFlags(0x00);
ManualObject *grid = mSceneMgr->createManualObject("Grid Lines");
grid->begin("WorldGrid/Lines", RenderOperation::OT_LINE_LIST);
float c;
for (int i = 10; i<=_units ; i+=10)
{
c = (i%100) ? 0.6 : 0.7;
grid->position(-_units, 0, i);
grid->colour(c, c, c);
grid->position( _units, 0, i);
grid->colour(c, c, c);
grid->position(-_units, 0, -i);
grid->colour(c, c, c);
grid->position( _units, 0, -i);
grid->colour(c, c, c);
grid->position(i, 0, -_units);
grid->colour(c, c, c);
grid->position(i, 0, _units);
grid->colour(c, c, c);
grid->position(-i, 0, -_units);
grid->colour(c, c, c);
grid->position(-i, 0, _units);
grid->colour(c, c, c);
}
grid->end();
grid->setQueryFlags(0x00);
gridNode->attachObject(grid);
} | [
"none@none"
]
| [
[
[
1,
400
]
]
]
|
877c76c0f38248017f5358c1c601726483c21973 | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Library/CComboToolBar.cpp | 0c37824f19b76b3f92a235a372f78a8e1fd96ec3 | []
| no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,965 | cpp | /*
CComboToolBar.cpp
Classe per il combo nella toolbar (MFC).
Nel file delle risorse bisogna definire l'id relativo al combo (IDC_COMBO_ON_TOOLBAR),
in caso contrario produce un errore in compilazione.
Luca Piergentili, 16/09/00
[email protected]
*/
#include "env.h"
#include "pragma.h"
#include "macro.h"
#include <string.h>
#include "window.h"
#include "CComboToolBar.h"
#include "resource.h"
#include "traceexpr.h"
//#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT
#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG_INFO _TRFLAG_NOTRACE
#define _TRACE_FLAG_WARN _TRFLAG_NOTRACE
#define _TRACE_FLAG_ERR _TRFLAG_NOTRACE
#if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL))
#ifdef PRAGMA_MESSAGE_VERBOSE
#pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro")
#endif
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
BEGIN_MESSAGE_MAP(CComboToolBar,CToolBar)
ON_CBN_SELENDOK(IDC_COMBO_ON_TOOLBAR,OnComboSelEndOk)
ON_CBN_SELCHANGE(IDC_COMBO_ON_TOOLBAR,OnComboSelChange)
END_MESSAGE_MAP()
/*
CComboToolBar()
*/
CComboToolBar::CComboToolBar() : CToolBar()
{
m_nComboIndex = -1;
memset(m_szComboText,'\0',sizeof(m_szComboText));
m_nMessage = m_nCommand = (UINT)-1;
}
/*
OnComboSelEndOk()
*/
void CComboToolBar::OnComboSelEndOk()
{
m_nComboIndex = m_wndCombo.GetCurSel();
m_wndCombo.GetLBText(m_nComboIndex,m_szComboText);
AfxGetMainWnd()->SetFocus();
}
/*
OnComboSelChange()
*/
void CComboToolBar::OnComboSelChange()
{
m_nComboIndex = m_wndCombo.GetCurSel();
m_wndCombo.GetLBText(m_nComboIndex,m_szComboText);
AfxGetMainWnd()->SetFocus();
if(m_nMessage!=(UINT)-1)
/*AfxGetMainWnd()->*/::SendMessage(m_hWnd,m_nMessage,(WPARAM)m_nComboIndex,(LPARAM)m_szComboText);
if(m_nCommand!=(UINT)-1)
/*AfxGetMainWnd()->*/::SendMessage(m_hWnd,WM_COMMAND,MAKELONG(m_nCommand,0),0L);
}
| [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
deaa2c84dbb97ab8ad43b17eca3148235ae25253 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/newline_test.cpp | 68a58f893281c280243a6412c180908ff26e6a0e | [
"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 | 16,271 | cpp | // (C) Copyright Jonathan Turkanis 2004
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#include <string>
#include <boost/iostreams/compose.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/newline.hpp>
#include <boost/iostreams/filter/test.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/utility/base_from_member.hpp>
namespace io = boost::iostreams;
using boost::unit_test::test_suite;
const std::string posix =
"When I was one-and-twenty\n"
"I heard a wise man say,\n"
"'Give crowns and pounds and guineas\n"
"But not your heart away;\n"
"\n"
"Give pearls away and rubies\n"
"But keep your fancy free.'\n"
"But I was one-and-twenty,\n"
"No use to talk to me.\n"
"\n"
"When I was one-and-twenty\n"
"I heard him say again,\n"
"'The heart out of the bosom\n"
"Was never given in vain;\n"
"\n"
"'Tis paid with sighs a plenty\n"
"And sold for endless rue.'\n"
"And I am two-and-twenty,\n"
"And oh, 'tis true, 'tis true.\n";
const std::string dos =
"When I was one-and-twenty\r\n"
"I heard a wise man say,\r\n"
"'Give crowns and pounds and guineas\r\n"
"But not your heart away;\r\n"
"\r\n"
"Give pearls away and rubies\r\n"
"But keep your fancy free.'\r\n"
"But I was one-and-twenty,\r\n"
"No use to talk to me.\r\n"
"\r\n"
"When I was one-and-twenty\r\n"
"I heard him say again,\r\n"
"'The heart out of the bosom\r\n"
"Was never given in vain;\r\n"
"\r\n"
"'Tis paid with sighs a plenty\r\n"
"And sold for endless rue.'\r\n"
"And I am two-and-twenty,\r\n"
"And oh, 'tis true, 'tis true.\r\n";
const std::string mac =
"When I was one-and-twenty\r"
"I heard a wise man say,\r"
"'Give crowns and pounds and guineas\r"
"But not your heart away;\r"
"\r"
"Give pearls away and rubies\r"
"But keep your fancy free.'\r"
"But I was one-and-twenty,\r"
"No use to talk to me.\r"
"\r"
"When I was one-and-twenty\r"
"I heard him say again,\r"
"'The heart out of the bosom\r"
"Was never given in vain;\r"
"\r"
"'Tis paid with sighs a plenty\r"
"And sold for endless rue.'\r"
"And I am two-and-twenty,\r"
"And oh, 'tis true, 'tis true.\r";
const std::string no_final_newline =
"When I was one-and-twenty\n"
"I heard a wise man say,\n"
"'Give crowns and pounds and guineas\n"
"But not your heart away;\n"
"\n"
"Give pearls away and rubies\n"
"But keep your fancy free.'\n"
"But I was one-and-twenty,\n"
"No use to talk to me.\n"
"\n"
"When I was one-and-twenty\n"
"I heard him say again,\n"
"'The heart out of the bosom\n"
"Was never given in vain;\n"
"\n"
"'Tis paid with sighs a plenty\n"
"And sold for endless rue.'\n"
"And I am two-and-twenty,\n"
"And oh, 'tis true, 'tis true.";
const std::string mixed =
"When I was one-and-twenty\n"
"I heard a wise man say,\r\n"
"'Give crowns and pounds and guineas\r"
"But not your heart away;\n"
"\r\n"
"Give pearls away and rubies\r"
"But keep your fancy free.'\n"
"But I was one-and-twenty,\r\n"
"No use to talk to me.\r"
"\r"
"When I was one-and-twenty\r\n"
"I heard him say again,\r"
"'The heart out of the bosom\n"
"Was never given in vain;\r\n"
"\r"
"'Tis paid with sighs a plenty\n"
"And sold for endless rue.'\r\n"
"And I am two-and-twenty,\r"
"And oh, 'tis true, 'tis true.\n";
struct string_source : boost::base_from_member<std::string>, io::array_source {
typedef io::array_source base_type;
typedef boost::base_from_member<std::string> pbase_type;
string_source(const std::string& src)
: pbase_type(src), base_type(member.data(), member.size())
{ }
string_source(const string_source& src)
: pbase_type(src.member), base_type(member.data(), member.size())
{ }
};
void read_newline_filter()
{
using namespace io;
// Test converting to posix format.
BOOST_CHECK(test_input_filter(newline_filter(newline::posix), posix, posix));
BOOST_CHECK(test_input_filter(newline_filter(newline::posix), dos, posix));
BOOST_CHECK(test_input_filter(newline_filter(newline::posix), mac, posix));
BOOST_CHECK(test_input_filter(newline_filter(newline::posix), mixed, posix));
// Test converting to dos format.
BOOST_CHECK(test_input_filter(newline_filter(newline::dos), posix, dos));
BOOST_CHECK(test_input_filter(newline_filter(newline::dos), dos, dos));
BOOST_CHECK(test_input_filter(newline_filter(newline::dos), mac, dos));
BOOST_CHECK(test_input_filter(newline_filter(newline::dos), mixed, dos));
// Test converting to mac format.
BOOST_CHECK(test_input_filter(newline_filter(newline::mac), posix, mac));
BOOST_CHECK(test_input_filter(newline_filter(newline::mac), dos, mac));
BOOST_CHECK(test_input_filter(newline_filter(newline::mac), mac, mac));
BOOST_CHECK(test_input_filter(newline_filter(newline::mac), mixed, mac));
}
void write_newline_filter()
{
using namespace io;
// Test converting to posix format.
BOOST_CHECK(test_output_filter(newline_filter(newline::posix), posix, posix));
BOOST_CHECK(test_output_filter(newline_filter(newline::posix), dos, posix));
BOOST_CHECK(test_output_filter(newline_filter(newline::posix), mac, posix));
BOOST_CHECK(test_output_filter(newline_filter(newline::posix), mixed, posix));
// Test converting to dos format.
BOOST_CHECK(test_output_filter(newline_filter(newline::dos), posix, dos));
BOOST_CHECK(test_output_filter(newline_filter(newline::dos), dos, dos));
BOOST_CHECK(test_output_filter(newline_filter(newline::dos), mac, dos));
BOOST_CHECK(test_output_filter(newline_filter(newline::dos), mixed, dos));
// Test converting to mac format.
BOOST_CHECK(test_output_filter(newline_filter(newline::mac), posix, mac));
BOOST_CHECK(test_output_filter(newline_filter(newline::mac), dos, mac));
BOOST_CHECK(test_output_filter(newline_filter(newline::mac), mac, mac));
BOOST_CHECK(test_output_filter(newline_filter(newline::mac), mixed, mac));
}
void test_input_against_flags(int flags, const std::string& input, bool read)
{
if (read) {
io::copy(
io::compose(
io::newline_checker(flags),
string_source(input)
),
io::null_sink()
);
} else {
io::copy(
string_source(input),
io::compose(io::newline_checker(flags), io::null_sink())
);
}
}
void read_newline_checker()
{
io::filtering_istream in;
io::newline_checker* checker = 0;
// Verify properties of ::posix.
in.push(io::newline_checker(io::newline::posix));
in.push(string_source(::posix));
BOOST_CHECK_NO_THROW(io::copy(in, io::null_sink()));
in.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(in, 0, io::newline_checker);
BOOST_CHECK(checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
in.pop(); // pop checker.
// Verify properties of ::dos.
in.push(io::newline_checker(io::newline::dos));
in.push(string_source(::dos));
try {
io::copy(in, io::null_sink());
} catch (io::newline_error&) {
BOOST_CHECK_MESSAGE(
false, "failed checking for dos line endings"
);
}
in.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(in, 0, io::newline_checker);
BOOST_CHECK(!checker->is_posix());
BOOST_CHECK(checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
in.pop(); // pop checker.
// Verify properties of ::mac.
in.push(io::newline_checker(io::newline::mac));
in.push(string_source(::mac));
BOOST_CHECK_NO_THROW(io::copy(in, io::null_sink()));
in.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(in, 0, io::newline_checker);
BOOST_CHECK(!checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
in.pop(); // pop checker.
// Verify properties of no_final_newline.
in.push(io::newline_checker(io::newline::posix));
in.push(string_source(::no_final_newline));
BOOST_CHECK_NO_THROW(io::copy(in, io::null_sink()));
in.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(in, 0, io::newline_checker);
BOOST_CHECK(checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(!checker->has_final_newline());
in.pop(); // pop checker.
// Verify properties of mixed.
in.push(io::newline_checker());
in.push(string_source(::mixed));
BOOST_CHECK_NO_THROW(io::copy(in, io::null_sink()));
in.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(in, 0, io::newline_checker);
BOOST_CHECK(!checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(checker->is_mixed_posix());
BOOST_CHECK(checker->is_mixed_dos());
BOOST_CHECK(checker->is_mixed_mac());
BOOST_CHECK(checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
in.pop(); // pop checker.
// Verify exceptions when input does not satisfy target conditions.
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::dos, ::posix, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::mac, ::posix, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::posix, ::dos, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::mac, ::dos, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::posix, ::mac, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::dos, ::mac, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::final_newline, ::no_final_newline, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::posix, ::mixed, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::dos, ::mixed, true),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::mac, ::mixed, true),
io::newline_error
)
}
void write_newline_checker()
{
io::filtering_ostream out;
io::newline_checker* checker = 0;
// Verify properties of ::posix.
out.push(io::newline_checker(io::newline::posix));
out.push(io::null_sink());
BOOST_CHECK_NO_THROW(io::copy(string_source(::posix), out))
out.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(out, 0, io::newline_checker);
BOOST_CHECK(checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
out.pop(); // pop checker.
// Verify properties of ::dos.
out.push(io::newline_checker(io::newline::dos));
out.push(io::null_sink());
BOOST_CHECK_NO_THROW(io::copy(string_source(::dos), out))
out.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(out, 0, io::newline_checker);
BOOST_CHECK(!checker->is_posix());
BOOST_CHECK(checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
out.pop(); // pop checker.
// Verify properties of ::mac.
out.push(io::newline_checker(io::newline::mac));
out.push(io::null_sink());
BOOST_CHECK_NO_THROW(io::copy(string_source(::mac), out))
out.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(out, 0, io::newline_checker);
BOOST_CHECK(!checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
out.pop(); // pop checker.
// Verify properties of no_final_newline.
out.push(io::newline_checker(io::newline::posix));
out.push(io::null_sink());
BOOST_CHECK_NO_THROW(io::copy(string_source(::no_final_newline), out))
out.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(out, 0, io::newline_checker);
BOOST_CHECK(checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(!checker->is_mixed());
BOOST_CHECK(!checker->has_final_newline());
out.pop(); // pop checker.
// Verify properties of mixed.
out.push(io::newline_checker());
out.push(io::null_sink());
BOOST_CHECK_NO_THROW(io::copy(string_source(::mixed), out))
out.pop(); // pop source.
checker = BOOST_IOSTREAMS_COMPONENT(out, 0, io::newline_checker);
BOOST_CHECK(!checker->is_posix());
BOOST_CHECK(!checker->is_dos());
BOOST_CHECK(!checker->is_mac());
BOOST_CHECK(checker->is_mixed_posix());
BOOST_CHECK(checker->is_mixed_dos());
BOOST_CHECK(checker->is_mixed_mac());
BOOST_CHECK(checker->is_mixed());
BOOST_CHECK(checker->has_final_newline());
out.pop(); // pop checker.
// Verify exceptions when input does not satisfy target conditions.
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::dos, ::posix, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::mac, ::posix, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::posix, ::dos, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::mac, ::dos, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::posix, ::mac, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::dos, ::mac, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::final_newline, ::no_final_newline, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::posix, ::mixed, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::dos, ::mixed, false),
io::newline_error
)
BOOST_CHECK_THROW(
test_input_against_flags(io::newline::mac, ::mixed, false),
io::newline_error
)
}
test_suite* init_unit_test_suite(int, char* [])
{
test_suite* test = BOOST_TEST_SUITE("newline_filter test");
test->add(BOOST_TEST_CASE(&read_newline_filter));
test->add(BOOST_TEST_CASE(&write_newline_filter));
test->add(BOOST_TEST_CASE(&read_newline_checker));
test->add(BOOST_TEST_CASE(&write_newline_checker));
return test;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
467
]
]
]
|
be52a23536beec9d7d3a6dad5327de68a348dcbf | 10bac563fc7e174d8f7c79c8777e4eb8460bc49e | /matlab/mexBee/bee_grab_all.cpp | a1505ae3add8b2614e0598287672c84fd0e8586d | []
| no_license | chenbk85/alcordev | 41154355a837ebd15db02ecaeaca6726e722892a | bdb9d0928c80315d24299000ca6d8c492808f1d5 | refs/heads/master | 2021-01-10T13:36:29.338077 | 2008-10-22T15:57:50 | 2008-10-22T15:57:50 | 44,953,286 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,770 | cpp | #include "matlab_bee_inc.h"
#include "alcor/matlab/matlab_mx_utils.hpp"
#include <boost/shared_array.hpp>
//--------------------------------------------------------------------++
using namespace all;
//--------------------------------------------------------------------++
#define OBJ_HANDLE_ prhs[0]
//--------------------------------------------------------------------++
#define L_RGB_IMAGE_BUF_ plhs[0]
#define R_RGB_IMAGE_BUF_ plhs[1]
#define XYZ_IMAGE_BUF_ plhs[2]
//--------------------------------------------------------------------++
void bee_grab_all( int nlhs
,mxArray *plhs[]
,int nrhs
,const mxArray
*prhs[])
{
sense::bumblebee_driver_t& bee =
get_object<sense::bumblebee_driver_t>(OBJ_HANDLE_);
bee.grab();
//printf("LEFT\n");
boost::shared_array<core::uint8_t> lbuf_
= bee.get_color_buffer(core::left_img);
//printf("RIGHT\n");
boost::shared_array<core::uint8_t> rbuf_
= bee.get_color_buffer(core::right_img);
//printf("ZED\n");
boost::shared_array<core::single_t> xyz_sptr
= bee.get_depth_buffer();
///
L_RGB_IMAGE_BUF_ = matlab::buffer2array< core::uint8_t >::create_from_planar(
lbuf_.get()
,matlab::row_major
,bee.nrows()
,bee.ncols());
///
R_RGB_IMAGE_BUF_ = matlab::buffer2array< core::uint8_t >::create_from_planar(
rbuf_.get()
,matlab::row_major
,bee.nrows()
,bee.ncols());
XYZ_IMAGE_BUF_ = all::matlab::buffer2array< core::single_t >::create_from_planar(
xyz_sptr.get()
,matlab::row_major
,bee.nrows()
,bee.ncols());
}
//--------------------------------------------------------------------++ | [
"andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81"
]
| [
[
[
1,
57
]
]
]
|
c8e1b4a709277a80f5e77631782e2d6ff8f287ee | 216398e30aca5f7874edfb8b72a13f95c22fbb5a | /Healthcare/Client/Test/LoginDlg.h | 9326968429ef4d7ca41eeb6d08d6282855212153 | []
| no_license | markisme/healthcare | 791813ac6ac811870f3f28d1d31c3d5a07fb2fa2 | 7ab5a959deba02e7637da02a3f3c681548871520 | refs/heads/master | 2021-01-10T07:18:42.195610 | 2009-09-09T13:00:10 | 2009-09-09T13:00:10 | 35,987,767 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 735 | h | #pragma once
#include "Resource.h"
#include <string>
class LoginDlg : public CDialog
{
DECLARE_DYNAMIC(LoginDlg)
public:
LoginDlg(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~LoginDlg();
// 대화 상자 데이터입니다.
enum { IDD = IDD_LOGIN_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
static UINT ThreadFunction(LPVOID pParam);
void ThreadDo();
private:
CEdit _editID;
CEdit _editPass;
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
public:
afx_msg void OnBnClickedOk();
};
| [
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
]
| [
[
[
1,
36
]
]
]
|
856b5b78a9b9fa3a3877954aadd0cede39893fba | 8a2e417c772eba9cf4653d0c688dd3ac96590964 | /prop-src/wam.h | a8e4e8e52dd5f6339128dbd1fc34bd888bee90c9 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | romix/prop-cc | 1a190ba6ed8922428352826de38efb736e464f50 | 3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f | refs/heads/master | 2023-08-30T12:55:00.192286 | 2011-07-19T20:56:39 | 2011-07-19T20:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,618 | h | ///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "..\..\prop-src\wam.ph".
///////////////////////////////////////////////////////////////////////////////
#define PROP_PRINTER_USED
#include <propdefs.h>
#line 1 "../../prop-src/wam.ph"
///////////////////////////////////////////////////////////////////////////////
//
// This file describes the internal abstract machine of the
// constraint compiler, which is based (very) loosely on the Warren
// Abstract Machine (WAM). It also describes various other semantic
// objects used in the analysis of the logic clauses.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef WAM_definitions_h
#define WAM_definitions_h
#include "basics.h"
///////////////////////////////////////////////////////////////////////////////
//
// Forward type definitions.
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/wam.ph"
#line 27 "../../prop-src/wam.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Ty
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Ty_defined
#define datatype_Ty_defined
class a_Ty;
typedef a_Ty * Ty;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Cons
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Cons_defined
#define datatype_Cons_defined
class a_Cons;
typedef a_Cons * Cons;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Exp
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Exp_defined
#define datatype_Exp_defined
class a_Exp;
typedef a_Exp * Exp;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Stmt
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Stmt_defined
#define datatype_Stmt_defined
class a_Stmt;
typedef a_Stmt * Stmt;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Def
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Def_defined
#define datatype_Def_defined
class a_Def;
typedef a_Def * Def;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Decl
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Decl_defined
#define datatype_Decl_defined
class a_Decl;
typedef a_Decl * Decl;
#endif
#line 27 "../../prop-src/wam.ph"
#line 27 "../../prop-src/wam.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Kind of variables. These are characterized as follows, in order
// of priority:
// (a) Global variables are variables that occur as argument
// in a structural pattern. These may escape the life-time of
// the clause.
// (b) Local variables are variables that occur multiple times in a clause
// (if they don't satisfy condition (a)).
// (c) Void variables are variables with only one occurrence. These
// can be elided since they are always unifiable and never accessed.
//
///////////////////////////////////////////////////////////////////////////////
#line 43 "../../prop-src/wam.ph"
#line 137 "../../prop-src/wam.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for VarKind
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_VarKind_defined
#define datatype_VarKind_defined
class a_VarKind;
typedef a_VarKind * VarKind;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Instness
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Instness_defined
#define datatype_Instness_defined
class a_Instness;
typedef a_Instness * Instness;
#endif
# define v_NOinst 0
# define NOinst (Instness)v_NOinst
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Determinism
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Determinism_defined
#define datatype_Determinism_defined
class a_Determinism;
typedef a_Determinism * Determinism;
#endif
# define v_UNKNOWN_DET 0
# define v_DET 1
# define v_SEMI_DET 2
# define v_MULTI_DET 3
# define v_NON_DET 4
# define v_FAIL_DET 5
# define v_ERROR_DET 6
# define UNKNOWN_DET (Determinism)v_UNKNOWN_DET
# define DET (Determinism)v_DET
# define SEMI_DET (Determinism)v_SEMI_DET
# define MULTI_DET (Determinism)v_MULTI_DET
# define NON_DET (Determinism)v_NON_DET
# define FAIL_DET (Determinism)v_FAIL_DET
# define ERROR_DET (Determinism)v_ERROR_DET
enum UnificationMode {
READ_MODE = 0, WRITE_MODE = 1
};
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for WAM
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_WAM_defined
#define datatype_WAM_defined
class a_WAM;
typedef a_WAM * WAM;
#endif
# define v_XX_g_e_t___xXX 0
# define v_XX_g_e_t___yXX 1
# define v_XX_p_r_o_c_e_e_dXX 2
# define v_XX_f_a_i_lXX 3
# define v_XX_d_e_r_e_fXX 4
# define v_XX_u_n_i_f_yXX 5
# define v_XX_u_n_i_f_y___v_a_r_i_a_b_l_eXX 6
# define v_XX_t_r_u_s_t___m_e___e_l_s_e___f_a_i_lXX 7
# define XX_g_e_t___xXX (WAM)v_XX_g_e_t___xXX
# define XX_g_e_t___yXX (WAM)v_XX_g_e_t___yXX
# define XX_p_r_o_c_e_e_dXX (WAM)v_XX_p_r_o_c_e_e_dXX
# define XX_f_a_i_lXX (WAM)v_XX_f_a_i_lXX
# define XX_d_e_r_e_fXX (WAM)v_XX_d_e_r_e_fXX
# define XX_u_n_i_f_yXX (WAM)v_XX_u_n_i_f_yXX
# define XX_u_n_i_f_y___v_a_r_i_a_b_l_eXX (WAM)v_XX_u_n_i_f_y___v_a_r_i_a_b_l_eXX
# define XX_t_r_u_s_t___m_e___e_l_s_e___f_a_i_lXX (WAM)v_XX_t_r_u_s_t___m_e___e_l_s_e___f_a_i_lXX
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Label
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Label_defined
#define datatype_Label_defined
class a_Label;
typedef a_Label * Label;
#endif
///////////////////////////////////////////////////////////////////////////////
// Definition of type WAMs
///////////////////////////////////////////////////////////////////////////////
#line 135 "../../prop-src/wam.ph"
typedef a_List<WAM> * WAMs;
///////////////////////////////////////////////////////////////////////////////
// Definition of type Labels
///////////////////////////////////////////////////////////////////////////////
#line 136 "../../prop-src/wam.ph"
typedef a_List<Label> * Labels;
///////////////////////////////////////////////////////////////////////////////
//
// Base class for datatype VarKind
//
///////////////////////////////////////////////////////////////////////////////
class a_VarKind : public MEM {
public:
enum Tag_VarKind {
tag_VOIDvar = 0, tag_LOCALvar = 1, tag_TEMPvar = 2,
tag_GLOBALvar = 3
};
public:
const Tag_VarKind tag__; // variant tag
protected:
inline a_VarKind(Tag_VarKind t__) : tag__(t__) {}
public:
};
inline int boxed(const a_VarKind *) { return 1; }
inline int untag(const a_VarKind * x) { return x->tag__; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor VarKind::VOIDvar
//
///////////////////////////////////////////////////////////////////////////////
class VarKind_VOIDvar : public a_VarKind {
public:
#line 44 "../../prop-src/wam.ph"
Ty VOIDvar;
inline VarKind_VOIDvar (Ty x_VOIDvar)
: a_VarKind(tag_VOIDvar), VOIDvar(x_VOIDvar)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor VarKind::LOCALvar
//
///////////////////////////////////////////////////////////////////////////////
class VarKind_LOCALvar : public a_VarKind {
public:
#line 45 "../../prop-src/wam.ph"
Ty LOCALvar;
inline VarKind_LOCALvar (Ty x_LOCALvar)
: a_VarKind(tag_LOCALvar), LOCALvar(x_LOCALvar)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor VarKind::TEMPvar
//
///////////////////////////////////////////////////////////////////////////////
class VarKind_TEMPvar : public a_VarKind {
public:
#line 46 "../../prop-src/wam.ph"
Ty TEMPvar;
inline VarKind_TEMPvar (Ty x_TEMPvar)
: a_VarKind(tag_TEMPvar), TEMPvar(x_TEMPvar)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor VarKind::GLOBALvar
//
///////////////////////////////////////////////////////////////////////////////
class VarKind_GLOBALvar : public a_VarKind {
public:
#line 47 "../../prop-src/wam.ph"
Ty GLOBALvar;
inline VarKind_GLOBALvar (Ty x_GLOBALvar)
: a_VarKind(tag_GLOBALvar), GLOBALvar(x_GLOBALvar)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for VarKind
//
///////////////////////////////////////////////////////////////////////////////
inline a_VarKind * VOIDvar (Ty x_VOIDvar)
{
return new VarKind_VOIDvar (x_VOIDvar);
}
inline a_VarKind * LOCALvar (Ty x_LOCALvar)
{
return new VarKind_LOCALvar (x_LOCALvar);
}
inline a_VarKind * TEMPvar (Ty x_TEMPvar)
{
return new VarKind_TEMPvar (x_TEMPvar);
}
inline a_VarKind * GLOBALvar (Ty x_GLOBALvar)
{
return new VarKind_GLOBALvar (x_GLOBALvar);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for VarKind
//
///////////////////////////////////////////////////////////////////////////////
inline VarKind_VOIDvar * _VOIDvar(const a_VarKind * _x_) { return (VarKind_VOIDvar *)_x_; }
inline VarKind_LOCALvar * _LOCALvar(const a_VarKind * _x_) { return (VarKind_LOCALvar *)_x_; }
inline VarKind_TEMPvar * _TEMPvar(const a_VarKind * _x_) { return (VarKind_TEMPvar *)_x_; }
inline VarKind_GLOBALvar * _GLOBALvar(const a_VarKind * _x_) { return (VarKind_GLOBALvar *)_x_; }
///////////////////////////////////////////////////////////////////////////////
//
// Base class for datatype Instness
//
///////////////////////////////////////////////////////////////////////////////
class a_Instness : public MEM {
public:
enum Tag_Instness {
tag_IDinst = 0, tag_FREEinst = 1, tag_GROUNDinst = 2,
tag_BOUNDinst = 3, tag_APPinst = 4, tag_FUNinst = 5,
tag_VARinst = 6
};
public:
const Tag_Instness tag__; // variant tag
protected:
inline a_Instness(Tag_Instness t__) : tag__(t__) {}
public:
};
inline int boxed(const a_Instness * x) { return x != 0; }
inline int untag(const a_Instness * x) { return x ? (x->tag__+1) : 0; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::IDinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_IDinst : public a_Instness {
public:
#line 57 "../../prop-src/wam.ph"
Id IDinst;
inline Instness_IDinst (Id x_IDinst)
: a_Instness(tag_IDinst), IDinst(x_IDinst)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::FREEinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_FREEinst : public a_Instness {
public:
#line 58 "../../prop-src/wam.ph"
Ty FREEinst;
inline Instness_FREEinst (Ty x_FREEinst)
: a_Instness(tag_FREEinst), FREEinst(x_FREEinst)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::GROUNDinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_GROUNDinst : public a_Instness {
public:
#line 59 "../../prop-src/wam.ph"
Ty GROUNDinst;
inline Instness_GROUNDinst (Ty x_GROUNDinst)
: a_Instness(tag_GROUNDinst), GROUNDinst(x_GROUNDinst)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::BOUNDinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_BOUNDinst : public a_Instness {
public:
#line 60 "../../prop-src/wam.ph"
Ty _1; a_List<Instness> * _2;
inline Instness_BOUNDinst (Ty x_1, a_List<Instness> * x_2)
: a_Instness(tag_BOUNDinst), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::APPinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_APPinst : public a_Instness {
public:
#line 61 "../../prop-src/wam.ph"
Cons _1; a_List<Instness> * _2;
inline Instness_APPinst (Cons x_1, a_List<Instness> * x_2)
: a_Instness(tag_APPinst), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::FUNinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_FUNinst : public a_Instness {
public:
#line 62 "../../prop-src/wam.ph"
Instness _1; Instness _2;
inline Instness_FUNinst (Instness x_1, Instness x_2)
: a_Instness(tag_FUNinst), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Instness::VARinst
//
///////////////////////////////////////////////////////////////////////////////
class Instness_VARinst : public a_Instness {
public:
#line 63 "../../prop-src/wam.ph"
Instness VARinst;
inline Instness_VARinst (Instness x_VARinst)
: a_Instness(tag_VARinst), VARinst(x_VARinst)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for Instness
//
///////////////////////////////////////////////////////////////////////////////
inline a_Instness * IDinst (Id x_IDinst)
{
return new Instness_IDinst (x_IDinst);
}
inline a_Instness * FREEinst (Ty x_FREEinst)
{
return new Instness_FREEinst (x_FREEinst);
}
inline a_Instness * GROUNDinst (Ty x_GROUNDinst)
{
return new Instness_GROUNDinst (x_GROUNDinst);
}
inline a_Instness * BOUNDinst (Ty x_1, a_List<Instness> * x_2)
{
return new Instness_BOUNDinst (x_1, x_2);
}
inline a_Instness * APPinst (Cons x_1, a_List<Instness> * x_2)
{
return new Instness_APPinst (x_1, x_2);
}
inline a_Instness * FUNinst (Instness x_1, Instness x_2)
{
return new Instness_FUNinst (x_1, x_2);
}
inline a_Instness * VARinst (Instness x_VARinst)
{
return new Instness_VARinst (x_VARinst);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for Instness
//
///////////////////////////////////////////////////////////////////////////////
inline Instness_IDinst * _IDinst(const a_Instness * _x_) { return (Instness_IDinst *)_x_; }
inline Instness_FREEinst * _FREEinst(const a_Instness * _x_) { return (Instness_FREEinst *)_x_; }
inline Instness_GROUNDinst * _GROUNDinst(const a_Instness * _x_) { return (Instness_GROUNDinst *)_x_; }
inline Instness_BOUNDinst * _BOUNDinst(const a_Instness * _x_) { return (Instness_BOUNDinst *)_x_; }
inline Instness_APPinst * _APPinst(const a_Instness * _x_) { return (Instness_APPinst *)_x_; }
inline Instness_FUNinst * _FUNinst(const a_Instness * _x_) { return (Instness_FUNinst *)_x_; }
inline Instness_VARinst * _VARinst(const a_Instness * _x_) { return (Instness_VARinst *)_x_; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Determinism::VAR_DET
//
///////////////////////////////////////////////////////////////////////////////
class a_Determinism : public MEM {
public:
#line 79 "../../prop-src/wam.ph"
Determinism VAR_DET;
inline a_Determinism (Determinism x_VAR_DET)
: VAR_DET(x_VAR_DET)
{
}
};
inline int boxed(const a_Determinism * x) { return (unsigned long)x >= 7; }
inline int untag(const a_Determinism * x) { return boxed(x) ? 8 : (int)x; }
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for Determinism
//
///////////////////////////////////////////////////////////////////////////////
inline a_Determinism * VAR_DET (Determinism x_VAR_DET)
{
return new a_Determinism (x_VAR_DET);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for Determinism
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Base class for datatype WAM
//
///////////////////////////////////////////////////////////////////////////////
class a_WAM : public MEM {
public:
enum Tag_WAM {
tag_XX_u_n_i_f_y___t_e_r_mXX = 0, tag_XX_t_r_yXX = 1, tag_XX_r_e_t_r_yXX = 2,
tag_XX_t_r_u_s_tXX = 3, tag_XX_t_r_y___m_e___e_l_s_eXX = 4, tag_XX_r_e_t_r_y___m_e___e_l_s_eXX = 5,
tag_XX_l_a_b_e_lXX = 6
};
public:
const Tag_WAM tag__; // variant tag
protected:
inline a_WAM(Tag_WAM t__) : tag__(t__) {}
public:
};
inline int boxed(const a_WAM * x) { return (unsigned long)x >= 8; }
inline int untag(const a_WAM * x) { return boxed(x) ? x->tag__ + 8 : (int)x; }
///////////////////////////////////////////////////////////////////////////////
//
// Pretty printing methods for WAM
//
///////////////////////////////////////////////////////////////////////////////
class PrettyOStream;
extern std::ostream& operator<<(std::ostream&, WAM);
extern PrettyOStream& operator<<(PrettyOStream&, WAM);
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"unify_term"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_u_n_i_f_y___t_e_r_mXX : public a_WAM {
public:
#line 112 "../../prop-src/wam.ph"
Ty _1; Cons _2;
inline WAM_XX_u_n_i_f_y___t_e_r_mXX (Ty x_1, Cons x_2)
: a_WAM(tag_XX_u_n_i_f_y___t_e_r_mXX), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"try"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_t_r_yXX : public a_WAM {
public:
#line 113 "../../prop-src/wam.ph"
Label XX_t_r_yXX;
inline WAM_XX_t_r_yXX (Label x_XX_t_r_yXX)
: a_WAM(tag_XX_t_r_yXX), XX_t_r_yXX(x_XX_t_r_yXX)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"retry"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_r_e_t_r_yXX : public a_WAM {
public:
#line 114 "../../prop-src/wam.ph"
Label XX_r_e_t_r_yXX;
inline WAM_XX_r_e_t_r_yXX (Label x_XX_r_e_t_r_yXX)
: a_WAM(tag_XX_r_e_t_r_yXX), XX_r_e_t_r_yXX(x_XX_r_e_t_r_yXX)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"trust"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_t_r_u_s_tXX : public a_WAM {
public:
#line 115 "../../prop-src/wam.ph"
Label XX_t_r_u_s_tXX;
inline WAM_XX_t_r_u_s_tXX (Label x_XX_t_r_u_s_tXX)
: a_WAM(tag_XX_t_r_u_s_tXX), XX_t_r_u_s_tXX(x_XX_t_r_u_s_tXX)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"try_me_else"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_t_r_y___m_e___e_l_s_eXX : public a_WAM {
public:
#line 116 "../../prop-src/wam.ph"
Label XX_t_r_y___m_e___e_l_s_eXX;
inline WAM_XX_t_r_y___m_e___e_l_s_eXX (Label x_XX_t_r_y___m_e___e_l_s_eXX)
: a_WAM(tag_XX_t_r_y___m_e___e_l_s_eXX), XX_t_r_y___m_e___e_l_s_eXX(x_XX_t_r_y___m_e___e_l_s_eXX)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"retry_me_else"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_r_e_t_r_y___m_e___e_l_s_eXX : public a_WAM {
public:
#line 117 "../../prop-src/wam.ph"
Label XX_r_e_t_r_y___m_e___e_l_s_eXX;
inline WAM_XX_r_e_t_r_y___m_e___e_l_s_eXX (Label x_XX_r_e_t_r_y___m_e___e_l_s_eXX)
: a_WAM(tag_XX_r_e_t_r_y___m_e___e_l_s_eXX), XX_r_e_t_r_y___m_e___e_l_s_eXX(x_XX_r_e_t_r_y___m_e___e_l_s_eXX)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor WAM::"label"
//
///////////////////////////////////////////////////////////////////////////////
class WAM_XX_l_a_b_e_lXX : public a_WAM {
public:
#line 119 "../../prop-src/wam.ph"
Label XX_l_a_b_e_lXX;
inline WAM_XX_l_a_b_e_lXX (Label x_XX_l_a_b_e_lXX)
: a_WAM(tag_XX_l_a_b_e_lXX), XX_l_a_b_e_lXX(x_XX_l_a_b_e_lXX)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for WAM
//
///////////////////////////////////////////////////////////////////////////////
inline a_WAM * XX_u_n_i_f_y___t_e_r_mXX (Ty x_1, Cons x_2)
{
return new WAM_XX_u_n_i_f_y___t_e_r_mXX (x_1, x_2);
}
inline a_WAM * XX_t_r_yXX (Label x_XX_t_r_yXX)
{
return new WAM_XX_t_r_yXX (x_XX_t_r_yXX);
}
inline a_WAM * XX_r_e_t_r_yXX (Label x_XX_r_e_t_r_yXX)
{
return new WAM_XX_r_e_t_r_yXX (x_XX_r_e_t_r_yXX);
}
inline a_WAM * XX_t_r_u_s_tXX (Label x_XX_t_r_u_s_tXX)
{
return new WAM_XX_t_r_u_s_tXX (x_XX_t_r_u_s_tXX);
}
inline a_WAM * XX_t_r_y___m_e___e_l_s_eXX (Label x_XX_t_r_y___m_e___e_l_s_eXX)
{
return new WAM_XX_t_r_y___m_e___e_l_s_eXX (x_XX_t_r_y___m_e___e_l_s_eXX);
}
inline a_WAM * XX_r_e_t_r_y___m_e___e_l_s_eXX (Label x_XX_r_e_t_r_y___m_e___e_l_s_eXX)
{
return new WAM_XX_r_e_t_r_y___m_e___e_l_s_eXX (x_XX_r_e_t_r_y___m_e___e_l_s_eXX);
}
inline a_WAM * XX_l_a_b_e_lXX (Label x_XX_l_a_b_e_lXX)
{
return new WAM_XX_l_a_b_e_lXX (x_XX_l_a_b_e_lXX);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for WAM
//
///////////////////////////////////////////////////////////////////////////////
inline WAM_XX_u_n_i_f_y___t_e_r_mXX * _XX_u_n_i_f_y___t_e_r_mXX(const a_WAM * _x_) { return (WAM_XX_u_n_i_f_y___t_e_r_mXX *)_x_; }
inline WAM_XX_t_r_yXX * _XX_t_r_yXX(const a_WAM * _x_) { return (WAM_XX_t_r_yXX *)_x_; }
inline WAM_XX_r_e_t_r_yXX * _XX_r_e_t_r_yXX(const a_WAM * _x_) { return (WAM_XX_r_e_t_r_yXX *)_x_; }
inline WAM_XX_t_r_u_s_tXX * _XX_t_r_u_s_tXX(const a_WAM * _x_) { return (WAM_XX_t_r_u_s_tXX *)_x_; }
inline WAM_XX_t_r_y___m_e___e_l_s_eXX * _XX_t_r_y___m_e___e_l_s_eXX(const a_WAM * _x_) { return (WAM_XX_t_r_y___m_e___e_l_s_eXX *)_x_; }
inline WAM_XX_r_e_t_r_y___m_e___e_l_s_eXX * _XX_r_e_t_r_y___m_e___e_l_s_eXX(const a_WAM * _x_) { return (WAM_XX_r_e_t_r_y___m_e___e_l_s_eXX *)_x_; }
inline WAM_XX_l_a_b_e_lXX * _XX_l_a_b_e_lXX(const a_WAM * _x_) { return (WAM_XX_l_a_b_e_lXX *)_x_; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor Label::LABEL
//
///////////////////////////////////////////////////////////////////////////////
class a_Label : public MEM {
public:
#line 127 "../../prop-src/wam.ph"
Id LABEL;
inline a_Label (Id x_LABEL)
: LABEL(x_LABEL)
{
}
};
inline int boxed(const a_Label *) { return 1; }
inline int untag(const a_Label *) { return 0; }
///////////////////////////////////////////////////////////////////////////////
//
// Pretty printing methods for Label
//
///////////////////////////////////////////////////////////////////////////////
class PrettyOStream;
extern std::ostream& operator<<(std::ostream&, Label);
extern PrettyOStream& operator<<(PrettyOStream&, Label);
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for Label
//
///////////////////////////////////////////////////////////////////////////////
inline a_Label * LABEL (Id x_LABEL)
{
return new a_Label (x_LABEL);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for Label
//
///////////////////////////////////////////////////////////////////////////////
#line 137 "../../prop-src/wam.ph"
#line 137 "../../prop-src/wam.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Optimization and manipulation of WAM code.
//
///////////////////////////////////////////////////////////////////////////////
extern WAMs peep_hole (WAMs); // peep hole optimizer.
///////////////////////////////////////////////////////////////////////////////
//
// Manipulation routines.
//
///////////////////////////////////////////////////////////////////////////////
extern Instness deref( Instness);
extern Determinism deref( Determinism);
///////////////////////////////////////////////////////////////////////////////
//
// Pretty printers.
//
///////////////////////////////////////////////////////////////////////////////
extern std::ostream& operator << (std::ostream&, WAM);
extern std::ostream& operator << (std::ostream&, WAMs);
extern std::ostream& operator << (std::ostream&, Label);
extern std::ostream& operator << (std::ostream&, Labels);
extern std::ostream& operator << (std::ostream&, Instness);
extern std::ostream& operator << (std::ostream&, Determinism);
#endif
#line 170 "../../prop-src/wam.ph"
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 0
Number of ifs generated = 0
Number of switches generated = 0
Number of labels = 0
Number of gotos = 0
Adaptive matching = disabled
Fast string matching = disabled
Inline downcasts = disabled
--------------------------------------------------------------------------
*/
| [
"[email protected]"
]
| [
[
[
1,
813
]
]
]
|
191e14d4e69fdd7617010e8b16990306f7f60cdd | a31b42df5677d051e843f32cb536b27ec710cd50 | /Arkane/src/Sample.h | 52a83f091b2d8feaa3b877c6e0f5578e79dada30 | []
| no_license | chuckrussell/Project-Volcano | 498ec04deb8a86cbf8c44e612ef24282faa8fa8d | 8f202dfc6bcd65e0523ed52662ed8954c5dda4d2 | refs/heads/master | 2020-04-07T20:45:25.016567 | 2011-02-09T16:20:15 | 2011-02-09T16:20:15 | 1,288,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,518 | h | #ifndef SAMPLE_H
#define SAMPLE_H
#include <fmod.h>
#include <fmod_errors.h>
/*
Sample Class
----------------------------------------------------
Responsible for holding the information about the
sample.
Assumes Time Signature = 4/4
-When a sample is added to a channel, a copy of the sample
object is given to the channel, rather than a reference to
the sample.
-When a sample is added to the channel, it needs to load
itself into memory using the information in the Sample
class.
-Contains a variable that holds the channel that it is
being loaded into
-Must include a function that calculates distance from
beat, and starts playing at that distance. Meaning
that if the sample is started off the beat, it will start
the sample on the previous beat. For example: if the sample
is triggered at beat 2.6, it will behave as if it were
triggered at beat 2
-Assuption the sample will start on the beat(1-2-3-4)
TODO
-Must define the maximum distance from the beat that is allowed
-Make a name attribute for easier reading. The name will be the
filepath unless the file contains a song title.
*/
#include <fmod.hpp>
#include <fmod_errors.h>
class Sample{
private:
char* filePath;
int channelLoadedInto;
int length;
int key;
float BPM;
bool isLoop;
FMOD::Sound * sample;
public:
Sample(void);
~Sample(void);
bool CreateSampleFromFile(char*, FMOD::System*);
bool Play(FMOD::System*, FMOD::Channel*);
};
#endif | [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
39
],
[
42,
51
],
[
53,
54
],
[
59,
61
]
],
[
[
40,
41
],
[
52,
52
],
[
55,
58
]
],
[
[
62,
62
]
]
]
|
c1c06c1f7b492e12edf96d5276481fe252d3dcce | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/2095.cpp | f6c94d2f26a0b92a6a9e690bd7a080a13d2ca838 | []
| no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | #include<cstdio>
//先计算所有乘数,再将它加到被除数上
using namespace std;
enum {
MaxSize = 500001,
};
int num;
int save[MaxSize] = {0};
void init(){
int i,j;
for(i=1;i<=MaxSize/2;i++){
for(j=i;j<MaxSize;j+=i){
save[j] += i;
}
}
}
int main(){
int tstcase;
int t;
init();
scanf("%d ", &tstcase);
while(tstcase --){
scanf("%d ", &num);
if(num <= MaxSize/2){
t = save[num] - num;
} else {
t = save[num];
}
printf("%d\n",t);
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
68a5e37074ea336ed7ac7bab013e6f532120989d | 96ae76a21d65bb48d04f74a2ae8d705b47d1d969 | /pongar/src/Capture.cpp | f39d1094fe1f630c2fcac12e56ec217f19eae9f9 | []
| no_license | tedwp/pongar | d48b9112bb2bfe27428a8df5e9b3bad31c03347e | de96ae581684874e96d562122008b4acd313ebbd | refs/heads/master | 2021-01-10T02:58:43.849201 | 2011-02-07T01:11:46 | 2011-02-07T01:11:46 | 48,293,673 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 15,600 | cpp | #include "Capture.h"
using namespace std;
Capture::Capture(void)
{
m_threshold = THRESHOLD;
m_thresholdBW = THRESHOLD_BW;
}
Capture::~Capture(void)
{
}
Capture& Capture::getInstance(void)
{
static Capture m_instance;
return m_instance;
}
void Capture::init()
{
//cvNamedWindow ("Original Image", CV_WINDOW_AUTOSIZE);
if(SHOW_CONVERTED && !FULLSCREEN_ENABLED)
{
cvNamedWindow ("Converted", CV_WINDOW_AUTOSIZE);
cvResizeWindow("Converted", 300, 80);
}
/*cvNamedWindow ("Stripe", CV_WINDOW_AUTOSIZE);*/
/*cvNamedWindow ("Marker", 0 );
cvResizeWindow("Marker", 120, 120 );*/
initVideoStream();
/*int value = m_threshold;
int max = 255;
cvCreateTrackbar( "Threshold", "Converted", &value, max, trackbarHandler);
int bw_value = Capture::getInstance().m_thresholdBW;
cvCreateTrackbar( "BW Threshold", "Converted", &bw_value, max, bw_trackbarHandler);
*/
m_memStorage = cvCreateMemStorage();
}
void Capture::initVideoStream(void)
{
m_cap = cvCaptureFromCAM (CAM_INDEX);
m_cap = cvCreateCameraCapture (CAM_INDEX);
cvSetCaptureProperty(m_cap, CV_CAP_PROP_FRAME_WIDTH, CAM_WIDTH);
cvSetCaptureProperty(m_cap, CV_CAP_PROP_FRAME_HEIGHT, CAM_HEIGHT);
if (!m_cap) {
cout << "No webcam found\n";
exit(0);
}
}
void Capture::updateMarkerPositions(void)
{
//bool isFirstStripe = true;
bool isFirstMarker = true;
IplImage* iplGrabbed = cvQueryFrame(Capture::getInstance().m_cap);
if(!iplGrabbed){
printf("Could not query frame. Trying to reinitialize.\n");
cvReleaseCapture (&Capture::getInstance().m_cap);
initVideoStream();
return;
}
CvSize picSize = cvGetSize(iplGrabbed);
IplImage* iplDisplay;
if (IMAGE_FLIP_H || IMAGE_FLIP_V)
{
iplDisplay = cvCreateImage(picSize, iplGrabbed->depth, iplGrabbed->nChannels);
if(IMAGE_FLIP_H && IMAGE_FLIP_V)
{
cvFlip(iplGrabbed, iplDisplay, 1);
cvFlip(iplDisplay, iplDisplay, 0);
}
else if(IMAGE_FLIP_H)
{
cvFlip(iplGrabbed, iplDisplay, 1);
}else if(IMAGE_FLIP_V)
{
cvFlip(iplGrabbed, iplDisplay, 0);
}
} else {
iplDisplay = cvCloneImage(iplGrabbed);
}
memcpy( Graphics::getInstance().m_bkgnd, iplDisplay->imageData, sizeof(Graphics::getInstance().m_bkgnd) );
IplImage* iplConverted = cvCreateImage(picSize, IPL_DEPTH_8U, 1);
IplImage* iplThreshold = cvCreateImage(picSize, IPL_DEPTH_8U, 1);
cvConvertImage(iplDisplay, iplConverted, 0);
cvThreshold(iplConverted, iplThreshold, getInstance().m_thresholdBW, 255, CV_THRESH_BINARY);
//cvAdaptiveThreshold(iplConverted, iplThreshold, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 33, 5);
// Find Contours
CvSeq* contours;
cvFindContours(
iplThreshold, Capture::getInstance().m_memStorage, &contours, sizeof(CvContour),
CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE
);
for (; contours; contours = contours->h_next)
{
CvSeq* result = cvApproxPoly(
contours, sizeof(CvContour), Capture::getInstance().m_memStorage, CV_POLY_APPROX_DP,
cvContourPerimeter(contours)*0.02, 0
);
CvRect r = cvBoundingRect(result);
if (r.height < 20 || r.width < 20 || r.height >= iplGrabbed->height - 10 || r.width >= iplGrabbed->width - 10) {
continue;
}
if (result->total==4)
{
int count = 4;
CvPoint *rect = new CvPoint[4];
cvCvtSeqToArray(result, rect);
cvPolyLine(iplGrabbed, &rect, &count, 1, 1, CV_RGB(255,0,0), 2);
float lineParams[16];
for (int i=0; i<4; ++i)
{
cvCircle (iplGrabbed, rect[i], 3, CV_RGB(0,255,0), -1);
double dx = (double)(rect[(i+1)%4].x-rect[i].x)/7.0;
double dy = (double)(rect[(i+1)%4].y-rect[i].y)/7.0;
int stripeLength = (int)(0.8*sqrt (dx*dx+dy*dy));
if (stripeLength < 5)
stripeLength = 5;
//make stripeLength odd (because of the shift in nStop)
stripeLength |= 1;
//e.g. stripeLength = 5 --> from -2 to 2
int nStop = stripeLength>>1;
int nStart = -nStop;
CvSize stripeSize;
stripeSize.width = 3;
stripeSize.height = stripeLength;
CvPoint2D32f stripeVecX;
CvPoint2D32f stripeVecY;
//normalize vectors
double diffLength = sqrt ( dx*dx+dy*dy );
stripeVecX.x = (float) (dx / diffLength);
stripeVecX.y = (float) (dy / diffLength);
stripeVecY.x = stripeVecX.y;
stripeVecY.y = -stripeVecX.x;
IplImage* iplStripe = cvCreateImage( stripeSize, IPL_DEPTH_8U, 1 );
// Array for edge point centers
CvPoint2D32f points[6];
for (int j=1; j<7; ++j)
{
double px = (double)rect[i].x+(double)j*dx;
double py = (double)rect[i].y+(double)j*dy;
CvPoint p;
p.x = (int)px;
p.y = (int)py;
cvCircle (iplGrabbed, p, 2, CV_RGB(0,0,255), -1);
for ( int m = -1; m <= 1; ++m )
{
for ( int n = nStart; n <= nStop; ++n )
{
CvPoint2D32f subPixel;
subPixel.x =(float) ( (double)p.x + ((double)m * stripeVecX.x) + ((double)n * stripeVecY.x));
subPixel.y =(float) ( (double)p.y + ((double)m * stripeVecX.y) + ((double)n * stripeVecY.y));
CvPoint p2;
p2.x = (int)subPixel.x;
p2.y = (int)subPixel.y;
/*if (isFirstStripe)
cvCircle (iplGrabbed, p2, 1, CV_RGB(255,0,255), -1);
else
cvCircle (iplGrabbed, p2, 1, CV_RGB(0,255,255), -1);
*/
int pixel = Capture::getInstance().subpixSampleSafe (iplConverted, subPixel);
int w = m + 1; //add 1 to shift to 0..2
int h = n + ( stripeLength >> 1 ); //add stripelenght>>1 to shift to 0..stripeLength
*(iplStripe->imageData + h * iplStripe->widthStep + w) = pixel; //set pointer to correct position and safe subpixel intensity
}
}
//use sobel operator on stripe
// ( -1 , -2, -1 )
// ( 0 , 0, 0 )
// ( 1 , 2, 1 )
double* sobelValues = new double[stripeLength-2];
for (int n = 1; n < (stripeLength-1); n++)
{
unsigned char* stripePtr = ( unsigned char* )( iplStripe->imageData + (n-1) * iplStripe->widthStep );
double r1 = -stripePtr[ 0 ] - 2 * stripePtr[ 1 ] - stripePtr[ 2 ];
stripePtr += 2*iplStripe->widthStep;
double r3 = stripePtr[ 0 ] + 2 * stripePtr[ 1 ] + stripePtr[ 2 ];
sobelValues[n-1] = r1+r3;
}
double maxVal = -1;
int maxIndex = 0;
for (int n=0; n<stripeLength-2; ++n)
{
if ( sobelValues[n] > maxVal )
{
maxVal = sobelValues[n];
maxIndex = n;
}
}
double y0,y1,y2; // y0 .. y1 .. y2
y0 = (maxIndex <= 0) ? 0 : sobelValues[maxIndex-1];
y1 = sobelValues[maxIndex];
y2 = (maxIndex >= stripeLength-2) ? 0 : sobelValues[maxIndex+1];
//formula for calculating the x-coordinate of the vertex of a parabola, given 3 points with equal distances
//(xv means the x value of the vertex, d the distance between the points):
//xv = x1 + (d / 2) * (y2 - y0)/(2*y1 - y0 - y2)
double pos = (y2 - y0) / (4*y1 - 2*y0 - 2*y2 ); //d = 1 because of the normalization and x1 will be added later
CvPoint2D32f edgeCenter; //exact point with subpixel accuracy
int maxIndexShift = maxIndex - (stripeLength>>1);
//shift the original edgepoint accordingly
edgeCenter.x = (float) ( (double)p.x + (((double)maxIndexShift+pos) * stripeVecY.x));
edgeCenter.y = (float) ((double)p.y + (((double)maxIndexShift+pos) * stripeVecY.y));
/*CvPoint p_tmp;
p_tmp.x = (int)edgeCenter.x;
p_tmp.y = (int)edgeCenter.y;
cvCircle (iplGrabbed, p_tmp, 1, CV_RGB(0,0,255), -1);*/
points[j-1].x = edgeCenter.x;
points[j-1].y = edgeCenter.y;
/*if (isFirstStripe)
{
//IplImage* iplTmp = cvCreateImage( cvSize(100,300), IPL_DEPTH_8U, 1 );
//cvResize( iplStripe, iplTmp, CV_INTER_NN );
//cvShowImage ( "Stripe", iplTmp );//iplStripe );
//cvReleaseImage( &iplTmp );
isFirstStripe = false;
}*/
} // end of loop over edge points of one edge
cvReleaseImage ( &iplStripe );
// we now have the array of exact edge centers stored in "points"
CvMat mat = cvMat ( 1, 6, CV_32FC2, points);
cvFitLine ( &mat, CV_DIST_L2, 0, 0.01, 0.01, &lineParams[4*i] );
// cvFitLine stores the calculated line in lineParams in the following way:
// vec.x, vec.y, point.x, point.y
/*CvPoint p;
p.x=(int)lineParams[4*i+2] - (int)(50.0*lineParams[4*i+0]);
p.y=(int)lineParams[4*i+3] - (int)(50.0*lineParams[4*i+1]);
CvPoint p2;
p2.x = (int)lineParams[4*i+2] + (int)(50.0*lineParams[4*i+0]);
p2.y = (int)lineParams[4*i+3] + (int)(50.0*lineParams[4*i+1]);
cvLine (iplGrabbed, p, p2, CV_RGB(0,255,255), 1, 8, 0);*/
} // end of loop over the 4 edges
// so far we stored the exact line parameters and show the lines in the image
// now we have to calculate the exact corners
CvPoint2D32f corners[4];
for (int i=0; i<4; ++i)
{
int j = (i+1)%4;
double x0,x1,y0,y1,u0,u1,v0,v1;
x0 = lineParams[4*i+2]; y0 = lineParams[4*i+3];
x1 = lineParams[4*j+2]; y1 = lineParams[4*j+3];
u0 = lineParams[4*i+0]; v0 = lineParams[4*i+1];
u1 = lineParams[4*j+0]; v1 = lineParams[4*j+1];
// (x|y) = p + s * vec
// s = Ds / D (see cramer's rule)
// (x|y) = p + (Ds / D) * vec
// (x|y) = (p * D / D) + (Ds * vec / D)
// (x|y) = (p * D + Ds * vec) / D
// (x|y) = a / c;
double a = x1*u0*v1 - y1*u0*u1 - x0*u1*v0 + y0*u0*u1;
double b = -x0*v0*v1 + y0*u0*v1 + x1*v0*v1 - y1*v0*u1;
double c = v1*u0-v0*u1;
if ( c == 0 ) //lines parallel?
{
//std::cout << "lines parallel" << std::endl;
continue;
}
a /= c;
b /= c;
//exact corner
corners[i].x = (float) a;
corners[i].y = (float) b;
/*CvPoint p;
p.x = (int)corners[i].x;
p.y = (int)corners[i].y;
cvCircle (iplGrabbed, p, 5, CV_RGB(i*60,i*60,0), -1);*/
} //finished the calculation of the exact corners
CvPoint2D32f targetCorners[4];
targetCorners[0].x = -0.5; targetCorners[0].y = -0.5;
targetCorners[1].x = 5.5; targetCorners[1].y = -0.5;
targetCorners[2].x = 5.5; targetCorners[2].y = 5.5;
targetCorners[3].x = -0.5; targetCorners[3].y = 5.5;
//create and calculate the matrix of perspective transform
CvMat* projMat = cvCreateMat (3, 3, CV_32F );
cvWarpPerspectiveQMatrix ( corners, targetCorners, projMat);
//create image for the marker
CvSize markerSize;
markerSize.width = 6;
markerSize.height = 6;
IplImage* iplMarker = cvCreateImage( markerSize, IPL_DEPTH_8U, 1 );
//change the perspective in the marker image using the previously calculated matrix
cvWarpPerspective(iplConverted, iplMarker, projMat, CV_WARP_FILL_OUTLIERS, cvScalarAll(0));
cvThreshold(iplMarker, iplMarker, Capture::getInstance().m_thresholdBW, 255, CV_THRESH_BINARY);
//now we have a B/W image of a supposed Marker
// check if border is black
int code = 0;
for (int i = 0; i < 6; ++i)
{
int pixel1 = ((unsigned char*)(iplMarker->imageData + 0*iplMarker->widthStep + i))[0]; //top
int pixel2 = ((unsigned char*)(iplMarker->imageData + 5*iplMarker->widthStep + i))[0]; //bottom
int pixel3 = ((unsigned char*)(iplMarker->imageData + i*iplMarker->widthStep))[0]; //left
int pixel4 = ((unsigned char*)(iplMarker->imageData + i*iplMarker->widthStep + 5))[0]; //right
if ( ( pixel1 > 0 ) || ( pixel2 > 0 ) || ( pixel3 > 0 ) || ( pixel4 > 0 ) )
{
code = -1;
break;
}
}
if ( code < 0 ) continue;
//copy the BW values into cP
int cP[4][4];
for ( int i=0; i < 4; ++i)
{
for ( int j=0; j < 4; ++j)
{
cP[i][j] = ((unsigned char*)(iplMarker->imageData + (i+1)*iplMarker->widthStep + (j+1) ))[0];
cP[i][j] = (cP[i][j]==0) ? 1 : 0; //if black then 1 else 0
}
}
//save the ID of the marker
int codes[4];
codes[0] = codes[1] = codes[2] = codes[3] = 0;
for (int i=0; i < 16; i++)
{
int row = i>>2;
int col = i%4;
codes[0] <<= 1;
codes[0] |= cP[row][col]; // 0°
codes[1] <<= 1;
codes[1] |= cP[3-col][row]; // 90°
codes[2] <<= 1;
codes[2] |= cP[3-row][3-col]; // 180°
codes[3] <<= 1;
codes[3] |= cP[col][3-row]; // 270°
}
if ( (codes[0]==0) || (codes[0]==0xffff) )
continue;
//account for symmetry
code = codes[0];
int angle = 0;
for ( int i=1; i<4; ++i )
{
if ( codes[i] < code )
{
code = codes[i];
angle = i;
}
}
//correct order of corners
if(angle != 0)
{
CvPoint2D32f corrected_corners[4];
for(int i = 0; i < 4; i++) corrected_corners[(i + angle)%4] = corners[i];
for(int i = 0; i < 4; i++) corners[i] = corrected_corners[i];
}
if ( isFirstMarker )
isFirstMarker = false;
// transfer camera coords to screen coords
for(int i = 0; i<4; i++)
{
corners[i].x -= CAM_WIDTH/2;
corners[i].y = -corners[i].y + CAM_HEIGHT/2;
}
//std::cout << "\nMarker found: " << code;
Marker* m = Game::getMarkerById(code);
if(m != NULL)
{
float shizzle[16];
estimateSquarePose( shizzle, corners, m->getSize() );
m->updatePosition(shizzle);
}
cvReleaseMat (&projMat);
cvReleaseImage (&iplMarker);
delete[] rect;
} // end of if(result->total == 4)
} // end of loop over contours
/*cvShowImage("Original Image", iplGrabbed);
*/
if(SHOW_CONVERTED && !FULLSCREEN_ENABLED)
cvShowImage("Converted", iplThreshold);
//isFirstStripe = true;
isFirstMarker = true;
cvReleaseImage (&iplConverted);
cvReleaseImage (&iplThreshold);
cvReleaseImage (&iplDisplay);
cvClearMemStorage ( Capture::getInstance().m_memStorage );
}
int Capture::subpixSampleSafe ( const IplImage* pSrc, CvPoint2D32f p )
{
int x = int( floorf ( p.x ) );
int y = int( floorf ( p.y ) );
if ( x < 0 || x >= pSrc->width - 1 ||
y < 0 || y >= pSrc->height - 1 )
return 127;
int dx = int ( 256 * ( p.x - floorf ( p.x ) ) );
int dy = int ( 256 * ( p.y - floorf ( p.y ) ) );
unsigned char* i = ( unsigned char* ) ( ( pSrc->imageData + y * pSrc->widthStep ) + x );
int a = i[ 0 ] + ( ( dx * ( i[ 1 ] - i[ 0 ] ) ) >> 8 );
i += pSrc->widthStep;
int b = i[ 0 ] + ( ( dx * ( i[ 1 ] - i[ 0 ] ) ) >> 8 );
return a + ( ( dy * ( b - a) ) >> 8 );
}
void Capture::cleanup()
{
cvReleaseMemStorage (&m_memStorage);
cvReleaseCapture (&(Capture::getInstance().m_cap));
//cvDestroyWindow ("Original Image");
if(SHOW_CONVERTED && !FULLSCREEN_ENABLED)
cvDestroyWindow ("Converted");
//cvDestroyWindow ("Stripe");
//cvDestroyWindow ("Marker");
}
//trackbar
/*void Capture::trackbarHandler(int pos)
{
getInstance().m_thresholdBW = pos;
}
void Capture::bw_trackbarHandler(int pos)
{
getInstance().m_thresholdBW = pos;
}*/
int Capture::getThreshold(void)
{
return m_threshold;
}
int Capture::getThresholdBW(void)
{
return m_thresholdBW;
}
void Capture::increaseThreshold(void)
{
if(m_threshold < 255)
m_threshold++;
}
void Capture::increaseThresholdBW(void)
{
if(m_thresholdBW < 255)
m_thresholdBW++;
}
void Capture::decreaseThreshold(void)
{
if(m_thresholdBW > 0)
m_threshold--;
}
void Capture::decreaseThresholdBW(void)
{
if(m_thresholdBW > 0)
m_thresholdBW--;
} | [
"[email protected]",
"salatgurke00@cd860a2f-db29-0b79-333e-049c8ca359aa",
"[email protected]"
]
| [
[
[
1,
6
],
[
9,
20
],
[
22,
31
],
[
35,
35
],
[
37,
39
],
[
41,
41
],
[
43,
45
],
[
50,
53
],
[
60,
70
],
[
72,
75
],
[
77,
78
],
[
80,
92
],
[
98,
102
],
[
104,
353
],
[
355,
435
],
[
438,
448
],
[
450,
454
],
[
456,
464
],
[
466,
489
],
[
495,
497
],
[
501,
502
],
[
504,
504
],
[
506,
509
],
[
540,
540
]
],
[
[
7,
8
],
[
36,
36
],
[
40,
40
],
[
42,
42
],
[
103,
103
],
[
354,
354
],
[
503,
503
],
[
505,
505
],
[
510,
539
]
],
[
[
21,
21
],
[
32,
34
],
[
46,
49
],
[
54,
59
],
[
71,
71
],
[
76,
76
],
[
79,
79
],
[
93,
97
],
[
436,
437
],
[
449,
449
],
[
455,
455
],
[
465,
465
],
[
490,
494
],
[
498,
500
]
]
]
|
fa877977f9cb594d67250d09cb975050d9bc2007 | 53ee90fbc1011cb17ba013d0a49812697d4e6130 | /MootoritePlaat/MootoriteJaam/CMotor.h | c2c487cfdd705159addbd2366af80930e817db50 | []
| no_license | janoschtraumstunde/Robin | c3f68667c37c44e19473119b4b9b9be0fe2fb57f | bd691cbd2a0091e5100df5dfe1268d27c99b39f6 | refs/heads/master | 2021-01-12T14:06:44.095094 | 2010-12-09T14:34:27 | 2010-12-09T14:34:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | #pragma once
class Motor {
byte pwmPin;
byte dirPin;
byte minPwm;
byte maxPwm;
public:
int speed;
byte pwm;
bool direction;
Motor(byte speedPin, byte directionPin);
void setSpeedWithDirection(int newSpeed);
void stop();
void setMinMaxPwm(byte min, byte max);
private:
void setPwm(byte newPwm);
void setDirection(bool forward);
};
| [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
681310480f08f433b9fa7aed80e1bbfb235130e8 | f71e82b7ed19200280b7164a2e959310d9bfa210 | /ExampleAIModule/ExampleAIModule/Grafo.h | be4786981872e27abfc34dcfbe04abcee26da493 | []
| no_license | albertouri/manolobot | 05cf4ee217e85f1332e0e063fcc209da4b71c7b5 | 44e7fee46abcf4f1efa6d292ea8ec7cdc57eb7c8 | refs/heads/master | 2021-01-02T08:32:48.281836 | 2011-02-03T23:28:08 | 2011-02-03T23:28:08 | 39,591,406 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 924 | h | #pragma once
#include "Nodo.h"
using namespace BWAPI;
using namespace BWTA;
class Grafo
{
public:
Grafo(int cantNodos);
~Grafo(void);
void agregarNodo(Nodo *n);
/*Region* primerNodoNiveles();
Region* siguienteNodoNiveles();*/
Position* primerNodoNiveles();
Position* siguienteNodoNiveles();
void dibujarPuntosVisitar();
//void dibujarRegionesNiveles();
private:
// estructura de datos para almacenar el grafo (lista de adyacencia)
Nodo* listaAdy;
// puntero para el recorrido por niveles, apunta al nodo que se esta recorriendo actualmente
//std::listRegiones<Region*> nivelesRegiones;
std::list<Position*> niveles;
//std::list<Region*>::iterator ItNivelesRegiones;
std::list<Position*>::iterator ItNiveles;
// devuelve el indice de la region pasada como parametro en la lista de adyacencia
int indiceRegion(Region *reg);
void crearListaNiveles();
};
| [
"marianomoreno3@82b963ee-1e64-6eb5-a9c5-6632919fd137"
]
| [
[
[
1,
40
]
]
]
|
d75b3d813d4af7caba3a0a92dec93d34a4ffda01 | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /plugins/dev9/dev9ghzdrk/Win32/net.cpp | c0f2fe50a1d44f5ccd543c6ac2dbed392086f615 | []
| no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | cpp | #include "net.h"
#include "Dev9.h"
//mtfifo<NetPacket*> rx_fifo;
//mtfifo<NetPacket*> tx_fifo;
NetAdapter* nif;
HANDLE rx_thread;
volatile bool RxRunning=false;
//rx thread
DWORD WINAPI NetRxThread(LPVOID lpThreadParameter)
{
NetPacket tmp;
while(RxRunning)
{
while(rx_fifo_can_rx() && nif->recv(&tmp))
{
rx_process(&tmp);
}
Sleep(10);
}
return 0;
}
void tx_put(NetPacket* pkt)
{
nif->send(pkt);
//pkt must be copied if its not processed by here, since it can be allocated on the callers stack
}
void InitNet(NetAdapter* ad)
{
nif=ad;
RxRunning=true;
rx_thread=CreateThread(0,0,NetRxThread,0,CREATE_SUSPENDED,0);
SetThreadPriority(rx_thread,THREAD_PRIORITY_HIGHEST);
ResumeThread(rx_thread);
}
void TermNet()
{
RxRunning=false;
printf("Waiting for RX-net thread to terminate..");
WaitForSingleObject(rx_thread,-1);
printf(".done\n");
delete nif;
} | [
"zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84"
]
| [
[
[
1,
51
]
]
]
|
bbdddc09eb10640d99b5fc5efbf93d085dd378bf | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPGroup.h | d056822a86eb66900c381863ea36994830b8f390 | []
| no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | h | #if !defined(AFX_BCGPGROUP_H__917CCAFD_2ED2_44EC_8297_0C3A5C62F28F__INCLUDED_)
#define AFX_BCGPGROUP_H__917CCAFD_2ED2_44EC_8297_0C3A5C62F28F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
//
// BCGPGroup.h : header file
//
#include "BCGCBPro.h"
/////////////////////////////////////////////////////////////////////////////
// CBCGPGroup window
class BCGCBPRODLLEXPORT CBCGPGroup : public CButton
{
DECLARE_DYNAMIC(CBCGPGroup)
// Construction
public:
CBCGPGroup();
// Attributes
public:
BOOL m_bOnGlass;
BOOL m_bVisualManagerStyle;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBCGPGroup)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CBCGPGroup();
// Generated message map functions
protected:
//{{AFX_MSG(CBCGPGroup)
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
//}}AFX_MSG
afx_msg LRESULT OnBCGSetControlVMMode (WPARAM, LPARAM);
afx_msg LRESULT OnBCGSetControlAero (WPARAM, LPARAM);
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BCGPGROUP_H__917CCAFD_2ED2_44EC_8297_0C3A5C62F28F__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
]
| [
[
[
1,
69
]
]
]
|
74a60cb59372708c28be42cf2a29111257694098 | 95e051bc96bd3f765ce1cec4868535b667be81b6 | /ExplodedVolume/VolumeRenderer/Shader.cpp | e8c5ed65f77fbb92da1d3995de19e8b4670198fb | []
| no_license | fabio-miranda/exploded | 6aacdb5ca1250b676990572ef028fcbc0af93b1a | 12ca185b161b78d0b903c86fb5a08cee3ed87362 | refs/heads/master | 2021-05-29T09:06:03.007813 | 2010-02-26T04:40:32 | 2010-02-26T04:40:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,790 | cpp | #include "Shader.h"
Shader::Shader(char* vertexShaderFile, char* fragShaderFile){
LoadFiles(vertexShaderFile, fragShaderFile);
}
Shader::~Shader(){
glDetachObjectARB(m_shaderProg, m_shaderVert);
glDeleteObjectARB(m_shaderVert);
glDetachObjectARB(m_shaderProg, m_shaderFrag);
glDeleteObjectARB(m_shaderFrag);
glDeleteObjectARB(m_shaderProg);
}
void Shader::Enable(){
glUseProgramObjectARB(m_shaderProg);
}
void Shader::Disable(){
glUseProgramObjectARB( 0 );
}
void Shader::LoadFiles(char* vertexShaderFile, char* fragShaderFile){
char *vs = NULL,*fs = NULL;
m_shaderVert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
m_shaderFrag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
vs = textFileRead(vertexShaderFile);
fs = textFileRead(fragShaderFile);
if(vs != NULL && fs != NULL){
const char * vv = vs;
const char * ff = fs;
glShaderSourceARB(m_shaderVert, 1, &vv,NULL);
glShaderSourceARB(m_shaderFrag, 1, &ff,NULL);
free(vs);free(fs);
glCompileShaderARB(m_shaderVert);
glCompileShaderARB(m_shaderFrag);
printInfoLog(m_shaderVert);
printInfoLog(m_shaderFrag);
m_shaderProg = glCreateProgramObjectARB();
glAttachObjectARB(m_shaderProg,m_shaderVert);
glAttachObjectARB(m_shaderProg,m_shaderFrag);
glLinkProgramARB(m_shaderProg);
printInfoLog(m_shaderProg);
}
else if(fs == NULL){
const char * vv = vs;
const char * ff = fs;
glShaderSourceARB(m_shaderVert, 1, &vv,NULL);
free(vs);
glCompileShaderARB(m_shaderVert);
printInfoLog(m_shaderVert);
m_shaderProg = glCreateProgramObjectARB();
glAttachObjectARB(m_shaderProg,m_shaderVert);
glLinkProgramARB(m_shaderProg);
printInfoLog(m_shaderProg);
}
} | [
"fabiom@2fa1dc7e-98ce-11de-bff5-93fd3790126f"
]
| [
[
[
1,
85
]
]
]
|
e60809334dc7d55b63ca17cd51beb13b5ab7d9bb | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/chromium/public/WebSecurityOrigin.h | 768c1e8840f1547163d19dfc671e8236b3a4f623 | [
"BSD-2-Clause"
]
| permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,507 | h | /*
* Copyright (C) 2010 Google Inc. 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.
*/
#ifndef WebSecurityOrigin_h
#define WebSecurityOrigin_h
#include "WebCommon.h"
#if WEBKIT_IMPLEMENTATION
namespace WebCore { class SecurityOrigin; }
namespace WTF { template <typename T> class PassRefPtr; }
#endif
namespace WebKit {
class WebSecurityOriginPrivate;
class WebString;
class WebURL;
class WebSecurityOrigin {
public:
~WebSecurityOrigin() { reset(); }
WebSecurityOrigin() : m_private(0) { }
WebSecurityOrigin(const WebSecurityOrigin& s) : m_private(0) { assign(s); }
WebSecurityOrigin& operator=(const WebSecurityOrigin& s)
{
assign(s);
return *this;
}
WEBKIT_API static WebSecurityOrigin createFromDatabaseIdentifier(const WebString& databaseIdentifier);
WEBKIT_API static WebSecurityOrigin createFromString(const WebString&);
WEBKIT_API static WebSecurityOrigin create(const WebURL&);
WEBKIT_API void reset();
WEBKIT_API void assign(const WebSecurityOrigin&);
bool isNull() const { return !m_private; }
WEBKIT_API WebString protocol() const;
WEBKIT_API WebString host() const;
WEBKIT_API unsigned short port() const;
// The empty WebSecurityOrigin is the least privileged WebSecurityOrigin.
WEBKIT_API bool isEmpty() const;
// Returns true if this WebSecurityOrigin can script objects in the given
// SecurityOrigin. For example, call this function before allowing
// script from one security origin to read or write objects from
// another SecurityOrigin.
WEBKIT_API bool canAccess(const WebSecurityOrigin&) const;
// Returns true if this WebSecurityOrigin can read content retrieved from
// the given URL. For example, call this function before allowing script
// from a given security origin to receive contents from a given URL.
WEBKIT_API bool canRequest(const WebURL&) const;
// Returns a string representation of the WebSecurityOrigin. The empty
// WebSecurityOrigin is represented by "null". The representation of a
// non-empty WebSecurityOrigin resembles a standard URL.
WEBKIT_API WebString toString() const;
// Returns a string representation of this WebSecurityOrigin that can
// be used as a file. Should be used in storage APIs only.
WEBKIT_API WebString databaseIdentifier() const;
// Returns true if this WebSecurityOrigin can access usernames and
// passwords stored in password manager.
WEBKIT_API bool canAccessPasswordManager() const;
#if WEBKIT_IMPLEMENTATION
WebSecurityOrigin(const WTF::PassRefPtr<WebCore::SecurityOrigin>&);
WebSecurityOrigin& operator=(const WTF::PassRefPtr<WebCore::SecurityOrigin>&);
operator WTF::PassRefPtr<WebCore::SecurityOrigin>() const;
#endif
private:
void assign(WebSecurityOriginPrivate*);
WebSecurityOriginPrivate* m_private;
};
} // namespace WebKit
#endif
| [
"[email protected]"
]
| [
[
[
1,
112
]
]
]
|
1846c3fee894bd379d509e404f9e57ca9f34f559 | ce0622a0f49dd0ca172db04efdd9484064f20973 | /tools/GameList/Common/AtgModel.cpp | 7ff36b70c7d05f93cf1f4e7cb7d3ce216e4e3038 | []
| no_license | maninha22crazy/xboxplayer | a78b0699d4002058e12c8f2b8c83b1cbc3316500 | e9ff96899ad8e8c93deb3b2fe9168239f6a61fe1 | refs/heads/master | 2020-12-24T18:42:28.174670 | 2010-03-14T13:57:37 | 2010-03-14T13:57:37 | 56,190,024 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,490 | cpp | //-----------------------------------------------------------------------------
// model.cpp
//
// Xbox Advanced Technology Group.
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "AtgSceneMesh.h"
#include "AtgMaterials.h"
#include "AtgModel.h"
namespace ATG
{
CONST StringID Model::TypeID( L"Model" );
//-----------------------------------------------------------------------------
// Name: Model::AddMesh()
//-----------------------------------------------------------------------------
VOID Model::AddMesh( BaseMesh* pMesh, DWORD dwMeshMappingFlags )
{
assert( pMesh );
MeshMapping mi;
mi.pMesh = pMesh;
mi.dwFlags = dwMeshMappingFlags;
m_MeshMappings.push_back( mi );
}
//-----------------------------------------------------------------------------
// Name: Model::GetMesh()
//-----------------------------------------------------------------------------
BaseMesh* Model::GetMesh( CONST WCHAR* strName ) CONST
{
for( UINT i = 0; i < m_MeshMappings.size(); i++ )
{
if( m_MeshMappings[i].pMesh->GetName() == strName )
return m_MeshMappings[i].pMesh;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Name: Model::RemoveMesh()
//-----------------------------------------------------------------------------
BOOL Model::RemoveMesh( CONST BaseMesh* pMesh )
{
std::vector<MeshMapping>::iterator i;
for( i = m_MeshMappings.begin(); i != m_MeshMappings.end(); i++ )
{
if( i->pMesh == pMesh )
{
m_MeshMappings.erase(i);
return TRUE;
}
}
return FALSE;
}
//-----------------------------------------------------------------------------
// Name: Model::AddMaterial()
//-----------------------------------------------------------------------------
VOID Model::AddMaterial( UINT MeshIndex, UINT MaterialIndex, MaterialInstance* pMaterial )
{
// assert that the mesh index is valid
assert( MeshIndex < m_MeshMappings.size() );
// assign the material
// $TODO: maybe do this a better way, if things are added out-of-order
if( MaterialIndex == m_MeshMappings[MeshIndex].Materials.size() )
{
m_MeshMappings[MeshIndex].Materials.push_back( pMaterial );
}
else
{
m_MeshMappings[MeshIndex].Materials[MaterialIndex] = pMaterial;
}
};
//-----------------------------------------------------------------------------
// Name: Model::GetMeshFlagUnion()
//-----------------------------------------------------------------------------
DWORD Model::GetMeshFlagUnion() CONST
{
DWORD dwFlagUnion = 0;
for( UINT i = 0; i < m_MeshMappings.size(); i++ )
dwFlagUnion |= m_MeshMappings[i].pMesh->GetFlags();
return dwFlagUnion;
}
//-----------------------------------------------------------------------------
// Name: Model::GetMeshMappingFlagUnion()
//-----------------------------------------------------------------------------
DWORD Model::GetMeshMappingFlagUnion() CONST
{
DWORD dwFlagUnion = 0;
for( UINT i = 0; i < m_MeshMappings.size(); i++ )
dwFlagUnion |= m_MeshMappings[i].dwFlags;
return dwFlagUnion;
}
BOOL Model::ContainsOpaqueSubsets() const
{
DWORD dwMeshMappingCount = ( DWORD )m_MeshMappings.size();
for( DWORD i = 0; i < dwMeshMappingCount; ++i )
{
const MeshMapping& mm = m_MeshMappings[i];
DWORD dwMaterialCount = ( DWORD )mm.Materials.size();
for( DWORD j = 0; j < dwMaterialCount; ++j )
{
MaterialInstance* pMaterial = mm.Materials[j];
if( !pMaterial->IsTransparent() )
return TRUE;
}
}
return FALSE;
}
BOOL Model::ContainsTransparentSubsets() const
{
DWORD dwMeshMappingCount = ( DWORD )m_MeshMappings.size();
for( DWORD i = 0; i < dwMeshMappingCount; ++i )
{
const MeshMapping& mm = m_MeshMappings[i];
DWORD dwMaterialCount = ( DWORD )mm.Materials.size();
for( DWORD j = 0; j < dwMaterialCount; ++j )
{
MaterialInstance* pMaterial = mm.Materials[j];
if( pMaterial->IsTransparent() )
return TRUE;
}
}
return FALSE;
}
} // namespace ATG
| [
"goohome@343f5ee6-a13e-11de-ba2c-3b65426ee844"
]
| [
[
[
1,
143
]
]
]
|
23372004ef342345daee3736156bb465558a65af | 1584e139552d36bbbcc461deb81c22a06d42b713 | /server/server.cpp | 1841a0b27633deda9ec3c19af8d777627f98881a | []
| no_license | joshmg/battle | fd458da8be387ff0b4f80f0d2029759cd3fabe30 | 14ab71d903fe0bcf7c3285169026b4f96a186309 | refs/heads/master | 2020-05-18T17:20:00.768647 | 2010-09-28T04:34:34 | 2010-09-28T04:34:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,508 | cpp | // File: server.cpp
// Written by Joshua Green
#include "server.h"
#include "../shared/shared.h"
#include "../shared/darkmatter.h"
#include "../shared/db/db.h"
#include "../shared/db_decl.h"
#include "../shared/connection/transmission.h"
#include "../shared/str/str.h"
#include <string>
#include <vector>
#include <ctime>
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;
extern vector<server*> hosts;
std::map<int, server*> all_servers;
int server::SERVER_COUNT;
bool STOP_TIME_LOOP = false;
//extern map<string, darkmatter*> all_dmatter_class;
extern void do_nothing(void*);
void time_loop(void*);
server::server() {
_id = SERVER_COUNT;
all_servers[_id] = this;
SERVER_COUNT++;
_shutting_down = false;
_battle_server = true;
}
server::~server() {
shutdown(1);
}
int server::size() const {
return _connections.size();
}
void server::shutdown(int WAIT_TIME) {
cout << "Server (ID " << _id << ") shutting down in " << WAIT_TIME << " seconds..." << endl;
_shutting_down = true;
map<int, p2p*>::iterator connection_it = _connections.begin();
while (connection_it != _connections.end()) {
connection_it->second->transmit(transmission().add(SERVER_SHUTDOWN).add(DELIM).add(itos(WAIT_TIME)));
connection_it++;
}
Sleep(WAIT_TIME*1000);
save(); // save all characters and dmatter to database
while (connection_it != _connections.end()) {
connection_it->second->set_disc_func(&do_nothing);
connection_it->second->disable_receive();
remove_connection(connection_it->first);
connection_it = _connections.begin();
}
_connections.clear();
// might want to comment this entire part out...
map<int, character*>::iterator toon_it = _characters.begin();
while (toon_it != _characters.end()) {
remove_character(toon_it->first); // redundently saves each character... whatever for now
toon_it = _characters.begin();
}
}
bool server::is_shutting_down() {return _shutting_down;}
int server::id() {
return _id;
}
void server::add_action(const string& name, void (*function)(int, int, string&)) {
_actions[name] = function;
}
void server::add_connection(p2p* connection) {
connection->transmit(transmission().add(DEFN_SERVER_CODE).add(DELIM).add(itos(_id)).add(DELIM).add(itos(connection->id())));
connection->transmit(transmission().add(DEFN_ID).add(DELIM).add(itos(connection->id())));
_connections[connection->id()] = connection;
_pings[connection->id()];
}
void server::remove_connection(int connection_id, bool close_connection) {
if (_connections.find(connection_id) != _connections.end()) {
if (close_connection) {
_connections[connection_id]->close();
delete _connections[connection_id];
}
_connections.erase(connection_id);
if (_pings.find(connection_id) != _pings.end()) {
_pings.erase(connection_id);
}
if (_battle_server) {
map<int, p2p*>::iterator it = _connections.begin();
while (it != _connections.end()) {
it->second->transmit(transmission().add(EXECUTE).add(DELIM).add(REMOVE_REMOTE_CHAR).add(DELIM).add(itos(connection_id)));
it++;
}
}
}
}
bool server::has_connection_id(int connection_id) {
return (_connections.find(connection_id) != _connections.end());
}
void server::recv(int connection_id, string& code, string& data) {
if (code == PONG) {
if (_connections.find(connection_id) != _connections.end()) {
_pings[connection_id].recv_t = time(NULL);
}
return;
}
if (_actions.find(code) == _actions.end()) {
cout << "Invalid action code: " << code << ". Connection ID: " << connection_id << endl;
return;
}
else (_actions[code])(_id, connection_id, data);
}
p2p* server::get_connection(int connection_id) const {
if (_connections.find(connection_id) == _connections.end()) return 0;
return _connections.find(connection_id)->second;
}
void server::add_character(int connection_id, character* toon) {
if (_characters.find(connection_id) != _characters.end()) delete _characters[connection_id];
toon->id(connection_id);
_characters[connection_id] = toon;
// add all of user's dark matter to memory:
_characters[connection_id]->load_dmatter();
}
character* server::get_character(int connection_id) const {
if (_characters.find(connection_id) == _characters.end()) return 0;
return _characters.find(connection_id)->second;
}
void server::remove_character(int connection_id, bool deallocate_mem) {
if (_characters.find(connection_id) != _characters.end()) {
save(connection_id);
if (deallocate_mem) {
_characters[connection_id]->clear_dmatter(); // deletes dmatter from memory
delete _characters[connection_id];
}
_characters.erase(connection_id);
}
}
map<int, character*> server::get_char_map() {
return _characters;
}
void server::change_client_id(int old_id, int new_id) {
if (_connections.find(old_id) == _connections.end()) return;
if (_connections.find(new_id) != _connections.end()) return;
_connections[old_id]->disable_receive();
_connections[old_id]->transmit(transmission().add(DEFN_SERVER_CODE).add(DELIM).add(itos(_id)).add(DELIM).add(itos(new_id)));
_connections[old_id]->transmit(transmission().add(DEFN_ID).add(DELIM).add(itos(new_id)));
_connections[new_id] = _connections[old_id];
_connections.erase(old_id);
_connections[new_id]->enable_receive();
if (_characters.find(old_id) != _characters.end()) {
_characters[new_id] = _characters[old_id];
_characters.erase(old_id);
}
if (_pings.find(old_id) != _pings.end()) {
_pings[new_id] = _pings[old_id];
_pings.erase(old_id);
}
}
void server::ping(int connection_id) {
_pings[connection_id].send_t = time(NULL);
_pings[connection_id].recv_t = 0;
if (_connections.find(connection_id) != _connections.end()) {
_connections[connection_id]->transmit(transmission().add(PING));
}
}
time_t server::pong(int connection_id) {
if (_connections.find(connection_id) != _connections.end()) {
return _pings[connection_id].recv_t;
}
else return 0;
}
void recv_branch(void* ptr) {
std::string transmission_stream = *(std::string*)ptr;
delete (std::string*)ptr;
int i = 0;
while (i<transmission_stream.length()) {
string single_transmission = transmission_stream.substr(i, TRANSMISSION_SIZE); // get the entire transmission
single_transmission = single_transmission.substr(0, single_transmission.find_first_of(0x04)); // truncate to the first EOT marker
i += TRANSMISSION_SIZE; // advance i used to find following transmissions
vector<std::string> temp = explode(single_transmission, DELIM, 3);
if (temp.size() < 4) temp.push_back(string());
int server_id = atoi(temp[0].c_str());
int connection_id = atoi(temp[1].c_str());
string code = temp[2];
string data = temp[3];
temp.clear();
if (all_servers.find(server_id) == all_servers.end()) {
std::cout << "WARNING: Invalid Server ID: " << server_id << endl;
return;
}
all_servers[server_id]->recv(connection_id, code, data);
}
}
void disc_branch(void* ptr) {
int connection_id = *(int*)ptr;
delete (int*)ptr;
cout << "Connection " << connection_id << " disconnected." << endl;
for (int i=0;i<hosts.size();i++) {
if (hosts[i]->has_connection_id(connection_id)) {
hosts[i]->remove_character(connection_id);
hosts[i]->remove_connection(connection_id);
break;
}
}
}
void time_loop(void*) {
int desired_wait = 1000; // 1 second
int wait_time = 1000;
bool wait = true;
int lag = 0;
int total_lag = 0;
clock_t last_t = 0;
while (!STOP_TIME_LOOP) {
if (last_t != 0) {
lag = (clock() - last_t) - desired_wait;
total_lag += lag;
wait_time -= (lag + total_lag*0.10f);
if (wait_time < 15) {
wait_time = 15;
wait = false;
}
else wait = true;
}
last_t = clock();
for (int host_id=0;host_id<hosts.size();host_id++) {
(*hosts[host_id])++;
}
if (wait) Sleep(wait_time);
else cout << "WARNING: Tick timer is lacking available resources! (Lagging: " << lag << ", Total: " << total_lag <<")" << endl;
//cout << "(Lagging: " << lag << ", Total: " << total_lag <<")" << endl;
}
}
void server::enable_battle(bool value) {
_battle_server = value;
}
bool server::is_battle_server() const {
return _battle_server;
}
void server::operator++(int) {
map<int, character*>::iterator char_it = _characters.begin();
if (_battle_server) {
while (char_it != _characters.end()) {
(*char_it->second)++;
char_it++;
}
}
else {
static int tick_count = 0;
if (tick_count == 0) {
cout << "Adding darkmatter (Host " << _id << ")" << endl;
srand(time(NULL));
vector<row> results = dmatter_class_table->select(query().where(predicate().And(equalto(dmclass_level, "1"))));
if (results.size() != 0) {
row dmatter_row = results[rand()%results.size()];
darkmatter* temp_dmatter = new darkmatter;
temp_dmatter->define(dmatter_row);
available_dmatter.insert(pair<int, darkmatter*>(temp_dmatter->id(), temp_dmatter));
}
else {
cout << "WARNING: Server++ found zero darkmatter objects." << endl;
}
}
while (char_it != _characters.end()) {
char_it->second->full_heal();
char_it++;
}
tick_count = (++tick_count)%60;
}
}
void server::save(int toon_id) const {
// if toon_id is negative, save all toons in the server
if (toon_id < 0) {
map<int, character*>::const_iterator toon_it = _characters.begin();
while (toon_it != _characters.end()) {
if (toon_it->first >= 0) // just for security
save(toon_it->first);
toon_it++;
}
return;
}
if (_characters.find(toon_id) == _characters.end()) { cout << "WARNING: Error saving character. ID not found: " << toon_id << endl; return; }
const character* toon = get_character(toon_id);
// update character's db entry:
row char_data = toon->to_row();
char_data.remove(char_id);
if (char_table->edit_row(char_table->select(query().where(predicate().And(equalto(char_id, itos(toon_id))))), char_data) == 0) {
char_table->delete_row(char_table->select(query().where(predicate().And(equalto(char_name, toon->name())))));
char_data.add(char_id, itos(toon_id));
char_table->add_row(char_data);
}
// update character's darkmatter db entries:
map<int, const darkmatter&> toon_dmatter = toon->get_dmatter();
map<int, const darkmatter&>::iterator dmatter_it = toon_dmatter.begin();
while (dmatter_it != toon_dmatter.end()) {
row dmatter_data = dmatter_it->second.to_row();
dmatter_data.remove(dmatter_id); // to avoid changing the unique ID...
dmatter_data[dmatter_owner_id] = toon_id;
if (dmatter_table->edit_row(dmatter_table->select(query().where(predicate().And(equalto(dmatter_id, itos(dmatter_it->second.id()))))), dmatter_data) == 0) {
dmatter_table->add_row(dmatter_data);
}
dmatter_it++;
}
}
| [
"[email protected]"
]
| [
[
[
1,
358
]
]
]
|
93719d90466809f6989ecdac6bdc6e0411f6c6cf | bdb1e38df8bf74ac0df4209a77ddea841045349e | /CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-14-1/CapuleDemo/CapuleDemoDlg.cpp | 99d1c162eb70938115b0a332b880c82421011164 | []
| no_license | Strongc/my001project | e0754f23c7818df964289dc07890e29144393432 | 07d6e31b9d4708d2ef691d9bedccbb818ea6b121 | refs/heads/master | 2021-01-19T07:02:29.673281 | 2010-12-17T03:10:52 | 2010-12-17T03:10:52 | 49,062,858 | 0 | 1 | null | 2016-01-05T11:53:07 | 2016-01-05T11:53:07 | null | GB18030 | C++ | false | false | 16,950 | cpp | // CapuleDemoDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "CapuleDemo.h"
#include "CapuleDemoDlg.h"
#include "TImgProcess.h"
#include "TBmpInfo.h "
#include "TBmpBoard.h "
#include "iCVFoundation.h"
#pragma comment(lib, "cvfoundation.lib")
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CCapuleDemoDlg 对话框
CCapuleDemoDlg::CCapuleDemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCapuleDemoDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CCapuleDemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CVDISPLAYCTRL1, m_display);
DDX_Control(pDX, IDC_CVIMAGECTRL1, m_imageControl);
}
BEGIN_MESSAGE_MAP(CCapuleDemoDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON1, &CCapuleDemoDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &CCapuleDemoDlg::OnBnClickedButton2)
ON_BN_CLICKED(IDC_BUTTON3, &CCapuleDemoDlg::OnBnClickedButton3)
ON_BN_CLICKED(IDC_BUTTON4, &CCapuleDemoDlg::OnBnClickedButton4)
ON_BN_CLICKED(IDC_BUTTON5, &CCapuleDemoDlg::OnBnClickedButton5)
ON_BN_CLICKED(IDC_BUTTON6, &CCapuleDemoDlg::OnBnClickedButton6)
ON_BN_CLICKED(IDC_BUTTON7, &CCapuleDemoDlg::OnBnClickedButton7)
ON_BN_CLICKED(IDC_BUTTON8, &CCapuleDemoDlg::OnBnClickedButton8)
END_MESSAGE_MAP()
// CCapuleDemoDlg 消息处理程序
BOOL CCapuleDemoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
m_display.SetLeftButtonMode(2);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CCapuleDemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CCapuleDemoDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标显示。
//
HCURSOR CCapuleDemoDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CCapuleDemoDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CFileDialog dlg( TRUE, //file open
_T("mfd"), //file ext
_T("*.mfd"), //file name
OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, // flags
_T("Multi Frame file (*.mfd)|*.mfd|")); // filter
dlg.m_ofn.lpstrInitialDir = GetExeFileDir().c_str();
if(IDOK == dlg.DoModal())
{
CString fileName = dlg.GetPathName();
TMfdArchive mfdFile;
/* for(int i = 0; i < THREADCOUNT; i++)
{
//m_firstThread[i].SetThreadFunc ( CapsuleSorterDlg::FirstCamFunc, this);
m_firstThread[i].Start(TThread::HIGHEST);
//m_secondThread[i].SetThreadFunc( CapsuleSorterDlg::SecondCamFunc, this);
m_secondThread[i].Start(TThread::HIGHEST);
}
*/
if(mfdFile.Load(LPCTSTR(fileName)))
{
m_buff = mfdFile.GetImgBuffer();
}
}
//m_buff.GoNextFrame();
IMG dispImg = GetIMGFromBuffer(m_buff);
m_display.SetImage((long)dispImg);
/* TImgDim dim = m_simCam.ImageDimension();
m_firstProcess.ReInit(dim);
dim = m_secondSimCam.ImageDimension();
m_secondProcess.ReInit(dim);
*/
}
std::string& CCapuleDemoDlg::GetExeFileDir ()
{
static std::string exeFileDir;
if (!exeFileDir.size())
{
char filePath[MAX_PATH];
GetModuleFileName(NULL, filePath, MAX_PATH);
exeFileDir = filePath;
size_t pathDot = exeFileDir.rfind("\\") + 1;
exeFileDir = exeFileDir.substr(0, pathDot);
}
return exeFileDir;
}
IMG CCapuleDemoDlg::GetIMGFromBuffer(TImgBuffer & buffer)
{
TImgDim dim = buffer.Dimension();
IMG imgOut;
CreateImageFromPointer(buffer.FrameData(), dim.bytesPerRow * dim.height, dim.width, dim.height,
dim.bytesPerPixel, 8,1, dim.bytesPerRow, dim.bytesPerPixel, 0, 0, 0, imgOut);
return imgOut;
}
IMG CCapuleDemoDlg::GetIMGFromImage(TImage<PelGray8> & image)
{
TImgDim dim = image.Dimension();
IMG imgOut;
CreateImageFromPointer(image.Base(), dim.bytesPerRow * dim.height, dim.width, dim.height,
dim.bytesPerPixel, 8,1, dim.bytesPerRow, dim.bytesPerPixel, 0, 0, 0, imgOut);
return imgOut;
}
void CCapuleDemoDlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
TImgDim dim = m_buff.Dimension();
TRect2D<int> rt(0, 0, dim.width- 1, dim.height -1);
TImage<PelGray8> sourceImage(rt);
//TImage<PelGray8> enhanceImage;
m_enhanceImage.ReInit(rt);
sourceImage.SetImage(m_buff.FrameData(), m_buff.Dimension());
// m_enhanceImage.SetImage(m_buff.FrameData(), m_buff.Dimension());
TImgProcess::SobelFilter(sourceImage, m_enhanceImage);
IMG dispImg = GetIMGFromImage(m_enhanceImage);
m_display.SetImage((long)dispImg);
}
void CCapuleDemoDlg::OnBnClickedButton3()
{
TImgDim dim = m_buff.Dimension();
TRect2D<int> rt(0, 0, dim.width- 1, dim.height -1);
TImage<PelGray8> sourceImage(rt);
m_binaryImage.ReInit(rt);
sourceImage.SetImage(m_buff.FrameData(), m_buff.Dimension());
TImgProcess::BinaryGray(sourceImage, m_binaryImage, 10, 255 );
IMG dispImg = GetIMGFromImage(m_binaryImage);
m_display.SetImage((long)dispImg);
}
void CCapuleDemoDlg::OnBnClickedButton4()
{
// TODO: 在此添加控件通知处理程序代码
m_display.RemoveAllLabels();
double x0, y0,x1,y1,x2,y2;
m_display.GetSelectedArea(&x0, &y0, &x1, &y1, &x2, &y2);
IMG sourceIMG = GetIMGFromImage(m_sourceImage);
IMG subImage = NULL;
const int subWidth = ((int)(x2 -x0))/16 *16;
x0 = (double)((int)(x0/16) * 16);
y0 = (double)((int)(y0/16) * 16);
const int subHeight = ((int)(y1 -y0))/16 *16;
TArea area;
area.X0 = x0;
area.Y0 = y0;
area.X1 = x0;
area.Y1 = y0 + subHeight -1;
area.X2 = x0 + subWidth-1;
area.Y2 = y0;
TCoordinateMap cm;
InitCoordinateMap(cm);
SetImageCoordinates (sourceIMG, cm);
CreateSubImage(sourceIMG, area, subImage);
InitCoordinateMap(cm);
SetImageCoordinates (sourceIMG, cm);
m_dstImage= GetTImageFromIMG(subImage);
TBmpInfo info;
info.Width (ImageWidth(subImage));
info.Height (ImageHeight(subImage));
info.AccordMem();
TBmpBoard bmpBoard;
bmpBoard.SetBmpInfo(info);
PixelMem *pPixel = bmpBoard.GetPixelBase();
memcpy(pPixel, m_dstImage.Base(), m_dstImage.Width() * m_dstImage.Height());
HDC memHDC = bmpBoard.GetMemDC();
ArcTemple uptemp = ArcCreator::CreateArc(69, ArcTemple::eUpArc);
ArcTemple downTemp = ArcCreator::CreateArc(70, ArcTemple::eDownArc);
TPoint2D<int> upCentre;
TPoint2D<int> downCentre;
const int imgWidth = ImageWidth(subImage);
const int imgHeight = ImageHeight(subImage);
TRect2D<int> subArea(0, 0, imgWidth-1, imgHeight-1);
GetTopPos(m_dstImage, subArea, downCentre, m_tempSet);
GetTopPos(m_dstImage, subArea, upCentre, m_capSet);
GetTopPoint();
//ResortDown(downCentre.x(), downCentre.y());
//ResortUp(upCentre.x(),upCentre.y());
m_capLeft.x += upCentre.x();
m_capLeft.y += upCentre.y();
m_capRight.x += upCentre.x();
m_capRight.y += upCentre.y();
m_downLeft.x += downCentre.x();
m_downLeft.y += downCentre.y();
m_downRight.x += downCentre.x();
m_downRight.y += downCentre.y();
m_display.AddLabel("", FALSE, 255, 0, m_capLeft.x, m_capLeft.y);
m_display.AddLabel("", FALSE, 255, 0, m_capRight.x, m_capRight.y);
m_display.AddLabel("", FALSE, 255, 0, m_downLeft.x, m_downLeft.y);
m_display.AddLabel("", FALSE, 255, 0, m_downRight.x, m_downRight.y);
FillDest(m_dstImage, m_capLeft, m_capRight,m_downLeft, m_downRight, memHDC, 0);
memcpy(m_dstImage.Base(), bmpBoard.GetPixelBase(), imgWidth * imgHeight);
IMG disp = GetIMGFromImage(m_dstImage);
m_display.SetImage((long)disp);
}
void CCapuleDemoDlg::GetTopPos( TImage<unsigned char> &image,
TRect2D<int> &rect,
TPoint2D<int> ¢re,
ArcTemple &temp)
{
ArcMatchor matchor;
matchor.SetImage(image);
matchor.GetMaxMatchPos(temp, rect, centre);
}
TImage<PelGray8> CCapuleDemoDlg::GetTImageFromIMG(IMG img)
{
const int imgWidth = ImageWidth(img);
const int imgHeight = ImageHeight(img);
TRect2D<int> rt(0, 0, imgWidth-1, imgHeight -1);
TImage<PelGray8> subImage(rt);
PVPAT vpa = NULL;
unsigned char *pImage = NULL;
GetImageVPA(img, 0, (void**)&pImage, &vpa);
for (int i = 0; i < imgHeight; i++)
{
for (int j = 0; j < imgWidth; j++)
{
subImage.SetPixel(j, i, *(vpa[j].XEntry + pImage + vpa[i].YEntry));
}
}
//memcpy(subImage.Base(), pImage,imgWidth * imgHeight);
return subImage;
}
void CCapuleDemoDlg::OnBnClickedButton5()
{
TImgDim dim = m_buff.Dimension();
TRect2D<int> rt(0, 0, dim.width- 1, dim.height -1);
m_sourceImage.ReInit(rt);
IMG sourceIMG = GetIMGFromImage(m_binaryImage);
IMG minBoxFilter = NULL;
const int boxWidth = 20;
ErodeImage(sourceIMG, MM_Cross, boxWidth,boxWidth, boxWidth/2 -5, boxWidth/2-5, NULL, minBoxFilter);
//FilterBoxMin(sourceIMG, 7,7, 3, 3, minBoxFilter);
m_binaryImage= GetTImageFromIMG(minBoxFilter);
TImgProcess::AndGrayImg(m_enhanceImage, m_binaryImage, m_sourceImage);
IMG dispImg = GetIMGFromImage(m_sourceImage);
m_display.SetImage((long)dispImg);
}
void CCapuleDemoDlg::OnBnClickedButton6()
{
// TODO: 在此添加控件通知处理程序代码
if (!m_imageControl.LoadImageByDialog())
{
return;
}
m_display.SetImage(m_imageControl.GetImage());
const int imgWidth = ImageWidth((IMG)(m_imageControl.GetImage()));
const int imgHeight = ImageHeight((IMG)(m_imageControl.GetImage()));
TRect2D<int> rt(0, 0, imgWidth - 1, imgHeight -1);
TImage<PelGray8> subImage(rt);
PVPAT vpa = NULL;
unsigned char *pImage = NULL;
GetImageVPA((IMG)m_imageControl.GetImage(), 0, (void**)&pImage, &vpa);
memcpy(subImage.Base(), pImage,imgWidth * imgHeight);
m_tempSet.clear();
for (int i = 0; i < imgHeight; i++)
{
unsigned char *pLine = subImage.Base() + i * imgWidth;
for (int j = 0; j < imgWidth; j++)
{
if (*(pLine + j) == 0)
{
POINT pt;
pt.x = j;
pt.y = i;
m_tempSet.push_back(pt);
}
}
}
}
void CCapuleDemoDlg::GetTopPos( TImage<unsigned char> &image,
TRect2D<int> &rect,
TPoint2D<int> ¢re,
vector<POINT> &temp)
{
ArcMatchor matchor;
matchor.SetImage(image);
matchor.GetMaxMatchPos(temp, rect, centre);
}
void CCapuleDemoDlg::OnBnClickedButton7()
{
// TODO: 在此添加控件通知处理程序代码
if (!m_imageControl.LoadImageByDialog())
{
return;
}
m_display.SetImage(m_imageControl.GetImage());
const int imgWidth = ImageWidth((IMG)(m_imageControl.GetImage()));
const int imgHeight = ImageHeight((IMG)(m_imageControl.GetImage()));
TRect2D<int> rt(0, 0, imgWidth - 1, imgHeight -1);
TImage<PelGray8> subImage(rt);
PVPAT vpa = NULL;
unsigned char *pImage = NULL;
GetImageVPA((IMG)m_imageControl.GetImage(), 0, (void**)&pImage, &vpa);
memcpy(subImage.Base(), pImage,imgWidth * imgHeight);
m_capSet.clear();
for (int i = 0; i < imgHeight; i++)
{
unsigned char *pLine = subImage.Base() + i * imgWidth;
for (int j = 0; j < imgWidth; j++)
{
if (*(pLine + j) == 0)
{
POINT pt;
pt.x = j;
pt.y = i;
m_capSet.push_back(pt);
}
}
}
}
void CCapuleDemoDlg::GetTopPoint()
{
if (!m_capSet.empty())
{
int count = m_capSet.size();
int nMix = 0;
int nMax = 0;
for (int nIndex = 0; nIndex < count; nIndex++)
{
POINT pt = (POINT)m_capSet.at(nIndex);
if (nIndex == 0)
{
nMix = pt.x;
nMax = pt.x;
m_capRight = pt;
m_capLeft = pt;
} else {
if (pt.x > nMax)
{
nMax = pt.x;
m_capRight = pt;
}
if (pt.x < nMix)
{
nMix = pt.x;
m_capLeft = pt;
}
}
}
count = m_tempSet.size();
nMix = 0;
nMax = 0;
for (int nIndex = 0; nIndex < count; nIndex++)
{
POINT pt = (POINT)m_tempSet.at(nIndex);
if (nIndex == 0)
{
nMix = pt.x;
nMax = pt.x;
m_downRight = pt;
m_downLeft = pt;
} else {
if (pt.x > nMax)
{
nMax = pt.x;
m_downRight = pt;
}
if (pt.x < nMix)
{
nMix = pt.x;
m_downLeft = pt;
}
}
}
}
}
void CCapuleDemoDlg::OnBnClickedButton8()
{
// TODO: 在此添加控件通知处理程序代码
// ResortUp();
}
void CCapuleDemoDlg::FillDest( TImage<unsigned char> &image,
POINT upLeft,
POINT upRight,
POINT downLeft,
POINT downRight,
HDC &memHDC,
const size_t radius)
{
CBrush bush;
//bush.CreateHatchBrush(HS_CROSS, RGB(255,255,255));
bush.CreateSolidBrush(RGB(255,255,255));
/*const int nCount = m_capSet.size();
POINT *upRect = new POINT [nCount];
for (int i = 0; i < nCount; i++)
{
upRect[i] = m_capSet[i];
}
CRgn upRgn;
upRgn.CreatePolygonRgn(upRect, m_capSet.size(), ALTERNATE);
FillRgn(memHDC , upRgn, bush);*/
CRgn midRgn;
POINT midRect[4];
midRect[0] = upLeft;
//midRect[0] = upRight;
midRect[1] = downLeft;
//midRect[1].y = downCentre.y();
midRect[2] = downRight;
//midRect[2].y = downCentre.y();
midRect[3] = upRight;
//midRect[3].y = upCentre.y();
midRgn.CreatePolygonRgn(midRect, 4, ALTERNATE);
BOOL err = FillRgn(memHDC, midRgn, bush);
}
void CCapuleDemoDlg::ResortUp(int nx, int ny)
{
vector<POINT> tempSet = m_capSet;
if (!tempSet.empty())
{
m_capSet.clear();
while (!tempSet.empty())
{
int nCount = tempSet.size();
int nMin = 0;
int nIndex = 0;
int nCurrent = 0;
POINT outpt;
outpt.x = 0;
outpt.y = 0;
for (nIndex = 0; nIndex < nCount; nIndex++)
{
POINT pt = (POINT)tempSet.at(nIndex);
if (nIndex == 0)
{
nMin = pt.x;
outpt.x = pt.x + nx;
outpt.y = pt.y + ny;
} else {
if (pt.x < nMin)
{
nMin = pt.x;
nCurrent = nIndex;
outpt.x = pt.x + nx;
outpt.y = pt.y + ny;
}
}
}
tempSet.erase(tempSet.begin() + nCurrent);
m_capSet.push_back(outpt);
}
}
}
void CCapuleDemoDlg::ResortDown(int nx, int ny)
{
vector<POINT> tempSet = m_tempSet;
if (!tempSet.empty())
{
m_tempSet.clear();
while (!tempSet.empty())
{
int nCount = tempSet.size();
int nMin = 0;
int nIndex = 0;
int nCurrent = 0;
POINT outpt;
outpt.x = 0;
outpt.y = 0;
for (nIndex = 0; nIndex < nCount; nIndex++)
{
POINT pt = (POINT)tempSet.at(nIndex);
if (nIndex == 0)
{
nMin = pt.x;
outpt.x = pt.x + nx;
outpt.y = pt.y + ny;
} else {
if (pt.x < nMin)
{
nMin = pt.x;
nCurrent = nIndex;
outpt.x = pt.x + nx;
outpt.y = pt.y + ny;
}
}
}
tempSet.erase(tempSet.begin() + nCurrent);
m_tempSet.push_back(outpt);
}
}
} | [
"vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e"
]
| [
[
[
1,
678
]
]
]
|
cefcb9966af05a95db279f9dd74df40590f549e7 | 38fa90e0adaf61d02802e77962075f6913a3cdfa | /src/aotk_unix.cpp | 1a1c039aa6f747f61b0501c02bdd9e9a7cfd294f | []
| no_license | r-englund/AoTK | 49097b39906c5f9cad1c79f3e22f867cbfe806e3 | 7a52b0788c25710b00fa5e582ef2fcbc4c839a8f | refs/heads/master | 2021-01-17T11:54:34.889565 | 2011-09-01T20:19:38 | 2011-09-01T20:19:38 | 1,339,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,077 | cpp | #include <AoTK/aotk.h>
#ifdef AoTK_UNIX
namespace AoTK{
Display *disp;
int scr;
AoTK::Math::Vector4<int> *devices;
int number_of_devices;
bool ___isInit = false;
void init(){
if(___isInit)
return;//throw "AoTK::init called two times, can only be called once";
___isInit = true;
disp = XOpenDisplay(0);
if(disp == NULL){
std::cerr << "Could not open a display" << std::endl;
exit(1);
return;
}
scr = DefaultScreen(disp);
}
AoTK::Math::Vector4<int> *getDevices(){return devices;}
unsigned int getNumberOfDevices(){return number_of_devices;}
KEY translateKEY(KeySym w){
switch(w){
case XK_F1 : return F1;
case XK_F2 : return F2;
case XK_F3 : return F3;
case XK_F4 : return F4;
case XK_F5 : return F5;
case XK_F6 : return F6;
case XK_F7 : return F7;
case XK_F8 : return F8;
case XK_F9 : return F9;
case XK_F10 : return F10;
case XK_F11 : return F11;
case XK_F12 : return F12;
case XK_F13 : return F13;
case XK_F14 : return F14;
case XK_F15 : return F15;
case XK_F16 : return F16;
case XK_F17 : return F17;
case XK_F18 : return F18;
case XK_F19 : return F19;
case XK_F20 : return F20;
case XK_F21 : return F21;
case XK_F22 : return F22;
case XK_F23 : return F23;
case XK_F24 : return F24;
case XK_Shift_L: return SHIFT;
case XK_Shift_R: return SHIFT;
case XK_Control_L : return CTRL;
case XK_Control_R : return CTRL;
case XK_Caps_Lock : return CAPSLOCK;
case XK_Num_Lock : return NUMLOCK;
case XK_Scroll_Lock : return SCROLLLOCK;
case XK_Alt_L : return ALT;
case XK_Alt_R : return ALT;
case XK_Super_L : return SUPER;
case XK_Super_R : return SUPER;
case XK_Return : return ENTER;
case XK_Tab : return TAB;
case XK_BackSpace : return BACKSPACE;
case XK_Escape : return ESC;
case XK_Delete : return DEL;
case XK_q : return Q;
case XK_w : return W;
case XK_e : return E;
case XK_r : return R;
case XK_t : return T;
case XK_y : return Y;
case XK_u : return U;
case XK_i : return I;
case XK_o : return O;
case XK_p : return P;
case XK_a : return A;
case XK_s : return S;
case XK_d : return D;
case XK_f : return F;
case XK_g : return G;
case XK_h : return H;
case XK_j : return J;
case XK_k : return K;
case XK_l : return L;
case XK_z : return Z;
case XK_x : return X;
case XK_c : return C;
case XK_v : return V;
case XK_b : return B;
case XK_n : return N;
case XK_m : return M;
case XK_0 : return KEY0;
case XK_1 : return KEY1;
case XK_2 : return KEY2;
case XK_3 : return KEY3;
case XK_4 : return KEY4;
case XK_5 : return KEY5;
case XK_6 : return KEY6;
case XK_7 : return KEY7;
case XK_8 : return KEY8;
case XK_9 : return KEY9;
// case 0xFE03 : return ALTGR;
case XK_space : return SPACE; // OR XP_KP_ 20
case XK_Home : return HOME;
case XK_End : return END;
case XK_Insert : return INS;
case XK_Page_Up : return PGUP;
case XK_Page_Down : return PGDOWN;
case XK_Left: return ARROW_LEFT;
case XK_Right: return ARROW_RIGHT;
case XK_Up: return ARROW_UP;
case XK_Down: return ARROW_DOWN;
// case 0x : return PRINT;
// case 0x : return PRINTSCREEN;
// case 0x : return MULTI;
case XK_plus : return ADD;
case XK_minus : return SUB;
case XK_comma : return DECIMAL;
// case 0x : return DIVIDE;
case XK_Pause : return PAUSE;
default:
char str[30];
sprintf(str,"%X", w);
std::cout << "WARNING: unhandled key pressed: " << str << std::endl;
return UNASIGNED_KEY;
}
}
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
143
]
]
]
|
696735249e1db6693282fd611b3cbd7f071901e0 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/CryEngine/CryCommon/IFacialAnimation.h | a39de70a9dd8528e8130cf0be0f9b84b66e45a11 | []
| no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,361 | h | ////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001-2005.
// -------------------------------------------------------------------------
// File name: IFacialAnimation.h
// Version: v1.00
// Created: 7/10/2005 by Timur.
// Compilers: Visual Studio.NET 2003
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include DEVIRTUALIZE_HEADER_FIX(IFacialAnimation.h)
#ifndef __IFacialAnimation_h__
#define __IFacialAnimation_h__
#pragma once
#include "ISplines.h"
#include "Range.h"
#include "functor.h"
struct IFacialEffCtrl;
struct IFacialAnimSequence;
class IJoystickSet;
#if !(defined(XENON) || defined(PS3))
#define FACE_STORE_ASSET_VALUES (1)
#endif
// This class is used all over the place in the Face Animation System
// to replace Strings by CRC32s on consoles. Internally,
// CFaceIdentifierStorage is used to store the string value on PC for the Editor.
// Note that an (nonempty) handle can not explicitly be created, it has to be created
// by the CFacialAnimation class (CreateIdentifier) or from a CFaceIdentifierStorage Object.
class CFaceIdentifierHandle
{
friend class CFaceIdentifierStorage;
friend class CFacialAnimation;
public:
const char* GetString() const
{
#ifdef FACE_STORE_ASSET_VALUES
return m_str;
#endif
return NULL;
}
uint32 GetCRC32() const
{
return m_crc32;
}
void GetMemoryUsage( ICrySizer* pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
}
// Allow for empty handles
CFaceIdentifierHandle()
{
#ifdef FACE_STORE_ASSET_VALUES
m_str = NULL;
#endif
m_crc32 = 0;
}
protected:
#ifdef FACE_STORE_ASSET_VALUES
const char* m_str;
#endif
uint32 m_crc32;
CFaceIdentifierHandle(const char* str, uint32 crc32)
{
#ifdef FACE_STORE_ASSET_VALUES
m_str = str;
#endif
m_crc32 = crc32;
}
};
//--------------------------------------------------------------------------------
enum EFacialSequenceLayer
{
eFacialSequenceLayer_Preview, // Used in facial editor.
eFacialSequenceLayer_Dialogue, // One shot with sound, requested together with wave file.
eFacialSequenceLayer_Trackview, // Triggered via trackview sequence
eFacialSequenceLayer_AGStateAndAIAlertness, // Per animation-state and per ai-alertness (looping, requested/cleared by AG state node enter/leave).
eFacialSequenceLayer_AIExpression, // Looping, requested/cleared by goalpipe/goalop.
eFacialSequenceLayer_FlowGraph, // Just in case we will need it later =).
eFacialSequenceLayer_COUNT,
};
//--------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////
// Types of face Effectors.
enum EFacialEffectorType
{
EFE_TYPE_GROUP = 0x00, // This effector is a group of sub effectors.
EFE_TYPE_EXPRESSION = 0x01, // This effector contain specific state of effectors.
EFE_TYPE_MORPH_TARGET = 0x02, // This Effector is a single morph target.
EFE_TYPE_BONE = 0x03, // This Effector controls a bone.
EFE_TYPE_MATERIAL = 0x04, // This Effector is a material parameter.
EFE_TYPE_ATTACHMENT = 0x05 // This Effector controls attachment.
};
enum EFacialEffectorFlags
{
EFE_FLAG_ROOT = 0x00001, // This is a root effector in the library.
EFE_FLAG_UI_EXTENDED = 0x01000, // When this flag is set this effector must be extended in ui.
EFE_FLAG_UI_MODIFIED = 0x02000, // When this flag is set this effector was modified.
EFE_FLAG_UI_PREVIEW = 0x04000, // This flag indicate preview only effector, it is not saved in library.
};
enum EFacialEffectorParam
{
EFE_PARAM_BONE_NAME, // String representing the name of the bone/attachment object in character, only for Bone/Attachment Effectors.
EFE_PARAM_BONE_ROT_AXIS, // Vec3 representing the angles in radians as multipliers of effector weight,for Bone/Attachment Effector rotation.
EFE_PARAM_BONE_POS_AXIS, // Vec3 representing the offset multiplied with effector weight,for Bone/Attachment Effector offset.
};
enum MergeCollisionAction
{
MergeCollisionActionNoOverwrite,
MergeCollisionActionOverwrite
};
class CFacialAnimForcedRotationEntry
{
public:
int jointId;
Quat rotation;
};
//////////////////////////////////////////////////////////////////////////
// General Effector that can be a muscle bone or some effect.
//////////////////////////////////////////////////////////////////////////
struct IFacialEffector
{
virtual void SetIdentifier( CFaceIdentifierHandle ident ) = 0;
virtual CFaceIdentifierHandle GetIdentifier() = 0;
#ifdef FACE_STORE_ASSET_VALUES
// functions should only be used in the editor.
virtual void SetName( const char* sNewName ) = 0;
virtual const char* GetName() const = 0;
#endif
virtual EFacialEffectorType GetType() = 0;
// @see EFacialEffectorFlags
virtual void SetFlags( uint32 nFlags ) = 0;
virtual uint32 GetFlags() = 0;
// Get index of the effector in Facial State array, only valid for end effectors.
virtual int GetIndexInState() = 0;
// Set/Get facial effector parameters, mostly used for editing.
virtual void SetParamString( EFacialEffectorParam param,const char *str ) = 0;
virtual const char* GetParamString( EFacialEffectorParam param ) = 0;
virtual void SetParamVec3( EFacialEffectorParam param,Vec3 vValue ) = 0;
virtual Vec3 GetParamVec3( EFacialEffectorParam param ) = 0;
virtual void SetParamInt( EFacialEffectorParam param,int nValue ) = 0;
virtual int GetParamInt( EFacialEffectorParam param ) = 0;
//////////////////////////////////////////////////////////////////////////
// Sub Effectors.
//////////////////////////////////////////////////////////////////////////
virtual int GetSubEffectorCount() = 0;
virtual IFacialEffector* GetSubEffector( int nIndex ) = 0;
virtual IFacialEffCtrl* GetSubEffCtrl( int nIndex ) = 0;
virtual IFacialEffCtrl* AddSubEffector( IFacialEffector *pEffector ) = 0;
virtual void RemoveSubEffector( IFacialEffector *pEffector ) = 0;
virtual void RemoveAllSubEffectors() = 0;
virtual ~IFacialEffector(){}
};
//////////////////////////////////////////////////////////////////////////
// Sub Effector controller.
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialEffCtrl
{
virtual ~IFacialEffCtrl(){}
enum ControlType
{
CTRL_LINEAR,
CTRL_SPLINE
};
enum ControlFlags
{
CTRL_FLAG_OFF = 0x0001, // Controller is off.
CTRL_FLAG_UI_EXPENDED = 0x01000, // Controller is expanded.
};
virtual IFacialEffCtrl::ControlType GetType() = 0;
virtual void SetType( ControlType t ) = 0;
virtual IFacialEffector* GetEffector() = 0;
virtual float GetConstantWeight() = 0;
virtual void SetConstantWeight( float fWeight ) = 0;
virtual float GetConstantBalance() = 0;
virtual void SetConstantBalance( float fBalance ) = 0;
// Get access to control spline.
virtual ISplineInterpolator* GetSpline() = 0;
virtual float Evaluate(float fInput) = 0;
// @see ControlFlags
virtual int GetFlags() = 0;
// @see ControlFlags
virtual void SetFlags( int nFlags ) = 0;
};
//////////////////////////////////////////////////////////////////////////
// Contains face Effectors.
//////////////////////////////////////////////////////////////////////////
struct IFacialEffectorsLibraryEffectorVisitor
{
virtual ~IFacialEffectorsLibraryEffectorVisitor(){}
virtual void VisitEffector(IFacialEffector* pEffector) = 0;
};
UNIQUE_IFACE struct IFacialEffectorsLibrary
{
virtual ~IFacialEffectorsLibrary(){}
virtual void AddRef() = 0;
virtual void Release() = 0;
// Assign filename of the effectors library.
virtual void SetName( const char *name ) = 0;
// Retrieve filename of the effectors library.
virtual const char* GetName() = 0;
// Find Effector by Identifier.
// Every Effector must have unique name.
virtual IFacialEffector* Find( CFaceIdentifierHandle ident ) = 0;
// find Effector by Name.
// DO NOT USE AT RUNTIME (Only in the editor)
virtual IFacialEffector* Find( const char* identStr ) = 0;
// Retrieve the root effector, all effectors contained in the library are direct or inderect siblings of this root.
virtual IFacialEffector* GetRoot() = 0;
// Direct access to effectors.
virtual void VisitEffectors(IFacialEffectorsLibraryEffectorVisitor* pVisitor) = 0;
// Creates a custom effector in the library.
virtual IFacialEffector* CreateEffector( EFacialEffectorType nType, CFaceIdentifierHandle ident ) = 0;
// Create a custom effector by supplying the name directly - ONLY USE IN EDITOR
virtual IFacialEffector* CreateEffector( EFacialEffectorType nType, const char* identStr ) = 0;
virtual void RemoveEffector(IFacialEffector* pEffector) = 0;
// Merges in effectors from another library - callback specifies what to do in case of name collision.
virtual void MergeLibrary(IFacialEffectorsLibrary* pMergeLibrary, const Functor1wRet<const char*, MergeCollisionAction>& collisionStrategy) = 0;
// Serialized library.
virtual void Serialize( XmlNodeRef &node,bool bLoading ) = 0;
};
//////////////////////////////////////////////////////////////////////////
// IFacialModel interface.
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialModel
{
virtual ~IFacialModel(){}
virtual int GetEffectorCount() const = 0;
virtual IFacialEffector* GetEffector( int nIndex ) const = 0;
// Assign facial effectors library to this model.
virtual void AssignLibrary( IFacialEffectorsLibrary *pLibrary ) = 0;
virtual IFacialEffectorsLibrary* GetLibrary() = 0;
virtual int GetMorphTargetCount() const = 0;
virtual const char* GetMorphTargetName(int morphTargetIndex) const = 0;
};
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFaceState
{
virtual ~IFaceState(){}
virtual float GetEffectorWeight( int nIndex ) = 0;
virtual void SetEffectorWeight( int nIndex,float fWeight ) = 0;
};
//////////////////////////////////////////////////////////////////////////
// IFacialInstance interface
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialInstance
{
virtual ~IFacialInstance(){}
virtual IFacialModel* GetFacialModel() = 0;
virtual IFaceState* GetFaceState() = 0;
virtual uint32 StartEffectorChannel(IFacialEffector* pEffector,float fWeight,float fFadeTime,float fLifeTime=0,int nRepeatCount=0) = 0;
virtual void StopEffectorChannel(uint32 nChannelID, float fFadeOutTime) = 0;
virtual void PreviewEffector( IFacialEffector *pEffector,float fWeight,float fBalance=0.0f ) = 0;
virtual void PreviewEffectors( IFacialEffector **pEffectors,float *fWeights,float *fBalances,int nEffectorsCount ) = 0;
virtual IFacialAnimSequence *LoadSequence( const char *sSequenceName, bool addToCache=true ) = 0;
virtual void PrecacheFacialExpression(const char *sSequenceName) = 0;
virtual void PlaySequence( IFacialAnimSequence *pSequence,EFacialSequenceLayer layer, bool bExclusive=false,bool bLooping=false ) = 0;
virtual void StopSequence( EFacialSequenceLayer layer ) = 0;
virtual bool IsPlaySequence( IFacialAnimSequence *pSequence, EFacialSequenceLayer layer ) = 0;
virtual void PauseSequence( EFacialSequenceLayer layer, bool bPaused ) = 0;
// Seek sequence current time to the specified time offset from the begining of sequence playback time.
virtual void SeekSequence( EFacialSequenceLayer layer,float fTime ) = 0;
// Start/Stop Lip syncing with the sound.
virtual void LipSyncWithSound( uint32 nSoundId, bool bStop=false ) = 0;
virtual void OnExpressionLibraryLoad() = 0;
virtual void EnableProceduralFacialAnimation( bool bEnable ) = 0;
virtual void SetForcedRotations(int numForcedRotations, CFacialAnimForcedRotationEntry* forcedRotations) = 0;
virtual void SetMasterCharacter(ICharacterInstance* pMasterInstance) = 0;
virtual void TemporarilyEnableBoneRotationSmoothing() = 0;
};
//////////////////////////////////////////////////////////////////////////
// LipSyncing.
//////////////////////////////////////////////////////////////////////////
struct SPhonemeInfo
{
wchar_t codeIPA; // IPA (International Phonetic Alphabet) code.
char ASCII[4]; // ASCII name for this phoneme.
const char* description; // Phoneme textual description.
};
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IPhonemeLibrary
{
virtual ~IPhonemeLibrary(){}
virtual int GetPhonemeCount() const = 0;
virtual bool GetPhonemeInfo( int nIndex,SPhonemeInfo &phoneme ) = 0;
virtual int FindPhonemeByName( const char *sPhonemeName ) = 0;
};
//////////////////////////////////////////////////////////////////////////
// Main interface to the facial animation system.
//////////////////////////////////////////////////////////////////////////
class IJoystickContext;
class IJoystickChannel;
struct IFacialAnimChannel;
UNIQUE_IFACE struct IFacialAnimation
{
virtual ~IFacialAnimation(){}
virtual IPhonemeLibrary* GetPhonemeLibrary() = 0;
virtual void ClearAllCaches() = 0;
// Creates a new effectors library.
virtual IFacialEffectorsLibrary* CreateEffectorsLibrary() = 0;
// Loads effectors library from the file.
virtual void ClearEffectorsLibraryFromCache(const char* filename) = 0;
virtual IFacialEffectorsLibrary* LoadEffectorsLibrary(const char* filename) = 0;
// Creates a new animation sequence.
virtual IFacialAnimSequence* CreateSequence() = 0;
virtual void ClearSequenceFromCache(const char* filename) = 0;
// Synchronous loading of sequence -> do not use in the game!
virtual IFacialAnimSequence* LoadSequence(const char* filename,bool bNoWarnings=false, bool addToCache=true) = 0;
// Starts to stream in a Sequence. IFacialAnimSequence* will be filled after StreamOnComplete
virtual IFacialAnimSequence* StartStreamingSequence(const char* filename) = 0;
// Access the joystick functionality.
virtual IJoystickContext* GetJoystickContext() = 0;
virtual IJoystickChannel* CreateJoystickChannel(IFacialAnimChannel* pEffector) = 0;
virtual void BindJoystickSetToSequence(IJoystickSet* pJoystickSet, IFacialAnimSequence* pSequence) = 0;
// Create an Identifier Handle to address objects in the Face Animation system by Handle
// instead of by strings.
virtual CFaceIdentifierHandle CreateIdentifierHandle(const char* identifierString) = 0;
};
//////////////////////////////////////////////////////////////////////////
// Sentence is a collection of phonemes and other lip syncing related data.
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialSentence
{
virtual ~IFacialSentence(){}
struct Phoneme
{
char phoneme[4]; // Phoneme name.
int time; // Start time of the phoneme in milliseconds.
int endtime; // End time the phoneme in milliseconds.
float intensity; // Phoneme intensity.
};
struct Word
{
const char *sWord; // Word text
int startTime; // Start time of the word in milliseconds.
int endTime; // End time of the word in milliseconds.
};
virtual void SetText( const char *text ) = 0;
virtual const char* GetText() = 0;
// Easy access to global phoneme library.
virtual struct IPhonemeLibrary* GetPhonemeLib() = 0;
virtual void ClearAllPhonemes() = 0;
virtual int GetPhonemeCount() = 0;
virtual bool GetPhoneme( int index,Phoneme &ph ) = 0;
virtual int AddPhoneme( const Phoneme &ph ) = 0;
// Delete all words in the sentence.
virtual void ClearAllWords() = 0;
// Return number of words in the sentence.
virtual int GetWordCount() = 0;
// Retrieve word by index, 0 <= index < GetWordCount().
virtual bool GetWord( int index,Word &wrd ) = 0;
// Add a new word into the sentence.
virtual void AddWord( const Word &wrd ) = 0;
struct ChannelSample
{
const char* phoneme;
float strength;
};
virtual int Evaluate(float fTime, float fInputPhonemeStrength, int maxSamples, ChannelSample* samples) = 0;
};
//////////////////////////////////////////////////////////////////////////
// Facial animation channel used in facial sequence.
// Each channel controls the weight of the single facial expression over time.
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialAnimChannel
{
virtual ~IFacialAnimChannel(){}
enum EFlags
{
FLAG_GROUP = 0x00001, // If set this channel is a group.
FLAG_PHONEME_STRENGTH = 0x00002, // This channel is the current phoneme strength.
FLAG_VERTEX_DRAG = 0x00004, // This channel is the vertex drag coefficient.
FLAG_BALANCE = 0x00008, // This channel controls the balance of the expressions.
FLAG_CATEGORY_BALANCE = 0x00010, // This channel controls the balance of the expressions in a certain folder.
FLAG_PROCEDURAL_STRENGTH = 0x00020, // This channel controls the strength of procedural animation.
FLAG_LIPSYNC_CATEGORY_STRENGTH = 0x00040, // This channel dampens all expressions in a folder during lipsyncing.
FLAG_BAKED_LIPSYNC_GROUP = 0x00080, // The contents of this folder override the auto-lipsynch.
FLAG_UI_SELECTED = 0x01000,
FLAG_UI_EXTENDED = 0x02000,
};
virtual void SetIdentifier( CFaceIdentifierHandle ident ) = 0;
virtual const CFaceIdentifierHandle GetIdentifier() = 0;
#ifdef FACE_STORE_ASSET_VALUES
// Only for the editor
virtual void SetName(const char* name) = 0;
virtual const char* GetName() const = 0;
virtual const char* GetEffectorName() = 0;
#endif
virtual void SetEffectorIdentifier( CFaceIdentifierHandle ident ) = 0;
virtual const CFaceIdentifierHandle GetEffectorIdentifier() = 0;
// Associate animation channel with the channel group.
virtual void SetParent( IFacialAnimChannel *pParent ) = 0;
// Get group of this animation channel.
virtual IFacialAnimChannel* GetParent() = 0;
// Change channel flags.
// See Also: EFlags
virtual void SetFlags( uint32 nFlags ) = 0;
virtual uint32 GetFlags() = 0;
virtual void SetEffector( IFacialEffector *pEffector ) = 0;
virtual IFacialEffector* GetEffector() = 0;
// Retrieve interpolator spline used to animated channel value.
virtual ISplineInterpolator* GetInterpolator(int i) = 0;
virtual ISplineInterpolator* GetLastInterpolator() = 0;
virtual void AddInterpolator() = 0;
virtual void DeleteInterpolator(int i) = 0;
virtual int GetInterpolatorCount() const = 0;
virtual void CleanupKeys(float fErrorMax) = 0;
virtual void SmoothKeys(float sigma) = 0;
virtual void RemoveNoise(float sigma, float threshold) = 0;
bool IsGroup() { return (GetFlags()&FLAG_GROUP) != 0; }
};
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialAnimSoundEntry
{
virtual ~IFacialAnimSoundEntry() {}
// Set filename of the sound associated with this facial sequence.
virtual void SetSoundFile( const char *sSoundFile ) = 0;
// Retrieve`s filename of the sound associated with this facial sequence.
virtual const char* GetSoundFile() = 0;
// Retrieve facial animation sentence interface.
virtual IFacialSentence* GetSentence() = 0;
virtual float GetStartTime() = 0;
virtual void SetStartTime(float time) = 0;
};
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialAnimSkeletonAnimationEntry
{
virtual ~IFacialAnimSkeletonAnimationEntry(){}
// Set the name of the animation associated with this entry.
virtual void SetName(const char* skeletonAnimationFile) = 0;
virtual const char* GetName() const = 0;
// Set the starting time of the animation.
virtual void SetStartTime(float time) = 0;
virtual float GetStartTime() const = 0;
virtual void SetEndTime(float time) = 0;
virtual float GetEndTime() const = 0;
};
//////////////////////////////////////////////////////////////////////////
UNIQUE_IFACE struct IFacialAnimSequence
{
virtual ~IFacialAnimSequence(){}
enum EFlags
{
FLAG_RANGE_FROM_SOUND = 0x00001, // Take time range from the sound length
};
enum ESerializationFlags
{
SFLAG_SOUND_ENTRIES = 0x00000001,
SFLAG_CAMERA_PATH = 0x00000002,
SFLAG_ANIMATION = 0x00000004,
SFLAG_ALL = 0xFFFFFFFF
};
virtual void AddRef() = 0;
virtual void Release() = 0;
// Changes sequence name.
virtual void SetName( const char *sNewName ) = 0;
// Retrieve sequence name.
virtual const char* GetName() = 0;
virtual void SetFlags( int nFlags ) = 0;
virtual int GetFlags() = 0;
virtual Range GetTimeRange() = 0;
virtual void SetTimeRange( Range range ) = 0;
//////////////////////////////////////////////////////////////////////////
// Access to channels.
//////////////////////////////////////////////////////////////////////////
virtual int GetChannelCount() = 0;
virtual IFacialAnimChannel* GetChannel( int nIndex ) = 0;
virtual IFacialAnimChannel* CreateChannel() = 0;
virtual IFacialAnimChannel* CreateChannelGroup() = 0;
virtual void RemoveChannel( IFacialAnimChannel *pChannel ) = 0;
//////////////////////////////////////////////////////////////////////////
// Access to sound entries.
virtual int GetSoundEntryCount() = 0;
virtual void InsertSoundEntry(int index) = 0;
virtual void DeleteSoundEntry(int index) = 0;
virtual IFacialAnimSoundEntry* GetSoundEntry(int index) = 0;
// Access the skeleton animations associated with this facial sequence.
virtual int GetSkeletonAnimationEntryCount() = 0;
virtual void InsertSkeletonAnimationEntry(int index) = 0;
virtual void DeleteSkeletonAnimationEntry(int index) = 0;
virtual IFacialAnimSkeletonAnimationEntry* GetSkeletonAnimationEntry(int index) = 0;
// Set the name of the joysticks associated with this sequence.
virtual void SetJoystickFile(const char* joystickFile) = 0;
virtual const char* GetJoystickFile() const = 0;
virtual void Serialize( XmlNodeRef &xmlNode,bool bLoading,ESerializationFlags flags=SFLAG_ALL ) = 0;
virtual void MergeSequence(IFacialAnimSequence* pMergeSequence, const Functor1wRet<const char*, MergeCollisionAction>& collisionStrategy) = 0;
virtual ISplineInterpolator* GetCameraPathPosition() = 0;
virtual ISplineInterpolator* GetCameraPathOrientation() = 0;
virtual ISplineInterpolator* GetCameraPathFOV() = 0;
// Streaming related - reports if the sequence has been streamed into memory and is available for animation
virtual bool IsInMemory() const = 0;
virtual void SetInMemory(bool bInMemory) = 0;
virtual void GetMemoryUsage( ICrySizer* pSizer ) const = 0;
};
static const float FACIAL_EDITOR_FPS = 30.0f;
inline float FacialEditorSnapTimeToFrame(float time) {return int((time * FACIAL_EDITOR_FPS) + 0.5f) * (1.0f / FACIAL_EDITOR_FPS);}
#endif // __IFacialAnimation_h__
| [
"[email protected]"
]
| [
[
[
1,
596
]
]
]
|
ec8b860ffd3eb372d1e4d589621923839e442794 | 12ea67a9bd20cbeed3ed839e036187e3d5437504 | /tpl/include/tpl/v1/script_parser.h | 94c5ca9ac05b1c19dd52a4b26cb0b9888719069c | []
| no_license | cnsuhao/winxgui | e0025edec44b9c93e13a6c2884692da3773f9103 | 348bb48994f56bf55e96e040d561ec25642d0e46 | refs/heads/master | 2021-05-28T21:33:54.407837 | 2008-09-13T19:43:38 | 2008-09-13T19:43:38 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 25,321 | h | /* -------------------------------------------------------------------------
// WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE
//
// This file is a part of the WINX Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.txt at this distribution. By using
// this software in any fashion, you are agreeing to be bound by the terms
// of this license. You must not remove this notice, or any other, from
// this software.
//
// Module: tpl/v1/script_parser.h
// Creator: xushiwei
// Email: [email protected]
// Date: 4/20/2003 19:10:13
// History:
// 1) 4/20/2003 19:10:13
// 输入脚本读取的核心模块,本文件内容不涉及具体的脚本语法,而针对抽象的Rule。
// 具体的脚本语法处理参考: text/script_in.h
// 2) 4/30/2003 13:19:03 移植到Linux
// 3) 5/3/2003 19:29:01 通配符*支持, 见 _MatchAll()
// 4) 5/4/2003 23:20:11 增加ErrorReport
// 5) 5/5/2003 15:20:43 支持()、[]、*{}
// 6) 8/22/2003 14:30:23 支持*[],用于辅助通配符*
//
// $Id: script_parser.h,v 1.4 2006/12/03 05:33:33 xushiwei Exp $
// -----------------------------------------------------------------------*/
#ifndef __TPL_V1_SCRIPT_PARSER_H__
#define __TPL_V1_SCRIPT_PARSER_H__
#ifndef __TPL_V1_SCRIPT_BASE_H__
#include "script_base.h"
#endif
#ifndef __TPL_V1_SCRIPT_VARIANT_H__
#include "script_variant.h"
#endif
#ifndef __TPL_V1_SCRIPT_ERROR_REPORT_H__
#include "script_error_report.h"
#endif
#ifndef TEXT_SCRIPT_API
#define TEXT_SCRIPT_API HRESULT __stdcall
#define TEXT_SCRIPT_API_(type) type __stdcall
#endif
#ifndef SCRIPT_RULE_API
#define SCRIPT_RULE_API static HRESULT __stdcall
#endif
#ifndef TEXT_SCRIPT_ERROR
#define TEXT_SCRIPT_ERROR(msg)
#endif
#ifndef E_UNKNOWN_SCRIPT_OP
#define E_UNKNOWN_SCRIPT_OP E_FAIL
#endif
#ifndef E_UNKNOWN_RULE
#define E_UNKNOWN_RULE E_FAIL
#endif
#define S_MATCH_EOF 0x123
// -------------------------------------------------------------------------
#ifndef ERRMSG
#define ERRMSG printf
#endif
#define _CHECK_HR(hr) NULL
// -------------------------------------------------------------------------
#if defined(_DEBUG) && defined(DEBUG_SCRIPT)
#define _StringImp String
#define HR_TRACE else printf
#define SCRIPT_TRACE printf
#else
#define _StringImp _NullString<char_type>
#define HR_TRACE(fmt, arg) 0
#define SCRIPT_TRACE 0
#endif
#if !defined(NO_PRETTY_PRINT)
#define _PrettyPrint(strc) PrettyPrint(strc)
#else
#define _PrettyPrint(strc)
#endif
// -------------------------------------------------------------------------
template <class _Archive, class _Variant, class _RecyleBin>
class KBuiltinRules
{
public:
typedef _Variant Variant;
typedef _Archive Archive;
typedef _RecyleBin RecycleBin;
typedef typename _Variant::String String;
typedef typename _Archive::size_type size_type;
typedef typename _Archive::char_type char_type;
typedef typename _Archive::int_type int_type;
typedef typename _Archive::pos_type pos_type;
typedef KScriptErrorReport<Archive, String> ErrorReport;
enum { endch = Archive::endch };
public:
SCRIPT_RULE_API match_blank(Archive& src, ErrorReport& report)
{
int_type ch = GetChar(src);
if (IsWhiteChar(ch))
return S_OK;
UngetChar(src, ch);
report.Except(src, ErrorReport::blank);
return E_UNEXPECTED;
}
SCRIPT_RULE_API match_quomark(Archive& src, ErrorReport& report)
{
SkipWhiteChars(src);
int_type ch = GetChar(src);
if (ch == '\"')
return S_OK;
UngetChar(src, ch);
report.Except(src, ErrorReport::quomark);
return E_UNEXPECTED;
}
SCRIPT_RULE_API match_csymbol(Archive& src, ErrorReport& report)
{
SkipWhiteChars(src);
_StringImp sym;
HRESULT hr = GetCLangSymbol(src, sym);
if (FAILED(hr))
report.Except(src, ErrorReport::csymbol);
HR_TRACE("---> _csymbol: \"%s\"\n", ToCStr(sym));
return hr;
}
SCRIPT_RULE_API match_matchrule(Archive& src, ErrorReport& report)
{
int_type ch = SkipWhiteCharsGetChar(src);
if (ch == '*')
return S_OK;
if (ch != '!')
UngetChar(src, ch);
_StringImp sym;
HRESULT hr = GetCLangSymbol(src, sym);
if (FAILED(hr))
report.Except(src, ErrorReport::csymbol_or_all);
return hr;
}
SCRIPT_RULE_API match_csymbol_or_all(Archive& src, ErrorReport& report)
{
int_type ch = SkipWhiteCharsGetChar(src);
if (ch == '*')
return S_OK;
UngetChar(src, ch);
_StringImp sym;
HRESULT hr = GetCLangSymbol(src, sym);
if (FAILED(hr))
report.Except(src, ErrorReport::csymbol_or_all);
return hr;
}
SCRIPT_RULE_API match_cint(Archive& src, ErrorReport& report)
{
SkipWhiteChars(src);
int intVal;
HRESULT hr = GetCLangIntConst(src, intVal);
if (FAILED(hr))
report.Except(src, ErrorReport::cint);
HR_TRACE("---> _cint: \"%d\"\n", intVal);
return hr;
}
SCRIPT_RULE_API match_eol(Archive& src, ErrorReport& report)
{
SCRIPT_TRACE("---> _eol\n");
for (;;)
{
switch ( GetChar(src) )
{
case '\n': case endch:
return S_OK;
}
}
}
SCRIPT_RULE_API match_ceol(Archive& src, ErrorReport& report)
{
SCRIPT_TRACE("---> _ceol\n");
int_type ch;
for (;;)
{
switch ( GetChar(src) )
{
case '\\':
while ( (ch = GetChar(src)) == '\r' || ch == '\n' );
UngetChar(src, ch);
break;
case '\n': case endch:
return S_OK;
}
}
}
SCRIPT_RULE_API match_eof(Archive& src, ErrorReport& report)
{
int_type ch = SkipWhiteCharsGetChar(src);
UngetChar(src, ch);
return ch == Archive::endch ? S_MATCH_EOF : E_UNEXPECTED;
}
SCRIPT_RULE_API match_cstring(Archive& src, ErrorReport& report)
{
SkipWhiteChars(src);
_StringImp strc;
HRESULT hr = GetCLangStringConst(src, strc);
if (FAILED(hr))
report.Except(src, ErrorReport::cstring);
HR_TRACE("---> _cstring: \"%s\"\n", ToCStr(strc));
return hr;
}
SCRIPT_RULE_API assign_cstring(
Archive& src, Variant& var, pos_type here, RecycleBin& recycle)
{
SkipWhiteChars(src);
String strc;
HRESULT hr = GetCLangStringConst(src, strc);
var.vt = Variant::vtAtom;
var.atomVal = recycle.NewAtom(strc);
return hr;
}
SCRIPT_RULE_API assign_cint(
Archive& src, Variant& var, pos_type here, RecycleBin& recycle)
{
SkipWhiteChars(src);
var.vt = Variant::vtInt;
return GetCLangIntConst(src, var.intVal);
}
SCRIPT_RULE_API assign_str_pretty(
Archive& src, Variant& var, pos_type here, RecycleBin& recycle)
{
String strc;
size_type strc_size = here - src.tell();
if ((int)strc_size > 0)
{
strc.resize(strc_size);
src.get(&strc[0], strc_size);
_PrettyPrint(strc);
}
var.vt = Variant::vtAtom;
var.atomVal = recycle.NewAtom(strc);
return S_OK;
}
SCRIPT_RULE_API assign_str(
Archive& src, Variant& var, pos_type here, RecycleBin& recycle)
{
SkipWhiteChars(src);
String strc;
size_type strc_size = here - src.tell();
if ((int)strc_size > 0)
{
strc.resize(strc_size);
src.get(&strc[0], strc_size);
}
var.vt = Variant::vtAtom;
var.atomVal = recycle.NewAtom(strc);
return S_OK;
}
SCRIPT_RULE_API assign_eol(
Archive& src, Variant& var, pos_type here, RecycleBin& recycle)
{
int_type ch;
String strc;
for (;;)
{
switch ( ch = GetChar(src) )
{
case '\r':
if (PeekChar(src) == '\n')
GetChar(src);
case '\n': case endch:
var.vt = Variant::vtAtom;
var.atomVal = recycle.NewAtom(strc);
return S_OK;
}
AppendChar(strc, ch);
}
}
};
// -------------------------------------------------------------------------
#pragma pack(1)
template <class _String>
struct KRule
{
typedef _String String;
typedef typename String::value_type char_type;
typedef std::list<KRule> RuleList;
typedef std::map<String, KRule> RuleMap;
struct MatchRule
{
String rule_name;
String var_name;
};
int op : 31;
int f_no_subtag : 1;
union
{
String* string_const;
MatchRule* mrule;
KRule* rule;
KRule* repeat_rule;
RuleList* or_rules;
RuleList* and_rules;
void* lpVal;
};
enum RuleType
{
match_none = 0x0000,
match_string_const = 0x0100,
match_mrule = 0x0200,
match_rule_and = 0x0300,
match_rule_or = 0x0400,
match_rule_repeat = 0x0501,
match_rule_repeat_or_not = 0x0500,
match_has_or_not = 0x0600,
match_rule_closeer = 0x0700,
match_all = 0x8000,
};
KRule() : op(match_none), f_no_subtag(0) {}
KRule(int opA, void* rule) : op(opA), f_no_subtag(0), lpVal(rule) {}
class RecycleBin
{
private:
std::AutoFreeAlloc m_alloc;
#if defined(_DEBUG)
private:
RecycleBin(const RecycleBin&);
void operator=(const RecycleBin&);
public:
RecycleBin() {
static nCount = 0;
TRACEA("====> %d) KRule::RecycleBin Construct...\n", ++nCount);
}
~RecycleBin() {
static nCount = 0;
TRACEA("====> %d) KRule::RecycleBin Destruct...\n", ++nCount);
}
#endif
public:
STDMETHODIMP_(KRule*) NewRule()
{
return STD_NEW(m_alloc, KRule);
}
STDMETHODIMP_(KRule*) NewRule(MatchRule* mrule)
{
return STD_NEW(m_alloc, KRule)(match_mrule, mrule);
}
STDMETHODIMP_(KRule*) NewRule(String* string_const)
{
return STD_NEW(m_alloc, KRule)(match_string_const, string_const);
}
STDMETHODIMP_(KRule*) NewRepeatRule(KRule* rule)
{
return STD_NEW(m_alloc, KRule)(match_rule_repeat, rule);
}
STDMETHODIMP_(KRule*) NewOrRule(RuleList* rules)
{
return STD_NEW(m_alloc, KRule)(match_rule_or, rules);
}
STDMETHODIMP_(KRule*) NewAndRule(RuleList* rules)
{
return STD_NEW(m_alloc, KRule)(match_rule_and, rules);
}
STDMETHODIMP_(KRule*) NewRuleMatchAll()
{
return STD_NEW(m_alloc, KRule)(match_all, NULL);
}
STDMETHODIMP_(MatchRule*) NewMRule()
{
return STD_NEW(m_alloc, MatchRule);
}
STDMETHODIMP_(RuleList*) NewRuleList()
{
return STD_NEW(m_alloc, RuleList);
}
STDMETHODIMP_(String*) NewString(const char_type* val)
{
return STD_NEW(m_alloc, String)(val);
}
};
};
#pragma pack()
// -------------------------------------------------------------------------
template
<
class _Archive,
class _String,
class _Rule = KRule<_String>,
class _Variant = KVariant<_String>
>
class KScriptParser
: public KBuiltinRules< _Archive, _Variant, typename _Variant::RecycleBin>,
public KScriptLog
{
public:
typedef typename _Archive::char_type char_type;
typedef typename _Archive::pos_type pos_type;
typedef char_type Char;
typedef _Archive Archive;
typedef _String String;
typedef _Variant Variant;
typedef typename _Variant::Node Node;
typedef typename _Variant::NodeList NodeList;
typedef typename _Variant::VariantType VariantType;
typedef _Rule Rule;
typedef typename _Rule::MatchRule MatchRule;
typedef typename _Rule::RuleList RuleList;
typedef typename _Rule::RuleMap RuleMap;
typedef typename _Variant::RecycleBin RecycleBin;
enum RuleType
{
match_none = Rule::match_none,
match_string_const = Rule::match_string_const,
match_mrule = Rule::match_mrule,
match_rule_and = Rule::match_rule_and,
match_rule_or = Rule::match_rule_or,
match_rule_repeat = Rule::match_rule_repeat,
match_rule_repeat_or_not = Rule::match_rule_repeat_or_not,
match_rule_closeer = Rule::match_rule_closeer,
match_all = Rule::match_all,
match_has_or_not = Rule::match_has_or_not,
};
typedef HRESULT __stdcall FnBuiltinMatch(Archive& src, ErrorReport& report);
typedef HRESULT __stdcall FnBuiltinAssign(
Archive& src, Variant& var, pos_type here, RecycleBin& recycle);
struct _BuiltinRule
{
FnBuiltinMatch* fnMatch;
FnBuiltinAssign* fnAssign;
_BuiltinRule() {}
_BuiltinRule(FnBuiltinMatch* fnMatchA, FnBuiltinAssign* fnAssignA)
: fnMatch(fnMatchA), fnAssign(fnAssignA) {}
};
typedef _BuiltinRule BuiltinRule;
typedef std::map<String, BuiltinRule> BuiltinRuleMap;
enum VariantAllocType
{
vat_none = 0,
vat_locale = 1,
vat_global = 2,
};
protected:
Archive& src;
RuleMap& rules;
BuiltinRuleMap& builtin_rules;
RecycleBin& recycle;
ErrorReport report;
protected:
STDMETHODIMP_(void) _AddVariant(NodeList& vars, const String& name, const Variant& value)
{
Node node;
node.name = recycle.NewAtom(name);
node.value = value;
vars.push_back(node);
}
TEXT_SCRIPT_API _MatchAll(MatchRule& mrule, NodeList& vars, Rule& ruleNext)
{
// _MatchAll() effect taken on 'vars': depend on _MatchAllNoResult()
BOOL fNoResult = mrule.var_name.empty();
if (fNoResult)
{
pos_type pos_goto;
HRESULT hr = _MatchAllNoResult(vars, ruleNext, &pos_goto, NULL);
if (SUCCEEDED(hr))
{
src.seek(pos_goto);
}
return hr;
}
else
{
pos_type pos_goto;
pos_type pos_next_rule_start;
pos_type start = src.tell();
HRESULT hr = _MatchAllNoResult(vars, ruleNext, &pos_goto, &pos_next_rule_start);
if (SUCCEEDED(hr))
{
Variant varg;
src.seek(start);
assign_str_pretty(src, varg, pos_next_rule_start, recycle);
src.seek(pos_goto);
_AddVariant(vars, mrule.var_name, varg);
}
return hr;
}
}
TEXT_SCRIPT_API _MatchAllNoResult(
NodeList& vars, Rule& ruleNext, pos_type* pos_goto, pos_type* pos_next_rule_start_ret)
{
// _MatchAllNoResult() effect taken on 'vars': depend on [?]
if (ruleNext.op != match_rule_or)
return _MatchAllNoResultBase(ruleNext, -1, pos_goto, pos_next_rule_start_ret);
// $(*) ("strc1" $(rule1) | "strc2" $(rule2) | *["strc3"|"strc4"] $(rule) | ...)
RuleList& rule_list = *ruleNext.or_rules;
Rule* rule_best_match = NULL;
int limit = -1;
HRESULT hr = E_STRING_UNMATCH;
pos_type pos_next_rule_start;
pos_type start = src.tell();
typename RuleList::iterator it;
for (it = rule_list.begin(); it != rule_list.end(); ++it)
{
src.seek(start);
Rule& rule = *it;
switch (rule.op)
{
case match_rule_and: {
RuleList& rule_and_list = *rule.and_rules;
if ( S_OK == _MatchAllNoResultBase(
*rule_and_list.begin(), limit, pos_goto, &pos_next_rule_start) )
{
hr = S_OK;
rule_best_match = &rule;
limit = src.tell() - start;
}
break; }
default:
if ( S_OK == _MatchAllNoResultBase(
rule, limit, pos_goto, &pos_next_rule_start) )
{
hr = S_OK;
rule_best_match = NULL;
limit = src.tell() - start;
}
}
}
if (pos_next_rule_start_ret)
*pos_next_rule_start_ret = pos_next_rule_start;
if (rule_best_match)
{
ASSERT(rule_best_match->op == match_rule_and);
src.seek(pos_next_rule_start);
hr = _MatchRuleAnd(*rule_best_match->and_rules, vars, FALSE);
}
if (SUCCEEDED(hr))
*pos_goto = src.tell();
return hr;
}
//
//@@bugfix:
// 将原先_MatchAllNoResultBase改名为__MatchAllNoResultBase。
// 因为原先$(*)就算匹配0个字节也算成功,现在我们认为是错误。
// 这样可以避免因为$(rule)匹配0字节而导致死循环问题。
//
TEXT_SCRIPT_API _MatchAllNoResultBase(
Rule& ruleNext, int limit, pos_type* pos_goto, pos_type* pos_next_rule_start)
{
pos_type pos_old = src.tell();
HRESULT hr = __MatchAllNoResultBase(ruleNext, limit, pos_goto, pos_next_rule_start);
if (SUCCEEDED(hr))
{
if (*pos_goto <= pos_old)
return E_FAIL;// 0字节匹配
}
return hr;
}
TEXT_SCRIPT_API __MatchAllNoResultBase(
Rule& ruleNext, int limit, pos_type* pos_goto, pos_type* pos_next_rule_start)
{
// _MatchAllNoResultBase() effect taken on 'vars': no change!!!
switch (ruleNext.op)
{
case match_string_const: {
// $(*) "strc"
String& strc = *ruleNext.string_const;
std::kmp::Finder<char> finder(strc);
if (S_OK == finder.next(src, limit))
{
*pos_goto = src.tell();
if (pos_next_rule_start)
*pos_next_rule_start = *pos_goto - strc.size();
return S_OK;
}
return E_STRING_UNMATCH; }
case match_rule_closeer:
switch (ruleNext.rule->op)
{
case match_string_const: {
// $(*) *[ "strc" ]
String& strc = *((ruleNext.rule)->string_const);
std::kmp::Finder<char> finder(strc);
if (S_OK == finder.next(src, limit))
{
*pos_goto = src.tell() - strc.size();
if (pos_next_rule_start)
*pos_next_rule_start = *pos_goto;
return S_OK;
}
return E_STRING_UNMATCH; }
case match_rule_or: {
// $(*) *[ "strc1" | "strc2" | ... | "strcn" ]
RuleList& rule_list = *ruleNext.rule->or_rules;
size_type next_rule_size;
if (S_OK == _MatchRuleCloseerOr(rule_list, limit, &next_rule_size))
{
*pos_goto = src.tell() - next_rule_size;
if (pos_next_rule_start)
*pos_next_rule_start = *pos_goto;
return S_OK;
}
return E_STRING_UNMATCH; }
default:
ASSERT(0);
return E_NOTIMPL;
}
break;
default:
ASSERT(0);
return E_FAIL;
}
}
TEXT_SCRIPT_API _MatchRuleCloseerOr(
RuleList& rule_list, int limit, size_type* next_rule_size)
{
// *[ "strc1" | "strc2" | ... | "strcn" ]
// _MatchRuleCloseerOr() effect taken on 'vars': no change!!!
HRESULT hr = E_STRING_UNMATCH;
pos_type start = src.tell();
typename RuleList::iterator it;
for (it = rule_list.begin(); it != rule_list.end(); ++it)
{
Rule& rule = *it;
ASSERT(rule.op == match_string_const);
if (rule.op == match_string_const)
{
src.seek(start);
String& strc = *rule.string_const;
std::kmp::Finder<char> finder(strc);
if (S_OK == finder.next(src, limit))
{
hr = S_OK;
*next_rule_size = strc.size();
limit = src.tell() - start;
}
}
}
return hr;
}
TEXT_SCRIPT_API _MatchMRule(MatchRule& mrule, NodeList& vars, BOOL fNotAllowToFail)
{
// _MatchMRule() effect taken on 'vars': depend on _MatchMRuleNoResult()
BOOL fNoResult = mrule.var_name.empty();
FnBuiltinAssign* fnAssign;
if (fNoResult)
return _MatchMRuleNoResult(mrule, &vars, &fnAssign, fNotAllowToFail);
else
{
pos_type start = src.tell();
HRESULT hr = _MatchMRuleNoResult(mrule, &vars, &fnAssign, fNotAllowToFail);
if (SUCCEEDED(hr))
{
pos_type here = src.tell();
Variant varg;
src.seek(start);
fnAssign(src, varg, here, recycle);
src.seek(here);
_AddVariant(vars, mrule.var_name, varg);
}
return hr;
}
}
TEXT_SCRIPT_API _MatchMRuleNoResult(
MatchRule& mrule, NodeList* vars, FnBuiltinAssign** fn, BOOL fNotAllowToFail)
{
// _MatchMRuleNoResult() effect taken on 'vars': depend on _MatchRule()
HRESULT hr;
const char_type* rule_name = mrule.rule_name.c_str();
VariantAllocType vat = vat_locale;
if (*rule_name == '!') // todo: 暂时不允许'!'与'_'相连。
{
++rule_name;
fNotAllowToFail |= TRUE;
}
else if (*rule_name == '_') // this rule doesn't need to create a subtag
{
++rule_name;
vat = vat_none;
}
typename RuleMap::iterator it = rules.find(rule_name);
if (it == rules.end()) // maybe is a builtin rule
{
if (vat == vat_none)
{
typename BuiltinRuleMap::iterator it = builtin_rules.find(--rule_name);
if (it != builtin_rules.end())
{
*fn = (*it).second.fnAssign;
report.SetContext(src, mrule.var_name);
return (*it).second.fnMatch(src, report);
}
}
ERRMSG("---> Invalid input script: rule '%s' not found.\n", rule_name);
return E_UNKNOWN_RULE;
}
NodeList* alter_vars = NULL;
if ( (*it).second.f_no_subtag )
{
*fn = assign_str_pretty;
alter_vars = vars = recycle.NewVariantList();
}
else
{
*fn = assign_str;
}
if (vat != vat_none) // create a subtag
{
NodeList& varList = *recycle.NewVariantList();
hr = _MatchRule((*it).second, varList, fNotAllowToFail);
if (SUCCEEDED(hr))
_AddVariant(*vars, rule_name, Variant(&varList));
else if (fNotAllowToFail)
_NotAllowToFail(rule_name, vars, varList);
}
else
{
hr = _MatchRule((*it).second, *vars, fNotAllowToFail);
}
if (alter_vars)
recycle.Delete(alter_vars);
return hr;
}
TEXT_SCRIPT_API _NotAllowToFail(
const char_type* rule_name, NodeList* vars, NodeList& varList)
{
log.Print(" ===> !!! Error when processing <%s>\n", rule_name);
PrintVariantListT(log, varList, 1);
log.Print("\n");
// _AddVariant(*vars, rule_name, Variant(&varList));
return S_OK;
}
TEXT_SCRIPT_API _MatchRuleAnd(RuleList& rule_list, NodeList& vars, BOOL fNotAllowToFail)
{
// _MatchRuleAnd() effect taken on 'vars': do it! [depend on _MatchRule()]
HRESULT hr = S_OK;
typename NodeList::size_type count = vars.size();
typename RuleList::iterator it;
for (it = rule_list.begin(); it != rule_list.end(); ++it)
{
switch ((*it).op)
{
case match_all: {
MatchRule& mrule = *(*it).mrule;
++it;
if (it == rule_list.end())
return E_UNEXPECTED;
hr = _MatchAll(mrule, vars, *it);
break; }
default:
hr = _MatchRule(*it, vars);
}
if (FAILED(hr) && !fNotAllowToFail)
{
vars.resize(count);
break;
}
}
_CHECK_HR(hr);
return hr;
}
TEXT_SCRIPT_API _MatchRuleOr(RuleList& rule_list, NodeList& vars)
{
// _MatchRuleOr() effect taken on 'vars': do it! [depend on _MatchRule()]
HRESULT hr = S_OK;
_DEBUG_ONLY(
typename NodeList::size_type count = vars.size()
);
pos_type here = src.tell();
typename RuleList::iterator it;
for (it = rule_list.begin(); it != rule_list.end(); ++it)
{
hr = _MatchRule(*it, vars);
if (SUCCEEDED(hr))
break;
ASSERT(vars.size() == count); //_Resize(vars, size);
src.seek(here);
}
_CHECK_HR(hr);
return hr;
}
TEXT_SCRIPT_API _MatchRuleRepeat(Rule& rule, NodeList& vars, int minCount)
{
// _MatchRuleRepeat() effect taken on 'vars': do it! [depend on _MatchRule()]
HRESULT hr = S_OK;
int matchCount = 0;
for (;;)
{
pos_type here = src.tell();
_DEBUG_ONLY(
typename NodeList::size_type count = vars.size()
);
hr = _MatchRule(rule, vars);
if (FAILED(hr))
{
ASSERT(vars.size() == count); //_Resize(vars, size);
src.seek(here);
break;
}
else
{
++matchCount;
if (hr == S_MATCH_EOF)
break;
}
}
return matchCount >= minCount ? S_OK : E_FAIL;
}
TEXT_SCRIPT_API _MatchRuleCloseer(Rule& rule, NodeList& vars, int minCount)
{
return E_FAIL;
}
TEXT_SCRIPT_API _MatchRule(Rule& rule, NodeList& vars, BOOL fNotAllowToFail = FALSE)
{
// _MatchRule() effect taken on 'vars':
// _MatchRuleAnd(), _MatchMRule(), _MatchRuleOr(), _MatchRuleRepeat()
HRESULT hr;
switch (rule.op)
{
case match_string_const: {
const char_type* strc = ToCStr(*rule.string_const);
if (*strc == '\0')
return S_OK;
SkipWhiteChars(src);
report.SetContext(src, *rule.string_const);
hr = MatchString(src, strc);
if (FAILED(hr))
report.Except(src, NULL);
HR_TRACE("---> _cstring: \"%s\"\n", strc);
break; }
case match_rule_and:
hr = _MatchRuleAnd(*rule.and_rules, vars, fNotAllowToFail);
break;
case match_mrule:
hr = _MatchMRule(*rule.mrule, vars, fNotAllowToFail);
break;
case match_rule_or:
hr = _MatchRuleOr(*rule.or_rules, vars);
break;
case match_rule_repeat:
case match_rule_repeat_or_not:
hr = _MatchRuleRepeat(*rule.rule, vars, rule.op & 0xff);
break;
case match_has_or_not: {
pos_type here = src.tell();
hr = _MatchRule(*rule.rule, vars);
if (FAILED(hr))
{
src.seek(here);
hr = S_OK;
}
break; }
//case match_rule_closeer:
// hr = E_FAIL;
// break;
default:
TEXT_SCRIPT_ERROR("Unknown Script Rule Operator!!!");
hr = E_UNKNOWN_SCRIPT_OP;
}
_CHECK_HR(hr);
return hr;
}
public:
KScriptParser(
Archive& srcA,
RuleMap& rulesA,
BuiltinRuleMap& builtin_rulesA,
RecycleBin& recycleA
)
: src(srcA), rules(rulesA), builtin_rules(builtin_rulesA), recycle(recycleA)
{
}
TEXT_SCRIPT_API Parse(MatchRule& mrule, NodeList& vars)
{
HRESULT hr = _MatchMRule(mrule, vars, FALSE);
if (SUCCEEDED(hr))
return SkipWhiteCharsGetChar(src) == Archive::endch ? S_OK : E_UNEXPECTED;
return hr;
}
TEXT_SCRIPT_API_(void) ReportError(Archive& src)
{
report.ReportError(src);
}
};
// -------------------------------------------------------------------------
// $Log: script_parser.h,v $
// Revision 1.4 2006/12/03 05:33:33 xushiwei
// Manul Tools - Version 1.0
//
// Revision 1.2 2006/12/02 07:57:49 xushiwei
// std::AutoFreeAlloc
//
// Revision 1.1 2006/12/02 06:44:18 xushiwei
// Text Processing Library - Version 1.0
//
#endif /* __TPL_V1_SCRIPT_PARSER_H__ */
| [
"xushiweizh@86f14454-5125-0410-a45d-e989635d7e98"
]
| [
[
[
1,
991
]
]
]
|
6f3aa7c2d85081050862372fafa85c66e40bf83d | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /connectivitylayer/isce/p2papi_dll/inc/p2pif.h | e95230fd1fc9922030655893ad7fc6ae43ea120d | []
| no_license | wannaphong/symbian-incubation-projects.fcl-modemadaptation | 9b9c61ba714ca8a786db01afda8f5a066420c0db | 0e6894da14b3b096cffe0182cedecc9b6dac7b8d | refs/heads/master | 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,867 | h | /*
* 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:
*
*/
#ifndef __P2PIF_H__
#define __P2PIF_H__
#include <e32cmn.h> // For RBusLogicalChannel
#include <p2pdefs.h> // For TP2PProtocol
/**
* An interface for transceiving point-to-point (P2P) data between
* two end points according to used P2P protocol.
* Interface is used from user side.
*/
class RP2PIf : public RBusLogicalChannel
{
public:
/*
* C++ default constructor.
*/
IMPORT_C RP2PIf();
/*
* Destructor
*/
IMPORT_C ~RP2PIf();
/*
* Closes the interface and cancels any outstanding requests with KErrCancel.
* If interface is not opened with RP2PIf::Open does nothing.
* Automatically called in destructor.
* Execution: Synchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @post Calling thread not blocked
*/
IMPORT_C void Close();
/*
* Notifies when connection to other point is lost.
* Automatically cancelled in RP2PIf::Close.
* All data received after connection is lost shall be discarded.
* NOTE! If interface is not open panicked with User::Panic.
* NOTE! After connection lost RP2PIf::Close shall be called.
* Execution: Asynchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @param aStatus, updated when connection is lost
* KErrNotReady when connection is lost
* KErrCancel when request is cancelled
* @post Calling thread not blocked
*/
IMPORT_C void ConnectionLost( TRequestStatus& aStatus );
/*
* Cancels the pending connection lost request with KErrCancel.
* Automatically cancelled in RP2PIf::Close.
* NOTE! If interface is not open panicked with User::Panic.
* Execution: Synchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @post Calling thread not blocked
*/
IMPORT_C void ConnectionLostCancel();
/**
* Asynchronously opens a P2P protocol communication path from this point to another.
* Open is not complited before the communication path is open.
* When request is set to pending blocked calling thread is released.
* Automatically cancelled in RP2PIf::Close.
* Execution: Asynchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @param aP2PProtocolId, unique identifier of the used point-to-point protocol
* @param aStatus, KErrNone if ok
* KErrNotSupported if protocol is not supported
* KErrInUse if someone uses the same protocol id
* KErrAlreadyExists same interface object is opened with other protocol id
* KErrCancel if outstanding request is cancelled
* KErrPermissionDenied if not enough capabilities
* @param aHandleType, specifies whether the handle is owned by process or by thread.
* @post Calling thread not blocked
*/
IMPORT_C void Open( const TP2PProtocol aP2PProtocolId,
TRequestStatus& aStatus,
TOwnerType aHandleType = EOwnerThread );
/**
* Cancel asynchronous channel opening with KErrCancel.
* Does nothing if request is not pending.
* Automatically called in RP2PIf::Close.
* NOTE! If interface is not open panicked with User::Panic.
* Execution: Synchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @post Calling thread not blocked
*/
IMPORT_C void OpenCancel();
/**
* Receive data from other point.
* Either receives data immediately or set the receive request pending.
* When request is set to pending blocked calling thread is released.
* Automatically cancelled in RP2PIf::Close.
* NOTE! If interface is not open panicked with User::Panic.
* NOTE! If interface is not opened when other point is sending data to it data shall
* be deallocated.
* Execution: Asynchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @param aStatus, KErrNone if ok.
* KErrBadDescriptor if receive buffer is invalid or too small.
* @param aReceiveBuffer, buffer where to receive data from kernel
*/
IMPORT_C void Receive( TRequestStatus& aStatus, TDes8& aReceiveBuffer );
/**
* Cancel asynchronous receive request with KErrCancel.
* Does nothing if request is not pending.
* Automatically called in RP2PIf::Close.
* NOTE! If interface is not open panicked with User::Panic.
* Execution: Synchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @post Calling thread not blocked
*/
IMPORT_C void ReceiveCancel();
/**
* Sends data to other point.
* NOTE! If interface is not open panicked with User::Panic.
* NOTE! Absolutely maximum send buffer size is 16-bit value.
* Execution: Synchronous
* Re-entrant: No
* Blocking: Yes
* Panic mode: User::Panic
* SMP safe: Yes
* @param aSendBuffer, data to be send
* @return KErrNone, is succesfull
* KErrNoMemory buffer size is over the maximum size
* KErrNotReady connection to other point lost, data lost
* KErrBadDescriptor if send buffer is invalid
* @post Calling thread not blocked
*/
IMPORT_C TInt Send( const TDesC8& aSendBuffer );
};
#endif // __P2PIF_H__
// End of File
| [
"dalarub@localhost"
]
| [
[
[
1,
183
]
]
]
|
e0381dd8d3362e67a801408b5d55574fbb824267 | 12203ea9fe0801d613bbb2159d4f69cab3c84816 | /Export/cpp/windows/obj/include/nme/events/IEventDispatcher.h | 57ef43a0579ae408ef7fe480b3c7e043d6e148f5 | []
| no_license | alecmce/haxe_game_of_life | 91b5557132043c6e9526254d17fdd9bcea9c5086 | 35ceb1565e06d12c89481451a7bedbbce20fa871 | refs/heads/master | 2016-09-16T00:47:24.032302 | 2011-10-10T12:38:14 | 2011-10-10T12:38:14 | 2,547,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,567 | h | #ifndef INCLUDED_nme_events_IEventDispatcher
#define INCLUDED_nme_events_IEventDispatcher
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS2(nme,events,Event)
HX_DECLARE_CLASS2(nme,events,IEventDispatcher)
namespace nme{
namespace events{
class IEventDispatcher_obj : public hx::Interface{
public:
typedef hx::Interface super;
typedef IEventDispatcher_obj OBJ_;
HX_DO_INTERFACE_RTTI;
virtual Void addEventListener( ::String type,Dynamic listener,bool useCapture=null(),int priority=null(),bool useWeakReference=null())=0;
Dynamic addEventListener_dyn();
virtual bool dispatchEvent( ::nme::events::Event event)=0;
Dynamic dispatchEvent_dyn();
virtual bool hasEventListener( ::String type)=0;
Dynamic hasEventListener_dyn();
virtual Void removeEventListener( ::String type,Dynamic listener,bool useCapture=null())=0;
Dynamic removeEventListener_dyn();
virtual bool willTrigger( ::String type)=0;
Dynamic willTrigger_dyn();
};
#define DELEGATE_nme_events_IEventDispatcher \
virtual Void addEventListener( ::String type,Dynamic listener,bool useCapture=null(),int priority=null(),bool useWeakReference=null()) { return mDelegate->addEventListener(type,listener,useCapture,priority,useWeakReference);} \
virtual Dynamic addEventListener_dyn() { return mDelegate->addEventListener_dyn();} \
virtual bool dispatchEvent( ::nme::events::Event event) { return mDelegate->dispatchEvent(event);} \
virtual Dynamic dispatchEvent_dyn() { return mDelegate->dispatchEvent_dyn();} \
virtual bool hasEventListener( ::String type) { return mDelegate->hasEventListener(type);} \
virtual Dynamic hasEventListener_dyn() { return mDelegate->hasEventListener_dyn();} \
virtual Void removeEventListener( ::String type,Dynamic listener,bool useCapture=null()) { return mDelegate->removeEventListener(type,listener,useCapture);} \
virtual Dynamic removeEventListener_dyn() { return mDelegate->removeEventListener_dyn();} \
virtual bool willTrigger( ::String type) { return mDelegate->willTrigger(type);} \
virtual Dynamic willTrigger_dyn() { return mDelegate->willTrigger_dyn();} \
template<typename IMPL>
class IEventDispatcher_delegate_ : public IEventDispatcher_obj
{
protected:
IMPL *mDelegate;
public:
IEventDispatcher_delegate_(IMPL *inDelegate) : mDelegate(inDelegate) {}
hx::Object *__GetRealObject() { return mDelegate; }
DELEGATE_nme_events_IEventDispatcher
};
} // end namespace nme
} // end namespace events
#endif /* INCLUDED_nme_events_IEventDispatcher */
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
d4bf773ed8e8df4a42d59bdad1cd6a4ca8c7d726 | 559770fbf0654bc0aecc0f8eb33843cbfb5834d9 | /haina/codes/beluga/client/symbian/BelugaDb/inc/contact/CContactDb.h | a91d3a442e8f178f1cf616cecb2a5fe11f9a7b67 | []
| no_license | CMGeorge/haina | 21126c70c8c143ca78b576e1ddf352c3d73ad525 | c68565d4bf43415c4542963cfcbd58922157c51a | refs/heads/master | 2021-01-11T07:07:16.089036 | 2010-08-18T09:25:07 | 2010-08-18T09:25:07 | 49,005,284 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,230 | h | /*
============================================================================
Name : CContactDb.h
Author : shaochuan.yang
Copyright : haina
Description : Contact Database
============================================================================
*/
#ifndef __CCONTACTDB_H__
#define __CCONTACTDB_H__
#include <time.h>
#include "CEntityDb.h"
#include "CContact.h"
#include "CContactIterator.h"
enum EContactEvent
{
ContactEvent_SMS = 1,
ContactEvent_Email,
ContactEvent_MMS,
ContactEvent_AnsweredCall,
ContactEvent_RejectedCall,
ContactEvent_OutgoCall,
ContactEvent_QQ,
ContactEvent_MSN
};
enum ECommType
{
CommType_Phone = 0x10,
CommType_Email = 0x20,
CommType_Address = 0x30,
CommType_IM = 0x40,
CommType_Home = 0x01,
CommType_Work = 0x02,
CommType_Other = 0x03,
CommType_Pref = 0x04,
CommType_QQ = 0x05,
CommType_MSN = 0x06,
};
struct stRecentContact
{
guint32 nContactId;
EContactEvent event;
gchar eventCommInfo[256];
tm * time;
};
#define MAX_RECENT_CONTACT_NUM 15
class CGroup;
class CContactIterator;
class CPhoneContact;
class CContactDb : public CEntityDb
{
public:
CContactDb();
~CContactDb();
IMPORT_C gint32 InitEntityDb();
IMPORT_C gint32 GetMaxId(guint32 * nMaxId);
IMPORT_C gint32 GetEntityById(guint32 nId, CDbEntity** ppEntity);
IMPORT_C gint32 SaveEntity(CDbEntity * pEntity);
IMPORT_C gint32 DeleteEntity(guint32 nEntityId);
IMPORT_C gint32 UpdateEntity(CDbEntity * pEntity);
IMPORT_C gint32 DeleteAllContactsByTag(guint32 nTagId); /* delete all contacts but groups */
IMPORT_C gint32 ReleaseContactGroupRelation(CContact * pContact, CGroup * pGroup);
IMPORT_C gint32 ReleaseContactGroupRelation(guint32 nContactId, guint32 nGroupId);
IMPORT_C gint32 ReleaseContactAllRelations(guint32 nContactId);
IMPORT_C gint32 ReleaseContactAllRelations(CContact * pContact);
IMPORT_C gint32 CreateContactGroupRelation(CContact * pContact, CGroup * pGroup);
IMPORT_C gint32 CreateContactGroupRelation(guint32 nContactId, guint32 nGroupId);
IMPORT_C gint32 SearchContactsByTag(guint32 nTagId, GArray * fieldsIndex, GPtrArray * fieldsValue,
gboolean onlyPref, CContactIterator ** ppContactIterator);
IMPORT_C gint32 SearchPhoneContactsByPhoneOrEmail(gchar * commValue,
gboolean onlyPref, CContactIterator ** ppContactIterator);
IMPORT_C gint32 SearchContactsByName(guint32 nTagId, gchar* name, gboolean onlyPref,
CContactIterator ** ppContactIterator);
// IMPORT_C gint32 SearchContactsByWordsFirstLetter(guint32 nTagId, gchar* nameLetters, gboolean onlyPref,
// CContactIterator ** ppContactIterator);
// IMPORT_C gint32 GetMostMatchingContactByTag(guint32 nTagId, GArray * fieldsIndex, GPtrArray * fieldsValue,
// gboolean onlyPref, CContact ** ppContact);
IMPORT_C gint32 GetMostMatchingPhoneContactByPhoneOrEmail(gchar * commValue, CContact ** ppContact);
IMPORT_C gint32 GetAllContactsByTag(guint32 nTagId, gboolean onlyPref, CContactIterator ** ppContactIterator);
IMPORT_C gint32 GetAllContactsNotInGroupByTag(guint32 nTagId, gboolean onlyPref, CContactIterator ** ppContactIterator);
IMPORT_C gint32 GetAllContactsByGroup(guint32 nGroupId, gboolean onlyPref, CContactIterator ** ppContactIterator);
IMPORT_C gint32 GetContactsTotalityByTag(guint32 nTagId, guint32 * totality);
IMPORT_C gint32 GetContactsTotalityByGroup(guint32 nGroupId, guint32 * totality);
IMPORT_C gint32 GetPhoneDistrict(gchar* phoneNumber, gchar ** districtNumber, gchar ** districtName, gchar ** feeType);
IMPORT_C gint32 GetRecentContacts(GPtrArray ** pContacts);
IMPORT_C gint32 SaveRecentContact(stRecentContact * contact);
gint32 GetContactCommInfo(CPhoneContact * pContact); /* must create a hashtable and a ptrarray */
private:
gint32 GetMaxContactCommId(guint32 * pMaxCommId);
gboolean CheckGroupInTag(guint32 nGroupId, guint32 nTagId);
private:
gint32 m_nDbErrCode;
};
#endif
| [
"shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d"
]
| [
[
[
1,
121
]
]
]
|
0e2b18bd0396c247ebef3493844f9e158e77ffd0 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /LaserBrothers/src/NelderMead_opt.cpp | 5f752183a46a0c54147c215f19e453d5ab4d81bc | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,233 | cpp | #include "NelderMead_opt.h"
#include <algorithm>
#include <iostream>
#ifdef WIN32
#define snprintf _snprintf
#endif
using namespace std;
double gsl_wrapper_measure_f(const gsl_vector* params, void* p)
{
return ((NelderMead_opt*) p)->measure_f(params);
}
NelderMead_opt::NelderMead_opt(unsigned N, unsigned num_to_measure, double dx0, opt_actuator* act) :
Actuator_opt(N, act),
num_to_measure(num_to_measure), num_measured(0),
fminimizer(0), f_total(0), simplex_size(0), f_max(0), bMeasuring(false), bHadFault(false)
{
/* Starting point */
x = gsl_vector_alloc(N);
gsl_vector_set_all (x, 0);
/* Set initial step sizes to */
ss = gsl_vector_alloc(N);
gsl_vector_set_all (ss, dx0);
/* Initialize method and iterate */
minex_func.n = N;
minex_func.f = gsl_wrapper_measure_f;
minex_func.params = this;
fminimizer = gsl_multimin_fminimizer_alloc (gsl_multimin_fminimizer_nmsimplex, N);
}
NelderMead_opt::~NelderMead_opt()
{
bStop = true;
is_measurement_complete.wakeAll();
this->wait();
gsl_multimin_fminimizer_free (fminimizer);
}
//! Tell the optimizer what the current function value is.
void NelderMead_opt::measured_f(double f, bool bFault)
{
if(!bMeasuring)
return;
if(num_measured == 0)
{
bHadFault = false;
f_total = 0;
f_max = 0;
}
bHadFault = bFault || bHadFault;
if(f_max < f)
f_max = f;
f_total += f;
num_measured++;
if(num_measured >= num_to_measure)
{
if(!bHadFault)
f_max = f_total / num_measured;
bMeasuring = false;
num_measured = 0;
is_measurement_complete.wakeAll();
}
}
double NelderMead_opt::measure_f(const gsl_vector* params)
{
if(bStop)
return 0;
tMeasured.start();
vector<double> xnew(nDimensions);
for(size_t i=0; i<nDimensions; i++)
xnew[i] = gsl_vector_get(params, i);
act->measure(xnew);
bMeasuring = true;
mtx.lock();
is_measurement_complete.wait(&mtx);
mtx.unlock();
cout << "[NelderMead_opt::measure_f] f_max = " << f_max << endl;
simplex_size = gsl_multimin_fminimizer_size (fminimizer);
if(fLog)
{
fprintf(fLog, "%u, %6.4f, %8.0f", tRun.elapsed(), f_max, simplex_size);
for(unsigned i=0; i<nDimensions; i++)
fprintf(fLog, ", %12.4f", gsl_vector_get (params, i));
fprintf(fLog, "\n");
fflush(fLog);
}
return -1*f_max;
}
void NelderMead_opt::iterate(unsigned iter)
{
if(iter == 0)
gsl_multimin_fminimizer_set (fminimizer, &minex_func, x, ss);
gsl_multimin_fminimizer_iterate(fminimizer);
simplex_size = gsl_multimin_fminimizer_size (fminimizer);
num_to_measure = 3000000 / (std::max<double>(fabs(simplex_size), 200.0));
num_to_measure = std::max<unsigned>(num_to_measure, 1000);
printf ("(%5d) %10.3e %10.3e f() = %7.6f size = %.5f\n", (int)iter, gsl_vector_get (fminimizer->x, 0), gsl_vector_get (fminimizer->x, 1), fminimizer->fval, simplex_size);
if(simplex_size < 50)
{
//restart optimizer from last position
gsl_vector_set_all (ss, 300);
for(size_t i=0; i<nDimensions; i++)
gsl_vector_set(x, i, act->x[i]);
gsl_multimin_fminimizer_set (fminimizer, &minex_func, x, ss);
}
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
145
]
]
]
|
71b7fe9973a28f9ff259c05f093bd81455029846 | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASFantasy/ASFIsOrb/Source/ASFantasyFreeAgentQueryRqst.h | 6fc69a8d59f65086505aa621133fc1ded1c057d3 | []
| no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,294 | h | /* ASFantasyFreeAgentQueryRqst.h */
/******************************************************************************/
/******************************************************************************/
#ifndef ASFantasyFreeAgentQueryRqstH
#define ASFantasyFreeAgentQueryRqstH
#include "Requestable.h"
#include "ASFantasyType.h"
#include "ASFantasyMiscRqst.h"
//using namespace tag;
namespace asfantasy
{
/******************************************************************************/
class FreeAgentQueryRqst : public TRequestable
{
private:
TEncodedParticID fEncodedParticID;
public:
virtual void readFromFiler(TDataFiler& filer);
virtual void writeToFiler(TDataFiler& filer);
virtual TStreamable* fulfillRequest();
protected:
void getClaimReleasePlayers(TTeamPtr teamPtr,
PlayerInfoPtr& claimPlayerInfoPtr,TPlayerID& releasePlayerID);
void fillRosterPlayerVector(TTeamPtr teamPtr,
PlayerInfoVector& rosterPlayerVector);
};
/******************************************************************************/
}; //namespace asfantasy
#endif //ASFantasyFreeAgentQueryRqstH
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
a8b559129a03812c6660c5ce241dd2a6d289edd8 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /MyGUIEngine/include/MyGUI_FooBarFactory.h | df33498641215239c9655bde187967ab30ef16a0 | []
| no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | h | /*!
@file
@author Denis Koronchik
@date 3/2008
@module
*/
#ifndef __MYGUI_FOOBAR_FACTORY_H__
#define __MYGUI_FOOBAR_FACTORY_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_WidgetFactoryInterface.h"
#include "MyGUI_WidgetDefines.h"
namespace MyGUI
{
namespace factory
{
class _MyGUIExport FooBarFactory : public WidgetFactoryInterface
{
public:
FooBarFactory();
~FooBarFactory();
const Ogre::String& getType();
WidgetPtr createWidget(const Ogre::String& _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, const Ogre::String& _name);
/*void Window_Snap(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
void Window_AutoAlpha(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
void Window_MinMax(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);*/
};
} // namespace factory
} // namespace MyGUI
#endif // __MYGUI_FOOBAR_FACTORY_H__ | [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
e80e876e3893d57548fca84d4cce1c781f1aad90 | ae028b72ebee6160043284f61aa0414c23cbfd0a | /Examples/Compile/CPP/ChainResolveStrategy/Lib0/Src/NameHolder0.cpp | 12230eb13d3d0c6d5b47384eba2dd5ad1a56ac84 | []
| no_license | XueHL/wudoo | c7aa60a93e1eabd2dc97987f5866582a2108bce2 | e46761a02364bf453542b4f2cb919fb310d6ac02 | refs/heads/master | 2021-01-10T14:35:48.452210 | 2009-12-31T21:00:00 | 2009-12-31T21:00:00 | 50,088,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | #include "NameHolder0.h"
char * NameHolder0::GetName()
{
return "I am lib-0";
}
| [
"rchbiu@localhost"
]
| [
[
[
1,
6
]
]
]
|
0fbf3c81618647eb48d100fe6ac22a7b72a1f14c | 102b11022aa5e7b2be4736b9d1be1162e7bf418f | /project_1/radio_control/radio.cpp | 4ad0f6fbdc72723767d5ff03f5cfecac71c89e09 | []
| no_license | daudet/seng466-2011-hovercraft | 52df9639a62c4a67c9129001fe959b11f36ebd09 | 46da8d0669de9dae71aa890f9349787a8756c3ad | refs/heads/master | 2021-03-12T20:42:45.030618 | 2011-04-19T05:14:55 | 2011-04-19T05:14:55 | 32,120,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,925 | cpp | /*
* radio.c
*
* Created on: 24-Jan-2009
* Author: Neil MacMillan
*/
#include "radio.h"
#include "../arduino/WProgram.h"
// non-public constants and macros
#define CHANNEL 112
#define ADDRESS_LENGTH 5
// Pin definitions for chip select and chip enable on the radio module
#define CE_PIN 8
#define CSN_PIN 9
// Definitions for selecting and enabling the radio
#define CSN_HIGH() digitalWrite(CSN_PIN, HIGH);
#define CSN_LOW() digitalWrite(CSN_PIN, LOW);
#define CE_HIGH() digitalWrite(CE_PIN, HIGH);
#define CE_LOW() digitalWrite(CE_PIN, LOW);
// Flag which denotes that the radio is currently transmitting
static volatile uint8_t transmit_lock;
// tracks the payload widths of the Rx pipes
static volatile uint8_t rx_pipe_widths[6] = {32, 32, 0, 0, 0, 0};
// holds the transmit address (Rx pipe 0 is set to this address when transmitting with auto-ack enabled).
static volatile uint8_t tx_address[5] = { 0xe7, 0xe7, 0xe7, 0xe7, 0xe7 };
// holds the receiver address for Rx pipe 0 (the address is overwritten when transmitting with auto-ack enabled).
static volatile uint8_t rx_pipe0_address[5] = { 0xe7, 0xe7, 0xe7, 0xe7, 0xe7 };
// the driver keeps track of the success status for the last 16 transmissions
static volatile uint16_t tx_history = 0xFF;
static volatile RADIO_TX_STATUS tx_last_status = RADIO_TX_SUCCESS;
void int0handler();
extern void radio_rxhandler(uint8_t pipenumber);
/**
* Retrieve the status register.
*/
static uint8_t get_status()
{
uint8_t status = 0;
CSN_LOW();
status = SPI_Write_Byte(NOP);
CSN_HIGH();
return status;
}
/**
* Set a register in the radio
* \param reg The register value defined in nRF24L01.h (e.g. CONFIG, EN_AA, &c.).
* \param value The value to write to the given register (the whole register is overwritten).
* \return The status register.
*/
static uint8_t set_register(radio_register_t reg, uint8_t* value, uint8_t len)
{
uint8_t status;
CSN_LOW();
status = SPI_Write_Byte(W_REGISTER | (REGISTER_MASK & reg));
SPI_Write_Block(value, len);
CSN_HIGH();
return status;
}
/**
* Retrieve a register value from the radio.
* \param reg The register value defined in nRF24L01.h (e.g. CONFIG, EN_AA, &c.).
* \param buffer A contiguous memory block into which the register contents will be copied. If the buffer is too long for the
* register contents, then the remaining bytes will be overwritten with 0xFF.
* \param len The length of the buffer.
*/
static uint8_t get_register(radio_register_t reg, uint8_t* buffer, uint8_t len)
{
uint8_t status, i;
for (i = 0; i < len; i++)
{
// If the buffer is too long for the register results, then the radio will interpret the extra bytes as instructions.
// To remove the risk, we set the buffer elements to NOP instructions.
buffer[i] = 0xFF;
}
CSN_LOW();
status = SPI_Write_Byte(R_REGISTER | (REGISTER_MASK & reg));
SPI_ReadWrite_Block(NULL, buffer, len);
CSN_HIGH();
return status;
}
/**
* Send an instruction to the nRF24L01.
* \param instruction The instruction to send (see the bottom of nRF24L01.h)
* \param data An array of argument data to the instruction. If len is 0, then this may be NULL.
* \param buffer An array for the instruction's return data. This can be NULL if the instruction has no output.
* \param len The length of the data and buffer arrays.
*/
static void send_instruction(uint8_t instruction, uint8_t* data, uint8_t* buffer, uint8_t len)
{
CSN_LOW();
// send the instruction
SPI_Write_Byte(instruction);
// pass in args
if (len > 0)
{
if (buffer == NULL) //
SPI_Write_Block(data, len);
else
SPI_ReadWrite_Block(data, buffer, len);
}
// resynch SPI
CSN_HIGH();
}
/**
* Switch the radio to receive mode. If the radio is already in receive mode, this does nothing.
*/
static void set_rx_mode()
{
uint8_t config;
get_register(CONFIG, &config, 1);
if ((config & _BV(PRIM_RX)) == 0)
{
config |= _BV(PRIM_RX);
set_register(CONFIG, &config, 1);
// the radio takes 130 us to power up the receiver.
delayMicroseconds(65);
delayMicroseconds(65);
}
}
/**
* Switch the radio to transmit mode. If the radio is already in transmit mode, this does nothing.
*/
static void set_tx_mode()
{
uint8_t config;
get_register(CONFIG, &config, 1);
if ((config & _BV(PRIM_RX)) != 0)
{
config &= ~_BV(PRIM_RX);
set_register(CONFIG, &config, 1);
// The radio takes 130 us to power up the transmitter
// You can delete this if you're sending large packets (I'm thinking > 25 bytes, but I'm not sure) because it
// sending the bytes over SPI can take this long.
delayMicroseconds(65);
delayMicroseconds(65);
}
}
/**
* Reset the pipe 0 address if pipe 0 is enabled. This is necessary when the radio is using Enhanced Shockburst, because
* the pipe 0 address is set to the transmit address while the radio is transmitting (this is how the radio receives
* auto-ack packets).
*/
static void reset_pipe0_address()
{
if (rx_pipe_widths[RADIO_PIPE_0] != 0)
{
// reset the pipe 0 address if pipe 0 is enabled.
set_register(RX_ADDR_P0, (uint8_t*)rx_pipe0_address, ADDRESS_LENGTH);
}
}
/**
* Configure radio defaults and turn on the radio in receive mode.
* This configures the radio to its max-power, max-packet-header-length settings. If you want to reduce power consumption
* or increase on-air payload bandwidth, you'll have to change the config.
*/
static void configure_registers()
{
uint8_t value;
SPI_Init();
// set address width to 5 bytes.
value = ADDRESS_LENGTH - 2; // 0b11 for 5 bytes, 0b10 for 4 bytes, 0b01 for 3 bytes
set_register(SETUP_AW, &value, 1);
// set Enhanced Shockburst retry to every 586 us, up to 5 times. If packet collisions are a problem even with AA enabled,
// then consider changing the retry delay to be different on the different stations so that they do not keep colliding on each retry.
value = 0x15;
//value = 0x10;
set_register(SETUP_RETR, &value, 1);
// Set to use 2.4 GHz channel 110.
value = CHANNEL;
set_register(RF_CH, &value, 1);
// Set radio to 2 Mbps and high power. Leave LNA_HCURR at its default.
value = _BV(RF_DR) | _BV(LNA_HCURR);
set_register(RF_SETUP, &value, 1);
// Enable 2-byte CRC and power up in receive mode.
value = _BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP) | _BV(PRIM_RX);
set_register(CONFIG, &value, 1);
// clear the interrupt flags in case the radio's still asserting an old unhandled interrupt
value = _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT);
set_register(STATUS, &value, 1);
// flush the FIFOs in case there are old data in them.
send_instruction(FLUSH_TX, NULL, NULL, 0);
send_instruction(FLUSH_RX, NULL, NULL, 0);
}
void Radio_Init()
{
transmit_lock = 0;
// disable radio during config
CE_LOW();
// set as output AT90 pins connected to the radio's slave select and chip enable pins.
pinMode(CE_PIN, OUTPUT);
pinMode(CSN_PIN, OUTPUT);
// Enable radio interrupt. This interrupt is triggered when data are received and when a transmission completes.
attachInterrupt(0, int0handler, LOW);
// A 10.3 ms delay is required between power off and power on states (controlled by 3.3 V supply).
delay(11);
// Configure the radio registers that are not application-dependent.
configure_registers();
// A 1.5 ms delay is required between power down and power up states (controlled by PWR_UP bit in CONFIG)
delay(2);
// enable radio as a receiver
CE_HIGH();
}
// default address for pipe 0 is 0xe7e7e7e7e7
// default address for pipe 1 is 0xc2c2c2c2c2
// default address for pipe 2 is 0xc2c2c2c2c3 (disabled)
// default address for pipe 3 is 0xc2c2c2c2c4 (disabled)
// default address for pipe 4 is 0xc2c2c2c2c5 (disabled)
// default address for pipe 5 is 0xc2c2c2c2c6 (disabled)
void Radio_Configure_Rx(RADIO_PIPE pipe, uint8_t* address, ON_OFF enable)
{
uint8_t value;
uint8_t use_aa = 1;
uint8_t payload_width = 32;
if (payload_width < 1 || payload_width > 32 || pipe < RADIO_PIPE_0 || pipe > RADIO_PIPE_5) return;
// store the pipe 0 address so that it can be overwritten when transmitting with auto-ack enabled.
if (pipe == RADIO_PIPE_0)
{
rx_pipe0_address[0] = address[0];
rx_pipe0_address[1] = address[1];
rx_pipe0_address[2] = address[2];
rx_pipe0_address[3] = address[3];
rx_pipe0_address[4] = address[4];
}
// Set the address. We set this stuff even if the pipe is being disabled, because for example the transmitter
// needs pipe 0 to have the same address as the Tx address for auto-ack to work, even if pipe 0 is disabled.
set_register(RX_ADDR_P0 + pipe, address, pipe > RADIO_PIPE_1 ? 1 : ADDRESS_LENGTH);
// Set auto-ack.
get_register(EN_AA, &value, 1);
if (use_aa)
value |= _BV(pipe);
else
value &= ~_BV(pipe);
set_register(EN_AA, &value, 1);
// Set the pipe's payload width. If the pipe is being disabled, then the payload width is set to 0.
value = enable ? payload_width : 0;
set_register(RX_PW_P0 + pipe, &value, 1);
rx_pipe_widths[pipe] = value;
// Enable or disable the pipe.
get_register(EN_RXADDR, &value, 1);
if (enable)
value |= _BV(pipe);
else
value &= ~_BV(pipe);
set_register(EN_RXADDR, &value, 1);
}
// default transmitter address is 0xe7e7e7e7e7.
void Radio_Set_Tx_Addr(uint8_t* address)
{
tx_address[0] = address[0];
tx_address[1] = address[1];
tx_address[2] = address[2];
tx_address[3] = address[3];
tx_address[4] = address[4];
set_register(TX_ADDR, address, ADDRESS_LENGTH);
}
void Radio_Configure(RADIO_DATA_RATE dr, RADIO_TX_POWER power)
{
uint8_t value;
if (power < RADIO_LOWEST_POWER || power > RADIO_HIGHEST_POWER || dr < RADIO_1MBPS || dr > RADIO_2MBPS) return;
// set the address
//Radio_Set_Tx_Addr(address);
// set the data rate and power bits in the RF_SETUP register
get_register(RF_SETUP, &value, 1);
value |= 3 << RF_PWR; // set the power bits so that the & will mask the power value in properly.
value &= power << RF_PWR; // mask the power value into the RF status byte.
if (dr)
value |= _BV(RF_DR);
else
value &= ~_BV(RF_DR);
set_register(RF_SETUP, &value, 1);
}
uint8_t Radio_Transmit(radiopacket_t* payload, RADIO_TX_WAIT wait)
{
//if (block && transmit_lock) while (transmit_lock);
//if (!block && transmit_lock) return 0;
uint8_t len = 32;
// indicate that the driver is transmitting.
transmit_lock = 1;
// disable the radio while writing to the Tx FIFO.
CE_LOW();
set_tx_mode();
// for auto-ack to work, the pipe0 address must be set to the Tx address while the radio is transmitting.
// The register will be set back to the original pipe 0 address when the TX_DS or MAX_RT interrupt is asserted.
set_register(RX_ADDR_P0, (uint8_t*)tx_address, ADDRESS_LENGTH);
// transfer the packet to the radio's Tx FIFO for transmission
send_instruction(W_TX_PAYLOAD, (uint8_t*)payload, NULL, len);
// start the transmission.
CE_HIGH();
if (wait == RADIO_WAIT_FOR_TX)
{
while (transmit_lock);
return tx_last_status;
}
return RADIO_TX_SUCCESS;
}
RADIO_RX_STATUS Radio_Receive(radiopacket_t* buffer)
{
uint8_t len = 32;
uint8_t status;
uint8_t pipe_number;
uint8_t doMove = 1;
RADIO_RX_STATUS result;
transmit_lock = 0;
CE_LOW();
status = get_status();
pipe_number = (status & 0xE) >> 1;
if (pipe_number == RADIO_PIPE_EMPTY)
{
result = RADIO_RX_FIFO_EMPTY;
doMove = 0;
}
if (rx_pipe_widths[pipe_number] > len)
{
// the buffer isn't big enough, so don't copy the data.
result = RADIO_RX_INVALID_ARGS;
doMove = 0;
}
if (doMove)
{
// Move the data payload into the local
send_instruction(R_RX_PAYLOAD, (uint8_t*)buffer, (uint8_t*)buffer, rx_pipe_widths[pipe_number]);
status = get_status();
pipe_number = (status & 0xE) >> 1;
if (pipe_number != RADIO_PIPE_EMPTY)
result = RADIO_RX_MORE_PACKETS;
else
result = RADIO_RX_SUCCESS;
}
CE_HIGH();
transmit_lock = 0;
//release_radio();
return result;
}
// This is only accurate if all the failed packets were sent using auto-ack.
uint8_t Radio_Drop_Rate()
{
uint16_t wh = tx_history;
uint8_t weight = 0;
while (wh != 0)
{
if ((wh & 1) != 0) weight++;
wh >>= 1;
}
wh = (16 - weight) * 100;
wh /= 16;
return wh;
}
void Radio_Flush()
{
send_instruction(FLUSH_TX, NULL, NULL, 0);
send_instruction(FLUSH_RX, NULL, NULL, 0);
}
// Interrupt handler
void int0handler()
{
uint8_t status;
uint8_t pipe_number;
CE_LOW();
status = get_status();
if (status & _BV(RX_DR))
{
pipe_number = (status & 0xE) >> 1;
radio_rxhandler(pipe_number);
}
// We can get the TX_DS or the MAX_RT interrupt, but not both.
if (status & _BV(TX_DS))
{
// if there's nothing left to transmit, switch back to receive mode.
transmit_lock = 0;
reset_pipe0_address();
set_rx_mode();
// indicate in the history that a packet was transmitted successfully by appending a 1.
tx_history <<= 1;
tx_history |= 1;
tx_last_status = RADIO_TX_SUCCESS;
}
else if (status & _BV(MAX_RT))
{
send_instruction(FLUSH_TX, NULL, NULL, 0);
transmit_lock = 0;
reset_pipe0_address();
set_rx_mode();
// indicate in the history that a packet was dropped by appending a 0.
tx_history <<= 1;
tx_last_status = RADIO_TX_MAX_RT;
}
// clear the interrupt flags.
status = _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT);
set_register(STATUS, &status, 1);
CE_HIGH();
}
| [
"david@b282a14c-f844-f624-09bc-e1946d22bf1e"
]
| [
[
[
1,
481
]
]
]
|
f851ca76f4faf5c43d87c014b3108dcfae759fc0 | 42a799a12ffd61672ac432036b6fc8a8f3b36891 | /cpp/IGC_Tron/IGC_Tron/OGLRenderer.h | 7e4ff239215bc9bff1989fc9ee074a1859d43767 | []
| no_license | timotheehub/igctron | 34c8aa111dbcc914183d5f6f405e7a07b819e12e | e608de209c5f5bd0d315a5f081bf0d1bb67fe097 | refs/heads/master | 2020-02-26T16:18:33.624955 | 2010-04-08T16:09:10 | 2010-04-08T16:09:10 | 71,101,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,884 | h | /**************************************************************************/
/* This file is part of IGC Tron */
/* (c) IGC Software 2009 - 2010 */
/* Author : Pierre-Yves GATOUILLAT */
/**************************************************************************/
/* This program is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/**************************************************************************/
#ifndef _OGLRENDERER
#define _OGLRENDERER
/***********************************************************************************/
/** INCLUSIONS **/
/***********************************************************************************/
#include "Common.h"
#include "IRenderer.h"
#ifdef _WIN32
#include <glew.h>
#else
#include <GL/glew.h>
#endif
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#ifndef _WIN32
#include <GL/glx.h>
#include <X11/extensions/xf86vmode.h>
#include <X11/keysym.h>
#endif
/***********************************************************************************/
namespace IGC
{
class Engine;
class OGLRenderer : public IRenderer
{
/***********************************************************************************/
/** CLASSES AMIES **/
/***********************************************************************************/
friend class OGLCamera;
friend class OGLFont;
friend class OGLMesh;
friend class OGLModel;
/***********************************************************************************/
/** ATTRIBUTS **/
/***********************************************************************************/
private:
#ifdef _WIN32
HDC hDC;
HGLRC hRC;
#else
GLXContext ctx;
#endif
GLuint glRenderTexture;
void* glHostTextureData;
GLuint glFontList;
/***********************************************************************************/
/** CONSTRUCTEURS / DESTRUCTEUR **/
/***********************************************************************************/
public:
/*
Instancie la classe et alloue la m�moire vid�o pour une surface de rendu dont la taille
correspond � celle de la fen�tre associ�e � _engine.
*/
OGLRenderer( Engine* _engine );
/*
Lib�re la m�moire vid�o r�serv�e pour une surface de rendu.
*/
virtual ~OGLRenderer();
/***********************************************************************************/
/** ACCESSEURS **/
/***********************************************************************************/
private:
/*
Sp�cifie une police pour le prochain rendu de texte.
*/
void setFont( GLuint _glFontList );
/***********************************************************************************/
/** METHODES PUBLIQUES **/
/***********************************************************************************/
public:
/*
Initialise OpenGL et lui associe la surface de rendu.
*/
virtual void initialize();
/*
Lib�re toutes les ressources relatives � OpenGL.
*/
virtual void finalize();
/*
Met � jour l'affichage en copiant le contenu du back buffer vers le frame buffer.
*/
virtual void update();
/*
Active ou non la transparence pour le prochain rendu.
*/
virtual void setTransparency( bool _value );
/*
Remplit le back buffer de la couleur sp�cifi�e et le depth buffer de la profondeur sp�cifi�e.
*/
virtual void clear( float _r = 0.0f, float _g = 0.0f, float _b = 0.0f, float _depth = 1.0f );
/*
Affiche du texte � la position absolue sp�cifi�e avec la couleur sp�cifi�e en fonction de la police
qui aura pr�c�demment �t� d�finie.
*/
virtual void drawText( const char* _text, int _x, int _y, float _r, float _g, float _b, float _a );
/*
Affiche une image � la position absolue sp�cifi�e avec la couleur sp�cifi�e en fonction de la texture
qui aura pr�c�demment �t� d�finie.
*/
virtual void drawImage( int _x0, int _y0, int _x1, int _y1,
float _px = 0.0f, float _py = 0.0f, float _sx = 1.0f, float _sy = 1.0f,
float _r = 1.0f, float _g = 1.0f, float _b = 1.0f, float _a = 1.0f );
/*
Redimensionne la scène.
*/
virtual void resizeScene ( int newWidth, int newHeight );
};
}
/***********************************************************************************/
#endif
| [
"fenrhil@de5929ad-f5d8-47c6-8969-ac6c484ef978",
"raoul12@de5929ad-f5d8-47c6-8969-ac6c484ef978"
]
| [
[
[
1,
131
],
[
137,
146
],
[
148,
149
],
[
154,
157
],
[
159,
164
]
],
[
[
132,
136
],
[
147,
147
],
[
150,
153
],
[
158,
158
]
]
]
|
e702c5ddba3cda23e5a0d4374b3f092459bc47a1 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/coreplugin/versiondialog.cpp | 20e317f4c9bc1172744cb0dc2e4ac5611829f476 | []
| no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,192 | cpp | /**
******************************************************************************
*
* @file versiondialog.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation ([email protected]) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "versiondialog.h"
#include "coreconstants.h"
#include "icore.h"
#include <utils/qtcassert.h>
#include <QtCore/QDate>
#include <QtCore/QFile>
#include <QtCore/QSysInfo>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTextBrowser>
using namespace Core;
using namespace Core::Internal;
using namespace Core::Constants;
VersionDialog::VersionDialog(QWidget *parent)
: QDialog(parent)
{
// We need to set the window icon explicitly here since for some reason the
// application icon isn't used when the size of the dialog is fixed (at least not on X11/GNOME)
setWindowIcon(QIcon(":/core/images/openpilot_logo_32.png"));
setWindowTitle(tr("About OpenPilot GCS"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
QGridLayout *layout = new QGridLayout(this);
layout->setSizeConstraint(QLayout::SetFixedSize);
QString version = QLatin1String(GCS_VERSION_LONG);
version += QDate(2007, 25, 10).toString(Qt::SystemLocaleDate);
QString ideRev;
#ifdef GCS_REVISION
//: This gets conditionally inserted as argument %8 into the description string.
ideRev = tr("From revision %1<br/>").arg(QString::fromLatin1(GCS_REVISION_STR).left(10));
#endif
const QString description = tr(
"<h3>OpenPilot GCS %1</h3>"
"Based on Qt %2 (%3 bit)<br/>"
"<br/>"
"Built on %4 at %5<br />"
"<br/>"
"%8"
"<br/>"
"Copyright 2008-%6 %7. All rights reserved.<br/>"
"<br/>"
"The program is provided AS IS with NO WARRANTY OF ANY KIND, "
"INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A "
"PARTICULAR PURPOSE.<br/>")
.arg(version, QLatin1String(QT_VERSION_STR), QString::number(QSysInfo::WordSize),
QLatin1String(__DATE__), QLatin1String(__TIME__), QLatin1String(GCS_YEAR),
(QLatin1String(GCS_AUTHOR)), ideRev);
QLabel *copyRightLabel = new QLabel(description);
copyRightLabel->setWordWrap(true);
copyRightLabel->setOpenExternalLinks(true);
copyRightLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
QPushButton *closeButton = buttonBox->button(QDialogButtonBox::Close);
QTC_ASSERT(closeButton, /**/);
buttonBox->addButton(closeButton, QDialogButtonBox::ButtonRole(QDialogButtonBox::RejectRole | QDialogButtonBox::AcceptRole));
connect(buttonBox , SIGNAL(rejected()), this, SLOT(reject()));
QLabel *logoLabel = new QLabel;
logoLabel->setPixmap(QPixmap(QLatin1String(":/core/images/openpilot_logo_128.png")));
layout->addWidget(logoLabel , 0, 0, 1, 1);
layout->addWidget(copyRightLabel, 0, 1, 4, 4);
layout->addWidget(buttonBox, 4, 0, 1, 5);
}
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
]
| [
[
[
1,
104
]
]
]
|
0341830312d51be2fed2709023596b3652c1e073 | b8c3d2d67e983bd996b76825f174bae1ba5741f2 | /RTMP/utils/gil_2/boost/gil/extension/toolbox/rgb_algorithms.hpp | 8753ca369167bb8e949320880bf3159960ce7de5 | []
| no_license | wangscript007/rtmp-cpp | 02172f7a209790afec4c00b8855d7a66b7834f23 | 3ec35590675560ac4fa9557ca7a5917c617d9999 | refs/heads/master | 2021-05-30T04:43:19.321113 | 2008-12-24T20:16:15 | 2008-12-24T20:16:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,004 | hpp | #ifndef RGB_ALGORITHMS_HPP
#define RGB_ALGORITHMS_HPP
#include <boost/gil/gil_all.hpp>
namespace boost { namespace gil {
namespace toolbox {
struct calc_negative
{
template < typename DST_CHANNEL
, typename SRC_CHANNEL
> void operator()( DST_CHANNEL& dst
, SRC_CHANNEL& src ) const
{
SRC_CHANNEL max = channel_traits< SRC_CHANNEL >::max_value();
dst = max - src;
}
template < typename CHANNEL
> void operator()( CHANNEL& c ) const
{
CHANNEL max = channel_traits< CHANNEL >::max_value();
c = max - c;
}
};
template< typename RGB_VIEW >
void negative( const RGB_VIEW& view )
{
typedef typename channel_type< RGB_VIEW >::type channel_t;
channel_t max = channel_traits<channel_t>::max_value();
for( int y=0; y < view.height(); ++y )
{
typename RGB_VIEW::x_iterator it = view.row_begin( y );
for( int x = 0; x < view.width(); ++x )
{
static_for_each( it[x], calc_negative() );
}
}
}
template< typename RGB_VIEW >
void negative( const RGB_VIEW& src
, const RGB_VIEW& dst )
{
// make sure src and dst have same dimensions.
// for rgba do it only for rgb channels
typedef typename channel_type< RGB_VIEW >::type channel_t;
channel_t max = channel_traits<channel_t>::max_value();
for( int y=0; y < src.height(); ++y )
{
typename RGB_VIEW::x_iterator src_it = src.row_begin( y );
typename RGB_VIEW::x_iterator dst_it = dst.row_begin( y );
for( int x = 0; x < src.width(); ++x )
{
static_for_each( dst_it[x], src_it[x], calc_negative() );
}
}
}
struct calc_brightness
{
float _factor;
template < typename DST_CHANNEL
, typename SRC_CHANNEL
> void operator()( DST_CHANNEL& dst
, const SRC_CHANNEL& src ) const
{
float d = static_cast<float>( src ) * _factor;
if( d > channel_traits< DST_CHANNEL >::max_value() )
{
dst = channel_traits< DST_CHANNEL >::max_value();
}
else
{
dst = static_cast< DST_CHANNEL >( d );
}
}
};
template< typename RGB_VIEW >
void brightness( const RGB_VIEW& src
, const RGB_VIEW& dst
, float factor )
{
calc_brightness calc;
calc._factor = factor;
for( int y=0; y < src.height(); ++y )
{
typename RGB_VIEW::x_iterator src_it = src.row_begin( y );
typename RGB_VIEW::x_iterator dst_it = dst.row_begin( y );
for( int x = 0; x < src.width(); ++x )
{
static_for_each( dst_it[x], src_it[x], calc );
}
}
}
template< typename VALUE >
struct calc_brightness_
{
VALUE _number;
template < typename DST_CHANNEL
, typename SRC_CHANNEL
> void operator()( DST_CHANNEL& dst
, const SRC_CHANNEL& src ) const
{
VALUE d = static_cast< VALUE >( src ) + _number;
if( d > channel_traits< DST_CHANNEL >::max_value() )
{
dst = channel_traits< DST_CHANNEL >::max_value();
}
else
{
dst = d;
}
}
};
template< typename RGB_VIEW
, typename VALUE >
void brightness_( const RGB_VIEW& src
, const RGB_VIEW& dst
, VALUE number )
{
calc_brightness_<VALUE> calc;
calc._number = number;
for( int y=0; y < src.height(); ++y )
{
typename RGB_VIEW::x_iterator src_it = src.row_begin( y );
typename RGB_VIEW::x_iterator dst_it = dst.row_begin( y );
for( int x = 0; x < src.width(); ++x )
{
static_for_each( dst_it[x], src_it[x], calc );
}
}
}
template< typename RGB_VIEW >
void remove_channel( const RGB_VIEW& src
, unsigned int c )
{
typedef typename channel_type< RGB_VIEW >::type channel_t;
channel_t min_value = channel_traits<channel_t>::min_value();
for( int y = 0; y < src.dimensions().y; ++y )
{
typename RGB_VIEW::x_iterator src_it = src.row_begin( y );
for( int x = 0; x < src.dimensions().x; ++x )
{
dynamic_at_c( src_it[x], c ) = min_value;
}
}
}
template< typename CHANNEL
, typename RGB_VIEW >
void remove_channel( const RGB_VIEW& src )
{
typedef typename channel_type< RGB_VIEW >::type channel_t;
channel_t min = channel_traits<channel_t>::min_value();
for( int y = 0; y < src.dimensions().y; ++y )
{
typename RGB_VIEW::x_iterator src_it = src.row_begin( y );
for( int x = 0; x < src.dimensions().x; ++x )
{
get_color( src_it[x], CHANNEL() ) = min;
}
}
}
template< typename RGB_VIEW >
void difference( const RGB_VIEW& src_1
, const RGB_VIEW& src_2
, const RGB_VIEW& dst )
{
if( src_1.dimensions() != src_2.dimensions() )
{
throw std::runtime_error( "Source image have different dimensions." );
}
if( src_1.dimensions() != dst.dimensions() )
{
throw std::runtime_error( "Destination image must have equal dimensions as the source images." );
}
for( int y = 0; y < src_1.dimensions().y; ++y )
{
typename RGB_VIEW::x_iterator src_1_it = src_1.row_begin( y );
typename RGB_VIEW::x_iterator src_2_it = src_2.row_begin( y );
typename RGB_VIEW::x_iterator dst_it = dst.row_begin( y );
typedef typename channel_type<RGB_VIEW>::type channel_t;
for( int x = 0; x < src_1.dimensions().x; ++x )
{
assert(false);
//TODO: what is calc_diff?
//static_for_each( src_1_it[x], src_1_it[x], dst_it[x], calc_diff() );
}
}
}
} //namespace toolbox
} //namespace gil
} //namespace boost
#endif // RGB_ALGORITHMS_HPP
| [
"fpelliccioni@71ea4c15-5055-0410-b3ce-cda77bae7b57"
]
| [
[
[
1,
232
]
]
]
|
cad3879ea882fd632d3285e6e556717364cc0a31 | 42cb8a28233be1cb744c9fd06f1d9655807b78b9 | /win32networkserver/TcpClient.h | 318fb24637d99688d6ba04a20b390b80db125634 | []
| no_license | BladeSmithJohn/win32networkserver | 3603a6bddaf6740575e32e682054d12093c63b5a | b66144d48a720da30a131eb0793e84d90cb0e6f8 | refs/heads/master | 2016-09-05T16:48:59.806469 | 2009-04-01T02:30:06 | 2009-04-01T02:30:06 | 33,292,716 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,662 | h | #ifndef _TCP_CLIENT_H_
#define _TCP_CLIENT_H_
#include "HeadFile.h"
#include "NetWork.h"
#pragma warning (disable:4251)
#ifdef WIN32
#ifdef _DLL_EXPORTS_
#define DLLENTRY __declspec(dllexport)
#include <windows.h>
#else
#define DLLENTRY __declspec(dllimport)
#endif //#ifdef _DLL_EXPORTS_
#else
#define DLLENTRY
#endif //#ifdef WIN32
#include<vector>
using namespace std;
namespace HelpMng
{
void ReleaseTcpClient();
class TCP_CLIENT_EX : public NET_CONTEXT
{
friend class TcpClient;
protected:
DWORD m_nDataLen; //TCP模式下为累计接收或发送的数据长度
TCP_CLIENT_EX()
: m_nDataLen(0)
{
}
virtual ~TCP_CLIENT_EX() {}
void* operator new(size_t nSize);
void operator delete(void* p);
enum
{
E_TCP_HEAP_SIZE = 1024 * 1024* 10,
MAX_IDL_DATA = 20000,
};
private:
static vector<TCP_CLIENT_EX* > s_IDLQue; //无效的数据队列
static CRITICAL_SECTION s_IDLQueLock; //访问s_IDLQue的互斥锁
static HANDLE s_hHeap; //NET_CONTEXT自己的堆内存
};
class DLLENTRY TCP_CLIENT_RCV_EX
{
friend class TcpClient;
public:
CHAR* m_pData; //数据缓冲区, 优化时可采用虚拟内存的方式实现
INT m_nLen; //数据缓冲区的长度
TCP_CLIENT_RCV_EX(const CHAR* pBuf, INT nLen);
~TCP_CLIENT_RCV_EX();
void* operator new(size_t nSize);
void operator delete(void* p);
enum
{
HEAP_SIZE = 1024 *1024* 50, //自定义堆的最大容量
DATA_HEAP_SIZE = 1024 *1024 * 100,
MAX_IDL_DATA = 100000,
};
private:
static vector<TCP_CLIENT_RCV_EX* > s_IDLQue; //无效的数据队列
static CRITICAL_SECTION s_IDLQueLock; //访问s_IDLQue的互斥锁
static HANDLE s_hHeap; //Rcv_DATA的自定义堆
static HANDLE s_DataHeap; //数据缓冲区的自定义堆, 最大容量为10M
};
class DLLENTRY TcpClient : public NetWork
{
friend void ReleaseTcpClient();
public:
/****************************************************
* Name : InitReource()
* Desc : 对相关全局及静态资源进行初始化
* 该方法由DllMain()方法调用, 开发者不能调用
* 该方法; 否则会造成内存泄露
****************************************************/
static void InitReource();
//* 注 : 请不要回调函数中做耗时操作, 否则会导致I/O线程阻塞
TcpClient(
LPCLOSE_ROUTINE pCloseFun //某个socket关闭的回调函数
, void *pParam //回调函数的pParam参数
, LPONCONNECT pConnFun //连接成功的回调函数
, void *pConnParam //pConnFun 的参数
);
virtual ~TcpClient();
/****************************************************
* Name : Init()
* Desc : 对网络模块进行初始化
****************************************************/
virtual BOOL Init(
const char *szIp //要启动服务的本地地址, NULL 则采用默认地址
, int nPort //要启动服务的端口
);
/****************************************************
* Name : Close()
* Desc : 关闭网络模块
****************************************************/
virtual void Close();
/****************************************************
* Name : SendData()
* Desc : TCP模式的发送数据
****************************************************/
virtual BOOL SendData(const char * szData, int nDataLen, SOCKET hSock = INVALID_SOCKET);
/****************************************************
* Name : GetRecvData()
* Desc : 从接收队列中取出一个接收数据
****************************************************/
virtual void *GetRecvData(DWORD* const pQueLen);
/****************************************************
* Name : Connect()
* Desc : 连接到指定的服务器, 客户端网络模块需实现该函数
****************************************************/
virtual BOOL Connect(
const char *szIp
, int nPort
, const char *szData = NULL //连接成功后发送的第一份数据
, int nLen = 0 //数据的长度
);
/*************************************************
* Name : IsConnected()
* Desc : 客户端连接是否正常
***********************************************/
BOOL IsConnected()const { return m_bConnected; }
void* operator new(size_t nSize);
void operator delete(void* p);
void *operator new(size_t nSize, const char *, int)
{
return operator new(nSize);
}
void operator delete(void *p, const char *, int)
{
operator delete(p);
}
protected:
vector<TCP_CLIENT_RCV_EX* > m_RcvDataQue; //接受数据缓冲区队列
CRITICAL_SECTION m_RcvQueLock; //访问s_RcvDataQue的互斥锁
LPCLOSE_ROUTINE m_pCloseFun; //网络关闭的回调通知函数
LPVOID m_pCloseParam; //传递给m_pCloseFun的参数
LPONCONNECT m_pConnFun; //连接成功的回调函数
void *m_pConnParam;
BOOL m_bConnected; //客户端连接是否正常
/****************************************************
* Name : IOCompletionProc()
* Desc : IO完成后的回调函数
****************************************************/
virtual void IOCompletionProc(BOOL bSuccess, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) ;
/****************************************************
* Name : OnConnect()
* Desc : 连接的回调函数
****************************************************/
void OnConnect(BOOL bSuccess, DWORD dwTrans, LPOVERLAPPED lpOverlapped);
/****************************************************
* Name : OnRead()
* Desc : 读操作完成的回调函数
****************************************************/
void OnRead(BOOL bSuccess, DWORD dwTrans, LPOVERLAPPED lpOverlapped);
private:
static HANDLE s_hHeap; //用于申请对象实例的堆
static vector<TcpClient*> s_IDLQue; //空闲的TcpClient队列
static CRITICAL_SECTION s_IDLQueLock; //访问s_IDLQue数据队列互斥锁
static LPFN_CONNECTEX s_pfConnectEx; //ConnectEx函数的地址
static BOOL s_bInit; //是否已经初始化
enum
{
E_BUF_SIZE = 4096,
E_HEAP_SIZE = 800 *1024, //对象实例的容量
E_MAX_IDL_NUM = 2000, //空闲实例队列的最大长度
};
/****************************************************
* Name : ReleaseReource()
* Desc : 对相关全局和静态资源进行释放
****************************************************/
static void ReleaseReource();
};
}
#endif //#ifndef _TCP_CLIENT_H_ | [
"[email protected]@8dc1211a-1e63-11de-a958-c9a343b5b891"
]
| [
[
[
1,
211
]
]
]
|
dc8fd51ec9b7a78cef371d4a598bbf5da35d0ff0 | 102d8810abb4d1c8aecb454304ec564030bf2f64 | /TP2/Version 2/06Graficador/XMLParser.cpp | 649ae2926738ec5683eb0007b8b47ac79492753e | []
| no_license | jfacorro/tp-taller-prog-1-fiuba | 2742d775b917cc6df28188ecc1f671d812017a0a | a1c95914c3be6b1de56d828ea9ff03e982560526 | refs/heads/master | 2016-09-14T04:32:49.047792 | 2008-07-15T20:17:27 | 2008-07-15T20:17:27 | 56,912,077 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,153 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
#include "Common.h"
#include "XMLParser.h"
#include "Exception.h"
#include "Tag.h"
#include "TagProperty.h"
#ifndef XMLParser_cpp
#define XMLParser_cpp
Tag * XMLParser::ParseFile(char * filename)
{
Tag * rootTag = NULL;
FILE * file;
file = fopen(filename, "rb");
if(file != NULL)
{
long filesize = 0;
fseek(file, 0, SEEK_END);
filesize = ftell(file);
char * source = new char[filesize + 1];
//char * source = (char *)malloc(sizeof(char) * filesize);
fseek(file, 0, SEEK_SET);
fread(source, sizeof(char), filesize, file);
fclose(file);
source[filesize] = '\0';
rootTag = this->Parse(source);
free(source);
}
else
{
throw FileNotFoundException();
}
return rootTag;
}
Tag * XMLParser::Parse(char * stringXml)
{
Tag * rootTag = NULL;
this->stringXml = stringXml;
this->stringLength = strlen(stringXml) + 1;
char * tagStr = NULL;
char * textStr = NULL;
ArrayList stringsArr;
ArrayList tagsArr;
do
{
textStr = this->GetNextText();
if(textStr != NULL)
{
stringsArr.Add(textStr);
/// printf("FOUND TEXT: %s\n", textStr);
}
tagStr = this->GetNextTag();
if(tagStr != NULL)
{
stringsArr.Add(tagStr);
/// printf("FOUND TAG: %s\n", tagStr);
}
}while(this->stringIndex < this->stringLength);
rootTag = this->BuildTree(&stringsArr, NULL, NULL);
return rootTag;
}
/**************************************************************************
Método recursivo que construye el arbol XML de tags.
**************************************************************************/
Tag * XMLParser::BuildTree(ArrayList * stringsArr, Tag * parentTag, Tag * currentTag )
{
char * currentStr = NULL;
bool currentTagIsClosed = false;
if(parentTag == NULL)
{
stringsArr->MoveFirst();
}
while(!stringsArr->IsEmpty() && !currentTagIsClosed)
{
char * str = (char *)stringsArr->RemoveCurrent();
/// Comprobar si la cadena es texto o un tag.
if(str != NULL && str[0] == '<')
{
Tag * tag = new Tag(str);
/// Si es un tag auto contenido
/// no necesita del tag de cierre.
if(tag->GetIsAutoClosed())
{
if(currentTag == NULL)
{
currentTag = tag;
currentTagIsClosed = true;
}
else
{
currentTag->AddChildTag(tag);
}
}
/// Si es un tag de cierre
/// verificar que coincida con el de apertura
/// si es que ya se cargo uno.
else if(tag->GetIsClosingTag())
{
if(currentTag != NULL && strcmp(currentTag->GetName(), tag->GetName()) == 0 )
{
currentTagIsClosed = true;
}
else
{
throw NotWellFormedException(tag->GetName());
}
}
else if(currentTag == NULL)
{
currentTag = tag;
}
else
{
Tag * childTag = this->BuildTree(stringsArr, currentTag, tag);
currentTag->AddChildTag(childTag);
}
}
else if(str != NULL)
{
/// Si hay un tag agregarle
/// el texto.
if(currentTag != NULL)
{
currentTag->SetInnerText(str);
}
else if(parentTag != NULL)
{
parentTag->SetInnerText(str);
}
/// Si no hay un tag padre entonces hay texto
/// afuera del root element, generar una excepcion.
else
{
throw NotWellFormedException("There's text outside the root element.");
}
}
}
if(currentTagIsClosed)
{
if(parentTag == NULL && !stringsArr->IsEmpty())
{
throw RootElementMissingException();
}
return currentTag;
}
/// No hay tag de cierre.
else
{
throw NotWellFormedException(StringHelper::AppendString("There's a closing tag missing for ", currentTag->GetName()));
}
return NULL;
}
char * XMLParser::GetNextTag()
{
char openChar;
char closeChar;
int openPos = 0;
int closePos = 0;
char * tagStr = NULL;
/// Los caracteres '\n' son contados de forma
/// distinta, cada vez que se extrae uno, el puntero get
/// aumenta en dos en realidad su indice.
int numNewLineChar = 0;
do
{
openChar = this->stringXml[this->stringIndex];
this->stringIndex++;
if(openChar == '\n')
{
numNewLineChar++;
}
if(openChar == '<')
{
openPos = this->stringIndex - (1 + numNewLineChar);
}
}while(this->stringIndex < this->stringLength && openChar != '<');
numNewLineChar = 0;
do
{
closeChar = this->stringXml[this->stringIndex];
this->stringIndex++;
if(closeChar == '\n')
{
numNewLineChar++;
}
if(closeChar == '>')
{
closePos = this->stringIndex - (1 + numNewLineChar);
}
else if (closeChar == '<')
{
throw ClosingTagMissingException();
}
}while(this->stringIndex <= this->stringLength && closeChar != '>');
if(closePos != 0 && this->stringIndex <= this->stringLength)
{
this->stringIndex = openPos;
tagStr = new char[closePos - openPos + 2];
tagStr = StringHelper::Substring(this->stringXml, this->stringIndex, closePos - openPos + 1);
tagStr[closePos - openPos + 1] = '\0';
this->stringIndex = closePos + 1;
char * temp = tagStr;
tagStr = StringHelper::Trim(temp);
delete temp;
}
return tagStr;
}
char * XMLParser::GetNextText()
{
char openChar;
int beginPos = this->stringIndex;
int endPos = beginPos;
int openCharPos = 0;
char * tagStr = NULL;
int numNewLineChar = 0;
do
{
openChar = this->stringXml[this->stringIndex];
this->stringIndex++;
if(openChar == '\n')
{
numNewLineChar++;
}
if(openChar == '<')
{
openCharPos = this->stringIndex - (1 + numNewLineChar);
endPos = openCharPos;
if(beginPos != endPos)
{
endPos--;
}
}
}while(this->stringIndex < this->stringLength && openChar != '<');
if(openCharPos != beginPos && this->stringIndex <= this->stringLength)
{
tagStr = new char[endPos - beginPos + 2];
this->stringIndex = beginPos;
tagStr = StringHelper::Substring(this->stringXml, this->stringIndex, endPos - beginPos + 1);
this->stringIndex = endPos + 1;
tagStr[endPos - beginPos + 1] = '\0';
char * temp = tagStr;
tagStr = StringHelper::Trim(temp);
delete temp;
if(tagStr[0] == '\0')
{
delete tagStr;
tagStr = NULL;
}
}
else
{
this->stringIndex = beginPos;
/// fseek(file, beginPos, SEEK_SET);
}
return tagStr;
}
bool XMLParser::ValidateName(char * nameStr)
{
int length = strlen(nameStr);
/// Verificar que no tiene ninguna ".
int quoteIndex = StringHelper::FindFirstOcurrence(nameStr, length, 0, '"');
if(quoteIndex != -1)
{
return false;
}
/// Verificar que no tiene ningun &.
int ampersandIndex = StringHelper::FindFirstOcurrence(nameStr, length, 0, '&');
if(ampersandIndex != -1)
{
return false;
}
/// Verificar que el primer caracter
/// no sea un número.
int numChar = (int)nameStr[0];
if(numChar >= (int)'0' && numChar <= (int)'9')
{
return false;
}
return true;
}
#endif
| [
"juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb"
]
| [
[
[
1,
371
]
]
]
|
fcee412ea18319b7c39048f814689608767c309c | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/framework/iosdevice.h | 0d22fae7a04024432aa94fa424783890b2ed71ef | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | h | /*!
@file
@brief OS固有の処理のベース
*/
#ifndef maid2_framework_iosdevice_h
#define maid2_framework_iosdevice_h
#include"../config/define.h"
#include<boost/smart_ptr.hpp>
namespace Maid
{
class IOSDevice
{
public:
virtual ~IOSDevice(){}
//! アプリケーションの初期化
/*!
*/
virtual void Initialize()=0;
//! アプリケーションの開放
/*!
*/
virtual void Finalize()=0;
//! アプリが生きているか?
/*!
@retval true 生きている
@retval false 終了する必要がある
*/
virtual bool IsValid()=0;
//! アプリケーションを終了させる
/*!
アプリを終了させるときに呼んでください
*/
virtual void Exit()=0;
};
typedef boost::shared_ptr<IOSDevice> SPOSDEVICE;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
3c2ca10a8ca780cd55b9aa6c29270f59c03896b0 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/UserList.cpp | 3b019e8d418376e60daadcb7eb6a09af99712531 | []
| 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 | WINDOWS-1252 | C++ | false | false | 26,389 | 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.
*/
// UserList.cpp : implementation of the CUserListView class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HydraIRC.h"
// Forward declares
class IRCUser;
class IRCUserGroupList;
// order relates to USER_TYPE_* defines and NOT UG_ID_* defines.
char *g_UserGroupNames[6] =
{
"Normal",
"Voice",
"Half-Ops",
"Ops",
"Admins",
"Owner"
};
/*
void CUserListView::OnDocked(HDOCKBAR hBar,bool bHorizontal)
{
DWORD dwStyle = GetWindowLong(GWL_STYLE)&(~WS_SIZEBOX);
SetWindowLong( GWL_STYLE, dwStyle);
baseClass::OnDocked(hBar,bHorizontal);
}
void CUserListView::OnUndocked(HDOCKBAR hBar)
{
DWORD dwStyle = GetWindowLong(GWL_STYLE) | WS_SIZEBOX;
SetWindowLong( GWL_STYLE , dwStyle);
baseClass::OnUndocked(hBar);
}
*/
LRESULT CUserListView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(m_dwIcon),
IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
SetIcon(hIconSmall, FALSE);
HWND tree = m_tree.Create(m_hWnd,NULL,NULL,
TVS_HASBUTTONS |
TVS_SHOWSELALWAYS |
//TVS_LINESATROOT |
TVS_HASLINES |
//TVS_FULLROWSELECT |
TVS_DISABLEDRAGDROP | TVS_INFOTIP |
WS_CHILD | WS_VISIBLE);
m_tree.SetImageList(g_UserListImages, TVSIL_NORMAL);
m_tree.SetIndent(5);
// TODO: add the groups of users that we were from out list of groups.
if (m_pChannel) // skip addition of users if our list has not been pointed at a
// channel
{
for (int i = 0 ; i < m_pChannel->m_Users.m_UserList.GetSize() ; i ++)
{
Add(m_pChannel->m_Users.m_UserList[i]);
}
}
m_tree.SelectItem(m_tree.GetRootItem());
/*
// FIXME: tooltips show immediately, not after a short delay
int n;
CToolTipCtrl pToolTip = m_tree.GetToolTips();
if (pToolTip)
{
pToolTip.Activate(TRUE);
n = pToolTip.GetDelayTime(TTDT_INITIAL);
n = pToolTip.GetDelayTime(TTDT_AUTOPOP);
n = pToolTip.GetDelayTime(TTDT_RESHOW);
}
*/
/*
If an application processes this message, it should return zero to
continue creation of the window. If the application returns –1,
the window is destroyed and the CreateWindowEx or CreateWindow
function returns a NULL handle.
*/
return 0;
}
LRESULT CUserListView::OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED )
{
RECT rc;
GetClientRect(&rc);
::SetWindowPos(m_tree.m_hWnd, NULL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top ,SWP_NOZORDER | SWP_NOACTIVATE);
}
bHandled = FALSE;
return bHandled ? 0 : 1; // WM_SIZE - If an application processes this message, it should return zero.
}
// Find a treeview group item.
// for valid GroupID's, see USER_TYPE_* defines in Server.h
HTREEITEM CUserListView::Find(int GroupID)
{
HTREEITEM hItem;
TVITEM item;
TreeItemInfo *ptii;
if (IsWindow())
{
hItem = m_tree.GetRootItem();
if (hItem != NULL)
{
do
{
item.mask = TVIF_PARAM;
item.lParam = 0;
item.hItem = hItem; // we want more info about this tree node.
if (m_tree.GetItem(&item) && item.lParam != NULL)
{
ptii = (TreeItemInfo*)item.lParam;
if (ptii->m_Type == TII_USERGROUP && ptii->m_Num == GroupID)
return hItem;
}
hItem = m_tree.GetNextSiblingItem(hItem);
} while (hItem);
}
}
return NULL;
}
// Find a treeview user item.
// use Find(Nick,GroupType) if possible as it will be quicker on longer lists.
//HTREEITEM CUserListView::Find(char *Nick)
HTREEITEM CUserListView::Find(IRCUser *pUser)
{
HTREEITEM hItem;
HTREEITEM hChildItem;
TVITEM item;
TreeItemInfo *ptii;
if (IsWindow())
{
hItem = m_tree.GetRootItem();
do
{
item.mask = TVIF_CHILDREN;
item.cChildren = 0;
item.hItem = hItem; // we want more info about this tree node.
if (m_tree.GetItem(&item))
{
if (item.cChildren > 0)
{
hChildItem = m_tree.GetChildItem(hItem);
if (hChildItem)
{
// then search the group for a matching nick
do
{
item.mask = TVIF_PARAM;
item.lParam = 0;
item.hItem = hChildItem; // we want more info about this tree node.
if (m_tree.GetItem(&item) && item.lParam != NULL)
{
ptii = (TreeItemInfo*)item.lParam;
if (ptii->m_Type == TII_USER && (IRCUser *)ptii->m_Data == pUser) // just compare the pointers
return hChildItem;
}
hChildItem = m_tree.GetNextSiblingItem(hChildItem);
} while (hChildItem);
}
}
}
hItem = m_tree.GetNextSiblingItem(hItem);
} while (hItem);
}
return NULL;
}
// find a treeview item for a given nick/usertype
// for valid UserType's, see USER_TYPE_* defines in Server.h
// HTREEITEM CUserListView::Find(char *Nick, int UserType)
HTREEITEM CUserListView::Find(IRCUser *pUser, int UserType)
{
HTREEITEM hItem;
TVITEM item;
TreeItemInfo *ptii;
// find the group first.
hItem = Find(UserType);
if (hItem != NULL)
{
hItem = m_tree.GetChildItem(hItem);
// then search the group for a matching nick
while (hItem)
{
item.mask = TVIF_PARAM;
item.lParam = 0;
item.hItem = hItem; // we want more info about this tree node.
if (m_tree.GetItem(&item))
{
ptii = (TreeItemInfo*)item.lParam;
// if (ptii->m_Type == TII_USER && stricmp( ((IRCUser *)ptii->m_Data)->m_Nick, Nick) == 0)
if (ptii->m_Type == TII_USER && (IRCUser *)ptii->m_Data == pUser)
return hItem;
}
hItem = m_tree.GetNextSiblingItem(hItem);
}
}
return NULL;
}
void CUserListView::Select(IRCUser *pUser)
{
if (!pUser)
return;
HTREEITEM hItem;
hItem = Find(pUser,pUser->m_UserType);
if (!hItem)
hItem = Find(pUser);
if (hItem)
{
m_tree.Select(hItem, TVGN_CARET);
}
}
// you still need to delete pUser...
void CUserListView::Remove(IRCUser *pUser)
{
IRCUser *pFoundUser;
TVITEM item;
TreeItemInfo *ptii;
HTREEITEM hItem, hParent;
/*
hItem = Find(pUser->m_Nick,pUser->m_UserType);
if (!hItem)
hItem = Find(pUser->m_Nick);
*/
hItem = Find(pUser,pUser->m_UserType);
if (!hItem)
hItem = Find(pUser);
if (hItem)
{
item.mask = TVIF_PARAM;
item.lParam = 0;
item.hItem = hItem; // we want more info about this tree node.
if (m_tree.GetItem(&item))
{
ptii = (TreeItemInfo*)item.lParam;
ATLASSERT(ptii->m_Type == TII_USER);
pFoundUser = (IRCUser *)ptii->m_Data;
hParent = m_tree.GetParentItem(hItem);
IRCUserGroup *pGroup;
if (m_ShowBuddyGroups && pFoundUser->m_CustomGroupID != -1)
pGroup = m_UserGroups.FindByGroupID(UG_ID_CUSTOM + pFoundUser->m_CustomGroupID);
else
pGroup = m_UserGroups.FindByGroupID(pFoundUser->m_UserType);
ATLASSERT(pGroup); // it's an error if we can't find the group, it's in there somewhere.
// delete stuff..
m_tree.DeleteItem(hItem);
m_TIIList.Remove(ptii);
delete ptii;
pGroup->RemoveUser(pFoundUser);
item.hItem = hParent; // we want more info about this tree node.
item.mask = TVIF_PARAM | TVIF_CHILDREN;
if (m_tree.GetItem(&item))
{
if (item.cChildren == 0)
{
ptii = (TreeItemInfo*)item.lParam;
m_tree.DeleteItem(hParent);
m_TIIList.Remove(ptii);
delete ptii;
m_UserGroups.Remove(pGroup);
delete pGroup;
}
else
{
// pGroup = (IRCUserGroup *)ptii->m_Data; // it's already set...
if (BOOLPREF(PREF_bShowUserListGroupCounts))
{
int newnamelen = strlen(pGroup->m_GroupName) + 10;
char *newname = (char *)malloc(newnamelen);
_snprintf(newname,newnamelen-1,"%s (%d)",pGroup->m_GroupName,pGroup->m_UserList.GetSize());
m_tree.SetItemText(hParent,newname);
free(newname);
}
}
}
}
}
}
// hmm, make it a member? probably...
static int CALLBACK UserGroupSorter(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
// lParamSort contains a pointer to the tree window.
// CTreeViewCtrl *pTree = (CTreeViewCtrl*) lParamSort;
TreeItemInfo *pTII1 = (TreeItemInfo *)lParam1;
TreeItemInfo *pTII2 = (TreeItemInfo *)lParam2;
if (pTII1->m_Type == TII_USERGROUP && pTII2->m_Type == TII_USERGROUP)
{
if (pTII1->m_Num > pTII2->m_Num)
return -1;
else if (pTII1->m_Num < pTII2->m_Num)
return 1;
else
return 0;
}
return 0;
}
void CUserListView::Update(IRCUser *pUser)
{
Remove(pUser);
Add(pUser);
}
// Add an item to the list, creating groups for the item as required.
// returns NULL or a valid HTREEITEM.
HTREEITEM CUserListView::Add(IRCUser *pUser)
{
HTREEITEM hLastFirstVisibleItem; //heh, what a great variable name
// remember what we're looking at so that we can move back to it after the add.
hLastFirstVisibleItem = m_tree.GetFirstVisibleItem();
// add an item
HTREEITEM hItem;
TreeItemInfo *pTII;
IRCUserGroup *pGroup;
//sys_Printf(BIC_NOTICE, "Adding user %s, type: %d", pUser->m_Nick, pUser->m_UserType);
// if a custom group is specified for the user, add them to it.
if (m_ShowBuddyGroups && pUser->m_CustomGroupID != -1)
{
// Find the group's HTREEITEM (using our custom group...)
hItem = Find(UG_ID_CUSTOM + pUser->m_CustomGroupID);
}
else
{
// Find the group's HTREEITEM
hItem = Find(pUser->m_UserType);
}
if (hItem == NULL)
{
// User group not created yet, so create it.
// we make a new user group, that this class manages
// based on the information in pUser
int GroupID;
//int GroupFlags = IRCUG_DEFAULTFLAGS;
char *GroupName;
IRCUserGroup *pSearchGroup;
// Get the group name.
if (m_ShowBuddyGroups && pUser->m_CustomGroupID != -1)
{
pSearchGroup = g_pPrefs->m_CustomUserGroups.FindByGroupID(pUser->m_CustomGroupID);
if (pSearchGroup)
{
GroupName = pSearchGroup->m_GroupName;
//GroupFlags = pSearchGroup->m_Flags;
}
else
{
ATLASSERT(pSearchGroup);
GroupName = "unknown group";
}
}
else
{
switch (pUser->m_UserType)
{
case USER_TYPE_NORMAL:
case USER_TYPE_VOICE:
case USER_TYPE_HALFOP:
case USER_TYPE_OP:
case USER_TYPE_ADMIN:
case USER_TYPE_OWNER:
GroupName = g_UserGroupNames[pUser->m_UserType];
break;
}
}
// create a custom group id for ourselves.
// (USER_TYPE_* and UG_ID_* only match numerically by conincidence)
if (m_ShowBuddyGroups && pUser->m_CustomGroupID != -1)
{
GroupID = UG_ID_CUSTOM + pUser->m_CustomGroupID;
}
else
{
switch (pUser->m_UserType)
{
case USER_TYPE_NORMAL:
GroupID = UG_ID_NORMAL;
break;
case USER_TYPE_VOICE:
GroupID = UG_ID_VOICE;
break;
case USER_TYPE_HALFOP:
GroupID = UG_ID_HALFOP;
break;
case USER_TYPE_OP:
GroupID = UG_ID_OP;
break;
case USER_TYPE_ADMIN:
GroupID = UG_ID_ADMIN;
break;
case USER_TYPE_OWNER:
GroupID = UG_ID_OWNER;
break;
}
}
// Create a new user group to store a refernce to the pUser in.
pGroup = new IRCUserGroup(GroupName, GroupID);
//pGroup->m_Flags = GroupFlags;
// Add our newly created group to the class's grouplist
m_UserGroups.Add(pGroup);
pTII = new TreeItemInfo(TII_USERGROUP, (void *)pGroup, GroupID);
m_TIIList.Add(pTII);
hItem = m_tree.InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM,
GroupName,
0,0, // image & selected image numbers
0,0, // unused
(LPARAM)pTII,
TVI_ROOT,TVI_LAST);
// Sort the group list.
TVSORTCB tvs;
tvs.hParent = TVI_ROOT;
tvs.lpfnCompare = UserGroupSorter;
tvs.lParam = (LPARAM)&m_tree;
m_tree.SortChildrenCB(&tvs);
}
if (hItem) // got somewhere to put out new node ?
{
TVITEM item;
item.mask = TVIF_PARAM | TVIF_STATE | TVIF_CHILDREN;
item.hItem = hItem;
item.lParam = 0;
if (m_tree.GetItem(&item) && item.lParam != NULL)
{
pTII = (TreeItemInfo *)item.lParam;
// Add the user to out own internal list of users.
pGroup = (IRCUserGroup *)pTII->m_Data;
pGroup->AddUser(pUser);
// Add the user to the tree under the group icon
pTII = new TreeItemInfo(TII_USER,(void *)pUser);
m_TIIList.Add(pTII);
long iIcon;
switch (pUser->m_UserType)
{
case USER_TYPE_NORMAL:
iIcon = 2;
break;
case USER_TYPE_VOICE:
iIcon = 3;
break;
case USER_TYPE_HALFOP:
iIcon = 4;
break;
case USER_TYPE_OP:
iIcon = 5;
break;
case USER_TYPE_ADMIN:
iIcon = 5;
break;
case USER_TYPE_OWNER:
iIcon = 5;
break;
}
/*
HTREEITEM hNewItem = m_tree.InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM,
pUser->m_Nick,
2+pUser->m_UserType,2+pUser->m_UserType, // image & selected image numbers
0,0, // unused
(LPARAM)pTII,
hItem,TVI_SORT); // insert alphabetically
*/
HTREEITEM hNewItem = m_tree.InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM,
pUser->m_Nick,
iIcon, iIcon, // image & selected image numbers
0,0, // unused
(LPARAM)pTII,
hItem,TVI_SORT); // insert alphabetically
// todo: delay the processing of group counts until after a channel
// has been joined to speed up joining large channels
if (BOOLPREF(PREF_bShowUserListGroupCounts))
{
int newnamelen = strlen(pGroup->m_GroupName) + 10;
char *newname = (char *)malloc(newnamelen);
_snprintf(newname,newnamelen-1,"%s (%d)",pGroup->m_GroupName,pGroup->m_UserList.GetSize());
m_tree.SetItemText(hItem,newname);
free(newname);
}
// Expand the parent, if we should..
// only expand if this is the first user we're adding
if (item.cChildren == 0)
{
// only expand if not already expanded
// REMOVE: this next "if" is not really needed.
if (!(item.state & TVIS_EXPANDED))
{
// if we're supposed to expand, then do so.
//if (pGroup->m_Flags & IRCUG_EXPAND || pGroup->m_Flags & IRCUG_EXPANDED)
//{
m_tree.Expand(hItem);
//}
}
}
/*
// attempt at drawing a box round the tree item.. (failed..)
RECT r;
m_tree.GetItemRect(hItem,&r,TRUE);
CPaintDC dc(m_tree.m_hWnd);
//RECT rect;
//GetClientRect(&rect);
//dc.FillRect(&r,COLOR_APPWORKSPACE);
//dc.FillRect(&r, COLOR_3DFACE);
dc.DrawEdge(&r, EDGE_RAISED, BF_LEFT | BF_RIGHT);
//::InvalidateRect(m_tree.m_hWnd,&r,FALSE);
*/
// go back to where we were before we added this user
if (m_tree.GetFirstVisibleItem() != hLastFirstVisibleItem)
{
m_tree.EnsureVisible(hLastFirstVisibleItem);
// *sigh* EnsureVisible scrolls the user left to the right a bit,
// even if it doesn't actually need to (bleh)
// so we scroll the window back again..
m_tree.SendMessage(WM_HSCROLL,SB_LEFT,(LPARAM)m_tree.m_hWnd); // todo: check lparam value
// Todo: if the user had scrolled to the right on purpose
// we would be resetting the scroll back to the left.
// so we need to get the Horizontal scroll position before
// calling EnsureVisible() and then set it back again after.
}
return hNewItem;
}
}
return NULL;
}
LRESULT CUserListView::OnTVNSelectChanged(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
{
TVITEM item;
LPNMTREEVIEW selectioninfo = (LPNMTREEVIEW)pnmh;
item.mask = TVIF_PARAM | TVIF_CHILDREN;
item.hItem = selectioninfo->itemNew.hItem;
if (m_tree.GetItem(&item))
{
// TODO: stuff
}
return 0;
}
LRESULT CUserListView::OnTVNItemExpanded(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
{
TVITEM item;
TreeItemInfo *pTII;
LPNMTREEVIEW selectioninfo = (LPNMTREEVIEW)pnmh;
//char buffer[20]; //remove
item.mask = TVIF_PARAM | TVIF_CHILDREN;
item.hItem = selectioninfo->itemNew.hItem;
if (m_tree.GetItem(&item) && item.lParam != NULL)
{
pTII = (TreeItemInfo *)item.lParam;
IRCUserGroup *pGroup = (IRCUserGroup *)pTII->m_Data;
if (item.cChildren > 0)
{
if (selectioninfo->action == TVE_EXPAND)
{
m_tree.SetItemImage(selectioninfo->itemNew.hItem,1,1);
//pGroup->m_Flags |= IRCUG_EXPANDED;
}
if (selectioninfo->action == TVE_COLLAPSE)
{
m_tree.SetItemImage(selectioninfo->itemNew.hItem,0,0);
//pGroup->m_Flags &= ~IRCUG_EXPANDED;
}
}
}
return 0;
}
LRESULT CUserListView::OnTVNGetInfoTip(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
char buffer[400];
TVITEM item;
buffer[0] = 0;
LPNMTVGETINFOTIPA lpGetInfoTip = (LPNMTVGETINFOTIP)pnmh;
if (lpGetInfoTip->hItem)
{
item.mask = TVIF_PARAM | TVIF_TEXT;
item.pszText = buffer;
item.cchTextMax = 399;
item.lParam = 0;
item.hItem = lpGetInfoTip->hItem;
if (m_tree.GetItem(&item))
{
if (item.lParam)
{
// TODO: stuff
}
else
{
strncpy(lpGetInfoTip->pszText,item.pszText,item.cchTextMax-1); // -1 really needed ?
}
}
}
return 0;
}
CUserListView::~CUserListView( void )
{
#ifdef VERBOSE_DEBUG
sys_Printf(BIC_FUNCTION,"CUserListView::~CUserListView\n");
#endif
RemoveAll();
}
void CUserListView::RemoveAll( void )
{
#ifdef VERBOSE_DEBUG
sys_Printf(BIC_FUNCTION,"CUserListView::RemoveAll\n");
#endif
// free the lists of users, but don't free the users themselves
// (so remove the users from the lists, then delete the groups and lists of groups)
m_UserGroups.RemoveAllUsers();
m_UserGroups.DeleteAll();
while (m_TIIList.GetSize() > 0)
{
delete m_TIIList[0];
m_TIIList.RemoveAt(0);
}
if (::IsWindow(m_tree.m_hWnd))
m_tree.DeleteAllItems();
}
void CUserListView::Refresh( void )
{
// export all users from all groups to a single group
IRCUserGroup *pAllUsers = m_UserGroups.ExportAll(NULL);
if (!pAllUsers)
return;
// remove all the users from all the groups, and the groups
// but don't don't delete the user instances themselves.
RemoveAll();
// then add the users back to the list, using now-current settings/prefs
while (pAllUsers->m_UserList.GetSize() > 0)
{
Add(pAllUsers->m_UserList[0]);
pAllUsers->RemoveUser(pAllUsers->m_UserList[0]);
}
delete pAllUsers;
}
void CUserListView::SetShowBuddyGroups(BOOL ShowBuddyGroups)
{
BOOL DoRefresh = m_ShowBuddyGroups != ShowBuddyGroups;
m_ShowBuddyGroups = ShowBuddyGroups;
if (DoRefresh)
Refresh();
}
void CUserListView::UpdateSettings( void )
{
if (g_pPrefs)
{
// if this instance is a docking window, get the colors from the prefs.
if (this == &g_pMainWnd->m_UserListView)
{
SetColors(g_pPrefs->m_ColorPrefs);
}
m_tree.SetFont(GetAppFont(PREF_fUserListFont));
m_tree.SetBkColor(m_BackColor);
m_tree.SetTextColor(m_TextColor);
}
m_tree.RedrawWindow();
}
LRESULT CUserListView::OnNMDblclk(int /*idCtrl*/, LPNMHDR pNMHDR, BOOL& bHandled)
{
if (!(m_pChannel && m_pChannel->m_pChildWnd && m_pChannel->m_pChildWnd->IsWindow()))
return 0;
RECT rc;
UINT Flags;
HTREEITEM hItem;
TreeItemInfo *pTII;
DWORD dwpos = GetMessagePos();
POINT pt =
{
GET_X_LPARAM(dwpos) ,
GET_Y_LPARAM(dwpos)
};
// mouse click location
m_tree.GetClientRect(&rc);
m_tree.ScreenToClient(&pt);
hItem = m_tree.HitTest(pt,&Flags);
if (hItem != NULL)
{
m_tree.SelectItem(hItem);
TVITEM item;
item.mask = TVIF_PARAM;
item.lParam = 0;
item.hItem = hItem; // we want more info about this tree node.
if (m_tree.GetItem(&item))
{
pTII = (TreeItemInfo *)item.lParam;
CHILDFRAMEPTR(m_pChannel->m_pChildWnd)->DoUserListDoubleClick(pTII);
}
}
bHandled = FALSE;
return 0;
}
LRESULT CUserListView::OnContextMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
if (!(m_pChannel && m_pChannel->m_pChildWnd && m_pChannel->m_pChildWnd->IsWindow()))
return 0;
RECT rc;
UINT Flags;
HTREEITEM hItem;
TreeItemInfo *pTII;
POINT pt =
{
GET_X_LPARAM(lParam) ,
GET_Y_LPARAM(lParam)
};
// mouse click location
m_tree.GetClientRect(&rc);
m_tree.ScreenToClient(&pt);
hItem = m_tree.HitTest(pt,&Flags);
if ((hItem != NULL) && ((Flags & TVHT_ONITEM) > 0))
{
m_tree.SelectItem(hItem);
TVITEM item;
item.mask = TVIF_PARAM;
item.lParam = 0;
item.hItem = hItem; // we want more info about this tree node.
if (m_tree.GetItem(&item))
{
pTII = (TreeItemInfo *)item.lParam;
CHILDFRAMEPTR(m_pChannel->m_pChildWnd)->DoUserListContextMenu(pTII,this);
}
}
else
{
CHILDFRAMEPTR(m_pChannel->m_pChildWnd)->DoUserListContextMenu(NULL,this);
}
bHandled = FALSE;
return 0;
}
void CUserListView::OnEvent(int EventID, void *pData)
{
switch(EventID)
{
case EV_PREFSCHANGED:
UpdateSettings();
break;
}
}
LRESULT CUserListView::OnNmCustomDraw(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
LPNMTVCUSTOMDRAW pNMH = (LPNMTVCUSTOMDRAW)pnmh;
switch(pNMH->nmcd.dwDrawStage)
{
case CDDS_PREPAINT:
return CDRF_NOTIFYITEMDRAW;
case CDDS_ITEMPREPAINT:
{
COLORREF NewBackground = -1;
//sys_Printf(BIC_INFO,"%d\n",pNMH->nmcd.uItemState);
// use a selected background color, if the item is selected
if (pNMH->nmcd.uItemState & CDIS_SELECTED)
{
NewBackground = m_SelectedBackColor;
}
if (NewBackground != -1)
pNMH->clrTextBk = NewBackground;
return NULL;// CDRF_NEWFONT
}
}
// shouldn't get here the return value is just to shut the compiler up.
#ifdef DEBUG
ATLASSERT(0);
#endif
return NULL;
}
void CUserListView::SetColors( COLORREF *pColors )
{
if (this == &g_pMainWnd->m_UserListView)
{
// extract just the colors we need from the array of colors.
m_TextColor = pColors[item_globaluserlistnormaltext - PREF_COLOR_FIRST];
m_BackColor = pColors[item_globaluserlistbackground - PREF_COLOR_FIRST];
m_SelectedBackColor = pColors[item_globaluserlistselectedbackground - PREF_COLOR_FIRST];
}
else
{
// extract just the colors we need from the array of colors.
m_TextColor = pColors[item_userlistnormaltext - PREF_COLOR_FIRST];
m_BackColor = pColors[item_userlistbackground - PREF_COLOR_FIRST];
m_SelectedBackColor = pColors[item_userlistselectedbackground - PREF_COLOR_FIRST];
}
}
LRESULT CUserListView::OnUserListContext(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
// handle window related items here, failing that, pass back to the window that owns this list of users.
switch (wID)
{
case ID_USERLIST_SHOWBUDDYGROUPS:
m_ShowBuddyGroups = !m_ShowBuddyGroups;
Refresh();
break;
default:
if (m_pChannel && m_pChannel->m_pChildWnd)
{
return CHILDFRAMEPTR(m_pChannel->m_pChildWnd)->OnUserListContext(wNotifyCode, wID, hWndCtl, bHandled);
}
}
return 0; // doesn't matter
} | [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
]
| [
[
[
1,
934
]
]
]
|
919fb7bab2d53db58e44d689bf7c9dc6190688b4 | 1493997bb11718d3c18c6632b6dd010535f742f5 | /homeworld/BigFile/File.cpp | 507fb5767dce1e2cb7f7d75c1d80128f2bf0aa2a | []
| 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 | 65,021 | cpp | /*=============================================================================
File.c: Functions for reading and saving files, including .BIG files.
Created June 1997 by Luke Moloney
Updated August 1998 by Darren Stone - added bigfile support
=============================================================================*/
//#include <limits.h>
//#include <stdarg.h>
//#include <stdlib.h>
//#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "LZSS/BitIO.h"
//#include "Debug.h"
#include "File.h"
//#include "LZSS.h"
#include "Memory.h"
#ifdef _WIN32
// #define WIN32_LEAN_AND_MEAN
// #include <windows.h>
#include <direct.h>
#else
// #include <dirent.h>
// #include <ctype.h>
#endif
#if defined _MSC_VER
#define stat _stat
#define S_ISDIR(mode) ((mode) & _S_IFDIR)
#endif
#include <assert.h>
#include <stdexcept>
#ifdef HW_BUILD_FOR_DEBUGGING
#define FILE_ERROR_CHECKING 1 // control error checking
#define FILE_OPEN_LOGGING 1 // display file names as they are opened
#define FILE_SEEK_WARNING 1 // display warnings as seeks are required
#define FILE_TEST 0 // test the file module
#define FILE_VERBOSE_LEVEL 1 // control level of verbose info
#else
#define FILE_ERROR_CHECKING 0
#define FILE_OPEN_LOGGING 0
#define FILE_SEEK_WARNING 0
#define FILE_TEST 0
#define FILE_VERBOSE_LEVEL 0
#endif
struct stat fileStat;
// bigfile externs -- options and structures from bigfile.c
extern bool IgnoreBigfiles;
extern bool CompareBigfiles;
extern bool LogFileLoads;
/*=============================================================================
Data:
=============================================================================*/
// filehandles are an index into this array
// (NOTE: the first entry is wasted -- since a filehandle of 0
// usually indicates an error, we don't want to use it. And having
// to add one to the index all the time seems like an invitation
// for bugs.)
fileOpenInfo filesOpen[MAX_FILES_OPEN+1];
// where all the data files are kept (*.big, *.vce, *.wxe)
char fileHomeworldDataPath [PATH_MAX] = "";
// local directory mimicking the .big archive hierarchy and overrides
// the contents of those archives. (Mainly used for testing.)
char fileOverrideBigPath [PATH_MAX] = "";
// the user's personal configuration/private file area
// (config/screenshots/savegames)
char fileUserSettingsPath [PATH_MAX] = "";
// where the CD ROM drive is mounted
char fileCDROMPath [PATH_MAX] = "";
// temporary path manipulation working area
char filePathTempBuffer [PATH_MAX] = "";
// space required for opening and reading from compressed streams within a bigfile
#define decompWorkspaceIncrement 65536;
static char *decompWorkspaceP = NULL;
static sdword decompWorkspaceSize = 0;
static sdword decompWorkspaceInUse = FALSE;
/*=============================================================================
Functions:
=============================================================================*/
/*-----------------------------------------------------------------------------
Name : fileNameReplaceSlashes
Description : Replaces all backward slashes (\) in the file name with
forward slashes (/) for use with local filesystem
operations.
Inputs : fileName - Path and name of file.
Outputs : fileName - Modified file name.
Return : (None.)
Note : This is not needed for use with BIG files (slashes are
replaced as needed within BIG file functions). Slashes are
also not condensed as with filenameSlashMassage() in
BigFile.c.
Windows is the only platform currently supported that does
not typically use forward slashes to separate components in
a path, but its file routines work just fine with forward
slashes.
----------------------------------------------------------------------------*/
void fileNameReplaceSlashesInPlace(char *filePath)
{
char *ptr = NULL;
#ifdef WIN32
#define PATH_DELIMITER '\\'
#define REPLACE_DELIMITER '/'
#else
#define PATH_DELIMITER '/'
#define REPLACE_DELIMITER '\\'
#endif
while ((ptr = strchr(filePath, REPLACE_DELIMITER)) != NULL)
{
*ptr = PATH_DELIMITER;
}
}
/*-----------------------------------------------------------------------------
Name : fileNameReducePath
Description : Removes extraneous slashes in the given path and reduces
occurences of "." and "..".
Inputs : pathName - File path.
Return : (None.)
----------------------------------------------------------------------------*/
static void fileNameReducePath (char* pathName)
{
size_t pathLen;
char* pathElem[PATH_MAX];
udword pathElemCount;
size_t searchLoc;
bool8 isPathAbsolute;
udword i;
assert(pathName != NULL); //dbgAssertOrIgnore(pathName != NULL);
pathLen = strlen(pathName);
/* Reduce slashes. */
for (i = 1; i < pathLen; i++)
{
char chPrev = pathName[i - 1];
char chCurr = pathName[i];
if ((chPrev == '/' || chPrev == '\\') &&
(chCurr == '/' || chCurr == '\\'))
{
memmove(pathName + i - 1, pathName + i, pathLen - i + 1);
pathLen--;
i--;
}
}
/* Remove trailing slashes. */
while (pathName[pathLen - 1] == '/' ||
pathName[pathLen - 1] == '\\')
{
pathLen--;
pathName[pathLen] = '\0';
}
/* Split up the path string into an array containing each path
component. */
pathElem[0] = pathName;
pathElemCount = 1;
searchLoc = strcspn(pathName, "/\\");
while (searchLoc != pathLen)
{
size_t searchLocPrev = searchLoc;
pathName[searchLoc] = '\0';
pathElem[pathElemCount] = pathName + searchLoc + 1;
pathElemCount++;
searchLoc = strcspn(pathName + searchLocPrev + 1, "/\\");
searchLoc += searchLocPrev + 1;
}
#ifdef _WIN32
isPathAbsolute = (isalpha(pathName[0]) && pathName[1] == ':' &&
pathName[2] == '\0');
#else
isPathAbsolute = (pathName[0] == '\0');
#endif
if (isPathAbsolute)
{
/* Skip over the root path element, we don't need to look at it for
now. */
pathElemCount--;
if (pathElemCount != 0)
{
memmove(pathElem, pathElem + 1, sizeof(char*) * pathElemCount);
}
}
/* Using our array of path components, reduce any occurences of "." and
"..". */
for (i = 0; i < pathElemCount; i++)
{
char* currentElem = pathElem[i];
if (currentElem[0] != '.')
continue;
if (currentElem[1] == '\0')
{
/* The current path element refers to the current directory ("."),
so we can remove it. */
pathElemCount--;
if (i < pathElemCount)
{
memmove(
pathElem + i, pathElem + i + 1,
sizeof(char*) * pathElemCount - i);
}
i--;
continue;
}
if (!(currentElem[1] == '.' && currentElem[2] == '\0'))
continue;
/* The current path element refers to the parent directory (".."). */
if (i == 0)
{
if (isPathAbsolute)
{
printf("fileNameReducePath(): Attempted to reach a "
"parent directory of the root directory.");
/* Attempting to reach a directory below the root directory, so
just get rid of the current element. */
pathElemCount--;
if (pathElemCount != 0)
{
memmove(
pathElem, pathElem + 1,
sizeof(char*) * pathElemCount);
}
i--;
}
continue;
}
if (!strcmp(pathElem[i - 1], ".."))
{
/* Previous path element also represents the previous directory, so
keep this element and allow further traversal up the directory
tree. */
continue;
}
/* Remove the current and previous path elements. */
assert(pathElemCount >= 2); //dbgAssertOrIgnore(pathElemCount >= 2);
pathElemCount--;
if (i < pathElemCount)
{
memmove(
pathElem + i - 1, pathElem + i + 1,
sizeof(char*) * pathElemCount - i);
}
pathElemCount--;
i -= 2;
}
/* Rebuild the path string. */
pathLen = 0;
if (isPathAbsolute)
{
#ifdef _WIN32
pathName[2] = '/';
pathLen = 3;
#else
pathName[0] = '/';
pathLen = 1;
#endif
}
if (pathElemCount == 0)
{
pathName[pathLen] = '\0';
return;
}
for (i = 0; i < pathElemCount; i++)
{
char* currentElem = pathElem[i];
size_t elemLen = strlen(currentElem);
memmove(
pathName + pathLen, currentElem, sizeof(char) * elemLen);
pathLen += elemLen;
pathName[pathLen] = '/';
pathLen++;
}
/* Remove the trailing slash. */
pathName[pathLen - 1] = '\0';
}
/*-----------------------------------------------------------------------------
Name : fileNameCorrectCase
Description : Perform a case-insensitive search for the given file or
directory, modifying the path string to represent its case
on the filesystem.
Inputs : fileName - Path and name of file.
Outputs : fileName - The modified file name. This will not be
modified if the file is not found.
Return : TRUE if the file was found, FALSE if not.
----------------------------------------------------------------------------*/
#if FILE_CASE_INSENSITIVE_SEARCH
static bool8 fileNameCorrectCase (char* fileName)
{
char fileNameCopy[PATH_MAX + 1];
char* pChar;
udword pathComponentCount;
bool8 isPathAbsolute;
udword i;
assert(fileName); //dbgAssertOrIgnore(fileName);
/* Make a copy of the file name string to abuse as we wish. */
assert(strlen(fileName) <= PATH_MAX); //dbgAssertOrIgnore(strlen(fileName) <= PATH_MAX);
strncpy(fileNameCopy, fileName, PATH_MAX);
fileNameCopy[PATH_MAX] = '\0';
/* Compress any directory changes in the path so we can easily search for
directory names while ignoring case. */
fileNameReducePath(fileNameCopy);
if (fileNameCopy[0] == '\0')
return FALSE;
/* Check if the file name is just a root directory reference. */
#ifdef _WIN32
if (isalpha(fileNameCopy[0]) && strcmp(fileNameCopy + 1, ":/") == 0)
{
struct stat fileInfo;
/* Make sure the drive specified exists. */
if (stat(fileNameCopy, &fileInfo) != 0)
{
return FALSE;
}
assert(strlen(fileNameCopy) <= strlen(fileName)); //dbgAssertOrIgnore(strlen(fileNameCopy) <= strlen(fileName));
strcpy(fileName, fileNameCopy);
return TRUE;
}
#else
if (strcmp(fileNameCopy, "/") == 0)
{
/* We should always have a root directory... */
fileName[0] = '/';
fileName[1] = '\0';
return TRUE;
}
#endif
/* Split the path name components into separate strings. */
pathComponentCount = 1;
while ((pChar = strrchr(fileNameCopy, '/')))
{
*pChar = '\0';
pathComponentCount++;
}
/* Find the first path component that is not a reference to the parent
directory. */
pChar = fileNameCopy;
for (i = 0; i < pathComponentCount; i++)
{
if (strcmp(pChar, "..") != 0)
break;
pChar += strlen(pChar);
/* Merge all parent directory references with the next path
component. */
if (i != pathComponentCount - 1)
{
*pChar = '/';
pChar++;
}
}
assert(i < pathComponentCount); //dbgAssertOrIgnore(i < pathComponentCount);
if (i == pathComponentCount)
{
/* Apparently every element of the path is a parent directory
reference. Whatever...let's at least check if it exists. */
struct stat fileInfo;
assert(pathComponentCount == 1); //dbgAssertOrIgnore(pathComponentCount == 1);
if (stat(fileNameCopy, &fileInfo) != 0)
return FALSE;
/* The entry exists, so copy the reduced file name string into the
original string. */
assert(strlen(fileNameCopy) <= strlen(fileName)); //dbgAssertOrIgnore(strlen(fileNameCopy) <= strlen(fileName));
strcpy(fileName, fileNameCopy);
return TRUE;
}
/* Check if the path name is an absolute path, merging the first two path
components (the root directory reference and the first path component
following it) if so. */
isPathAbsolute = FALSE;
#ifdef _WIN32
if (isalpha(fileNameCopy[0]) && strcmp(fileNameCopy + 1, ":") == 0)
{
fileNameCopy[2] = '/';
#else
if (fileNameCopy[0] == '\0')
{
fileNameCopy[0] = '/';
#endif
assert(pathComponentCount > 1); //dbgAssertOrIgnore(pathComponentCount > 1);
pathComponentCount--;
isPathAbsolute = TRUE;
}
/* Now we start the search for the given file. For each path component,
we first do an exact check to see if it exists using the case given
case. If that fails, we then perform a case-insensitive comparison
against each entry in the directory in which the path element resides.
If a match is found, the file name of the matching entry is copied into
the path string, and the search is continued with the next path
component. If a match is not found, the search is stopped, and we
return a null pointer immediately. */
for (i = 0; i < pathComponentCount; i++)
{
#ifdef _WIN32
char filespec[PATH_MAX + 1];
struct _finddata_t findData;
long hFile;
bool foundResult;
#else
struct dirent* pEntry;
DIR* pDir;
#endif
struct stat fileInfo;
/* Check if the current entry exists in the given case. */
if (stat(fileNameCopy, &fileInfo) != 0)
{
/* Temporarily remove the last path delimiter so we can separate
the entry we're searching for from the directory in which it
resides. */
pChar = strrchr(fileNameCopy, '/');
if (pChar)
{
if (i == 0 && isPathAbsolute)
{
/* Special case for the first entry in an absolute path:
keep the trailing slash in the root directory name when
opening the root directory for searching. */
char tempChar;
pChar++;
tempChar = *pChar;
*pChar = '\0';
#ifdef _WIN32
filespec[PATH_MAX] = '\0';
strncpy(filespec, fileNameCopy, PATH_MAX);
strncat(filespec, "/*.*", PATH_MAX - strlen(filespec));
#else
pDir = opendir(fileNameCopy);
#endif
*pChar = tempChar;
}
else
{
/* Remove the path delimiter and open the parent
directory. */
*pChar = '\0';
pChar++;
#ifdef _WIN32
filespec[PATH_MAX] = '\0';
strncpy(filespec, fileNameCopy, PATH_MAX);
strncat(filespec, "/*.*", PATH_MAX - strlen(filespec));
#else
pDir = opendir(fileNameCopy);
#endif
}
}
else
{
/* The current entry we're searching for should be in the
current working directory. */
pChar = fileNameCopy;
#ifdef _WIN32
strcpy(filespec, "*.*");
#else
pDir = opendir(".");
#endif
}
#ifdef _WIN32
/* Get the first entry in the directory. */
hFile = _findfirst(filespec, &findData);
if (hFile == -1)
return FALSE;
/* Search through each entry in the current directory, performing
a case-insensitive check against the entry name. */
foundResult = FALSE;
do
{
if (_stricmp(pChar, findData.name) == 0)
{
foundResult = TRUE;
break;
}
} while (_findnext(hFile, &findData) == 0);
_findclose(hFile);
/* Check if a match was found. */
if (!foundResult)
return FALSE;
/* Copy over the entry name with the correct case. */
strcpy(pChar, findData.name);
#else
/* Make sure we could successfully open the directory. */
if (!pDir)
return FALSE;
/* Search through each entry in the current directory, performing
a case-insensitive check against the entry name. */
while ((pEntry = readdir(pDir)))
{
if (strcasecmp(pChar, pEntry->d_name) == 0)
break;
}
/* Check if a match was found. */
if (!pEntry)
{
closedir(pDir);
return FALSE;
}
/* Copy over the entry name with the correct case. */
strcpy(pChar, pEntry->d_name);
#endif
/* Restore the full path up to the current entry. */
if (pChar != fileNameCopy)
{
pChar--;
*pChar = '/';
}
#ifndef _WIN32
closedir(pDir);
#endif
}
/* If this is not the last component of the path name, add a slash to
the end of the current entry to form a full path to the next
entry. */
if (i != pathComponentCount - 1)
{
fileNameCopy[strlen(fileNameCopy)] = '/';
}
}
/* Everything checks out with the file name, so copy the case-sensitive
result back over into the original file name string. */
assert(strlen(fileNameCopy) <= strlen(fileName)); //dbgAssertOrIgnore(strlen(fileNameCopy) <= strlen(fileName));
strcpy(fileName, fileNameCopy);
return TRUE;
}
#else /* FILE_CASE_INSENSITIVE_SEARCH */
/* If we're not manually performing case-insensitive file searches, merely
make sure the file exists. This should allow us to use this function even
when we don't want to manually perform case-insensitive searches yet still
give the same results on platforms that use case-insensitive file
systems. */
static bool8 fileNameCorrectCase (char* fileName)
{
char fileNameCopy[PATH_MAX + 1];
struct stat fileInfo;
assert(fileName); //dbgAssertOrIgnore(fileName);
/* Make a copy of the file name string. */
assert(strlen(fileName) <= PATH_MAX); //dbgAssertOrIgnore(strlen(fileName) <= PATH_MAX);
strncpy(fileNameCopy, fileName, PATH_MAX);
fileNameCopy[PATH_MAX] = '\0';
/* Compress any directory changes in the path and convert all slashes to
forward slashes. */
fileNameReducePath(fileNameCopy);
if (fileNameCopy[0] == '\0')
return FALSE;
/* Check if the file exists. */
if (stat(fileNameCopy, &fileInfo) != 0)
return FALSE;
/* File exists, so copy the reduced path string into the original file
name string. */
assert(strlen(fileNameCopy) <= strlen(fileName)); //dbgAssertOrIgnore(strlen(fileNameCopy) <= strlen(fileName));
strcpy(fileName, fileNameCopy);
return TRUE;
}
#endif /* FILE_CASE_INSENSITIVE_SEARCH */
/*-----------------------------------------------------------------------------
Name : fileMakeDirectory
Description : Creates the specified directory, creating parent directories
as necessary.
Inputs : directoryName - Name of the directory to create.
Return : TRUE if successful, FALSE if not.
----------------------------------------------------------------------------*/
bool8 fileMakeDirectory (const char* directoryName)
{
char directoryCopy[PATH_MAX + 1];
size_t directoryLen;
char* pChar;
assert(directoryName != NULL); //dbgAssertOrIgnore(directoryName != NULL);
assert(strlen(directoryName) <= PATH_MAX); //dbgAssertOrIgnore(strlen(directoryName) <= PATH_MAX);
/* Make a copy of the directory name with which we can modify as
needed. */
strncpy(directoryCopy, directoryName, PATH_MAX);
directoryCopy[PATH_MAX] = '\0';
/* Reduce the path name. */
fileNameReducePath(directoryCopy);
directoryLen = strlen(directoryCopy);
if (directoryLen == 0)
return TRUE;
/* Add a trailing slash to our directory name. */
#ifdef _WINDOWS
if (directoryCopy[directoryLen - 1] != '\\')
{
directoryCopy[directoryLen] = '\\';
directoryLen++;
directoryCopy[directoryLen] = '\0';
}
#else
if (directoryCopy[directoryLen - 1] != '/')
{
directoryCopy[directoryLen] = '/';
directoryLen++;
directoryCopy[directoryLen] = '\0';
}
#endif
/* Find the first path element that isn't the root directory or a parent
directory delimiter. */
#ifdef _WINDOWS
pChar = strchr(directoryCopy, '\\');
#else
pChar = strchr(directoryCopy, '/');
#endif
if (pChar)
{
*pChar = '\0';
#ifdef _WINDOWS
if (isalpha(directoryCopy[0]) && directoryCopy[1] == ':' &&
directoryCopy[2] == '\0')
#else
if (directoryCopy[0] == '\0')
#endif
{
#ifdef _WINDOWS
*pChar = '\\';
pChar = strchr(pChar + 1, '\\');
#else
*pChar = '/';
pChar = strchr(pChar + 1, '/');
#endif
*pChar = '\0';
}
}
/* Create each directory as needed. */
while (pChar)
{
*pChar = 0;
/* Check if the directory exists. */
if (stat(directoryCopy, &fileStat) == 0)
{
/* A filesystem entry exists, so make sure it's a directory. */
if (!S_ISDIR(fileStat.st_mode))
return FALSE;
}
else
{
/* Attempt to create the directory. */
#if defined(_MSC_VER) || defined(__MINGW32__)
if (_mkdir(directoryCopy) == -1)
#else
if (_mkdir(directoryCopy, 0777) == -1)
#endif
return FALSE;
}
/* Continue with the next path element. */
#ifdef _WINDOWS
*pChar = '\\';
pChar = strchr(pChar + 1, '\\');
#else
*pChar = '/';
pChar = strchr(pChar + 1, '/');
#endif
}
return TRUE;
}
/*-----------------------------------------------------------------------------
Name : fileMakeDestinationDirectory
Description : Creates the directory in which the given file resides.
Inputs : fileName - path and name of file.
Return : TRUE if the directory exists or could be created, FALSE if
not.
----------------------------------------------------------------------------*/
bool8 fileMakeDestinationDirectory (const char* fileName)
{
char directoryName[PATH_MAX + 1];
char* pChar0;
char* pChar1;
assert(fileName); //dbgAssertOrIgnore(fileName);
/* Make a copy of the directory name string, excluding the file itself. */
strncpy(directoryName, fileName, PATH_MAX);
directoryName[PATH_MAX] = '\0';
pChar0 = strrchr(directoryName, '/');
pChar1 = strrchr(directoryName, '\\');
if (pChar1 > pChar0)
pChar0 = pChar1;
/* If the file is in the current directory, assume the directory
exists. */
if (!pChar0)
return TRUE;
/* Create the directory. */
*pChar0 = '\0';
return fileMakeDirectory(directoryName);
}
/*-----------------------------------------------------------------------------
Name : fileLoadAlloc
Description : Loads specified file into memory after allocating memory for it.
Inputs : fileName - path and name of file to be loaded.
address - location to store the allocated pointer.
flags - NonVolatile, Pyrophoric or file access flags
Outputs : *address - pointer to newly allocated and loaded file.
Return : number of bytes allocated and loaded.
Note : Generates a fatal error if file doesn't exist. If you don't
like this behavior, call fileExists() first.
----------------------------------------------------------------------------*/
sdword fileLoadAlloc(char *_fileName, void **address, enum FF flags)
{
char *memoryName = NULL,
*fileName = NULL;
FILE *inFile = NULL;
bigFileConfiguration *whereFound = NULL;
udword nameLength = 0,
length = 0,
lengthRead = 0,
bigFileIndex = 0;
sdword bigfileResult = 0;
assert(address != NULL); //dbgAssertOrIgnore(address != NULL);
// try to load from bigfile
if (!IgnoreBigfiles && !bitTest(flags, FF_CDROM|FF_IgnoreBIG|FF_UserSettingsPath))
{
if (bigFindFile(_fileName, &whereFound, &bigFileIndex))
{
bigfileResult = bigFileLoadAlloc(&(whereFound->tableOfContents), whereFound->filePtr, _fileName, bigFileIndex, address);
if (bigfileResult != -1)
{
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%s | %s\n", whereFound->bigFileName, _fileName);
}
return bigfileResult;
}
}
}
// filesystem load
fileName = filePathPrepend(_fileName, flags); //get full path
fileNameCorrectCase(fileName);
nameLength = strlen(fileName); //set memory name to the
assert(nameLength > 1); //dbgAssertOrIgnore(nameLength > 1); // end of the filename if filename too long
if (nameLength > MEM_NameLength)
{
memoryName = &fileName[nameLength - MEM_NameLength];
}
else
{
memoryName = fileName;
}
length = fileSizeGet(_fileName, flags); //get size of file
assert(length > 0); //dbgAssertOrIgnore(length > 0); // and verify it
*address = memAllocAttempt(length, memoryName, (flags & (NonVolatile | Pyrophoric)) | MBF_String);//allocate the memory for this file
if (*address == NULL) //if couldn't allocate enough generate a fatal error
{
throw std::runtime_error("fileLoadAlloc: couldn't allocate"); //<< length << " bytes for " << fileName;
}
if ((inFile = fopen(fileName, "rb")) == NULL) //open the file
{
throw std::runtime_error("fileLoadAlloc: coundn't open file"); //<< fileName;
}
lengthRead = fread(*address, 1, length, inFile); //read the file
#if FILE_ERROR_CHECKING
if (lengthRead != length) //verify correct amount read
{
throw std::runtime_error("fileLoadAlloc: expected"); //<< length << " bytes, read " << lengthRead << " bytes";
}
#endif
fclose(inFile);
#if FILE_VERBOSE_LEVEL >= 2
printf("fileLoadAlloc: loaded %d bytes of '%s' to 0x%x from handle 0x%x", length, fileName, *address, inFile);
#endif
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s | [F] |\n", _fileName);
}
return length;
}
/*-----------------------------------------------------------------------------
Name : fileLoad
Description : Loads named file into specified address.
Inputs : fileName - path/name of file to load
address - address to load it to
flags - various load flags
Outputs : Reads the entire file into the buffer pointed to by address.
Return : number of bytes loaded
Note : Generates a fatal error if file doesn't exist. If you don't
like this behavior, call fileExists() first.
----------------------------------------------------------------------------*/
sdword fileLoad(char *_fileName, void *address, enum FF flags)
{
char *fileName = NULL;
FILE *inFile = NULL;
bigFileConfiguration *whereFound = NULL;
udword length = 0,
lengthRead = 0,
bigFileIndex = 0;
sdword bigfileResult = 0;
// try to load from bigfile
if (!IgnoreBigfiles && !bitTest(flags, FF_CDROM|FF_IgnoreBIG|FF_UserSettingsPath))
{
if (bigFindFile(_fileName, &whereFound, &bigFileIndex))
{
bigfileResult = bigFileLoad(&(whereFound->tableOfContents), whereFound->filePtr, bigFileIndex, address);
if (bigfileResult != -1)
{
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%s | %s\n", whereFound->bigFileName, _fileName);
}
return bigfileResult;
}
}
}
// filesystem
fileName = filePathPrepend(_fileName, flags); //get full path
fileNameCorrectCase(fileName);
length = fileSizeGet(_fileName, flags); //get length of file
if ((inFile = fopen(fileName, "rb")) == NULL) //open the file
{
throw std::runtime_error("fileLoadAlloc: couldn't open file"); //<< fileName;
}
lengthRead = fread(address, 1, length, inFile); //read the file
#if FILE_ERROR_CHECKING
if (lengthRead != length) //verify correct amount read
{
throw std::runtime_error("fileLoadAlloc: expected"); // %d bytes, read %d bytes", length, lengthRead);
}
#endif
fclose(inFile);
#if FILE_VERBOSE_LEVEL >= 2
printf("fileLoad: loaded %d bytes of '%s' to 0x%x", length, fileName, address);
#endif
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s | [F] |\n", _fileName);
}
return(length);
}
/*-----------------------------------------------------------------------------
Name : fileSave
Description : Saves data of length, address to fileName
Inputs : fileName, address, length
Outputs :
Return : length
----------------------------------------------------------------------------*/
sdword fileSave(char *_fileName, void *address, sdword length)
{
FILE *outFile;
char *fileName;
sdword lengthWrote;
fileName = filePathPrepend(_fileName, FF_UserSettingsPath); //get full path
fileNameCorrectCase(fileName);
if (!fileMakeDestinationDirectory(fileName))
{
throw std::runtime_error("fileSave: unable to create destination directory for file"); //<< fileName
}
if ((outFile = fopen(fileName, "wb")) == NULL) //open the file
{
throw std::runtime_error("fileSave: couldn't open file"); //<<fileName
}
lengthWrote = fwrite(address,1,length,outFile);
#if FILE_ERROR_CHECKING
if (lengthWrote != length) //verify correct amount read
{
throw std::runtime_error("fileSave: expected"); //<< bytes, wrote %d bytes", length, lengthWrote);
}
#endif
fclose(outFile);
#if FILE_VERBOSE_LEVEL >= 2
printf("fileSave: saved %d bytes of '%s' to 0x%x", length, fileName, address);
#endif
return lengthWrote;
}
/*-----------------------------------------------------------------------------
Name : fileExistsInBigFile
Description :
Inputs :
Outputs :
Return :
----------------------------------------------------------------------------*/
bool fileExistsInBigFile(char *fileName)
{
udword fileIndex = 0;
bigFileConfiguration *whereFound = NULL;
return bigFindFile(fileName, &whereFound, &fileIndex);
}
/*-----------------------------------------------------------------------------
Name : fileExists
Description : Checks to see if a file exists
Inputs : fileName - name of file to find
flags - where to search (disk or in .BIG files)
Outputs : ..
Return : TRUE if file found, FALSE otherwise
----------------------------------------------------------------------------*/
bool fileExists(char *_fileName, enum FF flags)
{
char *fileName;
if (!IgnoreBigfiles && !bitTest(flags, FF_CDROM|FF_IgnoreBIG|FF_UserSettingsPath))
{
if (fileExistsInBigFile(_fileName))
{
return TRUE;
}
}
fileName = filePathPrepend(_fileName, flags); //get full path
if (fileNameCorrectCase(fileName))
{
return TRUE;
}
return FALSE;
}
/*-----------------------------------------------------------------------------
Name : fileSizeGet
Description : Finds the length, in bytes, of a file.
Inputs : fileName - name of file to find the length of.
flags - where to search for file (dosk or in .BIG files)
Outputs : ..
Return : Length of file. Generates a fatal error if file doesn't exist.
Note : Because this may actually open the file to find it's length,
it should never be called on files which are already open.
----------------------------------------------------------------------------*/
sdword fileSizeGet(char *_fileName, enum FF flags)
{
FILE *file;
sdword length;
char *fileName;
if (!IgnoreBigfiles && !bitTest(flags, FF_CDROM|FF_IgnoreBIG|FF_UserSettingsPath))
{
bigFileConfiguration *whereFound = NULL;
udword fileIndex = 0;
if (bigFindFile(_fileName, &whereFound, &fileIndex))
{
length = (whereFound->tableOfContents.fileEntries + fileIndex)->realLength;
#if FILE_VERBOSE_LEVEL >= 3
printf("%s: '%s' is %d bytes in length (bigfile)", __func__, _fileName, length);
#endif
return length;
}
}
fileName = filePathPrepend(_fileName, flags); //get full path
fileNameCorrectCase(fileName);
if ((file = fopen(fileName, "rb")) == NULL) //open the file
{
throw std::runtime_error("fileSizeGet: can't find file"); //<< fileName);
}
length = fseek(file, 0, SEEK_END); //get length of file
assert(length == 0); //dbgAssertOrIgnore(length == 0);
length = ftell(file);
fclose(file);
#if FILE_VERBOSE_LEVEL >= 3
printf("fileSizeGet: '%s' is %d bytes in length", fileName, length);
#endif
return(length);
}
void fileDelete(char *_fileName)
{
char *fileName;
fileName = filePathPrepend(_fileName, FF_IgnorePrepend); //get full path
fileNameReplaceSlashesInPlace(fileName);
remove(fileName);
}
/*-----------------------------------------------------------------------------
Name : fileOpen
Description : Open specified file for reading
Inputs : fileName - name of file to be opened
flags - flags controlling where to find it and how to open it.
Outputs : creates a fileOpenInfo for subsequent accesses
Return : returns a handle (which may be reference a FILE * or the bigfile)
----------------------------------------------------------------------------*/
filehandle fileOpen(char *_fileName, enum FF flags)
{
FILE *file;
char access[3];
char *fileName;
char localPath[PATH_MAX] = "";
filehandle fh;
bool usingBigfile = FALSE;
bool firstBufUse = FALSE;
bool localFileExists = FALSE;
int expandedSize, storedSize;
BitFile *bitFile;
// find next available filehandle
fh = 1;
while (fh <= MAX_FILES_OPEN)
{
if (!filesOpen[fh].inUse)
break;
++fh;
}
if (fh > MAX_FILES_OPEN)
{
if (bitTest(flags, FF_ReturnNULLOnFail))
{
return 0;
}
throw std::runtime_error("fileOpen: too many files open - cannot open file"); //<<_fileName);
}
strcpy(filesOpen[fh].path, _fileName);
// if the filename starts with a slash it's a full path
// which we should use as is
if (_fileName[0] == '\\' || _fileName[0] == '/')
{
strcpy(localPath, _fileName);
}
// otherwise try a local filesystem version
else
{
filePathPrepend(_fileName, FF_NoModifers); // this ends up with the override path...
strcpy(localPath, filePathTempBuffer);
}
// don't fiddle with the path any more - we should have an explicit full path
// at this point; the question is does a file exist there?
localFileExists = fileExists(localPath, FF_IgnorePrepend);
// try to load from bigfile
if (!localFileExists && !IgnoreBigfiles && !bitTest(flags, FF_CDROM|FF_IgnoreBIG|FF_UserSettingsPath))
{
bigFileConfiguration *whereFound = NULL;
udword fileIndex = 0;
if (bigFindFile(_fileName, &whereFound, &fileIndex))
{
// no write support for bigfiles currently
assert(!bitTest(flags, FF_AppendMode)); //dbgAssertOrIgnore(!bitTest(flags, FF_AppendMode));
assert(!bitTest(flags, FF_WriteMode)); //dbgAssertOrIgnore(!bitTest(flags, FF_WriteMode));
usingBigfile = TRUE;
filesOpen[fh].usingBigfile = TRUE;
filesOpen[fh].bigFP = whereFound->filePtr;
filesOpen[fh].bigTOC = &(whereFound->tableOfContents);
filesOpen[fh].textMode = bitTest(flags, FF_TextMode);
filesOpen[fh].offsetStart = (filesOpen[fh].bigTOC->fileEntries + fileIndex)->offset + (filesOpen[fh].bigTOC->fileEntries + fileIndex)->nameLength + 1;
filesOpen[fh].offsetVirtual = 0;
filesOpen[fh].length = (filesOpen[fh].bigTOC->fileEntries + fileIndex)->realLength;
}
if (usingBigfile) // common stuff, whether it's in the main or update bigfile
{
if ((filesOpen[fh].bigTOC->fileEntries + fileIndex)->compressionType)
{
// compressed file
if (!decompWorkspaceInUse)
{
if (decompWorkspaceSize < filesOpen[fh].length) // workspace isn't big enough
{
// add a little extra room for the next possible reuse
// (an attempt to reduce too many memReallocs)
if (decompWorkspaceSize == 0)
{
firstBufUse = TRUE;
}
decompWorkspaceSize = filesOpen[fh].length + decompWorkspaceIncrement;
decompWorkspaceP = memRealloc(decompWorkspaceP, decompWorkspaceSize,
"decompWorkspace", 0);
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s", _fileName);
if (firstBufUse)
{
logfileLogf(FILELOADSLOG, "(decomp buffer created %dk)\n",
decompWorkspaceSize/1024);
}
else
{
logfileLogf(FILELOADSLOG, "(decomp buffer increased to %dk)\n",
decompWorkspaceSize/1024);
}
}
}
else // reuse buffer
{
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s", _fileName);
logfileLogf(FILELOADSLOG, "(decomp buffer reused)\n");
}
}
filesOpen[fh].decompBuf = decompWorkspaceP;
decompWorkspaceInUse = TRUE;
}
else // allocate a new, temporary buffer
{
filesOpen[fh].decompBuf = memAlloc(filesOpen[fh].length, "decompBuf", 0);
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s", _fileName);
logfileLogf(FILELOADSLOG, "(decomp buffer created %dk)\n",
decompWorkspaceSize/1024);
}
}
// decompress from file directly into workspace
fseek(filesOpen[fh].bigFP, filesOpen[fh].offsetStart, SEEK_SET);
bitFile = bitioFileInputStart(filesOpen[fh].bigFP);
expandedSize = lzssExpandFileToBuffer(bitFile, filesOpen[fh].decompBuf, filesOpen[fh].length);
storedSize = bitioFileInputStop(bitFile);
assert(expandedSize == filesOpen[fh].length); //dbgAssertOrIgnore(expandedSize == filesOpen[fh].length);
assert(storedSize == (filesOpen[fh].bigTOC->fileEntries + fileIndex)->storedLength); //dbgAssertOrIgnore(storedSize == (filesOpen[fh].bigTOC->fileEntries + fileIndex)->storedLength);
}
else
{
filesOpen[fh].decompBuf = NULL;
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s", _fileName);
logfileLogf(FILELOADSLOG, "(uncompressed file)\n");
}
}
#if FILE_VERBOSE_LEVEL >= 2
printf("fileOpen: '%s' (from bigfile) handle 0x%x", _fileName, fh);
#endif
filesOpen[fh].inUse = TRUE;
return fh;
}
}
// resort to the good old disk filesystem
fileName = filePathPrepend(_fileName, flags); //get full path
fileNameCorrectCase(fileName);
if (bitTest(flags, FF_AppendMode))
{
access[0] = 'a';
}
else if (bitTest(flags, FF_WriteMode))
{
access[0] = 'w';
}
else
{
access[0] = 'r';
}
#ifdef _WIN32
/* Only open files in text mode on Windows. Since text files are assumed
to use DOS end-of-line markers, we will handle end-of-line conversions
manually on other platforms. */
if (bitTest(flags, FF_TextMode))
{
access[1] = 't';
}
else
#endif
{
access[1] = 'b';
}
access[2] = 0;
if (LogFileLoads)
{
logfileLogf(FILELOADSLOG, "%-80s | [F] |\n", _fileName);
}
if (bitTest(flags, FF_AppendMode | FF_WriteMode) &&
!fileMakeDestinationDirectory(fileName))
{
throw std::runtime_error("fileOpen: unable to create destination directory for file"); //<<fileName);
}
if ((file = fopen(fileName, access)) == NULL)
{
if (bitTest(flags, FF_ReturnNULLOnFail))
{
return 0;
}
throw std::runtime_error("fileOpen: cannot open file"); //<<fileName);
}
#if FILE_VERBOSE_LEVEL >= 2
printf("fileOpen: '%s' (from filesystem) handle 0x%x, FILE *0x%x", fileName, fh, file);
#endif
filesOpen[fh].inUse = TRUE;
filesOpen[fh].fileP = file;
filesOpen[fh].usingBigfile = FALSE;
filesOpen[fh].textMode = bitTest(flags, FF_TextMode);
return fh;
}
/*-----------------------------------------------------------------------------
Name : fileClose
Description : Closes a previously open file.
Inputs : handle - handle to the file to be closed
Outputs :
Return : void
Note : generates an error if the file not open and debugging enabled
----------------------------------------------------------------------------*/
void fileClose(filehandle handle)
{
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
if (!filesOpen[handle].usingBigfile)
fclose(filesOpen[handle].fileP);
else if (filesOpen[handle].decompBuf)
{
if (filesOpen[handle].decompBuf == decompWorkspaceP)
decompWorkspaceInUse = FALSE;
else
// free decompression buffer if it was in use and not the stock workspace
// (ie, we must have allocated it during fileOpen())
memFree(filesOpen[handle].decompBuf);
}
filesOpen[handle].inUse = FALSE;
#if FILE_VERBOSE_LEVEL >= 2
printf("fileClose: handle 0x%x", handle);
#endif
}
/*-----------------------------------------------------------------------------
Name : fileSeek
Description : Seek to a new location in specified file.
Inputs : handle - handle to open file
offset - of new location
whence - where to seek from
Outputs : ..
Return : new location
Note :
----------------------------------------------------------------------------*/
sdword fileSeek(filehandle handle, sdword offset, sdword whence)
{
sdword newLocation = 0;
// dbgAssertOrIgnore(offset >= 0);
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
/* We can seek to the start of a text file, but that's it. */
assert(!filesOpen[handle].textMode || (whence == FS_Start && !offset)); //dbgAssertOrIgnore(!filesOpen[handle].textMode || (whence == FS_Start && !offset));
if (filesOpen[handle].usingBigfile)
{
switch (whence)
{
case FS_Start:
newLocation =
(filesOpen[handle].offsetVirtual = offset);
break;
case FS_Current:
newLocation =
(filesOpen[handle].offsetVirtual += offset);
break;
case FS_End:
newLocation =
(filesOpen[handle].offsetVirtual = filesOpen[handle].length - 1 + offset);
break;
}
assert(newLocation < filesOpen[handle].length); //dbgAssertOrIgnore(newLocation < filesOpen[handle].length);
}
else // filesystem
{
newLocation = fseek(filesOpen[handle].fileP, offset, whence);
assert(newLocation == 0); //dbgAssertOrIgnore(newLocation == 0);
newLocation = ftell(filesOpen[handle].fileP);
}
#if FILE_VERBOSE_LEVEL >= 3
printf("fileSeek: handle 0x%x seeked %d bytes (mode %d) to %d", handle, offset, whence, newLocation);
#endif
return newLocation;
}
/*-----------------------------------------------------------------------------
Name : fileBlockRead
Description : Reads a block from the specified file.
Inputs : handle - handle to open file
dest - buffer to read the data to
nBytes - number of bytes to read, in bytes
Outputs : fills the dest buffer with nBytes read from handle
Return : number of bytes read. If debugging enabled, we compare this
to the amount requested and generate a fatal error if there is a difference.
----------------------------------------------------------------------------*/
sdword fileBlockRead(filehandle handle, void *dest, sdword nBytes)
{
sdword lengthRead;
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
assert(!filesOpen[handle].textMode); //dbgAssertOrIgnore(!filesOpen[handle].textMode);
if (filesOpen[handle].usingBigfile)
{
assert(filesOpen[handle].offsetVirtual + nBytes <= filesOpen[handle].length); //dbgAssertOrIgnore(filesOpen[handle].offsetVirtual + nBytes <= filesOpen[handle].length);
if (filesOpen[handle].decompBuf)
{
// from memory buffer
memcpy(dest, filesOpen[handle].decompBuf + filesOpen[handle].offsetVirtual, nBytes);
lengthRead = nBytes;
}
else
{
// from bigfile
fseek(filesOpen[handle].bigFP, filesOpen[handle].offsetVirtual + filesOpen[handle].offsetStart, SEEK_SET);
lengthRead = fread(dest, 1, nBytes, filesOpen[handle].bigFP); //read in the data
}
filesOpen[handle].offsetVirtual += lengthRead;
}
else
{
lengthRead = fread(dest, 1, nBytes, filesOpen[handle].fileP); //read in the data
}
#ifndef _MACOSX_FIX_ME // zero-length .wxd since you can't play the original
#if FILE_ERROR_CHECKING
if (lengthRead != nBytes)
{ //make sure it was all read in
throw std::runtime_error("fileBlockRead: expected"); //<< %d bytes, read %d", nBytes, lengthRead);
}
#endif
#endif
#if FILE_VERBOSE_LEVEL >= 3
printf("fileBlockRead: handle 0x%x read %d bytes to 0x%x", handle, lengthRead, dest);
#endif
return lengthRead;
}
/*-----------------------------------------------------------------------------
Name : fileBlockReadNoError
Description : Reads a block from the specified file.
Inputs : handle - handle to open file
dest - buffer to read the data to
nBytes - number of bytes to read, in bytes
Outputs : fills the dest buffer with nBytes read from handle
Return : number of bytes read. This function will NOT generate an error
if fewer than expected bytes are read
----------------------------------------------------------------------------*/
sdword fileBlockReadNoError(filehandle handle, void *dest, sdword nBytes)
{
sdword lengthRead, ReadAmt = nBytes;
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
assert(!filesOpen[handle].textMode); //dbgAssertOrIgnore(!filesOpen[handle].textMode);
if (filesOpen[handle].usingBigfile)
{
if(filesOpen[handle].offsetVirtual + nBytes > filesOpen[handle].length)
ReadAmt = filesOpen[handle].length - filesOpen[handle].offsetVirtual;
if (filesOpen[handle].decompBuf)
{
// from memory buffer
memcpy(dest, filesOpen[handle].decompBuf + filesOpen[handle].offsetVirtual, ReadAmt);
lengthRead = ReadAmt;
}
else
{
// from bigfile
fseek(filesOpen[handle].bigFP, filesOpen[handle].offsetVirtual + filesOpen[handle].offsetStart, SEEK_SET);
lengthRead = fread(dest, 1, ReadAmt, filesOpen[handle].bigFP); //read in the data
}
filesOpen[handle].offsetVirtual += lengthRead;
}
else
{
lengthRead = fread(dest, 1, nBytes, filesOpen[handle].fileP); //read in the data
}
return lengthRead;
}
/*-----------------------------------------------------------------------------
Name : fileLineRead
Description : Reads a line from the specified file.
Inputs : handle - handle of open file
dest - destination string
nChars - length of string (dest)
Outputs : Reads up to nChars bytes from file converting CF/LF pairs to
just a CR. Removed LF characters are not counted in nChars
Return : Number of characters read or FR_EndOfFile if the end of file
reached. Note that a zero return value reflects empty lines.
----------------------------------------------------------------------------*/
sdword fileLineRead(filehandle handle, char *dest, sdword nChars)
{
sdword length;
int ch;
char *loc;
#ifdef _WIN32
char *retVal;
#endif
assert(nChars > 0); //dbgAssertOrIgnore(nChars > 0); // validate the params
assert(handle); //dbgAssertOrIgnore(handle);
assert(dest != NULL); //dbgAssertOrIgnore(dest != NULL);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
assert(filesOpen[handle].textMode); //dbgAssertOrIgnore(filesOpen[handle].textMode);
if (filesOpen[handle].usingBigfile)
{
if (filesOpen[handle].offsetVirtual >= filesOpen[handle].length)
return FR_EndOfFile;
if (filesOpen[handle].decompBuf)
{
// fake the filesystem fgets stuff on a mem buffer
length = 0;
loc = (char *)filesOpen[handle].decompBuf + filesOpen[handle].offsetVirtual;
while (length < nChars-1)
{
if (filesOpen[handle].offsetVirtual >= filesOpen[handle].length)
break;
// getc
ch = *(loc++);
++filesOpen[handle].offsetVirtual;
/* Check if we have reached the end of the line. */
if (ch == '\n')
break;
if (ch == '\r')
{
/* Remove the "\n" character if this is a DOS
end-of-line. */
// getc
ch = *(loc++);
++filesOpen[handle].offsetVirtual;
if (ch != '\n')
{
// ungetc
--loc;
--filesOpen[handle].offsetVirtual;
}
break;
}
/* Add the character to the end of the string. */
*(dest+length) = ch;
++length;
}
*(dest+length) = 0;
}
else
{
fseek(filesOpen[handle].bigFP, filesOpen[handle].offsetVirtual + filesOpen[handle].offsetStart, SEEK_SET);
// fake the filesystem fgets stuff (like below) here in binary mode
length = 0;
while (length < nChars-1)
{
if (feof(filesOpen[handle].bigFP) || filesOpen[handle].offsetVirtual >= filesOpen[handle].length)
break;
/* Get the next character from the file. */
ch = getc(filesOpen[handle].bigFP);
if (ch == EOF)
break;
++filesOpen[handle].offsetVirtual;
/* Check if we have reached the end of the line. */
if (ch == '\n')
break;
if (ch == '\r')
{
/* Remove the "\n" character if this is a DOS
end-of-line. */
ch = getc(filesOpen[handle].bigFP);
if (ch != '\n')
ungetc(ch, filesOpen[handle].bigFP);
else
++filesOpen[handle].offsetVirtual;
break;
}
/* Add the character to the end of the string. */
*(dest+length) = ch;
++length;
}
*(dest+length) = 0;
}
}
else
{
if (feof(filesOpen[handle].fileP)) //check if end of file
{
return FR_EndOfFile;
}
#ifdef _WIN32
/* Read a line from the file. */
retVal = fgets(dest, nChars, filesOpen[handle].fileP);
if (retVal != dest)
{
return(FR_EndOfFile);
}
length = strlen(dest); //get length of string
if (length) //if not a blank line
{
if (dest[length - 1] == '\n') //if newline at end of line
{
dest[length - 1] = 0; //kill newline character
length--; //one less character
}
}
#else
/* Read a line from the file, manually checking for an end-of-line
marker. */
length = 0;
while (length < nChars - 1)
{
/* Get the next character from the file. */
ch = getc(filesOpen[handle].fileP);
if (ch == EOF)
break;
/* Check if we have reached the end of the line. */
if (ch == '\n')
break;
if (ch == '\r')
{
/* Remove the "\n" character if this is a DOS end-of-line. */
ch = getc(filesOpen[handle].fileP);
if (ch != '\n')
ungetc(ch, filesOpen[handle].fileP);
break;
}
/* Add the character to the end of the string. */
dest[length] = ch;
length++;
}
dest[length] = '\0';
#endif
}
#if FILE_VERBOSE_LEVEL >= 3
printf("fileLineRead: handle 0x%x read %d chars to 0x%x ('%s')", handle, length, dest, dest);
#endif
return length;
}
/*-----------------------------------------------------------------------------
Name : fileCharRead
Description : Read a character from a file.
Inputs : handle - handle of open file.
Outputs : ..
Return : Character read from file.
----------------------------------------------------------------------------*/
sdword fileCharRead(filehandle handle)
{
sdword ch;
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
if (filesOpen[handle].usingBigfile)
{
if (filesOpen[handle].offsetVirtual >= filesOpen[handle].length)
return EOF;
if (filesOpen[handle].decompBuf)
{
ch = filesOpen[handle].decompBuf[filesOpen[handle].offsetVirtual++];
/* If reading a text file, check for a new line character. */
if (filesOpen[handle].textMode && ch == '\r')
{
/* Remove the "\n" character if this is a DOS end-of-line. */
ch = filesOpen[handle].decompBuf[filesOpen[handle].offsetVirtual++];
if (ch != '\n')
filesOpen[handle].offsetVirtual--;
/* Force the character to be a newline character in case this
is a Mac end-of-line. */
ch = '\n';
}
}
else
{
fseek(filesOpen[handle].bigFP, filesOpen[handle].offsetVirtual + filesOpen[handle].offsetStart, SEEK_SET);
ch = fgetc(filesOpen[handle].bigFP);
if (ch != EOF)
{
++filesOpen[handle].offsetVirtual;
/* If reading a text file, check for a new line character. */
if (filesOpen[handle].textMode && ch == '\r')
{
/* Remove the "\n" character if this is a DOS
end-of-line. */
ch = fgetc(filesOpen[handle].bigFP);
if (ch != '\n')
ungetc(ch, filesOpen[handle].bigFP);
else
filesOpen[handle].offsetVirtual++;
/* Force the character to be a newline character in case
this is a Mac end-of-line. */
ch = '\n';
}
}
}
return ch;
}
/* Read the next character from the local filesystem stream. */
#ifdef _WIN32
return fgetc(filesOpen[handle].fileP);
#else
ch = fgetc(filesOpen[handle].fileP);
if (!filesOpen[handle].textMode || ch != '\r')
return ch;
/* Handle possible DOS or Mac line ends. */
ch = fgetc(filesOpen[handle].fileP);
if (ch != '\n')
ungetc(ch, filesOpen[handle].fileP);
/* Force the character to be a newline character in case this is a Mac
end-of-line. */
return '\n';
#endif
}
//
// for using regular underlying i/o stream (filesystem, not bigfile)
//
sdword fileUsingBigfile(filehandle handle)
{
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
return filesOpen[handle].usingBigfile;
}
//
// for using regular underlying i/o stream (for files of the filesystem, not files of a bigfile)
//
FILE *fileStream(filehandle handle)
{
assert(handle); //dbgAssertOrIgnore(handle);
assert(filesOpen[handle].inUse); //dbgAssertOrIgnore(filesOpen[handle].inUse);
return filesOpen[handle].fileP;
}
/*-----------------------------------------------------------------------------
Name : filePathBufferSet
Description : populates preallocated buffer with given path and ensures
it is properly formatted/terminated. Buffer should ideally
be PATH_MAX bytes long.
Outputs :
Return :
----------------------------------------------------------------------------*/
void filePathMaxBufferSet(char *buffer, char *path)
{
unsigned int path_len = 0;
assert(buffer); //dbgAssertOrIgnore(buffer != NULL);
assert(path); //dbgAssertOrIgnore(path != NULL);
path_len = strlen(path);
assert(path_len < PATH_MAX); //dbgAssertOrIgnore(path_len < PATH_MAX);
strncpy(buffer, path, PATH_MAX);
// make sure path is delimited
strcat(buffer, "/");
fileNameReplaceSlashesInPlace(buffer);
}
/*-----------------------------------------------------------------------------
Name : filePathPrepend
Description : Prepend the default path for opening files.
Inputs : fileName - file name/relative path to add to end of default path
flags - flags to set the root directory we want
Outputs : Copies prepend path to global variable and concatenates fileName
Return : pointer to new full path
----------------------------------------------------------------------------*/
char *filePathPrepend(char *fileName, enum FF flags)
{
assert(fileName); //dbgAssertOrIgnore(fileName != NULL);
if (bitTest(flags, FF_IgnorePrepend))
{
strcpy(filePathTempBuffer, "");
}
else if (bitTest(flags, FF_HomeworldDataPath))
{
strcpy(filePathTempBuffer, fileHomeworldDataPath);
}
else if (bitTest(flags, FF_UserSettingsPath))
{
strcpy(filePathTempBuffer, fileUserSettingsPath);
}
else if (bitTest(flags, FF_CDROM))
{
strcpy(filePathTempBuffer, fileCDROMPath);
}
else
{
strcpy(filePathTempBuffer, fileOverrideBigPath);
}
strcat(filePathTempBuffer, fileName);
return filePathTempBuffer;
}
void fileCDROMPathSet(char *path)
{
#ifdef _WIN32
char message[80];
// TODO: check path to be drive root!
UINT res = GetDriveType(path);
if (res != DRIVE_CDROM)
{
sprintf(message, "'%s' Is not a valid CD-ROM; path ignored.", path);
MessageBox(NULL, message, "Invalid CD-ROM path", MB_OK | MB_APPLMODAL);
return FALSE;
}
#endif
filePathMaxBufferSet(fileCDROMPath, path);
}
void fileHomeworldDataPathSet(char *path)
{
filePathMaxBufferSet(fileHomeworldDataPath, path);
}
void fileOverrideBigPathSet(char *path)
{
filePathMaxBufferSet(fileOverrideBigPath, path);
}
void fileUserSettingsPathSet(char *path)
{
filePathMaxBufferSet(fileUserSettingsPath, path);
}
//
// How to interpret the LOGFILELOADS output log:
//
// 3 columns: main_bigfile update_bigfile filesystem
// M = main bigfile
// U = update bigfile
// F = filesystem
// Each column may be blank (indicating the file was not present there),
// or have a lowercase letter there (m/u/f) (indicating that it had an
// old or unused version of the file there), or have an uppercase letter
// there ([M]/[U]/[F]) (indicating that the file there was used for the
// load).
//
// WARNING: If you run with comparebigfiles OFF, it could invalidate some
// of the conclusions that this output draws.
//
/*-----------------------------------------------------------------------------
Name : logfileClear
Description : clears the logfile
Inputs : logfile
Outputs :
Return :
----------------------------------------------------------------------------*/
void logfileClear(char *logfile)
{
FILE *file = NULL;
if ((file = fopen(logfile, "wt")) != NULL) // open and close to make it 0 size
{
fclose(file);
}
}
/*-----------------------------------------------------------------------------
Name : logFileLog
Description : logs a log into the logfile
Inputs : logfile, str
Outputs :
Return :
----------------------------------------------------------------------------*/
void logfileLog(char *logfile, char *str)
{
FILE *file = NULL;
if ((file = fopen(logfile, "at")) != NULL)
{
fprintf(file,str);
fclose(file);
}
}
/*-----------------------------------------------------------------------------
Name : logfileLogf
Description : logs a log into the logfile, variable parameters
Inputs : logfile, str, ...
Outputs :
Return :
----------------------------------------------------------------------------*/
void logfileLogf(char *logfile, char *format, ...)
{
char buffer[200];
va_list argList;
va_start(argList, format); //get first arg
vsprintf(buffer, format, argList); //prepare output string
va_end(argList);
logfileLog(logfile,buffer);
}
| [
"[email protected]"
]
| [
[
[
1,
1997
]
]
]
|
599a7c772909d0a747ecbd3c43de544ab373427d | 0c5fd443401312fafae18ea6a9d17bac9ee61474 | /code/engine/EventSystem/Core/EventFunctorTable.h | dc76745e74bcc4ce4f974e9aeeed310183a3f1da | []
| no_license | nurF/Brute-Force-Game-Engine | fcfebc997d6ab487508a5706b849e9d7bc66792d | b930472429ec6d6f691230e36076cd2c868d853d | refs/heads/master | 2021-01-18T09:29:44.038036 | 2011-12-02T17:31:59 | 2011-12-02T17:31:59 | 2,877,061 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,963 | h | /* ___ _________ ____ __
/ _ )/ __/ ___/____/ __/___ ___ _/_/___ ___
/ _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_)
/____/_/ \___/ /___//_//_|_, /_//_//_|__/
/___/
This file is part of the Brute-Force Game Engine, BFG-Engine
For the latest info, see http://www.brute-force-games.com
Copyright (c) 2011 Brute-Force Games GbR
The BFG-Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The BFG-Engine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the BFG-Engine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __EVENT_FUNCTOR_TABLE_H_
#define __EVENT_FUNCTOR_TABLE_H_
#include <EventSystem/Core/EventDefs.h>
#include <EventSystem/Core/EventFunctor.h>
/// \brief Interface class for accessing EvenTabless
class IEventTable
{
public:
virtual ~IEventTable() {}
// Dispatch an event over all entries
virtual size_t call(IEvent* event) = 0;
// Number of stored functors
virtual long getSize() const = 0;
//virtual void AddEntry (BaseEventFunctor*) = 0;
// Delete an specific entry
virtual void deleteEntry (void* listener) = 0;
// Clear all
virtual void deleteAllEntries() = 0;
};
template < class EventListener, class EventType=IEvent >
class EventFunctorTable : public IEventTable
{
typedef SpecificEventFunctor<EventListener,EventType>* ConcretePtr;
public:
EventFunctorTable(size_t maxEvents=MAX_EVENTS) :
mEventTable(new ConcretePtr[maxEvents]),
mMaxEvents(maxEvents),
mEventCounter(0) {}
~EventFunctorTable()
{
// Free all functors
for (size_t i = 0; i < mEventCounter; ++i)
{
ConcretePtr fctr = mEventTable[i];
delete (fctr);
}
// free
delete[] mEventTable;
}
/// \return The number of calls done by this function
size_t call(IEvent* event)
{
// :TODO: BOOST_IS_TYPE_OF ...
// Always assume its the correct event type
EventType* realType = static_cast<EventType*>(event);
for (size_t i = 0; i < mEventCounter; ++i)
mEventTable[i]->call(realType);
// This may count wrong, if some calls are blocked due ReceiverID
return mEventCounter;
}
long getSize() const {return mEventCounter;}
//template<class EventListener, class EventType>
//void AddEntry( SpecificEventFunctor<EventListener,EventType> * EventEntry )
void addEntry(ConcretePtr eventEntry)
{
if (mEventCounter > mMaxEvents)
{
delete eventEntry;
}
else
{
mEventTable[mEventCounter] = (ConcretePtr) eventEntry;
//SpecificEventFunctor<EventListener, EventType> iFctor = m_EventTable [m_EventCounter];
++mEventCounter;
}
}
void deleteEntry(void* listener)
{
size_t i = 0;
while(i < mEventCounter)
{
if (mEventTable[i]->getEventListener() == listener )
{
// dont change !
mEventCounter--;
// Watch out! One specific EventListener could be subscribed with multiple Functions to this event-id
// This behaviour is not forbidden so far
// We have to find all Entries, so keep searching and dont break here !
size_t j = mEventCounter;
// Copy Last Entry to current position
delete mEventTable[i];
mEventTable[i] = mEventTable[j];
}
else
{
++i;
}
}
}
void deleteAllEntries()
{
for (size_t i = 0; i < mEventCounter; ++i)
{
delete mEventTable[i];
}
mEventCounter = 0;
}
private:
ConcretePtr* mEventTable;
size_t mMaxEvents;
size_t mEventCounter;
};
#endif //__EVENT_FUNCTOR_TABLE_H_
| [
"[email protected]"
]
| [
[
[
1,
143
]
]
]
|
15436613b1c5c68fab48afacf19a5d85f8fa4095 | d08c381305e3e675c3f8253ce88fafd5111b103c | /8_8_2008/curve_-project/doc/arm_curve_going/arm_curve_6/display.cpp | edb84bd51d4c3c79937d4571204471392d2e3b4a | []
| no_license | happypeter/tinylion | 07ea77febf6dff84089eddd6e1e47cd2ae032eb2 | 2f802f291ff43c568f9ef5eb846719efca03cc80 | refs/heads/master | 2020-06-03T09:14:19.682005 | 2010-10-19T09:12:56 | 2010-10-19T09:12:56 | 914,128 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,860 | cpp | #include "display.h"
#include "screen.h"
#include <qlayout.h>
#include <qtimer.h>
#include <qframe.h>
#include <qlineedit.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qpushbutton.h>
#include <qfile.h>
//#include <cstdlib>
#include <iostream>
using namespace std;
DisplayWidget::DisplayWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
timer = 0;
QVBoxLayout *vbox = new QVBoxLayout( this, 10 );
QHBoxLayout *hbox = new QHBoxLayout( vbox );
screen1 = new Screen( this );
screen1->setYTitle( QObject::tr( "Vlure 1" ) );
// screen2 = new Screen( this );
// screen2->setYTitle( QObject::tr( "Vlure 2" ) );
// screen3 = new Screen( this );
// screen3->setYTitle( QObject::tr( "Vlure 3" ) );
vbox->addWidget( screen1 );
// vbox->addWidget( screen2 );
// vbox->addWidget( screen3 );
lineEdit = new QLineEdit(this);
lineEdit->setReadOnly( TRUE );
hbox->addWidget( lineEdit );
startButton = new QPushButton( this );
startButton->setText( tr( "&Start" ) );
stopButton = new QPushButton( this );
stopButton->setText( tr( "Sto&p" ) );
hbox->addWidget( startButton );
hbox->addWidget( stopButton );
connect( startButton, SIGNAL( clicked () ), SLOT( start() ) );
connect( stopButton, SIGNAL( clicked () ), SLOT( stop() ) );
time = 0;
yval = 0.0;
readFile();
}
void DisplayWidget::run()
{
if ( !timer ) {
timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), SLOT( tick() ) );
}
timer->start( 1000 );
}
void DisplayWidget::tick()
{
yval = readCurveData();
screen1->animate( yval );
screen2->animate( yval );
screen3->animate( yval );
lineEdit->setText( QString::number( yval ) );
}
void DisplayWidget::start()
{
run();
}
void DisplayWidget::stop()
{
timer->stop();
}
QSize DisplayWidget::sizeHint() const
{
return QSize( 16 * Margin, 12 * Margin );
}
void DisplayWidget::readFile()
{
QFile file("in.txt");
file.open(IO_ReadOnly);
QTextStream in(&file);
str = in.read();
strlist = QStringList::split(" ", str);
it = strlist.begin();
}
double DisplayWidget::readCurveData( )
{
QString tempStr;
double tempData;
tempStr =(QString) *it;
tempData = tempStr.toDouble();
if (it != strlist.end())
{
++it;
}
else
{
it = strlist.begin();
}
return tempData;
}
| [
"[email protected]"
]
| [
[
[
1,
114
]
]
]
|
85385e0e9286e9bb8e2550d0245f53c5f44d4aa5 | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Autumn/WrapperDX/Shader/HullShader.h | 0edbff5368a5ca6d52f29e715a0dcbfd94dd064a | []
| no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | #ifndef _HULL_SHADER_
#define _HULL_SHADER_
#define HULL_SHADER_ENTRY "HSMain"
#ifndef _SHADER_
#include "WrapperDX/Shader/Shader.h"
#endif
class HullShader : public Shader
{
private:
ID3D11HullShader * m_pHullShader;
public:
HullShader();
HullShader(const char * name);
virtual ~HullShader();
virtual const char * GetEntryPoint();
virtual const char * GetShaderVersion();
virtual HRESULT Create();
virtual HRESULT Destroy();
virtual void Bind();
virtual void SetConstantBuffer( unsigned int _iSlot, ConstantBuffer * _pBuffer );
virtual void SetTexture( unsigned int _iSlot, Texture * _pTexture );
virtual void SetSampler( unsigned int _iSlot, SamplerBase * _pSampler );
inline ID3D11HullShader * GetVertexShader() { return m_pHullShader; };
};
#endif // _HULL_SHADER_ | [
"edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6"
]
| [
[
[
1,
32
]
]
]
|
7bf3cc343b966900ad133b6e337b808a4d144f07 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nnavmesh/src/nnavmesh/nnavmesh.cc | c78a30ba73c808fb5f219c0f3cdc5d12cbff184a | []
| 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 | 37,977 | cc | #include "precompiled/pchnnavmesh.h"
//------------------------------------------------------------------------------
// nnavmesh.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "nnavmesh/nnavmesh.h"
#include "ncnavmesh/ncnavmeshnode.h"
#include "nnavmeshparser/nnavmeshpersist.h"
#include "mathlib/polygon.h"
#include "nspatial/nspatialserver.h"
#include "nspatial/ncspatialquadtree.h"
#include "nspatial/ncspatialmc.h"
#include "ngeomipmap/ncterraingmmclass.h"
#include "nphysics/nphysicsserver.h"
#include "nphysics/nphysicsgeom.h"
#include "entity/nentityobjectserver.h"
#include "nnavmesh/nnavutils.h"
#include "kernel/nlogclass.h"
#ifndef NGAME
#include "gfx2/ngfxserver2.h"
#endif
#define EPSILON_DISTANCE 8.f
#define INDOOR_QUERY_FLAGS nSpatialTypes::SPF_ALL_INDOORS | nSpatialTypes::SPF_ALL_CELLS |\
nSpatialTypes::SPF_CONTAINING | nSpatialTypes::SPF_USE_BBOX |\
nSpatialTypes::SPF_USE_CELL_BBOX
#define OUTDOOR_QUERY_FLAGS nSpatialTypes::SPF_OUTDOORS | nSpatialTypes::SPF_ONE_CELL |\
nSpatialTypes::SPF_CONTAINING |\
nSpatialTypes::SPF_USE_CELL_BBOX
nNebulaClass(nNavMesh, "nresource");
//------------------------------------------------------------------------------
namespace
{
// Tolerance relative to a node's height within which a point is considered at the same height as the node
const float NodeHeightToleranceOver( 1.0f );
const float NodeHeightToleranceBelow( 0.5f );
// Max distance from a point where nodes are searched when looking for a near node
const float MaxNodeVisibilityDistance( 10.0f );
}
//------------------------------------------------------------------------------
/**
Constructor
*/
nNavMesh::nNavMesh() : collide(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
Destructor
*/
nNavMesh::~nNavMesh()
{
this->UnloadResource();
}
//------------------------------------------------------------------------------
/**
Destroy
*/
void
nNavMesh::Destroy()
{
for ( int i=0; this->mesh.Size(); )
{
this->ReleaseNode (this->mesh[i]);
}
this->mesh.Clear();
}
//------------------------------------------------------------------------------
/**
ReleaseNode
*/
void
nNavMesh::ReleaseNode (ncNavMeshNode* node)
{
int index = mesh.FindIndex (node);
if ( index != - 1 )
{
mesh.Erase (index);
}
// Updates all links with this node
node->UpdateLinks();
#ifndef NGAME
node->GetEntityObject()->SendToLimbo( node->GetEntityObject() );
#endif
nEntityObjectServer::Instance()->RemoveEntityObject(node->GetEntityObject());
node = 0;
}
//------------------------------------------------------------------------------
/**
InsertNode
*/
void
nNavMesh::InsertNode (ncNavMeshNode* node)
{
if ( this->mesh.FindIndex (node) == -1 )
{
this->mesh.Append (node);
}
}
//------------------------------------------------------------------------------
/**
GetNumNodes
*/
int
nNavMesh::GetNumNodes() const
{
return this->mesh.Size();
}
//------------------------------------------------------------------------------
/**
SetObstacles
*/
void
nNavMesh::SetObstacles (const nArray<polygon*>& obstacles)
{
this->DestroyObstacles();
for (int i=0; i<obstacles.Size(); i++ )
{
polygon* element = obstacles[i];
polygon* obstacle = n_new (polygon)(*element);
this->obstacles.Append (obstacle);
}
}
//------------------------------------------------------------------------------
/**
InsertObstacle
*/
void
nNavMesh::InsertObstacle (polygon* poly)
{
if ( this->obstacles.FindIndex (poly) == -1 )
{
this->obstacles.Append (poly);
}
}
//------------------------------------------------------------------------------
/**
GetNumObstacles
*/
int
nNavMesh::GetNumObstacles() const
{
return this->obstacles.Size();
}
//------------------------------------------------------------------------------
/**
GetObstaclePolygon
*/
polygon*
nNavMesh::GetObstaclePolygon (int index) const
{
n_assert( index >= 0 && index < this->obstacles.Size() );
polygon* poly = 0;
if ( index >= 0 && index < this->obstacles.Size() )
{
poly = this->obstacles[index];
}
return poly;
}
//------------------------------------------------------------------------------
/**
DestroyObstaclces
*/
void
nNavMesh::DestroyObstacles()
{
while ( this->obstacles.Size() )
{
polygon* obstacle = this->obstacles[0];
n_delete (obstacle);
this->obstacles.Erase (0);
}
}
//------------------------------------------------------------------------------
/**
GetNode
*/
ncNavMeshNode*
nNavMesh::GetNode (float x, float z) const
{
ncNavMeshNode* node = 0;
for ( int i=0; i<this->mesh.Size() && !node; i++ )
{
ncNavMeshNode* element = this->mesh[i];
if ( element && element->IsPointInside (x, z) )
{
node = element;
}
}
return node;
}
//------------------------------------------------------------------------------
/**
GetNode
*/
ncNavMeshNode*
nNavMesh::GetNode (const vector3& point) const
{
// Look for a navigation node in indoors first
nArray< nEntityObject* > nodes;
nSpatialServer::Instance()->GetEntitiesCategory( point, nSpatialTypes::CAT_NAVMESHNODES,
INDOOR_QUERY_FLAGS,
nodes );
for ( int i(0); i < nodes.Size(); ++i )
{
ncNavMeshNode* meshNode( nodes[i]->GetComponent<ncNavMeshNode>() );
if ( meshNode )
{
if ( meshNode->IsPointInside( point ) )
{
return meshNode;
};
}
}
// Look for a navigation node in outdoor
float terrainHeight;
GetHeightMap()->GetHeight( point.x, point.z, terrainHeight );
nodes.Clear();
nSpatialServer::Instance()->GetEntitiesCategory( point, nSpatialTypes::CAT_NAVMESHNODES,
OUTDOOR_QUERY_FLAGS, nodes );
for ( int i(0); i < nodes.Size(); ++i )
{
ncNavMeshNode* meshNode( nodes[i]->GetComponent<ncNavMeshNode>() );
if ( meshNode )
{
if ( meshNode->IsPointInside( point ) )
{
return meshNode;
};
}
}
// No nav node found containing the given point
return NULL;
}
//------------------------------------------------------------------------------
/**
Get the navigation node below the given point
Any type of navigation node can be returned, giving more priority to mesh nodes
*/
ncNavNode*
nNavMesh::GetNavNode( const vector3& point ) const
{
// Check if there's a mesh node containing the point
ncNavNode* node( this->GetNode( point ) );
if ( node )
{
return node;
}
// Check if there's a waypoint node containing the point
return this->GetWaypointNode( point );
}
//------------------------------------------------------------------------------
/**
Get the navigation waypoint node containing the given point
A waypoint node contains a point if it's walkable from the center of the
waypoint to the point
*/
ncNavNode*
nNavMesh::GetWaypointNode( const vector3& point ) const
{
// Max "visibility distance" to look for near nodes
sphere visibilitySphere( point, MaxNodeVisibilityDistance );
// Look for waypoints in indoors and outdoor space
float closestDistanceSq( FLT_MAX );
ncNavNode* closestNode( NULL );
nArray< nEntityObject* > nodes;
nSpatialServer::Instance()->GetEntitiesCategory( visibilitySphere, nSpatialTypes::CAT_WAYPOINTS,
nSpatialTypes::SPF_ALL_INDOORS | nSpatialTypes::SPF_ALL_CELLS |
nSpatialTypes::SPF_INTERSECTING | nSpatialTypes::SPF_USE_BBOX, nodes );
nSpatialServer::Instance()->GetEntitiesCategory( visibilitySphere, nSpatialTypes::CAT_WAYPOINTS,
nSpatialTypes::SPF_OUTDOORS | nSpatialTypes::SPF_ALL_CELLS |
nSpatialTypes::SPF_INTERSECTING | nSpatialTypes::SPF_USE_BBOX, nodes );
for ( int i(0); i < nodes.Size(); ++i )
{
ncNavNode* node( nodes[i]->GetComponent<ncNavNode>() );
if ( node )
{
// Build LoS
// @todo When not using anymore the midpoints for pathfinding, use the nearest point
// in the node for the LoS check instead of the midpoint
vector3 nodePoint;
node->GetMidpoint( nodePoint );
// Check for LoS to the node
vector3 los( nodePoint - point );
float losLengthSq( los.lensquared() );
if ( losLengthSq < closestDistanceSq )
{
if ( nNavUtils::IsWalkable( point, nodePoint, NULL ) )
{
closestDistanceSq = losLengthSq;
closestNode = node;
}
}
}
}
return closestNode;
}
//------------------------------------------------------------------------------
/**
GetClosestNode
*/
ncNavNode*
nNavMesh::GetClosestNode( const vector3& point ) const
{
// Check if there's already a node containing the point
ncNavNode* node( this->GetNavNode( point ) );
if ( node )
{
return node;
}
// -- Look for a close mesh node not containing the point
// Max "visibility distance" to look for near nodes
sphere visibilitySphere( point, MaxNodeVisibilityDistance );
// Look for mesh nodes in indoors
float closestDistanceSq( FLT_MAX );
ncNavNode* closestNode( NULL );
nArray< nEntityObject* > nodes;
nSpatialServer::Instance()->GetEntitiesCategory( visibilitySphere, nSpatialTypes::CAT_NAVMESHNODES,
nSpatialTypes::SPF_ALL_INDOORS | nSpatialTypes::SPF_ALL_CELLS |
nSpatialTypes::SPF_INTERSECTING | nSpatialTypes::SPF_USE_BBOX, nodes );
for ( int i(0); i < nodes.Size(); ++i )
{
ncNavNode* node( nodes[i]->GetComponent<ncNavNode>() );
if ( node )
{
// Build LoS
// @todo When not using anymore the midpoints for pathfinding, use the nearest point
// in the node for the LoS check instead of the midpoint
vector3 nodePoint;
node->GetMidpoint( nodePoint );
// Skip those nav nodes which don't share the same floor level as the given point
if ( point.y < nodePoint.y - NodeHeightToleranceBelow ||
point.y > nodePoint.y + NodeHeightToleranceOver )
{
continue;
}
// Check for LoS to the node
vector3 los( nodePoint - point );
float losLengthSq( los.lensquared() );
if ( losLengthSq < closestDistanceSq )
{
if ( nNavUtils::IsWalkable( point, nodePoint, NULL ) )
{
closestDistanceSq = losLengthSq;
closestNode = node;
}
}
}
}
// Max "visibility volume" for outdoor is less approximate since outdoor nodes' height cannot be easyly known,
// neither the spatial server supports for cylinder intersection checks.
bbox3 visibilityBBox( point, vector3( MaxNodeVisibilityDistance, FLT_MAX * 0.5f, MaxNodeVisibilityDistance ) );
// Look for mesh nodes in outdoor
nFloatMap* terrainMap( this->GetHeightMap() );
nodes.Clear();
nSpatialServer::Instance()->GetEntitiesCategory( visibilitySphere, nSpatialTypes::CAT_NAVMESHNODES,
nSpatialTypes::SPF_OUTDOORS | nSpatialTypes::SPF_ALL_CELLS |
nSpatialTypes::SPF_INTERSECTING | nSpatialTypes::SPF_USE_BBOX, nodes );
for ( int i(0); i < nodes.Size(); ++i )
{
ncNavNode* node( nodes[i]->GetComponent<ncNavNode>() );
if ( node )
{
// Project node point onto terrain to achieve a more precise LoS test
vector3 nodePoint;
node->GetMidpoint( nodePoint );
float terrainHeight;
terrainMap->GetHeight( nodePoint.x, nodePoint.z, terrainHeight );
if ( nodePoint.y < terrainHeight )
{
nodePoint.y = terrainHeight;
}
// Skip those nav nodes which don't share the same floor level as the given point
if ( point.y < nodePoint.y - NodeHeightToleranceBelow ||
point.y > nodePoint.y + NodeHeightToleranceOver )
{
continue;
}
// Check for LoS to the node
// @todo When not using the midpoints for pathfinding anymore, use the nearest point
// in the node for the LoS check instead of the midpoint
vector3 los( nodePoint - point );
float losLengthSq( los.lensquared() );
if ( losLengthSq < closestDistanceSq )
{
if ( nNavUtils::IsWalkable( point, nodePoint, NULL ) )
{
closestDistanceSq = losLengthSq;
closestNode = node;
}
}
}
}
return closestNode;
}
//------------------------------------------------------------------------------
/**
GetNode
*/
ncNavMeshNode*
nNavMesh::GetNode (int index) const
{
n_assert(index>=0&&index<this->mesh.Size());
ncNavMeshNode* node = 0;
if ( index >= 0 && index < this->mesh.Size() )
{
node = this->mesh[index];
}
return node;
}
//------------------------------------------------------------------------------
/**
GetIndexNode
@return the index of the node inside the mesh, -1 if not found
*/
int
nNavMesh::GetIndexNode (ncNavMeshNode* node) const
{
int index = -1;
for ( int i=0; i<this->mesh.Size() && index == -1; i++ )
{
ncNavMeshNode* element = this->mesh[i];
if ( element && element == node )
{
index = i;
}
}
return index;
}
//------------------------------------------------------------------------------
/**
GetDistance
@return the distance between two nodes in the navigation graph
*/
int
nNavMesh::GetDistance (ncNavMeshNode* source, ncNavMeshNode* goal) const
{
n_assert(source&&goal);
int distance = -1;
if ( source && goal )
{
int indexSource = this->GetIndexNode (source);
int indexGoal = this->GetIndexNode (goal);
distance = this->GetDistance (indexSource, indexGoal);
}
return distance;
}
//------------------------------------------------------------------------------
/**
GetDistance
@return the distance between two nodes in the navigation graph
*/
int
nNavMesh::GetDistance (int source, int goal) const
{
return this->navGraph.At (source, goal);
}
//------------------------------------------------------------------------------
/**
SetDistance
@param source Index of the source node
@param goal Index of the goal node
@param distance Distance from source node to goal node
*/
void
nNavMesh::SetDistance (int source, int goal, int distance)
{
if ( source >= 0 && goal >= 0 && this->navGraph.ValidIndex(source,goal) )
{
this->navGraph.Set (source, goal, distance);
}
}
//------------------------------------------------------------------------------
/**
GetNumGraphNodes
*/
int
nNavMesh::GetNumGraphNodes() const
{
n_assert( this->navGraph.GetHeight() == this->navGraph.GetWidth() );
return this->navGraph.GetHeight();
}
//------------------------------------------------------------------------------
/**
SetNumGraphNodes
*/
void
nNavMesh::SetNumGraphNodes (int numNodes)
{
if ( numNodes > 0 )
{
this->navGraph.SetSize (numNodes, numNodes);
n_assert( static_cast<int>(this->navGraph.GetHeight()) == numNodes );
n_assert( static_cast<int>(this->navGraph.GetWidth()) == numNodes );
}
}
//------------------------------------------------------------------------------
/**
AddMesh
@brief Adds nodes and all information about other mesh into this mesh
*/
void
nNavMesh::AddMesh (nNavMesh* mesh)
{
n_assert(mesh);
if ( mesh )
{
// Mesh nodes
for ( int i=0; i<mesh->mesh.Size(); i++ )
{
ncNavMeshNode* node = mesh->GetNode (i);
n_assert(node);
if ( node )
{
this->InsertNode (node);
}
}
// Obstacles
for ( int i(0); i < mesh->obstacles.Size(); ++i )
{
this->InsertObstacle( mesh->obstacles[i] );
}
// @TODO It is necessary update the navigation mesh (note, now, we must setup the links between meshes)
// this->BuildNavGraph();
this->SetState(Valid);
}
}
//------------------------------------------------------------------------------
/**
Removes all mesh nodes and obstacles, but without releasing them
Usually this is called after the mesh has been merged with another one and
we want to make sure that transfered nodes/obstacles aren't going to be
destroyed along with this now useless container
The resource is also invalidated
*/
void
nNavMesh::ClearMesh()
{
this->mesh.Clear();
this->obstacles.Clear();
this->SetState( Empty );
}
//------------------------------------------------------------------------------
/**
SetupNavGraph
*/
void
nNavMesh::SetupNavGraph()
{
int size = this->mesh.Size();
if ( size > 0 )
{
this->navGraph.SetSize (size, size);
int i;
for ( i=0; i<size; i++ )
{
for ( int j=0; j<size; j++ )
{
this->navGraph.Set (i, j, 0);
}
}
// Find the conexions between nodes
for ( i=0; i<this->mesh.Size(); i++ )
{
ncNavMeshNode* node = this->mesh[i];
n_assert(node);
if ( node )
{
// Calculates distances between links
for ( int k=0; k<node->links.Size(); k++ )
{
ncNavMeshNode* link = static_cast<ncNavMeshNode*>( node->GetLink(k) );
n_assert(link);
if ( link )
{
int j = this->GetIndexNode (link);
n_assert (this->navGraph.ValidIndex(i,j));
if ( j != -1 )
{
this->navGraph.Set (i, j, 1);
}
}
}
}
this->navGraph.Set (i, i, 0);
}
}
}
//------------------------------------------------------------------------------
/**
BuildNavGraph
@brief Generates the navigation graph since the mesh
*/
void
nNavMesh::BuildNavGraph()
{
int size = this->mesh.Size();
this->SetupNavGraph();
nTime startTime( nTimeServer::Instance()->GetTime() );
for ( int turn = 1; turn < size; turn++ )
{
for ( int row = 0; row < size; row++ )
{
for ( int column = 0; column < size; column++ )
{
if ( nTimeServer::Instance()->GetTime() - startTime > 10 )
{
startTime = nTimeServer::Instance()->GetTime();
float completed( 100.0f * (float(row)*float(size) + float(column)) / (float(size)*float(size)) );
NLOG_REL( navbuild, (NLOGUSER | 0, "[4/4] Building navigation graph...%d(%.2f%%)/%d ", turn-1, completed, size-1) );
}
if ( this->navGraph.At (row, column) == turn )
{
// We cover the row, adding 1 to the value
for ( int i=0; i<size; i++ )
{
if ( this->navGraph.At (column, i) != 0 )
{
int cost = turn + this->navGraph.At (column, i);
if ( this->navGraph.At (row, i) == 0 ||
this->navGraph.At (row, i) > cost )
{
this->navGraph.Set (row, i, cost);
this->navGraph.Set (i, row, cost);
}
if ( row == i )
{
this->navGraph.Set (row, i, 0);
}
}
}
}
}
}
}
}
//------------------------------------------------------------------------------
/**
GetStartPosition
*/
vector3
nNavMesh::GetStartPosition() const
{
vector3 position;
if ( this->mesh.Size() > 0 )
{
position;
this->mesh[0]->GetMidpoint( position );
}
return position;
}
//------------------------------------------------------------------------------
/**
GetCenterPosition
@brief Only used for outdoor navigation meshes
*/
vector3
nNavMesh::GetCenterPosition() const
{
nSpatialServer* spatialServer = nSpatialServer::Instance();
n_assert(spatialServer);
ncTerrainGMMClass* terrainGMM = spatialServer->GetOutdoorEntity()->GetClassComponent <ncTerrainGMMClass>();
n_assert(terrainGMM);
nFloatMap* heightMap = terrainGMM->GetHeightMap();
n_assert(heightMap);
int size = heightMap->GetSize();
float scale = heightMap->GetGridScale();
float x, h;
x = size * 0.5f * scale;
heightMap->GetHeight (x, x, h);
return vector3 (x, h, x);
}
//------------------------------------------------------------------------------
/**
AdjustPosition
*/
bool
nNavMesh::AdjustPosition (vector3* position, float radius) // const
{
bool valid = true;
if ( position )
{
vector3 axis1, axis2;
polygon* obstacle = this->IsInsideObstacle (*position, radius, &axis1, &axis2);
if ( obstacle )
{
// This is a first approximation
//*position = obstacle->Midpoint() + axis1 + axis2;
valid = false;
}
}
return valid;
}
//------------------------------------------------------------------------------
/**
IsInsideObstacle
@brief Says if a given point is inside an obstacle of the mesh
*/
polygon*
nNavMesh::IsInsideObstacle (const vector3& point, float radius, vector3* paxis1, vector3* paxis2) //const
{
polygon* obstacle = 0;
for ( int i=0; i<this->obstacles.Size() && !obstacle; i++ )
{
polygon* element = this->obstacles[i];
n_assert (element);
if ( element )
{
vector3 midpoint = element->Midpoint();
// Only check elements near to the position
if ( (midpoint - point).lensquared() < pow(EPSILON_DISTANCE, 2) )
{
vector3 p0 = element->GetVertex(0);
vector3 l1 = element->GetVertex(3) - p0;
vector3 l2 = element->GetVertex(1) - p0;
vector3 distance = point - midpoint;
l1 *= 0.5f;
l2 *= 0.5f;
// Use 2D vectors
vector2 axis1(l1.x, l1.z);
vector2 axis2(l2.x, l2.z);
vector2 d(distance.x, distance.z);
vector2 n(axis1);
n.norm();
// Project distance vector onto axis1 (n)
// d2 is the perperdicular component magnitude of d and
// d1 is the parallel component magnitude of d
vector2 d1, d2;
float axis1len, axis2len;
float d1len, d2len;
d1 = n * (d%n);
d2 = d - d1;
axis1len = axis1.len();
axis2len = axis2.len();
d1len = d1.len();
d2len = d2.len();
// Check the bbox of the entity
if ( d1len - radius < axis1len &&
d2len - radius < axis2len )
{
vector2 vRadius = axis1;
if ( axis2len > axis1len )
{
vRadius = axis2;
}
if ( d.len() - radius < vRadius.len() )
{
obstacle = element;
vector3 p1 = p0 + l1*2;
vector3 p2 = p1 + l2*2;
vector3 p3 = p0 + l2*2;
nArray<vector3> v;
v.Append (p0);
v.Append (p1);
v.Append (p2);
v.Append (p3);
this->check.Set (v);
this->distances[0] = vector3 (d.x, 0, d.y);
this->distances[1] = vector3 (d1.x, 0, d1.y);
this->distances[2] = vector3 (d2.x, 0, d2.y);
}
if ( paxis1 && paxis2 )
{
vector3 p1 = point - midpoint;
if ( axis1len - d1len > axis2len - d2len )
{
*paxis1 = vector3 (d1.x, 0.f, d1.y);
axis2len += radius;
axis2.norm();
axis2 *= axis2len;
*paxis2 = vector3 (axis2.x, 0.f, axis2.y);
// Check the direction
if ( p1.dot (*paxis2) < 0 )
{
*paxis2 *= -1.f;
}
}
else
{
*paxis2 = vector3 (d2.x, 0.f, d1.y);
axis1len += radius;
axis1.norm();
axis1 *= axis1len;
*paxis1 = vector3 (axis1.x, 0.f, axis1.y);
// Check the direction
if ( p1.dot (*paxis1) < 0 )
{
*paxis1 *= -1.f;
}
}
}
this->distances[3] = vector3 (vRadius.x, 0, vRadius.y);
float finalDist = this->distances[3].len() + radius;
this->distances[3].norm();
this->distances[3] *= finalDist;
}
}
}
}
this->collide = obstacle;
return obstacle;
}
//------------------------------------------------------------------------------
/**
GetByteSize
*/
int
nNavMesh::GetByteSize()
{
int size = 0;
// Navigation mesh
for ( int i = 0; i < this->mesh.Size(); ++i )
{
size += this->mesh[i]->GetByteSize();
}
// Navigation graph
size += this->navGraph.GetHeight() * this->navGraph.GetWidth() * sizeof(int);
// Obstacles
for ( int i = 0; i < this->obstacles.Size(); ++i )
{
size += this->obstacles[i]->GetNumVertices() * sizeof(vector3);
size += sizeof(polygon*);
}
return size;
}
//------------------------------------------------------------------------------
/**
LoadResource
This method is either called directly from the nResource::Load() method
(in synchronous mode), or from the loader thread (in asynchronous mode).
The method must try to validate its resources, set the valid and pending
flags, and return a success code.
This method may be called from a thread.
*/
bool
nNavMesh::LoadResource()
{
n_assert( !this->IsValid() );
// Clear any previous data
this->UnloadResource();
// Load the navigation mesh
nString filename( this->GetFilename().Get() );
bool success = false;
if ( !filename.IsEmpty() )
{
success = nNavMeshPersist::Load(filename.Get(), this);
}
// Set an empty and invalid navigation mesh if load fails
if ( !success )
{
this->UnloadResource();
}
else
{
this->SetState(Valid);
}
return success;
}
//------------------------------------------------------------------------------
/**
UnloadResource
*/
void
nNavMesh::UnloadResource()
{
this->DestroyObstacles();
this->Destroy();
this->SetState(Unloaded);
}
//------------------------------------------------------------------------------
/**
InsertIntoSpace
*/
void
nNavMesh::InsertIntoSpace( SpaceType spaceType )
{
// Space type flags (outdoor/indoor)
int flags = 0;
if ( spaceType == INDOOR )
{
flags |= nSpatialTypes::SPF_ALL_INDOORS;
flags |= nSpatialTypes::SPF_ALL_CELLS;
flags |= nSpatialTypes::SPF_INTERSECTING;
flags |= nSpatialTypes::SPF_USE_BBOX;
}
else
{
flags |= nSpatialTypes::SPF_OUTDOORS;
flags |= nSpatialTypes::SPF_ALL_CELLS;
flags |= nSpatialTypes::SPF_INTERSECTING;
flags |= nSpatialTypes::SPF_USE_BBOX;
}
// Fit the bounding box of all nodes to their respective polygon and insert them into the spatial server
for ( int i(0); i < this->mesh.Size(); ++i )
{
ncNavMeshNode* node( this->mesh[i] );
ncSpatialMC* spatialComp( node->GetEntityObject()->GetComponentSafe<ncSpatialMC>() );
bbox3 nodeBox;
node->GetZone()->GetBBox( &nodeBox );
if ( spaceType == OUTDOOR )
{
// Place bbox for terrain nodes just below the terrain, so other outdoor nodes (brush nodes)
// are found first when looking for a nav node below a goal point
const float BuryDepth( 2.f );
nEntityObject* outdoor( nSpatialServer::Instance()->GetOutdoorEntity() );
n_assert(outdoor);
ncTerrainGMMClass* terrain( outdoor->GetClassComponent<ncTerrainGMMClass>() );
terrain->GetHeightMap()->CalculateBoundingBoxLC(
rectangle( vector2(nodeBox.vmin.x, nodeBox.vmin.z), vector2(nodeBox.vmax.x, nodeBox.vmax.z) ),
nodeBox );
nodeBox.vmin.y -= BuryDepth;
nodeBox.vmax.y = nodeBox.vmin.y;
}
spatialComp->SetBBox( nodeBox );
n_verify( nSpatialServer::Instance()->InsertEntity( node->GetEntityObject(), flags ) );
node->SetIsInOutdoor( spaceType == OUTDOOR );
#ifndef NGAME
node->LookForBoundaryEdges();
#endif
}
}
//------------------------------------------------------------------------------
/**
Get the cross point where a ray exits the navegable space
@param ray Ray to check if it exits the navegable space
@retval crossPoint Point in the navegable boundary the ray is crossing
@retval crossNormal Normal to the boundary at the cross point, looking inside
@return True if the ray exits the navegable space, false otherwise (including if the ray starts out)
*/
bool
nNavMesh::GetBoundaryPoint( const line3& ray, vector3& crossPoint, vector3& crossNormal ) const
{
ncNavMeshNode* meshNode( this->GetNode( ray.start() ) );
if ( !meshNode )
{
// Already out of the navigation mesh
return false;
}
// Look for the navigation mesh boundary by following the ray across the mesh nodes
const int MaxNeighbors( 20 );
for ( int i(0); i < MaxNeighbors; ++i )
{
ncNavMeshNode* neighbor;
switch ( meshNode->GetCrossInfo( ray, neighbor, crossPoint, crossNormal ) )
{
case ncNavMeshNode::STAYING_INSIDE:
// Not leaving the current node, so not leaving the navegable space
return false;
case ncNavMeshNode::GOING_TO_NEIGHBOR:
// Continue searching on neighbors
meshNode = neighbor;
break;
case ncNavMeshNode::GOING_OUT_OF_MESH:
// Leaving the current node, return the last cross point and normal,
// unless navigation nodes are found that validate the last segment
{
if ( this->GetWaypointNode( crossPoint ) && this->GetWaypointNode( ray.end() ) )
{
if ( nNavUtils::IsWalkable( crossPoint, ray.end(), NULL ) )
{
// There's a close node validating the movement
return false;
}
}
// No nodes found validating the movement out of the mesh,
// so report navegable boundary found
return true;
}
}
}
// Some rare case has been reached where lots of neighbors are being crossed
// The last edge crossed is taken as the navigation boundary
return true;
}
//------------------------------------------------------------------------------
/**
GetHeightMap
*/
nFloatMap*
nNavMesh::GetHeightMap() const
{
nEntityObject* outdoor( nSpatialServer::Instance()->GetOutdoorEntity() );
n_assert( outdoor );
ncTerrainGMMClass* terrainGMM( outdoor->GetClassComponentSafe<ncTerrainGMMClass>() );
nFloatMap* heightMap( terrainGMM->GetHeightMap() );
n_assert( heightMap );
return heightMap;
}
#ifndef NGAME
//------------------------------------------------------------------------------
/**
DrawObstacles
*/
void
nNavMesh::DrawObstacles (nGfxServer2* server, float high)
{
vector4 blue (0.f, 0.f, 1.f, 1.f);
vector4 green (0.f, 1.f, 0.f, 1.f);
vector4 color;
matrix44 theMatrix;
server->SetTransform(nGfxServer2::Model, theMatrix);
server->BeginLines();
for ( int i=0; i<this->obstacles.Size(); i++ )
{
polygon* poly = this->obstacles[i];
if ( this->obstacles[i] == this->collide )
{
color = green;
}
else
{
color = blue;
}
if ( poly )
{
int iVertices = poly->GetNumVertices();
vector3 edges[30];
vector3 close[2];
for ( int j=0; j<iVertices; j++ )
{
edges[j] = poly->GetVertex(j);
nNavUtils::GetGroundHeight( edges[j], edges[j].y );
edges[j].y += high;
}
if ( iVertices > 1 )
{
close[0] = poly->GetVertex(0);
close[1] = poly->GetVertex(iVertices-1);
nNavUtils::GetGroundHeight( close[0], close[0].y );
nNavUtils::GetGroundHeight( close[1], close[1].y );
close[0].y += high;
close[1].y += high;
}
server->DrawLines3d (edges, iVertices, color);
server->DrawLines3d (close, 2, color);
}
}
if ( this->collide )
{
vector3 edges[4], close[2];
int i;
for ( i=0; i<4; i++ )
{
edges[i] = this->check.GetVertex(i);
nNavUtils::GetGroundHeight( edges[i], edges[i].y );
edges[i].y += 0.4f;
}
close[0] = edges[0];
close[1] = edges[3];
server->DrawLines3d (edges, 4, vector4 (1.f, 1.f, 0.f, 1.f));
server->DrawLines3d (close, 2, vector4 (1.f, 0.5f, 0.2f, 1.f));
// Draw the distance vectors
edges[0] = this->collide->Midpoint();
nNavUtils::GetGroundHeight( edges[0], edges[0].y );
edges[0].y += 0.4f;
edges[1] = edges[0] + this->distances[0];
server->DrawLines3d (edges, 2, vector4 (0.8f, 0.8f, 1.f, 1.f));
// Draw the circle
vector3 points[90];
float radius = 0.39f;
i=0;
for ( float f=0; f<N_TWOPI; f+=0.25f, i++ )
{
points[i] = edges[1] + vector3 (radius*n_cos(f), 0.f, radius*n_sin(f));
}
server->DrawLines3d (points, i, vector4(1.f, 1.f, 0.f, 1.f));
edges[1] = edges[0] + this->distances[1];
server->DrawLines3d (edges, 2, vector4 (0.8f, 0.8f, 0.2f, 1.f));
edges[1] = edges[0] + this->distances[2];
server->DrawLines3d (edges, 2, vector4 (0.8f, 0.8f, 0.4f, 1.f));
}
server->EndLines();
}
#endif // !NGAME
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
1260
]
]
]
|
e6fec0011024b1931185785a1ee0f0b8619ea9aa | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /terralib/src/qwt/qwt_symbol.cpp | 927ce25bd379ad81dae0ceaef6d071405bd2d770 | []
| no_license | radtek/terra-printer | 32a2568b1e92cb5a0495c651d7048db6b2bbc8e5 | 959241e52562128d196ccb806b51fda17d7342ae | refs/heads/master | 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,003 | cpp | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include <qpainter.h>
#include <qapplication.h>
#include "qwt_painter.h"
#include "qwt_symbol.h"
#if QT_VERSION < 0x040000
#include <qpointarray.h>
#define QwtPointArray QPointArray
#else
#include <qpolygon.h>
#define QwtPointArray QPolygon
#endif
/*!
Default Constructor
The symbol is constructed with gray interior,
black outline with zero width, no size and style 'None'.
*/
QwtSymbol::QwtSymbol():
d_brush(Qt::gray),
d_pen(Qt::black),
d_size(0,0),
d_style(QwtSymbol::None)
{
}
/*!
\brief Constructor
\param style Symbol Style
\param brush brush to fill the interior
\param pen outline pen
\param size size
*/
QwtSymbol::QwtSymbol(QwtSymbol::Style style, const QBrush &brush,
const QPen &pen, const QSize &size):
d_brush(brush),
d_pen(pen),
d_size(size),
d_style(style)
{
}
//! Destructor
QwtSymbol::~QwtSymbol()
{
}
/*!
\brief Specify the symbol's size
If the 'h' parameter is left out or less than 0,
and the 'w' parameter is greater than or equal to 0,
the symbol size will be set to (w,w).
\param w width
\param h height (defaults to -1)
*/
void QwtSymbol::setSize(int w, int h)
{
if ((w >= 0) && (h < 0))
h = w;
d_size = QSize(w,h);
}
//! Set the symbol's size
void QwtSymbol::setSize(const QSize &s)
{
if (s.isValid())
d_size = s;
}
/*!
\brief Assign a brush
The brush is used to draw the interior of the symbol.
\param br brush
*/
void QwtSymbol::setBrush(const QBrush &br)
{
d_brush = br;
}
/*!
\brief Assign a pen
The pen is used to draw the symbol's outline.
\param pn pen
*/
void QwtSymbol::setPen(const QPen &pn)
{
d_pen = pn;
}
/*!
\brief Draw the symbol at a point (x,y).
*/
void QwtSymbol::draw(QPainter *painter, int x, int y) const
{
draw(painter, QPoint(x, y));
}
/*!
\brief Draw the symbol into a bounding rectangle.
This function assumes that the painter has been initialized with
brush and pen before. This allows a much more performant implementation
when painting many symbols with the same brush and pen like in curves.
\param painter Painter
\param r Bounding rectangle
*/
void QwtSymbol::draw(QPainter *painter, const QRect& r) const
{
switch(d_style)
{
case QwtSymbol::Ellipse:
QwtPainter::drawEllipse(painter, r);
break;
case QwtSymbol::Rect:
QwtPainter::drawRect(painter, r);
break;
case QwtSymbol::Diamond:
{
const int w2 = r.width() / 2;
const int h2 = r.height() / 2;
QwtPointArray pa(4);
pa.setPoint(0, r.x() + w2, r.y());
pa.setPoint(1, r.right(), r.y() + h2);
pa.setPoint(2, r.x() + w2, r.bottom());
pa.setPoint(3, r.x(), r.y() + h2);
QwtPainter::drawPolygon(painter, pa);
break;
}
case QwtSymbol::Cross:
{
const int w2 = r.width() / 2;
const int h2 = r.height() / 2;
QwtPainter::drawLine(painter, r.x() + w2, r.y(),
r.x() + w2, r.bottom());
QwtPainter::drawLine(painter, r.x(), r.y() + h2,
r.right(), r.y() + h2);
break;
}
case QwtSymbol::XCross:
{
QwtPainter::drawLine(painter, r.left(), r.top(),
r.right(), r.bottom());
QwtPainter::drawLine(painter, r.left(), r.bottom(),
r.right(), r.top());
break;
}
case QwtSymbol::Triangle:
case QwtSymbol::UTriangle:
{
const int w2 = r.width() / 2;
QwtPointArray pa(3);
pa.setPoint(0, r.x() + w2, r.y());
pa.setPoint(1, r.right(), r.bottom());
pa.setPoint(2, r.x(), r.bottom());
QwtPainter::drawPolygon(painter, pa);
break;
}
case QwtSymbol::DTriangle:
{
const int w2 = r.width() / 2;
QwtPointArray pa(3);
pa.setPoint(0, r.x(), r.y());
pa.setPoint(1, r.right(), r.y());
pa.setPoint(2, r.x() + w2, r.bottom());
QwtPainter::drawPolygon(painter, pa);
break;
}
case QwtSymbol::RTriangle:
{
const int h2 = r.height() / 2;
QwtPointArray pa(3);
pa.setPoint(0, r.x(), r.y());
pa.setPoint(1, r.right(), r.y() + h2);
pa.setPoint(2, r.x(), r.bottom());
QwtPainter::drawPolygon(painter, pa);
break;
}
case QwtSymbol::LTriangle:
{
const int h2 = r.height() / 2;
QwtPointArray pa(3);
pa.setPoint(0, r.right(), r.y());
pa.setPoint(1, r.x(), r.y() + h2);
pa.setPoint(2, r.right(), r.bottom());
QwtPainter::drawPolygon(painter, pa);
break;
}
default:;
}
}
/*!
\brief Draw the symbol at a specified point
\param painter Painter
\param pos Center of the symbol
*/
void QwtSymbol::draw(QPainter *painter, const QPoint &pos) const
{
QRect rect;
rect.setSize(QwtPainter::metricsMap().screenToLayout(d_size));
rect.moveCenter(pos);
painter->setBrush(d_brush);
painter->setPen(d_pen);
draw(painter, rect);
}
/*!
\brief Specify the symbol style
The following styles are defined:<dl>
<dt>QwtSymbol::None<dd>No Style. The symbol cannot be drawn.
<dt>QwtSymbol::Ellipse<dd>Ellipse or circle
<dt>QwtSymbol::Rect<dd>Rectangle
<dt>QwtSymbol::Diamond<dd>Diamond
<dt>QwtSymbol::Triangle<dd>Triangle pointing upwards
<dt>QwtSymbol::DTriangle<dd>Triangle pointing downwards
<dt>QwtSymbol::UTriangle<dd>Triangle pointing upwards
<dt>QwtSymbol::LTriangle<dd>Triangle pointing left
<dt>QwtSymbol::RTriangle<dd>Triangle pointing right
<dt>QwtSymbol::Cross<dd>Cross
<dt>QwtSymbol::XCross<dd>Diagonal cross</dl>
\param s style
*/
void QwtSymbol::setStyle(QwtSymbol::Style s)
{
d_style = s;
}
//! == operator
bool QwtSymbol::operator==(const QwtSymbol &other) const
{
return brush() == other.brush() && pen() == other.pen()
&& style() == other.style() && size() == other.size();
}
//! != operator
bool QwtSymbol::operator!=(const QwtSymbol &other) const
{
return !(*this == other);
}
| [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
]
| [
[
[
1,
265
]
]
]
|
2c8a04a0b99904957485d1887755f9fd9b7d3099 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nanimation/src/animcomp/ncfourleggedragdollclass_main.cc | 1e9f68cd6a5b29d7633953ae7aaeda659d6b211d | []
| 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 | 804 | cc | #include "precompiled/pchnanimation.h"
//------------------------------------------------------------------------------
// ncragdollclass_main.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "animcomp/ncfourleggedragdollclass.h"
//------------------------------------------------------------------------------
nNebulaComponentClass(ncFourLeggedRagdollClass,ncRagDollClass);
//------------------------------------------------------------------------------
/**
*/
ncFourLeggedRagdollClass::ncFourLeggedRagdollClass()
{
//empty
}
//------------------------------------------------------------------------------
/**
*/
ncFourLeggedRagdollClass::~ncFourLeggedRagdollClass()
{
//empty
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
27
]
]
]
|
77be6b928d1f392d059fc6cc34e3fafa98489463 | 374f53386d36e3aadf0ed88e006394220f732f30 | /gl/shadow_volume/main.cpp | 2177be0aed46ddeb80682d181aa81d6ec48361c2 | [
"MIT"
]
| permissive | yatjf/sonson-code | e7edbc613f8c97be5f7c7367be2660b3cb75a61b | fbb564af37adb2305fe7d2148f8d4f5a3450f72b | refs/heads/master | 2020-06-13T08:02:38.469864 | 2010-07-01T14:20:40 | 2010-07-01T14:20:40 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 16,728 | cpp | //
// shadow_volume
// main.cpp
//
// The MIT License
//
// Copyright (c) 2009 sonson, sonson@Picture&Software
//
// 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.
//
#ifdef WIN32
#include <GL/glut.h>
#else
#include <glut/glut.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define V_SIZE 10 // 投影のサイズ
int flag_teapot=0; // オマケのフラグ
int flag_volume=0;
int flag_sphere=0;
float look_y=0; // 注視点のY座標
float t=0; // 時間
float ground_vertex[10][10][3];
// 床の座標
float object_vertex[4][3]={
{-1, 3, -1},
{ 2, 3, -1},
{-1, 3, 2},
{ 0, 5, 0}
}; //操作用の四面体の座標値
float base_object_vertex[4][3]={
{-1, -1, -1},
{ 2, -1, -1},
{-1, -1, 2},
{ 0, 1, 0}
}; // 元になる四面体の座標値
////////////////////////////////////////////////////////////////////
//方向ベクトルの平滑化関数
void Normalizef(float *vector){
float tmp=0;
//絶対値を計算
tmp+=vector[0]*vector[0];
tmp+=vector[1]*vector[1];
tmp+=vector[2]*vector[2];
//絶対値が0のとき処理
if(tmp!=0){
tmp=sqrt(tmp);
//単位ベクトルに処理
vector[0]/=tmp;
vector[1]/=tmp;
vector[2]/=tmp;
}
}
////////////////////////////////////////////////////////////////////
//与えられた3点からその面の法線ベクトルを算出する
void Normal_Vecf(GLfloat input1[3],GLfloat input2[3],GLfloat input3[3],GLfloat result[3]){
float temp1[3];
float temp2[3];
//
temp1[0]=input2[0]-input3[0];
temp1[1]=input2[1]-input3[1];
temp1[2]=input2[2]-input3[2];
temp2[0]=input2[0]-input1[0];
temp2[1]=input2[1]-input1[1];
temp2[2]=input2[2]-input1[2];
//外積
result[0]=temp1[1]*temp2[2]-temp1[2]*temp2[1];
result[1]=temp1[2]*temp2[0]-temp1[0]*temp2[2];
result[2]=temp1[0]*temp2[1]-temp1[1]*temp2[0];
//平滑化
Normalizef(result);
}
////////////////////////////////////////////////////////////////////
//3*3行列と3次元ベクトルの乗算
void multMatrix(double *m, //乗算する行列のポインタ
float input[3], //乗算する点のポインタ
float result[3] //結果
){
result[0] = m[0]*input[0] + m[4]*input[1] + m[8]*input[2];
result[1] = m[1]*input[0] + m[5]*input[1] + m[9]*input[2];
result[2] = m[2]*input[0] + m[6]*input[1] + m[10]*input[2];
}
///////////////////////////////////////////////////////////////////////////////
//部屋の描画関数
void DrawRoom(void){
int i,j;
float normal[3];
/////////////////////////////////////////////
//波打つ床
for(i=0;i<9;i++){
for(j=0;j<9;j++){
glBegin(GL_TRIANGLES);
Normal_Vecf(ground_vertex[i][j],ground_vertex[i][j+1],ground_vertex[i+1][j+1],normal);
glNormal3fv(normal);
glVertex3fv(ground_vertex[i][j]);
glVertex3fv(ground_vertex[i][j+1]);
glVertex3fv(ground_vertex[i+1][j+1]);
Normal_Vecf(ground_vertex[i][j],ground_vertex[i+1][j+1],ground_vertex[i+1][j],normal);
glNormal3fv(normal);
glVertex3fv(ground_vertex[i][j]);
glVertex3fv(ground_vertex[i+1][j+1]);
glVertex3fv(ground_vertex[i+1][j]);
glEnd();
}
}
/////////////////////////////////////////////
//壁
glBegin(GL_QUADS);
//1
glVertex3f(-10, 15,-10);
glVertex3f(-10, 15, 8);
glVertex3f(-10, 0, 8);
glVertex3f(-10, 0,-10);
//2
glVertex3f( 8, -5,-10);
glVertex3f( 8,-5, 8);
glVertex3f( 8, 15, 8);
glVertex3f( 8, 15,-10);
//3
glVertex3f(-10, -5,-10);
glVertex3f( 8, -5,-10);
glVertex3f( 8, 15,-10);
glVertex3f(-10, 15,-10);
//4
glVertex3f( 8, -5, 8);
glVertex3f(-10, -5, 8);
glVertex3f(-10, 15, 8);
glVertex3f( 8, 15, 8);
glEnd();
}
///////////////////////////////////////////////////////////////////////////////
//光源と任意の点の延長上にある点を算出
void ClacShadowPoint(float *lightpos, float *point, float *result){
float vec[3];
vec[0] = point[0] - lightpos[0];
vec[1] = point[1] - lightpos[1];
vec[2] = point[2] - lightpos[2];
result[0] = lightpos[0] + vec[0]*V_SIZE;
result[1] = lightpos[1] + vec[1]*V_SIZE;
result[2] = lightpos[2] + vec[2]*V_SIZE;
}
///////////////////////////////////////////////////////////////////////////////
//入力された3点から構成されるポリゴンのShadow Volumeを描画する
void drawShadowPolygon(float *lightpos,float *point0,float *point1,float *point2){
float shadow_point[3][3];
/////////////////////////////////////////////
//射影後の点をすべて算出
ClacShadowPoint(lightpos,point0, shadow_point[0]);
ClacShadowPoint(lightpos,point1, shadow_point[1]);
ClacShadowPoint(lightpos,point2, shadow_point[2]);
/////////////////////////////////////////////
//Shadow Volume描画
glBegin(GL_QUADS);
//1
glVertex3fv(point1);
glVertex3fv(point0);
glVertex3fv(shadow_point[0]);
glVertex3fv(shadow_point[1]);
//2
glVertex3fv(point2);
glVertex3fv(point1);
glVertex3fv(shadow_point[1]);
glVertex3fv(shadow_point[2]);
//3
glVertex3fv(point0);
glVertex3fv(point2);
glVertex3fv(shadow_point[2]);
glVertex3fv(shadow_point[0]);
glEnd();
}
///////////////////////////////////////////////////////////////////////////////
//光源に対しての向きをチェックする
int CheckShadow(float *lightpos, float *point0,float *point1,float *point2){
float center[3];
float light_direction[3];
float polygon_normal[3];
float inner_product;
//重心算出
center[0] = (point0[0] + point1[0] + point2[0])*0.333f;
center[1] = (point0[1] + point1[1] + point2[1])*0.333f;
center[2] = (point0[2] + point1[2] + point2[2])*0.333f;
//光線方向
light_direction[0] = center[0] - lightpos[0];
light_direction[1] = center[1] - lightpos[1];
light_direction[2] = center[2] - lightpos[2];
Normalizef(light_direction);
//ポリゴンの法線ベクトル
Normal_Vecf(point0,point1,point2,polygon_normal);
//内積算出
inner_product = light_direction[0]*polygon_normal[0]
+ light_direction[1]*polygon_normal[1]
+ light_direction[2]*polygon_normal[2];
if(inner_product>=0){
return 1;
}
else
return 0;
}
///////////////////////////////////////////////////////////////////////////////
//描画関数
void drawShadowVolume(float *lightpos){
//光源に対して向きが反対のものはShadowVolumeを逆向きで描画する
//CULL_FACEを使用するため
if( CheckShadow(lightpos,object_vertex[1],object_vertex[2],object_vertex[0])){
drawShadowPolygon(lightpos,object_vertex[1],object_vertex[2],object_vertex[0]);
}else{
drawShadowPolygon(lightpos,object_vertex[0],object_vertex[2],object_vertex[1]);
}
if( CheckShadow(lightpos,object_vertex[2],object_vertex[1],object_vertex[3])){
drawShadowPolygon(lightpos,object_vertex[2],object_vertex[1],object_vertex[3]);
}else{
drawShadowPolygon(lightpos,object_vertex[3],object_vertex[1],object_vertex[2]);
}
if( CheckShadow(lightpos,object_vertex[0],object_vertex[2],object_vertex[3])){
drawShadowPolygon(lightpos,object_vertex[0],object_vertex[2],object_vertex[3]);
}else{
drawShadowPolygon(lightpos,object_vertex[3],object_vertex[2],object_vertex[0]);
}
if( CheckShadow(lightpos,object_vertex[1],object_vertex[0],object_vertex[3])){
drawShadowPolygon(lightpos,object_vertex[1],object_vertex[0],object_vertex[3]);
}else{
drawShadowPolygon(lightpos,object_vertex[3],object_vertex[0],object_vertex[1]);
}
}
///////////////////////////////////////////////////////////////////////////////
//オブジェクトを回転させる
void rotateObject(float t){
float rotated[3];
double rM[16] = {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1};
//Z軸中心に回転
rM[0] = cos(t);rM[4] = -sin(t);
rM[1] = sin(t);rM[5] = cos(t);
//originalの座標値から常に計算する
multMatrix(rM,base_object_vertex[0],rotated);
object_vertex[0][0]=rotated[0];
object_vertex[0][1]=rotated[1]+5;
object_vertex[0][2]=rotated[2];
multMatrix(rM,base_object_vertex[1],rotated);
object_vertex[1][0]=rotated[0];
object_vertex[1][1]=rotated[1]+5;
object_vertex[1][2]=rotated[2];
multMatrix(rM,base_object_vertex[2],rotated);
object_vertex[2][0]=rotated[0];
object_vertex[2][1]=rotated[1]+5;
object_vertex[2][2]=rotated[2];
multMatrix(rM,base_object_vertex[3],rotated);
object_vertex[3][0]=rotated[0];
object_vertex[3][1]=rotated[1]+5;
object_vertex[3][2]=rotated[2];
}
///////////////////////////////////////////////////////////////////////////////
//四面体描画関数
void drawObject(void){
float normal[3];
glBegin(GL_TRIANGLES);
Normal_Vecf(object_vertex[1],object_vertex[2],object_vertex[0],normal);
glNormal3fv(normal);
glVertex3fv(object_vertex[1]);
glVertex3fv(object_vertex[2]);
glVertex3fv(object_vertex[0]);
Normal_Vecf(object_vertex[2],object_vertex[1],object_vertex[3],normal);
glNormal3fv(normal);
glVertex3fv(object_vertex[2]);
glVertex3fv(object_vertex[1]);
glVertex3fv(object_vertex[3]);
Normal_Vecf(object_vertex[0],object_vertex[2],object_vertex[3],normal);
glNormal3fv(normal);
glVertex3fv(object_vertex[0]);
glVertex3fv(object_vertex[2]);
glVertex3fv(object_vertex[3]);
Normal_Vecf(object_vertex[1],object_vertex[0],object_vertex[3],normal);
glNormal3fv(normal);
glVertex3fv(object_vertex[1]);
glVertex3fv(object_vertex[0]);
glVertex3fv(object_vertex[3]);
glEnd();
}
///////////////////////////////////////////////////////////////////////////////
//描画関数
void display(void){
//光源位置
float lightpos[4] = { 0, 10, 0, 1};
look_y = 7+ 5*sin(t*0.01);
//ウィンドウを塗りつぶす
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//視点の変換行列の初期化
glLoadIdentity();
//視点の決定
glPushMatrix();
gluLookAt(
0,look_y,10,
0,4,0,
0.0, 1.0, 0.0);
//シーン全体を回転
glRotatef(t*0.5,0,1,0);
/////////////////////////////////////////////
//光源の位置の計算と設定
lightpos[0] = 4*sin(t*0.035);
lightpos[1] = 10+2*cos(t*0.05);
lightpos[2] = 4*cos(t*0.05);
glLightfv(GL_LIGHT0, GL_POSITION, (float*)lightpos);
/////////////////////////////////////////////
//光源の描画
glColor3f(1.0,1.0,1.0);
glDisable(GL_LIGHTING);
glPushMatrix();
glTranslatef(lightpos[0],lightpos[1],lightpos[2]);
glutSolidSphere(0.2,10,10);
glPopMatrix();
glEnable(GL_LIGHTING);
/////////////////////////////////////////////
//付加効果のティーポット・オマケ
if(flag_teapot || flag_sphere){
glPushMatrix();
glTranslatef(4*sin(t*0.01),2,4*cos(t*0.01));
glDisable(GL_CULL_FACE);
if(flag_teapot)glutSolidTeapot(1.5);
if(flag_sphere)glutSolidSphere(1.5,20,20);
glEnable(GL_CULL_FACE);
glPopMatrix();
}
/////////////////////////////////////////////
//四面体描画
rotateObject(t*0.05);
drawObject();
glColor3f(0.0,0.0,0.6);
/////////////////////////////////////////////
//部屋の描画
DrawRoom();
//
glDisable(GL_LIGHTING);
/////////////////////////////////////////////
//Shadow Volumeの描画
if(flag_volume){
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glDisable(GL_CULL_FACE);
glColor3f(1,1,1);
drawShadowVolume(lightpos);
glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
}
/////////////////////////////////////////////
//Shadow Volumeステンシルのセット
//カラー・デプスマスク,セット
glColorMask(0,0,0,0);
glDepthMask( GL_FALSE );
//ステンシル
glEnable(GL_STENCIL_TEST);
glStencilFunc( GL_ALWAYS, 1, ~0);
/////////////////////////////////////////////
//前面のステンシル
glStencilOp( GL_KEEP, GL_KEEP, GL_INCR);
glFrontFace(GL_CW);
drawShadowVolume(lightpos);
//背面のステンシル
glStencilOp( GL_KEEP, GL_KEEP, GL_DECR);
if(!flag_volume){
glFrontFace(GL_CCW);
drawShadowVolume(lightpos);
}
/////////////////////////////////////////////
//描画方向を右手系に再セット
glFrontFace(GL_CCW);
//マスク解除
glColorMask(1,1,1,1);
glDepthMask(GL_TRUE);
glPopMatrix();
/////////////////////////////////////////////
//影・シーンよりも手前にドーンと描画する
glStencilFunc( GL_NOTEQUAL, 0, ~0 );
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0.0f, 0.1f, 0.1f, 0.5f);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glBegin(GL_QUADS);
//1
glVertex3f( 10, 10,-2);
glVertex3f( 10,-10,-2);
glVertex3f(-10,-10,-2);
glVertex3f(-10, 10,-2);
glEnd();
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_STENCIL_TEST);
glEnable(GL_LIGHTING);
glFinish();
glutSwapBuffers();
//時間
t++;
}
///////////////////////////////////////////////////////////////////////////////
//OpenGL初期化コマンド
void init (void){
int i,j;
glEnable(GL_DEPTH_TEST);
//クライアント領域の塗りつぶし色の設定
glClearColor( 0.0, 0.0, 0.0, 1.0 );
//デプスバッファクリア値の設定
glClearDepth( 1.0 );
//ステンシルバッファクリア値の設定
glClearStencil(0);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
//光源と材質の設定
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_AUTO_NORMAL );
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
//床の作成
for(i=-5;i<5;i++){
for(j=-5;j<5;j++){
ground_vertex[i+5][j+5][0] = 2*i;
ground_vertex[i+5][j+5][1] = 0.7*sin(i)-0.5*cos(j);
ground_vertex[i+5][j+5][2] = 2*j;
}
}
}
///////////////////////////////////////////////////////////////////////////////
//マウス処理
void mouse(int button, int state, int x, int y){
switch(button){
case GLUT_LEFT_BUTTON:
break;
}
}
///////////////////////////////////////////////////////////////////////////////
//リサイズ処理
void resize(int w, int h)
{
GLdouble aspect;
//それによってビューポートを設定する
glViewport(0, 0, w, h);
//アスペクト比の初期化
aspect = (GLdouble)w/(GLdouble)h;
//プロジェクションモードで射影
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 70.0, aspect, 1.0,100.0 );
//ノーマルのモデルビューモードへ移行
glMatrixMode( GL_MODELVIEW );
}
void keyboard(unsigned char key,int x, int y){
//オマケの操作
if(key=='t'){
if(flag_teapot)flag_teapot = 0;
else{
flag_sphere = 0;
flag_teapot = 1;
}
}
else if(key=='v'){
if(flag_volume)flag_volume = 0;
else flag_volume = 1;
}
else if(key=='s'){
if(flag_sphere)flag_sphere = 0;
else{
flag_sphere = 1;
flag_teapot = 0;
}
}
}
///////////////////////////////////////////////////////////////////////////////
//メイン関数
int main(int argc, char** argv){
//GLUT初期化
glutInit(&argc, argv);
//GLUTピクセルフォーマット
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
//ウィンドウの初期化と作成
glutInitWindowSize (800,600);
glutInitWindowPosition (200,200);
glutCreateWindow ("Shadow Volume Sample");
//OpenGL初期化
init();
//各処理関数の登録
glutDisplayFunc(display);
glutReshapeFunc(resize);
glutMouseFunc(mouse);
glutIdleFunc(display);
glutKeyboardFunc(keyboard);
//メインループ
glutMainLoop();
return 0;
} | [
"yoshida.yuichi@0d0a6a56-2bd1-11de-9cad-a3574e5575ef"
]
| [
[
[
1,
524
]
]
]
|
63bce9494663ef99d7e82c5ac2447fb96e3529c8 | 845083c2ab45d9f913bba4aed7d76944acbe0eee | /Source/SADStepProgram/StepMenu.h | 371d2ebbb22b74a00f99b4472a7cd669fcda9467 | []
| no_license | smaudet/sadstep | 8fdb51229b6415fab06528e0063c6a821141b137 | 7854693083f6cd31f6a26c738d0c054d9af5161e | refs/heads/master | 2020-06-04T21:22:12.444714 | 2010-11-06T20:26:21 | 2010-11-06T20:26:21 | 32,900,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 563 | h | #ifndef STEPMENU_H
#define STEPMENU_H
#include <QWidget>
#include <QEvent>
#include <QtDebug>
#include "BaseMenuForm.h"
class BaseMenuForm;
namespace Ui {
class StepMenu;
}
class StepMenu: public QWidget
{
public:
StepMenu(BaseMenuForm* form, QWidget *parent = 0);
~StepMenu();
QWidget* getWidget();
protected:
void setWidgetRep(QWidget* internalWidgetRep);
BaseMenuForm* form;
private:
QWidget* internalWidgetRep;
Ui::StepMenu* m_ui;
void changeEvent(QEvent *e);
};
#endif // STEPMENU_H
| [
"smaudet2@da972e84-c3cd-11de-84d4-09c59dc0309f"
]
| [
[
[
1,
32
]
]
]
|
30f8ef5f361ea87ae06d460974d4668ef3548ede | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/RTTS/RioTintoTS/MineralInfo1.cpp | a36109fa42726bcdc6458c375fe000f439a89f5d | []
| 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 | 9,343 | cpp | //-- MineralInfo1.cpp -------------------------------------------------------
#include <memory.h>
#include "MineralInfo1.h"
#include "CubicSpline.h"
using namespace RioTintoTS;
//#pragma optimize("", off)
/****************************************************************************
*
* MineralInfo1:: class constants
*
* Default values for unsupplied MineralInfo parameters
*
****************************************************************************/
const double MineralInfo1::DEFAULT_SG = 2.0;
const double MineralInfo1::DEFAULT_A = 60.0;
const double MineralInfo1::DEFAULT_B = 2.0;
const double MineralInfo1::DEFAULT_TA = 0.8;
const double MineralInfo1::DEFAULT_M = 0.0677;
const double MineralInfo1::DEFAULT_C = 1.2511;
/****************************************************************************
*
* MineralInfo1::MineralInfo1( )
*
* Construct default MineralInfo1 object
*
****************************************************************************/
MineralInfo1::MineralInfo1( )
{
// Dimension appearance spline data
PARAMT.resize( 7 );
X.resize( 4 );
Y2.resize( 4 );
Y4.resize( 4 );
Y25.resize( 4 );
Y50.resize( 4 );
Y75.resize( 4 );
S2.resize( 4 );
S4.resize( 4 );
S25.resize( 4 );
S50.resize( 4 );
S75.resize( 4 );
XX.resize( 7 );
YY.resize( 7 );
SS.resize( 7 );
}
/****************************************************************************
*
* MineralInfo1::SetMineralInfo( )
*
* Sets mineral property values
*
****************************************************************************/
bool MineralInfo1::SetMineralInfo
(
double SG, double A, double b, double ta, double m, double c
)
{
// Set members
SG_ = SG;
A_ = A;
b_ = b;
ta_ = ta;
m_ = m;
c_ = c;
// Always succeed ?
return true;
}
/****************************************************************************
*
* MineralInfo1::SetAppearance( )
*
* Sets mineral breakage appearance matrix
*
****************************************************************************/
bool MineralInfo1::SetAppearance
(
const VectorView& t10Values,
const VectorView& tValues,
const MatrixView& appMatrix
)
{
// Set appearance matrix
appMatrix_ = appMatrix;
// Pre-calculate cubic splines
AppearancePreCalc( );
// Always succeed ?
return true;
}
/****************************************************************************
*
* MineralInfo1::AppearancePreCalc( )
*
* Pre-calculate splines for a new appearance function
*
****************************************************************************/
void MineralInfo1::AppearancePreCalc( )
{
// Refer to rows of the appearance matrix
VectorView R1 = appMatrix_[0];
VectorView R2 = appMatrix_[1];
VectorView R3 = appMatrix_[2];
// Setup spline vectors
X[0] = 0.0;
X[1] = 10.0;
X[2] = 20.0;
X[3] = 30.0;
Y2[0] = 0.00;
Y2[1] = R1[4];
Y2[2] = R2[4];
Y2[3] = R3[4];
Y4[0] = 0.00;
Y4[1] = R1[3];
Y4[2] = R2[3];
Y4[3] = R3[3];
Y25[0] = 0.00;
Y25[1] = R1[2];
Y25[2] = R2[2];
Y25[3] = R3[2];
Y50[0] = 0.00;
Y50[1] = R1[1];
Y50[2] = R2[1];
Y50[3] = R3[1];
Y75[0] = 0.00;
Y75[1] = R1[0];
Y75[2] = R2[0];
Y75[3] = R3[0];
// Calculate splines
SPN3( 4, X, Y2, S2 );
SPN3( 4, X, Y4, S4 );
SPN3( 4, X, Y25, S25 );
SPN3( 4, X, Y50, S50 );
SPN3( 4, X, Y75, S75 );
}
/****************************************************************************
*
* MineralInfo1::BreakRockRR( )
*
* Break a quantity of rock into a size distribution of daughter particles
* depending on the strength of a applied reduction ratio to the rock.
*
****************************************************************************/
double MineralInfo1::BreakRockRR
(
double& RockSize, // The size of the rocks to break
double& Quantity, // The mass/volume of the rocks to break
double& RR, // Reduction ratio to apply to the rocks
VectorView& Sieves, // Vector of sieve sizes
VectorView& Product // Fractional size distribution to add
) // breakage products to
{
// Convert RR into an Ecs
double Ecs = CalcEcs( RR );
// Convert Ecs into a T10
double T10 = CalcT10( Ecs );
// Break the rock into the Product[] size distribution
BreakRockT10( RockSize, Quantity, T10, Sieves, Product );
// Calculate energy required for breakage
return Quantity * Ecs;
}
/****************************************************************************
*
* MineralInfo1::BreakRockEcs( )
*
* Break a quantity of rock into a size distribution of daughter particles
* depending on the strength of a specific energy applied to the rock.
*
****************************************************************************/
double MineralInfo1::BreakRockEcs
(
double& RockSize, // The size of the rocks to break
double& Quantity, // The mass/volume of the rocks to break
double& Ecs, // Specific energy to apply
VectorView& Sieves, // Vector of sieve sizes
VectorView& Product // Fractional size distribution to add
) // breakage products to
{
// Convert Ecs into a T10
double T10 = CalcT10( Ecs );
// Break the rock into the Product[] size distribution
BreakRockT10( RockSize, Quantity, T10, Sieves, Product );
// Calculate energy required for breakage
return Quantity * Ecs;
}
/****************************************************************************
*
* MineralInfo1::BreakRockT10( )
*
* Break a quantity of rock into a size distribution of daughter particles
* depending on the value of T10 that is required of the product size
* distribution.
*
****************************************************************************/
void MineralInfo1::BreakRockT10
(
double& RockSize, // The size of the rocks to break
double& Quantity, // The mass/volume of the rocks to break
double& T10, // T10 required
VectorView& Sieves, // Vector of sieve sizes
VectorView& Product // Fractional size distribution to add
) // breakage products to
{
// Use pre-calculated splines to get T curve for this T10
PARAMT[0] = 100.0;
PARAMT[1] = SPNV3( 4, X, Y2, S2, T10 );
PARAMT[2] = SPNV3( 4, X, Y4, S4, T10 );
PARAMT[3] = T10;
PARAMT[4] = SPNV3( 4, X, Y25, S25, T10 );
PARAMT[5] = SPNV3( 4, X, Y50, S50, T10 );
PARAMT[6] = SPNV3( 4, X, Y75, S50, T10 );
// Construct size x percent-passing coordinates
YY[6] = log( PARAMT[0] );
YY[5] = log( PARAMT[1] );
YY[4] = log( PARAMT[2] );
YY[3] = log( PARAMT[3] );
YY[2] = log( PARAMT[4] );
YY[1] = log( PARAMT[5] );
YY[0] = log( PARAMT[6] );
XX[6] = log( RockSize / 1.0 );
XX[5] = log( RockSize / 2.0 );
XX[4] = log( RockSize / 4.0 );
XX[3] = log( RockSize / 10.0 );
XX[2] = log( RockSize / 25.0 );
XX[1] = log( RockSize / 50.0 );
XX[0] = log( RockSize / 75.0 );
// Calculate spline through size x percent passing
SPN3( 7, XX, YY, SS );
// Use spline to determine daughter product quantities
const int N = Sieves.size();
const int M = N-1;
double prevPassing = 100.00;
double scaleFactor = 0.01 * Quantity;
for( int i=0; i<N; i++ )
{
double ThisSize = Sieves[i];
double Passing = 100.0;
if( ThisSize >= RockSize )
{
Passing = 100.0;
}
else if( fabs(ThisSize)<1e-8 )
{
Passing = 0.0;
}
else
{
Passing = exp( SPNV3( 7, XX, YY, SS, log(ThisSize) ) );
if( Passing>100.00 ) Passing = 100.00;
if( Passing>prevPassing ) Passing = prevPassing;
}
Product[i] += scaleFactor * ( prevPassing - Passing );
prevPassing = Passing;
}
}
bool MineralInfo1::SetDefaultAppearance( )
{
// Matrix is three rows, five columns
appMatrix_.resize( 3, 5 );
// Reference appearance matrix rows
VectorView R1 = appMatrix_[0];
VectorView R2 = appMatrix_[1];
VectorView R3 = appMatrix_[2];
// Fill with default data
// R1[0]=1.90; R1[1]= 2.70; R1[2]= 5.30; R1[3]=19.80; R1[4]=42.40;
// R2[0]=4.50; R2[1]= 6.20; R2[2]=11.20; R2[3]=38.20; R2[4]=71.40;
// R3[0]=7.90; R3[1]=10.50; R3[2]=17.50; R3[3]=54.80; R3[4]=89.40;
R1[0]=2.00; R1[1]= 2.70; R1[2]= 4.70; R1[3]=27.90; R1[4]=55.90;
R2[0]=5.20; R2[1]= 6.70; R2[2]=10.50; R2[3]=49.30; R2[4]=81.40;
R3[0]=8.30; R3[1]=10.70; R3[2]=16.40; R3[3]=65.60; R3[4]=98.50;
// Compute appearance splines
AppearancePreCalc( );
return true;
}
//-- MineralInfo1.cpp -------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
340
]
]
]
|
e459ee8b311ba8754cfe0831bdead4d8418b8619 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgIntrospection/TypeNameAliasProxy | 3b4054cee11914184729289143ad13d9a7aa9508 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
//osgIntrospection - Copyright (C) 2005 Marco Jez
#ifndef OSGINTROSPECTION_TYPENAMEALIASPROXY_
#define OSGINTROSPECTION_TYPENAMEALIASPROXY_
#include <osgIntrospection/Type>
#include <osgIntrospection/Reflection>
#include <string>
#include <algorithm>
namespace osgIntrospection
{
template<typename C>
struct TypeNameAliasProxy
{
TypeNameAliasProxy(const std::string& name)
{
Type* type = Reflection::getOrRegisterType(extended_typeid<C>());
if (std::find(type->_aliases.begin(), type->_aliases.end(), name) == type->_aliases.end())
type->_aliases.push_back(name);
}
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
40
]
]
]
|
|
791de354dc12682865d10eb805448429b2bde48c | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch10/Fig10_10_14/Employee.h | 6ded37ea4094185a649c422d61e7838dc2224561 | []
| 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 | 1,711 | h | // Fig. 10.12: Employee.h
// Employee class definition showing composition.
// Member functions defined in Employee.cpp.
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include "Date.h" // include Date class definition
class Employee
{
public:
Employee( const char * const, const char * const,
const Date &, const Date & );
void print() const;
~Employee(); // provided to confirm destruction order
private:
char firstName[ 25 ];
char lastName[ 25 ];
const Date birthDate; // composition: member object
const Date hireDate; // composition: member object
}; // end class Employee
#endif
/**************************************************************************
* (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,
38
]
]
]
|
f53a0ffcfea4146477563b929a7cdfa3aa36be13 | 28476e6f67b37670a87bfaed30fbeabaa5f773a2 | /src/UnitTest/TypeManagerTest.h | a7fd66311856c53110c5be3257b760c40eb16ffc | []
| no_license | rdmenezes/autumnframework | d1aeb657cd470b67616dfcf0aacdb173ac1e96e1 | d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d | refs/heads/master | 2021-01-20T13:48:52.187425 | 2008-07-17T18:25:19 | 2008-07-17T18:25:19 | 32,969,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | h |
#ifndef AUTUMN_TYPEMANAGERTEST_H
#define AUTUMN_TYPEMANAGERTEST_H
#include <cppunit/extensions/HelperMacros.h>
#include "TypeManager.h"
using namespace CppUnit;
class TypeManagerTest: public TestFixture{
CPPUNIT_TEST_SUITE(TypeManagerTest);
CPPUNIT_TEST(testBasicType);
CPPUNIT_TEST(testCombinedType);
CPPUNIT_TEST(testTypeSetter);
CPPUNIT_TEST_SUITE_END();
class dumbBT: public IBasicType{
public:
void* createValue(const StrValueList& vl, StrIterator& it){return NULL;}
void freeValue(void* p){ delete p;}
};
class dumbCT: public ICombinedType{
public:
void* createValue(const StrValueList& vl, string basicType, StrIterator& it){return NULL;}
void freeValue(void* p, string basicType){ delete p;}
void freeSelfSpace(void* p){ delete p;}
};
TypeManager* tm;
public:
void setUp(){ this->tm = new TypeManager(); }
void tearDown(){ delete this->tm;}
void testBasicType();
void testCombinedType();
void testTypeSetter();
};
#endif
| [
"sharplog@c16174ff-a625-0410-88e5-87db5789ed7d"
]
| [
[
[
1,
41
]
]
]
|
d87f94793009929a17f4c8b51093ce6a9932bcf8 | 35231241243cb13bd3187983d224e827bb693df3 | /cgpsmapper/cpreview/vcgl_interface.h | 945f765f7c4baafcc352f1c6fa90df8c0c86ee0d | []
| no_license | casaretto/cgpsmapper | b597aa2775cc112bf98732b182a9bc798c3dd967 | 76d90513514188ef82f4d869fc23781d6253f0ba | refs/heads/master | 2021-05-15T01:42:47.532459 | 2011-06-25T23:16:34 | 2011-06-25T23:16:34 | 1,943,334 | 2 | 2 | null | 2019-06-11T00:26:40 | 2011-06-23T18:31:36 | C++ | UTF-8 | C++ | false | false | 1,096 | h | #ifndef vcgl_interfaceH
#define vcgl_interfaceH
#include <vector>
#include <algorithm>
#include "../../geograph.h"
using namespace std;
//: Return intersection of two polygons
void
vcgl_polygon_clip_intersect(vector< TinyPolygon* >const &a, vector< TinyPolygon* > const &b, vector< TinyPolygon* > &result, byte zoom_factor,int &num_fill, int &num_holes);
//: Return difference of two polygons: points in "a" and not in "b".
void vcgl_polygon_clip_subtract(vector< TinyPolygon* > const & a, vector< TinyPolygon* > const& b, vector< TinyPolygon* > &result, byte zoom_factor,int &num_fill, int &num_holes);
//: Return difference of two polygons: points in one and not in the other.
void vcgl_polygon_clip_xor(vector< TinyPolygon* > const& a, vector< TinyPolygon* > const& b, vector< TinyPolygon* > &result, byte zoom_factor,int &num_fill, int &num_holes);
//: Return union of polygons.
void vcgl_polygon_clip_union(vector< TinyPolygon* > const& a, vector< TinyPolygon* > const& b, vector< TinyPolygon* > &result, byte zoom_factor,int &num_fill, int &num_holes);
#endif
| [
"cgpsmapper@ad713ecf-6e55-4363-b790-59b81426eeec"
]
| [
[
[
1,
23
]
]
]
|
e6c71c0cb16eb839b67c8fa8748860acddc6bfab | 7745a8d148e55e22dca4955f7ca4e83199495c17 | /test/test_packrat_helper.hpp | a56213ecef88ddd1f91f78318eea9abe098e5245 | []
| no_license | yak1ex/packrat_qi | e6c8058e39a77d8f6c1559c292b52cdb14b8608f | 423d08e48abf1c06fd5f2acd812295ec6e1b3d11 | refs/heads/master | 2020-06-05T02:57:45.157294 | 2011-06-28T17:24:46 | 2011-06-28T17:24:46 | 1,967,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,931 | hpp | /***********************************************************************/
/* */
/* test_packrat_helper.hpp: Test code helper for Packrat parser */
/* */
/* Written by Yak! / Yasutaka ATARASHI */
/* */
/* This software is distributed under the terms of */
/* Boost Software License 1.0 */
/* (http://www.boost.org/LICENSE_1_0.txt). */
/* */
/* $Id$ */
/* */
/***********************************************************************/
#ifndef YAK_SPIRIT_PACKRAT_TEST_PACKRAT_HELPER_HPP
#define YAK_SPIRIT_PACKRAT_TEST_PACKRAT_HELPER_HPP
#include <cstddef>
#include <iostream>
#include <sstream>
#include "any_key.hpp"
namespace yak { namespace spirit { namespace debug {
class trace
{
public:
static bool enable;
static void begin() {}
static void end() {}
static void before(std::ptrdiff_t pos, std::size_t hash_code, std::size_t hit, std::size_t size)
{
if(!enable) return;
std::cerr << "[before] position: " << pos << " : " << hash_code << std::endl;
std::cerr << "[before] table.count(key): " << hit << std::endl;
std::cerr << "[before] table.size(): " << size << std::endl;
}
static void after(std::ptrdiff_t pos, std::size_t hash_code, std::size_t hit, std::size_t size)
{
if(!enable) return;
std::cerr << "[after] position: " << pos << " : " << hash_code << std::endl;
std::cerr << "[after] table.count(key): " << hit << std::endl;
std::cerr << "[after] table.size(): " << size << std::endl;
}
static void hit_success(std::ptrdiff_t pos, std::size_t hash_code, const std::type_info* type_from, const std::type_info* type_to, const yak::util::any_key& k)
{
if(!enable) return;
std::cerr << "[hit_success] position: " << pos << " : " << hash_code << std::endl;
std::cerr << "[hit_success] type_from: " << type_from->name() << " type_to: " << type_to->name() << std::endl;
}
static void hit_fail(std::ptrdiff_t pos, std::size_t hash_code)
{
if(!enable) return;
std::cerr << "[hit_fail] position: " << pos << " : " << hash_code << std::endl;
}
static void parse_success(std::ptrdiff_t pos, std::size_t hash_code, const std::type_info* type_from, const std::type_info* type_to, const yak::util::any_key &k)
{
if(!enable) return;
std::cerr << "[parse_success] position: " << pos << " : " << hash_code << std::endl;
std::cerr << "[parse_success] type_from: " << type_from->name() << " type_to: " << type_to->name() << std::endl;
}
static void parse_fail(std::ptrdiff_t pos, std::size_t hash_code)
{
if(!enable) return;
std::cerr << "[parse_fail] position: " << pos << " : " << hash_code << std::endl;
}
struct enabler
{
enabler(bool = true) { begin(); enable = true; }
~enabler() { enable = false; }
operator bool() { return true; }
};
};
class count
{
public:
static bool enable;
static void begin()
{
hit_success_ = hit_fail_ = parse_success_ = parse_fail_ = 0;
}
static void end() {}
static void before(std::ptrdiff_t pos, std::size_t hash_code, std::size_t hit, std::size_t size)
{}
static void after(std::ptrdiff_t pos, std::size_t hash_code, std::size_t hit, std::size_t size)
{}
static void hit_success(std::ptrdiff_t pos, std::size_t hash_code, const std::type_info* type_from, const std::type_info* type_to, const yak::util::any_key& k)
{
if(!enable) return;
++hit_success_;
}
static void hit_fail(std::ptrdiff_t pos, std::size_t hash_code)
{
if(!enable) return;
++hit_fail_;
}
static void parse_success(std::ptrdiff_t pos, std::size_t hash_code, const std::type_info* type_from, const std::type_info* type_to, const yak::util::any_key &k)
{
if(!enable) return;
++parse_success_;
}
static void parse_fail(std::ptrdiff_t pos, std::size_t hash_code)
{
if(!enable) return;
++parse_fail_;
}
static void out(std::ostream &os)
{
os << "hit_success: " << hit_success_ << std::endl;
os << "hit_fail: " << hit_fail_ << std::endl;
os << "parse_sucess: " << parse_success_ << std::endl;
os << "parse_fail: " << parse_fail_ << std::endl;
}
static int hit_success_;
static int hit_fail_;
static int parse_success_;
static int parse_fail_;
struct enabler
{
enabler(bool = true) { begin(); enable = true; }
~enabler() { enable = false; }
operator bool() { return true; }
};
};
template<typename New, typename Base>
struct combine
{
struct enabler
{
enabler(bool = true)
{
begin();
New::enable = Base::enable = true;
}
~enabler()
{
New::enable = Base::enable = false;
}
operator bool() { return true; }
};
static void begin()
{ New::begin(); Base::begin(); }
static void end()
{ New::end(); Base::end(); }
static void before(std::ptrdiff_t pos, std::size_t hash_code, std::size_t hit, std::size_t size)
{
New::before(pos, hash_code, hit, size);
Base::before(pos, hash_code, hit, size);
}
static void after(std::ptrdiff_t pos, std::size_t hash_code, std::size_t hit, std::size_t size)
{
New::after(pos, hash_code, hit, size);
Base::after(pos, hash_code, hit, size);
}
static void hit_success(std::ptrdiff_t pos, std::size_t hash_code, const std::type_info* type_from, const std::type_info* type_to, const yak::util::any_key& k)
{
New::hit_success(pos, hash_code, type_from, type_to, k);
Base::hit_success(pos, hash_code, type_from, type_to, k);
}
static void hit_fail(std::ptrdiff_t pos, std::size_t hash_code)
{
New::hit_fail(pos, hash_code);
Base::hit_fail(pos, hash_code);
}
static void parse_success(std::ptrdiff_t pos, std::size_t hash_code, const std::type_info* type_from, const std::type_info* type_to, const yak::util::any_key &k)
{
New::parse_success(pos, hash_code, type_from, type_to, k);
Base::parse_success(pos, hash_code, type_from, type_to, k);
}
static void parse_fail(std::ptrdiff_t pos, std::size_t hash_code)
{
New::parse_fail(pos, hash_code);
Base::parse_fail(pos, hash_code);
}
};
extern std::stringstream test_ss;
}}}
#define BOOST_SPIRIT_DEBUG_OUT yak::spirit::debug::test_ss
#define YAK_SPIRIT_PACKRAT_DEBUG_CLASS yak::spirit::debug::count
#define YAK_SPIRIT_PACKRAT_TEST_BLOCK if(YAK_SPIRIT_PACKRAT_DEBUG_CLASS::enabler enabler ## __FILE__ ## __LINE__ = true)
#endif
| [
"[email protected]"
]
| [
[
[
1,
189
]
]
]
|
2c051f1814b1a13faf517ac7d5507a252a9232f6 | 9e4a5ffa0cdd3556730f82ffc4fe73c0d360ec8a | /Texture.h | cc81e64cd265a3f0472c6b177c0e09c523b6a7a5 | []
| no_license | ANorwell/Graphics | fde4e946ab2d6f3cd7ddc6daab1a847a49665475 | bbe73045b1fc83c2704a1881a7dd336f94388722 | refs/heads/master | 2021-01-19T13:53:07.549762 | 2010-09-06T04:49:02 | 2010-09-06T04:49:02 | 890,587 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | h | #pragma once
#include <string>
#include <vector>
#include <GL/glut.h>
#include "Util.h"
class TextureData {
private:
std::string pFilename;
protected:
unsigned int pHeight;
unsigned int pWidth;
public:
TextureData(std::string aFile) : pFilename(aFile),
pHeight(0),
pWidth(0) {};
//pure virtual functions to be subclassed
virtual unsigned char* getData() = 0;
virtual void setGLParams(GLuint aId) = 0;
virtual unsigned int getHeight() { return pHeight; }
virtual unsigned int getWidth() { return pWidth; }
const std::string& getFilename() { return pFilename; };
virtual ~TextureData() {};
};
class BMPData : public TextureData {
private:
unsigned char * pData;
enum { BMP_DATA_OFFSET = 0x36 };
public:
BMPData(std::string aFilename);
unsigned char* getData();
void setGLParams(GLuint aId);
~BMPData();
};
class RAWData : public TextureData {
private:
unsigned char * pData;
public:
RAWData(std::string aFilename,
unsigned int aHeight,
unsigned int aWidth);
unsigned char* getData();
void setGLParams(GLuint aId);
~RAWData();
};
| [
"[email protected]"
]
| [
[
[
1,
63
]
]
]
|
1d905ced6d78386cf6949294ad9fe9aeb502890a | 119ba245bea18df8d27b84ee06e152b35c707da1 | /unreal/branches/robots/qrgui/interpreters/robots/details/robotImplementations/sensorImplementations/nullSonarSensorImplementation.h | 84c95a13d5d9f95eef7ead2148c5d6fe103fdb5d | []
| no_license | nfrey/qreal | 05cd4f9b9d3193531eb68ff238d8a447babcb3d2 | 71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164 | refs/heads/master | 2020-04-06T06:43:41.910531 | 2011-05-30T19:30:09 | 2011-05-30T19:30:09 | 1,634,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | h | #pragma once
#include "nullSensorImplementation.h"
namespace qReal {
namespace interpreters {
namespace robots {
namespace details {
namespace robotImplementations {
namespace sensorImplementations {
class NullSonarSensorImplementation : public NullSensorImplementation
{
Q_OBJECT
public:
NullSonarSensorImplementation(inputPort::InputPortEnum const &port);
protected slots:
virtual void timerTimeout();
};
}
}
}
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
ac411cee5c0726d8c92f6bd59c6100ac4f2002f2 | a699a508742a0fd3c07901ab690cdeba2544a5d1 | /RailwayDetection/RWDSClient/DataService.cpp | 274d5737269e1ac6790de7eb97c7dd60029f331a | []
| no_license | xiaomailong/railway-detection | 2bf92126bceaa9aebd193b570ca6cd5556faef5b | 62e998f5de86ee2b6282ea71b592bc55ee25fe14 | refs/heads/master | 2021-01-17T06:04:48.782266 | 2011-09-27T15:13:55 | 2011-09-27T15:13:55 | 42,157,845 | 0 | 1 | null | 2015-09-09T05:24:10 | 2015-09-09T05:24:09 | null | GB18030 | C++ | false | false | 45,800 | cpp | #include "StdAfx.h"
#include "DataService.h"
#include "ErrorDefine.h"
#include "CmdDefine.h"
#include "cData.h"
#define TESTCODE
int VerifyLogin( CString& aLoginAccount, CString& aLoginPassword, int* orgID, PermissionGroup *pPower)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
*orgID = 1;
pPower->iBasical = 0x0FFF;
//pPower->iBasical = 3967;
pPower->iOperate = 1;
pPower->iReportForm = 1;
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
char *UserName = (LPSTR)(LPCTSTR)aLoginAccount;
char *PassWord = (LPSTR)(LPCTSTR)aLoginPassword;
//aLoginAccount.GetBuffer();
int iOrgid,p1,p2,p3;
int iResult = cd->UserLog(aLoginAccount.GetBuffer(),aLoginPassword.GetBuffer(),&iOrgid,&p1,&p2,&p3);
if(iResult == 0)
{
*orgID = iOrgid;
pPower->iBasical = p1;
pPower->iOperate = p2;
pPower->iReportForm = p3;
if (iOrgid <= 0)
{
iResult = KErrNotFound;
}
}
aLoginAccount.ReleaseBuffer();
aLoginPassword.ReleaseBuffer();
return iResult;
}
int GetSystemConfigure(SystemConfigure* aGetConfigure)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
return KErrNone;
// int SetSys(const sysBak sValue);
//int GetSys(sysBak* sValue);
sysBak sValue;
memset(&sValue,0,sizeof(sysBak));
cData *cd = new cData();
cd->GetSys(&sValue);
aGetConfigure->iAlarmMinute = sValue.bak;
aGetConfigure->iDuration = sValue.dataBak;
return 1;
}
int SetSystemConfigure(const SystemConfigure* aGetConfigure)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
return KErrNone;
cData *cd = new cData();
sysBak sValue;
memset(&sValue,0,sizeof(sysBak));
sValue.bak = aGetConfigure->iAlarmMinute;
sValue.dataBak = aGetConfigure->iDuration;
cd->SetSys(sValue);
return 1;
}
int GetRailLine( vector<RailLine*>* aRailLineList )
{
RailLine* root = new RailLine;
root->iRailID = 0;
root->iRailName = _T("未知线路");
aRailLineList->push_back(root);
///////////////////////////////////////////////////
#ifdef TESTCODE
RailLine* rail = new RailLine;
rail->iRailID = 1;
rail->iRailName = _T("宝成线");
aRailLineList->push_back(rail);
rail = new RailLine;
rail->iRailID = 2;
rail->iRailName = _T("成昆线");
aRailLineList->push_back(rail);
rail = new RailLine;
rail->iRailID = 3;
rail->iRailName = _T("成渝线");
aRailLineList->push_back(rail);
rail = new RailLine;
rail->iRailID = 4;
rail->iRailName = _T("成东线");
aRailLineList->push_back(rail);
rail = new RailLine;
rail->iRailID = 5;
rail->iRailName = _T("成西线");
aRailLineList->push_back(rail);
return KErrNone;
#endif
///////////////////////////////////////////////////
GetLinesName val;
val.LineId = 0;
lLineName llist;
cData *cd = new cData();
cd->GetLineName(val,&llist);
for(iterLineName iter = llist.begin(); iter != llist.end() ; iter++)
{
RailLine* report = new RailLine();
report->iRailName = iter->cName;
report->iRailID = iter->id;
aRailLineList->push_back(report);
}
delete cd;
return 0;
}
int SetRailLine( int aCmd, const RailLine* aRailLine )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
lines sValue;
switch(aCmd){
case CMD_RAIL_ADD:
{
sValue.iTpye = 0;
CString cTEMP1 = aRailLine->iRailName;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(sValue.name,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
sValue.id = aRailLine->iRailID;
cd->LinesMang(&sValue);
break;
}
case CMD_RAIL_MODIFY:
{
sValue.iTpye = 1;
CString cTEMP1 = aRailLine->iRailName;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(sValue.name,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
sValue.id = aRailLine->iRailID;
cd->LinesMang(&sValue);
break;
}
case CMD_RAIL_DELETE:
{
sValue.iTpye = 2;
CString cTEMP1 = aRailLine->iRailName;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(sValue.name,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
sValue.id = aRailLine->iRailID;
cd->LinesMang(&sValue);
break;
}
default:
break;
}
return KErrNone;
}
RailLine* GetRailLineByID(vector<RailLine*>& aRailLineList, int aRailID )
{
RailLine* retValue = aRailLineList[0];
for (size_t i=0; i<aRailLineList.size(); i++)
{
if (aRailID == aRailLineList[i]->iRailID)
{
retValue = aRailLineList[i];
break;
}
}
return retValue;
}
RailLine* GetRailLineByName(vector<RailLine*>& aRailLineList, CString aRailName )
{
RailLine* retValue = aRailLineList[0];
for (size_t i=0; i<aRailLineList.size(); i++)
{
if (aRailName == aRailLineList[i]->iRailName)
{
retValue = aRailLineList[i];
break;
}
}
return retValue;
}
int GetOrgTree(const int OrgId, vector<OrganizationInfo*>* a_OrgTree)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
OrganizationInfo* org = new OrganizationInfo;
org->iOrgName = _T("Admin");
org->iParentOrg = NULL;
org->iParentID = 0;
org->iOrgID = 1;
org->iBoundaryRail = 1;
org->iChildID.push_back(2);
org->iChildID.push_back(3);
a_OrgTree->push_back(org);
org = new OrganizationInfo;
org->iOrgName = _T("Child1");
org->iParentOrg = (*a_OrgTree)[0];
org->iParentID = org->iParentOrg->iOrgID;
(*a_OrgTree)[0]->iChildOrg.push_back(org);
org->iOrgID = 2;
org->iBoundaryRail = 2;
org->iChildID.push_back(4);
a_OrgTree->push_back(org);
org = new OrganizationInfo;
org->iOrgName = _T("Child2");
org->iParentOrg = (*a_OrgTree)[0];
org->iParentID = org->iParentOrg->iOrgID;
(*a_OrgTree)[0]->iChildOrg.push_back(org);
org->iBoundaryRail = 3;
org->iOrgID = 3;
org->iChildID.push_back(5);
a_OrgTree->push_back(org);
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
lOrg pOrg;
int iResult = cd->GetOrgList(OrgId,&pOrg);
if(iResult < 1)
{
return -1;
}
for(iterOrg iter = pOrg.begin() ; iter !=pOrg.end() ;iter++)
{
OrganizationInfo* org = new OrganizationInfo;
org->iOrgName= iter->OrgName;
org->iOrgAddress = iter->Address;
org->iParentID = iter->UpOrg ;
org->iOrgLevel = iter->iLevel;
org->iParentOrg = NULL;
org->iOrgID = iter->OrgId;
org->iBoundaryRail = iter->LineId ;
org->iBoundaryStartKM = iter->startid ;
org->iBoundaryEndKM = iter->EndID;
a_OrgTree->push_back(org);
}
for(vector<OrganizationInfo*>::iterator iterOrg = a_OrgTree->begin() ; iterOrg != a_OrgTree->end() ; iterOrg++)
{
CherkOrgType(a_OrgTree,*iterOrg);
}
delete cd;
return KErrNone;
}
void CherkOrgType(vector<OrganizationInfo*>* a_OrgTree,OrganizationInfo* OrgInfo)
{
for(vector<OrganizationInfo*>::iterator iterOrg = a_OrgTree->begin() ; iterOrg != a_OrgTree->end() ; iterOrg++)
{
//获取下属机构
if(OrgInfo->iOrgID == (*iterOrg)->iParentID)
{
OrgInfo->iChildID.push_back((*iterOrg)->iOrgID);
}
//获取上级机构
if(OrgInfo->iParentID ==(*iterOrg)->iOrgID )
{
OrgInfo->iParentOrg = *iterOrg;
(*iterOrg)->iChildOrg.push_back(OrgInfo);
}
}
return;
}
int SetOrganization(int aCmd, const OrganizationInfo* aOrganization )
{
int iResult;
cData *cd = new cData();
switch(aCmd)
{
case CMD_ORG_ADD:
{
AddOrg aOrg;
memset(&aOrg,0,sizeof(AddOrg));
aOrg.UpOrg = aOrganization->iParentID ;
aOrg.iLevel = aOrganization->iOrgLevel ;
aOrg.LineId = aOrganization->iBoundaryRail;
aOrg.startid = aOrganization->iBoundaryStartKM;
aOrg.EndID = aOrganization->iBoundaryEndKM;
char *p1;
CString cTEMP = aOrganization->iOrgAddress;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&aOrg.Address,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
cTEMP = aOrganization->iOrgName;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&aOrg.OrgName,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
iResult = cd->AddOrgs(&aOrg);
cTEMP.ReleaseBuffer();
break;
}
case CMD_ORG_MODIFY:
{
EditOrg eOrg;
memset(&eOrg,0,sizeof(EditOrg));
eOrg.UpOrg = aOrganization->iParentID ;
eOrg.iLevel = aOrganization->iOrgLevel ;
eOrg.LineId = aOrganization->iBoundaryRail;
eOrg.startid = aOrganization->iBoundaryStartKM;
eOrg.EndID = aOrganization->iBoundaryEndKM;
eOrg.OrgId = aOrganization->iOrgID ;
char *p1;
CString cTEMP = aOrganization->iOrgAddress;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&eOrg.Address,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
cTEMP = aOrganization->iOrgName;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&eOrg.OrgName,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
iResult = cd->EditOrgs(&eOrg);
break;
}
case CMD_ORG_DELETE:
DelOrg dOrg;
dOrg.OrgId = aOrganization->iOrgID;
iResult = cd->DelOrgs(&dOrg);
break;
default:
break;
}
return KErrNone;
}
//获取机构有效巡检范围 比如 成昆铁路 1- 8K出
int GetOrgPoint(int aOrgID, vector<RailLine*>& aRailLineList, vector<MapPoint*>* aPointList)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
MapPoint *pt = new MapPoint;
pt->iRailLine = aRailLineList[1];
pt->iKM = 251;
pt->iLon = 104.064531;
pt->iLat = 30.699965;
pt->iDirect = KUpLine;
aPointList->push_back(pt);
pt = new MapPoint;
pt->iRailLine = aRailLineList[1];
pt->iKM = 252;
pt->iLon = 104.075530;
pt->iLat = 30.699484;
pt->iDirect = KUpLine;
aPointList->push_back(pt);
pt = new MapPoint;
pt->iRailLine = aRailLineList[1];
pt->iKM = 253;
pt->iLon = 104.086526;
pt->iLat = 30.699484;
pt->iDirect = KUpLine;
aPointList->push_back(pt);
pt = new MapPoint;
pt->iRailLine = aRailLineList[1];
pt->iKM = 254;
pt->iLon = 104.097521;
pt->iLat = 30.699484;
pt->iDirect = KUpLine;
aPointList->push_back(pt);
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
lOrgLine llist;
if(cd->GetOrgPoint(aOrgID,&llist) > 0)
{
for(iterOrgLine iter = llist.begin() ; iter != llist.end() ; iter++)
{
MapPoint *pt = new MapPoint;
pt->iRailLine = GetRailLineByID(aRailLineList, iter->lineid);
pt->iKM = iter->gls;
pt->iLat = iter->wdu;
pt->iLon = iter->jdu;
pt->iPointId = iter->iPoint;
if(iter->iState == 1)
pt->iDirect = KDownLine;
else
pt->iDirect = KUpLine;
aPointList->push_back(pt);
//delete pt;
}
return ResultOk;
}else
{
return KErrNone;
}
}
int SetOrgPoint( int aOrgID, int aCmd, const MapPoint* aPoint )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
int iResult = 0;
PointMang pPoint;
switch (aCmd)
{
case CMD_POINT_ADD:
{
pPoint.iDirect = (int)aPoint->iDirect;
pPoint.iKM = aPoint->iKM;
pPoint.iLat = aPoint->iLat;
pPoint.iLon = aPoint->iLon;
pPoint.iRailLine = aPoint->iRailLine->iRailID;
pPoint.itype = 0;//tianjia
pPoint.PointId = aPoint->iPointId;
iResult=cd->setPoint(pPoint);
break;
}
case CMD_POINT_MODIFY:
{
pPoint.iDirect = (int)aPoint->iDirect;
pPoint.iKM = aPoint->iKM;
pPoint.iLat = aPoint->iLat;
pPoint.iLon = aPoint->iLon;
pPoint.iRailLine = aPoint->iRailLine->iRailID;
pPoint.itype = 1;//tianjia
pPoint.PointId = aPoint->iPointId;
iResult=cd->setPoint(pPoint);
break;
}
case CMD_POINT_DELETE:
{
pPoint.PointId = aPoint->iPointId;
pPoint.itype = 2;//tianjia
iResult=cd->setPoint(pPoint);
break;
}
default:
break;
}
delete cd;
return iResult;//设置正常,返回点ID
}
int GetOrgLine(int aOrgID, const vector<MapPoint*>& aPointList, vector<LineInfo*>* aLineList)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
LineInfo *line = new LineInfo;
line->iLineID = 1;
line->iLineName = _T("成局1段");
line->iStartKm = (aPointList)[0]->iKM;
line->iStartNo = KFirstDay;
line->iLineKmLonLat.push_back(aPointList[0]);
line->iLineKmTime.push_back(100);
line->iLineKmLonLat.push_back(aPointList[1]);
line->iLineKmTime.push_back(100);
line->iLineKmLonLat.push_back(aPointList[2]);
line->iLineKmTime.push_back(100);
line->iLineKmLonLat.push_back(aPointList[3]);
line->iLineKmTime.push_back(100);
aLineList->push_back(line);
line = new LineInfo;
line->iLineID = 2;
line->iLineName = _T("成局2段");
line->iStartKm = aPointList[1]->iKM;
line->iStartNo = KThirdDay;
line->iLineKmLonLat.push_back(aPointList[1]);
line->iLineKmTime.push_back(0);
line->iLineKmLonLat.push_back(aPointList[3]);
line->iLineKmTime.push_back(0);
aLineList->push_back(line);
return KErrNone;
#endif
///////////////////////////////////////////////////
aLineList->clear();
lallOrgLine llist ;
Orglines ol;
ol.orgid = aOrgID;
cData *cd = new cData();
if(1 == cd->GetOrgLine(ol,&llist))
{
for(riterOrgLine iter = llist.begin() ; iter != llist.end() ; iter++)
{
LineInfo *line = new LineInfo;
//memset(line,0,sizeof(LineInfo));
line->iLineID = iter->lineid;
line->iLineName = iter->line;
line->iStartNo = (LineStartNo)iter->lindday;
//int rGetLineTime(const rLinePointTime sValue,lrLinePointTimeResult *llist);
rLinePointTime sValue;
sValue.lineid = line->iLineID ; //
line->iOrgID = aOrgID;
lrLinePointTimeResult llists ;
if(0 == cd->rGetLineTime(sValue,&llists))
{
int i = llists.size();
for(iterrLinePointTime it = llists.begin() ; it!= llists.end() ;it++)
{
MapPoint *mp;
//mp->iDirect = (LineDirect)it->iDirect;
//mp->iKM = it->iKM;
//mp->iLat = it->iLat;
//mp->iLon = it->iLon;
//mp->iRailLine = (RailLine)sValue.lineid;
//mp->PointId = it->PointId;
bool find= false;
for(size_t i=0; i<aPointList.size(); i++)
{
if(aPointList[i]->iPointId == it->PointId)
{
find = true;
mp = aPointList[i];
break;
}
}
if(find)
{
line->iLineKmLonLat.push_back(mp);
line->iLineKmTime.push_back(Time2Strings1(it->time));
}
//delete mp;
}
}
aLineList->push_back(line);
//delete line;
}
}
return 1;
}
int SetOrgLine( int aOrgID, int aCmd, const LineInfo* aLine )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
//#define CMD_LINE_ADD 0x33
//#define CMD_LINE_MODIFY 0x34
//#define CMD_LINE_DELETE 0x35
cData *cd = new cData();
MangLine Ml;
int iResult = 0;
memset(&Ml,0,sizeof(MangLine));
switch(aCmd)
{
case CMD_LINE_ADD:
{
Ml.type = 0;
Ml.day = aLine->iStartNo;
Ml.orgid = aLine->iOrgID;
//char *pTemp = (LPSTR)(LPCTSTR)aLine->iLineName;
//memcpy(&Ml.cName,pTemp,sizeof(pTemp));
//Ml.cName = aLine->iLineName.GetBuffer();
CString cTEMP = aLine->iLineName;
char *p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&Ml.cName,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
iResult = cd->SetMangLine(Ml);
break;
}
case CMD_LINE_MODIFY:
{
Ml.type = 1;
Ml.day = aLine->iStartNo;
Ml.orgid = aLine->iOrgID;
Ml.id = aLine->iLineID;
//char *pTemp = (LPSTR)(LPCTSTR)aLine->iLineName;
//memcpy(&Ml.cName,pTemp,sizeof(pTemp));
//Ml.cName = aLine->iLineName.GetBuffer();
CString cTEMP = aLine->iLineName;
char *p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&Ml.cName,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
iResult = cd->SetMangLine(Ml);
if(iResult == 0) //增加点和时间
{
Sleep(2);
int iPointSize = aLine->iLineKmLonLat.size();
for(int i = 0;i < iPointSize ;i++)
{//
int iPoint = aLine->iLineKmLonLat[i]->iPointId;
time_t sec = aLine->iLineKmTime[i];
int iHour,iMin;
CTime t(sec);
iHour = t.GetHour();
iMin = t.GetMinute();
CString cs;
cs.Format(_T("%d:%d"),iHour,iMin);
xj pb;
memset(&pb,0,sizeof(xj));
pb.type = 0;
pb.lineid = aLine->iLineID;
pb.pointed = iPoint;
//char *pTemp = (LPSTR)(LPCTSTR)cs;
//Time2Strings1
CString cTEMP = cs;
char *p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&pb.time,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
//memcpy(&pb.time,pTemp,sizeof(pTemp));
cd->SetxjTime(pb);
}
//;
}
break;
}
case CMD_LINE_DELETE:
{
Ml.type = 2;
Ml.id = aLine->iLineID;
iResult = cd->SetMangLine(Ml);
break;
}
}
delete cd;
if(iResult==1)
{
return KErrNone;
}else
return ResultOk;
}
int GetOrgStaff(int aOrgID, const vector<DeviceInfo*>& aDeviceList, vector<StaffInfo*>* aStaffList)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
StaffInfo* staff = new StaffInfo;
staff->iID = _T("1");
staff->iOrgID = aOrgID;
staff->iPassword = _T("111");
staff->iLoginPermission = TRUE;
staff->iName = _T("张三");
staff->iPermissionGroup = 0;
if (aDeviceList.size() > 0)
{
staff->iTakeDevice = aDeviceList[0];
}
aStaffList->push_back(staff);
staff = new StaffInfo;
staff->iID = _T("2");;
staff->iOrgID = aOrgID;
staff->iPassword = _T("");
staff->iLoginPermission = FALSE;
staff->iName = _T("李四");
staff->iPermissionGroup = 0;
if (aDeviceList.size() > 0)
{
staff->iTakeDevice = aDeviceList[0];
}
aStaffList->push_back(staff);
staff = new StaffInfo;
staff->iID = _T("3");;
staff->iOrgID = aOrgID;
staff->iName = _T("王五");
staff->iPassword = _T("");
staff->iLoginPermission = FALSE;
staff->iPermissionGroup = 0;
if (aDeviceList.size() > 0)
{
staff->iTakeDevice = aDeviceList[0];
}
aStaffList->push_back(staff);
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
lUser lPoint;
if(cd->GetUserList(aOrgID,1,&lPoint) > 0)
{
for(iterUser iter = lPoint.begin() ; iter != lPoint.end() ; iter++)
{
StaffInfo* staff = new StaffInfo;
staff->iID = iter->Oper;
staff->iOrgID = iter->orgid;
staff->iPassword = _T("");
staff->iLoginPermission = TRUE;
staff->iName = iter->name;
for (size_t i=0; i<aDeviceList.size(); i++)
{
if (aDeviceList[i]->iDevID == iter->pda1)
{
staff->iTakeDevice = aDeviceList[i];
break;
}
}
staff->iPermissionGroup = iter->PowerGroup ;
aStaffList->push_back(staff);
}
return ResultOk;
}
return KErrNone;
}
int SetOrgStaff( int aOrgID, int aCmd, const StaffInfo* aStaff )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
// aStaff->
/*
#define CMD_STAFF_ADD 0x36
#define CMD_STAFF_MODIFY 0x37
#define CMD_STAFF_DELETE 0x38
*/
int iResult = 0;
cData *cd = new cData();
switch(aCmd)
{
case CMD_STAFF_ADD:
{
AddUser aUser;
memset(&aUser,0,sizeof(AddUser));
//char *pTemp = (LPSTR)(LPCTSTR)aStaff->iName;
//memcpy(&aUser.name,pTemp,sizeof(pTemp));
//pTemp = (LPSTR)(LPCTSTR)aStaff->iID;
//memcpy(&aUser.Oper,pTemp,sizeof(pTemp));
//aUser.name = aStaff->iName.GetBuffer();
//aUser.Oper = aStaff->iID.GetBuffer();
char *p1;
CString cTEMP = aStaff->iID;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&aUser.Oper,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
cTEMP = aStaff->iName;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&aUser.name,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
aUser.orgid = aStaff->iOrgID;
aUser.pda1 = 0;//aStaff->iTakeDevice->iDevID;
//aUser.pda2 = aStaff->iTakeDevice->iDevID;
aUser.PowerGroup = aStaff->iPermissionGroup;
int iLogin = 1;
if(aStaff->iLoginPermission)iLogin = 1;
else iLogin = 0;
aUser.UserState = iLogin;
iResult = cd->AddUsers(&aUser);
break;
}
case CMD_STAFF_MODIFY:
{
EditUser eUser;
memset(&eUser,0,sizeof(EditUser));
char *p1;
CString cTEMP = aStaff->iID;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&eUser.Oper,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
cTEMP = aStaff->iName;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&eUser.name,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
eUser.orgid = aStaff->iOrgID;
eUser.pda1 = 0;
if(aStaff->iTakeDevice)
eUser.pda1 = aStaff->iTakeDevice->iDevID;
eUser.PowerGroup = aStaff->iPermissionGroup;
int iLogin = 1;
if(aStaff->iLoginPermission)iLogin = 1;
else iLogin = 0;
eUser.UserState = iLogin;
iResult = cd->EditUsers(&eUser);
break;
}
case CMD_STAFF_DELETE:
{
DelUser dUser;
memset(&dUser,0,sizeof(DelUser));
char *p1 ;
CString cTEMP = aStaff->iID;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&dUser.Oper,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
iResult = cd->DelUsers(&dUser);
//aStaff->iID.ReleaseBuffer();
break;
}
}
return iResult;
}
int SetStaffPassword(int aOrgID, CString aStaffID, CString aPassword)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
CPassRequest sValue;
memset(&sValue,0,sizeof(CPassRequest));
CString cTEMP1 = aStaffID;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(sValue.oper,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
CString cTEMP2 = aPassword;
char *p3 = (char*)cTEMP2.GetBuffer(cTEMP2.GetLength());
memcpy(sValue.password,p3,cTEMP2.GetLength());
cTEMP2.ReleaseBuffer();
cData *cd = new cData();
cd->ChaengPassWord(&sValue);
return KErrNone;
}
//获取排版下 实际线路ID
int GetCalendarSchedule(int aOrgID, const vector<StaffInfo*>* ListStaff, CalendarSchedule* aSchedule)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
aSchedule->iCaledarID = 1;
aSchedule->iOrgID = aOrgID;
aSchedule->iStartDay = 1288915200;
aSchedule->iPeriods = 3;
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
OrgPxInfo oInfo ;
oInfo.Orgid = aOrgID;
GetOrgPxInfo llist ;
memset(&llist,0,sizeof(GetOrgPxInfo));
cd->GetOrgpInfo(oInfo,&llist);
aSchedule->iCaledarID = llist.id ;
aSchedule->iOrgID = aOrgID;
aSchedule->iPeriods = llist.cyc;
aSchedule->iScheduleRemark = llist.content;
aSchedule->iStartDay = Time2Strings2(llist.stime);
rOrgPB pb;
pb.orgid = aOrgID;
lUser lPoint;
if(cd->rGetOPb(pb,&lPoint) > 0)
{
for(iterUser iter = lPoint.begin() ; iter != lPoint.end() ; iter++)
{
StaffInfo* staff;// = new StaffInfo;
BOOL find = FALSE;
for (size_t i=0; i<ListStaff->size(); i++)
{
staff = (*ListStaff)[i];
if (staff->iID.Compare(iter->Oper) == 0)
{
find = TRUE;
break;
}
}
if (find)
{
aSchedule->iScheduleStaff.push_back(staff);
}
}
return ResultOk;
}
//int cData::rGetOPb(const rOrgPB sValue,lUser *lPoint)
delete cd;
return KErrNone;
}
//
int SetCalendarSchedule(int aOrgID, const CalendarSchedule* aSchedule/*, const <StaffInfo*>*ListStaff*/)
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
pb *p = new pb();
memset(p,0,sizeof(pb));
p->cyc = aSchedule->iPeriods;
p->id = aSchedule->iCaledarID;
p->orgid = aSchedule->iOrgID;
p->type = 1;
char *p2 ;
CString cTEMP1 = aSchedule->iScheduleRemark;
p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(p->content,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
cd->SetpxPb(*p);
int iOrder = 1;
for(vector<StaffInfo*>::iterator iter = ((CalendarSchedule*)aSchedule)->iScheduleStaff.begin();iter != aSchedule->iScheduleStaff.end();iter++)
{
pbpp pp;
memset(&pp,0,sizeof(pbpp));
pp.ppid = aSchedule->iCaledarID;
pp.px = iOrder;
char *p1 ;
CString cTEMP = (*iter)->iID;
p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(pp.ryid,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
cd->SetpxOrder(pp);
(*iter)->iID.ReleaseBuffer();
iOrder++;
}
delete cd;
return KErrNone;
}
int GetEmergencyTask( int aOrgID, vector<EmergencyTaskInfo*>* m_EmergencyList )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
ljjListresult lPoint;
cData *cs = new cData();
cs->GetJJRWList(aOrgID,&lPoint);
for(IterljjListresult iter = lPoint.begin();iter != lPoint.end(); iter++)
{
EmergencyTaskInfo *eInfo = new EmergencyTaskInfo;
eInfo->iBeginKm = (int)iter->spoint;
eInfo->iEndKm = (int)iter->epoint;
eInfo->iBeginTime = Time2Strings2(iter->stime);
eInfo->iEndTime = Time2Strings2(iter->etime);
eInfo->iStatus = (EmergencyStatus)iter->state;
eInfo->iTaskID = iter->id;
eInfo->iRailLine = iter->lineid;
eInfo->iTaskName = iter->rwName;
eInfo->iOrgId = aOrgID;
ljjryListresult lPoint;
cs->GetJJry(iter->id,&lPoint);
for(IterlljjryListresult iter = lPoint.begin(); iter != lPoint.end();iter++)
{
eInfo->iStaffID.push_back(iter->Jj_Pid);
eInfo->iStaffOrgID.push_back(iter->nJj_OrgID);
eInfo->iStaffName.push_back(iter->strJj_Name);
}
m_EmergencyList->push_back(eInfo);
}
return KErrNone;
}
int SetEmergencyTask( int aOrgID, int aCmd, const EmergencyTaskInfo* aEmergencyTask )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return GetCurrentTime()%100;
#endif
///////////////////////////////////////////////////
int iResult = 0;
if( CMD_EMERGENCY_MODIFY== aCmd )//紧急任务休息
{
if(aEmergencyTask->iStatus == KFinished)
{
return 0;
}
cData *cd = new cData();
jjrw *sVAL= new jjrw();
memset(sVAL,0,sizeof(jjrw));
sVAL->type = 1;
CString timeTemp = Time2Strings(aEmergencyTask->iEndTime);
char *p1 = (char*)timeTemp.GetBuffer(timeTemp.GetLength());
memcpy(sVAL->endTime,p1,timeTemp.GetLength());
timeTemp.ReleaseBuffer();
CString timeTemp1 = Time2Strings(aEmergencyTask->iBeginTime);
p1 = (char*)timeTemp1.GetBuffer(timeTemp1.GetLength());
memcpy(sVAL->startTime,p1,timeTemp1.GetLength());
timeTemp1.ReleaseBuffer();
sVAL->endPointId = aEmergencyTask->iBeginKm;
sVAL->lineid = (int)aEmergencyTask->iRailLine;
sVAL->orgid = aOrgID;
timeTemp = aEmergencyTask->iTaskName;
p1 = (char*)timeTemp.GetBuffer(timeTemp.GetLength());
memcpy(sVAL->rwName,p1,timeTemp.GetLength());
timeTemp.ReleaseBuffer();
sVAL->startPointId = aEmergencyTask->iBeginKm;
sVAL->endPointId = aEmergencyTask->iEndKm;
sVAL->state = 0;
sVAL->iTaskId = aEmergencyTask->iTaskID ;
iResult = cd->Setjjrw(*sVAL);
delete cd;
}
if( CMD_EMERGENCY_ADD == aCmd )//紧急任务天加
{
if(aEmergencyTask->iStatus == KFinished)
{
return 0;
}
cData *cd = new cData();
jjrw *sVAL= new jjrw();
memset(sVAL,0,sizeof(jjrw));
sVAL->type = 0;
CString timeTemp = Time2Strings(aEmergencyTask->iEndTime);
char *p1 = (char*)timeTemp.GetBuffer(timeTemp.GetLength());
memcpy(sVAL->endTime,p1,timeTemp.GetLength());
timeTemp.ReleaseBuffer();
timeTemp = Time2Strings(aEmergencyTask->iBeginTime);
p1 = (char*)timeTemp.GetBuffer(timeTemp.GetLength());
memcpy(sVAL->startTime,p1,timeTemp.GetLength());
timeTemp.ReleaseBuffer();
sVAL->endPointId = aEmergencyTask->iBeginKm;
sVAL->lineid = (int)aEmergencyTask->iRailLine;
sVAL->orgid = aOrgID;
timeTemp = aEmergencyTask->iTaskName;
p1 = (char*)timeTemp.GetBuffer(timeTemp.GetLength());
memcpy(sVAL->rwName,p1,timeTemp.GetLength());
timeTemp.ReleaseBuffer();
sVAL->startPointId = aEmergencyTask->iBeginKm;
sVAL->endPointId = aEmergencyTask->iEndKm;
sVAL->state = 0;
iResult = cd->Setjjrw(*sVAL);
delete cd;
}
if(CMD_EMERGENCY_MODIFYSTAFF == aCmd)
{
//GetXjRymx
cData *cs = new cData();
jjDel jVal;
jVal.iTaskId = aEmergencyTask->iTaskID;
cs->DelXjRymx(jVal);
for(size_t i =0;i < aEmergencyTask->iStaffID.size(); i++)
{
jjry sValue;
memset(&sValue,0,sizeof(jjry));
sValue.type = 0;
sValue.Jj_id = aEmergencyTask->iTaskID;
CString cTemp = aEmergencyTask->iStaffID[i];
char *p1 = (char*)cTemp.GetBuffer(cTemp.GetLength());
memcpy(&sValue.Jj_Pid,p1,cTemp.GetLength());
cTemp.ReleaseBuffer();
cs->Setjjry(sValue);
}
return 1;
}
return iResult;
}
int GetEmergencyLogs( int aTaskID, vector<EmergencyLogs*>* aEmergencyStaff )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
EmergencyLogs* logs = new EmergencyLogs;
logs->iTaskID = aTaskID;
logs->iStaffID = _T("123123");
logs->iStaffOrgID = 1;
logs->iTotalKM = 10.25;
logs->iTotalTime = _T("10223");
aEmergencyStaff->push_back(logs);
return KErrNone;
#endif
///////////////////////////////////////////////////
ljjryListresult lPoint;
cData *cd = new cData();
cd->GetJJry(aTaskID,&lPoint);
for(IterlljjryListresult iter = lPoint.begin(); iter != lPoint.end();iter++)
{
EmergencyLogs *eNew = new EmergencyLogs();
eNew->iStaffID = iter->Jj_Pid;
eNew->iStaffOrgID = iter->nJj_OrgID;
eNew->iTaskID = aTaskID;
eNew->iTotalTime = iter->Jj_time;
eNew->iTotalKM = iter->Jj_long;
aEmergencyStaff->push_back(eNew);
}
return KErrNone;
}
int GetOrgDevice( int aOrgID, vector<DeviceInfo*>* aDeviceList )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
DeviceInfo* device = new DeviceInfo;
device->iDeviceType = KPicture;
device->iOrgID = aOrgID;
device->iDevID = 1;
device->iPhoneNum = _T("18602812345");
aDeviceList->push_back(device);
return KErrNone;
#endif
///////////////////////////////////////////////////
cData *cd = new cData();
//if(cd->iSocketState < 0)
RequestDeviceList rRequest;
rRequest.Devicetype = 2;
rRequest.Orgid = aOrgID;
rRequest.type = 1;
lDevice lPoint ;
if(cd->GetDeviceList(rRequest,&lPoint) < 0)
{
return KErrNone;
}
aDeviceList->clear();
for(iterDevice iter = lPoint.begin() ; iter !=lPoint.end();iter++)
{
DeviceInfo *dInfo = new DeviceInfo;
//memset(dInfo,0,sizeof(DeviceInfo));
dInfo->iDeviceType = (DeviceType)iter->DeviceType;
dInfo->iOrgID = aOrgID;
dInfo->iDevID = iter->DeviceId;
//char *pTemp ;
//pTemp = (LPSTR)(LPCTSTR)iter->DevicePid;
//memcpy(&dInfo.iPhoneNum,pTemp,sizeof(pTemp));
dInfo->iPhoneNum = iter->DevicePid;
aDeviceList->push_back(dInfo);
}
return ResultOk;
}
int SetOrgDevice( int aOrgID, int aCmd, const DeviceInfo* aDeviceList )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
///////////////////////////////////////////////////
//#define CMD_DEVICE_ADD 0x40
//#define CMD_DEVICE_MODIFY 0x41
//#define CMD_DEVICE_DELETE 0x42
int iResult;
cData *cd = new cData();
switch(aCmd)
{
case CMD_DEVICE_ADD:
{
AddDevice *aDevice = new AddDevice;
memset(aDevice,0,sizeof(AddDevice));
aDevice->DeviceOrg = aDeviceList->iOrgID;
aDevice->DeviceType = aDeviceList->iDeviceType;
CString cTEMP = aDeviceList->iPhoneNum;
char *p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&aDevice->DevicePid,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
//char *pTemp = (LPSTR)(LPCTSTR)aDeviceList->iPhoneNum;
//memcpy(&aDevice->DevicePid,pTemp,sizeof(pTemp));
iResult = cd->AddDevices(aDevice);
break;
}
case CMD_DEVICE_MODIFY:
{
EditDevice *aDevice = new EditDevice;
memset(aDevice,0,sizeof(EditDevice));
aDevice->DeviceOrg = aDeviceList->iOrgID;
aDevice->DeviceType = aDeviceList->iDeviceType;
aDevice->DeviceId =aDeviceList->iDevID;
//char *pTemp = (LPSTR)(LPCTSTR)aDeviceList->iPhoneNum;
//memcpy(&aDevice->DevicePid,pTemp,sizeof(pTemp));
CString cTEMP = aDeviceList->iPhoneNum;
char *p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&aDevice->DevicePid,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
iResult = cd->EditDevices(aDevice);
break;
}
case CMD_DEVICE_DELETE:
{
DelDevice dDevice;
dDevice.DeviceId = aDeviceList->iDevID;
iResult = cd->DelDevices(&dDevice);
break;
}
default:
break;
}
if(iResult < 0)
{
return KErrNone;
}else
return ResultOk;
}
int GetOrgMonthPx(GetOrgPxEx const sValue,vector<getorgpxlistresultEx*> *Value)
{
cData *cd = new cData();
//int cData::GetOrgMonthPx(getorgpx const sValue,lOrgMonth *llist)
//{
getorgpx sValues;
lOrgMonth llist;
sValues.months = sValue.months;
sValues.orgid = sValue.orgid;
sValues.yesrs = sValue.yesrs;
if(cd->GetOrgMonthPx(sValues,&llist) == 1)
{
for (iterOrgMonth iter = llist.begin() ; iter != llist.end();iter++)
{
getorgpxlistresultEx *ex = new getorgpxlistresultEx();
ex->dates = iter->dates;
ex->xj = iter->xj;
ex->sGetPoint = iter->sGetPoint;
ex->sTotlePoint = iter->sTotlePoint;
ex->cPoint = iter->cPoint;
ex->lPoint = iter->lPoint;
ex->userid = iter->userid;
Value->push_back(ex);
}
}
return 0;
}
int GetPictureInfo( int aOrgID, time_t aStartDate, time_t aEndDate, vector<PictureInfo*>* aPictureList )
{
///////////////////////////////////////////////////
#ifdef TESTCODE
PictureInfo *pInfo = new PictureInfo;
//pInfo.iPicID = iter->
pInfo->iPicName = _T("516823.jpg");
pInfo->iShootingTime = _T("2011-7-1");
pInfo->iErrorType = 1;
aPictureList->push_back(pInfo);
return KErrNone;
#endif
///////////////////////////////////////////////////
CString sStart = Time2Strings(aStartDate);//_T("2011-1-1");//
CString eTimes = Time2Strings(aEndDate);//_T("2011-11-1");//
GetPic pc;
memset(&pc,0,sizeof(GetPic));
pc.Orgid = aOrgID;
CString cTEMP = sStart;
char *p1 = (char*)cTEMP.GetBuffer(cTEMP.GetLength());
memcpy(&pc.stime,p1,cTEMP.GetLength());
cTEMP.ReleaseBuffer();
CString cTEMP1 = eTimes;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(&pc.etime,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
lPicList llist ;
cData *cd = new cData();
if(cd->GetOrgPic(pc,&llist) != 1)
{
return 1;
}
for(iterPic iter = llist.begin();iter != llist.end() ;iter++)
{
PictureInfo *pInfo = new PictureInfo;
//memset(pInfo,0,sizeof(PictureInfo));
//pInfo.iPicID = iter->
pInfo->iPicName = iter->name;
pInfo->iShootingTime = iter->time;
pInfo->iErrorType = iter->itype;
aPictureList->push_back(pInfo);
}
return 0;
}
int GetOrgXl()
{
//int cData::GetXjRymx(const ryxj1 value,lryxj1result *lPoint)
ryxj1 user;
memset(&user,0,sizeof(UserGps));
strcpy_s(user.oper,_T("1234"));
strcpy_s(user.date,_T("2011-7-1"));
cData *cd = new cData();
lryxj1result lPoint;
cd->GetXjRymx(user,&lPoint);
return 1;
}
//
int GetOrgMonthxl()
{
//int PGPSDayData(const UserGps value,lOrgLineResult *lPoint);
UserGps user;
memset(&user,0,sizeof(UserGps));
strcpy_s(user.oper,_T("admin"));
strcpy_s(user.time,_T("2011-7-1"));
cData *cd = new cData();
lOrgLineResult lPoint;
cd->PGPSDayData(user,&lPoint);;
return 1;
}
int SavePictureToDirect( int aOrgID, const PictureInfo* aPicture, CString aToDirect )
{
Getrealpic cs;
memset(&cs,0,sizeof(Getrealpic));
CString cTEMP1 = aPicture->iPicName;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(&cs.pname,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
cData *cd = new cData();
if(cd->getPic((const Getrealpic)cs,aToDirect))
return ResultOk;
else
return KErrNone;
}
int GetStaffScheduleTrack(CString aStaffID, time_t aDate, RecordStaff* aRecord )
{//流水
/////////////////////////////////////////////////////
#ifdef TESTCODE
aRecord->iStaffID = aStaffID;
aRecord->iArrivedTime.push_back(_T("9:10"));
aRecord->iRecordLon.push_back(104.064631);
aRecord->iRecordLat.push_back(30.698965);
//
aRecord->iArrivedTime.push_back(_T("9:15"));
aRecord->iRecordLon.push_back(104.075630);
aRecord->iRecordLat.push_back(30.699584);
//
aRecord->iArrivedTime.push_back(_T("9:28"));
aRecord->iRecordLon.push_back(104.086426);
aRecord->iRecordLat.push_back(30.699584);
return KErrNone;
#endif
/////////////////////////////////////////////////////
aRecord->iStaffID = aStaffID;
//int PGPSDayData(const UserGps value,lOrgLineResult *lPoint);
char UserName[20];
memset(UserName,0,20);
UserGps user;
memset(&user,0,sizeof(UserGps));
CString cTEMP1 = aStaffID;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(UserName,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
memcpy(user.oper,UserName,20);
CString dates = Time2Strings(aDate);
char *p3 = (char*)dates.GetBuffer(dates.GetLength());
memcpy(user.time,p3,dates.GetLength());
dates.ReleaseBuffer();
cData *cd = new cData();
lOrgLineResult lPoint;
cd->PGPSDayData(user,&lPoint);
////OrgLineResults;
//typedef list <OrgLineResults> lOrgLineResult;
//typedef lOrgLineResult::iterator IterOrgLineResult;
aRecord->iStaffID = aStaffID;
for(IterOrgLineResult iter = lPoint.begin() ;iter !=lPoint.end(); iter++ )
{
aRecord->iRecordLat.push_back(iter->wdu) ;
aRecord->iRecordLon.push_back(iter->jdu);
aRecord->iArrivedTime.push_back(iter->time);
}
return KErrNone;
}
int GetReportDetail(CString aStaffID, CString aTime, ReportDetail* aReportList)
{//明细
/////////////////////////////////////////////////////
#ifdef TESTCODE
aReportList->iDay.push_back(aTime);
aReportList->iRailLineID.push_back(_T("成渝线"));
aReportList->iPointKM.push_back(100);
aReportList->iStaffID.push_back(aStaffID);
aReportList->iPlanArrivedTime.push_back(_T("9:00"));
aReportList->iActualArrivedTime.push_back(_T("9:05"));
aReportList->iState.push_back(KPointNormal);
aReportList->iRailLineID.push_back(_T("成渝线"));
aReportList->iPointKM.push_back(101);
aReportList->iStaffID.push_back(aStaffID);
aReportList->iPlanArrivedTime.push_back(_T("9:10"));
aReportList->iActualArrivedTime.push_back(_T("9:11"));
aReportList->iState.push_back(KPointUnArrived);
return KErrNone;
#endif
/////////////////////////////////////////////////////
ryxj1 user;
memset(&user,0,sizeof(ryxj1));
CString cTEMP1 = aStaffID;
char *p2 = (char*)cTEMP1.GetBuffer(cTEMP1.GetLength());
memcpy(user.oper,p2,cTEMP1.GetLength());
cTEMP1.ReleaseBuffer();
CString dates = aTime;
char *p3 = (char*)dates.GetBuffer(dates.GetLength());
memcpy(user.date,p3,dates.GetLength());
cData *cd = new cData();
lryxj1result lPoint;
cd->GetXjRymx(user,&lPoint);
for(Iterryxj1result iter = lPoint.begin();iter != lPoint.end();iter++)
{
aReportList->iActualArrivedTime.push_back(iter->realTime);
aReportList->iPlanArrivedTime.push_back(iter->sArrtime);
CString tmp = iter->date;
aReportList->iDay.push_back(tmp);
aReportList->iState.push_back((PointState)iter->pointstate);
aReportList->iStaffID.push_back(aStaffID);
}
return KErrNone;
}
int GetReportInfoList( int aOrgID, int aYear, int aMonth, vector<ReportInfo*>* aReportList )
{//月报表
/////////////////////////////////////////////////////
#ifdef TESTCODE
ReportInfo* report = new ReportInfo;
report->iOrgID = aOrgID;
report->iStaffName = _T("Admin");
report->iReportDay = _T("2011-1-1");
report->iPlanArrived = 50;
report->iActualArrived = 40;
report->iAbnormal = 10;
aReportList->push_back(report);
report = new ReportInfo;
report->iOrgID = aOrgID;
report->iStaffName = _T("admin2");
report->iReportDay = _T("2011-1-1");
report->iPlanArrived = 60;
report->iActualArrived = 40;
report->iAbnormal = 20;
aReportList->push_back(report);
return KErrNone;
#endif
/////////////////////////////////////////////////////
cData *cd = new cData();
getorgpx sValues;
lOrgMonth llist;
sValues.months = aMonth;
sValues.orgid = aOrgID;
sValues.yesrs = aYear;
if(cd->GetOrgMonthPx(sValues,&llist) == 1)
{
for (iterOrgMonth iter = llist.begin() ; iter != llist.end();iter++)
{
ReportInfo* report = new ReportInfo;
report->iOrgID = aOrgID;
report->iStaffName = iter->userid;
report->iReportDay = iter->dates;
report->iWeekDay = iter->xj;
report->iPlanArrived = iter->sTotlePoint;
report->iActualArrived = iter->sGetPoint;
report->iAbnormal = iter->cPoint;
report->iUnArrived = iter->lPoint;
aReportList->push_back(report);
}
}
return KErrNone;
}
int GetAlarmByMonth(int aOrgID, int aYear,int aMonth, ReportDetail* aAlarmList)
{
/////////////////////////////////////////////////////
#ifdef TESTCODE
return KErrNone;
#endif
/////////////////////////////////////////////////////
WarnRequest wValue;
wValue.Mon = aMonth;
wValue.Yea = aYear;
wValue.orgid = aOrgID;
lWarnRequestReturn warnValue;
cData *cd = new cData();
cd->GetWarnList(wValue,&warnValue);
for(IterlWarnRequestReturn iter = warnValue.begin();iter != warnValue.end(); iter++)
{
aAlarmList->iActualArrivedTime.push_back(iter->realTime);
aAlarmList->iDay.push_back(iter->data);
aAlarmList->iPlanArrivedTime.push_back(iter->STime);
aAlarmList->iStaffID.push_back(iter->UserId);
aAlarmList->iPointKM.push_back(iter->iDirect);
aAlarmList->iState.push_back((PointState)iter->iPointState);
aAlarmList->iRailLineID.push_back(iter->LineName);
}
return KErrNone;
}
time_t Time2Strings1(CString sec)
{
int iHour,iMonth;
sscanf_s((const char*)sec.GetBuffer(),"%d:%d",&iHour,&iMonth);
CTime time(2010,1,1,iHour,iMonth,0);
time_t time2=time.GetTime();
sec.ReleaseBuffer();
return time2;
}
time_t Time2Strings2(CString sec)
{
if(sec == "")
return 0;
int i1,i2,i3;
sscanf_s((const char*)sec.GetBuffer(),"%d-%d-%d",&i1,&i2,&i3);
CTime time(i1,i2,i3,0,0,1);
time_t time2=time.GetTime();
sec.ReleaseBuffer();
return time2;
}
CString Time2Strings(time_t sec)
{
if(sec==0){
return _T("");
}
time_t tm = sec;
CTime t(tm);
int year = t.GetYear();
int month = t.GetMonth();
int day = t.GetDay();
int hour = t.GetHour();
int minute = t.GetMinute();
int second = t.GetSecond();
CString strYear;
CString strMonth;
CString strDay;
CString strHour;
CString strMinute;
CString strSecond;
int year2 = year%100;
//strYear.Format("%d",year2);
strYear.Format(_T("%d"),year);
if((year2>=0)&&(year2<=9)){
strYear = _T("0") + strYear;
}
strMonth.Format(_T("%d"),month);
strDay.Format(_T("%d"),day);
CString result = strYear+"-"+strMonth+"-"+strDay;
return result;
}
void StringToChar(char *p,CString sVal)
{
p =(char*)sVal.GetBuffer(sVal.GetLength());
return;
}
void StringRelease(CString sVAL);
| [
"[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3",
"[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3"
]
| [
[
[
1,
314
],
[
324,
326
],
[
328,
340
],
[
352,
408
],
[
410,
418
],
[
420,
487
],
[
489,
520
],
[
522,
522
],
[
524,
524
],
[
526,
526
],
[
528,
529
],
[
531,
535
],
[
540,
540
],
[
543,
563
],
[
565,
565
],
[
568,
601
],
[
610,
619
],
[
628,
638
],
[
640,
648
],
[
658,
775
],
[
793,
808
],
[
819,
835
],
[
843,
843
],
[
845,
891
],
[
900,
906
],
[
922,
945
],
[
952,
952
],
[
954,
954
],
[
956,
961
],
[
968,
969
],
[
971,
1168
],
[
1170,
1173
],
[
1176,
1179
],
[
1181,
1181
],
[
1193,
1217
],
[
1225,
1234
],
[
1243,
1568
],
[
1570,
1570
],
[
1575,
1576
],
[
1581,
1582
],
[
1588,
1629
],
[
1636,
1637
]
],
[
[
315,
323
],
[
327,
327
],
[
341,
351
],
[
409,
409
],
[
419,
419
],
[
488,
488
],
[
521,
521
],
[
523,
523
],
[
525,
525
],
[
527,
527
],
[
530,
530
],
[
536,
539
],
[
541,
542
],
[
564,
564
],
[
566,
567
],
[
602,
609
],
[
620,
627
],
[
639,
639
],
[
649,
657
],
[
776,
792
],
[
809,
818
],
[
836,
842
],
[
844,
844
],
[
892,
899
],
[
907,
921
],
[
946,
951
],
[
953,
953
],
[
955,
955
],
[
962,
967
],
[
970,
970
],
[
1169,
1169
],
[
1174,
1175
],
[
1180,
1180
],
[
1182,
1192
],
[
1218,
1224
],
[
1235,
1242
],
[
1569,
1569
],
[
1571,
1574
],
[
1577,
1580
],
[
1583,
1587
],
[
1630,
1635
],
[
1638,
1638
]
]
]
|
b6808e773ef49b1767de8d16c7b61336a87fa4d5 | cfa1c9f0d1e0bef25f48586d19395b5658752f5b | /Proj_2/Trigger.h | 5ff81ec3b9b56d652a83c97575ecee8dc69de65f | []
| no_license | gemini14/AirBall | de9c9a9368bb58d7f7c8fe243a900b11d0596227 | 5d41d3f2c5282f50e7074010f7c1d3b5a804be77 | refs/heads/master | 2021-03-12T21:42:26.819173 | 2011-05-11T08:10:51 | 2011-05-11T08:10:51 | 1,732,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | h | #pragma once
#include <irrlicht.h>
#include <string>
namespace Tuatara
{
enum TriggerType
{
triggerLocation,
triggerNamed,
};
// simple trigger mechanism for tutorials
class Trigger
{
public:
Trigger( irr::scene::ISceneManager *smgr );
~Trigger(void);
TriggerType type;
irr::core::vector3di blockLoc; // some triggers are based on ball location
std::string name; // some triggers are on specific named events
std::string prompt; // the text to display
bool triggered; // has it already been triggered?
void HandleMouseClick( irr::s32 x, irr::s32 y );
void Show();
void Close();
void CloseNow();
bool Update();
private:
enum triggerState
{
unknown,
opening,
displaying,
closing,
};
irr::gui::IGUIEnvironment* GUIEnv;
irr::scene::ISceneManager* smgr;
irr::gui::IGUIImage* img;
irr::gui::IGUIStaticText* text;
triggerState currentState;
int currentStep;
bool promptShown;
};
}
| [
"devnull@localhost"
]
| [
[
[
1,
53
]
]
]
|
b3eef7b5c6d781b62fbe431e44c13ec21a343d7f | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/Audio/AudioDriver.h | 6b117288f7c243838ca79490d03fa59d1e956d7e | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,394 | h | // //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## AudioDriver.h - Audio device //
// ### # # ### //
// # ### # ### Sound output device which can play back various sound file formats //
// # ## # # ## ## //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_AUDIO_AUDIODRIVER_H
#define NUCLEX_AUDIO_AUDIODRIVER_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Audio/Sound.h"
#include "Nuclex/Support/Variant.h"
namespace Nuclex { namespace Audio {
class AudioDevice;
// //
// Nuclex::Audio::AudioDriver //
// //
/// Audio device
/**
*/
class AudioDriver {
public:
/// Enumerator for the available display modes
class OutputModeEnumerator;
/// Display mode information
/** Holds informations about a wave mode
*/
struct OutputMode {
/// Constructor
NUCLEX_API OutputMode(Sound::SampleFormat eFormat, size_t nChannels) :
eFormat(eFormat), nChannels(nChannels) {}
/// Get name of output mode
NUCLEX_API string getName() {
string sName;
switch(eFormat) {
case Sound::SF_11025_8: sName = " 8 Bits in 11 KHz"; break;
case Sound::SF_11025_16: sName = "16 Bits in 11 KHz"; break;
case Sound::SF_22050_8: sName = " 8 Bits in 22.5 KHz"; break;
case Sound::SF_22050_16: sName = "16 Bits in 22.5 KHz"; break;
case Sound::SF_44100_8: sName = " 8 Bits in 44.1 KHz"; break;
case Sound::SF_44100_16: sName = "16 Bits in 44.1 KHz"; break;
default: sName = "Unknown"; break;
}
return sName + " on " + lexical_cast<string>(nChannels) + " channels";
}
Sound::SampleFormat eFormat; ///< Audio sample format
size_t nChannels; ///< Number of channels
};
/// Destructor
NUCLEX_API virtual ~AudioDriver() {}
//
// AudioDriver implementation
//
public:
/// Create device
NUCLEX_API virtual shared_ptr<AudioDevice> createDevice() = 0;
/// Get an enumerator over all available output modes
/** Can be used to enumerate all output modes the device supports
@return A new output mode enumerator
*/
NUCLEX_API virtual shared_ptr<OutputModeEnumerator> enumOutputModes() const = 0;
/// Get device name
/** Returns a human readable name uniquely describing the
device. Should include the sound card used.
@return The device's name
*/
NUCLEX_API virtual const string &getName() const = 0;
};
// //
// Nuclex::Audio::AudioDriver::OutputModeEnumerator //
// //
/** Enumerates over a list of display modes
*/
class AudioDriver::OutputModeEnumerator {
public:
/// Destructor
/** Destroys an instance of IWaveModeEnumerator
*/
NUCLEX_API virtual ~OutputModeEnumerator() {}
//
// OutputModeEnumerator implementation
//
public:
/// Cycle through all output modes
/** Returns the current output mode and advances to the next one.
If no more output modes are available, returns NULL
@return The current output mode being enumerated
*/
NUCLEX_API virtual const OutputMode *cycle(void) = 0;
};
}} // namespace Nuclex::Audio
#endif // NUCLEX_AUDIO_AUDIODRIVER_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
]
| [
[
[
1,
112
]
]
]
|
6b69152116c5597326f074923e45a522e55215e8 | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/include/EdgeArchive.h | e1acd4d9786e8266fa0dde17c48cc9b1e8d8833e | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,998 | h | /*
-----------------------------------------------------------------------------
This source file is part of EDGE
(A very object-oriented and plugin-based 2d game engine)
For the latest info, see http://edge2d.googlecode.com
Copyright (c) 2007-2008 The EDGE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef EDGE_ARCHIVE_H
#define EDGE_ARCHIVE_H
#include "EdgeCompile.h"
#include <string>
#include "EdgeDataStream.h"
#include "EdgeSharedPtr.h"
#include "EdgeSingleton.h"
using std::string;
namespace Edge
{
/**
* Archive-handling class.
* @remarks Archive, an archive means a directory on file system, or a package like
* zip package lzo package etc.
* The archive's name is very necessary. To a FileSystemArchive, it's the directory
* path, to a ZipArchive, it's the zip file's file name(including the path ).
*
* @par Every archive's name is unique in the global range.
*/
class EDGE_EXPORT Archive
{
public:
/**
* Constructor, you donot need to create an archive yourself, you can get an
* archive by ArchiveManager::createArchive
*
*/
Archive( const string &name, const string &type );
/**
* Destructor
*
*/
virtual ~Archive() {}
/**
* load the archive.
*
* @ramarks some archive needs to be initiated.
* @warning this function is only called when you call ArchiveManager::createArchive.
* so you should not call this function.
*/
virtual bool load() = 0;
/**
* unload the archive.
*
* @ramarks called when the archive is deleted.
*/
virtual void unload() = 0;
/**
* open a file and it will not manage the object.
*
* @remarks this is the only function you will pay attention to. It will open a file in
* the archive.
*/
virtual DataStreamPtr open( const string &file ) = 0;
/**
* get the archive name of this archive.
*
*/
string &getName() { return mName; }
/**
* get the type name of this archive.
*
*/
string &getType() { return mType; }
protected:
/// archive name, should be a file name for a compressed achive like : ./data.zip
string mName;
/// archive type, can be "FileSystem", "Zip", "Lzo" etc...
string mType;
};
typedef shared_ptr<Archive> ArchivePtr;
/**
* ArchiveFactory, it's used to create an Archive.
*
*/
class EDGE_EXPORT ArchiveFactory
{
public:
/**
* createArchive, you can specify a password to pInData if you want to
* create a Zip archive.
*
*/
virtual Archive *createArchive( const string &name, void *pInData = 0 ) = 0;
/**
* destroyArchive
*
*/
virtual void destroyArchive( Archive *archive ) = 0;
/**
* get the archive factory type.
*
*/
virtual string getType() = 0;
};
/**
* FileSystemArchive, it's the basic archive, other archive can be Zip, Pkg, etc
* The name of a FileSystemArchive must be it's directory path.
*
*/
class EDGE_EXPORT FileSystemArchive : public Archive
{
public:
/**
* Constructor
*
* @param name the path of this file system archive
*/
FileSystemArchive( const string &name, const string &type );
/**
* Destructor
*
*/
~FileSystemArchive();
/**
* @copydoc Archive::load
*
*/
bool load();
/**
* @copydoc Archive::unload
*
*/
void unload();
/**
* @copydoc Archive::open
*
*/
DataStreamPtr open( const string &file );
private:
/// path
string mPath;
};
/**
* FileSystemArchiveFactory
*
* @remarks used to create a FileSystemArchive.
*/
class EDGE_EXPORT FileSystemArchiveFactory : public Singleton<FileSystemArchiveFactory>,
public ArchiveFactory
{
public:
/**
* create a FileSystem archive.
*
*/
Archive *createArchive( const string &name, void *pInData = 0 );
/**
* destroyo a FileSystem archive.
*
*/
void destroyArchive( Archive *archive );
/**
* get this archive type.
*
*/
string getType() { return "FileSystem"; }
};
}
#endif | [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
208
]
]
]
|
b0132e5098029040dd3a867799129942f3b26552 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/Lists/UploadListCtrl.cpp | ab22956e14f89a1079b53da7fe6bfc64352af92d | []
| 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 | GB18030 | C++ | false | false | 26,499 | cpp | //this file is part of eMule
//Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "emule.h"
#include "UploadListCtrl.h"
#include "TransferWnd.h"
#include "otherfunctions.h"
#include "MenuCmds.h"
#include "ClientDetailDialog.h"
#include "KademliaWnd.h"
#include "emuledlg.h"
#include "friendlist.h"
#include "MemDC.h"
#include "KnownFile.h"
#include "SharedFileList.h"
#include "UpDownClient.h"
#include "ClientCredits.h"
#include "ChatWnd.h"
#include "kademlia/kademlia/Kademlia.h"
#include "kademlia/net/KademliaUDPListener.h"
#include "UploadQueue.h"
#include "ToolTipCtrlX.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "IP2Country.h"//EastShare - added by AndCycle, IP to Country
#include ".\uploadlistctrl.h"
// CUploadListCtrl
IMPLEMENT_DYNAMIC(CUploadListCtrl, CMuleListCtrl)
BEGIN_MESSAGE_MAP(CUploadListCtrl, CMuleListCtrl)
ON_WM_CONTEXTMENU()
ON_WM_SYSCOLORCHANGE()
ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclk)
ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDispInfo)
ON_NOTIFY_REFLECT(LVN_GETINFOTIP, OnLvnGetInfoTip)
ON_WM_DRAWITEM()
ON_WM_MEASUREITEM()
END_MESSAGE_MAP()
CUploadListCtrl::CUploadListCtrl()
: CListCtrlItemWalk(this)
{
m_tooltip = new CToolTipCtrlX;
SetGeneralPurposeFind(true, false);
m_pMenuXP = NULL;
}
void CUploadListCtrl::Init()
{
SetName(_T("UploadListCtrl"));
CImageList ilDummyImageList; //dummy list for getting the proper height of listview entries
ilDummyImageList.Create(1, theApp.GetSmallSytemIconSize().cy,theApp.m_iDfltImageListColorFlags|ILC_MASK, 1, 1);
SetImageList(&ilDummyImageList, LVSIL_SMALL);
ASSERT( (GetStyle() & LVS_SHAREIMAGELISTS) == 0 );
ilDummyImageList.Detach();
SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP);
CToolTipCtrl* tooltip = GetToolTips();
if (tooltip){
m_tooltip->SubclassWindow(tooltip->m_hWnd);
tooltip->ModifyStyle(0, TTS_NOPREFIX);
tooltip->SetDelayTime(TTDT_AUTOPOP, 20000);
tooltip->SetDelayTime(TTDT_INITIAL, thePrefs.GetToolTipDelay()*1000);
}
InsertColumn(0,GetResString(IDS_QL_USERNAME),LVCFMT_LEFT,150,0);
InsertColumn(1,GetResString(IDS_FILE),LVCFMT_LEFT,275,1);
InsertColumn(2,GetResString(IDS_DL_SPEED),LVCFMT_LEFT,60,2);
InsertColumn(3,GetResString(IDS_DL_TRANSF),LVCFMT_LEFT,65,3);
InsertColumn(4,GetResString(IDS_WAITED),LVCFMT_LEFT,60,4);
InsertColumn(5,GetResString(IDS_UPLOADTIME),LVCFMT_LEFT,60,5);
InsertColumn(6,GetResString(IDS_STATUS),LVCFMT_LEFT,110,6);
InsertColumn(7,GetResString(IDS_UPSTATUS),LVCFMT_LEFT,100,7);
SetAllIcons();
Localize();
LoadSettings();
// Barry - Use preferred sort order from preferences
SetSortArrow();
SortItems(SortProc, GetSortItem() + (GetSortAscending() ? 0:100));
}
CUploadListCtrl::~CUploadListCtrl()
{
delete m_tooltip;
if(m_pMenuXP)
{
delete m_pMenuXP;
}
}
void CUploadListCtrl::OnSysColorChange()
{
CMuleListCtrl::OnSysColorChange();
SetAllIcons();
}
void CUploadListCtrl::SetAllIcons()
{
imagelist.DeleteImageList();
imagelist.Create(16,16,theApp.m_iDfltImageListColorFlags|ILC_MASK,0,1);
imagelist.SetBkColor(CLR_NONE);
imagelist.Add(CTempIconLoader(_T("ClientEDonkey")));
imagelist.Add(CTempIconLoader(_T("ClientCompatible")));
imagelist.Add(CTempIconLoader(_T("ClientEDonkeyPlus")));
imagelist.Add(CTempIconLoader(_T("ClientCompatiblePlus")));
imagelist.Add(CTempIconLoader(_T("Friend")));
imagelist.Add(CTempIconLoader(_T("ClientMLDonkey")));
imagelist.Add(CTempIconLoader(_T("ClientMLDonkeyPlus")));
imagelist.Add(CTempIconLoader(_T("ClientEDonkeyHybrid")));
imagelist.Add(CTempIconLoader(_T("ClientEDonkeyHybridPlus")));
imagelist.Add(CTempIconLoader(_T("ClientShareaza")));
imagelist.Add(CTempIconLoader(_T("ClientShareazaPlus")));
imagelist.Add(CTempIconLoader(_T("ClientAMule")));
imagelist.Add(CTempIconLoader(_T("ClientAMulePlus")));
imagelist.Add(CTempIconLoader(_T("ClientLPhant")));
imagelist.Add(CTempIconLoader(_T("ClientLPhantPlus")));
imagelist.SetOverlayImage(imagelist.Add(CTempIconLoader(_T("ClientSecureOvl"))), 1);
imagelist.SetOverlayImage(imagelist.Add(CTempIconLoader(_T("OverlayObfu"))), 2);
imagelist.SetOverlayImage(imagelist.Add(CTempIconLoader(_T("OverlaySecureObfu"))), 3);
}
void CUploadListCtrl::Localize()
{
CHeaderCtrl* pHeaderCtrl = GetHeaderCtrl();
HDITEM hdi;
hdi.mask = HDI_TEXT;
CString strRes;
strRes = GetResString(IDS_QL_USERNAME);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(0, &hdi);
strRes = GetResString(IDS_FILE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(1, &hdi);
strRes = GetResString(IDS_DL_SPEED);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(2, &hdi);
strRes = GetResString(IDS_DL_TRANSF);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(3, &hdi);
strRes = GetResString(IDS_WAITED);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(4, &hdi);
strRes = GetResString(IDS_UPLOADTIME);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(5, &hdi);
strRes = GetResString(IDS_STATUS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(6, &hdi);
strRes = GetResString(IDS_UPSTATUS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(7, &hdi);
}
void CUploadListCtrl::AddClient(const CUpDownClient* client)
{
if (!theApp.emuledlg->IsRunning())
return;
switch( client->GetUploadState() ) {
case US_ERROR:
case US_BANNED:
ASSERT( false );
case US_NONE:
case US_ONUPLOADQUEUE:
return ;
break;
}
int iItemCount = GetItemCount();
int iItem = InsertItem(LVIF_TEXT|LVIF_PARAM,iItemCount,LPSTR_TEXTCALLBACK,0,0,0,(LPARAM)client);
Update(iItem);
theApp.emuledlg->transferwnd->UpdateListCount(CTransferWnd::wnd2Uploading, iItemCount+1);
}
void CUploadListCtrl::RemoveClient(const CUpDownClient* client)
{
if (!theApp.emuledlg->IsRunning())
return;
LVFINDINFO find;
find.flags = LVFI_PARAM;
find.lParam = (LPARAM)client;
int result = FindItem(&find);
if (result != -1) {
DeleteItem(result);
theApp.emuledlg->transferwnd->UpdateListCount(CTransferWnd::wnd2Uploading);
}
}
void CUploadListCtrl::RefreshClient(const CUpDownClient* client)
{
// There is some type of timing issue here.. If you click on item in the queue or upload and leave
// the focus on it when you exit the cient, it breaks on line 854 of emuleDlg.cpp
// I added this IsRunning() check to this function and the DrawItem method and
// this seems to keep it from crashing. This is not the fix but a patch until
// someone points out what is going wrong.. Also, it will still assert in debug mode..
if (!theApp.emuledlg->IsRunning())
return;
LVFINDINFO find;
find.flags = LVFI_PARAM;
find.lParam = (LPARAM)client;
int result = FindItem(&find);
if (result != -1)
Update(result);
}
#define DLC_DT_TEXT (DT_LEFT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS)
void CUploadListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
if (!theApp.emuledlg->IsRunning())
return;
if (!lpDrawItemStruct->itemData)
return;
CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC);
BOOL bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS));
if (lpDrawItemStruct->itemState & ODS_SELECTED) {
if (bCtrlFocused)
odc->SetBkColor(m_crHighlight);
else
odc->SetBkColor(m_crNoHighlight);
}
else
odc->SetBkColor(GetBkColor());
const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData;
CMemDC dc(odc, &lpDrawItemStruct->rcItem);
CFont* pOldFont = dc.SelectObject(GetFont());
CRect cur_rec(lpDrawItemStruct->rcItem);
COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText);
if (client->GetSlotNumber() > CGlobalVariable::uploadqueue->GetActiveUploadsCount()) {
dc.SetTextColor(::GetSysColor(COLOR_GRAYTEXT));
}
int iOldBkMode;
if (m_crWindowTextBk == CLR_NONE){
DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0);
iOldBkMode = dc.SetBkMode(TRANSPARENT);
}
else
iOldBkMode = OPAQUE;
CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(client->GetUploadFileID());
CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
int iCount = pHeaderCtrl->GetItemCount();
cur_rec.right = cur_rec.left - 8;
cur_rec.left += 4;
CString Sbuffer;
for (int iCurrent = 0; iCurrent < iCount; iCurrent++)
{
int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
if (!IsColumnHidden(iColumn))
{
cur_rec.right += GetColumnWidth(iColumn);
switch (iColumn)
{
case 0:{
uint8 image;
if (client->IsFriend())
image = 4;
else if (client->GetClientSoft() == SO_EDONKEYHYBRID){
if (client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 8;
else
image = 7;
}
else if (client->GetClientSoft() == SO_MLDONKEY){
if (client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 6;
else
image = 5;
}
else if (client->GetClientSoft() == SO_SHAREAZA){
if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 10;
else
image = 9;
}
else if (client->GetClientSoft() == SO_AMULE){
if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 12;
else
image = 11;
}
else if (client->GetClientSoft() == SO_LPHANT){
if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 14;
else
image = 13;
}
else if (client->ExtProtocolAvailable()){
if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 3;
else
image = 1;
}
else{
if (client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
image = 2;
else
image = 0;
}
uint32 nOverlayImage = 0;
if ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED))
nOverlayImage |= 1;
if (client->IsObfuscatedConnectionEstablished())
nOverlayImage |= 2;
POINT point = {cur_rec.left, cur_rec.top+1};
imagelist.Draw(dc,image, point, ILD_NORMAL | ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED) ? INDEXTOOVERLAYMASK(1) : 0));
Sbuffer = client->GetUserName();
//EastShare Start - added by AndCycle, IP to Country
CString tempStr;
tempStr.Format(_T("%s%s"), client->GetCountryName(), Sbuffer);
Sbuffer = tempStr;
if(CGlobalVariable::ip2country->ShowCountryFlag()){
cur_rec.left += 20;
POINT point2= {cur_rec.left,cur_rec.top+1};
CGlobalVariable::ip2country->GetFlagImageList()->DrawIndirect(dc, client->GetCountryFlagIndex(), point2, CSize(18,16), CPoint(0,0), ILD_NORMAL);
}
//EastShare End - added by AndCycle, IP to Country
cur_rec.left += 20;
dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT);
cur_rec.left -= 20;
//EastShare Start - added by AndCycle, IP to Country
if(CGlobalVariable::ip2country->ShowCountryFlag()){
cur_rec.left-=20;
}
//EastShare End - added by AndCycle, IP to Country
break;
}
case 1:
if (file)
Sbuffer = file->GetFileName();
else
Sbuffer = _T("?");
break;
case 2:
Sbuffer = CastItoXBytes(client->GetDatarate(), false, true);
break;
case 3:
// NOTE: If you change (add/remove) anything which is displayed here, update also the sorting part..
if (thePrefs.m_bExtControls)
Sbuffer.Format( _T("%s (%s)"), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false));
else
Sbuffer = CastItoXBytes(client->GetSessionUp(), false, false);
break;
case 4:
if (client->HasLowID())
Sbuffer.Format(_T("%s (%s)"), CastSecondsToHM(client->GetWaitTime()/1000), GetResString(IDS_IDLOW));
else
Sbuffer = CastSecondsToHM(client->GetWaitTime()/1000);
break;
case 5:
Sbuffer = CastSecondsToHM(client->GetUpStartTimeDelay()/1000);
break;
case 6:
Sbuffer = client->GetUploadStateDisplayString();
break;
case 7:
cur_rec.bottom--;
cur_rec.top++;
client->DrawUpStatusBar(dc, &cur_rec, false, thePrefs.UseFlatBar());
cur_rec.bottom++;
cur_rec.top--;
break;
}
if (iColumn != 7 && iColumn != 0)
dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT);
cur_rec.left += GetColumnWidth(iColumn);
}
}
//draw rectangle around selected item(s)
if (lpDrawItemStruct->itemState & ODS_SELECTED)
{
RECT outline_rec = lpDrawItemStruct->rcItem;
outline_rec.top--;
outline_rec.bottom++;
dc.FrameRect(&outline_rec, &CBrush(GetBkColor()));
outline_rec.top++;
outline_rec.bottom--;
outline_rec.left++;
outline_rec.right--;
if (bCtrlFocused)
dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine));
else
dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine));
}
if (m_crWindowTextBk == CLR_NONE)
dc.SetBkMode(iOldBkMode);
dc.SelectObject(pOldFont);
dc.SetTextColor(crOldTextColor);
}
void CUploadListCtrl::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
{
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
const CUpDownClient* client = (iSel != -1) ? (CUpDownClient*)GetItemData(iSel) : NULL;
CTitleMenu ClientMenu;
ClientMenu.CreatePopupMenu();
//ClientMenu.AddMenuTitle(GetResString(IDS_CLIENTS), true);
ClientMenu.AppendMenu(MF_STRING | (client ? MF_ENABLED : MF_GRAYED), MP_DETAIL, GetResString(IDS_SHOWDETAILS), _T("CLIENTDETAILS"));
ClientMenu.SetDefaultItem(MP_DETAIL);
//ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && !client->IsFriend()) ? MF_ENABLED : MF_GRAYED), MP_ADDFRIEND, GetResString(IDS_ADDFRIEND), _T("ADDFRIEND"));
//ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient()) ? MF_ENABLED : MF_GRAYED), MP_MESSAGE, GetResString(IDS_SEND_MSG), _T("SENDMESSAGE"));
//ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && client->GetViewSharedFilesSupport()) ? MF_ENABLED : MF_GRAYED), MP_SHOWLIST, GetResString(IDS_VIEWFILES), _T("VIEWFILES"));
if (Kademlia::CKademlia::IsRunning() && !Kademlia::CKademlia::IsConnected())
ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && client->GetKadPort()!=0) ? MF_ENABLED : MF_GRAYED), MP_BOOT, GetResString(IDS_BOOTSTRAP));
//ClientMenu.AppendMenu(MF_STRING | (GetItemCount() > 0 ? MF_ENABLED : MF_GRAYED), MP_FIND, GetResString(IDS_FIND), _T("Search"));
GetPopupMenuPos(*this, point);
m_pMenuXP = new CMenuXP();
m_pMenuXP->AddMenu(&ClientMenu, TRUE);
ClientMenu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this);
delete m_pMenuXP;
m_pMenuXP = NULL;
}
BOOL CUploadListCtrl::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
wParam = LOWORD(wParam);
switch (wParam)
{
case MP_FIND:
OnFindStart();
return TRUE;
}
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
if (iSel != -1){
CUpDownClient* client = (CUpDownClient*)GetItemData(iSel);
switch (wParam){
case MP_SHOWLIST:
client->RequestSharedFileList();
break;
#if _DISABLE_NONUSE
case MP_MESSAGE:
theApp.emuledlg->chatwnd->StartSession(client);
break;
case MP_ADDFRIEND:
if (theApp.friendlist->AddFriend(client))
Update(iSel);
break;
#endif
case MP_DETAIL:
case MPG_ALTENTER:
case IDA_ENTER:
{
CClientDetailDialog dialog(client, this);
dialog.DoModal();
break;
}
case MP_BOOT:
if (client->GetKadPort())
Kademlia::CKademlia::Bootstrap(ntohl(client->GetIP()), client->GetKadPort(), (client->GetKadVersion() > 1));
break;
}
}
return true;
}
void CUploadListCtrl::OnColumnClick( NMHDR* pNMHDR, LRESULT* pResult){
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
// if it's a second click on the same column then reverse the sort order,
// otherwise sort the new column in ascending order.
// Barry - Store sort order in preferences
// Determine ascending based on whether already sorted on this column
bool sortAscending = (GetSortItem() != pNMListView->iSubItem) ? true : !GetSortAscending();
// Sort table
UpdateSortHistory(pNMListView->iSubItem + (sortAscending ? 0:100));
SetSortArrow(pNMListView->iSubItem, sortAscending);
SortItems(SortProc, pNMListView->iSubItem + (sortAscending ? 0:100));
*pResult = 0;
}
int CUploadListCtrl::SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
const CUpDownClient* item1 = (CUpDownClient*)lParam1;
const CUpDownClient* item2 = (CUpDownClient*)lParam2;
int iResult=0;
switch(lParamSort){
case 0:
if(item1->GetUserName() && item2->GetUserName())
iResult=CompareLocaleStringNoCase(item1->GetUserName(), item2->GetUserName());
else if(item1->GetUserName())
iResult=1;
else
iResult=-1;
break;
case 100:
if(item1->GetUserName() && item2->GetUserName())
iResult=CompareLocaleStringNoCase(item2->GetUserName(), item1->GetUserName());
else if(item2->GetUserName())
iResult=1;
else
iResult=-1;
break;
case 1: {
CKnownFile* file1 = CGlobalVariable::sharedfiles->GetFileByID(item1->GetUploadFileID());
CKnownFile* file2 = CGlobalVariable::sharedfiles->GetFileByID(item2->GetUploadFileID());
if( (file1 != NULL) && (file2 != NULL))
iResult=CompareLocaleStringNoCase(file1->GetFileName(), file2->GetFileName());
else if( file1 == NULL )
iResult=1;
else
iResult=-1;
break;
}
case 101:{
CKnownFile* file1 = CGlobalVariable::sharedfiles->GetFileByID(item1->GetUploadFileID());
CKnownFile* file2 = CGlobalVariable::sharedfiles->GetFileByID(item2->GetUploadFileID());
if( (file1 != NULL) && (file2 != NULL))
iResult=CompareLocaleStringNoCase(file2->GetFileName(), file1->GetFileName());
else if( file1 == NULL )
iResult=1;
else
iResult=-1;
break;
}
case 2:
iResult=CompareUnsigned(item1->GetDatarate(), item2->GetDatarate());
break;
case 102:
iResult=CompareUnsigned(item2->GetDatarate(), item1->GetDatarate());
break;
case 3:
iResult=CompareUnsigned(item1->GetSessionUp(), item2->GetSessionUp());
if (iResult == 0 && thePrefs.m_bExtControls) {
iResult = CompareUnsigned(item1->GetQueueSessionPayloadUp(), item2->GetQueueSessionPayloadUp());
}
break;
case 103:
iResult=CompareUnsigned(item2->GetSessionUp(), item1->GetSessionUp());
if (iResult == 0 && thePrefs.m_bExtControls) {
iResult = CompareUnsigned(item2->GetQueueSessionPayloadUp(), item1->GetQueueSessionPayloadUp());
}
break;
case 4:
iResult=item1->GetWaitTime() - item2->GetWaitTime();
break;
case 104:
iResult=item2->GetWaitTime() - item1->GetWaitTime();
break;
case 5:
iResult=item1->GetUpStartTimeDelay() - item2->GetUpStartTimeDelay();
break;
case 105:
iResult=item2->GetUpStartTimeDelay() - item1->GetUpStartTimeDelay();
break;
case 6:
iResult=item1->GetUploadState() - item2->GetUploadState();
break;
case 106:
iResult=item2->GetUploadState() - item1->GetUploadState();
break;
case 7:
iResult=item1->GetUpPartCount() - item2->GetUpPartCount();
break;
case 107:
iResult=item2->GetUpPartCount() - item1->GetUpPartCount();
break;
default:
iResult=0;
break;
}
int dwNextSort;
//call secondary sortorder, if this one results in equal
//(Note: yes I know this call is evil OO wise, but better than changing a lot more code, while we have only one instance anyway - might be fixed later)
if (iResult == 0 && (dwNextSort = theApp.emuledlg->transferwnd->uploadlistctrl.GetNextSortOrder(lParamSort)) != (-1)){
iResult= SortProc(lParam1, lParam2, dwNextSort);
}
return iResult;
}
void CUploadListCtrl::ShowSelectedUserDetails()
{
POINT point;
::GetCursorPos(&point);
CPoint p = point;
ScreenToClient(&p);
int it = HitTest(p);
if (it == -1)
return;
SetItemState(-1, 0, LVIS_SELECTED);
SetItemState(it, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
SetSelectionMark(it); // display selection mark correctly!
CUpDownClient* client = (CUpDownClient*)GetItemData(GetSelectionMark());
if (client){
CClientDetailDialog dialog(client, this);
dialog.DoModal();
}
}
void CUploadListCtrl::OnNMDblclk(NMHDR* /*pNMHDR*/, LRESULT* pResult)
{
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
if (iSel != -1){
CUpDownClient* client = (CUpDownClient*)GetItemData(iSel);
if (client){
CClientDetailDialog dialog(client, this);
dialog.DoModal();
}
}
*pResult = 0;
}
void CUploadListCtrl::OnGetDispInfo(NMHDR *pNMHDR, LRESULT *pResult)
{
__try
{
NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
if (theApp.emuledlg->IsRunning()){
// Although we have an owner drawn listview control we store the text for the primary item in the listview, to be
// capable of quick searching those items via the keyboard. Because our listview items may change their contents,
// we do this via a text callback function. The listview control will send us the LVN_DISPINFO notification if
// it needs to know the contents of the primary item.
//
// But, the listview control sends this notification all the time, even if we do not search for an item. At least
// this notification is only sent for the visible items and not for all items in the list. Though, because this
// function is invoked *very* often, no *NOT* put any time consuming code here in.
if (pDispInfo->item.mask & LVIF_TEXT){
const CUpDownClient* pClient = reinterpret_cast<CUpDownClient*>(pDispInfo->item.lParam);
if (pClient != NULL){
switch (pDispInfo->item.iSubItem){
case 0:
if (pClient->GetUserName() && pDispInfo->item.cchTextMax > 0){
_tcsncpy(pDispInfo->item.pszText, pClient->GetUserName(), pDispInfo->item.cchTextMax);
pDispInfo->item.pszText[pDispInfo->item.cchTextMax-1] = _T('\0');
}
break;
default:
// shouldn't happen
pDispInfo->item.pszText[0] = _T('\0');
break;
}
}
}
}
*pResult = 0;
}
__except(true)
{
}
}
void CUploadListCtrl::OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMLVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMLVGETINFOTIP>(pNMHDR);
if (pGetInfoTip->iSubItem == 0)
{
LVHITTESTINFO hti = {0};
::GetCursorPos(&hti.pt);
ScreenToClient(&hti.pt);
if (SubItemHitTest(&hti) == -1 || hti.iItem != pGetInfoTip->iItem || hti.iSubItem != 0){
// don' show the default label tip for the main item, if the mouse is not over the main item
if ((pGetInfoTip->dwFlags & LVGIT_UNFOLDED) == 0 && pGetInfoTip->cchTextMax > 0 && pGetInfoTip->pszText[0] != '\0')
pGetInfoTip->pszText[0] = '\0';
return;
}
const CUpDownClient* client = (CUpDownClient*)GetItemData(pGetInfoTip->iItem);
if (client && pGetInfoTip->pszText && pGetInfoTip->cchTextMax > 0)
{
CString info;
CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(client->GetUploadFileID());
// build info text and display it
info.Format(GetResString(IDS_USERINFO), client->GetUserName());
if (file)
{
info += GetResString(IDS_SF_REQUESTED) + _T(" ") + CString(file->GetFileName()) + _T("\n");
CString stat;
stat.Format(GetResString(IDS_FILESTATS_SESSION)+GetResString(IDS_FILESTATS_TOTAL),
file->statistic.GetAccepts(), file->statistic.GetRequests(), CastItoXBytes(file->statistic.GetTransferred(), false, false),
file->statistic.GetAllTimeAccepts(), file->statistic.GetAllTimeRequests(), CastItoXBytes(file->statistic.GetAllTimeTransferred(), false, false) );
info += stat;
}
else
{
info += GetResString(IDS_REQ_UNKNOWNFILE);
}
_tcsncpy(pGetInfoTip->pszText, info, pGetInfoTip->cchTextMax);
pGetInfoTip->pszText[pGetInfoTip->cchTextMax-1] = _T('\0');
}
}
*pResult = 0;
}
void CUploadListCtrl::ShowUpLoadingUsers(CList<CKnownFile *, CKnownFile*> & filelist)
{
DeleteAllItems();
CKnownFile* cur_file;
for (POSITION pos = filelist.GetHeadPosition(); pos != 0; )
{
cur_file =filelist.GetNext(pos);
CUpDownClient * pClient;
for (POSITION pos = cur_file->m_ClientUploadList.GetHeadPosition(); pos != 0; )
{
pClient = cur_file->m_ClientUploadList.GetNext(pos);
AddClient(pClient);
}
}
}
void CUploadListCtrl::OnDrawItem(int /*nIDCtl*/, LPDRAWITEMSTRUCT lpDrawItemStruct)// VC-linhai[2007-08-07]:warning C4100: “nIDCtl” : 未引用的形参
{
m_pMenuXP->DrawItem(lpDrawItemStruct);
}
void CUploadListCtrl::OnMeasureItem(int /*nIDCtl*/, LPMEASUREITEMSTRUCT lpMeasureItemStruct)// VC-linhai[2007-08-07]:warning C4100: “nIDCtl” : 未引用的形参
{
m_pMenuXP->MeasureItem(lpMeasureItemStruct);
}
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
]
| [
[
[
1,
784
]
]
]
|
34c90d873351bb4622f628fff747d94f64f42db2 | 0cf09d7cc26a513d0b93d3f8ef6158a9c5aaf5bc | /twittle/src/about_dialog.cpp | 334ce56c4dffe9f00f3e59bdf3a26433c144fae1 | []
| no_license | shenhuashan/Twittle | 0e276c1391c177e7586d71c607e6ca7bf17e04db | 03d3d388d5ba9d56ffcd03482ee50e0a2a5f47a1 | refs/heads/master | 2023-03-18T07:53:25.305468 | 2009-08-11T05:55:07 | 2009-08-11T05:55:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,924 | cpp | #include "about_dialog.h"
#include "static_url_text.h"
#include "application.h"
#include <wx/statline.h>
#include "resources/aboutlogo.xpm"
AboutDialog::AboutDialog(wxWindow *parent) : wxDialog(parent, wxID_ANY,
_T("About ") + wxGetApp().APPNAME, wxDefaultPosition, wxSize(305, 370))
{
InitializeComponents();
}
static void RecursiveBackground(wxSizer& sizer, const wxColour& colour)
{
wxSizerItemList::iterator it;
for (it = sizer.GetChildren().begin(); it != sizer.GetChildren().end(); ++it) {
wxWindow *win = (*it)->GetWindow();
if (win) win->SetBackgroundColour(colour);
else {
wxSizer *nextsizer = (*it)->GetSizer();
if (nextsizer) RecursiveBackground(*nextsizer, colour);
}
}
}
void AboutDialog::InitializeComponents()
{
wxButton *okButton = new wxButton(this, wxID_OK, _T("Ok"));
wxStaticText *twittle = new wxStaticText(this, wxID_ANY, wxGetApp().APPNAME);
wxFont font = twittle->GetFont();
font.SetWeight(wxFONTWEIGHT_BOLD);
twittle->SetOwnFont(font);
wxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
wxSizer *topImageSizer = new wxBoxSizer(wxHORIZONTAL);
wxSizer *topTextSizer = new wxBoxSizer(wxVERTICAL);
topImageSizer->Add(new wxStaticBitmap(this, wxID_ANY, wxBitmap(wxIcon(aboutlogo))));
topImageSizer->AddSpacer(10);
topTextSizer->Add(twittle, wxSizerFlags().Top());
topTextSizer->AddSpacer(3);
topTextSizer->Add(new wxStaticText(this, wxID_ANY, _T("A Really Friendly Twitter App")));
topTextSizer->Add(new wxStaticText(this, wxID_ANY, _T("By Loren Segal")), wxSizerFlags().Left());
topImageSizer->Add(topTextSizer, wxSizerFlags().Center());
topSizer->Add(topImageSizer, wxSizerFlags().Border(wxALL, 10));
topSizer->Add(new wxStaticText(this, wxID_ANY, wxGetApp().APPNAME));
topSizer->Add(new wxStaticText(this, wxID_ANY, _T("Version: ") + wxGetApp().APPVERSION));
topSizer->Add(new wxStaticText(this, wxID_ANY, _T("Copyright \xA9 2008")));
topSizer->Add(new wxStaticText(this, wxID_ANY, _T("Loren Segal")));
topSizer->Add(new wxStaticText(this, wxID_ANY, _T("All Rights Reserved.")));
topSizer->AddSpacer(17);
topSizer->Add(new StaticUrlText(this, wxID_ANY, _T("http://www.kthx.net/twittle")));
topSizer->AddSpacer(40);
wxSizer *topSizerBorder = new wxBoxSizer(wxVERTICAL);
topSizerBorder->Add(topSizer, wxSizerFlags(1).Expand().Border(wxALL, 15));
wxPanel *topPanel = new wxPanel(this);
RecursiveBackground(*topSizer, *wxWHITE);
topPanel->SetBackgroundColour(*wxWHITE);
topPanel->SetSizer(topSizerBorder);
wxSizer *bottomSizer = new wxBoxSizer(wxVERTICAL);
bottomSizer->Add(okButton, wxSizerFlags().Right().Bottom());
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(topPanel, wxSizerFlags(1).Expand());
sizer->Add(new wxStaticLine(this), wxSizerFlags().Expand());
sizer->Add(bottomSizer, wxSizerFlags(0).Border(wxALL, 15).Right());
SetSizer(sizer);
Center();
}
| [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
86d1fa00b261ff66e8911590bf674a63d0e2e221 | 99c792a222fd8fb93242598a247591e28a766769 | /commons/exception.cpp | 896d390281e38b380e0ed1b96bd50450c766bf60 | []
| no_license | benkopolis/windows-xml-logs-parser | 0cebfbdf104ef6d332278177eb89c1b7a375e7e9 | 54bc23afe11fc966ff848fa56ff9cb861af996e1 | refs/heads/master | 2016-09-06T02:17:09.855692 | 2011-06-06T10:29:53 | 2011-06-06T10:29:53 | 32,231,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | #include "exception.h"
Exception::Exception()
{
}
Exception::Exception(const QString& msg):
m_message(msg)
{
}
Exception::Exception(const QString& msg, const QString& file):
m_message(msg),
m_file(file)
{
}
Exception::Exception(const QString& msg, const QString& file, int line):
m_message(msg),
m_file(file),
m_line(line)
{
}
| [
"[email protected]@da19ff29-70bf-c5c3-61f4-a312932c5284"
]
| [
[
[
1,
26
]
]
]
|
048b1fc3ffaf4b9460ecb8d1328473a04678c7c4 | 216398e30aca5f7874edfb8b72a13f95c22fbb5a | /CamMonitor/Client/Test/ConfigDlg.cpp | 2a4a2891be5462d8ec2519135d38f80b46493fc2 | []
| no_license | markisme/healthcare | 791813ac6ac811870f3f28d1d31c3d5a07fb2fa2 | 7ab5a959deba02e7637da02a3f3c681548871520 | refs/heads/master | 2021-01-10T07:18:42.195610 | 2009-09-09T13:00:10 | 2009-09-09T13:00:10 | 35,987,767 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,549 | cpp | #include "stdafx.h"
#include "ConfigDlg.h"
#include "Config.h"
IMPLEMENT_DYNAMIC(ConfigDlg, CDialog)
ConfigDlg::ConfigDlg(CWnd* pParent /*=NULL*/) : CDialog(ConfigDlg::IDD, pParent)
{
}
ConfigDlg::~ConfigDlg()
{
}
void ConfigDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_ID, _editID);
DDX_Control(pDX, IDC_EDIT_PW, _editPass);
DDX_Control(pDX, IDC_CHECK1, _c1Box);
DDX_Control(pDX, IDC_CHECK2, _c2Box);
DDX_Control(pDX, IDC_CHECK3, _c3Box);
DDX_Control(pDX, IDC_CHECK4, _c4Box);
}
BEGIN_MESSAGE_MAP(ConfigDlg, CDialog)
ON_WM_SIZE()
ON_WM_CREATE()
ON_WM_DESTROY()
ON_BN_CLICKED(IDOK, &ConfigDlg::OnBnClickedOk)
ON_WM_CLOSE()
END_MESSAGE_MAP()
BOOL ConfigDlg::OnInitDialog()
{
CDialog::OnInitDialog();
_editID.SetWindowText( "asd" );
_editPass.SetWindowText( "1234" );
_c1Box.SetCheck( TRUE );
_c2Box.SetCheck( TRUE );
_c3Box.SetCheck( TRUE );
_c4Box.SetCheck( TRUE );
return TRUE; // return TRUE unless you set the focus to a control
}
void ConfigDlg::OnBnClickedOk()
{
CString id;
_editID.GetWindowText( id );
std::string idStr = id;
CString pass;
_editPass.GetWindowText( pass );
std::string passStr = pass;
// 로긴 요청
Network::GetInstance()._isSuccessAuth = -1;
Network::GetInstance().ReqLoginSend( idStr, passStr );
while( true )
{
// 패킷 처리
if( Network::GetInstance().ProcPacket() == TRUE )
{
if( Network::GetInstance()._isSuccessAuth == 1 )
{
// 프로그램 실행
AfxMessageBox("도난 감시 모드를 시작 하겠습니다.");
break;
}
else if( Network::GetInstance()._isSuccessAuth == 0 )
{
AfxMessageBox("비밀번호가 틀렸습니다.");
return;
}
}
}
//
Config::GetInstance()._isWebcamMode = IsWebcamMode();
Config::GetInstance()._isACPowerMode = IsACPowerMode();
Config::GetInstance()._isUSBMouseMode = IsUSBMouseMode();
Config::GetInstance()._isScreenSaverMode = IsScreenSaverMode();
//
OnOK();
}
void ConfigDlg::OnClose()
{
OnCancel();
}
BOOL ConfigDlg::IsWebcamMode()
{
if( _c1Box.GetCheck() )
{
return TRUE;
}
return FALSE;
}
BOOL ConfigDlg::IsACPowerMode()
{
if( _c2Box.GetCheck() )
{
return TRUE;
}
return FALSE;
}
BOOL ConfigDlg::IsUSBMouseMode()
{
if( _c3Box.GetCheck() )
{
return TRUE;
}
return FALSE;
}
BOOL ConfigDlg::IsScreenSaverMode()
{
if( _c4Box.GetCheck() )
{
return TRUE;
}
return FALSE;
} | [
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
]
| [
[
[
1,
130
]
]
]
|
28091ee797a5ca229fc33298563aee1941c278d1 | 38664d844d9fad34e88160f6ebf86c043db9f1c5 | /branches/initialize/infostudio/studio/publist.h | be65f5ade8bddefca36ca0f3bd884faf10697f12 | []
| no_license | cnsuhao/jezzitest | 84074b938b3e06ae820842dac62dae116d5fdaba | 9b5f6cf40750511350e5456349ead8346cabb56e | refs/heads/master | 2021-05-28T23:08:59.663581 | 2010-11-25T13:44:57 | 2010-11-25T13:44:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h |
#ifndef __PUBLISH_RESULT_LIST_H__
#define __PUBLISH_RESULT_LIST_H__
typedef CWinTraitsOR<WS_CLIPCHILDREN | WS_CLIPSIBLINGS> PublishResultListTraits;
class PublishResultList : public CWindowImpl<PublishResultList
, CListViewCtrl, PublishResultListTraits>
{
public:
BEGIN_MSG_MAP(PublishResultList)
END_MSG_MAP()
};
#endif // __PUBLISH_RESULT_LIST_H__
| [
"ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd"
]
| [
[
[
1,
17
]
]
]
|
5ecdeb5341ef2f7fd084576f2b5998fe4795b82a | b6f9507fe889d0a37d3ad4b4b884d81ca422ab70 | /functions/structures.cpp | 8a5fe53f4563564d5dd04bc7ff38244eeaa3d6e2 | []
| no_license | TheProjecter/stitchd | 12e446c530786591a1b0511d3bd81223c20cb4f0 | dd26757c7358abbbfe53b8cc0d7e6018f0306b03 | refs/heads/master | 2021-01-10T15:13:07.814211 | 2011-09-30T00:11:55 | 2011-09-30T00:11:55 | 45,934,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | class gameSave {
public:
int setLevel(int newLvl);
int setUnlock(int newUnlk);
int setRank(int newRnk);
private:
int playerLevel;
int playerUnlocks;
int playerRank;
};
int gameSave::setLevel(int newLvl) {
playerLevel = newLvl;
return playerLevel;
}
int gameSave::setUnlock(int newUnlk) {
playerUnlocks = newUnlk;
return newUnlk;
}
int gameSave::setRank(int newRnk) {
playerRank = newRnk;
return newRnk;
}
class createEnviro {
public:
OSL_IMAGE *target;
int xVar[];
int yVar[];
void makeObject(int xPos,
int yPos, int itemNo);
};
void createEnviro::makeObject(int xPos,
int yPos, int itemNo) {
xVar[itemNo] = xPos;
yVar[itemNo] = yPos;
oslDrawImageXY(target,
xVar[itemNo], yVar[itemNo]);
}
| [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
32490dc4c55422df61f885dff1e87d53d2d1b8ad | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /LoginServer/Application.cpp | f475537bd593d4fe35726df8589e38e87e493258 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,550 | cpp | #include "StdAfx.h"
#include "Application.h"
#include "resource.h"
extern LRESULT CALLBACK WindowProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam);
CApplication::CApplication(void)
: m_bContinue( TRUE )
, m_WindowWidth( 800 )
, m_WindowHeight( 600 )
{
}
CApplication::~CApplication(void)
{
}
ATOM CApplication::MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LOGINSERVER));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = m_szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
BOOL CApplication::InitInstance(HINSTANCE hInstance, int nCmdShow)
{
m_hInst = hInstance; // Store instance handle in our global variable
m_hWnd = CreateWindow(
m_szWindowClass,
m_szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0,
CW_USEDEFAULT, 0,
NULL,
NULL,
hInstance,
NULL);
if (!m_hWnd)
{
DWORD dwErr = GetLastError();
return FALSE;
}
ShowWindow(m_hWnd, nCmdShow);
UpdateWindow(m_hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CApplication::HandlerMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_NCCREATE:
if( !OnCreate() )
return DefWindowProc( hWnd, message, wParam, lParam );
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
if( !OnCommand( wmId, wmEvent, lParam ) )
return DefWindowProc( hWnd, message, wParam, lParam );
break;
case WM_PAINT:
hdc = BeginPaint(m_hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(m_hWnd, &ps);
break;
case WM_DESTROY:
m_bContinue = FALSE;
OnDestroy();
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
int CApplication::Go(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
MSG msg;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, m_szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDS_APPLICATION, m_szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
m_hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR));
// Main message loop:
while(m_bContinue)
{
if(GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, m_hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
return (int) msg.wParam;
}
bool CApplication::OnCreate()
{
return false;
}
bool CApplication::OnDestroy()
{
return false;
}
bool CApplication::OnCommand( INT nID, INT nEvent, LPARAM lParam )
{
return false;
}
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
158
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.