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
fe4bd5f273b33bbc29887675aaae6176951e5922
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/Kenwalt/KW_SMDK1/SMDK_FlashTank.h
40d4bee54a0370d79ad5b43a66fe344c7061d605
[]
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
2,102
h
#pragma once //================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __MD_HEADERS_H #include "md_headers.h" #endif //--------------------------------------------------------------------------- class CFlashTank : public MBaseMethod { friend class CSimpleSolverFn; public: CFlashTank(MUnitDefBase * pUnitDef, TaggedObject * pNd); virtual ~CFlashTank(void); virtual void Init(); virtual void BuildDataFields(); virtual bool ExchangeDataFields(); virtual void EvalMakeUpReqd(); virtual void EvalMakeUpAvail(); virtual bool EvalJoinPressures(); virtual void EvalProducts(); virtual void ClosureInfo(MClosureInfo & CI); // Flash Train - MacroMdls virtual void MacroMdlEvaluate(eScdMacroMdlEvals Eval); virtual bool MacroMdlValidNd(int iIONo) { return m_OnLine; }; virtual void MacroMdlAddNd(int iIONo) {}; virtual void MacroMdlRemoveNd(int iIONo) {}; virtual CMacroMdlBase* MacroMdlActivate() { return m_FTF; }; virtual void MacroMdlDeactivate() {}; protected: //void DoSimpleHeater(MStream & ShellI, MStream & TubeI, MStream & ShellO, MStream & TubeO); //double m_FlashPRqd; //double dRqdDuty; //double dActualDuty; //double dFeedT; //double dProdT; //long m_lOpMode; //double m_dHTC; //double m_dArea; //double m_dUA; //double m_dLMTD; //double m_dDuty; //double m_dLMTDFactor; //MReactionBlk m_RB; bool m_OnLine; MVLEBlk m_VLE; MFT_Flash m_FTF; MProbalPCtrl m_PCtrl; MStreamI m_Feed; // keep the feed in here - also save it. MStreamI m_WrkStrm; // temporary work };
[ [ [ 1, 61 ], [ 64, 64 ] ], [ [ 62, 63 ] ] ]
e02da9d727e350ff060d10062b457ab6bea6702c
c94135316a6706e7a1131e810222c12910cb8495
/MarbleMadness/Rampa.h
c94225e588c374b3e85f5b1174c6aab1070de22d
[]
no_license
lcianelli/compgraf-marble-madness
05d2e8f23adf034723dd3d1267e7cdf6350cf5e7
f3e79763b43a31095ffeff49f440c24614db045b
refs/heads/master
2016-09-06T14:20:10.951974
2011-05-28T21:10:48
2011-05-28T21:10:48
32,283,765
0
0
null
null
null
null
UTF-8
C++
false
false
568
h
#pragma once #ifndef MARBLE_Rampa_H #define MARBLE_Rampa_H #include "ObjetoEstatico.h" #include <list> #include <SDL_opengl.h> #include <gl\GL.h> #include <gl\GLU.h> #include "Vector.h" class Rampa : public ObjetoEstatico { protected: GLMmodel* objeto; public: float l, w, h; //dimensiones del Rampa, ancho, alto, y largo float *a; float froz; Rampa(void); void setAlturaSueloRampa(int nuevaAltura); Vector getNormalInteraccion(float* vectorDireccion, Vector &ptoCara); void dibujar(); ~Rampa(void); }; #endif
[ "lucia.cianelli@1aa7beb8-f67a-c4d8-682d-4e0fe4e45017", "srodriki@1aa7beb8-f67a-c4d8-682d-4e0fe4e45017" ]
[ [ [ 1, 11 ], [ 14, 27 ], [ 29, 36 ] ], [ [ 12, 13 ], [ 28, 28 ] ] ]
5eda06aea8502f6d7a97c52b22ffb2c4a9141924
314fa4d6839de9abfdedb72a521a156c06522761
/neckGirthTest/neckGirthTest/dib.h
ac12335d7bda81519f2b5f3bc49fb92804c0a2ba
[]
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
BIG5
C++
false
false
2,507
h
#pragma once //#include <afxwin.h> class CDib : public CObject { public: // 讀入檔案 // CDib ( const char* bmpfile ); CDib ( CFile& file ); // 轉換自 DDB // CDib ( CBitmap& ddb, CPalette* palette ); // 建立空白 DIB // CDib ( int Width, int Height, int BitsPerPixel ); ~CDib ( ); // DIB 相關資訊 // // 傳回像點陣列 // const void* GetBits() const; // 傳回每像點的位元數 // int GetBitsPerPixel ( ) const; // 傳回影像尺寸 // BOOL GetDimension ( CSize& size ) const; DWORD Width() const; DWORD Height() const; // 調色盤的大小 // int GetPaletteCount () const; // 每條掃瞄線所需的位元組數 // DWORD BytesPerLine() const; // 取得調色盤 // CPalette* GetPalette(); // 繪圖函數 // // 在 DC 上縮放輸出 // int StretchToDC ( CDC& dc, CRect& src, CRect& dst, DWORD rop = SRCCOPY ); // 在 DC 上等尺寸輸出 // int SetToDC ( CDC& dc, CRect& src, CPoint& dst ); // 輸出到 DDB // BOOL CopyTo ( CBitmap& ); // 檔案相關 // // 存檔 // BOOL SaveFile ( char* bmpfile ); // 寫入指定檔案 // BOOL DoWrite ( CFile& file ); // 自指定檔案讀入 // BOOL DoRead ( CFile& file ); protected: // 計算像點陣列的大小 // long GetBodySize() const; // 計算標頭含調色盤的大小 // int GetHeaderSize() const; // 初設標頭部的資料 // void InitDibInfo ( int , int = 0, int = 0 ); // 複製調色盤 // void CopyPalette ( CPalette& ); // 標頭 // BITMAPINFO* DibInfo; // 像點陣列 // void* DibBits; }; inline int CDib::GetBitsPerPixel() const { return ( !DibInfo ) ? 0 : DibInfo->bmiHeader.biBitCount; } inline const void* CDib::GetBits() const { return DibBits; } inline DWORD CDib::Width() const { return DibInfo->bmiHeader.biWidth; } inline DWORD CDib::Height() const { return DibInfo->bmiHeader.biHeight; } inline long CDib::GetBodySize() const { return BytesPerLine() * DibInfo->bmiHeader.biHeight; } inline DWORD CDib::BytesPerLine() const { DWORD bytes_per_line; // fillup byte // bytes_per_line = ( DibInfo->bmiHeader.biWidth * GetBitsPerPixel()+7)/8; // quad-byte alignment // bytes_per_line = ( bytes_per_line + 3 ) / 4; return bytes_per_line*4; } inline BOOL CDib::GetDimension ( CSize& size ) const { if ( !DibInfo ) return FALSE; size.cx = DibInfo->bmiHeader.biWidth; size.cy = DibInfo->bmiHeader.biHeight; return TRUE; }
[ "[email protected]@8026b7c3-d9ae-87c5-0fde-12bd377d1155" ]
[ [ [ 1, 87 ] ] ]
414602514c65daf783186c3d015aa89f1c942fae
a50397c3bf40972ed5d81ae506ba7d71cac5c9b8
/serverlib/Cnet.cpp
4e83a340606b51136497fe698565b1b7c771d1dd
[]
no_license
weimingtom/rpggamelib
f14cf5d4a7ddbaf335eeca6165e5a1e2ad742398
45c7b41976232b17ea68dbbaeab5b9d77201cdf5
refs/heads/master
2021-01-10T02:14:36.864458
2010-08-03T14:36:39
2010-08-03T14:36:39
44,464,476
1
0
null
null
null
null
GB18030
C++
false
false
1,704
cpp
#include "Cnet.h" Cnet::Cnet(void) { } Cnet::~Cnet(void) { } /************************************************************************/ /* 创建套接字 /************************************************************************/ bool Cnet::CreateSocket() { socket = ::WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED); if (INVALID_SOCKET==socket) { return false; } return true; } /************************************************************************/ /* 套接字端口绑定 /************************************************************************/ bool Cnet::bind(const unsigned short port) { ZeroMemory((char *)&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); if(::bind(socket,(sockaddr *)&addr,sizeof(addr)) == SOCKET_ERROR)return false; return true; } /************************************************************************/ /* 开始监听 /************************************************************************/ bool Cnet::listen(const unsigned int max_connections) { if(::listen(socket,max_connections) == SOCKET_ERROR)return false; return true; } /************************************************************************/ /* 获取错误信息 /************************************************************************/ int Cnet::getError() { return ::WSAGetLastError(); } /************************************************************************/ /* 关闭套接字 /************************************************************************/ bool Cnet::close() { if(::closesocket(socket) == SOCKET_ERROR) return false; return true; }
[ "cjmxp2009@9adff23b-f469-82f9-6d93-7372faa5fc81" ]
[ [ [ 1, 56 ] ] ]
2477d5e153fa24fbd6d93e12fcc3df3c6482380c
28a5dacf5e1a5a2d0d3fdf89bdc12a88dd897f86
/LoginDlg.h
f991a5c64ed567452272bdcd1248df60856692bb
[]
no_license
yogengg6/fp_attendance
3f4cababbe33d03e519341a6312015e5cb365a63
574338e53717ff2fbc62c57f14fa749a3a84a53a
refs/heads/master
2020-04-07T20:02:06.843808
2011-07-20T13:09:12
2011-07-20T13:09:12
158,672,408
0
0
null
null
null
null
GB18030
C++
false
false
1,039
h
/** * Project Name : FP_Attendance * description : a fingerprint based attendance(work with moodle attendanc * e module) * Copyleft : This program is published under GPL * Author : Yusuke([email protected]) * Date : 2011-5-11 20:29 */ #pragma once #include "mdldb/Mdldb.h" #include "Config.h" using namespace mdldb; class CLoginDlg : public CDialog { public: CLoginDlg(Config& cfg, CWnd* pParent = NULL); // 对话框数据 enum { IDD = IDD_FP_ATTENDANCE_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); protected: HICON m_hIcon; Config m_cfg; Mdldb m_mdl; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedConnect(); afx_msg void OnBnClickedExit(); afx_msg void OnMenuClickedConfig(); afx_msg void OnClickAbout(); };
[ "yusuke2000@e4a03d97-ca6b-4887-8e5f-4c51e936fd37" ]
[ [ [ 1, 46 ] ] ]
7b21caa3f84fa26e68103fe1ed59e56fe8abea42
be7df324d5509c7ebb368c884b53ea9445d32e4f
/GUI/Cardiac/MarchingCubes.cpp
771db956198a31685bd43d88e908c069d3a6ade7
[]
no_license
shadimsaleh/thesis.code
b75281001aa0358282e9cceefa0d5d0ecfffdef1
085931bee5b07eec9e276ed0041d494c4a86f6a5
refs/heads/master
2021-01-11T12:20:13.655912
2011-10-19T13:34:01
2011-10-19T13:34:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,433
cpp
////////////////////////////////////////////////////////////////////////////// // // Author : Josh Grant // Date : November 26th, 2001 // File : MarchingCubes.cpp // Description : Header file defining the MarchingCubes class // ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <cstring> #include "MarchingCubes.h" ////////////////////////////////////////////////////////////////////////////// // // MarchingCubes class // // All tables were based off of code written by Cory Bloyd // ([email protected]), from a nice description of the Marching // Cubes algorithm located at // http://www.swin.edu.au/astronomy/pbourke/modelling/polygonise/ // ////////////////////////////////////////////////////////////////////////////// // the blending percentage must be less than 0.5 #define MC_MAX_BLEND_PERCENT 0.499999f // blending technique added by Gokhan Kisacikoglu namespace blend { // The blending is nothing but a simple test to the closest voxel // corner. If we are too close, we accumulate the point and // average it later. The accumulated point will be kept in the // 'verts' for conservative memory management, but we have to // save at least its index and the number of accumulated points. // class point { public: point() : m_location(0, 0, 0), m_normal(0, 0, 0), m_vertexIndex(-1), m_hits(0) {} void set( int _vertexIndex, const SbVec3f &_location, const SbVec3f &_normal ) { m_vertexIndex = _vertexIndex; m_location = _location; m_normal = _normal; m_hits = 1; } int add( const SbVec3f &_location, const SbVec3f &_normal ) { m_location += _location; m_normal += _normal; ++ m_hits; return m_vertexIndex; } int hits() const { return m_hits; } SbVec3f location() const { return m_location / float(m_hits); } SbVec3f normal() const { return m_normal / float(m_hits); } int vertexIndex() const { return m_vertexIndex; } private: SbVec3f m_location, m_normal; int m_vertexIndex, m_hits; }; } // For each of the possible vertex states listed in this table there is a // specific triangulation of the edge intersection points. The table lists // all of them in the form of 0-5 edge triples with the list terminated by // the invalid value -1. For example: triTable[3] list the 2 triangles // formed when cube[0] and cube[1] are inside of the surface, but the rest of // the cube is not. static const short triTable[256][16] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, { 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, { 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, { 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, { 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, { 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, { 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, { 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, { 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, { 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, { 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, { 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, { 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, { 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, { 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, { 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, { 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, { 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, { 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, { 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, { 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, { 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, { 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, { 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, { 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, { 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, { 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, { 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, { 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, { 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, { 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, { 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, { 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, { 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, { 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, { 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, { 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, { 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, { 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, { 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, { 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, { 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, { 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, { 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, { 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, { 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, { 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, { 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, { 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, { 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, { 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, { 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, { 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, { 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, { 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, { 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, { 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, { 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, { 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, { 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, { 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, { 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, { 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, { 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, { 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, { 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, { 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, { 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, { 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, { 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, { 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, { 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, { 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, { 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, { 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, { 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, { 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, { 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, { 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, { 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, { 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, { 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, { 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, { 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, { 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, { 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, { 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, { 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, { 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, { 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, { 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, { 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, { 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, { 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, { 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, { 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, { 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, { 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, { 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, { 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, { 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, { 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, { 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, { 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, { 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, { 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, { 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, { 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, { 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, { 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, { 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, { 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, { 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, { 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, { 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, { 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, { 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, { 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, { 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, { 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, { 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, { 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, { 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, { 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, { 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, { 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, { 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, { 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, { 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, { 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, { 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, { 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, { 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, { 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, { 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, { 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, { 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, { 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, { 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, { 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, { 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, { 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, { 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, { 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, { 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, { 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, { 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, { 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, { 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, { 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, { 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, { 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, { 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, { 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; // offsets used to determine which vertex of a cube has a value >= to the // isoval. static const int cubeVertOffset[8][3] = { { 0, 0, 0}, {-1, 0, 0}, {-1, -1, 0}, { 0, -1, 0}, { 0, 0, -1}, {-1, 0, -1}, {-1, -1, -1}, { 0, -1, -1} }; // Inventor stuff SO_ENGINE_SOURCE(MarchingCubes); // Inventor stuff void MarchingCubes::initClass () { SO_ENGINE_INIT_CLASS(MarchingCubes, SoEngine, "Engine"); } ////////////////////////////////////////////////////////////////////////////// // // Description: // Default constructor initializes all class fields // ////////////////////////////////////////////////////////////////////////////// MarchingCubes::MarchingCubes () { SO_ENGINE_CONSTRUCTOR(MarchingCubes); dims[0] = dims[1] = dims[2] = 0; SO_ENGINE_ADD_INPUT(data, (dims, 0, false)); SO_ENGINE_ADD_INPUT(isoValue, (1.0)); SO_ENGINE_ADD_INPUT(blendPercent, (MC_MAX_BLEND_PERCENT)); SO_ENGINE_ADD_OUTPUT(points, SoMFVec3f); SO_ENGINE_ADD_OUTPUT(normals, SoMFVec3f); SO_ENGINE_ADD_OUTPUT(indexes, SoMFInt32); SO_ENGINE_ADD_OUTPUT(numTriangles, SoSFFloat); computeGradients = true; // surface will be created with coordinates between 0 and 1, making it // easier to translate and scale min = SbVec3f(0.0, 0.0, 0.0); max = SbVec3f(1.0, 1.0, 1.0); } MarchingCubes::~MarchingCubes () { } ////////////////////////////////////////////////////////////////////////////// // // Description: // Whenever the data field changes set the flag to recompute the // gradients. // ////////////////////////////////////////////////////////////////////////////// void MarchingCubes::inputChanged (SoField *which) { if (which == &data) computeGradients = true; } ////////////////////////////////////////////////////////////////////////////// // // Description: // Called by Inventor each time an output has been called and an input has // been modified. The points and the indexes will be computed here. // ////////////////////////////////////////////////////////////////////////////// void MarchingCubes::evaluate () { //currVert = 0; // reset the arrays holding the vertices and indexes before they are // modified. verts.setNum(0); norms.setNum(0); inds.setNum(0); // grab the current value of isoValue so that only one value will be used // during the computation. isoval = isoValue.getValue(); bperc = fabs(blendPercent.getValue()); bperc = (bperc < 0.5) ? bperc : MC_MAX_BLEND_PERCENT; // calculate the gradient at each grid point, this is called whenever the // data has been modified. if (computeGradients) { // get the latest values values = data.getValue(dims); // compute the size of each voxel (dependent on the dimensions of the // data) SbVec3f size = max - min; voxel[0] = (dims[0] > 1) ? size[0] / (float)(dims[0] - 1) : 0.0; voxel[1] = (dims[1] > 1) ? size[1] / (float)(dims[1] - 1) : 0.0; voxel[2] = (dims[2] > 1) ? size[2] / (float)(dims[2] - 1) : 0.0; // there are actually more than the standard (nx - 1)*(ny - 1)*(nz - 1) // number of cubes for the dataset. To speed computation up by // eliminating constant index bounds checking, a cube buffer is placed // around the actual cubes being used. This way if the indexing goes one // under zero or over the max it won't core dump :) cubeDims[0] = dims[0] + 1; cubeDims[1] = dims[1] + 1; cubeDims[2] = dims[2] + 1; // set the total number of cubes cubes.setNum(cubeDims[0] * cubeDims[1] * cubeDims[2]); // set the total number of edges being looked at. edgeIndex.setNum(3 * dims[0] * dims[1] * dims[2]); // calculate the gradients at each grid point. these gradients will be // used to interpolate the values at the surface points. calcGradients(); computeGradients = false; } // calculate the points on the surface calcPoints(); // create the triangle triples defining the triangles of the surface calcIndexes(); // send the results to the connected fields SO_ENGINE_OUTPUT(points, SoMFVec3f, setValues(0, verts.getNum(), verts.getValues(0))); SO_ENGINE_OUTPUT(normals, SoMFVec3f, setValues(0, norms.getNum(), norms.getValues(0))); int i = inds.getNum(); SO_ENGINE_OUTPUT(indexes, SoMFInt32, setNum(i)); SO_ENGINE_OUTPUT(indexes, SoMFInt32, setValues(0, i, inds.getValues(0))); SO_ENGINE_OUTPUT(numTriangles, SoSFFloat, setValue(triNum)); } ////////////////////////////////////////////////////////////////////////////// // // Description: // To avoid calculating points multiple times a "Marching Edges" // technique is used (this may as well be called something else by someone // else, I do not know. I did not research on this technique, just // thought of it one day while waiting in an airport.) Instead of // searching each cube of data one by one and accessing 8 different points // at once only 2 are looked at each time, and less assigments are made. // The two pulled out make up an edge on a cube. If the isoValue is // inbetween the two edge values then a point is computed for the // surface. To eliminate additional calls to the same data point the // order of operation is done in the following manner... // // V2 // | V1 // y| / // | / z // |/ // V0-------V3 // x // // V0 and V1 are checked, // V0 and V2 are checked, // V0 and V3 are checked // // Every time a point is added to the 'verts' array its index is stored in // the 'edgeIndex' array. This way when building the triangles with the // Marching Cubes tables the proper edge can point to the proper point. // ////////////////////////////////////////////////////////////////////////////// void MarchingCubes::calcPoints () { int i, j, k, ci, cj, ck, cv; int currCube, currEdge, currVert, lastVert; int offset[3], checkDims[3]; int cyOffset, czOffset; int32_t *cptr, *eptr; int v1, v2, index; float delta, percent; SbVec3f basePt, pt, norm; const SbVec3f *gptr; // the point blending: we are allocating the voxel structure // in order to process as locate the blended points as possible later // blend :: point *bTableP, *bPntP; bool nearCorner; bTableP = new blend :: point[ dims[0] * dims[1] * dims[2] ]; // add a point to the vertice list. A point is added when it is determined // that the isosurface goes through an edge. Sets the normal as well. // (accumulate if too close to the voxel corner except for the boundaries) // #define MC_ADD_POINT(comp, v1, v2) \ { \ pt = basePt; \ delta = values[v2] - values[v1]; \ percent = (delta == 0.0) ? 0.5 : (isoval - values[v1]) / delta; \ pt[comp] += voxel[comp] * percent; \ norm = gptr[v1] + (gptr[v2] - gptr[v1]) * percent; \ norm.normalize(); \ \ nearCorner = ( fabs( percent ) < bperc); \ if ( i && j && k && \ i < checkDims[0] && j < checkDims[1] && k < checkDims[2] && \ ( nearCorner || ( fabs( 1.0f - percent ) < bperc ) ) ) \ { \ bPntP = bTableP + ((nearCorner) ? v1 : v2); \ if ( bPntP->hits() ) \ { \ lastVert = bPntP->add( pt, norm ); \ } \ else \ { \ bPntP->set( currVert, pt, norm ); \ lastVert = currVert; \ ++ currVert; \ } \ } \ else \ { \ verts.set1Value(currVert, pt); \ norms.set1Value(currVert, norm); \ lastVert = currVert; \ ++ currVert; \ } \ eptr[currEdge] = lastVert; \ } // check an edge to see if v2 is > the isoval. This is called // when it is already known that the v1 is <= to the isoval #define MC_CHECK_EDGE_1(comp) \ { \ v2 = v1 + offset[comp]; \ if (values[v2] > isoval) { \ MC_ADD_POINT(comp, v1, v2); \ } \ } \ currEdge++; // check an edge to see if v2 is <= to the isoval. This is called when it // is already know that v1 is > than the isoval. #define MC_CHECK_EDGE_2(comp) \ { \ v2 = v1 + offset[comp]; \ if (values[v2] <= isoval) { \ MC_ADD_POINT(comp, v1, v2); \ } \ } \ currEdge++; // set offsets for each direction offset[0] = 1; offset[1] = dims[0]; offset[2] = dims[0]*dims[1]; // just a temporary variable to avoid checking (dims[x] - 1) against a // number, the less CPU cycles the better. checkDims[0] = dims[0] - 1; checkDims[1] = dims[1] - 1; checkDims[2] = dims[2] - 1; // set offsets for each direction when computing the index of surrounding // cubes cyOffset = cubeDims[0]; czOffset = cubeDims[0] * cubeDims[1]; // initialize all variables gptr = gradients.getValues(0); eptr = edgeIndex.startEditing(); cptr = cubes.startEditing(); memset(cptr, 0, sizeof(int32_t)*cubeDims[0]*cubeDims[1]*cubeDims[2]); for (i = 0; i < dims[0]*dims[1]*dims[2]; i++) eptr[i] = -1; currCube = 0; currVert = 0; currEdge = 0; v1 = 0; // for each vertice, check the edges it is connected to in the positive // x,y,z direction. for (k = 0, ck = 1; k < dims[2]; k++, ck++) { basePt[2] = min[2] + k*voxel[2]; for (j = 0, cj = 1; j < dims[1]; j++, cj++) { basePt[1] = min[1] + j*voxel[1]; for (i = 0, ci = 1; i < dims[0]; i++, ci++) { basePt[0] = min[0] + i*voxel[0]; // most of the time all edges in each direction will be checked if (k < checkDims[2] && j < checkDims[1] && i < checkDims[0]) { // if the value at data point 'v1' is <= isoval then the cubes that // contain the point as a vertice need to have the bits toggled. if (values[v1] <= isoval) { // compute index of the current cube, this is always the cube // where 'v1' is vertex 0 currCube = ck*czOffset + cj*cyOffset + ci; for (cv = 0; cv < 8; cv++) { index = currCube + cubeVertOffset[cv][2]*czOffset + cubeVertOffset[cv][1]*cyOffset + cubeVertOffset[cv][0]; cptr[index] |= (1 << cv); } MC_CHECK_EDGE_1(2); MC_CHECK_EDGE_1(1); MC_CHECK_EDGE_1(0); } else { MC_CHECK_EDGE_2(2); MC_CHECK_EDGE_2(1); MC_CHECK_EDGE_2(0); } } else { if (values[v1] <= isoval) { currCube = ck*czOffset + cj*cyOffset + ci; for (cv = 0; cv < 8; cv++) { index = currCube + cubeVertOffset[cv][2]*czOffset + cubeVertOffset[cv][1]*cyOffset + cubeVertOffset[cv][0]; cptr[index] |= (1 << cv); } if (k < checkDims[2]) MC_CHECK_EDGE_1(2); if (j < checkDims[1]) MC_CHECK_EDGE_1(1); if (i < checkDims[0]) MC_CHECK_EDGE_1(0); } else { if (k < checkDims[2]) MC_CHECK_EDGE_2(2); if (j < checkDims[1]) MC_CHECK_EDGE_2(1); if (i < checkDims[0]) MC_CHECK_EDGE_2(0); } } v1++; } } } bPntP = bTableP; for (k = 0; k < dims[2]; ++k) { for (j = 0; j < dims[1]; ++j) { for (i = 0; i < dims[0]; ++i, ++ bPntP) { if ( bPntP->hits() ) { verts.set1Value(bPntP->vertexIndex(), bPntP->location()); norms.set1Value(bPntP->vertexIndex(), bPntP->normal()); } } } } delete [] bTableP; } ////////////////////////////////////////////////////////////////////////////// // // Description: // Create the index triples which will define the triangles used to create // the surface. This is done by iterating through each cube in 'cubes' (not // including the buffer cubes) and using the value as an index into the // 'triTable' array. The 'triTable' array is used to determine which // edges the surface is intersecting. Based on this information the edge // index is computed and then the index of the point is found. // ////////////////////////////////////////////////////////////////////////////// void MarchingCubes::calcIndexes () { int c, e, i, j, k, t; int currIndex; int v1, v2, v3; const int32_t *cptr, *eptr; // these offsets are used to index into the 'edgeIndex' array. The edges // of a cube according to the Marching Cubes table 'triTable' are different // then how the edges are stored in the 'edgeIndex' array. The offset of // an edge is found by indexing into the array by the edge number (0-11). // Notice these offsets are a function of the dimensions of the data. const int32_t offset[12] = { 2, 4, 3*dims[0] + 2, 1, 3*dims[1]*dims[0] + 2, 3*dims[1]*dims[0] + 4, 3*dims[1]*dims[0] + 3*dims[0] + 2, 3*dims[1]*dims[0] + 1, 0, 3, 3*dims[0] + 3, 3*dims[0] }; // get pointers to the cubes and edges cptr = cubes.getValues(0); eptr = edgeIndex.getValues(0); e = currIndex = triNum = 0; // for each cube use the value as an index into 'triTable' and determine if // the cube should have any triangles in it. for (k = 1; k < cubeDims[2] - 1; k++) { for (j = 1; j < cubeDims[1] - 1; j++) { for (i = 1; i < cubeDims[0] - 1; i++) { // create the cube index c = cubeDims[0] * (k*cubeDims[1] + j) + i; // at most there will be 5 triangles in a cube, cycle through until a // -1 is found (signifying no more triangles) for (t = 0; t < 15; t += 3) { if (triTable[cptr[c]][t] < 0) break; // extract the indexes by... // - look up triangle combination in 'triTable' // - use 't' to index into 'triTable' and determine which edges // make up the triangle // - use edge value as an index into the 'offset' array // - add offset to the current edge (always the lower left edge // of the current cube pointing in the z-direction) // - index into the 'edgeIndex' array and get the index of the // point corresponding to that edge. v1 = eptr[offset[triTable[cptr[c]][t + 0]] + e]; v2 = eptr[offset[triTable[cptr[c]][t + 1]] + e]; v3 = eptr[offset[triTable[cptr[c]][t + 2]] + e]; // the blending of vertices may have edges pointing to the same // vertex, this would be a waste of a triangle so it is ignored. if ( v1 == v2 || v2 == v3 || v1 == v3 ) continue; // just incase something went wrong a check can be made //if (v1 < 0 || v2 < 0 || v3 < 0) { // cout << "no point " << v1 << " " << v2 << " " << v3 << endl; // continue; //} // set the values to form a triangle inds.set1Value(currIndex++, v1); inds.set1Value(currIndex++, v2); inds.set1Value(currIndex++, v3); inds.set1Value(currIndex++, -1); triNum++; } c++; e += 3; } e += 3; } e += 3*dims[0]; } } ////////////////////////////////////////////////////////////////////////////// // // Description: // Computes the gradients at each grid point. This is called only when // the data has been changed. This way when computing normals at each // triangle vertex, tri-linear interpolation will be used to efficiently // calculate the values. // ////////////////////////////////////////////////////////////////////////////// void MarchingCubes::calcGradients () { int i, j, k; int index, xOffset, yOffset, zOffset; SbVec3f *grad; // set the total number of gradient values gradients.setNum(dims[0] * dims[1] * dims[2]); // macro used to determine normal for a given component #define MC_COMPONENT(c, i, offset) \ if (i == 0) \ grad[index][c] = (values[index + offset] - values[index]) / voxel[c]; \ else if (i == dims[c] - 1) \ grad[index][c] = (values[index] - values[index - offset]) / voxel[c]; \ else \ grad[index][c] = (values[index + offset] - values[index - offset]) / \ (2.0 * voxel[c]); // get pointer to start editing gradients grad = gradients.startEditing(); index = 0; // set offsets for each direction xOffset = 1; yOffset = dims[0]; zOffset = dims[0]*dims[1]; for (k = 0; k < dims[2]; k++) { for (j = 0; j < dims[1]; j++) { for (i = 0; i < dims[0]; i++) { MC_COMPONENT(0, i, xOffset); MC_COMPONENT(1, j, yOffset); MC_COMPONENT(2, k, zOffset); grad[index].normalize(); index++; } } } gradients.finishEditing(); }
[ [ [ 1, 881 ] ] ]
f13f6e90cd9ebaf2ae5f24eea6bf8db6ca73d10c
7d349e6342c084a4d11234a0aa0846db41c50303
/themeagent/Observable.cpp
9593cd4c7f681516c76ab301297b21d770f96606
[]
no_license
Tobbe/themeagent
8f72641228a9cbb4c57e3bcd7475aee5f755eb3d
cbdbf93859ee7ef5d43330da7dd270f7b966f0b2
refs/heads/master
2020-12-24T17:44:42.819782
2009-04-18T22:38:58
2009-04-18T22:38:58
97,412
3
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
#include "Observable.h" #include "Observer.h" void Observable::addObserver(Observer *o) { observers.push_back(o); } void Observable::notifyObservers(const Observable *o) { for (size_t i = 0; i < observers.size(); ++i) { observers[i]->update(o); } }
[ [ [ 1, 15 ] ] ]
ed192f804058f2435d49a4e6e85cbad9aa15fba3
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireChanger/WCRemind/DLGEnterNumber.cpp
7ce2ab3640219d54de4ad8896cc01c9877c8af13
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
2,181
cpp
// DLGEnterNumber.cpp : implementation file // #include "stdafx.h" #include "wcremind.h" #include "DLGEnterNumber.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDLGEnterNumber dialog CDLGEnterNumber::CDLGEnterNumber(CWnd* pParent /*=NULL*/) : CDialog(CDLGEnterNumber::IDD, pParent) { //{{AFX_DATA_INIT(CDLGEnterNumber) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT pdwNumber=0; } void CDLGEnterNumber::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDLGEnterNumber) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDLGEnterNumber, CDialog) //{{AFX_MSG_MAP(CDLGEnterNumber) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDLGEnterNumber message handlers BOOL CDLGEnterNumber::OnInitDialog() { CDialog::OnInitDialog(); GetDlgItem(IDOK)->SetWindowText(_lx("RMX.UI.SAVECLOSE","Save and close")); GetDlgItem(IDCANCEL)->SetWindowText(_lx("RMX.UI.CANCEL","Cancel")); SetWindowText(_lx("RMX.UI.XMANUAL","Specify period")); GetDlgItem(IDC_STATIC1)->SetWindowText(_lx("RMX.UI.XMANUAL_DSC","Enter number to specify period")); CString sNumber="0"; if(pdwNumber){ sNumber.Format("%i",*pdwNumber); } GetDlgItem(IDC_EDIT1)->SetWindowText(sNumber); ((CEdit*)GetDlgItem(IDC_EDIT1))->SetSel(0,1000,0); GetDlgItem(IDC_EDIT1)->SetFocus(); return FALSE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDLGEnterNumber::OnOK() { char sNumber[128]={0}; GetDlgItem(IDC_EDIT1)->GetWindowText(sNumber,sizeof(sNumber)); if(pdwNumber){ *pdwNumber=atol(sNumber); } CDialog::OnOK(); } BOOL CDLGEnterNumber::PreTranslateMessage(MSG* pMsg) { if(pMsg->message==WM_KEYDOWN){ if(pMsg->wParam==VK_RETURN){ OnOK(); return TRUE; } } return CDialog::PreTranslateMessage(pMsg); }
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 82 ] ] ]
9c8a0eafc7ec6ab3c4fe8eef6e15b86db1c4d577
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/Display/NormalProcess.cpp
a095a57ac1dfe6db5ce04785b3155519ddaf166e
[]
no_license
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,609
cpp
#include "stdafx.h" #include "../Display/NormalProcess.h" #include "../Display/Display.h" #include "../Display/Effect.h" #include "../Display/Texture.h" #include "../Display/RenderTarget.h" #include "../Display/camera.h" #include "../Core/Scripting.h" namespace ElixirEngine { //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- Key DisplayNormalProcess::s_uTypeTex2DKey = MakeKey(string("tex2d")); Key DisplayNormalProcess::s_uTypeGBufferKey = MakeKey(string("gbuffer")); //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- DisplayNormalProcess::DisplayNormalProcess(DisplayRef _rDisplay) : CoreObject(), m_rDisplay(_rDisplay), m_uNameKey(0), m_uViewportNameKey(0), m_vRTTypes(), m_vRTNames(), m_vRTIndexes(), m_mTextures(), m_bClear(true) { } DisplayNormalProcess::~DisplayNormalProcess() { } bool DisplayNormalProcess::Create(const boost::any& _rConfig) { CreateInfoPtr pInfo = boost::any_cast<CreateInfoPtr>(_rConfig); bool bResult = (NULL != pInfo) && (NULL != pInfo->m_pLuaObject); if (false != bResult) { bResult = CreateFromLuaConfig(*pInfo); } if (false != bResult) { m_pRTChain = m_rDisplay.GetRenderTargetChain(); } return bResult; } void DisplayNormalProcess::Update() { } void DisplayNormalProcess::Release() { m_uNameKey = 0; m_vRTTypes.clear(); m_vRTNames.clear(); m_mTextures.clear(); } void DisplayNormalProcess::RenderBegin() { RenderBegin(true); } void DisplayNormalProcess::RenderEnd() { m_pRTChain->RenderEnd(); } Key DisplayNormalProcess::GetNameKey() { return m_uNameKey; } bool DisplayNormalProcess::ClearRequired() { return m_bClear; } bool DisplayNormalProcess::CreateFromLuaConfig(CreateInfoRef _rInfo) { LuaObjectRef rLuaObject = *_rInfo.m_pLuaObject; LuaObject oRenderTargets = rLuaObject["render_targets"]; const string strName = rLuaObject["name"].GetString(); const UInt uRTCount = UInt(oRenderTargets.GetCount()); bool bResult = (false == strName.empty());// && (0 < uRTCount); if (false != bResult) { m_uNameKey = MakeKey(strName); const string strViewportName = rLuaObject["viewport"].GetString(); m_uViewportNameKey = MakeKey(strViewportName); if (0 < uRTCount) { m_vRTTypes.resize(uRTCount); m_vRTNames.resize(uRTCount); m_vRTIndexes.resize(uRTCount); for (UInt i = 0 ; uRTCount > i ; ++i) { LuaObject oRenderTarget = oRenderTargets[i + 1]; const string strRTType = oRenderTarget["type"].GetString(); const Key uRTTypeKey = MakeKey(strRTType); if (s_uTypeTex2DKey == uRTTypeKey) { const UInt uRTIndex = UInt(oRenderTarget["index"].GetInteger()); const string strRTName = oRenderTarget["name"].GetString(); const Key uRTNameKey = MakeKey(strRTName); DisplayTexturePtr pTexture = m_rDisplay.GetTextureManager()->Get(uRTNameKey); m_mTextures[uRTNameKey] = pTexture; bResult = (NULL != pTexture); m_vRTTypes[i] = uRTTypeKey; m_vRTNames[i] = uRTNameKey; m_vRTIndexes[i] = uRTIndex; } else if (s_uTypeGBufferKey == uRTTypeKey) { const UInt uRTIndex = UInt(oRenderTarget["index"].GetInteger()); m_vRTTypes[i] = uRTTypeKey; m_vRTNames[i] = uRTIndex; m_vRTIndexes[i] = uRTIndex; } if (false == bResult) { break; } } } Scripting::Lua::Get(rLuaObject, "clear", m_bClear, m_bClear); } return bResult; } void DisplayNormalProcess::RenderBegin(const bool _bSetViewport) { // prepare render targets m_pRTChain->DisableAllRenderTargets(); const UInt uCount = UInt(m_vRTNames.size()); for (UInt i = 0 ; uCount > i ; ++i) { const Key uRTTypeKey = m_vRTTypes[i]; if (s_uTypeTex2DKey == uRTTypeKey) { const Key uRTIndex = m_vRTIndexes[i]; const Key uRTName = m_vRTNames[i]; DisplayRenderTargetPtr pRT = m_pRTChain->GetRenderTarget(UInt(uRTIndex)); pRT->SetEnabled(true); pRT->SetIndex(i); pRT->SetRTOverride(m_rDisplay.GetTextureManager()->Get(uRTName)); } else if (s_uTypeGBufferKey == uRTTypeKey) { const Key uRTIndex = m_vRTIndexes[i]; DisplayRenderTargetPtr pRT = m_pRTChain->GetRenderTarget(UInt(uRTIndex)); pRT->SetEnabled(true); pRT->SetIndex(i); pRT->SetRTOverride(NULL); } } if (false != _bSetViewport) { // set view port m_rDisplay.GetCurrentCamera()->SetViewport(m_uViewportNameKey); } // start scene render m_pRTChain->SetImmediateWrite(0 == uCount); m_pRTChain->RenderBegin(DisplayRenderTarget::ERenderMode_NORMALPROCESS); if (false != ClearRequired()) { const UInt uBlack = D3DCOLOR_XRGB(0, 0, 0); const UInt uBlue = D3DCOLOR_XRGB(16, 32, 64); const UInt uClearColor = uBlack; m_pRTChain->RenderBeginPass(0); m_rDisplay.GetDevicePtr()->Clear(0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, uClearColor, 1.0f, 0L); m_pRTChain->RenderEndPass(); } } }
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 196 ] ] ]
0d68498a2999a77713b7c999ca87d56bf466d363
3e69b159d352a57a48bc483cb8ca802b49679d65
/branches/bokeoa-scons/kicad/buildmnu.cpp
d82c11ce5a48442597d15694af22812da7d929ed
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
8,712
cpp
/***********************************************/ /* buildmnu.h: construction du menu principal */ /***********************************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "wx/spinctrl.h" #include "kicad.h" #include "protos.h" #define BITMAP wxBitmap // ---------------------------------------------------------------------------- // resources // ---------------------------------------------------------------------------- // USE_XPM_BITMAPS #include "bitmaps.h" // Common bitmaps #include "zip.xpm" #include "unzip.xpm" #include "Browse_Files.xpm" #include "Editor.xpm" #include "New_Project.xpm" #include "Open_Project.xpm" #include "id.h" /* Fonctions locales */ /* Variables locales */ BEGIN_EVENT_TABLE(WinEDA_MainFrame, WinEDA_BasicFrame) EVT_SIZE(WinEDA_MainFrame::OnSize) EVT_CLOSE(WinEDA_MainFrame::OnCloseWindow) EVT_SASH_DRAGGED(ID_LEFT_FRAME, WinEDA_MainFrame::OnSashDrag) EVT_SASH_DRAGGED(ID_BOTTOM_FRAME, WinEDA_MainFrame::OnSashDrag) EVT_SASH_DRAGGED(ID_MAIN_COMMAND, WinEDA_MainFrame::OnSashDrag) EVT_MENU_RANGE(ID_LOAD_PROJECT,ID_LOAD_FILE_10, WinEDA_MainFrame::Process_Files) EVT_MENU(ID_SAVE_PROJECT, WinEDA_MainFrame::Process_Files) EVT_TOOL(ID_NEW_PROJECT, WinEDA_MainFrame::Process_Files) EVT_TOOL(ID_LOAD_PROJECT, WinEDA_MainFrame::Process_Files) EVT_TOOL(ID_SAVE_PROJECT, WinEDA_MainFrame::Process_Files) EVT_TOOL(ID_SAVE_AND_ZIP_FILES, WinEDA_MainFrame::Process_Files) EVT_MENU(ID_EXIT, WinEDA_MainFrame::Process_Special_Functions) EVT_MENU(ID_TO_EDITOR, WinEDA_MainFrame::Process_Fct) EVT_MENU(ID_BROWSE_AN_SELECT_FILE, WinEDA_MainFrame::Process_Fct) EVT_MENU(ID_SELECT_PREFERED_EDITOR, WinEDA_MainFrame::Process_Preferences) EVT_MENU(ID_SAVE_AND_ZIP_FILES, WinEDA_MainFrame::Process_Files) EVT_MENU(ID_READ_ZIP_ARCHIVE, WinEDA_MainFrame::Process_Files) EVT_MENU(ID_PREFERENCES_FONT_INFOSCREEN, WinEDA_MainFrame::Process_Preferences) EVT_MENU_RANGE(ID_LANGUAGE_CHOICE, ID_LANGUAGE_CHOICE_END, WinEDA_MainFrame::SetLanguage) EVT_MENU(ID_GENERAL_HELP, WinEDA_MainFrame::GetKicadHelp) EVT_MENU(ID_KICAD_ABOUT, WinEDA_MainFrame::GetKicadAbout) EVT_BUTTON(ID_TO_PCB, WinEDA_MainFrame::Process_Fct) EVT_BUTTON(ID_TO_CVPCB, WinEDA_MainFrame::Process_Fct) EVT_BUTTON(ID_TO_EESCHEMA, WinEDA_MainFrame::Process_Fct) EVT_BUTTON(ID_TO_GERBVIEW, WinEDA_MainFrame::Process_Fct) END_EVENT_TABLE() /*******************************************/ void WinEDA_MainFrame::ReCreateMenuBar(void) /*******************************************/ { int ii, jj; wxMenuBar * menuBar = GetMenuBar() ; if( menuBar == NULL ) { m_MenuBar = menuBar = new wxMenuBar(); m_FilesMenu = new wxMenu; wxMenuItem *item = new wxMenuItem(m_FilesMenu, ID_LOAD_PROJECT, _("&Open Project Descr"), _("Select an existing project descriptor") ); item->SetBitmap(open_project_xpm); m_FilesMenu->Append(item); item = new wxMenuItem(m_FilesMenu, ID_NEW_PROJECT, _("&New Project Descr"), _("Create new project descriptor") ); item->SetBitmap(new_project_xpm); m_FilesMenu->Append(item); item = new wxMenuItem(m_FilesMenu, ID_SAVE_PROJECT, _("&Save Project Descr"), _("Save current project descriptor") ); item->SetBitmap(save_project_xpm); m_FilesMenu->Append(item); m_FilesMenu->AppendSeparator(); item = new wxMenuItem(m_FilesMenu, ID_SAVE_AND_ZIP_FILES, _("Save &Project Files"), _("Save and Zip all project files") ); item->SetBitmap(zip_xpm); m_FilesMenu->Append(item); item = new wxMenuItem(m_FilesMenu, ID_READ_ZIP_ARCHIVE, _("&Unzip Archive"), _("UnZip archive file") ); item->SetBitmap(unzip_xpm); m_FilesMenu->Append(item); m_FilesMenu->AppendSeparator(); item = new wxMenuItem(m_FilesMenu, ID_EXIT, _("E&xit"), _("Quit Kicad") ); item->SetBitmap(exit_xpm); m_FilesMenu->Append(item); // Creation des selections des anciens fichiers m_FilesMenu->AppendSeparator(); for ( ii = 0; ii < 10; ii++ ) { if ( GetLastProject(ii).IsEmpty() ) break; m_FilesMenu->Append(ID_LOAD_FILE_1 + ii, GetLastProject(ii) ); } // Menu Browse wxMenu *browseMenu = new wxMenu(); item = new wxMenuItem(browseMenu, ID_TO_EDITOR, _("&Editor"), _("Text editor") ); item->SetBitmap(editor_xpm); browseMenu->Append(item); item = new wxMenuItem(browseMenu, ID_BROWSE_AN_SELECT_FILE, _("&Browse Files"), _("Read or edit files") ); item->SetBitmap(browse_files_xpm); browseMenu->Append(item); browseMenu->AppendSeparator(); item = new wxMenuItem(browseMenu, ID_SELECT_PREFERED_EDITOR, _("&Select Editor"), _("Select your prefered editor for file browsing") ); item->SetBitmap(editor_xpm); browseMenu->Append(item); // Preferences menu: wxMenu *PreferencesMenu = new wxMenu; item = new wxMenuItem(PreferencesMenu , ID_PREFERENCES_FONT_INFOSCREEN, _("Select Fonts"), _("Select Fonts and Font sizes")); item->SetBitmap(fonts_xpm); PreferencesMenu->Append(item); PreferencesMenu->AppendSeparator(); m_Parent->SetLanguageList(PreferencesMenu); // Menu Help: wxMenu *helpMenu = new wxMenu; item = new wxMenuItem(helpMenu , ID_GENERAL_HELP, _("Kicad &Help"), _("On line doc")); item->SetBitmap(help_xpm); helpMenu->Append(item); item = new wxMenuItem(helpMenu , ID_KICAD_ABOUT, _("Kicad &About"), _("Kicad Infos")); item->SetBitmap(info_xpm); helpMenu->Append(item); menuBar->Append(m_FilesMenu, _("&Projects")); menuBar->Append(browseMenu, _("&Browse")); menuBar->Append(PreferencesMenu, _("&Preferences")); menuBar->Append(helpMenu, _("&Help")); // Associate the menu bar with the frame SetMenuBar(menuBar); } else // simple mise a jour de la liste des fichiers anciens { wxMenuItem * item; int max_file = m_Parent->m_LastProjectMaxCount; for ( ii = max_file-1; ii >=0 ; ii-- ) { if( m_FilesMenu->FindItem(ID_LOAD_FILE_1 + ii) ) { item = m_FilesMenu->Remove(ID_LOAD_FILE_1 + ii); if ( item ) delete item; } } for ( jj = 0, ii = 0; ii < max_file; ii++ ) { if (GetLastProject(ii).IsEmpty() ) break; m_FilesMenu->Append(ID_LOAD_FILE_1 + jj, GetLastProject(ii) ); jj++; } } } /***************************************************/ void WinEDA_MainFrame::RecreateBaseHToolbar(void) /***************************************************/ { if ( m_HToolBar != NULL ) return; m_HToolBar = new WinEDA_Toolbar(TOOLBAR_MAIN, this, ID_H_TOOLBAR, TRUE); SetToolBar(m_HToolBar); // Set up toolbar m_HToolBar->AddTool(ID_NEW_PROJECT, BITMAP(new_project_xpm), wxNullBitmap, FALSE, -1, -1, (wxObject *) NULL, _("Create new project descriptor")); m_HToolBar->AddTool(ID_LOAD_PROJECT, BITMAP(open_project_xpm), wxNullBitmap, FALSE, -1, -1, (wxObject *) NULL, _("Select an existing project descriptor")); m_HToolBar->AddTool(ID_SAVE_PROJECT, BITMAP(save_project_xpm), wxNullBitmap, FALSE, -1, -1, (wxObject *) NULL, _("Save current project descriptor")); m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_SAVE_AND_ZIP_FILES, BITMAP(zip_xpm), wxNullBitmap, FALSE, -1, -1, (wxObject *) NULL, _("Archive all project files")); // after adding the buttons to the toolbar, must call Realize() to reflect // the changes m_HToolBar->Realize(); } /*************************************************/ void WinEDA_MainFrame::CreateCommandToolbar(void) /*************************************************/ { #define SEPAR 20 int sizex, sizey,width; wxBitmapButton * Butt; wxPoint pos; // delete and recreate the toolbar if( m_VToolBar ) return; m_CommandWin->GetClientSize(&sizex, &sizey); width = 300; // Set up toolbar width = 32; pos.x = 20; pos.y = 20; Butt = new wxBitmapButton(m_CommandWin, ID_TO_EESCHEMA, BITMAP(icon_eeschema_xpm), pos ); Butt->SetToolTip(_("EeSchema (Schematic editor)")); pos.x += width + SEPAR; Butt = new wxBitmapButton(m_CommandWin,ID_TO_CVPCB, BITMAP(icon_cvpcb_xpm), pos ); Butt->SetToolTip(_("Cvpcb (Componants to modules)")); pos.x += width + SEPAR; Butt = new wxBitmapButton(m_CommandWin, ID_TO_PCB, BITMAP(a_icon_pcbnew_xpm), pos ); Butt->SetToolTip(_("Pcbnew ( board editor )")); pos.x += width + SEPAR; Butt = new wxBitmapButton(m_CommandWin, ID_TO_GERBVIEW, BITMAP(icon_gerbview_xpm), pos ); Butt->SetToolTip(_("GerbView ( Gerber viewer )")); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 281 ] ] ]
6649092bb0a39ceef27cfd8836c3b0d11abae0ba
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Shape/Compound/Collection/ExtendedMeshShape/hkpExtendedMeshShape.h
0b130b5ab8387eb11b3ed883545c36c2797c1633
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,915
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_COLLIDE2_EXTENDED_MESH2_SHAPE_H #define HK_COLLIDE2_EXTENDED_MESH2_SHAPE_H #include <Physics/Collide/Shape/Compound/Collection/hkpShapeCollection.h> #include <Physics/Collide/Shape/Convex/Triangle/hkpTriangleShape.h> extern hkReal hkConvexShapeDefaultRadius; extern const hkClass hkpExtendedMeshShapeClass; class hkpMeshMaterial; class hkpSimpleMeshShape; class hkpMoppBvTreeShape; /// A class for wrapping geometric collision detection information. It can directly reference /// sets of triangle strips with vertex striding, and either 16 or 32 bit indices to vertices. /// It can also directly reference triangle soups, using three indices per triangle rather than one. /// It also handles degenerate triangles internally, so no extra checking is required by the user. /// The mesh shape creates hkTriangleShapes in the ShapeBuffer passed in to the getChildShape function. /// It gives these shapes a radius (see hkpConvexShape::getRadius()) as specified by the hkpExtendedMeshShape::getRadius() function. /// This class can also store lists of convex shapes. class hkpExtendedMeshShape: public hkpShapeCollection { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_CDINFO); HK_DECLARE_REFLECTION(); public: /// The striding of mesh indices enum IndexStridingType { INDICES_INVALID, // default, will raise assert. /// 16 bit "short" striding INDICES_INT16, /// 32 bit "int" striding INDICES_INT32, INDICES_MAX_ID }; enum MaterialIndexStridingType { MATERIAL_INDICES_INVALID, MATERIAL_INDICES_INT8, MATERIAL_INDICES_INT16, MATERIAL_INDICES_MAX_ID }; enum SubpartType { SUBPART_TRIANGLES, SUBPART_SHAPE }; struct Subpart { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpExtendedMeshShape::Subpart ); HK_DECLARE_REFLECTION(); public: inline Subpart(SubpartType type); Subpart(hkFinishLoadedObjectFlag flag){}; public: /// Subpart type hkEnum<SubpartType,hkInt8> m_type; /// A type defining whether 8 or 16 bits are used to index material. hkEnum<MaterialIndexStridingType,hkInt8> m_materialIndexStridingType; /// The byte offset between two hkMeshMaterials hkInt16 m_materialStriding; /// a pointer, pointing to a strided array of material index (hkUint8), one index for each triangle. /// - You are limited to a maximum of 256 materials per subpart. /// - You are not forced to store those indices in a hkUint8 array, with the striding m_materialIndexStriding /// parameter you can extract this /// - If you do not want to use materials, simply set this element to HK_NULL const void* m_materialIndexBase; //+nosave /// The byte offset between two material indices (Usually sizeof(hkUint8) or...) hkUint16 m_materialIndexStriding; /// The number of materials hkUint16 m_numMaterials; /// The base for the material table, the byte offset between two hkMeshMaterials is defined by /// m_materialStriding /// Note: On PS3 this must be aligned to a m_materialStriding boundary if you wish to access materials in your own code on SPU. const hkpMeshMaterial* m_materialBase; //+nosave }; /// A vertices subpart defines a triangle, a triangle list or a triangle strip. struct TrianglesSubpart : public hkpExtendedMeshShape::Subpart { public: HK_DECLARE_REFLECTION(); HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpExtendedMeshShape::TrianglesSubpart ); public: /// A partial initializing constructor. It will only set values in Debug /// apart from a default material that gets set in Release too. inline TrianglesSubpart(); TrianglesSubpart(hkFinishLoadedObjectFlag flag) : Subpart(flag) {}; /// the number of triangles int m_numTriangleShapes; // // Vertex information // /// A pointer to the first vertex, defined by three floats. /// Must be aligned on a 16 byte boundary const float* m_vertexBase; //+nosave /// The byte offset between two consecutive vertices (usually 12, 16 or more). int m_vertexStriding; /// The number of vertices. int m_numVertices; /// Triangle extrusion. This setting can help the bullet through paper issue in certain situations, /// without using continuous simulation, however it does not guarantee robust results. All triangles /// in this subpart are extruded in the direction specified (which defaults to 0, i.e is disabled). If you have a ground /// made of triangles, with nothing beneath it, you can extrude the triangles a few meters in the downwards direction. /// When high speed non-continuous debris hits the landscape it will be more likely to bounce off rather than /// tunnel through. The effects of this extrusion is improved when also using one sided welding, as contact /// points will be correctly rotated to point up, even when objects are deeply penetrating. hkVector4 m_extrusion; // // Triangle Index Information // /// A pointer to triples of vertex indices. /// Used to be a union type, but to make /// auto serialization possible, we leave it as /// a void* here. const void* m_indexBase; //+nosave /// The byte offset between two indices triples. /// - Eg. (Usually sizeof(hkUint16) if you use triangle strips /// - or 3 * sizeof(hkUint16) if you use independent triangles int m_indexStriding; /// A type defining whether 16 or 32 bits are used to index vertices. hkEnum<IndexStridingType,hkInt8> m_stridingType; /// A flag used to specify whether triangles should be returned wound the same way /// or alternate ways. It must be set to 0 or 1, and defaults to 0. /// If Triangle strips are used, each subsequent triangle in a list /// will be wound the alternate way. However for one sided welding, we require that /// all triangles have a consistent winding. This flag should be set to 1 in this case. This /// means the first triangle will be returned with vertices set to (0, 1, 2) and the second /// triangle will be returned with vertices set to (1, 3, 2). If this flag is set to 0 the /// second triangle will be returned with vertices set to (1, 2, 3). If independent triangles /// are used this flag should be set to 0 to maintain winding. hkInt8 m_flipAlternateTriangles; /// This information is set automatically when a subpart is added to a mesh and should be left at -1. /// It is the offset in a global array for all triangles in the mesh of the first triangle of this sub piece /// This info is used for "welding" collisions between triangles. int m_triangleOffset; //+default(-1) }; /// A shapes subpart defines a list of one or more convex shapes of type hkpConvexShape. struct ShapesSubpart : public hkpExtendedMeshShape::Subpart { public: HK_DECLARE_REFLECTION(); HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpExtendedMeshShape::ShapesSubpart ); public: ShapesSubpart( const hkpConvexShape*const* childShapes, int numChildShapes, const hkVector4& offset = hkVector4::getZero() ); ShapesSubpart( const hkpConvexShape*const* childShapes, int numChildShapes, const hkTransform& transform ); ShapesSubpart(hkFinishLoadedObjectFlag flag) : Subpart(flag) {}; ~ShapesSubpart(); private: /// This variable holds the number of child shapes /// and whether the offset is set and the rotation is set in the two top most bits public: const hkpConvexShape*const* m_childShapes; int m_numChildShapes; hkBool m_offsetSet; hkBool m_rotationSet; hkQuaternion m_rotation; hkVector4 m_translation; }; public: /// Constructs a new hkpExtendedMeshShape. /// This mesh supports triangle soups as well as shape soups. /// - The triangles are grouped in subparts and can be scaled and get a radius applied /// - The shapes can be grouped in subparts and can be translated on a per subpart basis. /// "numBitsForSubpart" is the number of bits used (in the 32 bit shape key) for the subpart index. /// Note that the highest bit is used as the type identifier, discerning whether this subpart consists /// of triangles or convex shapes. /// The remaining bits from the 32 bit shape key are used for the terminal index. By /// default numBitsForSubpartIndex is 12, which means the mesh shape can have 2^11 - 1 /// subparts (0xffffffff is the "invalid" shape key) = 2047, and each subpart can have 2^20 triangles = 1048576. /// The subpart is stored in the high bits, so you can extract subpart/terminal indices like this:<br> /// int subpartIndex = key >> ( 32 - mymesh->getNumBitsForSubpartIndex() );<br> /// int terminalIndex = key & ( ~0U >> mymesh->getNumBitsForSubpartIndex() ); hkpExtendedMeshShape( hkReal radius = hkConvexShapeDefaultRadius, int numBitsForSubpartIndex = 12 ); /// A utility constructor that creates and extended mesh shape from a mesh shape. hkpExtendedMeshShape( const class hkpMeshShape* meshShape ); /// Destructor. Simply removes the references to all childShapes ~hkpExtendedMeshShape(); /// Compute welding info. In order to weld collisions between triangles in this mesh, welding info must be created. /// Note that this function only creates welding information between triangles, not between convex pieces. /// You must call this after all subparts have been added to the mesh. /// The hkpMoppBvTreeShape you pass in must be built referencing this hkpMeshShape. /// This adds an additional 2 bytes per triangle storage overhead. /// This is an expensive call, and should be done off line, and the resultant hkpMeshShape /// serialized, to save the runtime overhead of computing the welding info. void computeWeldingInfo( const hkpMoppBvTreeShape* mopp, hkpWeldingUtility::WeldingType weldingType ); // // Subpart access // /// Adds a triangle subpart. To modify member xxxx of this triangle subpart later on, call getTrianglesSubpartAt(int ).xxxx = yyyy. virtual void addTrianglesSubpart( const TrianglesSubpart& part ); /// Adds a shape subpart. To modify member xxxx of this shape subpart later on, call getShapesSubpartAt(int ).xxxx = yyyy. virtual void addShapesSubpart( const ShapesSubpart& part ); /// Returns the number of all triangle subparts. inline int getNumTrianglesSubparts() const; /// Returns the number of all shape subparts. inline int getNumShapesSubparts() const; /// Gets read/write access to a triangle subpart. inline TrianglesSubpart& getTrianglesSubpartAt( int i ); /// Gets const access to a triangle subpart. inline const TrianglesSubpart& getTrianglesSubpartAt( int i ) const; /// Gets read/write access to a shape subpart. inline ShapesSubpart& getShapesSubpartAt( int i ); /// Gets const access to a shape subpart. inline const ShapesSubpart& getShapesSubpartAt( int i ) const; /// Gets the subpart that a shape key belongs to. inline const Subpart& getSubPart( hkpShapeKey shapeKey ) const; /// Gets the index of a subpart that a shape key belongs to. /// Note that this will only return the index within the subpart's specific type list, i.e. either the index in the triangles list or in the shapes list. /// You can get the subpart's type by calling getSubpartType(). HK_FORCE_INLINE hkInt32 getSubPartIndex( hkpShapeKey shapeKey ) const; /// Get the terminal shape's index within the subpart. HK_FORCE_INLINE hkInt32 getTerminalIndexInSubPart( hkpShapeKey key ) const; /// Gets the number of bits of a shape key used to encode the subpart. HK_FORCE_INLINE hkInt32 getNumBitsForSubpartIndex() const; /// Returns the first shape key of a subpart HK_FORCE_INLINE hkInt32 getSubpartShapeKeyBase( int subpartIndex) const; /// Get the type of the shape referenced by the supplied shape key. HK_FORCE_INLINE SubpartType getSubpartType( hkpShapeKey key ) const; // // Scaling and radius access // /// Set the scaling of all triangle subparts of the shape inline const hkVector4& getScaling() const; void setScaling( const hkVector4& scaling ) ; /// Gets the extra radius for every triangle. inline hkReal getRadius() const; /// Sets the extra radius for every triangle. inline void setRadius(hkReal r ); // // hkpShape Collection interface // /// Get the first child shape key. virtual hkpShapeKey getFirstKey() const; /// This function implements hkpShapeCollection::getNextKey /// NOTE: This function calls hkpTriangleUtil::isDegenerate to make sure no keys for degenerate triangles are returned /// If you are implementing your own mesh shape, your getNextKey function must make sure that it similarly does /// not return keys for degenerate triangles. You can use the hkpTriangleUtil::isDegenerate utility function to check whether /// triangles are valid. virtual hkpShapeKey getNextKey( hkpShapeKey oldKey ) const; // Gets the mesh material by shape key, or returns HK_NULL if m_materialIndexBase isn't defined const hkpMeshMaterial* getMeshMaterial( hkpShapeKey key ) const; // hkpShapeContainer::getChildShape() interface implementation. HKP_SHAPE_VIRTUAL const hkpShape* getChildShapeImpl( HKP_SHAPE_VIRTUAL_THIS hkpShapeKey key, ShapeBuffer& buffer ) HKP_SHAPE_VIRTUAL_CONST; // hkpShapeContainer::getCollisionFilterInfo() interface implementation. HKP_SHAPE_VIRTUAL hkUint32 getCollisionFilterInfoImpl( HKP_SHAPE_VIRTUAL_THIS hkpShapeKey key ) HKP_SHAPE_VIRTUAL_CONST; // // hkpShape interface // // hkpShape interface implementation. HKP_SHAPE_VIRTUAL void getAabbImpl( HKP_SHAPE_VIRTUAL_THIS const hkTransform& localToWorld, hkReal tolerance, hkAabb& out ) HKP_SHAPE_VIRTUAL_CONST; void recalcAabbExtents(); virtual void calcStatistics( hkStatisticsCollector* collector) const; virtual int calcSizeForSpu(const CalcSizeForSpuInput& input, int spuBufferSizeLeft) const; #ifdef HK_PLATFORM_SPU static void HK_CALL registerSimulationFunctions( hkpShape::ShapeFuncs& sf ); static void HK_CALL registerCollideQueryFunctions( hkpShape::ShapeFuncs& sf ); #endif protected: void assertTrianglesSubpartValidity( const TrianglesSubpart& part ); void assertShapesSubpartValidity ( const ShapesSubpart& part ); public: hkInt32 m_numBitsForSubpartIndex; hkVector4 m_scaling; // Cached AABB hkVector4 m_aabbHalfExtents; hkVector4 m_aabbCenter; /// This member variable to determine the maximum triangle size allowed. /// This defaults to 1e-7 (and is used to check against the triangle area squared). If you have algorithms /// that fail with triangles passed by this value, you can increase it to make the culling more aggressive. static hkReal m_triangleDengeneracyTolerance; protected: // On PS3 these must be aligned according to their size. struct TrianglesSubpart* m_trianglesSubparts; int m_numTrianglesSubparts; struct ShapesSubpart* m_shapesSubparts; int m_numShapesSubparts; public: hkArray<hkUint16> m_weldingInfo; hkEnum<hkpWeldingUtility::WeldingType, hkUint8> m_weldingType; // +default(hkpWeldingUtility::WELDING_TYPE_NONE) public: hkpExtendedMeshShape( hkFinishLoadedObjectFlag flag ); protected: /// If this shape only contains a single triangle subpart and/or single shapes subpart then these /// Can be embedded directly into the shape. This saves significantly on DMA transfers struct TrianglesSubpart m_embeddedTrianglesSubpart; /// Internal methods to help simplify the memory mgt involved when the subparts are embedded struct TrianglesSubpart* expandOneTriangleSubparts(); struct ShapesSubpart* expandOneShapesSubparts(); void freeTriangleSubparts(); void freeShapesSubparts(); /// The radius can only be set on construction. hkReal m_triangleRadius; int m_pad16[3]; //+serialized(false) }; #include <Physics/Collide/Shape/Compound/Collection/ExtendedMeshShape/hkpExtendedMeshShape.inl> #endif // HK_COLLIDE2_EXTENDED_MESH2_SHAPE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 433 ] ] ]
15b76e9c65a24a45b62c8cd98c17bcb9672a76c5
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/开发库/include/HZipFile.h
98de9bcda954a885eeba74f7cbc477d91fb1a954
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
1,651
h
#ifndef __ZIPFILE__H__ #define __ZIPFILE__H__ #pragma once #include <map> #ifndef FILE_CONTROL_CLASS #include "zip/zip.h" #include "zip/unzip.h" #endif //该文件不能处理有密码的压缩文件 //HZipFile暂时不能用,UnZipFile可以解压winRar压缩起来的Zip文件 struct ZipEntryInfo { int m_nIndex; long m_nSize; CString m_sName; }; //ZIP文件操作类 class FILE_CONTROL_API HZipFile { public: HZipFile(void); virtual ~HZipFile(void); BOOL ZipCreate(LPCTSTR pZipFileName, LPCTSTR pZipPassword=NULL); BOOL ZipFileAdd(LPCTSTR pDestZipName, LPCTSTR pSrcDiskPath); void Close(); protected: HZIP m_hZip; }; // UNZIP文件操作类 class FILE_CONTROL_API HUnzipFile { public: //所有的nIndex都是ZIP文件在视觉上的索引,从1开始 HUnzipFile(void); virtual ~HUnzipFile(void); BOOL Open(LPCTSTR pZipFileName, LPCTSTR pPassword=NULL); void Close();//关闭Zip文件,释放资源 int GetEntryCount() const;//得到Zip文件中文件的数量 LPCTSTR GetItemName(int nIndex);//得到Zip文件中文件的名字 BOOL GetEntryInfo(int nIndex, ZipEntryInfo& info); BOOL GetEntryInfo(LPCTSTR pName, ZipEntryInfo& info); BOOL UnZipAll(LPCTSTR pDiskDir);//解压所有到磁盘路径 BOOL Unzip2File(int nIndex, LPCTSTR pDestDiskDir=NULL); BOOL Unzip2File(LPCTSTR pName, LPCTSTR pDestDiskDir=NULL); BOOL Unzip2Buffer(int nIndex, void* pBuffer, int nSize); BOOL Unzip2Buffer(LPCTSTR pName, void* pBuffer, int nSize); protected: typedef std::map<CString, ZipEntryInfo> EntryInfoVsl; HZIP m_hZip; EntryInfoVsl m_vslEntryInfo; }; #endif
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 59 ] ] ]
df8b5984c5bf06a19f3de2b4402c1944a1b51ec3
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.8/cbear.berlios.de/windows/com/itypelib.hpp
cf9e47497f7ba78a14dd5fe7b2e22cc32327277c
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
4,401
hpp
#ifndef CBEAR_BERLIOS_DE_WINDOWS_COM_ITYPELIB_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_COM_ITYPELIB_HPP_INCLUDED #include <boost/filesystem/path.hpp> #include <cbear.berlios.de/windows/hmodule.hpp> #include <cbear.berlios.de/windows/syskind.hpp> #include <cbear.berlios.de/windows/com/pointer.hpp> #include <cbear.berlios.de/windows/com/exception.hpp> #include <cbear.berlios.de/windows/com/lcid.hpp> #include <cbear.berlios.de/windows/com/itypeinfo.hpp> namespace cbear_berlios_de { namespace windows { namespace com { class tlibattr_t: public policy::wrap<tlibattr_t, ::TLIBATTR> { public: typedef policy::wrap<tlibattr_t, ::TLIBATTR> wrap_type; explicit tlibattr_t(const internal_type &X): wrap_type(X) {} // globally unique library ID. uuid &guid() { return uuid::cpp_in_out(&this->internal().guid); } const uuid &guid() const { return uuid::cpp_in(&this->internal().guid); } // Locale of the TypeLibrary. lcid_t &lcid() { return this->internal().lcid; } const lcid_t lcid() const { return this->internal().lcid; } // Target hardware platform. syskind_t &syskind() { return syskind_t::wrap_ref(this->internal().syskind); } const syskind_t &syskind() const { return syskind_t::wrap_ref(this->internal().syskind); } // Major version number. ushort_t &wMajorVerNum() { return this->internal().wMajorVerNum; } const ushort_t &wMajorVerNum() const { return this->internal().wMajorVerNum; } // Minor version number. ushort_t &wMinorVerNum() { return this->internal().wMinorVerNum; } const ushort_t &wMinorVerNum() const { return this->internal().wMinorVerNum; } // Library flags. ushort_t &wLibFlags() { return this->internal().wLibFlags; } const ushort_t &wLibFlags() const { return this->internal().wLibFlags; } }; template<class Base> class pointer_content<Base, ::ITypeLib>: public pointer_content<Base, ::IUnknown> { public: itypeinfo_t gettypeinfoofguid(uuid const &Uuid) const { itypeinfo_t Result; exception::throw_unless(this->reference().GetTypeInfoOfGuid( *Uuid.c_in(), com::internal<out>(Result))); return Result; } template<class Interface> itypeinfo_t gettypeinfoofguid() const { return this->gettypeinfoofguid(uuid::of<Interface>()); } tlibattr_t getlibattr() const { tlibattr_t::internal_type *Temp; exception::throw_unless(this->reference().GetLibAttr(&Temp)); tlibattr_t Result(*Temp); this->reference().ReleaseTLibAttr(Temp); return Result; } }; typedef pointer< ::ITypeLib> itypelib; inline itypelib loadtypelib(const lpcwstr_t File) { itypelib Result; com::exception::throw_unless(::LoadTypeLib( File.get(), com::internal<out>(Result))); return Result; } inline void register_type_lib( const itypelib &TypeLib, const lpcwstr_t &FullPath, const lpcwstr_t &HelpDir) { com::exception::throw_unless(::RegisterTypeLib( com::internal<in>(TypeLib), const_cast<wchar_t *>(FullPath.get()), const_cast<wchar_t *>(HelpDir.get()))); } inline void un_register_type_lib( const uuid &LibId, ushort_t VerMajor, ushort_t VerMinor, const lcid_t &Lcid, const syskind_t &Syskind) { com::exception::throw_unless(::UnRegisterTypeLib( *LibId.c_in(), VerMajor, VerMinor, com::internal<in>(Lcid), Syskind.internal())); } inline void un_register_type_lib(const tlibattr_t &LibAttr) { un_register_type_lib( LibAttr.guid(), LibAttr.wMajorVerNum(), LibAttr.wMinorVerNum(), LibAttr.lcid(), LibAttr.syskind()); } inline itypelib loadregtypelib( uuid const &Uuid, ushort_t Major, ushort_t Minor, lcid_t const &Lcid) { itypelib Result; com::exception::throw_unless( ::LoadRegTypeLib( *Uuid.c_in(), Major, Minor, com::internal<in>(Lcid), com::internal<out>(Result))); return Result; } template<class T> class scoped_typelib { public: static const itypelib &typelib() { return TypeLib; } protected: scoped_typelib( ::UUID const &Uuid, ushort_t Major, ushort_t Minor, lcid_t const &Lcid) { TypeLib = loadregtypelib(uuid::cpp_in(&Uuid), Major, Minor, Lcid); } private: static itypelib TypeLib; }; template<class T> itypelib scoped_typelib<T>::TypeLib; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 189 ] ] ]
38a358dd0c6cc12f01946cb4c7ced08cdec71fe5
1d0aaab36740e9117022b3cf03029cede9f558ab
/Boat.h
c69e6133810f1d3adf719b7217164c3d186661fa
[]
no_license
mikeqcp/superseaman
76ac7c4b4a19a705880a078ca66cfd8976fc07d1
bebeb48e90270dd94bb1c85090f12c4123002815
refs/heads/master
2021-01-25T12:09:29.096901
2011-09-13T21:44:33
2011-09-13T21:44:33
32,287,575
0
0
null
null
null
null
UTF-8
C++
false
false
644
h
#pragma once #include "Cloth.h" class Boat { private: Model *boat; Cloth *sail; GLfloat sailAngle; glm::vec4 bomEnd; glm::mat4 translateBomMatrix; public: Boat(Model *boat, Cloth *sail); ~Boat(void); void Draw(); void DrawReflection(); void Update(glm::mat4 P, glm::mat4 V, glm::mat4 M, glm::vec4 lightPos); void SetWind(glm::vec4 wind){ sail->SetWind(wind); }; void RotateSail(GLfloat angle); void SetClipPlane(glm::vec4 clipPlane); GLfloat getSailAngle() { return sailAngle; } void SetTextures(Texture *textures, int texCount); void SetLookAtPos(glm::vec3 lookAtPos); };
[ "[email protected]@a54423c0-632b-0463-fc5f-a1ef5643ace0", "[email protected]@a54423c0-632b-0463-fc5f-a1ef5643ace0" ]
[ [ [ 1, 4 ], [ 6, 31 ], [ 34, 39 ] ], [ [ 5, 5 ], [ 32, 33 ] ] ]
11074195f25d68fedb213537deed392328e0efd9
a01b67b20207e2d31404262146763d3839ee833d
/trunk/Projet/tags/Monofin_20090606_release/EdgeDetection/pixmapitem.cpp
c80d28ff6aac68dd2d5319e686a0fda3e7a0e2d7
[]
no_license
BackupTheBerlios/qtfin-svn
49b59747b6753c72a035bf1e2e95601f91f5992c
ee18d9eb4f80a57a9121ba32dade96971196a3a2
refs/heads/master
2016-09-05T09:42:14.189410
2010-09-21T17:34:43
2010-09-21T17:34:43
40,801,620
0
0
null
null
null
null
ISO-8859-1
C++
false
false
10,408
cpp
#include <QGraphicsScene> #include <QTransform> #include <stdio.h> #include <math.h> #include <QLineF> #include <QPointF> #include "pixmapitem.h" #include "edgesextractionscene.h" PixmapItem::PixmapItem(QPixmap pix): QGraphicsPixmapItem(pix), _rotateAngl(0), _scale(1), _enter(false), _isForAlgo(false), _posMousePress(QPointF(0,0)), _posMouseMove(QPointF(0,0)) { dimInitWidth = pixmap().width(); dimInitHeight = pixmap().height(); X = dimInitWidth; Y = dimInitHeight; this->setAcceptHoverEvents(true); this->setFlag(QGraphicsItem::ItemIsMovable,true); this->setFlag(QGraphicsItem::ItemIsSelectable, true); } PixmapItem::~PixmapItem(){ if(_isForAlgo) delete _scircle; } void PixmapItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget){ Q_UNUSED(option); Q_UNUSED(widget); if(!this->pixmap().isNull()){ if(_enter) painter->setPen(QColor("red")); QPointF c = this->boundingRect().center(); qreal x = offset().x() + dimInitWidth / 2; qreal y = offset().y() + dimInitHeight / 2; painter->translate(x, y); if(_isForAlgo){ painter->rotate(_rotateAngl); painter->scale(_scale, _scale); } else{ painter->rotate(_rotateAngl + 180); painter->scale(_scale, - _scale); } painter->translate(-x, -y); this->offset(); painter->drawPixmap(this->boundingRect().topLeft(), pixmap()); QPen pen(QBrush("black"), 1); painter->setPen(pen); QRectF rect = this->boundingRect(); qreal radius = sqrt(rect.width() * rect.width() + rect.height() * rect.height()) / 2; painter->drawEllipse(rect.center() + QPointF(-1, -1), radius, radius); pen = QPen(QBrush("red"), 3); painter->setPen(pen); if(_isForAlgo){ /* * très long code trop compliqué qui ne sert pas à grand chose */ qreal axeSymetry = ((EdgesExtractionScene*)this->scene())->symetryAxe(); qreal heal = ((EdgesExtractionScene*)this->scene())->heal(); QPointF point; bool overAxe; point = _scircle->getQPointRotate(0, _rotateAngl, _scale); overAxe = point.x() + this->offset().x() > heal && point.y() + this->offset().y() < axeSymetry; bool fPOverAxe = overAxe; for(int i = 1; i < _scircle->getSPointNb(); i++){ point = _scircle->getQPointRotate(i, _rotateAngl, _scale); if(point.x() + this->offset().x() > heal && point.y() + this->offset().y() < axeSymetry){ if(overAxe) painter->drawLine(*(_scircle->getQPoint(i - 1)) + this->offset(), *(_scircle->getQPoint(i)) + this->offset()); else{ QPointF* iP = new QPointF(); QLineF segment = QLineF(_scircle->getQPointRotate(i - 1, _rotateAngl, _scale) + this->offset(), _scircle->getQPointRotate(i, _rotateAngl, _scale) + this->offset()); int intersect = segment.intersect(QLineF(0, axeSymetry, heal * 100, axeSymetry), iP); if(intersect != QLineF::BoundedIntersection) segment.intersect(QLineF(heal, 0, heal, axeSymetry * 2), iP); painter->translate(x, y); painter->rotate(-_rotateAngl); painter->scale(1/_scale, 1/_scale); painter->translate(-x, -y); painter->drawLine(*iP, _scircle->getQPointRotate(i, _rotateAngl, _scale) + QPointF(0.5, 0.5) + this->offset()); painter->translate(x, y); painter->rotate(_rotateAngl); painter->scale(_scale,_scale); painter->translate(-x, -y); overAxe = true; delete iP; } }else{ if(overAxe){ QPointF* iP = new QPointF(); QLineF segment = QLineF(_scircle->getQPointRotate(i - 1, _rotateAngl, _scale)+ this->offset(), _scircle->getQPointRotate(i, _rotateAngl, _scale) + this->offset()); int intersect = segment.intersect(QLineF(0, axeSymetry, heal * 100, axeSymetry), iP); if(intersect != QLineF::BoundedIntersection) segment.intersect(QLineF(heal, 0, heal, axeSymetry * 2), iP); painter->translate(x, y); painter->rotate(-_rotateAngl); painter->scale(1/_scale, 1/_scale); painter->translate(-x, -y); painter->drawLine(_scircle->getQPointRotate(i - 1, _rotateAngl, _scale) + QPointF(0.5, 0.5) + this->offset(), *iP); painter->translate(x, y); painter->rotate(_rotateAngl); painter->scale(_scale,_scale); painter->translate(-x, -y); overAxe = false; delete iP; } } } if(overAxe && fPOverAxe) painter->drawLine(*(_scircle->getQPoint(_scircle->getSPointNb()-1)) + this->offset(), *(_scircle->getQPoint(0)) + this->offset()); if(!overAxe && fPOverAxe){ QPointF* iP = new QPointF(); QLineF segment = QLineF(_scircle->getQPointRotate(_scircle->getSPointNb()-1, _rotateAngl, _scale) + this->offset(), _scircle->getQPointRotate(0, _rotateAngl, _scale) + this->offset()); int intersect = segment.intersect(QLineF(0, axeSymetry, heal * 100, axeSymetry), iP); if(intersect != QLineF::BoundedIntersection) segment.intersect(QLineF(heal, 0, heal, axeSymetry * 2), iP); painter->translate(x, y); painter->rotate(-_rotateAngl); painter->scale(1/_scale, 1/_scale); painter->translate(-x, -y); painter->drawLine(*iP, _scircle->getQPointRotate(0, _rotateAngl, _scale) + this->offset()); painter->translate(x, y); painter->rotate(_rotateAngl); painter->scale(_scale,_scale); painter->translate(-x, -y); delete iP; } if(overAxe && !fPOverAxe){ QPointF* iP = new QPointF(); QLineF segment = QLineF(_scircle->getQPointRotate(_scircle->getSPointNb()-1, _rotateAngl, _scale)+ this->offset(), _scircle->getQPointRotate(0, _rotateAngl, _scale) + this->offset()); int intersect = segment.intersect(QLineF(0, axeSymetry, heal * 100, axeSymetry), iP); if(intersect != QLineF::BoundedIntersection) segment.intersect(QLineF(heal, 0, heal, axeSymetry * 2), iP); painter->translate(x, y); painter->rotate(-_rotateAngl); painter->scale(1/_scale, 1/_scale); painter->translate(-x, -y); painter->drawLine(_scircle->getQPointRotate(_scircle->getSPointNb()-1, _rotateAngl, _scale) + this->offset(), *iP); painter->translate(x, y); painter->rotate(_rotateAngl); painter->scale(_scale,_scale); painter->translate(-x, -y); delete iP; } QPen pen1(QBrush("yellow"), 5); painter->setPen(pen1); } } } void PixmapItem::center(){ qreal x = (this->scene()->width() - pixmap().width()) / 2; qreal y = (this->scene()->height() - pixmap().height()) / 2; setOffset(x, y); } void PixmapItem::translate2(qreal x, qreal y){ this->setOffset(offset().x() + x, offset().y() + y); if(this->childItems().first() != NULL) this->childItems().first()->translate(x, y); } void PixmapItem::rotate2(qreal angle){ _rotateAngl = angle; if(_rotateAngl >= 180) _rotateAngl -= 360; if(_rotateAngl < - 180) _rotateAngl += 360; } void PixmapItem::scaled(qreal scale){ if(scale >= 0.01 && scale <= 10){ _scale = scale; ((RotateCircle*)(this->childItems().first()))->setScale(_scale); X = dimInitWidth * _scale; Y = dimInitHeight * _scale; } } void PixmapItem::mousePressEvent ( QGraphicsSceneMouseEvent * event ){ _posMousePress = (event->scenePos() - this->offset()); _posMouseMove = event->scenePos(); } void PixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event){ this->prepareGeometryChange(); this->setOffset((event->scenePos() - _posMousePress)); this->childItems().first() ->translate(event->scenePos().x() - _posMouseMove.x(), event->scenePos().y() - _posMouseMove.y()); _posMouseMove = event->scenePos(); if(_isForAlgo) ((EdgesExtractionScene*)this->scene())->itemPositionChanged(); this->scene()->update(); } void PixmapItem::hoverEnterEvent(QGraphicsSceneHoverEvent * event){ _enter = true; this->setCursor(QCursor(Qt::OpenHandCursor)); this->scene()->update(); } void PixmapItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * event){ _enter = false; this->setCursor(QCursor(Qt::ArrowCursor)); this->scene()->update(); } void PixmapItem::wheelEvent ( QGraphicsSceneWheelEvent * event ){ event->accept(); if(event->delta() > 0 && _scale < 10) this->scaled(_scale + 0.01); if(event->delta() < 0 &&_scale > 0.01) this->scaled(_scale - 0.01); if(_isForAlgo) ((EdgesExtractionScene*)this->scene())->itemScaleChanged(); this->scene()->update(); }
[ "kryptos@314bda93-af5c-0410-b653-d297496769b1" ]
[ [ [ 1, 241 ] ] ]
3c87db359d9df94182a78a7a90e8c2083c2875e4
9b3403551e250529d7e6f04500d99f7c61669503
/WifiLoc/VirtualINS.h
14ba8f63bdc4a6c99e67dda44854bbd66625fcdc
[]
no_license
ashrafs/allhandstothepump
847f1cfe60927c76ba7a8c09092deb23327d42df
42abaf3e0478e0cca7374ee57a914895eddebc3f
refs/heads/master
2021-01-10T14:02:42.001763
2009-05-20T02:37:28
2009-05-20T02:37:28
44,780,671
0
0
null
null
null
null
UTF-8
C++
false
false
408
h
#pragma once class CVirtualINS { public: CVirtualINS(void); public: ~CVirtualINS(void); public: double m_X; double m_Y; double m_Speed; double m_SpdX; double m_SpdY; int m_bEnd; CPtrList *m_Path; POSITION m_CurPos; CPoint m_Start , m_End; void Init(CPtrList *path , double spd ); int Move(); CPoint GetPoint(); CPoint GetGrid(); CPoint SetGrid( int x , int y); };
[ "steampack99@fbba777c-2a28-11de-b896-015b45f1b0e6" ]
[ [ [ 1, 25 ] ] ]
1fefffd9dc79ba9c5ee9d2af25c65e7189183fcc
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/GameBase.cpp
ec71c4757795273d0694781182d6e2449058a2d8
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
19,589
cpp
// ----------------------------------------------------------------------- // // // MODULE : GameBase.cpp // // PURPOSE : Game base object class implementation // // CREATED : 10/8/99 // // (c) 1999-2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "GameBase.h" #include "CVarTrack.h" #include "ObjectMsgs.h" #include "CommandMgr.h" #include "VersionMgr.h" #include "TransitionAggregate.h" #include "ClientServerShared.h" #include "ParsedMsg.h" #include "ObjectTemplateMgr.h" #include "PlayerObj.h" extern CVarTrack g_ShowDimsTrack; CVarTrack g_vtDimsAlpha; LINKFROM_MODULE( GameBase ); BEGIN_CLASS(GameBase) ADD_BOOLPROP(Template, LTFALSE) PROP_DEFINEGROUP(GameType, PF_GROUP(16)) ADD_BOOLPROP_FLAG(SinglePlayer, 1, PF_GROUP(16)) ADD_BOOLPROP_FLAG(Cooperative, 1, PF_GROUP(16)) ADD_BOOLPROP_FLAG(Deathmatch, 1, PF_GROUP(16)) ADD_BOOLPROP_FLAG(TeamDeathmatch, 1, PF_GROUP(16)) ADD_BOOLPROP_FLAG(DoomsDay, 1, PF_GROUP(16)) END_CLASS_DEFAULT_FLAGS(GameBase, BaseClass, NULL, NULL, CF_HIDDEN) static CBankedList<CTransitionAggregate> s_bankCTransAggs; // ----------------------------------------------------------------------- // // // ROUTINE: LTBOOL ValidateMsgAttachDetach // // PURPOSE: Validation message for both ATTACH and DETACH messages // // ----------------------------------------------------------------------- // static LTBOOL ValidateMsgVisibleSolid( ILTPreInterface *pInterface, ConParse &cpMsgParams ) { char *pBoolValue = cpMsgParams.m_Args[1]; if( (!_stricmp(cpMsgParams.m_Args[1], "1")) || (!_stricmp(cpMsgParams.m_Args[1], "TRUE")) || (!_stricmp(cpMsgParams.m_Args[1], "0")) || (!_stricmp(cpMsgParams.m_Args[1], "FALSE")) ) { return LTTRUE; } if( CCommandMgrPlugin::s_bShowMsgErrors ) { pInterface->CPrint( "ERROR! - ValidateMsgVisibleSolid()" ); pInterface->CPrint( " MSG - %s - 2nd argument '%s' is not a valid bool value.", _strupr(cpMsgParams.m_Args[0]), cpMsgParams.m_Args[1] ); } return LTFALSE; } // // Register the calss with the command mgr plugin and add any messages to the class // CMDMGR_BEGIN_REGISTER_CLASS( GameBase ) CMDMGR_ADD_MSG( VISIBLE, 2, ValidateMsgVisibleSolid, "VISIBLE <bool>" ) CMDMGR_ADD_MSG( SOLID, 2, ValidateMsgVisibleSolid, "SOLID <bool>" ) CMDMGR_ADD_MSG( HIDDEN, 2, ValidateMsgVisibleSolid, "HIDDEN <bool>" ) CMDMGR_ADD_MSG( REMOVE, 1, NULL, "REMOVE" ) CMDMGR_END_REGISTER_CLASS( GameBase, BaseClass ) // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::GameBase() // // PURPOSE: Constructor // // ----------------------------------------------------------------------- // GameBase::GameBase(uint8 nType) : BaseClass(nType) { m_hDimsBox.SetReceiver( *this ); m_dwOriginalFlags = 0; m_pTransAgg = LTNULL; } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::~GameBase() // // PURPOSE: Destructor // // ----------------------------------------------------------------------- // GameBase::~GameBase() { DestroyTransitionAggregate(); RemoveBoundingBox(); } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::MakeTransitionable // // PURPOSE: Setup the transition aggregate... // // ----------------------------------------------------------------------- // void GameBase::MakeTransitionable( ) { // Only want one per object ASSERT( m_pTransAgg == LTNULL ); // Create it and add it... m_pTransAgg = s_bankCTransAggs.New(); if( !m_pTransAgg ) { g_pLTServer->CPrint( "new TransAgg FAILED!!!" ); return; } AddAggregate( (LPAGGREGATE)m_pTransAgg ); } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::DestroyTransitionAggregate // // PURPOSE: NONE // // ----------------------------------------------------------------------- // void GameBase::DestroyTransitionAggregate( ) { if( !m_pTransAgg ) return; #ifndef _FINAL CTransitionAggregate *pIAgg = dynamic_cast<CTransitionAggregate*>(m_pTransAgg); if( !pIAgg ) { g_pLTServer->CPrint( "NOT a CTransitionAggregate!!!" ); return; } #endif RemoveAggregate( (LPAGGREGATE)m_pTransAgg ); s_bankCTransAggs.Delete( m_pTransAgg ); m_pTransAgg = LTNULL; } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::AddToObjectList // // PURPOSE: Add ourselves to the list... // // ----------------------------------------------------------------------- // void GameBase::AddToObjectList( ObjectList *pObjList, eObjListControl eControl /*= eObjListNODuplicates*/ ) { if( !pObjList ) return; // Just add us... AddObjectToList( pObjList, m_hObject, eControl ); } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::ObjectMessageFn // // PURPOSE: Handle object-to-object messages // // ----------------------------------------------------------------------- // uint32 GameBase::ObjectMessageFn(HOBJECT hSender, ILTMessage_Read *pMsg) { if (!g_pLTServer) return 0; pMsg->SeekTo(0); uint32 messageID = pMsg->Readuint32(); switch(messageID) { case MID_TRIGGER: { const char* szMsg = (const char*)pMsg->Readuint32(); TriggerMsg(hSender, szMsg); // Make sure other people can read it... pMsg->SeekTo(0); } break; default : break; } return BaseClass::ObjectMessageFn(hSender, pMsg); } // --------------------------------------------------------------------------- // // // ROUTINE: GameBase::TriggerMsg() // // PURPOSE: Route trigger messages through the standard processing method // // --------------------------------------------------------------------------- // void GameBase::TriggerMsg(HOBJECT hSender, const char* szMsg) { if (!szMsg) return; // ConParse does not destroy szMsg, so this is safe ConParse parse; parse.Init((char*)szMsg); while (g_pCommonLT->Parse(&parse) == LT_OK) { // Don't parse empty messages if (!parse.m_nArgs || !parse.m_Args[0]) continue; CParsedMsg cCurMsg(parse.m_nArgs, parse.m_Args); OnTrigger(hSender, cCurMsg); } } // --------------------------------------------------------------------------- // // // ROUTINE: GameBase::OnTrigger() // // PURPOSE: Process GameBase trigger messages // // --------------------------------------------------------------------------- // bool GameBase::OnTrigger(HOBJECT hSender, const CParsedMsg &cMsg) { static CParsedMsg::CToken s_cTok_1("1"); static CParsedMsg::CToken s_cTok_True("TRUE"); static CParsedMsg::CToken s_cTok_0("0"); static CParsedMsg::CToken s_cTok_False("FALSE"); static CParsedMsg::CToken s_cTok_Visible("VISIBLE"); static CParsedMsg::CToken s_cTok_Solid("SOLID"); static CParsedMsg::CToken s_cTok_Hidden("HIDDEN"); static CParsedMsg::CToken s_cTok_Remove("REMOVE"); uint32 dwFlags; g_pCommonLT->GetObjectFlags(m_hObject, OFT_Flags, dwFlags); if (!m_dwOriginalFlags) { m_dwOriginalFlags = dwFlags; } if (cMsg.GetArg(0) == s_cTok_Visible) { if (cMsg.GetArgCount() > 1) { if ((cMsg.GetArg(1) == s_cTok_1) || (cMsg.GetArg(1) == s_cTok_True)) { dwFlags |= FLAG_VISIBLE; } else { if ((cMsg.GetArg(1) == s_cTok_0) || (cMsg.GetArg(1) == s_cTok_False)) { dwFlags &= ~FLAG_VISIBLE; } } g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, dwFlags, FLAGMASK_ALL); } } else if (cMsg.GetArg(0) == s_cTok_Solid) { if (cMsg.GetArgCount() > 1) { if ((cMsg.GetArg(1) == s_cTok_1) || (cMsg.GetArg(1) == s_cTok_True)) { dwFlags |= FLAG_SOLID; if (m_dwOriginalFlags & FLAG_RAYHIT) { dwFlags |= FLAG_RAYHIT; } } else { if ((cMsg.GetArg(1) == s_cTok_0) || (cMsg.GetArg(1) == s_cTok_False)) { dwFlags &= ~FLAG_SOLID; dwFlags &= ~FLAG_RAYHIT; } } g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, dwFlags, FLAGMASK_ALL); } } else if (cMsg.GetArg(0) == s_cTok_Hidden) { if (cMsg.GetArgCount() > 1) { if ((cMsg.GetArg(1) == s_cTok_1) || (cMsg.GetArg(1) == s_cTok_True)) { dwFlags &= ~FLAG_SOLID; dwFlags &= ~FLAG_RAYHIT; dwFlags &= ~FLAG_VISIBLE; } else { if ((cMsg.GetArg(1) == s_cTok_0) || (cMsg.GetArg(1) == s_cTok_False)) { // Not all objects should have solid set to true. // (e.g. AIs should never set solid true) if( m_dwOriginalFlags & FLAG_SOLID ) { dwFlags |= FLAG_SOLID; } if( m_dwOriginalFlags & FLAG_VISIBLE ) { dwFlags |= FLAG_VISIBLE; } if (m_dwOriginalFlags & FLAG_RAYHIT) { dwFlags |= FLAG_RAYHIT; } } } g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, dwFlags, FLAGMASK_ALL); } } else if ( cMsg.GetArg(0) == s_cTok_Remove ) { CPlayerObj* pPlayerObj = dynamic_cast< CPlayerObj* >( g_pLTServer->HandleToObject( m_hObject )); if( pPlayerObj ) { ASSERT( !"GameBase::OnTrigger: Tried to remove player object with trigger." ); g_pLTServer->CPrint( "Tried to remove player object with trigger" ); return false; } g_pLTServer->RemoveObject( m_hObject ); } else { return false; } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::CreateBoundingBox() // // PURPOSE: Create a bounding box // // ----------------------------------------------------------------------- // void GameBase::CreateBoundingBox() { if (m_hDimsBox) return; if (!g_vtDimsAlpha.IsInitted()) { g_vtDimsAlpha.Init(g_pLTServer, "DimsAlpha", LTNULL, 1.0f); } ObjectCreateStruct theStruct; INIT_OBJECTCREATESTRUCT(theStruct); LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); theStruct.m_Pos = vPos; SAFE_STRCPY(theStruct.m_Filename, "Models\\1x1_square.ltb"); SAFE_STRCPY(theStruct.m_SkinName, "Models\\1x1_square.dtx"); theStruct.m_Flags = FLAG_VISIBLE | FLAG_NOLIGHT | FLAG_GOTHRUWORLD; theStruct.m_ObjectType = OT_MODEL; HCLASS hClass = g_pLTServer->GetClass("BaseClass"); LPBASECLASS pModel = g_pLTServer->CreateObject(hClass, &theStruct); if (pModel) { m_hDimsBox = pModel->m_hObject; // Don't eat ticks please... ::SetNextUpdate(m_hDimsBox, UPDATE_NEVER); LTVector vDims; g_pPhysicsLT->GetObjectDims(m_hObject, &vDims); LTVector vScale; VEC_DIVSCALAR(vScale, vDims, 0.5f); g_pLTServer->ScaleObject(m_hDimsBox, &vScale); } LTVector vOffset; vOffset.Init(); LTRotation rOffset; HATTACHMENT hAttachment; LTRESULT dRes = g_pLTServer->CreateAttachment(m_hObject, m_hDimsBox, LTNULL, &vOffset, &rOffset, &hAttachment); if (dRes != LT_OK) { g_pLTServer->RemoveObject(m_hDimsBox); m_hDimsBox = LTNULL; } LTVector vColor = GetBoundingBoxColor(); g_pLTServer->SetObjectColor(m_hDimsBox, vColor.x, vColor.y, vColor.z, g_vtDimsAlpha.GetFloat()); } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::RemoveBoundingBox() // // PURPOSE: Remove the bounding box // // ----------------------------------------------------------------------- // void GameBase::RemoveBoundingBox() { if (m_hDimsBox) { HATTACHMENT hAttachment; if (g_pLTServer->FindAttachment(m_hObject, m_hDimsBox, &hAttachment) == LT_OK) { g_pLTServer->RemoveAttachment(hAttachment); } g_pLTServer->RemoveObject(m_hDimsBox); m_hDimsBox = LTNULL; } } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::EngineMessageFn // // PURPOSE: Handle engine messages // // ----------------------------------------------------------------------- // uint32 GameBase::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData) { switch(messageID) { case MID_ACTIVATING: { g_pCommonLT->SetObjectFlags(m_hObject, OFT_User, USRFLG_GAMEBASE_ACTIVE, USRFLG_GAMEBASE_ACTIVE); } break; case MID_DEACTIVATING: { g_pCommonLT->SetObjectFlags(m_hObject, OFT_User, 0, USRFLG_GAMEBASE_ACTIVE); } break; case MID_PRECREATE: { uint32 dwRet = BaseClass::EngineMessageFn(messageID, pData, fData); int nInfo = (int)fData; if (nInfo == PRECREATE_WORLDFILE || nInfo == PRECREATE_STRINGPROP || nInfo == PRECREATE_NORMAL) { ObjectCreateStruct* pocs = (ObjectCreateStruct*)pData; if( !ReadProp( pocs )) return 0; } return dwRet; } break; case MID_MODELSTRINGKEY: { uint32 dwRet = BaseClass::EngineMessageFn(messageID, pData, fData); // Let the CmdMgr take a crack at it. ArgList* pArgList = (ArgList*)pData; char szBuffer[256]; sprintf(szBuffer, ""); for ( int iArg = 0 ; iArg < pArgList->argc ; iArg++ ) { strcat(szBuffer, pArgList->argv[iArg]); strcat(szBuffer, " "); } szBuffer[strlen(szBuffer)-1] = 0; g_pCmdMgr->Process(szBuffer, m_hObject, m_hObject); return dwRet; } break; case MID_SAVEOBJECT: { Save((ILTMessage_Write*)pData); } break; case MID_LOADOBJECT: { Load((ILTMessage_Read*)pData); } break; default: break; } return BaseClass::EngineMessageFn(messageID, pData, fData); } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::GetBoundingBoxColor() // // PURPOSE: Get the color of the bounding box // // ----------------------------------------------------------------------- // LTVector GameBase::GetBoundingBoxColor() { LTVector vColor(1, 1, 1); switch (GetType()) { case OT_MODEL : vColor.Init(1, 0, 0); break; case OT_WORLDMODEL : vColor.Init(0, 0, 1); break; case OT_NORMAL : default : vColor.Init(1, 1, 1); break; } return vColor; } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::UpdateBoundingBox() // // PURPOSE: Update bounding box // // ----------------------------------------------------------------------- // void GameBase::UpdateBoundingBox() { int nVal = (int)g_ShowDimsTrack.GetFloat(); if (nVal < 4) { switch (GetType()) { case OT_WORLDMODEL : { if (nVal != 1) { RemoveBoundingBox(); return; } } break; case OT_MODEL : { if (nVal != 2) { RemoveBoundingBox(); return; } } break; case OT_NORMAL : { if (nVal != 3) { RemoveBoundingBox(); return; } } break; default : break; } } CreateBoundingBox(); if (m_hDimsBox) { LTVector vDims, vScale; g_pPhysicsLT->GetObjectDims(m_hObject, &vDims); vScale = (vDims * 2.0); g_pLTServer->ScaleObject(m_hDimsBox, &vScale); } } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::SetNextUpdate() // // PURPOSE: Allows objects to set their next update time and at // time same time update autodeactivation // // ----------------------------------------------------------------------- // void GameBase::SetNextUpdate(LTFLOAT fDelta, eUpdateControl eControl) { if (!m_hObject) return; fDelta = fDelta <= 0.0f ? 0.0f : fDelta; g_pLTServer->SetNextUpdate(m_hObject, fDelta); if (eControl == eControlDeactivation) { if (fDelta == 0.0f) { g_pLTServer->SetObjectState(m_hObject, OBJSTATE_INACTIVE); } else { g_pLTServer->SetObjectState(m_hObject, OBJSTATE_ACTIVE); } } } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::Save // // PURPOSE: Save the object // // ----------------------------------------------------------------------- // void GameBase::Save(ILTMessage_Write *pMsg) { SAVE_DWORD(g_pVersionMgr->GetSaveVersion()); SAVE_DWORD(m_dwOriginalFlags); } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::Load // // PURPOSE: Load the object // // ----------------------------------------------------------------------- // void GameBase::Load(ILTMessage_Read *pMsg) { // This old version didn't save the version number at the top. We need // to use an engine value to determine the version. uint32 nSaveFileVersion = 0; g_pLTServer->GetSaveFileVersion( nSaveFileVersion ); if( nSaveFileVersion == 2001 ) { LOAD_DWORD(m_dwOriginalFlags); uint32 nSaveVersion; LOAD_DWORD(nSaveVersion); g_pVersionMgr->SetCurrentSaveVersion( nSaveVersion ); HSTRING hDummy = NULL; LOAD_HSTRING(hDummy); g_pLTServer->FreeString( hDummy ); hDummy = NULL; } else { uint32 nSaveVersion; LOAD_DWORD(nSaveVersion); g_pVersionMgr->SetCurrentSaveVersion( nSaveVersion ); LOAD_DWORD(m_dwOriginalFlags); } } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::OnLinkBroken // // PURPOSE: Handle attached object getting removed. // // ----------------------------------------------------------------------- // void GameBase::OnLinkBroken( LTObjRefNotifier *pRef, HOBJECT hObj ) { if( pRef == &m_hDimsBox ) { HATTACHMENT hAttachment; if ( LT_OK == g_pLTServer->FindAttachment( m_hObject, hObj, &hAttachment) ) { g_pLTServer->RemoveAttachment(hAttachment); } } } // ----------------------------------------------------------------------- // // // ROUTINE: GameBase::ReadProp // // PURPOSE: Set property value // // ----------------------------------------------------------------------- // bool GameBase::ReadProp( ObjectCreateStruct* pStruct ) { if( !pStruct ) return false; // Check for a template object if( pStruct->m_cProperties.GetPropBool("Template", false)) { // Save the template g_pGameServerShell->GetObjectTemplates()->AddTemplate( pStruct ); // Don't actually create the object return false; } if ( !( pStruct->m_Name[0] )) { static int s_nUniqueId = 0; sprintf( pStruct->m_Name, "noname%d", s_nUniqueId++); } // Read properties based on gametype. switch( g_pGameServerShell->GetGameType( )) { case eGameTypeSingle: { if( !pStruct->m_cProperties.GetPropBool( "SinglePlayer", true )) return false; } break; case eGameTypeCooperative: { if( !pStruct->m_cProperties.GetPropBool( "Cooperative", true )) return false; } break; case eGameTypeDeathmatch: { if( !pStruct->m_cProperties.GetPropBool( "Deathmatch", true )) return false; } break; case eGameTypeTeamDeathmatch: { if( !pStruct->m_cProperties.GetPropBool( "TeamDeathmatch", true )) return false; } break; case eGameTypeDoomsDay: { if( !pStruct->m_cProperties.GetPropBool( "DoomsDay", true )) return false; } break; } return true; }
[ [ [ 1, 812 ] ] ]
85bc423d6698d3cd424fadcd0de4c8d4637d4c4f
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/include/RCF/Protocol/SF.hpp
8fb646d783fd3a2b548191cb48ca19f6864fdedc
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
1,710
hpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** #ifndef INCLUDE_RCF_PROTOCOL_SF_HPP #define INCLUDE_RCF_PROTOCOL_SF_HPP #include <RCF/Protocol/Protocol.hpp> #include <SF/IBinaryStream.hpp> #include <SF/OBinaryStream.hpp> #include <SF/string.hpp> namespace RCF { template<> class Protocol< boost::mpl::int_<SfBinary> > : public ProtocolImpl1<SF::IBinaryStream, SF::OBinaryStream> { public: static std::string getName() { return "SF binary serialization protocol"; } }; inline void enableSfPointerTracking_1(SF::OBinaryStream &obinStream, bool enable) { enable ? obinStream.enableContext(): obinStream.disableContext(); } } // namespace RCF /* #include <SF/ITextStream.hpp> #include <SF/OTextStream.hpp> namespace RCF { template<> class Protocol< boost::mpl::int_<SfText> > : public ProtocolImpl1<SF::ITextStream, SF::OTextStream> { public: static std::string getName() { return "SF text protocol"; } }; inline void enableSfPointerTracking_2(SF::OTextStream &otextStream, bool enable) { enable ? otextStream.enableContext(): otextStream.disableContext(); } } // namespace RCF */ #endif //! INCLUDE_RCF_PROTOCOL_SF_HPP
[ [ [ 1, 66 ] ] ]
96a02d5f875cc676593054f051f1a33408cbfee7
9f18fcd1e740b0b365cb9d97e2f99f315418be70
/my_tetris3d.cpp
f5e29c0477791162983595ed463dfee4d9647825
[]
no_license
ajantis/opengltetris3d
3227317648a66faa5456198d8c72c8727493157f
0626134baf4ff19e975de18e55344afb228969bd
refs/heads/master
2016-09-10T13:40:28.279730
2010-04-21T13:59:48
2010-04-21T13:59:48
32,183,937
0
0
null
null
null
null
UTF-8
C++
false
false
12,355
cpp
/* * * Authors: Miracle and Ajantis * mailto: [email protected] [email protected] * * 06.04.2010 * */ #include <stdlib.h> #include <string.h> #include <iostream> #include <GL/glut.h> #include "text3d.h" #include "figures.h" #include "game_logic.h" #include "imageloader.h" #include "simple_cube.h" #include "particles.h" #include "draw_objects.h" #pragma comment( lib, "opengl32.lib" ) #pragma comment( lib, "glu32.lib" ) #pragma comment( lib, "winmm.lib" ) #define UPDATE_ANIMATION_TIME 400 //Time between updating animation #define REAL_TIME 1000 // 1 second is 1 second :) #define GAME_SPEED 1000 // GAME SPEED in _milliseconds_ :crazy: using namespace std; float angl_mine = 0.0; // Angle for observing float angl_mine2 = 0.0; // Angle for observing float next_figure_angle = 0.0; // angle for rotating next figure preview float points_angle = 0.0; // angle for rotating points text int seconds = 0; int game_speed = GAME_SPEED; //int animate_appearance_time = 0; // until UPDATE_ANIMATION_TIME*25; Game game; // Instance of current Game process (all game logics are there) float game_over_z = -8.0; // beginning position of game_over notification text //For Text3d float _scale = 1.0f; // Scaling Text float zoom = 0.0f; // multiplier for zooming of the whole game 3d scene // Paths to all texture files for cubes char* bmp_names[7]={".\\textures\\L.bmp",".\\textures\\S.bmp",".\\textures\\Z.bmp",".\\textures\\T.bmp",".\\textures\\O.bmp",".\\textures\\I.bmp",".\\textures\\J.bmp"}; char* bmp_panel = ".\\textures\\panel2.bmp"; //Declaration of current figure Figure* current = NULL; // This figure for display next Figure* next_figure_type = NULL; ParticleEngine* _particleEngine; //particles GLuint _particle_textureId; // texture ID for particle GLuint _displayList_walls_Id; // ID of the display list for walls // cleaning objects created for text3D /* void cleanup() { t3dCleanup(); delete _particleEngine; } */ // Returns texture id of loaded from bmp(256*256) 24bit texture GLuint loadTexture(Image* image) { GLuint textureId; glGenTextures(1, &textureId); //Make room for our texture glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit //Map the image to the texture glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D 0, //0 for now GL_RGB, //Format OpenGL uses for image image->width, image->height, //Width and height 0, //The border of the image GL_RGB, //GL_RGB, because pixels are stored in RGB format GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored //as unsigned numbers image->pixels); //The actual pixel data return textureId; //Returns the id of the texture } // Function for handling mouse calls void handleMouse(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { angl_mine+=5.0f; glutPostRedisplay(); } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { angl_mine2+=5.0f; glutPostRedisplay(); } break; case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN) { angl_mine-=5.0f; glutPostRedisplay(); } break; default: break; } } // Function for handling keyboard calls void handleKeypress(unsigned char key, int x, int y) { float tmp_x = 0.0; float tmp_y = 0.0; float tmp_angle = 90.0f; switch (key) { case 27: //Escape key exit(0); break; if(!game.game_over) { case 97: // 'A' game.move_left(current); glutPostRedisplay(); break; case 100: // 'D' game.move_right(current); glutPostRedisplay(); break; case 115: // 'S' game.move_down(current,next_figure_type, game.game_over); game.check_map(); break; case 122: // 'Z' if(((*current).x_coord()>=0.3) && ((*current).x_coord()<=1.8))(*current).rotate(); glutPostRedisplay(); break; } case 120: // 'X' zoom-=0.2; glutPostRedisplay(); break; case 119: // 'W' zoom+=0.2; glutPostRedisplay(); break; } } // OpenGL initialization void initRendering() { glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_NORMALIZE); glShadeModel(GL_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Enable Alpha Blending (disable alpha testing) t3dInit(); // Text3d initialization // Enabling Fog glEnable(GL_FOG); // Loading textures for cubes for(int i=0;i<7;i++) { Image* image = loadBMP(bmp_names[i]); _textureId[i] = loadTexture(image); delete image; } // Loading texture for floor Image* image = loadBMP(".\\textures\\chess.bmp"); _floor_textureId = loadTexture(image); delete image; // Loading texture for floor and walls image = loadBMP(".\\textures\\floor.bmp"); _wall_textureId = loadTexture(image); delete image; // Loading texture for floor and walls image = loadBMP(".\\textures\\mirror.bmp"); _frontwall_textureId = loadTexture(image); delete image; // Loading texture for panel image = loadBMP(bmp_panel); _panel_textureId = loadTexture(image); delete image; //for particles image = loadBMP(".\\textures\\particle.bmp"); Image* alphaChannel = loadBMP(".\\textures\\particle_alpha.bmp"); _particle_textureId = loadAlphaTexture(image, alphaChannel); delete image; delete alphaChannel; // LISTS _displayList_walls_Id = glGenLists(1); //Make room for the display list glNewList(_displayList_walls_Id, GL_COMPILE); //Begin the display list drawWalls(game,current, next_figure_type, next_figure_angle,points_angle); glEndList(); //End the display list // Background color glClearColor(0.5,0.5,0.5,1.0f); // Grey Background! } // Function for handling of resizing game window void handleResize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (double)w / (double)h, 1.0, 200.0); } // Basic function for Drawing of the whole scene void drawScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Fog GLfloat FogColor[4]={0.5,0.5,0.5,1.0}; glFogfv(GL_FOG_COLOR,FogColor); glFogi(GL_FOG_MODE,GL_LINEAR); glFogf(GL_FOG_START,10.0); glFogf(GL_FOG_END,15.0); //glFogf(GL_FOG_DENSITY,0.20); // For GL_EXP GLfloat ambientColor[] = {0.1f, 0.1f, 0.1f, 1.0f}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor); // Lightning number 0 GLfloat lightColor0[] = {1.0f, 1.0f, 1.0f, 1.0f}; glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0); glLightfv(GL_LIGHT0, GL_POSITION, lightPos0); // Lightning number 1 GLfloat lightColor1[] = {0.3f,0.3f, 0.3f, 0.0f}; glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1); glLightfv(GL_LIGHT1, GL_POSITION, lightPos1); glTranslatef(-1.0,-1.5,0.0); glTranslatef(0.0f, 0.0f, -5.0f); glTranslatef(0.0f, 0.0f, -zoom); // Mouse zooming glRotatef(angl_mine,0,1,0); // Mouse rotate left-right glRotatef(angl_mine2+10.0,1,0,0); // Mouse rotate down glPushMatrix(); // GLOBAL /* if(animate_appearance_time <= 5){ glPushMatrix(); //partcles glTranslatef(0.0f, 1.5f, -1.0f); glScalef(0.5f, 0.5f, 0.5f); _particleEngine->draw(); glPopMatrix(); } */ glCullFace(GL_BACK); // Skipping backward faces to improve performance glEnable(GL_CULL_FACE); // Enable alpha CULLING - to not to draw backward polygons glPushMatrix(); //Draw the whole MAP game.draw_map(_panel_textureId); glPopMatrix(); glPushMatrix(); // Draw current Figure (*current).Draw(); glPopMatrix(); glPushMatrix(); // draws left panel glColor3f(1,1,1); glTranslatef(-11*BOX_SIZE,0,0); drawControlPanel(_panel_textureId); glPopMatrix(); drawPredictedFigure(next_figure_type,_panel_textureId,next_figure_angle); //draws next figure and frame drawText(game, points_angle); if(game.game_over) { // GAME OVER TEXT glPushMatrix(); glTranslatef(1.0f,0.0f,game_over_z); _scale=0.5f; glScalef(_scale, _scale, _scale); glColor3f(1.0f, 0.0f, 0.0f); t3dDraw3D("Game over!", 0, 0, 2*BOX_SIZE); glPopMatrix(); //END GAME OVER TEXT } glDisable(GL_CULL_FACE); // Disable alpha CULLING - to not to draw backward polygons drawMirrorFloor(game, current, next_figure_type, next_figure_angle, points_angle,_particleEngine); drawWall(game, current, next_figure_type, next_figure_angle,points_angle,_particleEngine); //drawWalls(game,current, next_figure_type, next_figure_angle,points_angle); glCallList(_displayList_walls_Id); // Draw left and right walls glPopMatrix();// GLOBAL glutSwapBuffers(); } // Function for updating animation of objects: rotating texts, next figure preview, etc void update_animation(int value) { next_figure_angle +=18.0; if(next_figure_angle>=360.0)next_figure_angle=0.0; points_angle+=18.0; if(points_angle>=360.0)points_angle=0.0; if(game.game_over) { if(game_over_z<=0.0) game_over_z+= 0.5; } _particleEngine->advance(UPDATE_ANIMATION_TIME / 1000.0f); if(animate_appearance_time <= 5) animate_appearance_time++; if(welldone_appearance_time <= 5) welldone_appearance_time++; glutPostRedisplay(); glutTimerFunc(UPDATE_ANIMATION_TIME, update_animation, 0); // Every second } // Function for updating time info in game void update_time(int value) { if(!game.game_over){ game.seconds+= 1; } glutTimerFunc(REAL_TIME, update_time, 0); // Every second } // Function for updating game logic void update_logic(int value) { if(!game.game_over){ game.move_down(current, next_figure_type, game.game_over); // Moving down :) game.check_map(); } glutPostRedisplay(); glutTimerFunc(game_speed, update_logic, 0); } // Main func int main(int argc, char** argv) { //srand((unsigned int)time(0)); //Seed the random number generator initrand(); if ( argc >= 5 ) { // We print argv[0] assuming it is the program name cout<<"Usage: " << argv[0] << " <game resolution <width><height>> <game speed 1,2,3..>"; return 1; } else { printf("Welcome to the Tetris 3D\r\n"); printf("\r\n"); printf("Press ESC to quit the game...\r\n"); printf("\r\n"); game = Game(); // Create new Game current = new Figure(1,2,0); // Creating current figure that will be moving to the map //next_figure_type = new Figure(0,0,0,(*current).get_next_type()); // Creating figure for displaying next figure next_figure_type = new Figure(0,0,0); // Creating figure for displaying next figure game.init_map(); // Initializes out Game Map glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL); char* window_name = "Tetris 3d v.0.50"; if(argc > 1) { if(strcmp(argv[1],"full")==0) { glutGameModeString("1024x768:32@75"); glutEnterGameMode(); } else { if(argc>=3) { glutInitWindowSize(atoi(argv[1]),atoi(argv[2])); } if(argc==2) { glutInitWindowSize(atoi(argv[1]),atoi(argv[1])); } glutCreateWindow(window_name); } if(argc==4) { game_speed = (int)game_speed/atoi(argv[3]); } } else { glutInitWindowSize(800,800); // default resotution glutCreateWindow(window_name); } initRendering(); glutDisplayFunc(drawScene); glutMouseFunc(handleMouse); glutKeyboardFunc(handleKeypress); glutReshapeFunc(handleResize); glutTimerFunc(25, update_logic, 0); // Main timer for game logic glutTimerFunc(REAL_TIME, update_time, 0); // Updating Every second glutTimerFunc(UPDATE_ANIMATION_TIME, update_animation, 0); // Updating all background animation _particleEngine = new ParticleEngine(_particle_textureId); glutMainLoop(); return 0; } }
[ [ [ 1, 484 ] ] ]
1bcbd15d94054f01389c3a04b743fbf92eeaab22
25281ba3fc17716aaca69186a6f115e914c8ecf8
/src/view.h
5bd39c62dcf49ed4bea6500424f23fbe3f5cb4fd
[]
no_license
rehno-lindeque/osi-glgui
97b2c6f771d2dd646e023366bcf05f7f68a5e2cc
0b9e939e17fdb62fd089985cb6e67ac7aa11d1e6
refs/heads/master
2020-03-30T20:12:48.683127
2011-01-29T09:57:45
2011-01-29T09:57:45
1,303,874
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
611
h
#ifndef __GLGUI_VIEW_H__ #define __GLGUI_VIEW_H__ ////////////////////////////////////////////////////////////////////////////// // // VIEW.H // // Copyright © 2007, Rehno Lindeque. All rights reserved. // ////////////////////////////////////////////////////////////////////////////// /* DOCUMENTATION */ /* DESCRIPTION: GLGUI view class. */ namespace GLGUI { /* CLASSES */ class View : public Base::Object { public: }; } #endif
[ [ [ 1, 26 ] ] ]
04ee5d7adfd07919abd82a9d819ab9c4d200dc14
842997c28ef03f8deb3422d0bb123c707732a252
/src/moaicore/MOAIThread.cpp
a23585943c6cc11d0ccac32636f680661e296544
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
4,053
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAIThread.h> //----------------------------------------------------------------// /** @name blockOnAction @text Skip updating current thread until the specified action is no longer busy. A little more efficient that spinlocking from Lua. @in MOAIAction blocker @out nil */ int MOAIThread::_blockOnAction ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "U" )) return 0; MOAIAction* current = MOAIActionMgr::Get ().GetCurrentAction (); if ( !current ) return 0; MOAIAction* blocker = state.GetLuaObject < MOAIAction >( 1 ); if ( !blocker ) return 0; current->SetBlocker ( blocker ); return lua_yield ( state, 0 ); } //----------------------------------------------------------------// /** @name currentThread @text Returns the currently running thread (if any). @out MOAIThread currentThread Current thread or nil. */ int MOAIThread::_currentThread ( lua_State* L ) { USLuaState state ( L ); MOAIAction* current = MOAIActionMgr::Get ().GetCurrentAction (); if ( !current ) return 0; current->PushLuaUserdata ( state ); return 1; } //----------------------------------------------------------------// /** @brief <tt>run ( self, func )</tt>\n \n Sets the thread's function and starts it. @param self (in) @param func (in) Function for this thread to run. */ /** @name run @text Starts a thread with a function and passes parameters to it. @in MOAIThread self @in function threadFunc @in ... @out nil */ int MOAIThread::_run ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIThread, "UF" ) self->mNarg = lua_gettop ( state ) - 2; self->mState = lua_newthread ( state ); self->mRef.SetRef ( state, -1, false ); lua_pop ( state, 1 ); lua_xmove ( state, self->mState, self->mNarg + 1 ); self->Start (); return 0; } //================================================================// // MOAIThread //================================================================// //----------------------------------------------------------------// MOAIThread::MOAIThread () : mState ( 0 ), mNarg ( 0 ) { RTTI_SINGLE ( MOAIAction ) } //----------------------------------------------------------------// MOAIThread::~MOAIThread () { } //----------------------------------------------------------------// bool MOAIThread::IsDone () { return this->mRef.IsNil (); } //----------------------------------------------------------------// void MOAIThread::OnUpdate ( float step ) { UNUSED ( step ); if ( this->mState ) { int result = lua_resume ( this->mState, this->mNarg ); this->mNarg = 0; if ( result != LUA_YIELD ) { if ( result != 0 ) { cc8* msg = lua_tostring ( this->mState, -1 ); USLog::Print ( "%s\n", msg ); lua_pop ( this->mState, 1 ); USLuaStateHandle state ( this->mState ); state.PrintStackTrace ( 0 ); } this->mRef.Clear (); this->mState = 0; this->Stop (); } } } //----------------------------------------------------------------// void MOAIThread::RegisterLuaClass ( USLuaState& state ) { luaL_Reg regTable [] = { { "blockOnAction", _blockOnAction }, { "currentThread", _currentThread }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIThread::RegisterLuaFuncs ( USLuaState& state ) { MOAIAction::RegisterLuaFuncs ( state ); luaL_Reg regTable [] = { { "run", _run }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); lua_getglobal ( state, "coroutine" ); lua_getfield ( state, -1, "create" ); lua_setfield ( state, -3, "create" ); lua_getfield ( state, -1, "resume" ); lua_setfield ( state, -3, "resume" ); lua_pop ( state, 1 ); }
[ [ [ 1, 163 ] ] ]
1840676d4732ede223278f7801ad52229c26e9ca
4b30b09448549ffbe73c2346447e249713c1a463
/Sources/mozilla/mozilla_v2.cpp
0c76156c164d1078762fd24fa98acaccb27bb098
[]
no_license
dblock/agnes
551fba6af6fcccfe863a1a36aad9fb066a2eaeae
3b3608eba8e7ee6a731f0d5a3191eceb0c012dd5
refs/heads/master
2023-09-05T22:32:10.661399
2009-10-29T11:23:28
2009-10-29T11:23:28
1,998,777
1
1
null
null
null
null
UTF-8
C++
false
false
5,851
cpp
#include <agnespch.hpp> int pParam_v2::entries_count(void){ return(entry_manager.entries_count()); } void pParam_v2::entries_clear(void){ entry_manager.clear(); } CString pParam_v2::get_name(int index){ if (method_post) return(entry_manager.get_name(index)); else { return ""; } } CString pParam_v2::get_entry(int index){ if (method_post) return(entry_manager.get_value(index)); else { return ""; } } CString pParam_v2::get_entry_list(const CString& name){ CString Result; if (method_post){ for (int i=0;i<entry_manager.entries_count();i++) if (entry_manager.get_name(i) == name) { if (Result.StrLength()) Result+="\t"; Result+=entry_manager.get_value(i); } } return Result; } CString pParam_v2::get_entry(const CString& name){ if (method_post) return(entry_manager.get_value(name)); else { return ""; } } void pParam_v2::create_cmdl(void){ if (argv.Count() >= 3) { cmdl = getenv("SCRIPT_NAME"); cmdl += "?"; cmdl += argv[1]; cmdl += "+"; cmdl += argv[2]; } } pParam_v2::pParam_v2(const CVector<CString>& args, const CVector<CString>& posts){ argv = args; create_cmdl(); if (posts.Count()){ method_post = 1; for (int i=0; i<posts.Count();i++){ CString Val = posts[i]; Val.Replace('+',' '); Val.unescape_url(); int iPos = Val.Pos('='); if (iPos >=0) { CString Left(Val.Copy(0, iPos)); CString Right(Val.Copy(iPos+1, Val.StrLength())); entry_manager.add_value(Left, Right); } } } else method_post = 0; } void pParam_v2::add_entry(const CString& name, const CString& value){ entry_manager.add_value(name, value); } void pParam_v2::set_entry(const CString& name, const CString& value){ entry_manager.set_value(name, value); } pParam_v2::pParam_v2(int i_argc, char * i_argv[]){ CString iArgv; for (int i=0;i<i_argc;i++) { iArgv = i_argv[i]; iArgv.unescape_url(); argv+=iArgv; } create_cmdl(); if ((!getenv("CONTENT_TYPE"))|| (!getenv("CONTENT_LENGTH"))|| (!getenv("REQUEST_METHOD"))) method_post = -1; else if (strcmp(getenv("REQUEST_METHOD"), "POST")) method_post = 0; else { method_post = 1; /* if(strcmp(getenv("CONTENT_TYPE"),"application/x-www-form-urlencoded")) cgi_error("this script can only be used to decode form results"); */ get_entries(); } } int pParam_v2::isPost(void){ return(method_post); } pParam_v2::~pParam_v2(void){ } CString pParam_v2::ReadStdin(int Size) { #ifndef ANSI setmode(fileno(stdin), O_BINARY); #endif FILE * StandardInput = fdopen(0, "rb"); char * Segment = ::new char[Size+1]; Size = fread(Segment, sizeof(char), Size, StandardInput); Segment[Size] = 0; CString Result; Result.StrAppend(Segment, Size); delete[] Segment; fclose(StandardInput); return Result; } void pParam_v2::get_entries(void){ int cl = atoi(getenv("CONTENT_LENGTH")); CString cType = getenv("CONTENT_TYPE"); entry_manager.set_value("CONTENT_TYPE", cType); entry_manager.set_value("CONTENT_TYPE_MULTIPART", cType); CVector<CString> GValues; cType.Tokenizer(';', GValues); for (int j=0;j<GValues.Count();j++){ CString GValue = GValues[j]; GValue.StrTrim32(); CVector<CString> GVector = GValue.Tokenizer('='); if (GVector.Count() >= 2) { CString GName = GVector[0]; int i=0; while (entry_manager.get_value(GName).StrLength()) { GName = GVector[0]; GName+=(i++); } entry_manager.set_value(GName, GVector[1]); } else { CString Tmp("CONTENT_TYPE=");Tmp+=GValue; putenv(Tmp.asString()); entry_manager.set_value("CONTENT_TYPE",GValue); } } RawData = ReadStdin(cl); if (entry_manager.get_value("CONTENT_TYPE") == "multipart/form-data") { CString Boundary = entry_manager.get_value("BOUNDARY"); if (Boundary.StrLength()) { CVector<CString> Boundaries = RawData.Tokenizer(Boundary); for (int l=0;l<Boundaries.Count();l++){ /* process each boundary */ CVector<CString> BGValues; Boundaries[l].Tokenizer(';', BGValues); for (int j=0;j<BGValues.Count();j++){ CString BGValue = BGValues[j]; BGValue.StrTrim32(); CVector<CString> BGVector = BGValue.Tokenizer('='); if ((BGVector.Count() >= 2)&&(BGVector[0]=="NAME")) { if (BGVector[1][0] == '\"') BGVector[1].StrDelete(0, 1); int sPos = BGVector[1].Pos('\"'); if (sPos == -1) sPos = BGVector[1].Pos(' '); if (sPos == -1) sPos = BGVector[1].Pos('\r'); if (sPos == -1) sPos = BGVector[1].Pos('\n'); if (sPos != -1) BGVector[1].StrDelete(sPos, BGVector[1].StrLength()); BGVector[1].unescape_url(); CString BP = Boundaries[l]; BP.ExtractLine(); BP.ExtractLine(); if (BP.EndsWith("--")) BP.StrDelete(BP.StrLength()-strlen("--"), BP.StrLength()); BP.StrTrim32(); BP.unescape_url(); CString BGName = BGVector[1]; int f=0; while (entry_manager.get_value(BGName).StrLength()) { BGName = BGVector[0]; BGName+=(f++); } entry_manager.set_value(BGName, BP); } } } } } else { CVector<CString> ValParams; RawData.Tokenizer('&', ValParams); for (int i = 0;i<ValParams.Count();i++){ ValParams[i].Replace('+',' '); int iPos = ValParams[i].Pos('='); if (iPos >=0) { CString Source = ValParams[i].Copy(0, iPos); Source.unescape_url(); CString Target = ValParams[i].Copy(iPos+1, ValParams[i].StrLength()); Target.unescape_url(); entry_manager.add_value(Source, Target); } } } } CString pParam_v2::c_params(void){ CString result; for (int i=0;i<extra_params.Count();i++){ result+="+"; result+=extra_params[i]; } return(result); } CString pParam_v2::getRawData(void) const { return RawData; }
[ [ [ 1, 223 ] ] ]
2d949e4910ba5f3746b179978f061ad5f53512b0
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/network/nsessionclientcontext_main.cc
07dd4059ddfd9911235962a153baf78fb00df5a8
[]
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
712
cc
#include "precompiled/pchnnetwork.h" //------------------------------------------------------------------------------ // nsessionclientcontext_main.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "network/nsessionclientcontext.h" nNebulaScriptClass(nSessionClientContext, "nroot"); //------------------------------------------------------------------------------ /** */ nSessionClientContext::nSessionClientContext() : ipcClientId(0) { // empty } //------------------------------------------------------------------------------ /** */ nSessionClientContext::~nSessionClientContext() { // empty }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 26 ] ] ]
cdbdd4f488a0de5760acfae5dd93c5cb2d4661f0
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGame/SanExecute/src/San.cpp
f55d521771d9776e27eee321d21272865a966924
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
GB18030
C++
false
false
3,058
cpp
#include "SanConfig.h" #include <tinyxml/tinyxml.h> #include <orz/Toolkit_Base/EventSystem/EventWorldUpdate.h> void LoadSingleChipPort(void) { TiXmlDocument document("SingleChip.xml"); document.LoadFile(); TiXmlElement* port = document.FirstChildElement("SingleChip_Port"); std::string COM_N("COM4"); if(port) { const std::string * value = port->Attribute(std::string("value")); if(value) COM_N = *value; } Orz::SystemInterface::getSingleton().setParame<std::string>("SingleChip_Port", COM_N); } #if 0 INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT) #else int main() #endif { using namespace Orz; //建立系统层(View) 计时器, Ogre图形管理 , CEGUI管理器 OIS管理器 音频管理器 插件管理器 单片机管理器 SystemPtr system(new SystemList<boost::mpl::list<AsioTimerManager, OgreGraphicsManager, CEGUIManager, OISInputManager, FmodSoundManager, PluginsManager, SingleChipManager, EventWorldUpdate> >()); //创建一个逻辑的外观 LogicConfiger::LogicFacadePtr logic(new LogicConfiger::LogicFacade()); CEGUIManager::getSingleton().mouseEvent(false); CEGUIManager::getSingleton().keyEvent(true); //构建一个builder LogicConfiger::ManualBuilder builder; // const std::string * type = root->Attribute(TYPE); //增加两个个动态插件 builder.addPlugin("SanController"); builder.addPlugin("Model_Base"); #ifdef _MyWheelDirector builder.addPlugin("MyWheelDirector"); #endif #ifdef _NetWheelDirector builder.addPlugin("NetWheelDirector"); #endif #ifdef _WheelAnimal2 builder.addPlugin("WheelAnimal2Model"); #endif builder.addPlugin("SanModel"); builder.addPlugin("NewGameComponents"); builder.addPlugin("NewGameSceneComponent"); builder.addPlugin("GameNeedleComponent"); builder.addPlugin("GameDiamondComponent"); //builder.addPlugin("VedioUIComponent"); builder.addPlugin("CodingComponent"); builder.addPlugin("MyJobComponent"); //builder.addPlugin("JsComponent"); //设置大厅 builder.setTheater("TheaterBase","main"); //NameValueList p; //p["XML_FILE"] = VariantData<std::string>::set(std::string("GameConfig.xml")); builder.addDirector("WheelDirector","wheel"/*, p*/); builder.setActiveDirector("wheel"); logic->building(builder); //SystemInterface::getSingleton().setParame<int>("SingleChip_BaudRate", 19200); //LoadSingleChipPort();// SystemInterface::getSingleton().setParame<bool>("SILENT", true); SystemInterface::getSingleton().setParame<bool>(SystemParame::SystemUpdateFilter, true); SystemInterface::getSingleton().setParame<unsigned int>(SystemParame::SystemUpdateFilterCount, 20); try { if(system->init()) { if(logic->load(EventWorld::Parameter())) { system->run(); logic->unload(); } system->shutdown(); } } catch(std::exception & e) { ORZ_LOG_CRITICAL_MESSAGE(e.what()); } }
[ [ [ 1, 115 ] ] ]
65752c3ad3c3e122f5105af95f14e9a17aedc011
c440e6c62e060ee70b82fc07dfb9a93e4cc13370
/src/gui2/guis/gslider.h
647a6e6712647ca10142f337fef7699d71078c13
[]
no_license
BackupTheBerlios/pgrtsound-svn
2a3f2ae2afa4482f9eba906f932c30853c6fe771
d7cefe2129d20ec50a9e18943a850d0bb26852e1
refs/heads/master
2020-05-21T01:01:41.354611
2005-10-02T13:09:13
2005-10-02T13:09:13
40,748,578
0
0
null
null
null
null
UTF-8
C++
false
false
693
h
#ifndef GSLIDER_H #define GSLIDER_H #include "gui.h" #include "mygtkslider.h" #include "mygtkfloatentry.h" #include "../../modules/slider.h" #include <gtkmm/button.h> #include <gtkmm/table.h> #include <gtkmm/label.h> /** * No description */ class GSlider : public Gui { public: GSlider( Module* mod ); ~GSlider(); virtual Gtk::Widget* GetGui(); REGISTER_GUI( Slider::GetTypeStatic(), GSlider ) protected: MyGtkSlider guiSlider; MyGtkFloatEntry entryMin, entryMax; Gtk::Button buttonApply; Gtk::Table table; Gtk::Label labelMin, labelMax; ParameterFloat* pMin, * pMax; // No description void OnApply(); }; #endif // GSLIDER_H
[ "ad4m@fa088095-53e8-0310-8a07-f9518708c3e6" ]
[ [ [ 1, 35 ] ] ]
4eeec6c3ed843e525750ceef8203eb536b4a14ab
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/Subscriber.cpp
04ecc26ca867767c709cbd3a1cd97c1161c3a482
[]
no_license
danishcake/FusionForever
8fc3b1a33ac47177666e6ada9d9d19df9fc13784
186d1426fe6b3732a49dfc8b60eb946d62aa0e3b
refs/heads/master
2016-09-05T16:16:02.040635
2010-04-24T11:05:10
2010-04-24T11:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
686
cpp
#include "StdAfx.h" #include "Subscriber.h" Subscriber::Subscriber(void) { } Subscriber::~Subscriber(void) { StopSubscribing(); } void Subscriber::AddSubscriber(Subscriber* _subscriber) { subscribers_.push_back(_subscriber); } void Subscriber::RemoveSubscriber(Subscriber* _subscriber) { subscribers_.remove(_subscriber); } void Subscriber::StopSubscribing() { BOOST_FOREACH(Subscriber* subscriber, subscribers_) { subscriber->EndSubscription(this); } subscribers_.clear(); } void Subscriber::EndSubscription(Subscriber*) { //Do nothing, but overloaded versions should check the incoming pointer, and invalidate them if they match }
[ "Edward Woolhouse@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "[email protected]" ]
[ [ [ 1, 9 ], [ 11, 22 ], [ 33, 34 ] ], [ [ 10, 10 ], [ 23, 32 ], [ 35, 36 ] ] ]
95f9e59f1c8c556e752f63c12d12d084da942c4f
21868e763ab7ee92486a16164ccf907328123c00
/project.cpp
dc5b51d6ed7388671601c2fad4bff5822d860ed2
[]
no_license
nodesman/flare
73aacd54b5b59480901164f83905cf6cc77fe2bb
ba95fbfdeec1d557056054cbf007bf485c8144a6
refs/heads/master
2020-05-09T11:17:15.929029
2011-11-26T16:54:07
2011-11-26T16:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
cpp
#include "project.h" #include <QString> #include <QStringList> Project::Project() { } Project::Project(QString stringToConstructFrom) { QStringList theSettings = stringToConstructFrom.split("%FL_PROJECT_INFO_SEPARATOR%"); this->name = theSettings.at(0); this->path = theSettings.at(1); if (theSettings.size() >2) { this->ftpcredentials.hostname = theSettings.at(2); this->ftpcredentials.port = theSettings.at(3); this->ftpcredentials.username = theSettings.at(4); this->ftpcredentials.password = theSettings.at(5); //this->ftpcredentials.mode = theSettings.at(6); } } Project::ftpinfo Project::getFTPInfo() { return this->ftpcredentials; } void Project::setFTPInfo(ftpinfo credentials) { this->ftpcredentials = credentials; } void Project::setName(QString name) { this->name = name; } void Project::setPath(QString path) { this->path = path; } QString Project::getName() { return this->name; } QString Project::getPath() { return this->path; } QString Project::getFTPHostname() { return this->ftpcredentials.hostname; } QString Project::getFTPPort() { return this->ftpcredentials.port; } QString Project::getFTPPassword() { return this->ftpcredentials.password; } QString Project::getFTPUsername() { return this->ftpcredentials.username; } QString Project::getFTPMode() { return this->ftpcredentials.mode; } QString Project::toString() { QStringList theSettings; theSettings.append(this->name); theSettings.append(this->path); theSettings.append(this->ftpcredentials.hostname); theSettings.append(this->ftpcredentials.port); theSettings.append(this->ftpcredentials.username); theSettings.append(this->ftpcredentials.password); //theSettings.append(this->ftpcredentials.mode); QString theString = theSettings.join("%FL_PROJECT_INFO_SEPARATOR%"); return theString; }
[ [ [ 1, 91 ] ] ]
6bf77fb3f5fc3cfef32e1a62bce6bf34d7606079
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/network/ngetprofileattr.cc
dcb3340fff6b80d9159ad3c5d45872c1f9ec8ca6
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cc
//------------------------------------------------------------------------------ // nGetProfileAttr.cc // (C) 2006 RadonLabs GmbH //------------------------------------------------------------------------------ #include "network/ngetprofileattr.h" #include "network/nbuddyclient.h" //------------------------------------------------------------------------------ /** */ nGetProfileAttr::nGetProfileAttr() { // empty } //------------------------------------------------------------------------------ /** */ nGetProfileAttr::~nGetProfileAttr() { // empty } //------------------------------------------------------------------------------ /** */ bool nGetProfileAttr::Execute() { nStream xmlStream; xmlStream.SetFilename("MyData"); xmlStream.OpenString(""); xmlStream.BeginNode("rlbuddysystem"); xmlStream.SetInt("ver",1); xmlStream.SetInt("id",this->uniqueID); xmlStream.SetString("type","get"); xmlStream.BeginNode("getprofileattr"); xmlStream.SetString("key",this->key); xmlStream.EndNode(); xmlStream.EndNode(); xmlStream.GetDocumentAsString(this->xmlRequest); return nBuddyClient::Instance()->SendCommand(this); } void nGetProfileAttr::EvaluateResult(nStream& result) { this->curStatus = COMMAMD_ERROR; if (result.HasAttr("type")) { nString type = result.GetString("type"); if (type=="result") { if (result.SetToFirstChild()) { nString message = result.GetString("message"); if (message == this->key) { this->value = result.GetString("value"); this->curStatus = COMMAMD_RESULT; } } } else if (type=="error") { this->curStatus = COMMAMD_ERROR; if (result.SetToFirstChild()) { nString message = result.GetString("message"); if (message == "nosuchattr") { this->curStatus = COMMAMD_ERROR; } } } } }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 83 ] ] ]
fbd876a23a493cef6fcc45310df2e5e4b8c459a8
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/TPLayer_IOCP/TPUDPClient.h
2bf1a3766bf003b5f641f91c2dc4190f74518060
[]
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
1,727
h
/* * Copyright (c) 2008, 浙江亿蛙技术股份有限公司 * All rights reserved. * * 文件名称:TPUDPClient.h * 摘  要:UDP客户端功能类 * * * 取代版本:0.1 * 原作者 :Peng Dongfeng * 完成日期:2008年8月6日 * 修订记录:创建 */ ////////////////////////////////////////////////////////////////////// #ifndef _TPUDPClient_H_ #define _TPUDPClient_H_ #include "ITPObject.h" class TPUDPClient : public ITPObject, protected IOCPListener { public: TPUDPClient(ITPListener *callback, int engineId = 0); virtual ~TPUDPClient(); public: /* 接口 */ virtual int Close(void); virtual int Connect(const char* szIp, int nPort); virtual int Connect(const char* szLocalIp, int nLocalPort, const char* szRemoteIp, int nRemotePort); virtual int Send(int id, IBufferRef pSendBuf); public: /* 内部完成端口回调 */ virtual int onIOData(int nEngineId, int nConnId, unsigned char* data, int nLen, BOOL bPostSuccess); virtual int onIODealData(int nEngineId, int nConnId, unsigned char* buffer, int nLen); virtual int onIODisconnect(int nEngineId, int nConnId); virtual int onIOSendDataAck(int nEngineId, int nConnId, int nId, BOOL bPostSuccess); protected: int CreateClientEnvironment(); int ClearClientEnvironment(); protected: CPerIoData *m_pPerIoRecv; // Receive PerIoData CPerHandleData *m_pPerHandleData; // Socket PerHandle BOOL m_bIsPostSend; // 是否可以投递发送 Queue_List m_lstSendQueue; CReadWriteMutex m_csSendQueue; DWORD m_dwLastDealTime; BOOL m_bLastStatus; BOOL m_bIsDealData; CReadWriteMutex m_csDealData; }; #endif // _TPUDPClient_H_
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 68 ] ] ]
43d661f2d5c6a60b327ad581260fe6caf454c01d
e618b452106f251f3ac7cf929da9c79256c3aace
/src/lib/cpp/DLL/stdafx.cpp
8b6f748582746f695c66f00e12691513e13ac045
[]
no_license
dlinsin/yfrog
714957669da86deff3a093a7714e7d800c9260d8
513e0d64a0ff749e902e797524ad4a521ead37f8
refs/heads/master
2020-12-25T15:40:54.751312
2010-04-13T16:31:15
2010-04-13T16:31:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
300
cpp
// stdafx.cpp : source file that includes just the standard includes // ImageShackAPI.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 8 ] ] ]
e62f9ab4410f6d0d9613e3cf921e4b27a3d02c6a
3b76b2980485417cb656215379b93b27d4444815
/8.Nop KLTN/DIA/SCVOICECHAT/SOURCE/SC Voice Chat Client/myapp.cpp
670a588c6a6e5ac9610badab3715b1b5f37435b2
[]
no_license
hemprasad/lvmm-sc
48d48625b467b3756aa510b5586af250c3a1664c
7c68d1d3b1489787f5ec3d09bc15b4329b0c087a
refs/heads/master
2016-09-06T11:05:32.770867
2011-07-25T01:09:07
2011-07-25T01:09:07
38,108,101
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
// myapp.cpp: implementation of the myapp class. // ////////////////////////////////////////////////////////////////////// #include <afxwin.h> #include "myapp.h" #include "resource.h" #include "Display.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Chuong trinh cua nhom co su dung cac nguon tham khao sau day : // -Giao dien va chuong trinh voice chat chua ma hoa lay tu trang web http://www.codeproject.com/KB/IP/voicechat2.aspx // -Source code cua AES 128 bit lay tu trang web http://www.efgh.com/software/rijndael.htm // -Source code cua ZUC lay tu file tai lieu http://www.gsmworld.com/documents/EEA3_EIA3_ZUC_v1_5.pdf ////////////////////////////////////////////////////////////////////// BOOL myapp::InitInstance() { Display dlg(IDD_DIALOG1); m_pMainWnd=&dlg; dlg.DoModal(); return FALSE; } myapp a;
[ [ [ 1, 30 ] ] ]
d5664eaa3291cd8065bb7b863fe90b66617c3fa6
52f70251d04ca4f42ba3cb991727003a87d2c358
/src/pragma/image/TGA.cpp
abbb20b8096ed5912ef69dc818b62a00c01c3b0e
[ "MIT" ]
permissive
vicutrinu/pragma-studios
71a14e39d28013dfe009014cb0e0a9ca16feb077
181fd14d072ccbb169fa786648dd942a3195d65a
refs/heads/master
2016-09-06T14:57:33.040762
2011-09-11T23:20:24
2011-09-11T23:20:24
2,151,432
0
0
null
null
null
null
UTF-8
C++
false
false
4,670
cpp
#include <pragma/types.h> #include <pragma/image/functions.h> #include <pragma/image/Image.h> #include <pragma/math/math.h> #include <stdio.h> namespace pragma { namespace impl { // this struct was taken from http://www.organicbit.com/closecombat/formats/tga.html // more info on http://en.wikipedia.org/wiki/Truevision_TGA #pragma pack(1) struct TGAHeader { uint8 identsize; // size of ID field that follows 18 byte header (0 usually) uint8 colourmaptype; // type of colour map 0=none, 1=has palette uint8 imagetype; // type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed uint16 colourmapstart; // first colour map entry in palette uint16 colourmaplength; // number of colours in palette uint8 colourmapbits; // number of bits per palette entry 15,16,24,32 uint16 xstart; // image x origin uint16 ystart; // image y origin uint16 width; // image width in pixels uint16 height; // image height in pixels uint8 bits; // image bits per pixel 8,16,24,32 uint8 descriptor; // image descriptor bits (vh flip bits) }; #pragma pack() } bool ExportToTGA(const Image& aImage, const char* aFilename) { FILE* handle = fopen(aFilename, "wb"); if(handle == 0) return false; impl::TGAHeader lHeader; lHeader.identsize = 0; // no data between header and image raw lHeader.colourmaptype = 0; // no color map lHeader.imagetype = 2; // RGB lHeader.colourmapstart = 0; lHeader.colourmaplength = 0; lHeader.colourmapbits = 0; // 24 bpp lHeader.xstart = 0; lHeader.ystart = 0; lHeader.width = uint16(aImage.GetWidth()); lHeader.height = uint16(aImage.GetHeight()); lHeader.bits = 24; // 24 bpp lHeader.descriptor = 1<<5; // bits 3-0 give the alpha channel depth, bits 5-4 give direction fwrite(&lHeader, 1, sizeof(lHeader), handle); Image::iterator lIter = aImage.begin(); while(lIter != aImage.end() ) { vector3<uint8> lRGB8; lRGB8.i[0] = uint8( clamp<ColorIntensity>(lIter->i[2], 0, 1) * 255 ); lRGB8.i[1] = uint8( clamp<ColorIntensity>(lIter->i[1], 0, 1) * 255 ); lRGB8.i[2] = uint8( clamp<ColorIntensity>(lIter->i[0], 0, 1) * 255 ); ++lIter; fwrite(&lRGB8, 1, sizeof(lRGB8), handle); } fclose(handle); return true; } bool ExportToTGA(const uint8* aImage, size_t aWidth, size_t aHeight, const char* aFilename) { FILE* handle = fopen(aFilename, "wb"); if(handle == 0) return false; impl::TGAHeader lHeader; lHeader.identsize = 0; // no data between header and image raw lHeader.colourmaptype = 0; // no color map lHeader.imagetype = 3; // Grey scale lHeader.colourmapstart = 0; lHeader.colourmaplength = 0; lHeader.colourmapbits = 0; // 8 bpp lHeader.xstart = 0; lHeader.ystart = 0; lHeader.width = uint16(aWidth); lHeader.height = uint16(aHeight); lHeader.bits = 8; // 8 bpp lHeader.descriptor = 1<<5; // bits 3-0 give the alpha channel depth, bits 5-4 give direction fwrite(&lHeader, 1, sizeof(lHeader), handle); size_t lNumPixels = aWidth * aHeight; while(lNumPixels) { fwrite(aImage, 1, sizeof(uint8), handle); lNumPixels--; aImage++; } fclose(handle); return true; } bool ImportFromTGA(Image& aImage, const char* aFilename) { FILE* handle = fopen(aFilename, "rb"); if(handle == 0) return false; impl::TGAHeader lHeader; fread(&lHeader, 1, sizeof(lHeader), handle); if(lHeader.imagetype != 2) { fclose(handle); return false; } aImage = Image(lHeader.width, lHeader.height); if(lHeader.bits == 32) { Image::iterator lIter = aImage.begin(); Image::alpha_iterator lAlphaIter = aImage.alpha_begin(); while(lIter != aImage.end() ) { vector3<uint8> lRGB8; uint8 lAlpha; fread(&lRGB8, 1, sizeof(lRGB8), handle); fread(&lAlpha, 1, sizeof(lAlpha), handle); lIter->i[0] = lRGB8.i[2] / 255.f; lIter->i[1] = lRGB8.i[1] / 255.f; lIter->i[2] = lRGB8.i[0] / 255.f; *lAlphaIter = lAlpha / 255.f; ++lIter; ++lAlphaIter; } } else if(lHeader.bits == 24) { Image::iterator lIter = aImage.begin(); Image::alpha_iterator lAlphaIter = aImage.alpha_begin(); while(lIter != aImage.end() ) { vector3<uint8> lRGB8; fread(&lRGB8, 1, sizeof(lRGB8), handle); lIter->i[0] = lRGB8.i[2] / 255.f; lIter->i[1] = lRGB8.i[1] / 255.f; lIter->i[2] = lRGB8.i[0] / 255.f; *lAlphaIter = 1; ++lIter; ++lAlphaIter; } } fclose(handle); return true; } }
[ [ [ 1, 163 ] ] ]
9bdf05c04d1dcd907bc6cb6a79a1f46f537644bd
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/multi_index/detail/hash_index_iterator.hpp
9e88d7acb7248a1a8bf0f5dfea6b21370e49d7e5
[ "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
ISO-8859-1
C++
false
false
2,740
hpp
/* Copyright 2003-2006 Joaquín M López Muñoz. * 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/multi_index for library home page. */ #ifndef BOOST_MULTI_INDEX_DETAIL_HASH_INDEX_ITERATOR_HPP #define BOOST_MULTI_INDEX_DETAIL_HASH_INDEX_ITERATOR_HPP #if defined(_MSC_VER)&&(_MSC_VER>=1200) #pragma once #endif #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <boost/operators.hpp> #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) #include <boost/serialization/nvp.hpp> #include <boost/serialization/split_member.hpp> #endif namespace boost{ namespace multi_index{ namespace detail{ /* Iterator class for hashed indices. */ template<typename Node,typename BucketArray,typename Derived=mpl::na> class hashed_index_iterator: public forward_iterator_helper< hashed_index_iterator<Node,BucketArray,Derived>, typename Node::value_type, std::ptrdiff_t, const typename Node::value_type*, const typename Node::value_type&> { public: hashed_index_iterator(){} hashed_index_iterator(Node* node_,BucketArray* buckets_): node(node_),buckets(buckets_) {} const typename Node::value_type& operator*()const { return node->value(); } friend bool operator==( const hashed_index_iterator& x,const hashed_index_iterator& y) { return x.node==y.node; } hashed_index_iterator& operator++() { Node::increment(node,buckets->begin(),buckets->end()); return *this; } #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) /* Serialization. As for why the following is public, * see explanation in safe_mode_iterator notes in safe_mode.hpp. */ BOOST_SERIALIZATION_SPLIT_MEMBER() typedef typename Node::base_type node_base_type; template<class Archive> void save(Archive& ar,const unsigned int)const { node_base_type* bnode=node; ar<<serialization::make_nvp("pointer",bnode); ar<<serialization::make_nvp("pointer",buckets); } template<class Archive> void load(Archive& ar,const unsigned int) { node_base_type* bnode; ar>>serialization::make_nvp("pointer",bnode); node=static_cast<Node*>(bnode); ar>>serialization::make_nvp("pointer",buckets); } #endif /* get_node is not to be used by the user */ typedef Node node_type; Node* get_node()const{return node;} private: Node* node; BucketArray* buckets; }; } /* namespace multi_index::detail */ } /* namespace multi_index */ } /* namespace boost */ #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 109 ] ] ]
cea4f322045066cd1df2a9ab2ca4caf9ea987037
60ef79535d316aaeb4efc4f79d700fcb1c87586f
/CUGBLinker/LinkerPage.cpp
031ed1953fcab9321c909f52358b66ac3fb9a152
[]
no_license
dinglx/cugblinker
9b4cc5e129268cf3b2c14c99cd43a322c3f3487b
f4a2ee5bdecf41ec8ba91c63cf1923672964eae1
refs/heads/master
2021-01-16T00:27:54.122346
2009-12-16T17:00:50
2009-12-16T17:00:50
32,516,245
0
0
null
null
null
null
GB18030
C++
false
false
17,987
cpp
// LinkerPage.cpp : 实现文件 // #include "stdafx.h" #include "CUGBLinker.h" #include "CUGBLinkerDlg.h" #include "LinkerPage.h" #include "AccountInfo.h" #include "AccountDlg.h" #include "global.h" #include "TrafficPage.h" // CLinkerPage 对话框 IMPLEMENT_DYNAMIC(CLinkerPage, CPropertyPage) CLinkerPage::CLinkerPage() : CPropertyPage(CLinkerPage::IDD) , m_dis(0) , m_bAutoStart(FALSE) , m_osVersion(0) , m_bAutoCon(FALSE) , m_curAccountIndex(0) { } CLinkerPage::~CLinkerPage() { } void CLinkerPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Control(pDX, IDC_STATIC_ID, m_lblID); DDX_Control(pDX, IDC_COMBO_ID, m_cboID); DDX_Control(pDX, IDC_EDIT_PWD, m_txtPwd); DDX_Control(pDX, IDC_CHECK_SAVEPWD, m_chkSavePwd); DDX_Control(pDX, IDC_CONNECTINFO, m_txtInfo); DDX_Control(pDX, IDC_RADIO_IN, m_rdoRangeIn); DDX_Control(pDX, IDC_RADIO_OUT, m_rdoRangeOut); DDX_Control(pDX, IDC_CHECK_AUTOCON, m_chkAutoCon); DDX_Control(pDX, IDC_CHECK_WITHSYS, m_chkAutoStart); DDX_Control(pDX, IDC_BUTTON_CON, m_btnConnect); DDX_Control(pDX, IDC_BUTTON_DISCON, m_btnDisCon); DDX_Control(pDX, IDC_BUTTONXP_DISCON, m_btnDisConXP); DDX_CBString(pDX, IDC_COMBO_ID, theApp.curAccount.m_username); DDX_Text(pDX, IDC_EDIT_PWD, theApp.curAccount.m_password); DDX_Check(pDX, IDC_CHECK_SAVEPWD, theApp.curAccount.m_savePwd); DDX_Radio(pDX, IDC_RADIO_IN, theApp.curAccount.m_range); DDX_Check(pDX, IDC_CHECK_WITHSYS, m_bAutoStart); DDX_Check(pDX, IDC_CHECK_AUTOCON, m_bAutoCon); } BEGIN_MESSAGE_MAP(CLinkerPage, CPropertyPage) ON_STN_CLICKED(IDC_STATIC_ID, &CLinkerPage::OnStnClickedStaticId) ON_BN_CLICKED(IDC_BUTTON_CON, &CLinkerPage::OnBnClickedButtonCon) ON_BN_CLICKED(IDC_BUTTON_DISCON, &CLinkerPage::OnBnClickedButtonDiscon) ON_BN_CLICKED(IDC_BUTTONXP_DISCON, &CLinkerPage::OnBnClickedButtonDiscon) ON_CBN_EDITCHANGE(IDC_COMBO_ID, &CLinkerPage::OnCbnEditchangeComboId) ON_CBN_SELCHANGE(IDC_COMBO_ID, &CLinkerPage::OnCbnSelchangeComboId) ON_EN_CHANGE(IDC_EDIT_PWD, &CLinkerPage::OnEnChangeEditPwd) ON_COMMAND(ID_DISCON, &CLinkerPage::OnMenuDiscon) ON_COMMAND(ID_DISCONALL, &CLinkerPage::OnMenuDisconAll) ON_UPDATE_COMMAND_UI(ID_DISCON, &CLinkerPage::OnUpdateDiscon) ON_UPDATE_COMMAND_UI(ID_DISCONALL, &CLinkerPage::OnUpdateDisconall) ON_WM_INITMENUPOPUP() ON_MESSAGE(WM_UPDATEINFO, &CLinkerPage::OnUpdateInfo) ON_BN_CLICKED(IDC_CHECK_WITHSYS, &CLinkerPage::OnBnClickedCheckWithsys) ON_WM_DESTROY() ON_BN_CLICKED(IDC_RADIO_IN, &CLinkerPage::OnBnClickedSaveAccount) ON_BN_CLICKED(IDC_RADIO_OUT, &CLinkerPage::OnBnClickedSaveAccount) ON_BN_CLICKED(IDC_CHECK_SAVEPWD, &CLinkerPage::OnBnClickedSaveAccount) END_MESSAGE_MAP() // CLinkerPage 消息处理程序 void CLinkerPage::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) { CPropertyPage::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu); // TODO: 在此处添加消息处理程序代码 ASSERT(pPopupMenu != NULL); // Check the enabled state of various menu items. CCmdUI state; state.m_pMenu = pPopupMenu; ASSERT(state.m_pOther == NULL); ASSERT(state.m_pParentMenu == NULL); // Determine if menu is popup in top-level menu and set m_pOther to // it if so (m_pParentMenu == NULL indicates that it is secondary popup). HMENU hParentMenu; if (AfxGetThreadState()->m_hTrackingMenu == pPopupMenu->m_hMenu) state.m_pParentMenu = pPopupMenu; // Parent == child for tracking popup. else if ((hParentMenu = ::GetMenu(m_hWnd)) != NULL) { CWnd* pParent = this; // Child windows don't have menus--need to go to the top! if (pParent != NULL && (hParentMenu = ::GetMenu(pParent->m_hWnd)) != NULL) { int nIndexMax = ::GetMenuItemCount(hParentMenu); for (int nIndex = 0; nIndex < nIndexMax; nIndex++) { if (::GetSubMenu(hParentMenu, nIndex) == pPopupMenu->m_hMenu) { // When popup is found, m_pParentMenu is containing menu. state.m_pParentMenu = CMenu::FromHandle(hParentMenu); break; } } } } state.m_nIndexMax = pPopupMenu->GetMenuItemCount(); for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax; state.m_nIndex++) { state.m_nID = pPopupMenu->GetMenuItemID(state.m_nIndex); if (state.m_nID == 0) continue; // Menu separator or invalid cmd - ignore it. ASSERT(state.m_pOther == NULL); ASSERT(state.m_pMenu != NULL); if (state.m_nID == (UINT)-1) { // Possibly a popup menu, route to first item of that popup. state.m_pSubMenu = pPopupMenu->GetSubMenu(state.m_nIndex); if (state.m_pSubMenu == NULL || (state.m_nID = state.m_pSubMenu->GetMenuItemID(0)) == 0 || state.m_nID == (UINT)-1) { continue; // First item of popup can't be routed to. } state.DoUpdate(this, TRUE); // Popups are never auto disabled. } else { // Normal menu item. // Auto enable/disable if frame window has m_bAutoMenuEnable // set and command is _not_ a system command. state.m_pSubMenu = NULL; state.DoUpdate(this, FALSE); } // Adjust for menu deletions and additions. UINT nCount = pPopupMenu->GetMenuItemCount(); if (nCount < state.m_nIndexMax) { state.m_nIndex -= (state.m_nIndexMax - nCount); while (state.m_nIndex < nCount && pPopupMenu->GetMenuItemID(state.m_nIndex) == state.m_nID) { state.m_nIndex++; } } state.m_nIndexMax = nCount; } } BOOL CLinkerPage::OnInitDialog() { CPropertyPage::OnInitDialog(); // TODO: 在此添加额外的初始化 // 判断当前使用的系统,来决定显示什么样式的断开按钮 OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); m_osVersion=osvi.dwMajorVersion; if (m_osVersion>=6) // VISTA以上版本 { m_btnDisConXP.ShowWindow(SW_HIDE); m_btnDisCon.ShowWindow(SW_SHOW); } else // VISTA以下版本,XP等 { m_btnDisConXP.ShowWindow(SW_SHOW); m_btnDisCon.ShowWindow(SW_HIDE); } // 设置提示信息 m_lblID.SetText(L"单机此处管理帐号"); m_btnDisCon.SetDropDownMenu(IDR_DISMENU,0); //CAccountInfo newUser; //newUser.m_username=L"1111111"; //newUser.m_password=L"2222222"; //newUser.m_autoDis=true; //newUser.m_range=0; //newUser.m_savePwd=true; //newUser.m_showTip=true; //theApp.configXml.SetAccount(newUser); //theApp.accounts.Add(newUser); //for(int i=0;i<theApp.accounts.GetCount();i++) //{ // m_cboID.AddString(theApp.accounts[i].m_username); //} //m_txtInfo.SetWindowText(L"网络连接成功\r\n\r\n" // L"用 户 名: 丁林枭\r\n" // L"访问范围: 国内\r\n" // L"欠费断网: 是 \r\n" // L"超时检查: 8小时 \r\n" // L"当前连接: 0个 \r\n" // L"帐户余额: 40.000元 \r\n" // L"如果欠费自动断网,请注意及时加款。\r\n"); // 更新界面,设置按钮的可用状态 //UpdateData(FALSE); InitStat(); SetBtnStat(); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void CLinkerPage::OnCbnEditchangeComboId() { // TODO: 在此添加控件通知处理程序代码 m_cboID.GetWindowText(theApp.curAccount.m_username); SetItemText(); SetBtnStat(); } void CLinkerPage::OnCbnSelchangeComboId() { // TODO: 在此添加控件通知处理程序代码 m_curAccountIndex=m_cboID.GetCurSel(); if (m_curAccountIndex>=0) m_cboID.GetLBText(m_curAccountIndex,theApp.curAccount.m_username); SetItemText(); SetBtnStat(); } void CLinkerPage::OnEnChangeEditPwd() { // TODO: 如果该控件是 RICHEDIT 控件,则它将不会 // 发送该通知,除非重写 CPropertyPage::OnInitDialog() // 函数并调用 CRichEditCtrl().SetEventMask(), // 同时将 ENM_CHANGE 标志“或”运算到掩码中。 // TODO: 在此添加控件通知处理程序代码 if (GetFocus()==&m_txtPwd) { OnBnClickedSaveAccount(); } SetBtnStat(); } // 用户改变时需要调用此函数来更新其他控件状态 void CLinkerPage::SetItemText(void) { // 更新界面其他控件状态 int index=m_cboID.FindStringExact(-1,theApp.curAccount.m_username); m_curAccountIndex=index; if (index>=0) { tip_flag=true;//恢复超流量提示功能 theApp.curAccount=theApp.accounts[index]; if (theApp.curAccount.m_savePwd) { m_txtPwd.SetWindowText(theApp.curAccount.m_password); } else m_txtPwd.SetWindowText(L""); if (theApp.curAccount.m_range==0) { m_rdoRangeIn.SetCheck(1); m_rdoRangeOut.SetCheck(0); } else { m_rdoRangeIn.SetCheck(0); m_rdoRangeOut.SetCheck(1); } m_chkSavePwd.SetCheck(theApp.curAccount.m_savePwd); if (m_chkSavePwd.GetCheck()) { m_chkAutoCon.EnableWindow(TRUE); } else m_chkAutoCon.EnableWindow(FALSE); CTime curTime=CTime::GetCurrentTime(); CString curDate=curTime.Format(L"%Y-%m-%d"); if (curDate!=theApp.configXml.GetDate()) { theApp.curAccount.m_curTraffic=0; } // 初始化流量界面 CCUGBLinkerDlg* pMainWnd=(CCUGBLinkerDlg*)theApp.m_pMainWnd; CTrafficPage* pTrafficPage=(CTrafficPage*)&(pMainWnd->m_trafficPage); pTrafficPage->SetItemStat(); //pTrafficPage->UpdateData(FALSE); //if (theApp.curAccount.m_showTip) //{ // pTrafficPage->m_chkAutoDis.EnableWindow(TRUE); //} //else // pTrafficPage->m_chkAutoDis.EnableWindow(FALSE); } else { m_txtPwd.SetWindowText(L""); m_chkSavePwd.SetCheck(0); m_chkAutoCon.EnableWindow(FALSE); } } void CLinkerPage::SetBtnStat(void) { // 更新按钮状态 m_txtPwd.GetWindowText(theApp.curAccount.m_password); if (theApp.curAccount.m_username!="" && theApp.curAccount.m_password!="") { m_btnConnect.EnableWindow(TRUE); m_btnDisConXP.EnableWindow(TRUE); } else { m_btnConnect.EnableWindow(FALSE); m_btnDisConXP.EnableWindow(FALSE); m_btnDisCon.SetWindowText(L"断开"); m_dis=0; } } void CLinkerPage::OnMenuDiscon() { // TODO: 在此添加命令处理程序代码 m_btnDisCon.SetWindowText(L"断开"); m_dis=0; //OnBnClickedButtonDiscon(); // 选择菜单后自动触发单击事件 } void CLinkerPage::OnMenuDisconAll() { // TODO: 在此添加命令处理程序代码 m_btnDisCon.SetWindowText(L"断开全部"); m_dis=1; //OnBnClickedButtonDiscon(); // 选择菜单后自动触发单击事件 } void CLinkerPage::OnUpdateDiscon(CCmdUI *pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(!m_dis); } void CLinkerPage::OnUpdateDisconall(CCmdUI *pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 if (theApp.curAccount.m_username!="" && theApp.curAccount.m_password!="") { pCmdUI->Enable(TRUE); } else pCmdUI->Enable(FALSE); pCmdUI->SetCheck(m_dis); } void CLinkerPage::OnStnClickedStaticId() { // TODO: 在此添加控件通知处理程序代码 CAccountDlg accountDlg; accountDlg.DoModal(); UpdateComboBox(); // 设置提示信息 m_lblID.SetText(L"单机此处管理帐号"); } void CLinkerPage::OnBnClickedButtonCon() { // TODO: 在此添加控件通知处理程序代码 // 当连接成功时添加新用户到用户列表中 UpdateData(TRUE); AfxBeginThread(Connect, NULL); m_txtInfo.SetWindowText(L"连接中…"); } void CLinkerPage::OnBnClickedButtonDiscon() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); if (m_osVersion<6) // VISTA以下版本,XP等 m_dis=1; AfxBeginThread(DisConnect, &m_dis); m_txtInfo.SetWindowText(L"断开中…"); } // 当用户列表改变后需要更新ComboBox内容 void CLinkerPage::UpdateComboBox(void) { //CString curStr; //m_cboID.GetWindowText(curStr); //UpdateData(TRUE); // 清空原ComboBox内容 int size=m_cboID.GetCount(); for (int i=0;i<size;i++) { m_cboID.DeleteString(0); } // 将列表中用户名添加到ComboBox中 size=theApp.accounts.GetCount(); for (int i=0;i<size;i++) { m_cboID.AddString(theApp.accounts[i].m_username); } if (m_cboID.FindStringExact(-1,theApp.curAccount.m_username)==CB_ERR) { m_cboID.SetWindowText(L""); } else { m_cboID.SetWindowText(theApp.curAccount.m_username); m_cboID.SelectString(-1,theApp.curAccount.m_username); } OnCbnEditchangeComboId(); } // 更新信息提示框内容已经添加新用户信息到用户列表 LRESULT CLinkerPage::OnUpdateInfo(WPARAM wParam, LPARAM lParam) { CCUGBLinkerDlg* pMainWnd=(CCUGBLinkerDlg*)theApp.m_pMainWnd; CString* strInfo=(CString*)wParam; int* success=(int*)lParam;//0不成功,1连接成功,2断开成功 // 设置中间提示窗口内容 m_txtInfo.SetWindowText(*strInfo); // 弹出托盘提示气球 strInfo->Replace(L"\n",L""); pMainWnd->nid.cbSize=NOTIFYICONDATA_V2_SIZE;//sizeof(NOTIFYICONDATA); pMainWnd->nid.uFlags = NIF_INFO; _tcscpy_s(pMainWnd->nid.szInfo,*strInfo); if (*success==1)//连接成功 { pMainWnd->nid.dwInfoFlags = NIIF_INFO; _tcscpy_s(pMainWnd->nid.szInfoTitle,L"连接成功"); } else if (*success==2)//断开成功 { pMainWnd->nid.dwInfoFlags = NIIF_INFO; _tcscpy_s(pMainWnd->nid.szInfoTitle,L"断开成功"); } else if (*success==-1)//连接失败 { pMainWnd->nid.dwInfoFlags = NIIF_ERROR; _tcscpy_s(pMainWnd->nid.szInfoTitle,L"连接失败"); } else if (*success==-2)//断开失败 { pMainWnd->nid.dwInfoFlags = NIIF_ERROR; _tcscpy_s(pMainWnd->nid.szInfoTitle,L"断开失败"); } Shell_NotifyIcon(NIM_MODIFY, &pMainWnd->nid); CString tempStr; m_txtPwd.GetWindowText(tempStr); // 添加新用户到用户列表 if (*success==1 || (m_dis==1 && *success==2)) { // 连接或断开全部成功时添加新用户到用户列表中 int index=m_cboID.FindStringExact(-1,theApp.curAccount.m_username); if (index==CB_ERR) { theApp.curAccount.m_curTraffic=0; theApp.accounts.Add(theApp.curAccount); UpdateComboBox(); } SaveAccountToXML(); //else //{ // theApp.accounts[index]=theApp.curAccount; //} } m_txtPwd.SetWindowText(tempStr); if(strInfo) delete strInfo; if(success) delete success; return 0; } void CLinkerPage::OnBnClickedCheckWithsys() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); CString fileName('\0',200); GetModuleFileName(NULL,fileName.GetBuffer(),200); fileName.ReleaseBuffer(); HKEY hRegKey=NULL; CString str=_T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"); if(RegOpenKey(HKEY_CURRENT_USER,str,&hRegKey) != ERROR_SUCCESS) return; if(m_bAutoStart) { RegSetValueEx(hRegKey,_T("CUGBLinker"),0,REG_SZ, (CONST BYTE *)fileName.GetBuffer(),fileName.GetLength()*2); fileName.ReleaseBuffer(); } else { RegDeleteValue(hRegKey,_T("CUGBLinker")); } RegCloseKey(hRegKey); } void CLinkerPage::InitStat(void) { // 随系统启动复选框状态 HKEY hRegKey=NULL; CString str=_T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"); if(RegOpenKey(HKEY_CURRENT_USER,str,&hRegKey) == ERROR_SUCCESS) { if(RegQueryValueEx(hRegKey,_T("CUGBLinker"),NULL,NULL,NULL,NULL)==ERROR_SUCCESS) m_chkAutoStart.SetCheck(1); else m_chkAutoStart.SetCheck(0); } RegCloseKey(hRegKey); // 用户名列表状态 int accountLen=theApp.configXml.GetAccountCount(); for (int i=0;i<accountLen;i++) { theApp.accounts.Add(theApp.configXml.GetAccount(i)); } UpdateComboBox(); m_curAccountIndex=theApp.configXml.GetActiveAccount(); m_cboID.SetCurSel(m_curAccountIndex); OnCbnSelchangeComboId(); //if (m_curAccountIndex>=0 && m_curAccountIndex<theApp.accounts.GetCount()) //{ // theApp.curAccount=theApp.accounts[m_curAccountIndex]; // SetItemText(); //} // 自动连接状态 m_chkAutoCon.SetCheck(theApp.configXml.GetAutoConnect()); if (m_btnConnect.IsWindowEnabled()) { if (m_chkAutoCon.GetCheck()) { OnBnClickedButtonCon(); } } else m_chkAutoCon.EnableWindow(FALSE); // 断开按钮状态 m_dis=theApp.configXml.GetDisBtnStatus(); if (m_dis) m_btnDisCon.SetWindowText(L"断开全部"); else m_btnDisCon.SetWindowText(L"断开"); } void CLinkerPage::OnDestroy() { CPropertyPage::OnDestroy(); // TODO: 在此处添加消息处理程序代码 // 保存各项设置到xml文件 SaveAccountToXML(); theApp.configXml.SaveFile(); } void CLinkerPage::OnBnClickedSaveAccount() { // TODO: 在此添加控件通知处理程序代码 // 保存当前用户设置 UpdateData(TRUE); if (m_curAccountIndex>=0 && m_curAccountIndex<theApp.accounts.GetCount()) { theApp.accounts[m_curAccountIndex]=theApp.curAccount; } if (m_chkSavePwd.GetCheck()) { m_chkAutoCon.EnableWindow(TRUE); } else m_chkAutoCon.EnableWindow(FALSE); } void CLinkerPage::SaveAccountToXML(void) { UpdateData(TRUE); // 用户名列表状态 int accountLen=theApp.configXml.GetAccountCount(); for (int i=accountLen-1;i>=0;i--) { theApp.configXml.DelAccount(i); } theApp.configXml.SaveFile(); accountLen=theApp.accounts.GetCount(); for (int i=0;i<accountLen;i++) { theApp.configXml.SetAccount(theApp.accounts[i]); } theApp.configXml.SetActiveAccount(m_curAccountIndex); // 自动连接状态 theApp.configXml.SetAutoConnect(m_bAutoCon); // 断开按钮状态 theApp.configXml.SetDisBtnStatus(m_dis); } BOOL CLinkerPage::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if( pMsg->message == WM_KEYDOWN ) { if (pMsg->wParam == VK_RETURN) { OnBnClickedButtonCon(); return true; } } return CPropertyPage::PreTranslateMessage(pMsg); }
[ "dlx1986@4ddcaae0-7081-11de-ae35-f3f989a3c448", "dinglinxiao@4ddcaae0-7081-11de-ae35-f3f989a3c448" ]
[ [ [ 1, 5 ], [ 7, 7 ], [ 12, 18 ], [ 22, 36 ], [ 47, 47 ], [ 53, 59 ], [ 61, 62 ], [ 72, 72 ], [ 76, 80 ], [ 166, 192 ], [ 203, 203 ], [ 217, 218 ], [ 221, 225 ], [ 237, 239 ], [ 264, 264 ], [ 267, 268 ], [ 319, 319 ], [ 330, 330 ], [ 335, 335 ], [ 380, 382 ], [ 386, 392 ], [ 398, 399 ], [ 401, 402 ], [ 405, 405 ], [ 408, 408 ], [ 456, 456 ], [ 458, 458 ], [ 462, 462 ], [ 467, 467 ], [ 472, 472 ], [ 477, 477 ], [ 501, 502 ], [ 535, 535 ], [ 548, 555 ], [ 557, 557 ], [ 559, 559 ], [ 565, 565 ], [ 575, 577 ], [ 582, 590 ], [ 615, 616 ], [ 624, 631 ], [ 634, 634 ] ], [ [ 6, 6 ], [ 8, 11 ], [ 19, 21 ], [ 37, 46 ], [ 48, 52 ], [ 60, 60 ], [ 63, 71 ], [ 73, 75 ], [ 81, 165 ], [ 193, 202 ], [ 204, 216 ], [ 219, 220 ], [ 226, 236 ], [ 240, 263 ], [ 265, 266 ], [ 269, 318 ], [ 320, 329 ], [ 331, 334 ], [ 336, 379 ], [ 383, 385 ], [ 393, 397 ], [ 400, 400 ], [ 403, 404 ], [ 406, 407 ], [ 409, 455 ], [ 457, 457 ], [ 459, 461 ], [ 463, 466 ], [ 468, 471 ], [ 473, 476 ], [ 478, 500 ], [ 503, 534 ], [ 536, 547 ], [ 556, 556 ], [ 558, 558 ], [ 560, 564 ], [ 566, 574 ], [ 578, 581 ], [ 591, 614 ], [ 617, 623 ], [ 632, 633 ], [ 635, 650 ] ] ]
d42546897caf72e300ba1bea4cf6f537c5eb0b1f
6eef3e34d3fe47a10336a53df1a96a591b15cd01
/ASearch/Mv4/EquivManager.hpp
1b9bea32f7212e04f46e43be5ee0b707a36e8af5
[]
no_license
praveenmunagapati/alkaline
25013c233a80b07869e0fdbcf9b8dfa7888cc32e
7cf43b115d3e40ba48854f80aca8d83b67f345ce
refs/heads/master
2021-05-27T16:44:12.356701
2009-10-29T11:23:09
2009-10-29T11:23:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,006
hpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved ______________________________________________ written by Daniel Doubrovkine - [email protected] */ #ifndef ALKALINE_EQUIV_MANAGER_HPP #define ALKALINE_EQUIV_MANAGER_HPP #include <platform/include.hpp> #include <String/TSStringTable.hpp> #include <Io/Io.hpp> class CEquivManager : public CTSStringTable { property(CString, Filename); property(CString, Class); property(CVector<CString>, EmailVector); protected_property(struct_stat, Stat); property(CStringTable, PersistentTable); property(CMutex, LoadMutex); public: CEquivManager(const CString& Class = CString::EmptyCString, const CString& Filename = CString::EmptyCString); virtual ~CEquivManager(void); CString GetBuffer(void) const; void Read(void); bool HasChanged(void) const; void Set(const CString& Name, const CString& Value); }; #endif
[ [ [ 1, 38 ] ] ]
c4bec7cb427d264acc9a1832164f324d8eb65e8b
f9351a01f0e2dec478e5b60c6ec6445dcd1421ec
/itl/boost/itl_xt/ordered_type.hpp
fabaff95ddbb06c7adcbdd91a4651cebd02021fe
[ "BSL-1.0" ]
permissive
WolfgangSt/itl
e43ed68933f554c952ddfadefef0e466612f542c
6609324171a96565cabcf755154ed81943f07d36
refs/heads/master
2016-09-05T20:35:36.628316
2008-11-04T11:44:44
2008-11-04T11:44:44
327,076
0
1
null
null
null
null
ISO-8859-1
C++
false
false
5,139
hpp
/*----------------------------------------------------------------------------+ Copyright (c) 2007-2008: Joachim Faulhaber +-----------------------------------------------------------------------------+ Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin +-----------------------------------------------------------------------------+ Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +----------------------------------------------------------------------------*/ #ifndef __ordered_type_h_JOFA_011005_H__ #define __ordered_type_h_JOFA_011005_H__ #include <string> namespace boost{namespace itl { /// an enumeration ordered class type /** class template <b>ordered_type</b> defines objects that can be ordered by an enumeration type that is associated to the template parameter TypeDomain. Every object of this class exposes a value of that enumeration type by a function <b>type()</b> @author Joachim Faulhaber */ template <class TypeDomain> class ordered_type { public: typedef ordered_type* OrderedTypePIT; public: /// virtual destructors to avoid memory leaks virtual ~ordered_type(){} /// the objects type virtual typename TypeDomain::DomainET type()const=0; /// the objects value virtual const typename TypeDomain::ValueBaseTD* value()const=0; /// Comparison on type level virtual bool isLessOnType(const ordered_type* x2)const=0; /// Equivalece relation <tt>this->type()==x2->type()</tt> virtual bool isTypeEquivalent(const ordered_type* x2)const=0; /// comparisons on value level virtual bool isEqual(const ordered_type* x2)const=0; virtual bool isLess(const ordered_type* x2)const=0; /// equality on value-level using == operator virtual bool operator == (const ordered_type& x2)const=0; //JODO Aufrufmechnismus für stl::container operator ==.verstehen //virtual bool operator == (const OrderedTypePIT& x2)const=0; //KEEP JODO einpflegen // virtual bool isLess(const ordered_type* x2)const=0; // virtual bool operator < (const ordered_type& x2)const=0; /// string representation virtual std::string as_string()const=0 ; }; template <class TypeDomain> class ordered_type_base : public ordered_type<TypeDomain> { public: typedef ordered_type<TypeDomain>* OrderedTypeOfDomPIT; public: virtual bool isLessOnType (const ordered_type<TypeDomain>* x2)const { return this->type() < x2->type(); } virtual bool isTypeEquivalent (const ordered_type<TypeDomain>* x2)const { return this->type() == x2->type(); } // comparisons on value level bool isEqual(const ordered_type<TypeDomain>* x2)const { return isTypeEquivalent(x2) && isValueEqual(x2); } bool operator == (const ordered_type<TypeDomain>& x2)const { return isEqual(&x2); } bool isLess(const ordered_type<TypeDomain>* x2)const { return this < x2; } /*JODO Aufrufmechnismus für stl::container operator ==.verstehen bool operator == (const OrderedTypeOfDomPIT& x2)const { return isEqual(x2); } */ /*KEEP JODO Einfplegen bool isLess(const ordered_type<TypeDomain>* x2)const { return isLessOnType(x2) && isValueLess(x2); } bool operator < (const ordered_type<TypeDomain>& x2)const { return isLess(&x2); } */ protected: /// Gleichheit der Werte virtual bool isValueEqual(const ordered_type<TypeDomain>* x2)const=0; //KEEP JODO Einfplegen //virtual bool isValueLess(const ordered_type<TypeDomain>* x2)const=0; }; }} // namespace itl boost #endif // __ordered_type_h_JOFA_011005_H__
[ "jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a" ]
[ [ [ 1, 147 ] ] ]
02b1930e745d3e0a9090a901e9ce6e644c3eda21
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Gfx/GUI/GuiScrollWindow.hpp
64a358d1f7a618ddf250f2642d7f05692baf1405
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
hpp
#ifndef GUI_SCROLL_WINDOW_HPP #define GUI_SCROLL_WINDOW_HPP #include "GuiWindow.hpp" namespace Spiral { namespace GUI { class GuiSlider; class GuiManager; class GuiScrollWindow : public GuiWindow { public: GuiScrollWindow( const Math::Vector2f& position, const Rect<SpReal>& rect,boost::uint32_t scrollBarThickness, const boost::shared_ptr<GuiWindow>& scrollContents, const boost::shared_ptr<GuiManager>& guiManager ); void AttachWindow( const boost::shared_ptr<GuiWindow>& window ); void DetachWindow(); private: void OnScrollH( boost::int32_t eventId, GuiWindow* window, const boost::any& data ); void OnScrollV( boost::int32_t eventId, GuiWindow* window, const boost::any& data ); private: boost::shared_ptr<GuiSlider> m_scrollVBar; boost::shared_ptr<GuiSlider> m_scrollHBar; boost::shared_ptr<GuiWindow> m_scrollArea; boost::shared_ptr<GuiWindow> m_scrollContents; boost::uint32_t m_scrollBarThickness; }; } } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 36 ] ] ]
ada4df321377975d34eb5efa0508977233c896b1
dc52cf6ac9fecbff2a430d8b4d6be4c6bbc4d593
/My_router/trunk/My_router/MyRouter.h
35c47b4f25b1234c257daefb43bbf9f485886399
[]
no_license
marmor7/my-router
ca23540bdd27958ef53c9c21c7b01c271b4b4c4f
73e78061fdcd6da96d0d46e143eba7bf3bddde27
refs/heads/master
2016-09-10T02:02:12.005182
2008-08-27T22:40:22
2008-08-27T22:40:22
32,452,857
0
0
null
null
null
null
UTF-8
C++
false
false
5,927
h
#pragma once #include "stdafx.h" #include "Utils.h" #include "RouterSocket.h" //Fwd declarations class RoutingTable; using namespace std; #define null 0 #define TIMEOUT_FAIL 82 #define TIMEOUT_SEND_MIN 20 #define TIMEOUT_SEND_MAX 40 #define SET_TIMEOUT(time, val) time.tv_sec = val; time.tv_usec = 0; #define SET_CMP(time, sec, micro) ((time.tv_sec == sec) && (time.tv_usec == micro)) #define TIMERSUB(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) class MyRouter { public: //************************************ // Method: ~MyRouter // FullName: MyRouter::~MyRouter // Access: public // Returns: // Qualifier: Destructor //************************************ ~MyRouter(); //************************************ // Method: MyRouter // FullName: MyRouter::MyRouter // Access: public // Returns: // Qualifier: Constructor // Parameter: string name - Router's name //************************************ MyRouter(string name); //************************************ // Method: GetName // FullName: MyRouter::GetName // Access: public // Returns: std::string // Qualifier: Gets router's name //************************************ char* GetName(); //************************************ // Method: SetName // FullName: MyRouter::SetName // Access: public // Returns: void // Qualifier: Sets a new name to the router // Parameter: string name //************************************ void SetName(string name); //************************************ // Method: AddRouter // FullName: MyRouter::AddRouter // Access: public // Returns: Utils::ReturnStatus // Qualifier: Add a router (name, ip, port) // Parameter: char name[8] // Parameter: in_addr * address // Parameter: short //************************************ Utils::ReturnStatus AddRouter(char name[MAX_ROUTER_NAME], in_addr* address, unsigned short port); //************************************ // Method: AddRoute // FullName: MyRouter::AddRoute // Access: public // Returns: Utils::ReturnStatus // Qualifier: Adds a subnets array for a router // Parameter: char name[MAX_ROUTER_NAME] // Parameter: in_addr * ip_array // Parameter: int mask //************************************ Utils::ReturnStatus AddRoute(char name[MAX_ROUTER_NAME], Subnet* subnet_ptr); //************************************ // Method: Run // FullName: MyRouter::Run // Access: public // Returns: void // Qualifier: Main loop of the router //************************************ void Run(); //************************************ // Method: SetRoutersIpAndPort // FullName: MyRouter::SetRoutersIpAndPort // Access: public // Returns: void // Qualifier: Set the routers internal configuration of its own IP and port // Parameter: string ip // Parameter: short port //************************************ void SetRoutersIpAndPort(string ip, unsigned short port); //************************************ // Method: GetMySubnets // FullName: MyRouter::GetMySubnets // Access: public // Returns: vector<Subnet*> // Qualifier: Gets the vector containing the router's subnets which it is connected to //************************************ vector<Subnet*> GetMySubnets(); //************************************ // Method: AddSubnet // FullName: MyRouter::AddSubnet // Access: public // Returns: void // Qualifier: Adds a subnet to subnet's vector // Parameter: Subnet * subnet //************************************ void AddSubnet(Subnet* subnet); //Enumerator of the possible events. enum RouterEvents { RT_EVENT_READ_CONFIG, RT_EVENT_TIMEOUT, RT_EVENT_DV_RECEIVED, RT_EVENT_SENDING_DV }; //************************************ // Method: PrintEvent // FullName: MyRouter::PrintEvent // Access: public // Returns: std::string // Qualifier: Prints an event // Parameter: RouterEvents event //************************************ string PrintEvent(RouterEvents event); //************************************ // Method: Handle // FullName: MyRouter::Handle // Access: public // Returns: Utils::ReturnStatus // Qualifier: Handles incoming data // Parameter: RouterEvents event // Parameter: void * data //************************************ Utils::ReturnStatus Handle(RouterEvents event, void* data); //Removes non-neighbors from the RouterEntry table Utils::ReturnStatus ClearRouters(); protected: //Initialize the fd_sets void InitSets(); //Is a router a neighbor bool IsNeighbor(Subnet* first_subnet_ptr, Subnet* second_subnet_ptr); //Display an fd_set void DisplaySet(string title, fd_set & set); //Router's name char m_name[MAX_ROUTER_NAME]; sockaddr_in m_router_ip; //Remove unsigned short m_router_port; //Remove //Router's routing table RoutingTable* m_table; //Router database (name, ip, port) RouterEntry* m_routers; RouterEntry m_my_entry; //Number of neighboring routers int m_num_of_routers; //List of router's subnets vector<Subnet*>* m_my_router_subnets; //Sets of sockets - used by select function fd_set m_active_fd_set, m_read_fd_set, m_write_fd_set; //Max socket descriptor int m_max_fd; //This router socket descriptor int m_my_fd; //In and out buffers buffer m_in_buf; private: };
[ "gazith@b5815fbd-9c51-0410-89e8-2153d734e944", "adam.sharvit@b5815fbd-9c51-0410-89e8-2153d734e944" ]
[ [ [ 1, 1 ], [ 4, 4 ], [ 11, 29 ], [ 36, 37 ], [ 45, 46 ], [ 55, 55 ], [ 59, 59 ], [ 64, 64 ], [ 74, 74 ], [ 79, 79 ], [ 82, 82 ], [ 86, 86 ], [ 94, 94 ], [ 98, 98 ], [ 103, 103 ], [ 107, 107 ], [ 118, 118 ], [ 127, 127 ], [ 134, 164 ], [ 166, 167 ], [ 169, 169 ], [ 171, 171 ], [ 173, 175 ], [ 177, 177 ], [ 179, 179 ], [ 182, 182 ], [ 188, 188 ], [ 190, 190 ], [ 194, 194 ], [ 198, 209 ], [ 211, 212 ] ], [ [ 2, 3 ], [ 5, 10 ], [ 30, 35 ], [ 38, 44 ], [ 47, 54 ], [ 56, 58 ], [ 60, 63 ], [ 65, 73 ], [ 75, 78 ], [ 80, 81 ], [ 83, 85 ], [ 87, 93 ], [ 95, 97 ], [ 99, 102 ], [ 104, 106 ], [ 108, 117 ], [ 119, 126 ], [ 128, 133 ], [ 165, 165 ], [ 168, 168 ], [ 170, 170 ], [ 172, 172 ], [ 176, 176 ], [ 178, 178 ], [ 180, 181 ], [ 183, 187 ], [ 189, 189 ], [ 191, 193 ], [ 195, 197 ], [ 210, 210 ] ] ]
2fda88775cc881c89a5cefd5c084d59ec49c0954
ad85dfd8765f528fd5815d94acde96e28e210a43
/trunk/include/OpenLayer/Includes.hpp
28e590a71235f03777be5ee4a3ea774fe56e09e2
[]
no_license
BackupTheBerlios/openlayer-svn
c53dcdd84b74fd4687c919642e6ccef3dd4bba79
3086e76972e6674c9b40282bb7028acb031d0593
refs/heads/master
2021-01-01T19:25:13.382956
2007-07-18T17:09:55
2007-07-18T17:09:55
40,823,139
1
0
null
null
null
null
UTF-8
C++
false
false
641
hpp
#ifndef OL_INCLUDES_HPP #define OL_INCLUDES_HPP #include "Declspec.hpp" /* #if (OL_DRIVER == SDL) #define SCREEN_W "notspecified" #define SCREEN_H "notspecified" #define getr32 #define getg32 #define getb32 #define OL_MEMORY_IMG void #else // (OL_DRIVER == ALLEGRO_GL) */ #include <allegro.h> #include <alleggl.h> #define OL_MEMORY_IMG BITMAP inline OL_LIB_DECLSPEC int OlGetAlpha( OL_MEMORY_IMG *bitmap, int x, int y ) { return geta32( _getpixel32( bitmap, x, y )); } //#endif // OL_DRIVER #include <string> #endif // OL_INCLUDES_HPP
[ "bradeeoh@9f4572f3-6e0d-0410-ba3b-903ab02ac46b", "juvinious@9f4572f3-6e0d-0410-ba3b-903ab02ac46b" ]
[ [ [ 1, 3 ], [ 5, 24 ], [ 26, 34 ] ], [ [ 4, 4 ], [ 25, 25 ] ] ]
182b4200efa4f7950c6d07bef3fb36ba46693abe
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/mpl/test/for_each.cpp
c7d28bdfb9e527720ad03b20e8bf5427484275f1
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,976
cpp
// Copyright Aleksey Gurtovoy 2000-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/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/test/for_each.cpp,v $ // $Date: 2004/10/30 08:27:47 $ // $Revision: 1.12.2.2 $ #include <boost/mpl/for_each.hpp> #include <boost/mpl/list.hpp> #include <boost/mpl/range_c.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/lambda.hpp> #include <boost/bind.hpp> #include <vector> #include <iostream> #include <algorithm> #include <typeinfo> #include <cassert> namespace mpl = boost::mpl; struct type_printer { type_printer(std::ostream& s) : f_stream(&s) {} template< typename U > void operator()(mpl::identity<U>) { *f_stream << typeid(U).name() << '\n'; } private: std::ostream* f_stream; }; struct value_printer { value_printer(std::ostream& s) : f_stream(&s) {} template< typename U > void operator()(U x) { *f_stream << x << '\n'; } private: std::ostream* f_stream; }; #ifdef __ICL # pragma warning(disable:985) #endif int main() { typedef mpl::list<char,short,int,long,float,double> types; mpl::for_each< types,mpl::make_identity<mpl::_1> >(type_printer(std::cout)); typedef mpl::range_c<int,0,10> numbers; std::vector<int> v; #if defined(__SGI_STL_PORT) void (std::vector<int>::* push_back)(int const&) = &std::vector<int>::push_back; mpl::for_each<numbers>( boost::bind(push_back, &v, _1) ); #else mpl::for_each<numbers>( boost::bind(&std::vector<int>::push_back, &v, _1) ); #endif mpl::for_each< numbers >(value_printer(std::cout)); for (unsigned i = 0; i < v.size(); ++i) assert(v[i] == (int)i); return 0; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 83 ] ] ]
57ae25275b2af78394d552194172f70cd5082252
b26957d6f3a64b19cda1d76b265d93047c114891
/StudentDetection/StudentDetection/AboutDlg.cpp
9e0b0c0f10fa8187f33ec9a517036749c8620807
[]
no_license
SachinTS/khoa-luan-tot-nghiep
58e7efbd51d5f807f08b62a641672b4fc62f7990
7200721aded827731232c49aeade804febfba086
refs/heads/master
2016-09-06T13:46:12.228528
2010-08-07T06:47:45
2010-08-07T06:47:45
33,529,631
0
0
null
null
null
null
UTF-8
C++
false
false
1,472
cpp
// AboutDlg.cpp : implementation file // #include "stdafx.h" #include "StudentDetection.h" #include "AboutDlg.h" // AboutDlg dialog IMPLEMENT_DYNAMIC(AboutDlg, CDialog) AboutDlg::AboutDlg(CWnd* pParent /*=NULL*/) : CDialog(AboutDlg::IDD, pParent) { } AboutDlg::~AboutDlg() { } void AboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(AboutDlg, CDialog) ON_WM_ERASEBKGND() ON_WM_CTLCOLOR() END_MESSAGE_MAP() // AboutDlg message handlers HBRUSH AboutDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr; if( nCtlColor == CTLCOLOR_STATIC ) { pDC->SetBkMode(TRANSPARENT); //pDC->SetTextColor(RGB(255, 0, 0)); hbr = (HBRUSH)GetStockObject( NULL_BRUSH ); } else { hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); } return hbr; } BOOL AboutDlg::OnEraseBkgnd(CDC* pDC) { // TODO: Add your message handler code here and/or call default CDialog::OnEraseBkgnd(pDC); SBitdraw(pDC,IDB_BMP_BACKGROUND); return true; } bool AboutDlg::SBitdraw(CDC *pDC, UINT nIDResource) { CBitmap* m_bitmap; m_bitmap=new CBitmap(); m_bitmap->LoadBitmap(nIDResource); if(!m_bitmap->m_hObject) return true; CRect rect; GetClientRect(&rect); CDC dc; dc.CreateCompatibleDC(pDC); dc.SelectObject(m_bitmap); int xo=0, yo=0; pDC->BitBlt(xo, yo, rect.Width(),rect.Height(), &dc, 0, 0, SRCCOPY); return true; }
[ "tuonghuy09@b0713345-de22-efb3-841d-461946120171" ]
[ [ [ 1, 80 ] ] ]
7dabb0e1fd8a70612bfb19e7986f46bb7bcac223
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/Blindmode/CPP/Targets/MapLib/Shared/include/Windows/mcostream.h
966a4ef0e3fcc5c2643b371df5331e47565b67e0
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MCOSTREAM_H #define MCOSTREAM_H #include <iostream> #endif
[ [ [ 1, 19 ] ] ]
d87d87bd74b12bb828e3e82739faa4f7e8b85797
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/tutorials/src/signals_tutorial/receiverscript_main.cc
8d1b2b3bef80bf23fc24499c4700a211810841a7
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
449
cc
/** @file receiverscript_main.cc @author Luis Jose Cabellos Gomez <[email protected]> (C) 2005 Tragnarion Studios */ #include "signals_tutorial/receiverscript.h" #include "kernel/nkernelserver.h" nNebulaScriptClass( ReceiverScript, "nroot" ); //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 13 ] ] ]
ec107874dba042a39eed346c7ae07b9700768453
2e5fd1fc05c0d3b28f64abc99f358145c3ddd658
/deps/quickfix/src/.NET/MemoryMessageStore.cpp
5bdb1d63853429f323ddf95196acf7a723ae37a5
[ "BSD-2-Clause" ]
permissive
indraj/fixfeed
9365c51e2b622eaff4ce5fac5b86bea86415c1e4
5ea71aab502c459da61862eaea2b78859b0c3ab3
refs/heads/master
2020-12-25T10:41:39.427032
2011-02-15T13:38:34
2011-02-15T20:50:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
52
cpp
#include "stdafx.h" #include "MemoryMessageStore.h"
[ [ [ 1, 2 ] ] ]
958b66e3ce7eee08075d50eec2e93fd4161261d4
09f09cd06656848ed80f132c7073568c4ce87bd5
/ANNRecognition/WTL71/atlmisc.h
15fe6940af3bbfad7c3754ab0f7e531cffc3a381
[]
no_license
cyb3727/annrecognition
90ecf3af572f8b629b276a06af51785f656ca2be
6e4f200e1119196eba5e7fe56efa93e3ed978bc1
refs/heads/master
2021-01-17T11:31:39.865232
2011-07-10T13:50:44
2011-07-10T13:50:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
100,196
h
// Windows Template Library - WTL version 7.1 // Copyright (C) 1997-2003 Microsoft Corporation // All rights reserved. // // This file is a part of the Windows Template Library. // The code and information is provided "as-is" without // warranty of any kind, either expressed or implied. #ifndef __ATLMISC_H__ #define __ATLMISC_H__ #pragma once #ifndef __cplusplus #error ATL requires C++ compilation (use a .cpp suffix) #endif #ifndef __ATLAPP_H__ #error atlmisc.h requires atlapp.h to be included first #endif #ifdef _ATL_TMP_NO_CSTRING #define _WTL_NO_CSTRING #endif #if defined(_WTL_USE_CSTRING) && defined(_WTL_NO_CSTRING) #error Conflicting options - both _WTL_USE_CSTRING and _WTL_NO_CSTRING are defined #endif //defined(_WTL_USE_CSTRING) && defined(_WTL_NO_CSTRING) #if !defined(_WTL_USE_CSTRING) && !defined(_WTL_NO_CSTRING) #define _WTL_USE_CSTRING #endif //!defined(_WTL_USE_CSTRING) && !defined(_WTL_NO_CSTRING) #ifndef _WTL_NO_CSTRING #if defined(_ATL_USE_CSTRING_FLOAT) && defined(_ATL_MIN_CRT) #error Cannot use CString floating point formatting with _ATL_MIN_CRT defined #endif //defined(_ATL_USE_CSTRING_FLOAT) && defined(_ATL_MIN_CRT) #ifndef _DEBUG #include <stdio.h> #endif //!_DEBUG #endif //!_WTL_NO_CSTRING /////////////////////////////////////////////////////////////////////////////// // Classes in this file: // // CSize // CPoint // CRect // CString // // CRecentDocumentListBase<T, t_cchItemLen, t_nFirstID, t_nLastID> // CRecentDocumentList // CFindFile // // Global functions: // AtlLoadAccelerators() // AtlLoadMenu() // AtlLoadBitmap() // AtlLoadSysBitmap() // AtlLoadCursor() // AtlLoadSysCursor() // AtlLoadIcon() // AtlLoadSysIcon() // AtlLoadBitmapImage() // AtlLoadCursorImage() // AtlLoadIconImage() // AtlLoadSysBitmapImage() // AtlLoadSysCursorImage() // AtlLoadSysIconImage() // AtlLoadString() // // AtlGetStockPen() // AtlGetStockBrush() // AtlGetStockFont() // AtlGetStockPalette() // // AtlCompactPath() namespace WTL { #ifndef _WTL_NO_WTYPES // forward declarations class CSize; class CPoint; class CRect; /////////////////////////////////////////////////////////////////////////////// // CSize - Wrapper for Windows SIZE structure. class CSize : public tagSIZE { public: // Constructors CSize(); CSize(int initCX, int initCY); CSize(SIZE initSize); CSize(POINT initPt); CSize(DWORD dwSize); // Operations BOOL operator ==(SIZE size) const; BOOL operator !=(SIZE size) const; void operator +=(SIZE size); void operator -=(SIZE size); void SetSize(int CX, int CY); // Operators returning CSize values CSize operator +(SIZE size) const; CSize operator -(SIZE size) const; CSize operator -() const; // Operators returning CPoint values CPoint operator +(POINT point) const; CPoint operator -(POINT point) const; // Operators returning CRect values CRect operator +(const RECT* lpRect) const; CRect operator -(const RECT* lpRect) const; }; /////////////////////////////////////////////////////////////////////////////// // CPoint - Wrapper for Windows POINT structure. class CPoint : public tagPOINT { public: // Constructors CPoint(); CPoint(int initX, int initY); CPoint(POINT initPt); CPoint(SIZE initSize); CPoint(DWORD dwPoint); // Operations void Offset(int xOffset, int yOffset); void Offset(POINT point); void Offset(SIZE size); BOOL operator ==(POINT point) const; BOOL operator !=(POINT point) const; void operator +=(SIZE size); void operator -=(SIZE size); void operator +=(POINT point); void operator -=(POINT point); void SetPoint(int X, int Y); // Operators returning CPoint values CPoint operator +(SIZE size) const; CPoint operator -(SIZE size) const; CPoint operator -() const; CPoint operator +(POINT point) const; // Operators returning CSize values CSize operator -(POINT point) const; // Operators returning CRect values CRect operator +(const RECT* lpRect) const; CRect operator -(const RECT* lpRect) const; }; /////////////////////////////////////////////////////////////////////////////// // CRect - Wrapper for Windows RECT structure. class CRect : public tagRECT { public: // Constructors CRect(); CRect(int l, int t, int r, int b); CRect(const RECT& srcRect); CRect(LPCRECT lpSrcRect); CRect(POINT point, SIZE size); CRect(POINT topLeft, POINT bottomRight); // Attributes (in addition to RECT members) int Width() const; int Height() const; CSize Size() const; CPoint& TopLeft(); CPoint& BottomRight(); const CPoint& TopLeft() const; const CPoint& BottomRight() const; CPoint CenterPoint() const; // convert between CRect and LPRECT/LPCRECT (no need for &) operator LPRECT(); operator LPCRECT() const; BOOL IsRectEmpty() const; BOOL IsRectNull() const; BOOL PtInRect(POINT point) const; // Operations void SetRect(int x1, int y1, int x2, int y2); void SetRect(POINT topLeft, POINT bottomRight); void SetRectEmpty(); void CopyRect(LPCRECT lpSrcRect); BOOL EqualRect(LPCRECT lpRect) const; void InflateRect(int x, int y); void InflateRect(SIZE size); void InflateRect(LPCRECT lpRect); void InflateRect(int l, int t, int r, int b); void DeflateRect(int x, int y); void DeflateRect(SIZE size); void DeflateRect(LPCRECT lpRect); void DeflateRect(int l, int t, int r, int b); void OffsetRect(int x, int y); void OffsetRect(SIZE size); void OffsetRect(POINT point); void NormalizeRect(); // absolute position of rectangle void MoveToY(int y); void MoveToX(int x); void MoveToXY(int x, int y); void MoveToXY(POINT point); // operations that fill '*this' with result BOOL IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2); BOOL UnionRect(LPCRECT lpRect1, LPCRECT lpRect2); BOOL SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2); // Additional Operations void operator =(const RECT& srcRect); BOOL operator ==(const RECT& rect) const; BOOL operator !=(const RECT& rect) const; void operator +=(POINT point); void operator +=(SIZE size); void operator +=(LPCRECT lpRect); void operator -=(POINT point); void operator -=(SIZE size); void operator -=(LPCRECT lpRect); void operator &=(const RECT& rect); void operator |=(const RECT& rect); // Operators returning CRect values CRect operator +(POINT point) const; CRect operator -(POINT point) const; CRect operator +(LPCRECT lpRect) const; CRect operator +(SIZE size) const; CRect operator -(SIZE size) const; CRect operator -(LPCRECT lpRect) const; CRect operator &(const RECT& rect2) const; CRect operator |(const RECT& rect2) const; CRect MulDiv(int nMultiplier, int nDivisor) const; }; /////////////////////////////////////////////////////////////////////////////// // CSize, CPoint, CRect Implementation // CSize inline CSize::CSize() { /* random filled */ } inline CSize::CSize(int initCX, int initCY) { cx = initCX; cy = initCY; } inline CSize::CSize(SIZE initSize) { *(SIZE*)this = initSize; } inline CSize::CSize(POINT initPt) { *(POINT*)this = initPt; } inline CSize::CSize(DWORD dwSize) { cx = (short)LOWORD(dwSize); cy = (short)HIWORD(dwSize); } inline BOOL CSize::operator ==(SIZE size) const { return (cx == size.cx && cy == size.cy); } inline BOOL CSize::operator !=(SIZE size) const { return (cx != size.cx || cy != size.cy); } inline void CSize::operator +=(SIZE size) { cx += size.cx; cy += size.cy; } inline void CSize::operator -=(SIZE size) { cx -= size.cx; cy -= size.cy; } inline void CSize::SetSize(int CX, int CY) { cx = CX; cy = CY; } inline CSize CSize::operator +(SIZE size) const { return CSize(cx + size.cx, cy + size.cy); } inline CSize CSize::operator -(SIZE size) const { return CSize(cx - size.cx, cy - size.cy); } inline CSize CSize::operator -() const { return CSize(-cx, -cy); } inline CPoint CSize::operator +(POINT point) const { return CPoint(cx + point.x, cy + point.y); } inline CPoint CSize::operator -(POINT point) const { return CPoint(cx - point.x, cy - point.y); } inline CRect CSize::operator +(const RECT* lpRect) const { return CRect(lpRect) + *this; } inline CRect CSize::operator -(const RECT* lpRect) const { return CRect(lpRect) - *this; } // CPoint inline CPoint::CPoint() { /* random filled */ } inline CPoint::CPoint(int initX, int initY) { x = initX; y = initY; } inline CPoint::CPoint(POINT initPt) { *(POINT*)this = initPt; } inline CPoint::CPoint(SIZE initSize) { *(SIZE*)this = initSize; } inline CPoint::CPoint(DWORD dwPoint) { x = (short)LOWORD(dwPoint); y = (short)HIWORD(dwPoint); } inline void CPoint::Offset(int xOffset, int yOffset) { x += xOffset; y += yOffset; } inline void CPoint::Offset(POINT point) { x += point.x; y += point.y; } inline void CPoint::Offset(SIZE size) { x += size.cx; y += size.cy; } inline BOOL CPoint::operator ==(POINT point) const { return (x == point.x && y == point.y); } inline BOOL CPoint::operator !=(POINT point) const { return (x != point.x || y != point.y); } inline void CPoint::operator +=(SIZE size) { x += size.cx; y += size.cy; } inline void CPoint::operator -=(SIZE size) { x -= size.cx; y -= size.cy; } inline void CPoint::operator +=(POINT point) { x += point.x; y += point.y; } inline void CPoint::operator -=(POINT point) { x -= point.x; y -= point.y; } inline void CPoint::SetPoint(int X, int Y) { x = X; y = Y; } inline CPoint CPoint::operator +(SIZE size) const { return CPoint(x + size.cx, y + size.cy); } inline CPoint CPoint::operator -(SIZE size) const { return CPoint(x - size.cx, y - size.cy); } inline CPoint CPoint::operator -() const { return CPoint(-x, -y); } inline CPoint CPoint::operator +(POINT point) const { return CPoint(x + point.x, y + point.y); } inline CSize CPoint::operator -(POINT point) const { return CSize(x - point.x, y - point.y); } inline CRect CPoint::operator +(const RECT* lpRect) const { return CRect(lpRect) + *this; } inline CRect CPoint::operator -(const RECT* lpRect) const { return CRect(lpRect) - *this; } // CRect inline CRect::CRect() { /* random filled */ } inline CRect::CRect(int l, int t, int r, int b) { left = l; top = t; right = r; bottom = b; } inline CRect::CRect(const RECT& srcRect) { ::CopyRect(this, &srcRect); } inline CRect::CRect(LPCRECT lpSrcRect) { ::CopyRect(this, lpSrcRect); } inline CRect::CRect(POINT point, SIZE size) { right = (left = point.x) + size.cx; bottom = (top = point.y) + size.cy; } inline CRect::CRect(POINT topLeft, POINT bottomRight) { left = topLeft.x; top = topLeft.y; right = bottomRight.x; bottom = bottomRight.y; } inline int CRect::Width() const { return right - left; } inline int CRect::Height() const { return bottom - top; } inline CSize CRect::Size() const { return CSize(right - left, bottom - top); } inline CPoint& CRect::TopLeft() { return *((CPoint*)this); } inline CPoint& CRect::BottomRight() { return *((CPoint*)this + 1); } inline const CPoint& CRect::TopLeft() const { return *((CPoint*)this); } inline const CPoint& CRect::BottomRight() const { return *((CPoint*)this + 1); } inline CPoint CRect::CenterPoint() const { return CPoint((left + right) / 2, (top + bottom) / 2); } inline CRect::operator LPRECT() { return this; } inline CRect::operator LPCRECT() const { return this; } inline BOOL CRect::IsRectEmpty() const { return ::IsRectEmpty(this); } inline BOOL CRect::IsRectNull() const { return (left == 0 && right == 0 && top == 0 && bottom == 0); } inline BOOL CRect::PtInRect(POINT point) const { return ::PtInRect(this, point); } inline void CRect::SetRect(int x1, int y1, int x2, int y2) { ::SetRect(this, x1, y1, x2, y2); } inline void CRect::SetRect(POINT topLeft, POINT bottomRight) { ::SetRect(this, topLeft.x, topLeft.y, bottomRight.x, bottomRight.y); } inline void CRect::SetRectEmpty() { ::SetRectEmpty(this); } inline void CRect::CopyRect(LPCRECT lpSrcRect) { ::CopyRect(this, lpSrcRect); } inline BOOL CRect::EqualRect(LPCRECT lpRect) const { return ::EqualRect(this, lpRect); } inline void CRect::InflateRect(int x, int y) { ::InflateRect(this, x, y); } inline void CRect::InflateRect(SIZE size) { ::InflateRect(this, size.cx, size.cy); } inline void CRect::DeflateRect(int x, int y) { ::InflateRect(this, -x, -y); } inline void CRect::DeflateRect(SIZE size) { ::InflateRect(this, -size.cx, -size.cy); } inline void CRect::OffsetRect(int x, int y) { ::OffsetRect(this, x, y); } inline void CRect::OffsetRect(POINT point) { ::OffsetRect(this, point.x, point.y); } inline void CRect::OffsetRect(SIZE size) { ::OffsetRect(this, size.cx, size.cy); } inline BOOL CRect::IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2) { return ::IntersectRect(this, lpRect1, lpRect2);} inline BOOL CRect::UnionRect(LPCRECT lpRect1, LPCRECT lpRect2) { return ::UnionRect(this, lpRect1, lpRect2); } inline void CRect::operator =(const RECT& srcRect) { ::CopyRect(this, &srcRect); } inline BOOL CRect::operator ==(const RECT& rect) const { return ::EqualRect(this, &rect); } inline BOOL CRect::operator !=(const RECT& rect) const { return !::EqualRect(this, &rect); } inline void CRect::operator +=(POINT point) { ::OffsetRect(this, point.x, point.y); } inline void CRect::operator +=(SIZE size) { ::OffsetRect(this, size.cx, size.cy); } inline void CRect::operator +=(LPCRECT lpRect) { InflateRect(lpRect); } inline void CRect::operator -=(POINT point) { ::OffsetRect(this, -point.x, -point.y); } inline void CRect::operator -=(SIZE size) { ::OffsetRect(this, -size.cx, -size.cy); } inline void CRect::operator -=(LPCRECT lpRect) { DeflateRect(lpRect); } inline void CRect::operator &=(const RECT& rect) { ::IntersectRect(this, this, &rect); } inline void CRect::operator |=(const RECT& rect) { ::UnionRect(this, this, &rect); } inline CRect CRect::operator +(POINT pt) const { CRect rect(*this); ::OffsetRect(&rect, pt.x, pt.y); return rect; } inline CRect CRect::operator -(POINT pt) const { CRect rect(*this); ::OffsetRect(&rect, -pt.x, -pt.y); return rect; } inline CRect CRect::operator +(SIZE size) const { CRect rect(*this); ::OffsetRect(&rect, size.cx, size.cy); return rect; } inline CRect CRect::operator -(SIZE size) const { CRect rect(*this); ::OffsetRect(&rect, -size.cx, -size.cy); return rect; } inline CRect CRect::operator +(LPCRECT lpRect) const { CRect rect(this); rect.InflateRect(lpRect); return rect; } inline CRect CRect::operator -(LPCRECT lpRect) const { CRect rect(this); rect.DeflateRect(lpRect); return rect; } inline CRect CRect::operator &(const RECT& rect2) const { CRect rect; ::IntersectRect(&rect, this, &rect2); return rect; } inline CRect CRect::operator |(const RECT& rect2) const { CRect rect; ::UnionRect(&rect, this, &rect2); return rect; } inline BOOL CRect::SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2) { return ::SubtractRect(this, lpRectSrc1, lpRectSrc2); } inline void CRect::NormalizeRect() { int nTemp; if (left > right) { nTemp = left; left = right; right = nTemp; } if (top > bottom) { nTemp = top; top = bottom; bottom = nTemp; } } inline void CRect::MoveToY(int y) { bottom = Height() + y; top = y; } inline void CRect::MoveToX(int x) { right = Width() + x; left = x; } inline void CRect::MoveToXY(int x, int y) { MoveToX(x); MoveToY(y); } inline void CRect::MoveToXY(POINT pt) { MoveToX(pt.x); MoveToY(pt.y); } inline void CRect::InflateRect(LPCRECT lpRect) { left -= lpRect->left; top -= lpRect->top; right += lpRect->right; bottom += lpRect->bottom; } inline void CRect::InflateRect(int l, int t, int r, int b) { left -= l; top -= t; right += r; bottom += b; } inline void CRect::DeflateRect(LPCRECT lpRect) { left += lpRect->left; top += lpRect->top; right -= lpRect->right; bottom -= lpRect->bottom; } inline void CRect::DeflateRect(int l, int t, int r, int b) { left += l; top += t; right -= r; bottom -= b; } inline CRect CRect::MulDiv(int nMultiplier, int nDivisor) const { return CRect( ::MulDiv(left, nMultiplier, nDivisor), ::MulDiv(top, nMultiplier, nDivisor), ::MulDiv(right, nMultiplier, nDivisor), ::MulDiv(bottom, nMultiplier, nDivisor)); } #endif //!_WTL_NO_WTYPES /////////////////////////////////////////////////////////////////////////////// // CString - String class #ifndef _WTL_NO_CSTRING struct CStringData { long nRefs; // reference count int nDataLength; int nAllocLength; // TCHAR data[nAllocLength] TCHAR* data() { return (TCHAR*)(this + 1); } }; // Globals // For an empty string, m_pchData will point here // (note: avoids special case of checking for NULL m_pchData) // empty string data (and locked) _declspec(selectany) int rgInitData[] = { -1, 0, 0, 0 }; _declspec(selectany) CStringData* _atltmpDataNil = (CStringData*)&rgInitData; _declspec(selectany) LPCTSTR _atltmpPchNil = (LPCTSTR)(((BYTE*)&rgInitData) + sizeof(CStringData)); class CString { public: // Constructors CString(); CString(const CString& stringSrc); CString(TCHAR ch, int nRepeat = 1); CString(LPCSTR lpsz); CString(LPCWSTR lpsz); CString(LPCSTR lpch, int nLength); CString(LPCWSTR lpch, int nLength); CString(const unsigned char* psz); // Attributes & Operations // as an array of characters int GetLength() const; BOOL IsEmpty() const; void Empty(); // free up the data TCHAR GetAt(int nIndex) const; // 0 based TCHAR operator [](int nIndex) const; // same as GetAt void SetAt(int nIndex, TCHAR ch); operator LPCTSTR() const; // as a C string // overloaded assignment const CString& operator =(const CString& stringSrc); const CString& operator =(TCHAR ch); #ifdef _UNICODE const CString& operator =(char ch); #endif const CString& operator =(LPCSTR lpsz); const CString& operator =(LPCWSTR lpsz); const CString& operator =(const unsigned char* psz); // string concatenation const CString& operator +=(const CString& string); const CString& operator +=(TCHAR ch); #ifdef _UNICODE const CString& operator +=(char ch); #endif const CString& operator +=(LPCTSTR lpsz); friend CString __stdcall operator +(const CString& string1, const CString& string2); friend CString __stdcall operator +(const CString& string, TCHAR ch); friend CString __stdcall operator +(TCHAR ch, const CString& string); #ifdef _UNICODE friend CString __stdcall operator +(const CString& string, char ch); friend CString __stdcall operator +(char ch, const CString& string); #endif friend CString __stdcall operator +(const CString& string, LPCTSTR lpsz); friend CString __stdcall operator +(LPCTSTR lpsz, const CString& string); // string comparison int Compare(LPCTSTR lpsz) const; // straight character int CompareNoCase(LPCTSTR lpsz) const; // ignore case int Collate(LPCTSTR lpsz) const; // NLS aware int CollateNoCase(LPCTSTR lpsz) const; // ignore case // simple sub-string extraction CString Mid(int nFirst, int nCount) const; CString Mid(int nFirst) const; CString Left(int nCount) const; CString Right(int nCount) const; CString SpanIncluding(LPCTSTR lpszCharSet) const; CString SpanExcluding(LPCTSTR lpszCharSet) const; // upper/lower/reverse conversion void MakeUpper(); void MakeLower(); void MakeReverse(); // trimming whitespace (either side) void TrimRight(); void TrimLeft(); // remove continuous occurrences of chTarget starting from right void TrimRight(TCHAR chTarget); // remove continuous occcurrences of characters in passed string, // starting from right void TrimRight(LPCTSTR lpszTargets); // remove continuous occurrences of chTarget starting from left void TrimLeft(TCHAR chTarget); // remove continuous occcurrences of characters in // passed string, starting from left void TrimLeft(LPCTSTR lpszTargets); // advanced manipulation // replace occurrences of chOld with chNew int Replace(TCHAR chOld, TCHAR chNew); // replace occurrences of substring lpszOld with lpszNew; // empty lpszNew removes instances of lpszOld int Replace(LPCTSTR lpszOld, LPCTSTR lpszNew); // remove occurrences of chRemove int Remove(TCHAR chRemove); // insert character at zero-based index; concatenates // if index is past end of string int Insert(int nIndex, TCHAR ch); // insert substring at zero-based index; concatenates // if index is past end of string int Insert(int nIndex, LPCTSTR pstr); // delete nCount characters starting at zero-based index int Delete(int nIndex, int nCount = 1); // searching (return starting index, or -1 if not found) // look for a single character match int Find(TCHAR ch) const; // like "C" strchr int ReverseFind(TCHAR ch) const; int Find(TCHAR ch, int nStart) const; // starting at index int FindOneOf(LPCTSTR lpszCharSet) const; // look for a specific sub-string int Find(LPCTSTR lpszSub) const; // like "C" strstr int Find(LPCTSTR lpszSub, int nStart) const; // starting at index // Concatentation for non strings const CString& Append(int n) { const int cchBuff = 12; TCHAR szBuffer[cchBuff]; wsprintf(szBuffer,_T("%d"),n); ConcatInPlace(SafeStrlen(szBuffer), szBuffer); return *this; } // simple formatting BOOL __cdecl Format(LPCTSTR lpszFormat, ...); BOOL __cdecl Format(UINT nFormatID, ...); BOOL FormatV(LPCTSTR lpszFormat, va_list argList); // formatting for localization (uses FormatMessage API) BOOL __cdecl FormatMessage(LPCTSTR lpszFormat, ...); BOOL __cdecl FormatMessage(UINT nFormatID, ...); // Windows support BOOL LoadString(UINT nID); // load from string resource (255 chars max.) #ifndef _UNICODE // ANSI <-> OEM support (convert string in place) void AnsiToOem(); void OemToAnsi(); #endif #ifndef _ATL_NO_COM // OLE BSTR support (use for OLE automation) BSTR AllocSysString() const; BSTR SetSysString(BSTR* pbstr) const; #endif //!_ATL_NO_COM // Access to string implementation buffer as "C" character array LPTSTR GetBuffer(int nMinBufLength); void ReleaseBuffer(int nNewLength = -1); LPTSTR GetBufferSetLength(int nNewLength); void FreeExtra(); // Use LockBuffer/UnlockBuffer to turn refcounting off LPTSTR LockBuffer(); void UnlockBuffer(); // Implementation public: ~CString(); int GetAllocLength() const; static BOOL __stdcall _IsValidString(LPCWSTR lpsz, int nLength = -1) { if(lpsz == NULL) return FALSE; #ifndef _WIN32_WCE return !::IsBadStringPtrW(lpsz, nLength); #else // CE specific nLength; return TRUE; #endif //_WIN32_WCE } static BOOL __stdcall _IsValidString(LPCSTR lpsz, int nLength = -1) { if(lpsz == NULL) return FALSE; #ifndef _WIN32_WCE return !::IsBadStringPtrA(lpsz, nLength); #else // CE specific nLength; return TRUE; #endif //_WIN32_WCE } protected: LPTSTR m_pchData; // pointer to ref counted string data // implementation helpers CStringData* GetData() const; void Init(); void AllocCopy(CString& dest, int nCopyLen, int nCopyIndex, int nExtraLen) const; BOOL AllocBuffer(int nLen); void AssignCopy(int nSrcLen, LPCTSTR lpszSrcData); BOOL ConcatCopy(int nSrc1Len, LPCTSTR lpszSrc1Data, int nSrc2Len, LPCTSTR lpszSrc2Data); void ConcatInPlace(int nSrcLen, LPCTSTR lpszSrcData); void CopyBeforeWrite(); BOOL AllocBeforeWrite(int nLen); void Release(); static void PASCAL Release(CStringData* pData); static int PASCAL SafeStrlen(LPCTSTR lpsz); static int __stdcall _LoadString(UINT nID, LPTSTR lpszBuf, UINT nMaxBuf) { #ifdef _DEBUG // LoadString without annoying warning from the Debug kernel if the // segment containing the string is not present #if (_ATL_VER >= 0x0700) if (::FindResource(ATL::_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE((nID>>4) + 1), RT_STRING) == NULL) #else //!(_ATL_VER >= 0x0700) if (::FindResource(_Module.GetResourceInstance(), MAKEINTRESOURCE((nID>>4) + 1), RT_STRING) == NULL) #endif //!(_ATL_VER >= 0x0700) { lpszBuf[0] = '\0'; return 0; // not found } #endif //_DEBUG #if (_ATL_VER >= 0x0700) int nLen = ::LoadString(ATL::_AtlBaseModule.GetResourceInstance(), nID, lpszBuf, nMaxBuf); #else //!(_ATL_VER >= 0x0700) int nLen = ::LoadString(_Module.GetResourceInstance(), nID, lpszBuf, nMaxBuf); #endif //!(_ATL_VER >= 0x0700) if (nLen == 0) lpszBuf[0] = '\0'; return nLen; } static const CString& __stdcall _GetEmptyString() { return *(CString*)&_atltmpPchNil; } // CString conversion helpers static int __cdecl _wcstombsz(char* mbstr, const wchar_t* wcstr, size_t count) { if (count == 0 && mbstr != NULL) return 0; int result = ::WideCharToMultiByte(CP_ACP, 0, wcstr, -1, mbstr, (int)count, NULL, NULL); ATLASSERT(mbstr == NULL || result <= (int)count); if (result > 0) mbstr[result - 1] = 0; return result; } static int __cdecl _mbstowcsz(wchar_t* wcstr, const char* mbstr, size_t count) { if (count == 0 && wcstr != NULL) return 0; int result = ::MultiByteToWideChar(CP_ACP, 0, mbstr, -1, wcstr, (int)count); ATLASSERT(wcstr == NULL || result <= (int)count); if (result > 0) wcstr[result - 1] = 0; return result; } // Helpers to avoid CRT startup code #ifdef _ATL_MIN_CRT static TCHAR* _cstrchr(const TCHAR* p, TCHAR ch) { //strchr for '\0' should succeed while (*p != 0) { if (*p == ch) break; p = ::CharNext(p); } return (TCHAR*)((*p == ch) ? p : NULL); } static TCHAR* _cstrrchr(const TCHAR* p, TCHAR ch) { const TCHAR* lpsz = NULL; while (*p != 0) { if (*p == ch) lpsz = p; p = ::CharNext(p); } return (TCHAR*)lpsz; } static TCHAR* _cstrrev(TCHAR* pStr) { // Optimize NULL, zero-length, and single-char case. if ((pStr == NULL) || (pStr[0] == '\0') || (pStr[1] == '\0')) return pStr; TCHAR* p = pStr; while (*p != 0) { TCHAR* pNext = ::CharNext(p); if(pNext > p + 1) { char p1 = *(char*)p; *(char*)p = *(char*)(p + 1); *(char*)(p + 1) = p1; } p = pNext; } p--; TCHAR* q = pStr; while (q < p) { TCHAR t = *q; *q = *p; *p = t; q++; p--; } return (TCHAR*)pStr; } static TCHAR* _cstrstr(const TCHAR* pStr, const TCHAR* pCharSet) { int nLen = lstrlen(pCharSet); if (nLen == 0) return (TCHAR*)pStr; const TCHAR* pRet = NULL; const TCHAR* pCur = pStr; while((pCur = _cstrchr(pCur, *pCharSet)) != NULL) { if(memcmp(pCur, pCharSet, nLen * sizeof(TCHAR)) == 0) { pRet = pCur; break; } pCur = ::CharNext(pCur); } return (TCHAR*) pRet; } static int _cstrspn(const TCHAR* pStr, const TCHAR* pCharSet) { int nRet = 0; TCHAR* p = (TCHAR*)pStr; while (*p != 0) { TCHAR* pNext = ::CharNext(p); if(pNext > p + 1) { if(_cstrchr_db(pCharSet, *p, *(p + 1)) == NULL) break; nRet += 2; } else { if(_cstrchr(pCharSet, *p) == NULL) break; nRet++; } p = pNext; } return nRet; } static int _cstrcspn(const TCHAR* pStr, const TCHAR* pCharSet) { int nRet = 0; TCHAR* p = (TCHAR*)pStr; while (*p != 0) { TCHAR* pNext = ::CharNext(p); if(pNext > p + 1) { if(_cstrchr_db(pCharSet, *p, *(p + 1)) != NULL) break; nRet += 2; } else { if(_cstrchr(pCharSet, *p) != NULL) break; nRet++; } p = pNext; } return nRet; } static TCHAR* _cstrpbrk(const TCHAR* p, const TCHAR* lpszCharSet) { int n = _cstrcspn(p, lpszCharSet); return (p[n] != 0) ? (TCHAR*)&p[n] : NULL; } static int _cstrisdigit(TCHAR ch) { WORD type; GetStringTypeEx(GetThreadLocale(), CT_CTYPE1, &ch, 1, &type); return (type & C1_DIGIT) == C1_DIGIT; } static int _cstrisspace(TCHAR ch) { WORD type; GetStringTypeEx(GetThreadLocale(), CT_CTYPE1, &ch, 1, &type); return (type & C1_SPACE) == C1_SPACE; } static int _cstrcmp(const TCHAR* pstrOne, const TCHAR* pstrOther) { return lstrcmp(pstrOne, pstrOther); } static int _cstrcmpi(const TCHAR* pstrOne, const TCHAR* pstrOther) { return lstrcmpi(pstrOne, pstrOther); } static int _cstrcoll(const TCHAR* pstrOne, const TCHAR* pstrOther) { int nRet = CompareString(GetThreadLocale(), 0, pstrOne, -1, pstrOther, -1); ATLASSERT(nRet != 0); return nRet - 2; // Convert to strcmp convention. This really is documented. } static int _cstrcolli(const TCHAR* pstrOne, const TCHAR* pstrOther) { int nRet = CompareString(GetThreadLocale(), NORM_IGNORECASE, pstrOne, -1, pstrOther, -1); ATLASSERT(nRet != 0); return nRet - 2; // Convert to strcmp convention. This really is documented. } static int _cstrtoi(const TCHAR* nptr) { int c; /* current char */ int total; /* current total */ int sign; /* if '-', then negative, otherwise positive */ while ( _cstrisspace(*nptr) ) ++nptr; c = (int)(_TUCHAR)*nptr++; sign = c; /* save sign indication */ if (c == _T('-') || c == _T('+')) c = (int)(_TUCHAR)*nptr++; /* skip sign */ total = 0; while (_cstrisdigit((TCHAR)c)) { total = 10 * total + (c - '0'); /* accumulate digit */ c = (int)(_TUCHAR)*nptr++; /* get next char */ } if (sign == '-') return -total; else return total; /* return result, negated if necessary */ } #else //!_ATL_MIN_CRT static TCHAR* _cstrchr(const TCHAR* p, TCHAR ch) { return _tcschr(p, ch); } static TCHAR* _cstrrchr(const TCHAR* p, TCHAR ch) { return _tcsrchr(p, ch); } static TCHAR* _cstrrev(TCHAR* pStr) { return _tcsrev(pStr); } static TCHAR* _cstrstr(const TCHAR* pStr, const TCHAR* pCharSet) { return _tcsstr(pStr, pCharSet); } static int _cstrspn(const TCHAR* pStr, const TCHAR* pCharSet) { return (int)_tcsspn(pStr, pCharSet); } static int _cstrcspn(const TCHAR* pStr, const TCHAR* pCharSet) { return (int)_tcscspn(pStr, pCharSet); } static TCHAR* _cstrpbrk(const TCHAR* p, const TCHAR* lpszCharSet) { return _tcspbrk(p, lpszCharSet); } static int _cstrisdigit(TCHAR ch) { return _istdigit(ch); } static int _cstrisspace(TCHAR ch) { return _istspace((_TUCHAR)ch); } static int _cstrcmp(const TCHAR* pstrOne, const TCHAR* pstrOther) { return _tcscmp(pstrOne, pstrOther); } static int _cstrcmpi(const TCHAR* pstrOne, const TCHAR* pstrOther) { return _tcsicmp(pstrOne, pstrOther); } #ifndef _WIN32_WCE static int _cstrcoll(const TCHAR* pstrOne, const TCHAR* pstrOther) { return _tcscoll(pstrOne, pstrOther); } static int _cstrcolli(const TCHAR* pstrOne, const TCHAR* pstrOther) { return _tcsicoll(pstrOne, pstrOther); } #endif //!_WIN32_WCE static int _cstrtoi(const TCHAR* nptr) { return _ttoi(nptr); } #endif //!_ATL_MIN_CRT static TCHAR* _cstrchr_db(const TCHAR* p, TCHAR ch1, TCHAR ch2) { const TCHAR* lpsz = NULL; while (*p != 0) { if (*p == ch1 && *(p + 1) == ch2) { lpsz = p; break; } p = ::CharNext(p); } return (TCHAR*)lpsz; } }; // Compare helpers bool __stdcall operator ==(const CString& s1, const CString& s2); bool __stdcall operator ==(const CString& s1, LPCTSTR s2); bool __stdcall operator ==(LPCTSTR s1, const CString& s2); bool __stdcall operator !=(const CString& s1, const CString& s2); bool __stdcall operator !=(const CString& s1, LPCTSTR s2); bool __stdcall operator !=(LPCTSTR s1, const CString& s2); bool __stdcall operator <(const CString& s1, const CString& s2); bool __stdcall operator <(const CString& s1, LPCTSTR s2); bool __stdcall operator <(LPCTSTR s1, const CString& s2); bool __stdcall operator >(const CString& s1, const CString& s2); bool __stdcall operator >(const CString& s1, LPCTSTR s2); bool __stdcall operator >(LPCTSTR s1, const CString& s2); bool __stdcall operator <=(const CString& s1, const CString& s2); bool __stdcall operator <=(const CString& s1, LPCTSTR s2); bool __stdcall operator <=(LPCTSTR s1, const CString& s2); bool __stdcall operator >=(const CString& s1, const CString& s2); bool __stdcall operator >=(const CString& s1, LPCTSTR s2); bool __stdcall operator >=(LPCTSTR s1, const CString& s2); /////////////////////////////////////////////////////////////////////////////// // CString Implementation inline CStringData* CString::GetData() const { ATLASSERT(m_pchData != NULL); return ((CStringData*)m_pchData) - 1; } inline void CString::Init() { m_pchData = _GetEmptyString().m_pchData; } inline CString::CString(const unsigned char* lpsz) { Init(); *this = (LPCSTR)lpsz; } inline const CString& CString::operator =(const unsigned char* lpsz) { *this = (LPCSTR)lpsz; return *this; } #ifdef _UNICODE inline const CString& CString::operator +=(char ch) { *this += (TCHAR)ch; return *this; } inline const CString& CString::operator =(char ch) { *this = (TCHAR)ch; return *this; } inline CString __stdcall operator +(const CString& string, char ch) { return string + (TCHAR)ch; } inline CString __stdcall operator +(char ch, const CString& string) { return (TCHAR)ch + string; } #endif //_UNICODE inline int CString::GetLength() const { return GetData()->nDataLength; } inline int CString::GetAllocLength() const { return GetData()->nAllocLength; } inline BOOL CString::IsEmpty() const { return GetData()->nDataLength == 0; } inline CString::operator LPCTSTR() const { return m_pchData; } inline int PASCAL CString::SafeStrlen(LPCTSTR lpsz) { return (lpsz == NULL) ? 0 : lstrlen(lpsz); } // CString support (windows specific) inline int CString::Compare(LPCTSTR lpsz) const { return _cstrcmp(m_pchData, lpsz); } // MBCS/Unicode aware inline int CString::CompareNoCase(LPCTSTR lpsz) const { return _cstrcmpi(m_pchData, lpsz); } // MBCS/Unicode aware // CString::Collate is often slower than Compare but is MBSC/Unicode // aware as well as locale-sensitive with respect to sort order. #ifndef _WIN32_WCE inline int CString::Collate(LPCTSTR lpsz) const { return _cstrcoll(m_pchData, lpsz); } // locale sensitive inline int CString::CollateNoCase(LPCTSTR lpsz) const { return _cstrcolli(m_pchData, lpsz); } // locale sensitive #endif //!_WIN32_WCE inline TCHAR CString::GetAt(int nIndex) const { ATLASSERT(nIndex >= 0); ATLASSERT(nIndex < GetData()->nDataLength); return m_pchData[nIndex]; } inline TCHAR CString::operator [](int nIndex) const { // same as GetAt ATLASSERT(nIndex >= 0); ATLASSERT(nIndex < GetData()->nDataLength); return m_pchData[nIndex]; } inline bool __stdcall operator ==(const CString& s1, const CString& s2) { return s1.Compare(s2) == 0; } inline bool __stdcall operator ==(const CString& s1, LPCTSTR s2) { return s1.Compare(s2) == 0; } inline bool __stdcall operator ==(LPCTSTR s1, const CString& s2) { return s2.Compare(s1) == 0; } inline bool __stdcall operator !=(const CString& s1, const CString& s2) { return s1.Compare(s2) != 0; } inline bool __stdcall operator !=(const CString& s1, LPCTSTR s2) { return s1.Compare(s2) != 0; } inline bool __stdcall operator !=(LPCTSTR s1, const CString& s2) { return s2.Compare(s1) != 0; } inline bool __stdcall operator <(const CString& s1, const CString& s2) { return s1.Compare(s2) < 0; } inline bool __stdcall operator <(const CString& s1, LPCTSTR s2) { return s1.Compare(s2) < 0; } inline bool __stdcall operator <(LPCTSTR s1, const CString& s2) { return s2.Compare(s1) > 0; } inline bool __stdcall operator >(const CString& s1, const CString& s2) { return s1.Compare(s2) > 0; } inline bool __stdcall operator >(const CString& s1, LPCTSTR s2) { return s1.Compare(s2) > 0; } inline bool __stdcall operator >(LPCTSTR s1, const CString& s2) { return s2.Compare(s1) < 0; } inline bool __stdcall operator <=(const CString& s1, const CString& s2) { return s1.Compare(s2) <= 0; } inline bool __stdcall operator <=(const CString& s1, LPCTSTR s2) { return s1.Compare(s2) <= 0; } inline bool __stdcall operator <=(LPCTSTR s1, const CString& s2) { return s2.Compare(s1) >= 0; } inline bool __stdcall operator >=(const CString& s1, const CString& s2) { return s1.Compare(s2) >= 0; } inline bool __stdcall operator >=(const CString& s1, LPCTSTR s2) { return s1.Compare(s2) >= 0; } inline bool __stdcall operator >=(LPCTSTR s1, const CString& s2) { return s2.Compare(s1) <= 0; } inline CString::CString() { Init(); } inline CString::CString(const CString& stringSrc) { ATLASSERT(stringSrc.GetData()->nRefs != 0); if (stringSrc.GetData()->nRefs >= 0) { ATLASSERT(stringSrc.GetData() != _atltmpDataNil); m_pchData = stringSrc.m_pchData; InterlockedIncrement(&GetData()->nRefs); } else { Init(); *this = stringSrc.m_pchData; } } inline BOOL CString::AllocBuffer(int nLen) // always allocate one extra character for '\0' termination // assumes [optimistically] that data length will equal allocation length { ATLASSERT(nLen >= 0); ATLASSERT(nLen <= INT_MAX - 1); // max size (enough room for 1 extra) if (nLen == 0) { Init(); } else { CStringData* pData = NULL; ATLTRY(pData = (CStringData*)new BYTE[sizeof(CStringData) + (nLen + 1) * sizeof(TCHAR)]); if(pData == NULL) return FALSE; pData->nRefs = 1; pData->data()[nLen] = '\0'; pData->nDataLength = nLen; pData->nAllocLength = nLen; m_pchData = pData->data(); } return TRUE; } inline void CString::Release() { if (GetData() != _atltmpDataNil) { ATLASSERT(GetData()->nRefs != 0); if (InterlockedDecrement(&GetData()->nRefs) <= 0) delete[] (BYTE*)GetData(); Init(); } } inline void PASCAL CString::Release(CStringData* pData) { if (pData != _atltmpDataNil) { ATLASSERT(pData->nRefs != 0); if (InterlockedDecrement(&pData->nRefs) <= 0) delete[] (BYTE*)pData; } } inline void CString::Empty() { if (GetData()->nDataLength == 0) return; if (GetData()->nRefs >= 0) Release(); else *this = _T(""); ATLASSERT(GetData()->nDataLength == 0); ATLASSERT(GetData()->nRefs < 0 || GetData()->nAllocLength == 0); } inline void CString::CopyBeforeWrite() { if (GetData()->nRefs > 1) { CStringData* pData = GetData(); Release(); if(AllocBuffer(pData->nDataLength)) memcpy(m_pchData, pData->data(), (pData->nDataLength + 1) * sizeof(TCHAR)); } ATLASSERT(GetData()->nRefs <= 1); } inline BOOL CString::AllocBeforeWrite(int nLen) { BOOL bRet = TRUE; if (GetData()->nRefs > 1 || nLen > GetData()->nAllocLength) { Release(); bRet = AllocBuffer(nLen); } ATLASSERT(GetData()->nRefs <= 1); return bRet; } inline CString::~CString() // free any attached data { if (GetData() != _atltmpDataNil) { if (InterlockedDecrement(&GetData()->nRefs) <= 0) delete[] (BYTE*)GetData(); } } inline void CString::AllocCopy(CString& dest, int nCopyLen, int nCopyIndex, int nExtraLen) const { // will clone the data attached to this string // allocating 'nExtraLen' characters // Places results in uninitialized string 'dest' // Will copy the part or all of original data to start of new string int nNewLen = nCopyLen + nExtraLen; if (nNewLen == 0) { dest.Init(); } else { if(dest.AllocBuffer(nNewLen)) memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen * sizeof(TCHAR)); } } inline CString::CString(LPCTSTR lpsz) { Init(); if (lpsz != NULL && HIWORD(lpsz) == NULL) { UINT nID = LOWORD((DWORD_PTR)lpsz); if (!LoadString(nID)) ATLTRACE2(atlTraceUI, 0, _T("Warning: implicit LoadString(%u) in CString failed\n"), nID); } else { int nLen = SafeStrlen(lpsz); if (nLen != 0) { if(AllocBuffer(nLen)) memcpy(m_pchData, lpsz, nLen * sizeof(TCHAR)); } } } #ifdef _UNICODE inline CString::CString(LPCSTR lpsz) { Init(); int nSrcLen = (lpsz != NULL) ? lstrlenA(lpsz) : 0; if (nSrcLen != 0) { if(AllocBuffer(nSrcLen)) { _mbstowcsz(m_pchData, lpsz, nSrcLen + 1); ReleaseBuffer(); } } } #else //_UNICODE inline CString::CString(LPCWSTR lpsz) { Init(); int nSrcLen = (lpsz != NULL) ? (int)wcslen(lpsz) : 0; if (nSrcLen != 0) { if(AllocBuffer(nSrcLen * 2)) { _wcstombsz(m_pchData, lpsz, (nSrcLen * 2) + 1); ReleaseBuffer(); } } } #endif //!_UNICODE // Assignment operators // All assign a new value to the string // (a) first see if the buffer is big enough // (b) if enough room, copy on top of old buffer, set size and type // (c) otherwise free old string data, and create a new one // // All routines return the new string (but as a 'const CString&' so that // assigning it again will cause a copy, eg: s1 = s2 = "hi there". // inline void CString::AssignCopy(int nSrcLen, LPCTSTR lpszSrcData) { if(AllocBeforeWrite(nSrcLen)) { memcpy(m_pchData, lpszSrcData, nSrcLen * sizeof(TCHAR)); GetData()->nDataLength = nSrcLen; m_pchData[nSrcLen] = '\0'; } } inline const CString& CString::operator =(const CString& stringSrc) { if (m_pchData != stringSrc.m_pchData) { if ((GetData()->nRefs < 0 && GetData() != _atltmpDataNil) || stringSrc.GetData()->nRefs < 0) { // actual copy necessary since one of the strings is locked AssignCopy(stringSrc.GetData()->nDataLength, stringSrc.m_pchData); } else { // can just copy references around Release(); ATLASSERT(stringSrc.GetData() != _atltmpDataNil); m_pchData = stringSrc.m_pchData; InterlockedIncrement(&GetData()->nRefs); } } return *this; } inline const CString& CString::operator =(LPCTSTR lpsz) { ATLASSERT(lpsz == NULL || _IsValidString(lpsz)); AssignCopy(SafeStrlen(lpsz), lpsz); return *this; } #ifdef _UNICODE inline const CString& CString::operator =(LPCSTR lpsz) { int nSrcLen = (lpsz != NULL) ? lstrlenA(lpsz) : 0; if(AllocBeforeWrite(nSrcLen)) { _mbstowcsz(m_pchData, lpsz, nSrcLen + 1); ReleaseBuffer(); } return *this; } #else //!_UNICODE inline const CString& CString::operator =(LPCWSTR lpsz) { int nSrcLen = (lpsz != NULL) ? (int)wcslen(lpsz) : 0; if(AllocBeforeWrite(nSrcLen * 2)) { _wcstombsz(m_pchData, lpsz, (nSrcLen * 2) + 1); ReleaseBuffer(); } return *this; } #endif //!_UNICODE // Concatenation // NOTE: "operator +" is done as friend functions for simplicity // There are three variants: // CString + CString // and for ? = TCHAR, LPCTSTR // CString + ? // ? + CString inline BOOL CString::ConcatCopy(int nSrc1Len, LPCTSTR lpszSrc1Data, int nSrc2Len, LPCTSTR lpszSrc2Data) { // -- master concatenation routine // Concatenate two sources // -- assume that 'this' is a new CString object BOOL bRet = TRUE; int nNewLen = nSrc1Len + nSrc2Len; if (nNewLen != 0) { bRet = AllocBuffer(nNewLen); if (bRet) { memcpy(m_pchData, lpszSrc1Data, nSrc1Len * sizeof(TCHAR)); memcpy(m_pchData + nSrc1Len, lpszSrc2Data, nSrc2Len * sizeof(TCHAR)); } } return bRet; } inline CString __stdcall operator +(const CString& string1, const CString& string2) { CString s; s.ConcatCopy(string1.GetData()->nDataLength, string1.m_pchData, string2.GetData()->nDataLength, string2.m_pchData); return s; } inline CString __stdcall operator +(const CString& string, LPCTSTR lpsz) { ATLASSERT(lpsz == NULL || CString::_IsValidString(lpsz)); CString s; s.ConcatCopy(string.GetData()->nDataLength, string.m_pchData, CString::SafeStrlen(lpsz), lpsz); return s; } inline CString __stdcall operator +(LPCTSTR lpsz, const CString& string) { ATLASSERT(lpsz == NULL || CString::_IsValidString(lpsz)); CString s; s.ConcatCopy(CString::SafeStrlen(lpsz), lpsz, string.GetData()->nDataLength, string.m_pchData); return s; } inline void CString::ConcatInPlace(int nSrcLen, LPCTSTR lpszSrcData) { // -- the main routine for += operators // concatenating an empty string is a no-op! if (nSrcLen == 0) return; // if the buffer is too small, or we have a width mis-match, just // allocate a new buffer (slow but sure) if (GetData()->nRefs > 1 || GetData()->nDataLength + nSrcLen > GetData()->nAllocLength) { // we have to grow the buffer, use the ConcatCopy routine CStringData* pOldData = GetData(); if (ConcatCopy(GetData()->nDataLength, m_pchData, nSrcLen, lpszSrcData)) { ATLASSERT(pOldData != NULL); CString::Release(pOldData); } } else { // fast concatenation when buffer big enough memcpy(m_pchData + GetData()->nDataLength, lpszSrcData, nSrcLen * sizeof(TCHAR)); GetData()->nDataLength += nSrcLen; ATLASSERT(GetData()->nDataLength <= GetData()->nAllocLength); m_pchData[GetData()->nDataLength] = '\0'; } } inline const CString& CString::operator +=(LPCTSTR lpsz) { ATLASSERT(lpsz == NULL || _IsValidString(lpsz)); ConcatInPlace(SafeStrlen(lpsz), lpsz); return *this; } inline const CString& CString::operator +=(TCHAR ch) { ConcatInPlace(1, &ch); return *this; } inline const CString& CString::operator +=(const CString& string) { ConcatInPlace(string.GetData()->nDataLength, string.m_pchData); return *this; } inline LPTSTR CString::GetBuffer(int nMinBufLength) { ATLASSERT(nMinBufLength >= 0); if (GetData()->nRefs > 1 || nMinBufLength > GetData()->nAllocLength) { // we have to grow the buffer CStringData* pOldData = GetData(); int nOldLen = GetData()->nDataLength; // AllocBuffer will tromp it if (nMinBufLength < nOldLen) nMinBufLength = nOldLen; if(!AllocBuffer(nMinBufLength)) return NULL; memcpy(m_pchData, pOldData->data(), (nOldLen + 1) * sizeof(TCHAR)); GetData()->nDataLength = nOldLen; CString::Release(pOldData); } ATLASSERT(GetData()->nRefs <= 1); // return a pointer to the character storage for this string ATLASSERT(m_pchData != NULL); return m_pchData; } inline void CString::ReleaseBuffer(int nNewLength) { CopyBeforeWrite(); // just in case GetBuffer was not called if (nNewLength == -1) nNewLength = lstrlen(m_pchData); // zero terminated ATLASSERT(nNewLength <= GetData()->nAllocLength); GetData()->nDataLength = nNewLength; m_pchData[nNewLength] = '\0'; } inline LPTSTR CString::GetBufferSetLength(int nNewLength) { ATLASSERT(nNewLength >= 0); if(GetBuffer(nNewLength) == NULL) return NULL; GetData()->nDataLength = nNewLength; m_pchData[nNewLength] = '\0'; return m_pchData; } inline void CString::FreeExtra() { ATLASSERT(GetData()->nDataLength <= GetData()->nAllocLength); if (GetData()->nDataLength != GetData()->nAllocLength) { CStringData* pOldData = GetData(); if(AllocBuffer(GetData()->nDataLength)) { memcpy(m_pchData, pOldData->data(), pOldData->nDataLength * sizeof(TCHAR)); ATLASSERT(m_pchData[GetData()->nDataLength] == '\0'); CString::Release(pOldData); } } ATLASSERT(GetData() != NULL); } inline LPTSTR CString::LockBuffer() { LPTSTR lpsz = GetBuffer(0); if(lpsz != NULL) GetData()->nRefs = -1; return lpsz; } inline void CString::UnlockBuffer() { ATLASSERT(GetData()->nRefs == -1); if (GetData() != _atltmpDataNil) GetData()->nRefs = 1; } inline int CString::Find(TCHAR ch) const { return Find(ch, 0); } inline int CString::Find(TCHAR ch, int nStart) const { int nLength = GetData()->nDataLength; if (nStart >= nLength) return -1; // find first single character LPTSTR lpsz = _cstrchr(m_pchData + nStart, (_TUCHAR)ch); // return -1 if not found and index otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } inline int CString::FindOneOf(LPCTSTR lpszCharSet) const { ATLASSERT(_IsValidString(lpszCharSet)); LPTSTR lpsz = _cstrpbrk(m_pchData, lpszCharSet); return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } inline void CString::MakeUpper() { CopyBeforeWrite(); CharUpper(m_pchData); } inline void CString::MakeLower() { CopyBeforeWrite(); CharLower(m_pchData); } inline void CString::MakeReverse() { CopyBeforeWrite(); _cstrrev(m_pchData); } inline void CString::SetAt(int nIndex, TCHAR ch) { ATLASSERT(nIndex >= 0); ATLASSERT(nIndex < GetData()->nDataLength); CopyBeforeWrite(); m_pchData[nIndex] = ch; } #ifndef _UNICODE inline void CString::AnsiToOem() { CopyBeforeWrite(); ::AnsiToOem(m_pchData, m_pchData); } inline void CString::OemToAnsi() { CopyBeforeWrite(); ::OemToAnsi(m_pchData, m_pchData); } #endif //_UNICODE inline CString::CString(TCHAR ch, int nLength) { ATLASSERT(!_istlead(ch)); // can't create a lead byte string Init(); if (nLength >= 1) { if(AllocBuffer(nLength)) { #ifdef _UNICODE for (int i = 0; i < nLength; i++) m_pchData[i] = ch; #else memset(m_pchData, ch, nLength); #endif } } } inline CString::CString(LPCTSTR lpch, int nLength) { Init(); if (nLength != 0) { if(AllocBuffer(nLength)) memcpy(m_pchData, lpch, nLength * sizeof(TCHAR)); } } #ifdef _UNICODE inline CString::CString(LPCSTR lpsz, int nLength) { Init(); if (nLength != 0) { if(AllocBuffer(nLength)) { int n = ::MultiByteToWideChar(CP_ACP, 0, lpsz, nLength, m_pchData, nLength + 1); ReleaseBuffer((n >= 0) ? n : -1); } } } #else //_UNICODE inline CString::CString(LPCWSTR lpsz, int nLength) { Init(); if (nLength != 0) { if(AllocBuffer(nLength * 2)) { int n = ::WideCharToMultiByte(CP_ACP, 0, lpsz, nLength, m_pchData, (nLength * 2) + 1, NULL, NULL); ReleaseBuffer((n >= 0) ? n : -1); } } } #endif //!_UNICODE inline const CString& CString::operator =(TCHAR ch) { ATLASSERT(!_istlead(ch)); // can't set single lead byte AssignCopy(1, &ch); return *this; } inline CString __stdcall operator +(const CString& string1, TCHAR ch) { CString s; s.ConcatCopy(string1.GetData()->nDataLength, string1.m_pchData, 1, &ch); return s; } inline CString __stdcall operator +(TCHAR ch, const CString& string) { CString s; s.ConcatCopy(1, &ch, string.GetData()->nDataLength, string.m_pchData); return s; } inline CString CString::Mid(int nFirst) const { return Mid(nFirst, GetData()->nDataLength - nFirst); } inline CString CString::Mid(int nFirst, int nCount) const { // out-of-bounds requests return sensible things if (nFirst < 0) nFirst = 0; if (nCount < 0) nCount = 0; if (nFirst + nCount > GetData()->nDataLength) nCount = GetData()->nDataLength - nFirst; if (nFirst > GetData()->nDataLength) nCount = 0; CString dest; AllocCopy(dest, nCount, nFirst, 0); return dest; } inline CString CString::Right(int nCount) const { if (nCount < 0) nCount = 0; else if (nCount > GetData()->nDataLength) nCount = GetData()->nDataLength; CString dest; AllocCopy(dest, nCount, GetData()->nDataLength-nCount, 0); return dest; } inline CString CString::Left(int nCount) const { if (nCount < 0) nCount = 0; else if (nCount > GetData()->nDataLength) nCount = GetData()->nDataLength; CString dest; AllocCopy(dest, nCount, 0, 0); return dest; } // strspn equivalent inline CString CString::SpanIncluding(LPCTSTR lpszCharSet) const { ATLASSERT(_IsValidString(lpszCharSet)); return Left(_cstrspn(m_pchData, lpszCharSet)); } // strcspn equivalent inline CString CString::SpanExcluding(LPCTSTR lpszCharSet) const { ATLASSERT(_IsValidString(lpszCharSet)); return Left(_cstrcspn(m_pchData, lpszCharSet)); } inline int CString::ReverseFind(TCHAR ch) const { // find last single character LPTSTR lpsz = _cstrrchr(m_pchData, (_TUCHAR)ch); // return -1 if not found, distance from beginning otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } // find a sub-string (like strstr) inline int CString::Find(LPCTSTR lpszSub) const { return Find(lpszSub, 0); } inline int CString::Find(LPCTSTR lpszSub, int nStart) const { ATLASSERT(_IsValidString(lpszSub)); int nLength = GetData()->nDataLength; if (nStart > nLength) return -1; // find first matching substring LPTSTR lpsz = _cstrstr(m_pchData + nStart, lpszSub); // return -1 for not found, distance from beginning otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } inline BOOL CString::FormatV(LPCTSTR lpszFormat, va_list argList) { ATLASSERT(_IsValidString(lpszFormat)); enum _FormatModifiers { FORCE_ANSI = 0x10000, FORCE_UNICODE = 0x20000, FORCE_INT64 = 0x40000 }; va_list argListSave = argList; // make a guess at the maximum length of the resulting string int nMaxLen = 0; for (LPCTSTR lpsz = lpszFormat; *lpsz != '\0'; lpsz = ::CharNext(lpsz)) { // handle '%' character, but watch out for '%%' if (*lpsz != '%' || *(lpsz = ::CharNext(lpsz)) == '%') { // this is instead of _tclen() #if !defined(_UNICODE) && defined(_MBCS) nMaxLen += (int)(::CharNext(lpsz) - lpsz); #else nMaxLen++; #endif continue; } int nItemLen = 0; // handle '%' character with format int nWidth = 0; for (; *lpsz != '\0'; lpsz = ::CharNext(lpsz)) { // check for valid flags if (*lpsz == '#') nMaxLen += 2; // for '0x' else if (*lpsz == '*') nWidth = va_arg(argList, int); else if (*lpsz == '-' || *lpsz == '+' || *lpsz == '0' || *lpsz == ' ') ; else // hit non-flag character break; } // get width and skip it if (nWidth == 0) { // width indicated by nWidth = _cstrtoi(lpsz); for (; *lpsz != '\0' && _cstrisdigit(*lpsz); lpsz = ::CharNext(lpsz)) ; } ATLASSERT(nWidth >= 0); int nPrecision = 0; if (*lpsz == '.') { // skip past '.' separator (width.precision) lpsz = ::CharNext(lpsz); // get precision and skip it if (*lpsz == '*') { nPrecision = va_arg(argList, int); lpsz = ::CharNext(lpsz); } else { nPrecision = _cstrtoi(lpsz); for (; *lpsz != '\0' && _cstrisdigit(*lpsz); lpsz = ::CharNext(lpsz)) ; } ATLASSERT(nPrecision >= 0); } // should be on type modifier or specifier int nModifier = 0; if(lpsz[0] == _T('I') && lpsz[1] == _T('6') && lpsz[2] == _T('4')) { lpsz += 3; nModifier = FORCE_INT64; } else { switch (*lpsz) { // modifiers that affect size case 'h': nModifier = FORCE_ANSI; lpsz = ::CharNext(lpsz); break; case 'l': nModifier = FORCE_UNICODE; lpsz = ::CharNext(lpsz); break; // modifiers that do not affect size case 'F': case 'N': case 'L': lpsz = ::CharNext(lpsz); break; } } // now should be on specifier switch (*lpsz | nModifier) { // single characters case 'c': case 'C': nItemLen = 2; va_arg(argList, TCHAR); break; case 'c' | FORCE_ANSI: case 'C' | FORCE_ANSI: nItemLen = 2; va_arg(argList, char); break; case 'c' | FORCE_UNICODE: case 'C' | FORCE_UNICODE: nItemLen = 2; va_arg(argList, WCHAR); break; // strings case 's': { LPCTSTR pstrNextArg = va_arg(argList, LPCTSTR); if (pstrNextArg == NULL) { nItemLen = 6; // "(null)" } else { nItemLen = lstrlen(pstrNextArg); nItemLen = max(1, nItemLen); } break; } case 'S': { #ifndef _UNICODE LPWSTR pstrNextArg = va_arg(argList, LPWSTR); if (pstrNextArg == NULL) { nItemLen = 6; // "(null)" } else { nItemLen = (int)wcslen(pstrNextArg); nItemLen = max(1, nItemLen); } #else //_UNICODE LPCSTR pstrNextArg = va_arg(argList, LPCSTR); if (pstrNextArg == NULL) { nItemLen = 6; // "(null)" } else { nItemLen = lstrlenA(pstrNextArg); nItemLen = max(1, nItemLen); } #endif //_UNICODE break; } case 's' | FORCE_ANSI: case 'S' | FORCE_ANSI: { LPCSTR pstrNextArg = va_arg(argList, LPCSTR); if (pstrNextArg == NULL) { nItemLen = 6; // "(null)" } else { nItemLen = lstrlenA(pstrNextArg); nItemLen = max(1, nItemLen); } break; } case 's' | FORCE_UNICODE: case 'S' | FORCE_UNICODE: { LPWSTR pstrNextArg = va_arg(argList, LPWSTR); if (pstrNextArg == NULL) { nItemLen = 6; // "(null)" } else { nItemLen = (int)wcslen(pstrNextArg); nItemLen = max(1, nItemLen); } break; } } // adjust nItemLen for strings if (nItemLen != 0) { nItemLen = max(nItemLen, nWidth); if (nPrecision != 0) nItemLen = min(nItemLen, nPrecision); } else { switch (*lpsz) { // integers case 'd': case 'i': case 'u': case 'x': case 'X': case 'o': if (nModifier & FORCE_INT64) va_arg(argList, __int64); else va_arg(argList, int); nItemLen = 32; nItemLen = max(nItemLen, nWidth + nPrecision); break; #ifndef _ATL_USE_CSTRING_FLOAT case 'e': case 'E': case 'f': case 'g': case 'G': ATLASSERT(!"Floating point (%%e, %%E, %%f, %%g, and %%G) is not supported by the WTL::CString class."); #ifndef _DEBUG ::OutputDebugString(_T("Floating point (%%e, %%f, %%g, and %%G) is not supported by the WTL::CString class.")); #ifndef _WIN32_WCE ::DebugBreak(); #else // CE specific DebugBreak(); #endif //_WIN32_WCE #endif //!_DEBUG break; #else //_ATL_USE_CSTRING_FLOAT case 'e': case 'E': case 'g': case 'G': va_arg(argList, double); nItemLen = 128; nItemLen = max(nItemLen, nWidth + nPrecision); break; case 'f': { double f; LPTSTR pszTemp; // 312 == strlen("-1+(309 zeroes).") // 309 zeroes == max precision of a double // 6 == adjustment in case precision is not specified, // which means that the precision defaults to 6 pszTemp = (LPTSTR)_alloca(max(nWidth, 312 + nPrecision + 6)); f = va_arg(argList, double); _stprintf(pszTemp, _T( "%*.*f" ), nWidth, nPrecision + 6, f); nItemLen = _tcslen(pszTemp); } break; #endif //_ATL_USE_CSTRING_FLOAT case 'p': va_arg(argList, void*); nItemLen = 32; nItemLen = max(nItemLen, nWidth + nPrecision); break; // no output case 'n': va_arg(argList, int*); break; default: ATLASSERT(FALSE); // unknown formatting option } } // adjust nMaxLen for output nItemLen nMaxLen += nItemLen; } if(GetBuffer(nMaxLen) == NULL) return FALSE; #ifndef _ATL_USE_CSTRING_FLOAT int nRet = wvsprintf(m_pchData, lpszFormat, argListSave); #else //_ATL_USE_CSTRING_FLOAT int nRet = _vstprintf(m_pchData, lpszFormat, argListSave); #endif //_ATL_USE_CSTRING_FLOAT nRet; // ref ATLASSERT(nRet <= GetAllocLength()); ReleaseBuffer(); va_end(argListSave); return TRUE; } // formatting (using wsprintf style formatting) inline BOOL __cdecl CString::Format(LPCTSTR lpszFormat, ...) { ATLASSERT(_IsValidString(lpszFormat)); va_list argList; va_start(argList, lpszFormat); BOOL bRet = FormatV(lpszFormat, argList); va_end(argList); return bRet; } inline BOOL __cdecl CString::Format(UINT nFormatID, ...) { CString strFormat; BOOL bRet = strFormat.LoadString(nFormatID); ATLASSERT(bRet != 0); va_list argList; va_start(argList, nFormatID); bRet = FormatV(strFormat, argList); va_end(argList); return bRet; } // formatting (using FormatMessage style formatting) inline BOOL __cdecl CString::FormatMessage(LPCTSTR lpszFormat, ...) { // format message into temporary buffer lpszTemp va_list argList; va_start(argList, lpszFormat); LPTSTR lpszTemp; BOOL bRet = TRUE; if (::FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER, lpszFormat, 0, 0, (LPTSTR)&lpszTemp, 0, &argList) == 0 || lpszTemp == NULL) bRet = FALSE; // assign lpszTemp into the resulting string and free the temporary *this = lpszTemp; LocalFree(lpszTemp); va_end(argList); return bRet; } inline BOOL __cdecl CString::FormatMessage(UINT nFormatID, ...) { // get format string from string table CString strFormat; BOOL bRetTmp = strFormat.LoadString(nFormatID); bRetTmp; // ref ATLASSERT(bRetTmp != 0); // format message into temporary buffer lpszTemp va_list argList; va_start(argList, nFormatID); LPTSTR lpszTemp; BOOL bRet = TRUE; if (::FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER, strFormat, 0, 0, (LPTSTR)&lpszTemp, 0, &argList) == 0 || lpszTemp == NULL) bRet = FALSE; // assign lpszTemp into the resulting string and free lpszTemp *this = lpszTemp; LocalFree(lpszTemp); va_end(argList); return bRet; } inline void CString::TrimRight() { CopyBeforeWrite(); // find beginning of trailing spaces by starting at beginning (DBCS aware) LPTSTR lpsz = m_pchData; LPTSTR lpszLast = NULL; while (*lpsz != '\0') { if (_cstrisspace(*lpsz)) { if (lpszLast == NULL) lpszLast = lpsz; } else { lpszLast = NULL; } lpsz = ::CharNext(lpsz); } if (lpszLast != NULL) { // truncate at trailing space start *lpszLast = '\0'; GetData()->nDataLength = (int)(DWORD_PTR)(lpszLast - m_pchData); } } inline void CString::TrimLeft() { CopyBeforeWrite(); // find first non-space character LPCTSTR lpsz = m_pchData; while (_cstrisspace(*lpsz)) lpsz = ::CharNext(lpsz); // fix up data and length int nDataLength = GetData()->nDataLength - (int)(DWORD_PTR)(lpsz - m_pchData); memmove(m_pchData, lpsz, (nDataLength + 1) * sizeof(TCHAR)); GetData()->nDataLength = nDataLength; } inline void CString::TrimRight(LPCTSTR lpszTargetList) { // find beginning of trailing matches // by starting at beginning (DBCS aware) CopyBeforeWrite(); LPTSTR lpsz = m_pchData; LPTSTR lpszLast = NULL; while (*lpsz != '\0') { TCHAR* pNext = ::CharNext(lpsz); if(pNext > lpsz + 1) { if (_cstrchr_db(lpszTargetList, *lpsz, *(lpsz + 1)) != NULL) { if (lpszLast == NULL) lpszLast = lpsz; } else { lpszLast = NULL; } } else { if (_cstrchr(lpszTargetList, *lpsz) != NULL) { if (lpszLast == NULL) lpszLast = lpsz; } else { lpszLast = NULL; } } lpsz = pNext; } if (lpszLast != NULL) { // truncate at left-most matching character *lpszLast = '\0'; GetData()->nDataLength = (int)(DWORD_PTR)(lpszLast - m_pchData); } } inline void CString::TrimRight(TCHAR chTarget) { // find beginning of trailing matches // by starting at beginning (DBCS aware) CopyBeforeWrite(); LPTSTR lpsz = m_pchData; LPTSTR lpszLast = NULL; while (*lpsz != '\0') { if (*lpsz == chTarget) { if (lpszLast == NULL) lpszLast = lpsz; } else lpszLast = NULL; lpsz = ::CharNext(lpsz); } if (lpszLast != NULL) { // truncate at left-most matching character *lpszLast = '\0'; GetData()->nDataLength = (int)(DWORD_PTR)(lpszLast - m_pchData); } } inline void CString::TrimLeft(LPCTSTR lpszTargets) { // if we're not trimming anything, we're not doing any work if (SafeStrlen(lpszTargets) == 0) return; CopyBeforeWrite(); LPCTSTR lpsz = m_pchData; while (*lpsz != '\0') { TCHAR* pNext = ::CharNext(lpsz); if(pNext > lpsz + 1) { if (_cstrchr_db(lpszTargets, *lpsz, *(lpsz + 1)) == NULL) break; } else { if (_cstrchr(lpszTargets, *lpsz) == NULL) break; } lpsz = pNext; } if (lpsz != m_pchData) { // fix up data and length int nDataLength = GetData()->nDataLength - (int)(DWORD_PTR)(lpsz - m_pchData); memmove(m_pchData, lpsz, (nDataLength + 1) * sizeof(TCHAR)); GetData()->nDataLength = nDataLength; } } inline void CString::TrimLeft(TCHAR chTarget) { // find first non-matching character CopyBeforeWrite(); LPCTSTR lpsz = m_pchData; while (chTarget == *lpsz) lpsz = ::CharNext(lpsz); if (lpsz != m_pchData) { // fix up data and length int nDataLength = GetData()->nDataLength - (int)(DWORD_PTR)(lpsz - m_pchData); memmove(m_pchData, lpsz, (nDataLength + 1) * sizeof(TCHAR)); GetData()->nDataLength = nDataLength; } } inline int CString::Delete(int nIndex, int nCount /* = 1 */) { if (nIndex < 0) nIndex = 0; int nLength = GetData()->nDataLength; if (nCount > 0 && nIndex < nLength) { if((nIndex + nCount) > nLength) nCount = nLength - nIndex; CopyBeforeWrite(); int nBytesToCopy = nLength - (nIndex + nCount) + 1; memmove(m_pchData + nIndex, m_pchData + nIndex + nCount, nBytesToCopy * sizeof(TCHAR)); nLength -= nCount; GetData()->nDataLength = nLength; } return nLength; } inline int CString::Insert(int nIndex, TCHAR ch) { CopyBeforeWrite(); if (nIndex < 0) nIndex = 0; int nNewLength = GetData()->nDataLength; if (nIndex > nNewLength) nIndex = nNewLength; nNewLength++; if (GetData()->nAllocLength < nNewLength) { CStringData* pOldData = GetData(); LPTSTR pstr = m_pchData; if(!AllocBuffer(nNewLength)) return -1; memcpy(m_pchData, pstr, (pOldData->nDataLength + 1) * sizeof(TCHAR)); CString::Release(pOldData); } // move existing bytes down memmove(m_pchData + nIndex + 1, m_pchData + nIndex, (nNewLength - nIndex) * sizeof(TCHAR)); m_pchData[nIndex] = ch; GetData()->nDataLength = nNewLength; return nNewLength; } inline int CString::Insert(int nIndex, LPCTSTR pstr) { if (nIndex < 0) nIndex = 0; int nInsertLength = SafeStrlen(pstr); int nNewLength = GetData()->nDataLength; if (nInsertLength > 0) { CopyBeforeWrite(); if (nIndex > nNewLength) nIndex = nNewLength; nNewLength += nInsertLength; if (GetData()->nAllocLength < nNewLength) { CStringData* pOldData = GetData(); LPTSTR pstr = m_pchData; if(!AllocBuffer(nNewLength)) return -1; memcpy(m_pchData, pstr, (pOldData->nDataLength + 1) * sizeof(TCHAR)); CString::Release(pOldData); } // move existing bytes down memmove(m_pchData + nIndex + nInsertLength, m_pchData + nIndex, (nNewLength - nIndex - nInsertLength + 1) * sizeof(TCHAR)); memcpy(m_pchData + nIndex, pstr, nInsertLength * sizeof(TCHAR)); GetData()->nDataLength = nNewLength; } return nNewLength; } inline int CString::Replace(TCHAR chOld, TCHAR chNew) { int nCount = 0; // short-circuit the nop case if (chOld != chNew) { // otherwise modify each character that matches in the string CopyBeforeWrite(); LPTSTR psz = m_pchData; LPTSTR pszEnd = psz + GetData()->nDataLength; while (psz < pszEnd) { // replace instances of the specified character only if (*psz == chOld) { *psz = chNew; nCount++; } psz = ::CharNext(psz); } } return nCount; } inline int CString::Replace(LPCTSTR lpszOld, LPCTSTR lpszNew) { // can't have empty or NULL lpszOld int nSourceLen = SafeStrlen(lpszOld); if (nSourceLen == 0) return 0; int nReplacementLen = SafeStrlen(lpszNew); // loop once to figure out the size of the result string int nCount = 0; LPTSTR lpszStart = m_pchData; LPTSTR lpszEnd = m_pchData + GetData()->nDataLength; LPTSTR lpszTarget; while (lpszStart < lpszEnd) { while ((lpszTarget = _cstrstr(lpszStart, lpszOld)) != NULL) { nCount++; lpszStart = lpszTarget + nSourceLen; } lpszStart += lstrlen(lpszStart) + 1; } // if any changes were made, make them if (nCount > 0) { CopyBeforeWrite(); // if the buffer is too small, just // allocate a new buffer (slow but sure) int nOldLength = GetData()->nDataLength; int nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; if (GetData()->nAllocLength < nNewLength || GetData()->nRefs > 1) { CStringData* pOldData = GetData(); LPTSTR pstr = m_pchData; if(!AllocBuffer(nNewLength)) return -1; memcpy(m_pchData, pstr, pOldData->nDataLength * sizeof(TCHAR)); CString::Release(pOldData); } // else, we just do it in-place lpszStart = m_pchData; lpszEnd = m_pchData + GetData()->nDataLength; // loop again to actually do the work while (lpszStart < lpszEnd) { while ( (lpszTarget = _cstrstr(lpszStart, lpszOld)) != NULL) { int nBalance = nOldLength - ((int)(DWORD_PTR)(lpszTarget - m_pchData) + nSourceLen); memmove(lpszTarget + nReplacementLen, lpszTarget + nSourceLen, nBalance * sizeof(TCHAR)); memcpy(lpszTarget, lpszNew, nReplacementLen * sizeof(TCHAR)); lpszStart = lpszTarget + nReplacementLen; lpszStart[nBalance] = '\0'; nOldLength += (nReplacementLen - nSourceLen); } lpszStart += lstrlen(lpszStart) + 1; } ATLASSERT(m_pchData[nNewLength] == '\0'); GetData()->nDataLength = nNewLength; } return nCount; } inline int CString::Remove(TCHAR chRemove) { CopyBeforeWrite(); LPTSTR pstrSource = m_pchData; LPTSTR pstrDest = m_pchData; LPTSTR pstrEnd = m_pchData + GetData()->nDataLength; while (pstrSource < pstrEnd) { if (*pstrSource != chRemove) { *pstrDest = *pstrSource; pstrDest = ::CharNext(pstrDest); } pstrSource = ::CharNext(pstrSource); } *pstrDest = '\0'; int nCount = (int)(DWORD_PTR)(pstrSource - pstrDest); GetData()->nDataLength -= nCount; return nCount; } #ifdef _UNICODE #define CHAR_FUDGE 1 // one TCHAR unused is good enough #else #define CHAR_FUDGE 2 // two BYTES unused for case of DBC last char #endif inline BOOL CString::LoadString(UINT nID) { // try fixed buffer first (to avoid wasting space in the heap) TCHAR szTemp[256]; int nCount = sizeof(szTemp) / sizeof(szTemp[0]); int nLen = _LoadString(nID, szTemp, nCount); if (nCount - nLen > CHAR_FUDGE) { *this = szTemp; return (nLen > 0); } // try buffer size of 512, then larger size until entire string is retrieved int nSize = 256; do { nSize += 256; LPTSTR lpstr = GetBuffer(nSize - 1); if(lpstr == NULL) { nLen = 0; break; } nLen = _LoadString(nID, lpstr, nSize); } while (nSize - nLen <= CHAR_FUDGE); ReleaseBuffer(); return (nLen > 0); } #ifndef _ATL_NO_COM inline BSTR CString::AllocSysString() const { #if defined(_UNICODE) || defined(OLE2ANSI) BSTR bstr = ::SysAllocStringLen(m_pchData, GetData()->nDataLength); #else int nLen = MultiByteToWideChar(CP_ACP, 0, m_pchData, GetData()->nDataLength, NULL, NULL); BSTR bstr = ::SysAllocStringLen(NULL, nLen); if(bstr != NULL) MultiByteToWideChar(CP_ACP, 0, m_pchData, GetData()->nDataLength, bstr, nLen); #endif return bstr; } inline BSTR CString::SetSysString(BSTR* pbstr) const { #if defined(_UNICODE) || defined(OLE2ANSI) ::SysReAllocStringLen(pbstr, m_pchData, GetData()->nDataLength); #else int nLen = MultiByteToWideChar(CP_ACP, 0, m_pchData, GetData()->nDataLength, NULL, NULL); if(::SysReAllocStringLen(pbstr, NULL, nLen)) MultiByteToWideChar(CP_ACP, 0, m_pchData, GetData()->nDataLength, *pbstr, nLen); #endif ATLASSERT(*pbstr != NULL); return *pbstr; } #endif //!_ATL_NO_COM #endif //!_WTL_NO_CSTRING /////////////////////////////////////////////////////////////////////////////// // CRecentDocumentList - MRU List Support #ifndef _WIN32_WCE #ifndef _WTL_MRUEMPTY_TEXT #define _WTL_MRUEMPTY_TEXT _T("(empty)") #endif // forward declaration inline bool AtlCompactPath(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen); template <class T, int t_cchItemLen = MAX_PATH, int t_nFirstID = ID_FILE_MRU_FIRST, int t_nLastID = ID_FILE_MRU_LAST> class CRecentDocumentListBase { public: // Declarations struct _DocEntry { TCHAR szDocName[t_cchItemLen]; bool operator ==(const _DocEntry& de) const { return (lstrcmpi(szDocName, de.szDocName) == 0); } }; enum { m_nMaxEntries_Min = 2, m_nMaxEntries_Max = t_nLastID - t_nFirstID + 1, m_cchMaxItemLen_Min = 6, m_cchMaxItemLen_Max = t_cchItemLen }; // Data members ATL::CSimpleArray<_DocEntry> m_arrDocs; int m_nMaxEntries; // default is 4 HMENU m_hMenu; TCHAR m_szNoEntries[t_cchItemLen]; int m_cchMaxItemLen; // Constructor CRecentDocumentListBase() : m_hMenu(NULL), m_nMaxEntries(4), m_cchMaxItemLen(-1) { // These ASSERTs verify values of the template arguments ATLASSERT(t_cchItemLen > m_cchMaxItemLen_Min); ATLASSERT(m_nMaxEntries_Max > m_nMaxEntries_Min); } // Attributes HMENU GetMenuHandle() const { return m_hMenu; } void SetMenuHandle(HMENU hMenu) { ATLASSERT(hMenu == NULL || ::IsMenu(hMenu)); m_hMenu = hMenu; if(m_hMenu == NULL || (::GetMenuString(m_hMenu, t_nFirstID, m_szNoEntries, t_cchItemLen, MF_BYCOMMAND) == 0)) lstrcpy(m_szNoEntries, _WTL_MRUEMPTY_TEXT); } int GetMaxEntries() const { return m_nMaxEntries; } void SetMaxEntries(int nMaxEntries) { ATLASSERT(nMaxEntries >= m_nMaxEntries_Min && nMaxEntries <= m_nMaxEntries_Max); if(nMaxEntries < m_nMaxEntries_Min) nMaxEntries = m_nMaxEntries_Min; else if(nMaxEntries > m_nMaxEntries_Max) nMaxEntries = m_nMaxEntries_Max; m_nMaxEntries = nMaxEntries; } int GetMaxItemLength() const { return m_cchMaxItemLen; } void SetMaxItemLength(int cchMaxLen) { ATLASSERT((cchMaxLen >= m_cchMaxItemLen_Min && cchMaxLen <= m_cchMaxItemLen_Max) || cchMaxLen == -1); if(cchMaxLen != -1) { if(cchMaxLen < m_cchMaxItemLen_Min) cchMaxLen = m_cchMaxItemLen_Min; else if(cchMaxLen > m_cchMaxItemLen_Max) cchMaxLen = m_cchMaxItemLen_Max; } m_cchMaxItemLen = cchMaxLen; T* pT = static_cast<T*>(this); pT->UpdateMenu(); } // Operations BOOL AddToList(LPCTSTR lpstrDocName) { _DocEntry de; if(lstrcpy(de.szDocName, lpstrDocName) == NULL) return FALSE; for(int i = 0; i < m_arrDocs.GetSize(); i++) { if(lstrcmpi(m_arrDocs[i].szDocName, lpstrDocName) == 0) { m_arrDocs.RemoveAt(i); break; } } if(m_arrDocs.GetSize() == m_nMaxEntries) m_arrDocs.RemoveAt(0); BOOL bRet = m_arrDocs.Add(de); if(bRet) { T* pT = static_cast<T*>(this); bRet = pT->UpdateMenu(); } return bRet; } BOOL GetFromList(int nItemID, LPTSTR lpstrDocName) { int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1; if(nIndex < 0 || nIndex >= m_arrDocs.GetSize()) return FALSE; return (lstrcpy(lpstrDocName, m_arrDocs[nIndex].szDocName) != NULL); } #if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__) BOOL GetFromList(int nItemID, _CSTRING_NS::CString& strDocName) { int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1; if(nIndex < 0 || nIndex >= m_arrDocs.GetSize()) return FALSE; strDocName = m_arrDocs[nIndex].szDocName; return TRUE; } #endif //defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__) BOOL RemoveFromList(int nItemID) { int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1; BOOL bRet = m_arrDocs.RemoveAt(nIndex); if(bRet) { T* pT = static_cast<T*>(this); bRet = pT->UpdateMenu(); } return bRet; } BOOL MoveToTop(int nItemID) { int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1; if(nIndex < 0 || nIndex >= m_arrDocs.GetSize()) return FALSE; _DocEntry de; de = m_arrDocs[nIndex]; m_arrDocs.RemoveAt(nIndex); BOOL bRet = m_arrDocs.Add(de); if(bRet) { T* pT = static_cast<T*>(this); bRet = pT->UpdateMenu(); } return bRet; } BOOL ReadFromRegistry(LPCTSTR lpstrRegKey) { T* pT = static_cast<T*>(this); ATL::CRegKey rkParent; ATL::CRegKey rk; LONG lRet = rkParent.Open(HKEY_CURRENT_USER, lpstrRegKey); if(lRet != ERROR_SUCCESS) return FALSE; lRet = rk.Open(rkParent, pT->GetRegKeyName()); if(lRet != ERROR_SUCCESS) return FALSE; DWORD dwRet = 0; #if (_ATL_VER >= 0x0700) lRet = rk.QueryDWORDValue(_T("DocumentCount"), dwRet); #else lRet = rk.QueryValue(dwRet, _T("DocumentCount")); #endif if(lRet != ERROR_SUCCESS) return FALSE; SetMaxEntries(dwRet); m_arrDocs.RemoveAll(); TCHAR szRetString[t_cchItemLen] = { 0 }; _DocEntry de; for(int nItem = m_nMaxEntries; nItem > 0; nItem--) { const int cchBuff = 11; TCHAR szBuff[cchBuff] = { 0 }; wsprintf(szBuff, _T("Document%i"), nItem); #if (_ATL_VER >= 0x0700) ULONG ulCount = t_cchItemLen; lRet = rk.QueryStringValue(szBuff, szRetString, &ulCount); #else DWORD dwCount = t_cchItemLen * sizeof(TCHAR); lRet = rk.QueryValue(szRetString, szBuff, &dwCount); #endif if(lRet == ERROR_SUCCESS && (lstrcpy(de.szDocName, szRetString) != NULL)) m_arrDocs.Add(de); } rk.Close(); rkParent.Close(); return pT->UpdateMenu(); } BOOL WriteToRegistry(LPCTSTR lpstrRegKey) { T* pT = static_cast<T*>(this); pT; // avoid level 4 warning ATL::CRegKey rkParent; ATL::CRegKey rk; LONG lRet = rkParent.Create(HKEY_CURRENT_USER, lpstrRegKey); if(lRet != ERROR_SUCCESS) return FALSE; lRet = rk.Create(rkParent, pT->GetRegKeyName()); if(lRet != ERROR_SUCCESS) return FALSE; #if (_ATL_VER >= 0x0700) lRet = rk.SetDWORDValue(_T("DocumentCount"), m_nMaxEntries); #else lRet = rk.SetValue(m_nMaxEntries, _T("DocumentCount")); #endif ATLASSERT(lRet == ERROR_SUCCESS); // set new values int nItem; for(nItem = m_arrDocs.GetSize(); nItem > 0; nItem--) { const int cchBuff = 11; TCHAR szBuff[cchBuff] = { 0 }; wsprintf(szBuff, _T("Document%i"), nItem); TCHAR szDocName[t_cchItemLen] = { 0 }; GetFromList(t_nFirstID + nItem - 1, szDocName); #if (_ATL_VER >= 0x0700) lRet = rk.SetStringValue(szBuff, szDocName); #else lRet = rk.SetValue(szDocName, szBuff); #endif ATLASSERT(lRet == ERROR_SUCCESS); } // delete unused keys for(nItem = m_arrDocs.GetSize() + 1; nItem < m_nMaxEntries_Max; nItem++) { const int cchBuff = 11; TCHAR szBuff[cchBuff] = { 0 }; wsprintf(szBuff, _T("Document%i"), nItem); rk.DeleteValue(szBuff); } rk.Close(); rkParent.Close(); return TRUE; } // Implementation BOOL UpdateMenu() { if(m_hMenu == NULL) return FALSE; ATLASSERT(::IsMenu(m_hMenu)); int nItems = ::GetMenuItemCount(m_hMenu); int nInsertPoint; for(nInsertPoint = 0; nInsertPoint < nItems; nInsertPoint++) { CMenuItemInfo mi; mi.fMask = MIIM_ID; ::GetMenuItemInfo(m_hMenu, nInsertPoint, TRUE, &mi); if (mi.wID == t_nFirstID) break; } ATLASSERT(nInsertPoint < nItems && "You need a menu item with an ID = t_nFirstID"); int nItem; for(nItem = t_nFirstID; nItem < t_nFirstID + m_nMaxEntries; nItem++) { // keep the first one as an insertion point if (nItem != t_nFirstID) ::DeleteMenu(m_hMenu, nItem, MF_BYCOMMAND); } TCHAR szItemText[t_cchItemLen + 6] = { 0 }; // add space for &, 2 digits, and a space int nSize = m_arrDocs.GetSize(); nItem = 0; if(nSize > 0) { for(nItem = 0; nItem < nSize; nItem++) { if(m_cchMaxItemLen == -1) { wsprintf(szItemText, _T("&%i %s"), nItem + 1, m_arrDocs[nSize - 1 - nItem].szDocName); } else { TCHAR szBuff[t_cchItemLen] = { 0 }; T* pT = static_cast<T*>(this); pT; // avoid level 4 warning bool bRet = pT->CompactDocumentName(szBuff, m_arrDocs[nSize - 1 - nItem].szDocName, m_cchMaxItemLen); bRet; // avoid level 4 warning ATLASSERT(bRet); wsprintf(szItemText, _T("&%i %s"), nItem + 1, szBuff); } ::InsertMenu(m_hMenu, nInsertPoint + nItem, MF_BYPOSITION | MF_STRING, t_nFirstID + nItem, szItemText); } } else // empty { ::InsertMenu(m_hMenu, nInsertPoint, MF_BYPOSITION | MF_STRING, t_nFirstID, m_szNoEntries); ::EnableMenuItem(m_hMenu, t_nFirstID, MF_GRAYED); nItem++; } ::DeleteMenu(m_hMenu, nInsertPoint + nItem, MF_BYPOSITION); return TRUE; } // Overrideables // override to provide a different method of compacting document names static bool CompactDocumentName(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen) { return AtlCompactPath(lpstrOut, lpstrIn, cchLen); } static LPCTSTR GetRegKeyName() { return _T("Recent Document List"); } }; class CRecentDocumentList : public CRecentDocumentListBase<CRecentDocumentList> { public: // nothing here }; #endif // _WIN32_WCE /////////////////////////////////////////////////////////////////////////////// // CFindFile - file search helper class #ifndef _WIN32_WCE class CFindFile { public: // Data members WIN32_FIND_DATA m_fd; TCHAR m_lpszRoot[MAX_PATH]; TCHAR m_chDirSeparator; HANDLE m_hFind; BOOL m_bFound; // Constructor/destructor CFindFile() : m_hFind(NULL), m_chDirSeparator('\\'), m_bFound(FALSE) { } ~CFindFile() { Close(); } // Attributes ULONGLONG GetFileSize() const { ATLASSERT(m_hFind != NULL); ULARGE_INTEGER nFileSize = { 0 }; if(m_bFound) { nFileSize.LowPart = m_fd.nFileSizeLow; nFileSize.HighPart = m_fd.nFileSizeHigh; } else { nFileSize.QuadPart = 0; } return nFileSize.QuadPart; } BOOL GetFileName(LPTSTR lpstrFileName, int cchLength) const { ATLASSERT(m_hFind != NULL); if(lstrlen(m_fd.cFileName) >= cchLength) return FALSE; return (m_bFound && (lstrcpy(lpstrFileName, m_fd.cFileName) != NULL)); } BOOL GetFilePath(LPTSTR lpstrFilePath, int cchLength) const { ATLASSERT(m_hFind != NULL); int nLen = lstrlen(m_lpszRoot); ATLASSERT(nLen > 0); if(nLen == 0) return FALSE; bool bAddSep = (m_lpszRoot[nLen - 1] != '\\' && m_lpszRoot[nLen - 1] != '/'); if((lstrlen(m_lpszRoot) + (bAddSep ? 1 : 0)) >= cchLength) return FALSE; BOOL bRet = (lstrcpy(lpstrFilePath, m_lpszRoot) != NULL); if(bRet) { if(bAddSep) { TCHAR szSeparator[2] = { m_chDirSeparator, 0 }; bRet = (lstrcat(lpstrFilePath, szSeparator) != NULL); } if(bRet) { bRet = (lstrcat(lpstrFilePath, m_fd.cFileName) != NULL); } } return bRet; } BOOL GetFileTitle(LPTSTR lpstrFileTitle, int cchLength) const { ATLASSERT(m_hFind != NULL); TCHAR szBuff[MAX_PATH] = { 0 }; if(!GetFileName(szBuff, MAX_PATH)) return FALSE; TCHAR szNameBuff[_MAX_FNAME] = { 0 }; _tsplitpath(szBuff, NULL, NULL, szNameBuff, NULL); if(lstrlen(szNameBuff) >= cchLength) return FALSE; return (lstrcpy(lpstrFileTitle, szNameBuff) != NULL); } BOOL GetFileURL(LPTSTR lpstrFileURL, int cchLength) const { ATLASSERT(m_hFind != NULL); TCHAR szBuff[MAX_PATH] = { 0 }; if(!GetFilePath(szBuff, MAX_PATH)) return FALSE; LPCTSTR lpstrFileURLPrefix = _T("file://"); if(lstrlen(szBuff) + lstrlen(lpstrFileURLPrefix) >= cchLength) return FALSE; if(lstrcpy(lpstrFileURL, lpstrFileURLPrefix) == NULL) return FALSE; return (lstrcat(lpstrFileURL, szBuff) != NULL); } BOOL GetRoot(LPTSTR lpstrRoot, int cchLength) const { ATLASSERT(m_hFind != NULL); if(lstrlen(m_lpszRoot) >= cchLength) return FALSE; return (lstrcpy(lpstrRoot, m_lpszRoot) != NULL); } #if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__) _CSTRING_NS::CString GetFileName() const { ATLASSERT(m_hFind != NULL); _CSTRING_NS::CString ret; if(m_bFound) ret = m_fd.cFileName; return ret; } _CSTRING_NS::CString GetFilePath() const { ATLASSERT(m_hFind != NULL); _CSTRING_NS::CString strResult = m_lpszRoot; if(strResult[strResult.GetLength() - 1] != '\\' && strResult[strResult.GetLength() - 1] != '/') strResult += m_chDirSeparator; strResult += GetFileName(); return strResult; } _CSTRING_NS::CString GetFileTitle() const { ATLASSERT(m_hFind != NULL); _CSTRING_NS::CString strFullName = GetFileName(); _CSTRING_NS::CString strResult; _tsplitpath(strFullName, NULL, NULL, strResult.GetBuffer(MAX_PATH), NULL); strResult.ReleaseBuffer(); return strResult; } _CSTRING_NS::CString GetFileURL() const { ATLASSERT(m_hFind != NULL); _CSTRING_NS::CString strResult("file://"); strResult += GetFilePath(); return strResult; } _CSTRING_NS::CString GetRoot() const { ATLASSERT(m_hFind != NULL); _CSTRING_NS::CString str = m_lpszRoot; return str; } #endif //defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__) BOOL GetLastWriteTime(FILETIME* pTimeStamp) const { ATLASSERT(m_hFind != NULL); ATLASSERT(pTimeStamp != NULL); if(m_bFound && pTimeStamp != NULL) { *pTimeStamp = m_fd.ftLastWriteTime; return TRUE; } return FALSE; } BOOL GetLastAccessTime(FILETIME* pTimeStamp) const { ATLASSERT(m_hFind != NULL); ATLASSERT(pTimeStamp != NULL); if(m_bFound && pTimeStamp != NULL) { *pTimeStamp = m_fd.ftLastAccessTime; return TRUE; } return FALSE; } BOOL GetCreationTime(FILETIME* pTimeStamp) const { ATLASSERT(m_hFind != NULL); if(m_bFound && pTimeStamp != NULL) { *pTimeStamp = m_fd.ftCreationTime; return TRUE; } return FALSE; } BOOL MatchesMask(DWORD dwMask) const { ATLASSERT(m_hFind != NULL); if(m_bFound) return ((m_fd.dwFileAttributes & dwMask) != 0); return FALSE; } BOOL IsDots() const { ATLASSERT(m_hFind != NULL); // return TRUE if the file name is "." or ".." and // the file is a directory BOOL bResult = FALSE; if(m_bFound && IsDirectory()) { if(m_fd.cFileName[0] == '.' && (m_fd.cFileName[1] == '\0' || (m_fd.cFileName[1] == '.' && m_fd.cFileName[2] == '\0'))) bResult = TRUE; } return bResult; } BOOL IsReadOnly() const { return MatchesMask(FILE_ATTRIBUTE_READONLY); } BOOL IsDirectory() const { return MatchesMask(FILE_ATTRIBUTE_DIRECTORY); } BOOL IsCompressed() const { return MatchesMask(FILE_ATTRIBUTE_COMPRESSED); } BOOL IsSystem() const { return MatchesMask(FILE_ATTRIBUTE_SYSTEM); } BOOL IsHidden() const { return MatchesMask(FILE_ATTRIBUTE_HIDDEN); } BOOL IsTemporary() const { return MatchesMask(FILE_ATTRIBUTE_TEMPORARY); } BOOL IsNormal() const { return MatchesMask(FILE_ATTRIBUTE_NORMAL); } BOOL IsArchived() const { return MatchesMask(FILE_ATTRIBUTE_ARCHIVE); } // Operations BOOL FindFile(LPCTSTR pstrName = NULL) { Close(); if(pstrName == NULL) pstrName = _T("*.*"); lstrcpy(m_fd.cFileName, pstrName); m_hFind = ::FindFirstFile(pstrName, &m_fd); if(m_hFind == INVALID_HANDLE_VALUE) return FALSE; LPCTSTR pstr = _tfullpath(m_lpszRoot, pstrName, MAX_PATH); // passed name isn't a valid path but was found by the API ATLASSERT(pstr != NULL); if(pstr == NULL) { Close(); ::SetLastError(ERROR_INVALID_NAME); return FALSE; } else { // find the last forward or backward whack LPTSTR pstrBack = _tcsrchr(m_lpszRoot, '\\'); LPTSTR pstrFront = _tcsrchr(m_lpszRoot, '/'); if(pstrFront != NULL || pstrBack != NULL) { if(pstrFront == NULL) pstrFront = m_lpszRoot; if(pstrBack == NULL) pstrBack = m_lpszRoot; // from the start to the last whack is the root if(pstrFront >= pstrBack) *pstrFront = '\0'; else *pstrBack = '\0'; } } m_bFound = TRUE; return TRUE; } BOOL FindNextFile() { ATLASSERT(m_hFind != NULL); if(m_hFind == NULL) return FALSE; if(!m_bFound) return FALSE; m_bFound = ::FindNextFile(m_hFind, &m_fd); return m_bFound; } void Close() { m_bFound = FALSE; if(m_hFind != NULL && m_hFind != INVALID_HANDLE_VALUE) { ::FindClose(m_hFind); m_hFind = NULL; } } }; #endif //!_WIN32_WCE /////////////////////////////////////////////////////////////////////////////// // Global functions for loading resources inline HACCEL AtlLoadAccelerators(ATL::_U_STRINGorID table) { #if (_ATL_VER >= 0x0700) return ::LoadAccelerators(ATL::_AtlBaseModule.GetResourceInstance(), table.m_lpstr); #else //!(_ATL_VER >= 0x0700) return ::LoadAccelerators(_Module.GetResourceInstance(), table.m_lpstr); #endif //!(_ATL_VER >= 0x0700) } inline HMENU AtlLoadMenu(ATL::_U_STRINGorID menu) { #if (_ATL_VER >= 0x0700) return ::LoadMenu(ATL::_AtlBaseModule.GetResourceInstance(), menu.m_lpstr); #else //!(_ATL_VER >= 0x0700) return ::LoadMenu(_Module.GetResourceInstance(), menu.m_lpstr); #endif //!(_ATL_VER >= 0x0700) } inline HBITMAP AtlLoadBitmap(ATL::_U_STRINGorID bitmap) { #if (_ATL_VER >= 0x0700) return ::LoadBitmap(ATL::_AtlBaseModule.GetResourceInstance(), bitmap.m_lpstr); #else //!(_ATL_VER >= 0x0700) return ::LoadBitmap(_Module.GetResourceInstance(), bitmap.m_lpstr); #endif //!(_ATL_VER >= 0x0700) } #ifdef OEMRESOURCE inline HBITMAP AtlLoadSysBitmap(LPCTSTR lpBitmapName) { #ifdef _DEBUG WORD wID = (WORD)lpBitmapName; ATLASSERT(wID >= 32734 && wID <= 32767); #endif //_DEBUG return ::LoadBitmap(NULL, lpBitmapName); } #endif //OEMRESOURCE inline HCURSOR AtlLoadCursor(ATL::_U_STRINGorID cursor) { #if (_ATL_VER >= 0x0700) return ::LoadCursor(ATL::_AtlBaseModule.GetResourceInstance(), cursor.m_lpstr); #else //!(_ATL_VER >= 0x0700) return ::LoadCursor(_Module.GetResourceInstance(), cursor.m_lpstr); #endif //!(_ATL_VER >= 0x0700) } inline HCURSOR AtlLoadSysCursor(LPCTSTR lpCursorName) { ATLASSERT(lpCursorName == IDC_ARROW || lpCursorName == IDC_IBEAM || lpCursorName == IDC_WAIT || lpCursorName == IDC_CROSS || lpCursorName == IDC_UPARROW || lpCursorName == IDC_SIZE || lpCursorName == IDC_ICON || lpCursorName == IDC_SIZENWSE || lpCursorName == IDC_SIZENESW || lpCursorName == IDC_SIZEWE || lpCursorName == IDC_SIZENS || lpCursorName == IDC_SIZEALL || lpCursorName == IDC_NO || lpCursorName == IDC_APPSTARTING || lpCursorName == IDC_HELP); return ::LoadCursor(NULL, lpCursorName); } inline HICON AtlLoadIcon(ATL::_U_STRINGorID icon) { #if (_ATL_VER >= 0x0700) return ::LoadIcon(ATL::_AtlBaseModule.GetResourceInstance(), icon.m_lpstr); #else //!(_ATL_VER >= 0x0700) return ::LoadIcon(_Module.GetResourceInstance(), icon.m_lpstr); #endif //!(_ATL_VER >= 0x0700) } #ifndef _WIN32_WCE inline HICON AtlLoadSysIcon(LPCTSTR lpIconName) { ATLASSERT(lpIconName == IDI_APPLICATION || lpIconName == IDI_ASTERISK || lpIconName == IDI_EXCLAMATION || lpIconName == IDI_HAND || lpIconName == IDI_QUESTION || lpIconName == IDI_WINLOGO); return ::LoadIcon(NULL, lpIconName); } #endif //!_WIN32_WCE inline HBITMAP AtlLoadBitmapImage(ATL::_U_STRINGorID bitmap, UINT fuLoad = LR_DEFAULTCOLOR) { #if (_ATL_VER >= 0x0700) return (HBITMAP)::LoadImage(ATL::_AtlBaseModule.GetResourceInstance(), bitmap.m_lpstr, IMAGE_BITMAP, 0, 0, fuLoad); #else //!(_ATL_VER >= 0x0700) return (HBITMAP)::LoadImage(_Module.GetResourceInstance(), bitmap.m_lpstr, IMAGE_BITMAP, 0, 0, fuLoad); #endif //!(_ATL_VER >= 0x0700) } inline HCURSOR AtlLoadCursorImage(ATL::_U_STRINGorID cursor, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0) { #if (_ATL_VER >= 0x0700) return (HCURSOR)::LoadImage(ATL::_AtlBaseModule.GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad); #else //!(_ATL_VER >= 0x0700) return (HCURSOR)::LoadImage(_Module.GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad); #endif //!(_ATL_VER >= 0x0700) } inline HICON AtlLoadIconImage(ATL::_U_STRINGorID icon, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0) { #if (_ATL_VER >= 0x0700) return (HICON)::LoadImage(ATL::_AtlBaseModule.GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad); #else //!(_ATL_VER >= 0x0700) return (HICON)::LoadImage(_Module.GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad); #endif //!(_ATL_VER >= 0x0700) } #ifdef OEMRESOURCE inline HBITMAP AtlLoadSysBitmapImage(WORD wBitmapID, UINT fuLoad = LR_DEFAULTCOLOR) { ATLASSERT(wBitmapID >= 32734 && wBitmapID <= 32767); ATLASSERT((fuLoad & LR_LOADFROMFILE) == 0); // this one doesn't load from a file return (HBITMAP)::LoadImage(NULL, MAKEINTRESOURCE(wBitmapID), IMAGE_BITMAP, 0, 0, fuLoad); } #endif //OEMRESOURCE inline HCURSOR AtlLoadSysCursorImage(ATL::_U_STRINGorID cursor, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0) { #ifdef _DEBUG WORD wID = (WORD)cursor.m_lpstr; ATLASSERT((wID >= 32512 && wID <= 32516) || (wID >= 32640 && wID <= 32648) || (wID == 32650) || (wID == 32651)); ATLASSERT((fuLoad & LR_LOADFROMFILE) == 0); // this one doesn't load from a file #endif //_DEBUG return (HCURSOR)::LoadImage(NULL, cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad); } inline HICON AtlLoadSysIconImage(ATL::_U_STRINGorID icon, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0) { #ifdef _DEBUG WORD wID = (WORD)icon.m_lpstr; ATLASSERT(wID >= 32512 && wID <= 32517); ATLASSERT((fuLoad & LR_LOADFROMFILE) == 0); // this one doesn't load from a file #endif //_DEBUG return (HICON)::LoadImage(NULL, icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad); } #if (_ATL_VER < 0x0700) inline int AtlLoadString(UINT uID, LPTSTR lpBuffer, int nBufferMax) { #if (_ATL_VER >= 0x0700) return ::LoadString(ATL::_AtlBaseModule.GetResourceInstance(), uID, lpBuffer, nBufferMax); #else //!(_ATL_VER >= 0x0700) return ::LoadString(_Module.GetResourceInstance(), uID, lpBuffer, nBufferMax); #endif //!(_ATL_VER >= 0x0700) } #endif //(_ATL_VER < 0x0700) inline bool AtlLoadString(UINT uID, BSTR& bstrText) { USES_CONVERSION; ATLASSERT(bstrText == NULL); LPTSTR lpstrText = NULL; int nRes = 0; for(int nLen = 256; ; nLen *= 2) { ATLTRY(lpstrText = new TCHAR[nLen]); if(lpstrText == NULL) break; #if (_ATL_VER >= 0x0700) nRes = ::LoadString(ATL::_AtlBaseModule.GetResourceInstance(), uID, lpstrText, nLen); #else //!(_ATL_VER >= 0x0700) nRes = ::LoadString(_Module.GetResourceInstance(), uID, lpstrText, nLen); #endif //!(_ATL_VER >= 0x0700) if(nRes < nLen - 1) break; delete [] lpstrText; lpstrText = NULL; } if(lpstrText != NULL) { if(nRes != 0) bstrText = ::SysAllocString(T2OLE(lpstrText)); delete [] lpstrText; } return (bstrText != NULL) ? true : false; } /////////////////////////////////////////////////////////////////////////////// // Global functions for stock GDI objects inline HPEN AtlGetStockPen(int nPen) { #if (_WIN32_WINNT >= 0x0500) && !defined(_WIN32_WCE) ATLASSERT(nPen == WHITE_PEN || nPen == BLACK_PEN || nPen == NULL_PEN || nPen == DC_PEN); #else ATLASSERT(nPen == WHITE_PEN || nPen == BLACK_PEN || nPen == NULL_PEN); #endif return (HPEN)::GetStockObject(nPen); } inline HBRUSH AtlGetStockBrush(int nBrush) { #if (_WIN32_WINNT >= 0x0500) && !defined(_WIN32_WCE) ATLASSERT((nBrush >= WHITE_BRUSH && nBrush <= HOLLOW_BRUSH) || nBrush == DC_BRUSH); #else ATLASSERT(nBrush >= WHITE_BRUSH && nBrush <= HOLLOW_BRUSH); #endif return (HBRUSH)::GetStockObject(nBrush); } inline HFONT AtlGetStockFont(int nFont) { #ifndef _WIN32_WCE ATLASSERT((nFont >= OEM_FIXED_FONT && nFont <= SYSTEM_FIXED_FONT) || nFont == DEFAULT_GUI_FONT); #else // CE specific ATLASSERT(nFont == SYSTEM_FONT); #endif //_WIN32_WCE return (HFONT)::GetStockObject(nFont); } inline HPALETTE AtlGetStockPalette(int nPalette) { ATLASSERT(nPalette == DEFAULT_PALETTE); // the only one supported return (HPALETTE)::GetStockObject(nPalette); } /////////////////////////////////////////////////////////////////////////////// // Global function for compacting a path by replacing parts with ellipsis // helper for multi-byte character sets inline bool _IsDBCSTrailByte(LPCTSTR lpstr, int nChar) { #ifndef _UNICODE int i = nChar; for( ; i > 0; i--) { if(!::IsDBCSLeadByte(lpstr[i - 1])) break; } return ((nChar > 0) && (((nChar - i) & 1) != 0)); #else //_UNICODE lpstr; nChar; return false; #endif //_UNICODE } inline bool AtlCompactPath(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen) { ATLASSERT(lpstrOut != NULL); ATLASSERT(lpstrIn != NULL); ATLASSERT(cchLen > 0); LPCTSTR szEllipsis = _T("..."); const int cchEndEllipsis = 3; const int cchMidEllipsis = 4; if(lstrlen(lpstrIn) + 1 < cchLen) return (lstrcpy(lpstrOut, lpstrIn) != NULL); lpstrOut[0] = 0; // check if the separator is a slash or a backslash TCHAR chSlash = _T('\\'); for(LPTSTR lpstr = (LPTSTR)lpstrIn; *lpstr != 0; lpstr = ::CharNext(lpstr)) { if((*lpstr == _T('/')) || (*lpstr == _T('\\'))) chSlash = *lpstr; } // find the filename portion of the path LPCTSTR lpstrFileName = lpstrIn; for(LPCTSTR pPath = lpstrIn; *pPath; pPath = ::CharNext(pPath)) { if((pPath[0] == _T('\\') || pPath[0] == _T(':') || pPath[0] == _T('/')) && pPath[1] && pPath[1] != _T('\\') && pPath[1] != _T('/')) lpstrFileName = pPath + 1; } int cchFileName = lstrlen(lpstrFileName); // handle just the filename without a path if(lpstrFileName == lpstrIn && cchLen > cchEndEllipsis) { bool bRet = (lstrcpyn(lpstrOut, lpstrIn, cchLen - cchEndEllipsis) != NULL); if(bRet) { #ifndef _UNICODE if(_IsDBCSTrailByte(lpstrIn, cchLen - cchEndEllipsis)) lpstrOut[cchLen - cchEndEllipsis - 1] = 0; #endif //_UNICODE bRet = (lstrcat(lpstrOut, szEllipsis) != NULL); } return bRet; } // handle just ellipsis if((cchLen < (cchMidEllipsis + cchEndEllipsis))) { for(int i = 0; i < cchLen - 1; i++) lpstrOut[i] = ((i + 1) == cchMidEllipsis) ? chSlash : _T('.'); lpstrOut[cchLen - 1] = 0; return true; } // calc how much we have to copy int cchToCopy = cchLen - (cchMidEllipsis + cchFileName); if(cchToCopy < 0) cchToCopy = 0; #ifndef _UNICODE if(cchToCopy > 0 && _IsDBCSTrailByte(lpstrIn, cchToCopy)) cchToCopy--; #endif //_UNICODE bool bRet = (lstrcpyn(lpstrOut, lpstrIn, cchToCopy) != NULL); if(!bRet) return false; // add ellipsis bRet = (lstrcat(lpstrOut, szEllipsis) != NULL); if(!bRet) return false; TCHAR szSlash[2] = { chSlash, 0 }; bRet = (lstrcat(lpstrOut, szSlash) != NULL); if(!bRet) return false; // add filename (and ellipsis, if needed) if(cchLen > (cchMidEllipsis + cchFileName)) { bRet = (lstrcat(lpstrOut, lpstrFileName) != NULL); } else { cchToCopy = cchLen - cchMidEllipsis - cchEndEllipsis; #ifndef _UNICODE if(cchToCopy > 0 && _IsDBCSTrailByte(lpstrFileName, cchToCopy)) cchToCopy--; #endif //_UNICODE bRet = (lstrcpyn(&lpstrOut[cchMidEllipsis], lpstrFileName, cchToCopy) != NULL); if(bRet) bRet = (lstrcat(lpstrOut, szEllipsis) != NULL); } return bRet; } }; //namespace WTL #endif // __ATLMISC_H__
[ "damoguyan8844@2e4fddd8-cc6a-11de-b393-33af5e5426e5" ]
[ [ [ 1, 3977 ] ] ]
c660924ff1f5aab84318035de0508fba308d8aa0
8ecc762aa0716342b64f8f60664659a2f1dd19aa
/third_party/boost/sandbox/boost/property_tree/detail/exceptions_implementation.hpp
3202f2cb142c17e55aa9e63206abd2bbe3186bd1
[ "MIT", "BSL-1.0" ]
permissive
gbucknell/fsc-sdk
71993dcf48c6f8dbb6379c929e22a7ecb2d41503
11b7cda4eea35ec53effbe37382f4b28020cd59d
refs/heads/master
2021-01-10T11:16:58.310281
2009-01-23T16:31:12
2009-01-23T16:31:12
54,295,008
0
0
null
null
null
null
UTF-8
C++
false
false
3,193
hpp
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef BOOST_PROPERTY_TREE_DETAIL_EXCEPTIONS_IMPLEMENTATION_HPP_INCLUDED #define BOOST_PROPERTY_TREE_DETAIL_EXCEPTIONS_IMPLEMENTATION_HPP_INCLUDED namespace boost { namespace property_tree { namespace detail { // Default path-to-string converter; this is overridden for default path template<class P> std::string path_to_string(const P &path) { return std::string("<cannot convert path to string>"); } // Helper for preparing what string in ptree_bad_path exception template<class P> std::string prepare_bad_path_what(const std::string &what, const P &path) { using namespace detail; // To allow correct resolution of path_to_string() return what + " (" + path_to_string(path) + ")"; } // Default data-to-string converter; this is overridden for default data (string) template<class D> std::string data_to_string(const D &data) { return std::string("<cannot convert data to string>"); } // Helper for preparing what string in ptree_bad_data exception template<class D> std::string prepare_bad_data_what(const std::string &what, const D &data) { using namespace detail; // To allow correct resolution of data_to_string() return what + " (" + data_to_string(data) + ")"; } } /////////////////////////////////////////////////////////////////////////// // ptree_error inline ptree_error::ptree_error(const std::string &what): std::runtime_error(what) { } inline ptree_error::~ptree_error() throw() { } /////////////////////////////////////////////////////////////////////////// // ptree_bad_data template<class D> ptree_bad_data::ptree_bad_data(const std::string &what, const D &data): ptree_error(detail::prepare_bad_data_what(what, data)), m_data(data) { } inline ptree_bad_data::~ptree_bad_data() throw() { } template<class D> D ptree_bad_data::data() { return boost::any_cast<D>(m_data); } /////////////////////////////////////////////////////////////////////////// // ptree_bad_path template<class P> ptree_bad_path::ptree_bad_path(const std::string &what, const P &path): ptree_error(detail::prepare_bad_path_what(what, path)), m_path(path) { } inline ptree_bad_path::~ptree_bad_path() throw() { } template<class P> P ptree_bad_path::path() { return boost::any_cast<P>(m_path); } } } #endif
[ "samuel.debionne@8ae27fb2-a4e6-11dd-9bad-6bc74a82fd44" ]
[ [ [ 1, 106 ] ] ]
d3e4d5d64ac95565b19c8f964a133804954f12ec
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/xpressive/test/test9.cpp
cdba219afefff9d5c192f8e12188c34f3afb2233
[ "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
779
cpp
/////////////////////////////////////////////////////////////////////////////// // test9.cpp // // Copyright 2004 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <algorithm> #include "./test9.hpp" /////////////////////////////////////////////////////////////////////////////// // test_main // read the tests from the input file and execute them int test_main( int, char*[] ) { typedef std::string::const_iterator iterator_type; boost::iterator_range<test_case<iterator_type> const *> rng = get_test_cases<iterator_type>(); std::for_each(rng.begin(), rng.end(), test_runner<iterator_type>()); return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 22 ] ] ]
89b219c348ca486cd006a52ec339354ccc3234c5
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/storage/src/entry.cpp
37b4eca6e6f4da2fc2b6297cffc44831fea44b7b
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,113
cpp
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: entry.cpp,v 1.6 2003/11/11 12:07:09 nsuzuki Exp $ ******************************************************************************/ #define NTK_BUILD #include "ntk/storage/entry.h" #include <ntk/windows/windows.h> namespace ntk { //######################################################## Entry::Entry() { } Entry::Entry(const String& path, bool traverse) { set_to(path, traverse); } Entry::Entry(const Directory& dir, const String& path, bool traverse) { set_to(dir, path, traverse); } Entry::Entry(const Entry& rhs) { operator=(rhs); } Entry::~Entry() { } Entry& Entry::operator=(const Entry& rhs) { if(&rhs == this) return *this; Statable::operator=(rhs); m_path = rhs.m_path; return *this; } status_t Entry::set_to(const String& path, bool traverse_) { status_t sts = m_path.set_to(path); if(sts.is_valid_without_eval()) { if(traverse_) traverse(); } return sts; } status_t Entry::set_to(const Directory& dir, const String& path, bool traverse_) { status_t sts = m_path.set_to(dir, path); if(sts.is_valid_without_eval()) { if(traverse_) traverse(); } return sts; } void Entry::unset() { m_path.unset(); } status_t Entry::init_check() const { return m_path.init_check(); } void Entry::traverse() { } //-------------------------------------------------------- // public accessors Entry::Ref Entry::ref(status_t* status) const { status_t sts_, &sts = status ? *status : sts_; Ref ref_; sts = get_ref(&ref_); return ref_; } status_t Entry::get_ref(Ref* ref) const { if(ref == NULL) return st::BAD_VALUE_ERROR; status_t sts = m_path.init_check(); if(sts.is_valid_without_eval() == false) return sts; return st::ERR; } Path Entry::path(status_t* status) const { status_t sts_, &sts = status ? *status : sts_; Path path_; sts = get_path(&path_); return path_; } status_t Entry::get_path(Path* path) const { if(path == NULL) return st::BAD_VALUE_ERROR; status_t sts = m_path.init_check(); if(sts.is_valid_without_eval() == false) return sts; *path = m_path; return st::OK; } String Entry::name(status_t* status) const { status_t sts_, &sts = status ? *status : sts_; String str; sts = get_name(&str); return str; } status_t Entry::get_name(String* str) const { if(str == NULL) return st::BAD_VALUE_ERROR; return m_path.get_leaf(str); } String Entry::extension(status_t* status) const { status_t sts_, &sts = status ? *status : sts_; String str; sts = get_extension(&str); return str; } status_t Entry::get_extension(String* str) const { if(str == NULL) return st::BAD_VALUE_ERROR; if(is_file() == false) return status_t(st::ERR, "このエントリはファイルではないので拡張子は取得できません\n"); String file_name = name(); char_t* dot = strrchr(&file_name[0], '.'); if(dot == NULL) return status_t(st::ERR, "拡張子はありません\n"); *str = dot+1; parent();// why is here this? (a question to me... return true; } String Entry::parent(status_t* status) const { status_t sts_, &sts = status ? *status : sts_; String str; sts = get_parent(&str); return str; } status_t Entry::get_parent(String* str) const { if(str == NULL) return st::BAD_VALUE_ERROR; return m_path.get_parent(str); } bool Entry::is_exists() const { return m_path.init_check() && GetFileAttributes(m_path.as_string().c_str()) != 0xffffffff; } bool Entry::is_file() const { return is_directory() == false; } bool Entry::is_directory() const { return (GetFileAttributes(m_path.as_string().c_str()) & FILE_ATTRIBUTE_DIRECTORY) != 0; } bool Entry::is_sym_link() const { return false; } //######################################################## }// namespace ntk
[ [ [ 1, 255 ] ] ]
5a0957347226cf7fe20eeaba600eb92c2bd7c3b6
fceff9260ff49d2707060241b6f9b927b97db469
/ZombieGentlemen_SeniorProject/DXText.cpp
bbad2129da553c7cdf015f5fcd15b174016e43d0
[]
no_license
EddyReyes/gentlemen-zombies-senior-project
9f5a6be90f0459831b3f044ed17ef2f085bec679
d88458b716c6eded376b3d44b5385c80deeb9a16
refs/heads/master
2021-05-29T12:13:47.506314
2011-07-04T17:20:38
2011-07-04T17:20:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,840
cpp
#include "DXText.h" DXText::DXText() { italic = bold = textToggle = imageOn = false; fontSize=0; box = NULL; font = NULL; fontColor = NULL; textBox = NULL; } DXText::DXText(dxManager * a_dxMgr) { dxMgr = a_dxMgr; dialogText = new std::string; fontName = new std::string; box = NULL; fontColor = new D3DCOLOR; textBox = new RECT; // by default set font to arial fontSize = 20; bold = false; italic = false; setFontName("Arial"); textToggle = true; imageOn = true; } DXText::DXText(dxManager * a_dxMgr, std::string filename) { dxMgr = a_dxMgr; dialogText = new std::string; fontName = new std::string; box = new HudImage(dxMgr, filename); fontColor = new D3DCOLOR; textBox = new RECT; // by default set font to arial fontSize = 20; bold = false; italic = false; setFontName("Arial"); textToggle = true; imageOn = true; } DXText::DXText(dxManager * a_dxMgr, LPDIRECT3DTEXTURE9 * img, D3DXIMAGE_INFO * imgInfo) { dxMgr = a_dxMgr; dialogText = new std::string; fontName = new std::string; box = new HudImage(dxMgr, img, imgInfo); fontColor = new D3DCOLOR; textBox = new RECT; // by default set font to arial fontSize = 20; italic = false; bold = false; setFontName("Arial"); textToggle = true; imageOn = true; } DXText::~DXText() { // destroy strings if(dialogText) { dialogText->~basic_string(); delete dialogText; dialogText = NULL; } if(fontName) { fontName->~basic_string(); delete fontName; fontName = NULL; } // destroy font if(font) { font->Release(); font = NULL; } //destroy font color if(fontColor) { delete fontColor; fontColor = NULL; } // destroy text box image if(box) { box->~HudImage(); box = NULL; } // destroy text rectangle if(textBox) { delete textBox; textBox = NULL; } } void DXText::setFont() { // set weight for bolding of characters int weight = 0; if(bold) weight = FW_BOLD; else weight = FW_DONTCARE; //Create a D3DX font object D3DXCreateFont( *dxMgr->getDevice(), fontSize, // SIZE 0, weight, // WEIGHT 0, italic, // Italic DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, PROOF_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT(fontName->c_str()), &font ); } void DXText::setFontName(std::string a_fontName) { *fontName = a_fontName; setFont(); } void DXText::setFontSize(int a_size) { fontSize = a_size; setFont(); } void DXText::setFontColor(int a, int r, int g, int b) { *fontColor = D3DCOLOR_ARGB(a, r, g, b); setFont(); } void DXText::setDialog(std::string a_text) { *dialogText = a_text; } void DXText::textInfo(std::string a_fontName, int a_size, D3DCOLOR a_textColor, std::string a_text) { setFontName(a_fontName); setFontSize(a_size); *fontColor = a_textColor; setDialog(a_text); } void DXText::setRect(int a_top, int a_bottom, int a_left, int a_right) { // indicate where on the screen it should draw text textBox->bottom = a_bottom; textBox->top = a_top; textBox->left = a_left; textBox->right = a_right; } void DXText::setImage(std::string filename) { box->setImage(filename); } void DXText::toggleItalic() { italic = !italic; setFont(); } void DXText::toggleBold() { bold = !bold; setFont(); } void DXText::toggleImage(){imageOn = !imageOn;} void DXText::toggleText(){textToggle = !textToggle;} void DXText::draw() { if(imageOn) { if(box) box->draw(); } if(textToggle) { font->DrawText(NULL, dialogText->c_str(), -1, textBox, DT_WORDBREAK, *fontColor); } } void DXText::setTextRectOffset(int offset) { if(box) { textBox->top = (long)box->getYPosition() + offset; textBox->bottom = (long)(box->getYPosition() + (long)box->getHeight()) - offset; textBox->left = (long)box->getXPosition() + offset; textBox->right = (long)(box->getXPosition() + (long)box->getWidth()) - offset; } } bool DXText::setTextBoxParameters(float width, float height, float a_x, float a_y, int offset) { if(box) { box->setParameters(width, height, a_x, a_y); setTextRectOffset(offset); return true; } else { setRect((int)a_y,(int)(a_y + height), (int)a_x, (int)(a_x + width)); } return false; } HudImage* DXText::getimg(){return box;} void DXText::loadFromTxtFile(std::string filename) { // open text file std::fstream file(filename.c_str()); // check to see if text file is empty file.peek(); if(file.eof()) MessageBox(NULL,"invalid DXText parameters","Text Error",MB_OK); else { // if not load font name std::string fontName; char font[100]; file.getline(font, 100); fontName.append(font); int a, r, g, b, offset; float width, height, x, y; file >> fontSize >> a >> r >> g >> b >> width >> height >> x >> y >> offset; if( a<0 || a > 255 || r<0 || r > 255 || g<0 || g > 255 || b<0 || b > 255) MessageBox(NULL,"invalid DXText color parameters","Text Error",MB_OK); if(fontSize <= 0) MessageBox(NULL,"invalid DXText size","Text Error",MB_OK); if(x < 0 || y < 0) MessageBox(NULL,"invalid DXText position","Text Error",MB_OK); if(width < 0 || height < 0) MessageBox(NULL,"invalid DXText width/height parameters","Text Error",MB_OK); if(offset < 0) MessageBox(NULL,"invalid offset","Text Error",MB_OK); *fontColor = D3DCOLOR_ARGB(a, r, g, b); setTextBoxParameters(width, height, x, y, offset); setFont(); } } int DXText::getTextBoxWidth(){return (textBox->right - textBox->left);} int DXText::getTextBoxHeight(){return (textBox->bottom - textBox->top);} int DXText::getTextBoxXPos(){return textBox->left;} int DXText::getTextBoxYPos(){return textBox->top;}
[ "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5", "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5", "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5" ]
[ [ [ 1, 1 ], [ 28, 38 ], [ 40, 41 ], [ 44, 44 ], [ 53, 53 ], [ 62, 63 ], [ 105, 108 ], [ 116, 119 ], [ 121, 124 ], [ 126, 169 ], [ 179, 179 ], [ 187, 187 ], [ 190, 191 ], [ 197, 197 ], [ 214, 214 ], [ 216, 216 ] ], [ [ 2, 10 ] ], [ [ 11, 27 ], [ 39, 39 ], [ 42, 43 ], [ 45, 52 ], [ 54, 61 ], [ 64, 104 ], [ 109, 115 ], [ 120, 120 ], [ 125, 125 ], [ 170, 178 ], [ 180, 186 ], [ 188, 189 ], [ 192, 196 ], [ 198, 213 ], [ 215, 215 ], [ 217, 275 ] ] ]
ce7baa5b781db7ecf5b5782d3e10e2fd8c321328
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/detail/most_derived.hpp
59d902358dc69828a3aa441812ed90704ba7d42b
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,645
hpp
// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef MOST_DERIVED_051018_HPP # define MOST_DERIVED_051018_HPP # include <boost/mpl/if.hpp> # include <boost/type_traits/is_base_and_derived.hpp> namespace luabind { namespace detail { template<class Class, class WrappedClass> struct most_derived { typedef typename boost::mpl::if_ < boost::is_base_and_derived<Class, WrappedClass> , WrappedClass , Class >::type type; }; } } // namespace luabind::detail #endif // MOST_DERIVED_051018_HPP
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 48 ] ] ]
19786e237706317c97984fcac16476ae266b7fa4
3a103ad1fc799ce85943c78bcaf092e34208c0e2
/Source/Sand.cpp
4a1cfcde728f32dbd7d9d560ee7683bc7352cc9b
[]
no_license
whirlp00l/rendering
2e93d5c6835e054e85f9710efac27de938cae445
770c2ad19b62fd8dce86ff0ebf2c7ffc829893ca
refs/heads/master
2020-05-16T23:19:16.307640
2010-10-20T22:36:47
2010-10-20T22:36:47
37,064,816
0
0
null
null
null
null
UTF-8
C++
false
false
1,214
cpp
#include "Sand.h" #include "Ray.h" #include "Scene.h" #include "DebugMem.h" #include "AreaLight.h" #include "PerlinNoise.h" #include "WorleyNoise.h" Sand::Sand(float noiseMultiplier, const Vector3 & kd) : Lambert(kd), mNoiseMultiplier(noiseMultiplier) { m_type = Material::SAND; mNoiseMaker = new CustomizablePerlinNoise(8, 8, 0.2, 36); // we always want to use a bump map with our sand setUseBumpMap( true, 2, 1, 0.4, 23 ); } Sand::~Sand() { delete mNoiseMaker; mNoiseMaker = NULL; } Vector3 Sand::shade(const Ray &ray, const HitInfo &hit, const Scene &scene) const { Vector3 L(0.0f, 0.0f, 0.0f); // use diffuse lighting float perlinNoise = (1 + mNoiseMaker->Get( hit.P.x, hit.P.y, hit.P.z )) / 2; L += getDiffuseColor( ray, hit, scene ) * perlinNoise; // incorporate indirect lighting if( USE_PATH_TRACING ) { // add in the indirect lighting result L += getIndirectLight( hit, scene ) * m_kd; } // end indirect lighting // add the ambient component L += m_ka; // make sure all components of the shading color are greater than 0 L.x = std::max( 0.0f, L.x ); L.y = std::max( 0.0f, L.y ); L.z = std::max( 0.0f, L.z ); return L; }
[ "DaStar2B@82a46b14-ece5-f9c8-6756-62631a89e06b" ]
[ [ [ 1, 48 ] ] ]
821e49b4acf8e1f120faf85b920f5c902cda5884
b308f1edaab2be56eb66b7c03b0bf4673621b62f
/Code/Game/GameDll/VehicleClient.cpp
c5e7844a0d3f7606b06796a2d22efa36b273851d
[]
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
16,589
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2006. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Implements a class which handle client actions on vehicles. ------------------------------------------------------------------------- History: - 17:10:2006: Created by Mathieu Pinard *************************************************************************/ #include "StdAfx.h" #include "IGame.h" #include "IActorSystem.h" #include "IVehicleSystem.h" #include "VehicleClient.h" #include "GameCVars.h" #include "Game.h" #include "Weapon.h" #include "Player.h" //------------------------------------------------------------------------ bool CVehicleClient::Init() { m_actionNameIds.clear(); m_actionNameIds.insert(TActionNameIdMap::value_type("v_exit", eVAI_Exit)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeseat", eVAI_ChangeSeat)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeseat1", eVAI_ChangeSeat1)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeseat2", eVAI_ChangeSeat2)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeseat3", eVAI_ChangeSeat3)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeseat4", eVAI_ChangeSeat4)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeseat5", eVAI_ChangeSeat5)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_changeview", eVAI_ChangeView)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_viewoption", eVAI_ViewOption)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_zoom_in", eVAI_ZoomIn)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_zoom_out", eVAI_ZoomOut)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_attack1", eVAI_Attack1)); m_actionNameIds.insert(TActionNameIdMap::value_type("zoom", eVAI_Attack2)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_attack2", eVAI_Attack2)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_zoom", eVAI_Attack2)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_attack1", eVAI_Attack1)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_attack2", eVAI_Attack2)); m_actionNameIds.insert(TActionNameIdMap::value_type("firemode", eVAI_FireMode)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_lights", eVAI_ToggleLights)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_horn", eVAI_Horn)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_rotateyaw", eVAI_RotateYaw)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_rotatepitch", eVAI_RotatePitch)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_moveforward", eVAI_MoveForward)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_moveback", eVAI_MoveBack)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_moveup", eVAI_MoveUp)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_movedown", eVAI_MoveDown)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_turnleft", eVAI_TurnLeft)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_turnright", eVAI_TurnRight)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_strafeleft", eVAI_StrafeLeft)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_straferight", eVAI_StrafeRight)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_rollleft", eVAI_RollLeft)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_rollright", eVAI_RollRight)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_rotateroll", eVAI_RotateRoll)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_rotateyaw", eVAI_XIRotateYaw)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_rotatepitch", eVAI_XIRotatePitch)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_movey", eVAI_XIMoveY)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_movex", eVAI_XIMoveX)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_accelerate", eVAI_XIAccelerate)); m_actionNameIds.insert(TActionNameIdMap::value_type("xi_v_deccelerate", eVAI_XIDeccelerate)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_pitchup", eVAI_PitchUp)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_pitchdown", eVAI_PitchDown)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_brake", eVAI_Brake)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_afterburner", eVAI_AfterBurner)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_boost", eVAI_Boost)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_debug_1", eVAI_Debug_1)); m_actionNameIds.insert(TActionNameIdMap::value_type("v_debug_2", eVAI_Debug_2)); m_xiRotation.Set(0,0,0); m_bMovementFlagForward = false; m_bMovementFlagBack = false; m_bMovementFlagRight = false; m_bMovementFlagLeft = false; m_fLeftRight = 0.f; m_fForwardBackward = 0.f; m_tp = false; return true; } //------------------------------------------------------------------------ void CVehicleClient::Reset() { m_tp = false; } //------------------------------------------------------------------------ void CVehicleClient::OnAction(IVehicle* pVehicle, EntityId actorId, const ActionId& actionId, int activationMode, float value) { assert(pVehicle); if (!pVehicle) return; TActionNameIdMap::const_iterator ite = m_actionNameIds.find(actionId); if (ite == m_actionNameIds.end()) return; switch (ite->second) { case (eVAI_XIMoveX): { IVehicleMovement *pMovement = pVehicle->GetMovement(); if(pMovement && pMovement->GetMovementType() == IVehicleMovement::eVMT_Air) { //strafe instead of turning for air vehicles if(value>0.f) { pVehicle->OnAction(eVAI_StrafeRight, eAAM_OnPress, value, actorId); m_bMovementFlagRight = true; } else if(value==0.f) { if(m_bMovementFlagRight) { pVehicle->OnAction(eVAI_StrafeRight, eAAM_OnRelease, 0.f, actorId); m_bMovementFlagRight = false; } else if(m_bMovementFlagLeft) { pVehicle->OnAction(eVAI_StrafeLeft, eAAM_OnRelease, 0.f, actorId); m_bMovementFlagLeft = false; } } else//value<0 { pVehicle->OnAction(eVAI_StrafeLeft, eAAM_OnPress, -value, actorId); m_bMovementFlagLeft = true; } } else { if(value>0.f) { pVehicle->OnAction(eVAI_TurnRight, eAAM_OnPress, value, actorId); m_bMovementFlagRight = true; } else if(value==0.f) { if(m_bMovementFlagRight) { pVehicle->OnAction(eVAI_TurnRight, eAAM_OnRelease, 0.f, actorId); m_bMovementFlagRight = false; } else if(m_bMovementFlagLeft) { pVehicle->OnAction(eVAI_TurnLeft, eAAM_OnRelease, 0.f, actorId); m_bMovementFlagLeft = false; } } else//value<0 { pVehicle->OnAction(eVAI_TurnLeft, eAAM_OnPress, -value, actorId); m_bMovementFlagLeft = true; } } break; } case (eVAI_XIMoveY): { EVehicleActionIds eForward = eVAI_MoveForward; EVehicleActionIds eBack = eVAI_MoveBack; if(!strcmp("Asian_helicopter",pVehicle->GetEntity()->GetClass()->GetName())) { eForward = eVAI_MoveUp; eBack = eVAI_MoveDown; } if(value>0.f) { pVehicle->OnAction(eForward, eAAM_OnPress, value, actorId); m_bMovementFlagForward = true; } else if(value==0.f) { if(m_bMovementFlagForward) { pVehicle->OnAction(eForward, eAAM_OnRelease, 0.f, actorId); m_bMovementFlagForward = false; } else if(m_bMovementFlagBack) { pVehicle->OnAction(eBack, eAAM_OnRelease, 0.f, actorId); m_bMovementFlagBack = false; } } else//value<0.f { pVehicle->OnAction(eBack, eAAM_OnPress, -value, actorId); m_bMovementFlagBack = true; } break; } case (eVAI_XIRotateYaw): { // action is sent to vehicle in PreUpdate, so it is repeated every frame. m_xiRotation.x = (value*value*value); break; } case (eVAI_XIRotatePitch): { // action is sent to vehicle in PreUpdate, so it is repeated every frame m_xiRotation.y = -(value*value*value); if(g_pGameCVars->cl_invertController) m_xiRotation.y*=-1; break; } case (eVAI_RotateYaw): { // attempt to normalise the input somewhat (to bring it in line with controller input). const float scale = 0.75f, limit = 6.0f; value = clamp_tpl<float>(scale * value * gEnv->pTimer->GetFrameTime(), -limit, limit); pVehicle->OnAction(ite->second, activationMode, value, actorId); break; } case (eVAI_RotatePitch): { // attempt to normalise the input somewhat (to bring it in line with controller input). const float scale = 0.75f, limit = 6.0f; value = clamp_tpl<float>(scale * value * gEnv->pTimer->GetFrameTime(), -limit, limit); if (g_pGameCVars->cl_invertMouse) value *= -1.f; pVehicle->OnAction(ite->second, activationMode, value, actorId); break; } case (eVAI_TurnLeft): { if (activationMode == eAAM_OnPress || activationMode == eAAM_OnRelease) m_fLeftRight -= value*2.f - 1.f; m_fLeftRight = CLAMP(m_fLeftRight, -1.0f, 1.0f); pVehicle->OnAction(ite->second, activationMode, -m_fLeftRight, actorId); break; } case (eVAI_TurnRight): { if (activationMode == eAAM_OnPress || activationMode == eAAM_OnRelease) m_fLeftRight += value*2.f - 1.f; m_fLeftRight = CLAMP(m_fLeftRight, -1.0f, 1.0f); pVehicle->OnAction(ite->second, activationMode, m_fLeftRight, actorId); break; } case (eVAI_MoveForward): { if (activationMode == eAAM_OnPress || activationMode == eAAM_OnRelease) m_fForwardBackward += value*2.f - 1.f; if(activationMode == eAAM_OnRelease) m_fForwardBackward = CLAMP(m_fForwardBackward, 0.0f, 1.0f); else m_fForwardBackward = CLAMP(m_fForwardBackward, -1.0f, 1.0f); pVehicle->OnAction(ite->second, activationMode, m_fForwardBackward, actorId); break; } case (eVAI_MoveBack): { if (activationMode == eAAM_OnPress || activationMode == eAAM_OnRelease) m_fForwardBackward -= value*2.f - 1.f; if(activationMode == eAAM_OnRelease) m_fForwardBackward = CLAMP(m_fForwardBackward, -1.0f, 0.0f); else m_fForwardBackward = CLAMP(m_fForwardBackward, -1.0f, 1.0f); pVehicle->OnAction(ite->second, activationMode, -m_fForwardBackward, actorId); break; } case (eVAI_ZoomIn): case (eVAI_ZoomOut): break; default: pVehicle->OnAction(ite->second, activationMode, value, actorId); break; } } //------------------------------------------------------------------------ void CVehicleClient::PreUpdate(IVehicle* pVehicle, EntityId actorId, float frameTime) { if(fabsf(m_xiRotation.x) > 0.001) { pVehicle->OnAction(eVAI_RotateYaw, eAAM_OnPress, m_xiRotation.x, actorId); } if(fabsf(m_xiRotation.y) > 0.001) { pVehicle->OnAction(eVAI_RotatePitch, eAAM_OnPress, m_xiRotation.y, actorId); } } //------------------------------------------------------------------------ void CVehicleClient::OnEnterVehicleSeat(IVehicleSeat* pSeat) { m_bMovementFlagRight=m_bMovementFlagLeft=m_bMovementFlagForward=m_bMovementFlagBack=false; m_fLeftRight = m_fForwardBackward = 0.f; IVehicle* pVehicle = pSeat->GetVehicle(); assert(pVehicle); IActorSystem* pActorSystem = gEnv->pGame->GetIGameFramework()->GetIActorSystem(); assert(pActorSystem); IActor* pActor = pActorSystem->GetActor(pSeat->GetPassenger()); if (pActor) { bool isThirdPerson = pActor->IsThirdPerson() || m_tp; TVehicleViewId viewId = InvalidVehicleViewId; TVehicleViewId firstViewId = InvalidVehicleViewId; while (viewId = pSeat->GetNextView(viewId)) { if (viewId == firstViewId) break; if (firstViewId == InvalidVehicleViewId) firstViewId = viewId; if (IVehicleView* pView = pSeat->GetView(viewId)) { if (pView->IsThirdPerson() == isThirdPerson) break; } } if (viewId != InvalidVehicleViewId) pSeat->SetView(viewId); if(IActor *pPassengerActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pSeat->GetPassenger())) { if(pPassengerActor->IsPlayer()) { EnableActionMaps(pSeat, true); } } } } //------------------------------------------------------------------------ void CVehicleClient::OnExitVehicleSeat(IVehicleSeat* pSeat) { if(pSeat && pSeat->IsDriver()) { m_bMovementFlagRight=m_bMovementFlagLeft=m_bMovementFlagForward=m_bMovementFlagBack=false; m_fLeftRight = m_fForwardBackward = 0.f; } TVehicleViewId viewId = pSeat->GetCurrentView(); if (viewId != InvalidVehicleViewId) { if (IVehicleView* pView = pSeat->GetView(viewId)) m_tp = pView->IsThirdPerson(); pSeat->SetView(InvalidVehicleViewId); } if(IActor *pPassengerActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pSeat->GetPassenger())) { if(pPassengerActor->IsPlayer()) { EnableActionMaps(pSeat, false); } } } //------------------------------------------------------------------------ CVehicleClient::SVehicleClientInfo& CVehicleClient::GetVehicleClientInfo(IVehicle* pVehicle) { IEntityClass* pClass = pVehicle->GetEntity()->GetClass(); TVehicleClientInfoMap::iterator ite = m_vehiclesInfo.find(pClass); if (ite == m_vehiclesInfo.end()) { // we need to add this class in our list SVehicleClientInfo clientInfo; clientInfo.seats.resize(pVehicle->GetSeatCount()); TVehicleSeatClientInfoVector::iterator seatInfoIte = clientInfo.seats.begin(); TVehicleSeatClientInfoVector::iterator seatInfoEnd = clientInfo.seats.end(); TVehicleSeatId seatId = InvalidVehicleSeatId; for (; seatInfoIte != seatInfoEnd; ++seatInfoIte) { seatId++; SVehicleSeatClientInfo& seatInfo = *seatInfoIte; seatInfo.seatId = seatId; seatInfo.viewId = InvalidVehicleViewId; } m_vehiclesInfo.insert(TVehicleClientInfoMap::value_type(pClass, clientInfo)); ite = m_vehiclesInfo.find(pClass); } // this will never happen assert(ite != m_vehiclesInfo.end()); return ite->second; } //------------------------------------------------------------------------ CVehicleClient::SVehicleSeatClientInfo& CVehicleClient::GetVehicleSeatClientInfo(SVehicleClientInfo& vehicleClientInfo, TVehicleSeatId seatId) { TVehicleSeatClientInfoVector::iterator seatInfoIte = vehicleClientInfo.seats.begin(); TVehicleSeatClientInfoVector::iterator seatInfoEnd = vehicleClientInfo.seats.end(); for (; seatInfoIte != seatInfoEnd; ++seatInfoIte) { SVehicleSeatClientInfo& seatClientInfo = *seatInfoIte; if (seatClientInfo.seatId == seatId) return *seatInfoIte; } // will never happen, unless the vehicle has new seat created after the // game started assert(0); return vehicleClientInfo.seats[0]; } void CVehicleClient::EnableActionMaps(IVehicleSeat* pSeat, bool enable) { assert(pSeat); // illegal to change action maps in demo playback - Lin if (!IsDemoPlayback() && pSeat) { IActionMapManager* pActionMapMan = g_pGame->GetIGameFramework()->GetIActionMapManager(); CRY_ASSERT(pActionMapMan); // normal c2 controls are disabled in a vehicle pActionMapMan->EnableActionMap("default", !enable); pActionMapMan->EnableActionMap("player", !enable); EntityId passengerID = pSeat->GetPassenger(); // now the general vehicle controls if (IActionMap* pActionMap = pActionMapMan->GetActionMap("vehicle_general")) { pActionMap->SetActionListener(enable ? passengerID : 0); pActionMapMan->EnableActionMap("vehicle_general", enable); } // todo: if necessary enable the vehicle-specific action map here // specific controls for this vehicle seat const char* actionMap = pSeat->GetActionMap(); if (actionMap && actionMap[0]) { if (IActionMap* pActionMap = pActionMapMan->GetActionMap(actionMap)) { pActionMap->SetActionListener(enable ? passengerID : 0); pActionMapMan->EnableActionMap(actionMap, enable); } } } } #include UNIQUE_VIRTUAL_WRAPPER(IVehicleClient)
[ [ [ 1, 482 ] ] ]
b0c33e6591f587045b85c9dfe9bde24d9b9f2b92
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/fusion/RelativePoseQueue.cpp
1a33907cc7b78e58375a08e9cfaa282ed805b7ef
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,485
cpp
#include "RelativePoseQueue.h" #ifdef __cplusplus_cli #pragma unmanaged #endif RelativePoseQueue::RelativePoseQueue(int iQueueSize, double iWXVar, double iWYVar, double iWZVar, double iVXVar, double iVYVar, double iVZVar) { /* Default constructor. Puts zeros in the queue. INPUTS: iQueueSize - number of odometry packets to keep iWXVar, iWYVar, iWZVar - continuous white noise variance on rates of rotation iVXVar, iVYVar, iVZVar - continuous white noise variance on velocities OUTPUTS: none. */ InitializeCriticalSection(&mQueueLock); EnterCriticalSection(&mQueueLock); //copy over the instantaneous white noise variances mWXVar = iWXVar; mWYVar = iWYVar; mWZVar = iWZVar; mVXVar = iVXVar; mVYVar = iVYVar; mVZVar = iVZVar; mQueueSize = iQueueSize; if (mQueueSize <= 0) { //check for invalid initial values mQueueSize = 100; } mRPPQueue = new double[RPQ_PACKETSIZE*mQueueSize]; //initialize the queue int i; int j; for (i = 0; i < mQueueSize; i++) { for (j = 0; j < RPQ_PACKETSIZE; j++) { mRPPQueue[midx(i, j, mQueueSize)] = 0.0; } } mQueueTail = -1; mNumPacketsInQueue = 0; mNumOldEventsIgnored = 0; LeaveCriticalSection(&mQueueLock); return; } RelativePoseQueue::~RelativePoseQueue(void) { /* Relative pose queue destructor. Frees memory allocated. INPUTS: none. OUTPUTS: none. */ EnterCriticalSection(&mQueueLock); DeleteCriticalSection(&mQueueLock); mNumPacketsInQueue = 0; //free memory in the odometry queue delete [] mRPPQueue; return; } void RelativePoseQueue::ResetQueue() { /* Resets the queue to its initial state. INPUTS: none. OUTPUTS: none. */ int i; int j; EnterCriticalSection(&mQueueLock); printf("Warning: resetting relative pose queue...\n"); //delete all relative pose packets for (i = 0; i < mQueueSize; i++) { for (j = 0; j < RPQ_PACKETSIZE; j++) { mRPPQueue[midx(i, j, mQueueSize)] = 0.0; } } mQueueTail = -1; mNumPacketsInQueue = 0; //and reset the number of old events ignored mNumOldEventsIgnored = 0; LeaveCriticalSection(&mQueueLock); return; } bool RelativePoseQueue::PushPacket(const pose_rel_msg& iOdomMessage) { /* Overloaded push method for pushing the actual odometry data structure. INPUTS: iOdomMessage - the input odometry message to copy OUTPUTS: rSuccess - true if packet push was successful, false otherwise. */ double iEventData[RPQ_PACKETSIZE]; //timestamp iEventData[0] = (double)(iOdomMessage.car_ts_secs) + (double)(iOdomMessage.car_ts_ticks)/10000.0; //integration time dt iEventData[1] = iOdomMessage.dt; //elements of the transformation matrix iEventData[2] = iOdomMessage.Rinit2veh[0][0]; iEventData[3] = iOdomMessage.Rinit2veh[1][0]; iEventData[4] = iOdomMessage.Rinit2veh[2][0]; iEventData[5] = iOdomMessage.Rinit2veh[0][1]; iEventData[6] = iOdomMessage.Rinit2veh[1][1]; iEventData[7] = iOdomMessage.Rinit2veh[2][1]; iEventData[8] = iOdomMessage.Rinit2veh[0][2]; iEventData[9] = iOdomMessage.Rinit2veh[1][2]; iEventData[10] = iOdomMessage.Rinit2veh[2][2]; iEventData[11] = iOdomMessage.Rinit2veh[0][3]; iEventData[12] = iOdomMessage.Rinit2veh[1][3]; iEventData[13] = iOdomMessage.Rinit2veh[2][3]; return PushPacket(iEventData); } bool RelativePoseQueue::PushPacket(double iPacket[RPQ_PACKETSIZE]) { /* Pushes a packet onto the queue. Since the queue is circular, this may delete the oldest element on the queue. INPUTS: iPacket - the packet to add to the queue OUTPUTS: rSuccess - returns true if push was successful, false otherwise. */ bool rSuccess = false; double mrqt = MostRecentQueueTime(); EnterCriticalSection(&mQueueLock); //check the event for a valid timestamp if (iPacket[0] < Q_MINTIMESTAMP || iPacket[0] > Q_MAXTIMESTAMP) { printf("Warning: ignoring type %d event with timestamp %.12lg.\n", ODOM_EVENT, iPacket[0]); LeaveCriticalSection(&mQueueLock); return rSuccess; } if (iPacket[0] < mrqt) { //don't push an out of order odometry packet to the queue printf("Warning: ignoring old type %d event of age %.12lg ms.\n", ODOM_EVENT, (mrqt - iPacket[0])*1000.0); mNumOldEventsIgnored++; LeaveCriticalSection(&mQueueLock); if (mNumOldEventsIgnored > RPQ_NUMEVENTSB4RESET) { //reset the queue if too many bad packets show up ResetQueue(); } return rSuccess; } //if this event has an OK timestamp then reset the "ignored old events" counter mNumOldEventsIgnored = 0; //increment the queue tail, and drop the packet at the tail mQueueTail = (mQueueTail + 1) % mQueueSize; int j; for (j = 0; j < RPQ_PACKETSIZE; j++) { mRPPQueue[midx(mQueueTail, j, mQueueSize)] = iPacket[j]; } //increment the number of elements in the queue mNumPacketsInQueue++; if (mNumPacketsInQueue > mQueueSize) { //but make sure never to have more than the queue's worth mNumPacketsInQueue = mQueueSize; } //if code gets here, push was successful rSuccess = true; LeaveCriticalSection(&mQueueLock); return rSuccess; } bool RelativePoseQueue::PullPacket(double oPacket[RPQ_PACKETSIZE], double iEventTime, int iQueryMode) { /* Pulls the packet with the timestamp closest to iEventTime under certain criteria. NOTE: this function is not thread-safe, so it must remain private, and must be called from a thread-safe public function. INPUTS: oPacket - will be filled with the returned packet iEventTime - time at which the packet is requested iQueryMode - determines the behavior of how packets are pulled. Can be: RPQ_PULLPACKETBEFORETS - pulls the packet closest to but before the desired timestamp. RPQ_PULLPACKETAFTERTS - pulls the packet closest to but after the desired timestamp. RPQ_PULLPACKETCLOSESTTS - pulls the packet closest to the desired timestamp. OUTPUTS: oPacket - filled with the packet. Function returns true if a packet was successfully pulled, false otherwise. */ if (mNumPacketsInQueue == 0) { //no packets in the queue return false; } //if code gets here, a packet was in the queue //search the queue for the best matching time and return it int imax; imax = mQueueSize; if (mNumPacketsInQueue < mQueueSize) { imax = mNumPacketsInQueue; } //try to find a relative pose packet that comes just before the desired time int i; double dtbest = DBL_MAX; int ibest = -1; for (i = 0; i < imax; i++) { //extract the timestamp for this element of the queue double ttst = mRPPQueue[midx(i, 0, mQueueSize)]; double dt = iEventTime - ttst; if (fabs(dt) < fabs(dtbest)) { //found a new closer timestamp switch (iQueryMode) { case RPQ_PULLPACKETBEFORETS: //pull a packet before the desired timestamp if (dt > 0.0) { //found a new closer timestamp that happened before the desired time dtbest = fabs(dt); ibest = i; } break; case RPQ_PULLPACKETAFTERTS: //pull a packet after the desired timestamp if (dt <= 0.0) { //found a new closer timestamp that happened after the desired time dtbest = fabs(dt); ibest = i; } break; case RPQ_PULLPACKETCLOSESTTS: //pull a packet closest to the desired timestamp //found a new closer timestamp dtbest = fabs(dt); ibest = i; break; } } } if (ibest == -1 || dtbest > RPQ_MAXPACKETOFFSET) { //couldn't find a valid odometry packet return false; } int j; for (j = 0; j < RPQ_PACKETSIZE; j++) { oPacket[j] = mRPPQueue[midx(ibest, j, mQueueSize)]; } return true; } void RelativePoseQueue::GetVehicleOdometry(VehicleOdometry* oVehicleOdometry, double iStartTime, double iEndTime) { /* Returns average vehicle odometry over a specified time window. INPUTS: oVehicleOdometry - will be populated with the vehicle's odometry at output iStartTime - starting time of relative pose transformation iEndTime - ending time of relative pose transformation OUTPUTS: none. Sets values in oVehicleOdometry appropriately. Check the IsValid flag to see whether the values are valid */ int i; int j; int k; //declare variables that will store the output values double dt; double wx; double wy; double wz; double vx; double vy; double vz; double qwx; double qwy; double qwz; double qvx; double qvy; double qvz; EnterCriticalSection(&mQueueLock); //set vehicle odometry process noises qvx = mVXVar; qvy = mVYVar; qvz = mVZVar; qwx = mWXVar; qwy = mWYVar; qwz = mWZVar; //find the two pertinent odometry buffers double start_packet[RPQ_PACKETSIZE]; if (PullPacket(start_packet, iStartTime, RPQ_PULLPACKETBEFORETS) == false) { //find an odometry packet before the start time oVehicleOdometry->IsValid = false; LeaveCriticalSection(&mQueueLock); return; } double end_packet[RPQ_PACKETSIZE]; if (PullPacket(end_packet, iEndTime, RPQ_PULLPACKETAFTERTS) == false) { //find an odometry packet after the end time oVehicleOdometry->IsValid = false; LeaveCriticalSection(&mQueueLock); return; } //extract the current odometry time double tk = end_packet[0]; double Ri2vk[16]; //extract the current transformation matrix Ri2vk[midx(0, 0, 4)] = end_packet[2]; Ri2vk[midx(1, 0, 4)] = end_packet[3]; Ri2vk[midx(2, 0, 4)] = end_packet[4]; Ri2vk[midx(3, 0, 4)] = 0.0; Ri2vk[midx(0, 1, 4)] = end_packet[5]; Ri2vk[midx(1, 1, 4)] = end_packet[6]; Ri2vk[midx(2, 1, 4)] = end_packet[7]; Ri2vk[midx(3, 1, 4)] = 0.0; Ri2vk[midx(0, 2, 4)] = end_packet[8]; Ri2vk[midx(1, 2, 4)] = end_packet[9]; Ri2vk[midx(2, 2, 4)] = end_packet[10]; Ri2vk[midx(3, 2, 4)] = 0.0; Ri2vk[midx(0, 3, 4)] = end_packet[11]; Ri2vk[midx(1, 3, 4)] = end_packet[12]; Ri2vk[midx(2, 3, 4)] = end_packet[13]; Ri2vk[midx(3, 3, 4)] = 1.0; //extract the old odometry time double tkmo = start_packet[0]; double Ri2vkmo[16]; //extract the old transformation matrix Ri2vkmo[midx(0, 0, 4)] = start_packet[2]; Ri2vkmo[midx(1, 0, 4)] = start_packet[3]; Ri2vkmo[midx(2, 0, 4)] = start_packet[4]; Ri2vkmo[midx(3, 0, 4)] = 0.0; Ri2vkmo[midx(0, 1, 4)] = start_packet[5]; Ri2vkmo[midx(1, 1, 4)] = start_packet[6]; Ri2vkmo[midx(2, 1, 4)] = start_packet[7]; Ri2vkmo[midx(3, 1, 4)] = 0.0; Ri2vkmo[midx(0, 2, 4)] = start_packet[8]; Ri2vkmo[midx(1, 2, 4)] = start_packet[9]; Ri2vkmo[midx(2, 2, 4)] = start_packet[10]; Ri2vkmo[midx(3, 2, 4)] = 0.0; Ri2vkmo[midx(0, 3, 4)] = start_packet[11]; Ri2vkmo[midx(1, 3, 4)] = start_packet[12]; Ri2vkmo[midx(2, 3, 4)] = start_packet[13]; Ri2vkmo[midx(3, 3, 4)] = 1.0; //create Rvkmo2vk, the incremental transformation matrix double invRi2vkmo[16]; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { //upper left 3x3 block is just transposed invRi2vkmo[midx(i, j, 4)] = Ri2vkmo[midx(j, i, 4)]; } } //last row is [0, 0, 0, 1] invRi2vkmo[midx(3, 0, 4)] = 0.0; invRi2vkmo[midx(3, 1, 4)] = 0.0; invRi2vkmo[midx(3, 2, 4)] = 0.0; invRi2vkmo[midx(3, 3, 4)] = 1.0; //last col is -R'*d for (i = 0; i < 3; i++) { invRi2vkmo[midx(i, 3, 4)] = 0.0; for (k = 0; k < 3; k++) { invRi2vkmo[midx(i, 3, 4)] -= Ri2vkmo[midx(k, i, 4)] * Ri2vkmo[midx(k, 3, 4)]; } } //Rvkmo2vk = Ri2vk*inv(Ri2vkmo); double Rvkmo2vk[16]; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { Rvkmo2vk[midx(i, j, 4)] = 0.0; for (k = 0; k < 4; k++) { Rvkmo2vk[midx(i, j, 4)] += Ri2vk[midx(i, k, 4)] * invRi2vkmo[midx(k, j, 4)]; } } } //extract inverse kinematics from sequential transformation matrix double sindy = Rvkmo2vk[midx(2, 0, 4)]; double cosdy = sqrt(Rvkmo2vk[midx(2, 1, 4)]*Rvkmo2vk[midx(2, 1, 4)] + Rvkmo2vk[midx(2, 2, 4)]*Rvkmo2vk[midx(2, 2, 4)]); double sindx = -Rvkmo2vk[midx(2, 1, 4)] / cosdy; double cosdx = Rvkmo2vk[midx(2, 2, 4)] / cosdy; double sindz = -Rvkmo2vk[midx(1, 0, 4)] / cosdy; double cosdz = Rvkmo2vk[midx(0, 0, 4)] / cosdy; //calculate average vehicle odometry dt = tk - tkmo; if (dt > 0.0) { //set average vehicle odometry wx = atan2(sindx, cosdx) / dt; wy = atan2(sindy, cosdy) / dt; wz = atan2(sindz, cosdz) / dt; vx = -(Rvkmo2vk[midx(0, 0, 4)]*Rvkmo2vk[midx(0, 3, 4)] + Rvkmo2vk[midx(1, 0, 4)]*Rvkmo2vk[midx(1, 3, 4)] + Rvkmo2vk[midx(2, 0, 4)]*Rvkmo2vk[midx(2, 3, 4)]) / dt; vy = -(Rvkmo2vk[midx(0, 1, 4)]*Rvkmo2vk[midx(0, 3, 4)] + Rvkmo2vk[midx(1, 1, 4)]*Rvkmo2vk[midx(1, 3, 4)] + Rvkmo2vk[midx(2, 1, 4)]*Rvkmo2vk[midx(2, 3, 4)]) / dt; vz = -(Rvkmo2vk[midx(0, 2, 4)]*Rvkmo2vk[midx(0, 3, 4)] + Rvkmo2vk[midx(1, 2, 4)]*Rvkmo2vk[midx(1, 3, 4)] + Rvkmo2vk[midx(2, 2, 4)]*Rvkmo2vk[midx(2, 3, 4)]) / dt; } else { //set odometry to zero and return a false packet wx = 0.0; wy = 0.0; wz = 0.0; vx = 0.0; vy = 0.0; vz = 0.0; oVehicleOdometry->IsValid = false; LeaveCriticalSection(&mQueueLock); return; } //store the information into the output argument oVehicleOdometry->IsValid = true; oVehicleOdometry->EndTime = tk; oVehicleOdometry->StartTime = tkmo; oVehicleOdometry->dt = dt; oVehicleOdometry->wx = wx; oVehicleOdometry->wy = wy; oVehicleOdometry->wz = wz; oVehicleOdometry->vx = vx; oVehicleOdometry->vy = vy; oVehicleOdometry->vz = vz; oVehicleOdometry->qwx = qwx; oVehicleOdometry->qwy = qwy; oVehicleOdometry->qwz = qwz; oVehicleOdometry->qvx = qvx; oVehicleOdometry->qvy = qvy; oVehicleOdometry->qvz = qvz; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { oVehicleOdometry->Rvkmo2vk[midx(i, j, 4)] = Rvkmo2vk[midx(i, j, 4)]; } } LeaveCriticalSection(&mQueueLock); return; } double RelativePoseQueue::LeastRecentQueueTime() { /* Returns the oldest time in the odometry queue INPUTS: none. OUTPUTS: rOldestTime - the oldest time in the odometry queue */ int idx; double rOldestTime = DBL_MAX; EnterCriticalSection(&mQueueLock); if (mNumPacketsInQueue > 0) { if (mNumPacketsInQueue < mQueueSize) { //queue hasn't filled up yet and rolled over idx = 0; } else { //queue has filled up idx = (mQueueTail + 1) % mQueueSize; } rOldestTime = mRPPQueue[midx(idx, 0, mQueueSize)]; } LeaveCriticalSection(&mQueueLock); return rOldestTime; } double RelativePoseQueue::MostRecentQueueTime() { /* Returns the newest time in the odometry queue INPUTS: none. OUTPUTS: rNewestTime - the newest time in the odometry queue */ double rNewestTime = -DBL_MAX; EnterCriticalSection(&mQueueLock); if (mNumPacketsInQueue > 0) { //if queue has packets, then mQueueTail is the most recent packet rNewestTime = mRPPQueue[midx(mQueueTail, 0, mQueueSize)]; } LeaveCriticalSection(&mQueueLock); return rNewestTime; } bool RelativePoseQueue::GetVehicleTransformation(VehicleTransformation& oVehicleTransformation, double iStartTime, double iEndTime) { /* Overloaded function for retrieving the vehicle transformation using a structure passed by reference instead of a pointer. INPUTS: oVehicleTransformation - the vehicle transformation structure, passed by reference. iStartTime - starting time of the transformation. iEndTime - ending time of the transformation OUTPUTS: rSuccess - true if the vehicle transformation is obtained successfully, false otherwise. If true, oVehicleTransformation is populated with the vehicle transformation. */ return GetVehicleTransformation(&oVehicleTransformation, iStartTime, iEndTime); } bool RelativePoseQueue::GetVehicleTransformation(VehicleTransformation* oVehicleTransformation, double iStartTime, double iEndTime) { /* Retrieves the vehicle transformation matrix to transform points from vehicle coordinates at time iStartTime to vehicle coordinates at iEndTime. Transformation is done by calculating: [new x; new y; new z; 1] = oRelativeMatrix * [old x; old y; old z; 1] INPUTS: oVehicleTransformation - vehicle transformation structure that describes the relative transformation between iStartTime and iEndTime on output. iStartTime - starting time of relative pose transformation iEndTime - ending time of relative pose transformation OUTPUTS: rSuccess - true if the transformation was successfully retrieved, false otherwise. If false, oVehicleTransformation is set to identity, otherwise it is set to the desired transformation matrix. */ bool rSuccess = false; int i; int j; int k; oVehicleTransformation->IsValid = false; //initialize oRelativeMatrix to identity for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { if (i == j) { oVehicleTransformation->T[midx(i, j, 4)] = 1.0; } else { oVehicleTransformation->T[midx(i, j, 4)] = 0.0; } } } EnterCriticalSection(&mQueueLock); //find the two pertinent odometry buffers double start_packet[RPQ_PACKETSIZE]; if (PullPacket(start_packet, iStartTime, RPQ_PULLPACKETBEFORETS) == false) { //failed to find an odometry packet near the desired start time LeaveCriticalSection(&mQueueLock); return rSuccess; } double end_packet[RPQ_PACKETSIZE]; if (PullPacket(end_packet, iEndTime, RPQ_PULLPACKETBEFORETS) == false) { //failed to find an odometry packet near the desired end time LeaveCriticalSection(&mQueueLock); return rSuccess; } //extract the current odometry time double tk = end_packet[0]; double Ri2vk[16]; //extract the current transformation matrix Ri2vk[midx(0, 0, 4)] = end_packet[2]; Ri2vk[midx(1, 0, 4)] = end_packet[3]; Ri2vk[midx(2, 0, 4)] = end_packet[4]; Ri2vk[midx(3, 0, 4)] = 0.0; Ri2vk[midx(0, 1, 4)] = end_packet[5]; Ri2vk[midx(1, 1, 4)] = end_packet[6]; Ri2vk[midx(2, 1, 4)] = end_packet[7]; Ri2vk[midx(3, 1, 4)] = 0.0; Ri2vk[midx(0, 2, 4)] = end_packet[8]; Ri2vk[midx(1, 2, 4)] = end_packet[9]; Ri2vk[midx(2, 2, 4)] = end_packet[10]; Ri2vk[midx(3, 2, 4)] = 0.0; Ri2vk[midx(0, 3, 4)] = end_packet[11]; Ri2vk[midx(1, 3, 4)] = end_packet[12]; Ri2vk[midx(2, 3, 4)] = end_packet[13]; Ri2vk[midx(3, 3, 4)] = 1.0; //extract the old odometry time double tkmo = start_packet[0]; double Ri2vkmo[16]; //extract the old transformation matrix Ri2vkmo[midx(0, 0, 4)] = start_packet[2]; Ri2vkmo[midx(1, 0, 4)] = start_packet[3]; Ri2vkmo[midx(2, 0, 4)] = start_packet[4]; Ri2vkmo[midx(3, 0, 4)] = 0.0; Ri2vkmo[midx(0, 1, 4)] = start_packet[5]; Ri2vkmo[midx(1, 1, 4)] = start_packet[6]; Ri2vkmo[midx(2, 1, 4)] = start_packet[7]; Ri2vkmo[midx(3, 1, 4)] = 0.0; Ri2vkmo[midx(0, 2, 4)] = start_packet[8]; Ri2vkmo[midx(1, 2, 4)] = start_packet[9]; Ri2vkmo[midx(2, 2, 4)] = start_packet[10]; Ri2vkmo[midx(3, 2, 4)] = 0.0; Ri2vkmo[midx(0, 3, 4)] = start_packet[11]; Ri2vkmo[midx(1, 3, 4)] = start_packet[12]; Ri2vkmo[midx(2, 3, 4)] = start_packet[13]; Ri2vkmo[midx(3, 3, 4)] = 1.0; //create Rvkmo2vk, the incremental transformation matrix double invRi2vkmo[16]; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { //upper left 3x3 block is just transposed invRi2vkmo[midx(i, j, 4)] = Ri2vkmo[midx(j, i, 4)]; } } //last row is [0, 0, 0, 1] invRi2vkmo[midx(3, 0, 4)] = 0.0; invRi2vkmo[midx(3, 1, 4)] = 0.0; invRi2vkmo[midx(3, 2, 4)] = 0.0; invRi2vkmo[midx(3, 3, 4)] = 1.0; //last col is -R'*d for (i = 0; i < 3; i++) { invRi2vkmo[midx(i, 3, 4)] = 0.0; for (k = 0; k < 3; k++) { invRi2vkmo[midx(i, 3, 4)] -= Ri2vkmo[midx(k, i, 4)] * Ri2vkmo[midx(k, 3, 4)]; } } //Rvkmo2vk = Ri2vk*inv(Ri2vkmo); double Rvkmo2vk[4*4]; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { Rvkmo2vk[midx(i, j, 4)] = 0.0; for (k = 0; k < 4; k++) { Rvkmo2vk[midx(i, j, 4)] += Ri2vk[midx(i, k, 4)] * invRi2vkmo[midx(k, j, 4)]; } oVehicleTransformation->T[midx(i, j, 4)] = Rvkmo2vk[midx(i, j, 4)]; } } //set the rest of the vehicle transformation values oVehicleTransformation->IsValid = true; oVehicleTransformation->StartTime = tkmo; oVehicleTransformation->EndTime = tk; double dt = tk - tkmo; oVehicleTransformation->dt = dt; //set the uncertainty in each element as it relates to uncertainty in vehicle odometry double fdt = fabs(dt); double var_wx = fdt*mWXVar; double var_wy = fdt*mWYVar; double var_wz = fdt*mWZVar; double var_vx = fdt*mVXVar; double var_vy = fdt*mVYVar; double var_vz = fdt*mVZVar; //extract trig computations of delta-angles double sindy = Rvkmo2vk[midx(2, 0, 4)]; double cosdy = sqrt(Rvkmo2vk[midx(2, 1, 4)]*Rvkmo2vk[midx(2, 1, 4)] + Rvkmo2vk[midx(2, 2, 4)]*Rvkmo2vk[midx(2, 2, 4)]); double sindx = -Rvkmo2vk[midx(2, 1, 4)] / cosdy; double cosdx = Rvkmo2vk[midx(2, 2, 4)] / cosdy; double sindz = -Rvkmo2vk[midx(1, 0, 4)] / cosdy; double cosdz = Rvkmo2vk[midx(0, 0, 4)] / cosdy; //extract delta-positions double dx = -(Rvkmo2vk[midx(0, 0, 4)]*Rvkmo2vk[midx(0, 3, 4)] + Rvkmo2vk[midx(1, 0, 4)]*Rvkmo2vk[midx(1, 3, 4)] + Rvkmo2vk[midx(2, 0, 4)]*Rvkmo2vk[midx(2, 3, 4)]); double dy = -(Rvkmo2vk[midx(0, 1, 4)]*Rvkmo2vk[midx(0, 3, 4)] + Rvkmo2vk[midx(1, 1, 4)]*Rvkmo2vk[midx(1, 3, 4)] + Rvkmo2vk[midx(2, 1, 4)]*Rvkmo2vk[midx(2, 3, 4)]); double dz = -(Rvkmo2vk[midx(0, 2, 4)]*Rvkmo2vk[midx(0, 3, 4)] + Rvkmo2vk[midx(1, 2, 4)]*Rvkmo2vk[midx(1, 3, 4)] + Rvkmo2vk[midx(2, 2, 4)]*Rvkmo2vk[midx(2, 3, 4)]); //use delta-angles and delta-positions to calculate jacobian of transformation double J[16*6]; for (i = 0; i < 16; i++) { for (j = 0; j < 6; j++) { J[midx(i, j, 16)] = 0.0; } } //element (0, 0) J[midx(0, 1, 16)] = -cosdz*sindy; J[midx(0, 2, 16)] = -sindz*cosdy; //element (1, 0) J[midx(1, 1, 16)] = sindz*sindy; J[midx(1, 2, 16)] = -cosdz*cosdy; //element (2, 0) J[midx(2, 1, 16)] = cosdy; //element (0, 1) J[midx(4, 0, 16)] = cosdz*sindy*cosdx - sindz*sindx; J[midx(4, 1, 16)] = cosdz*cosdy*sindx; J[midx(4, 2, 16)] = -sindz*sindy*sindx + cosdz*cosdx; //element (1, 1) J[midx(5, 0, 16)] = -sindz*sindy*cosdx - cosdz*sindx; J[midx(5, 1, 16)] = -sindz*cosdy*sindx; J[midx(5, 2, 16)] = -sindz*sindy*cosdx - sindz*cosdx; //element (2, 1) J[midx(6, 0, 16)] = -cosdy*cosdx; J[midx(6, 1, 16)] = sindy*sindx; //element (3, 0) J[midx(8, 0, 16)] = cosdz*sindy*sindx + sindz*cosdx; J[midx(8, 1, 16)] = -cosdz*cosdy*cosdx; J[midx(8, 2, 16)] = sindz*sindy*cosdx + cosdz*sindx; //element (3, 1) J[midx(9, 0, 16)] = -sindz*sindy*sindx + cosdz*cosdx; J[midx(9, 1, 16)] = sindz*cosdy*cosdx; J[midx(9, 2, 16)] = cosdz*sindy*cosdx - sindz*sindx; //elelment (3, 2) J[midx(10, 0, 16)] = -cosdy*sindx; J[midx(10, 1, 16)] = -sindy*cosdx; //element (4, 0) J[midx(12, 0, 16)] = -(J[midx(0, 0, 16)]*dx + J[midx(4, 0, 16)]*dy + J[midx(8, 0, 16)]*dz); J[midx(12, 1, 16)] = -(J[midx(0, 1, 16)]*dx + J[midx(4, 1, 16)]*dy + J[midx(8, 1, 16)]*dz); J[midx(12, 2, 16)] = -(J[midx(0, 2, 16)]*dx + J[midx(4, 2, 16)]*dy + J[midx(8, 2, 16)]*dz); J[midx(12, 3, 16)] = -(cosdz*cosdy); J[midx(12, 4, 16)] = -(cosdz*sindy*sindx + sindz*cosdx); J[midx(12, 5, 16)] = -(-cosdz*sindy*cosdx + sindz*sindx); //element (5, 0) J[midx(13, 0, 16)] = -(J[midx(1, 0, 16)]*dx + J[midx(5, 0, 16)]*dy + J[midx(9, 0, 16)]*dz); J[midx(13, 1, 16)] = -(J[midx(1, 1, 16)]*dx + J[midx(5, 1, 16)]*dy + J[midx(9, 1, 16)]*dz); J[midx(13, 2, 16)] = -(J[midx(1, 2, 16)]*dx + J[midx(5, 2, 16)]*dy + J[midx(9, 2, 16)]*dz); J[midx(13, 3, 16)] = -(sindz*cosdy); J[midx(13, 4, 16)] = -(sindz*sindy*sindx + cosdz*cosdx); J[midx(13, 5, 16)] = -(sindz*sindy*cosdx + cosdz*sindx); //element (6, 0) J[midx(14, 0, 16)] = -(J[midx(2, 0, 16)]*dx + J[midx(6, 0, 16)]*dy + J[midx(10, 0, 16)]*dz); J[midx(14, 1, 16)] = -(J[midx(2, 1, 16)]*dx + J[midx(6, 1, 16)]*dy + J[midx(10, 1, 16)]*dz); J[midx(14, 2, 16)] = -(J[midx(2, 2, 16)]*dx + J[midx(6, 2, 16)]*dy + J[midx(10, 2, 16)]*dz); J[midx(14, 3, 16)] = -(sindy); J[midx(14, 4, 16)] = -(-cosdy*sindx); J[midx(14, 5, 16)] = -(cosdy*cosdx); double Q[6*6]; for (i = 0; i < 6; i++) { for (j = 0; j < 6; j++) { Q[midx(i, j, 6)] = 0.0; } } Q[midx(0, 0, 6)] = var_wx; Q[midx(1, 1, 6)] = var_wy; Q[midx(2, 2, 6)] = var_wz; Q[midx(3, 3, 6)] = var_vx; Q[midx(4, 4, 6)] = var_vy; Q[midx(5, 5, 6)] = var_vz; //calculate the covariance of each element of the transformation matrix as JQJ' double JQ[16*6]; for (i = 0; i < 16; i++) { for (j = 0; j < 6; j++) { JQ[midx(i, j, 16)] = 0.0; for (k = 0; k < 6; k++) { JQ[midx(i, j, 16)] += J[midx(i, k, 16)]*Q[midx(k, j, 6)]; } } } for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { oVehicleTransformation->PTT[midx(i, j, 16)] = 0.0; for (k = 0; k < 6; k++) { oVehicleTransformation->PTT[midx(i, j, 16)] += JQ[midx(i, k, 16)]*J[midx(j, k, 16)]; } } } //done using the relative pose queue LeaveCriticalSection(&mQueueLock); //if code gets here, oVehicleTransformation has been set correctly rSuccess = true; return rSuccess; }
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 919 ] ] ]
598799db85b14ff453082d754058b429faedd1af
50dcdd1446d5de7551c5b55c58b79823e8bdc9a0
/jni/SampleUtils.h
3df02c92828c2221be44ec0d9b0701c28dffcd99
[]
no_license
CryptArc/ntu-nmlab-visualsonic
bcf494f3e0cf43bff5461335ad2cccd4a6d7f8f2
0589f5411782b965b346fd5733461d326db9f9ba
refs/heads/master
2021-01-10T18:19:11.490692
2011-01-15T14:27:39
2011-01-15T14:27:39
53,777,527
0
0
null
null
null
null
UTF-8
C++
false
false
2,004
h
/*============================================================================== Copyright (c) 2010 QUALCOMM Incorporated. All Rights Reserved. Qualcomm Confidential and Proprietary @file SampleUtils.h @brief A utility class. ==============================================================================*/ #ifndef _QCAR_SAMPLEUTILS_H_ #define _QCAR_SAMPLEUTILS_H_ // Includes: #include <stdio.h> #include <android/log.h> // Utility for logging: #define LOG_TAG "QCAR" #define LOG(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) /// A utility class used by the QCAR SDK samples. class SampleUtils { public: /// Prints a 4x4 matrix. static void printMatrix(const float* matrix); /// Prints GL error information. static void checkGlError(const char* operation); /// Set the rotation components of this 4x4 matrix. static void setRotationMatrix(float angle, float x, float y, float z, float *nMatrix); /// Set the translation components of this 4x4 matrix. static void translatePoseMatrix(float x, float y, float z, float* nMatrix = NULL); /// Applies a rotation. static void rotatePoseMatrix(float angle, float x, float y, float z, float* nMatrix = NULL); /// Applies a scaling transformation. static void scalePoseMatrix(float x, float y, float z, float* nMatrix = NULL); /// Multiplies the two matrices A and B and writes the result to C. static void multiplyMatrix(float *matrixA, float *matrixB, float *matrixC); /// Initialize a shader. static unsigned int initShader(unsigned int shaderType, const char* source); /// Create a shader program. static unsigned int createProgramFromBuffer(const char* vertexShaderBuffer, const char* fragmentShaderBuffer); }; #endif // _QCAR_SAMPLEUTILS_H_
[ [ [ 1, 66 ] ] ]
3c9a7c879cb54d9a521dafa1496fb37eec026f54
10c14a95421b63a71c7c99adf73e305608c391bf
/gui/image/qpnghandler_p.h
fd9e074a8d94068a96738618b4d19a397912d8ea
[]
no_license
eaglezzb/wtlcontrols
73fccea541c6ef1f6db5600f5f7349f5c5236daa
61b7fce28df1efe4a1d90c0678ec863b1fd7c81c
refs/heads/master
2021-01-22T13:47:19.456110
2009-05-19T10:58:42
2009-05-19T10:58:42
33,811,815
0
0
null
null
null
null
UTF-8
C++
false
false
2,993
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPNGHANDLER_P_H #define QPNGHANDLER_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of the QLibrary class. This header file may change from // version to version without notice, or even be removed. // // We mean it. // #include "QtGui/qimageiohandler.h" #ifndef QT_NO_IMAGEFORMAT_PNG QT_BEGIN_NAMESPACE class QPngHandlerPrivate; class QPngHandler : public QImageIOHandler { public: QPngHandler(); ~QPngHandler(); bool canRead() const; bool read(QImage *image); bool write(const QImage &image); QByteArray name() const; QVariant option(ImageOption option) const; void setOption(ImageOption option, const QVariant &value); bool supportsOption(ImageOption option) const; static bool canRead(QIODevice *device); private: QPngHandlerPrivate *d; }; QT_END_NAMESPACE #endif // QT_NO_IMAGEFORMAT_PNG #endif // QPNGHANDLER_P_H
[ "zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7" ]
[ [ [ 1, 88 ] ] ]
cfbe218924008ce883ba3694933d206b00214ca0
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Compilers/PTXCCDefs.hpp
bb6c4c802d14de1f768085d3272b4b93b61f9942
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
5,454
hpp
/* * Copyright 1999-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: PTXCCDefs.hpp,v $ * Revision 1.6 2004/09/08 13:56:32 peiyongz * Apache License Version 2.0 * * Revision 1.5 2002/11/04 14:45:20 tng * C++ Namespace Support. * * Revision 1.4 2002/05/28 12:57:17 tng * Fix typo. * * Revision 1.3 2002/05/27 18:02:40 tng * define XMLSize_t, XMLSSize_t and their associate MAX * * Revision 1.2 2002/05/21 19:45:53 tng * Define DOMSize_t and XMLSize_t * * Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz * sane_include * * Revision 1.3 2001/03/02 20:53:05 knoaman * Schema: Regular expression - misc. updates for error messages, * and additions of new functions to XMLString class. * * Revision 1.2 2000/04/04 21:07:39 abagchi * Fixed copyrights with initial checkin * */ #if !defined(PTXCCDEFS_HPP) #define PTXCCDEFS_HPP // --------------------------------------------------------------------------- // Include some runtime files that will be needed product wide // --------------------------------------------------------------------------- #include <sys/types.h> // for size_t and ssize_t #include <limits.h> // for MAX of size_t and ssize_t // --------------------------------------------------------------------------- // A define in the build for each project is also used to control whether // the export keyword is from the project's viewpoint or the client's. // These defines provide the platform specific keywords that they need // to do this. // --------------------------------------------------------------------------- #define PLATFORM_EXPORT #define PLATFORM_IMPORT // --------------------------------------------------------------------------- // Indicate that we do not support native bools // If the compiler can handle boolean itself, do not define it // --------------------------------------------------------------------------- // #define NO_NATIVE_BOOL // --------------------------------------------------------------------------- // Each compiler might support L"" prefixed constants. There are places // where it is advantageous to use the L"" where it supported, to avoid // unnecessary transcoding. // If your compiler does not support it, don't define this. // --------------------------------------------------------------------------- // #define XML_LSTRSUPPORT // --------------------------------------------------------------------------- // Indicate that we support C++ namespace // Do not define it if the compile cannot handle C++ namespace // --------------------------------------------------------------------------- // #define XERCES_HAS_CPP_NAMESPACE // --------------------------------------------------------------------------- // Define our version of the XML character // --------------------------------------------------------------------------- typedef unsigned short XMLCh; // --------------------------------------------------------------------------- // Define unsigned 16 and 32 bits integers // --------------------------------------------------------------------------- typedef unsigned short XMLUInt16; typedef unsigned int XMLUInt32; // --------------------------------------------------------------------------- // Define signed 32 bits integers // --------------------------------------------------------------------------- typedef int XMLInt32; // --------------------------------------------------------------------------- // XMLSize_t is the unsigned integral type. // --------------------------------------------------------------------------- #if defined(_SIZE_T) && defined(SIZE_MAX) && defined(_SSIZE_T) && defined(SSIZE_MAX) typedef size_t XMLSize_t; #define XML_SIZE_MAX SIZE_MAX typedef ssize_t XMLSSize_t; #define XML_SSIZE_MAX SSIZE_MAX #else typedef unsigned long XMLSize_t; #define XML_SIZE_MAX ULONG_MAX typedef long XMLSSize_t; #define XML_SSIZE_MAX LONG_MAX #endif // --------------------------------------------------------------------------- // Force on the Xerces debug token if it was on in the build environment // --------------------------------------------------------------------------- #if defined(_DEBUG) #define XERCES_DEBUG #endif int stricmp(const char* const str1, const char* const str2); int strnicmp(const char* const str1, const char* const str2, const unsigned int count); // --------------------------------------------------------------------------- // The name of the DLL that is built by the system // --------------------------------------------------------------------------- const char* const Xerces_DLLName = "libxerces-c"; #endif //PTXCCDEFS_HPP
[ [ [ 1, 133 ] ] ]
6b3f685e7957faa1421e5ed47c90cf96ecd3e8dc
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_graphics/juce_graphics.cpp
fdcfefc86bd25d8b4b1996ac3fd231d1b0395a96
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
5,061
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifdef __JUCE_GRAPHICS_MODULE_JUCEHEADER__ /* When you add this cpp file to your project, you mustn't include it in a file where you've already included any other headers - just put it inside a file on its own, possibly with your config flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix header files that the compiler may be using. */ #error "Incorrect use of JUCE cpp file" #endif // Your project must contain an AppConfig.h file with your project-specific settings in it, // and your header search path must make it accessible to the module's files. #include "AppConfig.h" #include "../juce_core/native/juce_BasicNativeHeaders.h" #include "juce_graphics.h" //============================================================================== #if JUCE_MAC #import <QuartzCore/QuartzCore.h> #elif JUCE_WINDOWS #if JUCE_USE_DIRECTWRITE /* If you hit a compile error trying to include these files, you may need to update your version of the Windows SDK to the latest one. The DirectWrite and Direct2D headers are in the version 7 SDKs. */ #include <d2d1.h> #include <dwrite.h> #endif #elif JUCE_IOS #import <QuartzCore/QuartzCore.h> #import <CoreText/CoreText.h> #elif JUCE_LINUX #include <ft2build.h> #include FT_FREETYPE_H #undef SIZEOF #endif //============================================================================== // START_AUTOINCLUDE colour/*.cpp, geometry/*.cpp, placement/*.cpp, contexts/*.cpp, images/*.cpp, // image_formats/*.cpp, fonts/*.cpp, effects/*.cpp #include "colour/juce_Colour.cpp" #include "colour/juce_ColourGradient.cpp" #include "colour/juce_Colours.cpp" #include "colour/juce_FillType.cpp" #include "geometry/juce_AffineTransform.cpp" #include "geometry/juce_EdgeTable.cpp" #include "geometry/juce_Path.cpp" #include "geometry/juce_PathIterator.cpp" #include "geometry/juce_PathStrokeType.cpp" #include "geometry/juce_RectangleList.cpp" #include "placement/juce_Justification.cpp" #include "placement/juce_RectanglePlacement.cpp" #include "contexts/juce_GraphicsContext.cpp" #include "contexts/juce_LowLevelGraphicsPostScriptRenderer.cpp" #include "contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp" #include "images/juce_Image.cpp" #include "images/juce_ImageCache.cpp" #include "images/juce_ImageConvolutionKernel.cpp" #include "images/juce_ImageFileFormat.cpp" #include "image_formats/juce_GIFLoader.cpp" #include "image_formats/juce_JPEGLoader.cpp" #include "image_formats/juce_PNGLoader.cpp" #include "fonts/juce_AttributedString.cpp" #include "fonts/juce_CustomTypeface.cpp" #include "fonts/juce_Font.cpp" #include "fonts/juce_GlyphArrangement.cpp" #include "fonts/juce_TextLayout.cpp" #include "fonts/juce_Typeface.cpp" #include "effects/juce_DropShadowEffect.cpp" #include "effects/juce_GlowEffect.cpp" // END_AUTOINCLUDE //============================================================================== BEGIN_JUCE_NAMESPACE #if JUCE_MAC || JUCE_IOS #include "../juce_core/native/juce_osx_ObjCHelpers.h" #include "../juce_core/native/juce_mac_ObjCSuffix.h" #include "native/juce_mac_CoreGraphicsHelpers.h" #include "native/juce_mac_Fonts.mm" #include "native/juce_mac_CoreGraphicsContext.mm" #elif JUCE_WINDOWS #include "../juce_core/native/juce_win32_ComSmartPtr.h" #if JUCE_DIRECT2D #include "native/juce_win32_Direct2DGraphicsContext.cpp" #endif #include "native/juce_win32_DirectWriteTypeface.cpp" #include "native/juce_win32_DirectWriteTypeLayout.cpp" #include "native/juce_win32_Fonts.cpp" #elif JUCE_LINUX #include "native/juce_linux_Fonts.cpp" #elif JUCE_ANDROID #include "../juce_core/native/juce_android_JNIHelpers.h" #include "native/juce_android_GraphicsContext.cpp" #include "native/juce_android_Fonts.cpp" #endif END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 130 ] ] ]
43e19642ba7b42c6a2bc549ac8dea27327eb03f5
81b7033dd0d0203290795b51513a4014b084d39d
/hash/rmd256.h
62da26033f748c797c845b09caa0c59c4932b905
[]
no_license
starcid/lua-binding-libraries
d27f5c2fccfeae2d667fdb60c86c3244d9ddc065
e33c85f773d88d3b31b026464066264820e4c302
refs/heads/master
2016-08-04T19:57:05.839477
2010-11-15T12:02:08
2010-11-15T12:02:08
35,589,712
0
0
null
null
null
null
UTF-8
C++
false
false
9,810
h
#ifndef HASH_RIPEMD256_H_ #define HASH_RIPEMD256_H_ /* the four basic functions F(), G() and H() */ #define RMD256F(x, y, z) ((x) ^ (y) ^ (z)) #define RMD256G(x, y, z) (((x) & (y)) | (~(x) & (z))) #define RMD256H(x, y, z) (((x) | ~(y)) ^ (z)) #define RMD256I(x, y, z) (((x) & (z)) | ((y) & ~(z))) /* the eight basic operations FF() through III() */ #define RMD256FF(a, b, c, d, x, s) \ (a) += RMD256F((b), (c), (d)) + (x);\ (a) = ROLc((a), (s)); #define RMD256GG(a, b, c, d, x, s) \ (a) += RMD256G((b), (c), (d)) + (x) + 0x5a827999UL;\ (a) = ROLc((a), (s)); #define RMD256HH(a, b, c, d, x, s) \ (a) += RMD256H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\ (a) = ROLc((a), (s)); #define RMD256II(a, b, c, d, x, s) \ (a) += RMD256I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\ (a) = ROLc((a), (s)); #define RMD256FFF(a, b, c, d, x, s) \ (a) += RMD256F((b), (c), (d)) + (x);\ (a) = ROLc((a), (s)); #define RMD256GGG(a, b, c, d, x, s) \ (a) += RMD256G((b), (c), (d)) + (x) + 0x6d703ef3UL;\ (a) = ROLc((a), (s)); #define RMD256HHH(a, b, c, d, x, s) \ (a) += RMD256H((b), (c), (d)) + (x) + 0x5c4dd124UL;\ (a) = ROLc((a), (s)); #define RMD256III(a, b, c, d, x, s) \ (a) += RMD256I((b), (c), (d)) + (x) + 0x50a28be6UL;\ (a) = ROLc((a), (s)); struct RMD256_CTX { ulong64 length; unsigned char buf[64]; ulong32 curlen, state[8]; }; class CRMD256 : public CHashUpdate<CRMD256> { RMD256_CTX m_context; public: enum { nDigestLength =16 }; int Compress(unsigned char *buf) { ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,tmp,X[16]; int i; /* load words X */ for (i = 0; i < 16; i++) { LOAD32L(X[i], buf + (4 * i)); } /* load state */ aa = m_context.state[0]; bb = m_context.state[1]; cc = m_context.state[2]; dd = m_context.state[3]; aaa = m_context.state[4]; bbb = m_context.state[5]; ccc = m_context.state[6]; ddd = m_context.state[7]; /* round 1 */ RMD256FF(aa, bb, cc, dd, X[ 0], 11); RMD256FF(dd, aa, bb, cc, X[ 1], 14); RMD256FF(cc, dd, aa, bb, X[ 2], 15); RMD256FF(bb, cc, dd, aa, X[ 3], 12); RMD256FF(aa, bb, cc, dd, X[ 4], 5); RMD256FF(dd, aa, bb, cc, X[ 5], 8); RMD256FF(cc, dd, aa, bb, X[ 6], 7); RMD256FF(bb, cc, dd, aa, X[ 7], 9); RMD256FF(aa, bb, cc, dd, X[ 8], 11); RMD256FF(dd, aa, bb, cc, X[ 9], 13); RMD256FF(cc, dd, aa, bb, X[10], 14); RMD256FF(bb, cc, dd, aa, X[11], 15); RMD256FF(aa, bb, cc, dd, X[12], 6); RMD256FF(dd, aa, bb, cc, X[13], 7); RMD256FF(cc, dd, aa, bb, X[14], 9); RMD256FF(bb, cc, dd, aa, X[15], 8); /* parallel round 1 */ RMD256III(aaa, bbb, ccc, ddd, X[ 5], 8); RMD256III(ddd, aaa, bbb, ccc, X[14], 9); RMD256III(ccc, ddd, aaa, bbb, X[ 7], 9); RMD256III(bbb, ccc, ddd, aaa, X[ 0], 11); RMD256III(aaa, bbb, ccc, ddd, X[ 9], 13); RMD256III(ddd, aaa, bbb, ccc, X[ 2], 15); RMD256III(ccc, ddd, aaa, bbb, X[11], 15); RMD256III(bbb, ccc, ddd, aaa, X[ 4], 5); RMD256III(aaa, bbb, ccc, ddd, X[13], 7); RMD256III(ddd, aaa, bbb, ccc, X[ 6], 7); RMD256III(ccc, ddd, aaa, bbb, X[15], 8); RMD256III(bbb, ccc, ddd, aaa, X[ 8], 11); RMD256III(aaa, bbb, ccc, ddd, X[ 1], 14); RMD256III(ddd, aaa, bbb, ccc, X[10], 14); RMD256III(ccc, ddd, aaa, bbb, X[ 3], 12); RMD256III(bbb, ccc, ddd, aaa, X[12], 6); tmp = aa; aa = aaa; aaa = tmp; /* round 2 */ RMD256GG(aa, bb, cc, dd, X[ 7], 7); RMD256GG(dd, aa, bb, cc, X[ 4], 6); RMD256GG(cc, dd, aa, bb, X[13], 8); RMD256GG(bb, cc, dd, aa, X[ 1], 13); RMD256GG(aa, bb, cc, dd, X[10], 11); RMD256GG(dd, aa, bb, cc, X[ 6], 9); RMD256GG(cc, dd, aa, bb, X[15], 7); RMD256GG(bb, cc, dd, aa, X[ 3], 15); RMD256GG(aa, bb, cc, dd, X[12], 7); RMD256GG(dd, aa, bb, cc, X[ 0], 12); RMD256GG(cc, dd, aa, bb, X[ 9], 15); RMD256GG(bb, cc, dd, aa, X[ 5], 9); RMD256GG(aa, bb, cc, dd, X[ 2], 11); RMD256GG(dd, aa, bb, cc, X[14], 7); RMD256GG(cc, dd, aa, bb, X[11], 13); RMD256GG(bb, cc, dd, aa, X[ 8], 12); /* parallel round 2 */ RMD256HHH(aaa, bbb, ccc, ddd, X[ 6], 9); RMD256HHH(ddd, aaa, bbb, ccc, X[11], 13); RMD256HHH(ccc, ddd, aaa, bbb, X[ 3], 15); RMD256HHH(bbb, ccc, ddd, aaa, X[ 7], 7); RMD256HHH(aaa, bbb, ccc, ddd, X[ 0], 12); RMD256HHH(ddd, aaa, bbb, ccc, X[13], 8); RMD256HHH(ccc, ddd, aaa, bbb, X[ 5], 9); RMD256HHH(bbb, ccc, ddd, aaa, X[10], 11); RMD256HHH(aaa, bbb, ccc, ddd, X[14], 7); RMD256HHH(ddd, aaa, bbb, ccc, X[15], 7); RMD256HHH(ccc, ddd, aaa, bbb, X[ 8], 12); RMD256HHH(bbb, ccc, ddd, aaa, X[12], 7); RMD256HHH(aaa, bbb, ccc, ddd, X[ 4], 6); RMD256HHH(ddd, aaa, bbb, ccc, X[ 9], 15); RMD256HHH(ccc, ddd, aaa, bbb, X[ 1], 13); RMD256HHH(bbb, ccc, ddd, aaa, X[ 2], 11); tmp = bb; bb = bbb; bbb = tmp; /* round 3 */ RMD256HH(aa, bb, cc, dd, X[ 3], 11); RMD256HH(dd, aa, bb, cc, X[10], 13); RMD256HH(cc, dd, aa, bb, X[14], 6); RMD256HH(bb, cc, dd, aa, X[ 4], 7); RMD256HH(aa, bb, cc, dd, X[ 9], 14); RMD256HH(dd, aa, bb, cc, X[15], 9); RMD256HH(cc, dd, aa, bb, X[ 8], 13); RMD256HH(bb, cc, dd, aa, X[ 1], 15); RMD256HH(aa, bb, cc, dd, X[ 2], 14); RMD256HH(dd, aa, bb, cc, X[ 7], 8); RMD256HH(cc, dd, aa, bb, X[ 0], 13); RMD256HH(bb, cc, dd, aa, X[ 6], 6); RMD256HH(aa, bb, cc, dd, X[13], 5); RMD256HH(dd, aa, bb, cc, X[11], 12); RMD256HH(cc, dd, aa, bb, X[ 5], 7); RMD256HH(bb, cc, dd, aa, X[12], 5); /* parallel round 3 */ RMD256GGG(aaa, bbb, ccc, ddd, X[15], 9); RMD256GGG(ddd, aaa, bbb, ccc, X[ 5], 7); RMD256GGG(ccc, ddd, aaa, bbb, X[ 1], 15); RMD256GGG(bbb, ccc, ddd, aaa, X[ 3], 11); RMD256GGG(aaa, bbb, ccc, ddd, X[ 7], 8); RMD256GGG(ddd, aaa, bbb, ccc, X[14], 6); RMD256GGG(ccc, ddd, aaa, bbb, X[ 6], 6); RMD256GGG(bbb, ccc, ddd, aaa, X[ 9], 14); RMD256GGG(aaa, bbb, ccc, ddd, X[11], 12); RMD256GGG(ddd, aaa, bbb, ccc, X[ 8], 13); RMD256GGG(ccc, ddd, aaa, bbb, X[12], 5); RMD256GGG(bbb, ccc, ddd, aaa, X[ 2], 14); RMD256GGG(aaa, bbb, ccc, ddd, X[10], 13); RMD256GGG(ddd, aaa, bbb, ccc, X[ 0], 13); RMD256GGG(ccc, ddd, aaa, bbb, X[ 4], 7); RMD256GGG(bbb, ccc, ddd, aaa, X[13], 5); tmp = cc; cc = ccc; ccc = tmp; /* round 4 */ RMD256II(aa, bb, cc, dd, X[ 1], 11); RMD256II(dd, aa, bb, cc, X[ 9], 12); RMD256II(cc, dd, aa, bb, X[11], 14); RMD256II(bb, cc, dd, aa, X[10], 15); RMD256II(aa, bb, cc, dd, X[ 0], 14); RMD256II(dd, aa, bb, cc, X[ 8], 15); RMD256II(cc, dd, aa, bb, X[12], 9); RMD256II(bb, cc, dd, aa, X[ 4], 8); RMD256II(aa, bb, cc, dd, X[13], 9); RMD256II(dd, aa, bb, cc, X[ 3], 14); RMD256II(cc, dd, aa, bb, X[ 7], 5); RMD256II(bb, cc, dd, aa, X[15], 6); RMD256II(aa, bb, cc, dd, X[14], 8); RMD256II(dd, aa, bb, cc, X[ 5], 6); RMD256II(cc, dd, aa, bb, X[ 6], 5); RMD256II(bb, cc, dd, aa, X[ 2], 12); /* parallel round 4 */ RMD256FFF(aaa, bbb, ccc, ddd, X[ 8], 15); RMD256FFF(ddd, aaa, bbb, ccc, X[ 6], 5); RMD256FFF(ccc, ddd, aaa, bbb, X[ 4], 8); RMD256FFF(bbb, ccc, ddd, aaa, X[ 1], 11); RMD256FFF(aaa, bbb, ccc, ddd, X[ 3], 14); RMD256FFF(ddd, aaa, bbb, ccc, X[11], 14); RMD256FFF(ccc, ddd, aaa, bbb, X[15], 6); RMD256FFF(bbb, ccc, ddd, aaa, X[ 0], 14); RMD256FFF(aaa, bbb, ccc, ddd, X[ 5], 6); RMD256FFF(ddd, aaa, bbb, ccc, X[12], 9); RMD256FFF(ccc, ddd, aaa, bbb, X[ 2], 12); RMD256FFF(bbb, ccc, ddd, aaa, X[13], 9); RMD256FFF(aaa, bbb, ccc, ddd, X[ 9], 12); RMD256FFF(ddd, aaa, bbb, ccc, X[ 7], 5); RMD256FFF(ccc, ddd, aaa, bbb, X[10], 15); RMD256FFF(bbb, ccc, ddd, aaa, X[14], 8); tmp = dd; dd = ddd; ddd = tmp; /* combine results */ m_context.state[0] += aa; m_context.state[1] += bb; m_context.state[2] += cc; m_context.state[3] += dd; m_context.state[4] += aaa; m_context.state[5] += bbb; m_context.state[6] += ccc; m_context.state[7] += ddd; return 0; } int Init() { m_context.state[0] = 0x67452301UL; m_context.state[1] = 0xefcdab89UL; m_context.state[2] = 0x98badcfeUL; m_context.state[3] = 0x10325476UL; m_context.state[4] = 0x76543210UL; m_context.state[5] = 0xfedcba98UL; m_context.state[6] = 0x89abcdefUL; m_context.state[7] = 0x01234567UL; m_context.curlen = 0; m_context.length = 0; return 0; } int Update(unsigned char * pData, unsigned long ulLen) { return CHashUpdate<CRMD256>::Update(pData, ulLen, m_context.curlen, m_context.length, m_context.buf, sizeof(m_context.buf)); } int Final(unsigned char *pszOut) { int i; if (m_context.curlen >= sizeof(m_context.buf)) { return -1; } /* increase the length of the message */ m_context.length += m_context.curlen * 8; /* append the '1' bit */ m_context.buf[m_context.curlen++] = (unsigned char)0x80; /* if the length is currently above 56 bytes we append zeros * then compress. Then we can fall back to padding zeros and length * encoding like normal. */ if (m_context.curlen > 56) { while (m_context.curlen < 64) { m_context.buf[m_context.curlen++] = (unsigned char)0; } Compress( m_context.buf); m_context.curlen = 0; } /* pad upto 56 bytes of zeroes */ while (m_context.curlen < 56) { m_context.buf[m_context.curlen++] = (unsigned char)0; } /* store length */ STORE64L(m_context.length, m_context.buf+56); Compress( m_context.buf); /* copy output */ for (i = 0; i < 8; i++) { STORE32L(m_context.state[i], pszOut+(4*i)); } return 0; } }; #endif
[ "missdeer@959521e0-e54e-11de-9298-fbd6a473cdd1" ]
[ [ [ 1, 318 ] ] ]
f45c53725f2c757bcd08edca87f16617e0c5c5c4
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestcmdlg/src/bctestcmdlgview.cpp
bc573d646c9c83bf0c9794fae3c8f526fc657c46
[]
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
4,544
cpp
/* * Copyright (c) 2006 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: view class * */ #include <aknviewappui.h> #include "BCTestCmDlg.hrh" #include <BCTestCmDlg.rsg> #include "BCTestCmDlgview.h" #include "BCTestCmDlgcontainer.h" #include "bctestutil.h" #include "BCTestCmDlgcase.h" #include "bctestmemselpage.h" #include "bctestfileseldlg.h" #include "bctestfilenamedlg.h" #include "bctestcommondlg.h" #include "bctestmemselitem.h" // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // Symbian 2nd static Constructor // --------------------------------------------------------------------------- // CBCTestCmDlgView* CBCTestCmDlgView::NewL() { CBCTestCmDlgView* self = new( ELeave ) CBCTestCmDlgView(); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } // --------------------------------------------------------------------------- // C++ default Constructor // --------------------------------------------------------------------------- // CBCTestCmDlgView::CBCTestCmDlgView() { } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestCmDlgView::ConstructL() { BaseConstructL( R_BCTESTCMDLG_VIEW ); iContainer = new( ELeave ) CBCTestCmDlgContainer(); iContainer->SetMopParent( this ); iContainer->ConstructL( ClientRect() ); AppUi()->AddToStackL( *this, iContainer ); iContainer->MakeVisible( ETrue ); iTestUtil = CBCTestUtil::NewL(); // Add test case here. iTestUtil->AddTestCaseL( CBCTestCmDlgCase::NewL(), _L("Mem selection dialog") ); iTestUtil->AddTestCaseL( CBCTestMemSelSettingPage::NewL(), _L("Mem selection setting page") ); iTestUtil->AddTestCaseL( CBCTestFileSelDlg::NewL(), _L("File selection dialog") ); iTestUtil->AddTestCaseL( CBCTestFileNameDlg::NewL(), _L("File name prompt dialog") ); iTestUtil->AddTestCaseL( CBCTestCommonDlg::NewL(), _L("Common dialog") ); iTestUtil->AddTestCaseL( CBCTestMemSelSettingItem::NewL(), _L("Mem selection setting item") ); } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestCmDlgView::~CBCTestCmDlgView() { if ( iContainer ) { AppUi()->RemoveFromStack( iContainer ); } delete iContainer; delete iTestUtil; } // --------------------------------------------------------------------------- // CBCTestCmDlgView::Id // --------------------------------------------------------------------------- // TUid CBCTestCmDlgView::Id() const { return KBCTestCmDlgViewId; } // --------------------------------------------------------------------------- // CBCTestCmDlgView::DoActivateL // --------------------------------------------------------------------------- // void CBCTestCmDlgView::DoActivateL( const TVwsViewId&, TUid, const TDesC8& ) { } // --------------------------------------------------------------------------- // CBCTestCmDlgView::DoDeactivate // --------------------------------------------------------------------------- // void CBCTestCmDlgView::DoDeactivate() { } // --------------------------------------------------------------------------- // CBCTestCmDlgView::HandleCommandL // --------------------------------------------------------------------------- // void CBCTestCmDlgView::HandleCommandL( TInt aCommand ) { switch ( aCommand ) { case EProgCmdAutoTest: iTestUtil->RunL(); break; default: if ( aCommand > EBCTestCmdEmptyOutline && aCommand < EBCTestCmdMaxOutline ) { iTestUtil->RunL( aCommand ); } break; } }
[ "none@none" ]
[ [ [ 1, 145 ] ] ]
192b308ea8019ea9a87acd64ba339501ce7a7023
2514632f2787fd4cba7396f60e49f5968884c688
/LinearMath/btMatrix3x3.h
1547e3d1220a20824916cc010f0337133ff5c7ea
[]
no_license
sabotage3d/pukak
936555b001ac738f80c69d99e3e99b5ba16c3e11
f84f5f683de5a454e233002c9c8a9ae7f2faab6c
refs/heads/master
2021-01-01T15:41:08.973658
2010-04-30T16:43:04
2010-04-30T16:43:04
35,413,544
0
0
null
null
null
null
UTF-8
C++
false
false
21,594
h
/* Copyright (c) 2003-2006 Gino van den Bergen / 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 btMatrix3x3_H #define btMatrix3x3_H #include "btScalar.h" #include "btVector3.h" #include "btQuaternion.h" /**@brief The btMatrix3x3 class implements a 3x3 rotation matrix, to perform linear algebra in combination with btQuaternion, btTransform and btVector3. * Make sure to only include a pure orthogonal matrix without scaling. */ class btMatrix3x3 { public: /** @brief No initializaion constructor */ btMatrix3x3 () {} // explicit btMatrix3x3(const btScalar *m) { setFromOpenGLSubMatrix(m); } /**@brief Constructor from Quaternion */ explicit btMatrix3x3(const btQuaternion& q) { setRotation(q); } /* template <typename btScalar> Matrix3x3(const btScalar& yaw, const btScalar& pitch, const btScalar& roll) { setEulerYPR(yaw, pitch, roll); } */ /** @brief Constructor with row major formatting */ btMatrix3x3(const btScalar& xx, const btScalar& xy, const btScalar& xz, const btScalar& yx, const btScalar& yy, const btScalar& yz, const btScalar& zx, const btScalar& zy, const btScalar& zz) { setValue(xx, xy, xz, yx, yy, yz, zx, zy, zz); } /** @brief Copy constructor */ SIMD_FORCE_INLINE btMatrix3x3 (const btMatrix3x3& other) { m_el[0] = other.m_el[0]; m_el[1] = other.m_el[1]; m_el[2] = other.m_el[2]; } /** @brief Assignment Operator */ SIMD_FORCE_INLINE btMatrix3x3& operator=(const btMatrix3x3& other) { m_el[0] = other.m_el[0]; m_el[1] = other.m_el[1]; m_el[2] = other.m_el[2]; return *this; } /** @brief Get a column of the matrix as a vector * @param i Column number 0 indexed */ SIMD_FORCE_INLINE btVector3 getColumn(int i) const { return btVector3(m_el[0][i],m_el[1][i],m_el[2][i]); } /** @brief Get a row of the matrix as a vector * @param i Row number 0 indexed */ SIMD_FORCE_INLINE const btVector3& getRow(int i) const { btFullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Get a mutable reference to a row of the matrix as a vector * @param i Row number 0 indexed */ SIMD_FORCE_INLINE btVector3& operator[](int i) { btFullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Get a const reference to a row of the matrix as a vector * @param i Row number 0 indexed */ SIMD_FORCE_INLINE const btVector3& operator[](int i) const { btFullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Multiply by the target matrix on the right * @param m Rotation matrix to be applied * Equivilant to this = this * m */ btMatrix3x3& operator*=(const btMatrix3x3& m); /** @brief Set from a carray of btScalars * @param m A pointer to the beginning of an array of 9 btScalars */ void setFromOpenGLSubMatrix(const btScalar *m) { m_el[0].setValue(m[0],m[4],m[8]); m_el[1].setValue(m[1],m[5],m[9]); m_el[2].setValue(m[2],m[6],m[10]); } /** @brief Set the values of the matrix explicitly (row major) * @param xx Top left * @param xy Top Middle * @param xz Top Right * @param yx Middle Left * @param yy Middle Middle * @param yz Middle Right * @param zx Bottom Left * @param zy Bottom Middle * @param zz Bottom Right*/ void setValue(const btScalar& xx, const btScalar& xy, const btScalar& xz, const btScalar& yx, const btScalar& yy, const btScalar& yz, const btScalar& zx, const btScalar& zy, const btScalar& zz) { m_el[0].setValue(xx,xy,xz); m_el[1].setValue(yx,yy,yz); m_el[2].setValue(zx,zy,zz); } /** @brief Set the matrix from a quaternion * @param q The Quaternion to match */ void setRotation(const btQuaternion& q) { btScalar d = q.length2(); btFullAssert(d != btScalar(0.0)); btScalar s = btScalar(2.0) / d; btScalar xs = q.x() * s, ys = q.y() * s, zs = q.z() * s; btScalar wx = q.w() * xs, wy = q.w() * ys, wz = q.w() * zs; btScalar xx = q.x() * xs, xy = q.x() * ys, xz = q.x() * zs; btScalar yy = q.y() * ys, yz = q.y() * zs, zz = q.z() * zs; setValue(btScalar(1.0) - (yy + zz), xy - wz, xz + wy, xy + wz, btScalar(1.0) - (xx + zz), yz - wx, xz - wy, yz + wx, btScalar(1.0) - (xx + yy)); } /** @brief Set the matrix from euler angles using YPR around YXZ respectively * @param yaw Yaw about Y axis * @param pitch Pitch about X axis * @param roll Roll about Z axis */ void setEulerYPR(const btScalar& yaw, const btScalar& pitch, const btScalar& roll) { setEulerZYX(roll, pitch, yaw); } /** @brief Set the matrix from euler angles YPR around ZYX axes * @param eulerX Roll about X axis * @param eulerY Pitch around Y axis * @param eulerZ Yaw aboud Z axis * * These angles are used to produce a rotation matrix. The euler * angles are applied in ZYX order. I.e a vector is first rotated * about X then Y and then Z **/ void setEulerZYX(btScalar eulerX,btScalar eulerY,btScalar eulerZ) { ///@todo proposed to reverse this since it's labeled zyx but takes arguments xyz and it will match all other parts of the code btScalar ci ( btCos(eulerX)); btScalar cj ( btCos(eulerY)); btScalar ch ( btCos(eulerZ)); btScalar si ( btSin(eulerX)); btScalar sj ( btSin(eulerY)); btScalar sh ( btSin(eulerZ)); btScalar cc = ci * ch; btScalar cs = ci * sh; btScalar sc = si * ch; btScalar ss = si * sh; setValue(cj * ch, sj * sc - cs, sj * cc + ss, cj * sh, sj * ss + cc, sj * cs - sc, -sj, cj * si, cj * ci); } /**@brief Set the matrix to the identity */ void setIdentity() { setValue(btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0)); } static const btMatrix3x3& getIdentity() { static const btMatrix3x3 identityMatrix(btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0)); return identityMatrix; } /**@brief Fill the values of the matrix into a 9 element array * @param m The array to be filled */ void getOpenGLSubMatrix(btScalar *m) const { m[0] = btScalar(m_el[0].x()); m[1] = btScalar(m_el[1].x()); m[2] = btScalar(m_el[2].x()); m[3] = btScalar(0.0); m[4] = btScalar(m_el[0].y()); m[5] = btScalar(m_el[1].y()); m[6] = btScalar(m_el[2].y()); m[7] = btScalar(0.0); m[8] = btScalar(m_el[0].z()); m[9] = btScalar(m_el[1].z()); m[10] = btScalar(m_el[2].z()); m[11] = btScalar(0.0); } /**@brief Get the matrix represented as a quaternion * @param q The quaternion which will be set */ void getRotation(btQuaternion& q) const { btScalar trace = m_el[0].x() + m_el[1].y() + m_el[2].z(); btScalar temp[4]; if (trace > btScalar(0.0)) { btScalar s = btSqrt(trace + btScalar(1.0)); temp[3]=(s * btScalar(0.5)); s = btScalar(0.5) / s; temp[0]=((m_el[2].y() - m_el[1].z()) * s); temp[1]=((m_el[0].z() - m_el[2].x()) * s); temp[2]=((m_el[1].x() - m_el[0].y()) * s); } else { int i = m_el[0].x() < m_el[1].y() ? (m_el[1].y() < m_el[2].z() ? 2 : 1) : (m_el[0].x() < m_el[2].z() ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; btScalar s = btSqrt(m_el[i][i] - m_el[j][j] - m_el[k][k] + btScalar(1.0)); temp[i] = s * btScalar(0.5); s = btScalar(0.5) / s; temp[3] = (m_el[k][j] - m_el[j][k]) * s; temp[j] = (m_el[j][i] + m_el[i][j]) * s; temp[k] = (m_el[k][i] + m_el[i][k]) * s; } q.setValue(temp[0],temp[1],temp[2],temp[3]); } /**@brief Get the matrix represented as euler angles around YXZ, roundtrip with setEulerYPR * @param yaw Yaw around Y axis * @param pitch Pitch around X axis * @param roll around Z axis */ void getEulerYPR(btScalar& yaw, btScalar& pitch, btScalar& roll) const { // first use the normal calculus yaw = btScalar(btAtan2(m_el[1].x(), m_el[0].x())); pitch = btScalar(btAsin(-m_el[2].x())); roll = btScalar(btAtan2(m_el[2].y(), m_el[2].z())); // on pitch = +/-HalfPI if (btFabs(pitch)==SIMD_HALF_PI) { if (yaw>0) yaw-=SIMD_PI; else yaw+=SIMD_PI; if (roll>0) roll-=SIMD_PI; else roll+=SIMD_PI; } }; /**@brief Get the matrix represented as euler angles around ZYX * @param yaw Yaw around X axis * @param pitch Pitch around Y axis * @param roll around X axis * @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/ void getEulerZYX(btScalar& yaw, btScalar& pitch, btScalar& roll, unsigned int solution_number = 1) const { struct Euler{btScalar yaw, pitch, roll;}; Euler euler_out; Euler euler_out2; //second solution //get the pointer to the raw data // Check that pitch is not at a singularity if (btFabs(m_el[2].x()) >= 1) { euler_out.yaw = 0; euler_out2.yaw = 0; // From difference of angles formula btScalar delta = btAtan2(m_el[0].x(),m_el[0].z()); if (m_el[2].x() > 0) //gimbal locked up { euler_out.pitch = SIMD_PI / btScalar(2.0); euler_out2.pitch = SIMD_PI / btScalar(2.0); euler_out.roll = euler_out.pitch + delta; euler_out2.roll = euler_out.pitch + delta; } else // gimbal locked down { euler_out.pitch = -SIMD_PI / btScalar(2.0); euler_out2.pitch = -SIMD_PI / btScalar(2.0); euler_out.roll = -euler_out.pitch + delta; euler_out2.roll = -euler_out.pitch + delta; } } else { euler_out.pitch = - btAsin(m_el[2].x()); euler_out2.pitch = SIMD_PI - euler_out.pitch; euler_out.roll = btAtan2(m_el[2].y()/btCos(euler_out.pitch), m_el[2].z()/btCos(euler_out.pitch)); euler_out2.roll = btAtan2(m_el[2].y()/btCos(euler_out2.pitch), m_el[2].z()/btCos(euler_out2.pitch)); euler_out.yaw = btAtan2(m_el[1].x()/btCos(euler_out.pitch), m_el[0].x()/btCos(euler_out.pitch)); euler_out2.yaw = btAtan2(m_el[1].x()/btCos(euler_out2.pitch), m_el[0].x()/btCos(euler_out2.pitch)); } if (solution_number == 1) { yaw = euler_out.yaw; pitch = euler_out.pitch; roll = euler_out.roll; } else { yaw = euler_out2.yaw; pitch = euler_out2.pitch; roll = euler_out2.roll; } } /**@brief Create a scaled copy of the matrix * @param s Scaling vector The elements of the vector will scale each column */ btMatrix3x3 scaled(const btVector3& s) const { return btMatrix3x3(m_el[0].x() * s.x(), m_el[0].y() * s.y(), m_el[0].z() * s.z(), m_el[1].x() * s.x(), m_el[1].y() * s.y(), m_el[1].z() * s.z(), m_el[2].x() * s.x(), m_el[2].y() * s.y(), m_el[2].z() * s.z()); } /**@brief Return the determinant of the matrix */ btScalar determinant() const; /**@brief Return the adjoint of the matrix */ btMatrix3x3 adjoint() const; /**@brief Return the matrix with all values non negative */ btMatrix3x3 absolute() const; /**@brief Return the transpose of the matrix */ btMatrix3x3 transpose() const; /**@brief Return the inverse of the matrix */ btMatrix3x3 inverse() const; btMatrix3x3 transposeTimes(const btMatrix3x3& m) const; btMatrix3x3 timesTranspose(const btMatrix3x3& m) const; SIMD_FORCE_INLINE btScalar tdotx(const btVector3& v) const { return m_el[0].x() * v.x() + m_el[1].x() * v.y() + m_el[2].x() * v.z(); } SIMD_FORCE_INLINE btScalar tdoty(const btVector3& v) const { return m_el[0].y() * v.x() + m_el[1].y() * v.y() + m_el[2].y() * v.z(); } SIMD_FORCE_INLINE btScalar tdotz(const btVector3& v) const { return m_el[0].z() * v.x() + m_el[1].z() * v.y() + m_el[2].z() * v.z(); } /**@brief diagonalizes this matrix by the Jacobi method. * @param rot stores the rotation from the coordinate system in which the matrix is diagonal to the original * coordinate system, i.e., old_this = rot * new_this * rot^T. * @param threshold See iteration * @param iteration The iteration stops when all off-diagonal elements are less than the threshold multiplied * by the sum of the absolute values of the diagonal, or when maxSteps have been executed. * * Note that this matrix is assumed to be symmetric. */ void diagonalize(btMatrix3x3& rot, btScalar threshold, int maxSteps) { rot.setIdentity(); for (int step = maxSteps; step > 0; step--) { // find off-diagonal element [p][q] with largest magnitude int p = 0; int q = 1; int r = 2; btScalar max = btFabs(m_el[0][1]); btScalar v = btFabs(m_el[0][2]); if (v > max) { q = 2; r = 1; max = v; } v = btFabs(m_el[1][2]); if (v > max) { p = 1; q = 2; r = 0; max = v; } btScalar t = threshold * (btFabs(m_el[0][0]) + btFabs(m_el[1][1]) + btFabs(m_el[2][2])); if (max <= t) { if (max <= SIMD_EPSILON * t) { return; } step = 1; } // compute Jacobi rotation J which leads to a zero for element [p][q] btScalar mpq = m_el[p][q]; btScalar theta = (m_el[q][q] - m_el[p][p]) / (2 * mpq); btScalar theta2 = theta * theta; btScalar cos; btScalar sin; if (theta2 * theta2 < btScalar(10 / SIMD_EPSILON)) { t = (theta >= 0) ? 1 / (theta + btSqrt(1 + theta2)) : 1 / (theta - btSqrt(1 + theta2)); cos = 1 / btSqrt(1 + t * t); sin = cos * t; } else { // approximation for large theta-value, i.e., a nearly diagonal matrix t = 1 / (theta * (2 + btScalar(0.5) / theta2)); cos = 1 - btScalar(0.5) * t * t; sin = cos * t; } // apply rotation to matrix (this = J^T * this * J) m_el[p][q] = m_el[q][p] = 0; m_el[p][p] -= t * mpq; m_el[q][q] += t * mpq; btScalar mrp = m_el[r][p]; btScalar mrq = m_el[r][q]; m_el[r][p] = m_el[p][r] = cos * mrp - sin * mrq; m_el[r][q] = m_el[q][r] = cos * mrq + sin * mrp; // apply rotation to rot (rot = rot * J) for (int i = 0; i < 3; i++) { btVector3& row = rot[i]; mrp = row[p]; mrq = row[q]; row[p] = cos * mrp - sin * mrq; row[q] = cos * mrq + sin * mrp; } } } protected: /**@brief Calculate the matrix cofactor * @param r1 The first row to use for calculating the cofactor * @param c1 The first column to use for calculating the cofactor * @param r1 The second row to use for calculating the cofactor * @param c1 The second column to use for calculating the cofactor * See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for more details */ btScalar cofac(int r1, int c1, int r2, int c2) const { return m_el[r1][c1] * m_el[r2][c2] - m_el[r1][c2] * m_el[r2][c1]; } ///Data storage for the matrix, each vector is a row of the matrix btVector3 m_el[3]; }; SIMD_FORCE_INLINE btMatrix3x3& btMatrix3x3::operator*=(const btMatrix3x3& m) { setValue(m.tdotx(m_el[0]), m.tdoty(m_el[0]), m.tdotz(m_el[0]), m.tdotx(m_el[1]), m.tdoty(m_el[1]), m.tdotz(m_el[1]), m.tdotx(m_el[2]), m.tdoty(m_el[2]), m.tdotz(m_el[2])); return *this; } SIMD_FORCE_INLINE btScalar btMatrix3x3::determinant() const { return btTriple((*this)[0], (*this)[1], (*this)[2]); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::absolute() const { return btMatrix3x3( btFabs(m_el[0].x()), btFabs(m_el[0].y()), btFabs(m_el[0].z()), btFabs(m_el[1].x()), btFabs(m_el[1].y()), btFabs(m_el[1].z()), btFabs(m_el[2].x()), btFabs(m_el[2].y()), btFabs(m_el[2].z())); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::transpose() const { return btMatrix3x3(m_el[0].x(), m_el[1].x(), m_el[2].x(), m_el[0].y(), m_el[1].y(), m_el[2].y(), m_el[0].z(), m_el[1].z(), m_el[2].z()); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::adjoint() const { return btMatrix3x3(cofac(1, 1, 2, 2), cofac(0, 2, 2, 1), cofac(0, 1, 1, 2), cofac(1, 2, 2, 0), cofac(0, 0, 2, 2), cofac(0, 2, 1, 0), cofac(1, 0, 2, 1), cofac(0, 1, 2, 0), cofac(0, 0, 1, 1)); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::inverse() const { btVector3 co(cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)); btScalar det = (*this)[0].dot(co); btFullAssert(det != btScalar(0.0)); btScalar s = btScalar(1.0) / det; return btMatrix3x3(co.x() * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s, co.y() * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s, co.z() * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::transposeTimes(const btMatrix3x3& m) const { return btMatrix3x3( m_el[0].x() * m[0].x() + m_el[1].x() * m[1].x() + m_el[2].x() * m[2].x(), m_el[0].x() * m[0].y() + m_el[1].x() * m[1].y() + m_el[2].x() * m[2].y(), m_el[0].x() * m[0].z() + m_el[1].x() * m[1].z() + m_el[2].x() * m[2].z(), m_el[0].y() * m[0].x() + m_el[1].y() * m[1].x() + m_el[2].y() * m[2].x(), m_el[0].y() * m[0].y() + m_el[1].y() * m[1].y() + m_el[2].y() * m[2].y(), m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(), m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(), m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(), m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z()); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::timesTranspose(const btMatrix3x3& m) const { return btMatrix3x3( m_el[0].dot(m[0]), m_el[0].dot(m[1]), m_el[0].dot(m[2]), m_el[1].dot(m[0]), m_el[1].dot(m[1]), m_el[1].dot(m[2]), m_el[2].dot(m[0]), m_el[2].dot(m[1]), m_el[2].dot(m[2])); } SIMD_FORCE_INLINE btVector3 operator*(const btMatrix3x3& m, const btVector3& v) { return btVector3(m[0].dot(v), m[1].dot(v), m[2].dot(v)); } SIMD_FORCE_INLINE btVector3 operator*(const btVector3& v, const btMatrix3x3& m) { return btVector3(m.tdotx(v), m.tdoty(v), m.tdotz(v)); } SIMD_FORCE_INLINE btMatrix3x3 operator*(const btMatrix3x3& m1, const btMatrix3x3& m2) { return btMatrix3x3( m2.tdotx( m1[0]), m2.tdoty( m1[0]), m2.tdotz( m1[0]), m2.tdotx( m1[1]), m2.tdoty( m1[1]), m2.tdotz( m1[1]), m2.tdotx( m1[2]), m2.tdoty( m1[2]), m2.tdotz( m1[2])); } /****** READDED BY SETH HOLLADAY 2010-01-16, FROM BULLET 2.74 ******/ SIMD_FORCE_INLINE btMatrix3x3 operator+(const btMatrix3x3& m1, const btMatrix3x3& m2) { return btMatrix3x3( m1[0][0] + m2[0][0], m1[0][1] + m2[0][1], m1[0][2] + m2[0][2], m1[1][0] + m2[1][0], m1[1][1] + m2[1][1], m1[1][2] + m2[1][2], m1[2][0] + m2[2][0], m1[2][1] + m2[2][1], m1[2][2] + m2[2][2] ); } // operator+ /* ************************ */ /* SIMD_FORCE_INLINE btMatrix3x3 btMultTransposeLeft(const btMatrix3x3& m1, const btMatrix3x3& m2) { return btMatrix3x3( m1[0][0] * m2[0][0] + m1[1][0] * m2[1][0] + m1[2][0] * m2[2][0], m1[0][0] * m2[0][1] + m1[1][0] * m2[1][1] + m1[2][0] * m2[2][1], m1[0][0] * m2[0][2] + m1[1][0] * m2[1][2] + m1[2][0] * m2[2][2], m1[0][1] * m2[0][0] + m1[1][1] * m2[1][0] + m1[2][1] * m2[2][0], m1[0][1] * m2[0][1] + m1[1][1] * m2[1][1] + m1[2][1] * m2[2][1], m1[0][1] * m2[0][2] + m1[1][1] * m2[1][2] + m1[2][1] * m2[2][2], m1[0][2] * m2[0][0] + m1[1][2] * m2[1][0] + m1[2][2] * m2[2][0], m1[0][2] * m2[0][1] + m1[1][2] * m2[1][1] + m1[2][2] * m2[2][1], m1[0][2] * m2[0][2] + m1[1][2] * m2[1][2] + m1[2][2] * m2[2][2]); } */ /**@brief Equality operator between two matrices * It will test all elements are equal. */ SIMD_FORCE_INLINE bool operator==(const btMatrix3x3& m1, const btMatrix3x3& m2) { return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] && m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] && m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] ); } #endif
[ "seth.holladay@b0b181a8-020e-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 631 ] ] ]
7812bcee0703bf4192ff148d44f38be1df0ae597
23017336d25e6ec49c4a51f11c1b3a3aa10acf22
/csc3750/prog6/BasicObject.h
cd1bc3a3626ad110a34d9185ca0cc4f85c537654
[]
no_license
tjshaffer21/School
5e7681c96e0c10966fc7362931412c4244507911
4aa5fc3a8bbbbb8d46d045244e8a7f84e71c768f
refs/heads/master
2020-05-27T19:05:06.422314
2011-05-17T19:55:40
2011-05-17T19:55:40
1,681,224
1
1
null
2017-07-29T13:35:54
2011-04-29T15:36:55
C++
UTF-8
C++
false
false
890
h
/** * BasicObject * Thomas Shaffer * 16 September 2009 * Basic object class handles the creation of basic objects (triangles) for * the purpose of creating more complex objects. */ #if !defined (BASICOBJECT_H) #define BASICOBJECT_H #include "Pixel.h" #include "DeleteObject.h" #include "List.h" #include "Matrix.h" #include "Face.h" class Light; class Color; class Vertex; class BasicObject : public DeleteObject { private: List<Face>* faces; List<Vertex>* vertices; public: BasicObject(); virtual ~BasicObject(); void addFace( Face* face ); void addVertex( Vertex* vrt ); void render( Pixel* pix, Matrix* wnd, Matrix* trs, Matrix* zbuffer, Light* light, Vertex* eye, Color* material, Color* amb, double attenuation, double shininess ); }; #endif
[ [ [ 1, 36 ] ] ]
393c31058e7663d95808610024d78b935c2e85ee
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/Qube.h
3c60056991bb77de16a1d3ec388ef79d6ca327c5
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UHC
C++
false
false
2,056
h
/** @file CQube.h @date 2011/09/06 @author @brief 블럭큐브 */ #pragma once class CCharactor; #include "CharCube.h" class CQube : public CCharCube { enum { GROUND = 0, }; private: D3DXVECTOR3 m_vMomentum; ///< 중력 가속도 누적 D3DXVECTOR3 m_vAccelerate; ///< 가속도 const FLOAT m_fItemLift; ///< 최소 가속도 //VOID Translate(); public: CQube(); virtual ~CQube(); VOID Update( CBoundBox * pBB ); VOID RandMome( D3DXVECTOR3 vMomentum, FLOAT fRate = 0.5f ); private: INT m_nType; ///< 큐브 종류 D3DXVECTOR3 m_vPos; ///< 중심좌표 D3DXVECTOR3 m_vAxisDir[3]; ///< 큐브 세축의 단위벡터 D3DXVECTOR3 m_vRotateTemp; ///< 회전 변화량 D3DXVECTOR3 m_vRotate; ///< 현재 회전량 BOOL m_bVisiable; ///< FLOAT m_fSize; ///< 큐브 반지름 //D3DXMATRIXA16 m_matChara; ///< 생성 당시 캐릭터 월드 매트릭스 행렬 저장 FLOAT m_fHeight; ///< 바닥으로 부터의 높이 보정값 // 속도를 위한 임시 저장소 D3DXVECTOR3 vDir; D3DXVECTOR3 vMomentum; D3DXVECTOR3 vAccelerate; std::vector<CBoundBox*> * vecBoundBox; std::vector<CBoundBox*>::iterator Iter; public: // Get FLOAT GetSize() { return m_fSize; } BOOL GetVisiable() { return m_bVisiable; } D3DXVECTOR3 GetPosition() { return m_vPos; } D3DXVECTOR3 GetAxisDir(INT n) { return m_vAxisDir[n]; } //D3DXMATRIXA16 GetCharMatrix() //{ // return m_matChara; //} // Set VOID SetType( INT nType ) { m_nType = nType; } VOID SetVisiable( BOOL bVisi ) { m_bVisiable = bVisi; } VOID SetPosition( D3DXVECTOR3 vec ) { m_vPos = vec; } //VOID SetCharMatrix( const D3DXMATRIXA16& a_matChara ) //{ // m_matChara = a_matChara; //} VOID SetHeight( FLOAT a_fHeight ) { m_fHeight = a_fHeight; } // temp virtual VOID SetRander(); VOID RanderPos( FLOAT fRate = 10.0f ); VOID RanderRotate( FLOAT fRate = 0.25f ); VOID RanderSize( FLOAT fRate = 1.0f ); BOOL InRect(D3DXVECTOR3 &_vec); };
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 26 ], [ 29, 30 ], [ 32, 37 ], [ 39, 40 ], [ 50, 55 ], [ 60, 61 ], [ 64, 64 ], [ 69, 81 ] ], [ [ 27, 28 ], [ 31, 31 ], [ 38, 38 ], [ 41, 49 ], [ 56, 59 ], [ 62, 63 ], [ 65, 68 ] ] ]
119bc1672e7c6b4ce960ba6e4ee5d0474fff0c6b
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/MyGUI/include/MyGUI_EditText.h
dbad4afe6f1c03472198a3cf9b94039600ea091f
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
4,770
h
/*! @file @author Albert Semenov @date 02/2008 @module *//* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __MYGUI_EDIT_TEXT_H__ #define __MYGUI_EDIT_TEXT_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_XmlDocument.h" #include "MyGUI_Types.h" #include "MyGUI_ISubWidgetText.h" #include "MyGUI_DrawItem.h" #include "MyGUI_Font.h" #include "MyGUI_EnumCharInfo.h" #include "MyGUI_WidgetSkinInfo.h" namespace MyGUI { class RenderItem; class MYGUI_EXPORT EditText : public ISubWidgetText { MYGUI_RTTI_CHILD_HEADER(EditText, ISubWidgetText); public: EditText(const SubWidgetInfo &_info, ICroppedRectangle * _parent); virtual ~EditText(); virtual void setVisible(bool _visible); // обновляет все данные связанные с тектом virtual void updateRawData(); // метод для отрисовки себя virtual size_t _drawItem(Vertex * _vertex, bool _update); void _updateView(); void _correctView(); void _setAlign(const IntSize& _size, bool _update); void _setAlign(const IntCoord& _coord, bool _update); void setCaption(const Ogre::UTFString & _caption); const Ogre::UTFString & getCaption(); void setTextColour(const Colour& _colour); const Colour& getTextColour(); void setAlpha(float _alpha); float getAlpha(); virtual void setFontName(const std::string & _font); virtual const std::string & getFontName(); virtual void setFontHeight(uint _height); virtual uint getFontHeight(); virtual void _createDrawItem(LayerItemKeeper * _keeper, RenderItem * _item); virtual void _destroyDrawItem(); virtual void setTextAlign(Align _align); virtual Align getTextAlign(); virtual size_t getSelectStart(); virtual size_t getSelectEnd(); virtual void setTextSelect(size_t _start, size_t _end); virtual bool getSelectBackground(); virtual void setSelectBackground(bool _normal); virtual bool isCursorShow(); virtual void setShowCursor(bool _show); virtual size_t getCursorPosition(); virtual void setCursorPosition(size_t _pos); virtual IntSize getTextSize(); // устанавливает смещение текста в пикселях virtual void setViewOffset(IntPoint _point); virtual IntPoint getViewOffset(); // возвращает положение курсора по произвольному положению virtual size_t getCursorPosition(const IntPoint & _point); // возвращает положение курсора в обсолютных координатах virtual IntCoord getCursorCoord(size_t _position); void setShiftText(bool _shift); void setBreakLine(bool _break); virtual void _setStateData(StateInfo * _data); // метод для генерации данных из описания xml static StateInfo * createStateData(xml::ElementPtr _node, xml::ElementPtr _root, Version _version); protected: bool mEmptyView; uint32 mCurrentColour, mInverseColour; uint32 mCurrentAlpha; IntCoord mCurrentCoord; Ogre::UTFString mCaption; bool mTextOutDate; Align mTextAlign; Colour mColour; float mAlpha; bool mRenderGL; FontPtr mpFont; Ogre::TexturePtr mpTexture; uint mFontHeight; Font::GlyphInfo * mSpaceGlyphInfo; Font::GlyphInfo * mTabGlyphInfo; float mTextureHeightOne, mTextureWidthOne; bool mBackgroundNormal; size_t mStartSelect, mEndSelect; size_t mCursorPosition; bool mShowCursor; FloatPoint mBackgroundEmpty, mBackgroundFill, mBackgroundFillDeactive, mCursorTexture; VectorLineInfo mLinesInfo; IntPoint mViewOffset; // смещение текста FloatSize mContextRealSize; // размер всего текста IntSize mContextSize; // размер всего текста LayerItemKeeper * mItemKeeper; RenderItem * mRenderItem; size_t mCountVertex; LayerManager * mManager; bool mManualView; bool mShiftText; bool mBreakLine; int mOldWidth; }; } // namespace MyGUI #endif // __MYGUI_EDIT_TEXT_H__
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 164 ] ] ]
7dfa8fa9fd54f4432de42e182b25b6b81214f4f5
de6ff9bed5935e3859e913d9fdcf335fee46113f
/Grupo5Practica2/src/RegistroIS.cpp
204491bbc8f4caa33d6a16487ecc1dcce0ea360f
[]
no_license
antoniovm/chustaware
b45a4dfd73f4c16c21d574f8d9d147e44d5df0cf
f18b046afdaf33c966b21be883e44b9e3acca928
refs/heads/master
2021-01-22T11:36:55.188436
2011-06-04T14:57:56
2011-06-04T14:57:56
38,199,249
0
0
null
null
null
null
UTF-8
C++
false
false
813
cpp
/* * RegistroIS.cpp * * Created on: 27/04/2011 * Author: Miguel Vicente Linares, Antonio Vicente Martin y Sergio Revueltas Estrada */ #include "RegistroIS.h" RegistroIS::RegistroIS() { this->claveSecundaria = -1; this->posPrimero = -1; } RegistroIS::RegistroIS(int claveSec, int pos) { this->claveSecundaria = claveSec; this->posPrimero = pos; } int RegistroIS::getClaveSecundaria() const { return claveSecundaria; } int RegistroIS::getPosPrimero() const { return posPrimero; } void RegistroIS::setClaveSecundaria(int claveSecundaria) { this->claveSecundaria = claveSecundaria; } void RegistroIS::setPosPrimero(int posPrimero) { this->posPrimero = posPrimero; } RegistroIS::~RegistroIS() { // TODO Auto-generated destructor stub }
[ [ [ 1, 42 ] ] ]
5257596d46cccd7218f7b1e49b5e883c0c4c5d93
ce28ec891a0d502e7461fd121b4d96a308c9dab7
/sql/SQLNullDatabase.h
8db53066f6a49240b1f342794472b70c18c4d19d
[]
no_license
aktau/Tangerine
fe84f6578ce918d1fa151138c0cc5780161b3b8f
179ac9901513f90b17c5cd4add35608a7101055b
refs/heads/master
2020-06-08T17:07:53.860642
2011-08-14T09:41:41
2011-08-14T09:41:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
754
h
#ifndef SQLNULLDATABASE_H_ #define SQLNULLDATABASE_H_ #include "SQLDatabase.h" class SQLNullDatabase : public SQLDatabase { Q_OBJECT public: SQLNullDatabase(QObject *parent) : SQLDatabase(parent, "NULL") { } virtual ~SQLNullDatabase() { } //virtual QSqlDatabase open(const QString& file); protected: virtual QString createViewQuery(const QString&, const QString&) const { return QString(); } virtual void setPragmas() { } virtual QSet<QString> tableFields(const QString&) const { return QSet<QString>(); } private: // disabling copy-constructor and copy-assignment for now SQLNullDatabase(const SQLNullDatabase&); SQLNullDatabase& operator=(const SQLNullDatabase&); }; #endif /* SQLNULLDATABASE_H_ */
[ [ [ 1, 25 ] ] ]
df839564aaf15ab154fd826dd39633e0d6a737c9
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/fuzzyGraphStorage.h
36c490d16255f856a830d1187c8956e65a329e43
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
1,354
h
#ifndef FUZZYGRAPHSTORAGE_H #define FUZZYGRAPHSTORAGE_H #include <map> #include <vector> #include <string> #include <iostream> #include "fuzzyGraph.h" #include "desirabilityMatrix.h" #include "fuzzyInput.h" class fuzzyGraphStorage { public: fuzzyGraphStorage(); ~fuzzyGraphStorage(); void addType(string graphKey, double low, double medStart, double medEnd, double high); // Registers a decision factor's graph, which is used to make fuzzy decisions! void addDesirabilityMatrix(string matrixKey, desirabilityMatrix mtx); // Registers a desirabilityMatrix, which is used to qualify our data during defuzzification void tweakFuzzy(string graphKeym, double newLow, double newMedStart, double newMedEnd, double newHigh); // Tweaks a registered fuzzy graph void getFuzzy(string graphKey, double input, double &outputLow, double &outputMed, double &outputHigh); // Returns the fuzzy outputs for a given input on one registered fuzzy graph void brainify(vector<fuzzyInput*> inputs, desirability &outputType, double &outputValue, string matrixKey); // Brainificates. void printGraphDataDEBUG(string graphKey); void printMapSizeDEBUG(); private: std::map<string, fuzzyGraph*, less<string>> availableGraphs; std::map<string, desirabilityMatrix, less<string>> availableDesirabilityMatrices; }; #endif
[ "davidbmoss@5457d560-9b84-11de-b17c-2fd642447241", "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 8 ], [ 10, 16 ], [ 22, 26 ], [ 28, 30 ] ], [ [ 9, 9 ], [ 17, 21 ], [ 27, 27 ] ] ]
e0d8713f417c001d424c6ca91a69cab70877f10d
dd7d419eb5bb1158f198a1009b0a4268b05d5a29
/ProyectoGame/Input/GenericDevice.h
cc4dfb89ca4df8c77644155ead7e3aed454f214b
[]
no_license
carlixyz/galacticinvaders
6cb09540a725357e118a1f4dcd45a2461536561f
1e08405b62846b7909144331fe72452737bc6d7d
refs/heads/master
2018-01-08T16:49:50.443309
2010-06-10T17:51:06
2010-06-10T17:51:06
36,534,643
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
358
h
#pragma once // Dispositivo Generico : todas las clases de dispositivos de entrada derivan de aqui class cGenericDevice // clase abstracta (instanciación imposible) { public: virtual void Init() = 0; virtual void Deinit(void) = 0; virtual void Update(void) = 0; virtual float Check(unsigned luiEntry) = 0; virtual bool IsValid(void) = 0; };
[ [ [ 1, 12 ] ] ]
15ec8575167cc95d9c80347064612d0cfa30dff3
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/src/ParticleEmitters/ParticleUniverseCircleEmitter.cpp
61bde526685358dbf198bd6f751b846d01029dd7
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,102
cpp
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #include "ParticleUniversePCH.h" #ifndef PARTICLE_UNIVERSE_EXPORTS #define PARTICLE_UNIVERSE_EXPORTS #endif #include "ParticleEmitters/ParticleUniverseCircleEmitter.h" namespace ParticleUniverse { // Constants const Ogre::Real CircleEmitter::DEFAULT_RADIUS = 100.0f; const Ogre::Real CircleEmitter::DEFAULT_STEP = 0.1f; const Ogre::Real CircleEmitter::DEFAULT_ANGLE = 0.0f; const bool CircleEmitter::DEFAULT_RANDOM = true; const Ogre::Vector3 CircleEmitter::DEFAULT_NORMAL = Ogre::Vector3::ZERO; //----------------------------------------------------------------------- CircleEmitter::CircleEmitter(void) : ParticleEmitter(), mRadius(DEFAULT_RADIUS), mCircleAngle(DEFAULT_ANGLE), mOriginalCircleAngle(DEFAULT_ANGLE), mStep(DEFAULT_STEP), mRandom(DEFAULT_RANDOM), mOrientation(Ogre::Quaternion::IDENTITY), mNormal(DEFAULT_NORMAL), mX(0.0f), mZ(0.0f) { } //----------------------------------------------------------------------- const Ogre::Real CircleEmitter::getRadius(void) const { return mRadius; } //----------------------------------------------------------------------- void CircleEmitter::setRadius(const Ogre::Real radius) { mRadius = radius; } //----------------------------------------------------------------------- const Ogre::Real CircleEmitter::getCircleAngle(void) const { return mOriginalCircleAngle; } //----------------------------------------------------------------------- void CircleEmitter::setCircleAngle(const Ogre::Real circleAngle) { mOriginalCircleAngle = circleAngle; mCircleAngle = circleAngle; } //----------------------------------------------------------------------- const Ogre::Real CircleEmitter::getStep(void) const { return mStep; } //----------------------------------------------------------------------- void CircleEmitter::setStep(const Ogre::Real step) { mStep = step; } //----------------------------------------------------------------------- const bool CircleEmitter::isRandom(void) const { return mRandom; } //----------------------------------------------------------------------- void CircleEmitter::setRandom(const bool random) { mRandom = random; } //----------------------------------------------------------------------- const Ogre::Quaternion& CircleEmitter::getOrientation(void) const { return mOrientation; } //----------------------------------------------------------------------- const Ogre::Vector3& CircleEmitter::getNormal(void) const { return mNormal; } //----------------------------------------------------------------------- void CircleEmitter::setNormal(const Ogre::Vector3& normal) { mOrientation = Ogre::Vector3::UNIT_Y.getRotationTo(normal, Ogre::Vector3::UNIT_X); mNormal = normal; } //----------------------------------------------------------------------- void CircleEmitter::_notifyStart (void) { // Reset the attributes to allow a restart. ParticleEmitter::_notifyStart(); mCircleAngle = mOriginalCircleAngle; } //----------------------------------------------------------------------- void CircleEmitter::_initParticlePosition(Particle* particle) { Ogre::Real angle = 0; if (mRandom) { // Choose a random position on the circle. angle = Ogre::Math::RangeRandom(0, Ogre::Math::TWO_PI); } else { // Follow the contour of the circle. mCircleAngle += mStep; mCircleAngle = mCircleAngle > Ogre::Math::TWO_PI ? mCircleAngle - Ogre::Math::TWO_PI : mCircleAngle; angle = mCircleAngle; } mX = Ogre::Math::Cos(angle); mZ = Ogre::Math::Sin(angle); ParticleSystem* sys = mParentTechnique->getParentSystem(); if (sys) { // Take both orientation of the node and its own orientation, based on the normal, into account particle->position = getDerivedPosition() + sys->getDerivedOrientation() * mOrientation * (_mEmitterScale * Ogre::Vector3(mX * mRadius, 0, mZ * mRadius)); } else { particle->position = getDerivedPosition() + _mEmitterScale * ( mOrientation * Ogre::Vector3(mX * mRadius, 0, mZ * mRadius) ); } particle->originalPosition = particle->position; } //----------------------------------------------------------------------- void CircleEmitter::_initParticleDirection(Particle* particle) { if (mAutoDirection) { // The value of the direction vector that has been set does not have a meaning for // the circle emitter. Ogre::Radian angle; _generateAngle(angle); if (angle != Ogre::Radian(0)) { particle->direction = (mOrientation * Ogre::Vector3(mX, 0, mZ) ).randomDeviant(angle, mUpVector); particle->originalDirection = particle->direction; } else { particle->direction = Ogre::Vector3(mX, 0, mZ); particle->direction = mOrientation * Ogre::Vector3(mX, 0, mZ); } } else { // Use the standard way ParticleEmitter::_initParticleDirection(particle); } } //----------------------------------------------------------------------- void CircleEmitter::copyAttributesTo (ParticleEmitter* emitter) { ParticleEmitter::copyAttributesTo(emitter); CircleEmitter* circleEmitter = static_cast<CircleEmitter*>(emitter); circleEmitter->mRadius = mRadius; circleEmitter->mCircleAngle = mCircleAngle; circleEmitter->mOriginalCircleAngle = mOriginalCircleAngle; circleEmitter->mStep = mStep; circleEmitter->mRandom = mRandom; circleEmitter->mNormal = mNormal; circleEmitter->mOrientation = mOrientation; } }
[ [ [ 1, 179 ] ] ]
1d8afcd10e5c76224b66a400770bd163dea1bcd9
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/Core/IOData/pipe_connection.cpp
b51cff984c334d7499194ad62fc7c535852a5ce9
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
2,452
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "precomp.h" #include "API/Core/IOData/pipe_connection.h" #include "iodevice_provider_pipe_connection.h" #include "Core/IOData/iodevice_impl.h" ///////////////////////////////////////////////////////////////////////////// // CL_PipeConnection Construction: CL_PipeConnection::CL_PipeConnection(const CL_StringRef &pipe_name) : CL_IODevice(new CL_IODeviceProvider_PipeConnection(pipe_name)) { } #ifdef WIN32 CL_PipeConnection::CL_PipeConnection(HANDLE pipe_handle, bool dummy) : CL_IODevice(new CL_IODeviceProvider_PipeConnection(pipe_handle)) { } #else CL_PipeConnection::CL_PipeConnection(int pipe_handle, bool dummy) : CL_IODevice(new CL_IODeviceProvider_PipeConnection(pipe_handle)) { } #endif CL_PipeConnection::~CL_PipeConnection() { } ///////////////////////////////////////////////////////////////////////////// // CL_PipeConnection Attributes: ///////////////////////////////////////////////////////////////////////////// // CL_PipeConnection Operations: void CL_PipeConnection::disconnect() { CL_IODeviceProvider_PipeConnection *provider = dynamic_cast<CL_IODeviceProvider_PipeConnection*>(impl->provider); provider->disconnect(); } ///////////////////////////////////////////////////////////////////////////// // CL_PipeConnection Implementation:
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 72 ] ] ]
456f5c663bd0e9fc337d89025148fd1e7b11d619
5b49ceb49ea7402b71707e3eaa64b422ae6ba5a3
/src/Object.cpp
2c759b5e07d1cc206a2ecaf44873c65d81d5119d
[]
no_license
noqisofon/libcanopus
255179ca6403bd17bc028e301025c75fe50b7fe3
8a7a06b217441273f95091cb5a4f1dd08d60ea40
refs/heads/master
2016-09-05T23:16:03.403999
2011-01-03T14:02:30
2011-01-03T14:02:30
1,071,228
0
0
null
null
null
null
UTF-8
C++
false
false
1,535
cpp
#include <stdafx.h> #include <stddef.h> #include <canopus/String.hxx> #include <canopus/ObjectAggregate.hxx> #include <canopus/Object.hxx> using namespace canopus; Object::Object() { } Object::Object(const Object& other) { } Object::~Object() { finalize(); } String* const Object::className() const { return new String( "Object" ); } bool Object::equals(const Object* const& other) const { return isIdentity( other ); } bool Object::equals(const Object& other) const { return equals( &other ); } bool Object::isIdentity(const Object* const& other) const { return this == other; } bool Object::isIdentity(const Object& other) const { return isIdentity( &other ); } void Object::printOn(Stream* const& stream) const { String* title = className(); if ( __DYNAMIC_CAST( Character *, title->first() )->is_vowel() ) stream->nextPutAll( "an " ); else stream->nextPutAll( "a " ); stream->nextPutAll( title ); } String* const Object::printString() const { WriteStream stream( new String( 16 ) ); printOn( stream ); return __DYNAMIC_CAST( String *, stream.contents() ); } int Object::hash() const { return __STATIC_CAST(int, __REINTERPRET_CAST(void *, this)); } void Object::finalize() { if ( name_ != NULL ) delete name_; parent_->removeChild( this ); } Object* const Object::clone() const { return new Object( *this ); }
[ [ [ 1, 93 ] ] ]
251beebb72b44d3807fe9ff556e35cf80e6c77f0
485a4c53387cbce41a835abfce40f1f462cd240a
/VectorList.h
6dbbcac46295466d59a142a5e795c72b86405d73
[]
no_license
khandady/hw5
a5ad43a8529366b8246234f979323c538d580a0d
d6973c78ba130419714f3ccd6fcd2a740d980ea9
refs/heads/master
2016-09-05T20:52:53.261518
2011-03-14T02:23:52
2011-03-14T02:23:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,874
h
#ifndef VECTORLIST_H #define VECTORLIST_H #include <iostream> #include <vector> using namespace std; template< typename NODETYPE > class VectorList { public: VectorList(); // constructor ~VectorList(); // destructor void insertAtFront( const NODETYPE & ); void insertAtBack( const NODETYPE & ); bool removeFromFront( NODETYPE & ); bool removeFromBack( NODETYPE & ); bool isEmpty() const; void print() const; ///////////////////////////////////////////////////////// // new member functions for HW 5 // overload array access operator NODETYPE &operator[](int index) const; // sum up all the values in the linked list, // assuming + is overloaded for NODETYPE NODETYPE sum() const; // Sort the linked list in ascending order, // assuming NODETYPE supports <, ==, etc. void sort(); // In-place reversal of the linked list, i.e., don't create a new list // to perform the reversal, and use the list itself void reverse(); // Check whether the current list and the input l2 share any nodes or not bool shared(const VectorList< NODETYPE > &l2); // Apply the function func to each element in the linked list void map(NODETYPE func(const NODETYPE &, const NODETYPE &)); // Keep only those nodes n where predicate(n) = true void filter(bool predicate(const NODETYPE &)); // Remove all duplicates from the list void removeDup(); // ///////////////////////////////////////////////////////// private: vector< NODETYPE > *vList; // list data as a vector }; template< typename NODETYPE > VectorList< NODETYPE >::VectorList() //: // Fill in the missing code { // empty body } template< typename NODETYPE > VectorList< NODETYPE >::~VectorList() { // Fill in the missing code } // insert node at front of list template< typename NODETYPE > void VectorList< NODETYPE >::insertAtFront( const NODETYPE &value ) { // Fill in the missing code } // insert node at back of list template< typename NODETYPE > void VectorList< NODETYPE >::insertAtBack( const NODETYPE &value ) { // Fill in the missing code } // delete node from front of list template< typename NODETYPE > bool VectorList< NODETYPE >::removeFromFront( NODETYPE &value ) { // Fill in the missing code } // delete node from back of list template< typename NODETYPE > bool VectorList< NODETYPE >::removeFromBack( NODETYPE &value ) { // Fill in the missing code } // is VectorList empty? template< typename NODETYPE > bool VectorList< NODETYPE >::isEmpty() const { // Fill in the missing code } // display contents of VectorList template< typename NODETYPE > void VectorList< NODETYPE >::print() const { // Fill in the missing code } #endif
[ [ [ 1, 123 ] ] ]
e54e577dc6dd7c34959d59cb3a7d75e35659e822
c4e8cb1539bc0cf5cb119af4a6b6212230f937aa
/Babel/PaIOSound.h
d9123fd85b4a5346a1c6dfded6175ee66bb6f493
[]
no_license
RemiGuillard/Babel-save-03
56e93fd7beda23be5faad102b43090a2d756f0d2
25893350dc14c6434dcc053302440bdca710c59e
refs/heads/master
2021-01-13T02:14:46.982890
2010-11-29T17:40:53
2010-11-29T17:40:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
836
h
#ifndef PAIOSOUND_H # define PAIOSOUND_H #include <iostream> #include <QObject> #include "AbsIOSound.hpp" #include "portaudio.h" #include "AudioThread.hpp" /*#define PA_SAMPLE_TYPE paFloat32 #define SAMPLE_SILENCE (0.0f) typedef float SAMPLE;*/ #define PA_SAMPLE_TYPE paInt16 #define SAMPLE_SILENCE (0) typedef short SAMPLE; class PaIOSound : public AbsIOSound<SAMPLE> { public: PaIOSound(); ~PaIOSound(); public: virtual void recordVoice(); virtual void playVoice(); //virtual StopPlayRecord(); virtual IOStreamData<SAMPLE> *getdata(); virtual Encoder &getEncode(); /* template <typename A> void setBuf(A *dest, A *from) { int i; for (i=0;i<FRAMES_PER_BUFFER;i++) dest[i] = from[i]; }*/ }; #endif // !PAIOSOUND_H
[ [ [ 1, 5 ], [ 7, 39 ] ], [ [ 6, 6 ] ] ]
3e4758529a25f74f126e477991b776187932d16e
5d36f6102c8cadcf1a124b366ae189d6a2609c59
/src/Qt/psx4cute/psx4Qt.h
33bd969898616369ba87dcfb77df1551f09db5c2
[]
no_license
Devil084/psx4all
336f2861246367c8d397ef5acfc0b7972085c21b
04c02bf8840007792d23d15ca42a572035a1d703
refs/heads/master
2020-02-26T15:18:04.554046
2010-08-11T13:49:24
2010-08-11T13:49:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,278
h
/* psx4cute * * Copyright (C) 2010 Summeli <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 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 */ #ifndef GPSP4QT_H #define GPSP4QT_H #include <QtGui/QMainWindow> #include <QKeyEvent> #include <QList> #include <QThread> #include "QBlitterWidget.h" #include "dpadwidget.h" #include "psxSettings.h" #include "MEmulatorAdaptation.h" #include "QRemoteControlKeys.h" #include "dpadwidget.h" #include "psxadaptation.h" class psx4Qt : public QMainWindow, MEmulatorAdaptation { Q_OBJECT public: psx4Qt(QWidget *parent = 0); ~psx4Qt(); public: void setRemoteControl( QRemoteControlKeys* remote ); void keyPressEvent( QKeyEvent * event); void keyReleaseEvent(QKeyEvent* event); public: //From MEmulatorAdaptation int getKeyEvent( antKeyEvent& keyEvent ); public: void LoadROM(QString rom, TPsxSettings antSettings); void LoadState( int state ); void SaveState( int state ); void reset(); void continueGame(); signals: void Start(); void Stop(); void doLoadROM(QString rom, TPsxSettings antSettings); void showmenu(); public slots: void showAntSnesMenu(); void updateSettings( TPsxSettings settings ); void virtualKeyEvent( quint32 aKey, bool isDown ); private slots: void listencontrols(); private: QBlitterWidget* widget; TPsxSettings iAntSettings; QList<antKeyEvent> iPressedKeys; QRemoteControlKeys* remotecontrol; DPadWidget* dpad; psxadaptation* adaptation; }; #endif // GPSP4QT_H
[ [ [ 1, 81 ] ] ]
6870179e229ec4d791d5583eb45105df9d39f144
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Internal/Collide/Tree/AabbTree/hkAabbTreeData.h
f8aa99f4e6bb1e05557a449ef19e7041162d41a1
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
5,511
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_AABB_TREE_H #define HK_AABB_TREE_H #include <Common/Base/Types/Geometry/Aabb/hkAabb.h> class hkJobQueue; class hkJobThreadPool; class hkAabbTreeData { public: struct Ray { HK_FORCE_INLINE void setRay( const hkVector4& start, const hkVector4& end ); hkVector4 m_start; hkVector4 m_invDir; }; struct Bundle { hkVector4 m_data[3]; // 0:X, 1:Y, 2:z }; struct SetRays { SetRays(){ m_numActiveRays = 4;} hkVector4 m_from[4]; hkVector4 m_to[4]; int m_numActiveRays; }; struct RayBundle { HK_FORCE_INLINE RayBundle(){} HK_FORCE_INLINE RayBundle( const Bundle& from, const Bundle& to, hkVector4Comparison::Mask mask = hkVector4Comparison::MASK_XYZW ); Bundle m_from; Bundle m_invDir; hkVector4Comparison::Mask m_mask; }; struct CastVolumeInput { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, CastVolumeInput ); hkVector4 m_from; hkVector4 m_to; hkVector4 m_halfExtents; }; struct hkAabbTreeAabb16 { struct Metric { hkVector4 m_center; /// Find the best matching aabb HK_FORCE_INLINE int select(const hkAabbTreeAabb16& a, const hkAabbTreeAabb16& b) const; }; typedef Metric METRIC; HK_FORCE_INLINE Metric getMetric() const; HK_FORCE_INLINE hkAabbTreeAabb16(){} HK_FORCE_INLINE void center( hkVector4& centerOut ) const; HK_FORCE_INLINE static void combine( const hkAabbTreeAabb16& a, const hkAabbTreeAabb16& b, hkAabbTreeAabb16& out); HK_FORCE_INLINE hkBool32 equals(const hkAabbTreeAabb16& aabb) const; HK_FORCE_INLINE hkBool contains(const hkAabbTreeAabb16& other) const; HK_FORCE_INLINE void includeAabb( const hkAabbTreeAabb16& aabb); HK_FORCE_INLINE hkBool isValid() const; HK_FORCE_INLINE void setEmpty(); HK_FORCE_INLINE hkBool32 overlaps( const hkAabbTreeAabb16& testAabb) const; HK_FORCE_INLINE hkReal distanceSquared(const hkVector4& point) const; HK_FORCE_INLINE static void HK_CALL convertAabbToTreeSpace(const hkAabb& volume, const hkVector4& bitOffsetLow, const hkVector4& bitOffsetHigh, const hkVector4& bitScale, hkAabbTreeAabb16& volumeOut); HK_FORCE_INLINE static void HK_CALL convertAabbToTreeSpace( const hkAabbUint32& volumeIn, const hkVector4& bitOffsetLow, const hkVector4& bitOffsetHigh, const hkVector4& bitScale, hkAabbTreeAabb16& volumeOut); HK_FORCE_INLINE static void HK_CALL restoreAabb(const hkAabbTreeAabb16& in, const hkVector4& bitScaleInv, const hkVector4& bitOffsetLow, hkAabb& out); //================= // temporary function for transition of quantized aabb tree. they will be deleted HK_FORCE_INLINE hkBool32 overlaps( const hkAabb& testAabb ) const; hkUint16 m_max[3]; hkUint16 m_min[3]; }; struct hkAabbTreeAabb : public hkAabb { struct Metric { hkVector4 m_center; /// Find the best matching aabb HK_FORCE_INLINE int select(const hkAabbTreeAabb& a, const hkAabbTreeAabb& b) const; }; typedef Metric METRIC; HK_FORCE_INLINE Metric getMetric() const; HK_FORCE_INLINE void center( hkVector4& centerOut ) const; HK_FORCE_INLINE static void combine( const hkAabbTreeAabb& a, const hkAabbTreeAabb& b, hkAabbTreeAabb& out); HK_FORCE_INLINE hkBool32 overlaps(const Ray& r, const hkVector4& earlyOutHitFraction ) const; HK_FORCE_INLINE hkBool32 overlaps(const RayBundle& ray, const hkVector4& ealyOutFractions, hkVector4Comparison& hitOut) const; HK_FORCE_INLINE hkBool32 overlaps(const hkAabb& aabb) const; HK_FORCE_INLINE void expand( hkVector4Parameter velocity, hkReal margin ); HK_FORCE_INLINE hkReal distanceSquared(const hkVector4& point) const; HK_FORCE_INLINE static void HK_CALL convertAabbToTreeSpace(const hkAabb& volume, const hkVector4& bitOffsetLow, const hkVector4& bitOffsetHigh, const hkVector4& bitScale, hkAabbTreeAabb& volumeOut); HK_FORCE_INLINE static void HK_CALL convertAabbToTreeSpace( const hkAabbUint32& volumeIn, const hkVector4& bitOffsetLow, const hkVector4& bitOffsetHigh, const hkVector4& bitScale, hkAabbTreeAabb& volumeOut); HK_FORCE_INLINE static void HK_CALL restoreAabb(const hkAabbTreeAabb& in, const hkVector4& bitScaleInv, const hkVector4& bitOffsetLow, hkAabb& out); }; }; #include <Common/Internal/Collide/Tree/AabbTree/hkAabbTreeData.inl> #endif /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 144 ] ] ]
bc6b0ce86384179c420f52e2a53bcbb4aaedfd24
3bfe835203f793ee00bdf261c26992b1efea69ed
/fall08/cs460/project/cs460_1/Graphics.h
6976ea23427b13f532a52ddad267c462de2d7799
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
UTF-8
C++
false
false
3,414
h
#pragma once #include <d3dx9.h> #include <string> #include <sstream> #include <float.h> #include "Model.h" #include "Macros.h" #include "Vertex.h" #include "Joint.h" #define Gfx Graphics::Instance() #define CP_RADIUS 5.f #define CP_HEIGHT .5f #define CCD_MAX_ITERS 200 #define CCD_FAIL 0.f #define CCD_SUCCESS 5.f struct Camera { D3DXVECTOR3 eye; D3DXVECTOR3 lookAt; D3DXVECTOR3 up; }; class Graphics { private: Graphics( void ); ~Graphics( void ); Graphics( const Graphics &rhs ); void operator =( const Graphics &rhs ); public: static Graphics *Instance(); void Initialize( HWND hWndApp ); void Update( void ); void LoadStaticModel( const std::string &file, const D3DXVECTOR3 &pos = D3DXVECTOR3( 1.f, 1.f, 1.f ), float scale = 1.f ); void LoadAnimatedModel( const std::string &file ); void IncDecAnimSpeed( bool inc ); void SetupMatrices( void ); void DisplayInfo( void ); void CreateSunLight( void ); void Cleanup( void ); void AddQuad( const ColoredVertex *verts ); LPDIRECT3DDEVICE9 GetDevice( void ) const; D3DXVECTOR3 IsectGroundPlane( int x, int y ); void DrawControlPoints( void ); void AddLine( const ColoredVertex *verts ); void AddLine( const ColoredVertex &begin, const ColoredVertex &end ); void AddPolyline( const ColoredVertex *verts, size_t nVerts, bool closed = true ); bool CCD( JointVec &joints, const D3DXVECTOR3 &dest ) const; void PauseAnims( void ); void PlayAnims( void ); bool IsPaused( void ) const; LPDIRECT3DDEVICE9 GetDevice( void ); void WriteText( const std::string &text ); Camera &MainCam; const bool &Ready; StaticModelList &StaticModels; AnimatedModelList &AnimatedModels; LPDIRECT3DTEXTURE9 pFloorTex; VertVec controlPoints; LPD3DXFONT pFont; ANIMCALLBACKFN animCallback; private: LPDIRECT3D9 pD3D; LPDIRECT3DDEVICE9 pDevice; LPD3DXMATRIXSTACK pMatrixStack; Camera mainCam; DWORD bgColor; StaticModelList staticModels; AnimatedModelList animModels; HWND hWnd; bool ready; bool paused; VertVec quadPrimitives; VertVec linePrimitives; VertVec polylinePrimitives; DWORD curTime; std::stringstream infoStrings; private: static void IncAnimSpeed( const AnimatedModel &animModel ) { animModel.AnimSpeed += ( ( animModel.AnimSpeed >= 1.f ) ? 1.f : animModel.AnimSpeed ); } static void DecAnimSpeed( const AnimatedModel &animModel ) { ( animModel.AnimSpeed > 1.f ) ? animModel.AnimSpeed -= 1.f : animModel.AnimSpeed /= 2.f; } struct AddModelInfo { AddModelInfo( std::stringstream *_pInfo ) : pInfo( _pInfo ) {} void operator ()( const AnimatedModel &model ) { *pInfo << "Animation Set: " << model.AnimSet + 1 << "/" << model.AnimSets.size() << std::endl << "Speed: " << model.AnimSpeed << "x" << std::endl; *pInfo << std::endl; } std::stringstream *pInfo; }; };
[ [ [ 1, 117 ] ] ]
7be4f93e38522ac1563541a87da24c8ad33fcb3e
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/FakeNavServerCom/Faker.h
dde7713390dff48f5bebd1522cef9b572dafb731
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,765
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FAKER_H #define FAKER_H #include <map> namespace isab{ class fakerstring { char* m_str; public: fakerstring() : m_str(NULL) {} explicit fakerstring(const char* s) : m_str(NULL) { m_str = strdup_new(s); } fakerstring(const fakerstring& f) : m_str(NULL) { m_str = strdup_new(f.m_str); } explicit fakerstring(const std::vector<char>& v) : m_str(NULL) { if(!v.empty()){ m_str = new char[v.size() + 1]; std::copy(v.begin(), v.end(), m_str); m_str[v.size()] = 0; } } const fakerstring& operator=(const fakerstring& rhs) { if(*this != rhs){ delete[] m_str; m_str = strdup_new(rhs.m_str); } return *this; } ~fakerstring() { delete[] m_str; } bool operator<(const fakerstring& rhs) const { return 0 > strcmp(m_str ? m_str : "", rhs.m_str ? rhs.m_str : ""); } bool operator>=(const fakerstring& rhs) const { return !(*this < rhs); } bool operator>(const fakerstring& rhs) const { return 0 < strcmp(m_str ? m_str : "", rhs.m_str ? rhs.m_str : ""); } bool operator<=(const fakerstring& rhs) const { return !(*this > rhs); } bool operator==(const fakerstring& rhs) const { return strequ(m_str ? m_str : "", rhs.m_str ? rhs.m_str : ""); } bool operator!=(const fakerstring& rhs) const { return !(*this == rhs); } const char* c_str() const { return m_str; } }; class Faker : public NavServerComProviderInterface, public NavServerComTimerCallBack { NavServerComReplyInterface* m_interface; Log* m_log; Faker(const Faker&); const Faker& operator=(const Faker&); // NOTE!!! Memory leak of AdditionalInfo's!!! // Need to delete when shutting down... std::multimap<fakerstring, class AdditionalInfo*> m_info; // NOTE!!! Memory leak of AdditionalInfo's!!! // Need to delete when shutting down... std::set<class SearchRegion* > m_regions; std::multimap<fakerstring, fakerstring> m_item2region; std::vector<class FullSearchItem*> m_items; void parseinfo(char** currentinfo, FILE* sf); void parseregion(FILE* sf); void parseitem(FILE* sf); void parsemap(FILE* sf); bool readSearchData(const char* filename); struct routeRequestData { routeRequestData() : timerid(0xffff), toLat(MAX_INT32), toLon(MAX_INT32), fromLat(MAX_INT32), fromLon(MAX_INT32), heading(0), oldRouteId(0), src(0) {} uint16 timerid; int32 toLat; int32 toLon; int32 fromLat; int32 fromLon; uint16 heading; int64 oldRouteId; uint8 rerouteReason; uint32 src; } m_routeRequest; public: Faker() : m_interface(NULL) { m_log = new Log("Faker"); } void timerExpired(uint16 id); void setInterface(NavServerComReplyInterface* a_interface) { m_interface = a_interface; } virtual ~Faker() { delete m_log; } /** This method is called from NavServerComDecoder::dispatch. * It clears out old parameter settings and set the new ones. * @param data the parameter data. This data is never parsed but sent * as is to the server at the beginning of every session. * NavServerCom depends on this block being terminated with * the end parameter tag. * @param length the size of the data block. * @param src the address of the sender of the parameter block. */ virtual void decodedSetServerParams(const uint8* data, size_t length, uint32 src); /** Called by NavServerComDecoder::dispatch when a syncdestinations * request arrives from another module. * XXX this method is not yet implemented. * @param length the size of the data block. * @param data a byte array containing the syncDestinationsRequest * already coded for transmission to the server. * @param src the original requester. */ virtual void decodedSyncDestinations(int length, const uint8* data, uint32 src) ; /** Called by NavServerComDecoder::dispatch when a whereAmI request * arrives from another module. * @param lat the latitude of the postion to look up. Given in rad*1e8. * @param lon the longitude of the position to look up. Given in rad*1e8. * @param src the address of the original requester. */ virtual void decodedWhereAmI(int32 lat, int32 lon, uint32 src); /** Called by NavServerComDecoder::dispatch when a search request * arrives from another module. * @param data the request data already coded as a server request. * @param length the size of the data block. * @param lat the latitude to search from. * (Redundant, but used for error checking.) * @param lon the longitude to search from. * (Redundant, but used for error checking.) * @param country the code for the country to search in. * (Redundant, but used for error checking.) * @param city the city string entered by the user. * (Redundant, but use for error checking.) * @param src the address of the original requester. * @param latOffset the offset into the data where the new latitude * should be written. Defaults to -1, which * means don't refresh. * @param lonOffset the offset into the data where the new longitude * should be written. Defaults to -1, which * means don't refresh. */ virtual void decodedSearchRequest(const uint8* data, int length, int32 lat, int32 lon, uint8 hdg, uint32 country, const char* city, uint32 src, int latOffset = -1, int lonOffset = -1, int hdgOffset = -1); /** Called by NavServerComDecoder::dispatch when a route request * arrives from another module. All latitude and lonitude coordinates * are specified in rad * 1e8. * @param toLat latitude to route to. * @param toLon longitude to route to. * @param fromLat latitude to route from. * @param fromLon longitude to route from. * @param heading current heading. * @param src the address of the original requester. */ virtual void decodedRouteToGps(int32 toLat, int32 toLon, int32 fromLat, int32 fromLon, uint16 heading, uint32 routeRequestorId, int64 oldRouteId, uint8 rerouteReason, uint32 src); virtual void decodedMapRequest(int len, const uint8* data, uint32 dst, int latOffset, int lonOffset, int hdgOffset, int spdOffset); virtual void decodedVectorMapRequest(int /*len*/, const uint8* /*data*/, uint32 /*src*/) { //this fubction intentionally left blank. } virtual void decodedMultiVectorMapRequest(int /*len*/, const uint8* /*data*/, uint32 /*src*/) { //This function intentionally left blank } virtual void decodedSearchInfoRequest(int len, const uint8* data, uint32 src); virtual void decodedMessageRequest(const uint8* /*data*/, unsigned /*length*/, uint32 /*src*/) {} /** Called by NavServerComDecoder::dispatch when a binary upload request * arrives from another module. * @param len the size of the data block. * @param data the bainry block to send to the server. * @param src the address of the original requester. */ virtual void decodedBinaryUpload(int len, const uint8 * data, uint32 src); virtual void decodedCancelRequest(uint32 originalSrc, uint32 netmask, uint32 src); virtual void decodedRequestReflash(uint32 src); virtual void decodedVerifyLicenseKey(const char *key, const char *phone, const char* name, const char* email, const char* optional, uint32 region, uint32 src); virtual void decodedParamSync(uint32 src); virtual void decodedCellReport(const uint8* /*data*/, uint32 /*size*/, uint32 /*dst*/) { /*This function intentionally left blank. */} virtual void decodedSendRequest( const MsgBuffer* /*buf*/ ) { /*This function intentionally left blank. */} }; } inline void isab::Faker::decodedSyncDestinations(int /*length*/, const uint8* /*data*/, uint32 src) { m_interface->sendError(Nav2Error::NSC_OPERATION_NOT_SUPPORTED, src); } inline void isab::Faker::decodedSetServerParams(const uint8* /*data*/, size_t /*length*/, uint32 /*src*/) { } inline void isab::Faker::decodedWhereAmI(int32 /*lat*/, int32 /*lon*/, uint32 src) { m_interface->sendError(Nav2Error::NSC_OPERATION_NOT_SUPPORTED, src); } inline void isab::Faker::decodedCancelRequest(uint32 /*originalSrc*/, uint32 /*netmask*/, uint32 src) { m_interface->sendError(Nav2Error::NSC_OPERATION_NOT_SUPPORTED, src); } inline void isab::Faker::decodedRequestReflash(uint32 src) { m_interface->sendError(Nav2Error::NSC_OPERATION_NOT_SUPPORTED, src); } inline void isab::Faker::decodedParamSync(uint32 src) { m_interface->sendError(Nav2Error::NSC_OPERATION_NOT_SUPPORTED, src); } #endif
[ [ [ 1, 301 ] ] ]
11a39d2860d455d726fadba15bff7c2543fc0a5c
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Models/BASIC1/Vlv4Port.H
39fb57cd94f6a792a9246ef53a6e0fad1fc76026
[]
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
6,980
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __VLV4PORT_H #define __VLV4PORT_H #include <sc_defs.h> #include "m_base.h" #include "flshtrn.h" #include "sp_react.h" #ifdef __VLV4PORT_CPP #define DllImportExport DllExport #elif !defined(Basic1) #define DllImportExport DllImport #else #define DllImportExport #endif // ========================================================================== // Basic Flow Object const long Max4WayIOPorts=4; const long Max4WayJoins=2; class C4PortMode { public: C4PortMode() { m_iMd = -1; //m_Jn[MaxIOPorts][MaxJoins]; memset(m_Jn, -1, sizeof(m_Jn)); memset(m_PortsJoin, -1, sizeof(m_PortsJoin)); for (int j=0; j<Max4WayJoins; j++) for (int i=0; i<Max4WayIOPorts; i++) m_Jn[j].m_Port[i] = -1; for (int i=0; i<Max4WayIOPorts; i++) m_PortsJoin[i] = -1; m_InTime = 0; m_OutTime = 0; m_iChgMd = -1; //m_Open = 0; } public: int m_iMd; CString m_sName; struct { signed char m_Port[Max4WayIOPorts]; } m_Jn[Max4WayJoins]; //signed char m_Jn[Max4WayJoins][Max4WayIOPorts]; signed char m_PortsJoin[Max4WayIOPorts]; double m_InTime; double m_OutTime; int m_iChgMd; }; class C4PortPort { public: C4PortPort() { m_ResMult = 1.0; m_Open = 0.0; }; double m_ResMult; double m_Open; }; class C4PortTrans { public: double m_TimeInc; double m_OpenS; double m_OpenE; long m_Mode; }; class C4PortProfPt { public: C4PortProfPt() { }; //long m_Mode; double m_Posn; struct { double m_Open[Max4WayIOPorts]; } m_Jn[Max4WayJoins]; }; class C4PortProfile { public: C4PortProfile & operator=(C4PortProfile & P) { m_sName=P.m_sName; m_Pts.SetSize(P.m_Pts.GetSize()); for (int i=0; i<m_Pts.GetSize(); i++) m_Pts[i]=P.m_Pts[i]; return *this; }; public: CString m_sName; CArray<C4PortProfPt, C4PortProfPt&> m_Pts; }; DEFINE_TAGOBJ(C4PortValve); class DllImportExport C4PortValve : public MdlNode { public: C4PortValve (pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~C4PortValve (){}; virtual void BuildDataDefn(DataDefnBlk & DDB); virtual flag DataXchg(DataChangeBlk & DCB); virtual flag ValidateData(ValidateDataBlk & VDB); virtual flag GetModelAction(CMdlActionArray & Acts); virtual flag SetModelAction(CMdlAction & Act); void CreateConfigFile(LPCTSTR Fn); bool TokenIs(CTokenParser &Tkns, LPCTSTR pRqdToken); bool CheckToken(CTokenParser &Tkns, LPCTSTR pRqdToken); void LoadVlvConfigurations();//LPCTSTR Fn); void LoadVlvModes();//LPCTSTR Fn, LPCTSTR Config); void SetVlvMode(long Md, bool Immediate, double RqdPosn=-1.2345); //void SetConnStrs(); LPTSTR GetJoinStr(long iJoin); LPTSTR GetJoinPipeStr(long iJoin, long iPipe); void FixModeStrs(int IONo); virtual void PostConnect(int IONo); virtual void PreDisConnect(int IONo); virtual void SetDatums(int Pass, CFlwNodeIndexList & List, int IOIn); virtual flag Set_Sizes(); virtual void SetState(eScdMdlStateActs RqdState); virtual bool PropagateNetInfo(CPropagateNetInfoCtrl & Ctrl, long IONo); virtual void ConfigureJoins(); virtual void StartStep(); virtual double GetMaxTimeInc(); virtual void EvalJoinPressures(long JoinMask); virtual flag EvalFlowEquations(eScdFlwEqnTasks Task, CSpPropInfo *pProps, int IONo, int FE, int LnkNo); virtual void EvalProductsInit(EvalProductsInitTasks Task); virtual bool EvalProductClusters(int Index, long & JoinMask); virtual void EvalProducts(CNodeEvalIndex & NEI); virtual void EvalCtrlActions(eScdCtrlTasks Tasks=CO_All); virtual void EvalDiscrete(); virtual void DumpDerivs(); virtual flag ChangeMode(dword NewMode, dword OldMode); virtual void EvalPBMakeUpReqd(long JoinMask); virtual void EvalPBMakeUpAvail(long JoinMask); virtual void OnAppActivate(BOOL bActive); virtual int FilesUsed(CFilesUsedArray & Files); virtual void ClosureInfo(); virtual dword ModelStatus(); LPTSTR ConfigFileX() { m_sConfigFileXTmp.FnExpand(m_sConfigFileC()); return m_sConfigFileXTmp(); }; public: CArray<C4PortMode, C4PortMode&> m_Modes; CArray<C4PortProfile, C4PortProfile&> m_Profiles; C4PortPort m_Ports[Max4WayIOPorts]; DDBValueLstMem m_ConfigNames; Strng m_sConfigFileXTmp; Strng m_sConfigFileC; FILETIME m_CfgFileTime; Strng m_sConfig; bool m_bErrorFound; HANDLE m_hProcess; //process handle for the editor DWORD m_dwProcessId; //process ID for the editor long m_iVlvModeAct; long m_iVlvModeRqd; //long m_iVlvModeMidPt; struct { byte m_iMethod; bool m_bOn; long m_iOffMode; long m_iOnMode; double m_ActualPosn; double m_ReqdPosn; } m_State; long m_nInterSteps; // The number of steps to transition over for each part of change long m_iTrans; double m_TmInStep; double m_OpnWRT50; double m_ClosedTime; CArray<C4PortTrans, C4PortTrans&> m_Trans; long m_iVlvModeStrs; DDBValueLstMem m_ModeStrs; DDBValueLstMem m_ProfileNames; long m_iProfile; //bool m_AllowManualPortPosn; Strng m_sConnStrs[Max4WayJoins]; Strng m_sConnPipeStrs[Max4WayJoins][Max4WayIOPorts]; CFlwEqnPtr m_FEP; DEFINE_CI(C4PortValve, MdlNode, 4); }; //=========================================================================== // // // //=========================================================================== #undef DllImportExport #endif
[ [ [ 1, 119 ], [ 122, 136 ], [ 138, 139 ], [ 141, 149 ], [ 151, 151 ], [ 153, 233 ] ], [ [ 120, 121 ], [ 137, 137 ], [ 140, 140 ], [ 150, 150 ], [ 152, 152 ] ] ]
689d891aca59390849a65d5f5123eabe1581b01d
0cc80cab288248cd9c3a2cc922487ac2afd5148c
/tu_quoque/tu_quoque/ConstDelegate.hpp
0e9ab9bc4d6899ada61664aadb8fc8c69f15212a
[]
no_license
WestleyArgentum/tu-quoque
a3fbdb37dfebe9e9f0b00254144a48fdee89e946
38f661a145916768727b1a6fb7df5aa37072b6d2
refs/heads/master
2021-01-02T08:57:39.513862
2011-02-20T05:56:36
2011-02-20T05:56:36
33,832,399
0
0
null
null
null
null
UTF-8
C++
false
false
16,116
hpp
/******************************************************************************/ /*! \file Delegate.hpp \author Chris Barrett \brief Delegate declaration. Copyright (C) 2009 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /******************************************************************************/ #pragma once #ifndef CONSTDELEGATE_HPP_INCLUDED_ #define CONSTDELEGATE_HPP_INCLUDED_ // disable warning about throw specifications being ignored #ifdef _MSC_VER #pragma warning(disable: 4290) #endif // def _MSC_VER // ConstDelegate_0Parameters template <typename T_Return, typename T_ClassType> struct ConstDelegate_0Parameters : public ConstMemberFunction_0Parameters<T_Return, T_ClassType> { typedef T_Return (T_ClassType::*FunctionType)(void) const; ConstDelegate_0Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_0Parameters<T_Return, T_ClassType>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & /*arguments*/) { last_return_ = (object_pointer_->*function_)(); } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_0Parameters - void return type specialization template <typename T_ClassType> struct ConstDelegate_0Parameters<void, T_ClassType> : public ConstMemberFunction_0Parameters<void, T_ClassType> { typedef void (T_ClassType::*FunctionType)(void) const; ConstDelegate_0Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_0Parameters<void, T_ClassType>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { (object_pointer_->*function_)(); last_return_ = 0; } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_1Parameters template <typename T_Return, typename T_ClassType, typename T_Parameter0> struct ConstDelegate_1Parameters : public ConstMemberFunction_1Parameters<T_Return, T_ClassType, T_Parameter0> { typedef T_Return (T_ClassType::*FunctionType)(T_Parameter0) const; ConstDelegate_1Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_1Parameters<T_Return, T_ClassType, T_Parameter0>(function, default_arguments), object_pointer_(object_pointer) { if (object_pointer) {} } virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 1); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); last_return_ = (object_pointer_->*function_)(argument0); } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_1Parameters - void return type specialization template <typename T_ClassType, typename T_Parameter0> struct ConstDelegate_1Parameters<void, T_ClassType, T_Parameter0> : public ConstMemberFunction_1Parameters<void, T_ClassType, T_Parameter0> { typedef void (T_ClassType::*FunctionType)(T_Parameter0) const; ConstDelegate_1Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_1Parameters<void, T_ClassType, T_Parameter0>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 1); if (object_pointer_ == 0 || this == 0) { /// TODO: Use error reporting here - attempt to invoke on null object //DebugBreak(); object_pointer_ = object_pointer_; } T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); (object_pointer_->*function_)(argument0); last_return_ = 0; } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_2Parameters template <typename T_Return, typename T_ClassType, typename T_Parameter0, typename T_Parameter1> struct ConstDelegate_2Parameters : public ConstMemberFunction_2Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1> { typedef T_Return (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1) const; ConstDelegate_2Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_2Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 2); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); last_return_ = (object_pointer_->*function_)(argument0, argument1); } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_2Parameters - void return type specialization template <typename T_ClassType, typename T_Parameter0, typename T_Parameter1> struct ConstDelegate_2Parameters<void, T_ClassType, T_Parameter0, T_Parameter1> : public ConstMemberFunction_2Parameters<void, T_ClassType, T_Parameter0, T_Parameter1> { typedef void (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1) const; ConstDelegate_2Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_2Parameters<void, T_ClassType, T_Parameter0, T_Parameter1>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 2); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); (object_pointer_->*function_)(argument0, argument1); last_return_ = 0; } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_3Parameters template <typename T_Return, typename T_ClassType, typename T_Parameter0, typename T_Parameter1, typename T_Parameter2> struct ConstDelegate_3Parameters : public ConstMemberFunction_3Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2> { typedef T_Return (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1, T_Parameter2) const; ConstDelegate_3Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_3Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 3); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); T_Parameter2 argument2 = arguments.extract<T_Parameter2>(2); last_return_ = (object_pointer_->*function_)(argument0, argument1, argument2); } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_3Parameters - void return type specialization template <typename T_ClassType, typename T_Parameter0, typename T_Parameter1, typename T_Parameter2> struct ConstDelegate_3Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2> : public ConstMemberFunction_3Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2> { typedef void (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1, T_Parameter2) const; ConstDelegate_3Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_3Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 3); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); T_Parameter2 argument2 = arguments.extract<T_Parameter2>(2); (object_pointer_->*function_)(argument0, argument1, argument2); last_return_ = 0; } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_4Parameters template <typename T_Return, typename T_ClassType, typename T_Parameter0, typename T_Parameter1, typename T_Parameter2, typename T_Parameter3> struct ConstDelegate_4Parameters : public ConstMemberFunction_4Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3> { typedef T_Return (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3) const; ConstDelegate_4Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_4Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 4); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); T_Parameter2 argument2 = arguments.extract<T_Parameter2>(2); T_Parameter3 argument3 = arguments.extract<T_Parameter3>(3); last_return_ = (object_pointer_->*function_)(argument0, argument1, argument2, argument3); } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_4Parameters - void return type specialization template <typename T_ClassType, typename T_Parameter0, typename T_Parameter1, typename T_Parameter2, typename T_Parameter3> struct ConstDelegate_4Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3> : public ConstMemberFunction_4Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3> { typedef void (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3) const; ConstDelegate_4Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_4Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 4); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); T_Parameter2 argument2 = arguments.extract<T_Parameter2>(2); T_Parameter3 argument3 = arguments.extract<T_Parameter3>(3); (object_pointer_->*function_)(argument0, argument1, argument2, argument3); last_return_ = 0; } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_5Parameters template <typename T_Return, typename T_ClassType, typename T_Parameter0, typename T_Parameter1, typename T_Parameter2, typename T_Parameter3, typename T_Parameter4> struct ConstDelegate_5Parameters : public ConstMemberFunction_5Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4> { typedef T_Return (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4) const; ConstDelegate_5Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_5Parameters<T_Return, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 5); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); T_Parameter2 argument2 = arguments.extract<T_Parameter2>(2); T_Parameter3 argument3 = arguments.extract<T_Parameter3>(3); T_Parameter3 argument4 = arguments.extract<T_Parameter4>(4); last_return_ = (object_pointer_->*function_)(argument0, argument1, argument2, argument3, argument4); } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; // ConstDelegate_5Parameters - void return type specialization template <typename T_ClassType, typename T_Parameter0, typename T_Parameter1, typename T_Parameter2, typename T_Parameter3, typename T_Parameter4> struct ConstDelegate_5Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4> : public ConstMemberFunction_5Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4> { typedef void (T_ClassType::*FunctionType)(T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4) const; ConstDelegate_5Parameters(FunctionType function, T_ClassType * object_pointer, AnyStack const & default_arguments=AnyStack()) : ConstMemberFunction_5Parameters<void, T_ClassType, T_Parameter0, T_Parameter1, T_Parameter2, T_Parameter3, T_Parameter4>(function, default_arguments), object_pointer_(object_pointer) {} virtual void operator()(AnyStack & arguments) { // make use of default arguments, if needed mergeArgumentsWithDefaultArguments(arguments, default_arguments_, 5); T_Parameter0 argument0 = arguments.extract<T_Parameter0>(0); T_Parameter1 argument1 = arguments.extract<T_Parameter1>(1); T_Parameter2 argument2 = arguments.extract<T_Parameter2>(2); T_Parameter3 argument3 = arguments.extract<T_Parameter3>(3); T_Parameter4 argument4 = arguments.extract<T_Parameter4>(4); (object_pointer_->*function_)(argument0, argument1, argument2, argument3, argument4); last_return_ = 0; } virtual void* getObjectPointer(void) const { return object_pointer_; } private: T_ClassType * object_pointer_; }; #endif // ndef CONSTDELEGATE_HPP_INCLUDED_
[ "westleyargentum@259acd2b-3792-e4e4-6ce2-44c093ac8a23" ]
[ [ [ 1, 412 ] ] ]
68dd8c11284bb8c798d0a15070124ff3eb27fb46
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-downloader/wxCURL/samples/curl_app/wxFTPRmdirDialog.cpp
46accee058e99478ded87900cb5e80fff2070717
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,755
cpp
/******************************************* * base.cpp * Created by Casey O'Donnell on Tue Jun 29 2004. * Copyright (c) 2004 Casey O'Donnell. All rights reserved. * Licence: wxWidgets Licence ******************************************/ #include "wxcurl/wxcurl_config.h" #include <wx/xrc/xmlres.h> #include <wxcurl/ftp.h> #include "wxFTPRmdirDialog.h" ////////////////////////////////////////////////////////////////////// // Resources ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Constants ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Event Tables and Other Macros for wxWindows ////////////////////////////////////////////////////////////////////// // the event tables connect the wxWindows events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. IMPLEMENT_CLASS(wxFTPRmdirDialog, wxDialog) BEGIN_EVENT_TABLE(wxFTPRmdirDialog, wxDialog) EVT_BUTTON(XRCID("rmdir_button"), wxFTPRmdirDialog::OnRmdir) END_EVENT_TABLE() ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// wxFTPRmdirDialog::wxFTPRmdirDialog(wxWindow* pParent) { wxXmlResource::Get()->LoadDialog(this, pParent, "rmdir_ftp_dialog"); SetSize(400, -1); m_pRmdirCtrl = XRCCTRL(*this, "rmdir_text_ctrl", wxTextCtrl); m_pUserCtrl = XRCCTRL(*this, "user_text_ctrl", wxTextCtrl); m_pPassCtrl = XRCCTRL(*this, "pass_text_ctrl", wxTextCtrl); m_pResponseCtrl = XRCCTRL(*this, "response_text_ctrl", wxTextCtrl); if(m_pRmdirCtrl && m_pUserCtrl && m_pPassCtrl) { m_szDefaultRmdir = m_pRmdirCtrl->GetValue(); m_szDefaultUser = m_pUserCtrl->GetValue(); m_szDefaultPass = m_pPassCtrl->GetValue(); } } wxFTPRmdirDialog::~wxFTPRmdirDialog() { } ////////////////////////////////////////////////////////////////////// // Event Handlers ////////////////////////////////////////////////////////////////////// void wxFTPRmdirDialog::OnRmdir(wxCommandEvent& WXUNUSED(event)) { if(m_pRmdirCtrl && m_pUserCtrl && m_pPassCtrl) { wxString szRmdir = m_pRmdirCtrl->GetValue(); wxString szUser = m_pUserCtrl->GetValue(); wxString szPass = m_pPassCtrl->GetValue(); wxString szResponse; if((szRmdir == m_szDefaultRmdir)) { wxMessageBox("Please change the RMDIR location.", "Error...", wxICON_INFORMATION|wxOK, this); } else if((szUser == m_szDefaultUser) && (szPass == m_szDefaultPass)) { wxMessageBox("Please change the username or password.", "Error...", wxICON_INFORMATION|wxOK, this); } else { // Do it! wxCurlFTP ftp(szRmdir, szUser, szPass); if(ftp.RmDir()) { szResponse = "SUCCESS!\n\n"; szResponse += wxString::Format("\nResponse Code: %d\n\n", ftp.GetResponseCode()); szResponse += ftp.GetResponseHeader(); szResponse += "\n\n"; szResponse += ftp.GetResponseBody(); if(m_pResponseCtrl) m_pResponseCtrl->SetValue(szResponse); } else { szResponse = "FAILURE!\n\n"; szResponse += wxString::Format("\nResponse Code: %d\n\n", ftp.GetResponseCode()); szResponse += ftp.GetResponseHeader(); szResponse += "\n\n"; szResponse += ftp.GetResponseBody(); szResponse += "\n\n"; szResponse += ftp.GetErrorString(); if(m_pResponseCtrl) m_pResponseCtrl->SetValue(szResponse); } } } }
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 118 ] ] ]
44f5d1bc8702d5448d583ec990f481504f91a3b2
740ed7e8d98fc0af56ee8e0832e3bd28f08cf362
/src/game/captain_badass/ThrowingAxe.h
d02c93e3318d2e852cc95d4f2ef84ea1da780008
[]
no_license
fgervais/armconsoledemogame
420c53f926728b30fe1723733de2f32961a6a6d9
9158c0e684db16c4327b51aec45d1e4eed96b2d4
refs/heads/master
2021-01-10T11:27:43.912609
2010-07-29T18:53:06
2010-07-29T18:53:06
44,270,121
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
h
/* * Buster.h * * Created on: Mar 8, 2010 * Author: fournierseb */ #ifndef THROWINGAXE_H_ #define THROWINGAXE_H_ #include "Entity.h" #include <stdint.h> class Environment; class ThrowingAxeState; class VideoMemory; class Collider; class Wave; class Random; class ThrowingAxe : public Entity { public: ThrowingAxe(ThrowingAxeState* initialState, Environment* environment, uint32_t positionX, uint32_t positionY); virtual ~ThrowingAxe(); void setState(ThrowingAxeState* state); // Base class override virtual void update(); virtual void collideWith(Collider*); virtual void collideWith(Megaman*); virtual void collideWith(Metool*); // SoundFX Accessors Wave* getShotSoundFX() { return ShotSoundFX; } Wave* getCollideSoundFX() { return collideSoundFX; } // Action functions void shotLeft(); void shotRight(); private: // Current state ThrowingAxeState* initialState; ThrowingAxeState* currentState; // SoundFX static Wave* ShotSoundFX; static Wave* collideSoundFX; Random* randomGen; //uint32_t test; }; #endif /* MEGAMAN_H_ */
[ "fournierseb2@051cbfc0-75b8-dce1-6088-688cefeb9347" ]
[ [ [ 1, 61 ] ] ]
c24d1d7abdd05a37c60a74e6946a29eec0a328fe
09a9b91bd52dee4764b8fb0605f949a98df05f68
/Dialogs.cpp
3c8e4c56a5ade9c5c156650d17cd37a20107a792
[]
no_license
xmas25/iPod_Recovery
b042b81c382f38f2bd814bbb463696bbb906f872
84a03c172ba6e839597056840e24dba487de0338
refs/heads/master
2023-03-20T17:28:09.521694
2010-03-15T15:25:45
2010-03-15T15:25:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
/* File: Dialogs.cpp * Creation Date: 12/23/2009 5:17PM * Last Modified Date: 12/23/2009 5:17PM * Version: 0.0.1 * Contact: Adam Lamers <[email protected]> */ #include "Dialogs.h" char* Dialogs::OpenFile(HWND parent, LPSTR filter) { OPENFILENAME ofn; char *szFileName = (char*)malloc(MAX_PATH); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = parent; ofn.lpstrFilter = filter; ofn.lpstrFile = szFileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = "txt"; if(GetOpenFileName(&ofn)) return szFileName; else return NULL; } char* Dialogs::FolderBrowser(HWND parent) { BROWSEINFO bi; char *szSelectedFolder = (char*)malloc(MAX_PATH); ZeroMemory(&bi, sizeof(bi)); bi.hwndOwner = parent; bi.pidlRoot = NULL; bi.pszDisplayName = szSelectedFolder; bi.lpszTitle = "Select a Folder"; LPITEMIDLIST idl = SHBrowseForFolder(&bi); if(idl != NULL) { if(!SHGetPathFromIDList(idl, szSelectedFolder)) return NULL; return szSelectedFolder; } else return NULL; }
[ [ [ 1, 45 ] ] ]
3f0c14c9ddd2d4c492cb16b7dfbd99150ca3f1a8
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/Nuclex/Support/Collection.h
b511ce09948b4e394ca896df43f1e8735b05f5fc
[]
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
3,063
h
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Synchronization.h - Thread synchronization  // // ### # # ###  // // # ### # ### Helper classes for thread synchronization  // // # ## # # ## ##  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_SUPPORT_COLLECTION_H #define NUCLEX_SUPPORT_COLLECTION_H #include "Nuclex/Nuclex.h" #include "Nuclex/Support/String.h" #include "Nuclex/Support/Exception.h" #include <map> namespace Nuclex { namespace Support { //  // //  Nuclex::Support::Collection  // //  // /// Collection /** A collection of named objects which can be manipulated by a standard set of accessor methods */ template< typename ItemType > class Collection { public: typedef typename ItemType ItemType; class Enumerator { // ... }; NUCLEX_API const shared_ptr<ItemType> &get(const string &sName) const { ItemMap::const_iterator ItemIt = m_Items.find(sName); if(ItemIt == m_Items.end()) throw FailedException("Nuclex::Support::Collection::get()", string("Item '") + sName + "' not found"); return ItemIt->second; } NUCLEX_API bool has(const string &sName) const { return m_Items.find(sName) != m_Items.end(); } NUCLEX_API void add(const string &sName, const shared_ptr<ItemType> &spItem) { ItemMap::const_iterator ItemIt = m_Items.find(sName); if(ItemIt != m_Items.end()) throw FailedException("Nuclex::Support::Collection::add()", string("An item with the name '") + sName + "' already exists"); m_Items.insert(ItemMap::value_type(sName, spItem)); } NUCLEX_API void remove(const string &sName) { ItemMap::const_iterator ItemIt = m_Items.find(sName); if(ItemIt == m_Items.end()) throw FailedException("Nuclex::Support::Collection::remove()", string("An item with the name '") + sName + "' does not exist"); m_Items.erase(ItemIt); } NUCLEX_API void clear() { m_Items.clear(); } NUCLEX_API shared_ptr<Enumerator> enumerate() const { return shared_ptr<Enumerator>(new Enumerator(m_Items)); } private: typedef std::map<string, shared_ptr<ItemType> > ItemMap; ItemMap m_Items; }; }} // namespace Nuclex::Support #endif // NUCLEX_SUPPORT_COLLECTION_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 84 ] ] ]
992e24016f36a48adfba31a18c05b64b14761f40
8aa65aef3daa1a52966b287ffa33a3155e48cc84
/Source/Common/Exceptions.h
deb5855169dc5c92496a5a41da3c0aadba3acd91
[]
no_license
jitrc/p3d
da2e63ef4c52ccb70023d64316cbd473f3bd77d9
b9943c5ee533ddc3a5afa6b92bad15a864e40e1e
refs/heads/master
2020-04-15T09:09:16.192788
2009-06-29T04:45:02
2009-06-29T04:45:02
37,063,569
1
0
null
null
null
null
UTF-8
C++
false
false
1,289
h
#pragma once namespace P3D { /* Base class for all exceptions. */ class Exception : public std::exception { public: Exception(const String& message, const Exception* inner = NULL); const String& GetInnerExceptionMessage() const { return _inner; }; const String& GetExceptionMessage() const { return _message; } /* Returns string with description of this exception and all inner exceptions. */ virtual const String GetFullDescription() const; protected: const String _inner; const String _message; }; /* Exception that terminates the program. */ class FatalException : public Exception { public: FatalException(const String& message, const Exception* inner = NULL) : Exception(message, inner) { } }; /* The operation is not supported. */ class NotSupportedException : public Exception { public: NotSupportedException() : Exception(L"The operation is not supported.", NULL) { } NotSupportedException(const String& message, const Exception* inner = NULL) : Exception(message, inner) { } }; }
[ "vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1" ]
[ [ [ 1, 51 ] ] ]
b2e2499baf7d257111afe5ec3c9ede62c6a035bb
b8fbe9079ce8996e739b476d226e73d4ec8e255c
/src/engine/rb_extmath/voronoi.h
0764aa47b24e4739fcc2a11cc7c031bb73479606
[]
no_license
dtbinh/rush
4294f84de1b6e6cc286aaa1dd48cf12b12a467d0
ad75072777438c564ccaa29af43e2a9fd2c51266
refs/heads/master
2021-01-15T17:14:48.417847
2011-06-16T17:41:20
2011-06-16T17:41:20
41,476,633
1
0
null
2015-08-27T09:03:44
2015-08-27T09:03:44
null
UTF-8
C++
false
false
6,346
h
/* * The author of this software is Steven Fortune. Copyright (c) 1994 by AT&T * Bell Laboratories. * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. */ /* * This code was originally written by Stephan Fortune in C code. I, Shane O'Sullivan, * have since modified it, encapsulating it in a C++ class and, fixing memory leaks and * adding accessors to the Voronoi Edges. * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. */ #ifndef VORONOI_DIAGRAM_GENERATOR #define VORONOI_DIAGRAM_GENERATOR #ifndef NULL #define NULL 0 #endif #define DELETED -2 #define le 0 #define re 1 #include "vec2.h" #include "frame.h" struct Freenode { struct Freenode *nextfree; }; struct FreeNodeArrayList { struct Freenode* memory; struct FreeNodeArrayList* next; }; struct Freelist { struct Freenode *head; int nodesize; }; struct Point { float x,y; }; // structure used both for sites and for vertices struct Site { struct Point coord; int sitenbr; int refcnt; }; struct Edge { float a,b,c; struct Site *ep[2]; struct Site *reg[2]; int edgenbr; }; struct GraphEdge { float x1,y1,x2,y2; struct GraphEdge* next; }; struct Halfedge { struct Halfedge *ELleft, *ELright; struct Edge *ELedge; int ELrefcnt; char ELpm; struct Site *vertex; float ystar; struct Halfedge *PQnext; }; class Voronoi { public: Voronoi(); ~Voronoi(); bool Generate( const Vec2* pSites, int numPoints, const Frame& bounds, float minDist = 0 ); void ResetIterator() { iteratorEdges = allEdges; } bool GetNextEdge( Vec2& a, Vec2& b ) { if(iteratorEdges == 0) return false; a.x = iteratorEdges->x1; b.x = iteratorEdges->x2; a.y = iteratorEdges->y1; b.y = iteratorEdges->y2; iteratorEdges = iteratorEdges->next; return true; } private: void cleanup(); void cleanupEdges(); char *getfree(struct Freelist *fl); struct Halfedge *PQfind(); int PQempty(); struct Halfedge **ELhash; struct Halfedge *HEcreate(), *ELleft(), *ELright(), *ELleftbnd(); struct Halfedge *HEcreate(struct Edge *e,int pm); struct Point PQ_min(); struct Halfedge *PQextractmin(); void freeinit(struct Freelist *fl,int size); void makefree(struct Freenode *curr,struct Freelist *fl); void geominit(); void plotinit(); bool voronoi(int triangulate); void ref(struct Site *v); void deref(struct Site *v); void endpoint(struct Edge *e,int lr,struct Site * s); void ELdelete(struct Halfedge *he); struct Halfedge *ELleftbnd(struct Point *p); struct Halfedge *ELright(struct Halfedge *he); void makevertex(struct Site *v); void out_triple(struct Site *s1, struct Site *s2,struct Site * s3); void PQinsert(struct Halfedge *he,struct Site * v, float offset); void PQdelete(struct Halfedge *he); bool ELinitialize(); void ELinsert(struct Halfedge *lb, struct Halfedge *newHe); struct Halfedge * ELgethash(int b); struct Halfedge *ELleft(struct Halfedge *he); struct Site *leftreg(struct Halfedge *he); void out_site(struct Site *s); bool PQinitialize(); int PQbucket(struct Halfedge *he); void clip_line(struct Edge *e); char *myalloc(unsigned n); int right_of(struct Halfedge *el,struct Point *p); struct Site *rightreg(struct Halfedge *he); struct Edge *bisect(struct Site *s1,struct Site *s2); float dist(struct Site *s,struct Site *t); struct Site *intersect(struct Halfedge *el1, struct Halfedge *el2, struct Point *p=0); void out_bisector(struct Edge *e); void out_ep(struct Edge *e); void out_vertex(struct Site *v); struct Site *nextone(); void pushGraphEdge(float x1, float y1, float x2, float y2); void openpl(); void line(float x1, float y1, float x2, float y2); void circle(float x, float y, float radius); void range(float minX, float minY, float maxX, float maxY); struct Freelist hfl; struct Halfedge *ELleftend, *ELrightend; int ELhashsize; int triangulate, sorted, plot, debug; float xmin, xmax, ymin, ymax, deltax, deltay; struct Site *sites; int nsites; int siteidx; int sqrt_nsites; int nvertices; struct Freelist sfl; struct Site *bottomsite; int nedges; struct Freelist efl; int PQhashsize; struct Halfedge *PQhash; int PQcount; int PQmin; int ntry, totalsearch; float pxmin, pxmax, pymin, pymax, cradius; int total_alloc; float borderMinX, borderMaxX, borderMinY, borderMaxY; FreeNodeArrayList* allMemoryList; FreeNodeArrayList* currentMemoryBlock; GraphEdge* allEdges; GraphEdge* iteratorEdges; float minDistanceBetweenSites; }; int scomp(const void *p1,const void *p2); #endif
[ [ [ 1, 244 ] ] ]
60b3d9578dcba1da95a4abb00ffbd2d83fdef015
5e9d631cf2e112b277c635976f3f6daaeb44ff76
/mycp.cc
0ab392bd7674d4955ebf390de94c38b939b8413f
[]
no_license
katti/serverstorage
374205035dcc0ecc83989817e71d87b12ce9f9a6
3d63f87c361cfa530c11eee6252413b0874f44aa
refs/heads/master
2021-01-10T20:50:55.856349
2008-08-22T12:45:38
2008-08-22T12:45:38
41,227
1
0
null
null
null
null
UTF-8
C++
false
false
3,534
cc
/* * Copyright (c) 2008 Samir Katti([email protected]) * mycp.cc * This file is implements copy command * * FileStorage 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. * * FileStorage 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, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <arpa/inet.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/wait.h> #include <unistd.h> #include<iostream> using namespace std; #define SOCK_PATH "echo_socket" string make_string(char* coming) { string data(coming); return coming; } int main(void) { int s, t, len; struct sockaddr_un remote; char str[100]; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } printf("Trying to connect...\n"); remote.sun_family = AF_UNIX; strcpy(remote.sun_path, SOCK_PATH); len = strlen(remote.sun_path) + sizeof(remote.sun_family); if (connect(s, (struct sockaddr *)&remote, len) == -1) { perror("connect"); exit(1); } printf("Connected.\n"); printf("This is mycp command\n Enter command in \"mycp filename1 filename2\" format\n"); printf("Enter Q or q to quit\n"); while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) { char *cmdmain1,result[0]; string command,filename1,filename2; cmdmain1 = strtok(str," "); command = make_string(cmdmain1); //printf("command %s\n",command); if(command == "mycp") { cmdmain1 = strtok(NULL," "); filename1 = make_string(cmdmain1); cmdmain1=strtok(NULL,"\n"); filename2 = make_string(cmdmain1); sprintf(str,"p %s %s",filename1.c_str(),filename2.c_str()); if (send(s, str, strlen(str), 0) == -1) { perror("send"); exit(1); } if ((t=recv (s, result, 1, 0)) > 0) { switch(result[0]) { case '0': printf("File Copying Successfull\n"); break; case '1': printf("File Name does not exist\n"); break; case '2': printf("Disk Full\n"); break; } } else { if (t < 0) perror("recv"); else printf("Server closed connection .... Quitting Client\n"); exit(1); } } else if(str[0]=='q' || str[0]=='Q') { if (send(s, str, 1, 0) == -1) { perror("send"); exit(1); } printf("Quitting Client\n"); break; } else { printf("Invalid command\n"); } strcpy(str,""); }//end of while loop close(s); return 0; }
[ [ [ 1, 136 ] ] ]
7d12ed3fec71aa4fd57035083ae2e269c7b7319d
f35188f3982c8791d4ea175afb4749e81425e9d4
/modules/ti.Growl/growl_module.cpp
dd1372e6eb557f2b56bff10848d33f59dd267f5c
[ "Apache-2.0" ]
permissive
mital/titanium_desktop
131978cf4e622eea7e7f8c5e6db00957df6b2d24
4f8ad0aeb82eab9bf6bfe92d4c16173a06c40d63
refs/heads/master
2023-09-03T17:32:33.044825
2009-12-16T06:03:19
2009-12-16T06:03:19
233,112
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
cpp
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <kroll/kroll.h> #include "growl_module.h" #include "growl_binding.h" #if defined(OS_OSX) #include "osx/growl_osx.h" #elif defined(OS_WIN32) #include "win32/snarl_win32.h" #elif defined(OS_LINUX) #include "libnotify/libnotify_binding.h" #endif using namespace kroll; using namespace ti; namespace ti { KROLL_MODULE(GrowlModule, STRING(MODULE_NAME), STRING(MODULE_VERSION)); void GrowlModule::Initialize() { #if defined(OS_OSX) // load our variables GrowlOSX *g = new GrowlOSX(host->GetGlobalObject()); binding = g; g->CopyToApp(host,this); #elif defined(OS_WIN32) binding = new SnarlWin32(host->GetGlobalObject()); #elif defined(OS_LINUX) binding = new LibNotifyBinding(host->GetGlobalObject()); #endif // set our ti.Growl KValueRef value = Value::NewObject(binding); host->GetGlobalObject()->Set("Growl", value); } void GrowlModule::Stop() { } }
[ [ [ 1, 39 ], [ 41, 48 ] ], [ [ 40, 40 ] ] ]
03bb2f223f3662beded391cf1c06d204a1cb8fdd
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/InterfaceSurfMgr.cpp
56deb46e9c31740d2b247dab90b483551959e344
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
4,154
cpp
// InterfaceSurfMgr.cpp: implementation of the CInterfaceSurfMgr class. // ////////////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "ltbasedefs.h" #include "iclientshell.h" #include "InterfaceSurfMgr.h" #ifndef __PSX2 #include <mbstring.h> #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CInterfaceSurfMgr::CInterfaceSurfMgr() { m_pClientDE=LTNULL; } CInterfaceSurfMgr::~CInterfaceSurfMgr() { Term(); } // Intialization LTBOOL CInterfaceSurfMgr::Init(ILTClient *pClientDE) { m_pClientDE=pClientDE; if (m_pClientDE == LTNULL) { return LTFALSE; } return LTTRUE; } // Termination void CInterfaceSurfMgr::Term() { if (!m_pClientDE) { return; } FreeAllSurfaces(); return; } void CInterfaceSurfMgr::FreeAllSurfaces() { unsigned int i; for (i=0; i < m_sharedSurfaceArray.GetSize(); i++) { m_pClientDE->DeleteSurface(m_sharedSurfaceArray[i]->m_hSurface); debug_delete(m_sharedSurfaceArray[i]); } m_sharedSurfaceArray.SetSize(0); } // Returns a handle to a surface from its bitmap filename. HSURFACE CInterfaceSurfMgr::GetSurface(char *lpszSurface) { if (!lpszSurface) { return LTNULL; } // Search for the surface to see if it has been loaded yet int nIndex=FindSurfaceIndex(lpszSurface); // Return the surface if it is already loaded if (nIndex != -1) { return m_sharedSurfaceArray[nIndex]->m_hSurface; } // Load the surface HSURFACE hSurface=m_pClientDE->CreateSurfaceFromBitmap(lpszSurface); if (hSurface == LTNULL) { return LTNULL; } // Create the new resource class CSharedSurface *pSharedSurface=debug_new(CSharedSurface); // Copy the filename #ifdef __PSX2 int nBufferSize=strlen(lpszSurface)+1; #else int nBufferSize=_mbstrlen(lpszSurface)+1; #endif pSharedSurface->m_lpszPathName=debug_newa(char, nBufferSize); #ifdef __PSX2 strncpy(pSharedSurface->m_lpszPathName, lpszSurface, nBufferSize); #else _mbsncpy((unsigned char*)pSharedSurface->m_lpszPathName, (const unsigned char*)lpszSurface, nBufferSize); #endif pSharedSurface->m_hSurface=hSurface; // Copy the surface handle m_sharedSurfaceArray.Add(pSharedSurface); // Add the class to the array // Return the surface handle return pSharedSurface->m_hSurface; } // Frees a surface. It is only removed when its reference count reaches zero void CInterfaceSurfMgr::FreeSurface(char *lpszSurface) { int nIndex=FindSurfaceIndex(lpszSurface); if (nIndex == -1) { return; } FreeSurface(nIndex); } // Frees a surface. It is only removed when its reference count reaches zero void CInterfaceSurfMgr::FreeSurface(HSURFACE hSurface) { int nIndex=FindSurfaceIndex(hSurface); if (nIndex == -1) { return; } FreeSurface(nIndex); } // Frees a surface based on its index into the surface array void CInterfaceSurfMgr::FreeSurface(int nIndex) { if (!m_pClientDE) { return; } m_pClientDE->DeleteSurface(m_sharedSurfaceArray[nIndex]->m_hSurface); debug_delete(m_sharedSurfaceArray[nIndex]); m_sharedSurfaceArray.Remove(nIndex); } // Finds a surface index into the surface array int CInterfaceSurfMgr::FindSurfaceIndex(char *lpszSurface) { unsigned int i; for (i=0; i < m_sharedSurfaceArray.GetSize(); i++) { #ifdef __PSX2 if (stricmp(m_sharedSurfaceArray[i]->m_lpszPathName, lpszSurface) == 0) #else if (_mbsicmp((const unsigned char*)m_sharedSurfaceArray[i]->m_lpszPathName, (const unsigned char*)lpszSurface) == 0) #endif { return i; } } // Surface was not found return -1; } // Finds a surface index into the surface array int CInterfaceSurfMgr::FindSurfaceIndex(HSURFACE hSurface) { unsigned int i; for (i=0; i < m_sharedSurfaceArray.GetSize(); i++) { if (m_sharedSurfaceArray[i]->m_hSurface == hSurface) { return i; } } // Surface was not found return -1; }
[ [ [ 1, 184 ] ] ]
41041b3008eb1359fbcb4a6b2d01c8b75b4bb584
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/Modules/BehaviorControl/CommonSymbols/KeySymbols.h
526eeb8c1c450c8569cdfbe4ea23d02328bbb12b
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
1,517
h
/** * @file KeySymbols.h * * Declaration of class KeySymbols. * * @author Judith Müller */ #ifndef __KeySymbols_h_ #define __KeySymbols_h_ #include "../Symbols.h" #include "Representations/Infrastructure/FrameInfo.h" #include "Representations/Infrastructure/KeyStates.h" /** * The Xabsl symbols that are defined in "switch_symbols.xabsl" * * @author Max Risler * @author Judith Müller */ class KeySymbols : public Symbols { public: /* * Constructor. * @param frameInfo A reference to the FrameInfo * @param switchState A reference to the SwitchState. */ KeySymbols(KeyStates const& keyStates, FrameInfo const& frameInfo) : keyStates(keyStates), frameInfo(frameInfo) { theInstance = this; for (int i=0; i < KeyStates::numberOfKeys; i++) { pressed_and_released[i] = false; last_pressed_time[i] = 0; last_not_pressed_time[i] = 0; } } PROCESS_WIDE_STORAGE_STATIC KeySymbols* theInstance; /**< Points to the only instance of this class in this process or is 0 if there is none. */ /** A reference to the keyState */ KeyStates const& keyStates; FrameInfo const& frameInfo; bool pressed_and_released[KeyStates::numberOfKeys]; unsigned last_pressed_time[KeyStates::numberOfKeys]; unsigned last_not_pressed_time[KeyStates::numberOfKeys]; /** registers the symbols at an engine */ void registerSymbols(xabsl::Engine& engine); void update(); }; #endif // __KeySymbols_h_
[ "alon@rogue.(none)" ]
[ [ [ 1, 61 ] ] ]
9eced696182aa373a08d74c8ece5b769fe8a7dde
bc3073755ed70dd63a7c947fec63ccce408e5710
/src/Qt/UserInterface/ConnectionFailed.h
1d873a633a74d2c702326db84009ad92de1eee66
[]
no_license
ptrefall/ste6274gamedesign
9e659f7a8a4801c5eaa060ebe2d7edba9c31e310
7d5517aa68910877fe9aa98243f6bb2444d533c7
refs/heads/master
2016-09-07T18:42:48.012493
2011-10-13T23:41:40
2011-10-13T23:41:40
32,448,466
1
0
null
null
null
null
UTF-8
C++
false
false
442
h
#pragma once #include <QtGui/QDialog.h> #include <ui_connectionFailed.h> #include <QTime> class Game; namespace Ui { class Join; class ConnectionFailed : public QDialog, public Ui::connectionFailedDialog { Q_OBJECT public: ConnectionFailed(Join *join, Game &game, QWidget *parent = 0, Qt::WFlags flags = 0); virtual ~ConnectionFailed(); private slots: void onClose(); private: Join *join; }; }
[ "[email protected]@2c5777c1-dd38-1616-73a3-7306c0addc79" ]
[ [ [ 1, 29 ] ] ]
d4670c0bd935e4b7cf9a8fe71d6226d046a5bd18
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/EmptyProject.cpp
315f2f0ef4e9b5fbb49a3374f85c0b23a2e67481
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
67,242
cpp
/*! * @file EmptyProject.cpp * @brief main()/WinMain() 함수가 있는 파일입니다. * * EP 전반에서 쓰이는 전역 변수의 할당/초기화/해제를 담당하고 있습니다. * EP는 DXUT(DirectX Utility Kit) 소스 코드를 기반으로 작성되었습니다. * DXUT는 DirectX 라이브러리를 좀 더 편리하게 사용할 수 있도록 도와주는 랩퍼 라이브러리라고 * 볼 수 있습니다. * DXUT는 화면 출력이나 입력, UI, 카메라 관련 클래스 및 비디오 게임에서 자주 사용되는 * 아주 많은 요소에 대해 다양한 프레임워크와 클래스를 제공하지만 EP에서 사용된 * 주된 기능은 화면 출력을 위한 프레임워크 및 카메라 클래스입니다. 이외의 기능은 사용하지 * 않았습니다. * * 본 프로그램이 처음으로 실행되었을 상태부터 끝날때까지의 함수 호출 순서는 다음과 같습니다. * * -# WinMain * -# OnCreateDevice * -# OnResetDevice * -# OnFrameMove / OnFrameRender loop (주 루프) * -# OnLostDevice * -# OnDestroyDevice */ #include "EmptyProjectPCH.h" #include "EmptyProject.h" #include "resource.h" #include "BattleState.h" #include "IntroState.h" #include "EpCamera.h" #include "MenuState.h" #include "TopStateManager.h" #include "ScriptManager.h" #include "VideoMan.h" #include "WorldStateManager.h" #include "ShaderWrapper.h" #include "TileManager.h" #include "World.h" #include "Dialog.h" #include "SpriteManager.h" #include "Sprite.h" #include "EpLight.h" #include "particlesystem.h" #include "Skill.h" #include "SkillManager.h" #include "EpReplicaManagerConnection.h" #include "EpUser.h" #include "VideoManDx9.h" G g_g; WorldManager* g_wm = 0; TopStateManager* g_tsm = 0; WorldStateManager* g_wsm = 0; ScriptManager* g_scriptManager = 0; // Set to zero is 'CRUCIAL!' SkillManager* g_skillManager = 0; SpriteManager* g_spriteManager = 0; EpLight* g_epLight = 0; SCREEN_VERTEX g_Vertex[4]; //LPD3DXEFFECT g_pEffect = 0; D3DXHANDLE g_tech = 0; LPDIRECT3DVERTEXBUFFER9 g_lineElement = 0; HANDLE g_scriptBindingFinishedEvent = 0; // Signal object to resolve multi-threaded problems on console thread and main app thread HANDLE g_consoleReleasedEvent = 0; // Signal object to resolve multi-threaded problems on console thread and main app thread LPD3DXMESH g_bst[BST_COUNT]; D3DCOLOR g_fillColor; // LPD3DXFONTs will be managed at global scope. LPD3DXFONT g_pFont = 0; LPD3DXFONT g_unitNameFont = 0; LPD3DXFONT g_dlgNameFont = 0; LPD3DXFONT g_dlgContentFont = 0; // CreditState LPD3DXFONT g_d3dxFont = 0; LPD3DXFONT g_d3dxFontBig = 0; // Battle State LPD3DXFONT g_fontBattle2 = 0; LPD3DXFONT g_fontBattle = 0; LPD3DXFONT g_fontSkill = 0; LPD3DXFONT g_fontSkillDescription = 0; LPD3DXFONT g_fontStat = 0; Tcl_Interp* g_consoleInterp = 0; std::wstring g_debugBuffer; bool g_bTileGrid = false; LPDIRECT3DTEXTURE9 g_pFullScreenRenderTarget = 0; LPDIRECT3DSURFACE9 g_pFullScreenRenderTargetSurf = 0; LPDIRECT3DTEXTURE9 g_sepiaRenderTarget = 0; LPDIRECT3DSURFACE9 g_sepiaRenderTargetSurf = 0; LPDIRECT3DTEXTURE9 g_radialBlurRenderTarget = 0; LPDIRECT3DSURFACE9 g_radialBlurRenderTargetSurf = 0; PostSepiaShader* g_postSepiaShader = 0; PostRadialBlurShader* g_postRadialBlurShader = 0; BombShader* g_bombShader = 0; // Particle System related int g_nActiveSystem = 0; CParticleSystem* g_pParticleSystems[6]; bool g_bParticleVisible = false; // RakNet RakPeerInterface* g_clientPeer = 0; ///< RakNet Client Peer RakNet::RPC3 g_rpc3Inst; NetworkIDManager g_networkIDManager; // The system that performs most of our functionality for this demo RakNet::ReplicaManager2* g_replicaManager = 0; // Instance of the class that creates the object we use to represent connections EpReplicaManagerConnectionFactory g_connectionFactory; // Called from EpCommonLibrary NetworkIDManager& GetNetworkIdManager() { return g_networkIDManager; } RakPeerInterface* GetRakPeer() { return g_clientPeer; } bool QueryIsNetworkServer() { return false; } void AddToCurrentWorld( UnitBase* unitBase ) { GetWorldManager().getCurWorld()->addUnit( unitBase ); } ////////////////////////////////////////////////////////////////////////// void ConfigureShaders( LPDIRECT3DDEVICE9 pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc ); void OnResetParticleSystem( LPDIRECT3DDEVICE9 pd3dDevice ); void OnD3D9LostDeviceParticleSystem(); void ConfigureTileGridGeometry( LPDIRECT3DDEVICE9 pd3dDevice ); void ConfigureTestGeometry( LPDIRECT3DDEVICE9 pd3dDevice ); void SetupFullscreenQuad( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ); void ConnectToServer(); void DisconnectFromServer(); void PrintHelloWorld( int number ) { odprintf( "Hello World from RPC!: %d\n", number ); } //-------------------------------------------------------------------------------------- // Rejects any D3D9 devices that aren't acceptable to the app by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D9DeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { // Typically want to skip back buffer formats that don't support alpha blending IDirect3D9* pD3D = DXUTGetD3D9Object(); if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) return false; return true; } //-------------------------------------------------------------------------------------- // Before a device is created, modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { //pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_MULTITHREADED; // For multi-threaded console return true; } /*! \brief 디바이스 리셋 이벤트에도 살아남는 개체를 생성합니다. \param pd3dDevice D3D9 디바이스 \param pBackBufferSurfaceDesc 백 버퍼 서피스 설정값을 참조하기 위한 포인터 \param pUserContext 사용하지 않는 매개변수 \details DXUT에서 정의된 콜백 함수입니다. 본 함수는 D3D9 디바이스가 얻어진 이후 실행됩니다. 이 함수에서는 디바이스 리셋 이벤트와 상관없이 항상(디바이스 로스트 전까지) 유효한 D3D 개체를 생성하게 됩니다. 일반적으로 디바이스 리셋 이벤트가 발생한 경우 D3D9 디바이스가 재생성되기 때문에 이에 의존적인 모든 개체를 다시 생성하거나 갱신해야만 합니다. 그러나 D3DPOOL_MANAGED 플래그로 생성된 D3DX 관련 개체는 디바이스 리셋 이벤트시 Direct3D가 자동으로 개체의 갱신을 책임지게 됩니다. 이렇듯 디바이스 리셋 이벤트에도 '살아남는' 개체의 경우 본 함수에서 생성하도록 합니다. 디바이스 리셋 이벤트에서 '살아남지 못하는' 개체의 할당 및 초기화는 OnD3D9ResetDevice()에서 호출해 주십시오. 참고로 처음 DXUT 소스 코드에는 아래와 같은 커맨트가 있었습니다. Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED) and aren't tied to the back buffer size 이후는 본 함수에서 일어나는 일 중 중요한 것을 나열한 것입니다. */ HRESULT CALLBACK OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { OutputDebugString( _T( " - INFO: OnCreateDevice called.\n" ) ); HRESULT hr = S_OK; UNREFERENCED_PARAMETER( hr ); /// - Aran 라이브러리의 D3D9 디바이스 값을 설정합니다. // ARAN3 INCOMPAT assert (GetVideoManagerDx9 ().GetDev () == 0); GetVideoManagerDx9 ().SetDev (pd3dDevice); /// - G::m_screenFlash를 초기화 GetG().m_screenFlash.onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc ); /// - 쉐이더 초기화 ConfigureShaders( pd3dDevice, pBackBufferSurfaceDesc ); /// - 타일 격자를 그리기 위한 프리미티브 및 기본 도형(::g_bst)을 초기화합니다. ConfigureTileGridGeometry( pd3dDevice ); ConfigureTestGeometry( pd3dDevice ); /// - 전역 광원을 설정합니다. GetEpLight().setupLight( pd3dDevice ); /// - 프로그램 전반에 쓰이는 폰트(LPD3DXFONT) 초기화 V_RETURN( D3DXCreateFont( pd3dDevice, 12, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Gulimche"), &g_pFont) ); V_RETURN( D3DXCreateFont( pd3dDevice, 26, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T( "Arial Black"), &g_unitNameFont ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 14, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Gulim"), &g_dlgContentFont) ); V_RETURN( D3DXCreateFont( pd3dDevice, 14, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Gulim"), &g_dlgNameFont) ); V_RETURN( D3DXCreateFont( pd3dDevice, 26, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T( "Palatino Linotype"), &g_d3dxFont ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 32, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T( "Palatino Linotype"), &g_d3dxFontBig ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 17, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("HYnamL"), &g_fontBattle2 ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 18, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Rockwell Extra Bold"), &g_fontBattle ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 20, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("HYnamL"), &g_fontSkill ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("HYnamL"), &g_fontSkillDescription ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 17, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET, OUT_RASTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("HYnamL"), &g_fontStat ) ); /// - 본 함수에서의 기본 초기화는 끝났습니다. 하부 구성원에게 OnCreateDevice 메시지를 전달합니다. GetTopStateManager().onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); GetWorldStateManager().onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); GetSpriteManager().onCreateDevice( pd3dDevice ); GetWorldManager().onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT) // or that are tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D9ResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { OutputDebugString( _T(" - INFO: OnResetDevice() called.\n") ); // ARAN3 INCOMPAT GetVideoManagerDx9 ().SetDev (pd3dDevice); GetG().m_scrWidth = pBackBufferSurfaceDesc->Width; GetG().m_scrHeight = pBackBufferSurfaceDesc->Height; HRESULT hr = S_OK; /// - 화면 해상도 값을 전역 변수 객체인 GetG()에 설정합니다. GetG().m_scrWidth = pBackBufferSurfaceDesc->Width; GetG().m_scrHeight = pBackBufferSurfaceDesc->Height; TCHAR scrSizeString[64]; StringCchPrintf( scrSizeString, 64, _T( "- INFO: Window width: %d / height: %d\n" ), GetG().m_scrWidth, GetG().m_scrHeight ); OutputDebugString( scrSizeString ); /// - GUI 요소나 고정된 2D 그래픽을 출력하기 위해 사용하는 orthogonal 뷰 변환 행렬을 설정합니다. ArnVec3 eye(0, 0, -50.0f), at(0, 0, 0), up(0, 1.0f, 0); ArnMatrixOrthoLH(&GetG().g_orthoProjMat, (FLOAT)pBackBufferSurfaceDesc->Width, (FLOAT)pBackBufferSurfaceDesc->Height, 0.1f, 100.0f); ArnMatrixLookAtLH(&GetG().g_fixedViewMat, &eye, &at, &up); GetG().g_fixedViewMat = GetG().g_fixedViewMat.transpose(); float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; GetG().m_camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 1.0f, 1000.0f ); pd3dDevice->SetRenderState( D3DRS_DITHERENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE ); pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE); pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE); pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); pd3dDevice->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR ); //g_fillColor = D3DCOLOR_ARGB( 0, 45, 50, 170 ); g_fillColor = D3DCOLOR_ARGB( 0, 0, 0, 0 ); GetG().m_screenFlash.onResetDevice( pd3dDevice, pBackBufferSurfaceDesc ); GetSpriteManager().onResetDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); GetTopStateManager().onResetDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); GetWorldManager().onResetDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); GetWorldStateManager().onResetDevice( pd3dDevice, pBackBufferSurfaceDesc, pUserContext ); D3DFORMAT d3dFormat = D3DFMT_A8R8G8B8; // Create a A8R8G8B8 render target texture. This will be used to render // the full screen and then rendered to the backbuffer using a quad. V_RETURN( D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pFullScreenRenderTarget ) ); // Create sepia render target V_RETURN( D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1, D3DUSAGE_RENDERTARGET, d3dFormat, D3DPOOL_DEFAULT, &g_sepiaRenderTarget ) ); // Create radial blur render target V_RETURN( D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1, D3DUSAGE_RENDERTARGET, d3dFormat, D3DPOOL_DEFAULT, &g_radialBlurRenderTarget ) ); // Store pointers to surfaces so we can call SetRenderTarget() later V_RETURN( g_pFullScreenRenderTarget->GetSurfaceLevel( 0, &g_pFullScreenRenderTargetSurf ) ); V_RETURN( g_sepiaRenderTarget->GetSurfaceLevel( 0, &g_sepiaRenderTargetSurf ) ); V_RETURN( g_radialBlurRenderTarget->GetSurfaceLevel( 0, &g_radialBlurRenderTargetSurf ) ); g_postSepiaShader->setFullscreenTexture( g_sepiaRenderTarget ); g_postRadialBlurShader->setFullscreenTexture( g_radialBlurRenderTarget ); SetupFullscreenQuad( pBackBufferSurfaceDesc ); g_pFont->OnResetDevice(); g_unitNameFont->OnResetDevice(); g_dlgNameFont->OnResetDevice(); g_dlgContentFont->OnResetDevice(); g_fontBattle2->OnResetDevice(); g_fontBattle->OnResetDevice(); g_fontSkill->OnResetDevice(); g_fontSkillDescription->OnResetDevice(); g_fontStat->OnResetDevice(); /// - 파티클 시스템 초기화 OnResetParticleSystem( pd3dDevice ); g_postRadialBlurShader->onResetDevice( pd3dDevice, pBackBufferSurfaceDesc ); g_postSepiaShader->onResetDevice( pd3dDevice, pBackBufferSurfaceDesc ); g_bombShader->onResetDevice( pd3dDevice, pBackBufferSurfaceDesc ); return hr; } /*! \brief 매 OnFrameMove() 시마다 RakNet 패킷 핸들링을 합니다. \details OnFrameMove() 마지막에 호출되는 함수입니다. 만일 클라이언트 피어 객체(::g_clientPeer)가 존재한다면 RakNet이 초기화되었다는 뜻이므로 여기서 지난 프레임부터 현재프레임 사이에 발생한 수신 패킷을 처리합니다. */ void OnFrameMoveNetworkProcess() { if ( g_clientPeer ) { Packet* p; for (p=g_clientPeer->Receive(); p; g_clientPeer->DeallocatePacket(p), p=g_clientPeer->Receive()) { switch (p->data[0]) { case ID_DISCONNECTION_NOTIFICATION: printf("ID_DISCONNECTION_NOTIFICATION\n"); break; case ID_ALREADY_CONNECTED: printf("ID_ALREADY_CONNECTED\n"); break; case ID_CONNECTION_ATTEMPT_FAILED: printf("Connection attempt failed\n"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("ID_NO_FREE_INCOMING_CONNECTIONS\n"); break; case ID_PONG: break; case ID_CONNECTION_REQUEST_ACCEPTED: // This tells the client they have connected printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); break; case ID_NEW_INCOMING_CONNECTION: printf("ID_NEW_INCOMING_CONNECTION\n"); break; case ID_RPC_REMOTE_ERROR: { // Recipient system returned an error switch (p->data[1]) { case RakNet::RPC_ERROR_NETWORK_ID_MANAGER_UNAVAILABLE: printf("RPC_ERROR_NETWORK_ID_MANAGER_UNAVAILABLE\n"); break; case RakNet::RPC_ERROR_OBJECT_DOES_NOT_EXIST: printf("RPC_ERROR_OBJECT_DOES_NOT_EXIST\n"); break; case RakNet::RPC_ERROR_FUNCTION_INDEX_OUT_OF_RANGE: printf("RPC_ERROR_FUNCTION_INDEX_OUT_OF_RANGE\n"); break; case RakNet::RPC_ERROR_FUNCTION_NOT_REGISTERED: printf("RPC_ERROR_FUNCTION_NOT_REGISTERED\n"); break; case RakNet::RPC_ERROR_FUNCTION_NO_LONGER_REGISTERED: printf("RPC_ERROR_FUNCTION_NO_LONGER_REGISTERED\n"); break; case RakNet::RPC_ERROR_CALLING_CPP_AS_C: printf("RPC_ERROR_CALLING_CPP_AS_C\n"); break; case RakNet::RPC_ERROR_CALLING_C_AS_CPP: printf("RPC_ERROR_CALLING_C_AS_CPP\n"); break; } printf("Function: %s", p->data+2); } } } } } /*! \brief 매 프레임마다 렌더링 이외의 게임 로직을 계산합니다. \param fTime 프로그램이 시작된 후 현재까지 흐른 시간을 초 단위로 나타냅니다. \param fElapsedTime 지난 프레임부터 현재 프레임까지 걸린 시간을 초 단위로 나타냅니다. \param pUserContext 사용하지 않는 매개변수 \warning 이 함수와 독립적으로 호출되는(즉, 이 함수로부터 호출되지 않는) 프레임 무브 관련 함수는 구조적으로 잘못된 것입니다. \details DXUT에서 정의된 콜백 함수입니다. 이 함수는 프레임이 렌더링 렌더링 될때마다 그 직전에 호출됩니다. 화면에 그리는 작업 이외의 대부분 작업이 여기서 일어납니다. 카메라의 위치를 바꾼다거나, 적군이 근처에 있어서 플레이어가 전투에 돌입해야하는지 판단한다거나 하는 일을 합니다. Child node의 OnFrameMove 함수가 재귀적으로 호출되는 곳도 여기입니다. 함수명과 파라미터에서 알 수 있듯이 이것은 D3D9/10 디바이스와는 완전히 독립적으로 움직입니다. 즉, 본 함수에서 D3D9 디바이스와 관련된 어떠한 변경이나 작업도 일어나서는 안됩니다. 참고로 처음 DXUT 소스 코드에는 아래와 같은 커맨트가 있었습니다. Handle updates to the scene. This is called regardless of which D3D API is used 이후는 본 함수에서 일어나는 일 중 중요한 것을 나열한 것입니다. */ void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; UNREFERENCED_PARAMETER( hr ); /// - 만일 WorldManager에 변경해야 할 다음 World가 설정되어 있다면 변경합니다. GetWorldManager().changeToNextWorldIfExist(); /// - 만일 TopStateManager에 변경해야 할 다음 스테이트가 설정되어 있다면 변경합니다. GetTopStateManager().transit( fTime ); /// - 현재 TopState의 프레임 무브 함수를 호출합니다. if (GetTopStateManager().getCurState()) GetTopStateManager().getCurState()->frameMove(fTime, fElapsedTime); /// - G::m_camera의 프레임 무브 함수를 호출합니다. GetG().m_camera.frameMove( fElapsedTime ); /// - EpLight의 프레임 무브 함수를 호출합니다. GetEpLight().frameMove( fElapsedTime ); WCHAR msg[128]; StringCchPrintf( msg, 128, L"FPS : %.2f\n", DXUTGetFPS() ); g_debugBuffer.append( msg ); StringCchPrintf( msg, 128, L"Camera Pos : (%.2f, %.2f, %.2f)\n", GetG().m_camera.GetEyePt()->x, GetG().m_camera.GetEyePt()->y, GetG().m_camera.GetEyePt()->z ); g_debugBuffer.append( msg ); StringCchPrintf( msg, 128, L"Camera LookAt : (%.2f, %.2f, %.2f)\n", GetG().m_camera.GetLookAtPt()->x, GetG().m_camera.GetLookAtPt()->y, GetG().m_camera.GetLookAtPt()->z ); g_debugBuffer.append( msg ); /// - G::m_screenFlash의 프레임 무브 함수를 호출합니다. GetG().m_screenFlash.frameMove( fTime, fElapsedTime ); // The particle system will need to know how much time has passed since // the last time it was updated, so we'll need to keep track of how much // time has elapsed since the last frame update... g_pParticleSystems[g_nActiveSystem]->Update( (float)fElapsedTime ); /// - RakNet 패킷을 처리하기 위해 OnFrameMoveNetworkProcess() 함수를 호출합니다. OnFrameMoveNetworkProcess(); } HRESULT drawBurningTeapot( double fTime, float fElapsedTime ) { HRESULT hr = S_OK; ArnMatrix mWorld; ArnMatrixIdentity( &mWorld ); UINT iPass, cPasses; V( g_bombShader->setMainTechnique() ); ArnMatrix arnvm, arnpm; memcpy(arnvm.m, GetG().m_camera.GetViewMatrix()->m, sizeof(float)*16 ); memcpy(arnpm.m, GetG().m_camera.GetProjMatrix()->m, sizeof(float)*16 ); V( g_bombShader->setWorldViewProj( fTime, fElapsedTime, &mWorld, &arnvm, &arnpm ) ); V( g_bombShader->begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_bombShader->beginPass( iPass ) ); // Draw mesh here... //D3DPERF_BeginEvent( 0, L"Shader applied teapot" ); g_bst[BST_TEAPOT]->DrawSubset( 0 ); //D3DPERF_EndEvent(); V( g_bombShader->endPass() ); } V( g_bombShader->end() ); return hr; } void renderDebugText() { EpCamera& g_camera = GetG().m_camera; RECT rc; rc.top = 0; rc.left = 0; rc.right = GetG().m_scrWidth; rc.bottom = GetG().m_scrHeight; D3DXCOLOR textColor = D3DXCOLOR( 1.0f, 0.0f, 0.0f, 1.0f ); g_pFont->DrawTextW( 0, g_debugBuffer.c_str(), -1, &rc, DT_NOCLIP | DT_RIGHT, textColor ); } void renderFixedElements( double fTime, float fElapsedTime ) { DXUTGetD3D9Device()->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); DXUTGetD3D9Device()->SetTransform(D3DTS_VIEW, (const D3DXMATRIX*)GetG().g_fixedViewMat.m); DXUTGetD3D9Device()->SetTransform(D3DTS_PROJECTION, (const D3DXMATRIX*)GetG().g_orthoProjMat.m); #ifdef DEBUG renderDebugText(); #endif g_debugBuffer.clear(); } HRESULT renderTileGrid( IDirect3DDevice9* pd3dDevice ) { HRESULT hr = S_OK; pd3dDevice->SetVertexShader( 0 ); pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); pd3dDevice->SetTexture( 0, 0 ); V( pd3dDevice->SetTransform( D3DTS_VIEW, GetG().m_camera.GetViewMatrix() ) ); V( pd3dDevice->SetTransform( D3DTS_PROJECTION, GetG().m_camera.GetProjMatrix() ) ); V( pd3dDevice->SetFVF( D3DFVF_XYZ | D3DFVF_DIFFUSE ) ); V( pd3dDevice->SetStreamSource( 0, g_lineElement, 0, 16 ) ); int i; ArnMatrix mWorld, mTrans, mRot, mScaling; ArnMatrixScaling( &mScaling, (float)(s_xSize) * s_tileSize, 1.0f, 1.0f ); for ( i = -s_ySize / 2; i < s_ySize / 2; ++i ) { ArnMatrixTranslation( &mTrans, 0, (float)i * s_tileSize, 0 ); mWorld = mScaling * mTrans; V( pd3dDevice->SetTransform( D3DTS_WORLD, (const D3DXMATRIX*)mWorld.m ) ); V( pd3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 1 ) ); } ArnMatrixScaling( &mScaling, (float)(s_ySize) * s_tileSize, 1.0f, 1.0f ); ArnMatrixRotationZ( &mRot, D3DXToRadian( 90 ) ); for ( i = -s_xSize / 2; i < s_xSize / 2; ++i ) { ArnMatrixTranslation( &mTrans, (float)i * s_tileSize, 0, 0 ); mWorld = mScaling * mRot * mTrans; V( pd3dDevice->SetTransform( D3DTS_WORLD, (const D3DXMATRIX*)mWorld.m ) ); D3DPERF_BeginEvent( 0, L"Boundary Line Drawing" ); V( pd3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 1 ) ); D3DPERF_EndEvent(); } return hr; } void SetupFullscreenQuad( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ) { D3DSURFACE_DESC desc; g_pFullScreenRenderTargetSurf->GetDesc( &desc ); // Ensure that we're directly mapping texels to pixels by offset by 0.5 // For more info see the doc page titled "Directly Mapping Texels to Pixels" FLOAT fWidth5 = ( FLOAT )pBackBufferSurfaceDesc->Width - 0.5f; FLOAT fHeight5 = ( FLOAT )pBackBufferSurfaceDesc->Height - 0.5f; FLOAT fTexWidth1 = ( FLOAT )pBackBufferSurfaceDesc->Width / ( FLOAT )desc.Width; FLOAT fTexHeight1 = ( FLOAT )pBackBufferSurfaceDesc->Height / ( FLOAT )desc.Height; // Fill in the vertex values g_Vertex[0].pos = D3DXVECTOR4( fWidth5, -0.5f, 0.0f, 1.0f ); g_Vertex[0].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[0].tex1 = D3DXVECTOR2( fTexWidth1, 0.0f ); g_Vertex[1].pos = D3DXVECTOR4( fWidth5, fHeight5, 0.0f, 1.0f ); g_Vertex[1].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[1].tex1 = D3DXVECTOR2( fTexWidth1, fTexHeight1 ); g_Vertex[2].pos = D3DXVECTOR4( -0.5f, -0.5f, 0.0f, 1.0f ); g_Vertex[2].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[2].tex1 = D3DXVECTOR2( 0.0f, 0.0f ); g_Vertex[3].pos = D3DXVECTOR4( -0.5f, fHeight5, 0.0f, 1.0f ); g_Vertex[3].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[3].tex1 = D3DXVECTOR2( 0.0f, fTexHeight1 ); } /*! \brief D3D9 디바이스를 이용해 화면에 렌더합니다. \param pd3dDevice D3D9 디바이스 \param fTime 프로그램이 시작된 후 현재까지 흐른 시간을 초 단위로 나타냅니다. \param fElapsedTime 지난 프레임부터 현재 프레임까지 걸린 시간을 초 단위로 나타냅니다. \param pUserContext 사용하지 않는 매개변수 \details DXUT에서 정의된 콜백 함수입니다. 모든 게임 루프의 최상위에 위치하는 렌더링 루틴입니다. 매 프레임이 그려질 때 본 함수가 호출됩니다. Child node의 OnFrameRender 함수가 재귀적으로 호출되는 곳도 여기입니다. \warning 이 함수와 독립적으로 호출되는(즉, 이 함수로부터 호출되지 않는) 렌더 관련 함수는 구조적으로 잘못된 것입니다. */ void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; LPDIRECT3DSURFACE9 originalRT = 0; const bool isShaderGood = g_postSepiaShader->isMainTechniqueOkay() && g_postRadialBlurShader->isMainTechniqueOkay(); if (isShaderGood) { V( pd3dDevice->GetRenderTarget( 0, &originalRT ) ); V( pd3dDevice->SetRenderTarget( 0, g_radialBlurRenderTargetSurf ) ); } // Clear the render target and the zbuffer V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, g_fillColor, 1.0f, 0 ) ); V( pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ) ); // Render the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { //drawBurningTeapot( fTime, fElapsedTime ); if ( g_bTileGrid ) renderTileGrid( pd3dDevice ); State* curState = GetTopStateManager().getCurState(); curState->frameRender( pd3dDevice, fTime, fElapsedTime ); renderFixedElements( fTime, fElapsedTime ); g_spriteManager->frameRender(); GetEpLight().frameRender( pd3dDevice ); if ( g_bParticleVisible ) { ////////////////////////////////////////////////////////////////////////// // // Transform for particle systems // pd3dDevice->SetTransform( D3DTS_VIEW, GetG().m_camera.GetViewMatrix() ); pd3dDevice->SetTransform( D3DTS_PROJECTION, GetG().m_camera.GetProjMatrix() ); ArnMatrix world; ArnMatrix scale; ArnMatrix rotate; ArnMatrix trans; ArnMatrixScaling( &scale, 0.5f, 0.5f, 0.5f ); ArnMatrixRotationX( &rotate, D3DXToRadian( -90.0f ) ); ArnMatrixTranslation( &trans, -30.0f, -4.0f, 0.0f ); world = rotate * scale * trans; pd3dDevice->SetTransform( D3DTS_WORLD, (const D3DXMATRIX*)world.m ); pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); // // Prepare to render particle system // // // Setting D3DRS_ZWRITEENABLE to FALSE makes the Z-Buffer read-only, which // helps remove graphical artifacts generated from rendering a list of // particles that haven't been sorted by distance to the eye. // // Setting D3DRS_ALPHABLENDENABLE to TRUE allows particles, which overlap, // to alpha blend with each other correctly. // pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE ); // // Render particle system // pd3dDevice->SetTexture( 0, g_pParticleSystems[g_nActiveSystem]->GetTextureObject() ); g_pParticleSystems[g_nActiveSystem]->Render( pd3dDevice ); // // Reset render states... // pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); } ////////////////////////////////////////////////////////////////////////// V( pd3dDevice->EndScene() ); } if (isShaderGood) { V( pd3dDevice->SetRenderTarget( 0, g_sepiaRenderTargetSurf ) ); V( pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ) ); // Clear the render target V( pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET, 0x00000000, 1.0f, 0L ) ); if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { UINT iPass, cPasses; V(g_postRadialBlurShader->setMainTechnique()); V( g_postRadialBlurShader->begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_postRadialBlurShader->beginPass( iPass ) ); V( pd3dDevice->SetFVF( SCREEN_VERTEX::FVF ) ); V( pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, g_Vertex, sizeof( SCREEN_VERTEX ) ) ); V( g_postRadialBlurShader->endPass() ); } V( g_postRadialBlurShader->end() ); V( pd3dDevice->EndScene() ); } V( pd3dDevice->SetRenderTarget( 0, originalRT ) ); // Clear the render target V( pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET, 0x00000000, 1.0f, 0L ) ); if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { UINT iPass, cPasses; V(g_postSepiaShader->setMainTechnique()); V( g_postSepiaShader->begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_postSepiaShader->beginPass( iPass ) ); V( pd3dDevice->SetFVF( SCREEN_VERTEX::FVF ) ); V( pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, g_Vertex, sizeof( SCREEN_VERTEX ) ) ); V( g_postSepiaShader->endPass() ); } V( g_postSepiaShader->end() ); V( pd3dDevice->EndScene() ); } SAFE_RELEASE( originalRT ); } } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { EpCamera& g_camera = GetG().m_camera; g_camera.handleMessages(hWnd, uMsg, wParam, lParam); GetEpLight().handleMessages(hWnd, uMsg, wParam, lParam); GetG().m_screenFlash.handleMessage( hWnd, uMsg, wParam, lParam ); if (g_tsm && GetTopStateManager().getCurState()) GetTopStateManager().getCurState()->handleMessages(hWnd, uMsg, wParam, lParam); if ( uMsg == WM_KEYDOWN ) { if ( wParam == 'P' ) { g_nActiveSystem++; g_nActiveSystem %= 6; } else if ( wParam == 'L' ) { g_bParticleVisible = g_bParticleVisible?false:true; } } return 0; } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9ResetDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnD3D9LostDevice( void* pUserContext ) { OutputDebugString( _T( " - INFO: OnLostDevice() called.\n" ) ); #define SAFE_ONLOSTDEVICE(x) if (x) (x)->OnLostDevice(); SAFE_ONLOSTDEVICE( g_pFont ); SAFE_ONLOSTDEVICE( g_unitNameFont ); SAFE_ONLOSTDEVICE( g_dlgNameFont ); SAFE_ONLOSTDEVICE( g_dlgContentFont ); SAFE_ONLOSTDEVICE( g_fontBattle2 ); SAFE_ONLOSTDEVICE( g_fontBattle ); SAFE_ONLOSTDEVICE( g_fontSkill ); SAFE_ONLOSTDEVICE( g_fontSkillDescription ); SAFE_ONLOSTDEVICE( g_fontStat ); if ( SpriteManager::getSingletonPtr() ) GetSpriteManager().onLostDevice(); if ( WorldManager::getSingletonPtr() ) GetWorldManager().onLostDevice(); if ( TopStateManager::getSingletonPtr() ) GetTopStateManager().onLostDevice(); if ( WorldStateManager::getSingletonPtr() ) GetWorldStateManager().onLostDevice(); SAFE_RELEASE( g_pFullScreenRenderTarget ); SAFE_RELEASE( g_pFullScreenRenderTargetSurf ); SAFE_RELEASE( g_sepiaRenderTarget ); SAFE_RELEASE( g_sepiaRenderTargetSurf ); SAFE_RELEASE( g_radialBlurRenderTarget ); SAFE_RELEASE( g_radialBlurRenderTargetSurf ); if ( g_postRadialBlurShader ) g_postRadialBlurShader->onLostDevice(); if ( g_postSepiaShader ) g_postSepiaShader->onLostDevice(); if ( g_bombShader ) g_bombShader->onLostDevice(); GetG().m_screenFlash.onLostDevice(); OnD3D9LostDeviceParticleSystem(); // GetG() related GetG().m_videoMan->SetDev(0); } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9CreateDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnD3D9DestroyDevice( void* pUserContext ) { OutputDebugString( _T( " - INFO: OnDestroyDevice() called.\n" ) ); // Globally used fonts SAFE_RELEASE( g_pFont ); SAFE_RELEASE( g_unitNameFont ); SAFE_RELEASE( g_dlgNameFont ); SAFE_RELEASE( g_dlgContentFont ); SAFE_RELEASE( g_d3dxFont ); SAFE_RELEASE( g_d3dxFontBig ); // Test geometries SAFE_RELEASE( g_bst[BST_TEAPOT] ); SAFE_RELEASE( g_bst[BST_CUBE] ); SAFE_RELEASE( g_bst[BST_PLANE] ); SAFE_RELEASE( g_bst[BST_SPHERE] ); // Tile grid geometry SAFE_RELEASE( g_lineElement ); // Shaders EP_SAFE_release( g_bombShader ); EP_SAFE_release( g_postSepiaShader ); EP_SAFE_release( g_postRadialBlurShader ); // GetG() related GetG().m_videoMan->SetDev(0); GetG().m_screenFlash.onDestroyDevice(); for( int i = 0; i < 6; ++i ) { SAFE_DELETE( g_pParticleSystems[i] ); } SAFE_RELEASE( g_fontBattle2 ); SAFE_RELEASE( g_fontBattle ); SAFE_RELEASE( g_fontSkill ); SAFE_RELEASE( g_fontSkillDescription ); SAFE_RELEASE( g_fontStat ); GetSpriteManager().onDestroyDevice(); GetG().m_screenFlash.onDestroyDevice(); } //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if( bKeyDown ) { switch( nChar ) { case VK_F1: if (g_fillColor == D3DCOLOR_ARGB( 0, 45, 50, 170 )) { g_fillColor = D3DCOLOR_ARGB(0, 200, 100, 25); } else { g_fillColor = D3DCOLOR_ARGB( 0, 45, 50, 170 ); } break; } } else { // Key up switch ( nChar ) { case VK_F3: g_bTileGrid = !g_bTileGrid; break; case VK_F4: GetG().m_camera.setShake( !GetG().m_camera.getShake() ); break; } } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// static bool isCurrentWorkingDir = false; /*! \brief 실행 파일이 있는 곳으로 작업 디렉토리를 변경합니다. \details 개발 중에는 MSVC에서 프로그램을 실행시키는 경우가 많은데, 작업 디렉토리가 바뀌기가 쉬워서 경우에 따라 경로 설정을 다르게 해야하는 번거로움이 있습니다. 본 함수가 현재 실행 파일이 있는 디렉토리를 작업 디렉토리(working directory)로 만들어서 다른 모든 경로가 작업 디렉토리를 기준으로 상대 경로로 나타낼 수 있도록 도와줍니다. */ void SetCurrentWorkingDirectory() { if ( isCurrentWorkingDir == false ) { TCHAR buf[MAX_PATH]; TCHAR drive[_MAX_DRIVE]; TCHAR dir[_MAX_DIR]; GetModuleFileName(NULL, buf, MAX_PATH); _tsplitpath_s(buf, drive, _MAX_DRIVE, dir, _MAX_DIR, 0, 0, 0, 0); StringCchPrintf(buf, MAX_PATH, _T("%s%s"), drive, dir); SetCurrentDirectory(buf); isCurrentWorkingDir = true; } } int EpOutputDebugString( const char* msg ) { OutputDebugStringA( msg ); return 0; } SCRIPT_CALLABLE_I_PC( EpOutputDebugString ) //#define EP_CONSOLE static int g_closeConsole = 2008; void EpConsoleThreadMain( void* cd ) { #if defined(DEBUG) && defined(EP_CONSOLE) g_consoleInterp = Tcl_CreateInterp(); if (Tcl_Init(g_consoleInterp) == TCL_ERROR) throw std::runtime_error( "Tcl_Init() error" ); #endif GetScriptManager().initScriptBindings(); CREATE_OBJ_COMMAND( EpOutputDebugString ); SetEvent( g_scriptBindingFinishedEvent ); #if defined(DEBUG) && defined(EP_CONSOLE) if ( Tcl_LinkVar( g_consoleInterp, "closeConsole", (char*)&g_closeConsole, TCL_LINK_INT ) != TCL_OK ) { DebugBreak(); } if ( Tcl_EvalFile( g_consoleInterp, "Script/EpThreadTest.tcl" ) != TCL_OK ) ScriptManager::throwScriptErrorWithMessage( g_consoleInterp ); // Could not reach here... Tcl_DeleteInterp( g_consoleInterp ); g_consoleInterp = 0; SetEvent( g_consoleReleasedEvent ); #endif return; } void CreateScriptManagerIfNotExist() { SetCurrentWorkingDirectory(); if ( !g_scriptManager ) { g_scriptManager = new ScriptManager(); GetScriptManager().init(); } } /*! @brief 모든 전역변수를 초기화하고 렌더 루프로 돌입합니다. @details 본 함수는 main()이거나 wWinMain()일 수 있습니다. EP 디버그 빌드에서는 윈도우 콘솔창에 디버그 정보를 나타내기 위해 main()을 사용하고, EP 릴리즈 빌드에서는 콘솔창이 필요없으므로 wWinMain()을 사용하도록 전처리계가 설정되어 있습니다.\n 본 함수에서는 D3D Device(LPDIRECT3DDEVICE9 혹은IDirect3DDevice9*)과 무관한 부분을 초기화합니다. 그리고 DXUT가 설정한 각종 콜백 함수를 등록하게 됩니다. 여기에는 OnD3D9CreateDevice(), OnD3D9ResetDevice(), OnD3D9FrameRender(), OnFrmaeMove(), OnD3D9LostDevice(), OnD3D9DestroyDevice() 등이 포함됩니다. 콜백 함수 이름에서 알 수 있듯이 OnFrameMove는 D3D9/D3D10을 구분하지 않는 루틴입니다. 이는 다시 말해 OnFrameMove에서는 D3D Device와 연관된 코드를 작성하지 않아야 함을 의미합니다. */ #ifdef DEBUG int main(int argc, char** argv) { system( "title EmptyProject Console" ); #else INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int ) { #endif // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif int err; err = ArnInitializeXmlParser(); assert(err == 0); err = ArnInitializeImageLibrary(); assert(err == 0); GetG().m_videoMan = VideoManDx9::create(); ZeroMemory( g_bst, sizeof(LPD3DXMESH) * 4 ); // TODO: Perform any application-level initialization here /*! 애플리케이션 레벨의 초기화는 이 부분에서 일어납니다. D3D device를 얻기 전이므로 이와 연관된 초기화를 수행해서는 안됩니다. */ /** - Working Directory 설정\n 현재 프로그램 실행파일이 있는 위치로 working directory를 변경합니다. */ SetCurrentWorkingDirectory(); g_debugBuffer.resize( 2048 ); /*! - ScriptManager 초기화\n Tcl 스크립트 언어를 해석하고 바인딩해주는 ScriptManager를 할당하고 초기화합니다. ScriptManager가 생성되어있지 않은 경우에만 생성해줍니다. 생성 여부를 체크하는 이유는 이 ScriptManager가 다른 스레드에서 먼저 생성되는 경우도 있기 때문입니다. 이후 게임 전반에 사용되는 스크립트 파일을 등록하게 됩니다.\n */ CreateScriptManagerIfNotExist(); GetScriptManager().executeFile( "Script/EpInitScript.tcl" ); GetScriptManager().executeFile( "Script/EpDialog1.tcl" ); GetScriptManager().executeFile( "Script/EpSkill.tcl" ); GetScriptManager().execute( "EpInitApp" ); /*! - SpriteManager 초기화\n 2D 그래픽을 단순히 찍어야 하는 경우(UI 등)에 사용하는 스프라이트를 관리해주는 SpriteManager를 할당하고 초기화합니다. 반드시 SpriteManager는 이곳에서 초기화되어야 합니다. 초기화 단계에서 미리 등록되는 스프라이트는 없으며, 이후에 명시적으로 등록한 후 사용해야 합니다.\n */ assert( g_spriteManager == 0 ); g_spriteManager = new SpriteManager(); /*! - TopStateManager (tsm) 초기화\n 게임의 최상위 스테이트를 관리해주는 tsm을 초기화합니다. 최상위 스테이트에는 게임 실행시 처음으로 설정되는 IntroState, 게임 플레이 중을 나타내는 PlayState, 제작자 목록을 보여주는 CreditState등이 있습니다. tsm의 초기화는 반드시 여기서, 그리고 프로그램 실행 주기에 단 한번 일어나야 합니다.\n */ assert( g_tsm == 0 ); g_tsm = new TopStateManager(); g_tsm->init(); /** - WorldStateManager (wsm) 초기화\n TopStateManager 중 가장 큰 비중을 차지하는 PlayState는 또 몇 개의 하위 스테이트로 나누어져 있습니다. 이러한 PlayState의 하위 스테이트를 관리해주는 클래스가 바로 wsm입니다. wsm의 초기화는 반드시 여기서, 그리고 프로그램 실행 주기에 단 한번 일어나야 합니다.\n */ assert( g_wsm == 0 ); g_wsm = new WorldStateManager(); g_wsm->init(); /** - WorldManager (wm) 초기화\n EP의 구조상 레벨(맵) 개념은 World란 단어로 정의됩니다. 플레이어는 몇 개의 World를 왔다갔다 할 수 있습니다. 이 공간은 비연속적일 수 있습니다. 이러한 World 객체를 관리해주는 클래스가 바로 WorldManager입니다. WorldStateManager (wsm)과 혼동하지 않도록 주의하십시오. wm의 초기화는 반드시 여기서, 그리고 프로그램 실행 주기에 단 한번 일어나야 합니다.\n */ assert( g_wm == 0 ); g_wm = new WorldManager(); /** - 모든 World 스크립트 파일을 읽어오기\n 각 World는 하나의 World 스크립트 파일에 의해 정의됩니다. 이전에 초기화된 ScriptManager를 이용해 EpWorldList 스크립트 변수를 읽어들여 어떤 World가 정의되어있는지 파악한 후, 각 World 스크립트 파일을 순차적으로 로드합니다. 이때, 각 World는 하나의 modelFilePath 스크립트 변수를 가지고 있는데, 이것이 화면에 렌더링될 레벨의 ARN 모델 파일이 됩니다. 물론 지금은 D3D9 디바이스가 초기화되기 전이므로 ARN 파일 이름만 로드해올 뿐 다른 일은 하지 않습니다. */ assert( GetWorldManager().getWorldCount() == 0 ); ConstCharList worldList; GetScriptManager().readCharPtrList( "EpWorldList", worldList ); char scriptCommand[512]; ConstCharList::iterator it = worldList.begin(); for ( ; it != worldList.end(); ++it ) { const char* worldName = *it; StringCchPrintfA( scriptCommand, 512, "Script/%s.tcl", worldName ); GetScriptManager().executeFile( scriptCommand ); StringCchPrintfA( scriptCommand, 512, "%s::modelFilePath", worldName ); const char* modelFilePath = GetScriptManager().readString( scriptCommand ); WCHAR mfp[128]; size_t numOfConvert; mbstowcs_s( &numOfConvert, mfp, 128, modelFilePath, 512 ); World* world = World::createWorld( worldName, mfp, false ); GetWorldManager().addWorld( world ); } /** - 전역 카메라(G::m_camera) 초기화\n <미작성된 부분> */ GetG().m_camera.SetAttachCameraToModel( true ); GetG().m_camera.SetEnablePositionMovement( true ); /** - 전역 광원(::g_epLight) 초기화\n <미작성된 부분> */ assert( g_epLight == 0 ); g_epLight = new EpLight(); /** - 콘솔 스레드 초기화\n 초기의 EP에서는 디버그 목적으로 콘솔 스레드가 따로 구성되어 있었습니다. 그렇지만 시간이 지나면서 동기화 문제 및 메모리 누수 문제가 생겨 결국에는 콘솔 스레드를 생성했다가 바로 해제하고 있는 상태입니다. */ g_scriptBindingFinishedEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); ResetEvent( g_scriptBindingFinishedEvent ); uintptr_t t = _beginthread( EpConsoleThreadMain, 0, 0 ); WaitForSingleObject( g_scriptBindingFinishedEvent, INFINITE ); /** - 스크립트 측 초기화 프로시저 실행\n EpInitScript.tcl 파일에 정의된 EpOnCreateDevice 프로시저가 실행됩니다. 현재 OnCreateDevice 상태는 아니지만 소스 코드가 어떻게 계속 바뀌다보니 이렇게 이상한 이름이 된 상태입니다. 차후 정정할 예정입니다. :( */ GetScriptManager().execute( "EpOnCreateDevice" ); /** - SkillManager 초기화\n Skill은 EP에서 정의한 '전투 중 가능한 행동'입니다. 이러한 행동은 매우 다양해질 수 있으므로 이를 관리할 수 있는 SkillManager를 만들었습니다. SkillManager는 WorldManager와 마찬가지로 스크립트 측에서 정의된 스킬 목록을 가져와서 초기화하게 됩니다. 이는 EpSkill.tcl에 정의된 EpSkillList라는 스크립트 변수에서 확인할 수 있습니다. */ SkillManager* g_skillManager = new SkillManager(); ConstCharList skillList; GetScriptManager().readCharPtrList( "EpSkillList", skillList ); it = skillList.begin(); for ( ; it != skillList.end(); ++it ) { const char* skillName = *it; GetSKillManager().registerSkill( Skill::createSkillByScript( skillName ) ); } /** - 초기 World를 설정\n 기본적으로 IntroState 이후 PlayState에 진입하게 되는데, PlayState에서는 여러 개의 로드된 World 중에 하나를 선택해야 합니다. 이러한 초기 World를 여기서 설정해줍니다. 어떤 World가 초기 월드가 되는지는 EpInitScript.tcl 파일의 EpStartWorldName 스크립트 변수에 정의되어 있습니다. */ const char* startWorldName = GetScriptManager().readString( "EpStartWorldName" ); GetWorldManager().setNextWorld( startWorldName ); //GetWorldManager().changeToNextWorldIfExist(); /** - 창모드 혹은 전체화면 모드 설정\n */ const char* windowMode = GetScriptManager().readString( "EpWindowMode" ); bool bWindowMode = (*windowMode)=='1'?true:false; /** - RakNet 초기화 및 서버 접속 시도\n RakNet 라이브러리는 멀티플레이어 게임 엔진입니다. RakNet을 적용한지 얼마 안되었으므로 이 부분은 자주, 그리고 급격히 변경될 수 있습니다. */ const char* networkMode = GetScriptManager().readString( "NetworkMode" ); if ( *networkMode == '1' ) ConnectToServer(); ////////////////////////////////////////////////////////////////////////// // Set the DXUT callback functions DXUTSetCallbackD3D9DeviceAcceptable( IsD3D9DeviceAcceptable ); DXUTSetCallbackD3D9DeviceCreated( OnD3D9CreateDevice ); DXUTSetCallbackD3D9DeviceReset( OnD3D9ResetDevice ); DXUTSetCallbackD3D9FrameRender( OnD3D9FrameRender ); DXUTSetCallbackD3D9DeviceLost( OnD3D9LostDevice ); DXUTSetCallbackD3D9DeviceDestroyed( OnD3D9DestroyDevice ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackKeyboard( KeyboardProc ); // Initialize DXUT and create the desired Win32 window and Direct3D device for the application DXUTInit( true, true ); // Parse the command line and show msgboxes DXUTSetHotkeyHandling( true, false, true ); // handle the default hotkeys DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"EmptyProject", 0, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, true ); if ( bWindowMode ) { // Window size is determined by script DXUTCreateDevice( true, GetG().m_scrWidth, GetG().m_scrHeight ); } else { // Window size is determined by monitor resolution. DXUTCreateDevice( false ); } DXUTMainLoop(); DXUTShutdown(); ////////////////////////////////////////////////////////////////////////// // TODO: Perform any application-level cleanup here #if defined(DEBUG) && defined(EP_CONSOLE) g_consoleReleasedEvent = CreateEvent( NULL , TRUE , FALSE , NULL ); ResetEvent( g_consoleReleasedEvent ); g_closeConsole = 1; WaitForSingleObject( g_consoleReleasedEvent, INFINITE ); #endif if ( g_clientPeer && g_clientPeer->IsConnected( g_clientPeer->GetSystemAddressFromIndex( 0 ) ) ) { Unit* hero = GetWorldManager().getCurWorld()->getHero(); GetWorldManager().getCurWorld()->detachUnit( hero ); // Detach from world since Hero will be deallocated by ReplicaManager. GetWorldManager().getCurWorld()->detachAllUnitBaseType(); // Detach from world since UnitBase typed instances will be deallocated by ReplicaManager. DisconnectFromServer(); } if ( g_clientPeer ) { // Be nice and let the server know we quit. g_clientPeer->Shutdown( 300 ); // We're done with the network RakNetworkFactory::DestroyRakPeerInterface( g_clientPeer ); } SAFE_DELETE( g_replicaManager ); // DO NOT USE EP_SAFE_release or SAFE_DELETE on these objects. // It should be allocated once time through the application lifetime, // and therefore should be deallocated only once. g_wm->release(); g_scriptManager->release(); g_tsm->release(); g_wsm->release(); delete g_wm; delete g_scriptManager; delete g_tsm; delete g_wsm; delete g_spriteManager; delete g_skillManager; delete g_epLight; delete GetG().m_videoMan; Tcl_Finalize(); // This should be done at the last stage of termination since // many replica objects have RakNet::RakString. RakNet::RakString::FreeMemory(); ArnCleanupXmlParser(); ArnCleanupImageLibrary(); return DXUTGetExitCode(); } void OnD3D9LostDeviceParticleSystem() { UINT i; for ( i = 0; i < 6; ++i ) { SAFE_DELETE( g_pParticleSystems[i] ); } } void OnResetParticleSystem( LPDIRECT3DDEVICE9 pd3dDevice ) { UINT i; for ( i = 0; i < 6; ++i ) { assert( g_pParticleSystems[i] == 0 ); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Particle systems initialize // // Exploding burst // g_pParticleSystems[0] = new CParticleSystem(); g_pParticleSystems[0]->SetTexture( "Images/particle.bmp" ); g_pParticleSystems[0]->SetMaxParticles( 100 ); g_pParticleSystems[0]->SetNumToRelease( 100 ); g_pParticleSystems[0]->SetReleaseInterval( 0.05f ); g_pParticleSystems[0]->SetLifeCycle( 0.5f ); g_pParticleSystems[0]->SetSize( 1.0f ); g_pParticleSystems[0]->SetColor( D3DXCOLOR( 1.0f, 0.0f, 0.0f, 1.0f )); g_pParticleSystems[0]->SetPosition( ArnVec3( 0.0f, 5.0f, 0.0f) ); g_pParticleSystems[0]->SetVelocity( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[0]->SetGravity( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[0]->SetWind( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[0]->SetVelocityVar( 10.0f ); g_pParticleSystems[0]->Init( pd3dDevice ); // // Wind blown fountain // g_pParticleSystems[1] = new CParticleSystem(); g_pParticleSystems[1]->SetTexture( "Images/particle.bmp" ); g_pParticleSystems[1]->SetMaxParticles( 500 ); g_pParticleSystems[1]->SetNumToRelease( 5 ); g_pParticleSystems[1]->SetReleaseInterval( 0.05f ); g_pParticleSystems[1]->SetLifeCycle( 4.0f ); g_pParticleSystems[1]->SetSize( 0.5f ); g_pParticleSystems[1]->SetColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f )); g_pParticleSystems[1]->SetPosition( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[1]->SetVelocity( ArnVec3( 0.0f, 5.0f, 0.0f ) ); g_pParticleSystems[1]->SetGravity( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[1]->SetWind( ArnVec3( 2.0f, 0.0f, 0.0f ) ); g_pParticleSystems[1]->SetVelocityVar( 1.5f ); g_pParticleSystems[1]->Init( pd3dDevice ); // // Omni-directiional emission expanding into space with no air resistence // g_pParticleSystems[2] = new CParticleSystem(); g_pParticleSystems[2]->SetTexture( "Images/particle.bmp" ); g_pParticleSystems[2]->SetMaxParticles( 2048 ); g_pParticleSystems[2]->SetNumToRelease( 10 ); g_pParticleSystems[2]->SetReleaseInterval( 0.05f ); g_pParticleSystems[2]->SetLifeCycle( 5.0f ); g_pParticleSystems[2]->SetSize( 0.5f ); g_pParticleSystems[2]->SetColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f )); g_pParticleSystems[2]->SetPosition( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[2]->SetVelocity( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[2]->SetGravity( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[2]->SetWind( ArnVec3( 0.0f, 0.0f, 0.0f) ); g_pParticleSystems[2]->SetAirResistence( false ); g_pParticleSystems[2]->SetVelocityVar(2.0f); g_pParticleSystems[2]->Init( pd3dDevice ); // // Fountain particles behave like paint spots when striking a plane as // the wind blowing them towards us // g_pParticleSystems[3] = new CParticleSystem(); g_pParticleSystems[3]->SetTexture( "Images/particle.bmp" ); g_pParticleSystems[3]->SetMaxParticles( 100 ); g_pParticleSystems[3]->SetNumToRelease( 10 ); g_pParticleSystems[3]->SetReleaseInterval( 0.05f ); g_pParticleSystems[3]->SetLifeCycle( 3.0f ); g_pParticleSystems[3]->SetSize( 0.5f ); g_pParticleSystems[3]->SetColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f )); g_pParticleSystems[3]->SetPosition( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[3]->SetVelocity( ArnVec3( 0.0f, 5.0f, 0.0f ) ); g_pParticleSystems[3]->SetGravity( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[3]->SetWind( ArnVec3( 0.0f, 0.0f, -20.0f ) ); g_pParticleSystems[3]->SetVelocityVar( 2.5f ); g_pParticleSystems[3]->SetCollisionPlane( ArnVec3( 0.0f, 0.0f,1.0f ), ArnVec3( 0.0f, 0.0f, -5.0f ), 1.0f, CR_STICK ); g_pParticleSystems[3]->Init( pd3dDevice ); // // Fountain using a single collision plane acting as a floor // g_pParticleSystems[4] = new CParticleSystem(); g_pParticleSystems[4]->SetTexture( "Images/particle.bmp" ); g_pParticleSystems[4]->SetMaxParticles( 200 ); g_pParticleSystems[4]->SetNumToRelease( 10 ); g_pParticleSystems[4]->SetReleaseInterval( 0.05f ); g_pParticleSystems[4]->SetLifeCycle( 5.0f ); g_pParticleSystems[4]->SetSize( 1.5f ); g_pParticleSystems[4]->SetColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f )); g_pParticleSystems[4]->SetPosition( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[4]->SetVelocity( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[4]->SetGravity( ArnVec3( 0.0f, -9.8f, 0.0f ) ); g_pParticleSystems[4]->SetWind( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[4]->SetVelocityVar( 20.0f ); g_pParticleSystems[4]->SetCollisionPlane( ArnVec3( 0.0f, 1.0f, 0.0f ), ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[4]->Init( pd3dDevice ); // // Fountain boxed-in by 6 collision planes // g_pParticleSystems[5] = new CParticleSystem(); g_pParticleSystems[5]->SetTexture( "Images/particle.bmp" ); g_pParticleSystems[5]->SetMaxParticles( 100 ); g_pParticleSystems[5]->SetNumToRelease( 5 ); g_pParticleSystems[5]->SetReleaseInterval( 0.05f ); g_pParticleSystems[5]->SetLifeCycle( 5.0f ); g_pParticleSystems[5]->SetSize( 1.0f ); g_pParticleSystems[5]->SetColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f )); g_pParticleSystems[5]->SetPosition( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[5]->SetVelocity( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[5]->SetGravity( ArnVec3( 0.0f, -9.8f, 0.0f ) ); g_pParticleSystems[5]->SetWind( ArnVec3( 0.0f, 0.0f, 0.0f ) ); g_pParticleSystems[5]->SetVelocityVar( 20.0f ); // Create a series of planes to collide with g_pParticleSystems[5]->SetCollisionPlane( ArnVec3( 0.0f, 1.0f, 0.0f ), ArnVec3( 0.0f, 0.0f, 0.0f ) ); // Floor g_pParticleSystems[5]->SetCollisionPlane( ArnVec3( 1.0f, 0.0f, 0.0f ), ArnVec3(-3.0f, 0.0f, 0.0f ) ); // Left Wall g_pParticleSystems[5]->SetCollisionPlane( ArnVec3(-1.0f, 0.0f, 0.0f ), ArnVec3( 3.0f, 0.0f, 0.0f ) ); // Right Wall g_pParticleSystems[5]->SetCollisionPlane( ArnVec3( 0.0f, 0.0f, 1.0f ), ArnVec3( 0.0f, 0.0f,-3.0f ) ); // Front Wall g_pParticleSystems[5]->SetCollisionPlane( ArnVec3( 0.0f, 0.0f,-1.0f ), ArnVec3( 0.0f, 0.0f, 3.0f ) ); // Back Wall g_pParticleSystems[5]->SetCollisionPlane( ArnVec3( 0.0f,-1.0f, 0.0f ), ArnVec3( 0.0f, 5.0f, 0.0f ) ); // Ceiling g_pParticleSystems[5]->Init( pd3dDevice ); } void ConfigureShaders( LPDIRECT3DDEVICE9 pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc ) { // Shader assert( g_bombShader == 0 ); g_bombShader = new BombShader(); g_bombShader->onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc ); assert( g_postSepiaShader == 0 ); g_postSepiaShader = new PostSepiaShader(); g_postSepiaShader->onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc ); assert( g_postRadialBlurShader == 0 ); g_postRadialBlurShader = new PostRadialBlurShader(); g_postRadialBlurShader->onCreateDevice( pd3dDevice, pBackBufferSurfaceDesc ); } void ConfigureTileGridGeometry( LPDIRECT3DDEVICE9 pd3dDevice ) { HRESULT hr = S_OK; assert( g_lineElement == 0 ); V( pd3dDevice->CreateVertexBuffer( sizeof( MY_COLOR_VERTEX ) * 2, D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE, D3DPOOL_MANAGED, &g_lineElement, 0 ) ); const D3DCOLOR gridColor = D3DCOLOR_ARGB( 255, 32, 128, 128 ); MY_COLOR_VERTEX data[] = { { -0.5f, 0.0f, -0.2f, gridColor }, { +0.5f, 0.0f, -0.2f, gridColor } }; void* pVB = 0; V( g_lineElement->Lock( 0, 0, &pVB, 0 ) ); memcpy( pVB, data, sizeof( data ) ); g_lineElement->Unlock(); } void ConfigureTestGeometry( LPDIRECT3DDEVICE9 pd3dDevice ) { UINT i; for ( i = 0; i < BST_COUNT; ++i ) { assert( g_bst[i] == 0 ); } //enum BasicShapeType { BST_UNKNOWN, BST_TEAPOT, BST_SPHERE, BST_CUBE, BST_PLANE, BST_COUNT }; D3DXCreateTeapot( pd3dDevice, &g_bst[BST_TEAPOT], 0 ); D3DXCreateSphere( pd3dDevice, 1.0f, 8, 8, &g_bst[BST_SPHERE], 0 ); D3DXCreateBox( pd3dDevice, 1.0f, 1.0f, 1.0f, &g_bst[BST_CUBE], 0 ); D3DXCreatePolygon( pd3dDevice, 1.0f, 4, &g_bst[BST_PLANE], 0 ); } // Copied from Multiplayer.cpp // If the first byte is ID_TIMESTAMP, then we want the 5th byte // Otherwise we want the 1st byte unsigned char GetPacketIdentifier(Packet *p) { if (p==0) return 255; if ((unsigned char)p->data[0] == ID_TIMESTAMP) { assert(p->length > sizeof(unsigned char) + sizeof(unsigned long)); return (unsigned char) p->data[sizeof(unsigned char) + sizeof(unsigned long)]; } else return (unsigned char) p->data[0]; } void EpRpcDoScript( RakNet::RakString command ) { GetScriptManager().execute( command ); } void ConnectToServer() { //g_rpc3Inst = new RakNet::RPC3; g_replicaManager = new RakNet::ReplicaManager2; UnitBase::myUnit=0; EpUser::myUser=0; g_networkIDManager.SetIsNetworkIDAuthority( false ); g_rpc3Inst.SetNetworkIDManager( &g_networkIDManager ); RPC3_REGISTER_FUNCTION( &g_rpc3Inst, PrintHelloWorld ); RPC3_REGISTER_FUNCTION( &g_rpc3Inst, EpRpcDoScript ); RPC3_REGISTER_FUNCTION( &g_rpc3Inst, &Unit::setTilePosRpc ); g_clientPeer = RakNetworkFactory::GetRakPeerInterface(); g_clientPeer->SetNetworkIDManager( &g_networkIDManager ); // Holds packets Packet* p; // GetPacketIdentifier returns this unsigned char packetIdentifier; // Just so we can remember where the packet came from bool isServer; // Record the first client that connects to us so we can pass it to the ping function SystemAddress clientID = UNASSIGNED_SYSTEM_ADDRESS; // Holds user data const char* serverIp = "143.248.139.115"; const unsigned short serverPort = 10000; // A client isServer = false; puts( "---------------------------" ); puts( "| EmptyProject Client |" ); puts( "---------------------------" ); printf( "Trying to connect server %s:%d ...\n", serverIp, serverPort); g_clientPeer->AllowConnectionResponseIPMigration(false); // Connecting the client is very simple. 0 means we don't care about // a connectionValidationInteger, and false for low priority threads SocketDescriptor socketDescriptor(0, 0); g_clientPeer->Startup(1, 30, &socketDescriptor, 1); g_clientPeer->AttachPlugin( g_replicaManager ); // Just test this g_replicaManager->SetAutoAddNewConnections( false ); // Register our custom connection factory g_replicaManager->SetConnectionFactory( &g_connectionFactory ); g_clientPeer->SetOccasionalPing(true); bool b = g_clientPeer->Connect(serverIp, serverPort, "Rumpelstiltskin", (int) strlen("Rumpelstiltskin")); g_clientPeer->AttachPlugin( &g_rpc3Inst ); RakNet::StringTable::Instance()->AddString( "UnitBase", false ); RakNet::StringTable::Instance()->AddString( "EpUser", false ); if (b) { puts("Attempting connection"); bool doLoop = true; while ( doLoop ) { Sleep(30); p = g_clientPeer->Receive(); if (p==0) continue; // Didn't get any packets // We got a packet, get the identifier with our handy function packetIdentifier = GetPacketIdentifier(p); // Check if this is a network message packet switch (packetIdentifier) { case ID_DISCONNECTION_NOTIFICATION: // Connection lost normally printf("ID_DISCONNECTION_NOTIFICATION\n"); doLoop = false; break; case ID_ALREADY_CONNECTED: // Connection lost normally printf("ID_ALREADY_CONNECTED\n"); break; case ID_REMOTE_DISCONNECTION_NOTIFICATION: // Server telling the clients of another client disconnecting gracefully. You can manually broadcast this in a peer to peer enviroment if you want. printf("ID_REMOTE_DISCONNECTION_NOTIFICATION\n"); break; case ID_REMOTE_CONNECTION_LOST: // Server telling the clients of another client disconnecting forcefully. You can manually broadcast this in a peer to peer enviroment if you want. printf("ID_REMOTE_CONNECTION_LOST\n"); break; case ID_REMOTE_NEW_INCOMING_CONNECTION: // Server telling the clients of another client connecting. You can manually broadcast this in a peer to peer enviroment if you want. printf("ID_REMOTE_NEW_INCOMING_CONNECTION\n"); break; case ID_CONNECTION_BANNED: // Banned from this server printf("We are banned from this server.\n"); break; case ID_CONNECTION_ATTEMPT_FAILED: printf("Connection attempt failed\n"); doLoop = false; break; case ID_NO_FREE_INCOMING_CONNECTIONS: // Sorry, the server is full. I don't do anything here but // A real app should tell the user printf("ID_NO_FREE_INCOMING_CONNECTIONS\n"); break; case ID_MODIFIED_PACKET: // Cheater! printf("ID_MODIFIED_PACKET\n"); break; case ID_INVALID_PASSWORD: printf("ID_INVALID_PASSWORD\n"); break; case ID_CONNECTION_LOST: // Couldn't deliver a reliable packet - i.e. the other system was abnormally // terminated printf("ID_CONNECTION_LOST\n"); break; case ID_CONNECTION_REQUEST_ACCEPTED: // This tells the client they have connected printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); g_replicaManager->AddNewConnection( p->systemAddress ); doLoop = false; break; default: // It's a client, so just show the message printf( "%s\n", p->data ); break; } // We're done with the packet g_clientPeer->DeallocatePacket( p ); } } else { puts( "Bad connection attempt. Terminating." ); DebugBreak(); } } void DisconnectFromServer() { if ( g_clientPeer == 0 ) return; Packet* p; unsigned char packetIdentifier; if ( g_clientPeer->IsConnected( g_clientPeer->GetSystemAddressFromIndex( 0 ) ) ) { g_clientPeer->CloseConnection( g_clientPeer->GetSystemAddressFromIndex( 0 ), true, 0 ); printf( "Disconnecting.\n" ); bool doLoop = true; while ( doLoop ) { Sleep(30); p = g_clientPeer->Receive(); if ( p == 0 ) continue; // Didn't get any packets // We got a packet, get the identifier with our handy function packetIdentifier = GetPacketIdentifier( p ); // Check if this is a network message packet switch ( packetIdentifier ) { case ID_DISCONNECTION_NOTIFICATION: // Connection lost normally printf("ID_DISCONNECTION_NOTIFICATION\n"); EpUser::DeleteAllUsers(); doLoop = false; break; } // We're done with the packet g_clientPeer->DeallocatePacket( p ); } } //SAFE_DELETE( g_rpc3Inst ); }
[ [ [ 1, 37 ], [ 39, 40 ], [ 43, 110 ], [ 112, 457 ], [ 459, 494 ], [ 496, 798 ], [ 800, 801 ], [ 803, 815 ], [ 819, 822 ], [ 828, 828 ], [ 836, 927 ], [ 931, 931 ], [ 933, 1138 ], [ 1140, 1826 ] ], [ [ 38, 38 ] ], [ [ 41, 42 ], [ 111, 111 ], [ 458, 458 ], [ 495, 495 ], [ 799, 799 ], [ 802, 802 ], [ 816, 818 ], [ 823, 827 ], [ 829, 835 ], [ 928, 930 ], [ 932, 932 ] ], [ [ 1139, 1139 ] ] ]
59e7b3cb257b1e04db5d382121e7e4f54a5a01bb
d8f64a24453c6f077426ea58aaa7313aafafc75c
/DeltaTime.h
aa33397e8f8883ca062a6522f087a7c48eb36fbc
[]
no_license
dotted/wfto
5b98591645f3ddd72cad33736da5def09484a339
6eebb66384e6eb519401bdd649ae986d94bcaf27
refs/heads/master
2021-01-20T06:25:20.468978
2010-11-04T21:01:51
2010-11-04T21:01:51
32,183,921
1
0
null
null
null
null
UTF-8
C++
false
false
334
h
#ifndef DELTA_TIME_H #define DELTA_TIME_H #include <windows.h> namespace control { class CDeltaTime { public: CDeltaTime(); ~CDeltaTime(); void beforeUpdate(); void afterUpdate(); float getDelta(); private: DWORD dwLastFrame, dwCurrent, dwDelta; }; }; #endif // DELTA_TIME_H
[ [ [ 1, 27 ] ] ]
4cf39997b1183b11f24e4f15a934e0e435dc9061
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/unique_id.hpp
b5a7dc8daa7fb6bc099ca3e7314a34a853b404fe
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
5,389
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // /** * @file * @brief Generated from unique_id.xsd. */ #ifndef AOSLCPP_AOSL__UNIQUE_ID_HPP #define AOSLCPP_AOSL__UNIQUE_ID_HPP // Begin prologue. // #include <aoslcpp/common.hpp> // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include "aosl/unique_id_forward.hpp" #include <memory> // std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include <xsd/cxx/tree/containers-wildcard.hxx> #ifndef XSD_DONT_INCLUDE_INLINE #define XSD_DONT_INCLUDE_INLINE #undef XSD_DONT_INCLUDE_INLINE #else #endif // XSD_DONT_INCLUDE_INLINE /** * @brief C++ namespace for the %artofsequence.org/aosl/1.0 * schema namespace. */ namespace aosl { /** * @brief Class corresponding to the %unique_id schema type. * * Unique identifier type. * * @nosubgrouping */ class Unique_id: public ::xml_schema::Id { public: /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ Unique_id (const ::xml_schema::Id&); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Unique_id (const ::xercesc::DOMElement& e, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Create an instance from a DOM attribute. * * @param a A DOM attribute to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Unique_id (const ::xercesc::DOMAttr& a, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Create an instance from a string fragment. * * @param s A string fragment to extract the data from. * @param e A pointer to DOM element containing the string fragment. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Unique_id (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ Unique_id (const Unique_id& x, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual Unique_id* _clone (::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0) const; //@} /** * @brief Destructor. */ virtual ~Unique_id (); }; } #ifndef XSD_DONT_INCLUDE_INLINE #endif // XSD_DONT_INCLUDE_INLINE #include <iosfwd> namespace aosl { ::std::ostream& operator<< (::std::ostream&, const Unique_id&); } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace aosl { } #include <iosfwd> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLFormatter.hpp> #include <xsd/cxx/xml/dom/auto-ptr.hxx> namespace aosl { void operator<< (::xercesc::DOMElement&, const Unique_id&); void operator<< (::xercesc::DOMAttr&, const Unique_id&); void operator<< (::xml_schema::ListStream&, const Unique_id&); } #ifndef XSD_DONT_INCLUDE_INLINE #include "aosl/unique_id.inl" #endif // XSD_DONT_INCLUDE_INLINE #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__UNIQUE_ID_HPP
[ "klaim@localhost" ]
[ [ [ 1, 216 ] ] ]
053b1d5cc593fe4397b2de6114383a26bc575923
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/signals/nsignalbindingset.cc
14975f4af627f2f4bc4c5fb7dae8fe6655a90374
[]
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
3,664
cc
//------------------------------------------------------------------------------ // nsignalbindingset.cc // (c) 2004 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchnkernel.h" #include "signals/nsignalbindingset.h" //------------------------------------------------------------------------------ bool nSignalBindingSet::RemoveBinding(nSignalBinding * binding) { if (!this->HasBinding(binding)) { return false; } n_delete(binding); return true; } //------------------------------------------------------------------------------ bool nSignalBindingSet::RemoveBinding(const nObject * objectPtr) { bool found = false; nSignalBinding * binding = this->GetHead(); while (binding != 0) { nSignalBinding * tmp = binding->GetSucc(); if (binding->IsBoundWithObject(objectPtr)) { n_delete(binding); found = true; } binding = tmp; } return found; } //------------------------------------------------------------------------------ bool nSignalBindingSet::RemoveBinding(const nObject * objectPtr, const nCmdProto * cmdPtr) { bool found = false; nSignalBinding * binding = this->GetHead(); while (binding != 0) { nSignalBinding * tmp = binding->GetSucc(); if (binding->IsBoundWithObject(objectPtr) && binding->IsBoundWithCmdProto(cmdPtr)) { n_delete(binding); found = true; } binding = tmp; } return found; } //------------------------------------------------------------------------------ bool nSignalBindingSet::RemoveBinding(const nObject * objectPtr, nFourCC fcc) { bool found = false; nSignalBinding * binding = this->GetHead(); while (binding != 0) { nSignalBinding * tmp = binding->GetSucc(); if (binding->IsBoundWithObject(objectPtr) && binding->IsBoundWithCmdFourCC(fcc)) { n_delete(binding); found = true; } binding = tmp; } return found; } //------------------------------------------------------------------------------ bool nSignalBindingSet::RemoveBinding(const nObject * objectPtr, const char * name) { bool found = false; nSignalBinding * binding = this->GetHead(); while (binding != 0) { nSignalBinding * tmp = binding->GetSucc(); if (binding->IsBoundWithObject(objectPtr) && binding->IsBoundWithCmdName(name)) { n_delete(binding); found = true; } binding = tmp; } return found; } //------------------------------------------------------------------------------ void nSignalBindingSet::RemoveAllBindings() { nSignalBinding * binding; while ( 0 != (binding = static_cast<nSignalBinding *> (this->bindings.RemHead()))) { n_delete(binding); } } //------------------------------------------------------------------------------ bool nSignalBindingSet::HasBinding(const nSignalBinding * binding) const { nSignalBinding * item = this->GetHead(); // Note the first element never is nSignalBinding while (0 != item) { if (item == binding) { return true; } item = item->GetSucc(); } return false; } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 134 ] ] ]
4bff2ad4928ac63affac0bc34c2fc9951365ccee
c655873fdcffba50abae5cba17eab2ea6ab1d63b
/core/temp.h
def212122aa791c7f259aa1568ef12a5f8811121
[]
no_license
Shiryu/ManShop
46a13f246ec2dba014aadc4c37ed9fd3fad3333c
979f587dcb6d98ddee4207e532a72015978a303b
refs/heads/master
2020-05-29T09:04:39.825239
2011-04-15T08:13:35
2011-04-15T08:13:35
1,560,109
0
0
null
null
null
null
UTF-8
C++
false
false
1,969
h
#ifndef TEMP_H #define TEMP_H #include "objet.h" #include "typeproduit.h" namespace Core { class Temp : public QDjangoModel { Q_OBJECT Q_PROPERTY( QString code READ getCode WRITE setCode ) Q_PROPERTY( QString constructeur READ getConstructeur WRITE setConstructeur ) Q_PROPERTY( QString nom READ getNom WRITE setNom ) Q_PROPERTY( QString description READ getDescription WRITE setDescription ) Q_PROPERTY( Core::TypeProduit* type READ getType WRITE setType ) Q_PROPERTY( double prixUnitaire READ getPrixUnitaire WRITE setPrixUnitaire ) Q_CLASSINFO( "__meta__", "db_table=temp" ) Q_CLASSINFO( "code", "primary_key=true" ) private: QString m_code; QString m_constructeur; QString m_nom; QString m_description; TypeProduit *type; double m_prixUnitaire; public: Temp( QObject *parent = 0 ) : QDjangoModel( parent ) { setForeignKey( "type", new TypeProduit( this ) ); } QString getCode() const { return m_code; } QString getConstructeur() const { return m_constructeur; } QString getNom() const { return m_nom; } QString getDescription() const { return m_description; } TypeProduit* getType() const { return qobject_cast< TypeProduit* >( foreignKey( "type" ) ); } double getPrixUnitaire() const { return m_prixUnitaire; } void setCode( QString code ) { m_code = code; } void setConstructeur( QString constructeur ) { m_constructeur = constructeur; } void setNom( QString nom ) { m_nom = nom; } void setDescription( QString description ) { m_description = description; } void setType( TypeProduit *type ) { setForeignKey( "type", type ); } void setPrixUnitaire( double prixUnitaire ) { m_prixUnitaire = prixUnitaire; } }; }; #endif // TEMP_H
[ [ [ 1, 53 ] ] ]
073ed3589ce23c6fec35d723c0cb6db1d8d83c4a
208475bcab65438eed5d8380f26eacd25eb58f70
/test/UdpTest.cpp
1f6a346082965e3f80cfaf6a9c8a2ea6b1adf05e
[]
no_license
awzhang/MyWork
83b3f0b9df5ff37330c0e976310d75593f806ec4
075ad5d0726c793a0c08f9158080a144e0bb5ea5
refs/heads/master
2021-01-18T07:57:03.219372
2011-07-05T02:41:55
2011-07-05T02:46:30
15,523,223
1
2
null
null
null
null
GB18030
C++
false
false
2,429
cpp
#include "../SockServExe/StdAfx.h" //arm-hismall-linux-g++ -o /work/Hi3511_VSSDK_V1.1.2.3/V8_rootbox/UdpTest ./test/UdpTest.cpp -lpthread -lComuServ -L./ComuServ #define PACK_SIZE 1024 int main() { int sock; BOOL blVal; int iVal; LINGER ling; struct sockaddr_in localaddr; struct sockaddr_in adrTo; unsigned long ulIP = INADDR_ANY; FILE *fp = NULL; char szBuf[PACK_SIZE+4] = {0}; sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if( -1 == sock ) { printf("create socket failed!\n"); return 1; } localaddr.sin_family = AF_INET; localaddr.sin_port = htons(3031); localaddr.sin_addr.s_addr = ulIP; if( bind( sock, (SOCKADDR*)&localaddr, sizeof(localaddr) ) ) { printf("bind socket failed!\n"); return 1; } ling.l_onoff = 1; // 强制关闭且立即释放资源 ling.l_linger = 0; setsockopt( sock, SOL_SOCKET, SO_LINGER, (char*)&ling, sizeof(ling) ); blVal = FALSE; setsockopt( sock, SOL_SOCKET, SO_OOBINLINE, (char*)&blVal, sizeof(blVal) ); iVal = 1024*20; setsockopt( sock, SOL_SOCKET, SO_RCVBUF, (char*)&iVal, sizeof(iVal) ); iVal = 0; setsockopt( sock, SOL_SOCKET, SO_SNDBUF, (char*)&iVal, sizeof(iVal) ); // 设置为非阻塞 // int iFlag = fcntl(sock, F_GETFL, 0); // fcntl(sock, F_SETFL, iFlag | O_NONBLOCK); adrTo.sin_family = AF_INET; // adrTo.sin_port = htons(10102); // adrTo.sin_addr.s_addr = inet_addr("202.118.226.74"); adrTo.sin_port = htons(4800); adrTo.sin_addr.s_addr = inet_addr("113.18.140.137"); fp = fopen("test.264", "rb"); if( NULL == fp ) { printf("open file test.264 failed!\n"); return 1; } int i=1; DWORD dwLastSendTm = GetTickCount(); //fread(szBuf+4, 1, PACK_SIZE, fp); _SEND: // while( GetTickCount() - dwLastSendTm > 50 ) for(i=1; i<=800; ) { // for(int j=0; j<2; j++) // { if( PACK_SIZE == fread(szBuf+4, 1, PACK_SIZE, fp) ) { memcpy(szBuf, (void*)&i, 4); if( 0 < sendto( sock, szBuf, PACK_SIZE+4, 0, (struct sockaddr*)&adrTo, sizeof(adrTo) ) ) { printf("send %d pack, TickCount: %d\n", i++, GetTickCount()); } else { printf("send failed!\n"); perror(""); break; } } else { break; } // i++; // } // dwLastSendTm = GetTickCount(); // usleep(60000); } // if( i<=200 ) goto _SEND; PRTMSG(MSG_NOR, "send over!\n"); fclose(fp); }
[ [ [ 1, 109 ] ] ]
0556ddc2adcfd9ffbdc04ffa33eaff4e2e07daea
777399eafeb952743fcb973fbba392842c2e9b14
/CyberneticWarrior/CyberneticWarrior/source/CBullet.h
495797eb23655dade204c27c809eb92994a7b7f6
[]
no_license
Warbeleth/cyberneticwarrior
7c0af33ada4d461b90dc843c6a25cd5dc2ba056a
21959c93d638b5bc8a881f75119d33d5708a3ea9
refs/heads/master
2021-01-10T14:31:27.017284
2010-11-23T23:16:28
2010-11-23T23:16:28
53,352,209
0
0
null
null
null
null
UTF-8
C++
false
false
245
h
#ifndef CBULLET_H_ #define CBULLET_H_ #include "CBaseProjectile.h" class CBullet : public CBaseProjectile { public: CBullet(void); ~CBullet(void); void Update(float fElapsedTime); bool CheckCollision(CBase* pBase); }; #endif
[ "[email protected]", "atmuccio@d49f6b0b-9fae-41b6-31ce-67b77e794db9" ]
[ [ [ 1, 3 ], [ 5, 5 ], [ 7, 15 ] ], [ [ 4, 4 ], [ 6, 6 ] ] ]
45fe777ca587cc9ef7cc9cee3cd9e738a5de8eee
bfe8eca44c0fca696a0031a98037f19a9938dd26
/libjingle-0.4.0/talk/base/helpers.h
8acbc6d88a062b1efecb9f6294b010c126d701d6
[ "BSD-3-Clause" ]
permissive
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
2,204
h
/* * libjingle * Copyright 2004--2005, 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. * 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 AUTHOR 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 __HELPERS_H__ #define __HELPERS_H__ #include "talk/base/basictypes.h" #include <string> namespace cricket { // srand initializer void InitRandom(const char *client_unique, size_t len); // For testing, the random seed can be directly accessed. long GetRandomSeed(); void SetRandomSeed(unsigned long seed); // Generates a (cryptographically) random string of the given length. std::string CreateRandomString(int length); // Generates a random id uint32 CreateRandomId(); // Determines whether the given string consists entirely of valid base64 // encoded characters. bool IsBase64Encoded(const std::string& str); } // namespace cricket #endif // __HELPERS_H__
[ "[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 55 ] ] ]
33183d50e218e3d777a3bb0a53bda86ecb8316e8
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor-0.32/GumpPropertyPage.cpp
eb3c5a5bf5b92950902829352e74bf262b5f191c
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UHC
C++
false
false
3,226
cpp
// GumpPropertyPage.cpp : 구현 파일입니다. // #include "stdafx.h" #include "GumpEditor.h" #include ".\gumppropertypage.h" #include "gumpentity.h" // CGumpPropertyPage 대화 상자입니다. IMPLEMENT_DYNAMIC(CGumpPropertyPage, CDiagramPropertyPage) CGumpPropertyPage::CGumpPropertyPage() : CDiagramPropertyPage(CGumpPropertyPage::IDD) , m_xPos(0) , m_yPos(0) , m_iWidth(0) , m_iHeight(0) , m_iAlpha(0) , m_strEvClick(_T("")) , m_strEvClose(_T("")) , m_strEvMouseUp(_T("")) , m_strEvMouseDown(_T("")) , m_strEvKeyPressed(_T("")) , m_strName(_T("")) , m_strType(_T("")) { } CGumpPropertyPage::~CGumpPropertyPage() { } void CGumpPropertyPage::DoDataExchange(CDataExchange* pDX) { CDiagramPropertyPage::DoDataExchange(pDX); DDX_Text(pDX, IDC_ALPHA, m_iAlpha); DDX_Control(pDX, IDC_ALPHASPIN, m_spinAlpha); DDX_Control(pDX, IDC_XSPIN, m_spinX); DDX_Control(pDX, IDC_YSPIN, m_spinY); DDX_Control(pDX, IDC_WSPIN, m_spinW); DDX_Control(pDX, IDC_HSPIN, m_spinH); DDX_Text(pDX, IDC_XPOS, m_xPos); DDX_Text(pDX, IDC_YPOS, m_yPos); DDX_Text(pDX, IDC_W, m_iWidth); DDX_Text(pDX, IDC_H, m_iHeight); DDX_Text(pDX, IDC_EVENT_ONCLICK, m_strEvClick); DDX_Text(pDX, IDC_EVENT_ONCLOSE, m_strEvClose); DDX_Text(pDX, IDC_EVENT_ONMOUSEUP, m_strEvMouseUp); DDX_Text(pDX, IDC_EVENT_ONMOUSEDOWN, m_strEvMouseDown); DDX_Text(pDX, IDC_EVENT_ONKEYPRESSED, m_strEvKeyPressed); DDX_Text(pDX, IDC_NAME, m_strName); DDX_Text(pDX, IDC_TYPE, m_strType); } BEGIN_MESSAGE_MAP(CGumpPropertyPage, CDiagramPropertyPage) END_MESSAGE_MAP() // CGumpPropertyPage 메시지 처리기입니다. BOOL CGumpPropertyPage::OnInitDialog() { CDiagramPropertyPage::OnInitDialog(); m_spinX.SetRange32(-0xffff,0xffff); m_spinY.SetRange32(-0xffff,0xffff); m_spinW.SetRange32(0,0xffff); m_spinH.SetRange32(0,0xffff); m_spinAlpha.SetRange32(0,0xffff); CGumpEntity* pEntity= (CGumpEntity*)GetEntity(); if (pEntity && pEntity->IsFixedSize()) { GetDlgItem(IDC_W)->SendMessage(EM_SETREADONLY,1); GetDlgItem(IDC_H)->SendMessage(EM_SETREADONLY,1); m_spinW.EnableWindow(FALSE); m_spinH.EnableWindow(FALSE); } return TRUE; } void CGumpPropertyPage::SetValues() { if (GetSafeHwnd() && GetEntity()) { CGumpEntity* pEntity= (CGumpEntity*)GetEntity(); m_strName = pEntity->GetName(); m_strType = pEntity->GetType(); m_iAlpha = pEntity->GetAlpha(); pEntity->GetEventHandler(m_strEvClick, m_strEvClose, m_strEvMouseUp, m_strEvMouseDown, m_strEvKeyPressed); CRect rect = pEntity->GetRect(); m_xPos = rect.left; m_yPos = rect.top; m_iWidth = rect.Width(); m_iHeight = rect.Height(); UpdateData(FALSE); } } void CGumpPropertyPage::ApplyValues() { if (GetSafeHwnd() && GetEntity()) { UpdateData(); CGumpEntity* pEntity = (CGumpEntity*)GetEntity(); pEntity->SetName(m_strName); pEntity->SetAlpha(m_iAlpha); pEntity->SetEventHandler(m_strEvClick, m_strEvClose, m_strEvMouseUp, m_strEvMouseDown, m_strEvKeyPressed); pEntity->SetRect(m_xPos, m_yPos, m_xPos + m_iWidth, m_yPos + m_iHeight); Redraw(); } } void CGumpPropertyPage::ResetValues() { }
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 128 ] ] ]
230dcf75b6800e30cb317188da0c4e04b462b27c
abafdd61ea123f3e90deb02fe5709951b453eec6
/fuzzy/patl/impl/partimator.hpp
8d31fcf75d6d3048fddb4ac388da1e1b50772c85
[ "BSD-3-Clause" ]
permissive
geoiq/geojoin-ruby
8a6a07938fe3d629de74aac50e61eb8af15ab027
247a80538c4fc68c365e71f9014b66d3c38526c1
refs/heads/master
2016-09-06T15:22:47.436634
2010-08-11T13:00:24
2010-08-11T13:00:24
13,863,658
2
0
null
null
null
null
UTF-8
C++
false
false
1,178
hpp
#ifndef PATL_IMPL_PARTIMATOR_HPP #define PATL_IMPL_PARTIMATOR_HPP #include "const_partimator.hpp" namespace uxn { namespace patl { namespace impl { template <typename Vertex, typename Decision> class partimator_generic : public const_partimator_generic<Vertex, Decision> { typedef const_partimator_generic<Vertex, Decision> super; typedef partimator_generic<Vertex, Decision> this_t; protected: typedef Vertex vertex; public: typedef typename super::value_type value_type; typedef value_type *pointer; typedef value_type &reference; explicit partimator_generic( const Decision &decis = Decision(), const vertex &vtx = vertex()) : super(decis, vtx) { } pointer operator->() { return &**this; } reference operator*() { return this->pit_->value(); } this_t &operator++() { ++(*(super*)this); return *this; } this_t operator++(int) { this_t it(*this); ++*this; return it; } }; } // namespace impl } // namespace patl } // namespace uxn #endif
[ "sderle@goldman.(none)" ]
[ [ [ 1, 61 ] ] ]
f9b5d423aa265678168aac8dc905abca7c9621c0
12fc725f8273ebfd9ece9ec19af748036823f495
/lua/sock/src/active_sock.cpp
cb52cacaed9f4fa279ac468c80d6dc8d608e27a6
[ "MIT" ]
permissive
contextlogger/contextlogger2
538e80c120f206553c4c88c5fc51546ae848785e
8af400c3da088f25fd1420dd63889aff5feb1102
refs/heads/master
2020-05-05T05:03:47.896638
2011-10-05T23:50:14
2011-10-05T23:50:14
1,675,623
1
0
null
null
null
null
UTF-8
C++
false
false
6,076
cpp
/* Copyright (c) 2009 David Bolcsfoldi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <es_sock.h> #include <in_sock.h> #include "active_sock.h" #include "activesocket.h" #include "lauxlib.h" _LIT8(KSocketServ, "active_socket.serv\0"); _LIT8(KSocketType, "active_socket.socket\0"); const TInt KDefaultBufferSize = 4096; using namespace ALua; static TUint to_addr_family(const char* aAddr) { TPtrC8 addr(reinterpret_cast<const unsigned char*>(aAddr), User::StringLength(reinterpret_cast<const unsigned char*>(aAddr))); _LIT8(KInet, "inet"); if (addr == KInet) { return KAfInet; } else { // Raise error return 0; } } static TUint to_sock_type(const char* aType) { TPtrC8 type(reinterpret_cast<const unsigned char*>(aType), User::StringLength(reinterpret_cast<const unsigned char*>(aType))); _LIT8(KStream, "stream"); _LIT8(KDatagram, "datagram"); if (type == KStream) { return KSockStream; } else if (type == KDatagram) { return KSockDatagram; } else { // Raise error return 0; } } static TUint to_protocol(const char* aProtocol) { TPtrC8 protocol(reinterpret_cast<const unsigned char*>(aProtocol), User::StringLength(reinterpret_cast<const unsigned char*>(aProtocol))); _LIT8(KTcp, "tcp"); _LIT8(KUdp, "udp"); if (protocol == KTcp) { return KProtocolInetTcp; } else if(protocol == KUdp) { return KProtocolInetUdp; } else { // Raise error return 0; } } static TInt socket_open(lua_State* L) { lua_pushstring(L, reinterpret_cast<const char*>(KSocketServ().Ptr())); lua_gettable(L, LUA_REGISTRYINDEX); TInt handle = luaL_checkint(L, -1); // Remove handle from stack lua_pop(L, 1); RSocketServ s; s.SetHandle(handle); TUint addrFamily = to_addr_family(luaL_optstring(L, 1, "inet")); TUint sockType = to_sock_type(luaL_optstring(L, 2, "stream")); TUint protocol = to_protocol(luaL_optstring(L, 3, "tcp")); // Allocate socket using user data so that we can return it from the function, // and have it collected using __gc CActiveSocket** socket = static_cast<CActiveSocket**>(lua_newuserdata(L, sizeof(CActiveSocket*))); TRAPD(err, *socket = CActiveSocket::NewL(s, addrFamily, sockType, protocol)); if (err != KErrNone) { // Raise massive error! } // Set up metadata table lua_pushstring(L, reinterpret_cast<const char*>(KSocketType().Ptr())); lua_gettable(L, LUA_REGISTRYINDEX); lua_setmetatable(L, 1); return 1; } static TInt socket_connect(lua_State* L) { CActiveSocket** socket = static_cast<CActiveSocket**>(luaL_checkudata(L, -3, reinterpret_cast<const char*>(KSocketType().Ptr()))); size_t len = 0; const char* u = luaL_checklstring(L, -2, &len); TPtrC8 uri(reinterpret_cast<const unsigned char*>(u), len); TInt port = luaL_checklong(L, -1); return (*socket)->Connect(*static_cast<CActiveFunction*>(active_ctx(L)), uri, port); } static TInt socket_read(lua_State* L) { CActiveSocket** socket = static_cast<CActiveSocket**>(luaL_checkudata(L, 1, reinterpret_cast<const char*>(KSocketType().Ptr()))); TInt bufferSize = luaL_optlong(L, 2, KDefaultBufferSize); return (*socket)->Read(*static_cast<CActiveFunction*>(active_ctx(L)), bufferSize); } static TInt socket_write(lua_State* L) { CActiveSocket** socket = static_cast<CActiveSocket**>(luaL_checkudata(L, -2, reinterpret_cast<const char*>(KSocketType().Ptr()))); size_t len = 0; const char* u = luaL_checklstring(L, -1, &len); TPtrC8 data(reinterpret_cast<const unsigned char*>(u), len); return (*socket)->Write(*static_cast<CActiveFunction*>(active_ctx(L)), data); } static TInt socket_close(lua_State* L) { CActiveSocket** socket = static_cast<CActiveSocket**>(luaL_checkudata(L, -1, reinterpret_cast<const char*>(KSocketType().Ptr()))); return (*socket)->Close(); } static TInt socket_gc(lua_State* L) { CActiveSocket** socket = static_cast<CActiveSocket**>(luaL_checkudata(L, -1, reinterpret_cast<const char*>(KSocketType().Ptr()))); TInt ret = (*socket)->Close(); delete *socket; return ret; } static const struct luaL_Reg active_socket[] = { {"open", socket_open}, {"connect", socket_connect}, {"read", socket_read}, {"write", socket_write}, {"close", socket_close}, {NULL, NULL} }; EXPORT_C int active_sock_open(lua_State* L) { RSocketServ sockServ; if (sockServ.Connect() != KErrNone) { return 0; } /* Register socket server with global context */ lua_pushstring(L, reinterpret_cast<const char*>(KSocketServ().Ptr())); lua_pushnumber(L, sockServ.Handle()); lua_settable(L, LUA_REGISTRYINDEX); luaL_register(L, "socket", active_socket); luaL_newmetatable(L, reinterpret_cast<const char*>(KSocketType().Ptr())); lua_pushcfunction(L, socket_gc); lua_setfield(L, -2, "__gc"); lua_pushstring(L, reinterpret_cast<const char*>(KSocketType().Ptr())); lua_settable(L, LUA_REGISTRYINDEX); return 1; }
[ [ [ 1, 218 ] ] ]