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
927cb24676388b1aa75d20e2054f9740c44e2dc3
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/PhysXStream.h
2375d9f8ac86381d22863bf660bc2736f2d2ab14
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
2,329
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: PhysXStream.h Version: 0.03 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_PHYSXSTREAM_H_ #define __INC_PHYSXSTREAM_H_ #include "Prerequisities.h" #include "PrerequisitiesPhysX.h" #pragma warning(push) #pragma warning(disable:4245) #pragma warning(disable:4512) #include "NxStream.h" #pragma warning(pop) namespace nGENE { /** NxStream implementation by Ageia Corp. */ class MemoryWriteBuffer: public NxStream { private: uint m_nCurrentSize; uint m_nMaxSize; byte* m_pData; public: MemoryWriteBuffer(); virtual ~MemoryWriteBuffer(); virtual byte readByte() const {return 0;} virtual ushort readWord() const {return 0;} virtual uint readDword() const {return 0;} virtual Real readFloat() const {return 0.0f;} virtual double readDouble() const {return 0.0;} virtual void readBuffer(void* buffer, uint size) const {} virtual NxStream& storeByte(byte b); virtual NxStream& storeWord(ushort w); virtual NxStream& storeDword(uint d); virtual NxStream& storeFloat(Real f); virtual NxStream& storeDouble(double f); virtual NxStream& storeBuffer(const void* buffer, uint size); byte* getData() const {return m_pData;} }; /** NxStream implementation by Ageia Corp. */ class MemoryReadBuffer: public NxStream { private: mutable const byte* m_pBuffer; public: MemoryReadBuffer(const byte* data); virtual ~MemoryReadBuffer(); virtual byte readByte() const; virtual ushort readWord() const; virtual uint readDword() const; virtual Real readFloat() const; virtual double readDouble() const; virtual void readBuffer(void* buffer, uint size) const; virtual NxStream& storeByte(byte b) {return *this;} virtual NxStream& storeWord(ushort w) {return *this;} virtual NxStream& storeDword(uint d) {return *this;} virtual NxStream& storeFloat(Real f) {return *this;} virtual NxStream& storeDouble(double f) {return *this;} virtual NxStream& storeBuffer(const void* buffer, uint size) {return *this;} }; } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 89 ] ] ]
d7dbc3eabce13c8be0de35c61283aec7de74e565
cd61c8405fae2fa91760ef796a5f7963fa7dbd37
/Sauron/Vision/CameraParams.h
5f6e72085ef510368020836d32b234cad975e53f
[]
no_license
rafaelhdr/tccsauron
b61ec89bc9266601140114a37d024376a0366d38
027ecc2ab3579db1214d8a404d7d5fa6b1a64439
refs/heads/master
2016-09-05T23:05:57.117805
2009-12-14T09:41:58
2009-12-14T09:41:58
32,693,544
0
0
null
null
null
null
UTF-8
C++
false
false
809
h
#ifndef __CAMERA_PARAMS_H__ #define __CAMERA_PARAMS_H__ namespace sauron { class CameraParams { public: // TODO Set the values static double getHorizontalFocalDistance() { return 394.8956276848544500; }//274.9938104610965900; } // run calibration static double getVerticalFocalDistance() { return 394.3910703010728300; }//274.2551230486371300; } // run calibration static double getProjectionPlaneHorizontalCenter() { return 161.9690548236380600; } // run calibration static double getProjectionPlaneVerticalCenter() { return 138.3758441701515100; } // run calibration static double getAngleOfView() { return 2.094; } // radians }; } // namespace sauron #endif // __CAMERA_PARAMS_H__
[ "fggodoy@8373e73c-ebb0-11dd-9ba5-89a75009fd5d" ]
[ [ [ 1, 21 ] ] ]
0ea940f2254cc3a1e84b1a49870e9f14718ba6a0
3ea8b8900d21d0113209fd02bd462310bd0fce83
/mt.hpp
081e9c90a431b60c0308701b8522b34518507ec8
[]
no_license
LazurasLong/bgmlib
56958b7dffd98d78f99466ce37c4abaddc7da5b1
a9d557ea76a383fae54dc3729aaea455c258777a
refs/heads/master
2022-12-04T02:58:36.450986
2011-08-16T17:44:46
2011-08-16T17:44:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
hpp
// Tasofro Mersenne Twister implementation // Stolen from Brightmoon sources... #ifndef MT_HPP #define MT_HPP typedef long int32_t; typedef unsigned short uint16_t; typedef unsigned char uint8_t; class RNG_MT { private: enum { N = 624, M = 397, MATRIX_A = 0x9908b0dfUL, UPPER_MASK = 0x80000000UL, LOWER_MASK = 0x7FFFFFFFUL }; private: ulong mt[N]; long mti; public: explicit RNG_MT(ulong s) { init(s); } void init(ulong s) { mt[0] = s; for(mti = 1; mti < N; ++mti) { mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); } } ulong next_int32() { ulong y; static const ulong mag01[2]={0x0UL, MATRIX_A}; if (mti >= N) { int kk; if (mti == N+1) init(5489UL); for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } }; #endif
[ [ [ 1, 76 ] ] ]
0bdbacfb97a56a9c425da44bbe089fc031815753
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/TaskManager.h
18134570ad5cbb0c5401064494973bc49828e06f
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
2,216
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: TaskManager.h Version: 0.01 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_TASKMANAGER_H_ #define __INC_TASKMANAGER_H_ #include "Prerequisities.h" #include "Singleton.h" #include "WorkerThread.h" namespace nGENE { /** Manages all the tasks. @todo remember to synchronize access to the vectors in this class! */ class nGENEDLL TaskManager: public Singleton <TaskManager> { private: vector <Task*> m_vNotCompleted; ///< List of task to do this frame vector <WorkerThread*> m_vWorkers; ///< Worker threads ///< Tasks currently possible to perform (ready to run). priority_queue <Task*, vector <Task*>, TaskComparator> m_vOpenTasks; Task* m_pRootTask; ///< Root task uint m_nActiveTasks; ///< Number of not completed tasks CriticalSection m_CriticalSection; ///< Critical section bool m_bRunning; public: TaskManager(); ~TaskManager(); /// Stops task manager. void stop(); /// Adds Task to open list. void addTask(Task* _task); /// Removes Task from the manager. void removeTask(Task* _task); /// Returns next Task to perform. Task* getNextTask(); /// Sets root task. void setRootTask(Task* _task); /// Returns root task. Task* getRootTask() const; /// Decreases number of active tasks. void decreaseActiveTasks(); void init(uint _threadsNum); void cleanup(); void setRunning(bool _run); void update(); }; inline void TaskManager::setRootTask(Task* _task) { m_pRootTask = _task; } //---------------------------------------------------------------------- inline Task* TaskManager::getRootTask() const { return m_pRootTask; } //---------------------------------------------------------------------- inline void TaskManager::setRunning(bool _run) { m_bRunning = _run; } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 97 ] ] ]
335d516207d4770acf48694b884925d421e24488
0466568120485fcabdba5aa22a4b0fea13068b8b
/opencv/samples/gpu/cascadeclassifier.cpp
7bb89834a1d02194185ee9f11dce7b905805ea65
[]
no_license
coapp-packages/opencv
be25a9aec58d9ac890fc764932ba67914add078d
c78981e0d8f602fde523a82c3a7e2c3fef1f39bc
refs/heads/master
2020-05-17T12:11:25.406742
2011-07-14T17:13:01
2011-07-14T17:13:01
2,048,483
3
0
null
null
null
null
UTF-8
C++
false
false
7,990
cpp
// WARNING: this sample is under construction! Use it on your own risk. #if defined _MSC_VER && _MSC_VER >= 1400 #pragma warning(disable : 4100) #endif #include <iostream> #include <iomanip> #include "opencv2/contrib/contrib.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/gpu/gpu.hpp" using namespace std; using namespace cv; using namespace cv::gpu; void help() { cout << "Usage: ./cascadeclassifier <cascade_file> <image_or_video_or_cameraid>\n" "Using OpenCV version " << CV_VERSION << endl << endl; } template<class T> void convertAndResize(const T& src, T& gray, T& resized, double scale) { if (src.channels() == 3) { cvtColor( src, gray, CV_BGR2GRAY ); } else { gray = src; } Size sz(cvRound(gray.cols * scale), cvRound(gray.rows * scale)); if (scale != 1) { resize(gray, resized, sz); } else { resized = gray; } } void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const string &ss) { int fontFace = FONT_HERSHEY_DUPLEX; double fontScale = 0.8; int fontThickness = 2; Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0); Point org; org.x = 1; org.y = 3 * fontSize.height * (lineOffsY + 1) / 2; putText(img, ss, org, fontFace, fontScale, CV_RGB(0,0,0), 5*fontThickness/2, 16); putText(img, ss, org, fontFace, fontScale, fontColor, fontThickness, 16); } void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps) { Scalar fontColorRed = CV_RGB(255,0,0); Scalar fontColorNV = CV_RGB(118,185,0); ostringstream ss; ss << "FPS = " << setprecision(1) << fixed << fps; matPrint(canvas, 0, fontColorRed, ss.str()); ss.str(""); ss << "[" << canvas.cols << "x" << canvas.rows << "], " << (bGpu ? "GPU, " : "CPU, ") << (bLargestFace ? "OneFace, " : "MultiFace, ") << (bFilter ? "Filter:ON" : "Filter:OFF"); matPrint(canvas, 1, fontColorRed, ss.str()); // by Anatoly. MacOS fix. ostringstream(const string&) is a private // matPrint(canvas, 2, fontColorNV, ostringstream("Space - switch GPU / CPU")); if (bHelp) { matPrint(canvas, 2, fontColorNV, "Space - switch GPU / CPU"); matPrint(canvas, 3, fontColorNV, "M - switch OneFace / MultiFace"); matPrint(canvas, 4, fontColorNV, "F - toggle rectangles Filter"); matPrint(canvas, 5, fontColorNV, "H - toggle hotkeys help"); matPrint(canvas, 6, fontColorNV, "1/Q - increase/decrease scale"); } else { matPrint(canvas, 2, fontColorNV, "H - toggle hotkeys help"); } } int main(int argc, const char *argv[]) { if (argc != 3) { return help(), -1; } if (getCudaEnabledDeviceCount() == 0) { return cerr << "No GPU found or the library is compiled without GPU support" << endl, -1; } VideoCapture capture; string cascadeName = argv[1]; string inputName = argv[2]; CascadeClassifier_GPU cascade_gpu; if (!cascade_gpu.load(cascadeName)) { return cerr << "ERROR: Could not load cascade classifier \"" << cascadeName << "\"" << endl, help(), -1; } CascadeClassifier cascade_cpu; if (!cascade_cpu.load(cascadeName)) { return cerr << "ERROR: Could not load cascade classifier \"" << cascadeName << "\"" << endl, help(), -1; } Mat image = imread(inputName); if (image.empty()) { if (!capture.open(inputName)) { int camid = -1; istringstream iss(inputName); iss >> camid; if (!capture.open(camid)) { cout << "Can't open source" << endl; return help(), -1; } } } namedWindow("result", 1); Mat frame, frame_cpu, gray_cpu, resized_cpu, faces_downloaded, frameDisp; vector<Rect> facesBuf_cpu; GpuMat frame_gpu, gray_gpu, resized_gpu, facesBuf_gpu; /* parameters */ bool useGPU = true; double scaleFactor = 1.0; bool findLargestObject = false; bool filterRects = true; bool helpScreen = false; int detections_num; for (;;) { if (capture.isOpened()) { capture >> frame; if (frame.empty()) { break; } } (image.empty() ? frame : image).copyTo(frame_cpu); frame_gpu.upload(image.empty() ? frame : image); convertAndResize(frame_gpu, gray_gpu, resized_gpu, scaleFactor); convertAndResize(frame_cpu, gray_cpu, resized_cpu, scaleFactor); TickMeter tm; tm.start(); if (useGPU) { cascade_gpu.visualizeInPlace = true; cascade_gpu.findLargestObject = findLargestObject; detections_num = cascade_gpu.detectMultiScale(resized_gpu, facesBuf_gpu, 1.2, (filterRects || findLargestObject) ? 4 : 0); facesBuf_gpu.colRange(0, detections_num).download(faces_downloaded); } else { Size minSize = cascade_gpu.getClassifierSize(); cascade_cpu.detectMultiScale(resized_cpu, facesBuf_cpu, 1.2, (filterRects || findLargestObject) ? 4 : 0, (findLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0) | CV_HAAR_SCALE_IMAGE, minSize); detections_num = (int)facesBuf_cpu.size(); } if (!useGPU && detections_num) { for (int i = 0; i < detections_num; ++i) { rectangle(resized_cpu, facesBuf_cpu[i], Scalar(255)); } } if (useGPU) { resized_gpu.download(resized_cpu); } tm.stop(); double detectionTime = tm.getTimeMilli(); double fps = 1000 / detectionTime; //print detections to console cout << setfill(' ') << setprecision(2); cout << setw(6) << fixed << fps << " FPS, " << detections_num << " det"; if ((filterRects || findLargestObject) && detections_num > 0) { Rect *faceRects = useGPU ? faces_downloaded.ptr<Rect>() : &facesBuf_cpu[0]; for (int i = 0; i < min(detections_num, 2); ++i) { cout << ", [" << setw(4) << faceRects[i].x << ", " << setw(4) << faceRects[i].y << ", " << setw(4) << faceRects[i].width << ", " << setw(4) << faceRects[i].height << "]"; } } cout << endl; cvtColor(resized_cpu, frameDisp, CV_GRAY2BGR); displayState(frameDisp, helpScreen, useGPU, findLargestObject, filterRects, fps); imshow("result", frameDisp); int key = waitKey(5); if (key == 27) { break; } switch ((char)key) { case ' ': useGPU = !useGPU; break; case 'm': case 'M': findLargestObject = !findLargestObject; break; case 'f': case 'F': filterRects = !filterRects; break; case '1': scaleFactor *= 1.05; break; case 'q': case 'Q': scaleFactor /= 1.05; break; case 'h': case 'H': helpScreen = !helpScreen; break; } } return 0; }
[ "anatoly@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08", "vp153@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08", "anton@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08" ]
[ [ [ 1, 1 ], [ 5, 6 ], [ 14, 18 ], [ 20, 26 ], [ 29, 53 ], [ 56, 72 ], [ 74, 74 ], [ 76, 78 ], [ 80, 133 ], [ 138, 185 ], [ 188, 192 ], [ 198, 200 ], [ 202, 202 ], [ 204, 204 ], [ 206, 272 ] ], [ [ 2, 2 ], [ 4, 4 ], [ 9, 13 ] ], [ [ 3, 3 ], [ 7, 8 ], [ 19, 19 ], [ 27, 28 ], [ 54, 55 ], [ 73, 73 ], [ 75, 75 ], [ 79, 79 ], [ 134, 137 ], [ 186, 187 ], [ 193, 197 ], [ 201, 201 ], [ 203, 203 ], [ 205, 205 ] ] ]
6f23bcd1ed4195fdaf073839bfa6c62127381e92
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/ServerModule/GameServer/GameServerDlg.h
74f9ff3164fd51e8108627e05cd277a3c627fbcc
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
3,018
h
#ifndef SERVIVE_LOADER_DLG_HEAD_FILE #define SERVIVE_LOADER_DLG_HEAD_FILE #pragma once #include "Stdafx.h" #include "Resource.h" #include "InitParamter.h" #include "RequestSocket.h" #include "../../ShareModule/GridCtrl/GridCtrl.h" #include "../../ShareModule/GridCtrl/NewCellTypes/GridBtnCell.h" #include "../../ShareModule/GameServiceParamFile/GameServiceParamFile.h" ////////////////////////////////////////////////////////////////////////// //配置对话框 class CSystemOptionDlg : public CDialog { //构造函数 public: //构造程序 CSystemOptionDlg(CInitParamter* pOutInitParamter=NULL); //析构函数 virtual ~CSystemOptionDlg(); CInitParamter* m_pOutInitParamter; //重载函数 protected: //初始化函数 virtual BOOL OnInitDialog(); //控件子类化 virtual void DoDataExchange(CDataExchange * pDX); //确定函数 virtual void OnOK(); //消息映射 DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////// //程序主窗口 class CGameServerDlg : public CDialog { //组件变量 public: //控件变量 public: CRichEditCtrl m_RichEditCtrl; //信息窗口 CGridCtrl m_gridGameService; CBtnDataBase m_BtnDataBase; CEventServiceHelper m_EventService; //事件服务 BOOL m_bSetStartGameServiceTimer; //函数定义 public: //构造函数 CGameServerDlg(); //析构函数 virtual ~CGameServerDlg(); //显示错误 void ShowErrorMessasge(LPCTSTR pszString, enTraceLevel TraceLevel); void ShowDescribeMessage(int nGameServiceHelperIndex,LPCTSTR pszString); void NotifyServiceStatus(int nGameServiceHelperIndex,bool bRunning); //重载函数 protected: //控件绑定 virtual void DoDataExchange(CDataExchange * pDX); //消息解释 virtual BOOL PreTranslateMessage(MSG * pMsg); //初始化函数 virtual BOOL OnInitDialog(); //确定消息 virtual void OnOK(); //取消函数 virtual void OnCancel(); //内部函数 protected: void LoadGameServiceParamFile(); void SaveGameServiceParamFile(); void StopAllGameService(); BOOL HaveGameServiceRunning(); BOOL IsAllGameServiceRunning(); void ClearGameService(); void NewGameService(GameServiceParam& param); void OnRunGameServerService(int nRow); void OnStopGameServerService(int nRow); void OnConfigGameServerService(int nRow); void CheckStartGameServiceTimer(); void KillStartGameServiceTimer(); //消息映射 protected: //启动服务 afx_msg void OnBnClickedStart(); //停止服务 afx_msg void OnBnClickedStop(); afx_msg void OnBnNewGameService(); afx_msg void OnBnDelGameService(); afx_msg void OnBnSaveGameService(); DECLARE_MESSAGE_MAP() public: afx_msg BOOL OnQueryEndSession(); afx_msg void OnGridClick (NMHDR *pNotifyStruct, LRESULT* pResult); afx_msg void OnTimer (UINT nIDEvent); }; ////////////////////////////////////////////////////////////////////////// #endif
[ [ [ 1, 118 ] ] ]
33a25cae92f9c0ba428936a01d86942693b5104d
cb318077a36ea2885b66ebdfb61cb37f9096b27d
/MT4ODBCBridgeTest/mobtest.cpp
b45ecd619821806f3a3c8dcbd904b1f6f9dc3688
[]
no_license
danmi1258/mt4-odbc-bridge
aede37e60959d60e0b524c0d25f7c4e24164113e
422d2ae4137886babdbf6dff17e594f8d729049f
refs/heads/master
2021-05-26T13:54:46.648670
2011-08-29T10:48:51
2011-08-29T10:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,549
cpp
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <tchar.h> #pragma pack(push,1) struct RateInfo { unsigned int ctm; double open; double low; double high; double close; double vol; }; #pragma pack(pop) struct MqlStr { int len; char *string; }; int __stdcall MOB_create (); int __stdcall MOB_open (const int conId, const TCHAR *dns, const TCHAR *username, const TCHAR *password); int __stdcall MOB_close (const int conId); int __stdcall MOB_isDead (const int conId); int __stdcall MOB_commit (const int conId); int __stdcall MOB_rollback (const int conId); int __stdcall MOB_getAutoCommit (const int conId); int __stdcall MOB_setAutoCommit (const int conId, const int autoCommit); int __stdcall MOB_execute (const int conId, const TCHAR *sql); int __stdcall MOB_getLastErrorNo (const int conId); const TCHAR* __stdcall MOB_getLastErrorMesg (const int conId); int __stdcall MOB_registerStatement (const int conId, const TCHAR *sql); int __stdcall MOB_unregisterStatement(const int conId, const int stmtId); int __stdcall MOB_bindIntParameter (const int conId, const int stmtId, const int slot, int *intp); int __stdcall MOB_bindDoubleParameter(const int conId, const int stmtId, const int slot, double *dblp); int __stdcall MOB_bindStringParameter(const int conId, const int stmtId, const int slot, TCHAR *strp); int __stdcall MOB_bindDatetimeParameter(const int conId, const int stmtId, const int slot, unsigned int *timep); int __stdcall MOB_bindToFetch (const int conId, const int stmtId, unsigned int *tVals, const int tSize, int *iVals, const int iSize, double *dVals, const int dSize, MqlStr *sVals, const int sSize); int __stdcall MOB_bindIntColumn (const int conId, const int stmtId, const int slot, int *intp); int __stdcall MOB_bindDoubleColumn (const int conId, const int stmtId, const int slot, double *dblp); int __stdcall MOB_bindStringColumn (const int conId, const int stmtId, const int slot, TCHAR *strp); int __stdcall MOB_bindDatetimeColumn (const int conId, const int stmtId, const int slot, unsigned int *timep); int __stdcall MOB_executeStatement (const int conId, const int stmtId); int __stdcall MOB_selectToFetch (const int conId, const int stmtId); int __stdcall MOB_fetch (const int conId, const int stmtId); int __stdcall MOB_fetchedAll (const int conId, const int stmtId); int __stdcall MOB_insertTick (const int conId, const int stmtId, unsigned int datetime, int fraction, double *vals, const int size); int __stdcall MOB_insertBar (const int conId, const int stmtId, unsigned int datetime, double *vals, const int size); int __stdcall MOB_copyRates (const int conId, const int stmtId, RateInfo *rates, const int size, const int start, const int end); double __stdcall MOB_selectDouble (const int conId, const TCHAR *sql, const double defaultVal); int __stdcall MOB_selectInt (const int conId, const TCHAR *sql, const int defaultVal); unsigned int __stdcall MOB_selectDatetime (const int conId, const TCHAR *sql, unsigned int defaultVal); static void logIfError(int conId, int rc) { if (rc < 0) { _tprintf(_T("ERROR(%d):%s\n"), MOB_getLastErrorNo(conId), MOB_getLastErrorMesg(conId)); } } int testTick() { int rc = 0; _tprintf(_T("=== MT4-ODBC Bridge Test Tick Begin\n")); int conId; conId = MOB_create(); rc = MOB_open(conId, _T("testpostgresql"), _T("testuser"), _T("password")); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_isDead(conId); if (!rc) _tprintf(_T("Connection is alive.\n")); rc = MOB_execute(conId, _T("drop table if exists ticks")); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_execute(conId, _T("create table ticks (time timestamp, fraction smallint, ask decimal(8, 5), bid decimal(8, 5), primary key (time, fraction))")); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_selectInt(conId, _T("select fraction from ticks"), 0); if (rc < 0) { logIfError(conId, rc); return rc; } int insertTick; insertTick = MOB_registerStatement(conId, _T("insert into ticks values (?, ?, ?, ?)")); rc = insertTick; if (rc < 0) { logIfError(conId, rc); return rc; } time_t t; int fraction; double ab[2]; int nab; time(&t); fraction = 123; ab[0] = 123.12345; ab[1] = 321.54321; nab = 2; rc = MOB_insertTick(conId, insertTick, (unsigned int) t, fraction, ab, nab); if (rc < 0) { logIfError(conId, rc); return rc; } t += 60; fraction = 444; ab[0] = 123.00001; ab[1] = 321.00009; nab = 2; rc = MOB_insertTick(conId, insertTick, (unsigned int) t, fraction, ab, nab); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_unregisterStatement(conId, insertTick); if (rc < 0) { logIfError(conId, rc); return rc; } int ti = MOB_selectInt(conId, _T("select count(*) from ticks"), -1); double td = MOB_selectDouble(conId, _T("select ask from ticks order by time, fraction"), -1.0); time_t tt = MOB_selectDatetime(conId, _T("select time from ticks order by time desc, fraction desc"), 0); if (tt == t) _tprintf(_T("Got the same time %d\n"), tt); rc = MOB_close(conId); if (rc < 0) { logIfError(conId, rc); return rc; } _tprintf(_T("=== MT4-ODBC Bridge Test Tick End\n")); return rc; } int testBar() { int rc = 0; _tprintf(_T("=== MT4-ODBC Bridge Test Bar Begin\n")); int conId; conId = MOB_create(); rc = MOB_open(conId, _T("testpostgresql"), NULL, NULL); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_isDead(conId); if (!rc) _tprintf(_T("Connection is alive.\n")); rc = MOB_execute(conId, _T("drop table if exists bars")); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_execute(conId, _T("create table bars (time timestamp, open decimal(8, 5), low decimal(8, 5), high decimal(8, 5), close decimal(8, 5), vol double precision, primary key (time))")); if (rc < 0) { logIfError(conId, rc); return rc; } double dblNull = MOB_selectDouble(conId, _T("select max(open) from bars"), -1); _tprintf(_T("DblNull is %f\n"), dblNull); int insertBar; insertBar = MOB_registerStatement(conId, _T("insert into bars values (?, ?, ?, ?, ?, ?)")); rc = insertBar; if (rc < 0) { logIfError(conId, rc); return rc; } /* double rates[][6] = { {0, 0.1, 0.1, 0.1, 0.1, 1}, {60, 0.2, 0.2, 0.2, 0.2, 2}, {120, 0.3, 0.3, 0.3, 0.3, 3} }; */ RateInfo r1; RateInfo r2; RateInfo r3; r1.ctm = 0; r1.open = 0.1; r1.low = 0.1; r1.high = 0.1; r1.close = 0.1; r1.vol = 1; r2.ctm = 60; r2.open = 0.2; r2.low = 0.2; r2.high = 0.2; r2.close = 0.2; r2.vol = 2; r3.ctm = 120; r3.open = 0.3; r3.low = 0.3; r3.high = 0.3; r3.close = 0.3; r3.vol = 3; RateInfo rates[] = {r1, r2, r3}; rc = MOB_copyRates(conId, insertBar, rates, 3, 0, 3); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_close(conId); if (rc < 0) { logIfError(conId, rc); return rc; } _tprintf(_T("=== MT4-ODBC Bridge Test Bar End\n")); return rc; } int testGeneric() { int rc = 0; _tprintf(_T("=== MT4-ODBC Bridge Test Generic Begin\n")); int conId; conId = MOB_create(); rc = MOB_open(conId, _T("testpostgresql"), NULL, NULL); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_isDead(conId); if (!rc) _tprintf(_T("Connection is alive.\n")); rc = MOB_execute(conId, _T("drop table if exists generic")); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_execute(conId, _T("create table generic (time1 timestamp, int1 integer, dbl1 double precision, str1 varchar(10))")); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_registerStatement(conId, _T("insert into generic (time1, int1, dbl1, str1) values (?, ?, ?, ?)")); if (rc < 0) { logIfError(conId, rc); return rc; } int insertStmt = rc; time_t t1; time(&t1); int i1 = 123; double d1 = 1.23; TCHAR *s1 = (TCHAR *) malloc(sizeof(TCHAR) * 10); _tcsncpy_s(s1, 10, _T("fugafuga"), _TRUNCATE); rc = MOB_bindDatetimeParameter(conId, insertStmt, 1, (unsigned int *) &t1); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_bindIntParameter(conId, insertStmt, 2, &i1); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_bindDoubleParameter(conId, insertStmt, 3, &d1); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_bindStringParameter(conId, insertStmt, 4, s1); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_executeStatement(conId, insertStmt); if (rc < 0) { logIfError(conId, rc); return rc; } i1 = 222; d1 = 4.56; _tcsncpy_s(s1, 10, _T("oeoeoeoehh"), _TRUNCATE); t1 += 60; rc = MOB_executeStatement(conId, insertStmt); if (rc < 0) { logIfError(conId, rc); return rc; } int i2 = -1; double d2 = -1.2; TCHAR *s2 = (TCHAR *) malloc(sizeof(TCHAR) * 10); time_t t2; _tcsncpy_s(s2, 10, _T("1234567890"), _TRUNCATE); rc = MOB_registerStatement(conId, _T("select time1, int1, dbl1, str1 from generic")); if (rc < 0) { logIfError(conId, rc); return rc; } int selectStmt = rc; rc = MOB_bindDatetimeColumn(conId, selectStmt, 1, (unsigned int *) &t2); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_bindIntColumn(conId, selectStmt, 2, &i2); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_bindDoubleColumn(conId, selectStmt, 3, &d2); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_bindStringColumn(conId, selectStmt, 4, s2); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_selectToFetch(conId, selectStmt); if (rc < 0) { logIfError(conId, rc); return rc; } while (MOB_fetch(conId, selectStmt)) { //_tprintf(_T("%i %i %f %s\n"), t2, i2, d2, s2); _tprintf(_T("%i\n"), t2); _tprintf(_T("%i\n"), i2); _tprintf(_T("%f\n"), d2); _tprintf(_T("%s\n"), s2); } MOB_fetchedAll(conId, selectStmt); if (rc < 0) { logIfError(conId, rc); return rc; } rc = MOB_close(conId); if (rc < 0) { logIfError(conId, rc); return rc; } _tprintf(_T("=== MT4-ODBC Bridge Test Generic End\n")); return rc; } int mobtest(int argc, TCHAR *argv[]) { int rc = 0; rc += testTick(); rc += testBar(); rc += testGeneric(); return rc; }
[ "onagano" ]
[ [ [ 1, 306 ] ] ]
3680ec7ebe3666489cda67e412a9076864562538
314fa4d6839de9abfdedb72a521a156c06522761
/MechineVision/DIB.cpp
207f9e5271349458cb54f007370ac979ff82d056
[]
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
WINDOWS-1252
C++
false
false
8,731
cpp
// DIB.cpp #include "stdafx.h" #include "DIB.h" //#include "Segment1.h" #include <math.h> #include <fstream> CDib::CDib() { // Set the Dib pointer to // NULL so we know if it's // been loaded. m_pDib = NULL; } CDib::~CDib() { // If a Dib has been loaded, // delete the memory. if( m_pDib != NULL ) delete [] m_pDib; } BOOL CDib::Load( const char *pszFilename ) { CFile cf; // Attempt to open the Dib file for reading. if( !cf.Open( pszFilename, CFile::modeRead ) ) return( FALSE ); // Get the size of the file and store // in a local variable. Subtract the // size of the BITMAPFILEHEADER structure // since we won't keep that in memory. DWORD dwDibSize; dwDibSize = cf.GetLength() - sizeof( BITMAPFILEHEADER ); /*ofstream fout("test10.txt"); fout<<cf.GetLength()<<endl; fout<<dwDibSize<<endl;*/ // Attempt to allocate the Dib memory. unsigned char *pDib; pDib = new unsigned char [dwDibSize]; if( pDib == NULL ) return( FALSE ); BITMAPFILEHEADER BFH; // Read in the Dib header and data. try{ // Did we read in the entire BITMAPFILEHEADER? if( cf.Read( &BFH, sizeof( BITMAPFILEHEADER ) ) != sizeof( BITMAPFILEHEADER ) || // Is the type 'MB'? BFH.bfType != 'MB' || // Did we read in the remaining data? cf.Read( pDib, dwDibSize ) != dwDibSize ){ // Delete the memory if we had any // errors and return FALSE. delete [] pDib; return( FALSE ); } } // If we catch an exception, delete the // exception, the temporary Dib memory, // and return FALSE. catch( CFileException *e ){ e->Delete(); delete [] pDib; return( FALSE ); } // If we got to this point, the Dib has been // loaded. If a Dib was already loaded into // this class, we must now delete it. if( m_pDib != NULL ) delete m_pDib; // Store the local Dib data pointer and // Dib size variables in the class member // variables. m_pDib = pDib; m_dwDibSize = dwDibSize; // Pointer our BITMAPINFOHEADER and RGBQUAD // variables to the correct place in the Dib data. m_pBIH = (BITMAPINFOHEADER *) m_pDib; m_pPalette = (RGBQUAD *) &m_pDib[sizeof(BITMAPINFOHEADER)]; // Calculate the number of palette entries. m_nPaletteEntries = 1 << m_pBIH->biBitCount; if( m_pBIH->biBitCount > 8 ) m_nPaletteEntries = 0; else if( m_pBIH->biClrUsed != 0 ) m_nPaletteEntries = m_pBIH->biClrUsed; // Point m_pDibBits to the actual Dib bits data. m_pDibBits = &m_pDib[sizeof(BITMAPINFOHEADER)+ m_nPaletteEntries*sizeof(RGBQUAD)]; // If we have a valid palette, delete it. if( m_Palette.GetSafeHandle() != NULL ) m_Palette.DeleteObject(); // If there are palette entries, we'll need // to create a LOGPALETTE then create the // CPalette palette. if( m_nPaletteEntries != 0 ){ // Allocate the LOGPALETTE structure. LOGPALETTE *pLogPal = (LOGPALETTE *) new char [sizeof(LOGPALETTE)+ m_nPaletteEntries*sizeof(PALETTEENTRY)]; if( pLogPal != NULL ){ // Set the LOGPALETTE to version 0x300 // and store the number of palette // entries. pLogPal->palVersion = 0x300; pLogPal->palNumEntries = m_nPaletteEntries; // Store the RGB values into each // PALETTEENTRY element. for( int i=0; i<m_nPaletteEntries; i++ ){ pLogPal->palPalEntry[i].peRed = m_pPalette[i].rgbRed; pLogPal->palPalEntry[i].peGreen = m_pPalette[i].rgbGreen; pLogPal->palPalEntry[i].peBlue = m_pPalette[i].rgbBlue; } // Create the CPalette object and // delete the LOGPALETTE memory. m_Palette.CreatePalette( pLogPal ); delete [] pLogPal; } } /* ofstream fout("±m¦â.txt"); int o=0; while(o != 10000) { fout<<(int)m_pDib[o]<<endl; o++; } fout.close(); */ return( TRUE ); } BOOL CDib::Save( const char *pszFilename ) { // If we have no data, we can't save. if( m_pDib == NULL ) return( FALSE ); CFile cf; // Attempt to create the file. if( !cf.Open( pszFilename, CFile::modeCreate | CFile::modeWrite ) ) return( FALSE ); // Write the data. try{ // First, create a BITMAPFILEHEADER // with the correct data. BITMAPFILEHEADER BFH; memset( &BFH, 0, sizeof( BITMAPFILEHEADER ) ); BFH.bfType = 'MB'; BFH.bfSize = sizeof( BITMAPFILEHEADER ) + m_dwDibSize; BFH.bfOffBits = sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER ) + m_nPaletteEntries * sizeof( RGBQUAD ); // Write the BITMAPFILEHEADER and the // Dib data. cf.Write( &BFH, sizeof( BITMAPFILEHEADER ) ); cf.Write( m_pDib, m_dwDibSize ); } // If we get an exception, delete the exception and // return FALSE. catch( CFileException *e ){ e->Delete(); return( FALSE ); } return( TRUE ); } BOOL CDib::Save2(unsigned char * array, const char *pszFilename ) { /* for(int i=0;i<m_pBIH->biHeight ;i++) for(int j=0;j<m_pBIH->biWidth ;j++) array[i*2160+j]=m_pDib[i*2160+j+1064];*/ for(int i=0;i<m_pBIH->biHeight ;i++) for(int j=0;j<m_pBIH->biWidth ;j++) m_pDib[i*m_pBIH->biWidth+j+1064]=array[i*m_pBIH->biWidth+j]; // If we have no data, we can't save. if( m_pDib == NULL ) return( FALSE ); CFile cf; // Attempt to create the file. if( !cf.Open( pszFilename, CFile::modeCreate | CFile::modeWrite ) ) return( FALSE ); // Write the data. try{ // First, create a BITMAPFILEHEADER // with the correct data. BITMAPFILEHEADER BFH; memset( &BFH, 0, sizeof( BITMAPFILEHEADER ) ); BFH.bfType = 'MB'; BFH.bfSize = sizeof( BITMAPFILEHEADER ) + m_dwDibSize; BFH.bfOffBits = sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER ) + m_nPaletteEntries * sizeof( RGBQUAD ); // Write the BITMAPFILEHEADER and the // Dib data. cf.Write( &BFH, sizeof( BITMAPFILEHEADER ) ); cf.Write( m_pDib, m_dwDibSize ); } // If we get an exception, delete the exception and // return FALSE. catch( CFileException *e ){ e->Delete(); return( FALSE ); } return( TRUE ); } BOOL CDib::Draw( CDC *pDC, int nX, int nY, int nWidth, int nHeight ) { // If we have not data we can't draw. if( m_pDib == NULL ) return( FALSE ); // Check for the default values of -1 // in the width and height arguments. If // we find -1 in either, we'll set them // to the value that's in the BITMAPINFOHEADER. if( nWidth == -1 ) nWidth = m_pBIH->biWidth; if( nHeight == -1 ) nHeight = m_pBIH->biHeight; // Use StretchDIBits to draw the Dib. StretchDIBits( pDC->m_hDC, nX, nY, nWidth, nHeight, 0, 0, m_pBIH->biWidth, m_pBIH->biHeight, m_pDibBits, (BITMAPINFO *) m_pBIH, BI_RGB, SRCCOPY ); return( TRUE ); } BOOL CDib::Draw2( CDC *pDC, int nX, int nY, int nWidth, int nHeight ,unsigned char *array, int Width, int Height) { if( m_pDib == NULL ) return( FALSE ); for(int i=0;i<Height ;i++) for(int j=0;j<Width ;j++) { m_pDib[i * Width+j+1064]=array[i * Width+j]; } // If we have not data we can't draw. if( m_pDib == NULL ) return( FALSE ); // Check for the default values of -1 // in the width and height arguments. If // we find -1 in either, we'll set them // to the value that's in the BITMAPINFOHEADER. if( nWidth == -1 ) nWidth =Width;//nWidth = m_pBIH->biWidth; if( nHeight == -1 ) nHeight =Height;//nHeight = m_pBIH->biHeight; // Use StretchDIBits to draw the Dib. StretchDIBits( pDC->m_hDC, nX, nY, nWidth, nHeight, 0, 0, Width, Height, m_pDibBits, (BITMAPINFO *) m_pBIH, BI_RGB, SRCCOPY ); return( TRUE ); } BOOL CDib::SetPalette( CDC *pDC ) { // If we have not data we // won't want to set the palette. if( m_pDib == NULL ) return( FALSE ); // Check to see if we have a palette // handle. For Dibs greater than 8 bits, // this will be NULL. if( m_Palette.GetSafeHandle() == NULL ) return( TRUE ); // Select the palette, realize the palette, // then finally restore the old palette. CPalette *pOldPalette; pOldPalette = pDC->SelectPalette( &m_Palette, FALSE ); pDC->RealizePalette(); pDC->SelectPalette( pOldPalette, FALSE ); return( TRUE ); } int ** CDib::Get_Image_Array(int height,int width) { int **array; array=new int*[height]; for(int i=0;i<height;i++) array[i]=new int[width]; for(int i=0;i<height;i++) for(int j=0;j<width;j++) { array[i][j]=(int)m_pDib[i*width+j+1064]; } return array; } void CDib::CCopyImage(unsigned char *array4) { unsigned char *temp1; temp1=(m_pDib+1064); memcpy(array4,temp1,(m_pBIH->biWidth * m_pBIH->biHeight)); }
[ "[email protected]@8026b7c3-d9ae-87c5-0fde-12bd377d1155" ]
[ [ [ 1, 365 ] ] ]
fdf528cdc64c9437ecb44f31f4d822da1ceef7a7
8a88075abf60e213a490840bebee97df01b8827a
/implementation/geometry/include/geometry/homogenous/angles.hpp
6523af1b13af41a1214cb7571ad7c9b7e721ae4b
[]
no_license
DavidGeorge528/minigeolib
e078f1bbc874c09584ae48e1c269f5f90789ebfb
58233609203953acf1c0346cd48950d2212b8922
refs/heads/master
2020-05-20T09:36:53.921996
2009-04-23T16:25:30
2009-04-23T16:25:30
33,925,133
0
1
null
null
null
null
UTF-8
C++
false
false
1,719
hpp
#ifndef GEOMETRY_HOMOGENOUS_ANGLES_HPP #define GEOMETRY_HOMOGENOUS_ANGLES_HPP #include "geometry/homogenous/hcoord_system_concept.hpp" #include "geometry/line_concept.hpp" #include "geometry/plane_concept.hpp" #include <boost/concept/requires.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <cmath> namespace geometry { namespace impl { /// \ingroup geometry /// \brief It calculates the cosinus of the angle between two given directions. /// \tparam CS the coordinate system, providing the direction representation. It must be an implementation of homogenous /// coordinates. template< typename CS> BOOST_CONCEPT_REQUIRES( ((HCoordSystem<CS>)), (typename CS::unit_type)) cos_angle( const typename CS::dir_rep& d1, const typename CS::dir_rep& d2) { return d1*d2 / (algebra::norm( d1) * algebra::norm(d2)); } } // namespace impl /// \ingroup geometry /// \brief It calculates the dihedral angle between two planes. /// \tparam P the plane type, implementing the Plane concept. template< typename P> typename boost::enable_if< impl::is_plane<P,3>, typename P::unit_type>::type angle( const P& p1, const P& p2) { BOOST_CONCEPT_ASSERT( (Plane<P>)); typedef P plane_type; typedef typename plane_type::coord_system coord_system; typedef typename plane_type::unit_type unit_type; // Get nromal direction components for the planes typename coord_system::dir_rep n1( p1.a(), p1.b(), p1.c()), n2( p2.a(), p2.b(), p2.c()); // cos(dihedral): n1.n2/|n1||n2| unit_type cangle = impl::cos_angle<coord_system>( n1, n2); return std::acos( cangle); } } // namespace geometry #endif // GEOMETRY_HOMOGENOUS_ANGLES_HPP
[ "cpitis@834bb202-e8be-11dd-9d8c-a70aa0a93a20" ]
[ [ [ 1, 54 ] ] ]
a6c3c40f39ac56dbdcfb90370de0b2c134e236c7
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/01032005/sound/fmod/FMODModuleBuffer.h
109a4e4c666a7f4899b99f90d92a593f991214b2
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
820
h
#ifndef _FMODMODULEBUFFER_H_ #define _FMODMODULEBUFFER_H_ #include <fmod/fmod.h> #include <Sound/ISoundBuffer.h> /** @ingroup FMOD_Sound_Group * @brief Derived ISoundBuffer class for playing Tracker Modules */ class FMODModuleBuffer: public ISoundBuffer{ protected: /** @var FMUSIC_MODULE *m_module * @brief FMOD handle to the tracker module */ FMUSIC_MODULE *m_module; public: FMODModuleBuffer (); virtual ~FMODModuleBuffer (); virtual bool Load (std::string filename); virtual bool Close (void); virtual int Play (void); virtual bool Pause (bool pause); virtual bool Stop (void); virtual bool SetPosition (int position); virtual bool Volume (unsigned char volume); virtual bool IsPlaying (void); }; #endif // #ifndef _FMODMODULEBUFFER_H_
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 29 ] ] ]
9aede403d2d98615cce4e071b05fe09703c8e95e
b6bad03a59ec436b60c30fc793bdcf687a21cf31
/som2416/wince5/Rt5621.h
877bae3108dbd6c84a5b9492f6b9d963d7ffd016
[]
no_license
blackfa1con/openembed
9697f99b12df16b1c5135e962890e8a3935be877
3029d7d8c181449723bb16d0a73ee87f63860864
refs/heads/master
2021-01-10T14:14:39.694809
2010-12-16T03:20:27
2010-12-16T03:20:27
52,422,065
0
0
null
null
null
null
UTF-8
C++
false
false
19,790
h
#ifndef __RTCODEC5621_H__ #define __RTCODEC5621_H__ #include "wavemain.h" //Index of Codec Register definition #define RT5621_RESET 0X00 //RESET CODEC TO DEFAULT #define RT5621_SPK_OUT_VOL 0X02 //SPEAKER OUT VOLUME #define RT5621_HP_OUT_VOL 0X04 //HEADPHONE OUTPUT VOLUME #define RT5621_MONO_AUX_OUT_VOL 0X06 //MONO OUTPUT/AUXOUT VOLUME #define RT5621_AUXIN_VOL 0X08 //AUXIN VOLUME #define RT5621_LINE_IN_VOL 0X0A //LINE IN VOLUME #define RT5621_STEREO_DAC_VOL 0X0C //STEREO DAC VOLUME #define RT5621_MIC_VOL 0X0E //MICROPHONE VOLUME #define RT5621_MIC_ROUTING_CTRL 0X10 //MIC ROUTING CONTROL #define RT5621_ADC_REC_GAIN 0X12 //ADC RECORD GAIN #define RT5621_ADC_REC_MIXER 0X14 //ADC RECORD MIXER CONTROL #define RT5621_SOFT_VOL_CTRL_TIME 0X16 //SOFT VOLUME CONTROL TIME #define RT5621_OUTPUT_MIXER_CTRL 0X1C //OUTPUT MIXER CONTROL #define RT5621_MICROPHONE_CTRL 0X22 //MICROPHONE CONTROL #define RT5621_AUDIO_INTERFACE 0X34 //AUDIO INTERFACE #define RT5621_STEREO_AD_DA_CLK_CTRL 0X36 //STEREO AD/DA CLOCK CONTROL #define RT5621_COMPANDING_CTRL 0X38 //COMPANDING CONTROL #define RT5621_PWR_MANAG_ADD1 0X3A //POWER MANAGMENT ADDITION 1 #define RT5621_PWR_MANAG_ADD2 0X3C //POWER MANAGMENT ADDITION 2 #define RT5621_PWR_MANAG_ADD3 0X3E //POWER MANAGMENT ADDITION 3 #define RT5621_ADD_CTRL_REG 0X40 //ADDITIONAL CONTROL REGISTER #define RT5621_GLOBAL_CLK_CTRL_REG 0X42 //GLOBAL CLOCK CONTROL REGISTER #define RT5621_PLL_CTRL 0X44 //PLL CONTROL #define RT5621_GPIO_OUTPUT_PIN_CTRL 0X4A //GPIO OUTPUT PIN CONTROL #define RT5621_GPIO_PIN_CONFIG 0X4C //GPIO PIN CONFIGURATION #define RT5621_GPIO_PIN_POLARITY 0X4E //GPIO PIN POLARITY/TYPE #define RT5621_GPIO_PIN_STICKY 0X50 //GPIO PIN STICKY #define RT5621_GPIO_PIN_WAKEUP 0X52 //GPIO PIN WAKE UP #define RT5621_GPIO_PIN_STATUS 0X54 //GPIO PIN STATUS #define RT5621_GPIO_PIN_SHARING 0X56 //GPIO PIN SHARING #define RT5621_OVER_TEMP_CURR_STATUS 0X58 //OVER TEMPERATURE AND CURRENT STATUS #define RT5621_JACK_DET_CTRL 0X5A //JACK DETECT CONTROL REGISTER #define RT5621_MISC_CTRL 0X5E //MISC CONTROL #define RT5621_PSEDUEO_SPATIAL_CTRL 0X60 //PSEDUEO STEREO & SPATIAL EFFECT BLOCK CONTROL #define RT5621_EQ_CTRL 0X62 //EQ CONTROL #define RT5621_EQ_STATUS 0X64 //EQ STATUS #define RT5621_EQ_MODE_ENABLE 0X66 //EQ MODE CHANGE ENABLE #define RT5621_AVC_CTRL 0X68 //AVC CONTROL #define RT5621_HID_CTRL_INDEX 0X6A //HIDDEN CONTROL INDEX PORT #define RT5621_HID_CTRL_DATA 0X6C //HIDDEN CONTROL DATA PORT #define RT5621_VENDOR_ID1 0x7C //VENDOR ID1 #define RT5621_VENDOR_ID2 0x7E //VENDOR ID2 //global definition #define RT_L_MUTE (0x1<<15) //MUTE LEFT CONTROL BIT #define RT_L_ZC (0x1<<14) //LEFT ZERO CROSS CONTROL BIT #define RT_L_SM (0x1<<13) //LEFT SOFTMUTE CONTROL BIT #define RT_R_MUTE (0x1<<7) //MUTE RIGHT CONTROL BIT #define RT_R_ZC (0x1<<6) //RIGHT ZERO CROSS CONTROL BIT #define RT_R_SM (0x1<<5) //RIGHT SOFTMUTE CONTROL BIT #define RT_M_HP_MIXER (0x1<<15) //Mute source to HP Mixer #define RT_M_SPK_MIXER (0x1<<14) //Mute source to Speaker Mixer #define RT_M_MONO_MIXER (0x1<<13) //Mute source to Mono Mixer #define SPK_CLASS_AB 0 #define SPK_CLASS_D 1 //Mic Routing Control(0x10) #define MIC1_DIFF_INPUT_CTRL (0x1<<12) //MIC1 different input control #define M_MIC2_TO_HP_MIXER (0x1<<7) //Mute MIC2 to HP mixer #define M_MIC2_TO_SPK_MIXER (0x1<<6) //Mute MiC2 to SPK mixer #define M_MIC2_TO_MONO_MIXER (0x1<<5) //Mute MIC2 to MONO mixer #define MIC2_DIFF_INPUT_CTRL (0x1<<4) //MIC2 different input control #define ALL_FIELD 0xffff #define MHZ11_980 11980000 #define KHZ08_000 8000 #define KHZ11_025 11025 #define KHZ12_000 12000 #define KHZ16_000 16000 #define KHZ22_050 22050 #define KHZ24_000 24000 #define KHZ32_000 32000 #define KHZ44_100 44100 #define KHZ48_000 48000 //ADC Input Mixer Control(0x14) #define M_MIC1_TO_ADC_L_MIXER (0x1<<14) //Mute mic1 to left channel of ADC mixer #define M_MIC2_TO_ADC_L_MIXER (0x1<<13) //Mute mic2 to left channel of ADC mixer #define M_LINEIN_L_TO_ADC_L_MIXER (0x1<<12) //Mute line In left channel to left channel of ADC mixer #define M_AUXIN_L_TO_ADC_L_MIXER (0x1<<11) //Mute aux In left channel to left channel of ADC mixer #define M_HPMIXER_L_TO_ADC_L_MIXER (0x1<<10) //Mute HP mixer left channel to left channel of ADC mixer #define M_SPKMIXER_L_TO_ADC_L_MIXER (0x1<<9) //Mute SPK mixer left channel to left channel of ADC mixer #define M_MONOMIXER_L_TO_ADC_L_MIXER (0x1<<8) //Mute MONO mixer left channel to left channel of ADC mixer #define M_MIC1_TO_ADC_R_MIXER (0x1<<6) //Mute mic1 to right channel of ADC mixer #define M_MIC2_TO_ADC_R_MIXER (0x1<<5) //Mute mic2 to right channel of ADC mixer #define M_LINEIN_R_TO_ADC_R_MIXER (0x1<<4) //Mute lineIn right channel to right channel of ADC mixer #define M_AUXIN_R_TO_ADC_R_MIXER (0x1<<3) //Mute aux In right channel to right channel of ADC mixer #define M_HPMIXER_R_TO_ADC_R_MIXER (0x1<<2) //Mute HP mixer right channel to right channel of ADC mixer #define M_SPKMIXER_R_TO_ADC_R_MIXER (0x1<<1) //Mute SPK mixer right channel to right channel of ADC mixer #define M_MONOMIXER_R_TO_ADC_R_MIXER (0x1<<0) //Mute MONO mixer right channel to right channel of ADC mixer //Output Mixer Control(0x1C) #define SPKOUT_N_SOUR_MASK (0x3<<14) #define SPKOUT_N_SOUR_LN (0x2<<14) #define SPKOUT_N_SOUR_RP (0x1<<14) #define SPKOUT_N_SOUR_RN (0x0<<14) #define SPK_OUTPUT_CLASS_AB (0x0<<13) #define SPK_OUTPUT_CLASS_D (0x1<<13) #define SPK_CLASS_AB_S_AMP (0x0<<12) #define SPK_CALSS_AB_W_AMP (0x1<<12) #define SPKOUT_INPUT_SEL_MASK (0x3<<10) #define SPKOUT_INPUT_SEL_MONOMIXER (0x3<<10) #define SPKOUT_INPUT_SEL_SPKMIXER (0x2<<10) #define SPKOUT_INPUT_SEL_HPMIXER (0x1<<10) #define SPKOUT_INPUT_SEL_VMID (0x0<<10) #define HPL_INPUT_SEL_HPLMIXER (0x1<<9) #define HPR_INPUT_SEL_HPRMIXER (0x1<<8) #define MONO_AUX_INPUT_SEL_MASK (0x3<<6) #define MONO_AUX_INPUT_SEL_MONO (0x3<<6) #define MONO_AUX_INPUT_SEL_SPK (0x2<<6) #define MONO_AUX_INPUT_SEL_HP (0x1<<6) #define MONO_AUX_INPUT_SEL_VMID (0x0<<6) //Micphone Control define(0x22) #define MIC1 1 #define MIC2 2 #define MIC_BIAS_90_PRECNET_AVDD 1 #define MIC_BIAS_75_PRECNET_AVDD 2 #define MIC1_BOOST_CTRL_MASK (0x3<<10) #define MIC1_BOOST_CTRL_BYPASS (0x0<<10) #define MIC1_BOOST_CTRL_20DB (0x1<<10) #define MIC1_BOOST_CTRL_30DB (0x2<<10) #define MIC1_BOOST_CTRL_40DB (0x3<<10) #define MIC2_BOOST_CTRL_MASK (0x3<<8) #define MIC2_BOOST_CTRL_BYPASS (0x0<<8) #define MIC2_BOOST_CTRL_20DB (0x1<<8) #define MIC2_BOOST_CTRL_30DB (0x2<<8) #define MIC2_BOOST_CTRL_40DB (0x3<<8) #define MICBIAS_VOLT_CTRL_MASK (0x1<<5) #define MICBIAS_VOLT_CTRL_90P (0x0<<5) #define MICBIAS_VOLT_CTRL_75P (0x1<<5) #define MICBIAS_SHORT_CURR_DET_MASK (0x3) #define MICBIAS_SHORT_CURR_DET_600UA (0x0) #define MICBIAS_SHORT_CURR_DET_1200UA (0x1) #define MICBIAS_SHORT_CURR_DET_1800UA (0x2) //Audio Interface(0x34) #define SDP_MASTER_MODE (0x0<<15) #define SDP_SLAVE_MODE (0x1<<15) #define I2S_PCM_MODE (0x1<<14) //PCM 0:mode A ,1:mode B //Non PCM 0:Normal SADLRCK/SDALRCK,1:Invert SADLRCK/SDALRCK #define MAIN_I2S_BCLK_POL_CTRL (0x1<<7) //0:Normal 1:Invert #define ADC_DATA_L_R_SWAP (0x1<<5) //0:ADC data appear at left phase of LRCK //1:ADC data appear at right phase of LRCK #define DAC_DATA_L_R_SWAP (0x1<<4) //0:DAC data appear at left phase of LRCK //1:DAC data appear at right phase of LRCK //Data Length Slection #define I2S_DL_MASK (0x3<<2) //main i2s Data Length mask #define I2S_DL_16 (0x0<<2) //16 bits #define I2S_DL_20 (0x1<<2) //20 bits #define I2S_DL_24 (0x2<<2) //24 bits #define I2S_DL_32 (0x3<<2) //32 bits //PCM Data Format Selection #define I2S_DF_MASK (0x3) //main i2s Data Format mask #define I2S_DF_I2S (0x0) //I2S FORMAT #define I2S_DF_RIGHT (0x1) //RIGHT JUSTIFIED format #define I2S_DF_LEFT (0x2) //LEFT JUSTIFIED format #define I2S_DF_PCM (0x3) //PCM format //Stereo AD/DA Clock Control(0x36h) #define I2S_PRE_DIV_MASK (0x7<<12) #define I2S_PRE_DIV_1 (0x0<<12) //DIV 1 #define I2S_PRE_DIV_2 (0x1<<12) //DIV 2 #define I2S_PRE_DIV_4 (0x2<<12) //DIV 4 #define I2S_PRE_DIV_8 (0x3<<12) //DIV 8 #define I2S_PRE_DIV_16 (0x4<<12) //DIV 16 #define I2S_PRE_DIV_32 (0x5<<12) //DIV 32 #define I2S_SCLK_DIV_MASK (0x7<<9) #define I2S_SCLK_DIV_1 (0x0<<9) //DIV 1 #define I2S_SCLK_DIV_2 (0x1<<9) //DIV 2 #define I2S_SCLK_DIV_3 (0x2<<9) //DIV 3 #define I2S_SCLK_DIV_4 (0x3<<9) //DIV 4 #define I2S_SCLK_DIV_6 (0x4<<9) //DIV 6 #define I2S_SCLK_DIV_8 (0x5<<9) //DIV 8 #define I2S_SCLK_DIV_12 (0x6<<9) //DIV 12 #define I2S_SCLK_DIV_16 (0x7<<9) //DIV 16 #define I2S_WCLK_DIV_PRE_MASK (0xF<<5) #define I2S_WCLK_PRE_DIV_1 (0x0<<5) //DIV 1 #define I2S_WCLK_PRE_DIV_2 (0x1<<5) //DIV 2 #define I2S_WCLK_PRE_DIV_3 (0x2<<5) //DIV 3 #define I2S_WCLK_PRE_DIV_4 (0x3<<5) //DIV 4 #define I2S_WCLK_PRE_DIV_5 (0x4<<5) //DIV 5 #define I2S_WCLK_PRE_DIV_6 (0x5<<5) //DIV 6 #define I2S_WCLK_PRE_DIV_7 (0x6<<5) //DIV 7 #define I2S_WCLK_PRE_DIV_8 (0x7<<5) //DIV 8 //........................ #define I2S_WCLK_DIV_MASK (0x7<<2) #define I2S_WCLK_DIV_2 (0x0<<2) //DIV 2 #define I2S_WCLK_DIV_4 (0x1<<2) //DIV 4 #define I2S_WCLK_DIV_8 (0x2<<2) //DIV 8 #define I2S_WCLK_DIV_16 (0x3<<2) //DIV 16 #define I2S_WCLK_DIV_32 (0x4<<2) //DIV 32 #define ADDA_FILTER_CLK_SEL_256FS (0<<1) //256FS #define ADDA_FILTER_CLK_SEL_384FS (1<<1) //384FS #define ADDA_OSR_SEL_64FS (0) //64FS #define ADDA_OSR_SEL_128FS (1) //128FS //Power managment addition 1 (0x3A),0:Disable,1:Enable #define PWR_MAIN_I2S_EN (0x1<<15) #define PWR_ZC_DET_PD_EN (0x1<<14) #define PWR_MIC1_BIAS_EN (0x1<<11) #define PWR_SHORT_CURR_DET_EN (0x1<<10) #define PWR_SOFTGEN_EN (0x1<<8) #define PWR_DEPOP_BUF_HP (0x1<<6) #define PWR_HP_OUT (0x1<<5) #define PWR_HP_AMP (0x1<<4) #define PWR_DEPOP_BUF_AUX (0x1<<2) #define PWR_AUX_OUT (0x1<<1) #define PWR_AUX_AMP (0x1) //Power managment addition 2(0x3C),0:Disable,1:Enable #define PWR_CLASS_AB (0x1<<15) #define PWR_CLASS_D (0x1<<14) #define PWR_VREF (0x1<<13) #define PWR_PLL (0x1<<12) #define PWR_THERMAL_SD (0x1<<11) #define PWR_DAC_REF_CIR (0x1<<10) #define PWR_L_DAC_CLK (0x1<<9) #define PWR_R_DAC_CLK (0x1<<8) #define PWR_L_ADC_CLK_GAIN (0x1<<7) #define PWR_R_ADC_CLK_GAIN (0x1<<6) #define PWR_L_HP_MIXER (0x1<<5) #define PWR_R_HP_MIXER (0x1<<4) #define PWR_SPK_MIXER (0x1<<3) #define PWR_MONO_MIXER (0x1<<2) #define PWR_L_ADC_REC_MIXER (0x1<<1) #define PWR_R_ADC_REC_MIXER (0x1) //Power managment addition 3(0x3E),0:Disable,1:Enable #define PWR_MAIN_BIAS (0x1<<15) #define PWR_AUXOUT_R_VOL_AMP (0x1<<14) #define PWR_AUXOUT_L_VOL_AMP (0x1<<13) #define PWR_SPK_R_OUT (0x1<<12) #define PWR_SPK_RN_OUT (0x1<<11) #define PWR_HP_L_OUT_VOL (0x1<<10) #define PWR_HP_R_OUT_VOL (0x1<<9) #define PWR_LINEIN_L_VOL (0x1<<7) #define PWR_LINEIN_R_VOL (0x1<<6) #define PWR_AUXIN_L_VOL (0x1<<5) #define PWR_AUXIN_R_VOL (0x1<<4) #define PWR_MIC1_FUN_CTRL (0x1<<3) #define PWR_MIC2_FUN_CTRL (0x1<<2) #define PWR_MIC1_BOOST_MIXER (0x1<<1) #define PWR_MIC2_BOOST_MIXER (0x1) //Additional Control Register(0x40) #define AUXOUT_SEL_DIFF (0x1<<15) //Differential Mode #define AUXOUT_SEL_SE (0x1<<15) //Single-End Mode #define SPK_AB_AMP_CTRL_MASK (0x7<<12) #define SPK_AB_AMP_CTRL_RATIO_225 (0x0<<12) //2.25 Vdd #define SPK_AB_AMP_CTRL_RATIO_200 (0x1<<12) //2.00 Vdd #define SPK_AB_AMP_CTRL_RATIO_175 (0x2<<12) //1.75 Vdd #define SPK_AB_AMP_CTRL_RATIO_150 (0x3<<12) //1.50 Vdd #define SPK_AB_AMP_CTRL_RATIO_125 (0x4<<12) //1.25 Vdd #define SPK_AB_AMP_CTRL_RATIO_100 (0x5<<12) //1.00 Vdd #define SPK_D_AMP_CTRL_MASK (0x3<<10) #define SPK_D_AMP_CTRL_RATIO_175 (0x0<<10) //1.75 Vdd #define SPK_D_AMP_CTRL_RATIO_150 (0x1<<10) //1.50 Vdd #define SPK_D_AMP_CTRL_RATIO_125 (0x2<<10) //1.25 Vdd #define SPK_D_AMP_CTRL_RATIO_100 (0x3<<10) //1.00 Vdd //Global Clock Control Register(0x42) #define SYSCLK_SOUR_SEL_MASK (0x1<<15) #define SYSCLK_SOUR_SEL_MCLK (0x0<<15) //system Clock source from MCLK #define SYSCLK_SOUR_SEL_PLL (0x1<<15) //system Clock source from PLL #define PLLCLK_SOUR_SEL_MCLK (0x0<<14) //PLL clock source from MCLK #define PLLCLK_SOUR_SEL_BITCLK (0x1<<14) //PLL clock source from BITCLK #define PLLCLK_DIV_RATIO_MASK (0x3<<1) #define PLLCLK_DIV_RATIO_DIV1 (0x0<<1) //DIV 1 #define PLLCLK_DIV_RATIO_DIV2 (0x1<<1) //DIV 2 #define PLLCLK_DIV_RATIO_DIV4 (0x2<<1) //DIV 4 #define PLLCLK_DIV_RATIO_DIV8 (0x3<<1) //DIV 8 #define PLLCLK_PRE_DIV1 (0x0) //DIV 1 #define PLLCLK_PRE_DIV2 (0x1) //DIV 2 //PLL Control(0x44) #define PLL_CTRL_M_VAL(m) ((m)&0xf) #define PLL_CTRL_K_VAL(k) (((k)&0x7)<<4) #define PLL_CTRL_N_VAL(n) (((n)&0xff)<<8) ////MISC CONTROL(0x5E) #define DISABLE_FAST_VREG (0x1<<15) #define THERMAL_SHUT_DOWN_EN (0x1<<14) #define SPK_CLASS_AB_OC_PD (0x1<<13) #define HP_DEPOP_MODE3_EN (0x1<<10) #define HP_DEPOP_MODE2_EN (0x1<<9) #define HP_DEPOP_MODE1_EN (0x1<<8) #define AUXOUT_DEPOP_MODE3_EN (0x1<<6) #define AUXOUT_DEPOP_MODE2_EN (0x1<<5) #define AUXOUT_DEPOP_MODE1_EN (0x1<<4) #define M_DAC_L_INPUT (0x1<<3) #define M_DAC_R_INPUT (0x1<<2) #define IRQOUT_INV_CTRL (0x1<<0) //Psedueo Stereo & Spatial Effect Block Control(0x60) #define SPATIAL_CTRL_EN (0x1<<15) #define ALL_PASS_FILTER_EN (0x1<<14) #define PSEUDO_STEREO_EN (0x1<<13) #define STEREO_EXPENSION_EN (0x1<<12) #define GAIN_3D_PARA_L_MASK (0x7<<9) #define GAIN_3D_PARA_L_1_00 (0x0<<9) #define GAIN_3D_PARA_L_1_25 (0x1<<9) #define GAIN_3D_PARA_L_1_50 (0x2<<9) #define GAIN_3D_PARA_L_1_75 (0x3<<9) #define GAIN_3D_PARA_L_2_00 (0x4<<9) #define GAIN_3D_PARA_R_MASK (0x7<<6) #define GAIN_3D_PARA_R_1_00 (0x0<<6) #define GAIN_3D_PARA_R_1_25 (0x1<<6) #define GAIN_3D_PARA_R_1_50 (0x2<<6) #define GAIN_3D_PARA_R_1_75 (0x3<<6) #define GAIN_3D_PARA_R_2_00 (0x4<<6) #define RATIO_3D_L_MASK (0x3<<4) #define RATIO_3D_L_0_0 (0x0<<4) #define RATIO_3D_L_0_66 (0x1<<4) #define RATIO_3D_L_1_0 (0x2<<4) #define RATIO_3D_R_MASK (0x3<<2) #define RATIO_3D_R_0_0 (0x0<<2) #define RATIO_3D_R_0_66 (0x1<<2) #define RATIO_3D_R_1_0 (0x2<<2) #define APF_MASK (0x3) #define APF_FOR_48K (0x3) #define APF_FOR_44_1K (0x2) #define APF_FOR_32K (0x1) //EQ CONTROL(0x62) #define EN_HW_EQ_BLK (0x1<<15) //HW EQ block control #define EN_HW_EQ_HPF_MODE (0x1<<14) //High Frequency shelving filter mode #define EN_HW_EQ_SOUR (0x1<<11) //0:DAC PATH,1:ADC PATH #define EN_HW_EQ_HPF (0x1<<4) //EQ High Pass Filter Control #define EN_HW_EQ_BP3 (0x1<<3) //EQ Band-3 Control #define EN_HW_EQ_BP2 (0x1<<2) //EQ Band-2 Control #define EN_HW_EQ_BP1 (0x1<<1) //EQ Band-1 Control #define EN_HW_EQ_LPF (0x1<<0) //EQ Low Pass Filter Control //EQ Mode Change Enable(0x66) #define EQ_HPF_CHANGE_EN (0x1<<4) //EQ High Pass Filter Mode Change Enable #define EQ_BP3_CHANGE_EN (0x1<<3) //EQ Band-3 Pass Filter Mode Change Enable #define EQ_BP2_CHANGE_EN (0x1<<2) //EQ Band-2 Pass Filter Mode Change Enable #define EQ_BP1_CHANGE_EN (0x1<<1) //EQ Band-1 Pass Filter Mode Change Enable #define EQ_LPF_CHANGE_EN (0x1<<0) //EQ Low Pass Filter Mode Change Enable //AVC Control(0x68) #define AVC_ENABLE (0x1<<15) #define AVC_TARTGET_SEL_MASK (0x1<<14) #define AVC_TARTGET_SEL_R (0x1<<14) #define AVC_TARTGET_SEL_L (0x0<<14) typedef enum { BOOST_BYPASS, BOOST_20DB, BOOST_30DB, BOOST_40DB }MIC_BOOST_TYPE; typedef struct { BYTE CodecIndex; unsigned short int wCodecValue; }CodecRegister; typedef enum { HW_EQ_LP0_A1=0, HW_EQ_LP0_H0, HW_EQ_BP1_A1, HW_EQ_BP1_A2, HW_EQ_BP1_H0, HW_EQ_BP2_A1, HW_EQ_BP2_A2, HW_EQ_BP2_H0, HW_EQ_BP3_A1, HW_EQ_BP3_A2, HW_EQ_BP3_H0, HW_EQ_BP4_A1, HW_EQ_HP4_H0, HW_EQ_INPUT_VOL=0x11, HW_EQ_OUTPUT_VOL, AVC_CTRL_REG1=0x21, AVC_CTRL_REG2, AVC_CTRL_REG3, AVC_CTRL_REG4, AVC_CTRL_REG5, CLASS_AB_REG=0x44, CLASS_D_REG=0x46, AD_DA_MIXER_IR5=0x54, AD_DA_MIXER_IR6=0x55, }EXT_CODEC_INDEX; typedef enum { POWER_STATE_D0=0, POWER_STATE_D1, POWER_STATE_D1_PLAYBACK, POWER_STATE_D1_RECORD, POWER_STATE_D2, POWER_STATE_D2_PLAYBACK, POWER_STATE_D2_RECORD, POWER_STATE_D3, POWER_STATE_D4 }POWER_STATE; typedef enum { DEPOP_MODE1_HP, DEPOP_MODE2_HP, DEPOP_MODE3_HP }DEPOP_MODE; typedef enum { SET_3D_L_GAIN=0, SET_3D_R_GAIN, SET_3D_L_RATIO, SET_3D_R_RATIO, SET_3D_ENABLE, SET_3D_DISABLE }SET_3D_PARA_MODE; typedef enum { RT_WAVOUT_PATH_ALL=0, RT_WAVOUT_PATH_HP, RT_WAVOUT_PATH_SPK, RT_WAVOUT_PATH_AUX, RT_WAVOUT_PATH_MONO, RT_WAVOUT_PATH_DAC, }WAVOUT_PATH; typedef enum { CLUB=0, DANCE, LIVE, POP, ROCK, }HW_EQ_PRESET_TYPE; typedef struct _HW_EQ_PRESET { HW_EQ_PRESET_TYPE HwEqType; unsigned short int EqValue[14]; unsigned short int HwEQCtrl; }HW_EQ_PRESET; class RT5621_Codec { public: HardwareContext *m_pHWContext; RT5621_Codec(); ~RT5621_Codec(); BOOL ShadowReadCodec(BYTE Offset, unsigned short int *Data); BOOL ShadowWriteCodec(BYTE Offset, unsigned short int Data); BOOL WriteCodecRegMask(BYTE Offset, unsigned short int Data,unsigned short int Mask); BOOL WriteCodecAdvance(EXT_CODEC_INDEX Ext_Index,unsigned short int Data); BOOL ReadCodecAdvance(EXT_CODEC_INDEX Index,unsigned short int *Data); BOOL WriteCodecAdvanceMask(EXT_CODEC_INDEX Ext_Index,unsigned short int Ext_Data,unsigned short int Ext_Data_Mask); BOOL Init(HardwareContext *HwCxt); BOOL InitRTCodecReg(void); BOOL ConfigMicBias(BYTE Mic,BYTE MicBiasCtrl); BOOL ConfigVmidOutput(BYTE SPK_Type,unsigned short int VMID_RATIO); BOOL ConfigMicBoost(BYTE Mic,MIC_BOOST_TYPE BoostType); BOOL EnablePLLPath(BOOL bEnablePLL,unsigned short int K,unsigned short int M,unsigned short int N); BOOL Enable_ADC_Input_Source(unsigned short int ADC_Input_Sour,BOOL Enable); void DepopForHP(DEPOP_MODE Depop_mode); void SaveCodecRegToShadow(); void RestoreRegToCodec(); void SaveCodecExtRegToShadow(); void ReStoreExtRegToCodec(); void DelayMSTime(unsigned int MilliSec); BOOL ChangeCodecPowerStatus(POWER_STATE power_state); BOOL EnableAVC(BOOL Enable_AVC); BOOL Enable_Main_Spatial(BOOL Enable_Main_Spatial); BOOL Set_3D_Func(SET_3D_PARA_MODE S_3d_para,BYTE para); BOOL Enable_Pseudo_Stereo(BOOL Enable_Pseudo_Stereo); BOOL Enable_All_Pass_Filter(BOOL Enable_APF); BOOL EnableHwEq(HW_EQ_PRESET_TYPE Hw_Eq_Type,BOOL HwEqEnable); BOOL AudioOutEnable(WAVOUT_PATH WavOutPath,BOOL Mute); DWORD ProcessAudioMessage(UINT uMsg,DWORD dwParam1,DWORD dwParam2); private: unsigned short int m_WaveInSampleRate; unsigned short int m_WaveOutSampleRate; friend class HardwareContext; }; #endif //__RTCODEC5621_H__
[ [ [ 1, 538 ] ] ]
aca68df1745936fdf9b9da433f4df2f098aff9c1
2a0e358f2f24b6c5d9086f9e07fcb6f7f87bdead
/src/Plugin_ScriptSerializer/src/ScriptSerializerPreCompiled.cpp
58b8f6369a8e6f0453a26eea83270d8629efc5ee
[]
no_license
coderespawn/ogre-script-serializer
e54e3e9de9ad969b75329c00627202772a4ffb16
eaa13116eb4b93927cf9962a0ff6cebc70660f78
refs/heads/master
2021-01-01T05:37:21.660084
2011-02-02T21:36:32
2011-02-02T21:36:32
41,284,341
0
0
null
null
null
null
UTF-8
C++
false
false
240
cpp
// stdafx.cpp : source file that includes just the standard includes // Plugin_ScriptSerializer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "ScriptSerializerPreCompiled.h"
[ "ali.akbar@e31138a1-012d-d96d-50da-1e7f8dcec721" ]
[ [ [ 1, 5 ] ] ]
6d289b2f674f30667feb83a2cb0ad2241c41ee85
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/ZoomViewDlg.cpp
06d21e0f68b6e41daa43b0f28d9aabb4079db99b
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,670
cpp
// ZoomViewDlg.cpp : implementation file // #include "stdafx.h" #include "AIPI.h" #include "ZoomViewDlg.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CZoomViewDlg dialog CZoomViewDlg::CZoomViewDlg(CWnd* pParent /*=NULL*/) : CDialog(CZoomViewDlg::IDD, pParent) { //{{AFX_DATA_INIT(CZoomViewDlg) m_iValue = 100; // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CZoomViewDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CZoomViewDlg) DDX_Control(pDX, IDC_STATIC_EXPANSION, m_stcExpansion); DDX_Control(pDX, IDC_SPIN_CUSTOM, m_spinCustom); DDX_Control(pDX, IDC_EDIT_CUSTOM, m_editCustom); DDX_Control(pDX, IDC_RADIO_200, m_radio200); DDX_Control(pDX, IDC_RADIO_100, m_radio100); DDX_Control(pDX, IDC_RADIO_75, m_radio75); DDX_Control(pDX, IDC_RADIO_50, m_radio50); DDX_Control(pDX, IDC_RADIO_25, m_radio25); DDX_Control(pDX, IDC_RADIO_CUSTOM, m_radioCustom); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CZoomViewDlg, CDialog) //{{AFX_MSG_MAP(CZoomViewDlg) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_CUSTOM, OnDeltaposSpinCustom) ON_BN_CLICKED(IDC_RADIO_200, OnRadio200) ON_BN_CLICKED(IDC_RADIO_100, OnRadio100) ON_BN_CLICKED(IDC_RADIO_75, OnRadio75) ON_BN_CLICKED(IDC_RADIO_50, OnRadio50) ON_BN_CLICKED(IDC_RADIO_25, OnRadio25) ON_BN_CLICKED(IDC_RADIO_CUSTOM, OnRadioCustom) ON_EN_CHANGE(IDC_EDIT_CUSTOM, OnChangeEditCustom) ON_EN_SETFOCUS(IDC_EDIT_CUSTOM, OnSetfocusEditCustom) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CZoomViewDlg message handlers BOOL CZoomViewDlg::OnInitDialog() { CDialog::OnInitDialog(); m_iValue = 100; m_radio100.SetCheck(true); m_editCustom.SetValue(m_iValue); m_editCustom.SetFractionalDigitCount(0); m_editCustom.SetTextColor(RGB(0, 0, 255), true); m_editCustom.SetGroupLength(0); m_spinCustom.SetBuddy(&m_editCustom); m_spinCustom.SetRange(10, 200); m_spinCustom.SetPos(100); m_spinCustom.SetComputationMethod(OX_SPIN_DELTA_PIXEL_IS_DELTA_VALUE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CZoomViewDlg::OnDeltaposSpinCustom(NMHDR* pNMHDR, LRESULT* pResult) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; /* if(pNMUpDown->iDelta <0 ) { if( m_iValue > 200 ) { AfxMessageBox(_T("Maximun limit has been reached")); } else { m_iValue++; } m_editCustom.SetValue(m_iValue*10); } else { if( m_iValue < 0 ) { AfxMessageBox(_T("Minimum limit has been reached")); } else { m_iValue--; } m_editCustom.SetValue(m_iValue*10); } */ *pResult = 0; } void CZoomViewDlg::OnRadio200() { m_iValue = 200; m_spinCustom.SetPos(m_iValue); m_radioCustom.SetCheck(false); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(FALSE); } void CZoomViewDlg::OnRadio100() { m_iValue = 100; m_spinCustom.SetPos(m_iValue); m_radioCustom.SetCheck(false); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(FALSE); } void CZoomViewDlg::OnRadio75() { m_iValue = 75; m_spinCustom.SetPos(m_iValue); m_radioCustom.SetCheck(false); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(FALSE); } void CZoomViewDlg::OnRadio50() { m_iValue = 50; m_spinCustom.SetPos(m_iValue); m_radioCustom.SetCheck(false); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(FALSE); } void CZoomViewDlg::OnRadio25() { m_iValue = 25; m_spinCustom.SetPos(m_iValue); m_radioCustom.SetCheck(false); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(FALSE); } void CZoomViewDlg::OnRadioCustom() { m_spinCustom.SetPos(m_iValue); //GetDlgItem(IDC_EDIT_CUSTOM)->EnableWindow(TRUE); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(TRUE); } void CZoomViewDlg::OnChangeEditCustom() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. m_iValue = m_spinCustom.GetPos(); GetDlgItem(IDC_SPIN_CUSTOM)->EnableWindow(TRUE); if( m_radio100.GetCheck() == 1 ) { m_radioCustom.SetCheck(false); } /* if( m_radioCustom.GetCheck() == 1 ) { if(m_iValue < 10 ) { CString str1 = _T("WARNING: Value range out of limit.The input value is too low."); CString str2 = _T("Please insert value between 10% - 200% "); CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); pMainFrame->m_wndOutputTabView.AddMsg1(str1); pMainFrame->m_wndOutputTabView.AddMsg1(str2); m_iValue = 100; //m_spinCustom.SetPos(100); } if(m_iValue > 200 ) { CString str1 = _T("Value range out of limit.The input value is too high"); CString str2 = _T("Please insert value between 10% - 200% "); CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); pMainFrame->m_wndOutputTabView.AddMsg1(str1); pMainFrame->m_wndOutputTabView.AddMsg1(str2); m_iValue = 100; //m_spinCustom.SetPos(100); } } */ } void CZoomViewDlg::OnSetfocusEditCustom() { m_radioCustom.SetCheck(true); m_radio200.SetCheck(false); m_radio100.SetCheck(false); m_radio75.SetCheck(false); m_radio50.SetCheck(false); m_radio25.SetCheck(false); }
[ [ [ 1, 242 ] ] ]
202bb3400e3f90c1c08de15581f0b11964e0fcf0
ad33a51b7d45d8bf1aa900022564495bc08e0096
/DES/DES_GOBSTG/Core/ParserFunction.cpp
766866ca5b9b398f8bf3032a40d5d2c222b47a55
[]
no_license
CBE7F1F65/e20671a6add96e9aa3551d07edee6bd4
31aff43df2571d334672929c88dfd41315a4098a
f33d52bbb59dfb758b24c0651449322ecd1b56b7
refs/heads/master
2016-09-11T02:42:42.116248
2011-09-26T04:30:32
2011-09-26T04:30:32
32,192,691
0
0
null
null
null
null
UTF-8
C++
false
false
18,157
cpp
#include "../Header/Scripter.h" //#include "../Header/processPrep.h" void * Scripter::Value(vector<Script>::iterator * p, int i, BYTE force) { /* if((*p)->type & SCR_TOKEN_VALUE) { if(force & SCR_FORCE_INT) { d[i].bfloat = false; if((*p)->type & SCR_TOKEN_FLOAT) { idesc[i] = (int)CFLOAT(&((*p)->value)); } else { idesc[i] = (int)CINT(&((*p)->value)); } } else if(force & SCR_FORCE_FLOAT) { d[i].bfloat = true; if((*p)->type & SCR_TOKEN_FLOAT) { fdesc[i] = (float)CFLOAT(&((*p)->value)); } else { fdesc[i] = (float)CINT(&((*p)->value)); } } else { if((*p)->type & SCR_TOKEN_FLOAT) { d[i].bfloat = true; fdesc[i] = CFLOAT(&((*p)->value)); } else { d[i].bfloat = false; idesc[i] = CINT(&((*p)->value)); } } } else if((*p)->type & SCR_TOKEN_HANDLE) { d[i].bfloat = false; idesc[i] = (*p)->value; } else if((*p)->type & SCR_TOKEN_VARIABLE) { int _tdi = (*p)->value; d[i].bfloat = d[_tdi].bfloat; if(d[i].bfloat) fdesc[i] = CFLOAT(d[_tdi].value); else idesc[i] = CINT(d[_tdi].value); } else { int _tdi; float _tdf; DWORD nowval = (*p)->value; switch(nowval & SCRKWMASK_CLASS) { / ************************************************************************ / / * AttackObject * / / ************************************************************************ / case SCRKW_CLASS_ATTACKOBJECT: switch (nowval) { case SCR_BUI: idesc[i] = Bullet::index; d[i].bfloat = false; break; case SCR_BUANGLE: idesc[i] = bu[Bullet::index].angle; d[i].bfloat = false; break; case SCR_BUSPEED: fdesc[i] = bu[Bullet::index].speed; d[i].bfloat = true; break; case SCR_BUX: fdesc[i] = bu[Bullet::index].x; d[i].bfloat = true; break; case SCR_BUY: fdesc[i] = bu[Bullet::index].y; d[i].bfloat = true; break; case SCR_BUTIMER: idesc[i] = bu[Bullet::index].timer; d[i].bfloat = false; break; case SCR_BUCANCELABLE: idesc[i] = bu[Bullet::index].cancelable; d[i].bfloat = false; break; case SCR_BUHAVEGRAY: idesc[i] = (int)bu[Bullet::index].HaveGray(); d[i].bfloat = false; break; case SCR_BEI: idesc[i] = Beam::index; d[i].bfloat = false; break; case SCR_BEANGLE: idesc[i] = be[Beam::index].angle; d[i].bfloat = false; break; case SCR_BESPEED: fdesc[i] = be[Beam::index].speed; d[i].bfloat = true; break; case SCR_BEX: fdesc[i] = be[Beam::index].x; d[i].bfloat = true; break; case SCR_BEY: fdesc[i] = be[Beam::index].y; d[i].bfloat = true; break; case SCR_BETIMER: idesc[i] = be[Beam::index].timer; d[i].bfloat = false; break; case SCR_BEHOLDTAR: idesc[i] = be[Beam::index].holdtar; d[i].bfloat = false; break; case SCR_BEPINTAR: idesc[i] = be[Beam::index].pintar; d[i].bfloat = false; break; } break; / ************************************************************************ / / * Ghost * / / ************************************************************************ / case SCRKW_CLASS_GHOST: switch (nowval) { case SCR_GHX: fdesc[i] = gh[Ghost::index].x; d[i].bfloat = true; break; case SCR_GHY: fdesc[i] = gh[Ghost::index].y; d[i].bfloat = true; break; case SCR_GHTIMER: idesc[i] = gh[Ghost::index].timer; d[i].bfloat = false; break; case SCR_GHI: idesc[i] = Ghost::index; d[i].bfloat = false; break; case SCR_GHANGLE: idesc[i] = gh[Ghost::index].angle; d[i].bfloat = false; break; case SCR_GHSPEED: fdesc[i] = gh[Ghost::index].speed; d[i].bfloat = true; break; case SCR_GHAMAP: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = gh[Ghost::index].aMainAngle(Player::p[0], _tdi); d[i].bfloat = false; break; case SCR_GHRMAP: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = gh[Ghost::index].rMainAngle(Player::p[0], _tdi); d[i].bfloat = false; break; case SCR_GHAIMX: fdesc[i] = gh[Ghost::index].aim.x; d[i].bfloat = true; break; case SCR_GHAIMY: fdesc[i] = gh[Ghost::index].aim.y; d[i].bfloat = true; break; case SCR_GHLIFE: fdesc[i] = gh[Ghost::index].life; d[i].bfloat = true; break; case SCR_GHAC: idesc[i] = gh[Ghost::index].ac; d[i].bfloat = false; break; } break; / ************************************************************************ / / * Enemy * / / ************************************************************************ / case SCRKW_CLASS_ENEMY: switch (nowval) { case SCR_ENX: fdesc[i] = en[Enemy::index].x; d[i].bfloat = true; break; case SCR_ENY: fdesc[i] = en[Enemy::index].y; d[i].bfloat = true; break; case SCR_ENTIMER: idesc[i] = en[Enemy::index].timer; d[i].bfloat = false; break; case SCR_ENI: idesc[i] = Enemy::index; d[i].bfloat = false; break; case SCR_ENANGLE: idesc[i] = en[Enemy::index].angle; d[i].bfloat = false; break; case SCR_ENSPEED: fdesc[i] = en[Enemy::index].speed; d[i].bfloat = true; break; case SCR_ENAMAP: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = en[Enemy::index].aMainAngle(Player::p[0], _tdi); d[i].bfloat = false; break; case SCR_ENRMAP: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = en[Enemy::index].rMainAngle(Player::p[0], _tdi); d[i].bfloat = false; break; case SCR_ENAIMX: fdesc[i] = en[Enemy::index].aim.x; d[i].bfloat = true; break; case SCR_ENAIMY: fdesc[i] = en[Enemy::index].aim.y; d[i].bfloat = true; break; case SCR_ENLIFE: fdesc[i] = en[Enemy::index].life; d[i].bfloat = true; break; } break; / ************************************************************************ / / * Math * / / ************************************************************************ / case SCRKW_CLASS_MATH: switch (nowval) { case SCR_RAND: idesc[i] = randt(); d[i].bfloat = false; break; case SCR_RANDR: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = randt() % (_tdi * 2 + 1) - _tdi; d[i].bfloat = false; break; case SCR_SEED: idesc[i] = mp.seed; d[i].bfloat = false; break; case SCR_SINA: ++(*p); fdesc[i] = sint(CINT(Value(&(*p), i, 0))); d[i].bfloat = true; break; case SCR_COSA: ++(*p); fdesc[i] = cost(CINT(Value(&(*p), i, 0))); d[i].bfloat = true; break; case SCR_TANA: ++(*p); fdesc[i] = tant(CINT(Value(&(*p), i, 0))); d[i].bfloat = true; break; case SCR_ASIN2: ++(*p); _tdf = CFLOAT((Value(&(*p), i, 0))); ++(*p); idesc[i] = asin2t(_tdf, CFLOAT(Value(&(*p), i, 0))); d[i].bfloat = false; break; case SCR_ACOS2: ++(*p); _tdf = CFLOAT((Value(&(*p), i, 0))); ++(*p); idesc[i] = acos2t(_tdf, CFLOAT(Value(&(*p), i, 0))); d[i].bfloat = false; break; case SCR_ATAN2: ++(*p); _tdf = CFLOAT((Value(&(*p), i, 0))); ++(*p); idesc[i] = atan2t(_tdf, CFLOAT(Value(&(*p), i, 0))); d[i].bfloat = false; break; case SCR_SQRT: ++(*p); fdesc[i] = sqrtf(CFLOAT((Value(&(*p), i, 0)))); d[i].bfloat = true; break; case SCR_SIGN: ++(*p); idesc[i] = SIGN(CINT(Value(&(*p), i, 0))); d[i].bfloat = false; break; case SCR_ROLL: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); ++(*p); idesc[i] = ROLL(_tdi, CINT(Value(&(*p), i, 0))); d[i].bfloat = false; break; } break; / ************************************************************************ / / * Other * / / ************************************************************************ / case SCRKW_CLASS_OTHER: switch (nowval) { case SCR_D: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); if(d[_tdi].bfloat) fdesc[i] = CAST(d[_tdi]); else idesc[i] = CAST(d[_tdi]); d[i].bfloat = d[_tdi].bfloat; break; case SCR_DU: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = UCAST(d[_tdi]); d[i].bfloat = false; break; case SCR_TX: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); fdesc[i] = tar[_tdi].x; d[i].bfloat = true; break; case SCR_TY: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); fdesc[i] = tar[_tdi].y; d[i].bfloat = true; break; case SCR_TIME: idesc[i] = time; d[i].bfloat = false; break; case SCR_NOWNAME: idesc[i] = nowName; d[i].bfloat = false; break; case SCR_NOWCON: idesc[i] = nowCon; d[i].bfloat = false; break; case SCR_DIFFI: idesc[i] = mp.nowdifflv; d[i].bfloat = false; break; case SCR_SNOSTAGE: _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = data.getStage(_tdi); d[i].bfloat = false; break; case SCR_SNODIFFI: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = data.getDiffi(_tdi); d[i].bfloat = false; break; case SCR_SNOBATTLE: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = data.getBattle(_tdi); d[i].bfloat = false; break; case SCR_SNOUSER: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = data.getSpellUser(_tdi); d[i].bfloat = false; break; case SCR_CHARA: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); if (_tdi == 0) { idesc[i] = Player::p[0].ID; } else if (_tdi == 1) { idesc[i] = Player::p[0].ID_sub_1; } else if (_tdi == 2) { idesc[i] = Player::p[0].ID_sub_2; } else { idesc[i] = Player::p[0].nowID; } d[i].bfloat = false; break; case SCR_GETSCENE: idesc[i] = mp.scene; d[i].bfloat = false; break; case SCR_MODE: if (mp.practicemode) { if (mp.spellmode) { idesc[i] = M_MODE_SPELL; } else { idesc[i] = M_MODE_STAGE; } } else { idesc[i] = M_MODE_NORMAL; } d[i].bfloat = false; break; case SCR_REPLAYMODE: idesc[i] = mp.replaymode; d[i].bfloat = false; break; case SCR_FRAMESKIP: idesc[i] = mp.frameskip; d[i].bfloat = false; break; } break; / ************************************************************************ / / * Special * / / ************************************************************************ / case SCRKW_CLASS_SPECIAL: switch (nowval) { case SCR_CHATI: idesc[i] = chat.chati; d[i].bfloat = false; break; case SCR_BOSSFAILED: idesc[i] = BossInfo::failed; d[i].bfloat = false; break; case SCR_BOSSFLAG: idesc[i] = BossInfo::flag; d[i].bfloat = false; break; case SCR_CHECKKEY: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); ++(*p); idesc[i] = Export::Input_GetDIKey(_tdi, CINT(Value(&(*p), i, 0))); d[i].bfloat = false; break; case SCR_GETFLAG: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = data.iRead(DATA_BINFILE, DATAS_FLAG, _tdi, 0); d[i].bfloat = false; break; case SCR_PLAYERNAME: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); CUINT(&idesc[i]) = (DWORD)data.getPlayerName(_tdi); d[i].bfloat = true;/ *Specialized for Handle* / break; case SCR_ENEMYNAME: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); CUINT(&idesc[i]) = (DWORD)data.getEnemyName(_tdi); d[i].bfloat = true;/ *Specialized for Handle* / break; case SCR_SPELLNAME: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); CUINT(&idesc[i]) = (DWORD)data.getSpellName(_tdi); d[i].bfloat = true;/ *Specialized for Handle* / break; case SCR_SPELLUSERNAME: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); CUINT(&idesc[i]) = (DWORD)data.getSpellUserName(_tdi); d[i].bfloat = true;/ *Specialized for Handle* / break; case SCR_SPELLUSERENAME: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); CUINT(&idesc[i]) = (DWORD)data.getSpellUserEName(_tdi); d[i].bfloat = true;/ *Specialized for Handle* / break; } break; / ************************************************************************ / / * Effect * / / ************************************************************************ / case SCRKW_CLASS_EFFECT: switch (nowval) { } break; / ************************************************************************ / / * Player * / / ************************************************************************ / case SCRKW_CLASS_PLAYER: switch (nowval) { case SCR_PX: fdesc[i] = Player::p[0].x; d[i].bfloat = true; break; case SCR_PY: fdesc[i] = Player::p[0].y; d[i].bfloat = true; break; case SCR_PLIFE: idesc[i] = Player::p[0].nLife; d[i].bfloat = false; break; case SCR_PBOMB: idesc[i] = (float)Player::p[0].nPower / Player::p[0].bombperpower; d[i].bfloat = false; break; case SCR_PPOWER: idesc[i] = Player::p[0].nPower; d[i].bfloat = false; break; case SCR_PFAITH: idesc[i] = Player::p[0].nFaith; d[i].bfloat =false; break; case SCR_PPOINT: idesc[i] = Player::p[0].nPoint; d[i].bfloat = false; break; case SCR_PBBORDER: idesc[i] = (int)(Player::p[0].bBorder); d[i].bfloat = false; break; case SCR_PBSLOW: idesc[i] = (int)(Player::p[0].bSlow); d[i].bfloat = false; break; case SCR_PBINFI: idesc[i] = (int)(Player::p[0].bInfi); d[i].bfloat = false; break; case SCR_PSPEED: fdesc[i] = Player::p[0].speed; d[i].bfloat = true; break; case SCR_PSLOWSPEED: fdesc[i] = Player::p[0].slowspeed; d[i].bfloat = true; break; case SCR_PGX: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); fdesc[i] = Player::p[0].pg[_tdi].x; d[i].bfloat = true; break; case SCR_PGY: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); fdesc[i] = Player::p[0].pg[_tdi].y; d[i].bfloat = true; break; case SCR_HAVEPLAYER: ++(*p); _tdi = CINT(Value(&(*p), i, 0)); idesc[i] = Player::p[0].HavePlayer(_tdi); d[i].bfloat = false; break; } break; / ************************************************************************ / / * Layer * / / ************************************************************************ / case SCRKW_CLASS_LAYER: switch (nowval) { case SCR_BGSINDEX: idesc[i] = BGLayer::setindex; d[i].bfloat = false; break; case SCR_BGSTIMER: idesc[i] = BGLayer::set[BGLayer::setindex].timer; d[i].bfloat = false; break; } break; / ************************************************************************ / / * Select * / / ************************************************************************ / case SCRKW_CLASS_SELECT: switch (nowval) { case SCR_SELCOMPLETE: idesc[i] = false;//SelectSystem::complete; d[i].bfloat = false; break; case SCR_SEL: idesc[i] = 0;//SelectSystem::select; d[i].bfloat = false; break; case SCR_SELFIRSTID: idesc[i] = 0;//SelectSystem::firstID; d[i].bfloat = false; break; case SCR_ISELCOMPLETE: idesc[i] = InfoSelect::complete; d[i].bfloat = false; break; case SCR_ISEL: idesc[i] = InfoSelect::select; d[i].bfloat = false; break; case SCR_ISELFIRSTID: idesc[i] = InfoSelect::firstID; d[i].bfloat = false; break; } break; } } if(d[i].bfloat) return &fdesc[i];*/ return &idesc[i]; }
[ "CBE7F1F65@b503aa94-de59-8b24-8582-4b2cb17628fa" ]
[ [ [ 1, 663 ] ] ]
8c6a687fe9b9b4538c3e16f8e9e888cbe1b12928
ca2395f4eec7e941d0d91d7e2913f8cc66b14472
/NetThread.cpp
aecea8c04602b4f97673bdc94ea73dbfa45d99be
[]
no_license
EmilHernvall/chatclient
21a27de2e44bb25dd2acb34a8d75a79d8e7bd46a
47e16866992e4dd4ce3e5538b32b09ed2dfaef06
refs/heads/master
2021-01-15T22:28:44.465662
2008-04-16T16:12:48
2008-04-16T16:12:48
1,697,523
0
0
null
null
null
null
UTF-8
C++
false
false
4,050
cpp
#include "stdafx.h" #include "ChatClient.h" #include "Net.h" #include "IRC.h" #include "String.h" VOID ProcessCommand(LPWSTR szRead, int iLen, ChatClient *bwChatClient); VOID NetworkThread(PVOID pvoid) { ChatClient *bwChatClient; Net *net; IRC *irc; WCHAR buffer[1024]; LPWSTR szRead; int iLen; bwChatClient = (ChatClient*)pvoid; net = bwChatClient->GetNet(); irc = bwChatClient->GetIRC(); swprintf(buffer, sizeof(buffer)/sizeof(TCHAR), L"NICK %s\r\n", irc->GetNick()); net->Write(buffer); swprintf(buffer, sizeof(buffer)/sizeof(TCHAR), L"USER %s %s %s %s\r\n", irc->GetUser(), irc->GetUser(), irc->GetUser(), irc->GetUser()); net->Write(buffer); while (TRUE) { iLen = net->Read(&szRead); ProcessCommand(szRead, iLen, bwChatClient); //Sleep(10); } } VOID ProcessCommand(LPWSTR szRead, int iLen, ChatClient *bwChatClient) { Net *net; IRC *irc; WCHAR szBuffer[1024]; LPWSTR *split; INT arrSize, i, iCommand; LPTSTR szMsg, szTmp; net = bwChatClient->GetNet(); irc = bwChatClient->GetIRC(); arrSize = Explode(&split, szRead, ' '); if (arrSize <= 1) { bwChatClient->AppendToBuffer(0, szRead); return; } if (wcsncmp(split[1], L"PRIVMSG", 7) == 0) { szMsg = szRead + wcslen(split[0]) + wcslen(split[1]) + wcslen(split[2]) + 4; szTmp = wcschr(split[0], '!'); *szTmp = '\0'; i = bwChatClient->GetWindowNameByID(split[2]); if (i < 0) { i = 0; } swprintf(szBuffer, sizeof(szBuffer)/sizeof(WCHAR), L"<%s> %s", split[0] + 1, szMsg); bwChatClient->AppendToBuffer(i, szBuffer); } else if (wcsncmp(split[1], L"NOTICE", 6) == 0) { szMsg = szRead + wcslen(split[0]) + wcslen(split[1]) + wcslen(split[2]) + 4; szTmp = wcschr(split[0], '!'); if (szTmp != NULL) { *szTmp = '\0'; } swprintf(szBuffer, sizeof(szBuffer)/sizeof(WCHAR), L" -%s- %s", split[0] + 1, szMsg); bwChatClient->AppendToBuffer(0, szBuffer); } else if (wcsncmp(split[1], L"JOIN", 4) == 0) { // :[email protected] JOIN :#floodffs! szTmp = wcschr(szRead, '!'); if (szTmp != NULL) { i = szTmp - (szRead + 1); wcsncpy(szBuffer, szRead + 1, i); szBuffer[i] = '\0'; //bwChatClient->AppendToBuffer(0, szBuffer); //bwChatClient->AppendToBuffer(0, split[2]+1); if (wcsncmp(irc->GetNick(), szBuffer, wcslen(irc->GetNick())) == 0) { //bwChatClient->CreateSubWindow(split[2]+1); //bwChatClient->AppendToBuffer(0, split[2]+1); SendMessage(bwChatClient->GetHWND(), WM_BASICWINDOW_CREATEWINDOW, (WPARAM)(split[2]+1), 0); } } } else if (wcsncmp(split[0], L"PING", 4) == 0) { swprintf(szBuffer, sizeof(szBuffer)/sizeof(WCHAR), L"PONG %s\r\n", split[1]); net->Write(szBuffer); } else if (IsNumeric(split[1])) { iCommand = _wtoi(split[1]); switch (iCommand) { case 1: // welcome swprintf(szBuffer, sizeof(szBuffer)/sizeof(WCHAR), L"JOIN %s\r\n", irc->GetChannel()); net->Write(szBuffer); case 2: // host, version case 3: // date szMsg = szRead + wcslen(split[0]) + wcslen(split[1]) + wcslen(split[2]) + 4; bwChatClient->AppendToBuffer(0, szMsg); break; case 4: case 5: szMsg = szRead + wcslen(split[0]) + wcslen(split[1]) + wcslen(split[2]) + 3; bwChatClient->AppendToBuffer(0, szMsg); break; case 251: // usage stats case 255: case 265: case 266: szMsg = szRead + wcslen(split[0]) + wcslen(split[1]) + wcslen(split[2]) + 4; bwChatClient->AppendToBuffer(0, szMsg); break; case 372: // motd case 375: // motd start case 376: // motd end szMsg = szRead + wcslen(split[0]) + wcslen(split[1]) + wcslen(split[2]) + 4; bwChatClient->AppendToBuffer(0, szMsg); break; case 451: // Not registered break; default: bwChatClient->AppendToBuffer(0, szRead); } } else { bwChatClient->AppendToBuffer(0, szRead); } if (arrSize > 0) { for (i = 0; i < arrSize; i++) { free(split[i]); } free(split); } }
[ "emil@2d89dd5f-9cc0-461d-8d4c-555c0e271dc8" ]
[ [ [ 1, 153 ] ] ]
a3406026e6264624b3340b9c6ba7b8c2ca881abb
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-network/src/jingxian/string/os_string.h
c1e6b2872f9743fca66afbf99cda017f2236cded
[]
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
5,187
h
 #ifndef os_string_h #define os_string_h #include "jingxian/config.h" #if !defined (JINGXIAN_LACKS_PRAGMA_ONCE) # pragma once #endif /* JINGXIAN_LACKS_PRAGMA_ONCE */ #include <tchar.h> #include <string.h> #include <string> #include <sstream> typedef char char_t; #ifdef _UNICODE typedef std::wstring tstring; typedef std::wostream tostream; typedef std::wstringstream tstringstream; typedef std::wstringstream LogStream; typedef wchar_t tchar; #define tcout std::wcout #define tcerr std::wcerr #define tcin std::wcin #else typedef std::string tstring; typedef std::ostream tostream; typedef std::stringstream tstringstream; typedef std::stringstream LogStream; typedef char_t tchar; #define tcout std::cout #define tcerr std::cerr #define tcin std::cin #endif _jingxian_begin template<typename charT> struct stringData { // 内存块大小(可选值,为0时为无效值) size_t capacity; // 字符串大小(可选值,为0或-1为无效值) size_t len; // 字符串指针 charT* ptr; }; struct string_t { // 内存块大小(可选值,为0时为无效值) size_t capacity; // 字符串大小(可选值,为0或-1为无效值) size_t len; // 字符串指针 tchar* ptr; }; inline const char* c_str_ptr(const char* t) { return t; } inline const tchar* c_str_ptr(const string_t* t) { return t->ptr; } inline const tchar* c_str_ptr(const string_t& t) { return t.ptr; } template<typename charT> inline const charT* c_str_ptr(const stringData<charT>& t) { return t.ptr; } template<typename charT> inline const charT* c_str_ptr(const stringData<charT>* t) { return t->ptr; } inline std::string::const_pointer c_str_ptr(const std::string& t) { return t.c_str(); } inline std::string::const_pointer c_str_ptr(const std::string* t) { return t->c_str(); } inline const wchar_t* c_str_ptr(const wchar_t* t) { return t; } inline std::wstring::const_pointer c_str_ptr(const std::wstring& t) { return t.c_str(); } inline std::wstring::const_pointer c_str_ptr(const std::wstring* t) { return t->c_str(); } #pragma warning(disable: 4267) inline std::wstring toWideString(const char* pStr , size_t len = -1) { int nChars = MultiByteToWideChar(CP_ACP , 0 , pStr , len , NULL , 0) ; if ((size_t) - 1 == len) -- nChars; if (nChars == 0) return L""; std::wstring buf; buf.resize(nChars) ; MultiByteToWideChar(CP_ACP , 0 , pStr , len , const_cast<wchar_t*>(buf.c_str()) , nChars) ; return buf ; } #pragma warning(default: 4267) inline std::wstring toWideString(const std::string& str) { return toWideString(str.c_str(), str.length()) ; } inline std::wstring toWideString(const wchar_t* pStr , size_t len = -1) { return ((size_t) - 1 == len) ? pStr : std::wstring(pStr, len) ; } inline const std::wstring& toWideString(const std::wstring& str) { return str ; } #pragma warning(disable: 4267) inline std::string toNarrowString(const wchar_t* pStr , size_t len = -1) { int nChars = WideCharToMultiByte(CP_ACP , 0 , pStr , len , NULL , 0 , NULL , NULL) ; if ((size_t) - 1 == len) -- nChars ; if (nChars == 0) return "" ; std::string buf; buf.resize(nChars) ; WideCharToMultiByte(CP_ACP , 0 , pStr , len , const_cast<char*>(buf.c_str()) , nChars , NULL , NULL) ; return buf ; } #pragma warning(default: 4267) inline std::string toNarrowString(const std::wstring& str) { return toNarrowString(str.c_str(), str.length()) ; } inline std::string toNarrowString(const char* pStr , size_t len = -1) { return ((size_t) - 1 == len) ? pStr : std::string(pStr, len) ; } inline const std::string& toNarrowString(const std::string& str) { return str ; } #ifdef _UNICODE inline tchar toTchar(char ch) { return (wchar_t)ch ; } inline tchar toTchar(wchar_t ch) { return ch ; } inline tstring toTstring(const std::string& s) { return toWideString(s) ; } inline const tstring& toTstring(const std::wstring& s) { return s; } inline tstring toTstring(const char* p , size_t len = -1) { return toWideString(p, len); } inline tstring toTstring(const wchar_t* p , size_t len = -1) { return (-1 == len) ? p : std::wstring(p, len) ; } #else inline tchar toTchar(char ch) { return ch ; } inline tchar toTchar(wchar_t ch) { return (ch >= 0 && ch <= 0xFF) ? (char)ch : '?' ; } inline const tstring& toTstring(const std::string& s) { return s ; } inline tstring toTstring(const char* p , size_t len = -1) { return ((size_t) - 1 == len) ? p : std::string(p, len) ; } inline tstring toTstring(const std::wstring& s) { return toNarrowString(s) ; } inline tstring toTstring(const wchar_t* p , size_t len = -1) { return toNarrowString(p, len) ; } #endif // _UNICODE _jingxian_end #endif // LOG4CPLUS_TSTRING_HEADER_
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 237 ] ] ]
846cae465e72fa5e3b895259f5743f58debe9bac
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/direct3d11/drawcommandexecuted3d11_2.cpp
8bbfa41c84ce1d6c12d5092e66774df28804a3fe
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
6,810
cpp
#include"drawcommandexecuted3d11.h" #include"deviced3d11.h" // ここは各シェーダーステージのset,getを書く #include"bufferd3d11.h" #include"texture2dd3d11.h" #include"rendertargetd3d11.h" #include"depthstencild3d11.h" #include"materiald3d11.h" #include"inputlayoutd3d11.h" #include"rasterizerstated3d11.h" #include"samplerstated3d11.h" #include"blendstated3d11.h" #include"depthstencilstated3d11.h" #include"vertexshaderd3d11.h" #include"pixelshaderd3d11.h" namespace Maid { namespace Graphics { void DrawCommandExecuteD3D11::SetIndex( const SPBUFFER& pBuffer, size_t Offset ) { BufferD3D11* p = static_cast<BufferD3D11*>(pBuffer.get()); const DXGI_FORMAT fmt = DXGI_FORMAT_R16_UINT; m_pDevice->IASetIndexBuffer( p->pBuffer.get(), fmt, Offset ); } void DrawCommandExecuteD3D11::SetVertex( int Slot, const SPBUFFER& pVertex, int Offset, int Stride ) { BufferD3D11* p = static_cast<BufferD3D11*>(pVertex.get()); const UINT StartSlot = Slot; const UINT NumBuffers = 1; ID3D11Buffer* pBuff[] = { p->pBuffer.get() }; const UINT Strides[] = {Stride}; const UINT Offsets[] = {Offset}; m_pDevice->IASetVertexBuffers( StartSlot, NumBuffers, pBuff, Strides, Offsets ); } void DrawCommandExecuteD3D11::SetInputLayout( const SPINPUTLAYOUT& pLayout ) { InputLayoutD3D11* p = static_cast<InputLayoutD3D11*>(pLayout.get()); m_pDevice->IASetInputLayout( p->pDecl.get() ); } void DrawCommandExecuteD3D11::SetPrimitiveTopology( PRIMITIVE_TOPOLOGY Topology ) { D3D11_PRIMITIVE_TOPOLOGY t = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; switch( Topology ) { case PRIMITIVE_TOPOLOGY_POINTLIST: { t = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; }break; case PRIMITIVE_TOPOLOGY_LINELIST: { t = D3D11_PRIMITIVE_TOPOLOGY_LINELIST ; }break; case PRIMITIVE_TOPOLOGY_LINESTRIP: { t = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; }break; case PRIMITIVE_TOPOLOGY_TRIANGLELIST: { t = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; }break; case PRIMITIVE_TOPOLOGY_TRIANGLESTRIP:{ t = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; }break; } m_pDevice->IASetPrimitiveTopology( t ); } void DrawCommandExecuteD3D11::VSSetMaterial( int stage, const SPMATERIAL& pBuffer ) { MaterialD3D11* p = static_cast<MaterialD3D11*>(pBuffer.get()); const UINT NumBuffers = 1; ID3D11ShaderResourceView* pBuff[] = { p->pView.get() }; m_pDevice->VSSetShaderResources( stage, NumBuffers, pBuff ); } void DrawCommandExecuteD3D11::VSSetSamplerState( int stage, const SPSAMPLERSTATE& Sampler ) { SamplerStateD3D11* p = static_cast<SamplerStateD3D11*>(Sampler.get()); const UINT NumBuffers = 1; ID3D11SamplerState* pBuff[] = { p->pState.get() }; m_pDevice->VSSetSamplers( stage, NumBuffers, pBuff ); } void DrawCommandExecuteD3D11::VSSetShader( const SPVERTEXSHADER& Shader ) { VertexShaderD3D11* p = static_cast<VertexShaderD3D11*>(Shader.get()); m_pDevice->VSSetShader( p->pShader.get(), NULL, 0 ); } void DrawCommandExecuteD3D11::VSSetConstant( int slot, const SPBUFFER& pBuffer ) { BufferD3D11* p = static_cast<BufferD3D11*>(pBuffer.get()); const UINT NumBuffers = 1; ID3D11Buffer * pBuff[] = { p->pBuffer.get() }; m_pDevice->VSSetConstantBuffers( slot, NumBuffers, pBuff ); } void DrawCommandExecuteD3D11::PSSetMaterial( int stage, const SPMATERIAL& pMaterial ) { MaterialD3D11* p = static_cast<MaterialD3D11*>(pMaterial.get()); const UINT NumBuffers = 1; ID3D11ShaderResourceView* pBuff[] = { p->pView.get() }; m_pDevice->PSSetShaderResources( stage, NumBuffers, pBuff ); } void DrawCommandExecuteD3D11::PSSetSamplerState( int stage, const SPSAMPLERSTATE& Sampler ) { SamplerStateD3D11* p = static_cast<SamplerStateD3D11*>(Sampler.get()); const UINT NumBuffers = 1; ID3D11SamplerState* pBuff[] = { p->pState.get() }; m_pDevice->PSSetSamplers( stage, NumBuffers, pBuff ); } void DrawCommandExecuteD3D11::PSSetShader( const SPPIXELSHADER& Shader ) { PixelShaderD3D11* p = static_cast<PixelShaderD3D11*>(Shader.get()); m_pDevice->PSSetShader( p->pShader.get(), NULL, 0 ); } void DrawCommandExecuteD3D11::PSSetConstant( int slot, const SPBUFFER& pBuffer ) { BufferD3D11* p = static_cast<BufferD3D11*>(pBuffer.get()); const UINT NumBuffers = 1; ID3D11Buffer * pBuff[] = { p->pBuffer.get() }; m_pDevice->PSSetConstantBuffers( slot, NumBuffers, pBuff ); } void DrawCommandExecuteD3D11::SetViewPort( const VIEWPORT& port ) { D3D11_VIEWPORT vp; vp.TopLeftX = (FLOAT)port.Screen.x; vp.TopLeftY = (FLOAT)port.Screen.y; vp.Width = (FLOAT)port.Screen.w; vp.Height = (FLOAT)port.Screen.h; vp.MinDepth = (FLOAT)port.MinZ; vp.MaxDepth = (FLOAT)port.MaxZ; m_pDevice->RSSetViewports( 1, &vp ); } void DrawCommandExecuteD3D11::SetRasterizerState( const SPRASTERIZERSTATE& State ) { RasterizerStateD3D11* p = static_cast<RasterizerStateD3D11*>(State.get()); m_pDevice->RSSetState( p->pState.get() ); } void DrawCommandExecuteD3D11::SetDepthStencilState( const SPDEPTHSTENCILSTATE& State ) { DepthStencilStateD3D11* p = static_cast<DepthStencilStateD3D11*>(State.get()); m_pDevice->OMSetDepthStencilState( p->pState.get(), 0x00 ); } void DrawCommandExecuteD3D11::SetBlendState( const SPBLENDSTATE& State ) { BlendStateD3D11* p = static_cast<BlendStateD3D11*>(State.get()); const FLOAT c[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; m_pDevice->OMSetBlendState( p->pState.get(), c, 0xFFFFFFFF ); } void DrawCommandExecuteD3D11::SetRenderTarget( int no, const SPRENDERTARGET& pColor, const SPDEPTHSTENCIL& pDepth ) { MAID_ASSERT( !(no<8), "値が大きすぎます "<< no ); m_NowRenderTarget[no] = pColor; m_NowDepthStencil[no] = pDepth; ID3D11DepthStencilView* d = NULL; if( pDepth.get()!=NULL ){ d = static_cast<DepthStencilD3D11*>(pDepth.get())->pView.get(); } ID3D11RenderTargetView* c[8] = { NULL }; for( int i=0; i<NUMELEMENTS(c); ++i ) { if( m_NowRenderTarget[i].get()!=NULL ){ c[i] = static_cast<RenderTargetD3D11*>(m_NowRenderTarget[i].get())->pView.get(); } } m_pDevice->OMSetRenderTargets( 8, c, d ); } VIEWPORT DrawCommandExecuteD3D11::GetViewport() { D3D11_VIEWPORT vp[1]; UINT num = NUMELEMENTS(vp); m_pDevice->RSGetViewports( &num, vp ); const D3D11_VIEWPORT& v = vp[0]; return VIEWPORT( RECT2DI(v.TopLeftX,v.TopLeftY,v.Width,v.Height), v.MinDepth, v.MaxDepth ); } void DrawCommandExecuteD3D11::GetRenderTarget( int no, SPRENDERTARGET& pColor, SPDEPTHSTENCIL& pDepth ) { MAID_ASSERT( (no<8), "値が大きすぎます "<< no ); pColor = m_NowRenderTarget[no]; pDepth = m_NowDepthStencil[no]; } }}
[ "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 239 ] ] ]
00447c874cb743d9c8e2a87ce788330be7d8d09a
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Standard/Source/StringUtils.h
d9b728217cf1fe2575fbb46a8a34c84537d1d079
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
1,931
h
#pragma once #include <cstdarg> class StringUtils { public: static KVOID Split(KSTR str, KSTR delim, KVEC<KSTR>& results) { KINT cutAt; while( (cutAt = str.find_first_of(delim)) != str.npos ) { if(cutAt > 0) { results.push_back(str.substr(0,cutAt)); } str = str.substr(cutAt+1); } if(str.length() > 0) { results.push_back(str); } } static KSTR ws2s(const KWSTR& ws) { KSTR curLocale = setlocale(LC_ALL, NULL); // curLocale = "C"; setlocale(LC_ALL, "chs"); const wchar_t* _Source = ws.c_str(); size_t _Dsize = 2 * ws.size() + 1; KCHAR *_Dest = KNEW KCHAR[_Dsize]; memset(_Dest,0,_Dsize); wcstombs(_Dest,_Source,_Dsize); KSTR result = _Dest; KDEL []_Dest; setlocale(LC_ALL, curLocale.c_str()); return result; } static KWSTR s2ws(KCSTR& s) { setlocale(LC_ALL, "chs"); const KCHAR* _Source = s.c_str(); size_t _Dsize = s.size() + 1; wchar_t *_Dest = KNEW wchar_t[_Dsize]; wmemset(_Dest, 0, _Dsize); mbstowcs(_Dest,_Source,_Dsize); KWSTR result = _Dest; KDEL []_Dest; setlocale(LC_ALL, "C"); return result; } static KSTR format(const KSTR& fmt, ...) { va_list argptr; va_start(argptr, fmt); KINT bufsize = _vsnprintf(NULL, 0, fmt.c_str(), argptr) + 2; KCHAR* buf = KNEW KCHAR[bufsize]; _vsnprintf(buf, bufsize, fmt.c_str(), argptr); KSTR s(buf); KDEL[] buf; va_end(argptr); return s; } static KSTR replace(KCSTR &str, KCCHAR *string_to_replace, KCCHAR *new_string) { KSTR tmp = str; // Find the first string to replace int index = tmp.find(string_to_replace); // while there is one while(index != std::string::npos) { // Replace it tmp.replace(index, strlen(string_to_replace), new_string); // Find the next one index = tmp.find(string_to_replace, index + strlen(new_string)); } return tmp; } };
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 2 ], [ 5, 26 ], [ 28, 53 ], [ 84, 84 ] ], [ [ 3, 4 ], [ 27, 27 ], [ 54, 83 ] ] ]
eeb4977b3059a8dad071601b7eb82e78e6e6790e
3b2322c1adf5e6166259540e767ec67df0887c17
/finite-state-machine/src/state/StateCarrierApproach.cpp
1ea3de3f282097e70f28a0e092e343df0a93faaa
[]
no_license
aruwen/various-stefan-ebner
750aac6e546ddb3e571ac468ecc26087843817d3
49eac46ed3a01131d711ea6feca77c32accb4733
refs/heads/master
2021-01-20T00:42:40.803881
2011-03-13T14:08:22
2011-03-13T14:08:22
32,136,593
0
0
null
null
null
null
UTF-8
C++
false
false
1,189
cpp
#include "StateCarrierApproach.h" #include "..\EnemyCarrier.h" #include "StateIdentifiers.h" #include "ofTypes.h" const float StateCarrierApproach::attackDistance = 100.0; const float StateCarrierApproach::maxSpeed = 1.0; void StateCarrierApproach::initState() { mID = EnemyState::CARRIER_APPROACH; printf("Init Carrier Approach State\n"); } void StateCarrierApproach::enterState() { printf("Enter Carrier Approach State\n"); } void StateCarrierApproach::exitState() { printf("Exit Carrier Approach State\n"); } int StateCarrierApproach::update() { // distance check ofPoint distanceVector = mTarget->getPosition() - mOwnCarrier->getPosition(); float distance = sqrt( distanceVector.x * distanceVector.x + distanceVector.y * distanceVector.y); // check for state change if(distance <= attackDistance) return EnemyState::CARRIER_ATTACK; else { // seek behavior as described by Craig W. Reynolds. ofPoint accelerationVector = (distanceVector/distance)*maxSpeed; accelerationVector -= mOwnCarrier->getSpeed(); mOwnCarrier->accelerateWithVector(accelerationVector); mOwnCarrier->move(); return mID; } }
[ "nightwolve@bb536436-bb54-8cee-38f9-046b9e77f541" ]
[ [ [ 1, 48 ] ] ]
0fee1516f1f5bc74e36b9634700e3a8ca9860b54
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/Menus/GameNetworkProfile.cpp
90d3281c48626f4cdfdc1172bd3b88d210e4d410
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,527
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2007. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Game-side part of Palyer's network profile ------------------------------------------------------------------------- History: - 03/2007: Created by Stas Spivakov *************************************************************************/ #include "StdAfx.h" #include "INetwork.h" #include "GameNetworkProfile.h" #include "MPHub.h" #include "Game.h" #include "GameCVars.h" #include "HUD/HUD.h" #include "HUD/HUDRadar.h" #include "HUD/HUDTextChat.h" static const bool DEBUG_VERBOSE = false; enum EUserInfoKey { eUIK_none, eUIK_nick, eUIK_namespace, eUIK_country }; static TKeyValuePair<EUserInfoKey,const char*> gUserInfoKeys[] = { {eUIK_none,""}, {eUIK_nick,"nick"}, {eUIK_namespace,"namespace"}, {eUIK_country,"country"}, }; struct CGameNetworkProfile::SChatText { struct SChatLine { string text; int id; }; SChatText():m_viewed(false),m_size(1000) {} void AddText(const char* str, int text_id) { m_viewed = false; m_text.push_back(SChatLine()); m_text.back().text = str; m_text.back().id = text_id; while(m_size && m_text.size()>m_size) { int id = m_text.front().id; do { m_text.pop_front(); }while(m_text.front().id == id); } } int m_size; bool m_viewed; std::list<SChatLine> m_text; std::vector<SChatUser> m_chatList; }; struct IStoredSerialize { virtual void Serialize(int& val,const char* name) = 0; virtual void Serialize(float& val, const char* name) = 0; virtual void Serialize(string& val, const char* name) = 0; }; class CStoredBase { public: struct SMetaData { SMetaData(int recid = -1, bool fr = false):recordId(recid),free(fr),locked(false){} int recordId; bool free:1; bool locked:1; }; enum EFieldType { eFT_int, eFT_float, eFT_string }; struct SFieldConfig { SFieldConfig(EFieldType t = eFT_int, const char* n = ""):type(t),name(n){} EFieldType type; const char* name; }; struct SConfigBuilder : public IStoredSerialize { SConfigBuilder(std::vector<SFieldConfig>& cfg):m_cfg(cfg){} virtual void Serialize(int& val,const char* name) { m_cfg.push_back(SFieldConfig(eFT_int,name)); } virtual void Serialize(float& val, const char* name) { m_cfg.push_back(SFieldConfig(eFT_float,name)); } virtual void Serialize(string& val, const char* name) { m_cfg.push_back(SFieldConfig(eFT_string,name)); } std::vector<SFieldConfig>& m_cfg; }; class SReadSerializer : public IStoredSerialize { public: SReadSerializer(int value, int idx):ivalue(value),type(eFT_int),field_idx(idx),cur_field(0){} SReadSerializer(float value, int idx):fvalue(value),type(eFT_float),field_idx(idx),cur_field(0){} SReadSerializer(const char* value, int idx):svalue(value),type(eFT_string),field_idx(idx),cur_field(0){} virtual void Serialize(int& val,const char* name) { if(cur_field == field_idx) { val = ivalue; } cur_field++; } virtual void Serialize(float& val, const char* name) { if(cur_field == field_idx) { val = fvalue; } cur_field++; } virtual void Serialize(string& val, const char* name) { if(cur_field == field_idx) { val = svalue; } cur_field++; } private: int ivalue; float fvalue; const char* svalue; int field_idx; int cur_field; EFieldType type; }; class SWriteSerializer : public IStoredSerialize { public: SWriteSerializer(int idx):field_idx(idx),cur_field(0){} virtual void Serialize(int& val,const char* name) { if(cur_field == field_idx) { ivalue = val; type = eFT_int; } cur_field++; } virtual void Serialize(float& val, const char* name) { if(cur_field == field_idx) { fvalue = val; type = eFT_float; } cur_field++; } virtual void Serialize(string& val, const char* name) { if(cur_field == field_idx) { svalue = val; type = eFT_string; } cur_field++; } const char* GetSValue()const { return svalue; } const int GetIValue()const { return ivalue; } const float GetFValue()const { return fvalue; } private: int ivalue; float fvalue; const char* svalue; int field_idx; int cur_field; EFieldType type; }; CStoredBase() { } template<class T> void InitConfig() { T val; SConfigBuilder bld(m_config); val.Serialize(&bld); } virtual ~CStoredBase() {} std::vector<SFieldConfig> m_config; }; template<class T> class CGameNetworkProfile::TStoredArray : public CStoredBase { private: struct SReader : public CGameNetworkProfile::SStorageQuery, public IStatsReader { SReader(TStoredArray* p,CGameNetworkProfile* pr, const char* table_name):SStorageQuery(pr),m_array(p),m_id(-1),m_table(table_name){} virtual const char* GetTableName() { return m_table; } virtual int GetFieldsNum() { return m_array->m_config.size(); } virtual const char* GetFieldName(int i) { return m_array->m_config[i].name; } virtual void NextRecord(int id) { AddValue(); m_id = id; } virtual void OnValue(int field, const char* val) { SReadSerializer s(val,field); m_value.Serialize(&s); } virtual void OnValue(int field, int val) { SReadSerializer s(val,field); m_value.Serialize(&s); } virtual void OnValue(int field, float val) { SReadSerializer s(val,field); m_value.Serialize(&s); } virtual void End(bool ok) { if(ok) AddValue(); delete this;//we're done } void AddValue() { if(m_id != -1 && m_parent) { m_array->m_array.push_back(std::make_pair(m_value,SMetaData(m_id))); } } T m_value; int m_id; TStoredArray* m_array; const char* m_table; }; struct SWriter : public CGameNetworkProfile::SStorageQuery, public IStatsWriter { SWriter(TStoredArray* p, CGameNetworkProfile* pr, const char* table_name):SStorageQuery(pr),m_array(p),m_curidx(-1),m_processed(0),m_table(table_name) { for(int i=0;i<m_array->m_array.size();++i) { SMetaData& md = m_array->GetMetaData(i); if(!md.free && md.recordId == -1 && !md.locked) { md.locked = true; if(DEBUG_VERBOSE) CryLog("Writing %d",i); m_ids.push_back(i); } } } virtual const char* GetTableName() { return m_table; } virtual int GetFieldsNum() { return m_array->m_config.size(); } virtual const char* GetFieldName(int i) { return m_array->m_config[i].name; } virtual int GetRecordsNum() { return m_ids.size(); } virtual int NextRecord() { ++m_curidx; return -1; } virtual bool GetValue(int field, const char*& val) { if(m_array->m_config[field].type != eFT_string) return false; SWriteSerializer ser(field); m_array->m_array[m_ids[m_curidx]].first.Serialize(&ser); val = ser.GetSValue(); return true; } virtual bool GetValue(int field, int& val) { if(m_array->m_config[field].type != eFT_int) return false; SWriteSerializer ser(field); m_array->m_array[m_ids[m_curidx]].first.Serialize(&ser); val = ser.GetIValue(); return true; } virtual bool GetValue(int field, float& val) { if(m_array->m_config[field].type != eFT_float) return false; SWriteSerializer ser(field); m_array->m_array[m_ids[m_curidx]].first.Serialize(&ser); val = ser.GetFValue(); return true; } //output virtual void OnResult(int idx, int id, bool success) { m_processed++; if(DEBUG_VERBOSE) CryLog("Written %s %d, id:%x",success?"ok":"failed",m_ids[idx],id); if(m_parent) { m_array->GetMetaData(m_ids[idx]).locked = false; if(success) { m_array->GetMetaData(m_ids[idx]).recordId = id; } } } virtual void End(bool ok) { delete this; } int m_processed; int m_curidx; std::vector<int> m_ids; TStoredArray* m_array; const char* m_table; }; struct SDeleter : public CGameNetworkProfile::SStorageQuery, public IStatsDeleter { SDeleter(TStoredArray* p, CGameNetworkProfile* pr, const char* table_name):SStorageQuery(pr),m_array(p),cur_idx(0),processed(0),m_table(table_name) { for(int i=0;i<m_array->m_array.size();++i) { SMetaData& md = m_array->GetMetaData(i); if(md.free && md.recordId != -1 && !md.locked) { md.locked = true; if(DEBUG_VERBOSE) CryLog("Deleting %d, id:%x",i,md.recordId); ids.push_back(i); } } } virtual const char* GetTableName() { return m_table; } virtual int GetRecordsNum() { return ids.size(); } virtual int NextRecord() { return m_array->GetMetaData(ids[cur_idx++]).recordId; } virtual void OnResult(int idx, int id, bool success) { processed++; if(DEBUG_VERBOSE) CryLog("Deleted %s %d, id:%x",success?"ok":"failed",ids[idx],id); if(m_parent) { m_array->GetMetaData(ids[idx]).locked = false; if(success) m_array->GetMetaData(ids[idx]).recordId = -1; } } virtual void End(bool success) { delete this;//we're done } std::vector<int> ids; int cur_idx; int processed; TStoredArray* m_array; const char* m_table; }; SMetaData& GetMetaData(int idx) { return m_array[idx].second; } public: TStoredArray():m_numFree(0) { InitConfig<T>(); } void push(const T& val) { if(m_numFree) { for(int i=0;i<m_array.size();++i) { if(m_array[i].second.free) { m_array[i].first = val; m_array[i].second.free = false; m_numFree--; return; } } } m_array.push_back(std::make_pair(val,SMetaData())); } void erase(int idx) { assert(idx<size()); int r_idx = 0; for(int i=0;i<m_array.size();++i) { if(m_array[i].second.free) continue; if(r_idx == idx) { m_array[i].first = T(); m_array[i].second.free = true; m_numFree++; return; } ++r_idx; } assert(false); } bool empty()const { return m_array.empty() || m_array.size() == m_numFree; } int size()const { return m_array.size()-m_numFree; } const T& operator[](int idx)const { assert(idx<size()); int r_idx = 0; for(int i=0;i<m_array.size();++i) { if(m_array[i].second.free) continue; if(r_idx == idx) { return m_array[i].first; } ++r_idx; } assert(false); return m_array[0].first; } void clear() { m_array.resize(0); m_numFree = 0; } void LoadRecords(CGameNetworkProfile* np, const char* table_name) { np->m_profile->ReadStats(new SReader(this,np,table_name)); } void SaveRecords(CGameNetworkProfile* np, const char* table_name) { if(m_numFree) { for(int i=0;i<m_array.size();++i) if(GetMetaData(i).free && !GetMetaData(i).locked && GetMetaData(i).recordId != -1) { np->m_profile->DeleteStats(new SDeleter(this, np, table_name)); break; } } for(int i=0;i<m_array.size();++i) if(!GetMetaData(i).free && !GetMetaData(i).locked && GetMetaData(i).recordId == -1) { np->m_profile->WriteStats(new SWriter(this, np, table_name)); } } std::vector<std::pair<T,SMetaData> > m_array; int m_numFree; }; void SStoredUserInfo::Serialize(struct IStoredSerialize* ser) { ser->Serialize(m_kills,"Kills"); ser->Serialize(m_deaths,"Deaths"); ser->Serialize(m_shots,"Shots"); ser->Serialize(m_hits,"Hits"); ser->Serialize(m_played,"Played"); ser->Serialize(m_mode,"FavoriteMode"); ser->Serialize(m_map,"FavoriteMap"); ser->Serialize(m_weapon,"FavoriteWeapon"); ser->Serialize(m_vehicle,"FavoriteVehicle"); ser->Serialize(m_suitmode,"FavoriteSuitMode"); } struct CGameNetworkProfile::SUserInfoReader : public CStoredBase { struct SReader : public CGameNetworkProfile::SStorageQuery, public IStatsReader { SReader(SUserInfoReader* r,CGameNetworkProfile* pr, const char* table_name, int id):SStorageQuery(pr),m_reader(r),m_id(-1),m_table(table_name),m_profile(id){} virtual const char* GetTableName() { return m_table; } virtual int GetFieldsNum() { return m_reader->m_config.size(); } virtual const char* GetFieldName(int i) { return m_reader->m_config[i].name; } virtual void NextRecord(int id) { AddValue(); m_id = id; } virtual void OnValue(int field, const char* val) { SReadSerializer s(val,field); m_value.Serialize(&s); } virtual void OnValue(int field, int val) { SReadSerializer s(val,field); m_value.Serialize(&s); } virtual void OnValue(int field, float val) { SReadSerializer s(val,field); m_value.Serialize(&s); } virtual void End(bool ok) { if(ok) AddValue(); delete this;//we're done } void AddValue() { if(m_id != -1 && m_parent) { m_reader->OnValue(m_profile, m_value); } } SStoredUserInfo m_value; int m_id; SUserInfoReader* m_reader; const char* m_table; int m_profile; }; SUserInfoReader(CGameNetworkProfile *pr):m_profile(pr) { InitConfig<SStoredUserInfo>(); } void ReadInfo(int profileId) { static string m_table; if(m_table.empty()) { m_table.Format("PlayerStats_v%d",g_pGame->GetIGameFramework()->GetIGameStatsConfig()->GetStatsVersion()); } m_profile->m_profile->ReadStats(profileId, new SReader(this, m_profile, m_table, profileId)); } void OnValue(int id, SStoredUserInfo& info) { if(DEBUG_VERBOSE) CryLog("Info for %d read successfully - kills %d", id, info.m_kills); IGameStatsConfig* config = g_pGame->GetIGameFramework()->GetIGameStatsConfig(); SUserStats stats; stats.m_accuracy = info.m_shots?(info.m_hits/float(info.m_shots)):0.0f; stats.m_deaths = info.m_deaths; stats.m_kills = info.m_kills; stats.m_played = info.m_played; stats.m_killsPerMinute = info.m_played?(info.m_kills/(float)info.m_played):0; if(int mod = config->GetCategoryMod("mode")) { stats.m_gameMode = config->GetValueNameByCode("mode",info.m_mode%mod); } if(int mod = config->GetCategoryMod("map")) { stats.m_map = config->GetValueNameByCode("map",info.m_map%mod); } if(int mod = config->GetCategoryMod("weapon")) { stats.m_weapon = config->GetValueNameByCode("weapon",info.m_weapon%mod); } if(int mod = config->GetCategoryMod("vehicle")) { stats.m_vehicle = config->GetValueNameByCode("vehicle",info.m_vehicle%mod); } if(int mod = config->GetCategoryMod("suit_mode")) { stats.m_suitMode = config->GetValueNameByCode("suit_mode",info.m_suitmode%mod); } m_profile->OnUserStats(id, stats, eUIS_backend); } CGameNetworkProfile *m_profile; }; static TKeyValuePair<ENetworkProfileError,const char*> gProfileErrors[] = { {eNPE_ok,""}, {eNPE_connectFailed,"@ui_menu_connectFailed"}, {eNPE_disconnected,"@ui_menu_disconnected"}, {eNPE_loginFailed,"@ui_menu_loginFailed"}, {eNPE_loginTimeout,"@ui_menu_loginTimeout"}, {eNPE_anotherLogin,"@ui_menu_anotherLogin"}, {eNPE_nickTaken,"@ui_menu_nickTaken"}, {eNPE_registerAccountError,"@ui_menu_registerAccountError"}, {eNPE_registerGeneric,"@ui_menu_registerGeneric"}, {eNPE_nickTooLong,"@ui_menu_nickTooLong"}, {eNPE_nickFirstNumber,"@ui_menu_nickFirstNumber"}, {eNPE_nickSlash,"@ui_menu_nickSlash"}, {eNPE_nickFirstSpecial,"@ui_menu_nickFirstSpecial"}, {eNPE_nickNoSpaces,"@ui_menu_nickNoSpaces"}, {eNPE_nickEmpty,"@ui_menu_nickEmpty"}, {eNPE_profileEmpty,"@ui_menu_profileEmpty"}, {eNPE_passTooLong,"@ui_menu_passTooLong"}, {eNPE_passEmpty,"@ui_menu_passEmpty"}, {eNPE_mailTooLong,"@ui_menu_mailTooLong"}, {eNPE_mailEmpty,"@ui_menu_mailEmpty"} }; struct CGameNetworkProfile::SBuddies : public INetworkProfileListener { enum EQueryReason { eQR_addBuddy, eQR_showInfo, eQR_addIgnore, eQR_stopIgnore, eQR_getStats, eQR_buddyRequest, }; struct SPendingOperation { SPendingOperation(){} SPendingOperation(EQueryReason t):m_id(0),m_type(t) {} string m_nick; int m_id; string m_param; EQueryReason m_type; }; struct SBuddyRequest { SBuddyRequest(const string& n, const string& m):nick(n),message(m){} string nick; string message; }; struct SIgnoredProfile { int id; string nick; void Serialize(IStoredSerialize* ser) { ser->Serialize(id,"profile"); ser->Serialize(nick,"nick"); } }; typedef std::map<int, SBuddyRequest> TBuddyRequestsMap; SBuddies(CGameNetworkProfile* p):m_parent(p),m_textId(0),m_ui(0) {} void AddNick(const char* nick){} void UpdateFriend(int id, const char* nick, EUserStatus s, const char* location, bool foreign) { SChatUser *u = 0; for(int i=0;i<m_buddyList.size();++i) { if(m_buddyList[i].m_id == id) { u = &m_buddyList[i]; break; } } bool added = false; if(!u) { m_buddyList.push_back(SChatUser()); u = &m_buddyList.back(); added = true; } u->m_nick = nick; u->m_status = s; u->m_id = id; u->m_location = location; u->m_foreign = foreign; //updated user with id if(m_ui) { if(added) m_ui->AddBuddy(*u); else m_ui->UpdateBuddy(*u); } } void RemoveFriend(int id) { for(int i=0;i<m_buddyList.size();++i) { if(m_buddyList[i].m_id == id) { //remove if(m_ui) m_ui->RemoveBuddy(id); m_buddyList.erase(m_buddyList.begin()+i); break; } } } void AddIgnore(int id, const char* nick) { SIgnoredProfile ip; ip.id = id; ip.nick = nick; m_ignoreList.push(ip); SaveIgnoreList(); if(m_ui) { SChatUser u; u.m_id = id; u.m_nick = nick; m_ui->AddIgnore(u); } } void RemoveIgnore(int id) { for(int i=0;i<m_ignoreList.size();++i) { if(m_ignoreList[i].id == id) { m_ignoreList.erase(i); if(m_ui) m_ui->RemoveIgnore(id); SaveIgnoreList(); break; } } } void OnFriendRequest(int id, const char* message) { if(IsIgnoring(id)) { m_parent->m_profile->AuthFriend(id,false); return; } SPendingOperation op(eQR_buddyRequest); op.m_id = id; op.m_param = message; m_operations.push_back(op); //if(!CheckId(id)) - not checking because there is a lag about having buddy added - omitted for possibility of auto add m_parent->m_profile->GetUserNick(id); } void OnMessage(int id, const char* message) { if(IsIgnoring(id)) return; TChatTextMap::iterator it = m_buddyChats.find(id); if(it==m_buddyChats.end()) it = m_buddyChats.insert(std::make_pair(id,SChatText())).first; m_textId++; it->second.AddText(message,m_textId); if(m_ui) m_ui->OnMessage(id,message); if(m_parent->m_hub->IsIngame() && g_pGame->GetCVars()->g_buddyMessagesIngame) { if(CHUDTextChat *pChat = SAFE_HUD_FUNC_RET(GetMPChat())) { const char* name = ""; for(int i=0;i<m_buddyList.size();++i) { if(m_buddyList[i].m_id == id) { name = m_buddyList[i].m_nick.c_str(); break; } } pChat->AddChatMessage(string().Format("From [%s] :",name), message, 0, false); } } } void LoginResult(ENetworkProfileError res, const char* descr, int id, const char* nick) { if(res == eNPE_ok) { m_parent->OnLoggedIn(id, nick); } else { m_parent->m_loggingIn = false; const char* err = VALUE_BY_KEY(res,gProfileErrors); m_parent->m_hub->OnLoginFailed(err); } } void OnError(ENetworkProfileError res, const char* descr) { bool logoff = false; switch(res) { case eNPE_connectFailed: case eNPE_disconnected: case eNPE_anotherLogin: { const char* err = VALUE_BY_KEY(res,gProfileErrors); m_parent->m_hub->ShowError(err,true); logoff = true; } break; } if(m_parent->m_loggingIn && m_parent->m_hub) m_parent->m_hub->CloseLoadingDlg(); if(logoff && m_parent->m_hub) m_parent->m_hub->DoLogoff(); } void OnProfileInfo(int id, const char* key, const char* value) { TUserInfoMap::iterator it = m_infoCache.find(id); if(it == m_infoCache.end()) { it = m_infoCache.insert(std::make_pair(id,SUserInfo())).first; } SUserInfo &u = it->second; EUserInfoKey k = KEY_BY_VALUE(string(key),gUserInfoKeys); switch(k) { case eUIK_nick: u.m_nick = value; break; case eUIK_namespace: u.m_foreignName = !strcmp(value,"foreign"); break; case eUIK_country: u.m_country = value; if(id == m_parent->m_profileId) m_parent->m_country = value; break; default:; } } virtual void OnProfileComplete(int id) { TUserInfoMap::iterator iit = m_infoCache.find(id); if(iit == m_infoCache.end()) return; if(m_ui) m_ui->ProfileInfo(id,iit->second); } virtual void OnSearchResult(int id, const char* nick) { if(m_ui) m_ui->SearchResult(id,nick); } virtual void OnSearchComplete() { if(m_ui && !m_uisearch.empty()) { m_uisearch.resize(0); m_ui->SearchCompleted(); } } virtual void OnUserId(const char* nick, int id) { for(int i=0;i<m_operations.size();++i) { if(m_operations[i].m_nick == nick) { m_operations[i].m_id = id; ExecuteOperation(i); break; } } } virtual void OnUserNick(int id, const char* nick, bool foreign_name) { if(m_infoCache.find(id) == m_infoCache.end()) { OnProfileInfo(id,"namespace",foreign_name?"foreign":"home"); OnProfileInfo(id,"nick",nick); } for(int i=0;i<m_operations.size();++i) { if(m_operations[i].m_id == id && m_operations[i].m_nick.empty()) { m_operations[i].m_nick = nick; ExecuteOperation(i); break; } } } bool GetUserInfo(int id, SUserInfo& info) { TUserInfoMap::iterator it = m_infoCache.find(id); if(it != m_infoCache.end()) { if(!it->second.m_basic)//we have extended info { if(it->second.m_expires < gEnv->pTimer->GetFrameStartTime()) { if(DEBUG_VERBOSE) CryLog("Stats for %d expired on %d",it->first, uint32(it->second.m_expires.GetValue()&0xFFFFFFFF)); it->second.m_basic = true;//clear it } else { info = it->second; return true; } } } return false; } bool GetUserInfo(const char* nick, SUserInfo& info, int& id) { for(TUserInfoMap::iterator it = m_infoCache.begin(),eit = m_infoCache.end(); it!=eit; ++it) { if(it->second.m_nick == nick && !it->second.m_foreignName) { if(!it->second.m_basic)//we have extended info { if(it->second.m_expires < gEnv->pTimer->GetFrameStartTime()) { if(DEBUG_VERBOSE) CryLog("Stats for %d expired on %d",it->first, uint32(it->second.m_expires.GetValue()&0xFFFFFFFF)); it->second.m_basic = true;//clear it } else { id = it->first; info = it->second; return true; } } } } return false; } void ExecuteOperation(int idx) { assert(0 <= idx && idx < m_operations.size()); SPendingOperation &o = m_operations[idx]; assert(!o.m_nick.empty() && o.m_id); switch(o.m_type) { case eQR_addBuddy: m_parent->m_profile->AddFriend(o.m_id,o.m_param); break; case eQR_showInfo: m_parent->m_profile->GetProfileInfo(o.m_id); break; case eQR_addIgnore: AddIgnore(o.m_id,o.m_nick); break; case eQR_stopIgnore: RemoveIgnore(o.m_id); break; case eQR_getStats: m_parent->m_profile->GetProfileInfo(o.m_id); m_parent->m_infoReader->ReadInfo(o.m_id); break; case eQR_buddyRequest: { if(!strncmp(o.m_param.c_str(), AUTO_INVITE_TEXT, strlen(AUTO_INVITE_TEXT)))//this may be autogenerated { bool buddy = false; for(int i=0;i<m_buddyList.size();++i) if(m_buddyList[i].m_id == o.m_id) { buddy = true; break; } if(buddy) { m_parent->m_profile->AuthFriend(o.m_id,true); return; } else { o.m_param = "@ui_menu_auto_invite"; } } m_requests.insert(std::make_pair(o.m_id,SBuddyRequest(o.m_nick,o.m_param))); if(m_ui) m_ui->OnAuthRequest(o.m_id,o.m_nick,o.m_param); } break; } m_operations.erase(m_operations.begin()+idx); } void Accept(int id, bool accept) { TBuddyRequestsMap::iterator it = m_requests.find(id); if(it!= m_requests.end()) { m_parent->m_profile->AuthFriend(it->first,accept); m_requests.erase(it); } } void Request(const char* nick, const char* reason) { SPendingOperation op(eQR_addBuddy); op.m_nick = nick; op.m_param = reason; m_operations.push_back(op); if(!CheckNick(nick)) m_parent->m_profile->GetUserId(nick); } void Request(int id, const char* reason) { m_parent->m_profile->AddFriend(id,reason); } bool CheckNick(const char* nick) { for(TUserInfoMap::iterator it = m_infoCache.begin();it!=m_infoCache.end();++it) { if(it->second.m_nick == nick) { OnUserId(nick,it->first); return true; } } return false; } bool CheckId(int id) { TUserInfoMap::iterator it = m_infoCache.find(id); if(it!=m_infoCache.end()) { OnUserNick(id,it->second.m_nick,it->second.m_foreignName); return true; } return false; } void Remove(const char* nick) { for(int i=0;i<m_buddyList.size();++i) { if(m_buddyList[i].m_nick == nick) { m_parent->m_profile->RemoveFriend(m_buddyList[i].m_id,false); break; } } } void Ignore(const char* nick) { if(!CanIgnore(nick)) return; Remove(nick); SPendingOperation op(eQR_addIgnore); op.m_nick = nick; m_operations.push_back(op); if(!CheckNick(nick)) m_parent->m_profile->GetUserId(nick); } void QueryUserInfo(const char* nick) { SPendingOperation op(eQR_getStats); op.m_nick = nick; m_operations.push_back(op); if(!CheckNick(nick)) m_parent->m_profile->GetUserId(nick); } void QueryUserInfo(int id) { SPendingOperation op(eQR_getStats); op.m_id = id; m_operations.push_back(op); if(!CheckId(id)) m_parent->m_profile->GetUserNick(id); } void StopIgnore(const char* nick) { SPendingOperation op(eQR_stopIgnore); op.m_nick = nick; m_operations.push_back(op); if(!CheckNick(nick)) m_parent->m_profile->GetUserId(nick); } bool IsIgnoring(int id) { for(int i=0;i<m_ignoreList.size();++i) { if(m_ignoreList[i].id == id) return true; } return false; } bool IsIgnoring(const char* nick) { for(int i=0;i<m_ignoreList.size();++i) { if(m_ignoreList[i].nick == nick) return true; } return false; } void SendUserMessage(int id, const char* message) { m_parent->m_profile->SendFriendMessage(id,message); } void OnUserStats(int id, const SUserStats& stats, EUserInfoSource src) { TUserInfoMap::iterator it = m_infoCache.find(id); if(it != m_infoCache.end()) { it->second.m_stats = stats; it->second.m_source = src; it->second.m_basic = false; if(src == eUIS_backend) it->second.m_expires = gEnv->pTimer->GetFrameStartTime() + 10*60.0f;//10 minutes cache else it->second.m_expires = gEnv->pTimer->GetFrameStartTime() + 20*60.0f;//20 minutes for chat users if(DEBUG_VERBOSE) CryLog("Stats for %d cached on %d",it->first, uint32(it->second.m_expires.GetValue()&0xFFFFFFFF)); if(m_ui) m_ui->ProfileInfo(id, it->second); } else { it = m_infoCache.insert(std::make_pair(id,SUserInfo())).first; it->second.m_stats = stats; if(m_ui) m_ui->ProfileInfo(id, it->second); } } void ReadIgnoreList() { m_ignoreList.LoadRecords(m_parent,"ignorelist"); } void SaveIgnoreList() { m_ignoreList.SaveRecords(m_parent,"ignorelist"); } bool CanInvite(const char* nick) { if(!strcmp(nick,"ChatMonitor")) return false; for(TUserInfoMap::iterator it = m_infoCache.begin();it!=m_infoCache.end();++it) { if(it->second.m_nick == nick) { return CanInvite(it->first); } } return true; } bool CanInvite(int id) { for(int i=0;i<m_buddyList.size();++i) if(m_buddyList[i].m_id == id) return false; return true; } bool CanIgnore(const char* nick) { for(int i=0;i<m_ignoreList.size();++i) { if(m_ignoreList[i].nick == nick) { return false; } } return true; } bool CanIgnore(int id) { for(int i=0;i<m_ignoreList.size();++i) { if(m_ignoreList[i].id == id) { return false; } } return true; } void UIActivated(INProfileUI* ui) { m_ui = ui; if(!m_ui) return; for(int i=0;i<m_buddyList.size();++i) { m_ui->AddBuddy(m_buddyList[i]); } for(int i=0;i<m_ignoreList.size();++i) { SChatUser u; u.m_id = m_ignoreList[i].id; u.m_nick = m_ignoreList[i].nick; m_ui->AddIgnore(u); } } std::vector<SChatUser> m_buddyList; //std::vector<SIgnoredProfile> m_ignoreList; TStoredArray<SIgnoredProfile> m_ignoreList; TUserInfoMap m_infoCache; TBuddyRequestsMap m_requests; TChatTextMap m_buddyChats; std::auto_ptr<SChatText> m_globalChat; std::vector<SPendingOperation> m_operations; int m_textId; CGameNetworkProfile* m_parent; INProfileUI* m_ui; string m_uisearch; }; void SStoredServer::Serialize(struct IStoredSerialize* ser) { ser->Serialize(ip,"ip"); ser->Serialize(port,"port"); } struct CGameNetworkProfile::SStoredServerLists { SStoredServerLists(CGameNetworkProfile* p): m_parent(p) { } ~SStoredServerLists() { } void ReadLists() { m_favorites.LoadRecords(m_parent,"favorites"); m_recent.LoadRecords(m_parent,"recent"); } void SaveFavoritesList() { m_favorites.SaveRecords(m_parent,"favorites"); } void SaveRecentList() { m_recent.SaveRecords(m_parent,"recent"); } void UIActivated(INProfileUI* ui) { m_ui = ui; if(!m_ui) return; for(int i=0;i<m_favorites.size();++i) m_ui->AddFavoriteServer(m_favorites[i].ip,m_favorites[i].port); for(int i=0;i<m_recent.size();++i) m_ui->AddRecentServer(m_recent[i].ip,m_recent[i].port); } void AddFavoriteServer(uint ip, ushort port) { SStoredServer s; s.ip = ip; s.port = port; m_favorites.push(s); SaveFavoritesList(); } void RemoveFavoriteServer(uint ip, ushort port) { for(int i=0;i<m_favorites.size();++i) { if(m_favorites[i].ip==ip && m_favorites[i].port==port) { m_favorites.erase(i); SaveFavoritesList(); break; } } } void AddRecentServer(uint ip, ushort port) { SStoredServer s; s.ip = ip; s.port = port; m_recent.push(s); if(m_recent.size()>20) m_recent.erase(0); SaveRecentList(); } TStoredArray<SStoredServer> m_favorites; TStoredArray<SStoredServer> m_recent; INProfileUI* m_ui; CGameNetworkProfile* m_parent; }; CGameNetworkProfile::CGameNetworkProfile(CMPHub* hub): m_hub(hub),m_loggingIn(false),m_profileId(-1) { INetworkService *serv = gEnv->pNetwork->GetService("GameSpy"); if(serv) { m_profile = serv->GetNetworkProfile(); m_infoReader.reset(new SUserInfoReader(this)); } else { m_profile = 0; } } CGameNetworkProfile::~CGameNetworkProfile() { if(m_profile) m_profile->RemoveListener(m_buddies.get()); } void CGameNetworkProfile::Login(const char* login, const char* password) { m_login = login; m_password = password; m_loggingIn = true; m_buddies.reset(new SBuddies(this)); m_stroredServers.reset(new SStoredServerLists(this)); m_profile->AddListener(m_buddies.get()); m_profile->Login(login,password); } void CGameNetworkProfile::LoginProfile(const char* email, const char* password, const char* profile) { m_login = profile; m_password = password; m_loggingIn = true; m_buddies.reset(new SBuddies(this)); m_stroredServers.reset(new SStoredServerLists(this)); m_profile->AddListener(m_buddies.get()); m_profile->LoginProfile(email,password,profile); } void CGameNetworkProfile::Register(const char* login, const char* email, const char* pass, const char* country, SRegisterDayOfBirth dob) { assert(m_profile); m_login = login; m_password = pass; m_loggingIn = true; m_buddies.reset(new SBuddies(this)); m_stroredServers.reset(new SStoredServerLists(this)); m_profile->AddListener(m_buddies.get()); m_profile->Register(login,email,pass,country, dob); } void CGameNetworkProfile::Logoff() { assert(m_profile); //cancel pending storage queries.. //TODO: wait for important queries to finish. CleanUpQueries(); m_loggingIn = false; m_profile->Logoff(); m_profile->RemoveListener(m_buddies.get()); m_buddies.reset(0); m_stroredServers.reset(0); } void CGameNetworkProfile::AcceptBuddy(int id, bool accept) { m_buddies->Accept(id,accept); } void CGameNetworkProfile::RequestBuddy(const char* nick, const char* reason) { m_buddies->Request(nick, reason); } void CGameNetworkProfile::RequestBuddy(int id, const char* reason) { m_buddies->Request(id,reason); } void CGameNetworkProfile::RemoveBuddy(const char* nick) { m_buddies->Remove(nick); } void CGameNetworkProfile::AddIgnore(const char* nick) { m_buddies->Ignore(nick); } void CGameNetworkProfile::StopIgnore(const char* nick) { m_buddies->StopIgnore(nick); } void CGameNetworkProfile::QueryUserInfo(const char* nick) { m_buddies->QueryUserInfo(nick); } void CGameNetworkProfile::QueryUserInfo(int id) { //m_infoReader->ReadInfo(id); m_buddies->QueryUserInfo(id); } void CGameNetworkProfile::SendBuddyMessage(int id, const char* message) { m_buddies->SendUserMessage(id,message); } void CGameNetworkProfile::InitUI(INProfileUI* a) { if(m_buddies.get()) m_buddies->UIActivated(a); if(m_stroredServers.get()) m_stroredServers->UIActivated(a); } void CGameNetworkProfile::DestroyUI() { if(m_buddies.get()) m_buddies->m_ui = 0; } void CGameNetworkProfile::AddFavoriteServer(uint ip, ushort port) { m_stroredServers->AddFavoriteServer(ip,port); } void CGameNetworkProfile::RemoveFavoriteServer(uint ip, ushort port) { m_stroredServers->RemoveFavoriteServer(ip,port); } void CGameNetworkProfile::AddRecentServer(uint ip, ushort port) { m_stroredServers->AddRecentServer(ip,port); } bool CGameNetworkProfile::IsLoggedIn()const { return m_profile->IsLoggedIn() && !m_loggingIn; } bool CGameNetworkProfile::IsLoggingIn()const { return m_loggingIn; } const char* CGameNetworkProfile::GetLogin()const { return m_login.c_str(); } const char* CGameNetworkProfile::GetPassword()const { return m_password.c_str(); } const char* CGameNetworkProfile::GetCountry()const { return m_country.c_str(); } const int CGameNetworkProfile::GetProfileId()const { return m_profileId; } void CGameNetworkProfile::SearchUsers(const char* nick) { m_buddies->m_uisearch=nick; if(m_profile) m_profile->SearchFriends(nick); } bool CGameNetworkProfile::CanInvite(const char* nick) { if(!stricmp(m_login.c_str(),nick)) return false; return m_buddies->CanInvite(nick); } bool CGameNetworkProfile::CanIgnore(const char* nick) { if(!stricmp(m_login.c_str(),nick)) return false; return m_buddies->CanIgnore(nick); } bool CGameNetworkProfile::CanInvite(int id) { if(m_profileId == id) return false; return m_buddies->CanInvite(id); } bool CGameNetworkProfile::CanIgnore(int id) { if(m_profileId == id) return false; return m_buddies->CanIgnore(id); } bool CGameNetworkProfile::GetUserInfo(int id, SUserInfo& info) { return m_buddies->GetUserInfo(id, info); } bool CGameNetworkProfile::GetUserInfo(const char* nick, SUserInfo& info, int& id) { return m_buddies->GetUserInfo(nick, info, id); } bool CGameNetworkProfile::IsIgnored(const char* nick) { if(!stricmp(m_login.c_str(),nick)) return false; return m_buddies->IsIgnoring(nick); } void CGameNetworkProfile::SetPlayingStatus(uint ip, ushort port, ushort publicport, const char* game_type) { string loc; loc.Format("%d.%d.%d.%d:%d/?type=game&queryport=%d&game=%s",ip&0xFF,(ip>>8)&0xFF,(ip>>16)&0xFF,(ip>>24)&0xFF,port,publicport,game_type); if(m_profile) m_profile->SetStatus(eUS_playing,loc); } void CGameNetworkProfile::SetChattingStatus() { assert(m_profile); if(m_profile) m_profile->SetStatus(eUS_chatting,"/?chatting"); } void CGameNetworkProfile::OnUserStats(int id, const SUserStats& stats, EUserInfoSource src, const char* country) { m_buddies->OnUserStats(id, stats, src); if(strlen(country)) m_buddies->OnProfileInfo(id, "country", country); if(id == m_profileId)//my stats m_stats = stats; } void CGameNetworkProfile::OnUserNick(int profile, const char* user) { m_buddies->OnUserNick(profile, user, false); } void CGameNetworkProfile::OnLoggedIn(int id, const char* nick) { m_profileId = id; m_login = nick; m_stroredServers->ReadLists(); m_buddies->ReadIgnoreList(); m_infoReader->ReadInfo(m_profileId); if(m_profile) m_profile->SetStatus(eUS_online,""); } void CGameNetworkProfile::OnEndQuery() { if(m_queries.empty() && m_loggingIn) { m_loggingIn = false; m_hub->OnLoginSuccess(m_login); } } void CGameNetworkProfile::RetrievePassword(const char *email) { if(m_profile) m_profile->RetrievePassword(email); } void CGameNetworkProfile::CleanUpQueries() { for(int i=0;i<m_queries.size();++i) m_queries[i]->m_parent = 0; } bool CGameNetworkProfile::IsDead() const { return m_profile == 0; } const SUserStats& CGameNetworkProfile::GetMyStats()const { return m_stats; } bool CGameNetworkProfile::GetFavoriteServers(std::vector<SStoredServer>& svr_list) { if(m_profile && m_profile->IsLoggedIn()) { for(int i=0;i<m_stroredServers->m_favorites.size();++i) svr_list.push_back(m_stroredServers->m_favorites[i]); return true; } return false; }
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 24 ], [ 26, 30 ], [ 33, 38 ], [ 40, 72 ], [ 704, 729 ], [ 731, 739 ], [ 745, 746 ], [ 748, 753 ], [ 755, 775 ], [ 777, 803 ], [ 808, 809 ], [ 811, 825 ], [ 827, 836 ], [ 839, 839 ], [ 849, 866 ], [ 868, 877 ], [ 879, 890 ], [ 895, 899 ], [ 919, 934 ], [ 938, 939 ], [ 942, 943 ], [ 945, 983 ], [ 985, 985 ], [ 992, 1002 ], [ 1052, 1073 ], [ 1075, 1076 ], [ 1101, 1148 ], [ 1150, 1168 ], [ 1172, 1180 ], [ 1182, 1189 ], [ 1191, 1232 ], [ 1260, 1261 ], [ 1263, 1266 ], [ 1268, 1336 ], [ 1339, 1354 ], [ 1356, 1356 ], [ 1360, 1360 ], [ 1363, 1374 ], [ 1377, 1378 ], [ 1389, 1404 ], [ 1407, 1414 ], [ 1417, 1426 ], [ 1431, 1432 ], [ 1436, 1436 ], [ 1438, 1440 ], [ 1442, 1446 ], [ 1448, 1463 ], [ 1466, 1471 ], [ 1473, 1473 ], [ 1486, 1486 ], [ 1489, 1491 ], [ 1493, 1502 ], [ 1504, 1539 ], [ 1541, 1541 ], [ 1543, 1544 ], [ 1546, 1546 ], [ 1549, 1586 ], [ 1613, 1617 ], [ 1620, 1649 ], [ 1667, 1670 ], [ 1674, 1677 ], [ 1695, 1702 ], [ 1723, 1728 ], [ 1750, 1750 ] ], [ [ 25, 25 ], [ 31, 32 ], [ 39, 39 ], [ 73, 703 ], [ 730, 730 ], [ 740, 744 ], [ 747, 747 ], [ 754, 754 ], [ 776, 776 ], [ 804, 807 ], [ 810, 810 ], [ 826, 826 ], [ 837, 838 ], [ 840, 848 ], [ 867, 867 ], [ 878, 878 ], [ 891, 894 ], [ 900, 918 ], [ 935, 937 ], [ 940, 941 ], [ 944, 944 ], [ 984, 984 ], [ 986, 991 ], [ 1003, 1051 ], [ 1074, 1074 ], [ 1077, 1100 ], [ 1149, 1149 ], [ 1169, 1171 ], [ 1181, 1181 ], [ 1190, 1190 ], [ 1233, 1259 ], [ 1262, 1262 ], [ 1267, 1267 ], [ 1337, 1338 ], [ 1355, 1355 ], [ 1357, 1359 ], [ 1361, 1362 ], [ 1375, 1376 ], [ 1379, 1388 ], [ 1405, 1406 ], [ 1415, 1416 ], [ 1427, 1430 ], [ 1433, 1435 ], [ 1437, 1437 ], [ 1441, 1441 ], [ 1447, 1447 ], [ 1464, 1465 ], [ 1472, 1472 ], [ 1474, 1485 ], [ 1487, 1488 ], [ 1492, 1492 ], [ 1503, 1503 ], [ 1540, 1540 ], [ 1542, 1542 ], [ 1545, 1545 ], [ 1547, 1548 ], [ 1587, 1612 ], [ 1618, 1619 ], [ 1650, 1666 ], [ 1671, 1673 ], [ 1678, 1694 ], [ 1703, 1722 ], [ 1729, 1749 ] ] ]
67f213646c96d8113db18bcf6551e341854a9fee
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPEdit.h
2e74af23731b71bb80bd9bebfae5f6c45ff4b79a
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
3,988
h
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* #if !defined(AFX_BCGPEDIT_H__A7B40464_1C05_4981_A5F2_E21D74058A09__INCLUDED_) #define AFX_BCGPEDIT_H__A7B40464_1C05_4981_A5F2_E21D74058A09__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // BCGPEdit.h : header file // #include "BCGCBPro.h" class CBCGPCalculatorPopup; class CBCGPCalculator; ///////////////////////////////////////////////////////////////////////////// // CBCGPEdit window class BCGCBPRODLLEXPORT CBCGPEdit : public CEdit { DECLARE_DYNAMIC(CBCGPEdit) friend class CBCGPCalculator; // Construction public: CBCGPEdit(); // Attributes public: enum BrowseMode { BrowseMode_None, BrowseMode_Default, BrowseMode_Calculator, BrowseMode_File, BrowseMode_Folder, }; CBCGPEdit::BrowseMode GetMode () const { return m_Mode; } BOOL m_bVisualManagerStyle; BOOL m_bOnGlass; protected: CRect m_rectBtn; BOOL m_bIsButtonPressed; BOOL m_bIsButtonHighlighted; BOOL m_bIsButtonCaptured; BrowseMode m_Mode; CImageList m_ImageBrowse; BOOL m_bDefaultImage; CSize m_sizeImage; CString m_strLabel; CString m_strDefFileExt; CString m_strFileFilter; int m_nBrowseButtonWidth; CBCGPCalculatorPopup* m_pCalcPopup; CStringList m_lstCalcAdditionalCommands; // Operations public: void EnableBrowseButton (BOOL bEnable = TRUE, LPCTSTR szLabel = _T("...")); void EnableFileBrowseButton (LPCTSTR lpszDefExt = NULL, LPCTSTR lpszFilter = NULL); void EnableFolderBrowseButton (); void EnableCalculatorButton (const CStringList* plstAdditionalCommands = NULL); void SetBrowseButtonImage (HICON hIcon, BOOL bAutoDestroy = TRUE); void SetBrowseButtonImage (HBITMAP hBitmap, BOOL bAutoDestroy = TRUE); void SetBrowseButtonImage (UINT uiBmpResId); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPEdit) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //}}AFX_VIRTUAL virtual void OnBrowse (); virtual void OnDrawBrowseButton (CDC* pDC, CRect rect, BOOL bIsButtonPressed, BOOL bIsButtonHot); virtual void OnChangeLayout (); virtual void OnAfterUpdate (); virtual BOOL FilterCalcKey (int nChar); virtual void OnCalculatorUserCommand (CBCGPCalculator* pCalculator, UINT uiCmd); // Implementation public: virtual ~CBCGPEdit(); // Generated message map functions protected: //{{AFX_MSG(CBCGPEdit) afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp); afx_msg void OnNcPaint(); afx_msg void OnNcLButtonDblClk(UINT nHitTest, CPoint point); afx_msg void OnNcMouseMove(UINT nHitTest, CPoint point); afx_msg void OnCancelMode(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnPaint(); afx_msg void OnChange(); //}}AFX_MSG afx_msg BCGNcHitTestType OnNcHitTest(CPoint point); afx_msg LRESULT OnBCGSetControlVMMode (WPARAM, LPARAM); afx_msg LRESULT OnBCGSetControlAero (WPARAM, LPARAM); DECLARE_MESSAGE_MAP() void SetIntenalImage (); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BCGPEDIT_H__A7B40464_1C05_4981_A5F2_E21D74058A09__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 135 ] ] ]
5d955a36ac8bd25e173222f494e66c23ea07bd14
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/core/wx_image_panel.cpp
4959e60185f3b1b901ca3e825a2622f32e42a0d7
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
6,524
cpp
///////////////////////////////////////////////////////////////////////////// // Name: wx_image_panel.cpp // Purpose: // Author: Andrea Carbone // Modified by: // Created: 18/03/2007 16:06:56 // RCS-ID: // Copyright: Alcor // Licence: ///////////////////////////////////////////////////////////////////////////// #define WIN32_LEAN_AND_MEAN #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "wx_image_panel.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include <wx/dcbuffer.h> #include "wx_image_panel.h" ////@begin XPM images ////@end XPM images /*! * wx_image_panel type definition */ IMPLEMENT_DYNAMIC_CLASS( wx_image_panel, wxPanel ) /*! * wx_image_panel event table definition */ BEGIN_EVENT_TABLE( wx_image_panel, wxPanel ) ////@begin wx_image_panel event table entries EVT_WINDOW_DESTROY( wx_image_panel::OnDestroy ) EVT_PAINT( wx_image_panel::OnPaint ) EVT_LEFT_UP( wx_image_panel::OnLeftUp ) EVT_MOUSE_EVENTS( wx_image_panel::OnMouse ) ////@end wx_image_panel event table entries EVT_TIMER(wx_image_panel::ID_TIMER_EVENT, wx_image_panel::on_timer_) END_EVENT_TABLE() /*! * wx_image_panel constructors */ wx_image_panel::wx_image_panel() { Init(); } wx_image_panel::wx_image_panel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create(parent, id, pos, size, style); } /*! * wx_image_panel creator */ bool wx_image_panel::Create( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) { ////@begin wx_image_panel creation wxPanel::Create( parent, id, pos, size, style ); CreateControls(); ////@end wx_image_panel creation return true; } /*! * wx_image_panel destructor */ wx_image_panel::~wx_image_panel() { ////@begin wx_image_panel destruction ////@end wx_image_panel destruction } /*! * Member initialisation */ void wx_image_panel::Init() { stream_dest.reset(new wx_stream_dest_t); //link drawing callback stream_dest->set_update_callback (boost::bind(&wx_image_panel::update_image, this, _1)); //create streaming client endpoint stream_ptr = new all::core::stream_client_t(stream_dest, "config/trm_stream_client.ini"); //run! stream_ptr->run_async(); //wxMessageBox(_T("stream_ptr created and running")); ////@begin wx_image_panel member initialisation beginx = 0; beginy = 0; is_dragging = false; selection_h = 1; selection_w = 1; dragging_enabled = false; ////@end wx_image_panel member initialisation m_timer = new wxTimer(this, ID_TIMER_EVENT); m_timer->Start(75); } /*! * Control creation for wx_image_panel */ void wx_image_panel::CreateControls() { ////@begin wx_image_panel content construction // Connect events and objects Connect(ID_IMAGE_PANEL, wxEVT_DESTROY, wxWindowDestroyEventHandler(wx_image_panel::OnDestroy), NULL, this); ////@end wx_image_panel content construction } /*! * Should we show tooltips? */ bool wx_image_panel::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap wx_image_panel::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin wx_image_panel bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end wx_image_panel bitmap retrieval } /*! * Get icon resources */ wxIcon wx_image_panel::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin wx_image_panel icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end wx_image_panel icon retrieval } /*! * wxEVT_PAINT event handler for ID__IMAGE_PANEL */ void wx_image_panel::OnPaint( wxPaintEvent& event ) { wxBufferedPaintDC dc(this); { boost::mutex::scoped_lock lock (stream_dest->mutex); draw_image_panel(dc); } if(dragging_enabled) { if(is_dragging || selection_h>1) { draw_model_selection(dc); } } } /*! * wxEVT_DESTROY event handler for ID__IMAGE_PANEL */ void wx_image_panel::OnDestroy( wxWindowDestroyEvent& event ) { stream_ptr->stop(); //delete stream_ptr; } /*! * Drawing Routine (called from stream_dest) */ void wx_image_panel::draw_image_panel(wxDC& dc) { //PrepareDC(dc); if(my_jpeg_data.size > 0) { wxImage cam_image(my_jpeg_data.width , my_jpeg_data.height, reinterpret_cast <unsigned char*> (my_jpeg_data.data.get()) , true); wxBitmap cam_bmp(cam_image, 24); dc.DrawBitmap(cam_bmp, 0, 0, false); } } /*! * Draw Selection. */ void wx_image_panel::draw_model_selection(wxDC& dc) { dc.SetPen(*wxGREEN_PEN); dc.SetBrush( *wxTRANSPARENT_BRUSH ); dc.DrawRectangle(beginx, beginy,selection_w, selection_h); } /*! * Updating Routine (called from stream_dest) */ void wx_image_panel::update_image(const core::jpeg_data_t& newimage) { if(newimage.size != my_jpeg_data.size) { my_jpeg_data.data.reset(new core::uint8_t[newimage.size]); my_jpeg_data.size = newimage.size; my_jpeg_data.height = newimage.height; my_jpeg_data.width = newimage.width; my_jpeg_data.depth = newimage.depth; //my_jpeg_data.data = newimage.data; my_jpeg_data.size = newimage.size; } my_jpeg_data.data = newimage.data; } /*! * All mouse events event handler for ID__IMAGE_PANEL */ void wx_image_panel::OnMouse( wxMouseEvent& event ) { if (event.Dragging()) { if(event.LeftIsDown()) { if(is_dragging) { selection_h = event.GetY() - beginy; selection_w = event.GetX() - beginx; } else { beginx = event.GetX(); beginy = event.GetY(); is_dragging=true; selection_h = 1; selection_w = 1; } } } } /*! * wxEVT_LEFT_UP event handler for ID__IMAGE_PANEL */ void wx_image_panel::OnLeftUp( wxMouseEvent& event ) { is_dragging=false; } /*! * EVT_TIMER event handler for timer */ void wx_image_panel::on_timer_(wxTimerEvent&) { Refresh(false); }
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 305 ] ] ]
4fddecb75d512fbbb676f0127ec4153bf0df872c
5a39be53de11cddb52af7d0b70b56ef94cc52d35
/src/invert.cpp
3efc47e62ac4df66a2482eadc3bd7fbc5d0f2dfe
[]
no_license
zchn/jsepku
2b76eb5d118f86a5c942a9f4ec25a5adae24f802
8290fef5ff8abaf62cf050cead489dc7d44efa5f
refs/heads/master
2016-09-10T19:44:23.882210
2008-01-01T07:32:13
2008-01-01T07:32:13
33,052,475
0
0
null
null
null
null
GB18030
C++
false
false
2,779
cpp
// 我真诚地保证: // 我自己独立地完成了整个程序从分析、设计到编码的所有工作。 // 如果在上述过程中,我遇到了什么困难而求教于人,那么,我将在程序实习报告中 // 详细地列举我所遇到的问题,以及别人给我的提示。 // 在此,我感谢 XXX, …, XXX对我的启发和帮助。下面的报告中,我还会具体地提到 // 他们在各个方法对我的帮助。 // 我的程序里中凡是引用到其他程序或文档之处, // 例如教材、课堂笔记、网上的源代码以及其他参考书上的代码段, // 我都已经在程序的注释里很清楚地注明了引用的出处。 // 我从未没抄袭过别人的程序,也没有盗用别人的程序, // 不管是修改式的抄袭还是原封不动的抄袭。 // 我编写这个程序,从来没有想过要去破坏或妨碍其他计算机系统的正常运转。 // 陈志杰 揭忠 #include<iostream> #include<fstream> #include<string> #include<iomanip> using namespace std; const int TERM_LEN=32; struct word_info { string words; string id; }; /********************************************************************** 函数名:invert 功能:将.piidx.sort类型的文件转化为.iidx类型的文件,有关文件类型的说明请参考解题报告。 输入参数:一个string类型的文件路径。 返回值:如果成功则返回0,否则返回-1。 ***************************************************************************/ int invert(string path) { ifstream in_piidx_sort(path.c_str()); if(!in_piidx_sort.is_open()) { cerr<<"[ERROR]:piidx file can't be opened"<<endl; return -1; } /*将文件名中的.piidx.sort转化为.iidx*/ word_info *words_info; words_info=new word_info[2]; string out_name=path; int len=out_name.length(); len-=11; out_name.erase(len); out_name+=".iidx"; ofstream out_iidx(out_name.c_str()); in_piidx_sort>>words_info[0].words; in_piidx_sort>>words_info[0].id; out_iidx<<setw(TERM_LEN)<<left<<words_info[0].words; out_iidx<<setw(8)<<left<<words_info[0].id<<' '; /*按照.iidx的要求从左开始输出*/ while(!in_piidx_sort.eof()) { in_piidx_sort>>words_info[1].words; in_piidx_sort>>words_info[1].id; if(words_info[1].words==words_info[0].words) { out_iidx<<setw(8)<<left<<words_info[1].id<<' '; } else { out_iidx<<endl<<setw(TERM_LEN)<<left<<words_info[1].words; out_iidx<<setw(8)<<left<<words_info[1].id<<' '; } words_info[0].words=words_info[1].words; words_info[0].id=words_info[1].id; words_info[1].words=""; words_info[1].id=""; } return 0; } int main(int argc,char *argv[]) { string file_name=argv[1]; if(invert(file_name) != 0){ return -1; } return 0; }
[ "joyanlj@702d1322-cd41-0410-9eed-0fefee27d168" ]
[ [ [ 1, 88 ] ] ]
65eacb3dacccdd96e4add69bbcbfa2d8db7f2054
1d693dd1b12b23c72dd0bb12a3fc29ed88a7e2d5
/src/nbpflcompiler/pflexpression.cpp
dd5bdba4affdbb1ad925e918a1e673d625b5ec92
[]
no_license
rrdenicol/Netbee
8765ebc2db4ba9bd27c2263483741b409da8300a
38edb4ffa78b8fb7a4167a5d04f40f8f4466be3e
refs/heads/master
2021-01-16T18:42:17.961177
2011-12-26T20:27:03
2011-12-26T20:27:03
3,053,086
0
0
null
null
null
null
UTF-8
C++
false
false
5,826
cpp
/*****************************************************************************/ /* */ /* Copyright notice: please read file license.txt in the NetBee root folder. */ /* */ /*****************************************************************************/ #include "pflexpression.h" #include "dump.h" //!\ brief literal values corresponding to the elements of the \ref PFLOperator enumeration char *PFLOperators[] = { "and", ///< Logical AND "or", ///< Logical OR "boolnot", ///< Boolean negation }; uint32 PFLExpression::m_Count = 0; PFLStatement::PFLStatement(PFLExpression *exp, PFLAction *action, PFLIndex *index) :m_Exp(exp), m_Action(action), m_HeaderIndex(index) { } PFLStatement::~PFLStatement() { delete m_Exp; delete m_Action; delete m_HeaderIndex; } PFLExpression *PFLStatement::GetExpression(void) { return m_Exp; } PFLAction *PFLStatement::GetAction(void) { return m_Action; } PFLIndex *PFLStatement::GetHeaderIndex(void) { return m_HeaderIndex; } PFLAction::~PFLAction() { } PFLBinaryExpression::PFLBinaryExpression(PFLExpression *LeftExpression, PFLExpression *RightExpression, PFLOperator Operator) :PFLExpression(PFL_BINARY_EXPRESSION), m_LeftNode(LeftExpression), m_RightNode(RightExpression), m_Operator(Operator) { } PFLBinaryExpression::~PFLBinaryExpression() { if (m_LeftNode != NULL) delete m_LeftNode; if (m_RightNode != NULL) delete m_RightNode; } void PFLBinaryExpression::Printme(int level) { for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr,"-->PFLBinaryExpression\n"); for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr," LeftChild\n"); if (m_LeftNode != NULL) { m_LeftNode->Printme(level+1); } else { for (int i=0; i< level+1;i++) fprintf(stderr,"\t"); fprintf(stderr,"NULL\n"); } for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr," RightChild\n"); if (m_RightNode != NULL) { m_RightNode->Printme(level+1); } else { for (int i=0; i< level+1;i++) fprintf(stderr,"\t"); fprintf(stderr,"NULL\n"); } for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr,"<--PFLBinaryExpression\n"); } void PFLBinaryExpression::PrintMeDotFormat(ostream &outFile) { outFile << "expr" << GetID() << "[label=\"" << PFLOperators[m_Operator] << "\"];" << endl; m_LeftNode->PrintMeDotFormat(outFile); outFile << "expr" << GetID() << "->expr" << m_LeftNode->GetID() << ";" << endl; m_RightNode->PrintMeDotFormat(outFile); outFile << "expr" << GetID() << "->expr" << m_RightNode->GetID() << ";" << endl; } void PFLBinaryExpression::SwapChilds() { PFLExpression *tmp = m_LeftNode; m_LeftNode = m_RightNode; m_RightNode = tmp; } void PFLBinaryExpression::ToCanonicalForm() { m_LeftNode->ToCanonicalForm(); m_RightNode->ToCanonicalForm(); if (m_LeftNode->IsConst() && !m_RightNode->IsConst()) SwapChilds(); } PFLUnaryExpression::PFLUnaryExpression(PFLExpression *Expression, PFLOperator Operator) :PFLExpression(PFL_UNARY_EXPRESSION), m_Operator(Operator), m_Node(Expression) { } PFLUnaryExpression::~PFLUnaryExpression() { if (m_Node != NULL) delete m_Node; } void PFLUnaryExpression::Printme(int level) { for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr,"-->PFLUnaryExpression"); fprintf(stderr, " %s\n", PFLOperators[m_Operator]); if (m_Node != NULL) { m_Node->Printme(level+1); } else { for (int i=0; i< level+1;i++) fprintf(stderr,"\t"); fprintf(stderr,"NULL\n"); } for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr,"<--PFLUnaryExpression\n"); } void PFLUnaryExpression::PrintMeDotFormat(ostream &outFile) { outFile << "expr" << GetID() << "[label=\"" << PFLOperators[m_Operator] << "\"];" << endl; m_Node->PrintMeDotFormat(outFile); outFile << "expr" << GetID() << "->expr" << m_Node->GetID() << ";" << endl; } void PFLUnaryExpression::ToCanonicalForm() { m_Node->ToCanonicalForm(); return; } PFLTermExpression::PFLTermExpression(SymbolProto *proto, Node *expr, uint32 index) :PFLExpression(PFL_TERM_EXPRESSION), m_Protocol(proto), m_IRExpr(expr), m_Ind(index) { } PFLTermExpression::~PFLTermExpression() { } void PFLTermExpression::Printme(int level) { for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr,"-->PFLTermExpression\n"); nbASSERT(m_Protocol != NULL, "Protocol cannot be NULL"); if (m_Protocol != NULL) { for (int i=0; i< level+1;i++) fprintf(stderr,"\t"); fprintf(stderr,"%s\n", m_Protocol->Name.c_str()); } else { for (int i=0; i< level+1;i++) fprintf(stderr,"\t"); fprintf(stderr,"NULL PROTO\n"); } if (m_IRExpr != NULL) { for (int i=0; i< level+1;i++) fprintf(stderr,"\t"); //DumpTree(stderr, m_IRExpr, 0); } for (int i=0; i< level;i++) fprintf(stderr,"\t"); fprintf(stderr,"<--PFLTermExpression\n"); } void PFLTermExpression::PrintMeDotFormat(ostream &outFile) { nbASSERT(!(m_Protocol == NULL && m_IRExpr == NULL), "Terminal node should refer to at least one protocol or to a valid IR expression tree"); outFile << "expr" << GetID() << "[label=\""; if (m_Protocol != NULL) outFile << "proto: " << m_Protocol->Name << "\\n"; if (m_IRExpr != NULL) { outFile << "cond: "; CodeWriter codeWriter(outFile); codeWriter.DumpTree(m_IRExpr, 0); } outFile << "\"];" << endl; } void PFLTermExpression::ToCanonicalForm() { return; } PFLExpression::~PFLExpression() { }
[ [ [ 1, 264 ] ] ]
a79e99ca67b238eba77d2b94572bae7f0d0eb385
700aec6c62833fdbfa058959e43e9b1408acf8fc
/AngelSript/sdk/angelscript/source/as_module.h
211df6ffd3cf250e2925337ca5a5217793acfaff
[]
no_license
avansc/qLib
7427dbb1cf5019c91fc290c82e4338d4c60b010d
a8dbb5a6b0efcfac906868a876ca71e7989853ad
refs/heads/master
2021-01-01T05:38:15.132895
2011-06-07T16:49:28
2011-06-07T16:49:28
1,811,678
1
0
null
null
null
null
UTF-8
C++
false
false
8,623
h
/* AngelCode Scripting Library Copyright (c) 2003-2011 Andreas Jonsson 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. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson [email protected] */ // // as_module.h // // A class that holds a script module // #ifndef AS_MODULE_H #define AS_MODULE_H #include "as_config.h" #include "as_atomic.h" #include "as_string.h" #include "as_array.h" #include "as_datatype.h" #include "as_scriptfunction.h" #include "as_property.h" BEGIN_AS_NAMESPACE // TODO: import: Remove this when the imported functions are removed const int FUNC_IMPORTED = 0x40000000; class asCScriptEngine; class asCCompiler; class asCBuilder; class asCContext; class asCConfigGroup; struct sBindInfo { asCScriptFunction *importedFunctionSignature; asCString importFromModule; int boundFunctionId; }; struct sObjectTypePair { asCObjectType *a; asCObjectType *b; }; // TODO: import: Remove function imports. When I have implemented function // pointers the function imports should be deprecated. // TODO: Need a separate interface for compiling scripts. The asIScriptCompiler // will have a target module, and will allow the compilation of an entire // script or just individual functions within the scope of the module // // With this separation it will be possible to compile the library without // the compiler, thus giving a much smaller binary executable. // TODO: There should be an special compile option that will let the application // recompile an already compiled script. The compiler should check if no // destructive changes have been made (changing function signatures, etc) // then it should simply replace the bytecode within the functions without // changing the values of existing global properties, etc. class asCModule : public asIScriptModule { //------------------------------------------- // Public interface //-------------------------------------------- public: virtual asIScriptEngine *GetEngine() const; virtual void SetName(const char *name); virtual const char *GetName() const; // Compilation virtual int AddScriptSection(const char *name, const char *code, size_t codeLength, int lineOffset); virtual int Build(); virtual int CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD reserved, asIScriptFunction **outFunc); virtual int CompileGlobalVar(const char *sectionName, const char *code, int lineOffset); // Script functions virtual int GetFunctionCount() const; virtual int GetFunctionIdByIndex(int index) const; virtual int GetFunctionIdByName(const char *name) const; virtual int GetFunctionIdByDecl(const char *decl) const; virtual asIScriptFunction *GetFunctionDescriptorByIndex(int index) const; virtual asIScriptFunction *GetFunctionDescriptorById(int funcId) const; virtual int RemoveFunction(int funcId); // Script global variables virtual int ResetGlobalVars(); virtual int GetGlobalVarCount() const; virtual int GetGlobalVarIndexByName(const char *name) const; virtual int GetGlobalVarIndexByDecl(const char *decl) const; virtual const char *GetGlobalVarDeclaration(asUINT index) const; virtual int GetGlobalVar(asUINT index, const char **name, int *typeId, bool *isConst) const; virtual void *GetAddressOfGlobalVar(asUINT index); virtual int RemoveGlobalVar(asUINT index); // Type identification virtual int GetObjectTypeCount() const; virtual asIObjectType *GetObjectTypeByIndex(asUINT index) const; virtual int GetTypeIdByDecl(const char *decl) const; // Enums virtual int GetEnumCount() const; virtual const char *GetEnumByIndex(asUINT index, int *enumTypeId) const; virtual int GetEnumValueCount(int enumTypeId) const; virtual const char *GetEnumValueByIndex(int enumTypeId, asUINT index, int *outValue) const; // Typedefs virtual int GetTypedefCount() const; virtual const char *GetTypedefByIndex(asUINT index, int *typeId) const; // Dynamic binding between modules virtual int GetImportedFunctionCount() const; virtual int GetImportedFunctionIndexByDecl(const char *decl) const; virtual const char *GetImportedFunctionDeclaration(int importIndex) const; virtual const char *GetImportedFunctionSourceModule(int importIndex) const; virtual int BindImportedFunction(int index, int sourceID); virtual int UnbindImportedFunction(int importIndex); virtual int BindAllImportedFunctions(); virtual int UnbindAllImportedFunctions(); // Bytecode Saving/Loading virtual int SaveByteCode(asIBinaryStream *out) const; virtual int LoadByteCode(asIBinaryStream *in); #ifdef AS_DEPRECATED // Since 2.20.0 virtual const char *GetGlobalVarName(int index) const; virtual int GetGlobalVarTypeId(int index, bool *isConst) const; #endif //----------------------------------------------- // Internal //----------------------------------------------- asCModule(const char *name, asCScriptEngine *engine); ~asCModule(); //protected: friend class asCScriptEngine; friend class asCBuilder; friend class asCCompiler; friend class asCContext; friend class asCRestore; void InternalReset(); int CallInit(); void CallExit(); void JITCompile(); int AddScriptFunction(int sectionIdx, int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, asCString **defaultArgs, int paramCount, bool isInterface, asCObjectType *objType = 0, bool isConstMethod = false, bool isGlobalFunction = false, bool isPrivate = false); int AddScriptFunction(asCScriptFunction *func); int AddImportedFunction(int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, int paramCount, const asCString &moduleName); int AddFuncDef(const char *name); int GetNextImportedFunctionId(); void ResolveInterfaceIds(asCArray<void*> *substitutions = 0); bool AreInterfacesEqual(asCObjectType *a, asCObjectType *b, asCArray<sObjectTypePair> &equals); bool AreTypesEqual(const asCDataType &a, const asCDataType &b, asCArray<sObjectTypePair> &equals); asCScriptFunction *GetImportedFunction(int funcId) const; asCObjectType *GetObjectType(const char *type); asCGlobalProperty *AllocateGlobalProperty(const char *name, const asCDataType &dt); asCString name; asCScriptEngine *engine; asCBuilder *builder; // This array holds all functions, class members, factories, etc that were compiled with the module asCArray<asCScriptFunction *> scriptFunctions; // This array holds global functions declared in the module asCArray<asCScriptFunction *> globalFunctions; // This array holds imported functions in the module asCArray<sBindInfo *> bindInformations; // This array holds the global variables declared in the script asCArray<asCGlobalProperty *> scriptGlobals; bool isGlobalVarInitialized; // This array holds class and interface types asCArray<asCObjectType*> classTypes; // This array holds enum types asCArray<asCObjectType*> enumTypes; // This array holds typedefs asCArray<asCObjectType*> typeDefs; // This array holds the funcdefs declared in the module asCArray<asCScriptFunction*> funcDefs; }; END_AS_NAMESPACE #endif
[ [ [ 1, 227 ] ] ]
610fd26e4b8bae12123c636e62cd88978cf42ba3
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/v102/ok/10201/c.cpp
c04696b4fcc92c3bea04e7ae440f87eb73db7e82
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,891
cpp
#include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> using namespace std; class StrArray { public: char **s; int tot; StrArray(int i){ s = (char **) malloc(sizeof(char *)*i); clear(); } void clear() { tot = 0; } void add(char *c) { s[tot++] = c; } void split(char *st, char c) { clear(); bool b = false; char *start = st; while((*st)!='\0') { if((*st)!=c) { if(!b) { start = st; b = true; } } else { (*st) = '\0'; if(b) { b = false; add(start); } } st++; } if(b) add(start); } int *toInt() { int *z = (int *) malloc(sizeof(int) * tot); for(int i=0;i!=tot;i++) { if(s[i][0]=='-') z[i] = -atoi(s[i]+1); else z[i] = atoi(s[i]); } return z; } long *toLong() { long *z = (long *) malloc(sizeof(long) * tot); for(int i=0;i!=tot;i++) { if(s[i][0]=='-') z[i] = -atol(s[i]+1); else z[i] = atol(s[i]); } return z; } }; int pos[111]; int posfinal; int preco[111]; long long dp[111][211]; int n; long long melhor; bool calc() { int i,j,k,lev; long long v = 0; bool b; for(i=0;i<=n;i++) for(j=0;j!=201;j++) dp[i][j] = -1; if(pos[0]>100) return false; dp[0][100-pos[0]] = 0; for(lev=0;lev!=n;lev++) { b = false; for(i=0;i!=200;i++) { if(dp[lev][i]!=-1) { b = true; v = preco[lev] + dp[lev][i]; for(j=i+1; j<=200 ; j++, v+=preco[lev]) { if(dp[lev][j]==-1 || dp[lev][j]>v) dp[lev][j]=v; } } } if(lev==n-1) break; if(!b) return false; k = pos[lev+1] - pos[lev]; for(i=k;i<=200;i++) { if(dp[lev][i]!=-1) { dp[lev+1][i-k] = dp[lev][i]; } } } k = posfinal - pos[n-1] + 100; v = -1; for(i=k;i<=200;i++) { if(dp[n-1][i]!=-1) { if(v==-1 || dp[n-1][i]<v) v = dp[n-1][i]; } } melhor = v; if(v==-1) return false; return true; } StrArray ar = StrArray(300); void st() { cin >> posfinal; n = 0; char c[1000]; int len,i,j,k; cin.getline(c,1000); while((true)) { cin.getline(c,1000); len = strlen(c); if(c[len-1]=='\n') c[len-1]='\0'; if(c[len-1]=='\r') c[len-1]='\0'; ar.clear(); ar.split(c,' '); if(ar.tot==0) break; int *iz = ar.toInt(); pos[n] = iz[0]; preco[n] = iz[1]; n++; } if(calc()) { cout << melhor << endl; } else { cout << "Impossible" << endl; } } int main() { int t; cin >> t; while(t--) { st(); if(t!=0) cout << endl; } return 0; }
[ [ [ 1, 158 ] ] ]
0f6f2e7c90d767b70b03a21701917a1c07ebee26
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/RefHash3KeysIdPool.hpp
53dc59370de8a1cbed9f709748a04ff2b61666fe
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
11,196
hpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: RefHash3KeysIdPool.hpp 191054 2005-06-17 02:56:35Z jberry $ */ #if !defined(REFHASH3KEYSIDPOOL_HPP) #define REFHASH3KEYSIDPOOL_HPP #include <xercesc/util/HashBase.hpp> #include <xercesc/util/IllegalArgumentException.hpp> #include <xercesc/util/NoSuchElementException.hpp> #include <xercesc/util/RuntimeException.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/HashXMLCh.hpp> XERCES_CPP_NAMESPACE_BEGIN // This hash table is a combination of RefHash2KeyTableOf (with an additional integer as key3) // and NameIdPool with an id as index // // Forward declare the enumerator so he can be our friend. Can you say // friend? Sure... // template <class TVal> class RefHash3KeysIdPoolEnumerator; template <class TVal> struct RefHash3KeysTableBucketElem; // // This should really be a nested class, but some of the compilers we // have to support cannot deal with that! // template <class TVal> struct RefHash3KeysTableBucketElem { RefHash3KeysTableBucketElem( void* key1 , int key2 , int key3 , TVal* const value , RefHash3KeysTableBucketElem<TVal>* next) : fData(value) , fNext(next) , fKey1(key1) , fKey2(key2) , fKey3(key3) { } RefHash3KeysTableBucketElem() {}; ~RefHash3KeysTableBucketElem() {}; TVal* fData; RefHash3KeysTableBucketElem<TVal>* fNext; void* fKey1; int fKey2; int fKey3; private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- RefHash3KeysTableBucketElem(const RefHash3KeysTableBucketElem<TVal>&); RefHash3KeysTableBucketElem<TVal>& operator=(const RefHash3KeysTableBucketElem<TVal>&); }; template <class TVal> class RefHash3KeysIdPool : public XMemory { public: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- // backwards compatability - default hasher is HashXMLCh RefHash3KeysIdPool ( const unsigned int modulus , const unsigned int initSize = 128 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // backwards compatability - default hasher is HashXMLCh RefHash3KeysIdPool ( const unsigned int modulus , const bool adoptElems , const unsigned int initSize = 128 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // if a hash function is passed in, it will be deleted when the hashtable is deleted. // use a new instance of the hasher class for each hashtable, otherwise one hashtable // may delete the hasher of a different hashtable if both use the same hasher. RefHash3KeysIdPool ( const unsigned int modulus , const bool adoptElems , HashBase* hashBase , const unsigned int initSize = 128 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); ~RefHash3KeysIdPool(); // ----------------------------------------------------------------------- // Element management // ----------------------------------------------------------------------- bool isEmpty() const; bool containsKey(const void* const key1, const int key2, const int key3) const; void removeAll(); // ----------------------------------------------------------------------- // Getters // ----------------------------------------------------------------------- TVal* getByKey(const void* const key1, const int key2, const int key3); const TVal* getByKey(const void* const key1, const int key2, const int key3) const; TVal* getById(const unsigned elemId); const TVal* getById(const unsigned elemId) const; MemoryManager* getMemoryManager() const; unsigned int getHashModulus() const; // ----------------------------------------------------------------------- // Putters // ----------------------------------------------------------------------- unsigned int put(void* key1, int key2, int key3, TVal* const valueToAdopt); private : // ----------------------------------------------------------------------- // Declare our friends // ----------------------------------------------------------------------- friend class RefHash3KeysIdPoolEnumerator<TVal>; private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- RefHash3KeysIdPool(const RefHash3KeysIdPool<TVal>&); RefHash3KeysIdPool<TVal>& operator=(const RefHash3KeysIdPool<TVal>&); // ----------------------------------------------------------------------- // Private methods // ----------------------------------------------------------------------- RefHash3KeysTableBucketElem<TVal>* findBucketElem(const void* const key1, const int key2, const int key3, unsigned int& hashVal); const RefHash3KeysTableBucketElem<TVal>* findBucketElem(const void* const key1, const int key2, const int key3, unsigned int& hashVal) const; void initialize(const unsigned int modulus); // ----------------------------------------------------------------------- // Data members // // fAdoptedElems // Indicates whether the values added are adopted or just referenced. // If adopted, then they are deleted when they are removed from the // hash table. // // fBucketList // This is the array that contains the heads of all of the list // buckets, one for each possible hash value. // // fHashModulus // The modulus used for this hash table, to hash the keys. This is // also the number of elements in the bucket list. // // fHash // The hasher for the key1 data type. // // fIdPtrs // fIdPtrsCount // This is the array of pointers to the bucket elements in order of // their assigned ids. So taking id N and referencing this array // gives you the element with that id. The count field indicates // the current size of this list. When fIdCounter+1 reaches this // value the list must be expanded. // // fIdCounter // This is used to give out unique ids to added elements. It starts // at zero (which means empty), and is bumped up for each newly added // element. So the first element is 1, the next is 2, etc... This // means that this value is set to the top index of the fIdPtrs array. // ----------------------------------------------------------------------- MemoryManager* fMemoryManager; bool fAdoptedElems; RefHash3KeysTableBucketElem<TVal>** fBucketList; unsigned int fHashModulus; HashBase* fHash; TVal** fIdPtrs; unsigned int fIdPtrsCount; unsigned int fIdCounter; }; // // An enumerator for a value array. It derives from the basic enumerator // class, so that value vectors can be generically enumerated. // template <class TVal> class RefHash3KeysIdPoolEnumerator : public XMLEnumerator<TVal>, public XMemory { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- RefHash3KeysIdPoolEnumerator(RefHash3KeysIdPool<TVal>* const toEnum , const bool adopt = false , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); virtual ~RefHash3KeysIdPoolEnumerator(); RefHash3KeysIdPoolEnumerator(const RefHash3KeysIdPoolEnumerator<TVal>&); // ----------------------------------------------------------------------- // Enum interface // ----------------------------------------------------------------------- bool hasMoreElements() const; TVal& nextElement(); void Reset(); int size() const; // ----------------------------------------------------------------------- // New interface // ----------------------------------------------------------------------- void resetKey(); void nextElementKey(void*&, int&, int&); bool hasMoreKeys() const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- RefHash3KeysIdPoolEnumerator<TVal>& operator=(const RefHash3KeysIdPoolEnumerator<TVal>&); // ----------------------------------------------------------------------- // Private methods // ----------------------------------------------------------------------- void findNext(); // ----------------------------------------------------------------------- // Data Members // fAdoptedElems // Indicates whether the values added are adopted or just referenced. // If adopted, then they are deleted when they are removed from the // hash table // // fCurIndex // This is the current index into the pool's id mapping array. This // is now we enumerate it. // // fToEnum // The name id pool that is being enumerated. // ----------------------------------------------------------------------- bool fAdoptedElems; unsigned int fCurIndex; RefHash3KeysIdPool<TVal>* fToEnum; RefHash3KeysTableBucketElem<TVal>* fCurElem; unsigned int fCurHash; MemoryManager* const fMemoryManager; }; XERCES_CPP_NAMESPACE_END #if !defined(XERCES_TMPLSINC) #include <xercesc/util/RefHash3KeysIdPool.c> #endif #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 284 ] ] ]
a630d98c8bc5c499a7f33c5890f8682e0db090d2
04480fe64bb0d0535711f534ac1d343f41fa297d
/arquiteturaQuaseFinal/Arquitetura-build-desktop/tmp/moc/debug_shared/moc_circulo.cpp
0fbdb9dd456c40468d71378c3c84f28a69fdfa32
[]
no_license
prosanes/arquitetura-pli
e37a69cd6b5e0c9dc6e8ae605cda5f1f21f328b4
05fc902d4cce4c009a1714e893bb04e02e7f94a9
refs/heads/master
2020-04-27T17:08:41.913097
2010-12-13T18:55:08
2010-12-13T18:55:08
32,121,762
0
0
null
null
null
null
UTF-8
C++
false
false
2,101
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'circulo.h' ** ** Created: Sun 1. Aug 19:57:54 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../Arquitetura/circulo.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'circulo.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_Circulo[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_Circulo[] = { "Circulo\0" }; const QMetaObject Circulo::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_Circulo, qt_meta_data_Circulo, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &Circulo::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *Circulo::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *Circulo::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Circulo)) return static_cast<void*>(const_cast< Circulo*>(this)); return QWidget::qt_metacast(_clname); } int Circulo::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "prosanes@d2cc51ec-644b-ba46-3315-dce07c01be90" ]
[ [ [ 1, 69 ] ] ]
545d6cb95bacc684442572448e07bb42f61f9fd2
d6a28d9d845a20463704afe8ebe644a241dc1a46
/tests/mrt.cpp
179405de188dff30ad0c50c401eb7ed26bf6d336
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
marky0720/irrlicht-android
6932058563bf4150cd7090d1dc09466132df5448
86512d871eeb55dfaae2d2bf327299348cc5202c
refs/heads/master
2021-04-30T08:19:25.297407
2010-10-08T08:27:33
2010-10-08T08:27:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,035
cpp
// Copyright (C) 2008-2009 Christian Stehno, Colin MacDonald // No rights reserved: this software is in the public domain. #include "testUtils.h" using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; //! Tests rendering MRTs static bool testWithDriver(E_DRIVER_TYPE driverType) { IrrlichtDevice *device = createDevice (driverType, core::dimension2d < u32 > (220, 80)); if (!device) return true; // No error if device does not exist if (device->getVideoDriver()->getDriverAttributes().getAttributeAsInt("MaxMultipleRenderTargets") < 3) return true; IVideoDriver* driver = device->getVideoDriver(); const char* const ps1="struct PS_INPUT\n {\n float4 Position : POSITION0;\n };\n\n struct PS_OUTPUT\n {\n float4 Color : COLOR0;\n float4 Normal : COLOR1;\n float4 Depth : COLOR2;\n };\n PS_OUTPUT pixelMain( PS_INPUT Input )\n {\n PS_OUTPUT Output;\n Output.Color = float4(1.0,1.0,1.0,1.0);\n Output.Normal = float4(0.0,1.0,0.0,1.0);\n Output.Depth = float4(0.0,0.0,1.0,1.0);\n return Output;\n }"; const char* const ps2="void main(void)\n {\n gl_FragData[0] = vec4(1.0,1.0,1.0,1.0);\n gl_FragData[1] = vec4(0.0,1.0,0.0,1.0);\n gl_FragData[2] = vec4(0.0,0.0,1.0,1.0);\n }"; // variable ITexture* gbuffer[3]; array<IRenderTarget> gbufferlist; core::dimension2du texsize(64,64); // allocate buffer gbuffer[0] = driver->addRenderTargetTexture(texsize, "rta", ECF_A8R8G8B8); gbuffer[1] = driver->addRenderTargetTexture(texsize, "rtb", ECF_A8R8G8B8); gbuffer[2] = driver->addRenderTargetTexture(texsize, "rtc", ECF_A8R8G8B8); for( u32 i = 0; i < 3; ++i ) gbufferlist.push_back( IRenderTarget(gbuffer[i]) ); video::IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices(); s32 newMaterialType = 0; if (gpu) { newMaterialType = gpu->addHighLevelShaderMaterial( 0, "vertexMain", video::EVST_VS_1_1, driverType==video::EDT_DIRECT3D9?ps1:ps2, "pixelMain", video::EPST_PS_1_1); } ISceneNode* node = device->getSceneManager()->addCubeSceneNode(); node->setMaterialType((video::E_MATERIAL_TYPE)newMaterialType); device->getSceneManager()->addCameraSceneNode(0, core::vector3df(0,0,-10)); driver->beginScene (true, true, video::SColor (255, 200, 200, 200)); // render driver->setRenderTarget( gbufferlist ); device->getSceneManager()->drawAll(); driver->setRenderTarget(0); // draw debug rt driver->draw2DImage(gbuffer[0], core::position2d<s32>(0,0)); driver->draw2DImage(gbuffer[1], core::position2d<s32>(64,0)); driver->draw2DImage(gbuffer[2], core::position2d<s32>(128,0)); driver->endScene(); bool result = takeScreenshotAndCompareAgainstReference(driver, "-mrt.png"); device->closeDevice(); device->run(); device->drop(); return result; } bool mrt(void) { bool passed = true; passed &= testWithDriver(EDT_OPENGL); passed &= testWithDriver(EDT_DIRECT3D9); return passed; }
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
[ [ [ 1, 84 ] ] ]
c0593b88903a05d112c889f3469a21589a9d6d36
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkMergeColumns.h
a0065a0d627e0c4855648c00bb81aa3ddba0cf05
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,582
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkMergeColumns.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // .NAME vtkMergeColumns - merge two columns into a single column // // .SECTION Description // vtkMergeColumns replaces two columns in a table with a single column // containing data in both columns. The columns are set using // // SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_NONE, "col1") // // and // // SetInputArrayToProcess(1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_NONE, "col2") // // where "col1" and "col2" are the names of the columns to merge. // The user may also specify the name of the merged column. // The arrays must be of the same type. // If the arrays are numeric, the values are summed in the merged column. // If the arrays are strings, the values are concatenated. The strings are // separated by a space if they are both nonempty. #ifndef __vtkMergeColumns_h #define __vtkMergeColumns_h #include "vtkTableAlgorithm.h" class VTK_INFOVIS_EXPORT vtkMergeColumns : public vtkTableAlgorithm { public: static vtkMergeColumns* New(); vtkTypeRevisionMacro(vtkMergeColumns,vtkTableAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // The name to give the merged column created by this filter. vtkSetStringMacro(MergedColumnName); vtkGetStringMacro(MergedColumnName); protected: vtkMergeColumns(); ~vtkMergeColumns(); char* MergedColumnName; int RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector*); private: vtkMergeColumns(const vtkMergeColumns&); // Not implemented void operator=(const vtkMergeColumns&); // Not implemented }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 73 ] ] ]
3e296932214220de7a18308db5d9b5fa52bdb115
282057a05d0cbf9a0fe87457229f966a2ecd3550
/EIBStdLib/src/SearchResponse.cpp
4014843d5dc6e8c61b2088f5f12b78d31d4af021
[]
no_license
radtek/eibsuite
0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd
4504fcf4fa8c7df529177b3460d469b5770abf7a
refs/heads/master
2021-05-29T08:34:08.764000
2011-12-06T20:42:06
2011-12-06T20:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,133
cpp
#include "SearchResponse.h" using namespace EibStack; CSearchResponse::CSearchResponse(const CString& ctrl_addr, int ctrl_port, KNXMedium knxMedium, const CEibAddress& devAddr, short projInstallId, const char serial[], unsigned long multicatAddr, const char macAddr[], const char name[], int suppServices) : CEIBNetPacket<EIBNETIP_SEARCH_RESPONSE>(SEARCH_RESPONSE), _desc(knxMedium, devAddr, projInstallId, serial, multicatAddr, macAddr, name, suppServices) { _control_ip = ctrl_addr; _control_port = ctrl_port; //set the data of control endpoint CHPAI ctrl_ep(ctrl_port,ctrl_addr); memcpy(&_data.endpoint,ctrl_ep.ToByteArray(),ctrl_ep.GetDataSize()); } CSearchResponse::CSearchResponse(unsigned char* data, int len): CEIBNetPacket<EIBNETIP_SEARCH_RESPONSE>(data) { CHPAI discovered(data); memcpy(&_data.endpoint,discovered.ToByteArray(),discovered.GetDataSize()); _control_ip = discovered.GetAddress(); _control_port = discovered.GetPort(); if((unsigned)(_header.totalsize - _header.headersize) > sizeof(EIBNETIP_HPAI)){ _desc.Parse(data + _data.endpoint.structlength, len - _header.headersize - _data.endpoint.structlength); } } CSearchResponse::~CSearchResponse() { } void CSearchResponse::FillBuffer(unsigned char* buffer, int max_length) { CEIBNetPacket<EIBNETIP_SEARCH_RESPONSE>::FillBuffer(buffer,max_length); buffer += GetHeaderSize(); max_length -= GetHeaderSize(); //copy the HPAI into the buffer memcpy(buffer, &_data.endpoint, _data.endpoint.structlength); EIBNETIP_SEARCH_RESPONSE* ptr = ((EIBNETIP_SEARCH_RESPONSE*)buffer); ptr->endpoint.port = htons(_data.endpoint.port); //now copy the description element buffer += _data.endpoint.structlength; max_length -= _data.endpoint.structlength; _desc.FillBuffer(buffer, max_length, false); } void CSearchResponse::Dump() { printf("****************************************************************\n"); _desc.Dump(); printf("****************************************************************\n"); }
[ [ [ 1, 63 ] ] ]
6be2ef2aec7ffb367fa22229a18d82f00bf8d217
27167a5a0340fdc9544752bd724db27d3699a9a2
/include/dockwins/sstate.h
23fbd280b5c16862e350811ecbe784387e986248
[]
no_license
eaglexmw-gmail/wtl-dockwins
2b464be3958e1683cd668a10abafb528f43ac695
ae307a1978b73bfd2823945068224bb6c01ae350
refs/heads/master
2020-06-30T21:03:26.075864
2011-10-23T12:50:14
2011-10-23T12:50:14
200,951,487
2
1
null
null
null
null
UTF-8
C++
false
false
31,358
h
// Copyright (c) 2002 // Sergey Klimov ([email protected]) #ifndef WTL_DW_SSTATE_H_INCLUDED_ #define WTL_DW_SSTATE_H_INCLUDED_ #pragma once // NOTE: To be able to CSplitterWindowStateAdapter include atlsplit.h first #include <algorithm> #include <limits> #include <map> #include <memory> #include <sstream> #include <string> #include <utility> #include "stg.h" namespace sstate { const TCHAR ctxtGeneral[] = _T("General"); const TCHAR ctxtCXScreen[] = _T("SM_CXSCREEN"); const TCHAR ctxtCYScreen[] = _T("SM_CYSCREEN"); const TCHAR ctxtPlacement[] = _T("placement"); const TCHAR ctxtPosition[] = _T("position"); const TCHAR ctxtMainWindow[] = _T("MainWindow"); const TCHAR ctxtVisible[] = _T("visible"); const TCHAR ctxtBand[] = _T("band"); const TCHAR ctxtWndPrefix[] = _T("Wnd-"); typedef std::basic_string<TCHAR> tstring; typedef UINT ID; //typedef tstring ID; const unsigned int ForceDefaultCmdShow = 0x80000000; struct IState { virtual ~IState() {} virtual bool Store(IStorge& /*stg*/) = 0; virtual bool Restore(IStorge& /*stg*/, const std::pair<long, long>& /*xratio*/, const std::pair<long, long>& /*yratio*/) = 0; virtual bool RestoreDefault() = 0; virtual void AddRef() = 0; virtual void Release() = 0; }; template<class T> class CStateBase : public T { public: CStateBase(): m_ref(1) { } virtual void AddRef() { m_ref++; } virtual void Release() { if (--m_ref == 0) delete this; } virtual ~CStateBase() { ATLASSERT(m_ref == 0); } private: CStateBase(const CStateBase&); const CStateBase& operator=(const CStateBase&); protected: UINT m_ref; }; template<class T = IState> class CStateHolder { typedef CStateHolder<T> thisClass; public: CStateHolder() : m_pState(0) { } CStateHolder(T* pState) { pState->AddRef(); m_pState = pState; } CStateHolder(const thisClass& sholder) { *this = (sholder); } thisClass& operator = (const thisClass& sholder) { m_pState = const_cast<T*>(sholder.m_pState); if (m_pState != 0) m_pState->AddRef(); return *this; } ~CStateHolder() { if (m_pState != 0) m_pState->Release(); } const T* operator ->() const { return m_pState; } T* operator ->() { return m_pState; } protected: T* m_pState; }; template<class TStorage> class CContainerImpl : public CStateBase<IState> { protected: typedef CStateHolder<IState> CItem; typedef std::map<ID, CItem> CBunch; class CStorer { public: CStorer(IStorge& stgTop) : m_stgTop(stgTop) { } void operator()(std::pair<const ID, CItem>& x) const { std::basic_ostringstream<TCHAR> sstrKey; sstrKey.flags(std::ios::hex | std::ios::showbase); sstrKey << ctxtWndPrefix << x.first; /* CRegKey key; DWORD dwDisposition; LONG lRes = key.Create(m_keyTop,sstrKey.str().c_str(),REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,&dwDisposition); if(lRes==ERROR_SUCCESS) x.second->Store(key); */ TStorage stg; if (stg.Create(m_stgTop, sstrKey.str().c_str(), IStorge::ReadWrite) == ERROR_SUCCESS) x.second->Store(stg); } protected: IStorge& m_stgTop; }; class CRestorer { public: CRestorer(IStorge& stgTop, const std::pair<long, long>& xratio, const std::pair<long, long>& yratio) : m_stgTop(stgTop) , m_xratio(xratio) , m_yratio(yratio) { } void operator()(std::pair<const ID, CItem>& x) const { std::basic_ostringstream<TCHAR> sstrKey; sstrKey.flags(std::ios::hex | std::ios::showbase); sstrKey << ctxtWndPrefix << x.first; /* CRegKey key; LONG lRes = key.Open(m_keyTop,sstrKey.str().c_str(),KEY_READ); if(lRes==ERROR_SUCCESS) x.second->Restore(key,m_xratio,m_yratio); else x.second->RestoreDefault(); */ TStorage stg; if (stg.Open(m_stgTop, sstrKey.str().c_str(), IStorge::Read) != ERROR_SUCCESS || !x.second->Restore(stg, m_xratio, m_yratio)) x.second->RestoreDefault(); } protected: IStorge& m_stgTop; std::pair<long, long> m_xratio; std::pair<long, long> m_yratio; }; struct CDefRestorer { void operator()(std::pair<const ID, CItem>& x) const { x.second->RestoreDefault(); } }; public: CContainerImpl() : m_nextFreeID(/*std::numeric_limits<ID>::max()*/ULONG_MAX) { } ID GetUniqueID() const { return m_nextFreeID--; } virtual bool Store(IStorge& stg) { std::for_each(m_bunch.begin(), m_bunch.end(), CStorer(stg)); return true; } virtual bool Restore(IStorge& stg, const std::pair<long, long>& xratio, const std::pair<long, long>& yratio) { std::for_each(m_bunch.begin(), m_bunch.end(), CRestorer(stg, xratio, yratio)); return true; } virtual bool RestoreDefault() { std::for_each(m_bunch.begin(), m_bunch.end(), CDefRestorer()); return true; } ID Add(IState* pState) { ID id = GetUniqueID(); Add(id, pState); return id; } void Add(ID id, IState* pState) { CStateHolder<IState> h(pState); m_bunch[id] = h; } void Remove(ID id) { ATLASSERT(m_bunch.find(id) != m_bunch.end()); m_bunch.erase(id); } protected: mutable ID m_nextFreeID; CBunch m_bunch; }; namespace { class SetWindowPlacementInsensibly { public: SetWindowPlacementInsensibly(HWND hWnd, const WINDOWPLACEMENT* wp) : m_hWnd(hWnd) { m_oldWindowProc = (WNDPROC)(::SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, LONG_PTR(&WndProc))); ::SetWindowPlacement(m_hWnd, wp); } ~SetWindowPlacementInsensibly() { ::SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, LONG_PTR(m_oldWindowProc)); } static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT res = 0; switch (uMsg) { case WM_PAINT: case WM_NCACTIVATE: case WM_ACTIVATE: case WM_SIZE: break; default: res =::DefWindowProc(hWnd, uMsg, wParam, lParam); } return res; } private: HWND m_hWnd; WNDPROC m_oldWindowProc; }; } template<class TStorage> class CWindowStateMgr { protected: class CImpl : public CContainerImpl<TStorage> { typedef CContainerImpl<TStorage> baseClass; public: CImpl(HWND hWnd = NULL, int nDefCmdShow = SW_SHOWDEFAULT) : m_hWnd(hWnd), m_nDefCmdShow(nDefCmdShow) { } void SetWindow(HWND hWnd = NULL, int nDefCmdShow = SW_SHOWDEFAULT) { ATLASSERT(::IsWindow(hWnd)); m_hWnd = hWnd; m_nDefCmdShow = nDefCmdShow; } virtual bool Store(IStorge& stg) { ATLASSERT(IsWindow(m_hWnd)); WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); bool bRes = false; if (::GetWindowPlacement(m_hWnd, &wp)) { if (wp.showCmd == SW_SHOWMINIMIZED) wp.showCmd = SW_SHOWNORMAL; wp.flags &= WPF_RESTORETOMAXIMIZED; // if(::IsZoomed(m_hWnd)) // wp.flags |= WPF_RESTORETOMAXIMIZED; if (wp.flags != 0) wp.showCmd = SW_SHOWMAXIMIZED; bRes = (stg.SetBinary(ctxtPlacement, &wp, sizeof(WINDOWPLACEMENT)) == ERROR_SUCCESS); /* bRes=(::RegSetValueEx(key,ctxtPlacement,NULL,REG_BINARY, reinterpret_cast<CONST BYTE *>(&wp), sizeof(WINDOWPLACEMENT))==ERROR_SUCCESS); */ } return baseClass::Store(stg); } virtual bool Restore(IStorge& stg, const std::pair<long, long>& xratio, const std::pair<long, long>& yratio) { ATLASSERT(IsWindow(m_hWnd)); WINDOWPLACEMENT wp; /* DWORD dwType; DWORD cbData=sizeof(WINDOWPLACEMENT); bool bRes=(::RegQueryValueEx(key,ctxtPlacement,NULL,&dwType, reinterpret_cast<LPBYTE>(&wp),&cbData)==ERROR_SUCCESS) &&(dwType==REG_BINARY); */ size_t size = sizeof(WINDOWPLACEMENT); bool bRes = (stg.GetBinary(ctxtPlacement, &wp, size) == ERROR_SUCCESS && (size == sizeof(WINDOWPLACEMENT))); if (bRes) { wp.ptMaxPosition.x = long(::MulDiv(wp.ptMaxPosition.x, xratio.first, xratio.second)); wp.ptMaxPosition.y = long(::MulDiv(wp.ptMaxPosition.y, yratio.first, yratio.second)); wp.ptMinPosition.x = long(::MulDiv(wp.ptMinPosition.x, xratio.first, xratio.second)); wp.ptMinPosition.y = long(::MulDiv(wp.ptMinPosition.y, yratio.first, yratio.second)); wp.rcNormalPosition.left = long(::MulDiv(wp.rcNormalPosition.left, xratio.first, xratio.second)); wp.rcNormalPosition.top = long(::MulDiv(wp.rcNormalPosition.top, yratio.first, yratio.second)); wp.rcNormalPosition.right = long(::MulDiv(wp.rcNormalPosition.right, xratio.first, xratio.second)); wp.rcNormalPosition.bottom = long(::MulDiv(wp.rcNormalPosition.bottom, yratio.first, yratio.second)); UINT showCmd = ((m_nDefCmdShow & ForceDefaultCmdShow) != 0) ? m_nDefCmdShow & (~ForceDefaultCmdShow) : wp.showCmd; wp.showCmd = SW_HIDE; if (showCmd == SW_MAXIMIZE) { RECT rc; GetWorkAreaOfMonitorFromWindow(&rc); ::SetWindowPos(m_hWnd, 0, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_DEFERERASE | SWP_NOREDRAW | /*SWP_NOCOPYBITS|*/ SWP_NOACTIVATE | SWP_NOZORDER); bRes = baseClass::Restore(stg, xratio, yratio); { SetWindowPlacementInsensibly(m_hWnd, &wp); } ::ShowWindow(m_hWnd, SW_MAXIMIZE); ::SetWindowPos(m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING); } else { ::SetWindowPlacement(m_hWnd, &wp); bRes = baseClass::Restore(stg, xratio, yratio); ::ShowWindow(m_hWnd, showCmd); } ::SetForegroundWindow(m_hWnd); // Win95 needs this } else bRes = baseClass::RestoreDefault(); return bRes; } virtual bool RestoreDefault() { ATLASSERT(IsWindow(m_hWnd)); bool bRes = baseClass::RestoreDefault(); ShowWindow(m_hWnd, m_nDefCmdShow & (~ForceDefaultCmdShow)); return bRes; } void GetWorkAreaOfMonitorFromWindow(RECT* rc) { #ifdef HMONITOR_DECLARED MONITORINFO info; info.cbSize = sizeof(MONITORINFO); HMONITOR mon; if (m_hWnd != 0 && ((mon =::MonitorFromWindow(m_hWnd, MONITOR_DEFAULTTOPRIMARY)) != 0) && (::GetMonitorInfo(mon, &info))) ::CopyRect(rc, &info.rcWork); else #endif// HMONITOR_DECLARED { if (!::SystemParametersInfo(SPI_GETWORKAREA, 0, rc, 0)) { rc->left = rc->top = 0; rc->right =::GetSystemMetrics(SM_CXFULLSCREEN); rc->bottom =::GetSystemMetrics(SM_CYFULLSCREEN); } } } protected: HWND m_hWnd; int m_nDefCmdShow; }; public: CWindowStateMgr(HWND hWnd = NULL, int nDefCmdShow = SW_SHOWDEFAULT) { m_pImpl = new CImpl(hWnd, nDefCmdShow); } ~CWindowStateMgr() { ATLASSERT(m_pImpl); m_pImpl->Release(); } operator IState* () { return m_pImpl; } ID Add(IState* pState) { return m_pImpl->Add(pState); } void Add(ID id, IState* pState) { m_pImpl->Add(id, pState); } void Remove(ID id) { m_pImpl->Remove(id); } void Initialize(HWND hWnd, int nDefCmdShow = SW_SHOWDEFAULT) { m_pImpl->SetWindow(hWnd, nDefCmdShow); } bool Store(TStorage& stgMain) { TStorage general; if (general.Create(stgMain, ctxtGeneral, IStorge::ReadWrite) == ERROR_SUCCESS) { RECT rc; m_pImpl->GetWorkAreaOfMonitorFromWindow(&rc); DWORD val = rc.right - rc.left/*::GetSystemMetrics(SM_CXSCREEN)*/; general.SetBinary(ctxtCXScreen, &val, sizeof(DWORD)); val = rc.bottom - rc.top/*::GetSystemMetrics(SM_CYSCREEN)*/; general.SetBinary(ctxtCYScreen, &val, sizeof(DWORD)); } TStorage stg; bool bRes = (stg.Create(stgMain, ctxtMainWindow, IStorge::ReadWrite) == ERROR_SUCCESS); if (bRes) bRes = m_pImpl->Store(stg); // DWORD dwDisposition; // CRegKey keyMain; // if(keyMain.Create(HKEY_CURRENT_USER,m_strMainKey.c_str(),REG_NONE, // REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, // NULL,&dwDisposition)==ERROR_SUCCESS) // { // CRegKey keyGeneral; // if(keyGeneral.Create(keyMain,ctxtGeneral,REG_NONE, // REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, // NULL,&dwDisposition)==ERROR_SUCCESS) // { // // DWORD val=::GetSystemMetrics(SM_CXSCREEN); // ::RegSetValueEx(keyGeneral, ctxtCXScreen, NULL, REG_DWORD, // reinterpret_cast<BYTE*>(&val), sizeof(DWORD)); // val=::GetSystemMetrics(SM_CYSCREEN); // ::RegSetValueEx(keyGeneral, ctxtCYScreen, NULL, REG_DWORD, // reinterpret_cast<BYTE*>(&val), sizeof(DWORD)); // /* // keyGeneral.SetValue(::GetSystemMetrics(SM_CXSCREEN),ctxtCXScreen); // keyGeneral.SetValue(::GetSystemMetrics(SM_CYSCREEN),ctxtCYScreen); // */ // } // CRegKey key; // if(key.Create(keyMain,ctxtMainWindow,REG_NONE, // REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, // NULL,&dwDisposition)==ERROR_SUCCESS) // m_pImpl->Store(key); // } return bRes; } bool Restore(TStorage& stgMain) { TStorage general; bool bRes = (general.Open(stgMain, ctxtGeneral, IStorge::Read) == ERROR_SUCCESS); if (bRes) { RECT rc; m_pImpl->GetWorkAreaOfMonitorFromWindow(&rc); std::pair<long, long> xratio(rc.right - rc.left, 1); std::pair<long, long> yratio(rc.bottom - rc.top, 1); DWORD val; size_t size = sizeof(DWORD); if (general.GetBinary(ctxtCXScreen, &val, size) == ERROR_SUCCESS && (size == sizeof(DWORD)) && (xratio.first != long(val))) xratio.second = long(val); else xratio.first = 1; size = sizeof(DWORD); if (general.GetBinary(ctxtCYScreen, &val, size) == ERROR_SUCCESS && (size == sizeof(DWORD)) && (yratio.first != long(val))) yratio.second = long(val); else yratio.first = 1; /* SIZE szScreen; size_t size = sizeof(DWORD); float xratio=(general.GetBinary(ctxtCXScreen,&szScreen.cx,size)==ERROR_SUCCESS && (size == sizeof(DWORD)) ?float(::GetSystemMetrics(SM_CXSCREEN))/szScreen.cx :float(1.0)); size = sizeof(DWORD); float yratio=(general.GetBinary(ctxtCYScreen,&szScreen.cy,size)==ERROR_SUCCESS && (size == sizeof(DWORD)) ?float(::GetSystemMetrics(SM_CYSCREEN))/szScreen.cy :float(1.0)); */ TStorage stg; bRes = (stg.Open(stgMain, ctxtMainWindow, IStorge::Read) == ERROR_SUCCESS && m_pImpl->Restore(stg, xratio, yratio)); } // CRegKey keyMain; // CRegKey keyGeneral; // bool bRes=keyMain.Open(HKEY_CURRENT_USER,m_strMainKey.c_str(),KEY_READ)==ERROR_SUCCESS // && (keyGeneral.Open(keyMain,ctxtGeneral,KEY_READ)==ERROR_SUCCESS); // if(bRes) // { // SIZE szScreen; // DWORD dwCount = sizeof(DWORD); // float xratio=(::RegQueryValueEx(keyGeneral,ctxtCXScreen,NULL,NULL, // reinterpret_cast<LPBYTE>(&szScreen.cx),&dwCount) ==ERROR_SUCCESS // && (dwCount == sizeof(DWORD))) // ?float(::GetSystemMetrics(SM_CXSCREEN))/szScreen.cx // :float(1.0); // dwCount = sizeof(DWORD); // float yratio=(::RegQueryValueEx(keyGeneral,ctxtCYScreen,NULL,NULL, // reinterpret_cast<LPBYTE>(&szScreen.cy),&dwCount) ==ERROR_SUCCESS // &&(dwCount == sizeof(DWORD))) // ?float(::GetSystemMetrics(SM_CYSCREEN))/szScreen.cy // :float(1.0); // /* // xratio=(keyGeneral.QueryValue(reinterpret_cast<DWORD&>(szScreen.cx),ctxtCXScreen)==ERROR_SUCCESS) // ?float(::GetSystemMetrics(SM_CXSCREEN))/szScreen.cx // :float(1.0); // yratio=(keyGeneral.QueryValue(reinterpret_cast<DWORD&>(szScreen.cy),ctxtCYScreen)==ERROR_SUCCESS) // ?float(::GetSystemMetrics(SM_CYSCREEN))/szScreen.cy // :float(1.0); // */ // CRegKey key; // bRes=key.Open(keyMain,ctxtMainWindow,KEY_READ)==ERROR_SUCCESS // && m_pImpl->Restore(key,xratio,yratio); // // } if (!bRes) bRes = m_pImpl->RestoreDefault(); return bRes; } bool RestoreDefault() { return m_pImpl->RestoreDefault(); } protected: CImpl* m_pImpl; }; class CWindowStateAdapter { protected: class CImpl : public CStateBase<IState> { public: CImpl(HWND hWnd, int nDefCmdShow = SW_SHOWNA) : m_hWnd(hWnd), m_nDefCmdShow(nDefCmdShow) { ATLASSERT(::IsWindow(hWnd)); } virtual bool Store(IStorge& stg) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ATLASSERT(::IsWindow(m_hWnd)); bool bRes = false; if (::GetWindowPlacement(m_hWnd, &wp)) { wp.flags = 0; if (::IsZoomed(m_hWnd)) wp.flags |= WPF_RESTORETOMAXIMIZED; /* bRes=(::RegSetValueEx(key,ctxtPlacement,NULL,REG_BINARY, reinterpret_cast<CONST BYTE *>(&wp), sizeof(WINDOWPLACEMENT))==ERROR_SUCCESS); */ bRes = (stg.SetBinary(ctxtPlacement, &wp, sizeof(WINDOWPLACEMENT)) == ERROR_SUCCESS); } return bRes; } virtual bool Restore(IStorge& stg, const std::pair<long, long>& /*xratio*/, const std::pair<long, long>& /*yratio*/) { ATLASSERT(::IsWindow(m_hWnd)); WINDOWPLACEMENT wp; /* DWORD dwType; DWORD cbData=sizeof(WINDOWPLACEMENT); bool bRes=(::RegQueryValueEx(key,ctxtPlacement,NULL,&dwType, reinterpret_cast<LPBYTE>(&wp),&cbData)==ERROR_SUCCESS) &&(dwType==REG_BINARY); */ size_t size = sizeof(WINDOWPLACEMENT); bool bRes = (stg.GetBinary(ctxtPlacement, &wp, size) == ERROR_SUCCESS && (size == sizeof(WINDOWPLACEMENT))); if (bRes) bRes = (::SetWindowPlacement(m_hWnd, &wp) != FALSE); return bRes; } virtual bool RestoreDefault() { ::ShowWindow(m_hWnd, m_nDefCmdShow); return true; } protected: HWND m_hWnd; int m_nDefCmdShow; }; public: CWindowStateAdapter(HWND hWnd, int nDefCmdShow = SW_SHOWNOACTIVATE) { m_pImpl = new CImpl(hWnd, nDefCmdShow); } ~CWindowStateAdapter() { ATLASSERT(m_pImpl); m_pImpl->Release(); } operator IState* () { return m_pImpl; } protected: CImpl* m_pImpl; }; class CToggleWindowAdapter { protected: class CImpl : public CStateBase<IState> { public: CImpl(HWND hWnd, int nDefCmdShow = SW_SHOWNA) : m_hWnd(hWnd), m_nDefCmdShow(nDefCmdShow) { ATLASSERT(::IsWindow(hWnd)); } virtual bool Store(IStorge& stg) { DWORD visible = (::GetWindowLong(m_hWnd, GWL_STYLE)&WS_VISIBLE) != 0; // DWORD visible=::IsWindowVisible(m_hWnd); /* return (::RegSetValueEx(key, ctxtVisible, NULL, REG_DWORD, reinterpret_cast<BYTE*>(&visible), sizeof(DWORD))==ERROR_SUCCESS); // return (key.SetValue(visible,ctxtVisible)==ERROR_SUCCESS); */ return (stg.SetBinary(ctxtVisible, &visible, sizeof(DWORD)) == ERROR_SUCCESS); } virtual bool Restore(IStorge& stg, const std::pair<long, long>& /*xratio*/, const std::pair<long, long>& /*yratio*/) { DWORD visible; // bool bRes=(key.QueryValue(visible,ctxtVisible)==ERROR_SUCCESS); /* DWORD dwCount = sizeof(DWORD); bool bRes=(::RegQueryValueEx(key,ctxtVisible,NULL,NULL, reinterpret_cast<LPBYTE>(&visible),&dwCount)==ERROR_SUCCESS && (dwCount == sizeof(DWORD))); */ size_t size = sizeof(DWORD); bool bRes = (stg.GetBinary(ctxtVisible, &visible, size) == ERROR_SUCCESS && (size == sizeof(DWORD))); if (bRes) ::ShowWindow(m_hWnd, (visible != 0) ? SW_SHOWNA : SW_HIDE); else RestoreDefault(); return bRes; } virtual bool RestoreDefault() { ::ShowWindow(m_hWnd, m_nDefCmdShow); return true; } protected: HWND m_hWnd; int m_nDefCmdShow; }; public: CToggleWindowAdapter(HWND hWnd, int nDefCmdShow = SW_SHOWNOACTIVATE) { m_pImpl = new CImpl(hWnd, nDefCmdShow); } ~CToggleWindowAdapter() { ATLASSERT(m_pImpl); m_pImpl->Release(); } operator IState* () { return m_pImpl; } protected: CImpl* m_pImpl; }; class CRebarStateAdapter { protected: class CImpl : public CStateBase<IState> { public: CImpl(HWND hWnd) : m_rebar(hWnd) { ATLASSERT(::IsWindow(hWnd)); } virtual bool Store(IStorge& stg) { ATLASSERT(m_rebar.IsWindow()); unsigned int bandCount = m_rebar.GetBandCount(); for (unsigned int i = 0; i < bandCount; i++) { std::basic_ostringstream<TCHAR> sstrKey; sstrKey << ctxtBand << i; REBARBANDINFO rbi; ZeroMemory(&rbi, sizeof(REBARBANDINFO)); rbi.cbSize = sizeof(REBARBANDINFO); rbi.fMask = RBBIM_ID | RBBIM_COLORS | RBBIM_SIZE | RBBIM_STYLE | RBBIM_CHILDSIZE #if (_WIN32_IE >= 0x0400) | /*RBBIM_HEADERSIZE |*/ RBBIM_IDEALSIZE #endif ; m_rebar.GetBandInfo(i, &rbi); /* ::RegSetValueEx(key,sstrKey.str().c_str(),NULL,REG_BINARY, reinterpret_cast<CONST BYTE *>(&rbi), rbi.cbSize); */ stg.SetBinary(sstrKey.str().c_str(), &rbi, size_t(rbi.cbSize)); } return true; } virtual bool Restore(IStorge& stg, const std::pair<long, long>& /*xratio*/, const std::pair<long, long>& /*yratio*/) { unsigned int bandCount = m_rebar.GetBandCount(); for (unsigned int i = 0; i < bandCount; i++) { std::basic_ostringstream<TCHAR> sstrKey; sstrKey << ctxtBand << i; REBARBANDINFO rbi; //ZeroMemory(&rbi,sizeof(REBARBANDINFO)); /* DWORD dwType; DWORD cbData=sizeof(REBARBANDINFO); if((::RegQueryValueEx(key,sstrKey.str().c_str(),NULL,&dwType, reinterpret_cast<LPBYTE>(&rbi),&cbData)==ERROR_SUCCESS) &&(dwType==REG_BINARY)) */ size_t size = sizeof(REBARBANDINFO); if (stg.GetBinary(sstrKey.str().c_str(), &rbi, size) == ERROR_SUCCESS && (size == sizeof(REBARBANDINFO))) { m_rebar.MoveBand(m_rebar.IdToIndex(rbi.wID), i); m_rebar.SetBandInfo(i, &rbi); } } return true; } virtual bool RestoreDefault() { return true; } protected: CReBarCtrl m_rebar; }; public: CRebarStateAdapter(HWND hWnd) { m_pImpl = new CImpl(hWnd); } ~CRebarStateAdapter() { ATLASSERT(m_pImpl); m_pImpl->Release(); } operator IState* () { return m_pImpl; } protected: CImpl* m_pImpl; }; #ifdef __ATLSPLIT_H__ template <bool t_bVertical = true> class CSplitterWindowStateAdapter { protected: template <bool t_bVertical> class CImplT : public CStateBase<IState> { public: CImplT(CSplitterWindow& splitter, int defaultPos) : m_splitter(splitter) , m_defaultPos(defaultPos) { } virtual bool Store(IStorge& stg) { int pos = m_splitter.GetSplitterPos(); return (stg.SetBinary(ctxtPosition, &pos, sizeof(int)) == ERROR_SUCCESS); } virtual bool Restore(IStorge& stg, const std::pair<long, long>& xratio, const std::pair<long, long>& yratio) { int pos; size_t size = sizeof(int); bool res = (stg.GetBinary(ctxtPosition, &pos, size) == ERROR_SUCCESS && (size == sizeof(int))); if (res) { if (t_bVertical) pos =::MulDiv(pos, xratio.first, xratio.second); else pos =::MulDiv(pos, yratio.first, yratio.second); m_splitter.SetSplitterPos(pos); } return true; } virtual bool RestoreDefault() { m_splitter.SetSplitterPos(m_defaultPos); return true; } protected: CSplitterWindowT<t_bVertical>& m_splitter; int m_defaultPos; }; typedef CImplT<t_bVertical> CImpl; public: CSplitterWindowStateAdapter(CSplitterWindow& splitter, int defaultPos = -1) { m_pImpl = new CImpl(splitter, defaultPos); } ~CSplitterWindowStateAdapter() { ATLASSERT(m_pImpl); m_pImpl->Release(); } operator IState* () { return m_pImpl; } protected: CImpl* m_pImpl; }; #endif // __ATLSPLIT_H__ } // namespace sstate #endif // WTL_DW_SSTATE_H_INCLUDED_
[ [ [ 1, 928 ] ] ]
6d3de25e52f01b59ec579bfa1bafa857223c773a
16d6176d43bf822ad8d86d4363c3fee863ac26f9
/Submission/Submission/Source code/rayTracer/Transform.h
f92abce6434c1b62b8923fbb70f01741119959a5
[]
no_license
preethinarayan/cgraytracer
7a0a16e30ef53075644700494b2f8cf2a0693fbd
46a4a22771bd3f71785713c31730fdd8f3aebfc7
refs/heads/master
2016-09-06T19:28:04.282199
2008-12-10T00:02:32
2008-12-10T00:02:32
32,247,889
0
0
null
null
null
null
UTF-8
C++
false
false
584
h
#pragma once #include "nv_math.h" #define MAX_DEPTH 10 /* maintain current transform stack */ class Transform { mat4 *stack[MAX_DEPTH]; int top; mat4 currTransform; void calcCurrTransform(); void push(mat4 M); mat4 pop(); bool isEmpty(){return top==-1;}; bool isFull(){return top==MAX_DEPTH-1;}; public: Transform(void); mat4 getCurrTransform(){return currTransform;}; /* commands */ bool pushMatrix(); bool popMatrix(); bool translate(char **args); bool rotate(char **args); bool scale(char **args); public: ~Transform(void); };
[ "[email protected]@074c0a88-b503-11dd-858c-a3a1ac847323" ]
[ [ [ 1, 31 ] ] ]
7417affc02ee38fdff0b72185e41580a5a9636d0
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/tools/hoportal/main.cpp
2adb318f29500a9516873fd5d192b75185282352
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,971
cpp
/*** * hoportal: main.cpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include <iostream> #include <string> #include <vector> #include <boost/lexical_cast.hpp> using boost::bad_lexical_cast; using boost::lexical_cast; #include <source/io/files/OnionPortalsFile.h> #include <source/io/files/OnionTreeFile.h> #include <source/level/portals/OnionPortalGenerator.h> #include <source/level/trees/OnionTree.h> #include <source/util/PolygonTypes.h> using namespace hesp; //#################### FUNCTIONS #################### void quit_with_error(const std::string& error) { std::cout << "Error: " << error << std::endl; exit(EXIT_FAILURE); } void quit_with_usage() { std::cout << "Usage: hoportal {-r|-c} <input filename> <output filename>" << std::endl; exit(EXIT_FAILURE); } template <typename Poly> void run_generator(const std::string& inputFilename, const std::string& outputFilename) { typedef shared_ptr<Poly> Poly_Ptr; typedef std::vector<Poly_Ptr> PolyVector; // Read in the polygons and onion tree. PolyVector polygons; OnionTree_Ptr tree; OnionTreeFile::load(inputFilename, polygons, tree); // Generate the onion portals. shared_ptr<std::list<OnionPortal_Ptr> > portals = OnionPortalGenerator().generate_portals(tree); // Save the onion portals to the output file. std::vector<OnionPortal_Ptr> vec(portals->begin(), portals->end()); OnionPortalsFile::save(outputFilename, vec); } int main(int argc, char *argv[]) try { if(argc != 4) quit_with_usage(); const std::vector<std::string> args(argv, argv+argc); std::string inputFilename = args[2]; std::string outputFilename = args[3]; if(args[1] == "-r") run_generator<TexturedPolygon>(inputFilename, outputFilename); else if(args[1] == "-c") run_generator<CollisionPolygon>(inputFilename, outputFilename); else quit_with_usage(); return 0; } catch(Exception& e) { quit_with_error(e.cause()); }
[ [ [ 1, 69 ] ] ]
f639fb007afa1e960b6ee9ae34d2fd365962e7b3
f5a3e2fcfe01bfe95d125a903c0af454c1b9cdd6
/PoppingTabWidget.cpp
cd7b2c2c1f7f896f938a05a25c899ad72aa2189d
[]
no_license
congchenutd/congchenmywords
11418c97d3d260d35766cdfbb9968a54f569fad7
29fd31f7e7a99b17fe789e9d97879728ea9dbb80
refs/heads/master
2021-01-02T09:08:59.667661
2011-02-21T02:05:05
2011-02-21T02:05:05
32,358,808
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
#include "PoppingTabWidget.h" #include "PoppingTabBar.h" #include "UserSetting.h" #include "MainWindow.h" #include <QTabBar> #include <QDesktopWidget> #include <QApplication> PoppingTabWidget::PoppingTabWidget(QWidget *parent) : QTabWidget(parent) { PoppingTabBar* tb = new PoppingTabBar(this); setTabBar(tb); connect(&timerHide, SIGNAL(timeout()), this, SLOT(slotShrink())); connect(&timerShow, SIGNAL(timeout()), this, SLOT(slotExtend())); connect(tb, SIGNAL(extend()), this, SLOT(slotExtend())); connect(tb, SIGNAL(shrink()), this, SLOT(slotShrink())); } void PoppingTabWidget::leaveEvent(QEvent* event) { if(autoHide()) { timerHide.start(hideDelay() * 1000); timerShow.stop(); } QWidget::leaveEvent(event); } void PoppingTabWidget::enterEvent(QEvent* event) { if(autoHide()) { timerHide.stop(); timerShow.start(showDelay() * 1000); } QWidget::enterEvent(event); } void PoppingTabWidget::slotExtend() { timerShow.stop(); setMaximumWidth(1000); setMinimumWidth(getMinShowWidth()); } void PoppingTabWidget::slotShrink() { timerHide.stop(); setMinimumWidth(tabBar()->width()); setMaximumWidth(tabBar()->width()); } void PoppingTabWidget::showEvent(QShowEvent*) { autoHide() ? slotShrink() : slotExtend(); } bool PoppingTabWidget::autoHide() const { return UserSetting::getInstance(MainWindow::userName)->value("LeftPanel/autoHide").toBool(); } int PoppingTabWidget::showDelay() const { return UserSetting::getInstance(MainWindow::userName)->value("LeftPanel/showDelay").toInt(); } int PoppingTabWidget::hideDelay() const { return UserSetting::getInstance(MainWindow::userName)->value("LeftPanel/hideDelay").toInt(); } int PoppingTabWidget::getMinShowWidth() const { return QApplication::desktop()->screenGeometry().width() * 0.25; }
[ "congchenutd@33c296ca-c6a8-bfc7-d74f-b3a1fff04ced" ]
[ [ [ 1, 72 ] ] ]
6e38f815ce2fb4150893b3a89cd1421b3572e61e
e68cf672cdb98181db47dab9fb8c45e69b91e256
/src/ComputeDevice.cpp
0a0d9b5daad694a67862f6bbd2ef291425770837
[]
no_license
jiawen/QD3D11
09fc794f580db59bfc2faffbe3373a442180e0a5
c1411967bd2da8d012eddf640eeb5f7b86e66374
refs/heads/master
2021-01-21T13:52:48.111246
2011-12-19T19:07:17
2011-12-19T19:07:17
2,549,080
5
0
null
null
null
null
UTF-8
C++
false
false
1,799
cpp
#include "ComputeDevice.h" // static ComputeDevice* ComputeDevice::create( IDXGIAdapter* pAdapter ) { UINT createDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif // For some odd reason, D3D11 requires that: // if pAdapter != NULL (you used a known adapter) // then the driver type must be D3D_DRIVER_TYPE_UNKNOWN // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476082(v=vs.85).aspx D3D_DRIVER_TYPE driverType = ( pAdapter == NULL ) ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN; D3D_FEATURE_LEVEL requestedFeatureLevel = D3D_FEATURE_LEVEL_11_0; D3D_FEATURE_LEVEL actualFeatureLevel; ID3D11Device* pDevice; ID3D11DeviceContext* pImmediateContext; HRESULT hr = D3D11CreateDevice ( pAdapter, // existing DXGI adapter driverType, // driver type NULL, // HMODULE pointing to loaded software rasterizer dll createDeviceFlags, // device creation flags &requestedFeatureLevel, // DX feature level 1, // number of feature levels: 1 D3D11_SDK_VERSION, // SDK version, must be D3D11_SDK_VERSION &pDevice, &actualFeatureLevel, &pImmediateContext ); ComputeDevice* pCD = NULL; if( SUCCEEDED( hr ) ) { pCD = new ComputeDevice( pDevice, pImmediateContext ); } return pCD; } // virtual ComputeDevice::~ComputeDevice() { m_pImmediateContext->Release(); m_pDevice->Release(); } ID3D11Device* ComputeDevice::device() { return m_pDevice; } ID3D11DeviceContext* ComputeDevice::immediateContext() { return m_pImmediateContext; } ComputeDevice::ComputeDevice( ID3D11Device* pDevice, ID3D11DeviceContext* pImmediateContext ) : m_pDevice( pDevice ), m_pImmediateContext( pImmediateContext ) { }
[ [ [ 1, 73 ] ] ]
36015000862dc4b0c6c38db5aae84142029684b0
3920e5fc5cbc2512701a3d2f52e072fd50debb83
/Source/Common/itkManagedPixelType.cxx
487f1c2cdc868bb132f31d099a8464549b923630
[ "MIT" ]
permissive
amirsalah/manageditk
4063a37d7370dcbcd08bfe9d24d22015d226ceaf
1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761
refs/heads/master
2016-08-12T05:38:03.377086
2010-08-02T08:17:32
2010-08-02T08:17:32
52,595,294
0
0
null
null
null
null
UTF-8
C++
false
false
36,102
cxx
/*============================================================================= NOTE: THIS FILE IS A HANDMADE WRAPPER FOR THE ManagedITK PROJECT. Project: ManagedITK Program: Insight Segmentation & Registration Toolkit Module: itkManagedPixelType.cxx Language: C++/CLI Author: Dan Mueller Date: $Date: 2008-06-21 09:20:09 +0200 (Sat, 21 Jun 2008) $ Revision: $Revision: 18 $ Portions of this code are covered under the ITK and VTK copyright. See http://www.itk.org/HTML/Copyright.htm for details. See http://www.vtk.org/copyright.php for details. Copyright (c) 2007-2008 Daniel Mueller 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. =============================================================================*/ #pragma once #pragma warning( disable : 4635 ) // Disable warnings about XML doc comments #ifndef __itkManagedPixelType_cxx #define __itkManagedPixelType_cxx // Include some useful ManagedITK headers #include "itkManagedINativePointer.cxx" // Use some managed namespaces #using <mscorlib.dll> #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Reflection; using namespace System::ComponentModel; using namespace System::Diagnostics; namespace itk { ///<summary>This enumeration lists all the possible pixel types.</summary> public enum class itkPixelTypeEnum { UnsignedChar, SignedChar, UnsignedShort, SignedShort, UnsignedLong, SignedLong, Float, Double, Boolean }; ///<summary>This enumeration lists all the possible array types.</summary> public enum class itkPixelArrayEnum { Scalar, ArrayVector, ArrayCovariantVector, ArrayVariableLengthVector, ArrayVectorImage, ArrayRGB, ArrayRGBA }; ///<summary> ///This class is a managed replacement for the Image template variable TPixel. ///This class also acts in the role of itk::NumericTraits. ///</summary> ///<remarks> ///In native itk, images are templated over the pixel type: TPixel (eg. unsigned ///char, float, etc). In ManagedITK, to allow for the specification of image types ///at runtime, the itkPixelType and itkPixel classes were introduced. ///</remarks> public ref class itkPixelType : INativePointer { private: itkPixelTypeEnum m_TypeAsEnum; itkPixelArrayEnum m_ArrayAsEnum; unsigned int m_NumberOfComponentsPerPixel; public: ///<summary>Default constructor taking the pixel type. The type defaults to a single value (not an array).</summary> ///<param name="typeAsEnum">The enumerated type of the pixel.</param> itkPixelType ( itkPixelTypeEnum typeAsEnum ) { this->m_TypeAsEnum = typeAsEnum; this->m_ArrayAsEnum = itkPixelArrayEnum::Scalar; // Default to not an array this->m_NumberOfComponentsPerPixel = 1; // Default to 1 component per pixel } ///<summary>Constructor taking the pixel type and number of components in array types.</summary> ///<param name="typeAsEnum">The enumerated type of the pixel.</param> ///<param name="arrayAsEnum">The enumerated type of array.</param> ///<param name="numberOfComponentsPerPixel">The number of components in the pixel array.</param> itkPixelType ( itkPixelTypeEnum typeAsEnum, itkPixelArrayEnum arrayAsEnum, unsigned int numberOfComponentsPerPixel ) { // Set the member varuabkes this->m_TypeAsEnum = typeAsEnum; this->m_ArrayAsEnum = arrayAsEnum; this->m_NumberOfComponentsPerPixel = numberOfComponentsPerPixel; } ///<summary>Get the type of the pixel as an enumeration.</summary> property itkPixelTypeEnum TypeAsEnum { itkPixelTypeEnum get() { return this->m_TypeAsEnum; } } ///<summary>Get the type of the pixel element as an enumeration.</summary> property itkPixelArrayEnum ArrayAsEnum { itkPixelArrayEnum get() { return this->m_ArrayAsEnum; } } ///<summary>Get the number of components in array pixel types.</summary> ///<remarks> ///This property will be one for itkPixelArrayEnum::Scalar or zero if ///unknown at compile time (eg. itkPixelArrayEnum::VariableLengthVector). ///</remarks> property unsigned int NumberOfComponentsPerPixel { unsigned int get() { return this->m_NumberOfComponentsPerPixel; } } ///<summary>Get the number of bits the pixel type occupies.</summary> ///<remarks> ///Array element types (eg. Vector, CovariantVector) are adjusted for the ///size of the array by multiplying by the number of components in the array. ///</remarks> property unsigned int PixelSize { unsigned int get() { switch (this->m_TypeAsEnum) { case itkPixelTypeEnum::UnsignedChar: return 8*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::SignedChar: return 8*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::UnsignedShort: return 16*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::SignedShort: return 16*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::UnsignedLong: return 32*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::SignedLong: return 32*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::Float: return 16*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::Double: return 32*m_NumberOfComponentsPerPixel; case itkPixelTypeEnum::Boolean: return 1*m_NumberOfComponentsPerPixel; default: return 0; } } } ///<summary>Get the minimum value of the single element pixel type.</summary> property Object^ MinValue { Object^ get() { switch (this->m_TypeAsEnum) { case itkPixelTypeEnum::UnsignedChar: return (Object^)Byte::MinValue; case itkPixelTypeEnum::SignedChar: return (Object^)SByte::MinValue; case itkPixelTypeEnum::UnsignedShort: return (Object^)UInt16::MinValue; case itkPixelTypeEnum::SignedShort: return (Object^)Int16::MinValue; case itkPixelTypeEnum::UnsignedLong: return (Object^)UInt32::MinValue; case itkPixelTypeEnum::SignedLong: return (Object^)Int32::MinValue; case itkPixelTypeEnum::Float: return (Object^)Single::MinValue; case itkPixelTypeEnum::Double: return (Object^)Double::MinValue; case itkPixelTypeEnum::Boolean: return (Object^)false; default: return (Object^)0; } } } ///<summary>Get the maximum value of the single element pixel type.</summary> property Object^ MaxValue { Object^ get() { switch (this->m_TypeAsEnum) { case itkPixelTypeEnum::UnsignedChar: return (Object^)Byte::MaxValue; case itkPixelTypeEnum::SignedChar: return (Object^)SByte::MaxValue; case itkPixelTypeEnum::UnsignedShort: return (Object^)UInt16::MaxValue; case itkPixelTypeEnum::SignedShort: return (Object^)Int16::MaxValue; case itkPixelTypeEnum::UnsignedLong: return (Object^)UInt32::MaxValue; case itkPixelTypeEnum::SignedLong: return (Object^)Int32::MaxValue; case itkPixelTypeEnum::Float: return (Object^)Single::MaxValue; case itkPixelTypeEnum::Double: return (Object^)Double::MaxValue; case itkPixelTypeEnum::Boolean: return (Object^)true; default: return (Object^)0; } } } ///<summary>Get the zero value of the single element pixel type.</summary> property Object^ Zero { Object^ get() { switch (this->m_TypeAsEnum) { case itkPixelTypeEnum::UnsignedChar: // Fall through case itkPixelTypeEnum::SignedChar: // Fall through case itkPixelTypeEnum::UnsignedShort: // Fall through case itkPixelTypeEnum::SignedShort: // Fall through case itkPixelTypeEnum::UnsignedLong: // Fall through case itkPixelTypeEnum::SignedLong: return (Object^)0; case itkPixelTypeEnum::Float: // Fall through case itkPixelTypeEnum::Double: return (Object^)0.0; case itkPixelTypeEnum::Boolean: return (Object^)false; default: return (Object^)0; } } } ///<summary> ///Get if the pixel is a scalar value (one value per pixel) ///or a vector/array value (mor than one value per pixel). ///</summary> ///<returns>True if the type is a scalar, false otherwise.</returns> property bool IsScalar { bool get() { return (this->m_ArrayAsEnum == itkPixelArrayEnum::Scalar); } } ///<summary> ///Get if the pixel is a scalar value (one value per pixel) ///or a vector/array value (mor than one value per pixel). ///</summary> ///<returns>True if the type is an array or vector, false otherwise.</returns> property bool IsArray { bool get() { return (this->m_ArrayAsEnum != itkPixelArrayEnum::Scalar); } } ///<summary> ///Get if the pixel is a color value (ie. RGB or RGBA) value. ///</summary> ///<returns>True if the type is a color type (ie. RGB or RGBA), false otherwise.</returns> property bool IsColor { bool get() { return (this->m_ArrayAsEnum == itkPixelArrayEnum::ArrayRGB || this->m_ArrayAsEnum == itkPixelArrayEnum::ArrayRGBA); } } ///<summary> ///Get if the pixel value type is a char value (ie. unsigned char or signed char). ///</summary> ///<returns>True if the pixel type is a char value (ie. unsigned char or signed char), false otherwise.</returns> property bool IsChar { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::UnsignedChar || this->m_TypeAsEnum == itkPixelTypeEnum::SignedChar); } } ///<summary> ///Get if the pixel value type is a short value (ie. unsigned short or signed short). ///</summary> ///<returns>True if the pixel type is a short value (ie. unsigned short or signed short), false otherwise.</returns> property bool IsShort { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::UnsignedShort || this->m_TypeAsEnum == itkPixelTypeEnum::SignedShort); } } ///<summary> ///Get if the pixel value type is a long value (ie. unsigned long or signed long). ///</summary> ///<returns>True if the pixel type is a long value (ie. unsigned long or signed long), false otherwise.</returns> property bool IsLong { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::UnsignedLong || this->m_TypeAsEnum == itkPixelTypeEnum::SignedLong); } } ///<summary> ///Get if the pixel value type is a real value (ie. float or double), ///as opposed to an integer value. ///</summary> ///<returns>True if the pixel type is float or double, false otherwise.</returns> property bool IsReal { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::Float || this->m_TypeAsEnum == itkPixelTypeEnum::Double); } } ///<summary> ///Get if the pixel value type is a single bit value (ie. boolean). ///</summary> ///<returns>True if the pixel type is boolean, false otherwise.</returns> property bool IsSingleBit { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::Boolean); } } ///<summary> ///Get if the pixel value type is an integer value (ie. unsigned char, signed long, etc), ///as opposed to a real value. ///</summary> ///<returns>True if the pixel type is integer (ie. unsigned char, signed long, etc), false otherwise.</returns> property bool IsInteger { bool get() { return !this->IsReal; } } ///<summary> ///Get if the pixel value type is an signed value (ie. signed char, signed long, float, etc). ///</summary> ///<returns>True if the pixel type is signed (ie. signed char, signed long, float, etc), false otherwise.</returns> property bool IsSigned { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::SignedChar || this->m_TypeAsEnum == itkPixelTypeEnum::SignedShort || this->m_TypeAsEnum == itkPixelTypeEnum::SignedLong || this->m_TypeAsEnum == itkPixelTypeEnum::Float || this->m_TypeAsEnum == itkPixelTypeEnum::Double); } } ///<summary> ///Get if the pixel value type is an unsigned value (ie. unsigned char, unsigned long, etc). ///Boolean pixel values are considered unsigned. ///</summary> ///<returns>True if the pixel type is unsigned (ie. unsigned char, unsigned long, etc), false otherwise.</returns> property bool IsUnsigned { bool get() { return (this->m_TypeAsEnum == itkPixelTypeEnum::UnsignedChar || this->m_TypeAsEnum == itkPixelTypeEnum::UnsignedShort || this->m_TypeAsEnum == itkPixelTypeEnum::UnsignedLong || this->m_TypeAsEnum == itkPixelTypeEnum::Boolean); } } ///<summary>Get a string representing the type instance of this INativePointer.</summary> ///<example>"UC" = UnsignedChar, "SS" = Signed Short, "F" = float.</example> virtual property String^ MangledTypeString { String^ get() { String^ format = String::Empty; switch (this->m_ArrayAsEnum) { case itkPixelArrayEnum::Scalar: format = "{0}"; break; case itkPixelArrayEnum::ArrayVector: format = "V{0}" + this->m_NumberOfComponentsPerPixel.ToString(); break; case itkPixelArrayEnum::ArrayCovariantVector: format = "CV{0}" + this->m_NumberOfComponentsPerPixel.ToString(); break; case itkPixelArrayEnum::ArrayVariableLengthVector: format = "VLV{0}"; break; case itkPixelArrayEnum::ArrayVectorImage: format = "VI{0}"; break; case itkPixelArrayEnum::ArrayRGB: format = "RGB{0}"; break; case itkPixelArrayEnum::ArrayRGBA: format = "RGBA{0}"; break; default: format = "Unknown{0}"; } switch (this->m_TypeAsEnum) { case itkPixelTypeEnum::UnsignedChar: return String::Format(format, "UC"); case itkPixelTypeEnum::SignedChar: return String::Format(format, "SC"); case itkPixelTypeEnum::UnsignedShort: return String::Format(format, "US"); case itkPixelTypeEnum::SignedShort: return String::Format(format, "SS"); case itkPixelTypeEnum::UnsignedLong: return String::Format(format, "UL"); case itkPixelTypeEnum::SignedLong: return String::Format(format, "SL"); case itkPixelTypeEnum::Float: return String::Format(format, "F"); case itkPixelTypeEnum::Double: return String::Format(format, "D"); case itkPixelTypeEnum::Boolean: return String::Format(format, "B"); default: return String::Empty; } } } ///<summary>The NativePointer property is not applicable for itkPixelType.</summary> ///<returns>Always returns zero for itkPixelType.</returns> virtual property IntPtr NativePointer { // INativePointer.NativePointer is not applicable for itkPixelType. IntPtr get() { return IntPtr::Zero; } void set(IntPtr ptr) { /*Do nothing*/ } } ///<summary>Get a 'long' string representing the pixel type.</summary> ///<example>"Unsigned Char", "Float"</example> property String^ LongTypeString { String^ get() { String^ format = String::Empty; switch (this->m_ArrayAsEnum) { case itkPixelArrayEnum::Scalar: format = "{0}"; break; case itkPixelArrayEnum::ArrayVector: format = "Vector {0}"; break; case itkPixelArrayEnum::ArrayCovariantVector: format = "Covariant Vector {0}"; break; case itkPixelArrayEnum::ArrayVariableLengthVector: format = "Variable Length Vector {0}"; break; case itkPixelArrayEnum::ArrayVectorImage: format = "Vector Image {0}"; break; case itkPixelArrayEnum::ArrayRGB: format = "RGB {0}"; break; case itkPixelArrayEnum::ArrayRGBA: format = "RGBA {0}"; break; default: format = "Unknown {0}"; } switch (this->m_TypeAsEnum) { case itkPixelTypeEnum::UnsignedChar: return String::Format(format, "Unsigned Char"); case itkPixelTypeEnum::SignedChar: return String::Format(format, "Signed Char"); case itkPixelTypeEnum::UnsignedShort: return String::Format(format, "Unsigned Short"); case itkPixelTypeEnum::SignedShort: return String::Format(format, "Signed Short"); case itkPixelTypeEnum::UnsignedLong: return String::Format(format, "Unsigned Long"); case itkPixelTypeEnum::SignedLong: return String::Format(format, "Signed Long"); case itkPixelTypeEnum::Float: return String::Format(format, "Float"); case itkPixelTypeEnum::Double: return String::Format(format, "Double"); case itkPixelTypeEnum::Boolean: return String::Format(format, "Boolean"); default: return String::Empty; } } } ///<summary>Get a 'long' string representing the pixel type.</summary> ///<example>"Unsigned Char", "Float"</example> virtual String^ ToString() override { return this->LongTypeString; } ///<summary>Create a pixel type from a given string.</summary> ///<param name="mangledType">The type of the pixel as a string. Eg. "UC" = UnsignedChar.</param> ///<returns>A new pixel type instance of the type specified by the mangled string.</returns> ///<remarks>This method also works with a mangledType string from an image. Eg. "ISS3" = SignedShort.</remarks> static itkPixelType^ CreateFromMangledType(String^ mangledType) { const bool IGNORE_CASE = true; System::Globalization::CultureInfo^ currentCulture = System::Globalization::CultureInfo::CurrentCulture; // Trim any 'I's from the start String^ sType = mangledType->TrimStart('I', 'i'); // Setup default member information bool foundPixelType = false; itkPixelTypeEnum enumType = itkPixelTypeEnum::UnsignedChar; itkPixelArrayEnum enumArray = itkPixelArrayEnum::Scalar; System::Int32 iNumberOfComponentsPerPixel = 1; // Detect the element type // NOTE: The order of the below if statements are important! if (sType->StartsWith("VI", IGNORE_CASE, currentCulture)) { sType = sType->Replace("VI", ""); enumArray = itkPixelArrayEnum::ArrayVectorImage; iNumberOfComponentsPerPixel = 0; //TODO: The number of components is unknown } else if (sType->StartsWith("VLV", IGNORE_CASE, currentCulture)) { sType = sType->Replace("VLV", ""); enumArray = itkPixelArrayEnum::ArrayVariableLengthVector; iNumberOfComponentsPerPixel = 0; //TODO: The number of components is unknown } else if (sType->StartsWith("V", IGNORE_CASE, currentCulture)) { sType = sType->Replace("V", ""); enumArray = itkPixelArrayEnum::ArrayVector; } else if (sType->StartsWith("CV", IGNORE_CASE, currentCulture)) { sType = sType->Replace("CV", ""); enumArray = itkPixelArrayEnum::ArrayCovariantVector; } else if (sType->StartsWith("RGBA", IGNORE_CASE, currentCulture)) { sType = sType->Replace("RGBA", ""); enumArray = itkPixelArrayEnum::ArrayRGBA; iNumberOfComponentsPerPixel = 4; } else if (sType->StartsWith("RGB", IGNORE_CASE, currentCulture)) { sType = sType->Replace("RGB", ""); enumArray = itkPixelArrayEnum::ArrayRGB; iNumberOfComponentsPerPixel = 3; } // Detect the pixel type and get the number of elements String^ sNumberOfComponentsPerPixel = String::Empty; if (sType->StartsWith("UC", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::UnsignedChar; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(2, 1); } else if (sType->StartsWith("SC", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::SignedChar; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(2, 1); } else if (sType->StartsWith("US", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::UnsignedShort; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(2, 1); } else if (sType->StartsWith("SS", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::SignedShort; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(2, 1); } else if (sType->StartsWith("UL", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::UnsignedLong; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(2, 1); } else if (sType->StartsWith("SL", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::SignedLong; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(2, 1); } else if (sType->StartsWith("F", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::Float; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(1, 1); } else if (sType->StartsWith("D", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::Double; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(1, 1); } else if (sType->StartsWith("B", IGNORE_CASE, currentCulture)) { enumType = itkPixelTypeEnum::Boolean; foundPixelType = true; if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) sNumberOfComponentsPerPixel = sType->Substring(1, 1); } // Try to parse the number of elements if (enumArray == itkPixelArrayEnum::ArrayVector || enumArray == itkPixelArrayEnum::ArrayCovariantVector) { if ( !Int32::TryParse(sNumberOfComponentsPerPixel, iNumberOfComponentsPerPixel) ) throw gcnew NotSupportedException("The pixel type '" + mangledType + "' is not supported. The number of components per pixel could not be determined."); } // Check that we got everything if ( foundPixelType ) return gcnew itkPixelType(enumType, enumArray, iNumberOfComponentsPerPixel); else throw gcnew NotSupportedException("The pixel type '" + mangledType + "' is not supported. The pixel type could not be determined."); } // Scalar Pixel Types static itkPixelType^ UC = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar ); static itkPixelType^ SC = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar ); static itkPixelType^ US = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort ); static itkPixelType^ SS = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort ); static itkPixelType^ UL = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong ); static itkPixelType^ SL = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong ); static itkPixelType^ F = gcnew itkPixelType ( itkPixelTypeEnum::Float ); static itkPixelType^ D = gcnew itkPixelType ( itkPixelTypeEnum::Double ); static itkPixelType^ B = gcnew itkPixelType ( itkPixelTypeEnum::Boolean ); // Vector Pixel Types static itkPixelType^ VUC2 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VUC3 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VSC2 = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VSC3 = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VUS2 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VUS3 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VSS2 = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VSS3 = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VUL2 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VUL3 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VSL2 = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VSL3 = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VF2 = gcnew itkPixelType ( itkPixelTypeEnum::Float, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VF3 = gcnew itkPixelType ( itkPixelTypeEnum::Float, itkPixelArrayEnum::ArrayVector, 3 ); static itkPixelType^ VD2 = gcnew itkPixelType ( itkPixelTypeEnum::Double, itkPixelArrayEnum::ArrayVector, 2 ); static itkPixelType^ VD3 = gcnew itkPixelType ( itkPixelTypeEnum::Double, itkPixelArrayEnum::ArrayVector, 3 ); // CovariantVector Pixel Types static itkPixelType^ CVUC2 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVUC3 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVSC2 = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVSC3 = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVUS2 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVUS3 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVSS2 = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVSS3 = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVUL2 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVUL3 = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVSL2 = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVSL3 = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVF2 = gcnew itkPixelType ( itkPixelTypeEnum::Float, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVF3 = gcnew itkPixelType ( itkPixelTypeEnum::Float, itkPixelArrayEnum::ArrayCovariantVector, 3 ); static itkPixelType^ CVD2 = gcnew itkPixelType ( itkPixelTypeEnum::Double, itkPixelArrayEnum::ArrayCovariantVector, 2 ); static itkPixelType^ CVD3 = gcnew itkPixelType ( itkPixelTypeEnum::Double, itkPixelArrayEnum::ArrayCovariantVector, 3 ); // VectorImage Pixel Types static itkPixelType^ VIUC = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VISC = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VIUS = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VISS = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VIUL = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VISL = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VIF = gcnew itkPixelType ( itkPixelTypeEnum::Float, itkPixelArrayEnum::ArrayVectorImage, 0 ); static itkPixelType^ VID = gcnew itkPixelType ( itkPixelTypeEnum::Double, itkPixelArrayEnum::ArrayVectorImage, 0 ); // VariableLengthVector Pixel Types static itkPixelType^ VLVUC = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVSC = gcnew itkPixelType ( itkPixelTypeEnum::SignedChar, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVUS = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVSS = gcnew itkPixelType ( itkPixelTypeEnum::SignedShort, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVUL = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedLong, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVSL = gcnew itkPixelType ( itkPixelTypeEnum::SignedLong, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVF = gcnew itkPixelType ( itkPixelTypeEnum::Float, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); static itkPixelType^ VLVD = gcnew itkPixelType ( itkPixelTypeEnum::Double, itkPixelArrayEnum::ArrayVariableLengthVector, 0 ); // RGB and RGBA Pixel Types static itkPixelType^ RGBUC = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayRGB, 3 ); static itkPixelType^ RGBAUC = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedChar, itkPixelArrayEnum::ArrayRGBA, 4 ); static itkPixelType^ RGBUS = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayRGB, 3 ); static itkPixelType^ RGBAUS = gcnew itkPixelType ( itkPixelTypeEnum::UnsignedShort, itkPixelArrayEnum::ArrayRGBA, 4 ); }; } // end namespace itk #endif
[ "dan.muel@a4e08166-d753-0410-af4e-431cb8890a25" ]
[ [ [ 1, 836 ] ] ]
8c19fb68d80c005efe27b4198d129bc9d9201cc5
c8ab6c440f0e70e848c5f69ccbbfd9fe2913fbad
/bowling/Gutter.cpp
40a7a1c0360df58e5c422f057e943e57da71eb14
[]
no_license
alyshamsy/power-bowling
2b6426cfd4feb355928de95f1840bd39eb88de0b
dd650b2a8e146f6cdf7b6ce703801b96360a90fe
refs/heads/master
2020-12-24T16:50:09.092801
2011-05-12T14:37:15
2011-05-12T14:37:15
32,115,585
0
0
null
null
null
null
UTF-8
C++
false
false
4,200
cpp
#include "Gutter.h" Gutter::Gutter() { body = new cyclone::RigidBody(); } Gutter::~Gutter() { delete body; } /** Draws the block. */ void Gutter::render(GLuint texture) { // Get the OpenGL transformation GLfloat mat[16]; body->getGLTransform(mat); glColor3f(0.3f, 0.3f, 0.3f); //if (body->getAwake()) glColor3f(1.0,0.0,1.0); //else glColor3f(1.0,1.0,0.0); glPushMatrix(); glMultMatrixf(mat); glScalef(halfSize.x, halfSize.y, halfSize.z); //glutSolidCube(1.0f); glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_QUADS); { glTexCoord2f(0.0, 1.0); glVertex3f(1.0f, 1.0f, 0.0f); //A glTexCoord2f(1.0, 1.0); glVertex3f(1.0f, 0.0f, 0.0f); //B glTexCoord2f(1.0, 0.0); glVertex3f(-1.0f, 0.0f, 0.0f); //C glTexCoord2f(0.0, 0.0); glVertex3f(-1.0f, 1.0f, 0.0f); //D glTexCoord2f(1.0, 1.0); glVertex3f(1.0f, 1.0f, 0.0f); //A glTexCoord2f(1.0, 0.0); glVertex3f(1.0f, 1.0f, -1.0f); //F glTexCoord2f(0.0, 0.0); glVertex3f(1.0f, 0.0f, -1.0f); //G glTexCoord2f(0.0, 1.0); glVertex3f(1.0f, 0.0f, 0.0f); //B glTexCoord2f(1.0, 1.0); glVertex3f(-1.0f, 1.0f, -1.0f); //E glTexCoord2f(1.0, 0.0); glVertex3f(1.0f, 1.0f, -1.0f); //F glTexCoord2f(0.0, 0.0); glVertex3f(1.0f, 0.0f, -1.0f); //G glTexCoord2f(0.0, 1.0); glVertex3f(-1.0f, 0.0f, -1.0f); //H glTexCoord2f(1.0, 1.0); glVertex3f(-1.0f, 1.0f, 0.0f); //D glTexCoord2f(1.0, 0.0); glVertex3f(-1.0f, 1.0f, -1.0f); //E glTexCoord2f(0.0, 0.0); glVertex3f(-1.0f, 0.0f, -1.0f); //H glTexCoord2f(0.0, 1.0); glVertex3f(-1.0f, 0.0f, 0.0f); //C glTexCoord2f(1.0, 1.0); glVertex3f(-1.0f, 0.0f, -1.0f); //H glTexCoord2f(1.0, 0.0); glVertex3f(1.0f, 0.0f, -1.0f); //G glTexCoord2f(0.0, 0.0); glVertex3f(1.0f, 0.0f, 0.0f); //B glTexCoord2f(0.0, 1.0); glVertex3f(-1.0f, 0.0f, 0.0f); //C glTexCoord2f(0.0, 0.0); glVertex3f(-1.0f, 1.0f, -1.0f); //E glTexCoord2f(1.0, 0.0); glVertex3f(1.0f, 1.0f, -1.0f); //F glTexCoord2f(1.0, 1.0); glVertex3f(1.0f, 1.0f, 0.0f); //A glTexCoord2f(0.0, 1.0); glVertex3f(-1.0f, 1.0f, 0.0f); //D } glEnd(); glPopMatrix(); } /** Sets the block to a specific location. */ void Gutter::setState(const cyclone::Vector3 &position, const cyclone::Quaternion &orientation, const cyclone::Vector3 &extents, const cyclone::Vector3 &velocity) { body->setPosition(position); body->setOrientation(orientation); body->setVelocity(velocity); body->setRotation(cyclone::Vector3(0,0,0)); halfSize = extents; cyclone::real mass = 150.0f; body->setMass(mass); cyclone::Matrix3 tensor; tensor.setBlockInertiaTensor(halfSize, mass); body->setInertiaTensor(tensor); body->setLinearDamping(0.95f); body->setAngularDamping(0.8f); body->clearAccumulators(); body->setAcceleration(0,-10.0f,0); //body->setCanSleep(false); body->setAwake(); body->calculateDerivedData(); } ///>CalculateBlockTensor /** * Calculates and sets the mass and inertia tensor of this block, * assuming it has the given constant density. */ void Gutter::calculateMassProperties(cyclone::real invDensity) { // Check for infinite mass if (invDensity <= 0) { // Just set zeros for both mass and inertia tensor body->setInverseMass(0); body->setInverseInertiaTensor(cyclone::Matrix3()); } else { // Otherwise we need to calculate the mass cyclone::real volume = halfSize.magnitude() * 2.0; cyclone::real mass = volume / invDensity; body->setMass(mass); // And calculate the inertia tensor from the mass and size mass *= 0.333f; cyclone::Matrix3 tensor; tensor.setInertiaTensorCoeffs( mass * halfSize.y*halfSize.y + halfSize.z*halfSize.z, mass * halfSize.y*halfSize.x + halfSize.z*halfSize.z, mass * halfSize.y*halfSize.x + halfSize.z*halfSize.y ); body->setInertiaTensor(tensor); } } ///<CalculateBlockTensor
[ "aly.shamsy@71b57f4a-8c0b-a9ba-d1fe-6729e2c2215a" ]
[ [ [ 1, 129 ] ] ]
5701af84ba09bc4f4b656c2bd3cb3c6ad8abd1e7
05869e5d7a32845b306353bdf45d2eab70d5eddc
/soft/application/NetworkSimulator/SimulatorStart.cpp
834a45f3fc497dfca7e2e73ed79ab5cca0bf52ba
[]
no_license
shenfahsu/sc-fix
beb9dc8034f2a8fd9feb384155fa01d52f3a4b6a
ccc96bfaa3c18f68c38036cf68d3cb34ca5b40cd
refs/heads/master
2020-07-14T16:13:47.424654
2011-07-22T16:46:45
2011-07-22T16:46:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,592
cpp
// SimulatorStart.cpp: implementation of the CSimulatorStart class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "NetworkSimulator.h" #include "SimulatorStart.h" #include "MainDialog.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CSimulatorStart::CSimulatorStart() { } CSimulatorStart::~CSimulatorStart() { } void CSimulatorStart::ShowSimulator() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if (AfxGetApp()->m_pMainWnd) { (AfxGetApp()->m_pMainWnd)->ShowWindow(SW_SHOW); } } BOOL CSimulatorStart::InitSimulator(int nXPos,int nYPos) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); BOOL bResult = FALSE; if (AfxGetApp()->m_pMainWnd) { bResult = ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->InitSimulator(nXPos,nYPos); } return bResult; } BOOL CSimulatorStart::IsInit() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); BOOL bResult = FALSE; if (AfxGetApp()->m_pMainWnd) { bResult = ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->IsInit(); } return bResult; } void CSimulatorStart::SetReadQueueHandle(oslMsgqid_handle handle) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if (AfxGetApp()->m_pMainWnd) { ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->SetReadQueueHandle((oslMsgqid)handle); } } void CSimulatorStart::SetWriteQueueHandle(oslMsgqid_handle handle) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if (AfxGetApp()->m_pMainWnd) { ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->SetWriteQueueHandle((oslMsgqid)handle); } } void CSimulatorStart::SetReadQueueHandler(NWRECEIVEQ pRecvHandler) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if (AfxGetApp()->m_pMainWnd) { ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->SetReadQueueHandler(pRecvHandler); } } void CSimulatorStart::SetWriteQueueHandler(NWWRITEQ pWriteHandler) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if (AfxGetApp()->m_pMainWnd) { ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->SetWriteQueueHandler(pWriteHandler); } } BOOL CSimulatorStart::Bootup() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); BOOL bResult = FALSE; if (AfxGetApp()->m_pMainWnd) { bResult = ((CMainDialog*)(AfxGetApp()->m_pMainWnd))->Bootup(); } return bResult; }
[ "windyin@2490691b-6763-96f4-2dba-14a298306784" ]
[ [ [ 1, 108 ] ] ]
4ee2b3b6c62b04d32702e8dce644ef04a74adc2c
559770fbf0654bc0aecc0f8eb33843cbfb5834d9
/haina/codes/beluga/client/symbian/BelugaDb/src/CEntityDb.cpp
fe176a3d9f376cefe124155b2d07318edbed8ad1
[]
no_license
CMGeorge/haina
21126c70c8c143ca78b576e1ddf352c3d73ad525
c68565d4bf43415c4542963cfcbd58922157c51a
refs/heads/master
2021-01-11T07:07:16.089036
2010-08-18T09:25:07
2010-08-18T09:25:07
49,005,284
1
0
null
null
null
null
UTF-8
C++
false
false
1,515
cpp
/* ============================================================================ Name : CEntityDb.cpp Author : shaochuan.yang Copyright : haina Description : Database access base class ============================================================================ */ #include "CEntityDb.h" #include "Beluga.h" GLDEF_C void freeGStringArray(GPtrArray * pArray); CEntityDb::CEntityDb() { m_nSortFieldIndex = -1; m_ndbCount = 0; m_bSortAscending = TRUE; m_pFieldsName = NULL; } CEntityDb::~CEntityDb() { if (m_pFieldsName) freeGStringArray(m_pFieldsName); m_pFieldsName = NULL; } EXPORT_C gint32 CEntityDb::SetSortKey(guint32 fieldIndex, gboolean ascending) { m_nSortFieldIndex = fieldIndex; m_bSortAscending = ascending; return 0; } gint32 CEntityDb::GetEntityFieldsName(GPtrArray ** fieldsName) { *fieldsName = g_ptr_array_sized_new(m_pFieldsName->len); for(guint32 i=0; i<m_pFieldsName->len; i++) g_ptr_array_add(*fieldsName, g_string_new(((GString*)g_ptr_array_index(m_pFieldsName, i))->str)); return 0; } gint32 CEntityDb::OpenDatabase() { if (m_ndbCount == 0) m_dbBeluga.open(BELUGA_DATABASE); else m_ndbCount++; return 0; } gint32 CEntityDb::CloseDatabase() { if (m_ndbCount > 0) m_ndbCount--; else m_dbBeluga.close(); return 0; } CppSQLite3DB * CEntityDb::GetDatabase() { return &m_dbBeluga; } CppSQLite3Query * CEntityDb::GetDbQuery() { return &m_dbQuery; }
[ "shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d" ]
[ [ [ 1, 73 ] ] ]
4b48df45d3899574eabdc26a42c3cc07e0ca3ce1
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Internal/Collide/Util/hkpCollideTriangleUtil.h
864b4607c0aea8b9dca01ecfd27602ee6438c606
[]
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
5,663
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_COLLIDE_TRIANGLEUTIL_H #define HK_COLLIDE2_COLLIDE_TRIANGLEUTIL_H /// Triangle utilities, including ray intersection, normal calculation, and point-in-triangle tests. /// These methods are used internally by the engine. You should use the hkpShape, and hkpCollisionAgent interfaces instead class hkpCollideTriangleUtil { public: /// calculate the barycentric coordinates of a point projected onto a triangle. /// Note: result 0 and 2 are always sign correct, result 1 is calculated as 1.0f - p0 - p2, this function is not epsilon safe. static void HK_CALL calcBarycentricCoordinates(hkVector4Parameter pos, hkVector4Parameter t0, hkVector4Parameter t1, hkVector4Parameter t2, hkPadSpu<hkReal> result[3]); // // EDGE EDGE // enum { CLSLS_POINTA_START = 1, CLSLS_POINTA_END = 2, CLSLS_POINTB_START = 4, CLSLS_POINTB_END = 8 }; struct ClosestLineSegLineSegResult { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO, hkpCollideTriangleUtil::ClosestLineSegLineSegResult ); hkVector4 m_closestPointA; hkVector4 m_closestAminusClosestB; hkPadSpu<hkReal> m_distanceSquared; }; /// returns (see enum): if bit is set, point can be deleted static int HK_CALL closestLineSegLineSeg( hkVector4Parameter A, hkVector4Parameter dA, hkVector4Parameter B, hkVector4Parameter dB, ClosestLineSegLineSegResult& result ); // // POINT EDGE // struct ClosestPointLineSegResult { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO, hkpCollideTriangleUtil::ClosestPointLineSegResult ); hkVector4 m_pointOnEdge; }; static int HK_CALL closestPointLineSeg( hkVector4Parameter A, hkVector4Parameter B0, hkVector4Parameter B1, ClosestPointLineSegResult& result ); // // POINT TRIANGLE // /// Fast way to repeatedly get the closest point between a triangle and a vertex struct ClosestPointTriangleCache { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO, hkpCollideTriangleUtil::ClosestPointTriangleCache ); #if defined(HK_PLATFORM_SPU) hkPadSpu<hkReal> m_QQ; hkPadSpu<hkReal> m_RR; hkPadSpu<hkReal> m_QR; hkPadSpu<hkReal> m_invTriNormal; #else hkReal m_QQ; hkReal m_RR; hkReal m_QR; hkReal m_invTriNormal; #endif }; struct ClosestPointTriangleResult { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO, hkpCollideTriangleUtil::ClosestPointTriangleResult ); hkVector4 hitDirection; hkPadSpu<hkReal> distance; void calcClosestPoint( hkVector4Parameter point, hkVector4& closestPoint ) { closestPoint.setAddMul4( point, hitDirection, distance.val() ); } }; static void HK_CALL setupClosestPointTriangleCache( const hkVector4* triangle, ClosestPointTriangleCache& cache ); enum ClosestPointTriangleStatus { HIT_TRIANGLE_FACE = 0, HIT_TRIANGLE_EDGE }; static ClosestPointTriangleStatus HK_CALL closestPointTriangle( hkVector4Parameter position, const hkVector4* tri, const ClosestPointTriangleCache& cache, ClosestPointTriangleResult& result ); // // for fast triangle distance calculation // struct PointTriangleDistanceCache { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO, hkpCollideTriangleUtil::PointTriangleDistanceCache ); hkReal m_invEdgeLen[3]; hkReal m_invNormalLen; hkReal m_normalLen; }; static void HK_CALL setupPointTriangleDistanceCache( const hkVector4* triangle, PointTriangleDistanceCache& cache ); /// Calculate the distances to the triangle planes (edge0 = x ... edge2 = z, dist to triangle = w static void HK_CALL calcTrianglePlaneDirections( const hkVector4* tri, const PointTriangleDistanceCache& cache, hkTransform& planeEquationsOut, hkVector4& normalOut ); // // MASKS // /// returns the index of the bit set if passed in a compare mask or a index-8 of the only bit not set, works only on XYZ /// returns -1 for invalid input static const hkInt8 maskToIndex[]; static const hkInt8 vertexToEdgeLut[]; static inline int HK_CALL getNextModulo3( int i ) { return vertexToEdgeLut[i+2]; } static inline int HK_CALL getPrevModulo3( int i ) { return vertexToEdgeLut[i]; } protected: hkpCollideTriangleUtil(); }; //#include <hkinternal/collide/util/hkpCollideTriangleUtil.inl> #endif // HK_GEOMETRY2_TRIANGLEUTIL_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, 165 ] ] ]
c627d0416eebcf4cf143155f455c5c6994d5ac7e
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Common/Graphics/kpgAnimationManager.h
db18487396c44ba4d4476b4e846e76838bb4179e
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
1,513
h
#pragma once #include "Common/Utility/kpuMap.h" #include "Common/Utility/kpuFixedArray.h" #include "kpgAnimation.h" class kpuXmlParser; class kpgLinkedList; class kpgAnimationInstance; class kpgAnimationManager { public: kpgAnimationManager(void); ~kpgAnimationManager(void); static kpgAnimationManager* kpgAnimationManager::GetInstance(); void LoadAnimation(const char* szFile, u32 uName); kpgAnimationInstance* GetNewAnimation(u32 uName); protected: typedef struct _sNodeData { u32 uName; char* pData; }sNodeData; typedef struct _sBoneData { int iIndex; u32 uParent; u32 uName; char* pFloats; kpuMatrix mWorld; }sBoneData; void LoadAnimationLibrary(kpuXmlParser* pParser, kpuFixedArray<kpgAnimation::sBone*>& bones); void LoadSkeleton(kpuXmlParser* pParser); void LoadBone(kpuXmlParser* pParser, u32 uParent); void LoadControllers(kpuXmlParser* pParser); void LoadInverseBinds(kpuXmlParser* pParser, kpuLinkedList* pSources); void LoadBoneIndicies(kpuXmlParser* pParser, kpuLinkedList* pSources); void CreateAnimation(u32 uName,kpuFixedArray<kpgAnimation::sBone*>* bones); bool CreateSkeletonMap(u32 uBone); protected: static kpgAnimationManager* m_spAnimationManager; kpuMap<u32, kpgAnimation*>* m_pAnimations; //Not for runtime kpuMap<u32, sBoneData>* m_pBoneIndicieMap; kpuLinkedList* m_plSkeletonSources; kpuLinkedList* m_plBoneHierarchy; kpuFixedArray<kpuMatrix>* m_paInvBindMatricies; };
[ "bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 57 ] ] ]
f92473c5fbc1c196f48df6dc390405ca730b5280
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/Shared/Utility/Memory/MemoryManager.h
0006b3f89528b68ef66c6169b3529992f12422a3
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
2,571
h
// // The Epoch Language Project // FUGUE Virtual Machine // // Memory management subsystems. These classes handle the internal // memory allocations and services for the virtual machine. // #pragma once // // Platform-independent wrapper for managing heaps. // class HeapManager { // Construction and destruction public: HeapManager(); ~HeapManager(); // System parameter retrieval public: HANDLE GetHeap() const { return HeapHandle; } unsigned GetPageSize() const { return PageSize; } // Internal storage private: HANDLE HeapHandle; unsigned PageSize; }; extern HeapManager TheGlobalHeap; // // Base interface for all memory allocators. // class MemoryAllocator { // Destruction public: virtual ~MemoryAllocator() { } // Memory operations public: virtual void AllocateBlock(size_t numbytes) = 0; virtual void* CommitMemory(size_t numbytes) = 0; virtual void FreeMemory(void* address) = 0; }; // // This memory allocator is the simplest and has the least overhead, both in // terms of allocation/deallocation complexity, and in terms of extra memory // padding. All memory is packed as tightly as possible on the heap without // regards for alignment. // class UnalignedMemoryAllocator : public MemoryAllocator { // Construction and destruction public: UnalignedMemoryAllocator(size_t initialblocksize); virtual ~UnalignedMemoryAllocator(); // Memory operations public: virtual void AllocateBlock(size_t numbytes); virtual void* CommitMemory(size_t numbytes); virtual void FreeMemory(void* address); protected: // // Helper structure for recording allocations // struct AllocBlock { void* Storage; size_t NumBytes; size_t FreeOffset; // // Initialize the block tracking structure // AllocBlock(void* storage, size_t numbytes) : Storage(storage), NumBytes(numbytes), FreeOffset(0) { } // // Commit a chunk of memory out of the allocated space // May throw an exception if too much space is committed // void* Commit(size_t numbytes) { // WARNING - this code makes a platform-dependent assumption that char is 1 byte const size_t PLATFORM_CHAR_NUMBYTES = 1; void* ptr = reinterpret_cast<Byte*>(Storage) + (FreeOffset / PLATFORM_CHAR_NUMBYTES); FreeOffset += numbytes; if(FreeOffset > NumBytes) throw MemoryException("Overcommitted an unaligned allocation block!"); return ptr; } }; // Internal storage protected: std::vector<AllocBlock> AllocBlocks; };
[ [ [ 1, 117 ] ] ]
1b96c6e501a2a284e365e005b81cda821fe33dc4
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/ncterrain2/src/nct2tools/ntgafile.cc
b0f75a60acc43f8f62ce2f268c24c81049b92db5
[]
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
6,023
cc
//------------------------------------------------------------------------------ // ntgafile.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nct2tools/ntgafile.h" //------------------------------------------------------------------------------ /** */ nTgaFile::nTgaFile(nKernelServer* ks) : kernelServer(ks), file(0), width(0), height(0), dataOffset(0), error(Success) { // empty } //------------------------------------------------------------------------------ /** */ nTgaFile::~nTgaFile() { if (this->IsOpen()) { this->Close(); } } //------------------------------------------------------------------------------ /** Open the file in read mode. */ bool nTgaFile::OpenRead(const char* filename) { n_assert(this->kernelServer); n_assert(0 == this->file); // open file this->file = kernelServer->GetFileServer()->NewFileObject(); if (!this->file->Open(filename, "rb")) { this->error = CouldNotOpenFile; file->Release(); return false; } // read header char idFieldSize = file->GetChar(); file->GetChar(); // colorMapType file->GetChar(); // imageType file->GetShort(); // colorMapStart file->GetShort(); // colorMapLength file->GetChar(); // colorMapBits file->GetShort(); // xStart file->GetShort(); // yStart this->width = file->GetShort(); this->height = file->GetShort(); char bitsPerPixel = file->GetChar(); file->GetChar(); // descriptor // correct pixel format? if (bitsPerPixel != 32) { this->error = InvalidPixelFormat; file->Release(); return false; } // fill remaining object attributes const int headerSize = 18; this->dataOffset = headerSize + idFieldSize; this->error = Success; return true; } //------------------------------------------------------------------------------ /** Open the chunk in write mode. */ bool nTgaFile::OpenWrite(const char* filename) { n_assert(this->GetWidth() > 0); n_assert(this->GetHeight() > 0); n_assert(filename); n_assert(this->kernelServer); n_assert(0 == this->file); // open file this->file = kernelServer->GetFileServer()->NewFileObject(); if (!this->file->Open(filename, "wb")) { this->error = CouldNotOpenFile; file->Release(); return false; } // write tga header file->PutChar(0); // identsize file->PutChar(0); // colormap type = none file->PutChar(2); // imagetype = rgb file->PutShort(0); // colormapstart file->PutShort(0); // colormaplength file->PutChar(0); // colormapbits file->PutShort(0); // x origin file->PutShort(0); // y origin file->PutShort(this->width); // width file->PutShort(this->height); // height file->PutChar(32); // bits per pixel file->PutChar(8); // h/v flip, alpha bits // standard header of 18 bytes this->dataOffset = 18; // write data (all violet pixels) uint* row = n_new_array(uint, this->width); int i; for (i = 0; i < this->width; i++) { row[i] = 0xffff00ff; } for (i = 0; i < this->height; i++) { file->Write(row, this->width * sizeof(uint)); } n_delete_array(row); return true; } //------------------------------------------------------------------------------ /** */ void nTgaFile::Close() { n_assert(this->file); this->file->Close(); this->file->Release(); this->file = 0; } //------------------------------------------------------------------------------ /** Read a chunk from the image defined by position and size in pixels into the provided buffer. Returns true on success, otherwise sets ErrorCodes InvalidChunkSize or BufferTooSmall. */ bool nTgaFile::ReadChunk(int x, int y, int w, int h, char* buffer, int bufSize) { n_assert(this->file); n_assert(buffer); // check for parameter errors if (bufSize < (w * h * this->GetBytesPerPixel())) { this->error = BufferTooSmall; return false; } if (((x + w) > this->width) || (y + h) > this->height) { this->error = InvalidChunkSize; return false; } int bytesPerPixel = this->GetBytesPerPixel(); int bytesPerRow = this->GetBytesPerRow(); int startPos = y * bytesPerRow + x * bytesPerPixel + this->dataOffset; // number of bytes to read per row int readBytesPerRow = w * bytesPerPixel; int row; char* ptr = buffer; for (row = 0; row < h; row++) { file->Seek(startPos + row * bytesPerRow, nFile::START); file->Read(ptr, readBytesPerRow); ptr += readBytesPerRow; } return true; } //------------------------------------------------------------------------------ /** Write a chunk to the tga image. */ bool nTgaFile::WriteChunk(int x, int y, int w, int h, char* buffer) { n_assert(this->file); n_assert(buffer); // check for parameter errors if (((x + w) > this->width) || (y + h) > this->height) { this->error = InvalidChunkSize; return false; } int bytesPerPixel = this->GetBytesPerPixel(); int bytesPerRow = this->GetBytesPerRow(); int startPos = y * bytesPerRow + x * bytesPerPixel + this->dataOffset; // number of bytes to write per row int writeBytesPerRow = w * bytesPerPixel; int row; char* ptr = buffer; for (row = 0; row < h; row++) { file->Seek(startPos + row * bytesPerRow, nFile::START); file->Write(ptr, writeBytesPerRow); ptr += writeBytesPerRow; } return true; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 221 ] ] ]
f53b8d13964d3cead2fc26d110caf8e8bed3176e
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swWxGuiTesting/CppGuiTest/swCRCaptureTest.h
f660122aacb5698efe1b99453fbf3eca732606d7
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
1,292
h
/////////////////////////////////////////////////////////////////////////////// // Name: swWxGuiTesting/CppGuiTest/swCRCaptureTest.h // Author: Reinhold Füreder // Created: 2004 // Copyright: (c) 2005 Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef SWCRCAPTURETEST_H #define SWCRCAPTURETEST_H #ifdef __GNUG__ #pragma interface "swCRCaptureTest.h" #endif #include <cppunit/extensions/HelperMacros.h> namespace swTst { /*! \class CRCaptureTest \brief Test capturing of GUI interaction. */ class CRCaptureTest : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE( CRCaptureTest ); CPPUNIT_TEST( testCapture ); CPPUNIT_TEST_SUITE_END(); public: /*! \fn virtual void setUp () \brief Set up context before running a test. */ virtual void setUp (); /*! \fn virtual void tearDown () \brief Clean up after the test run. */ virtual void tearDown (); /*! \fn virtual void testCapture () \brief Minimal capture test case. */ virtual void testCapture (); protected: private: }; } // End namespace swTst #endif // SWCRCAPTURETEST_H
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 59 ] ] ]
1ce99b49079ba211f28d5e9d51948ad154948235
a97b8228807e6cc6cb2e2a6bf32ca10373af053c
/uxn/patl/config.hpp
32fa72a2c3a2c35ec81def8434b21692e6e573f1
[]
no_license
swagatata/patl
e04308d3ce77fb242a86b79d017d028f4d039c29
805522055874de82efcb297ef9e7168e7b01c870
refs/heads/master
2021-01-16T17:49:08.382127
2011-06-28T15:52:39
2011-06-28T15:52:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
hpp
/*- | This source code is part of PATL (Practical Algorithm Template Library) | Released under the BSD License (http://www.opensource.org/licenses/bsd-license.php) | Copyright (c) 2005, 2007..2009, Roman S. Klyujkov (uxnuxn AT gmail.com) -*/ #ifndef PATL_CONFIG_HPP #define PATL_CONFIG_HPP #ifdef __GNUG__ #define PATL_32 typedef unsigned int word_t; typedef int sword_t; #else // PATL_GCC #ifdef _WIN64 #define PATL_64 typedef unsigned long long word_t; typedef long long sword_t; #elif _WIN32 #define PATL_32 typedef unsigned int word_t; typedef int sword_t; #else #define PATL_NN typedef undefined word_t; typedef undefined sword_t; #endif #define PATL_INTRINSIC #endif // PATL_GCC const word_t bits_in_word = 8 * sizeof(word_t), highest_bit = word_t(1) << (bits_in_word - 1); // allow to store additional info in less significant bit in some pointers // used in "impl/node.hpp" and "impl/algorithm.hpp" #define PATL_ALIGNHACK #ifdef _DEBUG #define PATL_DEBUG #undef PATL_ALIGNHACK #undef PATL_INTRINSIC #define PATL_ASSERT(x) assert(x) #else #define PATL_ASSERT(x) #endif // _DEBUG #endif
[ "uxnuxn@ac5c578c-d34d-0410-9547-55c0b358f148" ]
[ [ [ 1, 63 ] ] ]
e137b8f3d31c6923923d8a1ab00fa654703adc6d
aee9f4a7a277c3f44eac40072adb81dc52db3079
/Code/core/ComponentCalibrationTSAI.cpp
fa6735d6d9d30ddeddd3e7329efc4b3a983e7cd8
[]
no_license
SiChiTong/swistrackplus
1a1bbc7dd8457ec908ced0cae3e30ef1f0d85551
7746c32dcfdbe1988c82e7a1561534c519ac0872
refs/heads/master
2020-04-05T02:31:55.840432
2010-06-01T14:12:46
2010-06-01T14:12:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,071
cpp
#include "ComponentCalibrationTSAI.h" #define THISCLASS ComponentCalibrationTSAI #include "DisplayEditor.h" #include "DataStructureParticles.h" #include "libtsai.h" #include <wx/log.h> #include <fstream> THISCLASS::ComponentCalibrationTSAI(SwisTrackCore *stc): Component(stc, wxT("CalibrationTSAI")), mDisplayOutput(wxT("Output"), wxT("TSAI Calibration: Output")) { // Data structure relations mCategory = &(mCore->mCategoryCalibration); AddDataStructureRead(&(mCore->mDataStructureParticles)); AddDataStructureWrite(&(mCore->mDataStructureParticles)); AddDisplay(&mDisplayOutput); // Read the XML configuration file Initialize(); } THISCLASS::~ComponentCalibrationTSAI() { } void THISCLASS::OnStart() { // Read the file containing the calibration points wxString filename_string = GetConfigurationString(wxT("CalibrationPoints"), wxT("")); wxFileName filename = mCore->GetProjectFileName(filename_string); wxLogNull log; wxXmlDocument document; bool isopen = document.Load(filename.GetFullPath()); if (! isopen) { AddError(wxT("Could not open or parse the XML file!")); return; } // Select the root element and check its name SetRootNode(document.GetRoot()); if (GetRootNode()->GetName() != wxT("pointlist")) { AddError(wxT("The XML root node must be called 'pointlist'!")); return; } // Enumerate all points in the list SelectChildNode(wxT("points")); if (! mSelectedNode) { AddError(wxT("No node 'points' found!")); return; } // Empty the vector calibrationPointList.clear(); // Fill the vector with the readen points wxXmlNode *node = mSelectedNode->GetChildren(); while (node) { if (node->GetName() == wxT("point")) { ReadPoint(node); } node = node->GetNext(); } //Getting camera parametrs from configuration file cameraParameters.Ncx = GetConfigurationDouble(wxT("Ncx"), 640); cameraParameters.Nfx = GetConfigurationDouble(wxT("Nfx"), 640); cameraParameters.dx = GetConfigurationDouble(wxT("dx"), 0.0065); cameraParameters.dpx = cameraParameters.dx * cameraParameters.Ncx / cameraParameters.Nfx; cameraParameters.dy = GetConfigurationDouble(wxT("dy"), 0.0065); cameraParameters.dpy = cameraParameters.dy * GetConfigurationDouble(wxT("Ncy"), 480) / GetConfigurationDouble(wxT("Nfy"), 480); cameraParameters.Cx = cameraParameters.Ncx / 2; cameraParameters.Cy = GetConfigurationDouble(wxT("Ncy"), 480) / 2; cameraParameters.sx = GetConfigurationDouble(wxT("sx"), 1.0); // Put the points into the matrix if (calibrationPointList.size() > TSAI_MAX_POINTS) { AddError(wxT("There are more calibration points than accepted by the Tsai calibration library")); } calibrationData.point_count = calibrationPointList.size(); for (int i = 0; i < calibrationData.point_count; i++) { calibrationData.zw[i] = 0; calibrationData.xw[i] = (calibrationPointList.at(i)).xWorld; calibrationData.yw[i] = (calibrationPointList.at(i)).yWorld; calibrationData.Xf[i] = (calibrationPointList.at(i)).xImage; calibrationData.Yf[i] = (calibrationPointList.at(i)).yImage; } // Do the calibration try { coplanar_calibration_with_full_optimization(&calibrationData, &calibrationConstants, &cameraParameters); } catch (...) { AddError(wxT("Calibration using libtsai failed.")); } //Compute error of calibration on calibration points double errorX, errorY, maxErrorX, maxErrorY, maxErrorD, errorD; maxErrorX = 0; maxErrorY = 0; errorX = 0; errorY = 0; maxErrorD = 0; errorD = 0; for (unsigned int i = 0; i < calibrationPointList.size(); i++) { double tmpErrorX, tmpErrorY, tmpErrorD; CvPoint2D32f originalImage, originalWorld, finalWorld; originalImage.x = (float)(calibrationPointList.at(i)).xImage; originalImage.y = (float)(calibrationPointList.at(i)).yImage; originalWorld.x = (float)(calibrationPointList.at(i)).xWorld; originalWorld.y = (float)(calibrationPointList.at(i)).yWorld; finalWorld = THISCLASS::Image2World(originalImage); tmpErrorX = abs(originalWorld.x - finalWorld.x); tmpErrorY = abs(originalWorld.y - finalWorld.y); tmpErrorD = sqrt(tmpErrorX * tmpErrorX + tmpErrorY * tmpErrorY); errorX += tmpErrorX; errorY += tmpErrorY; errorD += tmpErrorD; if (tmpErrorX > maxErrorX) maxErrorX = tmpErrorX; if (tmpErrorY > maxErrorY) maxErrorY = tmpErrorY; if (tmpErrorD > maxErrorD) maxErrorD = tmpErrorD; } errorX = errorX / calibrationPointList.size(); errorY = errorY / calibrationPointList.size(); errorD = errorD / calibrationPointList.size(); //Write error into calibration.log std::fstream logfile; wxFileName logfilename = mCore->GetRunFileName(wxT("CalibrationTSAI.log")); logfile.open(logfilename.GetFullPath().mb_str(wxConvFile), std::fstream::out | std::fstream::trunc); logfile << "Calibration error" << std::endl; logfile << "Max error in X: \t" << maxErrorX << std::endl; logfile << "Max error in Y: \t" << maxErrorY << std::endl; logfile << "Average error in X: \t" << errorX << std::endl; logfile << "Average error in Y: \t" << errorY << std::endl; logfile << "Max distance error: \t" << maxErrorD << std::endl; logfile << "Average distance error: \t" << errorD << std::endl; logfile.close(); } void THISCLASS::OnReloadConfiguration() { } void THISCLASS::OnStep() { // These are the particles to transform DataStructureParticles::tParticleVector *particles = mCore->mDataStructureParticles.mParticles; if (! particles) { return; } // Transform all particle positions DataStructureParticles::tParticleVector::iterator it = particles->begin(); while (it != particles->end()) { it->mWorldCenter = Image2World(it->mCenter); it++; } } void THISCLASS::OnStepCleanup() { } void THISCLASS::OnStop() { } void THISCLASS::ReadPoint(wxXmlNode *node) { mSelectedNode = node; CalibrationPoint calibrationPoint; calibrationPoint.xImage = ConfigurationConversion::Double(ReadChildContent(wxT("ximage")), 0); calibrationPoint.yImage = ConfigurationConversion::Double(ReadChildContent(wxT("yimage")), 0); calibrationPoint.xWorld = ConfigurationConversion::Double(ReadChildContent(wxT("xworld")), 0); calibrationPoint.yWorld = ConfigurationConversion::Double(ReadChildContent(wxT("yworld")), 0); calibrationPointList.push_back(calibrationPoint); } CvPoint2D32f THISCLASS::Image2World(CvPoint2D32f imageCoordinates) { double wx, wy; CvPoint2D32f worldCoordinates; image_coord_to_world_coord(calibrationConstants, cameraParameters, (double)imageCoordinates.x, (double)imageCoordinates.y, 0, &wx, &wy); worldCoordinates = cvPoint2D32f(wx, wy); return worldCoordinates; } CvPoint2D32f THISCLASS::World2Image(CvPoint2D32f worldCoordinates) { double ix, iy; CvPoint2D32f imageCoordinates; world_coord_to_image_coord(calibrationConstants, cameraParameters, (double)worldCoordinates.x, (double)worldCoordinates.y, 0, &ix, &iy); imageCoordinates = cvPoint2D32f(ix, iy); return imageCoordinates; }
[ "root@newport-ril-server.(none)" ]
[ [ [ 1, 194 ] ] ]
167a14df6ecb69acf1e9c1c996620559cfe9d686
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/app/messaging/mms_client_mtm_api/src/MMSClientMTMBCTesterTools.cpp
613022697b45000cc61e4d1a786bd1ac0f7de49a
[]
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
3,720
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: Helper functions for MMSClientMTMBCTester * */ // INCLUDE FILES #include "MMSClientMTMBCTesterController.h" #include <utf.h> #include <f32file.h> #include <apparc.h> // ----------------------------------------------------------------------------- // CMMSClientMTMBCTesterController::ReadConfigFile // Read data into memory from the test module configuration file // ----------------------------------------------------------------------------- // void CMMSClientMTMBCTesterController::ReadConfigFileL( TFileName& aIniFile ) { // Connect to the file RFs fs; User::LeaveIfError( fs.Connect() ); RFile file; User::LeaveIfError( file.Open( fs, aIniFile, EFileRead ) ); // Read the content of the file into a buffer TInt fileSize; User::LeaveIfError( file.Size( fileSize ) ); iFileBuf = HBufC8::NewL( fileSize ); TPtr8 modBuffer = iFileBuf->Des(); User::LeaveIfError( file.Read( modBuffer ) ); // Close the file and clean up file.Close(); fs.Close(); } // ----------------------------------------------------------------------------- // CMMSClientMTMBCTesterController::GetItemFromFile // Get a wanted item from the configuration file // ----------------------------------------------------------------------------- // HBufC* CMMSClientMTMBCTesterController::GetItemFromFile( const TDesC8& aID, HBufC* iBuf) { // Needed variables _LIT( KAllocationFailure, "*** Memory allocation FAILED: %d ***" ); TPtrC8 tempFile = iFileBuf->Des(); TRAPD ( error1, iBuf = HBufC::NewL( iBufSize ) ); if ( error1 != KErrNone ) { iLogger->Log( KAllocationFailure, error1 ); return NULL; } TPtrC8 prtPropPart; TInt line; TInt start; TInt end; // Find the wanted item line = tempFile.Find( aID ); TPtrC8 foundLine = tempFile.Mid( line, KLineLength ); start = foundLine.Locate( '[' ); end = foundLine.Locate( ']' ); // Get the data prtPropPart.Set( foundLine.Mid( start+1, end-start-1 ) ); // Make sure we can use the item and return it _LIT( KConversionFailure, "*** ConvertToUnicodeFromUtf8 FAILED: %d ***" ); TInt size = prtPropPart.Length(); if ( size > iBufSize - iExtraSpace ) { delete iBuf; iBuf = NULL; iBufSize = 0; TRAPD ( error2, iBuf = HBufC::NewL( size + iExtraSpace ) ); if ( error2 != KErrNone ) { iLogger->Log( KAllocationFailure, error2 ); return NULL; } iBufSize = size; TPtr16 modBuf = iBuf->Des(); TInt rcode = CnvUtfConverter::ConvertToUnicodeFromUtf8( modBuf, prtPropPart ); if (rcode != KErrNone) { iLogger->Log( KConversionFailure, rcode ); } iBuf->Des().ZeroTerminate(); } else { TPtr16 modBuf = iBuf->Des(); TInt rcode = CnvUtfConverter::ConvertToUnicodeFromUtf8( modBuf, prtPropPart ); if (rcode != KErrNone) { iLogger->Log( KConversionFailure, rcode ); } iBuf->Des().ZeroTerminate(); } return iBuf; } // End of file: MMSClientMTMBCTesterTools.cpp
[ "none@none" ]
[ [ [ 1, 123 ] ] ]
68efac0458c316ea3ecc90e2bee6336a6239c55c
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsgameplay/src/npopulator/npopulator.cc
f3e4708c6c56a7889b6cc57b13e9b7d5a644b15a
[]
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
6,718
cc
#include "precompiled/pchrnsgameplay.h" //------------------------------------------------------------------------------ // npopulator.cc // (C) Conjurer Services, S.A. 2006 //------------------------------------------------------------------------------ #include "npopulator/npopulator.h" #include "util/nrandomlogic.h" #include "ncspawner/ncspawner.h" nNebulaClass(nPopulator, "nobject"); nPopulator* nPopulator::Singleton = 0; //------------------------------------------------------------------------------ /** Constructor */ nPopulator::nPopulator() { n_assert(Singleton==0); Singleton = this; } //------------------------------------------------------------------------------ /** Destructor */ nPopulator::~nPopulator() { this->UnregisterAllSpawners(); this->UnregisterAllPopulatorAreas(); Singleton = 0; } //------------------------------------------------------------------------------ /** InitInstance */ void nPopulator::InitInstance(nObject::InitInstanceMsg /*initType*/) { // empty } //------------------------------------------------------------------------------ /** SpawnRandomEntity */ nEntityObject* nPopulator::SpawnRandomEntity() { return 0; } //------------------------------------------------------------------------------ /** RegisterSpawner */ void nPopulator::RegisterSpawner (nEntityObject* spawner) { if ( !this->IsRegisteredPopulatorArea (spawner) ) { this->populatorAreas.Append (spawner); } } //------------------------------------------------------------------------------ /** UnregisterSpawner */ void nPopulator::UnregisterSpawner (nEntityObject* spawner) { bool found = false; for ( int i=0; i<this->spawners.Size() && !found; ) { nEntityObject* element = this->spawners[i]; if ( element == spawner ) { this->spawners.EraseQuick (i); found = true; } else { i++; } } } //------------------------------------------------------------------------------ /** RegisterPopulatorArea */ void nPopulator::RegisterPopulatorArea (nEntityObject* populatorArea) { if ( !this->IsRegisteredPopulatorArea (populatorArea) ) { this->populatorAreas.Append (populatorArea); } } //------------------------------------------------------------------------------ /** UnregisterPopulatorArea */ void nPopulator::UnregisterPopulatorArea (nEntityObject* populatorArea) { bool found = false; for ( int i=0; i<this->populatorAreas.Size() && !found; ) { nEntityObject* element = this->populatorAreas[i]; if ( element == populatorArea ) { this->populatorAreas.EraseQuick (i); found = true; } else { i++; } } } //------------------------------------------------------------------------------ /** UnregisterAllSpawners */ void nPopulator::UnregisterAllSpawners() { for ( int i=0; i<this->spawners.Size(); i++ ) { this->spawners.EraseQuick(i); } } //------------------------------------------------------------------------------ /** UnregisterAllPopulatorAreas */ void nPopulator::UnregisterAllPopulatorAreas() { for ( int i=0; i<this->populatorAreas.Size(); i++ ) { this->populatorAreas.EraseQuick(i); } } //------------------------------------------------------------------------------ /** IsRegisteredSpawner */ bool nPopulator::IsRegisteredSpawner (nEntityObject* spawner) { bool found = false; for ( int i=0; i<this->spawners.Size() && !found; i++ ) { found = bool (this->spawners[i] == spawner); } return found; } //------------------------------------------------------------------------------ /** IsRegisteredPopulatorArea */ bool nPopulator::IsRegisteredPopulatorArea (nEntityObject* populatorArea) { bool found = false; for ( int i=0; i<this->populatorAreas.Size() && !found; i++ ) { found = bool (this->populatorAreas[i] == populatorArea); } return found; } //------------------------------------------------------------------------------ /** CheckAllPopulatorAreas */ void nPopulator::CheckAllPopulatorAreas() { // Note: You must just check the active areas, not all. Do this depending the // LOD system chosen. for ( int i=0; i<this->populatorAreas.Size(); i++ ) { nEntityObject* pa = this->populatorAreas[i]; this->CheckPopulatorArea (pa); } } //------------------------------------------------------------------------------ /** CheckPopulatorArea */ void nPopulator::CheckPopulatorArea (nEntityObject* populatorArea) { n_assert(populatorArea); if ( populatorArea ) { nArray<ncPopulatorArea::nSpawnItem*> breeds; ncPopulatorArea* pa = populatorArea->GetComponentSafe <ncPopulatorArea>(); n_assert(pa); if ( pa ) { pa->GetBreeds (breeds); // Now, say how many creatures are needed for each breed for ( int i=0; i<breeds.Size(); i++ ) { ncPopulatorArea::nSpawnItem* spawnItem = breeds[i]; int current = pa->GetNumberIndividuals (spawnItem->name); spawnItem->needed = spawnItem->totals - current; } // Now, we know the needed elements to put in the area, choose one kind ncPopulatorArea::nSpawnItem* spawnItem = this->ChooseBreed (breeds); if ( spawnItem ) { nEntityObject* spawner = pa->GetSpawner(); n_assert(spawner); if ( spawner ) { ncSpawner* sp = spawner->GetComponentSafe <ncSpawner>(); n_assert(sp); // Finally, we spawn the selected entity if ( sp ) { //#ifndef NGAME sp->SpawnEntity (spawnItem->name); //#endif } } } } // if ( pa ) } } //------------------------------------------------------------------------------ /** ChooseBreed */ ncPopulatorArea::nSpawnItem* nPopulator::ChooseBreed (const nArray<ncPopulatorArea::nSpawnItem*>& spawnItems) const { ncPopulatorArea::nSpawnItem* selected = 0; // We'll use a token ring algorithm to select the given spawn // First, we choose a random entry and check if is a valid spawn // after this, we run the list looking for a valid one. int maxItems = spawnItems.Size(); int index = n_rand_int (maxItems); int counter = 0; do { ncPopulatorArea::nSpawnItem* candidate = spawnItems[index]; if ( candidate->needed > 0 ) { selected = candidate; } else { if ( ++index >= maxItems ) { index = 0; } } } while ( !selected && ++counter < maxItems ); return selected; } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 300 ] ] ]
894710f39dfd7572673ebb293c3feabf4ab02726
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/variable/nvariableserver_cmds.cc
3a077f28aa820afc63e225f3e499330eab51d7ff
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,374
cc
#define N_IMPLEMENTS nVariableServer //------------------------------------------------------------------------------ // nvariableserver_cmds.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "kernel/nclass.h" #include "variable/nvariableserver.h" static void n_declarevariable(void* slf, nCmd* cmd); static void n_getnumvariables(void* slf, nCmd* cmd); static void n_getvariableat(void* slf, nCmd* cmd); static void n_setfloatvariable(void* slf, nCmd* cmd); static void n_setintvariable(void* slf, nCmd* cmd); static void n_setvectorvariable(void* slf, nCmd* cmd); static void n_setstringvariable(void* slf, nCmd* cmd); //------------------------------------------------------------------------------ /** @scriptclass nvariableserver @superclass nroot @classinfo Manages variable declarations. A variable declaration consists of a variable name and an associated variable fourcc code. */ void n_initcmds(nClass* cl) { cl->BeginCmds(); cl->AddCmd("v_declarevariable_ss", 'DCLV', n_declarevariable); cl->AddCmd("i_getnumvariables_v", 'GNMV', n_getnumvariables); cl->AddCmd("ss_getvariableat_i", 'GVAT', n_getvariableat); cl->AddCmd("v_setfloatvariable_sf", 'SFLV', n_setfloatvariable); cl->AddCmd("v_setintvariable_si", 'SINV', n_setintvariable); cl->AddCmd("v_setvectorvariable_sffff", 'SVCV', n_setvectorvariable); cl->AddCmd("v_setstringvariable_ss", 'SSTV', n_setstringvariable); cl->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd declarevariable @input s(VariableName), s(VariableFourCC) @output v @info Add a new variable declaration. Declaring variables is not required but the only way to get variables with both a valid name and a valid fourcc code. */ static void n_declarevariable(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; const char* s0 = cmd->In()->GetS(); const char* s1 = cmd->In()->GetS(); self->DeclareVariable(s0, nVariableServer::StringToFourCC(s1)); } //------------------------------------------------------------------------------ /** @cmd getnumvariables @input v @output i(NumVariables) @info Get number of variable declarations. */ static void n_getnumvariables(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; cmd->Out()->SetI(self->GetNumVariables()); } //------------------------------------------------------------------------------ /** @cmd getvariableat @input i(VariableIndex) @output s(VariableName), s(VariableFourCC) @info Return the variable name and fourcc code at given index. */ static void n_getvariableat(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; const char* varName; nFourCC varFourCC; char buf[5]; self->GetVariableAt(cmd->In()->GetI(), varName, varFourCC); cmd->Out()->SetS(varName); cmd->Out()->SetS(nVariableServer::FourCCToString(varFourCC, buf, sizeof(buf))); } //------------------------------------------------------------------------------ /** @cmd setfloatvariable @input s(VarName), f(Value) @output v @info Set float value of a global variable. */ static void n_setfloatvariable(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; nVariable::Handle var = self->GetVariableHandleByName(cmd->In()->GetS()); self->SetFloatVariable(var, cmd->In()->GetF()); } //------------------------------------------------------------------------------ /** @cmd setintvariable @input s(VarName), i(Value) @output v @info Set integer value of a global variable. */ static void n_setintvariable(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; nVariable::Handle var = self->GetVariableHandleByName(cmd->In()->GetS()); self->SetIntVariable(var, cmd->In()->GetI()); } //------------------------------------------------------------------------------ /** @cmd setvectorvariable @input s(VarName), f(ValX), f(ValY), f(ValZ), f(ValW) @output v @info Set vector value of a global variable. */ static void n_setvectorvariable(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; nVariable::Handle var = self->GetVariableHandleByName(cmd->In()->GetS()); float4 vec; vec[0] = cmd->In()->GetF(); vec[1] = cmd->In()->GetF(); vec[2] = cmd->In()->GetF(); vec[3] = cmd->In()->GetF(); self->SetVectorVariable(var, vec); } //------------------------------------------------------------------------------ /** @cmd setstringvariable @input s(VarName), s(Value) @output v @info Set string value of a global variable. */ static void n_setstringvariable(void* slf, nCmd* cmd) { nVariableServer* self = (nVariableServer*) slf; nVariable::Handle var = self->GetVariableHandleByName(cmd->In()->GetS()); self->SetStringVariable(var, cmd->In()->GetS()); }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 182 ] ] ]
54d57100a722162f0bdb4b5cf3b8585f08e04224
c82ae5a5c899298a3155fd6d4b46be2638df41e9
/utconfig.h
05a51b7d1f23dc2d17c96df07e88bcf1f05c6d1e
[]
no_license
toslunar/UTyping
5a4e3ab46d218ab27fd2c2bcc635c5f792ccbc49
1b2eff072bda776ae4d7091f39d0c440f45d2727
refs/heads/master
2023-08-17T09:59:34.132597
2010-01-05T11:06:39
2010-01-05T11:06:39
412,716,324
3
1
null
null
null
null
SHIFT_JIS
C++
false
false
7,082
h
#ifndef __UTYPING_CONFIG #define __UTYPING_CONFIG enum{ CONFIG_NEVER, CONFIG_QUERY, CONFIG_ALWAYS, }; #include <stdio.h> #include <string.h> class UTypingConfig{ public: UTypingConfig(); void init(); void read(); public: //bool f_useMultiThread; int loadSoundType; int volume; char defaultReplayFile[256]; int overwriteReplay; bool f_rankingCheckDate; bool f_rankingCheckChallenge; bool f_failByGauge; bool f_fullScreen; bool f_showFPS; bool f_waitVSync; bool f_debugMode; bool f_debugBeat; /* false 普通に debug / true BEATLINE を音符にする */ int debugTime; /* デバッグ開始位置(ミリ秒) */ bool f_showProcessTime; }; UTypingConfig g_config; UTypingConfig::UTypingConfig(){ init(); } void UTypingConfig::init(){ //f_useMultiThread = true; loadSoundType = DX_SOUNDDATATYPE_MEMPRESS; volume = -1; strcpy(defaultReplayFile, "default.rep"); overwriteReplay = CONFIG_QUERY; f_rankingCheckDate = false; f_rankingCheckChallenge = true; f_failByGauge = false; f_fullScreen = false; f_showFPS = false; f_waitVSync = true; f_debugMode = false; f_debugBeat = false; debugTime = 0; f_showProcessTime = false; } void UTypingConfig::read(){ FILE *fp; fp = fopen("UTyping_config.txt", "r"); if(!fp){ /* configがなければ、特に何もしないでよい。 */ /* configがないことをエラーにするのは微妙すぎる。 */ return; } char buf[256]; while(fgetline(buf, fp)){ char *ptr1 = strtok(buf, "="); if(ptr1 == NULL || ptr1[0] == '#'){ /* 何も書かれていないか'#'で始まるコメント行 */ continue; } char *ptr2 = strtok(NULL, ""); if(ptr2 == NULL){ ptr2 = ""; /* ""を指させておく */ } /* if(!strcmp(ptr1, "UseMultiThread")){ if(!strcmp(ptr2, "true")){ f_useMultiThread = true; }else if(!strcmp(ptr2, "false")){ f_useMultiThread = false; }else{ throw "[config] UseMultiThread は true または false で指定しなければならない。(デフォルト: true )"; } }else */ if(!strcmp(ptr1, "LoadSoundType")){ if(!strcmp(ptr2, "0")){ /* 少し読み込み時間が長い、再生負荷は軽い */ loadSoundType = DX_SOUNDDATATYPE_MEMNOPRESS; /* 読み込むときに圧縮を展開 */ }else if(!strcmp(ptr2, "1")){ /* 程々の読み込み時間と再生負荷 */ loadSoundType = DX_SOUNDDATATYPE_MEMPRESS; /* 再生するときに圧縮を展開 */ }else if(!strcmp(ptr2, "2")){ /* 読み込み時間は短い、再生負荷は重い */ loadSoundType = DX_SOUNDDATATYPE_FILE; /* メモリにロードしない */ }else{ throw "[config] LoadSoundType は 0, 1 または 2 で指定しなければならない。(デフォルト: 1 )"; } }else if(!strcmp(ptr1, "Volume")){ if(!strcmp(ptr2, "default")){ volume = -1; }else{ int n; int tmp; tmp = sscanf(ptr2, "%d", &n); if(tmp < 1 || n < 0 || n > 255){ throw "[config] Volume は default または 0 以上 255 以下 で指定しなければならない。(デフォルト: default )"; } volume = n; } }else if(!strcmp(ptr1, "DefaultReplayFile")){ strcpy(defaultReplayFile, ptr2); /* 特に失敗はしない */ //throw ""; }else if(!strcmp(ptr1, "OverwriteReplay")){ if(!strcmp(ptr2, "never")){ overwriteReplay = CONFIG_NEVER; }else if(!strcmp(ptr2, "query")){ overwriteReplay = CONFIG_QUERY; }else if(!strcmp(ptr2, "always")){ overwriteReplay = CONFIG_ALWAYS; }else{ throw "[config] OverwriteReplay は never, query または always で指定しなければならない。(デフォルト: query )"; } }else if(!strcmp(ptr1, "RankingCheckDate")){ if(!strcmp(ptr2, "true")){ f_rankingCheckDate = true; }else if(!strcmp(ptr2, "false")){ f_rankingCheckDate = false; }else{ throw "[config] RankingCheckDate は true または false で指定しなければならない。(デフォルト: false )"; } }else if(!strcmp(ptr1, "RankingCheckChallenge")){ if(!strcmp(ptr2, "true")){ f_rankingCheckChallenge = true; }else if(!strcmp(ptr2, "false")){ f_rankingCheckChallenge = false; }else{ throw "[config] RankingCheckChallenge は true または false で指定しなければならない。(デフォルト: true )"; } }else if(!strcmp(ptr1, "FailByGauge")){ if(!strcmp(ptr2, "true")){ f_failByGauge = true; }else if(!strcmp(ptr2, "false")){ f_failByGauge = false; }else{ throw "[config] FailByGauge は true または false で指定しなければならない。(デフォルト: false )"; } }else if(!strcmp(ptr1, "FullScreen")){ if(!strcmp(ptr2, "true")){ f_fullScreen = true; }else if(!strcmp(ptr2, "false")){ f_fullScreen = false; }else{ throw "[config] FullScreen は true または false で指定しなければならない。(デフォルト: false )"; } }else if(!strcmp(ptr1, "ShowFPS")){ if(!strcmp(ptr2, "true")){ f_showFPS = true; }else if(!strcmp(ptr2, "false")){ f_showFPS = false; }else{ throw "[config] ShowFPS は true または false で指定しなければならない。(デフォルト: false )"; } }else if(!strcmp(ptr1, "WaitVSync")){ if(!strcmp(ptr2, "true")){ f_waitVSync = true; }else if(!strcmp(ptr2, "false")){ f_waitVSync = false; }else{ throw "[config] WaitVSync は true または false で指定しなければならない。(デフォルト: true )"; } }else if(!strcmp(ptr1, "DebugMode")){ if(!strcmp(ptr2, "true")){ f_debugMode = true; f_debugBeat = false; }else if(!strcmp(ptr2, "beat")){ f_debugMode = true; f_debugBeat = true; }else if(!strcmp(ptr2, "false")){ f_debugMode = false; }else{ throw "[config] DebugMode は true または beat または false で指定しなければならない。(デフォルト: false )"; } }else if(!strcmp(ptr1, "DebugTime")){ int n; int tmp; tmp = sscanf(ptr2, "%d", &n); if(tmp < 1 || n < 0){ throw "[config] DebugTime は 0 以上 で指定しなければならない。(デフォルト: 0 )"; } debugTime = n; }else if(!strcmp(ptr1, "ShowProcessTime")){ if(!strcmp(ptr2, "true")){ f_showProcessTime = true; }else if(!strcmp(ptr2, "false")){ f_showProcessTime = false; }else{ throw "[config] ShowProcessTime は true または false で指定しなければならない。(デフォルト: false )"; } }else{ //throw "[config] 設定できる値は UseMultiThread, LoadSoundType, DebugMode である。"; //throw "[config] 設定できる値は LoadSoundType, Volume, FullScreen, ShowFPS, WaitVSync, DebugMode である。"; throw "[config] 設定できない項目を設定しようとした。"; } } fclose(fp); } #endif
[ [ [ 1, 221 ] ] ]
4835fca6077218001af8d7bede9e2798da497419
8a3fce9fb893696b8e408703b62fa452feec65c5
/业余时间学习笔记/宏定义.cpp
ba4f6e3e7fc20717825ea7ef719e5958d62a4f2c
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
GB18030
C++
false
false
4,120
cpp
1,防止一个头文件被重复包含 #ifndef BODYDEF_H #define BODYDEF_H //头文件内容 #endif 2,得到指定地址上的一个字节或字 #define MEM_B( x ) ( *( (byte *) (x) ) ) #define MEM_W( x ) ( *( (word *) (x) ) ) 3,得到一个field在结构体(struct)中的偏移量 #define FPOS( type, field ) ( (dword) &(( type *) 0)-> field ) 4,得到一个结构体中field所占用的字节数 #define FSIZ( type, field ) sizeof( ((type *) 0)->field ) 5,得到一个变量的地址(word宽度) #define B_PTR( var ) ( (byte *) (void *) &(var) ) #define W_PTR( var ) ( (word *) (void *) &(var) ) 6,将一个字母转换为大写 #define UPCASE( c ) ( ((c) >= ''a'' && (c) <= ''z'') ? ((c) - 0x20) : (c) ) 7,判断字符是不是10进值的数字 #define DECCHK( c ) ((c) >= ''0'' && (c) <= ''9'') 8,判断字符是不是16进值的数字 #define HEXCHK( c ) ( ((c) >= ''0'' && (c) <= ''9'') ||((c) >= ''A'' && (c) <= ''F'') ||((c) >= ''a'' && (c) <= ''f'') ) 9,防止溢出的一个方法 #define INC_SAT( val ) (val = ((val)+1 > (val)) ? (val)+1 : (val)) 10,返回数组元素的个数 #define ARR_SIZE( a ) ( sizeof( (a) ) / sizeof( (a[0]) ) ) 11,使用一些宏跟踪调试 ANSI标准说明了五个预定义的宏名。它们是: _LINE_ (两个下划线),对应%d _FILE_ 对应%s _DATE_ 对应%s _TIME_ 对应%s _STDC_ 宏中"#"和"##"的用法 我们使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起. #define STR(s) #s #define CONS(a,b) int(a##e##b) Printf(STR(vck)); // 输出字符串"vck" printf("%d\n", CONS(2,3)); // 2e3 输出:2000 当宏参数是另一个宏的时候 需要注意的是凡宏定义里有用"#"或"##"的地方宏参数是不会再展开. #define A (2) #define STR(s) #s #define CONS(a,b) int(a##e##b) printf("%s\n", CONS(A, A)); // compile error 这一行则是: printf("%s\n", int(AeA)); INT_MAX和A都不会再被展开, 然而解决这个问题的方法很简单. 加多一层中间转换宏. 加这层宏的用意是把所有宏的参数在这层里全部展开, 那么在转换宏里的那一个宏(_STR)就能得到正确的宏参数 #define STR(s) _STR(s) // 转换宏 #define CONS(a,b) _CONS(a,b) // 转换宏 printf("int max: %s\n", STR(INT_MAX)); // INT_MAX,int型的最大值,为一个变量 #include<climits> 输出为: int max: 0x7fffffff STR(INT_MAX) --> _STR(0x7fffffff) 然后再转换成字符串; printf("%d\n", CONS(A, A)); 输出为:200 CONS(A, A) --> _CONS((2), (2)) --> int((2)e(2)) "#"和"##"的一些应用特例 1、合并匿名变量名 #define ___ANONYMOUS1(type, var, line) type var##line #define __ANONYMOUS0(type, line) ___ANONYMOUS1(type, _anonymous, line) #define ANONYMOUS(type) __ANONYMOUS0(type, __LINE__) 例:ANONYMOUS(static int); 即: static int _anonymous70; 70表示该行行号; 第一层:ANONYMOUS(static int); --> __ANONYMOUS0(static int, __LINE__); 第二层: --> ___ANONYMOUS1(static int, _anonymous, 70); 第三层: --> static int _anonymous70; 即每次只能解开当前层的宏,所以__LINE__在第二层才能被解开; 2、填充结构 #define FILL(a) {a, #a} enum IDD{OPEN, CLOSE}; typedef struct MSG{ IDD id; const char * msg; }MSG; MSG _msg[] = {FILL(OPEN), FILL(CLOSE)}; 相当于: MSG _msg[] = {{OPEN, "OPEN"}, {CLOSE, "CLOSE"}}; 3、记录文件名 #define _GET_FILE_NAME(f) #f #define GET_FILE_NAME(f) _GET_FILE_NAME(f) static char FILE_NAME[] = GET_FILE_NAME(__FILE__); 4、得到一个数值类型所对应的字符串缓冲大小 #define _TYPE_BUF_SIZE(type) sizeof #type #define TYPE_BUF_SIZE(type) _TYPE_BUF_SIZE(type) char buf[TYPE_BUF_SIZE(INT_MAX)]; --> char buf[_TYPE_BUF_SIZE(0x7fffffff)]; --> char buf[sizeof "0x7fffffff"]; 这里相当于: char buf[11];
[ [ [ 1, 99 ] ] ]
aa5a67b365adac6d3f1109797f0e4e2caeed16f3
f2b70f0f8d6f61899eb70b9f2626f1eb44f68cc7
/libs/qtutil/include/qtutil/highlighter.h
c9024044d182cdc7ff95321219821c1d3f860f03
[]
no_license
vikas100/VoxOx
cc36efcbb9a82da03c05ea76093426aafba3bd8c
d4fae14f3f5a4de29abad3b79f4903db01daa913
refs/heads/master
2020-05-18T06:57:08.968725
2011-05-14T01:56:29
2011-05-14T01:56:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,815
h
/**************************************************************************** ** ** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Alternatively you may (at ** your option) use any later version of the GNU General Public ** License if such license has been publicly approved by Trolltech ASA ** (or its successors, if any) and the KDE Free Qt Foundation. In ** addition, as a special exception, Trolltech gives you certain ** additional rights. These rights are described in the Trolltech GPL ** Exception version 1.1, which can be found at ** http://www.trolltech.com/products/qt/gplexception/ and in the file ** GPL_EXCEPTION.txt in this package. ** ** Please review the following information to ensure GNU General ** Public Licensing requirements will be met: ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If ** you are unsure which license is appropriate for your use, please ** review the following information: ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview ** or contact the sales department at [email protected]. ** ** In addition, as a special exception, Trolltech, as the sole ** copyright holder for Qt Designer, grants users of the Qt/Eclipse ** Integration plug-in the right for the Qt/Eclipse Integration to ** link to functionality provided by Qt Designer and its related ** libraries. ** ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly ** granted herein. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #ifndef HIGHLIGHTER_H #define HIGHLIGHTER_H #include <QtGui/QSyntaxHighlighter> #include <QtCore/QHash> #include <QtGui/QTextCharFormat> #include "hunspell/hunspell.hxx" class QTextDocument; class Highlighter : public QSyntaxHighlighter { Q_OBJECT public: Highlighter(Hunspell * Checker,QTextDocument *parent = 0,QString SpellDic="",bool spellCheckState=false); ~Highlighter(); void clearCheck(); QStringList misspelled(); QStringList correct(); void enableSpellChecking(const bool state); void setSpellCheck(const bool state); bool setDict(const QString SpellDic); //VOXOX - CJC - 2009.05.03 Add set method so not 2 variables are created void setHuspellChecker(Hunspell * Checker){pChecker = Checker;} public Q_SLOTS: void slot_addWord(QString word); protected: void highlightBlock(const QString &text); void spellCheck(const QString &text); bool checkWord(QString word); private: struct HighlightingRule { QRegExp pattern; QTextCharFormat format; }; QVector<HighlightingRule> highlightingRules; QRegExp commentStartExpression; QRegExp commentEndExpression; QTextCharFormat keywordFormat; QTextCharFormat classFormat; QTextCharFormat singleLineCommentFormat; QTextCharFormat multiLineCommentFormat; QTextCharFormat quotationFormat; QTextCharFormat functionFormat; QString spell_dic, spell_encoding; Hunspell * pChecker; bool spellCheckActive,spellerError; QTextCharFormat spellCheckFormat; QTextCodec *codec; }; #endif
[ [ [ 1, 105 ] ] ]
3ec41541e68c99bfe3a9df23182ce311353d84d2
27687dfacdfa03f7a1f509e36e848fa1767f47b3
/Addonissimo2/includes/CDetourReq.h
df6bce1cf340c3334a49a053168dd339e9474362
[]
no_license
Gbps/gmod
7f11a79e439c2c63233ad9dcc2e3c32e6c8ceb95
125f7c94e5732abc4dac441181bc3bad51c7aa23
refs/heads/master
2022-06-20T18:36:45.742134
2011-08-04T03:08:58
2011-08-04T03:08:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
h
#pragma once #define _TARGET_PROCESS_NAME "hl2.exe" // Includes win headers // Many includes are unnnecessary for this project #include <Windows.h> #include <stdio.h> #include <fstream> #include <intrin.h> #include <windows.h> #include <winnt.h> #include <WinBase.h> #include <tlhelp32.h> #include <shlwapi.h> #include <stdio.h> #include <iostream> #include <direct.h> #include <time.h> #include <Psapi.h> #include <math.h> // Pragma comments #pragma comment(lib, "shlwapi.lib") #pragma comment(lib, "Psapi.lib") // Namespace defines using namespace std; #define GET_INT(x) (*(int *) (x)) #define GET_SHORT(x) (*(short *) (x)) #define GET_BYTE(x) (*(char *) (x)) #define GET_FLOAT(x) (*(float *) (x)) #define GET_DWORD(x) (*(DWORD *) (x)) #define GET_CHAR(x) (*(char*) (x)) typedef unsigned __int8 uint8; typedef unsigned __int16 uint16; typedef unsigned __int32 uint32; typedef unsigned __int64 uint64; typedef __int8 int8; typedef __int16 int16; typedef __int32 int32; typedef __int64 int64; #include "ADE32.h" #include "CDetour.h"
[ "cowmonkey111@ea4bc6c7-d654-2506-312e-aa9fc04bc719" ]
[ [ [ 1, 49 ] ] ]
24a84e2a7357cbda14f4010d5c7b41db0cf5c21b
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/include/Ngl/OpenGL/BufferGL.h
97f9fef606b72cfd0d1a3114938047d44e917804
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,691
h
/*******************************************************************************/ /** * @file BufferGL.h. * * @brief OpenGL バッファクラスヘッダファイル. * * @date 2008/07/20. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_OPENGL_BUFFERGL_H_ #define _NGL_OPENGL_BUFFERGL_H_ #include "Ngl/IBuffer.h" #include "OpenGL.h" namespace Ngl{ namespace OpenGL{ /** * @class BufferGL. * @brief OpenGL バッファクラス. */ class BufferGL : public IBuffer { public: /*=========================================================================*/ /** * @brief コンストラクタ * * @param[in] desc バッファ作成記述子. * @param[in] data バッファデータ. */ BufferGL( const BufferDesc& desc, const void* data=0 ); /*=========================================================================*/ /** * @brief デストラクタ * * @param[in] なし. */ virtual ~BufferGL(); /*=========================================================================*/ /** * @brief 記述子を取得する * * @param[in] なし. * @return バッファ記述子. */ const BufferDesc& desc() const; /*=========================================================================*/ /** * @brief バッファデータの設定 * * @param[in] data 設定するデータ. * @return なし. */ void setData( const void* data ); /*=========================================================================*/ /** * @brief バッファデータの取得 * * @param[out] data バッファデータを格納するデータ. * @return なし. */ void getData( void* data ) const; /*=========================================================================*/ /** * @brief OepnGLバッファインデックスの取得 * * @param[out] なし. * @return OpenGLバッファインデックス. */ GLuint buffer() const; private: /*=========================================================================*/ /** * @brief バッファタイプを変換 * * @param[in] type 変換するバッファタイプ. * @return 変換したOpenGLバッファタイプ. */ static GLenum toTarget( BufferType type ); /*=========================================================================*/ /** * @brief バッファの使用方法を変換 * * @param[in] usage 変換するバッファの使用方法フラグ. * @return 変換したOpenGLバッファ使用方法フラグ. */ static GLenum toUsage( BufferUsage usage ); private: /*=========================================================================*/ /** * @brief コピーコンストラクタ( コピー禁止 ) * * @param[in] other 代入するオブジェクト. */ BufferGL( const BufferGL& other ); /*=========================================================================*/ /** * @brief = 演算子オーバーロード( コピー禁止 ) * * @param[in] other 代入するオブジェクト. * @return 代入結果のオブジェクト. */ BufferGL& operator = ( const BufferGL& other ); private: /** 記述子 */ BufferDesc desc_; /** バッファオブジェクト */ GLuint buffer_; /** ターゲット */ GLenum target_; /** 使用方法 */ GLenum usage_; }; } // namespace OpenGL } // namespace Ngl #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 155 ] ] ]
56c2b3c1b1531ecf60aada5a2d6dc1f013cc274b
b2fa537cef03244de283e231932f22ee41aec051
/src/agg/agg_span_image_filter.h
8ecbbd4138853e2cc38c37a97bb708dc79f3102c
[]
no_license
rebolsource/r3-hostkit
2e0037119cde8a161e2f7994fd3842cc3891e9d5
f331c6a46947e6e5afedc90f3d375bcd3f7ad8a1
refs/heads/master
2021-01-10T18:34:50.420402
2010-09-09T18:38:59
2010-09-10T11:59:58
813,301
0
0
null
null
null
null
UTF-8
C++
false
false
5,367
h
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.3 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: [email protected] // [email protected] // http://www.antigrain.com //---------------------------------------------------------------------------- // // Image transformations with filtering. Span generator base class // //---------------------------------------------------------------------------- #ifndef AGG_SPAN_IMAGE_FILTER_INCLUDED #define AGG_SPAN_IMAGE_FILTER_INCLUDED #include "agg_basics.h" #include "agg_image_filters.h" #include "agg_rendering_buffer.h" #include "agg_span_generator.h" namespace agg { //--------------------------------------------------span_image_filter template<class ColorT, class Interpolator, class Allocator> class span_image_filter : public span_generator<ColorT, Allocator> { public: typedef ColorT color_type; typedef Allocator alloc_type; typedef Interpolator interpolator_type; typedef span_generator<color_type, alloc_type> base_type; //---------------------------------------------------------------- span_image_filter(alloc_type& alloc) : span_generator<color_type, alloc_type>(alloc) {} //---------------------------------------------------------------- span_image_filter(alloc_type& alloc, const rendering_buffer& src, const color_type& back_color, interpolator_type& interpolator, const image_filter_lut* filter) : span_generator<color_type, alloc_type>(alloc), m_src(&src), m_back_color(&back_color), m_interpolator(&interpolator), m_filter(filter), m_dx_dbl(0.5), m_dy_dbl(0.5), m_dx_int(image_subpixel_size / 2), m_dy_int(image_subpixel_size / 2) {} //---------------------------------------------------------------- span_image_filter(alloc_type& alloc, const rendering_buffer& src, const rendering_buffer& dst, interpolator_type& interpolator, const image_filter_lut* filter) : span_generator<color_type, alloc_type>(alloc), m_src(&src), m_dst(&dst), m_back_color(NULL), m_interpolator(&interpolator), m_filter(filter), m_dx_dbl(0.5), m_dy_dbl(0.5), m_dx_int(image_subpixel_size / 2), m_dy_int(image_subpixel_size / 2) {} //---------------------------------------------------------------- const rendering_buffer& source_image() const { return *m_src; } const rendering_buffer& destination_image() const { return *m_dst; } const color_type& background_color() const { return *m_back_color; } const image_filter_lut& filter() const { return *m_filter; } int filter_dx_int() const { return m_dx_int; } int filter_dy_int() const { return m_dy_int; } double filter_dx_dbl() const { return m_dx_dbl; } double filter_dy_dbl() const { return m_dy_dbl; } //---------------------------------------------------------------- void source_image(const rendering_buffer& v) { m_src = &v; } void background_color(const color_type& v) { m_back_color = &v; } void interpolator(interpolator_type& v) { m_interpolator = &v; } void filter(const image_filter_lut& v) { m_filter = &v; } void filter_offset(double dx, double dy) { m_dx_dbl = dx; m_dy_dbl = dy; m_dx_int = int(dx * image_subpixel_size); m_dy_int = int(dy * image_subpixel_size); } void filter_offset(double d) { filter_offset(d, d); } //---------------------------------------------------------------- interpolator_type& interpolator() { return *m_interpolator; } //-------------------------------------------------------------------- void prepare(unsigned max_span_len) { base_type::prepare(max_span_len); } //---------------------------------------------------------------- private: const rendering_buffer* m_src; const rendering_buffer* m_dst; const color_type* m_back_color; interpolator_type* m_interpolator; const image_filter_lut* m_filter; double m_dx_dbl; double m_dy_dbl; unsigned m_dx_int; unsigned m_dy_int; }; } #endif
[ [ [ 1, 129 ] ] ]
f4f87ea6e3743588479daffc6e8cd91da09737df
99c792a222fd8fb93242598a247591e28a766769
/configuration.h
9b8baeaa5b92b4ebfe3925eae4f0a0e43edae716
[]
no_license
benkopolis/windows-xml-logs-parser
0cebfbdf104ef6d332278177eb89c1b7a375e7e9
54bc23afe11fc966ff848fa56ff9cb861af996e1
refs/heads/master
2016-09-06T02:17:09.855692
2011-06-06T10:29:53
2011-06-06T10:29:53
32,231,282
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#ifndef CONFIGURATION_H #define CONFIGURATION_H #include <QObject> #include <QIODevice> #include <QVariantMap> #include "commons/exception.h" #include <QMutex> /** * This class reads configuration from given file. * Coniguration should have proper format, described in documentation. * It is singleton protected by MUTEX. */ class Configuration : public QObject { Q_OBJECT public: static Configuration* instance(); bool validateConfiguration() const; inline QVariantMap& properties() { return m_properties; } signals: public slots: void readConfig(QIODevice* device); void saveConfig(QIODevice* device); protected: QVariantMap m_properties; static Configuration* m_instance; static QMutex* m_mutex; void readSingleLine(QString line); explicit Configuration(QObject *parent = 0); }; #endif // CONFIGURATION_H
[ "[email protected]@da19ff29-70bf-c5c3-61f4-a312932c5284" ]
[ [ [ 1, 45 ] ] ]
ce2d874a5ec9b6fab7e4736946cc6a170f1d6a6d
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/august/AugustText.h
e3477dcb7812b35703fb54e73e6e04bdb09e55e1
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,066
h
////////////////////////////////////////////////////////// // // AugustText // ////////////////////////////////////////////////////////// #ifndef __AugustText_H__ #define __AugustText_H__ #include "agh.h" #include "AugustCommon.h" #include "MglGraphicManager.h" #include "MglText.h" //class DLL_EXP agh::CTextBase; //class DLL_EXP agh::CTextBase< CAugustVisualControlBase >; #pragma warning( disable : 4660 ) template class DLL_EXP agh::CTextBaseT< CAugustVisualControlBase >; // クラス宣言 ///////////////////////////////////////////////////////// //class DLL_EXP CAugustText : public agh::CTextBase, public CAugustControlBase class DLL_EXP CAugustText : public agh::CTextBaseT< CAugustVisualControlBase > { private: typedef agh::CTextBaseT< CAugustVisualControlBase > _BASE; //BOOL bBold, bItalic, bUnderLine, bStrikeOut; void ReCreateFont(); DWORD GetDrawInternalOption(); protected: CMglText m_text; // ---- Event Handlers ---- void OnRegist(CAugustGlobalCommon *pGlobal); void OnDraw(); public: // ---- Public Event Handlers ---- virtual void SetOption(agh::AGHDWORD dwOption); virtual void SetFontName(const char* szFontName); virtual void SetFontPoint(int point); //virtual void SetStr(const char* szStr){ m_textData = szStr; } //virtual const char* GetStr(){ return m_textData.c_str(); } virtual void SetColor(agh::COLOR color); //virtual void SetOption(AGHDWORD dwOption); //virtual AGHCOLOR GetColor(){ return m_color; } //virtual AGHDWORD GetOption(){ return m_dwOption; } //virtual void Align(int align){ m_nAlign = align; } public: // コンストラクタ CAugustText(){ m_pGrp = NULL; /*bBold = FALSE; bItalic = FALSE; bUnderLine = FALSE; bStrikeOut = FALSE;*/ } virtual ~CAugustText(){} // 作っておかないと恐らくCTextBaseからのデストラクタが上手く動かない気がする・・・ virtual agh::CControlBase* _GetAghControl(){ return this; } }; //typedef CAugustText CMglguiText; #endif//__AugustText_H__
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 68 ] ] ]
610a750d33a62c55191434d2fdfa4dfc085365a7
fbf246f1ea06a14b61bf04f20d9bf90b9ff73ef5
/GameAndWatch/src/devices/deveng_vtech_banana.cpp
c7a8314402a732f98e86937e40c67ec10501aa12
[]
no_license
biappi/GameAndWatch
e503f4ebabb326a45c81380f32358f9f810c9b2d
a586b16a48727b587253f1b95c89cf40fb4429d6
refs/heads/master
2020-09-21T14:02:05.733066
2011-08-31T16:16:23
2011-08-31T16:16:23
2,295,881
1
0
null
null
null
null
UTF-8
C++
false
false
10,710
cpp
#include "gwdbg.h" #include "devices/deveng_vtech_banana.h" GW_GameEngine_VTech_Banana::GW_GameEngine_VTech_Banana(int engineoptions, int options) : GW_GameEngine_VTech(engineoptions), options_(options) { // "BANANA" is default gamepath_set("banana"); size_set(561, 347); // game screen position GW_PLATFORM_RECT(gr, 152, 53, 257, 192); gamerect_set(gr); // transparent colors GW_PLATFORM_RGB(tcolor_bg, 255, 0, 255); GW_PLATFORM_RGB(tcolor_img, 255, 255, 255); // character 1 data(). position_add(PS_CHAR_1, 1, 258, 138, IM_CHAR_1, 1, "im_char_1_1.bmp", &tcolor_img); if ((options_&GO_HAVECHARANIM)==GO_HAVECHARANIM) data(). position_add(PS_CHAR_1, 2, 236, 145, IM_CHAR_1, 2, "im_char_1_2.bmp", &tcolor_img)-> position_add(PS_CHAR_1, 3, 247, 128, IM_CHAR_1, 3, "im_char_1_3.bmp", &tcolor_img); // character 2 data(). position_add(PS_CHAR_2, 1, 280, 141, IM_CHAR_2, 1, "im_char_2_1.bmp", &tcolor_img); if ((options_&GO_HAVECHARANIM)==GO_HAVECHARANIM) data(). position_add(PS_CHAR_2, 2, 312, 149, IM_CHAR_2, 2, "im_char_2_2.bmp", &tcolor_img)-> position_add(PS_CHAR_2, 3, 309, 129, IM_CHAR_2, 3, "im_char_2_3.bmp", &tcolor_img); // character 3 data(). position_add(PS_CHAR_3, 1, 200, 207, IM_CHAR_3, 1, "im_char_3_1.bmp", &tcolor_img); if ((options_&GO_HAVECHARANIM)==GO_HAVECHARANIM) data(). position_add(PS_CHAR_3, 2, 226, 214, IM_CHAR_3, 2, "im_char_3_2.bmp", &tcolor_img)-> position_add(PS_CHAR_3, 3, 225, 197, IM_CHAR_3, 3, "im_char_3_3.bmp", &tcolor_img); // character 4 data(). position_add(PS_CHAR_4, 1, 349, 211, IM_CHAR_4, 1, "im_char_4_1.bmp", &tcolor_img); if ((options_&GO_HAVECHARANIM)==GO_HAVECHARANIM) data(). position_add(PS_CHAR_4, 2, 327, 215, IM_CHAR_4, 2, "im_char_4_2.bmp", &tcolor_img)-> position_add(PS_CHAR_4, 3, 335, 201, IM_CHAR_4, 3, "im_char_4_3.bmp", &tcolor_img); // item 1 data(). position_add(PS_ITEM_1, 1, 160, 99, IM_ITEM_1, 1, "im_item_1_01.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 2, 178, 101, IM_ITEM_1, 2, "im_item_1_02.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 3, 200, 101, IM_ITEM_1, 3, "im_item_1_03.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 4, 226, 99, IM_ITEM_1, 4, "im_item_1_04.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 5, 264, 100, IM_ITEM_1, 5, "im_item_1_05.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 6, 281, 100, IM_ITEM_1, 6, "im_item_1_06.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 7, 307, 99, IM_ITEM_1, 7, "im_item_1_07.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 8, 340, 100, IM_ITEM_1, 8, "im_item_1_08.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 9, 359, 100, IM_ITEM_1, 9, "im_item_1_09.bmp", &tcolor_img)-> position_add(PS_ITEM_1, 10, 380, 101, IM_ITEM_1, 10, "im_item_1_10.bmp", &tcolor_img)-> position_add(PS_ITEM_1, IDX_MISS_4, 244, 94, IM_ITEM_1, IDX_MISS_4, "im_item_1_04miss.bmp", &tcolor_img)-> //position_add(PS_ITEM_1, IDX_OBSTACLE_4, 236, 130, IM_ITEM_1, IDX_OBSTACLE_4, "im_item_1_04obstacle.bmp", &tcolor_img)-> position_add(PS_ITEM_1, IDX_MISS_7, 320, 93, IM_ITEM_1, IDX_MISS_7, "im_item_1_07miss.bmp", &tcolor_img); /* if ((options_&GO_HAVEOBSTACLE17)==GO_HAVEOBSTACLE17) data(). position_add(PS_ITEM_1, IDX_OBSTACLE_7, 321, 132, IM_ITEM_1, IDX_OBSTACLE_7, "im_item_1_07obstacle.bmp", &tcolor_img); */ // item 2 data(). position_add(PS_ITEM_2, 1, 160, 171, IM_ITEM_2, 1, "im_item_2_01.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 2, 184, 169, IM_ITEM_2, 2, "im_item_2_02.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 3, 205, 169, IM_ITEM_2, 3, "im_item_2_03.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 4, 238, 168, IM_ITEM_2, 4, "im_item_2_04.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 5, 265, 168, IM_ITEM_2, 5, "im_item_2_05.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 6, 291, 168, IM_ITEM_2, 6, "im_item_2_06.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 7, 330, 169, IM_ITEM_2, 7, "im_item_2_07.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 8, 347, 170, IM_ITEM_2, 8, "im_item_2_08.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 9, 367, 169, IM_ITEM_2, 9, "im_item_2_09.bmp", &tcolor_img)-> position_add(PS_ITEM_2, 10, 386, 166, IM_ITEM_2, 10, "im_item_2_10.bmp", &tcolor_img)-> position_add(PS_ITEM_2, IDX_MISS_4, 207, 159, IM_ITEM_2, IDX_MISS_4, "im_item_2_04miss.bmp", &tcolor_img)-> //position_add(PS_ITEM_2, IDX_OBSTACLE_4, 239, 202, IM_ITEM_2, IDX_OBSTACLE_4, "im_item_2_04obstacle.bmp", &tcolor_img)-> position_add(PS_ITEM_2, IDX_MISS_7, 304, 167, IM_ITEM_2, IDX_MISS_7, "im_item_2_07miss.bmp", &tcolor_img); //position_add(PS_ITEM_2, IDX_OBSTACLE_7, 324, 201, IM_ITEM_2, IDX_OBSTACLE_7, "im_item_2_07obstacle.bmp", &tcolor_img); // obstacle data(). position_add(PS_OBSTACLE, 1, 236, 130, IM_OBSTACLE, 1, "im_item_1_04obstacle.bmp", &tcolor_img)-> position_add(PS_OBSTACLE, 3, 239, 202, IM_OBSTACLE, 3, "im_item_2_04obstacle.bmp", &tcolor_img)-> position_add(PS_OBSTACLE, 4, 324, 201, IM_OBSTACLE, 4, "im_item_2_07obstacle.bmp", &tcolor_img); if ((options_&GO_HAVEOBSTACLE17)==GO_HAVEOBSTACLE17) data(). position_add(PS_OBSTACLE, 2, 321, 132, IM_OBSTACLE, 2, "im_item_1_07obstacle.bmp", &tcolor_img); // numbers data(). position_change(PS_NUMBER, 1, 257, 61)-> position_change(PS_NUMBER, 2, 272, 61)-> position_change(PS_NUMBER, 3, 290, 61)-> position_change(PS_NUMBER, 4, 305, 61)-> position_change(PS_SEMICOLON, 0, 286, 66); // miss data(). position_change(PS_MISS, 1, 333, 61)-> position_change(PS_MISS, 2, 349, 61)-> position_change(PS_MISS, 3, 363, 61)-> position_change(PS_MISS, 4, 377, 61)-> position_change(PS_MISS, 5, 392, 61)-> position_change(PS_MISS, 6, 334, 75)-> position_change(PS_MISS, 7, 349, 75)-> position_change(PS_MISS, 8, 363, 75)-> position_change(PS_MISS, 9, 377, 75)-> position_change(PS_MISS, 10, 392, 75); // options data(). position_change(PS_GAMEA, 0, 160, 61)-> position_change(PS_GAMEB, 0, 160, 72)-> position_change(PS_ALARM, 0, 206, 73)-> position_change(PS_BELL, 0, 186, 63)-> position_change(PS_CHRONO, 0, 223, 73)-> position_change(PS_DATE, 0, 237, 73)-> position_change(PS_TIME1, 0, 229, 61)-> position_change(PS_TIME2, 0, 206, 61)-> position_change(PS_AM, 0, 320, 61)-> position_change(PS_PM, 0, 320, 76); // sounds data(). sound_add(SND_HIGH, "High.wav")-> sound_add(SND_LOW, "Low.wav")-> sound_add(SND_MISS, "Miss.wav")-> sound_add(SND_OVER, "Over.wav")-> sound_add(SND_SAFE, "Safe.wav")-> sound_add(SND_START, "Start.wav"); // timers data(). timer_add(TMR_HIT, 75, false)-> timer_get(TMR_GAME)->time_set(500); } void GW_GameEngine_VTech_Banana::do_timer(int timerid) { GW_GameEngine_VTech::do_timer(timerid); switch (timerid) { case TMR_HIT: char_update(char_position_, false); break; } } void GW_GameEngine_VTech_Banana::Event(GW_Platform_Event *event) { GW_GameEngine_VTech::Event(event); if (event->id==GPE_KEYDOWN) { switch (event->data) { case GPK_UPLEFT: if ((GetMode()==MODE_GAMEA || GetMode()==MODE_GAMEB) && canmove_get()) { char_update(0, true); data_starttimer(TMR_HIT); } break; case GPK_DOWNLEFT: if ((GetMode()==MODE_GAMEA || GetMode()==MODE_GAMEB) && canmove_get()) { char_update(2, true); data_starttimer(TMR_HIT); } break; case GPK_UPRIGHT: if ((GetMode()==MODE_GAMEA || GetMode()==MODE_GAMEB) && canmove_get()) { char_update(1, true); data_starttimer(TMR_HIT); } break; case GPK_DOWNRIGHT: if ((GetMode()==MODE_GAMEA || GetMode()==MODE_GAMEB) && canmove_get()) { char_update(3, true); data_starttimer(TMR_HIT); } break; } } } void GW_GameEngine_VTech_Banana::game_start(int mode) { GW_GameEngine_VTech::game_start(mode); tick_=1; char_update(0, false); data().position_get(PS_ITEM_1, 1)->show(); data().position_get(PS_ITEM_2, 10)->show(); data_playsound(SND_START); } void GW_GameEngine_VTech_Banana::game_tick() { static int curitem, posmod; tick_++; if (tick_>1) tick_=0; GWDBG_FOUTPUT("game_tick: %d\n", tick_) curitem=PS_ITEM_1+tick_; if (curitem==PS_ITEM_1) posmod=0; else posmod=10+1; for (int i=10; i>=2; i--) { if (curitem==PS_ITEM_1) data().position_get(PS_ITEM_1, i)->visible_set(data().position_get(PS_ITEM_1, i-1)->visible_get()); else if (curitem==PS_ITEM_2) data().position_get(PS_ITEM_2, 10-i+1)->visible_set(data().position_get(PS_ITEM_2, 10-i+2)->visible_get()); } if (curitem==PS_ITEM_1) data().position_get(PS_ITEM_1, 1)->visible_set(false); else if (curitem==PS_ITEM_2) data().position_get(PS_ITEM_2, 10)->visible_set(false); if (tick_==0) data_playsound(SND_HIGH); else if (tick_==1) data_playsound(SND_LOW); } void GW_GameEngine_VTech_Banana::char_update(int pos, bool hit) { char_position_=pos; for (int i=PS_CHAR_1; i<=PS_CHAR_4; i++) { data().position_get(i, 1)->visible_set(i-PS_CHAR_1==pos); if ((options_&GO_HAVECHARANIM)==GO_HAVECHARANIM) { data().position_get(i, 2)->visible_set(i-PS_CHAR_1==pos && !hit); data().position_get(i, 3)->visible_set(i-PS_CHAR_1==pos && hit); } } obstacle_update(pos+1); } void GW_GameEngine_VTech_Banana::obstacle_update(int pos) { for (int i=1; i<=4; i++) { if (i==2 && (options_&GO_HAVEOBSTACLE17)!=GO_HAVEOBSTACLE17) continue; data().position_get(PS_OBSTACLE, i)->visible_set(i!=pos); } }
[ [ [ 1, 272 ] ] ]
3dfe4245a424003a84ae16492b4de1576e8df1c3
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleCore/TLDebug.h
59fb6e19dea15d0c29cc20e92a6efd0628225e64
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,789
h
/*------------------------------------------------------ Debug routines - mostly dummy wrappers for the GutGut debug stuff for now FAQ: Are you getting an error like... error C2664: 'TLDebug::Break' : cannot convert parameter 1 from 'const char [17]' to 'const TString &' error C2665: 'TLDebug::Break' : none of the 2 overloads could convert all the argument types Then include TString.h in your source. Just to clarify (because I think some of my debug code is wrong) if a debug check/break routine returns FALSE, then HALT/ABORT/QUIT if it returns TRUE, CONTINUE as if nothing wrong so; if ( CheckIndex() == FALSE ) FAIL if ( DebugBreak() == FALSE ) FAIL if ( DebugBreak() == TRUE ) CONTINUE -------------------------------------------------------*/ #pragma once #include "TLTypes.h" // ENABLE_DEBUG_TRACE can now be used in debug or release. This will enable the debug break, assert and printing. // Ideally we want to have this functionality available at all times and switch it on/off based on some // runtime setting but there is a large overhead to the debug printing code. Perhaps we need to alter the // debug code to be some kind of static object that publishers messages and have the console printing an optional subscriber? // - it would be nice to be able to intercept debug calls and send them via the network to a network client for instance // rather than just being output to the console. We could intercept these debug messages and send them to a file instead of or as well? // We probably need a couple more debug routines too i.e. Debug_Informational, Debug_Critical that could be enabled/disabled based on // the release type. Rather than using the _DEBUG option we should try and use some kind of define with granularity // such as DEBUG_LEVEL == [ NONE | CRITICAL | MINIMAL | ALL ] or some kind of runtime bitwise set of flags for each type so we can alter the // level of debug information at runtime? Things to consider is code within the debug that is ONLY available in debug or not. #if defined(_DEBUG) #define ENABLE_DEBUG_TRACE #else //#define ENABLE_DEBUG_TRACE #endif // enable this define to enable array/float/limit checks #if defined(_DEBUG) && defined(TL_USER_GRAHAM) #define DEBUG_CHECK_INDEXES #define DEBUG_CHECK_VALUES #endif // macro interfaces to debug routines... why? because we want to catch the FILE and LINE where it breaks // using these will also be faster in release mode because the strings won't be constructed // gr: because of how _DEBUG is defined, if your lib is release the do-nothing-macros will do nothing. The use of these // is per-lib, not how the Core lib is built. // use TLDebug::IsEnabled() for more accurate global debug support #if defined(ENABLE_DEBUG_TRACE) #define TLDebug_Break(String) TLDebug::Break( String, (const char*)__FUNCTION__ ) #define TLDebug_Assert(Condition,String) ( (Condition) ? TRUE : TLDebug::Break( String, (const char*)__FUNCTION__ ) ) #define TLDebug_Print(String) TLDebug::Print( String, (const char*)__FUNCTION__ ) #define TLDebug_Warning(String) TLDebug::Print( String, (const char*)__FUNCTION__ ) #define TLDebug_FlushBuffer() TLDebug::FlushBuffer() #else #define TLDebug_Assert(Conditon,String) FALSE // [13/05/10] DB - When testing for why the release build often fails when setting the optimisation level (to anything now) I was // able to swap the debug break from a FALSE define to a function returning FALSE that fixed the problem. // It only seemed to occur for this routine ( I tested each of the other debug routines in turn and in combinations) // and it could be coincidence due to volume of this call combined with code re-ordering, macro replacement as well // as the optimisation but for now this appeared to fix the issue. //#define TLDebug_Break(String) FALSE // by default do NOT continue from breaks #define TLDebug_Break(String) TLDebug::NoBreak() #define TLDebug_Print(String) {} #define TLDebug_Warning(String) {} #define TLDebug_FlushBuffer() {} //#define TLDebug_Assert(Condition,String) ( (Condition) ? TRUE : TLDebug::Break( String, (const char*)__FUNCTION__ ) ) //#define TLDebug_Break(String) TLDebug::Break( String, (const char*)__FUNCTION__ ) //#define TLDebug_Print(String) TLDebug::Print( String, (const char*)__FUNCTION__ ) //#define TLDebug_Warning(String) TLDebug::Print( String, (const char*)__FUNCTION__ ) //#define TLDebug_FlushBuffer() TLDebug::FlushBuffer() #endif #if defined(_DEBUG) && defined(DEBUG_CHECK_INDEXES) #define TLDebug_CheckIndex(Index,Max) TLDebug::CheckIndex( Index, Max, (const char*)__FUNCTION__ ) #define TLDebug_CheckInRange(Value,Min,Max) TLDebug::CheckInRange( Value, Min, Max, (const char*)__FUNCTION__ ) #else #define TLDebug_CheckIndex(Index,Max) TRUE // in realease just continue, assume index/value is fine #define TLDebug_CheckInRange(Value,Min,Max) TRUE // in realease just continue, assume index/value is fine #endif #if defined(_DEBUG) && defined(DEBUG_CHECK_VALUES) #define TLDebug_CheckFloat(Value) TLDebug::CheckFloatType( Value, (const char*)__FUNCTION__ ) #else #define TLDebug_CheckFloat(Value) TRUE // in realease just continue, assume index/value is fine #endif // forward declaration class TString; namespace TLMaths { class TMatrix; class TQuaternion; } namespace TLDebug { namespace Platform { void PrintToBuffer(const TString& String); // platform specific debug output - buffered Bool Break(const TString& String); // return FALSE to stop app, TRUE and will attempt to continue void FlushBuffer(); } extern Bool g_IsEnabled; // gr: require a global Debug-is-enabled flag as the use of _DEBUG cannot garuntee the same results project to project if using a mix of release and debug extern Bool g_IsBreaking; // stops recursive debug break calls FORCEINLINE Bool IsEnabled() { return g_IsEnabled; } FORCEINLINE Bool IsBreaking() { return g_IsBreaking; } // check this if function callbacks or threads etc and dont do anything! void GetLastBreak(TString& String); // get our last break position appended to this string void SetLastBreak(const char* pSourceFunction); // note last break place in the code Bool Break(const TString& String,const char* pSourceFunction); // halt! return TRUE to ignore the error and continue Bool Break(const char* String,const char* pSourceFunction); // Break for where we extern the use of break and can't include strings FORCEINLINE Bool Break(const TString& String) { return Break( String, NULL ); } void Print(const TString& String,const char* pSourceFunction); // print to console FORCEINLINE void Print(const TString& String) { Print( String, NULL ); } FORCEINLINE Bool NoBreak() { return false; } FORCEINLINE void FlushBuffer() { Platform::FlushBuffer(); } FORCEINLINE Bool CheckIndex(s32 Index,u32 Max,const char* pSourceFunction); // check & assert if index is out of bounds. Max is NOT inclusive... Min <= N < Max FORCEINLINE Bool CheckIndex(s32 Index,u32 Max) { return CheckIndex( Index, Max, NULL ); } FORCEINLINE Bool CheckInRange(s32 Value,s32 Min,u32 Max,const char* pSourceFunction); // check & assert if range is out of bounds. Max IS inclusive... Min <= N <= Max FORCEINLINE Bool CheckInRange(s32 Value,s32 Min,u32 Max) { return CheckInRange( Value, Min, Max, NULL ); } // todo: replace the specialisations for a generic template function and specialise it in the class-specific places and leave the basic float check here Bool CheckFloat(const float& Value,const char* pSourceFunction); // check float is valid Bool CheckFloat(const TLMaths::TMatrix& Value,const char* pSourceFunction); // check float is valid Bool CheckFloat(const TLMaths::TQuaternion& Value,const char* pSourceFunction); // check float is valid template<typename TYPE> Bool CheckFloatType(const TYPE& Value,const char* pSourceFunction); template<> FORCEINLINE Bool CheckFloatType(const float& Value,const char* pSourceFunction) { return CheckFloat( Value, pSourceFunction ); } template<> FORCEINLINE Bool CheckFloatType(const TLMaths::TMatrix& Value,const char* pSourceFunction) { return CheckFloat( Value, pSourceFunction ); } template<> FORCEINLINE Bool CheckFloatType(const TLMaths::TQuaternion& Value,const char* pSourceFunction) { return CheckFloat( Value, pSourceFunction ); } //private: Bool DoCheckIndexBreak(int Index,int Max,const char* pSourceFunction); Bool DoCheckRangeBreak(int Value,int Min,int Max,const char* pSourceFunction); } //------------------------------------------------------- // check a generic float type //------------------------------------------------------- template<typename TYPE> Bool TLDebug::CheckFloatType(const TYPE& Value,const char* pSourceFunction) { if ( !IsEnabled() ) return TRUE; for ( u32 i=0; i<Value.GetSize(); i++ ) { if ( !CheckFloat( Value[i], pSourceFunction ) ) return FALSE; } return TRUE; } //------------------------------------------------------- // check & assert if index is out of bounds. Max is NOT inclusive... Min <= N < Max //------------------------------------------------------- FORCEINLINE Bool TLDebug::CheckIndex(s32 Index,u32 Max,const char* pSourceFunction) { // don't let max go negative in the range check if ( Max == 0 ) return DoCheckRangeBreak( Index, 0, Max, pSourceFunction ); // range for an index is 0..Max-1 return CheckInRange( Index, 0, Max-1, pSourceFunction ); } //------------------------------------------------------- // check & assert if value is out of range. Max IS inclusive... Min <= N <= Max // todo: handle a negative max //------------------------------------------------------- FORCEINLINE Bool TLDebug::CheckInRange(s32 Value,s32 Min,u32 Max,const char* pSourceFunction) { if ( !IsEnabled() ) return true; // check params are correct if ( Min > 0 && Max < (u32)Min ) { //TDebugString Debug_String; //Debug_String << "Min/Max params are incorrect; " << Min << " <= " << Max; //TLDebug_Break( Debug_String ); Break("Min/Max params are incorrect; Min <= Max", __FUNCTION__); return false; } // watch out for signed values! comparing Value as u32 when negative fails against max! if ( Min <= Value && ( Value>0 ? (u32)Value <= Max : true ) ) return true; return DoCheckRangeBreak( Value, Min, Max, pSourceFunction ); }
[ [ [ 1, 37 ], [ 39, 43 ], [ 45, 45 ], [ 50, 70 ], [ 72, 89 ], [ 92, 96 ], [ 98, 130 ], [ 133, 133 ], [ 135, 135 ], [ 137, 139 ], [ 144, 144 ], [ 146, 190 ], [ 192, 192 ], [ 196, 196 ], [ 199, 203 ], [ 205, 205 ], [ 207, 208 ], [ 210, 210 ], [ 220, 220 ], [ 224, 224 ], [ 226, 226 ] ], [ [ 38, 38 ], [ 44, 44 ], [ 46, 49 ], [ 71, 71 ], [ 90, 91 ], [ 97, 97 ], [ 131, 132 ], [ 134, 134 ], [ 136, 136 ], [ 140, 143 ], [ 145, 145 ], [ 191, 191 ], [ 193, 195 ], [ 197, 198 ], [ 204, 204 ], [ 206, 206 ], [ 209, 209 ], [ 211, 219 ], [ 221, 223 ], [ 225, 225 ] ] ]
dfc5c48bab1cd7c7f194dbfff1c42336b0c36af0
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleEmitters/ParticleUniverseMeshSurfaceEmitter.h
882750884b1311d3bfd83826c9e2034988f9c5bf
[]
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
WINDOWS-1258
C++
false
false
7,776
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_MESH_SURFACE_EMITTER_H__ #define __PU_MESH_SURFACE_EMITTER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseSystem.h" #include "ParticleUniverseEmitter.h" namespace ParticleUniverse { /** Definition of a Triangle */ class Triangle { public: /** The struct is used to return both the position and the normal */ struct PositionAndNormal { Ogre::Vector3 position; Ogre::Vector3 normal; }; /** Public attributes **/ Ogre::Real squareSurface; Ogre::Vector3 surfaceNormal; // Normal of triangle v1-v2-v3 Ogre::Vector3 v1; // Vertex v1 Ogre::Vector3 v2; // Vertex v2 Ogre::Vector3 v3; // Vertex v3 Ogre::Vector3 vn1; // Normal of vertex v1 Ogre::Vector3 vn2; // Normal of vertex v2 Ogre::Vector3 vn3; // Normal of vertex v3 Ogre::Vector3 en1; // Normal of edge v1-v2 Ogre::Vector3 en2; // Normal of edge v2-v3 Ogre::Vector3 en3; // Normal of edge v3-v1 /** Constructor **/ Triangle(void){}; /** Calculate the (square) surface of the triangle **/ void calculateSquareSurface (void); /** Calculate the surface normal of the triangle **/ void calculateSurfaceNormal (void); /** Calculate the edge normals of the 3 edges **/ void calculateEdgeNormals (void); /** Determine a random position on this triangle **/ const Ogre::Vector3 getRandomTrianglePosition (void); /** Determine a random position including its normal on a one of the edges **/ const PositionAndNormal getRandomEdgePositionAndNormal (void); /** Determine a random vertex including its normal of this triangle **/ const PositionAndNormal getRandomVertexAndNormal (void); }; /** Comparer used for sorting vector in ascending order */ struct SortAscending { bool operator() (const Triangle& a, const Triangle& b) { return a.squareSurface < b.squareSurface; } }; /** Comparer used for sorting vector in descending order */ struct SortDescending { bool operator() (const Triangle& a, const Triangle& b) { return a.squareSurface > b.squareSurface; } }; /** Define a template class for a vector of triangles. */ typedef std::vector<Triangle> Triangles; /** Class that constructs mesh information of a given mesh name @remarks */ class MeshInfo { public: /** Defining several methods to emit particles on the mesh surface @remarks Sometimes the difference is not always visible, for example if the mesh contains triangles with more or less the same size. Only in case a mesh contains both small and large triangles the difference between the various distribution methods is more obvious. */ enum MeshSurfaceDistribution { MSD_HOMOGENEOUS, // Distribute particles homogeneous (random) on the mesh surface MSD_HETEROGENEOUS_1, // Distribute more particles on the smaller faces MSD_HETEROGENEOUS_2, // Same as above, but now more particles are emitting from the larger faces MSD_VERTEX, // Particles only emit from the vertices MSD_EDGE // Particles emit random on the edges }; /** Constructor **/ MeshInfo (const Ogre::String& meshName, const MeshSurfaceDistribution distribution = MSD_HOMOGENEOUS, const Ogre::Quaternion& orientation = Ogre::Quaternion::IDENTITY, const Ogre::Vector3& scale = Ogre::Vector3::ZERO); /** Destructor **/ ~MeshInfo (void); /** Generate a random number. The ´high´ argument determines that numbers are returned between [0..high] **/ Ogre::Real getGaussianRandom (Ogre::Real high, Ogre::Real cutoff = 4); /** Retrieve vertex info **/ void getMeshInformation(Ogre::MeshPtr mesh, const Ogre::Vector3& position = Ogre::Vector3::ZERO, const Ogre::Quaternion& orient = Ogre::Quaternion::IDENTITY, const Ogre::Vector3& scale = Ogre::Vector3::UNIT_SCALE); /** Get a triangle based on the index. */ const Triangle& getTriangle (size_t triangleIndex); /** Get a random triangle (index) from the mesh. */ const size_t getRandomTriangleIndex (void); /** Returns both a random point on a given triangle and its normal vector. How the random point and the normal are determined depends on the distribution type. **/ const Triangle::PositionAndNormal getRandomPositionAndNormal (const size_t triangleIndex); protected: Triangles _triangles; MeshSurfaceDistribution mDistribution; }; /** The MeshSurfaceEmitter is a ParticleEmitter that emits particles on the surface of a mesh. @remarks There are several ways of emitting it on the surface, from the vertices, edges and faces of a mesh. It is also possible to define whether more particles emit on larger faces. */ class _ParticleUniverseExport MeshSurfaceEmitter : public ParticleEmitter { public: MeshSurfaceEmitter(void); virtual ~MeshSurfaceEmitter(void); /** Returns the mesh name. */ const Ogre::String& getMeshName(void) const; /** Sets the mesh name. */ void setMeshName(const Ogre::String& meshName, bool doBuild = true); /** Returns true if normals are used for the particle direction. */ bool useNormals (void) const; /** Set indication whether normals are used for the particle direction. */ void setUseNormals (bool useNormals); /** Returns the type op distribution. @remarks There are several ways to emit particles on the surface of a mesh. This attribute indicates the type of distrubution on the surface. */ const MeshInfo::MeshSurfaceDistribution getDistribution (void) const; /** Set the type of particle distribution on the surface of a mesh. */ void setDistribution(MeshInfo::MeshSurfaceDistribution distribution); /** Returns the scale of the mesh. */ const Ogre::Vector3& getScale (void); /** Set the scale of the mesh. @remarks This options makes it possible to scale the mesh independently from the particle system scale as a whole. */ void setScale (const Ogre::Vector3& scale); /** Build all the data needed to generate the particles. */ void build(void); /** Build the data if the mesh name has been set. */ virtual void _prepare(ParticleTechnique* particleTechnique); /** Determine a particle position on the mesh surface. */ virtual void _initParticlePosition(Particle* particle); /** Determine the particle direction. */ virtual void _initParticleDirection(Particle* particle); /** */ virtual void copyAttributesTo (ParticleEmitter* emitter); protected: Ogre::String mMeshName; Ogre::Quaternion mOrientation; Ogre::Vector3 mScale; MeshInfo::MeshSurfaceDistribution mDistribution; MeshInfo* mMeshInfo; size_t mTriangleIndex; bool mDirectionSet; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 233 ] ] ]
9cdcd6d0db87e7d0d4d9f2ef646be513c92547f7
7acbb1c1941bd6edae0a4217eb5d3513929324c0
/GLibrary-CPP/sources/GISocketServer.cpp
260196c73bc54ab8009825635e1b0e1697db8436
[]
no_license
hungconcon/geofreylibrary
a5bfc96e0602298b5a7b53d4afe7395a993498f1
3abf3e1c31a245a79fa26b4bcf2e6e86fa258e4d
refs/heads/master
2021-01-10T10:11:51.535513
2009-11-30T15:29:34
2009-11-30T15:29:34
46,771,895
1
1
null
null
null
null
UTF-8
C++
false
false
172
cpp
#include "GISocketServer.h" GString GISocketServer::GetIp(GISocketServer *Socket) { if (Socket) return (Socket->GetIp(Socket->GetSocket())); return (""); }
[ "mvoirgard@34e8d5ee-a372-11de-889f-a79cef5dd62c" ]
[ [ [ 1, 9 ] ] ]
2c0468cb9c1e7415c26d901f39317a165ee0c4e5
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestlist/src/bctestlistformatbasecase.cpp
6e72c5321465041353b435e079bf013d6da2b766
[]
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
16,064
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: test case for CEikFormattedCellListBox * */ #include <w32std.h> #include <eikenv.h> #include <aknlists.h> #include <barsread.h> #include <akndef.h> #include <aknsconstants.h> #include <eiktxlbm.h> #include <eikfrlbd.h> #include "bctestlistcolumnbasecase.h" #include "bctestlistformatbasecase.h" #include "bctestlistcontainer.h" #include "bctestlist.hrh" #include <bctestlist.rsg> #include <bctestlist.mbg> _LIT( KFormatBaseCreate, "Create CEikFormattedCellListBox" ); _LIT( KFormatTest1, "CEikFormattedCellListBox::UseLogicalToVisualConversion" ); _LIT( KFormatTest2, "CEikFormattedCellListBox::FocusChanged" ); _LIT( KFormatTest3, "CEikFormattedCellListBox::GetColorUseListL" ); _LIT( KFormatTest4, "CEikFormattedCellListBox::HandleResourceChange" ); _LIT( KFormatItemDrawerTest1, "CFormattedCellListBoxItemDrawer::ClearAllPropertiesL" ); _LIT( KFormatItemDrawerTest2, "CFormattedCellListBoxItemDrawer::SetPropertiesL" ); _LIT( KFormatItemDrawerTest3, "CFormattedCellListBoxItemDrawer::ItemWidthInPixels" ); _LIT( KFormatItemDrawerTest4, "CFormattedCellListBoxItemDrawer::DrawItemMark" ); _LIT( KFormateDataTest1, "CFormattedCellListBoxData::SetSkinEnabledL" ); _LIT( KFormateDataTest2, "CFormattedCellListBoxData::SetSkinHighlightFrame" ); _LIT( KFormateDataTest3, "CFormattedCellListBoxData::SetSkinPopupFrame" ); _LIT( KFormateDataTest4, "CFormattedCellListBoxData::SetSkinPopupFramePosition" ); _LIT( KFormateDataTest5, "CFormattedCellListBoxData::UseLogicalToVisualConversion" ); _LIT( KFormateDataTest6, "CFormattedCellListBoxData::SetRespectFocus" ); _LIT( KFormateDataTest7, "CFormattedCellListBoxData::EnableMarqueeL" ); _LIT( KFormateDataTest8, "CFormattedCellListBoxData::SetSubCellFontForRowL" ); _LIT( KFormateDataTest9, "CFormattedCellListBoxData::SetDrawBackground" ); _LIT( KFormateDataTest10, "CFormattedCellListBoxData::SetMarqueeParams" ); _LIT( KFormateDataTest11, "CFormattedCellListBoxData::SetSubcellUnderlined" ); _LIT( KFormateDataTest12, "CFormattedCellListBoxData::ConstructLD" ); _LIT( KFormateDataTest13, "CFormattedCellListBoxData::HighlightAnim" ); _LIT( KFormateDataTest14, "CFormattedCellListBoxData::SetHighlightAnimBackgroundDrawer" ); _LIT( KFormateDataTest15, "CFormattedCellListBoxData::AboutToDrawHighlightAnim" ); _LIT( KFormateDataTest16, "CFormGraphicListBoxData::NewL" ); _LIT( KFormateDataTest17, "CFormGraphicListBoxData::Draw" ); _LIT( KFormateDataTest18, "CPopupFormattedListBoxData::NewL" ); _LIT( KFormateDataTest19, "CFormGraphicListBoxData::Draw" ); _LIT( KFormatDataTestText, "Test text for draw" ); // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // Symbian 2nd static Constructor // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase* CBCTestListFormatBaseCase::NewL( CBCTestListContainer* aContainer, CEikonEnv* aEikEnv ) { CBCTestListFormatBaseCase* self = new( ELeave ) CBCTestListFormatBaseCase( aContainer, aEikEnv ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } // --------------------------------------------------------------------------- // C++ default constructor // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::CBCTestListFormatBaseCase( CBCTestListContainer* aContainer, CEikonEnv* aEikEnv ) : CBCTestListBaseCase( aContainer, aEikEnv ) { } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::~CBCTestListFormatBaseCase() { } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::ConstructL() { BuildScriptL(); } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::BuildScriptL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::BuildScriptL() { for ( TInt i=0; i <= EBCTestCmdOutline50 - EBCTestCmdOutline48; i++ ) { AddTestL( LeftCBA, REP( Down, 7 ), KeyOK, TEND ); AddTestL( REP( Down, i ), KeyOK, TEND ); } } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::RunL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::RunL( TInt aCmd ) { if ( aCmd < EBCTestCmdOutline48 || aCmd > EBCTestCmdOutline50 ) { return; } ReleaseCase(); PrepareCaseL(); switch ( aCmd ) { case EBCTestCmdOutline48: TestFormatListL(); break; case EBCTestCmdOutline49: TestFormatItemDrawerL(); break; case EBCTestCmdOutline50: TestFormatListDataL(); break; default: break; } } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::PrepareCaseL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::PrepareCaseL() { iListBox = new( ELeave ) CAknDoubleStyle2ListBox(); AssertNotNullL( iListBox, KFormatBaseCreate ); CDesCArray* textArray = iEikEnv->ReadDesCArrayResourceL( R_BCTESTLIST_DOUBLE2_ITEM ); if ( iListBox ) { if ( textArray ) { SetListBoxFromInnerDescriptionL( iListBox, EAknListBoxSelectionList, textArray ); } SetGraphicIconL( iListBox ); iContainer->SetControl( iListBox ); } } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::ReleaseCaseL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::ReleaseCase() { iContainer->ResetControl(); iListBox = NULL; } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::TestFormatListL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::TestFormatListL() { iListBox->UseLogicalToVisualConversion( ETrue ); iListBox->UseLogicalToVisualConversion( EFalse ); AssertTrueL( ETrue, KFormatTest1 ); iListBox->FocusChanged( EDrawNow ); iListBox->FocusChanged( ENoDrawNow ); AssertTrueL( ETrue, KFormatTest2 ); TInt granularity = 4; CArrayFixFlat<TCoeColorUse>* colorUseList = new( ELeave ) CArrayFixFlat<TCoeColorUse>( granularity ); CleanupStack::PushL( colorUseList ); iListBox->GetColorUseListL( *colorUseList ); AssertTrueL( ( colorUseList->Count() > 0 ), KFormatTest3 ); colorUseList->Reset(); CleanupStack::PopAndDestroy( colorUseList ); iListBox->HandleResourceChange( KAknsMessageSkinChange ); iListBox->HandleResourceChange( KEikDynamicLayoutVariantSwitch ); AssertTrueL( ETrue, KFormatTest4 ); } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::TestFormatItemDrawerL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::TestFormatItemDrawerL() { CFormattedCellListBoxItemDrawer* itemDrawer = iListBox->ItemDrawer(); itemDrawer->ClearAllPropertiesL(); AssertTrueL( ETrue, KFormatItemDrawerTest1 ); TListItemProperties itemProp; itemProp.SetBold( ETrue ); itemProp.SetItalics( ETrue ); itemProp.SetUnderlined( ETrue ); itemProp.SetDimmed( ETrue ); itemProp.SetColor( KRgbGray ); itemProp.SetSeparatorAfter( ETrue ); itemDrawer->SetPropertiesL( 0, itemProp ); AssertTrueL( ETrue, KFormatItemDrawerTest2 ); TInt width = itemDrawer->ItemWidthInPixels( 0 ); AssertTrueL( ETrue, KFormatItemDrawerTest3 ); TPoint pt( 0, 0 ); itemDrawer->DrawItemMark( ETrue, EFalse, pt ); AssertTrueL( ETrue, KFormatItemDrawerTest4 ); } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::TestFormatListDataL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::TestFormatListDataL() { CFormattedCellListBoxData* data = iListBox->ItemDrawer()->FormattedCellData(); data->SetSkinEnabledL( ETrue ); TBool skin = data->SkinEnabled(); AssertTrueL( skin, KFormateDataTest1 ); TAknsItemID id; id.Set( KAknsIIDDefault ); data->SetSkinHighlightFrame( &id, &id ); AssertTrueL( ETrue, KFormateDataTest2 ); data->SetSkinPopupFrame( &id, &id ); AssertTrueL( ETrue, KFormateDataTest3 ); TRect rect = iContainer->Rect(); TRect innerRect( rect.iTl.iX + 2, rect.iTl.iY + 2, rect.iBr.iX - 2, rect.iBr.iY - 2 ); data->SetSkinPopupFramePosition( rect, innerRect ); AssertTrueL( ETrue, KFormateDataTest4 ); data->UseLogicalToVisualConversion( ETrue ); AssertTrueL( ETrue, KFormateDataTest5 ); data->SetRespectFocus( ETrue ); AssertTrueL( ETrue, KFormateDataTest6 ); data->EnableMarqueeL( ETrue ); AssertTrueL( ETrue, KFormateDataTest7 ); data->SetSubCellFontForRowL( 0, 0, iEikEnv->NormalFont() ); AssertTrueL( ETrue, KFormateDataTest8 ); data->SetDrawBackground( ETrue ); AssertTrueL( ETrue, KFormateDataTest9 ); data->SetMarqueeParams( 1, 6, 1000000, 100000 ); AssertTrueL( ETrue, KFormateDataTest10 ); TBitFlags32 flags; data->SetSubcellUnderlined( flags ); AssertTrueL( ETrue, KFormateDataTest11 ); #ifdef __S60_32__ iListBox->SetCurrentItemIndex( 2 );//item 3; TUint32 tInt = data->CurrentItemTextWasClipped(); _LIT( KColumnDataTest35, "Test CurrentItemTextWasClipped() at short item." ); AssertTrueL( ETrue, KColumnDataTest35 ); iListBox->SetCurrentItemIndex( 3 );//item 4; tInt = data->CurrentItemTextWasClipped(); _LIT( KColumnDataTest36, "Test CurrentItemTextWasClipped() at long item." ); AssertTrueL( ETrue, KColumnDataTest36 ); iListBox->DrawNow(); #endif //__S60_32__ CBCTestListFormatData* bcData = new( ELeave ) CBCTestListFormatData(); CleanupStack::PushL( bcData ); bcData->TestConstructLD( id ); AssertTrueL( ETrue, KFormateDataTest12 ); CleanupStack::PopAndDestroy( bcData ); iContainer->ActivateGc(); CWindowGc& gc = iContainer->SystemGc(); DrawCaseL( gc ); iContainer->DeactivateGc(); } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::DrawCaseL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::DrawCaseL( CWindowGc& aGc ) { CFormattedCellListBoxData* data = iListBox->ItemDrawer()->FormattedCellData(); data->HighlightAnim(); AssertTrueL( ETrue, KFormateDataTest13 ); data->SetHighlightAnimBackgroundDrawer( &iDrawer ); AssertTrueL( ETrue, KFormateDataTest14 ); data->AboutToDrawHighlightAnim(); AssertTrueL( ETrue, KFormateDataTest15 ); TListItemProperties itemProp; itemProp.SetBold( ETrue ); itemProp.SetItalics( ETrue ); itemProp.SetUnderlined( ETrue ); itemProp.SetDimmed( ETrue ); itemProp.SetColor( KRgbGray ); itemProp.SetSeparatorAfter( ETrue ); TSize size = iListBox->ItemDrawer()->ItemCellSize(); TRect rect( iContainer->Rect().iTl.iX, iContainer->Rect().iTl.iY, iContainer->Rect().iTl.iX + size.iWidth, iContainer->Rect().iTl.iY + size.iHeight ); const CFormattedCellListBoxData::TColors& colors = data->SubCellColors( 0 ); TPtrC text( KFormatDataTestText ); CFormGraphicListBoxData* graphicData = CFormGraphicListBoxData::NewL(); CleanupStack::PushL( graphicData ); AssertNotNullL( graphicData, KFormateDataTest16 ); graphicData->SetControl( iListBox ); graphicData->Draw( itemProp, aGc, &text, rect, ETrue, colors ); AssertTrueL( ETrue, KFormateDataTest17 ); CleanupStack::PopAndDestroy( graphicData ); CPopupFormattedListBoxData* popupData = CPopupFormattedListBoxData::NewL(); CleanupStack::PushL( popupData ); AssertNotNullL( popupData, KFormateDataTest18 ); popupData->SetControl( iListBox ); popupData->Draw( itemProp, aGc, &text, rect, ETrue, colors ); AssertTrueL( ETrue, KFormateDataTest19 ); CleanupStack::PopAndDestroy( popupData ); } // --------------------------------------------------------------------------- // CBCTestListFormatBaseCase::GraphicIconL // --------------------------------------------------------------------------- // void CBCTestListFormatBaseCase::GraphicIconL( CArrayPtr<CGulIcon>* aIcons ) { if ( aIcons ) { CreateIconAndAddToArrayL( aIcons, KBCTestListMifFileName, EMbmBctestlistQgn_indi_marked_add, EMbmBctestlistQgn_indi_marked_add_mask ); CreateIconAndAddToArrayL( aIcons, KBCTestListMbmFileName, EMbmBctestlistGolgo3, EMbmBctestlistGolgo3_mask ); } } // ======== MEMBER FUNCTIONS ======== // CBCTestListFormatData // --------------------------------------------------------------------------- // Constructor // --------------------------------------------------------------------------- // CBCTestListFormatData::CBCTestListFormatData() { } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestListFormatData::~CBCTestListFormatData() { } // --------------------------------------------------------------------------- // CBCTestListFormatData::ConstructLD // --------------------------------------------------------------------------- // void CBCTestListFormatData::TestConstructLD( const TAknsItemID& aAnimationIID ) { CFormattedCellListBoxData::ConstructLD( aAnimationIID ); } // ======== MEMBER FUNCTIONS ======== // TBCTestListFormatAnimBgDrawer // --------------------------------------------------------------------------- // TBCTestListFormatAnimBgDrawer::DrawHighlightAnimBackground // --------------------------------------------------------------------------- // TBool TBCTestListFormatAnimBgDrawer:: DrawHighlightAnimBackground( CFbsBitGc& ) const { return ETrue; }
[ "none@none" ]
[ [ [ 1, 431 ] ] ]
39683e65a0f98f814b14d925b0463ebd13793eac
3d560d0b4772580943946c78e2612ac0589c7958
/article_code/02.cpp
29fe84e96d6d455b0a98e7f419f8d9897036becb
[]
no_license
black-square/id2type-cast
b792f9d9c00afebba856494db58a4151dcfd2b33
1a313b55c1dac2ea388c943fa4bf326eaa1957c3
refs/heads/master
2020-05-30T13:03:58.304192
2011-11-01T09:46:58
2011-11-01T09:46:58
32,418,189
0
0
null
null
null
null
UTF-8
C++
false
false
1,616
cpp
#include <iostream> #include <string> #include <vector> #include <iterator> #include <complex> #include <algorithm> #include <functional> struct IStatistics { //... virtual void append( double v ) = 0; }; struct IData { //... virtual void processStatistics( IStatistics *pStat ) = 0; }; class RealData: public IData { public: RealData( double v ): val(v) {} void processStatistics( IStatistics *pStat ) { pStat->append(val); } //... private: double val; }; class ComplexData: public IData { public: ComplexData( double r, double im ): val(r, im) {} void processStatistics( IStatistics *pStat ) { pStat->append(val.real()); } //... private: std::complex<double> val; }; class ConcreteStat: public IStatistics { public: void append( double v ) { std::cout << ">> " << v << std::endl; } //... }; typedef std::vector<IData *> TDataContainer; typedef std::vector<IData *>::const_iterator TDataConstIterator; void calcStat( const TDataContainer &vecData, IStatistics *pStat ) { for( TDataConstIterator iter = vecData.begin(); iter != vecData.end(); ++iter ) (*iter)->processStatistics(pStat); std::cout << "======= " << std::endl; } int main() { TDataContainer vecData; IStatistics *pStat = new ConcreteStat; vecData.push_back( new RealData(1) ); vecData.push_back( new ComplexData(2, 3) ); vecData.push_back( new RealData(4) ); calcStat( vecData, pStat ); //... return 0; }
[ [ [ 1, 76 ] ] ]
c677f45915da6e7eaaf94138ede3d82625816f41
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Script/ExposePropertyContainer.cpp
1a3734cd027371780eb5018c54ec7cad558190a2
[]
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
5,538
cpp
#include "precomp.h" #include "ExposePropertyContainer.h" #include "ExposeIProperty.h" #include "ExposeIEntity.h" #include "ScriptMgr.h" #include <Core/CoreMgr.h> #include <Event/IEventManager.h> #include <Entity/IEntity.h> #include <Event/Event.h> using namespace Engine; using namespace LuaPlus; ExposePropertyContainer::ExposePropertyContainer(CoreMgr *coreMgr, ExposeIEntity *exposedEntity) : engineEvents(coreMgr->getEventMgr()) { this->coreMgr = coreMgr; this->exposedEntity = exposedEntity; init(); } ExposePropertyContainer::~ExposePropertyContainer() { for(unsigned int i = 0; i < exposedProperties.size(); i++) { ExposeIProperty *exposedProp = exposedProperties[i]; delete exposedProp; exposedProp = NULL; } exposedProperties.clear(); lProperties.AssignNil(coreMgr->getScriptMgr()->GetGlobalState()->Get()); } void ExposePropertyContainer::init() { LuaObject globals = (*coreMgr->getScriptMgr()->GetGlobalState())->GetGlobals(); if(exposedEntity) { lProperties = exposedEntity->getLEntity().CreateTable("Properties"); IEntity *entity = exposedEntity->getEntity(); std::map<CL_String, IProperty*> &properties = entity->GetProperties(); std::map<CL_String, IProperty*>::iterator propIt = properties.begin(); for(; propIt != properties.end(); ++propIt) { ExposeIProperty *exposedProp = new ExposeIProperty(coreMgr, exposedEntity, this, propIt->second); exposedProperties.push_back(exposedProp); } LuaObject lMeta = exposedEntity->getLMeta(); lMeta.RegisterDirect("AddProperty", *this, &ExposePropertyContainer::AddProperty); lMeta.RegisterDirect("HasProperty", *this, &ExposePropertyContainer::HasProperty); } engineEvents.Connect("PropertyAdded", this, &ExposePropertyContainer::OnPropertyAdded); } void ExposePropertyContainer::AddProperty(LuaObject self, LuaObject lName, LuaObject defValue) { if(!self.IsTable()) { CL_String msg = cl_format("Failed to add property, because the type of self was %1 when expecting Table", self.TypeName()); throw CL_Exception(msg); } if(!lName.IsString()) { CL_String msg = cl_format("Failed to add property, because the type of name was %1 when expecting String", lName.TypeName()); throw CL_Exception(msg); } CL_String name = lName.ToString(); IEntity *entity = NULL; if(exposedEntity) entity = exposedEntity->getEntity(); if(defValue.IsBoolean()) { bool val = defValue.GetBoolean(); if(entity) entity->AddProperty<bool>(name, val); } else if(defValue.IsNumber()) { float val = (float)defValue.ToNumber(); if(entity) entity->AddProperty<float>(name, val); } else if(defValue.IsInteger()) { int val = defValue.ToInteger(); if(entity) entity->AddProperty<int>(name, val); } else if(defValue.IsString()) { CL_String val = defValue.ToString(); if(entity) entity->AddProperty<CL_String>(name, val); } else if(defValue.IsTable()) { bool hasX = false; bool hasY = false; bool hasZ = false; bool hasW = false; LuaObject xObj = defValue.GetByName("x"); if(xObj.IsNumber()) hasX = true; LuaObject yObj = defValue.GetByName("y"); if(yObj.IsNumber()) hasY = true; LuaObject zObj = defValue.GetByName("z"); if(zObj.IsNumber()) hasZ = true; LuaObject wObj = defValue.GetByName("w"); if(wObj.IsNumber()) hasW = true; if(hasX && hasY && hasZ && hasW) { CL_Vec4f val = CL_Vec4f((float)xObj.ToNumber(),(float)yObj.ToNumber(),(float)zObj.ToNumber(),(float)wObj.ToNumber()); if(entity) entity->AddProperty<CL_Vec4f>(name, val); } else if(hasX && hasY && hasZ) { CL_Vec3f val = CL_Vec3f((float)xObj.ToNumber(),(float)yObj.ToNumber(),(float)zObj.ToNumber()); if(entity) entity->AddProperty<CL_Vec3f>(name, val); } else if(hasX && hasY) { CL_Vec2f val = CL_Vec2f((float)xObj.ToNumber(),(float)yObj.ToNumber()); if(entity) entity->AddProperty<CL_Vec2f>(name, val); } } return; } LuaPlus::LuaObject ExposePropertyContainer::HasProperty(LuaPlus::LuaObject self, LuaPlus::LuaObject name) { if(!self.IsTable()) { CL_String msg = cl_format("Self was not a table (it's a %1)", self.TypeName()); throw CL_Exception(msg); } if(!name.IsString()) { CL_String msg = cl_format("Name was not a string (it's a %1)", name.TypeName()); throw CL_Exception(msg); } bool retVal = false; if(exposedEntity) retVal = exposedEntity->getEntity()->HasProperty(name.ToString()); LuaObject lRetVal; lRetVal.AssignBoolean(coreMgr->getScriptMgr()->GetGlobalState()->Get(), retVal); return lRetVal; } void ExposePropertyContainer::add(const CL_String &name, IProperty *prop, ExposeIProperty *exposedProp) { if(prop == NULL) { CL_String msg = cl_format("Failed to add property %1, because no property was returned", name); throw CL_Exception(msg); } if(exposedEntity) { exposedProp = new ExposeIProperty(coreMgr, exposedEntity, this, prop); exposedProperties.push_back(exposedProp); } } void ExposePropertyContainer::OnPropertyAdded(const Events::Event &event) { if(event.getArgument(1).IsEntity() && exposedEntity) { IEntity *entity = event.getArgument(1).ToEntity(); if(entity->getId() != exposedEntity->getEntity()->getId()) return; } IProperty *prop = event.getArgument(0).ToProperty(); ExposeIProperty *exposedProp = NULL; add(prop->GetName(), prop, exposedProp); }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 200 ] ] ]
fc222101cb41164d7b23546b26ea6385aae4de6f
e54a55ca1039abc3120b8a6e6eb16a439c934858
/src/ofxControlPanel/src/guiXmlValue.h
b01b54eaa9062a72427cb857d189ba14b5795c8f
[]
no_license
pach/ofxControlPanel
75f7594447eb1a06a2cd3394b9ccb035545274c7
497f8414779e8aab0bb7595520a862b08bd085f4
refs/heads/master
2020-02-26T17:12:15.913658
2011-06-01T19:28:57
2011-06-01T19:28:57
1,833,613
0
0
null
null
null
null
UTF-8
C++
false
false
6,672
h
#pragma once class guiValue{ public: guiValue(){ } //------------------------------------------------ void addValue(float val, float _min, float _max){ value.push_back(val); valueI.push_back((int)val); valueB.push_back((bool)val); valueS.push_back(ofToString(val)); min.push_back(_min); max.push_back(_max); pct.push_back( 0.0 ); //update our pct updatePct(value.size()-1); } //------------------------------------------------ void addValue(string val, float _min, float _max){ value.push_back(0); valueI.push_back((int)0); valueB.push_back((bool)0); valueS.push_back(val); min.push_back(0); max.push_back(0); pct.push_back( 0.0 ); //update our pct updatePct(value.size()-1); } //------------------------------------------------ void addValueI(int val, int _min, int _max){ value.push_back((float)val); valueI.push_back(val); valueB.push_back((bool)val); valueS.push_back(ofToString(val)); min.push_back((float)_min); max.push_back((float)_max); pct.push_back( 0.0 ); //update our pct updatePct(value.size()-1); } //------------------------------------------------ void addValueB(bool val){ value.push_back((float)val); valueI.push_back((int)val); valueB.push_back(val); valueS.push_back(ofToString(val)); min.push_back(0); max.push_back(1); pct.push_back( 0.0 ); //update our pct updatePct(value.size()-1); } //------------------------------------------------ void addValueS(string val){ value.push_back((float)0.); valueI.push_back((int)0); valueB.push_back(false); valueS.push_back(val); min.push_back(0); max.push_back(1); pct.push_back( 0.0 ); //update our pct updatePct(value.size()-1); } //------------------------------------------------ bool setValue(float val, int which = 0){ if(which >= 0 && which < value.size() ){ if( max[which] - min[which] == 0 ) return false; //check out bounds if(val < min[which]) val = min[which]; else if(val > max[which]) val = max[which]; value[which] = val; valueI[which] = (int)val; valueB[which] = (bool)val; valueS[which] = ofToString(val); //recalulate our pct updatePct(which); return true; } return false; } //------------------------------------------------ bool setValue(string val, int which = 0){ if(which >= 0 && which < value.size() ){ value[which] = 0; valueI[which] = (int)0; valueB[which] = (bool)0; valueS[which] = val; //recalulate our pct updatePct(which); return true; } return false; } //------------------------------------------------ bool setValueAsPct(float percent, int which = 0){ if(which >= 0 && which < value.size() ){ if( max[which] - min[which] == 0 ) return false; if(percent < 0.0) percent = 0.0; else if(percent > 1.0) percent = 1.0; pct[which] = percent; value[which] = ( pct[which] * ( max[which] - min[which] ) ) + min[which]; valueI[which] = (int)value[which]; valueB[which] = (bool)value[which]; valueS[which] = ofToString(val); return true; } return false; } //------------------------------------------------ float getValueF(int which = 0){ if(which >= 0 && which < value.size() ){ return value[which]; } return 0.0; } //------------------------------------------------ float getValueI(int which = 0){ if(which >= 0 && which < valueI.size() ){ return valueI[which]; } return false; } //------------------------------------------------ float getValueB(int which = 0){ if(which >= 0 && which < valueB.size() ){ return valueB[which]; } return false; } string getValueS(int which = 0){ if(which >= 0 && which < valueS.size() ){ return valueS[which]; } return false; } //------------------------------------------------ float getMin(int which = 0){ if(which >= 0 && which < min.size() ){ return min[which]; } return 0.0; } //------------------------------------------------ float getMax(int which = 0){ if(which >= 0 && which < max.size() ){ return max[which]; } return 0.0; } //------------------------------------------------ float getPct(int which = 0){ if(which >= 0 && which < pct.size() ){ return pct[which]; } return 0.0; } //------------------------------------------------ int getNumValues(){ return value.size(); } protected: //----------------------------------------------- void updatePct(int which){ pct[which] = (value[which] - min[which]) / (max[which] - min[which]); } //-------------- //-------------- vector <float> value; vector <float> valueI; vector <float> valueB; vector <string> valueS; vector <float> min; vector <float> max; vector <float> pct; };
[ [ [ 1, 15 ], [ 17, 24 ], [ 38, 42 ], [ 44, 56 ], [ 58, 65 ], [ 81, 93 ], [ 95, 95 ], [ 97, 103 ], [ 123, 137 ], [ 140, 167 ], [ 175, 216 ], [ 218, 224 ] ], [ [ 16, 16 ], [ 25, 37 ], [ 43, 43 ], [ 57, 57 ], [ 66, 80 ], [ 94, 94 ], [ 96, 96 ], [ 104, 122 ], [ 138, 139 ], [ 168, 174 ], [ 217, 217 ] ] ]
884b17bc7fced1a1bb8f081eb2cb4e5b7bed1b6f
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-04-24/include/wxstruct.h
d692117b2357c87ecde117b254953fb110239c49
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
50,653
h
/***********************************************************/ /* wxstruct.h: */ /* descriptions des principales classes derivees utilisees */ /***********************************************************/ #ifndef WXSTRUCT_H #define WXSTRUCT_H #ifndef eda_global #define eda_global extern #endif #include <wx/socket.h> #include "wx/log.h" #include "wx/config.h" #include <wx/wxhtml.h> #include <wx/laywin.h> #include <wx/snglinst.h> #define INTERNAL_UNIT_TYPE 0 // Internal unit = inch #ifndef EESCHEMA_INTERNAL_UNIT #define EESCHEMA_INTERNAL_UNIT 1000 #endif #ifndef PCB_INTERNAL_UNIT #define PCB_INTERNAL_UNIT 10000 #endif // Option d'affichage des fenetres de dialogue //#define DIALOG_STYLE wxDEFAULT_DIALOG_STYLE|wxFRAME_FLOAT_ON_PARENT|wxSTAY_ON_TOP #define DIALOG_STYLE wxDEFAULT_DIALOG_STYLE|wxFRAME_FLOAT_ON_PARENT #define EDA_DRAW_PANEL wxScrolledWindow class wxMyDialogModalData; /* Forward declarations of classes. */ class WinEDA_DrawPanel; class WinEDA_DrawFrame; #include "base_struct.h" class WinEDA_App; class WinEDA_MsgPanel; class COMMAND; class WinEDA_MainFrame; class BASE_SCREEN; class SCH_SCREEN; class PCB_SCREEN; class WinEDA_SchematicFrame; // Edition des Schemas class WinEDA_LibeditFrame; // Edition des composants class WinEDA_ViewlibFrame; // Visualisation des composants class WinEDA_GerberFrame; // Visualisation des fichiers GERBER class WinEDA_Toolbar; class WinEDA_CvpcbFrame; class WinEDA_PcbFrame; class WinEDA_ModuleEditFrame; class WinEDAChoiceBox; #define WinEDA_MenuBar wxMenuBar #define WinEDA_Menu wxMenu #define WinEDA_MenuItem wxMenuItem // Utilisées mais non definies ici : class LibraryStruct; class EDA_LibComponentStruct; class LibEDA_BaseStruct; class EDA_BaseStruct; class DrawBusEntryStruct; class DrawGlobalLabelStruct; class DrawTextStruct; class EDA_DrawLineStruct; class DrawSheetStruct; class DrawSheetLabelStruct; class EDA_SchComponentStruct; class LibDrawField; class PartTextStruct; class LibDrawPin; class DrawJunctionStruct; class BOARD; class TEXTE_PCB; class MODULE; class TRACK; class SEGZONE; class SEGVIA; class EDGE_ZONE; class D_PAD; class TEXTE_MODULE; class MIREPCB; class DRAWSEGMENT; class COTATION; class EDGE_MODULE; class WinEDA3D_DrawFrame; class PARAM_CFG_BASE; class Ki_PageDescr; enum id_librarytype { LIBRARY_TYPE_EESCHEMA, LIBRARY_TYPE_PCBNEW, LIBRARY_TYPE_DOC }; enum id_drawframe { NOT_INIT_FRAME = 0, SCHEMATIC_FRAME, LIBEDITOR_FRAME, VIEWER_FRAME, PCB_FRAME, MODULE_EDITOR_FRAME, CVPCB_FRAME, CVPCB_DISPLAY_FRAME, GERBER_FRAME, TEXT_EDITOR_FRAME, DISPLAY3D_FRAME, KICAD_MAIN_FRAME }; enum id_toolbar { TOOLBAR_MAIN = 1, // Toolbar horizontal (main) TOOLBAR_TOOL, // Toolbar vertical tools TOOLBAR_OPTION, // Toolbar vertical options TOOLBAR_AUX }; /**********************/ /* Classes pour WXWIN */ /**********************/ #define MSG_PANEL_DEFAULT_HEIGHT ( 28 ) // hauteur de la zone d'affichage des infos en bas d'ecran /**********************************************/ /* Class representing the entire Application */ /**********************************************/ #include "appl_wxstruct.h" /********************************************/ /* classe pour la Fenetre generale de trace */ /********************************************/ class WinEDA_BasicFrame: public wxFrame { public: int m_Ident; // Id Type (pcb, schematic, library..) WinEDA_App * m_Parent; wxPoint m_FramePos; wxSize m_FrameSize; int m_MsgFrameHeight; WinEDA_MenuBar * m_MenuBar; // menu du haut d'ecran WinEDA_Toolbar * m_HToolBar; // Standard horizontal Toolbar bool m_FrameIsActive; wxString m_FrameName; // name used for writting and reading setup // It is "SchematicFrame", "PcbFrame" .... public: // Constructor and destructor WinEDA_BasicFrame( wxWindow * father, int idtype, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_BasicFrame(void); void GetKicadHelp(wxCommandEvent& event); void GetKicadAbout(wxCommandEvent& event); void PrintMsg(const wxString & text); void GetSettings(void); void SaveSettings(void); void SetLanguage(wxCommandEvent& event); void ProcessFontPreferences(int id); wxString GetLastProject(int rang); void SetLastProject(const wxString & FullFileName); void DisplayActivity(int PerCent, const wxString & Text); virtual void ReCreateMenuBar(void); }; /********************************************/ /* classe pour la Fenetre generale de trace */ /********************************************/ class WinEDA_DrawFrame: public WinEDA_BasicFrame { public: WinEDA_DrawPanel * DrawPanel; // surface de dessin WinEDA_MsgPanel * MsgPanel; // Zone d'affichage de caracteristiques WinEDA_Toolbar * m_VToolBar; // Vertical (right side) Toolbar WinEDA_Toolbar * m_AuxVToolBar; // Auxiliary Vertical (right side) Toolbar WinEDA_Toolbar * m_OptionsToolBar; // Options Toolbar (left side) WinEDA_Toolbar * m_AuxiliaryToolBar; // Toolbar auxiliaire (utilisé dans pcbnew) WinEDAChoiceBox * m_SelGridBox; // Dialog box to choose the grid size WinEDAChoiceBox * m_SelZoomBox; // Dialog box to choose the Zoom value int m_ZoomMaxValue; // Max zoom value: Draw min scale is 1/m_ZoomMaxValue BASE_SCREEN * m_CurrentScreen; // SCREEN en cours int m_CurrentCursorShape; // shape for cursor (0 = default cursor) int m_ID_current_state; // Id du bouton actif du tool bar vertical int m_HTOOL_current_state; // Id du bouton actif du tool bar horizontal int m_InternalUnits; // nombre d'unites internes pour 1 pouce // = 1000 pour schema, = 10000 pour PCB int m_UnitType; // Internal Unit type (0 = inch) bool m_Draw_Axes; // TRUE pour avoir les axes dessines bool m_Draw_Grid; // TRUE pour avoir la grille dessinee bool m_Draw_Sheet_Ref; // TRUE pour avoir le cartouche dessiné bool m_Print_Sheet_Ref; // TRUE pour avoir le cartouche imprimé bool m_Draw_Auxiliary_Axe; // TRUE pour avoir les axes auxiliaires dessines wxPoint m_Auxiliary_Axe_Position; /* origine de l'axe auxiliaire (app: dans la generation les fichiers de positionnement des composants) */ public: // Constructor and destructor WinEDA_DrawFrame( wxWindow * father, int idtype, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_DrawFrame(void); BASE_SCREEN * GetScreen(void) { return m_CurrentScreen; } void OnMenuOpen(wxMenuEvent& event); void OnMouseEvent(wxMouseEvent& event); virtual void OnHotKey(wxDC * DC, int hotkey, EDA_BaseStruct * DrawStruct); void AddFontSelectionMenu(wxMenu * main_menu); void ProcessFontPreferences(wxCommandEvent& event); void Affiche_Message(const wxString & message); void EraseMsgBox(void); void Process_PageSettings(wxCommandEvent& event); void SetDrawBgColor(int color_num); virtual void SetToolbars(void); void SetLanguage(wxCommandEvent& event); virtual void ReCreateHToolbar(void) = 0; virtual void ReCreateVToolbar(void) = 0; virtual void ReCreateMenuBar(void); virtual void ReCreateAuxiliaryToolbar(void); void SetToolID(int id, int new_cursor_id, const wxString & title); virtual void OnSelectGrid(wxCommandEvent& event); virtual void OnSelectZoom(wxCommandEvent& event); virtual void GeneralControle(wxDC *DC, wxPoint Mouse); virtual void OnSize(wxSizeEvent& event); void OnEraseBackground(wxEraseEvent& SizeEvent); // void OnChar(wxKeyEvent& event); void SetToolbarBgColor(int color_num); void OnZoom(int zoom_type); void OnGrid(int grid_type); void Recadre_Trace(bool ToMouse); void PutOnGrid(wxPoint * coord); /* corrige la valeur de la coordonnee coord pour etre sur le point de grille le plus proche */ void Zoom_Automatique(bool move_mouse_cursor); /* Affiche le schema au meilleur zoom au meilleur centrage pour le dessin de facon a avoir tout le circuit affiche a l'ecran */ void Window_Zoom(EDA_Rect &Rect); /* Recalcule le zoom et les offsets pour que l'affichage se fasse dans la fenetre de coord x0, y0 a x1, y1 */ virtual int BestZoom(void) = 0; // Retourne le meilleur zoom void ToPrinter(wxCommandEvent& event); void SVG_Print(wxCommandEvent& event); void OnActivate(wxActivateEvent& event); void ReDrawPanel(void); void TraceWorkSheet(wxDC * DC, BASE_SCREEN * screen); void DisplayToolMsg(const wxString msg); void Process_Zoom(wxCommandEvent& event); void Process_Grid(wxCommandEvent& event); virtual void RedrawActiveWindow(wxDC * DC, bool EraseBg) = 0; virtual void Process_Special_Functions(wxCommandEvent& event) = 0; virtual void OnLeftClick(wxDC * DC, const wxPoint& MousePos) = 0; virtual void OnLeftDClick(wxDC * DC, const wxPoint& MousePos); virtual void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu) = 0; virtual void ToolOnRightClick(wxCommandEvent& event); void AdjustScrollBars(void); void Affiche_Status_Box(void); /* Affichage des coord curseur, zoom .. */ void DisplayUnitsMsg(void); /* Gestion generale des operations sur block */ virtual int ReturnBlockCommand(int key); virtual void InitBlockPasteInfos(); virtual bool HandleBlockBegin(wxDC * DC, int cmd_type, const wxPoint & startpos); virtual void HandleBlockPlace(wxDC * DC); virtual int HandleBlockEnd(wxDC * DC); void OnSockRequest(wxSocketEvent &evt); void OnSockRequestServer (wxSocketEvent &evt); }; #define COMMON_EVENTS_DRAWFRAME \ EVT_MOUSEWHEEL(WinEDA_DrawFrame::OnMouseEvent)\ EVT_MENU_OPEN(WinEDA_DrawFrame::OnMenuOpen)\ EVT_ACTIVATE(WinEDA_DrawFrame::OnActivate) /**************************************************************/ /* class WinEDA_BasePcbFrame: classe de base commune */ /* aux classes d'affichage de PCB, et de l'editeur de Modules */ /**************************************************************/ class WinEDA_BasePcbFrame: public WinEDA_DrawFrame { public: BOARD * m_Pcb; bool m_DisplayPadFill; // How show pads bool m_DisplayPadNum; // show pads number int m_DisplayModEdge; // How show module drawings int m_DisplayModText; // How show module texts bool m_DisplayPcbTrackFill; /* FALSE = sketch , TRUE = rempli */ WinEDA3D_DrawFrame * m_Draw3DFrame; public: WinEDA_BasePcbFrame( wxWindow * father, WinEDA_App *parent, int idtype, const wxString &title, const wxPoint& pos, const wxSize& size); ~WinEDA_BasePcbFrame(void); // General virtual void OnCloseWindow(wxCloseEvent & Event) = 0; virtual void Process_Special_Functions(wxCommandEvent& event) = 0; virtual void RedrawActiveWindow(wxDC * DC, bool EraseBg) = 0; virtual void ReCreateHToolbar(void) = 0; virtual void ReCreateVToolbar(void) = 0; virtual void OnLeftClick(wxDC * DC, const wxPoint& MousePos) = 0; virtual void OnLeftDClick(wxDC * DC, const wxPoint& MousePos) = 0; virtual void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu) = 0; virtual void ReCreateMenuBar(void); PCB_SCREEN * GetScreen(void) { return (PCB_SCREEN *) m_CurrentScreen;} int BestZoom(void); // Retourne le meilleur zoom void Show3D_Frame(wxCommandEvent& event); virtual void GeneralControle(wxDC *DC, wxPoint Mouse); // Undo and redo functions public: virtual void SaveCopyInUndoList(void); private: virtual void GetComponentFromUndoList(void); virtual void GetComponentFromRedoList(void); public: // Read/write fonctions: EDA_BaseStruct * ReadDrawSegmentDescr(FILE * File, int * LineNum); int ReadListeSegmentDescr(wxDC * DC, FILE * File, TRACK * PtSegm,int StructType, int * LineNum, int NumSegm); int ReadSetup(FILE * File, int * LineNum); int ReadGeneralDescrPcb(wxDC * DC, FILE * File, int * LineNum); // Gestion du PCB bool Clear_Pcb(wxDC * DC, bool query); EDA_BaseStruct * PcbGeneralLocateAndDisplay(void); EDA_BaseStruct * Locate(int typeloc ); // Gestion du curseur void place_marqueur( wxDC * DC, const wxPoint & pos, char* pt_bitmap, int DrawMode, int color, int type); /* Place un repere sur l'ecran au point de coordonnees PCB pos */ // Gestion des modules void InstallModuleOptionsFrame(MODULE * Module, wxDC * DC, const wxPoint & pos); MODULE * Copie_Module(MODULE * module); MODULE * Exchange_Module(wxWindow * winaff, MODULE * old_module, MODULE * new_module); int Save_1_Module(const wxString & LibName, MODULE* Module, bool Overwrite, bool DisplayDialog); void Archive_Modules(const wxString & LibName, bool NewModulesOnly); MODULE * Select_1_Module_From_BOARD(BOARD * Pcb); // Modules MODULE * Create_1_Module(wxDC * DC, const wxString & module_name); void Edit_Module(MODULE * module, wxDC * DC); void Rotate_Module(wxDC * DC, MODULE * module, int angle, bool incremental); void Change_Side_Module(MODULE * Module, wxDC * DC); void Place_Module(MODULE * module, wxDC * DC); void InstallExchangeModuleFrame(MODULE * ExchangeModuleModule, wxDC * DC, const wxPoint & pos); // Textes sur modules void RotateTextModule(TEXTE_MODULE * Text, wxDC * DC); void DeleteTextModule(TEXTE_MODULE * Text, wxDC * DC); void PlaceTexteModule(TEXTE_MODULE * Text, wxDC * DC); void StartMoveTexteModule(TEXTE_MODULE * Text, wxDC * DC); TEXTE_MODULE * CreateTextModule(MODULE * Module, wxDC * DC); void InstallPadOptionsFrame(D_PAD * pad, wxDC * DC, const wxPoint & pos); void InstallTextModOptionsFrame(TEXTE_MODULE * TextMod, wxDC * DC, const wxPoint & pos); // Pads sur modules void AddPad(MODULE * Module, wxDC * DC); void DeletePad(D_PAD* Pad, wxDC * DC); void StartMovePad(D_PAD * Pad, wxDC * DC); void RotatePad(D_PAD * Pad, wxDC * DC); void PlacePad(D_PAD * Pad, wxDC * DC); void Export_Pad_Settings( D_PAD * pt_pad); void Import_Pad_Settings( D_PAD * pt_pad, wxDC * DC); void Global_Import_Pad_Settings( D_PAD * Pad, wxDC * DC); // Chargement de modules MODULE * Get_Librairie_Module(wxWindow * winaff, const wxString & library, const wxString & ModuleName, bool show_msg_err); wxString Select_1_Module_From_List( wxWindow * active_window, const wxString & Library, const wxString & Mask, const wxString & KeyWord); MODULE * Load_Module_From_Library(const wxString & library, wxDC * DC); // Gestion des chevelus (ratsnest) void Compile_Ratsnest(wxDC * DC, bool affiche); /* Recalcul complet du chevelu */ void ReCompile_Ratsnest_After_Changes(wxDC * DC ); int Test_1_Net_Ratsnest(wxDC * DC, int net_code); char * build_ratsnest_module(wxDC * DC, MODULE *Module); void trace_ratsnest_module(wxDC * DC); void Build_Board_Ratsnest(wxDC * DC); void DrawGeneralRatsnest(wxDC * DC, int net_code = 0); void trace_ratsnest_pad(wxDC * DC); void recalcule_pad_net_code(void); /* Routine de calcul et de mise a jour des net_codes des PADS */ void build_liste_pads(void); int * build_ratsnest_pad(EDA_BaseStruct * ref, const wxPoint & refpos, bool init); void Tst_Ratsnest(wxDC * DC, int ref_netcode ); void Recalcule_all_net_connexion(wxDC * DC); void test_connexions(wxDC * DC) ; void test_1_net_connexion(wxDC * DC, int net_code ); void reattribution_reference_piste(int affiche); // Plotting void ToPlotter(wxCommandEvent& event); void Plot_Serigraphie(int format_plot, FILE * File, int masque_layer); void Genere_GERBER(const wxString & FullFileName, int Layer); void Genere_HPGL(const wxString & FullFileName, int Layer); void Genere_PS(const wxString & FullFileName, int Layer); void Plot_Layer_HPGL(FILE * File,int masque_layer, int garde, int tracevia, int modetrace); void Plot_Layer_GERBER(FILE * File,int masque_layer, int garde, int tracevia); int Gen_D_CODE_File(FILE * file); void Plot_Layer_PS(FILE * File,int masque_layer, int garde, int tracevia, int modetrace); /* Block operations: */ void Block_Delete(wxDC *DC); void Block_Rotate(wxDC *DC); void Block_Invert(wxDC * DC); void Block_Move(wxDC * DC); void Block_Duplicate(wxDC * DC); // Gestion des zones: void DelLimitesZone(wxDC *DC, bool Redraw); // Gestion des layers: int SelectLayer(int default_layer, int min_layer, int max_layer); void SelectLayerPair(void); // divers void AddHistory(int value, DrawStructureType type); // Add value in data list history void InstallGridFrame(const wxPoint & pos); }; /*****************************************************/ /* class WinEDA_PcbFrame: public WinEDA_BasePcbFrame */ /*****************************************************/ class WinEDA_PcbFrame: public WinEDA_BasePcbFrame { public: WinEDAChoiceBox * m_SelLayerBox; WinEDAChoiceBox * m_SelTrackWidthBox; WinEDAChoiceBox * m_SelViaSizeBox; private: bool m_SelTrackWidthBox_Changed; bool m_SelViaSizeBox_Changed; wxMenu * m_FilesMenu; public: WinEDA_PcbFrame( wxWindow * father, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_PcbFrame(void); // Configurations: void InstallConfigFrame(const wxPoint & pos); void Process_Config(wxCommandEvent& event); void Update_config(wxWindow * displayframe); void OnHotKey(wxDC * DC, int hotkey, EDA_BaseStruct * DrawStruct); bool OnHotkeyDeleteItem(wxDC * DC, EDA_BaseStruct * DrawStruct); void OnCloseWindow(wxCloseEvent & Event); void Process_Special_Functions(wxCommandEvent& event); void ProcessMuWaveFunctions(wxCommandEvent& event); void MuWaveCommand(wxDC * DC, const wxPoint& MousePos); void RedrawActiveWindow(wxDC * DC, bool EraseBg); void ReCreateHToolbar(void); void ReCreateAuxiliaryToolbar(void); void ReCreateVToolbar(void); void ReCreateAuxVToolbar(void); void ReCreateOptToolbar(void); void ReCreateMenuBar(void); WinEDAChoiceBox * ReCreateLayerBox( WinEDA_Toolbar * parent); void OnLeftClick(wxDC * DC, const wxPoint& MousePos); void OnLeftDClick(wxDC * DC, const wxPoint& MousePos); void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu); void OnSelectOptionToolbar(wxCommandEvent& event); void ToolOnRightClick(wxCommandEvent& event); /* Gestion generale des operations sur block */ int ReturnBlockCommand(int key); void HandleBlockPlace(wxDC * DC); int HandleBlockEnd(wxDC * DC); void SetToolbars(void); void Process_Settings(wxCommandEvent& event); void InstallPcbOptionsFrame(const wxPoint & pos, wxDC * DC, int id); void InstallPcbGlobalDeleteFrame(const wxPoint & pos); void GenModulesPosition(wxCommandEvent& event); void GenModuleReport(wxCommandEvent& event); void InstallDrillFrame(wxCommandEvent& event); void ToPostProcess(wxCommandEvent& event); void Files_io(wxCommandEvent& event); int LoadOnePcbFile(const wxString & FileName, wxDC * DC, bool Append); int ReadPcbFile(wxDC * DC, FILE * File, bool Append); bool SavePcbFile(const wxString & FileName); int SavePcbFormatAscii(FILE * File); bool WriteGeneralDescrPcb(FILE * File); bool RecreateCmpFileFromBoard(void); void ExportToGenCAD(wxCommandEvent& event); /* Fonctions specifiques */ MODULE * ListAndSelectModuleName(void); void Liste_Equipot(wxCommandEvent & event); void Swap_Layers(wxCommandEvent & event); int Test_DRC(wxDC * DC); void Install_Test_DRC_Frame(wxDC * DC); void Trace_Pcb(wxDC * DC, int mode); void Trace_PcbEdges(wxDC * DC, int mode_color); // Gestion des textes sur pcb void Rotate_Texte_Pcb(TEXTE_PCB * TextePcb, wxDC * DC); TEXTE_PCB * Create_Texte_Pcb( wxDC * DC); void Delete_Texte_Pcb(TEXTE_PCB * TextePcb, wxDC * DC); void StartMoveTextePcb(TEXTE_PCB * TextePcb, wxDC * DC); void Place_Texte_Pcb(TEXTE_PCB * TextePcb, wxDC * DC); void InstallTextPCBOptionsFrame(TEXTE_PCB * TextPCB, wxDC * DC, const wxPoint & pos); // Gestion des Segments type DRAWITEM void Start_Move_DrawItem(DRAWSEGMENT * drawitem, wxDC * DC); void Place_DrawItem(DRAWSEGMENT * drawitem, wxDC * DC); // Gestion des modules (voir egalement WinEDA_BasePcbFrame) void StartMove_Module(MODULE * module, wxDC * DC); bool Delete_Module(MODULE * module, wxDC * DC); // Chargement de modules: voir WinEDA_BasePcbFrame // Gestion du PCB void Erase_Zones(wxDC * DC, bool query); void Erase_Segments_Pcb(wxDC * DC, bool is_edges, bool query); void Erase_Pistes(wxDC * DC, int masque_type, bool query); void Erase_Modules(wxDC * DC, bool query); void Erase_Textes_Pcb(wxDC * DC, bool query); void Erase_Marqueurs(wxDC * DC, bool query); void UnDeleteItem(wxDC * DC); void RemoveStruct(EDA_BaseStruct * Item, wxDC * DC); void Via_Edit_Control(wxDC * DC, int command_type, SEGVIA * via); // Mise en surbrillance des nets: int Select_High_Light(wxDC * DC); void Hight_Light(wxDC * DC); void DrawHightLight(wxDC * DC, int NetCode); // Edition des pistes: void DisplayTrackSettings(void); void Other_Layer_Route(TRACK * track, wxDC * DC); void Affiche_PadsNoConnect(wxDC * DC); void Affiche_Status_Net(wxDC * DC); TRACK * Delete_Segment(wxDC * DC, TRACK *Track); void Delete_Track(wxDC * DC, TRACK *Track); void Delete_net(wxDC * DC, TRACK *Track); void Delete_Zone(wxDC * DC, SEGZONE *Track); void Supprime_Une_Piste(wxDC * DC, TRACK* pt_segm); bool Resize_Pistes_Vias(wxDC * DC, bool Track, bool Via); void Edit_Zone_Width(wxDC * DC, SEGZONE * pt_ref); void Edit_Net_Width(wxDC * DC, int Netcode); void Edit_Track_Width(wxDC * DC, TRACK *Track); int Edit_TrackSegm_Width(wxDC * DC, TRACK * segm); TRACK * Begin_Route(TRACK * track, wxDC * DC); void End_Route(TRACK * track, wxDC * DC); void ExChange_Track_Layer(TRACK *pt_segm, wxDC * DC); void Attribut_Segment(TRACK * track, wxDC * DC, bool Flag_On); void Attribut_Track(TRACK * track, wxDC * DC, bool Flag_On); void Attribut_net(wxDC * DC, int net_code, bool Flag_On); void Start_MoveOneTrackSegment(TRACK * track, wxDC * DC, bool Drag); bool PlaceDraggedTrackSegment(TRACK * Track, wxDC * DC); // Edition des zones EDGE_ZONE * Del_SegmEdgeZone(wxDC * DC, EDGE_ZONE * edge_zone); void CaptureNetName(wxDC * DC); EDGE_ZONE * Begin_Zone(void); void End_Zone(wxDC * DC); void Fill_Zone(wxDC * DC); // Edition des mires de centrage MIREPCB * Create_Mire( wxDC *DC); void Delete_Mire(MIREPCB * MirePcb, wxDC * DC); void StartMove_Mire(MIREPCB * MirePcb, wxDC * DC); void Place_Mire(MIREPCB * MirePcb, wxDC * DC); void InstallMireOptionsFrame(MIREPCB * MirePcb, wxDC * DC, const wxPoint & pos); // Gestion des segments de dessin type DRAWSEGMENT: DRAWSEGMENT * Begin_DrawSegment(DRAWSEGMENT * Segment, int shape, wxDC * DC); void End_Edge(DRAWSEGMENT * Segment, wxDC * DC); void Drawing_SetNewWidth(DRAWSEGMENT *DrawSegm, wxDC * DC); void Delete_Segment_Edge( DRAWSEGMENT* Segment, wxDC * DC); void Delete_Drawings_All_Layer(DRAWSEGMENT *Segment, wxDC * DC); // Gestion des cotations: void Install_Edit_Cotation(COTATION * Cotation, wxDC * DC, const wxPoint & pos); COTATION * Begin_Cotation(COTATION * Cotation, wxDC * DC); void Delete_Cotation(COTATION * Cotation, wxDC * DC); // Gestion des netlistes: void InstallNetlistFrame( wxDC * DC, const wxPoint & pos); // Autoplacement: void AutoPlace(wxCommandEvent& event); void ReOrientModules(const wxString & ModuleMask, int Orient, bool include_fixe, wxDC * DC); void FixeModule(MODULE * Module, bool Fixe); void AutoMoveModulesOnPcb(wxDC * DC, bool PlaceModulesHorsPcb); bool SetBoardBoundaryBoxFromEdgesOnly(void); void AutoPlaceModule(MODULE * Module, int place_mode, wxDC * DC); int RecherchePlacementModule(MODULE * Module, wxDC * DC); void GenModuleOnBoard(MODULE * Module); float Compute_Ratsnest_PlaceModule(wxDC * DC); int GenPlaceBoard(void); void DrawInfoPlace(wxDC * DC); // Autoroutage: int Solve(wxDC * DC, int two_sides); void Reset_Noroutable(wxDC * DC); void Autoroute(wxDC * DC, int mode); void ReadAutoroutedTracks(wxDC * DC); void GlobalRoute(wxDC * DC); // fonctions generales void Show_1_Ratsnest(EDA_BaseStruct * item, wxDC * DC); void Ratsnest_On_Off(wxDC * DC); void Clean_Pcb(wxDC * DC); EDA_BaseStruct * SaveItemEfface(EDA_BaseStruct * PtItem, int nbitems); // divers void InstallFindFrame(const wxPoint & pos, wxDC * DC); /* Special micro_ondes */ void Edit_Gap(wxDC * DC, MODULE * Module); MODULE * Create_MuWaveBasicShape(wxDC * DC, const wxString & name, int pad_count); MODULE * Create_MuWaveComponent(wxDC * DC, int shape_type); MODULE * Create_MuWavePolygonShape(wxDC * DC); void Begin_Self( wxDC *DC); MODULE * Genere_Self( wxDC *DC); DECLARE_EVENT_TABLE() }; /****************************************************/ /* class WinEDA_GerberFrame: public WinEDA_PcbFrame */ /****************************************************/ class WinEDA_GerberFrame: public WinEDA_BasePcbFrame { public: WinEDAChoiceBox * m_SelLayerBox; WinEDAChoiceBox * m_SelLayerTool; private: wxMenu * m_FilesMenu; public: WinEDA_GerberFrame( wxWindow * father, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_GerberFrame(void); void Update_config(void); void OnCloseWindow(wxCloseEvent & Event); void Process_Special_Functions(wxCommandEvent& event); void RedrawActiveWindow(wxDC * DC, bool EraseBg); void ReCreateHToolbar(void); void ReCreateVToolbar(void); void ReCreateOptToolbar(void); void ReCreateMenuBar(void); void OnLeftClick(wxDC * DC, const wxPoint& MousePos); void OnLeftDClick(wxDC * DC, const wxPoint& MousePos); void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu); int BestZoom(void); // Retourne le meilleur zoom void OnSelectOptionToolbar(wxCommandEvent& event); EDA_BaseStruct * GerberGeneralLocateAndDisplay(void); EDA_BaseStruct * Locate(int typeloc ); void SetToolbars(void); void Process_Settings(wxCommandEvent& event); void Process_Config(wxCommandEvent& event); void InstallConfigFrame(const wxPoint & pos); void InstallPcbOptionsFrame(const wxPoint & pos, int id); void InstallPcbGlobalDeleteFrame(const wxPoint & pos); /* Gestion generale des operations sur block */ int ReturnBlockCommand(int key); virtual void HandleBlockPlace(wxDC * DC); virtual int HandleBlockEnd(wxDC * DC); void InstallDrillFrame(wxCommandEvent& event); void ToPostProcess(wxCommandEvent& event); void Genere_HPGL(const wxString & FullFileName, int Layers); void Genere_GERBER(const wxString & FullFileName, int Layers); void Genere_PS(const wxString & FullFileName, int Layers); void Plot_Layer_HPGL(FILE * File,int masque_layer, int garde, int tracevia, int modetrace); void Plot_Layer_GERBER(FILE * File,int masque_layer, int garde, int tracevia); int Gen_D_CODE_File(const wxString & Name_File); void Plot_Layer_PS(FILE * File,int masque_layer, int garde, int tracevia, int modetrace); void Files_io(wxCommandEvent& event); int LoadOneGerberFile(const wxString &FileName, wxDC * DC, int mode); int ReadGerberFile(wxDC * DC, FILE * File, bool Append); bool Read_GERBER_File(wxDC * DC, const wxString & GERBER_FullFileName, const wxString & D_Code_FullFileName); bool SaveGerberFile(const wxString & FileName, wxDC * DC); int Read_D_Code_File( const wxString & D_Code_FullFileName); void CopyDCodesSizeToItems(void); void Liste_D_Codes(wxDC * DC); /* Fonctions specifiques */ void Trace_Gerber(wxDC * DC, int mode); // Gestion des textes sur pcb void Rotate_Texte_Pcb(TEXTE_PCB * TextePcb, wxDC * DC); TEXTE_PCB * Create_Texte_Pcb( wxDC * DC); void Delete_Texte_Pcb(TEXTE_PCB * TextePcb, wxDC * DC); void StartMoveTextePcb(TEXTE_PCB * TextePcb, wxDC * DC); void Place_Texte_Pcb(TEXTE_PCB * TextePcb, wxDC * DC); // Gestion du PCB bool Clear_Pcb(wxDC * DC, bool query); void Erase_Current_Layer(wxDC * DC, bool query); void Erase_Zones(wxDC * DC, bool query); void Erase_Segments_Pcb(wxDC * DC, bool is_edges, bool query); void Erase_Pistes(wxDC * DC, int masque_type, bool query); void Erase_Textes_Pcb(wxDC * DC, bool query); void UnDeleteItem(wxDC * DC); TRACK * Begin_Route(TRACK * track, wxDC * DC); void End_Route(TRACK * track, wxDC * DC); TRACK * Delete_Segment(wxDC * DC, TRACK *Track); int Edit_TrackSegm_Width(wxDC * DC, TRACK * segm); DECLARE_EVENT_TABLE() }; /*********************************************************/ /* class WinEDA_ModuleEditFrame: public WinEDA_DrawFrame */ /* Class de la fenetre d'édition des modules pour PCB */ /*********************************************************/ class WinEDA_ModuleEditFrame: public WinEDA_BasePcbFrame { public: MODULE * CurrentModule; wxString m_CurrentLib; public: WinEDA_ModuleEditFrame( wxWindow * father, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_ModuleEditFrame(void); void InstallOptionsFrame(const wxPoint & pos); void OnCloseWindow(wxCloseEvent & Event); void Process_Special_Functions(wxCommandEvent& event); void RedrawActiveWindow(wxDC * DC, bool EraseBg); void ReCreateHToolbar(void); void ReCreateVToolbar(void); void ReCreateOptToolbar(void); void ReCreateAuxiliaryToolbar(void); void OnLeftClick(wxDC * DC, const wxPoint& MousePos); void OnLeftDClick(wxDC * DC, const wxPoint& MousePos); void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu); void SetToolbars(void); void ReCreateMenuBar(void); void ToolOnRightClick(wxCommandEvent& event); void OnSelectOptionToolbar(wxCommandEvent& event); void OnHotKey(wxDC * DC, int hotkey, EDA_BaseStruct * DrawStruct); /* Gestion generale des operations sur block */ int ReturnBlockCommand(int key); virtual void HandleBlockPlace(wxDC * DC); virtual int HandleBlockEnd(wxDC * DC); EDA_BaseStruct * ModeditLocateAndDisplay(void); public: void SaveCopyInUndoList(void); private: void GetComponentFromUndoList(void); void GetComponentFromRedoList(void); public: // Gestion des modules void Place_Ancre(MODULE* module, wxDC * DC); void RemoveStruct(EDA_BaseStruct * Item, wxDC * DC); void Transform(MODULE* module, wxDC * DC, int transform); // Chargement de modules MODULE * Import_Module(wxDC * DC); void Export_Module(MODULE* ptmod, bool createlib); void Load_Module_Module_From_BOARD( MODULE * Module ); // Gestion des contours void Edit_Edge_Width(EDGE_MODULE * Edge, wxDC * DC); void Edit_Edge_Layer(EDGE_MODULE * Edge, wxDC * DC); void Delete_Edge_Module(EDGE_MODULE * Edge, wxDC * DC); EDGE_MODULE * Begin_Edge_Module(EDGE_MODULE * Edge, wxDC * DC, int type_edge); void End_Edge_Module(EDGE_MODULE * Edge,wxDC * DC); void Enter_Edge_Width(EDGE_MODULE * Edge, wxDC * DC); void Start_Move_EdgeMod(EDGE_MODULE * drawitem, wxDC * DC); void Place_EdgeMod(EDGE_MODULE * drawitem, wxDC * DC); // Gestion des librairies: void Delete_Module_In_Library(const wxString & libname); int Create_Librairie(const wxString & LibName); void Select_Active_Library(void); DECLARE_EVENT_TABLE() }; /*******************************/ /* class WinEDA_SchematicFrame */ /*******************************/ /* enum utilisé dans RotationMiroir() */ enum fl_rot_cmp { CMP_NORMAL, // orientation normale (O, pas de miroir) CMP_ROTATE_CLOCKWISE, // nouvelle rotation de -90 CMP_ROTATE_COUNTERCLOCKWISE, // nouvelle rotation de +90 CMP_ORIENT_0, // orientation 0, pas de miroir, id CMP_NORMAL CMP_ORIENT_90, // orientation 90, pas de miroir CMP_ORIENT_180, // orientation 180, pas de miroir CMP_ORIENT_270, // orientation -90, pas de miroir CMP_MIROIR_X = 0x100, // miroir selon axe X CMP_MIROIR_Y = 0x200 // miroir selon axe Y }; class WinEDA_SchematicFrame: public WinEDA_DrawFrame { public: WinEDAChoiceBox * m_SelPartBox; private: wxMenu * m_FilesMenu; public: WinEDA_SchematicFrame( wxWindow * father, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_SchematicFrame(void); void OnCloseWindow(wxCloseEvent & Event); void Process_Special_Functions(wxCommandEvent& event); void Process_Config(wxCommandEvent& event); void Save_Config(wxWindow * displayframe); void RedrawActiveWindow(wxDC * DC, bool EraseBg); void ReCreateHToolbar(void); void ReCreateVToolbar(void); void ReCreateOptToolbar(void); void ReCreateMenuBar(void); void SetToolbars(void); SCH_SCREEN * GetScreen(void) { return (SCH_SCREEN *) m_CurrentScreen;} void InstallConfigFrame(const wxPoint & pos); void OnLeftClick(wxDC * DC, const wxPoint& MousePos); void OnLeftDClick(wxDC * DC, const wxPoint& MousePos); void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu); void OnSelectOptionToolbar(wxCommandEvent& event); void ToolOnRightClick(wxCommandEvent& event); int BestZoom(void); // Retourne le meilleur zoom EDA_BaseStruct * SchematicGeneralLocateAndDisplay(bool IncludePin = TRUE); void InstallPreviousScreen(void); void InstallNextScreen(DrawSheetStruct * Sheet); void ToPlot_PS(wxCommandEvent& event); void ToPlot_HPGL(wxCommandEvent& event); void ToPostProcess(wxCommandEvent& event); void Save_File(wxCommandEvent& event); int LoadOneEEProject(const wxString & FileName, bool IsNew); bool LoadOneEEFile(BASE_SCREEN * Window, const wxString & FullFileName); bool SaveEEFile(BASE_SCREEN *Window, int FileSave); bool LoadOneSheet(SCH_SCREEN * screen, const wxString & FullFileName); // General search: EDA_BaseStruct * FindSchematicItem(const wxString & pattern, int SearchType); EDA_BaseStruct * FindMarker(int SearchType); private: void Process_Move_Item(EDA_BaseStruct *DrawStruct, wxDC * DC); // Bus Entry DrawBusEntryStruct * CreateBusEntry(wxDC * DC, int entry_type); void SetBusEntryShape(wxDC * DC, DrawBusEntryStruct *BusEntry, int entry_type); int GetBusEntryShape( DrawBusEntryStruct *BusEntry); void StartMoveBusEntry(DrawBusEntryStruct * DrawLibItem, wxDC * DC); // NoConnect EDA_BaseStruct *CreateNewNoConnectStruct(wxDC * DC); // Junction DrawJunctionStruct * CreateNewJunctionStruct(wxDC * DC, const wxPoint & pos); // Text ,label, glabel EDA_BaseStruct * CreateNewText(wxDC * DC, int type); void EditSchematicText(DrawTextStruct * TextStruct, wxDC * DC); void ChangeTextOrient(DrawTextStruct * TextStruct, wxDC * DC); void StartMoveTexte(DrawTextStruct * TextStruct, wxDC *DC); void ChangeTypeText(DrawTextStruct * Text, wxDC * DC, int newtype); // Wire, Bus void BeginSegment(wxDC * DC, int type); void EndSegment(wxDC *DC); void DeleteCurrentSegment(wxDC * DC); void DeleteConnection(wxDC * DC, bool DeleteFullConnection); // graphic lines void Delete_Segment_Edge( DRAWSEGMENT* Segment, wxDC * DC); void Drawing_SetNewWidth(DRAWSEGMENT *DrawSegm, wxDC * DC); void Delete_Drawings_All_Layer(DRAWSEGMENT *Segment, wxDC * DC); DRAWSEGMENT * Begin_Edge(DRAWSEGMENT * Segment, wxDC * DC); // Hierarchical Sheet & PinSheet void InstallHierarchyFrame(wxDC * DC, wxPoint &pos); DrawSheetStruct * CreateSheet(wxDC * DC); void ReSizeSheet(DrawSheetStruct * Sheet, wxDC * DC); public: bool EditSheet(DrawSheetStruct * Sheet, wxDC * DC); private: void StartMoveSheet(DrawSheetStruct* sheet, wxDC * DC); DrawSheetLabelStruct * Create_PinSheet(DrawSheetStruct * Sheet, wxDC * DC); void Edit_PinSheet(DrawSheetLabelStruct * SheetLabel, wxDC * DC); void StartMove_PinSheet(DrawSheetLabelStruct * SheetLabel, wxDC * DC); void Place_PinSheet(DrawSheetLabelStruct * SheetLabel, wxDC * DC); DrawSheetLabelStruct * Import_PinSheet(DrawSheetStruct * Sheet, wxDC * DC); public: void DeleteSheetLabel(wxDC * DC, DrawSheetLabelStruct * SheetLabelToDel); private: // Component EDA_SchComponentStruct * Load_Component(wxDC * DC, const wxString & libname, wxArrayString & List, bool UseLibBrowser ); void StartMovePart(EDA_SchComponentStruct * DrawLibItem, wxDC * DC); void CmpRotationMiroir( EDA_SchComponentStruct * DrawComponent, wxDC * DC, int type_rotate ); void SelPartUnit(EDA_SchComponentStruct *DrawComponent, int unit, wxDC * DC); void ConvertPart(EDA_SchComponentStruct *DrawComponent, wxDC * DC); void SetInitCmp(EDA_SchComponentStruct * DrawComponent, wxDC * DC); void EditComponentReference(EDA_SchComponentStruct * DrawLibItem, wxDC * DC); void EditComponentValue(EDA_SchComponentStruct * DrawLibItem, wxDC * DC); void StartMoveCmpField(PartTextStruct * Field, wxDC * DC); void EditCmpFieldText(PartTextStruct * Field, wxDC *DC); void RotateCmpField(PartTextStruct * Field, wxDC * DC); /* Operations sur bloc */ bool UnDeleteStruct(wxDC * DC); void PasteStruct(wxDC * DC); public: void OnHotKey(wxDC * DC, int hotkey, EDA_BaseStruct * DrawStruct); /* Gestion generale des operations sur block */ int ReturnBlockCommand(int key); void InitBlockPasteInfos(); void HandleBlockPlace(wxDC * DC); int HandleBlockEnd(wxDC * DC); void HandleBlockEndByPopUp(int Command, wxDC * DC); // Repetition automatique de placements void RepeatDrawItem(wxDC *DC); // Test des points de connexion en l'air (dangling ends) void TestDanglingEnds(EDA_BaseStruct *DrawList, wxDC *DC); LibDrawPin * LocatePinEnd(EDA_BaseStruct *DrawList, const wxPoint & pos); DECLARE_EVENT_TABLE() }; /*****************************/ /* class WinEDA_LibeditFrame */ /*****************************/ class WinEDA_LibeditFrame: public WinEDA_DrawFrame { public: WinEDAChoiceBox * m_SelpartBox; WinEDAChoiceBox * m_SelAliasBox; public: WinEDA_LibeditFrame( wxWindow * father, WinEDA_App *parent, const wxString & title, const wxPoint& pos, const wxSize& size); ~WinEDA_LibeditFrame(void); void Process_Special_Functions(wxCommandEvent& event); void DisplayLibInfos(void); void RedrawActiveWindow(wxDC * DC, bool EraseBg); void OnCloseWindow(wxCloseEvent & Event); void ReCreateHToolbar(void); void ReCreateVToolbar(void); void OnLeftClick(wxDC * DC, const wxPoint& MousePos); void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu); int BestZoom(void); // Retourne le meilleur zoom void SetToolbars(void); void OnLeftDClick(wxDC * DC, const wxPoint& MousePos); SCH_SCREEN * GetScreen(void) { return (SCH_SCREEN *) m_CurrentScreen;} private: // General: void CreateNewLibraryPart(void); void DeleteOnePart(void); void SaveOnePartInMemory(void); void SelectActiveLibrary(void); bool LoadOneLibraryPart(void); void SaveActiveLibrary(void); void ImportOnePart(void); void ExportOnePart(bool create_lib); int LoadOneLibraryPartAux(EDA_LibComponentStruct *LibEntry, LibraryStruct *Library, int noMsg = 0); void DisplayCmpDoc(const wxString & Name); void InstallLibeditFrame(const wxPoint & pos); // General editing public: void SaveCopyInUndoList(void); private: void GetComponentFromUndoList(void); void GetComponentFromRedoList(void); // Edition des Pins: void CreatePin(wxDC * DC); void DeletePin(wxDC * DC, EDA_LibComponentStruct* LibEntry, LibDrawPin* Pin); void StartMovePin(wxDC * DC); // Test des pins ( duplicates...) bool TestPins(EDA_LibComponentStruct* LibEntry); // Edition de l'ancre void PlaceAncre(void); // Edition des graphismes: LibEDA_BaseStruct * CreateGraphicItem(wxDC * DC); void GraphicItemBeginDraw(wxDC * DC); void StartMoveDrawSymbol(wxDC * DC); void EndDrawGraphicItem(wxDC * DC); void LoadOneSymbol(wxDC * DC); void SaveOneSymbol(void); void EditGraphicSymbol(wxDC * DC, LibEDA_BaseStruct * DrawItem); void EditSymbolText(wxDC * DC, LibEDA_BaseStruct * DrawItem); void RotateSymbolText(wxDC * DC); void DeleteDrawPoly(wxDC * DC); LibDrawField * LocateField(EDA_LibComponentStruct *LibEntry); void RotateField(wxDC * DC, LibDrawField *Field); void PlaceField(wxDC * DC, LibDrawField *Field); void EditField(wxDC * DC, LibDrawField *Field); void StartMoveField(wxDC * DC, LibDrawField *field); public: /* Block commands: */ int ReturnBlockCommand(int key); void HandleBlockPlace(wxDC * DC); int HandleBlockEnd(wxDC * DC); void DeletePartInLib( LibraryStruct * Library, EDA_LibComponentStruct *Entry); void PlacePin(wxDC * DC); void InitEditOnePin(void); void GlobalSetPins(wxDC * DC, LibDrawPin * MasterPin, int id); // Repetition automatique de placement de pins void RepeatPinItem(wxDC *DC, LibDrawPin * Pin); DECLARE_EVENT_TABLE() }; class LibraryStruct; class WinEDA_ViewlibFrame: public WinEDA_DrawFrame { public: WinEDAChoiceBox *SelpartBox; wxListBox * m_LibList; wxSize m_LibListSize; wxListBox * m_CmpList; wxSize m_CmpListSize; bool m_IsModal; // this pointer is non-NULL only while the modal event loop is running wxMyDialogModalData * m_modalData; public: WinEDA_ViewlibFrame( wxWindow * father, WinEDA_App *parent, LibraryStruct * Library = NULL, bool IsModal = FALSE); ~WinEDA_ViewlibFrame(void); void OnSize(wxSizeEvent& event); void ReCreateListLib(void); void ReCreateListCmp(void); void Process_Special_Functions(wxCommandEvent& event); void DisplayLibInfos(void); void RedrawActiveWindow(wxDC * DC, bool EraseBg); void OnCloseWindow(wxCloseEvent & Event); void ReCreateHToolbar(void); void ReCreateVToolbar(void); void OnLeftClick(wxDC * DC, const wxPoint& MousePos); int BestZoom(void); // Retourne le meilleur zoom void ClickOnLibList(wxCommandEvent& event); void ClickOnCmpList(wxCommandEvent & event); SCH_SCREEN * GetScreen(void) { return (SCH_SCREEN *) m_CurrentScreen;} void ShowInModalMode(void); private: void SelectCurrentLibrary(void); void SelectAndViewLibraryPart(int option); void ExportToSchematicLibraryPart(wxCommandEvent& event); void ViewOneLibraryContent(LibraryStruct *Lib, int Flag); void OnRightClick(const wxPoint& MousePos, wxMenu * PopMenu); DECLARE_EVENT_TABLE() }; /****************************************************/ /* classe representant un ecran graphique de dessin */ /****************************************************/ #include "drawpanel_wxstruct.h" /*********************************************************/ /* classe representant un ecran d'affichage des messages */ /*********************************************************/ class WinEDA_MsgPanel: public wxPanel { public: WinEDA_DrawFrame * m_Parent; int m_BgColor; // couleur de fond public: // Constructor and destructor WinEDA_MsgPanel(WinEDA_DrawFrame *parent, int id, const wxPoint& pos, const wxSize& size); ~WinEDA_MsgPanel(void); void OnPaint(wxPaintEvent & event); void EraseMsgBox(void); void EraseMsgBox(wxDC * DC); void Affiche_1_Parametre(int pos_X,const wxString & texte_H, const wxString & texte_L,int color); DECLARE_EVENT_TABLE() }; /******************************************************************/ /* Classe pour editer une ligne de texte dans les menus de config */ /******************************************************************/ class WinEDA_EnterText { public: bool m_Modify; private: wxString m_NewText; wxTextCtrl * m_FrameText; wxStaticText * m_Title; public: // Constructor and destructor WinEDA_EnterText(wxWindow *parent, const wxString & Title, const wxString & TextToEdit, wxBoxSizer * BoxSizer, const wxSize & Size ); ~WinEDA_EnterText(void) { } wxString GetValue(void); void GetValue(char * buffer, int lenmax); void SetValue(const wxString & new_text); void Enable(bool enbl); void SetFocus(void) { m_FrameText->SetFocus(); } void SetInsertionPoint(int n) { m_FrameText->SetInsertionPoint(n); } void SetSelection(int n, int m) { m_FrameText->SetSelection(n, m); } }; /*********************************************************************/ /* Classe pour editer un texte graphique + dimension en INCHES ou MM */ /*********************************************************************/ class WinEDA_GraphicTextCtrl { public: int m_Units, m_Internal_Unit; wxTextCtrl * m_FrameText; wxTextCtrl * m_FrameSize; private: wxStaticText * m_Title; public: // Constructor and destructor WinEDA_GraphicTextCtrl(wxWindow *parent, const wxString & Title, const wxString & TextToEdit, int textsize, int units, wxBoxSizer * BoxSizer, int framelen = 200, int internal_unit = EESCHEMA_INTERNAL_UNIT); ~WinEDA_GraphicTextCtrl(void); wxString GetText(void); int GetTextSize(void); void Enable(bool state); void SetTitle(const wxString & title); void SetFocus(void) { m_FrameText->SetFocus(); } void SetValue(const wxString & value); void SetValue(int value); }; /*****************************************************************/ /* Classe pour afficher et editer une coordonnée en INCHES ou MM */ /*****************************************************************/ class WinEDA_PositionCtrl { public: int m_Units, m_Internal_Unit; wxPoint m_Pos_To_Edit; wxTextCtrl * m_FramePosX; wxTextCtrl * m_FramePosY; private: wxStaticText * m_TextX, * m_TextY; public: // Constructor and destructor WinEDA_PositionCtrl(wxWindow *parent, const wxString & title, const wxPoint & pos_to_edit, int units, wxBoxSizer * BoxSizer, int internal_unit = EESCHEMA_INTERNAL_UNIT ); ~WinEDA_PositionCtrl(void); void Enable(bool on); void SetValue(int x_value, int y_value); wxPoint GetValue(void); }; /*****************************************************************/ /* Classe pour afficher et editer une coordonnée en INCHES ou MM */ /*****************************************************************/ class WinEDA_SizeCtrl: public WinEDA_PositionCtrl { public: // Constructor and destructor WinEDA_SizeCtrl(wxWindow *parent, const wxString & title, const wxSize & size_to_edit, int units, wxBoxSizer * BoxSizer, int internal_unit = EESCHEMA_INTERNAL_UNIT ); ~WinEDA_SizeCtrl(void) {} wxSize GetValue(void); }; /*****************************************************************/ /* Classe pour afficher et editer une valeur en INCHES ou MM */ /*****************************************************************/ /* internal_unit est le nombre d'unites internes par inch - 1000 sur EESchema - 10000 sur PcbNew */ class WinEDA_ValueCtrl { public: int m_Units; int m_Value; wxTextCtrl * m_ValueCtrl; private: int m_Internal_Unit; wxStaticText * m_Text; public: // Constructor and destructor WinEDA_ValueCtrl(wxWindow *parent, const wxString & title, int value, int units, wxBoxSizer * BoxSizer, int internal_unit = EESCHEMA_INTERNAL_UNIT ); ~WinEDA_ValueCtrl(void); int GetValue(void); void SetValue(int new_value); void Enable(bool enbl); void SetToolTip(const wxString & text) { m_ValueCtrl->SetToolTip(text); } }; /*****************************************************************/ /* Classe pour afficher et editer une valeur double flottant */ /*****************************************************************/ class WinEDA_DFloatValueCtrl { public: double m_Value; wxTextCtrl * m_ValueCtrl; private: wxStaticText * m_Text; public: // Constructor and destructor WinEDA_DFloatValueCtrl(wxWindow *parent, const wxString & title, double value, wxBoxSizer * BoxSizer); ~WinEDA_DFloatValueCtrl(void); double GetValue(void); void SetValue(double new_value); void Enable(bool enbl); void SetToolTip(const wxString & text) { m_ValueCtrl->SetToolTip(text); } }; /*************************/ /* class WinEDA_Toolbar */ /*************************/ class WinEDA_Toolbar: public wxToolBar { public: wxWindow * m_Parent; id_toolbar m_Ident; WinEDA_Toolbar * Pnext; bool m_Horizontal; int m_Size; public: WinEDA_Toolbar(id_toolbar type, wxWindow * parent, wxWindowID id, bool horizontal); WinEDA_Toolbar * Next(void) { return Pnext;} }; /***********************/ /* class WinEDAListBox */ /***********************/ class WinEDAListBox : public wxDialog { public: wxWindow * m_Parent; wxListBox * m_List; wxTextCtrl * m_WinMsg; const wxChar ** m_ItemList; private: void(* m_MoveFct)(wxString & Text); public: WinEDAListBox( wxWindow * parent, const wxString & title, const wxChar ** ItemList, const wxString & RefText, void(* movefct)(wxString & Text) = NULL, const wxColour & colour = wxNullColour, wxPoint dialog_position = wxDefaultPosition); ~WinEDAListBox(void); void SortList( void ); void Append(const wxString & item); void InsertItems(const wxArrayString & itemlist, int position=0); void MoveMouseToOrigin(void); wxString GetTextSelection(void); private: void OnClose(wxCloseEvent& event); void Cancel(wxCommandEvent& event); void Ok(wxCommandEvent& event); void ClickOnList(wxCommandEvent& event); void D_ClickOnList(wxCommandEvent& event); DECLARE_EVENT_TABLE() }; /*************************/ /* class WinEDAChoiceBox */ /*************************/ /* class to display a choice list. This is a wrapper to wxComboBox (or wxChoice) but because they have some problems, WinEDAChoiceBox uses workarounds: - in wxGTK 2.6.2 wxGetSelection() does not work properly, - and wxChoice crashes if compiled in non unicode mode and uses utf8 codes */ #define EVT_KICAD_CHOICEBOX EVT_COMBOBOX class WinEDAChoiceBox : public wxComboBox { public: WinEDAChoiceBox(wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL) : wxComboBox(parent, id, wxEmptyString, pos, size, n, choices, wxCB_READONLY) { } WinEDAChoiceBox(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, const wxArrayString & choices) : wxComboBox(parent, id, wxEmptyString, pos, size, choices, wxCB_READONLY) { } int GetChoice(void){ return GetCurrentSelection(); } }; #endif /* WXSTRUCT_H */
[ "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 1491 ] ] ]
f3c07daedf7e2b4b16c17735831da15c2b84d672
bfc0e4b6c3ed04d90b20335987c51935e445d774
/newgrid.cpp
b7475edf504fd4df3e2784974cafdabc178f5628
[]
no_license
luzhskij/geoid
4f4a817e723b7deac98f7f132b7a10ec45b18f04
d2208addd40134da2242cbb430cd233307eaf12d
refs/heads/master
2021-01-10T07:39:17.449922
2008-04-17T06:28:03
2008-04-17T06:28:03
51,741,070
0
0
null
null
null
null
UTF-8
C++
false
false
10,171
cpp
/* * This file is part of the Geoid and licensed under the GNU General Public License, version 3 * http://www.gnu.org/licenses/gpl-3.0.html */ #include "newgrid.h" #include <math.h> #include <QFileDialog> #include <QFile> #include <QTextStream> #include <QMessageBox> NewGrid::NewGrid(QWidget *parent) : QDialog(parent) { ui.setupUi(this); QWidget::setWindowFlags(Qt::Dialog ); // | Qt::MSWindowsFixedSizeDialogHint validDataFile = false; xSizeEditing = false; ySizeEditing = false; QDoubleValidator * val = new QDoubleValidator( this ); ui.minXEdit->setValidator(val); ui.maxXEdit->setValidator(val); ui.minYEdit->setValidator(val); ui.maxYEdit->setValidator(val); ui.xSizeEdit->setValidator(val); ui.ySizeEdit->setValidator(val); connect(this, SIGNAL(accepted()), this, SLOT(onAccepted())); } NewGrid::~NewGrid() { } void NewGrid::on_radioImport_toggled(bool) { ui.importEdit->setEnabled(true); ui.importButton->setEnabled(true); ui.createEdit->setEnabled(false); ui.createButton->setEnabled(false); ui.defineCooBox->setEnabled(false); ui.paramBox->setEnabled(false); ui.okButton->setEnabled(validGridFile); } void NewGrid::on_radioCreate_toggled(bool) { ui.importEdit->setEnabled(false); ui.importButton->setEnabled(false); ui.defineCooBox->setEnabled(true); ui.paramBox->setEnabled(true); ui.createEdit->setEnabled(true); ui.createButton->setEnabled(true); ui.okButton->setEnabled(validDataFile); } void NewGrid::on_importButton_clicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open grid file"), ui.importEdit->text(), tr("Surfer grid (*.grd)")); if (!fileName.isEmpty()) { validGridFile = true; ui.okButton->setEnabled(true); ui.importEdit->setText(fileName); } } void NewGrid::on_createButton_clicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open dat-file"), ui.createEdit->text(), tr("Data files (*.dat);;All files(*)")); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); QString line = in.readLine(); QStringList headlist = line.split(" "); if (headlist.size()>1) { if (validDataFile) { disconnect(ui.xCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboChanged())); disconnect(ui.yCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboChanged())); disconnect(ui.minXEdit, SIGNAL(textEdited(QString)), this, SLOT(defineXCellSize())); disconnect(ui.maxXEdit, SIGNAL(textEdited(QString)), this, SLOT(defineXCellSize())); disconnect(ui.minYEdit, SIGNAL(textEdited(QString)), this, SLOT(defineYCellSize())); disconnect(ui.maxYEdit, SIGNAL(textEdited(QString)), this, SLOT(defineYCellSize())); disconnect(ui.xSizeEdit, SIGNAL(textEdited(QString)), this, SLOT(onXSizeEdited())); disconnect(ui.ySizeEdit, SIGNAL(textEdited(QString)), this, SLOT(onYSizeEdited())); disconnect(ui.xSizeEdit, SIGNAL(editingFinished()), this, SLOT(finishedXCellSize())); disconnect(ui.ySizeEdit, SIGNAL(editingFinished()), this, SLOT(finishedYCellSize())); disconnect(ui.numXSpin, SIGNAL(valueChanged(int)), this, SLOT(defineXCellSize())); disconnect(ui.numYSpin, SIGNAL(valueChanged(int)), this, SLOT(defineYCellSize())); } validDataFile = true; ui.createEdit->setText(fileName); limits.clear(); dataTable.clear(); vector <double> headline; QString letters[16]={"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"} ; ui.xCombo->clear(); ui.yCombo->clear(); ui.zCombo->clear(); ui.okButton->setEnabled(true); int isHeadline=0; minmax minmaxBuf; for (int i = 0; i < headlist.size(); ++i) { limits.push_back(minmaxBuf); headlist[i].replace(" ",""); bool ok; headline.push_back(headlist.at(i).toDouble(&ok)); if (!ok) { ui.xCombo->addItem(tr("Column ")+letters[i]+": "+headlist.at(i)); ui.yCombo->addItem(tr("Column ")+letters[i]+": "+headlist.at(i)); ui.zCombo->addItem(tr("Column ")+letters[i]+": "+headlist.at(i)); isHeadline--; } else { ui.xCombo->addItem(tr("Column ")+letters[i]); ui.yCombo->addItem(tr("Column ")+letters[i]); ui.zCombo->addItem(tr("Column ")+letters[i]); } } int iterForMinMax = 0; if (isHeadline>=-2) { dataTable.push_back(headline); iterForMinMax++; for (int i = 0; i < headlist.size(); ++i) { limits[i].min = headline[i]; limits[i].max = headline[i]; } } while (!in.atEnd()) { iterForMinMax++; line = in.readLine(); QStringList list = line.split(" "); vector <double> dataline; bool ok; while (limits.size()<list.size()) limits.push_back(minmaxBuf); for (int i = 0; i < list.size(); i++) { list[i].replace(" ",""); dataline.push_back(list.at(i).toDouble(&ok)); if (iterForMinMax==1) { limits[i].min = dataline[i]; limits[i].max = dataline[i]; } else MinMax(dataline[i], limits[i].min, limits[i].max); } dataTable.push_back(dataline); } connect(ui.xCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboChanged())); connect(ui.yCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboChanged())); connect(ui.minXEdit, SIGNAL(textEdited(QString)), this, SLOT(defineXCellSize())); connect(ui.maxXEdit, SIGNAL(textEdited(QString)), this, SLOT(defineXCellSize())); connect(ui.minYEdit, SIGNAL(textEdited(QString)), this, SLOT(defineYCellSize())); connect(ui.maxYEdit, SIGNAL(textEdited(QString)), this, SLOT(defineYCellSize())); connect(ui.xSizeEdit, SIGNAL(textEdited(QString)), this, SLOT(onXSizeEdited())); connect(ui.ySizeEdit, SIGNAL(textEdited(QString)), this, SLOT(onYSizeEdited())); connect(ui.xSizeEdit, SIGNAL(editingFinished()), this, SLOT(finishedXCellSize())); connect(ui.ySizeEdit, SIGNAL(editingFinished()), this, SLOT(finishedYCellSize())); connect(ui.numXSpin, SIGNAL(valueChanged(int)), this, SLOT(defineXCellSize())); connect(ui.numYSpin, SIGNAL(valueChanged(int)), this, SLOT(defineYCellSize())); ui.yCombo->setCurrentIndex(1); ui.zCombo->setCurrentIndex(2); ui.numXSpin->setMinimum(1); ui.numYSpin->setMinimum(1); } else { QMessageBox msgBox(QMessageBox::Warning, tr("Error"), tr("Wrong file format!"), 0, this); msgBox.addButton(tr("Ok"), QMessageBox::AcceptRole); if (msgBox.exec() == QMessageBox::AcceptRole); } } void NewGrid::onComboChanged() { int fieldX = ui.xCombo->currentIndex(); int fieldY = ui.yCombo->currentIndex(); minX = limits[fieldX].min; maxX = limits[fieldX].max; minY = limits[fieldY].min; maxY = limits[fieldY].max; QString str; str.setNum(minX); ui.minXEdit->setText(str); str.setNum(maxX); ui.maxXEdit->setText(str); str.setNum(minY); ui.minYEdit->setText(str); str.setNum(maxY); ui.maxYEdit->setText(str); if ((maxX-minX)>(maxY-minY)) { ui.numXSpin->setValue(defaultCellNumber); ui.numYSpin->setValue(round((maxY-minY)/(maxX-minX)*defaultCellNumber)); } else { ui.numXSpin->setValue(round((maxX-minX)/(maxY-minY)*defaultCellNumber)); ui.numYSpin->setValue(defaultCellNumber); } defineXCellSize(); defineYCellSize(); } void NewGrid::defineXCellSize() { if (!xSizeEditing) { minX = ui.minXEdit->text().toDouble(); maxX = ui.maxXEdit->text().toDouble(); numX = ui.numXSpin->value(); QString str; str.setNum((maxX-minX)/(numX-1)); ui.xSizeEdit->setText(str); } } void NewGrid::defineYCellSize() { if (!ySizeEditing) { minY = ui.minYEdit->text().toDouble(); maxY = ui.maxYEdit->text().toDouble(); numY = ui.numYSpin->value(); QString str; str.setNum((maxY-minY)/(numY-1)); ui.ySizeEdit->setText(str); } } void NewGrid::onXSizeEdited() { xSizeEditing = true; xSize = ui.xSizeEdit->text().toDouble(); minX = ui.minXEdit->text().toDouble(); maxX = ui.maxXEdit->text().toDouble(); ui.numXSpin->setValue(round((maxX-minX)/xSize)+1); } void NewGrid::onYSizeEdited() { ySizeEditing = true; ySize = ui.ySizeEdit->text().toDouble(); minY = ui.minYEdit->text().toDouble(); maxY = ui.maxYEdit->text().toDouble(); ui.numYSpin->setValue(round((maxY-minY)/ySize)+1); } void NewGrid::finishedXCellSize() { xSizeEditing = false; defineXCellSize(); } void NewGrid::finishedYCellSize() { ySizeEditing = false; defineYCellSize(); } void NewGrid::onAccepted() { import = ui.radioImport->isChecked(); create = ui.radioCreate->isChecked(); if (import) { fileName = ui.importEdit->text(); invert = invertQuestion(); } else if (create) { int fieldX = ui.xCombo->currentIndex(); int fieldY = ui.yCombo->currentIndex(); int fieldZ = ui.zCombo->currentIndex(); finishedXCellSize(); finishedYCellSize(); createParams.objectName = ui.createEdit->text(); createParams.xSize = ui.xSizeEdit->text().toDouble(); createParams.ySize = ui.ySizeEdit->text().toDouble(); createParams.minX = minX; createParams.minY = minY; createParams.numX = numX; createParams.numY = numY; int kInvert; if (invertQuestion()) kInvert=-1; else kInvert=1; for (int i=0; i<dataTable.size(); i++) sourcePoints.push_back(MPoint(dataTable[i][fieldX], dataTable[i][fieldY], kInvert*dataTable[i][fieldZ])); } } bool NewGrid::invertQuestion() { QString message= tr("<p>The file, probably, contains positive z coordinates" \ "<p>Do you wish to change the values to negatives?"); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("QMessageBox::question()"), message, QMessageBox::Yes | QMessageBox::No ); if (reply == QMessageBox::Yes) return true; else return false; }
[ "e.insafutdinov@aa633bd7-114a-0410-8488-2d504122b2f1" ]
[ [ [ 1, 334 ] ] ]
4513cff738ed60e44aab71e9f843d5053cc81bab
6712f8313dd77ae820aaf400a5836a36af003075
/testBaud.cpp
621f490c32af3f06cbace46fb51fcb372ac521f6
[]
no_license
AdamTT1/bdScript
d83c7c63c2c992e516dca118cfeb34af65955c14
5483f239935ec02ad082666021077cbc74d1790c
refs/heads/master
2021-12-02T22:57:35.846198
2010-08-08T22:32:02
2010-08-08T22:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,890
cpp
/* * rtsCTS.cpp * * This program will test the ability to get the state of the * CTS pin, toggle the RTS pin, and spew data over a serial port. * */ #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <termios.h> #include <sys/ioctl.h> #include <signal.h> #include <sys/poll.h> #include <ctype.h> #include "baudRate.h" #include <stdlib.h> #include <linux/serial.h> #include "physMem.h" #include <string.h> static bool volatile doExit = false ; static void ctrlcHandler( int signo ) { printf( "<ctrl-c>\r\n" ); doExit = true ; } static void toggleRTS( int fdSerial ) { int line ; if( 0 == ioctl(fdSerial, TIOCMGET, &line) ) { line ^= TIOCM_RTS ; if( 0 == ioctl(fdSerial, TIOCMSET, &line) ) { printf( "toggled\r\n" ); } else perror( "TIOCMGET" ); } else perror( "TIOCMGET" ); } static void setRaw( int fd, int baud, int databits, char parity, unsigned stopBits, struct termios &oldState ) { tcgetattr(fd,&oldState); /* set raw mode for keyboard input */ struct termios newState = oldState; newState.c_cc[VMIN] = 1; bool nonStandard = false ; unsigned baudConst ; if( baudRateToConst( baud, baudConst ) ){ cfsetispeed(&newState, baudConst); cfsetospeed(&newState, baudConst); } else { cfsetispeed(&newState,B38400); cfsetospeed(&newState,B38400); fprintf( stderr, "Non-standard baud <%u>, old constant %u\n", baud, cfgetispeed(&newState) ); bool worked = false ; struct serial_struct nuts; int rval = ioctl(fd, TIOCGSERIAL, &nuts); if( 0 == rval ){ unsigned const divisor = nuts.baud_base / baud ; nuts.custom_divisor = divisor ; printf( "custom divisor %lu (baud base %u)\n", nuts.custom_divisor, nuts.baud_base ); nuts.flags &= ~ASYNC_SPD_MASK; nuts.flags |= ASYNC_SPD_CUST; rval = ioctl(fd, TIOCSSERIAL, &nuts); if( 0 == rval ){ printf( "baud changed\n" ); rval = ioctl(fd, TIOCGSERIAL, &nuts); if( 0 == rval ){ printf( "divisor is now %u\n", nuts.custom_divisor ); worked = (nuts.custom_divisor == divisor); if( worked ){ physMem_t pm( 0x01c20000, 0x1000, O_RDWR ); unsigned long div0 ; memcpy(&div0, (char const *)pm.ptr() + 0x820, sizeof(div0) ); unsigned long div1 ; memcpy(&div1, (char const *)pm.ptr() + 0x824, sizeof(div1) ); printf( "divisors: 0x%08lx, 0x%08lx\n", div0, div1 ); nonStandard = true ; } } else perror( "TIOCGSERIAL2" ); } else perror( "TIOCSSERIAL" ); } else perror( "TIOCGSERIAL" ); } // non-standard serial // // Note that this doesn't appear to work! // Reads always seem to be terminated at 16 chars! // newState.c_cc[VTIME] = 0; // 1/10th's of a second, see http://www.opengroup.org/onlinepubs/007908799/xbd/termios.html newState.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS); // Mask character size to 8 bits, no parity, Disable hardware flow control if( 'E' == parity ) { newState.c_cflag |= PARENB ; newState.c_cflag &= ~PARODD ; } else if( 'O' == parity ) { newState.c_cflag |= PARENB | PARODD ; } else if( 'S' == parity ) { newState.c_cflag |= PARENB | IGNPAR | CMSPAR ; newState.c_cflag &= ~PARODD ; } else if( 'M' == parity ) { newState.c_cflag |= PARENB | IGNPAR | CMSPAR | PARODD ; } else { } // no parity... already set newState.c_cflag |= (CLOCAL | CREAD |CS8); // Select 8 data bits if( 7 == databits ){ newState.c_cflag &= ~CS8 ; } if( 1 != stopBits ) newState.c_cflag |= CSTOPB ; newState.c_lflag &= ~(ICANON | ECHO ); // set raw mode for input newState.c_iflag &= ~(IXON | IXOFF | IXANY|INLCR|ICRNL|IUCLC); //no software flow control newState.c_oflag &= ~OPOST; //raw output tcsetattr( fd, TCSANOW, &newState ); if( nonStandard ){ physMem_t pm( 0x01c20000, 0x1000, O_RDWR ); unsigned long div0 ; memcpy(&div0, (char const *)pm.ptr() + 0x820, sizeof(div0) ); unsigned long div1 ; memcpy(&div1, (char const *)pm.ptr() + 0x824, sizeof(div1) ); printf( "divisors now: 0x%08lx, 0x%08lx\n", div0, div1 ); } } static void showStatus( int fd ) { int line ; if( 0 == ioctl(fd, TIOCMGET, &line) ) { printf( "line status 0x%04x: ", line ); if( line & TIOCM_CTS ) printf( "CTS " ); else printf( "~CTS " ); if( line & TIOCM_RTS ) printf( "RTS " ); else printf( "~RTS " ); printf( "\r\n" ); } else perror( "TIOCMGET" ); } static void waitModemChange( int fd ) { printf( "wait modem status..." ); fflush(stdout); int line = TIOCM_RNG | TIOCM_DSR | TIOCM_CTS | TIOCM_CD ; int result = ioctl(fd, TIOCMIWAIT, &line); printf( "\r\n" ); if( 0 == result ){ printf( "changed\r\n" ); showStatus(fd); } else perror( "TIOCMWAIT" ); } static char const spewOutput[] = { "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890\r\n" }; int main( int argc, char const * const argv[] ) { if( 2 < argc ) { char const *const deviceName = argv[1]; int const fdSerial = open( deviceName, O_RDWR ); if( 0 <= fdSerial ) { fcntl( fdSerial, F_SETFD, FD_CLOEXEC ); fcntl( fdSerial, F_SETFL, O_NONBLOCK ); int baud = strtoul( argv[2], 0, 0 ); int databits = ( ( 3 < argc ) && ( 7 == strtoul( argv[3], 0, 0 ) ) ) ? 7 : 8 ; char parity = ( 4 < argc ) ? toupper( *argv[4] ) : 'N' ; unsigned stopBits = ( ( 5 < argc ) && ( '2' == *argv[5] ) ) ? 2 : 1 ; printf( "device %s opened\n", deviceName ); struct termios oldSerialState; setRaw( fdSerial, baud, databits, parity, stopBits, oldSerialState); struct termios oldStdinState; showStatus(fdSerial); signal( SIGINT, ctrlcHandler ); pollfd fds[2]; fds[0].fd = fdSerial ; fds[0].events = POLLIN | POLLERR ; fds[1].fd = fileno(stdin); fds[1].events = POLLIN | POLLERR ; unsigned prevChars = 0 ; while( !doExit ) { int const numReady = ::poll( fds, 2, 10 ); if( 0 < numReady ) { for( unsigned i = 0 ; i < 2 ; i++ ) { if( fds[i].revents & POLLIN ) { char inBuf[80]; int numRead = read( fds[i].fd, inBuf, sizeof(inBuf) ); prevChars += numRead ; } } } else if( prevChars ){ printf( "%u\n", prevChars ); prevChars = 0 ; fflush(stdout); } } tcsetattr( fdSerial, TCSANOW, &oldSerialState ); close( fdSerial ); } else perror( deviceName ); } else fprintf( stderr, "Usage: setBaud /dev/ttyS0 baudRate\n" ); return 0 ; }
[ "ericn" ]
[ [ [ 1, 267 ] ] ]
4957c075f7d6a70543387de629d0f91d33d99891
5139374516102fade66e197acf4326157bbbab0c
/src/SoundManager.cpp
741cf6298da195a6c3cca66a89165e8ec135abf7
[]
no_license
DaHoC/ogrefps
0b123e06a0ad8507a1aaa758cd75cbf73318477a
6dbc32569383fc4678cbb36ba5fc5800f1a63b70
refs/heads/master
2016-09-06T07:42:12.306750
2011-01-02T21:18:01
2011-01-02T21:18:01
1,120,251
0
0
null
null
null
null
UTF-8
C++
false
false
18,089
cpp
#include "SoundManager.h" #include <fmod_errors.h> #define INITIAL_VECTOR_SIZE 100 #define INCREASE_VECTOR_SIZE 20 #define DOPPLER_SCALE 1.0 #define DISTANCE_FACTOR 1.0 #define ROLLOFF_SCALE 0.5 template<> SoundManager* Singleton<SoundManager>::ms_Singleton = 0; void SoundInstance::Clear(void) { fileName.clear(); streamPtr.setNull(); fileArchive = NULL; fmodSound = NULL; soundType = SOUND_TYPE_INVALID; } void ChannelInstance::Clear(void) { sceneNode = NULL; prevPosition = Ogre::Vector3(0, 0, 0); } class FileLocator : public ResourceGroupManager { public: FileLocator() { } ~FileLocator() { } Archive *Find(String &filename) { ResourceGroup* grp = getResourceGroup("General"); if (!grp) OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate a resource group called 'General'", "ResourceGroupManager::openResource"); OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME) // lock group mutex ResourceLocationIndex::iterator rit = grp->resourceIndexCaseSensitive.find(filename); if (rit != grp->resourceIndexCaseSensitive.end()) { // Found in the index Archive *fileArchive = rit->second; filename = fileArchive->getName() + "/" + filename; return fileArchive; } return NULL; } }; SoundManager::SoundManager() { system = NULL; prevListenerPosition = Vector3(0, 0, 0); soundInstanceVector = new SoundInstanceVector; // Initialized to zero, but pre-incremented in GetNextSoundInstanceIndex(), so vector starts at one. nextSoundInstanceIndex = 0; // Start off with INITIAL_VECTOR_SIZE soundInstanceVectors. It can grow from here. soundInstanceVector->resize(INITIAL_VECTOR_SIZE); for (int vectorIndex = 0; vectorIndex < INITIAL_VECTOR_SIZE; vectorIndex++) { soundInstanceVector->at(vectorIndex) = new SoundInstance; soundInstanceVector->at(vectorIndex)->Clear(); } for (int channelIndex = 0; channelIndex < MAX_SOUND_CHANNELS; channelIndex++) channelArray[channelIndex].Clear(); } SoundManager::~SoundManager() { for (int vectorIndex = 0; vectorIndex < (int) soundInstanceVector->capacity(); vectorIndex++) { soundInstanceVector->at(vectorIndex)->fileName.clear(); // soundInstanceVector->at(vectorIndex)->streamPtr->close(); delete soundInstanceVector->at(vectorIndex); } delete soundInstanceVector; if (system) system->release(); } void SoundManager::Initialize(void) { FMOD_RESULT result; // Create the main system object. result = FMOD::System_Create(&system); if (result != FMOD_OK) OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "FMOD error! (" + StringConverter::toString(result) + "): " + FMOD_ErrorString(result), "SoundManager::Initialize"); result = system->init(MAX_SOUND_CHANNELS, FMOD_INIT_NORMAL, 0); // Initialize FMOD. if (result != FMOD_OK) OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "FMOD error! (" + StringConverter::toString(result) + "): " + FMOD_ErrorString(result), "SoundManager::Initialize"); system->set3DSettings(DOPPLER_SCALE, DISTANCE_FACTOR, ROLLOFF_SCALE); // result = system->setFileSystem(&fmodFileOpenCallback, &fmodFileCloseCallback, &fmodFileReadCallback, &fmodFileSeekCallback, &fmodFileAsyncReadCallback, &fmodFileAsyncCancelCallback, 2048); if (result != FMOD_OK) OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "FMOD error! (" + StringConverter::toString(result) + "): " + FMOD_ErrorString(result), "SoundManager::Initialize"); Ogre::LogManager::getSingleton().logMessage("SoundManager Initialized"); } SoundManager* SoundManager::getSingletonPtr(void) { return ms_Singleton; } SoundManager& SoundManager::getSingleton(void) { assert(ms_Singleton); return ( *ms_Singleton); } void SoundManager::FrameStarted(Ogre::SceneNode *listenerNode, Ogre::Real timeElapsed) { int channelIndex; FMOD::Channel *nextChannel; FMOD_VECTOR listenerPosition; FMOD_VECTOR listenerForward; FMOD_VECTOR listenerUp; FMOD_VECTOR listenerVelocity; Ogre::Vector3 vectorVelocity; Ogre::Vector3 vectorForward; Ogre::Vector3 vectorUp; if (timeElapsed > 0) vectorVelocity = (listenerNode->getPosition() - prevListenerPosition) / timeElapsed; else vectorVelocity = Vector3(0, 0, 0); vectorForward = listenerNode->getOrientation().zAxis(); vectorForward.normalise(); vectorUp = listenerNode->getOrientation().yAxis(); vectorUp.normalise(); listenerPosition.x = listenerNode->getPosition().x; listenerPosition.y = listenerNode->getPosition().y; listenerPosition.z = listenerNode->getPosition().z; listenerForward.x = vectorForward.x; listenerForward.y = vectorForward.y; listenerForward.z = vectorForward.z; listenerUp.x = vectorUp.x; listenerUp.y = vectorUp.y; listenerUp.z = vectorUp.z; listenerVelocity.x = vectorVelocity.x; listenerVelocity.y = vectorVelocity.y; listenerVelocity.z = vectorVelocity.z; // update 'ears' system->set3DListenerAttributes(0, &listenerPosition, &listenerVelocity, &listenerForward, &listenerUp); system->update(); prevListenerPosition = listenerNode->getPosition(); for (channelIndex = 0; channelIndex < MAX_SOUND_CHANNELS; channelIndex++) { if (channelArray[channelIndex].sceneNode != NULL) { system->getChannel(channelIndex, &nextChannel); if (timeElapsed > 0) vectorVelocity = (channelArray[channelIndex].sceneNode->getPosition() - channelArray[channelIndex].prevPosition) / timeElapsed; else vectorVelocity = Vector3(0, 0, 0); listenerPosition.x = channelArray[channelIndex].sceneNode->getPosition().x; listenerPosition.y = channelArray[channelIndex].sceneNode->getPosition().y; listenerPosition.z = channelArray[channelIndex].sceneNode->getPosition().z; listenerVelocity.x = vectorVelocity.x; listenerVelocity.y = vectorVelocity.y; listenerVelocity.z = vectorVelocity.z; nextChannel->set3DAttributes(&listenerPosition, &listenerVelocity); channelArray[channelIndex].prevPosition = channelArray[channelIndex].sceneNode->getPosition(); } } } int SoundManager::CreateStream(String &fileName) { return CreateSound(fileName, SOUND_TYPE_2D_SOUND); } int SoundManager::CreateSound(String &fileName) { return CreateSound(fileName, SOUND_TYPE_3D_SOUND); } int SoundManager::CreateLoopedSound(String &fileName) { return CreateSound(fileName, SOUND_TYPE_3D_SOUND_LOOPED); } int SoundManager::CreateLoopedStream(String &fileName) { return CreateSound(fileName, SOUND_TYPE_2D_SOUND_LOOPED); } // fileName is actually a pointer to a SoundInstance, passed in from CreateSound(). FMOD_RESULT SoundManager::fmodFileOpenCallback(const char *fileName, int unicode, unsigned int *filesize, void **handle, void **userdata) { SoundInstance *soundInstance; assert(fileName); soundInstance = (SoundInstance *) fileName; assert(soundInstance->fileArchive); *handle = (void *) soundInstance; *userdata = NULL; soundInstance->streamPtr = soundInstance->fileArchive->open(soundInstance->fileName); if (soundInstance->streamPtr.isNull()) { *filesize = 0; return FMOD_ERR_FILE_NOTFOUND; } *filesize = (unsigned int) soundInstance->streamPtr->size(); return FMOD_OK; } FMOD_RESULT SoundManager::fmodFileCloseCallback(void *handle, void *userdata) { return FMOD_OK; } FMOD_RESULT SoundManager::fmodFileReadCallback(void *handle, void *buffer, unsigned int sizeBytes, unsigned int *bytesRead, void *userData) { SoundInstance *soundInstance; soundInstance = (SoundInstance *) handle; *bytesRead = (unsigned int) soundInstance->streamPtr->read(buffer, (size_t) sizeBytes); if (*bytesRead == 0) return FMOD_ERR_FILE_EOF; return FMOD_OK; } FMOD_RESULT SoundManager::fmodFileSeekCallback(void *handle, unsigned int pos, void *userdata) { SoundInstance *soundInstance; soundInstance = (SoundInstance *) handle; soundInstance->streamPtr->seek((size_t) pos); return FMOD_OK; } int SoundManager::CreateSound(String &fileName, SOUND_TYPE soundType) { Archive * fileArchive; FMOD_RESULT result; FMOD::Sound * sound; String fullPathName; SoundInstance *newSoundInstance; int soundIndex; soundIndex = FindSound(fileName, soundType); if (soundIndex != INVALID_SOUND_INDEX) return soundIndex; fullPathName = fileName; FileLocator * fileLocator = (FileLocator *) ResourceGroupManager::getSingletonPtr(); fileArchive = fileLocator->Find(fullPathName); if (!fileArchive) { Ogre::LogManager::getSingleton().logMessage("SoundManager::CreateSound could not find sound '" + fileName + "'"); return INVALID_SOUND_INDEX; } IncrementNextSoundInstanceIndex(); newSoundInstance = soundInstanceVector->at(nextSoundInstanceIndex); newSoundInstance->fileName = fileName; newSoundInstance->fileArchive = fileArchive; newSoundInstance->soundType = soundType; switch (soundType) { case SOUND_TYPE_3D_SOUND: { result = system->createSound((const char *) newSoundInstance, FMOD_3D | FMOD_HARDWARE, 0, &sound); break; } case SOUND_TYPE_3D_SOUND_LOOPED: { result = system->createSound((const char *) newSoundInstance, FMOD_LOOP_NORMAL | FMOD_3D | FMOD_HARDWARE, 0, &sound); break; } case SOUND_TYPE_2D_SOUND: { result = system->createStream((const char *) newSoundInstance, FMOD_DEFAULT, 0, &sound); break; } case SOUND_TYPE_2D_SOUND_LOOPED: { result = system->createStream((const char *) newSoundInstance, FMOD_LOOP_NORMAL | FMOD_2D | FMOD_HARDWARE, 0, &sound); break; } default: { Ogre::LogManager::getSingleton().logMessage("SoundManager::CreateSound could not load sound '" + fileName + "' (invalid soundType)"); return INVALID_SOUND_INDEX; } } if (result != FMOD_OK) { Ogre::LogManager::getSingleton().logMessage("SoundManager::CreateSound could not load sound '" + fileName + "' FMOD Error:" + FMOD_ErrorString(result)); return INVALID_SOUND_INDEX; } newSoundInstance->fmodSound = sound; return nextSoundInstanceIndex; } void SoundManager::IncrementNextSoundInstanceIndex(void) { int oldVectorCapacity; oldVectorCapacity = (int) soundInstanceVector->capacity(); nextSoundInstanceIndex += 1; if (nextSoundInstanceIndex < oldVectorCapacity) return; int vectorIndex; SoundInstanceVector *newSoundInstanceVector; // Create a new, larger SoundInstanceVector newSoundInstanceVector = new SoundInstanceVector; newSoundInstanceVector->resize(oldVectorCapacity + INCREASE_VECTOR_SIZE); // Check Ogre.log for these messages, and change INITIAL_VECTOR_SIZE to be a more appropriate value Ogre::LogManager::getSingleton().logMessage("SoundManager::IncrementNextSoundInstanceIndex increasing size of soundInstanceVector to " + StringConverter::toString(oldVectorCapacity + INCREASE_VECTOR_SIZE)); // Copy values from old vector to new for (vectorIndex = 0; vectorIndex < oldVectorCapacity; vectorIndex++) newSoundInstanceVector->at(vectorIndex) = soundInstanceVector->at(vectorIndex); int newVectorCapacity; newVectorCapacity = (int) newSoundInstanceVector->capacity(); // Clear out the rest of the new vector while (vectorIndex < newVectorCapacity) { newSoundInstanceVector->at(vectorIndex) = new SoundInstance; newSoundInstanceVector->at(vectorIndex)->Clear(); vectorIndex++; } // Clear out the old vector and point to the new one. soundInstanceVector->clear(); delete(soundInstanceVector); soundInstanceVector = newSoundInstanceVector; } void SoundManager::PlaySound(int soundIndex, SceneNode *soundNode, int *channelIndex) { int channelIndexTemp; FMOD_RESULT result; FMOD_VECTOR initialPosition; FMOD::Channel *channel; SoundInstance *soundInstance; if (soundIndex == INVALID_SOUND_INDEX) return; if (channelIndex) channelIndexTemp = *channelIndex; else channelIndexTemp = INVALID_SOUND_CHANNEL; assert((soundIndex > 0) && (soundIndex < (int) soundInstanceVector->capacity())); // If the channelIndex already has a sound assigned to it, test if it's the same sceneNode. if ((channelIndexTemp != INVALID_SOUND_CHANNEL) && (channelArray[channelIndexTemp].sceneNode != NULL)) { result = system->getChannel(channelIndexTemp, &channel); if (result == FMOD_OK) { bool isPlaying; result = channel->isPlaying(&isPlaying); if ((result == FMOD_OK) && (isPlaying == true) && (channelArray[channelIndexTemp].sceneNode == soundNode)) return; // Already playing this sound attached to this node. } } soundInstance = soundInstanceVector->at(soundIndex); // Start the sound paused result = system->playSound(FMOD_CHANNEL_FREE, soundInstance->fmodSound, true, &channel); if (result != FMOD_OK) { Ogre::LogManager::getSingleton().logMessage(String("SoundManager::PlaySound could not play sound FMOD Error:") + FMOD_ErrorString(result)); if (channelIndex) *channelIndex = INVALID_SOUND_CHANNEL; return; } channel->getIndex(&channelIndexTemp); channelArray[channelIndexTemp].sceneNode = soundNode; if (soundNode) { channelArray[channelIndexTemp].prevPosition = soundNode->getPosition(); initialPosition.x = soundNode->getPosition().x; initialPosition.y = soundNode->getPosition().y; initialPosition.z = soundNode->getPosition().z; channel->set3DAttributes(&initialPosition, NULL); } result = channel->setVolume(1.0); // This is where the sound really starts. result = channel->setPaused(false); if (channelIndex) *channelIndex = channelIndexTemp; } SoundInstance *SoundManager::GetSoundInstance(int soundIndex) { return soundInstanceVector->at(soundIndex); } FMOD::Channel *SoundManager::GetSoundChannel(int channelIndex) { if (channelIndex == INVALID_SOUND_CHANNEL) return NULL; FMOD::Channel *soundChannel; assert((channelIndex > 0) && (channelIndex < MAX_SOUND_CHANNELS)); system->getChannel(channelIndex, &soundChannel); return soundChannel; } void SoundManager::Set3DMinMaxDistance(int channelIndex, float minDistance, float maxDistance) { FMOD_RESULT result; FMOD::Channel *channel; if (channelIndex == INVALID_SOUND_CHANNEL) return; result = system->getChannel(channelIndex, &channel); if (result == FMOD_OK) channel->set3DMinMaxDistance(minDistance, maxDistance); } void SoundManager::StopAllSounds(void) { int channelIndex; FMOD_RESULT result; FMOD::Channel *nextChannel; for (channelIndex = 0; channelIndex < MAX_SOUND_CHANNELS; channelIndex++) { result = system->getChannel(channelIndex, &nextChannel); if ((result == FMOD_OK) && (nextChannel != NULL)) nextChannel->stop(); channelArray[channelIndex].Clear(); } } void SoundManager::StopSound(int *channelIndex) { if (*channelIndex == INVALID_SOUND_CHANNEL) return; FMOD::Channel *soundChannel; assert((*channelIndex > 0) && (*channelIndex < MAX_SOUND_CHANNELS)); system->getChannel(*channelIndex, &soundChannel); soundChannel->stop(); channelArray[*channelIndex].Clear(); *channelIndex = INVALID_SOUND_CHANNEL; } int SoundManager::FindSound(String &fileName, SOUND_TYPE soundType) { int vectorIndex; int vectorCapacity; SoundInstance *nextSoundInstance; vectorCapacity = (int) soundInstanceVector->capacity(); for (vectorIndex = 0; vectorIndex < vectorCapacity; vectorIndex++) { nextSoundInstance = soundInstanceVector->at(vectorIndex); if ((soundType == nextSoundInstance->soundType) && (fileName == nextSoundInstance->fileName)) // if ((soundType == nextSoundInstance->soundType) && (fileName == nextSoundInstance->fileArchive->getName())) return vectorIndex; } return INVALID_SOUND_INDEX; } float SoundManager::GetSoundLength(int soundIndex) { if (soundIndex == INVALID_SOUND_INDEX) return 0.0; assert((soundIndex > 0) && (soundIndex < (int) soundInstanceVector->capacity())); unsigned int soundLength; // length in milliseconds FMOD_RESULT result; SoundInstance *soundInstance; soundInstance = soundInstanceVector->at(soundIndex); if (soundInstance) { result = soundInstance->fmodSound->getLength(&soundLength, FMOD_TIMEUNIT_MS); if (result != FMOD_OK) { Ogre::LogManager::getSingleton().logMessage(String("SoundManager::GetSoundLength could not get length FMOD Error:") + FMOD_ErrorString(result)); return 0.0; } } else { Ogre::LogManager::getSingleton().logMessage(String("SoundManager::GetSoundLength could not find soundInstance")); return 0.0; } return (float) soundLength / 1000.0f; }
[ [ [ 1, 501 ] ] ]
7fba44ff36071e194983d9e4e5234179b8c5cffe
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_events/messages/juce_MessageListener.cpp
afd7525afb0c14e8d9c7644fdee416a45bfb5deb
[]
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
2,243
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. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== MessageListener::MessageListener() noexcept { // are you trying to create a messagelistener before or after juce has been intialised?? jassert (MessageManager::instance != nullptr); if (MessageManager::instance != nullptr) MessageManager::instance->messageListeners.add (this); } MessageListener::~MessageListener() { if (MessageManager::instance != nullptr) MessageManager::instance->messageListeners.removeValue (this); } void MessageListener::postMessage (Message* const message) const { message->messageRecipient = const_cast <MessageListener*> (this); if (MessageManager::instance == nullptr) MessageManager::getInstance(); MessageManager::instance->postMessageToQueue (message); } bool MessageListener::isValidMessageListener() const noexcept { return MessageManager::instance != nullptr && MessageManager::instance->messageListeners.contains (this); } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 60 ] ] ]
c6dc43780fd872b9f132e7df4e79b36104880e72
e1f7c2f6dd66916fe5b562d9dd4c0a5925197ec4
/Engine/Project/include/AGUtilities.h
9d462009e64ffcd2baecb0a923c443d226405af9
[]
no_license
OtterOrder/agengineproject
de990ad91885b54a0c63adf66ff2ecc113e0109d
0b92a590af4142369e2946f692d5f30a06d32135
refs/heads/master
2020-05-27T07:44:25.593878
2011-05-01T14:52:05
2011-05-01T14:52:05
32,115,301
0
0
null
null
null
null
UTF-8
C++
false
false
2,631
h
#pragma once #include "AGTypes.h" //------------------------------------------------------------------------------------------------------------------------------ #define SAFE_DELETE(p) \ { \ if (p) \ { \ delete p; \ p = NULL; \ } \ } //------------------------------------------------------------------------------------------------------------------------------ #define SAFE_RELEASE(p) \ { \ if (p) \ { \ p->Release(); \ p = NULL; \ } \ } //------------------------------------------------------------------------------------------------------------------------------ #define SAFE_NEW(p, type) \ { \ if (!p) \ { \ p = new type; \ } \ } //------------------------------------------------------------------------------------------------------------------------------ #define SAFE_DECREF(p) \ { \ if (p) \ { \ p->DecRefCount(); \ p = NULL; \ } \ } //------------------------------------------------------------------------------------------------------------------------------ #include <vector> #include <map> #define DefineVectorIterator(type, name) typedef std::vector< type* >::iterator name #define DefineMapIterator(IdType, type, name) typedef std::map<IdType, type* >::iterator name //------------------------------------------------------------------------------------------------------------------------------ #ifdef UNICODE #undef UNICODE #endif void AGDebugPrint(cStr _str, ...); bool AGWarning(bool _test, cStr _str, ...); //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ class CRC { private: static u32 _mUlTable[256]; public: static void Initialize (void); static u32 GetCRC (cStr sData); private: static void PartialCRC (u32* ulCRC, cStr sData, u32 ulDataLength); static u32 Reflect (u32 ulReflect, const s8 cChar); }; //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ #define AGPi 3.1415926f #define AGMax(_A, _B) (((_A) > (_B)) ? (_A) : (_B)) #define AGMin(_A, _B) (((_A) < (_B)) ? (_A) : (_B)) #define AGClamp(_Min, _Max, _Value) (AGMax(AGMin(_Max, _Value), _Min))
[ "alban.chagnoleau@fe70d4ac-e33c-11de-8d18-5b59c22968bc" ]
[ [ [ 1, 82 ] ] ]
0cb51f11c4775de773f25b1bee250d5b238f9514
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/source_uri.inl
82e804d4361234fe716e45ceef9cebd4bdc1f6eb
[]
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
614
inl
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__SOURCE_URI_INL #define AOSLCPP_AOSL__SOURCE_URI_INL // Begin prologue. // // // End prologue. namespace aosl { // Source_uri // } // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__SOURCE_URI_INL
[ "klaim@localhost" ]
[ [ [ 1, 29 ] ] ]
9910ddd21c71d624d4a66a8141484b7919038963
508bfb3220be28811600a2cbf0aabae382f78775
/AcademicCrawler-sdk/Qt/Qt-4.6.2/include/Qt/qvarlengtharray.h
f62e506694c1616b03815ad4e4478b01d6de754c
[]
no_license
darkbtf/academic-crawler
295f3bd74b18e700402bc2be59f15694d6195471
5dfcb0f1b88b93aa7545ef233344a41570011532
refs/heads/master
2021-01-01T19:21:00.162442
2011-03-10T16:29:25
2011-03-10T16:29:25
42,468,175
0
0
null
null
null
null
UTF-8
C++
false
false
7,889
h
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtCore 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.1, 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 have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QVARLENGTHARRAY_H #define QVARLENGTHARRAY_H #include <QtCore/qcontainerfwd.h> #include <QtCore/qglobal.h> #include <new> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Core) template<class T, int Prealloc> class QPodList; // Prealloc = 256 by default, specified in qcontainerfwd.h template<class T, int Prealloc> class QVarLengthArray { public: inline explicit QVarLengthArray(int size = 0); inline QVarLengthArray(const QVarLengthArray<T, Prealloc> &other) : a(Prealloc), s(0), ptr(reinterpret_cast<T *>(array)) { append(other.constData(), other.size()); } inline ~QVarLengthArray() { if (QTypeInfo<T>::isComplex) { T *i = ptr + s; while (i-- != ptr) i->~T(); } if (ptr != reinterpret_cast<T *>(array)) qFree(ptr); } inline QVarLengthArray<T, Prealloc> &operator=(const QVarLengthArray<T, Prealloc> &other) { if (this != &other) { clear(); append(other.constData(), other.size()); } return *this; } inline void removeLast() { Q_ASSERT(s > 0); realloc(s - 1, a); } inline int size() const { return s; } inline int count() const { return s; } inline bool isEmpty() const { return (s == 0); } inline void resize(int size); inline void clear() { resize(0); } inline int capacity() const { return a; } inline void reserve(int size); inline T &operator[](int idx) { Q_ASSERT(idx >= 0 && idx < s); return ptr[idx]; } inline const T &operator[](int idx) const { Q_ASSERT(idx >= 0 && idx < s); return ptr[idx]; } inline void append(const T &t) { if (s == a) // i.e. s != 0 realloc(s, s<<1); const int idx = s++; if (QTypeInfo<T>::isComplex) { new (ptr + idx) T(t); } else { ptr[idx] = t; } } void append(const T *buf, int size); inline T *data() { return ptr; } inline const T *data() const { return ptr; } inline const T * constData() const { return ptr; } private: friend class QPodList<T, Prealloc>; void realloc(int size, int alloc); int a; int s; T *ptr; union { // ### Qt 5: Use 'Prealloc * sizeof(T)' as array size char array[sizeof(qint64) * (((Prealloc * sizeof(T)) / sizeof(qint64)) + 1)]; qint64 q_for_alignment_1; double q_for_alignment_2; }; }; template <class T, int Prealloc> Q_INLINE_TEMPLATE QVarLengthArray<T, Prealloc>::QVarLengthArray(int asize) : s(asize) { if (s > Prealloc) { ptr = reinterpret_cast<T *>(qMalloc(s * sizeof(T))); Q_CHECK_PTR(ptr); a = s; } else { ptr = reinterpret_cast<T *>(array); a = Prealloc; } if (QTypeInfo<T>::isComplex) { T *i = ptr + s; while (i != ptr) new (--i) T; } } template <class T, int Prealloc> Q_INLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::resize(int asize) { realloc(asize, qMax(asize, a)); } template <class T, int Prealloc> Q_INLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::reserve(int asize) { if (asize > a) realloc(s, asize); } template <class T, int Prealloc> Q_OUTOFLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::append(const T *abuf, int increment) { Q_ASSERT(abuf); if (increment <= 0) return; const int asize = s + increment; if (asize >= a) realloc(s, qMax(s*2, asize)); if (QTypeInfo<T>::isComplex) { // call constructor for new objects (which can throw) while (s < asize) new (ptr+(s++)) T(*abuf++); } else { qMemCopy(&ptr[s], abuf, increment * sizeof(T)); s = asize; } } template <class T, int Prealloc> Q_OUTOFLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::realloc(int asize, int aalloc) { Q_ASSERT(aalloc >= asize); T *oldPtr = ptr; int osize = s; // s = asize; if (aalloc != a) { ptr = reinterpret_cast<T *>(qMalloc(aalloc * sizeof(T))); Q_CHECK_PTR(ptr); if (ptr) { s = 0; a = aalloc; if (QTypeInfo<T>::isStatic) { QT_TRY { // copy all the old elements const int copySize = qMin(asize, osize); while (s < copySize) { new (ptr+s) T(*(oldPtr+s)); (oldPtr+s)->~T(); s++; } } QT_CATCH(...) { // clean up all the old objects and then free the old ptr int sClean = s; while (sClean < osize) (oldPtr+(sClean++))->~T(); if (oldPtr != reinterpret_cast<T *>(array) && oldPtr != ptr) qFree(oldPtr); QT_RETHROW; } } else { qMemCopy(ptr, oldPtr, qMin(asize, osize) * sizeof(T)); s = asize; } } else { ptr = oldPtr; return; } } if (QTypeInfo<T>::isComplex) { while (osize > asize) (oldPtr+(--osize))->~T(); if( oldPtr == ptr ) s = osize; } if (oldPtr != reinterpret_cast<T *>(array) && oldPtr != ptr) qFree(oldPtr); if (QTypeInfo<T>::isComplex) { // call default constructor for new objects (which can throw) while (s < asize) new (ptr+(s++)) T; } else { s = asize; } } QT_END_NAMESPACE QT_END_HEADER #endif // QVARLENGTHARRAY_H
[ "ulmonkey1987@7c5ce3f8-edad-37de-be84-b98c484540b5" ]
[ [ [ 1, 256 ] ] ]
b872aa7d752fc45350b773732a299f52af3772ee
7c51155f60ff037d1b8d6eea1797c7d17e1d95c2
/Demo/Loader.cpp
59d97067e446830c9a6845584860615d4a6ce4d4
[]
no_license
BackupTheBerlios/ejvm
7258cd180256970d57399d0c153d00257dbb127c
626602de9ed55a825efeefd70970c36bcef0588d
refs/heads/master
2020-06-11T19:47:07.882834
2006-07-10T16:39:59
2006-07-10T16:39:59
39,960,044
0
0
null
null
null
null
UTF-8
C++
false
false
3,377
cpp
#include "Loader.h" #include "Heap.h" #include <stdio.h> #include <sys/stat.h> //#include <unistd.h> Loader * Loader::loaderInstance = NULL; //-------------------------------------------------------------- Loader * Loader::getInstance() { if(loaderInstance == NULL) loaderInstance = new Loader; return loaderInstance; } //----------------------------------------------------- void Loader::deleteLoader() { delete loaderInstance; loaderInstance =NULL; } //--------------------------------------------------------- Loader::Loader() { } //---------------------------------------------------------- byte * Loader::makeArrayInCPP(char * fileName) { struct stat len; FILE *stream; void * classFile; if((stream = fopen(fileName, "rb")) == NULL) { //cout<<"File Not Found"<<endl; exit(1); } stat(fileName,&len); int size = len.st_size; classFile = new byte[size]; size_t bytesRead =fread(classFile,1,(size_t)size,stream); //cout<<bytesRead<<" bytes read\n"; fclose(stream); /*char ch; unsigned long length = 0; ifstream fin(fileName, ios::in | ios::binary); if(!fin) { //cout<<"Cannot open the file"; return NULL; } //Calaculate the file length while(fin.get(ch)) length++; fin.close(); //now read the file fin.open(fileName, ios::in | ios::binary); byte * pData=new byte[length]; fin.read((char *)pData,length); //see how many bytes have beed read //cout<<fin.gcount()<<" bytes read\n"; fin.close(); /* char file2[80]="/Khaled/eclipseWork/hello/OPS2.class"; ofstream fout(file2, ios::out | ios::binary); fout.write((char *)pData,length); //see how many bytes have beed written //cout<<fin.gcount()<<" bytes written\n"; fout.close();*/ //return pData ; return (byte *)classFile; } //--------------------------------------------------------------------------------------------- ClassData * Loader::getClassData(const char * className) { ///////////////////////////class name must be without .class /** * psudoCode: * if(!(classData=lookupdClassData(className))) * u1[] classFile = classFiel2bytes(className); * classData = Heap->createClassData(classFile); * return classData; */ // char path[80]="/Khaled/eclipseWork/testPrototype1/"; char path[80]=""; Heap * heap= Heap::getInstance(); ClassData * cdata =NULL; byte * classFile = NULL; cdata = heap->lookupClassData(className); if(cdata == NULL)//Class not loaded { //cout<<endl<<className<<endl<<endl; if(*className == '[') { cdata = heap->createArrayClassData(className); } else { //prepare the path of the class file strcat(path,className); strcat(path,".class"); //put the class file in array of bytes classFile=this->makeArrayInCPP(path);//*********************************************************************************DONT forget to uncomment //create classdata on the heap cdata = heap->createClassData(className,classFile); //*************************************************dont forget to modify it to take array of bytes or u1 //after checking that there are no errors during parsing, insert in the hash } heap->addToHash(cdata); } delete [] classFile; return cdata; }
[ "almahallawy" ]
[ [ [ 1, 134 ] ] ]
528389b015939c565326c29a2a1968472cbdedec
28b0332fabba904ac0668630f185e0ecd292d2a1
/src/Common/ClassInstance.cpp
7fb86e1261a05ec890b25e46e95793c3c723f2ce
[]
no_license
iplayfast/crylib
57a507ba996d1abe020f93ea4a58f47f62b31434
dbd435e14abc508c31d1f2f041f8254620e24dc0
refs/heads/master
2016-09-05T10:33:02.861605
2009-04-19T05:17:55
2009-04-19T05:17:55
35,353,897
0
0
null
null
null
null
UTF-8
C++
false
false
13,003
cpp
/*************************************************************************** * Copyright (C) 2006 by Chris Bruner * * [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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <stdarg.h> #include "ClassObject.h" #include "ClassBuilder.h" #include "ClassXML.h" #include "CryBackProp.h" #include "ClassInstance.h" #include "ClassFunction.h" #include "ClassFileStream.h" //#define DIAGNOSE using namespace Crystal; using namespace std; /*=========================================================================== // ClassInstance ============================================================================*/ /*ClassInstance::ClassInstance(CodeFactory *Parent,const char *ClassType,const char *ClassName,int _Count,bool _IsProperty,bool _IsPointer,bool _IsArrayPointer,const char *DefaultValue) : PrimInstance(Parent,"class",ClassName,DefaultValue, _Count,_IsProperty,_IsPointer,_IsArrayPointer) { p = Object::Create(ClassType,0); Type = ClassType; } */ ClassInstance::~ClassInstance() { delete p; } bool ClassInstance::HasProperty(const PropertyParser &PropertyName) const { if (PropertyName=="HasDefault") return true; if (PropertyName=="Default") return HasDefault; return PrimInstance::HasProperty(PropertyName); } PropertyList *ClassInstance::PropertyNames() const { PropertyList *Names = PrimInstance::PropertyNames(); Names->AddPropertyByName("HasDefault",this); if (!HasDefault) { Names->RemoveNodeValue(String("Default")); } return Names; } /*! will return the property named in PropertyName in a string format */ const char *ClassInstance::GetProperty(const PropertyParser &PropertyName,String &Result) const { if (PropertyName=="HasDefault") { Result = HasDefault ? "Yes" : "No"; return Result.AsPChar(); } if (PropertyName=="Default") { if(!HasDefault) return PrimInstance::GetProperty(PropertyName,Result); // throw CryException("Default Requested, when none was set"); XML x("obj"); x.LoadFrom(*p); x.SaveTo(Result); return Result.AsPChar(); } return PrimInstance::GetProperty(PropertyName,Result); } /*! The count of the properties a class has */ int ClassInstance::GetPropertyCount() const { return 2 + PrimInstance::GetPropertyCount(); } bool ClassInstance::SetProperty(const PropertyParser &PropertyName,const char *PropertyValue) { if (PropertyName=="HasDefault") { HasDefault = strcasecmp(PropertyValue,"Yes")==0; return true; } if (PropertyName=="Type") { PropertyParser pv(PropertyValue); p = Object::Create(pv,0); Type = PropertyValue; PrimInstance::SetType("class"); return true; } if (PropertyName=="Default") { // if the class couldn't use the default just let it go. XML x("obj"); String s(PropertyValue); x.LoadFrom(s); x.SaveTo(*p); HasDefault = true; return true; } return PrimInstance::SetProperty(PropertyName,PropertyValue); } Object *ClassInstance::Create(const PropertyParser &PropertyName,CodeFactory *Parent) { return PrimInstance::Create(PropertyName,Parent); /* if ((strcmp(CClassInstance,PropertyName)==0) && (!Parent->IsA(CClassBuilder))) { return this; } if (strcmp(CCountDefine,PropertyName)==0) { if (GetCount()<2) return 0; String s; s.printf("\n#define %s_LEN %d",GetName(),GetCount()); SetHead(PropertyName,s.AsPChar()); Parent->AppendHead(*GetHead(PropertyName)); return 0; } if (strcmp(CDeclaration,PropertyName)==0) { String s; if (GetCount()>1) { //Create(TCountDefine,Parent); s.printf("\n%s *%s[%s_LEN];", Type.AsPChar(),GetName(),GetName()); } else s.printf("\n%s %s%s;",Type.AsPChar(),GetIsPointer() ? "*" : "",GetName()); SetHead(PropertyName,s.AsPChar()); Parent->AppendHead(*GetHead(PropertyName)); return 0; }; if (strcmp(CConstructor,PropertyName)==0) { // we are construction our variables String s; s.Clear(); String C; if (GetCount()>1) { s.printf("\n\t%s = new %s*[%s_LEN];",GetName(),GetType(),GetName()); s.printf("\n\tfor(int i=0;i<%s_LEN;i++)\n\t\t%s[i] = new %s();",GetName(),GetName(),GetType()); } else if (GetIsPointer()) s.printf("\n%s = new %s%s;",GetName(),Type.AsPChar(),GetName()); SetImp(PropertyName,s.AsPChar()); Parent->AppendImp(*GetImp(PropertyName)); return 0; } if (strcmp(CDestructor,PropertyName)==0) { String s; if (GetCount()>1) s.printf("\n\tfor(int i=0;i<%s_LEN;i++)\n\t\tdelete %s[i];",GetName(),GetName()); if (GetCount()>1 || GetIsPointer()) s.printf("\n\tdelete %s%s;",GetCount()>1 ? "[]" : "",GetName()); SetImp(PropertyName,s.AsPChar()); Parent->AppendImp(*GetImp(PropertyName)); return 0; } if ((strcmp(CSetProperty,PropertyName)==0) && CanBuildProduct(PropertyName))//Can't build if it isn't a property { String s; FunctionDef Func; if (GetCount()>1) { s.printf("void Set%s(int Index,const char *Value);",GetName()); Func.Parse(s); s = Func.GetNPDeclaration(); SetHead(PropertyName,s.AsPChar()); s.Clear(); s = Func.GetImplementedDeclaration(Parent->GetName(),true); s.printf("\n{\n#ifdef RangeChecking\n\tif ((Index<0) || (Index>=%s_LEN))\n\t\tthrow CryException(\"Range Error\");\n#endif", GetName(),GetName()); if (Type==CString) { s.printf("\n\t%s[Index] = Value;",GetName()); } else { s.printf("\nCryString a(Value);"); s.printf("\nCryXML x(\"obj\");"); s.printf("\n\n\tx.LoadFrom(a);"); s.printf("\n\tx.SaveTo(%s[Index]);",GetName()); } s.printf("\n}\n"); } else { s.printf("void Set%s(const char *Value);",GetName()); Func.Parse(s); s = "\n"; s += Func.GetNPDeclaration(); SetHead(PropertyName,s.AsPChar()); s.Clear(); s = Func.GetImplementedDeclaration(Parent->GetName(),true); s.printf("\n{"); if (Type==CString) { s.printf("\n\t%s = Value;",GetName()); } else { s.printf("\nCryString a(Value);"); s.printf("\nCryXML x(\"obj\");"); s.printf("\n\n\tx.LoadFrom(a);"); s.printf("\n\tx.SaveTo(%s);",GetName()); } s.printf("\n}\n"); } SetImp(PropertyName,s); Parent->AppendHead(*GetHead(PropertyName)); Parent->AppendImp(*GetImp(PropertyName)); return 0; } if (PropertyName==CCopyTo) { String s; if (GetIsPointer()) { if (GetCount()>1) s.printf("\n\t\tfor(int i=0;i<%s_LEN;i++)\n\t\t\t*CastDest->%s[i] = *%s[i];", GetName(),GetName(),GetName()); else s.printf("\n\t\t%sCastDest%s%s = %s%s%s;", (GetIsPointer() || GetIsArrayPointer()) ? "*" : "", GetIsPointer() ? "->" : ".",GetName(),GetIsArrayPointer() ? "*" : "",GetIsPointer() ? "*" : "", GetName()); } else { if (GetCount()>1) s.printf("\n\t\tfor(int i=0;i<%s_LEN;i++)\n\t\t\tCastDest->%s[i] = %s[i];", GetName(),GetName(),GetName()); else s.printf("\n\t\tCastDest->%s = %s;",GetName(),GetName()); } SetImp(PropertyName,s.AsPChar()); Parent->AppendImp(*GetImp(PropertyName)); return 0; } if ((strcmp(CGetProperty,PropertyName)==0) && CanBuildProduct(PropertyName))//Can't build if it isn't a property { String s; FunctionDef Func; if (GetCount()>1) { s.printf("void Get%s(int Index,CryString &Result) const;",GetName()); Func.Parse(s); s = "\n"; s += Func.GetNPDeclaration(); SetHead(PropertyName,s.AsPChar()); s.Clear(); s = Func.GetImplementedDeclaration(Parent->GetName(),true); s.printf("\n{\n#ifdef RangeChecking\n\tif ((Index<0) || (Index>=%s_LEN))\n\t\tthrow CryException(\"Range Error\");\n#endif", GetName(),GetName()); if (Type==CString) { s.printf("\n\tResult = %s[Index];",GetName()); } else { s.printf("\n\t//Result.Clear()"); s.printf("\nCryXML x(\"obj\");"); s.printf("\n\tx.LoadFrom(%s[Index]);",GetName()); s.printf("\n\tx.SaveTo(Result);"); } s.printf("\n}"); } else { s.printf("\nvoid Get%s(CryString &Result) const;",GetName()); Func.Parse(s); s = "\n"; s += Func.GetNPDeclaration(); SetHead(PropertyName,s.AsPChar()); s.Clear(); s = Func.GetImplementedDeclaration(Parent->GetName(),true); s.printf("\n{"); if (Type==CString) { s.printf("\n\tResult = %s;",GetName()); } else { s.printf("\n\t//Result.Clear()"); s.printf("\nCryXML x(\"obj\");"); s.printf("\n\tx.LoadFrom(%s);",GetName()); s.printf("\n\tx.SaveTo(Result);"); } s.printf("\n}"); } SetImp(PropertyName,s); Parent->AppendHead(*GetHead(PropertyName)); Parent->AppendImp(*GetImp(PropertyName)); return 0; } //if (strcmp("VarName",PropertyName)==0) //{ //return &GetName(); //} return 0; */ } const char *ClassInstance::Code_AssignDefaultValue(String &Result) const { String Default; if (HasDefault) { PropertyParser p("Default"); GetProperty(p,Default); } Result = ""; if (p->IsA(CString)) Result.printf(" = \"%s\"",Default.AsPChar()); else if (p->IsA(CProperty)) { if (GetCount()>1) Result.printf(".SetNameValue(CryString(\"%s_%%d\",i),\"%s\")",GetName(),Default.AsPChar()); else Result.printf(".SetNameValue(\"%s\",\"%s\")",GetName(),Default.AsPChar()); } else Result.printf("// Add Default values here \n\t"); Default = Result; Result = ""; if (p->IsContainer() && !p->IsA(CString)) Result.printf("// %s Container needs your personal attention for default values\n//",GetType()); if (GetIsPointer()) { if (GetCount()>1) Result.printf("*%s[i]%s", GetName(), Default.AsPChar()); else Result.printf("*%s%s",GetName(),Default.AsPChar()); } else { if (GetCount()>1) { Result.printf("%s[i]%s",GetName(),Default.AsPChar()); } else { Result.printf("%s%s", GetName(),Default.AsPChar()); } } return Result.AsPChar(); } const char *ClassInstance::GetType() const { return Type.AsPChar(); } /*bool ClassInstance::GetIsProperty() const { return IsProperty; } void ClassInstance::SetIsArrayPointer(bool _IsArrayPointer) { IsArrayPointer = _IsArrayPointer; } bool ClassInstance::GetIsArrayPointer() const { return IsArrayPointer; } */ const char *ClassInstance::Code_SetProperty(String &Result) const { String pName; String ExtraCode; if (!p->IsA(CString)) ExtraCode = ".SetValue(Value)"; else ExtraCode= "= Value"; bool Comment = false; //! p->IsA(CString); pName.printf("%s%s%s%s", Comment ? "/*" : "", this->GetIsPointer() ? "*" : "",GetName(),GetCount()>1 ? "[Index]" : ""); Result.printf("%s%s;%s",pName.AsPChar(),ExtraCode.AsPChar(),Comment ? "*/" : ""); return Result.AsPChar(); } const char *ClassInstance::Code_GetProperty(String &Result) const { String pName; String ExtraCode; bool Comment = false;//! p->IsA(CString); if (!p->IsA(CString)) ExtraCode = ".GetValue()"; else ExtraCode= ""; pName.printf("%s%s%s%s", Comment ? "/*" : "", this->GetIsPointer() ? "*" : "",GetName(),GetCount()>1 ? "[Index]" : ""); Result.printf("Result = %s%s;%s",pName.AsPChar(),ExtraCode.AsPChar(),Comment ? "*/" : ""); return Result.AsPChar(); }
[ "cwbruner@f8ea3247-a519-0410-8bc2-439d413616df" ]
[ [ [ 1, 438 ] ] ]
de0d4d269b8fa11a669c2485fe27b7df789ee541
3276915b349aec4d26b466d48d9c8022a909ec16
/c++/派生和继承/单继承/派生与有缘/派生与有缘函数.cpp
f69a21ee13c70baf97bb8f711a27a147f78aab41
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
1,216
cpp
#include<iostream.h> class xiao { private:int x; protected:int y; public:int z; xiao(int i,int j,int k) { x=i;y=j;z=k; } void disp() { cout<<"x="<<x<<endl; cout<<"y="<<y<<endl; } }; class da:private xiao { int w; protected:int v; public: da(int i,int j,int k,int l,int b):xiao(i,j,k) { w=l;v=b; } friend void f(da &p); friend class mid; }; class mid { da o; public: mid(int i,int j,int k,int l,int b):o(i,j,k,l,b) { } void disp() { cout<<"o.w="<<o.w<<endl; cout<<"o.v"<<o.v<<endl; cout<<"o.z="<<o.z<<endl; o.disp(); } }; void f(da &p) //派生类的有缘函数除了能访问派生类的私有和保护成员外,还只能访问派生类的父类的公有成员,父类的中的私有和保护成员是不能被派生类的有缘访问的// { cout<<"p.w="<<p.w<<endl<<"p.v"<<p.v<<endl<<"p.z="<<p.z<<endl; p.disp(); //如果要访问,只能通过有缘来调用派生类中从父类继承过来的父类的成员函数来访问,disp()是派生类da从xiao中继承来的xiao的公有成员函数// } void main() { da x(1,2,3,4,5); mid y(1,2,3,4,5); f(x); y.disp(); }
[ [ [ 1, 64 ] ] ]
c009877703be99fdb205b48118948f1e070dcbb4
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/Sprinkles.cpp
947c392ba00a39a49df984fb79b29f1e76ebba39
[]
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,637
cpp
#include "stdafx.h" #include "sprinkles.h" #include "sfxmsgids.h" LINKFROM_MODULE( Sprinkles ); #define ADD_SPRINKLE_PROP(num, defFilename) \ ADD_STRINGPROP_FLAG(Filename##num##, defFilename, PF_FILENAME)\ ADD_STRINGPROP_FLAG(SkinName##num##, "", PF_FILENAME)\ ADD_LONGINTPROP(Count##num##, 16)\ ADD_REALPROP(Speed##num##, 50.0f)\ ADD_REALPROP(Size##num##, 10.0f)\ ADD_REALPROP_FLAG(SpawnRadius##num##, 500.0f, PF_RADIUS)\ ADD_COLORPROP(ColorMin##num##, 255.0f, 255.0f, 255.0f)\ ADD_COLORPROP(ColorMax##num##, 255.0f, 255.0f, 255.0f)\ ADD_VECTORPROP_VAL(AnglesVel##num##, 1.0f, 1.0f, 1.0f) #pragma force_active on BEGIN_CLASS(Sprinkles) ADD_SPRINKLE_PROP(0, "SFX\\Snow\\SprTex\\Snow1.dtx") ADD_SPRINKLE_PROP(1, "") ADD_SPRINKLE_PROP(2, "") ADD_SPRINKLE_PROP(3, "") ADD_SPRINKLE_PROP(4, "") ADD_SPRINKLE_PROP(5, "") ADD_SPRINKLE_PROP(6, "") ADD_SPRINKLE_PROP(7, "") END_CLASS_DEFAULT(Sprinkles, BaseClass, NULL, NULL) #pragma force_active off // --------------------------------------------------------------------------------- // // Sprinkles // --------------------------------------------------------------------------------- // Sprinkles::Sprinkles() : BaseClass(OT_NORMAL) { } Sprinkles::~Sprinkles() { if(g_pLTServer) { for(uint32 i = 0; i < MAX_SPRINKLE_TYPES; i++) { if (m_SprinkleStruct.m_Types[i].m_hFilename) { g_pLTServer->FreeString(m_SprinkleStruct.m_Types[i].m_hFilename); } if (m_SprinkleStruct.m_Types[i].m_hSkinName) { g_pLTServer->FreeString(m_SprinkleStruct.m_Types[i].m_hSkinName); } } } } uint32 Sprinkles::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData) { switch(messageID) { case MID_PRECREATE: { OnPreCreate((ObjectCreateStruct*)pData); } break; case MID_INITIALUPDATE: { OnInitialUpdate(); } break; case MID_UPDATE: { OnUpdate(); } break; } return BaseClass::EngineMessageFn(messageID, pData, fData); } void Sprinkles::OnPreCreate(ObjectCreateStruct *pStruct) { char propName[64]; GenericProp gProp; SPRINKLETYPECREATESTRUCT *pType; uint32 i; pStruct->m_Flags = FLAG_FORCECLIENTUPDATE; m_SprinkleStruct.m_nTypes = 0; for(i=0; i < MAX_SPRINKLE_TYPES; i++) { pType = &(m_SprinkleStruct.m_Types[i]); // FilenameX sprintf(propName, "Filename%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) != LT_OK) break; if(gProp.m_String[0] == 0) break; pType->m_hFilename = g_pLTServer->CreateString(gProp.m_String); if(!pType->m_hFilename) break; // SkinNameX sprintf(propName, "SkinName%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) != LT_OK) break; pType->m_hSkinName = g_pLTServer->CreateString(gProp.m_String); // CountX sprintf(propName, "Count%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_Count = (uint32)gProp.m_Long; if(pType->m_Count > 255) { g_pLTServer->CPrint("Warning: SprinklesFX count > 255, clamping"); pType->m_Count = 255; } } // SpeedX sprintf(propName, "Speed%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_Speed = gProp.m_Float; } // SizeX sprintf(propName, "Size%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_Size = gProp.m_Float; } // SpawnRadiusX sprintf(propName, "SpawnRadius%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_SpawnRadius = gProp.m_Float; } // AnglesVelX sprintf(propName, "AnglesVel%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_AnglesVel = gProp.m_Vec; } // ColorMinX sprintf(propName, "ColorMin%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_ColorMin = gProp.m_Color; } // ColorMaxX sprintf(propName, "ColorMax%d", i); if(g_pLTServer->GetPropGeneric(propName, &gProp) == LT_OK) { pType->m_ColorMax = gProp.m_Color; } ++m_SprinkleStruct.m_nTypes; } } void Sprinkles::OnInitialUpdate() { CAutoMessage cMsg; cMsg.Writeuint8(SFX_SPRINKLES_ID); m_SprinkleStruct.Write(cMsg); g_pLTServer->SetObjectSFXMessage(m_hObject, cMsg.Read()); } uint32 Sprinkles::OnUpdate() { return 1; }
[ [ [ 1, 201 ] ] ]
ada5a7fd5200cfbd8a047da9725c41c069b86767
a29ec259efa2c2f13e24be86a4c6ba174780857d
/include/ZakEngine/VertexBufferManager.h
3552d1856e22d554fe11cee2006d4cb507d0e3ea
[]
no_license
nlelouche/programacion2
639ffb55d06af4f696031ec777bec898b6224774
5ec9b29014c13786230e834deb44679b110351b4
refs/heads/master
2016-09-06T15:40:38.888016
2007-11-09T01:03:51
2007-11-09T01:03:51
32,653,635
0
0
null
null
null
null
ISO-8859-1
C++
false
false
6,025
h
#ifndef _VertexBufferManager_H_ #define _VertexBufferManager_H_ #include <windows.h> #include <d3d9.h> //#include "Renderer.h" //#include <assert.h> namespace zak { template <class PixelFormatClass, unsigned int FVF> class VertexBufferManager { static const int VB_SIZE = 450; static const int FLUSH_COUNT = 150; public: // Constructor (es conveniente que flush sea múltiplo de size y de 3) VertexBufferManager() : _vbSize(VB_SIZE), _flushCount(FLUSH_COUNT), _pVertexBuffer(NULL), _primitiveType(D3DPT_TRIANGLELIST) {} // Destructor ~VertexBufferManager() { if (_pVertexBuffer) _pVertexBuffer->Release(); } // Crea un vertex buffer bool Create(IDirect3DDevice9 *pDev, bool bDynamic=true); // Libera a un vertex buffer void Release(void) { if (_pVertexBuffer) _pVertexBuffer->Release(); _pVertexBuffer=NULL; } // Actualiza el contenido del vertex buffer bool Draw(PixelFormatClass * pVtxCollection, D3DPRIMITIVETYPE primitiveType, unsigned int uiVtxCount); // Bind void Bind(void) { _pDev->SetVertexShader(NULL); _pDev->SetFVF(FVF); _pDev->SetStreamSource(0, _pVertexBuffer, 0, sizeof(PixelFormatClass)); } // Envía los datos al pipeline void Flush(); private: const unsigned int _vbSize; // Cantidad de vértices que contiene el vertex buffer const unsigned int _flushCount; // Cantidad de vértices entre flushes LPDIRECT3DVERTEXBUFFER9 _pVertexBuffer; // Vertex Buffer encapsulado IDirect3DDevice9 *_pDev; // Device asociado en el método Create unsigned int _baseNum; // Base del vertex buffer a lockear unsigned int _vtxToLock; // Indica la cantidad de vértices lockeados en el vb D3DPRIMITIVETYPE _primitiveType; // Primitiva actual }; // ------------------------------------------------------------------------------ template <class PixelFormatClass, unsigned int FVF> bool VertexBufferManager<PixelFormatClass, FVF>::Create(IDirect3DDevice9 *pDev, bool bDynamic) { _pDev = pDev; HRESULT hr = pDev->CreateVertexBuffer(_vbSize*sizeof(PixelFormatClass), (bDynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : 0), FVF, D3DPOOL_DEFAULT, &_pVertexBuffer, NULL); // Indico que la base de vb a lockear es cero _baseNum = 0; if (hr == D3D_OK) return true; else return false; } // ------------------------------------------------------------------------------ // Actualiza el contenido del vertex buffer template <class PixelFormatClass, unsigned int FVF> bool VertexBufferManager<PixelFormatClass, FVF>::Draw(PixelFormatClass * pVtxCollection, D3DPRIMITIVETYPE primitiveType, unsigned int uiVtxCount) { VOID * pVertices; // Almaceno cual es la primitiva deseada _primitiveType = primitiveType; // Si la cantidad de vértices que faltan para realizar un flush es menor // a la cantidad de vértices pasados, copio primero sólo los que faltan // para el flush y realizo el mismo _vtxToLock = (_flushCount < uiVtxCount ? _flushCount : uiVtxCount); // Verifico que la cantidad de vértices a lockear + la base // no exeda el tamaño total del vertex buffer if (_baseNum + _vtxToLock > _vbSize) _baseNum = 0; // Lockeo el vertex buffer a partir de la base y un chunk correspondiente // al tamaño del flush HRESULT hr = _pVertexBuffer->Lock(_baseNum * sizeof(PixelFormatClass), _vtxToLock * sizeof(PixelFormatClass), (VOID **) &pVertices, _baseNum ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD); // Si no he podido realizar un lock, retorno false if (hr != D3D_OK) return false; unsigned int uiVtxProcNow = 0; // Mientras que queden vértices a copiar... while (_vtxToLock > 0) { // Copio vértices al vertex buffer memcpy( pVertices, &pVtxCollection[uiVtxProcNow], sizeof(PixelFormatClass)*_vtxToLock); // Actualizo el índice de copia de los vértices pasados como parámetros uiVtxProcNow += _vtxToLock; // ------------------------------------------------------------------------- // Copiados los vértices al vb, los envío al pipeline // por medio del DrawPrimitive // ------------------------------------------------------------------------- // Destrabo el vb _pVertexBuffer->Unlock(); // Realizo el DrawPrimitive Flush(); // Actualizo la base de vértices a lockear _baseNum += _vtxToLock; // Calculo nuevamente la cantidad de vértices a copiar _vtxToLock = (_flushCount < (uiVtxCount-uiVtxProcNow) ? _flushCount : uiVtxCount-uiVtxProcNow); // Verifico que la cantidad de vértices a lockear + la base // no exeda el tamaño total del vertex buffer if (_baseNum + _vtxToLock > _vbSize) _baseNum = 0; hr = _pVertexBuffer->Lock(_baseNum * sizeof(PixelFormatClass), _vtxToLock * sizeof(PixelFormatClass), (VOID **) &pVertices, _baseNum ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD); // Si no he podido realizar un lock, retorno false if (hr != D3D_OK) return false; } // Destrabo el vb _pVertexBuffer->Unlock(); return true; } // ------------------------------------------------------------------------------ // Envía los datos al pipeline template <class PixelFormatClass, unsigned int FVF> void VertexBufferManager<PixelFormatClass, FVF>::Flush(void) { HRESULT hr; int primitiveCount; // Determino la cantidad de primitivas a realizar en función // del tipo if (_primitiveType == D3DPT_POINTLIST) primitiveCount = _vtxToLock; else if (_primitiveType == D3DPT_LINELIST) primitiveCount = _vtxToLock/2; else if (_primitiveType == D3DPT_LINESTRIP) primitiveCount = _vtxToLock-1; else if (_primitiveType == D3DPT_TRIANGLELIST) primitiveCount = _vtxToLock/3; else if (_primitiveType == D3DPT_TRIANGLESTRIP) primitiveCount = _vtxToLock-2; else primitiveCount = 0; hr = _pDev->DrawPrimitive(_primitiveType, _baseNum, primitiveCount); } } #endif // _VertexBufferManager_H_
[ "yoviacthulhu@70076bbf-733e-0410-a12a-85c366f55b74" ]
[ [ [ 1, 185 ] ] ]
4813574c93d986e1545d08ea3ac72fb7ccbb2ef5
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/NxOgre/build/source/NxOgreSpringDescription.cpp
b7058cdb77dcf80ccf639f48c5fa51fd01f9c8f2
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,620
cpp
/** File: NxOgreSpringDescription.cpp Created on: 16-Apr-09 Author: Robin Southern "betajaen" © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre 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. NxOgre 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 NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #include "NxOgreStable.h" #include "NxOgreSpringDescription.h" namespace NxOgre { SpringDescription::SpringDescription(void) { reset(); } void SpringDescription::reset(void) { mSpring = 0; mDamper = 0; mTargetValue = 0; } } // namespace NxOgre
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 52 ] ] ]
fe51202ec0c1f1b7d76f8977f25ae78f626574ae
701f9ab221639b56c28417ee6f6ee984acb24142
/Src/Force Engine/Animation/AnimationInfo.cpp
d7ea568567028b21702551afb5cac1fd05aa9308
[]
no_license
nlelouche/desprog1
2397130e427b4ada83721ecbb1a131682bc73187
71c7839675698e74ca43dd26c4af752e309dccb6
refs/heads/master
2021-01-22T06:33:14.083467
2010-02-26T16:18:39
2010-02-26T16:18:39
32,653,851
0
0
null
null
null
null
UTF-8
C++
false
false
899
cpp
/**************************************************************************** Force Engine v0.5 Creado: 28/03/08 Clase: AnimationInfo.cpp Hecho by: German Battiston AKA Melkor ****************************************************************************/ //--------------------------------------------------------------------------- #include "../Animation/AnimationInfo.h" #include "../Entity2D/Sprite.h" //--------------------------------------------------------------------------- void AnimationInfo::addFrame( unsigned int uiOffsetX, unsigned int uiOffsetY, unsigned int uiWidth, unsigned int uiHeight ) { FrameInfo kInfo; kInfo.uiWidth = uiWidth; kInfo.uiHeight = uiHeight; kInfo.uiOffsetX = uiOffsetX; kInfo.uiOffsetY = uiOffsetY; m_akFramesInfo.push_back(kInfo); m_fTimePerFrame = m_fLength / getFrameCount(); }
[ "gersurfer@a82ef5f6-654a-0410-99b4-23d68ab79cb1" ]
[ [ [ 1, 32 ] ] ]
3012c96c8032b22c946f917f595e3616abbb4ea5
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/ContentTools/Common/Filters/FilterTexture/GatherAndConvertTexture/hctGatherAndConvertTextureFilter.h
923744a096168721fcf780228efc97d7feeae5e2
[]
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
3,773
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 HAVOK_FILTER_TEXTURES_GATHER_AND_CONVERT__H #define HAVOK_FILTER_TEXTURES_GATHER_AND_CONVERT__H #include <ContentTools/Common/Filters/FilterTexture/GatherAndConvertTexture/hctGatherAndConvertTextureFilterOptions.h> class hctGatherAndConvertTextureFilter : public hctFilterInterface { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_EXPORT); hctGatherAndConvertTextureFilter(const hctFilterManagerInterface* owner); /*virtual*/ ~hctGatherAndConvertTextureFilter(); /*virtual*/ void setOptions(const void* optionData, int optionDataSize, unsigned int version); /*virtual*/ HWND showOptions(HWND owner); /*virtual*/ void process( class hkRootLevelContainer& data ); /// Option ptr only valid until the filter is deleted and/or the filter dll is unloaded /*virtual*/ int getOptionsSize() const; /*virtual*/ void getOptions(void* optionData) const; virtual void hideOptions(); void updateOptions(); // filter options hctGatherAndConvertTextureFilterOptions m_options; hkArray< hkStringOld > m_nameStrings; hkArray< hkxTextureFile* > m_listedFileTextures; hkArray< hkxTextureInplace* > m_listedInplaceTextures; hkArray< int > m_currentEditOptionIndices; hkRootLevelContainer* m_optionSceneData; hkPackfileData* m_optionSceneDataTracker; // A buffer for storing the options in XML form. mutable hkArray<char> m_getOptionsBuf; mutable hkArray<char> m_setOptionsBuf; // dialog HWND m_optionsDialog; }; class hctGatherAndConvertTextureFilterDesc : public hctFilterDescriptor { public: /*virtual*/ unsigned int getID() const { return 0x7382abaa; } /*virtual*/ FilterCategory getCategory() const { return HK_CATEGORY_GRAPHICS; } /*virtual*/ FilterBehaviour getFilterBehaviour() const { return HK_DATA_MUTATES_INPLACE; } /*virtual*/ const char* getShortName() const { return "GatherAndConvertTextures"; } /*virtual*/ const char* getLongName() const { return "Convert textures using FreeImage (so a lot of file types supported). Creates new file or new inplace texture depending on input."; } /*virtual*/ unsigned int getFilterVersion() const { return HCT_FILTER_VERSION(1,1,1); } /*virtual*/ hctFilterInterface* createFilter(const hctFilterManagerInterface* owner) const { return new hctGatherAndConvertTextureFilter(owner); } /*virtual*/ HavokComponentMask getRequiredHavokComponents () const { return HK_COMPONENT_COMMON; } }; extern hctGatherAndConvertTextureFilterDesc g_gatherAndConvertTextureDesc; #endif // HAVOK_FILTER_TEXTURES_GATHER_AND_CONVERT__H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 85 ] ] ]
8e923f11ac7c4b2b45343fceaa86fea9f60cee3f
ca99bc050dbc58be61a92e04f2a80a4b83cb6000
/Game/src/Map/World.h
9391b7a87e5464974b7c8792073b2e0113350e5a
[]
no_license
NicolasBeaudrot/angry-tux
e26c619346c63a468ad3711de786e94f5b78a2f1
5a8259f57ba59db9071158a775948d06e424a9a8
refs/heads/master
2021-01-06T20:41:23.705460
2011-04-14T18:28:04
2011-04-14T18:28:04
32,141,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
h
/* Copyright (C) 2010 Nicolas Beaudrot This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef WORLD_H #define WORLD_H #include "../Utilities/Config.h" class World { private : std::string _directory ,_name; sf::Image *_image; sf::Sprite _sprite; public : World(std::string directory, std::string name, std::string file_name); std::string& getDirectory(); std::string& getName(); sf::Sprite& getSprite(); }; #endif
[ "nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad" ]
[ [ [ 1, 36 ] ] ]
e8b15ae836f8d783500c6a4675d6638e6c29fb81
e9522499ed4d3b89f8538f5507347a255cd7fa52
/drawcli/statpage.h
8d3676c13f0981cae06a3a1472394168f551a8aa
[]
no_license
markraz/hhhjjjff
380f075bb468b8c8cda48b25f592498d1a937ba7
bd81c2f6e97e232645aff745e557760f9cea698d
refs/heads/master
2021-01-23T07:26:59.874200
2009-06-11T05:14:14
2009-06-11T05:14:14
35,393,785
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
h
// statpage.h : header file ///////////////////////////////////////////////////////////////////////////// // CStatPage dialog class CStatPage : public CPropertyPage { DECLARE_DYNCREATE(CStatPage) // Construction public: CStatPage(); ~CStatPage(); // Dialog Data //{{AFX_DATA(CStatPage) enum { IDD = IDD_STAT_PAGE }; CString m_strSavedBy; CString m_strRevNum; CString m_strEditTime; CString m_strLastPrint; CString m_strCreateDate; CString m_strLastSave; CString m_strNumPages; CString m_strNumWords; CString m_strNumChars; CString m_strSecurity; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CStatPage) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CStatPage) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ "[email protected]@cfa3df76-2cb6-11de-b2a4-4f96ceaaac44" ]
[ [ [ 1, 46 ] ] ]
e145521f03c777d92a5ff1b1ebb2b18f20d8cd11
74d531abb9fda8dc621c5d8376eb10ec4ef19568
/src/game.cpp
05affc510c488c6d39f2726c1f6dbc0ba0d32feb
[]
no_license
aljosaosep/xsoko
e207d6ec8de3196029e569e7765424a399a50f04
c52440ecee65dc2f3f38d996936e65b3ff3b8b5e
refs/heads/master
2021-01-10T14:27:04.644013
2009-09-02T20:39:53
2009-09-02T20:39:53
49,592,571
0
0
null
null
null
null
UTF-8
C++
false
false
2,614
cpp
/* * codename: xSoko * Copyright (C) Aljosa Osep, Jernej Skrabec, Jernej Halozan 2008 <[email protected], [email protected], [email protected]> * * xSoko project is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * xSoko project is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Codename: xSoko * File: game.cpp * * Summary: * Includes game core implementation * * Author: Aljosa Osep 2007 * Changes: * Aljosa May 28 2008 */ #include "game.h" //#include <AL/alut.h> using namespace PacGame; namespace PacGame { namespace GameClasses { // construcotrs PGame::PGame() { windowTitle = "xSoko"; } PGame::PGame(int _width, int _height, string _title) { windowWidth = _width; windowHeight = _height; windowTitle = _title; // alutInit (NULL, NULL); // inicializacija ALUT in OpenAL API // alGetError(); // počisti napake } // destructor PGame::~PGame() { terminateGLFW(); // alutExit (); } // methods void PGame::loadSession(PGameSession *session) { this->session = session; } bool PGame::run() { //TODO: fix this this->session->mainLoop(); return true; } // setters void PGame::setWindow(int _width, int _height) { windowWidth = _width; windowHeight = _height; } void PGame::setWindowTitle(string _title) { windowTitle = _title; } void PGame::terminateGLFW() { Messages::infoMessage("Termination, destroying glfw..."); glfwTerminate(); } } }
[ "aljosa.osep@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb", "jernej.halozan@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb", "jernej.skrabec@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb" ]
[ [ [ 1, 30 ], [ 32, 35 ], [ 38, 50 ], [ 52, 57 ], [ 59, 63 ], [ 65, 70 ], [ 74, 91 ], [ 93, 93 ] ], [ [ 31, 31 ], [ 36, 37 ], [ 51, 51 ], [ 58, 58 ], [ 92, 92 ], [ 94, 94 ] ], [ [ 64, 64 ], [ 71, 73 ] ] ]
c834103e77e3790b9072e81ae5cc7d55209c74ca
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXMultiComboBox.inl
3a6ffc860fff4efd86b6cb538ec19c3837b8383d
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,452
inl
// ========================================================================== // inline functions for class : COXMultiComboBox // ========================================================================== // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // ////////////////////////////////////////////////////////////////////////// #ifndef COXMULTICOMBOBOX_INL #define COXMULTICOMBOBOX_INL //Inline member functions //public inline BOOL COXMultiComboBox::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID) { ASSERT((dwStyle & CBS_OWNERDRAWFIXED) | (dwStyle & CBS_OWNERDRAWVARIABLE) ); return CComboBox::Create(dwStyle, rect, pParentWnd, nID); } inline COXMultiComboBox::~COXMultiComboBox() { m_GridPen.DeleteObject(); m_aColumnWidth.SetSize(0); } inline int COXMultiComboBox::GetColumnCount() const { return m_nColumnCount; } inline int COXMultiComboBox::GetMasterColumn() const { return m_nMasterColumn; } inline int COXMultiComboBox::GetColumnWidth(int nColIndex) const { return ((nColIndex < 0 || nColIndex >= m_nColumnCount) ? CB_ERR : m_aColumnWidth[nColIndex]); } inline int COXMultiComboBox::GetLBText(int nIndex, LPTSTR lpszText) const { return GetLBText(nIndex, m_nMasterColumn, lpszText); } inline void COXMultiComboBox::GetLBText(int nIndex, CString& rString) const { GetLBText(nIndex, m_nMasterColumn, rString); } inline int COXMultiComboBox::GetLBTextLen(int nIndex) const { return GetLBTextLen(nIndex,m_nMasterColumn); } inline int COXMultiComboBox::FindStringExact(int nIndexStart, LPCTSTR lpszFind, BOOL bCaseSensitive/*=FALSE*/) const { return FindStringExact(nIndexStart, m_nMasterColumn, lpszFind, bCaseSensitive); } inline int COXMultiComboBox::FindString(int nStartAfter, LPCTSTR lpszString, BOOL bCaseSensitive/*=FALSE*/) const { return FindString(nStartAfter, m_nMasterColumn, lpszString, bCaseSensitive); } inline int COXMultiComboBox::SelectString(int nStartAfter, LPCTSTR lpszString) { return SelectString(nStartAfter, m_nMasterColumn, lpszString); } //protected inline COXMultiComboBox::COXRowData::COXRowData(int nColCount) // --- In : nColCount : Column Count // --- Out : // --- Returns : // --- Effect : constructs the object and sets the size of string array { ASSERT(nColCount>=0); ColumnString.SetSize(nColCount); //sets the string array size ItemData = 0; } inline void COXMultiComboBox::COXRowData::SetColumnCount(int nCount) // --- In : nColCount : Column Count // --- Out : // --- Returns : // --- Effect : Sets the size of string array { ASSERT(nCount>=0); ColumnString.SetSize(nCount); } inline void COXMultiComboBox::COXRowData::SetItemData(DWORD Data) // --- In : Data : Item Data to set // --- Out : // --- Returns : // --- Effect : Sets the Data to ItemData { ItemData = Data; } inline DWORD COXMultiComboBox::COXRowData::GetItemData() const // --- In : // --- Out : // --- Returns : Item data // --- Effect : { return ItemData; } inline void COXMultiComboBox::COXRowData::SetColumnString(int nColIndex,const CString& rString) // --- In : nColIndex : Column Index // rString : String to set // --- Out : // --- Returns : // --- Effect : Copies the given string into nColIndex string in string array { ASSERT(nColIndex >= 0 && nColIndex < ColumnString.GetSize()); ColumnString[nColIndex] = rString; } inline CString COXMultiComboBox::COXRowData::GetColumnString(int nColIndex) const // --- In : nColCount : Column Count // --- Out : // --- Returns : Returns the nColIndex'th string // --- Effect : { ASSERT(nColIndex >= 0 && nColIndex<ColumnString.GetSize()); return ColumnString[nColIndex]; } inline void COXMultiComboBox::COXRowData::DeleteColumnString(int nColIndex) // --- In : nColCount : Column Count // --- Out : // --- Returns : // --- Effect : Removes the string at nColIndex { ASSERT(nColIndex >= 0 && nColIndex<ColumnString.GetSize()); ColumnString.RemoveAt(nColIndex); } inline void COXMultiComboBox::COXComboLBox::Init(CWnd* pCombo) // --- In : pCombo : Combobox CWnd pointer // --- Out : // --- Returns : // --- Effect : Initializes the combo pointer { m_pWndCombo = pCombo; } inline void COXMultiComboBox::PreSubclassWindow() // --- In : // --- Out : // --- Returns : // --- Effect : Asserts the owner draw style and calls CComboBoxs // PreSubclassWindow. { DWORD dwStyle = GetStyle(); dwStyle = dwStyle; // prevent level 4 warning in release mode ASSERT((dwStyle & CBS_OWNERDRAWFIXED) | (dwStyle & CBS_OWNERDRAWVARIABLE) ); CComboBox::PreSubclassWindow(); } #endif // COXMULTICOMBOBOX_INL // //////////////////////////////////////////////////////////////////////////
[ [ [ 1, 178 ] ] ]
7f1bb54af1e319c27b517cba5199fed6bb8a30ea
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/include/OEUI/IOEUIFont.h
d6355ecc68ae1e81a150a4f8dafa1688cbf5df73
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
875
h
/*! * \file IOEUIFont.h * \date 27-7-2009 17:49:03 * * * \author zjhlogo ([email protected]) */ #ifndef __IOEUIFONT_H__ #define __IOEUIFONT_H__ #include "../libOEUI/OEUIType.h" #include "../libOEBase/IOEObject.h" #include "../OECore/IOETexture.h" class IOEUIFont : public IOEObject { public: typedef struct CHAR_INFO_tag { int nID; float x; float y; float width; float height; float u; float v; float w; float h; IOETexture* pTexture; float fOffsetX; float fOffsetY; float fAdvance; int nRef; } CHAR_INFO; public: RTTI_DEF(IOEUIFont, IOEObject); IOEUIFont() {}; virtual ~IOEUIFont() {}; virtual float GetLineHeight() const = 0; virtual const CHAR_INFO* GetCharInfo(int nID) const = 0; virtual float GetKerning(int nFirstID, int nSecondID) const = 0; }; #endif // __IOEUIFONT_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 47 ] ] ]
e724d93c6795d753cf65f52d3c52bf59ebec0960
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/emu/cpu/uml.h
3e685cbdd8990a41e82ce986d8d3e11eb4801a9a
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,036
h
/*************************************************************************** uml.h Universal machine language definitions and classes. **************************************************************************** Copyright Aaron Giles 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 'MAME' 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 AARON GILES ''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 AARON GILES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #pragma once #ifndef __UML_H__ #define __UML_H__ #include "drccache.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // opaque structure describing UML generation state class drcuml_state; struct drcuml_machine_state; // use a namespace to wrap all the UML instruction concepts so that // we can keep names short namespace uml { // integer registers const int REG_I0 = 0x400; const int REG_I_COUNT = 10; const int REG_I_END = REG_I0 + REG_I_COUNT; // floating point registers const int REG_F0 = 0x800; const int REG_F_COUNT = 10; const int REG_F_END = REG_F0 + REG_F_COUNT; // vector registers const int REG_V0 = 0xc00; const int REG_V_COUNT = 10; const int REG_V_END = REG_V0 + REG_V_COUNT; // map variables const int MAPVAR_M0 = 0x1000; const int MAPVAR_COUNT = 10; const int MAPVAR_END = MAPVAR_M0 + MAPVAR_COUNT; // flag definitions const UINT8 FLAG_C = 0x01; // carry flag const UINT8 FLAG_V = 0x02; // overflow flag (defined for integer only) const UINT8 FLAG_Z = 0x04; // zero flag const UINT8 FLAG_S = 0x08; // sign flag (defined for integer only) const UINT8 FLAG_U = 0x10; // unordered flag (defined for FP only) // testable conditions; note that these are defined such that (condition ^ 1) is // always the opposite enum condition_t { COND_ALWAYS = 0, COND_Z = 0x80, // requires Z COND_NZ, // requires Z COND_S, // requires S COND_NS, // requires S COND_C, // requires C COND_NC, // requires C COND_V, // requires V COND_NV, // requires V COND_U, // requires U COND_NU, // requires U COND_A, // requires CZ COND_BE, // requires CZ COND_G, // requires SVZ COND_LE, // requires SVZ COND_L, // requires SV COND_GE, // requires SV COND_MAX, // basic condition code aliases COND_E = COND_Z, COND_NE = COND_NZ, COND_B = COND_C, COND_AE = COND_NC }; // floating point rounding modes enum float_rounding_mode { ROUND_TRUNC = 0, // truncate ROUND_ROUND, // round ROUND_CEIL, // round up ROUND_FLOOR, // round down ROUND_DEFAULT }; // operand sizes enum operand_size { SIZE_BYTE = 0, // 1-byte SIZE_WORD, // 2-byte SIZE_DWORD, // 4-byte SIZE_QWORD, // 8-byte SIZE_DQWORD, // 16-byte (vector) SIZE_SHORT = SIZE_DWORD, // 4-byte (float) SIZE_DOUBLE = SIZE_QWORD // 8-byte (float) }; // memory scale factors enum memory_scale { SCALE_x1 = 0, // index * 1 SCALE_x2, // index * 2 SCALE_x4, // index * 4 SCALE_x8, // index * 8 SCALE_DEFAULT }; // spaces enum memory_space { SPACE_PROGRAM = AS_PROGRAM, SPACE_DATA = AS_DATA, SPACE_IO = AS_IO }; // opcodes enum opcode_t { OP_INVALID, // compile-time opcodes OP_HANDLE, // HANDLE handle OP_HASH, // HASH mode,pc OP_LABEL, // LABEL imm OP_COMMENT, // COMMENT string OP_MAPVAR, // MAPVAR mapvar,value // control flow operations OP_NOP, // NOP OP_DEBUG, // DEBUG pc OP_EXIT, // EXIT src1[,c] OP_HASHJMP, // HASHJMP mode,pc,handle OP_JMP, // JMP imm[,c] OP_EXH, // EXH handle,param[,c] OP_CALLH, // CALLH handle[,c] OP_RET, // RET [c] OP_CALLC, // CALLC func,ptr[,c] OP_RECOVER, // RECOVER dst,mapvar // internal register operations OP_SETFMOD, // SETFMOD src OP_GETFMOD, // GETFMOD dst OP_GETEXP, // GETEXP dst OP_GETFLGS, // GETFLGS dst[,f] OP_SAVE, // SAVE mem OP_RESTORE, // RESTORE mem // integer operations OP_LOAD, // LOAD dst,base,index,size OP_LOADS, // LOADS dst,base,index,size OP_STORE, // STORE base,index,src,size OP_READ, // READ dst,src1,space/size OP_READM, // READM dst,src1,mask,space/size OP_WRITE, // WRITE dst,src1,space/size OP_WRITEM, // WRITEM dst,mask,src1,space/size OP_CARRY, // CARRY src,bitnum OP_SET, // SET dst,c OP_MOV, // MOV dst,src[,c] OP_SEXT, // SEXT dst,src,size OP_ROLAND, // ROLAND dst,src,shift,mask OP_ROLINS, // ROLINS dst,src,shift,mask OP_ADD, // ADD dst,src1,src2[,f] OP_ADDC, // ADDC dst,src1,src2[,f] OP_SUB, // SUB dst,src1,src2[,f] OP_SUBB, // SUBB dst,src1,src2[,f] OP_CMP, // CMP src1,src2[,f] OP_MULU, // MULU dst,edst,src1,src2[,f] OP_MULS, // MULS dst,edst,src1,src2[,f] OP_DIVU, // DIVU dst,edst,src1,src2[,f] OP_DIVS, // DIVS dst,edst,src1,src2[,f] OP_AND, // AND dst,src1,src2[,f] OP_TEST, // TEST src1,src2[,f] OP_OR, // OR dst,src1,src2[,f] OP_XOR, // XOR dst,src1,src2[,f] OP_LZCNT, // LZCNT dst,src OP_BSWAP, // BSWAP dst,src OP_SHL, // SHL dst,src,count[,f] OP_SHR, // SHR dst,src,count[,f] OP_SAR, // SAR dst,src,count[,f] OP_ROL, // ROL dst,src,count[,f] OP_ROLC, // ROLC dst,src,count[,f] OP_ROR, // ROL dst,src,count[,f] OP_RORC, // ROLC dst,src,count[,f] // floating point operations OP_FLOAD, // FLOAD dst,base,index OP_FSTORE, // FSTORE base,index,src OP_FREAD, // FREAD dst,space,src1 OP_FWRITE, // FWRITE space,dst,src1 OP_FMOV, // FMOV dst,src1[,c] OP_FTOINT, // FTOINT dst,src1,size,round OP_FFRINT, // FFRINT dst,src1,size OP_FFRFLT, // FFRFLT dst,src1,size OP_FRNDS, // FRNDS dst,src1 OP_FADD, // FADD dst,src1,src2 OP_FSUB, // FSUB dst,src1,src2 OP_FCMP, // FCMP src1,src2 OP_FMUL, // FMUL dst,src1,src2 OP_FDIV, // FDIV dst,src1,src2 OP_FNEG, // FNEG dst,src1 OP_FABS, // FABS dst,src1 OP_FSQRT, // FSQRT dst,src1 OP_FRECIP, // FRECIP dst,src1 OP_FRSQRT, // FRSQRT dst,src1 OP_MAX }; // C function callback deinition typedef void (*c_function)(void *ptr); // class describing a global code handle class code_handle { friend class ::drcuml_state; template<class T> friend class ::simple_list; // construction/destruction code_handle(drcuml_state &drcuml, const char *name); public: // getters code_handle *next() const { return m_next; } drccodeptr codeptr() const { return *m_code; } drccodeptr *codeptr_addr() { return m_code; } const char *string() const { return m_string; } // setters void set_codeptr(drccodeptr code); private: // internal state drccodeptr * m_code; // pointer in the cache to the associated code astring m_string; // pointer to string attached to handle code_handle * m_next; // link to next handle in the list drcuml_state & m_drcuml; // pointer to owning object }; // class describing a local code label class code_label { public: // construction code_label(UINT32 label = 0) : m_label(label) { } // operators operator UINT32 &() { return m_label; } bool operator==(const code_label &rhs) const { return (m_label == rhs.m_label); } bool operator!=(const code_label &rhs) const { return (m_label != rhs.m_label); } // getters UINT32 label() const { return m_label; } private: UINT32 m_label; }; // a parameter for a UML instructon is encoded like this class parameter { public: // opcode parameter types enum parameter_type { PTYPE_NONE = 0, // invalid PTYPE_IMMEDIATE, // immediate; value = sign-extended to 64 bits PTYPE_INT_REGISTER, // integer register; value = REG_I0 - REG_I_END PTYPE_FLOAT_REGISTER, // floating point register; value = REG_F0 - REG_F_END PTYPE_VECTOR_REGISTER, // vector register; value = REG_V0 - REG_V_END PTYPE_MAPVAR, // map variable; value = MAPVAR_M0 - MAPVAR_END PTYPE_MEMORY, // memory; value = pointer to memory PTYPE_SIZE, // size; value = operand_size PTYPE_SIZE_SCALE, // scale + size; value = memory_scale * 16 + operand_size PTYPE_SIZE_SPACE, // space + size; value = memory_space * 16 + operand_size PTYPE_CODE_HANDLE, // code handle; value = pointer to handle PTYPE_CODE_LABEL, // code label; value = label index PTYPE_C_FUNCTION, // C function; value = pointer to C code PTYPE_ROUNDING, // floating point rounding mode; value = float_rounding_mode PTYPE_STRING, // string parameter; value = pointer to string PTYPE_MAX }; // represents the value of an opcode parameter typedef UINT64 parameter_value; // construction parameter() : m_type(PTYPE_NONE), m_value(0) { } parameter(const parameter &param) : m_type(param.m_type), m_value(param.m_value) { } parameter(UINT64 val) : m_type(PTYPE_IMMEDIATE), m_value(val) { } parameter(operand_size size, memory_scale scale) : m_type(PTYPE_SIZE_SCALE), m_value((scale << 4) | size) { assert(size >= SIZE_BYTE && size <= SIZE_DQWORD); assert(scale >= SCALE_x1 && scale <= SCALE_x8); } parameter(operand_size size, memory_space space) : m_type(PTYPE_SIZE_SPACE), m_value((space << 4) | size) { assert(size >= SIZE_BYTE && size <= SIZE_DQWORD); assert(space >= SPACE_PROGRAM && space <= SPACE_IO); } parameter(code_handle &handle) : m_type(PTYPE_CODE_HANDLE), m_value(reinterpret_cast<parameter_value>(&handle)) { } parameter(code_label &label) : m_type(PTYPE_CODE_LABEL), m_value(label) { } // creators for types that don't safely default static inline parameter make_ireg(int regnum) { assert(regnum >= REG_I0 && regnum < REG_I_END); return parameter(PTYPE_INT_REGISTER, regnum); } static inline parameter make_freg(int regnum) { assert(regnum >= REG_F0 && regnum < REG_F_END); return parameter(PTYPE_FLOAT_REGISTER, regnum); } static inline parameter make_vreg(int regnum) { assert(regnum >= REG_V0 && regnum < REG_V_END); return parameter(PTYPE_VECTOR_REGISTER, regnum); } static inline parameter make_mapvar(int mvnum) { assert(mvnum >= MAPVAR_M0 && mvnum < MAPVAR_END); return parameter(PTYPE_MAPVAR, mvnum); } static inline parameter make_memory(void *base) { return parameter(PTYPE_MEMORY, reinterpret_cast<parameter_value>(base)); } static inline parameter make_memory(const void *base) { return parameter(PTYPE_MEMORY, reinterpret_cast<parameter_value>(const_cast<void *>(base))); } static inline parameter make_size(operand_size size) { assert(size >= SIZE_BYTE && size <= SIZE_DQWORD); return parameter(PTYPE_SIZE, size); } static inline parameter make_string(const char *string) { return parameter(PTYPE_STRING, reinterpret_cast<parameter_value>(const_cast<char *>(string))); } static inline parameter make_cfunc(c_function func) { return parameter(PTYPE_C_FUNCTION, reinterpret_cast<parameter_value>(func)); } static inline parameter make_rounding(float_rounding_mode mode) { assert(mode >= ROUND_TRUNC && mode <= ROUND_DEFAULT); return parameter(PTYPE_ROUNDING, mode); } // operators bool operator==(const parameter &rhs) const { return (m_type == rhs.m_type && m_value == rhs.m_value); } bool operator!=(const parameter &rhs) const { return (m_type != rhs.m_type || m_value != rhs.m_value); } // getters parameter_type type() const { return m_type; } UINT64 immediate() const { assert(m_type == PTYPE_IMMEDIATE); return m_value; } int ireg() const { assert(m_type == PTYPE_INT_REGISTER); assert(m_value >= REG_I0 && m_value < REG_I_END); return m_value; } int freg() const { assert(m_type == PTYPE_FLOAT_REGISTER); assert(m_value >= REG_F0 && m_value < REG_F_END); return m_value; } int vreg() const { assert(m_type == PTYPE_VECTOR_REGISTER); assert(m_value >= REG_V0 && m_value < REG_V_END); return m_value; } int mapvar() const { assert(m_type == PTYPE_MAPVAR); assert(m_value >= MAPVAR_M0 && m_value < MAPVAR_END); return m_value; } void *memory() const { assert(m_type == PTYPE_MEMORY); return reinterpret_cast<void *>(m_value); } operand_size size() const { assert(m_type == PTYPE_SIZE || m_type == PTYPE_SIZE_SCALE || m_type == PTYPE_SIZE_SPACE); return operand_size(m_value & 15); } memory_scale scale() const { assert(m_type == PTYPE_SIZE_SCALE); return memory_scale(m_value >> 4); } memory_space space() const { assert(m_type == PTYPE_SIZE_SPACE); return memory_space(m_value >> 4); } code_handle &handle() const { assert(m_type == PTYPE_CODE_HANDLE); return *reinterpret_cast<code_handle *>(m_value); } code_label label() const { assert(m_type == PTYPE_CODE_LABEL); return code_label(m_value); } c_function cfunc() const { assert(m_type == PTYPE_C_FUNCTION); return reinterpret_cast<c_function>(m_value); } float_rounding_mode rounding() const { assert(m_type == PTYPE_ROUNDING); return float_rounding_mode(m_value); } const char *string() const { assert(m_type == PTYPE_STRING); return reinterpret_cast<const char *>(m_value); } // type queries bool is_immediate() const { return (m_type == PTYPE_IMMEDIATE); } bool is_int_register() const { return (m_type == PTYPE_INT_REGISTER); } bool is_float_register() const { return (m_type == PTYPE_FLOAT_REGISTER); } bool is_vector_register() const { return (m_type == PTYPE_VECTOR_REGISTER); } bool is_mapvar() const { return (m_type == PTYPE_MAPVAR); } bool is_memory() const { return (m_type == PTYPE_MEMORY); } bool is_size() const { return (m_type == PTYPE_SIZE); } bool is_size_scale() const { return (m_type == PTYPE_SIZE_SCALE); } bool is_size_space() const { return (m_type == PTYPE_SIZE_SPACE); } bool is_code_handle() const { return (m_type == PTYPE_CODE_HANDLE); } bool is_code_label() const { return (m_type == PTYPE_CODE_LABEL); } bool is_c_function() const { return (m_type == PTYPE_C_FUNCTION); } bool is_rounding() const { return (m_type == PTYPE_ROUNDING); } bool is_string() const { return (m_type == PTYPE_STRING); } // other queries bool is_immediate_value(UINT64 value) const { return (m_type == PTYPE_IMMEDIATE && m_value == value); } private: // private constructor parameter(parameter_type type, parameter_value value) : m_type(type), m_value(value) { } // internals parameter_type m_type; // parameter type parameter_value m_value; // parameter value }; // structure describing rules for opcode encoding struct opcode_info { struct parameter_info { UINT8 output; // input or output? UINT8 size; // size of the parameter UINT16 typemask; // types allowed }; opcode_t opcode; // the opcode itself const char * mnemonic; // mnemonic string UINT8 sizes; // allowed sizes bool condition; // conditions allowed? UINT8 inflags; // input flags UINT8 outflags; // output flags UINT8 modflags; // modified flags parameter_info param[4]; // information about parameters }; // a single UML instructon is encoded like this class instruction { public: // construction/destruction instruction(); // getters opcode_t opcode() const { return m_opcode; } condition_t condition() const { return m_condition; } UINT8 flags() const { return m_flags; } UINT8 size() const { return m_size; } UINT8 numparams() const { return m_numparams; } const parameter &param(int index) const { assert(index < m_numparams); return m_param[index]; } // setters void set_flags(UINT8 flags) { m_flags = flags; } void set_mapvar(int paramnum, UINT32 value) { assert(paramnum < m_numparams); assert(m_param[paramnum].is_mapvar()); m_param[paramnum] = value; } // misc const char *disasm(astring &string, drcuml_state *drcuml = NULL) const; UINT8 input_flags() const; UINT8 output_flags() const; UINT8 modified_flags() const; void simplify(); // compile-time opcodes void handle(code_handle &hand) { configure(OP_HANDLE, 4, hand); } void hash(UINT32 mode, UINT32 pc) { configure(OP_HASH, 4, mode, pc); } void label(code_label lab) { configure(OP_LABEL, 4, lab); } void comment(const char *string) { configure(OP_COMMENT, 4, parameter::make_string(string)); } void mapvar(parameter mapvar, UINT32 value) { assert(mapvar.is_mapvar()); configure(OP_MAPVAR, 4, mapvar, value); } // control flow operations void nop() { configure(OP_NOP, 4); } void debug(UINT32 pc) { configure(OP_DEBUG, 4, pc); } void exit(parameter param) { configure(OP_EXIT, 4, param); } void exit(condition_t cond, parameter param) { configure(OP_EXIT, 4, param, cond); } void hashjmp(parameter mode, parameter pc, code_handle &handle) { configure(OP_HASHJMP, 4, mode, pc, handle); } void jmp(code_label label) { configure(OP_JMP, 4, label); } void jmp(condition_t cond, code_label label) { configure(OP_JMP, 4, label, cond); } void exh(code_handle &handle, parameter param) { configure(OP_EXH, 4, handle, param); } void exh(condition_t cond, code_handle &handle, parameter param) { configure(OP_EXH, 4, handle, param, cond); } void callh(code_handle &handle) { configure(OP_CALLH, 4, handle); } void callh(condition_t cond, code_handle &handle) { configure(OP_CALLH, 4, handle, cond); } void ret() { configure(OP_RET, 4); } void ret(condition_t cond) { configure(OP_RET, 4, cond); } void callc(c_function func, void *ptr) { configure(OP_CALLC, 4, parameter::make_cfunc(func), parameter::make_memory(ptr)); } void callc(condition_t cond, c_function func, void *ptr) { configure(OP_CALLC, 4, parameter::make_cfunc(func), parameter::make_memory(ptr), cond); } void recover(parameter dst, parameter mapvar) { assert(mapvar.is_mapvar()); configure(OP_RECOVER, 4, dst, mapvar); } // internal register operations void setfmod(parameter mode) { configure(OP_SETFMOD, 4, mode); } void getfmod(parameter dst) { configure(OP_GETFMOD, 4, dst); } void getexp(parameter dst) { configure(OP_GETEXP, 4, dst); } void getflgs(parameter dst, UINT32 flags) { configure(OP_GETFLGS, 4, dst, flags); } void save(drcuml_machine_state *dst) { configure(OP_SAVE, 4, parameter::make_memory(dst)); } void restore(drcuml_machine_state *src) { configure(OP_RESTORE, 4, parameter::make_memory(src)); } // 32-bit integer operations void load(parameter dst, const void *base, parameter index, operand_size size, memory_scale scale = SCALE_DEFAULT) { configure(OP_LOAD, 4, dst, parameter::make_memory(base), index, parameter(size, scale)); } void loads(parameter dst, const void *base, parameter index, operand_size size, memory_scale scale = SCALE_DEFAULT) { configure(OP_LOADS, 4, dst, parameter::make_memory(base), index, parameter(size, scale)); } void store(void *base, parameter index, parameter src1, operand_size size, memory_scale scale = SCALE_DEFAULT) { configure(OP_STORE, 4, parameter::make_memory(base), index, src1, parameter(size, scale)); } void read(parameter dst, parameter src1, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_READ, 4, dst, src1, parameter(size, space)); } void readm(parameter dst, parameter src1, parameter mask, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_READM, 4, dst, src1, mask, parameter(size, space)); } void write(parameter dst, parameter src1, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_WRITE, 4, dst, src1, parameter(size, space)); } void writem(parameter dst, parameter src1, parameter mask, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_WRITEM, 4, dst, src1, mask, parameter(size, space)); } void carry(parameter src, parameter bitnum) { configure(OP_CARRY, 4, src, bitnum); } void set(condition_t cond, parameter dst) { configure(OP_SET, 4, dst, cond); } void mov(parameter dst, parameter src1) { configure(OP_MOV, 4, dst, src1); } void mov(condition_t cond, parameter dst, parameter src1) { configure(OP_MOV, 4, dst, src1, cond); } void sext(parameter dst, parameter src1, operand_size size) { configure(OP_SEXT, 4, dst, src1, parameter::make_size(size)); } void roland(parameter dst, parameter src, parameter shift, parameter mask) { configure(OP_ROLAND, 4, dst, src, shift, mask); } void rolins(parameter dst, parameter src, parameter shift, parameter mask) { configure(OP_ROLINS, 4, dst, src, shift, mask); } void add(parameter dst, parameter src1, parameter src2) { configure(OP_ADD, 4, dst, src1, src2); } void addc(parameter dst, parameter src1, parameter src2) { configure(OP_ADDC, 4, dst, src1, src2); } void sub(parameter dst, parameter src1, parameter src2) { configure(OP_SUB, 4, dst, src1, src2); } void subb(parameter dst, parameter src1, parameter src2) { configure(OP_SUBB, 4, dst, src1, src2); } void cmp(parameter src1, parameter src2) { configure(OP_CMP, 4, src1, src2); } void mulu(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_MULU, 4, dst, edst, src1, src2); } void muls(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_MULS, 4, dst, edst, src1, src2); } void divu(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_DIVU, 4, dst, edst, src1, src2); } void divs(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_DIVS, 4, dst, edst, src1, src2); } void _and(parameter dst, parameter src1, parameter src2) { configure(OP_AND, 4, dst, src1, src2); } void test(parameter src1, parameter src2) { configure(OP_TEST, 4, src1, src2); } void _or(parameter dst, parameter src1, parameter src2) { configure(OP_OR, 4, dst, src1, src2); } void _xor(parameter dst, parameter src1, parameter src2) { configure(OP_XOR, 4, dst, src1, src2); } void lzcnt(parameter dst, parameter src) { configure(OP_LZCNT, 4, dst, src); } void bswap(parameter dst, parameter src) { configure(OP_BSWAP, 4, dst, src); } void shl(parameter dst, parameter src, parameter count) { configure(OP_SHL, 4, dst, src, count); } void shr(parameter dst, parameter src, parameter count) { configure(OP_SHR, 4, dst, src, count); } void sar(parameter dst, parameter src, parameter count) { configure(OP_SAR, 4, dst, src, count); } void rol(parameter dst, parameter src, parameter count) { configure(OP_ROL, 4, dst, src, count); } void rolc(parameter dst, parameter src, parameter count) { configure(OP_ROLC, 4, dst, src, count); } void ror(parameter dst, parameter src, parameter count) { configure(OP_ROR, 4, dst, src, count); } void rorc(parameter dst, parameter src, parameter count) { configure(OP_RORC, 4, dst, src, count); } // 64-bit integer operations void dload(parameter dst, const void *base, parameter index, operand_size size, memory_scale scale = SCALE_DEFAULT) { configure(OP_LOAD, 8, dst, parameter::make_memory(base), index, parameter(size, scale)); } void dloads(parameter dst, const void *base, parameter index, operand_size size, memory_scale scale = SCALE_DEFAULT) { configure(OP_LOADS, 8, dst, parameter::make_memory(base), index, parameter(size, scale)); } void dstore(void *base, parameter index, parameter src1, operand_size size, memory_scale scale = SCALE_DEFAULT) { configure(OP_STORE, 8, parameter::make_memory(base), index, src1, parameter(size, scale)); } void dread(parameter dst, parameter src1, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_READ, 8, dst, src1, parameter(size, space)); } void dreadm(parameter dst, parameter src1, parameter mask, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_READM, 8, dst, src1, mask, parameter(size, space)); } void dwrite(parameter dst, parameter src1, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_WRITE, 8, dst, src1, parameter(size, space)); } void dwritem(parameter dst, parameter src1, parameter mask, operand_size size, memory_space space = SPACE_PROGRAM) { configure(OP_WRITEM, 8, dst, src1, mask, parameter(size, space)); } void dcarry(parameter src, parameter bitnum) { configure(OP_CARRY, 8, src, bitnum); } void dset(condition_t cond, parameter dst) { configure(OP_SET, 8, dst, cond); } void dmov(parameter dst, parameter src1) { configure(OP_MOV, 8, dst, src1); } void dmov(condition_t cond, parameter dst, parameter src1) { configure(OP_MOV, 8, dst, src1, cond); } void dsext(parameter dst, parameter src1, operand_size size) { configure(OP_SEXT, 8, dst, src1, parameter::make_size(size)); } void droland(parameter dst, parameter src, parameter shift, parameter mask) { configure(OP_ROLAND, 8, dst, src, shift, mask); } void drolins(parameter dst, parameter src, parameter shift, parameter mask) { configure(OP_ROLINS, 8, dst, src, shift, mask); } void dadd(parameter dst, parameter src1, parameter src2) { configure(OP_ADD, 8, dst, src1, src2); } void daddc(parameter dst, parameter src1, parameter src2) { configure(OP_ADDC, 8, dst, src1, src2); } void dsub(parameter dst, parameter src1, parameter src2) { configure(OP_SUB, 8, dst, src1, src2); } void dsubb(parameter dst, parameter src1, parameter src2) { configure(OP_SUBB, 8, dst, src1, src2); } void dcmp(parameter src1, parameter src2) { configure(OP_CMP, 8, src1, src2); } void dmulu(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_MULU, 8, dst, edst, src1, src2); } void dmuls(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_MULS, 8, dst, edst, src1, src2); } void ddivu(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_DIVU, 8, dst, edst, src1, src2); } void ddivs(parameter dst, parameter edst, parameter src1, parameter src2) { configure(OP_DIVS, 8, dst, edst, src1, src2); } void dand(parameter dst, parameter src1, parameter src2) { configure(OP_AND, 8, dst, src1, src2); } void dtest(parameter src1, parameter src2) { configure(OP_TEST, 8, src1, src2); } void dor(parameter dst, parameter src1, parameter src2) { configure(OP_OR, 8, dst, src1, src2); } void dxor(parameter dst, parameter src1, parameter src2) { configure(OP_XOR, 8, dst, src1, src2); } void dlzcnt(parameter dst, parameter src) { configure(OP_LZCNT, 8, dst, src); } void dbswap(parameter dst, parameter src) { configure(OP_BSWAP, 8, dst, src); } void dshl(parameter dst, parameter src, parameter count) { configure(OP_SHL, 8, dst, src, count); } void dshr(parameter dst, parameter src, parameter count) { configure(OP_SHR, 8, dst, src, count); } void dsar(parameter dst, parameter src, parameter count) { configure(OP_SAR, 8, dst, src, count); } void drol(parameter dst, parameter src, parameter count) { configure(OP_ROL, 8, dst, src, count); } void drolc(parameter dst, parameter src, parameter count) { configure(OP_ROLC, 8, dst, src, count); } void dror(parameter dst, parameter src, parameter count) { configure(OP_ROR, 8, dst, src, count); } void drorc(parameter dst, parameter src, parameter count) { configure(OP_RORC, 8, dst, src, count); } // 32-bit floating point operations void fsload(parameter dst, const void *base, parameter index) { configure(OP_FLOAD, 4, dst, parameter::make_memory(base), index); } void fsstore(void *base, parameter index, parameter src1) { configure(OP_FSTORE, 4, parameter::make_memory(base), index, src1); } void fsread(parameter dst, parameter src1, memory_space space) { configure(OP_FREAD, 4, dst, src1, parameter(SIZE_SHORT, space)); } void fswrite(parameter dst, parameter src1, memory_space space) { configure(OP_FWRITE, 4, dst, src1, parameter(SIZE_SHORT, space)); } void fsmov(parameter dst, parameter src1) { configure(OP_FMOV, 4, dst, src1); } void fsmov(condition_t cond, parameter dst, parameter src1) { configure(OP_FMOV, 4, dst, src1, cond); } void fstoint(parameter dst, parameter src1, operand_size size, float_rounding_mode round) { configure(OP_FTOINT, 4, dst, src1, parameter::make_size(size), parameter::make_rounding(round)); } void fsfrint(parameter dst, parameter src1, operand_size size) { configure(OP_FFRINT, 4, dst, src1, parameter::make_size(size)); } void fsfrflt(parameter dst, parameter src1, operand_size size) { configure(OP_FFRFLT, 4, dst, src1, parameter::make_size(size)); } void fsadd(parameter dst, parameter src1, parameter src2) { configure(OP_FADD, 4, dst, src1, src2); } void fssub(parameter dst, parameter src1, parameter src2) { configure(OP_FSUB, 4, dst, src1, src2); } void fscmp(parameter src1, parameter src2) { configure(OP_FCMP, 4, src1, src2); } void fsmul(parameter dst, parameter src1, parameter src2) { configure(OP_FMUL, 4, dst, src1, src2); } void fsdiv(parameter dst, parameter src1, parameter src2) { configure(OP_FDIV, 4, dst, src1, src2); } void fsneg(parameter dst, parameter src1) { configure(OP_FNEG, 4, dst, src1); } void fsabs(parameter dst, parameter src1) { configure(OP_FABS, 4, dst, src1); } void fssqrt(parameter dst, parameter src1) { configure(OP_FSQRT, 4, dst, src1); } void fsrecip(parameter dst, parameter src1) { configure(OP_FRECIP, 4, dst, src1); } void fsrsqrt(parameter dst, parameter src1) { configure(OP_FRSQRT, 4, dst, src1); } // 64-bit floating point operations void fdload(parameter dst, const void *base, parameter index) { configure(OP_FLOAD, 8, dst, parameter::make_memory(base), index); } void fdstore(void *base, parameter index, parameter src1) { configure(OP_FSTORE, 8, parameter::make_memory(base), index, src1); } void fdread(parameter dst, parameter src1, memory_space space) { configure(OP_FREAD, 8, dst, src1, parameter(SIZE_DOUBLE, space)); } void fdwrite(parameter dst, parameter src1, memory_space space) { configure(OP_FWRITE, 8, dst, src1, parameter(SIZE_DOUBLE, space)); } void fdmov(parameter dst, parameter src1) { configure(OP_FMOV, 8, dst, src1); } void fdmov(condition_t cond, parameter dst, parameter src1) { configure(OP_FMOV, 8, dst, src1, cond); } void fdtoint(parameter dst, parameter src1, operand_size size, float_rounding_mode round) { configure(OP_FTOINT, 8, dst, src1, parameter::make_size(size), parameter::make_rounding(round)); } void fdfrint(parameter dst, parameter src1, operand_size size) { configure(OP_FFRINT, 8, dst, src1, parameter::make_size(size)); } void fdfrflt(parameter dst, parameter src1, operand_size size) { configure(OP_FFRFLT, 8, dst, src1, parameter::make_size(size)); } void fdrnds(parameter dst, parameter src1) { configure(OP_FRNDS, 8, dst, src1); } void fdadd(parameter dst, parameter src1, parameter src2) { configure(OP_FADD, 8, dst, src1, src2); } void fdsub(parameter dst, parameter src1, parameter src2) { configure(OP_FSUB, 8, dst, src1, src2); } void fdcmp(parameter src1, parameter src2) { configure(OP_FCMP, 8, src1, src2); } void fdmul(parameter dst, parameter src1, parameter src2) { configure(OP_FMUL, 8, dst, src1, src2); } void fddiv(parameter dst, parameter src1, parameter src2) { configure(OP_FDIV, 8, dst, src1, src2); } void fdneg(parameter dst, parameter src1) { configure(OP_FNEG, 8, dst, src1); } void fdabs(parameter dst, parameter src1) { configure(OP_FABS, 8, dst, src1); } void fdsqrt(parameter dst, parameter src1) { configure(OP_FSQRT, 8, dst, src1); } void fdrecip(parameter dst, parameter src1) { configure(OP_FRECIP, 8, dst, src1); } void fdrsqrt(parameter dst, parameter src1) { configure(OP_FRSQRT, 8, dst, src1); } // constants static const int MAX_PARAMS = 4; private: // internal configuration void configure(opcode_t op, UINT8 size, condition_t cond = COND_ALWAYS); void configure(opcode_t op, UINT8 size, parameter p0, condition_t cond = COND_ALWAYS); void configure(opcode_t op, UINT8 size, parameter p0, parameter p1, condition_t cond = COND_ALWAYS); void configure(opcode_t op, UINT8 size, parameter p0, parameter p1, parameter p2, condition_t cond = COND_ALWAYS); void configure(opcode_t op, UINT8 size, parameter p0, parameter p1, parameter p2, parameter p3, condition_t cond = COND_ALWAYS); // opcode validation and simplification void validate(); void convert_to_mov_immediate(UINT64 immediate) { m_opcode = OP_MOV; m_numparams = 2; m_param[1] = immediate; } void convert_to_mov_param(int pnum) { m_opcode = OP_MOV; m_numparams = 2; m_param[1] = m_param[pnum]; } // internal state opcode_t m_opcode; // opcode condition_t m_condition; // condition UINT8 m_flags; // flags UINT8 m_size; // operation size UINT8 m_numparams; // number of parameters parameter m_param[MAX_PARAMS];// up to 4 parameters static const opcode_info s_opcode_info_table[OP_MAX]; }; // structure describing rules for parameter encoding struct parameter_info { UINT8 output; // input or output? UINT8 size; // size of the parameter UINT16 typemask; // types allowed }; // global inline functions to specify a register parameter by index inline parameter ireg(int n) { return parameter::make_ireg(REG_I0 + n); } inline parameter freg(int n) { return parameter::make_freg(REG_F0 + n); } inline parameter vreg(int n) { return parameter::make_vreg(REG_V0 + n); } inline parameter mapvar(int n) { return parameter::make_mapvar(MAPVAR_M0 + n); } // global inline functions to define memory parameters inline parameter mem(const void *ptr) { return parameter::make_memory(ptr); } // global register objects for direct access const parameter I0(parameter::make_ireg(REG_I0 + 0)); const parameter I1(parameter::make_ireg(REG_I0 + 1)); const parameter I2(parameter::make_ireg(REG_I0 + 2)); const parameter I3(parameter::make_ireg(REG_I0 + 3)); const parameter I4(parameter::make_ireg(REG_I0 + 4)); const parameter I5(parameter::make_ireg(REG_I0 + 5)); const parameter I6(parameter::make_ireg(REG_I0 + 6)); const parameter I7(parameter::make_ireg(REG_I0 + 7)); const parameter I8(parameter::make_ireg(REG_I0 + 8)); const parameter I9(parameter::make_ireg(REG_I0 + 9)); const parameter F0(parameter::make_freg(REG_F0 + 0)); const parameter F1(parameter::make_freg(REG_F0 + 1)); const parameter F2(parameter::make_freg(REG_F0 + 2)); const parameter F3(parameter::make_freg(REG_F0 + 3)); const parameter F4(parameter::make_freg(REG_F0 + 4)); const parameter F5(parameter::make_freg(REG_F0 + 5)); const parameter F6(parameter::make_freg(REG_F0 + 6)); const parameter F7(parameter::make_freg(REG_F0 + 7)); const parameter F8(parameter::make_freg(REG_F0 + 8)); const parameter F9(parameter::make_freg(REG_F0 + 9)); const parameter V0(parameter::make_vreg(REG_V0 + 0)); const parameter V1(parameter::make_vreg(REG_V0 + 1)); const parameter V2(parameter::make_vreg(REG_V0 + 2)); const parameter V3(parameter::make_vreg(REG_V0 + 3)); const parameter V4(parameter::make_vreg(REG_V0 + 4)); const parameter V5(parameter::make_vreg(REG_V0 + 5)); const parameter V6(parameter::make_vreg(REG_V0 + 6)); const parameter V7(parameter::make_vreg(REG_V0 + 7)); const parameter V8(parameter::make_vreg(REG_V0 + 8)); const parameter V9(parameter::make_vreg(REG_V0 + 9)); const parameter M0(parameter::make_mapvar(MAPVAR_M0 + 0)); const parameter M1(parameter::make_mapvar(MAPVAR_M0 + 1)); const parameter M2(parameter::make_mapvar(MAPVAR_M0 + 2)); const parameter M3(parameter::make_mapvar(MAPVAR_M0 + 3)); const parameter M4(parameter::make_mapvar(MAPVAR_M0 + 4)); const parameter M5(parameter::make_mapvar(MAPVAR_M0 + 5)); const parameter M6(parameter::make_mapvar(MAPVAR_M0 + 6)); const parameter M7(parameter::make_mapvar(MAPVAR_M0 + 7)); const parameter M8(parameter::make_mapvar(MAPVAR_M0 + 8)); const parameter M9(parameter::make_mapvar(MAPVAR_M0 + 9)); }; #endif /* __UML_H__ */
[ "Mike@localhost" ]
[ [ [ 1, 690 ] ] ]
c8ec6bfa3ada1bd7037fef16a8951d4dd0078417
6188f1aaaf5508e046cde6da16b56feb3d5914bc
/CamFighter/Physics/PhysicalBody.h
9603358625c2814acec0cc3ea35ec2760c3b1071
[]
no_license
dogtwelve/fighter3d
7bb099f0dc396e8224c573743ee28c54cdd3d5a2
c073194989bc1589e4aa665714c5511f001e6400
refs/heads/master
2021-04-30T15:58:11.300681
2011-06-27T18:51:30
2011-06-27T18:51:30
33,675,635
1
0
null
null
null
null
UTF-8
C++
false
false
2,418
h
#ifndef __incl_Physics_PhysicalBody_h #define __incl_Physics_PhysicalBody_h #include "IPhysicalBody.h" #include "Constants.h" namespace Physics { class PhysicalBody : public IPhysicalBody { public: xVector3 NW_velocity; xVector3 NW_velocity_new; // REWRITE: Should be sth. different to store velocity of rotation. // QT may only store up to 720 degrees of rotation, faster rotations can't exist. xQuaternion QT_velocity; xQuaternion QT_velocity_new; xFLOAT M_mass; public: virtual void Stop() { NW_velocity.zero(); QT_velocity.zeroQ(); NW_velocity_new.zero(); QT_velocity_new.zeroQ(); } virtual xFLOAT GetMass() const { return M_mass; } virtual xVector3 GetVelocity() const { return NW_velocity; } virtual xVector3 GetVelocity(const CollisionPoint &CP_point) const { return NW_velocity + xVector3::CrossProduct(QT_velocity.angularVelocity(), CP_point.P_collision - P_center_Trfm); } virtual void ApplyFix(const CollisionPoint &CP_point) { MX_LocalToWorld_Set().postTranslateT(CP_point.NW_fix * CP_point.W_fix); } virtual void ApplyAcceleration(const xVector3 &NW_accel, xFLOAT T_time) { NW_velocity_new += NW_accel * T_time; } virtual void ApplyAcceleration(const xVector3 &NW_accel, xFLOAT T_time, const CollisionPoint &CP_point); public: virtual void LocationChanged() { BVHierarchy.invalidateTransformation(); } void Translate(xFLOAT x, xFLOAT y, xFLOAT z) { Stop(); MX_LocalToWorld_Set() *= xMatrixTranslateT(x,y,z); if (IsCreated()) LocationChanged(); } void Rotate(xFLOAT rotX, xFLOAT rotY, xFLOAT rotZ) { Stop(); MX_LocalToWorld_Set() *= xMatrixRotateRad(DegToRad(rotX), DegToRad(rotY), DegToRad(rotZ)); if (IsCreated()) LocationChanged(); } public: virtual void ApplyDefaults() { IPhysicalBody::ApplyDefaults(); M_mass = FL_stationary ? xFLOAT_HUGE_POSITIVE : 10.f; Stop(); } virtual void Update(xFLOAT T_time); }; } // namespace Physics #endif
[ "dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561" ]
[ [ [ 1, 74 ] ] ]
0fd78cde04ed8a798b41622aab10dcbca7c3e02f
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleAffectors/ParticleUniverseVelocityMatchingAffectorTokens.h
9ad06c2c5857430628da05f82fc149e3ff089663
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
1,529
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_VELOCITY_MATCHING_AFFECTOR_TOKENS_H__ #define __PU_VELOCITY_MATCHING_AFFECTOR_TOKENS_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseITokenInitialiser.h" namespace ParticleUniverse { /** This class contains the tokens that are needed for the VelocityMatchingAffector. */ class _ParticleUniverseExport VelocityMatchingAffectorTokens : public ITokenInitialiser { public: VelocityMatchingAffectorTokens(void) {}; virtual ~VelocityMatchingAffectorTokens(void) {}; /** @see ITokenInitialiser::setupTokenDefinitions */ virtual void setupTokenDefinitions(ITokenRegister* tokenRegister); protected: /** Tokens which get called during parsing. */ class RadiusToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mRadiusToken; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 45 ] ] ]
d4cec876445a89ea6d5198534595cd7de00170bf
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Resource/ResourceFactory.hpp
2a477d64f2b09ae44450a5a3613a4b42b2e2168c
[]
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,336
hpp
/*! */ #ifndef RESOURCE_FACTORY_HPP #define RESOURCE_FACTORY_HPP #include <boost/shared_ptr.hpp> #include <boost/cstdint.hpp> #include "../Core/TypeUtils.hpp" #include "../Core/Singleton.ipp" namespace Spiral { class Resource; namespace detail { template< class ResPolicyClass > class ResourceFactory : public Singleton< ResourceFactory< ResPolicyClass > > { DECL_SINGLETON( ResourceFactory< ResPolicyClass > ) public: template< class ResourceType > boost::shared_ptr< ResourceType > Create( boost::int32_t size, EmptyType< ResourceType > ); /*! @function Create @brief creates a resource using ResPolicyClass @return boost::shared_ptr< Resource > @param boost::int32_t size - size of the resource in bytes @param EmptyType< Resource > */ template<> boost::shared_ptr< Resource > Create( boost::int32_t size, EmptyType< Resource > ); }; template<class ResPolicyClass> boost::shared_ptr< Resource > ResourceFactory<ResPolicyClass>::Create( boost::int32_t size, EmptyType< Resource > ) { boost::shared_ptr< Resource > res = ResPolicyClass::Create( size, EmptyType< Resource > ); return res; } }// detail } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 50 ] ] ]
ebb71d91e47dc2349982995796ecba2e8f691d4a
63b1d959ad819cf748e66ffa4a5813967011e4af
/trunk/output_win/outputwin.h
b221560b5f44d4a011a32896465526091d34cc19
[]
no_license
BackupTheBerlios/caide-svn
a9f9beb7c78c882a1948fc9b82f60892c833f2aa
9513c174f2f1ba7a23a3cd8dbadb3acb284c0cfe
refs/heads/master
2020-04-07T13:00:10.062236
2005-04-23T16:03:19
2005-04-23T16:03:19
40,718,578
0
0
null
null
null
null
UTF-8
C++
false
false
593
h
// outputwin.h : Header file for class OutputWindow //////////////// #ifndef __SFS_OUTPUTWINDOW__H_ #define __SFS_OUTPUTWINDOW__H_ // Includes #include <qdockwindow.h> // Forward Declarations class QProcess; class QTextEdit; class COutputWindow : public QDockWindow { Q_OBJECT public: COutputWindow(QWidget *parent = 0, const char *name = 0); void execute(const QString &command); public slots: void updateText(); void updateExit(); void updateError(); void go(); private: QTextEdit *output; QProcess *compiler; }; #endif
[ "rshadowstalker@bf732942-59f5-0310-8ee4-97220ecff736" ]
[ [ [ 1, 34 ] ] ]
3269cc6151afd549d1dc9c5baeae08bdd54641a8
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Transcoders/Uniconv390/Uniconv390TransService.hpp
e54bb32239d9a4da6c2ee8098e57b2838caf6369
[ "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
8,492
hpp
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: Uniconv390TransService.hpp,v 1.7 2004/09/08 13:56:46 peiyongz Exp $ */ #ifndef UNICONV390TRANSSERVICE_HPP #define UNICONV390TRANSSERVICE_HPP #include <xercesc/util/Mutexes.hpp> #include <xercesc/util/TransService.hpp> #include <xercesc/util/Transcoders/ICU/ICUTransService.hpp> #include "uniconv.h" XERCES_CPP_NAMESPACE_BEGIN typedef struct uniconvconverter { XMLMutex fMutex; uniconv_t fIconv390DescriptorFrom; uniconv_t fIconv390DescriptorTo; } uniconvconverter_t; typedef struct uniconvcaseconverter { XMLMutex fcaseMutex; uniconv_t ftoupperhand; uniconv_t ftolowerhand; } uniconvcaseconverter_t; class XMLUTIL_EXPORT Uniconv390TransService : public XMLTransService { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- Uniconv390TransService(); ~Uniconv390TransService(); // ----------------------------------------------------------------------- // Implementation of the virtual transcoding service API // ----------------------------------------------------------------------- virtual int compareIString ( const XMLCh* const comp1 , const XMLCh* const comp2 ); virtual int compareNIString ( const XMLCh* const comp1 , const XMLCh* const comp2 , const unsigned int maxChars ); virtual const XMLCh* getId() const; virtual bool isSpace(const XMLCh toCheck) const; virtual XMLLCPTranscoder* makeNewLCPTranscoder(); virtual bool supportsSrcOfs() const; virtual void upperCase(XMLCh* const toUpperCase) const; virtual void lowerCase(XMLCh* const toLowerCase) const; protected : // ----------------------------------------------------------------------- // Protected virtual methods // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNewXMLTranscoder ( const XMLCh* const encodingName , XMLTransService::Codes& resValue , const unsigned int blockSize , MemoryManager* const manager ); virtual void initTransService(); private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- Uniconv390TransService(const Uniconv390TransService&); Uniconv390TransService& operator=(const Uniconv390TransService&); ICUTransService * fICUService; XMLLCPTranscoder* fLCPTranscoder; uniconvcaseconverter_t *fCaseConverter; }; class XMLUTIL_EXPORT Uniconv390Transcoder : public XMLTranscoder { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- Uniconv390Transcoder ( const XMLCh* const encodingName , uniconvconverter_t* const toAdopt , const unsigned int blockSize , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); ~Uniconv390Transcoder(); // ----------------------------------------------------------------------- // Implementation of the virtual transcoder interface // ----------------------------------------------------------------------- virtual unsigned int transcodeFrom ( const XMLByte* const srcData , const unsigned int srcCount , XMLCh* const toFill , const unsigned int maxChars , unsigned int& bytesEaten , unsigned char* const charSizes ); virtual unsigned int transcodeTo ( const XMLCh* const srcData , const unsigned int srcCount , XMLByte* const toFill , const unsigned int maxBytes , unsigned int& charsEaten , const UnRepOpts options ); virtual bool canTranscodeTo ( const unsigned int toCheck ) const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- Uniconv390Transcoder(); Uniconv390Transcoder(const Uniconv390Transcoder&); Uniconv390Transcoder& operator=(const Uniconv390Transcoder&); ICUTranscoder * fICUTranscoder; // ----------------------------------------------------------------------- // Private data members // // fConverter // This is a pointer to the converter structure that this transcoder // uses. // // ----------------------------------------------------------------------- uniconvconverter_t *fConverter; }; class XMLUTIL_EXPORT Uniconv390LCPTranscoder : public XMLLCPTranscoder { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- Uniconv390LCPTranscoder( uniconvconverter_t* const toAdopt); ~Uniconv390LCPTranscoder(); // ----------------------------------------------------------------------- // Implementation of the virtual transcoder interface // ----------------------------------------------------------------------- virtual unsigned int calcRequiredSize(const char* const srcText , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); virtual unsigned int calcRequiredSize(const XMLCh* const srcText , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); virtual char* transcode(const XMLCh* const toTranscode); virtual char* transcode(const XMLCh* const toTranscode, MemoryManager* const manager); virtual XMLCh* transcode(const char* const toTranscode); virtual XMLCh* transcode(const char* const toTranscode, MemoryManager* const manager); virtual bool transcode ( const char* const toTranscode , XMLCh* const toFill , const unsigned int maxChars , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); virtual bool transcode ( const XMLCh* const toTranscode , char* const toFill , const unsigned int maxChars , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- Uniconv390LCPTranscoder(); Uniconv390LCPTranscoder(const Uniconv390LCPTranscoder&); Uniconv390LCPTranscoder& operator=(const Uniconv390LCPTranscoder&); ICULCPTranscoder * fICULCPTranscoder; // ----------------------------------------------------------------------- // Private data members // // fConverter // This is a pointer to the converter structure that this transcoder // uses. // ----------------------------------------------------------------------- uniconvconverter_t *fConverter; }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 242 ] ] ]
538debc4ac466381efdaf8580f1a85bb07a3da7c
1741474383f0b3bc3518d7935a904f7903f40506
/A7/IfStmt.h
04f47090551781807ba9e5d8ddef69fd62317913
[]
no_license
osecki/drexelgroupwork
739df86f361e00528a6b03032985288d64b464aa
7c3bde253a50cab42c22d286c80cad72348b4fcf
refs/heads/master
2020-05-31T02:25:57.734312
2009-06-03T18:34:59
2009-06-03T18:34:59
32,121,248
0
0
null
null
null
null
UTF-8
C++
false
false
538
h
#ifndef IFSTMT_H #define IFSTMT_H #include <map> #include <string> #include <vector> #include "StmtList.h" #include "Stmt.h" #include "Expr.h" using namespace std; class IfStmt: public Stmt { public: IfStmt(Expr *E, StmtList *S1, StmtList *S2); ~IfStmt() {delete E_;}; void translate(map<int, string> &constantValues, map<string, SymbolDetails> &symbolTable, vector<string> &ralProgram, map<string, Proc*> &ralProgramFT) const; private: Expr* E_; StmtList *S1_; StmtList *S2_; }; #endif
[ "jordan.osecki@c6e0ff0a-2120-11de-a108-cd2f117ce590", "geoff.oxholm@c6e0ff0a-2120-11de-a108-cd2f117ce590" ]
[ [ [ 1, 16 ], [ 18, 24 ] ], [ [ 17, 17 ] ] ]
b7631dbcce26c5f8f9870fae69bc65cdccb213a3
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/shared/so2/weapon_sobasehlmpcombatweapon.h
c011c11f22ff2a7efa646ecf4fb0d93cd41e79c0
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
UTF-8
C++
false
false
1,324
h
#ifndef WEAPON_BASESOCOMBATWEAPON_SHARED_H #define WEAPON_BASESOCOMBATWEAPON_SHARED_H #ifdef _WIN32 #pragma once #endif #ifdef CLIENT_DLL #include "c_so_player.h" #else #include "so_player.h" #endif #include "weapon_sobase.h" #if defined( CLIENT_DLL ) #define CBaseSOCombatWeapon C_BaseSOCombatWeapon #endif class CBaseSOCombatWeapon : public CWeaponSOBase { #if !defined( CLIENT_DLL ) DECLARE_DATADESC(); #endif DECLARE_CLASS( CBaseSOCombatWeapon, CWeaponSOBase ); public: DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); CBaseSOCombatWeapon(); virtual bool WeaponShouldBeLowered( void ); virtual bool Ready( void ); virtual bool Lower( void ); virtual bool Deploy( void ); virtual void WeaponIdle( void ); virtual Vector GetBulletSpread( WeaponProficiency_t proficiency ); virtual float GetSpreadBias( WeaponProficiency_t proficiency ); virtual const WeaponProficiencyInfo_t *GetProficiencyValues(); static const WeaponProficiencyInfo_t *GetDefaultProficiencyValues(); protected: bool m_bLowered; // Whether the viewmodel is raised or lowered float m_flRaiseTime; // If lowered, the time we should raise the viewmodel private: CBaseSOCombatWeapon( const CBaseSOCombatWeapon & ); }; #endif // WEAPON_BASESOCOMBATWEAPON_SHARED_H
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 55 ] ] ]
40a60d261e99993327d7513d59f01416a85de194
cc336f796b029620d6828804a866824daa6cc2e0
/screensavers/cpBlobs/IsoSurface.h
6b83287209d807783627c9ed29a29cb76a58a6ef
[]
no_license
tokyovigilante/xbmc-sources-fork
84fa1a4b6fec5570ce37a69d667e9b48974e3dc3
ac3c6ef8c567f1eeb750ce6e74c63c2d53fcde11
refs/heads/master
2021-01-19T10:11:37.336476
2009-03-09T20:33:58
2009-03-09T20:33:58
29,232
2
0
null
null
null
null
UTF-8
C++
false
false
816
h
#ifndef ISOSURFACE_H #define ISOSURFACE_H #include "xbsBase.h" class IsoSurface { public: IsoSurface(); ~IsoSurface(); void Init( LPDIRECT3DDEVICE8 pd3dDevice ); virtual float Sample( float mx, float my, float mz ); void March(); void Render( LPDIRECT3DDEVICE8 pd3dDevice ); void SetDensity( int density ); float m_TargetValue; D3DXVECTOR3 *m_pVxs; D3DXVECTOR3 *m_pNorms; int m_iVxCount; int m_iFaceCount; private: void GetNormal( D3DXVECTOR3 &normal, D3DXVECTOR3 &position ); void MarchCube( float mx, float my, float mz, float scale ); float GetOffset( float val1, float val2, float wanted ); LPDIRECT3DVERTEXBUFFER8 m_pVertexBuffer; int m_DatasetSize; float m_StepSize; }; #endif
[ "spiff_@568bbfeb-2a22-0410-94d2-cc84cf5bfa90" ]
[ [ [ 1, 34 ] ] ]
6a8a3eeceb41279152281a86adaecebe8195ab02
353bd39ba7ae46ed521936753176ed17ea8546b5
/src/layer0_base/containers/src/axe_stc_array.h
8d75eada751499dd83eb48dc6a3956d6b01bddc9
[]
no_license
d0n3val/axe-engine
1a13e8eee0da667ac40ac4d92b6a084ab8a910e8
320b08df3a1a5254b776c81775b28fa7004861dc
refs/heads/master
2021-01-01T19:46:39.641648
2007-12-10T18:26:22
2007-12-10T18:26:22
32,251,179
1
0
null
null
null
null
UTF-8
C++
false
false
3,191
h
/** * @file * Static array * @author Ricard Pillosu <d0n3val\@gmail.com> * @version 1.0 * @date 04 Apr 2004 */ #ifndef __AXE_STC_ARRAY_H__ #define __AXE_STC_ARRAY_H__ /** * Static size array */ template<class type, long custom_size> class axe_stc_array { public: const long& size; const type* data; private: long _size; type _data[custom_size]; public: /** * Constructor */ axe_stc_array() : size( _size ), data( &_data[0] ) { AXE_ASSERT( custom_size > 0 ); _size = custom_size; } /** * Destructor */ ~axe_stc_array() { } /** * read / write access */ type & operator [] (long index) { AXE_ASSERT( index >= 0 && index < _size ); return( _data[index] ); } /** * get first item */ type& first() { AXE_ASSERT( _size > 0 ); return( _data[0] ); } /** * get last item */ type& last() { AXE_ASSERT( _size > 0 ); return( _data[_size - 1] ); } /** * Asignation operator */ axe_stc_array &operator=( const axe_stc_array<type, custom_size> array ) { AXE_ASSERT( array.size == custom_size ); for( register long i = 0; i < custom_size; ++i ) { _data[i] = array.data[i]; } //memcpy( _data, array.data, custom_size * sizeof(type) ); return( *this ); } /** * foreach implementation using a C callback */ int foreach( int (*foreach_callback) (type &item, const long index) ) { for( register long i = 0; i < _size; ++i ) { if( AXE_FALSE == (*foreach_callback) (_data[i], i) ) { return( AXE_FALSE ); } } return( AXE_TRUE ); } /** * swap two values */ void swap( long index1, long index2 ) { AXE_ASSERT( index1 >= 0 && index1 < _size ); AXE_ASSERT( index2 >= 0 && index2 < _size ); if( index1 == index2 ) { return; } type tmp = _data[index1]; _data[index1] = _data[index2]; _data[index2] = tmp; } /** * quicksort implementation */ void sort( int (*sort_callback) (type &item1, type &item2), long first = 0, long last = -1 ) { long last_pos = ( last < 0 ) ? _size - 1 : last; long left = first - 1; long right = last_pos; type item = _data[last_pos]; if( first >= last_pos ) { return; } while( true ) { while( (*sort_callback) (_data[++left], item) ) { if( left >= last_pos ) { break; } } while( (*sort_callback) (item, _data[--right]) ) { if( right == 0 ) { break; } } if( left >= right ) { break; } swap( left, right ); } swap( left, last_pos ); sort( sort_callback, first, left - 1 ); sort( sort_callback, left + 1, last ); } }; #endif // __AXE_STC_ARRAY_H__ /* $Id: axe_stc_array.h,v 1.4 2004/07/21 22:08:50 doneval Exp $ */
[ "d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54" ]
[ [ [ 1, 149 ] ] ]
36214a3aab8ac31fbdc2e0ef213bdd9d373e8118
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/ULLib/include/ULPtr.inl
395891a4bee01929902c3e2feb370e524578ca8e
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
6,390
inl
///\file ULPtr.inl ///\brief Заголовочный файл классов указатель и строк(29.12.2007) #include <windows.h> #include <tchar.h> #include "ULRes.h" namespace ULOther { ///\Класс динамического массива указателя (30.07.2007) template<typename object_t> class CULArr { ///\brief Текущий размер в единицах типа size_t m_nObjSize; public: ///\brief Сам указатель на буфер object_t* m_lpObject; ///\brief Конструктор,не выделяющий память CULArr(): m_nObjSize(0), m_lpObject(NULL) { } ///\brief Конструктор для массива элементов ///\param nObjSize стартовый размер CULArr(size_t nObjSize): m_nObjSize(nObjSize) { m_lpObject=new object_t[nObjSize]; } ///\brief Конструктор копирования CULArr(CULArr<object_t>& Arr): m_nObjSize(Arr.m_nObjSize) { m_lpObject=new object_t[m_nObjSize]; for(size_t i=0;i<m_nObjSize;++i) m_lpObject[i]=Arr.m_lpObject[i]; } ///\brief оператор присваивания void operator=(CULArr<object_t>& Arr) { m_nObjSize=Arr.m_nObjSize; m_lpObject=new object_t[m_nObjSize]; for(size_t i=0;i<m_nObjSize;++i) m_lpObject[i]=Arr.m_lpObject[i]; } ///\brief Изменение размера выделенной памяти с сохранением элементов ///\param nObjSize новый размер ///\return указатеь на буфер object_t* Resize(size_t nObjSize) { object_t* lpNewObj=NULL; if(nObjSize==0) Free(); else { lpNewObj=new object_t[nObjSize]; size_t size = (m_nObjSize<nObjSize)?m_nObjSize:nObjSize; for(size_t i = 0; i < size; ++i) lpNewObj[i]=m_lpObject[i]; Free(); } m_lpObject=lpNewObj; m_nObjSize=nObjSize; return m_lpObject; }; ///\brief Возвращает размер указателя inline size_t GetSize() { return m_nObjSize; } ///\brief Возвращает указатель inline operator object_t*() { return m_lpObject; } ///\brief Освобождает выделенную память inline void Free() { if((m_lpObject!=NULL)&&(m_nObjSize!=0)) { delete[] m_lpObject; m_lpObject=NULL; m_nObjSize=0; } } ///\brief отсоединяет выделенную память от класса ///\return указатель на выделенную память object_t* Detach() { object_t* lpRet=m_lpObject; m_lpObject=NULL; m_nObjSize=0; return lpRet; } ///\brief Деструктор virtual ~CULArr() { Free(); } }; template<typename object_t> ///\class CULStrT ///\brief Класс строки(29.12.2007) class CULStrT:public CULArr<typename object_t> { public: ///\brief Конструктор ///\param nObjSize - размер выделяемой памяти CULStrT(size_t nObjSize=32767): CULArr<object_t>(nObjSize) { (*this)[0]=0; }; ///\brief Деструктор virtual ~CULStrT(){}; ///\brief Возвращает длину строки ///\return длина строки int GetLen() { return (int)_tcslen(*this); } /* ///\brief оператор присвоения object_t* operator=(const object_t pszRight[]) { if(!pszRight) return *this; size_t nSize=_tcslen(pszRight); if(nSize>GetSize()) Resize(nSize+1); _tcscpy_s(*this,(int)GetSize(),pszRight); return *this; }; */ ///\brief оператор присвоения object_t* operator=(const object_t* pszRight) { if(!pszRight) return *this; size_t nSize=_tcslen(pszRight); if(nSize>GetSize()) Resize(nSize+1); _tcscpy_s(*this,(int)GetSize(),pszRight); return *this; }; ///\brief оператор присвоения object_t* operator=(CULStrT<object_t> &pszRight) { if(pszRight.GetSize()>GetSize()) Resize(pszRight.GetSize()+1); _tcscpy_s(*this,(int)GetSize(),pszRight); return *this; }; ///\brief оператор сложения строк ///\return получившаяся строка CULStrT operator+(const object_t* pszRight) { CULString pszTmp; pszTmp=*this; size_t nSize=_tcslen(pszRight); if(nSize>pszTmp.GetSize()) pszTmp.Resize(pszTmp.GetSize()+nSize); _tcscat_s(pszTmp,pszRight); return pszTmp; } ///\brief оператор прибавления к строке void operator+=(const object_t* pszRight) { size_t nSize=GetSize()+_tcslen(pszRight); if(nSize>GetSize()) Resize(nSize); _tcscat_s(*this,GetSize(),pszRight); } ///\brief оператор сравнения строк ///\return 0 если равны int operator==(const object_t* pszRight) { return _tcscmp(*this,pszRight); } ///\brief оператор сравнения строк ///\return 0 если равны int operator==(const CULStrT<object_t> &pszRight) { return _tcscmp(*this,pszRight); } ///\brief Выводит форматированный текст в строку ///\param szFormat - Формат вывода ///\param ... - набор параметров ///\return число выведенных символов int Format(LPTSTR szFormat,...) { va_list va; va_start( va, szFormat ); int nRet=_vstprintf(*this,szFormat,va); va_end( va ); return nRet; } }; ///\brief переопределенный тип класса строки typedef CULStrT<TCHAR> CULStr; ///\class CULStrTable ///\brief Класс для ускорения загрузки строк из StringTable(05.10.2008) class CULStrTable { ///\brief id строки UINT m_uID; ///\brief строка вывода TCHAR m_szStr[MAX_PATH]; public: ///\brief конструктор ///\param uID - идентификатор строки CULStrTable(UINT uID):m_uID(uID) {} ///\оператор LPTSTR operator LPCTSTR() { LoadString(ULGetResourceHandle(),m_uID,m_szStr,MAX_PATH); return m_szStr; } }; }
[ "UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f" ]
[ [ [ 1, 222 ] ] ]
93d4784608d2b71cdc321350a47f787e946c6ea7
accd6e4daa3fc1103c86d245c784182e31681ea4
/HappyHunter/Core/Camera.h
aad943cdf0991a9fb7399bda42e0ae63c553cd9f
[]
no_license
linfuqing/zero3d
d87ad6cf97069aea7861332a9ab8fc02b016d286
cebb12c37fe0c9047fb5b8fd3c50157638764c24
refs/heads/master
2016-09-05T19:37:56.213992
2011-08-04T01:37:36
2011-08-04T01:37:36
34,048,942
0
1
null
null
null
null
GB18030
C++
false
false
3,758
h
#pragma once #include "Sprite.h" #include "BitFlag.h" namespace zerO { /// //视锥体 /// typedef struct FRUSTUM { union { struct { D3DXPLANE Left; D3DXPLANE Right; D3DXPLANE Top; D3DXPLANE Bottom; D3DXPLANE Far; D3DXPLANE Near; }; struct { D3DXPLANE Plane[6]; }; }; //根据CRectangle3D::TESTPLANESTATE值测试矩形位置 bool Test(const CRectangle3D& Rect, UINT32 uTestFlag)const; bool TestHit(const CRectangle3D& Rect)const; void Transform(const D3DXMATRIX& Matrix); //从视口投影矩阵构建视锥体 void ExtractFromMatrix(const D3DXMATRIX& Matrix); void Normalize(); }FRUSTUM, * LPFRUSTUM; inline bool FRUSTUM::Test(const CRectangle3D& Rect, UINT32 uTestFlag)const { INT32 nFlag = uTestFlag; return TEST_FLAG( nFlag, Rect.Test(Left ) ) && TEST_FLAG( nFlag, Rect.Test(Right ) ) && TEST_FLAG( nFlag, Rect.Test(Top ) ) && TEST_FLAG( nFlag, Rect.Test(Bottom) ) && TEST_FLAG( nFlag, Rect.Test(Far ) ) && TEST_FLAG( nFlag, Rect.Test(Near ) ); } inline bool FRUSTUM::TestHit(const CRectangle3D& Rect)const { static UINT32 s_uTestFlag = CRectangle3D::PLANE_FRONT | CRectangle3D::PLANE_INTERSECT; return Test(Rect, s_uTestFlag); } inline void FRUSTUM::Transform(const D3DXMATRIX& Matrix) { D3DXPlaneTransformArray(Plane, sizeof(D3DXPLANE), Plane, sizeof(D3DXPLANE), &Matrix, 6); } inline void FRUSTUM::Normalize() { D3DXPlaneNormalize(&Left , &Left ); D3DXPlaneNormalize(&Right , &Right ); D3DXPlaneNormalize(&Top , &Top ); D3DXPlaneNormalize(&Bottom, &Bottom); D3DXPlaneNormalize(&Far , &Far ); D3DXPlaneNormalize(&Near , &Near ); } /// // 相机类 /// class CCamera : public CSprite { public: CCamera(void); ~CCamera(void); const D3DXMATRIX& GetViewMatrix()const; const D3DXMATRIX& GetProjectionMatrix()const; const D3DXMATRIX& GetViewProjectionMatrix()const; const D3DXVECTOR3& GetWorldPosition()const; const FRUSTUM& GetFrustum()const; FLOAT GetFOV()const; FLOAT GetAspect()const; FLOAT GetNearPlane()const; FLOAT GetFarPlane()const; //投影矩阵参数. void SetProjection( FLOAT fFOV, FLOAT fNearPlane, FLOAT fFarPlane, FLOAT fAspect = 0); void SetProjection(); void ModifyProjectionMatrix(const D3DXPLANE& Plane); void GetRayByScreenPosition(D3DXVECTOR3* pRayPosition, D3DXVECTOR3* pRayDirection, FLOAT fScreenX, FLOAT fScreenY); void UpdateTransform(); private: D3DXMATRIX m_ViewMatrix; D3DXMATRIX m_ProjectionMatrix; D3DXMATRIX m_InverseProjectionMatrix; D3DXMATRIX m_ViewProjectionMatrix; D3DXMATRIX m_InverseViewProjectionMatrix; D3DXVECTOR3 m_WorldPosition; FRUSTUM m_Frustum; D3DXVECTOR3 m_FarPlanePoints[8]; FLOAT m_fFOV; FLOAT m_fAspect; FLOAT m_fNearPlane; FLOAT m_fFarPlane; }; inline const D3DXMATRIX& CCamera::GetViewMatrix()const { return m_ViewMatrix; } inline const D3DXMATRIX& CCamera::GetProjectionMatrix()const { return m_ProjectionMatrix; } inline const D3DXMATRIX& CCamera::GetViewProjectionMatrix()const { return m_ViewProjectionMatrix; } inline const FRUSTUM& CCamera::GetFrustum()const { return m_Frustum; } inline const D3DXVECTOR3& CCamera::GetWorldPosition()const { return m_WorldPosition; } inline FLOAT CCamera::GetFOV()const { return m_fFOV; } inline FLOAT CCamera::GetAspect()const { return m_fAspect; } inline FLOAT CCamera::GetNearPlane()const { return m_fNearPlane; } inline FLOAT CCamera::GetFarPlane()const { return m_fFarPlane; } }
[ [ [ 1, 176 ] ] ]
c621f5c0809e22775d4517a7227bb1591e8b2e7a
63937d06f9f4083609200cb743ec0122c6da9f40
/tests/test_beta.cpp
93047eaa0b60247d6a35aa3eeed9408871006a1a
[]
no_license
funkjunky/slogic
924704b192f102390e1fde1402aedfcb13d3af40
4795a9f7aa626faa215012d94686b1769af4f2c7
refs/heads/master
2021-01-22T09:46:51.990756
2011-02-10T08:51:27
2011-02-10T08:51:27
1,341,519
1
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
/** * \todo Do inherited members show up in initializer lists??? */ #include "subj_logic.hpp" #include "beta_opinion.hpp" #include <iostream> #include <set> using namespace std; using namespace Subj_logic; int main() { Beta_Opinion z1(5, 2, Real(1,2)); cout << "z1, an explicitly made Beta Opinion:" << endl; cout << "belief = " << z1.get_belief() << endl; cout << "disbelief = " << z1.get_disbelief() << endl; cout << "uncertainty = " << z1.get_uncertainty() << endl; cout << "rel atomicity = " << z1.get_base_rate() << endl; }
[ [ [ 1, 22 ] ] ]