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
e733ef563f083c012bbe2f442a9b9e18a4b18805
cfa1c9f0d1e0bef25f48586d19395b5658752f5b
/Proj_2/SoundSystem.h
b02dfb3b21b69ece391d79228d08c2fe2180a90d
[]
no_license
gemini14/AirBall
de9c9a9368bb58d7f7c8fe243a900b11d0596227
5d41d3f2c5282f50e7074010f7c1d3b5a804be77
refs/heads/master
2021-03-12T21:42:26.819173
2011-05-11T08:10:51
2011-05-11T08:10:51
1,732,008
0
0
null
null
null
null
UTF-8
C++
false
false
971
h
#ifndef SOUNDSYSTEM_H #define SOUNDSYSTEM_H #include <map> #include <memory> #include <boost/noncopyable.hpp> namespace Tuatara { typedef std::map<std::string, std::string> SoundFilenameMap; struct FMOD_System; class SoundSystem : boost::noncopyable { private: std::shared_ptr<FMOD_System> system; public: SoundSystem(); ~SoundSystem(); bool SoundSystemInitOK() const; void CreateSounds( const SoundFilenameMap& soundFilenameMap ); void CreateVentSound( const float& x, const float& y, const float& z ); void StartPlayingLoopingSounds(); void PlayCollisionSound(); void PlayJetSound(); void PlayRollSound(); void PausePlayback(); void ResumePlayback(); void Update( const float& posX, const float& posY, const float& posZ, const float& forwardX, const float& forwardY, const float& forwardZ, const float& ballPosX, const float& ballPosY, const float& ballPosZ ); }; } #endif
[ "devnull@localhost" ]
[ [ [ 1, 44 ] ] ]
605d4c273c3e8d08f4cce57442aff054e7a5de6c
fb7d4d40bf4c170328263629acbd0bbc765c34aa
/SpaceBattle/SpaceBattleLib/GeneratedCode/Controleur/Instruments/Clavier.h
a3acd040251dbee6aa190cdc77599ad444bc1e43
[]
no_license
bvannier/SpaceBattle
e146cda9bac1608141ad8377620623514174c0cb
6b3e1a8acc5d765223cc2b135d2b98c8400adf06
refs/heads/master
2020-05-18T03:40:16.782219
2011-11-28T22:49:36
2011-11-28T22:49:36
2,659,535
0
1
null
null
null
null
UTF-8
C++
false
false
916
h
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #pragma once #define WANTDLLEXP #ifdef WANTDLLEXP //exportation dll #define DLL __declspec( dllexport ) #define EXTERNC extern "C" #else #define DLL //standard #define EXTERNC #endif #include "Instruments.h" using namespace ControleurInstruments; #include<vector> namespace ControleurInstruments { class Clavier : public Instruments { private : protected : public : private : protected : public : override void setActivated(object b boolean); }; EXTERNC DLL void CLAVIER_setActivated(Clavier*, object b boolean); }
[ [ [ 1, 46 ] ] ]
f6aeeb3c98757ee40cd58fb02b8d3ed95561c6ca
097c5ec89727bca9c69964fdb0125174bd535387
/src/objectManager.cpp
91d5fc163a6fa3cfd5f36975d5a7aba3ec4fce33
[]
no_license
jsj2008/Captain
280501d3bc2dbd778519fddac3afe1d1fb14ebe8
099ee3f7cdd5e81ac741a7e6c69a131fcbccc7c6
refs/heads/master
2020-12-25T15:40:53.390224
2011-11-28T07:36:05
2011-11-28T07:36:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,568
cpp
#include "objectManager.hpp" #include "programManager.hpp" #include "scene.hpp" typedef boost::shared_ptr<Text> TextPtr; typedef boost::shared_ptr<Sprite> SpritePtr; typedef boost::shared_ptr<Stars> StarsPtr; typedef boost::shared_ptr<Scene> ScenePtr; typedef boost::shared_ptr<Menu> MenuPtr; typedef boost::shared_ptr<Arena> ArenaPtr; ObjectManager objectmgr; // Construct our divine Object Manager. Set some "first loop variables" // and generate some basic objects ObjectManager::ObjectManager() { sceneNumber = 0; arenaCreated = false; } ObjectManager::~ObjectManager() { } void ObjectManager::doFirstScene() { // Create the main menu, and make it the current scene // These need to be done elsewhere as opengl can't give ids yet std::vector<std::string> menuItems; menuItems.push_back("Play game"); menuItems.push_back("Options"); menuItems.push_back("Help"); menuItems.push_back("Quit"); std::cout << "Creating menu" << std::endl; // Construct a new menu with the boolean "true" for using bg stars MenuPtr tempMenuPtr(new Menu(menuItems, true)); ScenePtr tempScenePtr(new Scene(tempMenuPtr)); sceneVector.push_back(tempScenePtr); currentScenePtr = sceneVector.at(0); // Add something to work as the placeholder before loading anything real changeMainBackground("default.png"); std::cout << "ObjectManager reports all ready" << std::endl; } // Call each of the object vectors, and ask the objects to render void ObjectManager::render() { for (int i = 0; i < shipVector.size(); i++) { Ship &s = shipVector[i]; s.render(); } for (std::vector<TextPtr>::iterator iter = genericTexts.begin(); iter != genericTexts.end(); iter++) { (*iter)->render(); } } void ObjectManager::renderHUD() { } // Create a new Text Sprite, then push it to the generic text vector void ObjectManager::addNewGenericText(int w, int h, std::string message, std::string fontPath, int fontSize, int locx, int locy) { TextPtr tempTextPtr(new Text(w, h, message.c_str(), fontPath, fontSize)); tempTextPtr->x = locx; tempTextPtr->y = locy; genericTexts.push_back(tempTextPtr); } // Add a new Sprite, then push it into the background sprite vector void ObjectManager::addNewBGSprite(const std::string &filename) { SpritePtr tempSpritePtr(new Sprite(filename)); backgroundSprites.push_back(tempSpritePtr); } // Change our current background by making the main background pointer to point // to a new, freshly created background Sprite. Consider doing this by // iterating in the background vector void ObjectManager::changeMainBackground(std::string filename) { SpritePtr tempSprite(new Sprite(filename)); mainBackgroundPtr = tempSprite; } // For now, if we are in the menu, render the speed bg stars // Else, render whatever is our current background void ObjectManager::renderBackground() { //mainBackgroundPtr->render(); } void ObjectManager::createNewArena() { ArenaPtr tempPtr(new Arena()); ScenePtr tempPtr2(new Scene(tempPtr)); sceneVector.push_back(tempPtr2); sceneNumber++; changeScene(sceneNumber); arenaCreated = true; } // Tell everyone that we don't have a current arena active void ObjectManager::removeArena() { arenaCreated = false; } // Change our current scene to something else void ObjectManager::changeScene(int sceneNum) { currentScenePtr = sceneVector.at(sceneNum); } // Call our current scene, whatever it may be, to update void ObjectManager::update() { currentScenePtr->operate(); }
[ [ [ 1, 124 ] ] ]
0aa1ac907c79a2f0ce22059ad7400ab6004dfbb5
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/android/third_party/gecko-1.9.0.11/win32/include/nsIWebBrowserSetup.h
274ef8a9ebcea552c14a109be0864d6f1840f039
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
5,395
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/xr19rel/WINNT_5.2_Depend/mozilla/embedding/browser/webBrowser/nsIWebBrowserSetup.idl */ #ifndef __gen_nsIWebBrowserSetup_h__ #define __gen_nsIWebBrowserSetup_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIWebBrowserSetup */ #define NS_IWEBBROWSERSETUP_IID_STR "f15398a0-8018-11d3-af70-00a024ffc08c" #define NS_IWEBBROWSERSETUP_IID \ {0xf15398a0, 0x8018, 0x11d3, \ { 0xaf, 0x70, 0x00, 0xa0, 0x24, 0xff, 0xc0, 0x8c }} /** * The nsIWebBrowserSetup interface lets you set properties on a browser * object; you can do so at any time during the life cycle of the browser. * * @note Unless stated otherwise, settings are presumed to be enabled by * default. * * @status FROZEN */ class NS_NO_VTABLE NS_SCRIPTABLE nsIWebBrowserSetup : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWEBBROWSERSETUP_IID) /** * Boolean. Enables/disables plugin support for this browser. * * @see setProperty */ enum { SETUP_ALLOW_PLUGINS = 1U }; /** * Boolean. Enables/disables Javascript support for this browser. * * @see setProperty */ enum { SETUP_ALLOW_JAVASCRIPT = 2U }; /** * Boolean. Enables/disables meta redirect support for this browser. * Meta redirect timers will be ignored if this option is disabled. * * @see setProperty */ enum { SETUP_ALLOW_META_REDIRECTS = 3U }; /** * Boolean. Enables/disables subframes within the browser * * @see setProperty */ enum { SETUP_ALLOW_SUBFRAMES = 4U }; /** * Boolean. Enables/disables image loading for this browser * window. If you disable the images, load a page, then enable the images, * the page will *not* automatically load the images for the previously * loaded page. This flag controls the state of a webBrowser at load time * and does not automatically re-load a page when the state is toggled. * Reloading must be done by hand, or by walking through the DOM tree and * re-setting the src attributes. * * @see setProperty */ enum { SETUP_ALLOW_IMAGES = 5U }; /** * Boolean. Enables/disables whether the document as a whole gets focus before * traversing the document's content, or after traversing its content. * * NOTE: this property is obsolete and now has no effect * * @see setProperty */ enum { SETUP_FOCUS_DOC_BEFORE_CONTENT = 6U }; /** * Boolean. Enables/disables the use of global history in the browser. Visited * URLs will not be recorded in the global history when it is disabled. * * @see setProperty */ enum { SETUP_USE_GLOBAL_HISTORY = 256U }; /** * Boolean. A value of PR_TRUE makes the browser a chrome wrapper. * Default is PR_FALSE. * * @since mozilla1.0 * * @see setProperty */ enum { SETUP_IS_CHROME_WRAPPER = 7U }; /** * Sets an integer or boolean property on the new web browser object. * Only PR_TRUE and PR_FALSE are legal boolean values. * * @param aId The identifier of the property to be set. * @param aValue The value of the property. */ /* void setProperty (in unsigned long aId, in unsigned long aValue); */ NS_SCRIPTABLE NS_IMETHOD SetProperty(PRUint32 aId, PRUint32 aValue) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIWebBrowserSetup, NS_IWEBBROWSERSETUP_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIWEBBROWSERSETUP \ NS_SCRIPTABLE NS_IMETHOD SetProperty(PRUint32 aId, PRUint32 aValue); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIWEBBROWSERSETUP(_to) \ NS_SCRIPTABLE NS_IMETHOD SetProperty(PRUint32 aId, PRUint32 aValue) { return _to SetProperty(aId, aValue); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIWEBBROWSERSETUP(_to) \ NS_SCRIPTABLE NS_IMETHOD SetProperty(PRUint32 aId, PRUint32 aValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetProperty(aId, aValue); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsWebBrowserSetup : public nsIWebBrowserSetup { public: NS_DECL_ISUPPORTS NS_DECL_NSIWEBBROWSERSETUP nsWebBrowserSetup(); private: ~nsWebBrowserSetup(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsWebBrowserSetup, nsIWebBrowserSetup) nsWebBrowserSetup::nsWebBrowserSetup() { /* member initializers and constructor code */ } nsWebBrowserSetup::~nsWebBrowserSetup() { /* destructor code */ } /* void setProperty (in unsigned long aId, in unsigned long aValue); */ NS_IMETHODIMP nsWebBrowserSetup::SetProperty(PRUint32 aId, PRUint32 aValue) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIWebBrowserSetup_h__ */
[ "alexber@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 177 ] ] ]
35db6a534a22c34cb4b0b6e710cdf1042cc69941
0d32d7cd4fb22b60c4173b970bdf2851808c0d71
/src/hancock/hancock/SelDepDlg.cpp
16dd4cb15605dba0cc273713376e6e43cd640085
[]
no_license
kanakb/cs130-hancock
a6eaef9a44955846d486ee2330bec61046cb91bd
d1f77798d90c42074c7a26b03eb9d13925c6e9d7
refs/heads/master
2021-01-18T13:04:25.582562
2009-06-12T03:49:56
2009-06-12T03:49:56
32,226,524
1
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
// SelDepDlg.cpp : implementation file // #include "stdafx.h" #include "hancock.h" #include "SelDepDlg.h" #include "Scheduler.h" #include <list> #include <string> using namespace std; // SelDepDlg dialog IMPLEMENT_DYNAMIC(SelDepDlg, CDialog) SelDepDlg::SelDepDlg(Scheduler::actData *action, CWnd* pParent /*=NULL*/) : CDialog(SelDepDlg::IDD, pParent), m_actData(action) { } SelDepDlg::~SelDepDlg() { } void SelDepDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST1, m_fileList); // Populate ListBox with action outputs list<string>::iterator it = m_actData->outputs.begin(); for (; it != m_actData->outputs.end(); it++) { CString act(it->c_str()); m_fileList.AddString(act); } } BEGIN_MESSAGE_MAP(SelDepDlg, CDialog) ON_BN_CLICKED(IDOK, &SelDepDlg::OnBnClickedOk) END_MESSAGE_MAP() // SelDepDlg message handlers void SelDepDlg::OnBnClickedOk() { // set file string to the selected one int nIndex = m_fileList.GetCurSel(); if (nIndex != LB_ERR) m_fileList.GetText(nIndex, m_filename); else MessageBox(_T("No dependency selected.")); OnOK(); } void SelDepDlg::getFileString(CString &file) { file = m_filename; }
[ "kanakb@1f8f3222-2881-11de-bcab-dfcfbda92187" ]
[ [ [ 1, 63 ] ] ]
54305b7aa7aed9d3ef244e09ac1c0105eccc5918
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/ImProSyncFilter/ImProSyncFilter.cpp
80987a5ce4f4203308235d3b1b43aef81dcf59d5
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
10,619
cpp
#include "stdafx.h" #include "ImProSyncFilter.h" #include "GSD3DMediaType.h" #include "GSMacro.h" #include "cv.h" #include "MyMediaSample.h" #include "MyARTagMediaSample.h" ImProSyncFilter::ImProSyncFilter(IUnknown * pOuter, HRESULT * phr, BOOL ModifiesData) : GSDXMuxFilter(NAME("ImProSyncFilter"), 0, CLSID_ImProSyncFilter), CPersistStream(pOuter, phr) { setDirty(false); setBlock(false); } ImProSyncFilter::~ImProSyncFilter() { } CUnknown *WINAPI ImProSyncFilter::CreateInstance(LPUNKNOWN punk, HRESULT *phr) { ASSERT(phr); // assuming we don't want to modify the data ImProSyncFilter *pNewObject = new ImProSyncFilter(punk, phr, FALSE); if(pNewObject == NULL) { if (phr) *phr = E_OUTOFMEMORY; } return pNewObject; } HRESULT ImProSyncFilter::NonDelegatingQueryInterface(REFIID iid, void **ppv) { if (iid == IID_IImProSyncFilter) { return GetInterface(static_cast<IImProSyncFilter*>(this), ppv); } else if (iid == IID_ISpecifyPropertyPages) { return GetInterface( static_cast<ISpecifyPropertyPages*>(this), ppv); } else if (iid == IID_IPersistStream) { return GetInterface(static_cast<IPersistStream*>(this), ppv); } else if (iid == IID_IGSPersist) { return GetInterface(static_cast<IGSPersist*>(this), ppv); } else { // Call the parent class. return __super::NonDelegatingQueryInterface(iid, ppv); } } HRESULT ImProSyncFilter::CreatePins() { HRESULT hr = S_OK; GSPIN_ACCEPT_MEDIATYPE camAccType[] = { GSPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_RGB32, FORMAT_VideoInfo, FALSE), GSPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_ARGB32, FORMAT_VideoInfo, FALSE) }; GSPIN_ACCEPT_MEDIATYPE layoutDirtyAccType[] = { GSPIN_ACCEPT_MEDIATYPE(GUID_IMPRO_FeedbackTYPE, GUID_ARLayoutConfigData, FALSE) }; GSPIN_ACCEPT_MEDIATYPE arlayoutAccType[] = { GSPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_GSDX11_SHAREDEVICE_MEDIATYPE, GSMEDIASUBTYPE_GSTEX2D_POINTER, GSFORMAT_DX11TEX2D_DESC, FALSE), GSPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_GSDX11_MEDIATYPE, GSMEDIASUBTYPE_GSTEX2D_POINTER, GSFORMAT_DX11TEX2D_DESC, FALSE), GSPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_RGB32, FORMAT_VideoInfo, FALSE), GSPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_ARGB32, FORMAT_VideoInfo, FALSE) }; GSFILTER_INPUTPIN_DESC inputPinDesc[] = { GSFILTER_INPUTPIN_DESC(L"camInput", 0, GSINPUT_PIN, GSPIN_ACCEPT_MEDIATYPE_GROUP(camAccType, ARRAYSIZE(camAccType)), GSFILTER_INPUTPIN_FUNCS(GSDXMuxFilter::PreReceive_InitSample, OnCamTransform, PostReceiveCamImg, GSDXMuxFilter::CompleteConnect_ReconnectOutput, NULL)), GSFILTER_INPUTPIN_DESC(L"layoutDirty", 0, GSINPUT_PIN, GSPIN_ACCEPT_MEDIATYPE_GROUP(layoutDirtyAccType, ARRAYSIZE(layoutDirtyAccType)), GSFILTER_INPUTPIN_FUNCS(ReceiveLayoutDirty, NULL, NULL, NULL, NULL)), GSFILTER_INPUTPIN_DESC(L"layoutInput", 2, GSINPUT_PIN, GSPIN_ACCEPT_MEDIATYPE_GROUP(arlayoutAccType, ARRAYSIZE(arlayoutAccType)), GSFILTER_INPUTPIN_FUNCS(GSDXMuxFilter::PreReceive_InitSample, GSDXMuxFilter::Transform_D3DRender, PostReceiveARLayout, GSDXMuxFilter::CompleteConnect_InitD3D, GSDXMuxFilter::BreakConnect_ReleaseD3D)), }; GSOUTPIN_ACCEPT_MEDIATYPE camoutAccType[] = { GSOUTPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_RGB32, FORMAT_VideoInfo, FALSE, GSREF_INPUT_PIN, 0, 0, 0) }; GSOUTPIN_ACCEPT_MEDIATYPE layoutCfgAccType[] = { GSOUTPIN_ACCEPT_MEDIATYPE(GUID_IMPRO_FeedbackTYPE, GUID_ARLayoutConfigData, FALSE, GSREF_ACCEPT_MEDIATYPE, sizeof(ARLayoutConfigData), 0, 0) }; GSOUTPIN_ACCEPT_MEDIATYPE layoutRenderAccType[] = { GSOUTPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_GSDX11_SHAREDEVICE_MEDIATYPE, GSMEDIASUBTYPE_GSTEX2D_POINTER, GSFORMAT_DX11TEX2D_DESC, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_GSDX11_MEDIATYPE, GSMEDIASUBTYPE_GSTEX2D_POINTER, GSFORMAT_DX11TEX2D_DESC, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_RGB32, FORMAT_VideoInfo, FALSE, GSREF_RENDERTARGET, 0, 0, 0) }; GSFILTER_OUTPUTPIN_DESC outPinDesc[] = { GSFILTER_OUTPUTPIN_DESC(L"camOut", 0, GSOUTPUT_PIN, GSOUTPIN_ACCEPT_MEDIATYPE_GROUP(camoutAccType, ARRAYSIZE(camoutAccType)), GSFILTER_OUTPUTPIN_FUNCS(NULL, NULL)), GSFILTER_OUTPUTPIN_DESC(L"layoutCfg", 1, GSOUTPUT_PIN, GSOUTPIN_ACCEPT_MEDIATYPE_GROUP(layoutCfgAccType, ARRAYSIZE(layoutCfgAccType)), GSFILTER_OUTPUTPIN_FUNCS(NULL, NULL)), GSFILTER_OUTPUTPIN_DESC(L"layoutRender", 0, GSOUTPUT_PIN, GSOUTPIN_ACCEPT_MEDIATYPE_GROUP(layoutRenderAccType, ARRAYSIZE(layoutRenderAccType)), GSFILTER_OUTPUTPIN_FUNCS(NULL, NULL)), }; hr = _CreatePins(inputPinDesc, ARRAYSIZE(inputPinDesc), outPinDesc, ARRAYSIZE(outPinDesc), NULL, 0); return hr; } HRESULT ImProSyncFilter::GetPages(CAUUID *pPages) { pPages->cElems = 1; pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID)); if (pPages->pElems == NULL) { return E_OUTOFMEMORY; } pPages->pElems[0] = CLSID_ImProSyncFilterProp; return S_OK; } HRESULT ImProSyncFilter::GetName(WCHAR* name, UINT szName) { if (name == NULL) return S_FALSE; FILTER_INFO filterInfo; this->QueryFilterInfo(&filterInfo); wcscpy_s(name, szName, filterInfo.achName); if (filterInfo.pGraph != NULL) { filterInfo.pGraph->Release(); filterInfo.pGraph = NULL; } return S_OK; } HRESULT ImProSyncFilter::SaveToFile(WCHAR* path) { return S_OK; } HRESULT ImProSyncFilter::LoadFromFile(WCHAR* path) { return S_OK; } HRESULT ImProSyncFilter::GetClassID(__out CLSID *pClsID) { if (pClsID == NULL) return E_INVALIDARG; *pClsID = CLSID_ImProSyncFilter; return S_OK; } HRESULT ImProSyncFilter::WriteToStream(IStream *pStream) { if (pStream == NULL) return E_INVALIDARG; return S_OK; } HRESULT ImProSyncFilter::ReadFromStream(IStream *pStream) { if (pStream == NULL) return E_INVALIDARG; return S_OK; } int ImProSyncFilter::SizeMax() { return 0; } HRESULT ImProSyncFilter::OnCamTransform(void* self, IMediaSample *pInSample, CMediaType* inMT, IMediaSample *pOutSample, CMediaType* outMT) { if (self == NULL || pInSample == NULL || pOutSample == NULL || inMT == NULL || outMT == NULL) { return E_FAIL; } HRESULT hr = S_OK; ImProSyncFilter* pSelf = (ImProSyncFilter*)(GSDXMuxFilter*)self; hr = GSMuxFilter::Transform_MediaSampleCopy(self, pInSample, inMT, pOutSample, outMT); return hr; } HRESULT ImProSyncFilter::ReceiveLayoutDirty(void* self, IMediaSample *pSample, const IPin* pReceivePin, IMediaSample*& pOutSample) { if (self == NULL || pSample == NULL || pReceivePin == NULL) { return E_FAIL; } ImProSyncFilter* pSelf = (ImProSyncFilter*)(GSMuxFilter*)self; HRESULT hr = S_OK; UINT pinIdx = 0; GSPIN_TYPE pinType = GSINPUT_PIN; hr = pSelf->_GetPinIdx(pReceivePin, pinIdx, pinType); if (FAILED(hr) || pinType != GSINPUT_PIN) return E_FAIL; if (pinIdx >= pSelf->m_pInputPinDesc.size()) return E_FAIL; CAutoLock lck(&pSelf->locMarkerInfo); ARLayoutConfigData* pARTagResult = NULL; pSample->GetPointer((BYTE**)&pARTagResult); if (pARTagResult == NULL) { return S_FALSE; } pSelf->tagConfig = *pARTagResult; pSelf->setDirty(true); return S_OK; } HRESULT ImProSyncFilter::PostReceiveCamImg(void* self, IMediaSample *pOutSample, const IPin* pOutputPin, HRESULT preHr) { if (self == NULL || pOutSample == NULL || pOutputPin == NULL) { return E_FAIL; } ImProSyncFilter* pSelf = (ImProSyncFilter*)(GSMuxFilter*)self; HRESULT hr = S_OK; if(pSelf->getBlock() == true){ // if block not to send Camera image return hr; } if (FAILED(preHr)) { DbgLog((LOG_TRACE,1,TEXT("Error from transform"))); } else { if (preHr == NOERROR) { hr = ((GSMuxOutputPin*)pOutputPin)->Deliver(pOutSample);// m_pInputPin->Receive(pOutSample); pSelf->m_bSampleSkipped = FALSE; // last thing no longer dropped } else { if (S_FALSE == preHr) { SAFE_RELEASE(pOutSample); pSelf->m_bSampleSkipped = TRUE; if (!pSelf->m_bQualityChanged) { pSelf->NotifyEvent(EC_QUALITY_CHANGE,0,0); pSelf->m_bQualityChanged = TRUE; } return NOERROR; } } } return hr; } HRESULT ImProSyncFilter::PostReceiveARLayout(void* self, IMediaSample *pOutSample, const IPin* pOutputPin, HRESULT preHr) { if (self == NULL || pOutSample == NULL || pOutputPin == NULL) { return E_FAIL; } ImProSyncFilter* pSelf = (ImProSyncFilter*)(GSMuxFilter*)self; CMediaSample* pOutSampleConfig = NULL ; ARLayoutConfigData sendData ; GSMuxOutputPin* pConfigOutputPin = pSelf->m_pOutputPins[1]; // get the Dirty output Pin HRESULT hr = S_OK; if (pSelf->getDirty() == true){ pSelf->setBlock(true); CAutoLock lck(&pSelf->locMarkerInfo); sendData.m_ARMarkers = pSelf->tagConfig.m_ARMarkers; sendData.m_numMarker = pSelf->tagConfig.m_numMarker; IMemAllocator* pAllocator = pSelf->m_pOutputPins[1]->Allocator(); pAllocator->GetBuffer((IMediaSample**)&pOutSampleConfig, NULL, NULL, 0); if (pOutSampleConfig == NULL) { sendData.m_ARMarkers = NULL; sendData.m_numMarker = 0; return S_FALSE; } pOutSampleConfig->SetPointer((BYTE*)&sendData, sizeof(ARLayoutConfigData)); } if (FAILED(preHr)) { DbgLog((LOG_TRACE,1,TEXT("Error from transform"))); } else { if (preHr == NOERROR) { if(pSelf->getDirty() == true){ hr =pConfigOutputPin->Deliver(pOutSampleConfig);// m_pInputPin->Receive(pOutSample); pSelf->setDirty(false); } hr = ((GSMuxOutputPin*)pOutputPin)->Deliver(pOutSample);// m_pInputPin->Receive(pOutSample); pSelf->m_bSampleSkipped = FALSE; // last thing no longer dropped pSelf->setBlock(false); } else { if (S_FALSE == preHr) { SAFE_RELEASE(pOutSample); pSelf->m_bSampleSkipped = TRUE; if (!pSelf->m_bQualityChanged) { pSelf->NotifyEvent(EC_QUALITY_CHANGE,0,0); pSelf->m_bQualityChanged = TRUE; } return NOERROR; } } } sendData.m_ARMarkers = NULL; sendData.m_numMarker = 0; if (pOutSampleConfig != NULL) { pOutSampleConfig->Release(); pOutSampleConfig = NULL; } return hr; } bool ImProSyncFilter::getDirty(){ CAutoLock lck(&locDirty); return Dirty; } HRESULT ImProSyncFilter::setDirty(bool isDirty){ CAutoLock lck(&locDirty); Dirty = isDirty; return S_OK; } bool ImProSyncFilter::getBlock(){ CAutoLock lck(&locBlock); return Block; } HRESULT ImProSyncFilter::setBlock(bool isBlock){ CAutoLock lck(&locBlock); Block = isBlock; return S_OK; }
[ "claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 370 ] ] ]
d1f1aad36688be9469a6a8cf9b5b69134d208c7b
5c32ff848169b05f0627f24db99a4a77a3d62ac7
/BioStreamDB/DbPunch.h
c0dabcec51241438597c3775f2f35eb8cb7247db
[]
no_license
namin/micado
2ad5c269d93ac4a56ef1c346636587c6d49c14e0
04a675cfaf071b5cd9e4c005f0cd629fcbca3e95
refs/heads/master
2016-09-05T21:03:11.545033
2009-01-19T00:38:03
2009-01-19T00:38:03
40,253,425
1
0
null
null
null
null
UTF-8
C++
false
false
6,562
h
// (C) Copyright 2002-2005 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // //----------------------------------------------------------------------------- //----- DbPunch.h : Declaration of the DbPunch //----------------------------------------------------------------------------- #pragma once #ifdef BIOSTREAMDB_MODULE #define DLLIMPEXP __declspec(dllexport) #else //----- Note: we don't use __declspec(dllimport) here, because of the //----- "local vtable" problem with msvc. If you use __declspec(dllimport), //----- then, when a client dll does a new on the class, the object's //----- vtable pointer points to a vtable allocated in that client //----- dll. If the client dll then passes the object to another dll, //----- and the client dll is then unloaded, the vtable becomes invalid //----- and any virtual calls on the object will access invalid memory. //----- //----- By not using __declspec(dllimport), we guarantee that the //----- vtable is allocated in the server dll during the ctor and the //----- client dll does not overwrite the vtable pointer after calling //----- the ctor. And, since we expect the server dll to remain in //----- memory indefinitely, there is no problem with vtables unexpectedly //----- going away. #define DLLIMPEXP #endif //----------------------------------------------------------------------------- #include "dbpl.h" //----------------------------------------------------------------------------- class DLLIMPEXP DbPunch : public AcDbPolyline { public: ACRX_DECLARE_MEMBERS(DbPunch) ; protected: static Adesk::UInt32 kCurrentVersionNumber ; public: DbPunch () ; virtual ~DbPunch () ; //----- BioStream protocols virtual Acad::ErrorStatus setCenter(const AcGePoint2d& center); virtual Acad::ErrorStatus getCenter(AcGePoint2d& center) const; //----- AcDbObject protocols //- Dwg Filing protocol virtual Acad::ErrorStatus dwgOutFields (AcDbDwgFiler *pFiler) const ; virtual Acad::ErrorStatus dwgInFields (AcDbDwgFiler *pFiler) ; //- Dxf Filing protocol virtual Acad::ErrorStatus dxfOutFields (AcDbDxfFiler *pFiler) const ; virtual Acad::ErrorStatus dxfInFields (AcDbDxfFiler *pFiler) ; //- Automation support virtual Acad::ErrorStatus getClassID (CLSID *pClsid) const ; //----- AcDbEntity protocols //- Graphics protocol virtual Adesk::Boolean worldDraw (AcGiWorldDraw *mode) ; //----- AcDbCurve protocols //- Curve property tests. virtual Adesk::Boolean isClosed () const ; virtual Adesk::Boolean isPeriodic () const ; //- Get planar and start/end geometric properties. virtual Acad::ErrorStatus getStartParam (double &param) const ; virtual Acad::ErrorStatus getEndParam (double &param) const ; virtual Acad::ErrorStatus getStartPoint (AcGePoint3d &point) const ; virtual Acad::ErrorStatus getEndPoint (AcGePoint3d &point) const ; //- Conversions to/from parametric/world/distance. virtual Acad::ErrorStatus getPointAtParam (double param, AcGePoint3d &point) const ; virtual Acad::ErrorStatus getParamAtPoint (const AcGePoint3d &point, double &param) const ; virtual Acad::ErrorStatus getDistAtParam (double param, double &dist) const ; virtual Acad::ErrorStatus getParamAtDist (double dist, double &param) const ; virtual Acad::ErrorStatus getDistAtPoint (const AcGePoint3d &point , double &dist) const ; virtual Acad::ErrorStatus getPointAtDist (double dist, AcGePoint3d &point) const ; //- Derivative information. virtual Acad::ErrorStatus getFirstDeriv (double param, AcGeVector3d &firstDeriv) const ; virtual Acad::ErrorStatus getFirstDeriv (const AcGePoint3d &point, AcGeVector3d &firstDeriv) const ; virtual Acad::ErrorStatus getSecondDeriv (double param, AcGeVector3d &secDeriv) const ; virtual Acad::ErrorStatus getSecondDeriv (const AcGePoint3d &point, AcGeVector3d &secDeriv) const ; //- Closest point on curve. virtual Acad::ErrorStatus getClosestPointTo (const AcGePoint3d &givenPnt, AcGePoint3d &pointOnCurve, Adesk::Boolean extend =Adesk::kFalse) const ; virtual Acad::ErrorStatus getClosestPointTo (const AcGePoint3d &givenPnt, const AcGeVector3d &direction, AcGePoint3d &pointOnCurve, Adesk::Boolean extend =Adesk::kFalse) const ; //- Get a projected copy of the curve. virtual Acad::ErrorStatus getOrthoProjectedCurve (const AcGePlane &plane, AcDbCurve *&projCrv) const ; virtual Acad::ErrorStatus getProjectedCurve (const AcGePlane &plane, const AcGeVector3d &projDir, AcDbCurve *&projCrv) const ; //- Get offset, spline and split copies of the curve. virtual Acad::ErrorStatus getOffsetCurves (double offsetDist, AcDbVoidPtrArray &offsetCurves) const ; virtual Acad::ErrorStatus getOffsetCurvesGivenPlaneNormal (const AcGeVector3d &normal, double offsetDist, AcDbVoidPtrArray &offsetCurves) const ; virtual Acad::ErrorStatus getSpline (AcDbSpline *&spline) const ; virtual Acad::ErrorStatus getSplitCurves (const AcGeDoubleArray &params, AcDbVoidPtrArray &curveSegments) const ; virtual Acad::ErrorStatus getSplitCurves (const AcGePoint3dArray &points, AcDbVoidPtrArray &curveSegments) const ; //- Extend the curve. virtual Acad::ErrorStatus extend (double newParam) ; virtual Acad::ErrorStatus extend (Adesk::Boolean extendStart, const AcGePoint3d &toPoint) ; //- Area calculation. virtual Acad::ErrorStatus getArea (double &area) const ; private: AcGePoint2d m_center; // ----------------------------------------------------------------------------- virtual Acad::ErrorStatus transformBy(const AcGeMatrix3d & xform); } ; #ifdef BIOSTREAMDB_MODULE ACDB_REGISTER_OBJECT_ENTRY_AUTO(DbPunch) #endif
[ "Nada AMIN@b571c760-3347-0410-a02b-4f11275fb890" ]
[ [ [ 1, 130 ] ] ]
4f9ae413abad2a628ae3117b841dcffccada8b3b
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/sample/0130guitest/windowsample.cpp
c8e84cadaa0bcd6dd234d8cfc454c165496a1e40
[]
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
3,032
cpp
#include"windowsample.h" using namespace Maid; void WindowSample::Initialize( Maid::Graphics2DRender* r ) { m_pRender = r; m_hFont.Create( SIZE2DI(8,16), true ); } void WindowSample::OnInitialize( ID id, const IGUIParts& Parent ) { } void WindowSample::OnFinalize() { } const RECT2DI BARRECT(0,0,200,30); const RECT2DI CLIENTRECT(0,BARRECT.GetBottom(),200,200); const RECT2DI MINIRECT( 0,0, 30, 30); const RECT2DI HIDERECT(30,0, 30, 30); bool WindowSample::IsBarCollision( const POINT2DI& pos ) const { return Collision<int>::IsPointToRect( pos, BARRECT ); } bool WindowSample::IsClientCollision( const POINT2DI& pos ) const { return Collision<int>::IsPointToRect( pos, CLIENTRECT ); } bool WindowSample::IsMinimumButtonCollision( const POINT2DI& pos ) const { return Collision<int>::IsPointToRect( pos, MINIRECT ); } bool WindowSample::IsHideButtonCollision( const POINT2DI& pos ) const { return Collision<int>::IsPointToRect( pos, HIDERECT ); } void WindowSample::OnUpdateFrame() { } void WindowSample::OnUpdateDraw( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos ) { String str = MAIDTEXT("window:"); const bool in = IsMouseIn(); const WindowSample::STATE state = GetState(); const bool mini = IsMinimum(); switch( state ) { case WindowSample::STATE_NORMAL: { if( in ) { str += MAIDTEXT("入った"); } else { str += MAIDTEXT("通常"); } }break; case WindowSample::STATE_MOVING: { str += MAIDTEXT("移動中"); }break; case WindowSample::STATE_MINIMUMBUTTONDOWN: { str += MAIDTEXT("最小化ボタン"); }break; case WindowSample::STATE_HIDEBUTTONDOWN: { str += MAIDTEXT("消えるボタン"); }break; } { POINT2DI p = pos; p.x += BARRECT.x; p.y += BARRECT.y; m_pRender->Fill( p, COLOR_R32G32B32A32F(1,0,0,1), BARRECT.GetSize(), POINT2DI(0,0) ); } { POINT2DI p = pos; p.x += MINIRECT.x; p.y += MINIRECT.y; m_pRender->Fill( p, COLOR_R32G32B32A32F(0,1,1,1), MINIRECT.GetSize(), POINT2DI(0,0) ); } { POINT2DI p = pos; p.x += HIDERECT.x; p.y += HIDERECT.y; m_pRender->Fill( p, COLOR_R32G32B32A32F(0,0,1,1), HIDERECT.GetSize(), POINT2DI(0,0) ); } if( !mini ) { POINT2DI p = pos; p.x += CLIENTRECT.x; p.y += CLIENTRECT.y; m_pRender->Fill( p, COLOR_R32G32B32A32F(0,1,0,1), CLIENTRECT.GetSize(), POINT2DI(0,0) ); } m_pRender->BltText( pos, m_hFont, str, COLOR_R32G32B32A32F(1,1,1,1) ); } void WindowSample::OnMouseIn( const POINT2DI& pos ) { } void WindowSample::OnMouseOut( const POINT2DI& pos ) { } void WindowSample::OnMoveBegin( const POINT2DI& pos ) { } void WindowSample::OnMoveEnd( const POINT2DI& pos ) { } void WindowSample::OnMinimum( bool IsMin ) { } void WindowSample::OnChangeState( const POINT2DI& pos, STATE state ) { }
[ [ [ 1, 145 ] ] ]
e05eec9ae6f7dff1c5db2a23b6b2080bc96b5be1
8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab
/src-ginga-editing/gingancl-cpp/src/gingancl/adapters/av/AVPlayerAdapter.cpp
27daf4abdd4d8231142352a3847232fa61b3584d
[]
no_license
BrunoSSts/ginga-wac
7436a9815427a74032c9d58028394ccaac45cbf9
ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c
refs/heads/master
2020-05-20T22:21:33.645904
2011-10-17T12:34:32
2011-10-17T12:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,344
cpp
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Direitos Autorais Reservados (c) 1989-2007 PUC-Rio/Laboratorio TeleMidia Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licen�a Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribu�do na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: ncl @ telemidia.puc-rio.br http://www.ncl.org.br http://www.ginga.org.br http://www.telemidia.puc-rio.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright: 1989-2007 PUC-RIO/LABORATORIO TELEMIDIA, All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: ncl @ telemidia.puc-rio.br http://www.ncl.org.br http://www.ginga.org.br http://www.telemidia.puc-rio.br *******************************************************************************/ #include "../../../include/AVPlayerAdapter.h" namespace br { namespace pucrio { namespace telemidia { namespace ginga { namespace ncl { namespace adapters { namespace av { AVPlayerAdapter::AVPlayerAdapter(bool hasVisual) : FormatterPlayerAdapter() { this->hasVisual = hasVisual; typeSet.insert("AVPlayerAdapter"); } void AVPlayerAdapter::createPlayer() { CascadingDescriptor* descriptor; string soundLevel; player = new AVPlayer((char*)mrl.c_str(), hasVisual); descriptor = object->getDescriptor(); if (descriptor != NULL) { soundLevel = descriptor->getParameterValue("soundLevel"); if (soundLevel == "") { soundLevel = "1.0"; } player->setPropertyValue("soundLevel", soundLevel); } FormatterPlayerAdapter::createPlayer(); } bool AVPlayerAdapter::setPropertyValue( AttributionEvent* event, string value, Animation* animation) { return FormatterPlayerAdapter::setPropertyValue( event, value, animation); #ifdef STx7100 #ifdef GEODE if (value == "") { return; } string propName; AVPlayer* vp; CascadingDescriptor* descriptor; FormatterRegion* region; LayoutRegion* ncmRegion; propName = event->getAnchor()->getPropertyName(); propName = event->getAnchor()->getPropertyName(); if (propName == "size" || propName == "location" || propName == "bounds" || propName == "top" || propName == "left" || propName == "bottom" || propName == "right" || propName == "width" || propName == "height") { if (playerObj->instanceOf("AVPlayerObject")) { descriptor = object->getDescriptor(); region = descriptor->getFormatterRegion(); ncmRegion = region->getLayoutRegion(); vp = ((AVPlayerObject*)playerObj)->getPlayer(); vp->setVoutWindow(ncmRegion->getAbsoluteLeft(), ncmRegion->getAbsoluteTop(), ncmRegion->getWidthInPixels(), ncmRegion->getHeightInPixels()); vp->setAlphaBlend(ncmRegion->getAbsoluteLeft(), ncmRegion->getAbsoluteTop(), ncmRegion->getWidthInPixels(), ncmRegion->getHeightInPixels()); } } #endif /*GEODE*/ #endif /*STx7100*/ } bool AVPlayerAdapter::getHasVisual() { return this->hasVisual; } } } } } } } }
[ [ [ 1, 140 ] ] ]
2ad2fe58c1db3b0b9594586e2b218c9b310c8254
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Models/CONTROL1/Transmitter.h
e5a2e84f9ba37e2f15efdd4bf88478bdb28dd035
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,537
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __TRANSMITTER_H #define __TRANSMITTER_H #ifndef __SC_DEFS_H #include "sc_defs.h" #endif #ifndef __FLWNODE_H #include "flwnode.h" #endif #ifndef __MODELS_H #include "xrefs.h" #endif #ifndef __MODELS_H #include "models.h" #endif #ifdef __TRANSMITTER_CPP #define DllImportExport #elif !defined(Control1) #define DllImportExport DllImport #else #define DllImportExport #endif #define SKIPIT 0 #if SKIPIT #pragma message ("---------------------------------------SKIPPED") #else //============================================================================ _FWDDEF(CTransmitterBlk) class CTransmitterBlk : public CXRefStatus { public: Strng m_sID; Strng m_sIDMeas; Strng m_sIDVal; Strng m_sIDRaw; Strng m_sTagMeas; Strng m_sTagVal; Strng m_sTagRaw; CTgFnIoVar m_MeasVar; CTgFnIoVar m_TxVar; CTgFnIoVar m_RawVar; flag m_bValid:1; long m_iPriority; double m_dMeasValue; struct { byte m_iType; float m_dFactor; float m_dBias; } m_Xform; struct { byte m_iType; float m_dTau; double m_dPrevValue; } m_Flt; struct { byte m_iType; float m_dSlewTime; float m_dLoValue; float m_dHiValue; float m_dNoiseStdDevFrac; double m_dPrevValue; } m_Fail; float m_dMinValue; float m_dMaxValue; double m_dTXValue; float m_dLoLimit; float m_dHiLimit; flag m_bLoInvert; flag m_bHiInvert; flag m_bLo; flag m_bHi; struct { byte m_iType; float m_dMinValue; float m_dMaxValue; } m_RawXform; double m_dRawValue; Strng m_sPLCAddress; CTransmitterBlk(); virtual ~CTransmitterBlk(); void Init(CNodeXRefMngr * pXRM, int iNo); //flag DoSetVars(char* Tag); void ExecIns(double dT); //CXRefStatus Override bool IsXRefActive() const { return m_bValid; }; }; typedef CSmartPtrAllocate<CTransmitterBlk> CSPTransmitterBlk; typedef CArray<CSPTransmitterBlk, CSPTransmitterBlk&> CTransmitterArray; //-------------------------------------------------------------------------- DEFINE_TAGOBJ(CTransmitter); class CTransmitter : public FlwNode { friend class CTgFnIoVar; public: CTransmitterArray m_DataBlk; CArray <IOAreaRec, IOAreaRec> m_IOAreas; flag bOn; // static flag bWithCnvComment; Strng m_StateLine[3]; //status messages flag bDoneExtRefs:1, // bAboutToStart:1; //flag set True for first iteration when run is pressed CTransmitter(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~CTransmitter(); virtual void ResetData(flag Complete); private: void SetCount(long NewSize); flag SortRqd(); void Sort(); void FixIOTags(); public: virtual LPSTR Tag(); virtual LPSTR SetTag(LPSTR ReqdTag, bool AllowEmptyTag=false); virtual void Ctrl_ConnIDStr(int i, Strng & ID, Strng & Tg); virtual void BuildDataDefn(DataDefnBlk & DDB); virtual flag DataXchg(DataChangeBlk & DCB); virtual flag ValidateData(ValidateDataBlk & VDB); virtual flag PreStartCheck(); virtual void EvalCtrlStrategy(eScdCtrlTasks Tasks=CO_All); virtual int ChangeTag(pchar pOldTag, pchar pNewTag); virtual int DeleteTag(pchar pDelTag); // CNodeXRefMngr Overides virtual bool TestXRefListActive(); virtual int UpdateXRefLists(CXRefBuildResults & Results); virtual void UnlinkAllXRefs(); virtual void SetState(eScdMdlStateActs RqdState); virtual void EvalDiscrete(); virtual dword ModelStatus(); DEFINE_CI(CTransmitter, FlwNode, 4); }; //=========================================================================== #endif #undef DllImportExport #endif
[ [ [ 1, 142 ], [ 145, 150 ], [ 152, 155 ], [ 157, 175 ] ], [ [ 143, 144 ], [ 151, 151 ], [ 156, 156 ] ] ]
9b4bdb592fd7ffd9c2035e03b8f99eb4ef42cef7
b83c990328347a0a2130716fd99788c49c29621e
/include/boost/wave/util/cpp_macromap.hpp
137787ddc7032480521529409199413ec6c4ccff
[]
no_license
SpliFF/mingwlibs
c6249fbb13abd74ee9c16e0a049c88b27bd357cf
12d1369c9c1c2cc342f66c51d045b95c811ff90c
refs/heads/master
2021-01-18T03:51:51.198506
2010-06-13T15:13:20
2010-06-13T15:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
75,736
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Macro expansion engine http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(CPP_MACROMAP_HPP_CB8F51B0_A3F0_411C_AEF4_6FF631B8B414_INCLUDED) #define CPP_MACROMAP_HPP_CB8F51B0_A3F0_411C_AEF4_6FF631B8B414_INCLUDED #include <cstdlib> #include <cstdio> #include <ctime> #include <list> #include <map> #include <set> #include <vector> #include <iterator> #include <algorithm> #include <boost/assert.hpp> #include <boost/wave/wave_config.hpp> #if BOOST_WAVE_SERIALIZATION != 0 #include <boost/serialization/serialization.hpp> #include <boost/serialization/shared_ptr.hpp> #endif #include <boost/filesystem/path.hpp> #include <boost/wave/util/time_conversion_helper.hpp> #include <boost/wave/util/unput_queue_iterator.hpp> #include <boost/wave/util/macro_helpers.hpp> #include <boost/wave/util/macro_definition.hpp> #include <boost/wave/util/symbol_table.hpp> #include <boost/wave/util/cpp_macromap_utils.hpp> #include <boost/wave/util/cpp_macromap_predef.hpp> #include <boost/wave/util/filesystem_compatibility.hpp> #include <boost/wave/grammars/cpp_defined_grammar_gen.hpp> #include <boost/wave/wave_version.hpp> #include <boost/wave/cpp_exceptions.hpp> #include <boost/wave/language_support.hpp> // this must occur after all of the includes and before any code appears #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { namespace util { /////////////////////////////////////////////////////////////////////////////// // // macromap // // This class holds all currently defined macros and on demand expands // those macro definitions // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> class macromap { typedef macromap<ContextT> self_type; typedef typename ContextT::token_type token_type; typedef typename token_type::string_type string_type; typedef typename token_type::position_type position_type; typedef typename ContextT::token_sequence_type definition_container_type; typedef std::vector<token_type> parameter_container_type; typedef macro_definition<token_type, definition_container_type> macro_definition_type; typedef symbol_table<string_type, macro_definition_type> defined_macros_type; typedef typename defined_macros_type::value_type::second_type macro_ref_type; public: macromap(ContextT &ctx_) : current_macros(0), defined_macros(new defined_macros_type(1)), main_pos("", 0), ctx(ctx_), macro_uid(1) { current_macros = defined_macros.get(); } ~macromap() {} // Add a new macro to the given macro scope bool add_macro(token_type const &name, bool has_parameters, parameter_container_type &parameters, definition_container_type &definition, bool is_predefined = false, defined_macros_type *scope = 0); // Tests, whether the given macro name is defined in the given macro scope bool is_defined(string_type const &name, typename defined_macros_type::iterator &it, defined_macros_type *scope = 0) const; // expects a token sequence as its parameters template <typename IteratorT> bool is_defined(IteratorT const &begin, IteratorT const &end) const; // expects an arbitrary string as its parameter bool is_defined(string_type const &str) const; // Get the macro definition for the given macro scope bool get_macro(string_type const &name, bool &has_parameters, bool &is_predefined, position_type &pos, parameter_container_type &parameters, definition_container_type &definition, defined_macros_type *scope = 0) const; // Remove a macro name from the given macro scope bool remove_macro(string_type const &name, position_type const& pos, bool even_predefined = false); template <typename IteratorT, typename ContainerT> token_type const &expand_tokensequence(IteratorT &first, IteratorT const &last, ContainerT &pending, ContainerT &expanded, bool& seen_newline, bool expand_operator_defined); // Expand all macros inside the given token sequence template <typename IteratorT, typename ContainerT> void expand_whole_tokensequence(ContainerT &expanded, IteratorT &first, IteratorT const &last, bool expand_operator_defined); // Init the predefined macros (add them to the given scope) void init_predefined_macros(char const *fname = "<Unknown>", defined_macros_type *scope = 0, bool at_global_scope = true); void predefine_macro(defined_macros_type *scope, string_type const &name, token_type const &t); // Init the internal macro symbol namespace void reset_macromap(); position_type &get_main_pos() { return main_pos; } // interface for macro name introspection typedef typename defined_macros_type::name_iterator name_iterator; typedef typename defined_macros_type::const_name_iterator const_name_iterator; name_iterator begin() { return defined_macros_type::make_iterator(current_macros->begin()); } name_iterator end() { return defined_macros_type::make_iterator(current_macros->end()); } const_name_iterator begin() const { return defined_macros_type::make_iterator(current_macros->begin()); } const_name_iterator end() const { return defined_macros_type::make_iterator(current_macros->end()); } protected: // Helper functions for expanding all macros in token sequences template <typename IteratorT, typename ContainerT> token_type const &expand_tokensequence_worker(ContainerT &pending, unput_queue_iterator<IteratorT, token_type, ContainerT> &first, unput_queue_iterator<IteratorT, token_type, ContainerT> const &last, bool& seen_newline, bool expand_operator_defined); // Collect all arguments supplied to a macro invocation #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 template <typename IteratorT, typename ContainerT, typename SizeT> typename std::vector<ContainerT>::size_type collect_arguments ( token_type const curr_token, std::vector<ContainerT> &arguments, IteratorT &next, IteratorT const &end, SizeT const &parameter_count, bool& seen_newline); #else template <typename IteratorT, typename ContainerT, typename SizeT> typename std::vector<ContainerT>::size_type collect_arguments ( token_type const curr_token, std::vector<ContainerT> &arguments, IteratorT &next, IteratorT &endparen, IteratorT const &end, SizeT const &parameter_count, bool& seen_newline); #endif // Expand a single macro name template <typename IteratorT, typename ContainerT> bool expand_macro(ContainerT &pending, token_type const &name, typename defined_macros_type::iterator it, IteratorT &first, IteratorT const &last, bool& seen_newline, bool expand_operator_defined, defined_macros_type *scope = 0, ContainerT *queue_symbol = 0); // Expand a predefined macro (__LINE__, __FILE__ and __INCLUDE_LEVEL__) template <typename ContainerT> bool expand_predefined_macro(token_type const &curr_token, ContainerT &expanded); // Expand a single macro argument template <typename ContainerT> void expand_argument (typename std::vector<ContainerT>::size_type arg, std::vector<ContainerT> &arguments, std::vector<ContainerT> &expanded_args, bool expand_operator_defined, std::vector<bool> &has_expanded_args); // Expand the replacement list (replaces parameters with arguments) template <typename ContainerT> void expand_replacement_list( macro_definition_type const &macrodefinition, std::vector<ContainerT> &arguments, bool expand_operator_defined, ContainerT &expanded); // Rescans the replacement list for macro expansion template <typename IteratorT, typename ContainerT> void rescan_replacement_list(token_type const &curr_token, macro_definition_type &macrodef, ContainerT &replacement_list, ContainerT &expanded, bool expand_operator_defined, IteratorT &nfirst, IteratorT const &nlast); // Resolves the operator defined() and replces the token with "0" or "1" template <typename IteratorT, typename ContainerT> token_type const &resolve_defined(IteratorT &first, IteratorT const &last, ContainerT &expanded); // Resolve operator _Pragma or the #pragma directive template <typename IteratorT, typename ContainerT> bool resolve_operator_pragma(IteratorT &first, IteratorT const &last, ContainerT &expanded, bool& seen_newline); // Handle the concatenation operator '##' template <typename ContainerT> bool concat_tokensequence(ContainerT &expanded); template <typename ContainerT> bool is_valid_concat(string_type new_value, position_type const &pos, ContainerT &rescanned); #if BOOST_WAVE_SERIALIZATION != 0 public: BOOST_STATIC_CONSTANT(unsigned int, version = 0x10); BOOST_STATIC_CONSTANT(unsigned int, version_mask = 0x0f); private: friend class boost::serialization::access; template<typename Archive> void save(Archive &ar, const unsigned int version) const { using namespace boost::serialization; ar & make_nvp("defined_macros", defined_macros); } template<typename Archive> void load(Archive &ar, const unsigned int loaded_version) { using namespace boost::serialization; if (version != (loaded_version & ~version_mask)) { BOOST_WAVE_THROW(preprocess_exception, incompatible_config, "cpp_context state version", get_main_pos()); } ar & make_nvp("defined_macros", defined_macros); current_macros = defined_macros.get(); } BOOST_SERIALIZATION_SPLIT_MEMBER() #endif private: defined_macros_type *current_macros; // current symbol table boost::shared_ptr<defined_macros_type> defined_macros; // global symbol table token_type act_token; // current token position_type main_pos; // last token position in the pp_iterator string_type base_name; // the name to be expanded by __BASE_FILE__ ContextT &ctx; // context object associated with the macromap long macro_uid; predefined_macros predef; // predefined macro support }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // add_macro(): adds a new macro to the macromap // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline bool macromap<ContextT>::add_macro(token_type const &name, bool has_parameters, parameter_container_type &parameters, definition_container_type &definition, bool is_predefined, defined_macros_type *scope) { if (!is_predefined && impl::is_special_macroname (name.get_value())) { // exclude special macro names BOOST_WAVE_THROW_NAME_CTX(ctx, macro_handling_exception, illegal_redefinition, name.get_value().c_str(), main_pos, name.get_value().c_str()); return false; } if (boost::wave::need_variadics(ctx.get_language()) && "__VA_ARGS__" == name.get_value()) { // can't use __VA_ARGS__ as a macro name BOOST_WAVE_THROW_NAME_CTX(ctx, macro_handling_exception, bad_define_statement_va_args, name.get_value().c_str(), main_pos, name.get_value().c_str()); return false; } if (AltExtTokenType == (token_id(name) & ExtTokenOnlyMask)) { // exclude special operator names BOOST_WAVE_THROW_NAME_CTX(ctx, macro_handling_exception, illegal_operator_redefinition, name.get_value().c_str(), main_pos, name.get_value().c_str()); return false; } // try to define the new macro defined_macros_type *current_scope = scope ? scope : current_macros; typename defined_macros_type::iterator it = current_scope->find(name.get_value()); if (it != current_scope->end()) { // redefinition, should not be different macro_definition_type* macrodef = (*it).second.get(); if (macrodef->is_functionlike != has_parameters || !impl::parameters_equal(macrodef->macroparameters, parameters) || !impl::definition_equals(macrodef->macrodefinition, definition)) { BOOST_WAVE_THROW_NAME_CTX(ctx, macro_handling_exception, macro_redefinition, name.get_value().c_str(), main_pos, name.get_value().c_str()); } return false; } // test the validity of the parameter names if (has_parameters) { std::set<typename token_type::string_type> names; typedef typename parameter_container_type::iterator parameter_iterator_type; typedef typename std::set<typename token_type::string_type>::iterator name_iterator_type; parameter_iterator_type end = parameters.end(); for (parameter_iterator_type itp = parameters.begin(); itp != end; ++itp) { name_iterator_type pit = names.find((*itp).get_value()); if (pit != names.end()) { // duplicate parameter name BOOST_WAVE_THROW_NAME_CTX(ctx, macro_handling_exception, duplicate_parameter_name, (*pit).c_str(), main_pos, name.get_value().c_str()); return false; } names.insert((*itp).get_value()); } } // insert a new macro node std::pair<typename defined_macros_type::iterator, bool> p = current_scope->insert( typename defined_macros_type::value_type( name.get_value(), macro_ref_type(new macro_definition_type(name, has_parameters, is_predefined, ++macro_uid) ) ) ); if (!p.second) { BOOST_WAVE_THROW_NAME_CTX(ctx, macro_handling_exception, macro_insertion_error, name.get_value().c_str(), main_pos, name.get_value().c_str()); return false; } // add the parameters and the definition std::swap((*p.first).second->macroparameters, parameters); std::swap((*p.first).second->macrodefinition, definition); // call the context supplied preprocessing hook #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().defined_macro(name, has_parameters, (*p.first).second->macroparameters, (*p.first).second->macrodefinition, is_predefined); #else ctx.get_hooks().defined_macro(ctx.derived(), name, has_parameters, (*p.first).second->macroparameters, (*p.first).second->macrodefinition, is_predefined); #endif return true; } /////////////////////////////////////////////////////////////////////////////// // // is_defined(): returns, whether a given macro is already defined // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline bool macromap<ContextT>::is_defined(typename token_type::string_type const &name, typename defined_macros_type::iterator &it, defined_macros_type *scope) const { if (0 == scope) scope = current_macros; if ((it = scope->find(name)) != scope->end()) return true; // found in symbol table // quick pre-check if (name.size() < 8 || '_' != name[0] || '_' != name[1]) return false; // quick check failed return name == "__LINE__" || name == "__FILE__" || name == "__INCLUDE_LEVEL__"; } template <typename ContextT> template <typename IteratorT> inline bool macromap<ContextT>::is_defined(IteratorT const &begin, IteratorT const &end) const { // in normal mode the name under inspection should consist of an identifier // only token_id id = token_id(*begin); if (T_IDENTIFIER != id && !IS_CATEGORY(id, KeywordTokenType) && !IS_EXTCATEGORY(id, OperatorTokenType|AltExtTokenType) && !IS_CATEGORY(id, BoolLiteralTokenType)) { BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, invalid_macroname, impl::get_full_name(begin, end).c_str(), main_pos); return false; } IteratorT it = begin; string_type name ((*it).get_value()); typename defined_macros_type::iterator cit; if (++it != end) { // there should be only one token as the inspected name BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, invalid_macroname, impl::get_full_name(begin, end).c_str(), main_pos); return false; } return is_defined(name, cit, 0); } /////////////////////////////////////////////////////////////////////////////// // same as above, only takes an arbitrary string type as its parameter template <typename ContextT> inline bool macromap<ContextT>::is_defined(string_type const &str) const { typename defined_macros_type::iterator cit; return is_defined(str, cit, 0); } /////////////////////////////////////////////////////////////////////////////// // // Get the macro definition for the given macro scope // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline bool macromap<ContextT>::get_macro(string_type const &name, bool &has_parameters, bool &is_predefined, position_type &pos, parameter_container_type &parameters, definition_container_type &definition, defined_macros_type *scope) const { typename defined_macros_type::iterator it; if (!is_defined(name, it, scope)) return false; macro_definition_type &macro_def = *(*it).second.get(); has_parameters = macro_def.is_functionlike; is_predefined = macro_def.is_predefined; pos = macro_def.macroname.get_position(); parameters = macro_def.macroparameters; definition = macro_def.macrodefinition; return true; } /////////////////////////////////////////////////////////////////////////////// // // remove_macro(): remove a macro from the macromap // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline bool macromap<ContextT>::remove_macro(string_type const &name, position_type const& pos, bool even_predefined) { typename defined_macros_type::iterator it = current_macros->find(name); if (it != current_macros->end()) { if ((*it).second->is_predefined) { if (!even_predefined || impl::is_special_macroname(name)) { BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, bad_undefine_statement, name.c_str(), main_pos); return false; } } current_macros->erase(it); // call the context supplied preprocessing hook function token_type tok(T_IDENTIFIER, name, pos); #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().undefined_macro(tok); #else ctx.get_hooks().undefined_macro(ctx.derived(), tok); #endif return true; } else if (impl::is_special_macroname(name)) { BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, bad_undefine_statement, name.c_str(), pos); } return false; // macro was not defined } /////////////////////////////////////////////////////////////////////////////// // // expand_tokensequence // // This function is a helper function which wraps the given iterator // range into corresponding unput_iterator's and calls the main workhorse // of the macro expansion engine (the function expand_tokensequence_worker) // // This is the top level macro expansion function called from the // preprocessing iterator component only. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline typename ContextT::token_type const & macromap<ContextT>::expand_tokensequence(IteratorT &first, IteratorT const &last, ContainerT &pending, ContainerT &expanded, bool& seen_newline, bool expand_operator_defined) { typedef impl::gen_unput_queue_iterator<IteratorT, token_type, ContainerT> gen_type; typedef typename gen_type::return_type iterator_type; iterator_type first_it = gen_type::generate(expanded, first); iterator_type last_it = gen_type::generate(last); on_exit::assign<IteratorT, iterator_type> on_exit(first, first_it); return expand_tokensequence_worker(pending, first_it, last_it, seen_newline, expand_operator_defined); } /////////////////////////////////////////////////////////////////////////////// // // expand_tokensequence_worker // // This function is the main workhorse of the macro expansion engine. It // expands as much tokens as needed to identify the next preprocessed // token to return to the caller. // It returns the next preprocessed token. // // The iterator 'first' is adjusted accordingly. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline typename ContextT::token_type const & macromap<ContextT>::expand_tokensequence_worker( ContainerT &pending, unput_queue_iterator<IteratorT, token_type, ContainerT> &first, unput_queue_iterator<IteratorT, token_type, ContainerT> const &last, bool& seen_newline, bool expand_operator_defined) { // if there exist pending tokens (tokens, which are already preprocessed), then // return the next one from there if (!pending.empty()) { on_exit::pop_front<definition_container_type> pop_front_token(pending); return act_token = pending.front(); } // analyze the next element of the given sequence, if it is an // T_IDENTIFIER token, try to replace this as a macro etc. using namespace boost::wave; typedef unput_queue_iterator<IteratorT, token_type, ContainerT> iterator_type; if (first != last) { token_id id = token_id(*first); // ignore placeholder tokens if (T_PLACEHOLDER == id) { token_type placeholder = *first; ++first; if (first == last) return act_token = placeholder; id = token_id(*first); } if (T_IDENTIFIER == id || IS_CATEGORY(id, KeywordTokenType) || IS_EXTCATEGORY(id, OperatorTokenType|AltExtTokenType) || IS_CATEGORY(id, BoolLiteralTokenType)) { // try to replace this identifier as a macro if (expand_operator_defined && (*first).get_value() == "defined") { // resolve operator defined() return resolve_defined(first, last, pending); } else if (boost::wave::need_variadics(ctx.get_language()) && (*first).get_value() == "_Pragma") { // in C99 mode only: resolve the operator _Pragma token_type curr_token = *first; if (!resolve_operator_pragma(first, last, pending, seen_newline) || pending.size() > 0) { // unknown to us pragma or supplied replacement, return the // next token on_exit::pop_front<definition_container_type> pop_token(pending); return act_token = pending.front(); } // the operator _Pragma() was eaten completely, continue return act_token = token_type(T_PLACEHOLDER, "_", curr_token.get_position()); } token_type name_token (*first); typename defined_macros_type::iterator it; if (is_defined(name_token.get_value(), it)) { // the current token contains an identifier, which is currently // defined as a macro if (expand_macro(pending, name_token, it, first, last, seen_newline, expand_operator_defined)) { // the tokens returned by expand_macro should be rescanned // beginning at the last token of the returned replacement list if (first != last) { // splice the last token back into the input queue typename ContainerT::reverse_iterator rit = pending.rbegin(); first.get_unput_queue().splice( first.get_unput_queue().begin(), pending, (++rit).base(), pending.end()); } // fall through ... } else if (!pending.empty()) { // return the first token from the pending queue on_exit::pop_front<definition_container_type> pop_queue (pending); return act_token = pending.front(); } else { // macro expansion reached the eoi return act_token = token_type(); } // return the next preprocessed token return expand_tokensequence_worker(pending, first, last, seen_newline, expand_operator_defined); } // else if (expand_operator_defined) { // // in preprocessing conditionals undefined identifiers and keywords // // are to be replaced with '0' (see. C++ standard 16.1.4, [cpp.cond]) // return act_token = // token_type(T_INTLIT, "0", (*first++).get_position()); // } else { act_token = name_token; ++first; return act_token; } } else if (expand_operator_defined && IS_CATEGORY(*first, BoolLiteralTokenType)) { // expanding a constant expression inside #if/#elif, special handling // of 'true' and 'false' // all remaining identifiers and keywords, except for true and false, // are replaced with the pp-number 0 (C++ standard 16.1.4, [cpp.cond]) return act_token = token_type(T_INTLIT, T_TRUE != id ? "0" : "1", (*first++).get_position()); } else { act_token = *first; ++first; return act_token; } } return act_token = token_type(); // eoi } /////////////////////////////////////////////////////////////////////////////// // // collect_arguments(): collect the actual arguments of a macro invocation // // return the number of successfully detected non-empty arguments // /////////////////////////////////////////////////////////////////////////////// #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 template <typename ContextT> template <typename IteratorT, typename ContainerT, typename SizeT> inline typename std::vector<ContainerT>::size_type macromap<ContextT>::collect_arguments (token_type const curr_token, std::vector<ContainerT> &arguments, IteratorT &next, IteratorT const &end, SizeT const &parameter_count, bool& seen_newline) #else template <typename ContextT> template <typename IteratorT, typename ContainerT, typename SizeT> inline typename std::vector<ContainerT>::size_type macromap<ContextT>::collect_arguments (token_type const curr_token, std::vector<ContainerT> &arguments, IteratorT &next, IteratorT &endparen, IteratorT const &end, SizeT const &parameter_count, bool& seen_newline) #endif { using namespace boost::wave; arguments.push_back(ContainerT()); // collect the actual arguments typename std::vector<ContainerT>::size_type count_arguments = 0; int nested_parenthesis_level = 1; ContainerT *argument = &arguments[0]; bool was_whitespace = false; token_type startof_argument_list = *next; while (++next != end && nested_parenthesis_level) { token_id id = token_id(*next); if (0 == parameter_count && !IS_CATEGORY((*next), WhiteSpaceTokenType) && id != T_NEWLINE && id != T_RIGHTPAREN && id != T_LEFTPAREN) { // there shouldn't be any arguments BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, too_many_macroarguments, curr_token.get_value().c_str(), main_pos); return 0; } switch (static_cast<unsigned int>(id)) { case T_LEFTPAREN: ++nested_parenthesis_level; argument->push_back(*next); was_whitespace = false; break; case T_RIGHTPAREN: { if (--nested_parenthesis_level >= 1) argument->push_back(*next); else { // found closing parenthesis // trim_sequence(argument); #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS == 0 endparen = next; #endif if (parameter_count > 0) { if (argument->empty() || impl::is_whitespace_only(*argument)) { #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (boost::wave::need_variadics(ctx.get_language())) { // store a placemarker as the argument argument->push_back(token_type(T_PLACEMARKER, "\xA7", (*next).get_position())); ++count_arguments; } #endif } else { ++count_arguments; } } } was_whitespace = false; } break; case T_COMMA: if (1 == nested_parenthesis_level) { // next parameter // trim_sequence(argument); if (argument->empty() || impl::is_whitespace_only(*argument)) { #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (boost::wave::need_variadics(ctx.get_language())) { // store a placemarker as the argument argument->push_back(token_type(T_PLACEMARKER, "\xA7", (*next).get_position())); ++count_arguments; } #endif } else { ++count_arguments; } arguments.push_back(ContainerT()); // add new arg argument = &arguments[arguments.size()-1]; } else { // surrounded by parenthesises, so store to current argument argument->push_back(*next); } was_whitespace = false; break; case T_NEWLINE: seen_newline = true; /* fall through */ case T_SPACE: case T_SPACE2: case T_CCOMMENT: if (!was_whitespace) argument->push_back(token_type(T_SPACE, " ", (*next).get_position())); was_whitespace = true; break; // skip whitespace case T_PLACEHOLDER: break; // ignore placeholder default: argument->push_back(*next); was_whitespace = false; break; } } if (nested_parenthesis_level >= 1) { // missing ')': improperly terminated macro invocation BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, improperly_terminated_macro, "missing ')'", main_pos); return 0; } // if no argument was expected and we didn't find any, than remove the empty // element if (0 == parameter_count && 0 == count_arguments) { BOOST_ASSERT(1 == arguments.size()); arguments.clear(); } return count_arguments; } /////////////////////////////////////////////////////////////////////////////// // // expand_whole_tokensequence // // fully expands a given token sequence // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline void macromap<ContextT>::expand_whole_tokensequence(ContainerT &expanded, IteratorT &first, IteratorT const &last, bool expand_operator_defined) { typedef impl::gen_unput_queue_iterator<IteratorT, token_type, ContainerT> gen_type; typedef typename gen_type::return_type iterator_type; iterator_type first_it = gen_type::generate(first); iterator_type last_it = gen_type::generate(last); on_exit::assign<IteratorT, iterator_type> on_exit(first, first_it); ContainerT pending_queue; bool seen_newline; while (!pending_queue.empty() || first_it != last_it) { expanded.push_back( expand_tokensequence_worker(pending_queue, first_it, last_it, seen_newline, expand_operator_defined) ); } // should have returned all expanded tokens BOOST_ASSERT(pending_queue.empty()/* && unput_queue.empty()*/); } /////////////////////////////////////////////////////////////////////////////// // // expand_argument // // fully expands the given argument of a macro call // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename ContainerT> inline void macromap<ContextT>::expand_argument ( typename std::vector<ContainerT>::size_type arg, std::vector<ContainerT> &arguments, std::vector<ContainerT> &expanded_args, bool expand_operator_defined, std::vector<bool> &has_expanded_args) { if (!has_expanded_args[arg]) { // expand the argument only once typedef typename std::vector<ContainerT>::value_type::iterator argument_iterator_type; argument_iterator_type begin_it = arguments[arg].begin(); argument_iterator_type end_it = arguments[arg].end(); expand_whole_tokensequence(expanded_args[arg], begin_it, end_it, expand_operator_defined); impl::remove_placeholders(expanded_args[arg]); has_expanded_args[arg] = true; } } /////////////////////////////////////////////////////////////////////////////// // // expand_replacement_list // // fully expands the replacement list of a given macro with the // actual arguments/expanded arguments // handles the '#' [cpp.stringize] and the '##' [cpp.concat] operator // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename ContainerT> inline void macromap<ContextT>::expand_replacement_list( macro_definition_type const &macrodef, std::vector<ContainerT> &arguments, bool expand_operator_defined, ContainerT &expanded) { using namespace boost::wave; typedef typename macro_definition_type::const_definition_iterator_t macro_definition_iter_t; std::vector<ContainerT> expanded_args(arguments.size()); std::vector<bool> has_expanded_args(arguments.size()); bool seen_concat = false; bool adjacent_concat = false; bool adjacent_stringize = false; macro_definition_iter_t cend = macrodef.macrodefinition.end(); for (macro_definition_iter_t cit = macrodef.macrodefinition.begin(); cit != cend; ++cit) { bool use_replaced_arg = true; token_id base_id = BASE_TOKEN(token_id(*cit)); if (T_POUND_POUND == base_id) { // concatenation operator adjacent_concat = true; seen_concat = true; } else if (T_POUND == base_id) { // stringize operator adjacent_stringize = true; } else { if (adjacent_stringize || adjacent_concat || T_POUND_POUND == impl::next_token<macro_definition_iter_t> ::peek(cit, cend)) { use_replaced_arg = false; } if (adjacent_concat) // spaces after '##' ? adjacent_concat = IS_CATEGORY(*cit, WhiteSpaceTokenType); } if (IS_CATEGORY((*cit), ParameterTokenType)) { // copy argument 'i' instead of the parameter token i typename ContainerT::size_type i; #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 bool is_ellipsis = false; if (IS_EXTCATEGORY((*cit), ExtParameterTokenType)) { BOOST_ASSERT(boost::wave::need_variadics(ctx.get_language())); i = token_id(*cit) - T_EXTPARAMETERBASE; is_ellipsis = true; } else #endif { i = token_id(*cit) - T_PARAMETERBASE; } BOOST_ASSERT(i < arguments.size()); if (use_replaced_arg) { #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (is_ellipsis) { position_type const &pos = (*cit).get_position(); BOOST_ASSERT(boost::wave::need_variadics(ctx.get_language())); // ensure all variadic arguments to be expanded for (typename vector<ContainerT>::size_type arg = i; arg < expanded_args.size(); ++arg) { expand_argument(arg, arguments, expanded_args, expand_operator_defined, has_expanded_args); } impl::replace_ellipsis(expanded_args, i, expanded, pos); } else #endif { // ensure argument i to be expanded expand_argument(i, arguments, expanded_args, expand_operator_defined, has_expanded_args); // replace argument ContainerT const &arg = expanded_args[i]; std::copy(arg.begin(), arg.end(), std::inserter(expanded, expanded.end())); } } else if (adjacent_stringize && !IS_CATEGORY(*cit, WhiteSpaceTokenType)) { // stringize the current argument BOOST_ASSERT(!arguments[i].empty()); // safe a copy of the first tokens position (not a reference!) position_type pos ((*arguments[i].begin()).get_position()); #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (is_ellipsis && boost::wave::need_variadics(ctx.get_language())) { impl::trim_sequence_left(arguments[i]); impl::trim_sequence_right(arguments.back()); expanded.push_back(token_type(T_STRINGLIT, impl::as_stringlit(arguments, i, pos), pos)); } else #endif { impl::trim_sequence(arguments[i]); expanded.push_back(token_type(T_STRINGLIT, impl::as_stringlit(arguments[i], pos), pos)); } adjacent_stringize = false; } else { // simply copy the original argument (adjacent '##' or '#') #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (is_ellipsis) { position_type const &pos = (*cit).get_position(); impl::trim_sequence_left(arguments[i]); impl::trim_sequence_right(arguments.back()); BOOST_ASSERT(boost::wave::need_variadics(ctx.get_language())); impl::replace_ellipsis(arguments, i, expanded, pos); } else #endif { ContainerT &arg = arguments[i]; impl::trim_sequence(arg); std::copy(arg.begin(), arg.end(), std::inserter(expanded, expanded.end())); } } } else if (!adjacent_stringize || T_POUND != base_id) { // insert the actual replacement token (if it is not the '#' operator) expanded.push_back(*cit); } } if (adjacent_stringize) { // error, '#' should not be the last token BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_operator, "stringize ('#')", main_pos); return; } // handle the cpp.concat operator if (seen_concat) concat_tokensequence(expanded); } /////////////////////////////////////////////////////////////////////////////// // // rescan_replacement_list // // As the name implies, this function is used to rescan the replacement list // after the first macro substitution phase. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline void macromap<ContextT>::rescan_replacement_list(token_type const &curr_token, macro_definition_type &macro_def, ContainerT &replacement_list, ContainerT &expanded, bool expand_operator_defined, IteratorT &nfirst, IteratorT const &nlast) { if (!replacement_list.empty()) { #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 // remove the placemarkers if (boost::wave::need_variadics(ctx.get_language())) { typename ContainerT::iterator end = replacement_list.end(); typename ContainerT::iterator it = replacement_list.begin(); while (it != end) { using namespace boost::wave; if (T_PLACEMARKER == token_id(*it)) { typename ContainerT::iterator placemarker = it; ++it; replacement_list.erase(placemarker); } else { ++it; } } } #endif // rescan the replacement list, during this rescan the current macro under // expansion isn't available as an expandable macro on_exit::reset<bool> on_exit(macro_def.is_available_for_replacement, false); typename ContainerT::iterator begin_it = replacement_list.begin(); typename ContainerT::iterator end_it = replacement_list.end(); expand_whole_tokensequence(expanded, begin_it, end_it, expand_operator_defined); // trim replacement list, leave placeholder tokens untouched impl::trim_replacement_list(expanded); } if (expanded.empty()) { // the resulting replacement list should contain at least a placeholder // token expanded.push_back(token_type(T_PLACEHOLDER, "_", curr_token.get_position())); } } /////////////////////////////////////////////////////////////////////////////// // // expand_macro(): expands a defined macro // // This functions tries to expand the macro, to which points the 'first' // iterator. The functions eats up more tokens, if the macro to expand is // a function-like macro. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline bool macromap<ContextT>::expand_macro(ContainerT &expanded, token_type const &curr_token, typename defined_macros_type::iterator it, IteratorT &first, IteratorT const &last, bool& seen_newline, bool expand_operator_defined, defined_macros_type *scope, ContainerT *queue_symbol) { using namespace boost::wave; if (0 == scope) scope = current_macros; BOOST_ASSERT(T_IDENTIFIER == token_id(curr_token) || IS_CATEGORY(token_id(curr_token), KeywordTokenType) || IS_EXTCATEGORY(token_id(curr_token), OperatorTokenType|AltExtTokenType) || IS_CATEGORY(token_id(curr_token), BoolLiteralTokenType)); if (it == scope->end()) { ++first; // advance // try to expand a predefined macro (__FILE__, __LINE__ or __INCLUDE_LEVEL__) if (expand_predefined_macro(curr_token, expanded)) return false; // not defined as a macro if (0 != queue_symbol) { expanded.splice(expanded.end(), *queue_symbol); } else { expanded.push_back(curr_token); } return false; } // ensure the parameters to be replaced with special parameter tokens macro_definition_type &macro_def = *(*it).second.get(); macro_def.replace_parameters(); // test if this macro is currently available for replacement if (!macro_def.is_available_for_replacement) { // this macro is marked as non-replaceable // copy the macro name itself if (0 != queue_symbol) { queue_symbol->push_back(token_type(T_NONREPLACABLE_IDENTIFIER, curr_token.get_value(), curr_token.get_position())); expanded.splice(expanded.end(), *queue_symbol); } else { expanded.push_back(token_type(T_NONREPLACABLE_IDENTIFIER, curr_token.get_value(), curr_token.get_position())); } ++first; return false; } // try to replace the current identifier as a function-like macro ContainerT replacement_list; if (T_LEFTPAREN == impl::next_token<IteratorT>::peek(first, last)) { // called as a function-like macro impl::skip_to_token(first, last, T_LEFTPAREN, seen_newline); #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS == 0 IteratorT seqstart = first; IteratorT seqend = first; #endif if (macro_def.is_functionlike) { // defined as a function-like macro // collect the arguments std::vector<ContainerT> arguments; #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 typename std::vector<ContainerT>::size_type count_args = collect_arguments (curr_token, arguments, first, last, macro_def.macroparameters.size(), seen_newline); #else typename std::vector<ContainerT>::size_type count_args = collect_arguments (curr_token, arguments, first, seqend, last, macro_def.macroparameters.size(), seen_newline); #endif // verify the parameter count if (count_args < macro_def.macroparameters.size() || arguments.size() < macro_def.macroparameters.size()) { if (count_args != arguments.size()) { // must been at least one empty argument in C++ mode BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, empty_macroarguments, curr_token.get_value().c_str(), main_pos); } else { // too few macro arguments BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, too_few_macroarguments, curr_token.get_value().c_str(), main_pos); } return false; } if (count_args > macro_def.macroparameters.size() || arguments.size() > macro_def.macroparameters.size()) { #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (!macro_def.has_ellipsis) #endif { // too many macro arguments BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, too_many_macroarguments, curr_token.get_value().c_str(), main_pos); return false; } } // inject tracing support #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().expanding_function_like_macro( macro_def.macroname, macro_def.macroparameters, macro_def.macrodefinition, curr_token, arguments); #else if (ctx.get_hooks().expanding_function_like_macro(ctx.derived(), macro_def.macroname, macro_def.macroparameters, macro_def.macrodefinition, curr_token, arguments, seqstart, seqend)) { // do not expand this macro, just copy the whole sequence std::copy(seqstart, first, std::inserter(replacement_list, replacement_list.end())); return false; // no further preprocessing required } #endif // expand the replacement list of this macro expand_replacement_list(macro_def, arguments, expand_operator_defined, replacement_list); } else { // defined as an object-like macro #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().expanding_object_like_macro( macro_def.macroname, macro_def.macrodefinition, curr_token); #else if (ctx.get_hooks().expanding_object_like_macro(ctx.derived(), macro_def.macroname, macro_def.macrodefinition, curr_token)) { // do not expand this macro, just copy the whole sequence replacement_list.push_back(curr_token); ++first; // skip macro name return false; // no further preprocessing required } #endif bool found = false; impl::find_concat_operator concat_tag(found); std::remove_copy_if(macro_def.macrodefinition.begin(), macro_def.macrodefinition.end(), std::inserter(replacement_list, replacement_list.end()), concat_tag); // handle concatenation operators if (found && !concat_tokensequence(replacement_list)) return false; } } else { // called as an object like macro if ((*it).second->is_functionlike) { // defined as a function-like macro if (0 != queue_symbol) { queue_symbol->push_back(curr_token); expanded.splice(expanded.end(), *queue_symbol); } else { expanded.push_back(curr_token); } ++first; // skip macro name return false; // no further preprocessing required } else { // defined as an object-like macro (expand it) #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().expanding_object_like_macro( macro_def.macroname, macro_def.macrodefinition, curr_token); #else if (ctx.get_hooks().expanding_object_like_macro(ctx.derived(), macro_def.macroname, macro_def.macrodefinition, curr_token)) { // do not expand this macro, just copy the whole sequence replacement_list.push_back(curr_token); ++first; // skip macro name return false; // no further preprocessing required } #endif bool found = false; impl::find_concat_operator concat_tag(found); std::remove_copy_if(macro_def.macrodefinition.begin(), macro_def.macrodefinition.end(), std::inserter(replacement_list, replacement_list.end()), concat_tag); // handle concatenation operators if (found && !concat_tokensequence(replacement_list)) return false; ++first; // skip macro name } } // rescan the replacement list ContainerT expanded_list; #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().expanded_macro(replacement_list); #else ctx.get_hooks().expanded_macro(ctx.derived(), replacement_list); #endif rescan_replacement_list(curr_token, macro_def, replacement_list, expanded_list, expand_operator_defined, first, last); #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 ctx.get_hooks().rescanned_macro(expanded_list); #else ctx.get_hooks().rescanned_macro(ctx.derived(), expanded_list); #endif expanded.splice(expanded.end(), expanded_list); return true; // rescan is required } /////////////////////////////////////////////////////////////////////////////// // // If the token under inspection points to a certain predefined macro it will // be expanded, otherwise false is returned. // (only __FILE__, __LINE__ and __INCLUDE_LEVEL__ macros are expanded here) // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename ContainerT> inline bool macromap<ContextT>::expand_predefined_macro(token_type const &curr_token, ContainerT &expanded) { using namespace boost::wave; string_type const &value = curr_token.get_value(); if (value.size() < 8 || '_' != value[0] || '_' != value[1]) return false; // quick check failed if (value == "__LINE__") { // expand the __LINE__ macro char buffer[22]; // 21 bytes holds all NUL-terminated unsigned 64-bit numbers using namespace std; // for some systems sprintf is in namespace std sprintf(buffer, "%d", main_pos.get_line()); expanded.push_back(token_type(T_INTLIT, buffer, curr_token.get_position())); return true; } else if (value == "__FILE__") { // expand the __FILE__ macro namespace fs = boost::filesystem; std::string file("\""); fs::path filename(wave::util::create_path(main_pos.get_file().c_str())); using boost::wave::util::impl::escape_lit; file += escape_lit(wave::util::native_file_string(filename)) + "\""; expanded.push_back(token_type(T_STRINGLIT, file.c_str(), curr_token.get_position())); return true; } else if (value == "__INCLUDE_LEVEL__") { // expand the __INCLUDE_LEVEL__ macro char buffer[22]; // 21 bytes holds all NUL-terminated unsigned 64-bit numbers using namespace std; // for some systems sprintf is in namespace std sprintf(buffer, "%d", (int)ctx.get_iteration_depth()); expanded.push_back(token_type(T_INTLIT, buffer, curr_token.get_position())); return true; } return false; // no predefined token } /////////////////////////////////////////////////////////////////////////////// // // resolve_defined(): resolve the operator defined() and replace it with the // correct T_INTLIT token // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline typename ContextT::token_type const & macromap<ContextT>::resolve_defined(IteratorT &first, IteratorT const &last, ContainerT &pending) { using namespace boost::wave; using namespace boost::wave::grammars; ContainerT result; IteratorT start = first; boost::spirit::classic::parse_info<IteratorT> hit = defined_grammar_gen<typename ContextT::lexer_type>:: parse_operator_defined(start, last, result); if (!hit.hit) { string_type msg ("defined(): "); msg = msg + util::impl::as_string<string_type>(first, last); BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_expression, msg.c_str(), main_pos); // insert a dummy token pending.push_back(token_type(T_INTLIT, "0", main_pos)); } else { impl::assign_iterator<IteratorT>::do_(first, hit.stop); // insert a token, which reflects the outcome pending.push_back(token_type(T_INTLIT, is_defined(result.begin(), result.end()) ? "1" : "0", main_pos)); } on_exit::pop_front<definition_container_type> pop_front_token(pending); return act_token = pending.front(); } /////////////////////////////////////////////////////////////////////////////// // // resolve_operator_pragma(): resolve the operator _Pragma() and dispatch to // the associated action // // This function returns true, if the pragma was correctly interpreted. // The iterator 'first' is positioned behind the closing ')'. // This function returns false, if the _Pragma was not known, the // preprocessed token sequence is pushed back to the 'pending' sequence. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename IteratorT, typename ContainerT> inline bool macromap<ContextT>::resolve_operator_pragma(IteratorT &first, IteratorT const &last, ContainerT &pending, bool& seen_newline) { // isolate the parameter of the operator _Pragma token_type pragma_token = *first; if (!impl::skip_to_token(first, last, T_LEFTPAREN, seen_newline)) { // illformed operator _Pragma BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_expression, "operator _Pragma()", pragma_token.get_position()); return false; } std::vector<ContainerT> arguments; #if BOOST_WAVE_USE_DEPRECIATED_PREPROCESSING_HOOKS != 0 typename std::vector<ContainerT>::size_type count_args = collect_arguments (pragma_token, arguments, first, last, 1, seen_newline); #else IteratorT endparen = first; typename std::vector<ContainerT>::size_type count_args = collect_arguments (pragma_token, arguments, first, endparen, last, 1, seen_newline); #endif // verify the parameter count if (pragma_token.get_position().get_file().empty()) pragma_token.set_position(act_token.get_position()); if (count_args < 1 || arguments.size() < 1) { // too few macro arguments BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, too_few_macroarguments, pragma_token.get_value().c_str(), pragma_token.get_position()); return false; } if (count_args > 1 || arguments.size() > 1) { // too many macro arguments BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, too_many_macroarguments, pragma_token.get_value().c_str(), pragma_token.get_position()); return false; } // preprocess the pragma token body typedef typename std::vector<ContainerT>::value_type::iterator argument_iterator_type; ContainerT expanded; argument_iterator_type begin_it = arguments[0].begin(); argument_iterator_type end_it = arguments[0].end(); expand_whole_tokensequence(expanded, begin_it, end_it, false); // un-escape the parameter of the operator _Pragma typedef typename token_type::string_type string_type; string_type pragma_cmd; typename ContainerT::const_iterator end_exp = expanded.end(); for (typename ContainerT::const_iterator it_exp = expanded.begin(); it_exp != end_exp; ++it_exp) { if (T_EOF == token_id(*it_exp)) break; if (IS_CATEGORY(*it_exp, WhiteSpaceTokenType)) continue; if (T_STRINGLIT != token_id(*it_exp)) { // ill formed operator _Pragma BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_pragma_option, "_Pragma", pragma_token.get_position()); return false; } if (pragma_cmd.size() > 0) { // there should be exactly one string literal (string literals are to // be concatenated at translation phase 6, but _Pragma operators are // to be executed at translation phase 4) BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_pragma_option, "_Pragma", pragma_token.get_position()); return false; } // remove the '\"' and concat all given string literal-values string_type token_str = (*it_exp).get_value(); pragma_cmd += token_str.substr(1, token_str.size() - 2); } string_type pragma_cmd_unesc = impl::unescape_lit(pragma_cmd); // tokenize the pragma body typedef typename ContextT::lexer_type lexer_type; ContainerT pragma; std::string pragma_cmd_str(pragma_cmd_unesc.c_str()); lexer_type it = lexer_type(pragma_cmd_str.begin(), pragma_cmd_str.end(), pragma_token.get_position(), ctx.get_language()); lexer_type end = lexer_type(); for (/**/; it != end; ++it) pragma.push_back(*it); // analyze the preprocessed token sequence and eventually dispatch to the // associated action if (interpret_pragma(ctx, pragma_token, pragma.begin(), pragma.end(), pending)) { return true; // successfully recognized a wave specific pragma } // unknown pragma token sequence, push it back and return to the caller pending.push_front(token_type(T_SPACE, " ", pragma_token.get_position())); pending.push_front(token_type(T_RIGHTPAREN, ")", pragma_token.get_position())); pending.push_front(token_type(T_STRINGLIT, string_type("\"") + pragma_cmd + "\"", pragma_token.get_position())); pending.push_front(token_type(T_LEFTPAREN, "(", pragma_token.get_position())); pending.push_front(pragma_token); return false; } /////////////////////////////////////////////////////////////////////////////// // // Test, whether the result of a concat operator is well formed or not. // // This is done by re-scanning (re-tokenizing) the resulting token sequence, // which should give back exactly one token. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename ContainerT> inline bool macromap<ContextT>::is_valid_concat(string_type new_value, position_type const &pos, ContainerT &rescanned) { // re-tokenize the newly generated string typedef typename ContextT::lexer_type lexer_type; std::string value_to_test(new_value.c_str()); boost::wave::language_support lang = boost::wave::enable_prefer_pp_numbers(ctx.get_language()); lang = boost::wave::enable_single_line(lang); lexer_type it = lexer_type(value_to_test.begin(), value_to_test.end(), pos, lang); lexer_type end = lexer_type(); for (/**/; it != end && T_EOF != token_id(*it); ++it) rescanned.push_back(*it); #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (boost::wave::need_variadics(ctx.get_language())) return true; // in variadics mode token pasting is well defined #endif // test if the newly generated token sequence contains more than 1 token // the second one is the T_EOF token // BOOST_ASSERT(T_EOF == token_id(rescanned.back())); return 1 == rescanned.size(); } /////////////////////////////////////////////////////////////////////////////// // // Handle all occurrences of the concatenation operator '##' inside the given // token sequence. // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> template <typename ContainerT> inline bool macromap<ContextT>::concat_tokensequence(ContainerT &expanded) { using namespace boost::wave; typedef typename ContainerT::iterator iterator_type; iterator_type end = expanded.end(); iterator_type prev = end; for (iterator_type it = expanded.begin(); it != end; /**/) { if (T_POUND_POUND == BASE_TOKEN(token_id(*it))) { iterator_type next = it; ++next; if (prev == end || next == end) { // error, '##' should be in between two tokens BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_operator, "concat ('##')", main_pos); return false; } // replace prev##next with the concatenated value, skip whitespace // before and after the '##' operator while (IS_CATEGORY(*next, WhiteSpaceTokenType)) { ++next; if (next == end) { // error, '##' should be in between two tokens BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, ill_formed_operator, "concat ('##')", main_pos); return false; } } #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (boost::wave::need_variadics(ctx.get_language())) { if (T_PLACEMARKER == token_id(*next)) { // remove the '##' and the next tokens from the sequence iterator_type first_to_delete = prev; expanded.erase(++first_to_delete, ++next); it = next; continue; } else if (T_PLACEMARKER == token_id(*prev)) { // remove the '##' and the next tokens from the sequence iterator_type first_to_delete = prev; *prev = *next; expanded.erase(++first_to_delete, ++next); it = next; continue; } } #endif // BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 // test if the concat operator has to concatenate two unrelated // tokens i.e. the result yields more then one token string_type concat_result; ContainerT rescanned; concat_result = ((*prev).get_value() + (*next).get_value()); // analyze the validity of the concatenation result if (!is_valid_concat(concat_result, (*prev).get_position(), rescanned) && !IS_CATEGORY(*prev, WhiteSpaceTokenType) && !IS_CATEGORY(*next, WhiteSpaceTokenType)) { string_type error_string("\""); error_string += (*prev).get_value(); error_string += "\" and \""; error_string += (*next).get_value(); error_string += "\""; BOOST_WAVE_THROW_CTX(ctx, preprocess_exception, invalid_concat, error_string.c_str(), main_pos); return false; } #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (boost::wave::need_variadics(ctx.get_language())) { // remove the prev, '##' and the next tokens from the sequence expanded.erase(prev, ++next); // remove not needed tokens // some stl implementations clear() the container if we erased all // the elements, which orphans all iterators. we re-initialize these // here if (expanded.empty()) end = next = expanded.end(); // replace the old token (pointed to by *prev) with the re-tokenized // sequence expanded.splice(next, rescanned); // the last token of the inserted sequence is the new previous prev = next; if (next != expanded.end()) --prev; } else #endif // BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 { // we leave the token_id unchanged, but unmark the token as // disabled, if appropriate (*prev).set_value(concat_result); if (T_NONREPLACABLE_IDENTIFIER == token_id(*prev)) (*prev).set_token_id(T_IDENTIFIER); // remove the '##' and the next tokens from the sequence iterator_type first_to_delete = prev; expanded.erase(++first_to_delete, ++next); } it = next; continue; } // save last non-whitespace token position if (!IS_CATEGORY(*it, WhiteSpaceTokenType)) prev = it; ++it; // next token, please } return true; } /////////////////////////////////////////////////////////////////////////////// // // predefine_macro(): predefine a single macro // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline void macromap<ContextT>::predefine_macro(defined_macros_type *scope, string_type const &name, token_type const &t) { definition_container_type macrodefinition; std::vector<token_type> param; macrodefinition.push_back(t); add_macro(token_type(T_IDENTIFIER, name, t.get_position()), false, param, macrodefinition, true, scope); } /////////////////////////////////////////////////////////////////////////////// // // init_predefined_macros(): init the predefined macros // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline void macromap<ContextT>::init_predefined_macros(char const *fname, defined_macros_type *scope, bool at_global_scope) { // if no scope is given, use the current one defined_macros_type *current_scope = scope ? scope : current_macros; // first, add the static macros position_type pos("<built-in>"); #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 if (boost::wave::need_c99(ctx.get_language())) { // define C99 specifics for (int i = 0; 0 != predef.static_data_c99(i).name; ++i) { predefined_macros::static_macros const& m = predef.static_data_c99(i); predefine_macro(current_scope, m.name, token_type(m.token_id, m.value, pos)); } } else #endif { // define C++ specifics for (int i = 0; 0 != predef.static_data_cpp(i).name; ++i) { predefined_macros::static_macros const& m = predef.static_data_cpp(i); predefine_macro(current_scope, m.name, token_type(m.token_id, m.value, pos)); } #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 // define __WAVE_HAS_VARIADICS__, if appropriate if (boost::wave::need_variadics(ctx.get_language())) { predefine_macro(current_scope, "__WAVE_HAS_VARIADICS__", token_type(T_INTLIT, "1", pos)); } #endif } // predefine the __BASE_FILE__ macro which contains the main file name namespace fs = boost::filesystem; if (string_type(fname) != "<Unknown>") { fs::path filename(create_path(fname)); using boost::wave::util::impl::escape_lit; predefine_macro(current_scope, "__BASE_FILE__", token_type(T_STRINGLIT, string_type("\"") + escape_lit(native_file_string(filename)).c_str() + "\"", pos)); base_name = fname; } else if (!base_name.empty()) { fs::path filename(create_path(base_name.c_str())); using boost::wave::util::impl::escape_lit; predefine_macro(current_scope, "__BASE_FILE__", token_type(T_STRINGLIT, string_type("\"") + escape_lit(native_file_string(filename)).c_str() + "\"", pos)); } // now add the dynamic macros for (int j = 0; 0 != predef.dynamic_data(j).name; ++j) { predefined_macros::dynamic_macros const& m = predef.dynamic_data(j); predefine_macro(current_scope, m.name, token_type(m.token_id, (predef.* m.generator)(), pos)); } } /////////////////////////////////////////////////////////////////////////////// // // reset_macromap(): initialize the internal macro symbol namespace // /////////////////////////////////////////////////////////////////////////////// template <typename ContextT> inline void macromap<ContextT>::reset_macromap() { current_macros->clear(); predef.reset(); act_token = token_type(); } /////////////////////////////////////////////////////////////////////////////// }}} // namespace boost::wave::util #if BOOST_WAVE_SERIALIZATION != 0 namespace boost { namespace serialization { template<typename ContextT> struct version<boost::wave::util::macromap<ContextT> > { typedef boost::wave::util::macromap<ContextT> target_type; typedef mpl::int_<target_type::version> type; typedef mpl::integral_c_tag tag; BOOST_STATIC_CONSTANT(unsigned int, value = version::type::value); }; }} // namespace boost::serialization #endif // the suffix header occurs after all of the code #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // !defined(CPP_MACROMAP_HPP_CB8F51B0_A3F0_411C_AEF4_6FF631B8B414_INCLUDED)
[ [ [ 1, 1912 ] ] ]
6b80935a45c5d4d4a5d190bf8d9c8c77c2ae4fc5
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/core/thread/ThreadWorker.h
2a8fab13942be470a3ea96fbc96b6e63c99b8f62
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,751
h
/** * vim: set ts=4 : * ============================================================================= * SourceMod * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * 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/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #ifndef _INCLUDE_SOURCEMOD_THREADWORKER_H #define _INCLUDE_SOURCEMOD_THREADWORKER_H #include "BaseWorker.h" #define DEFAULT_THINK_TIME_MS 50 class ThreadWorker : public BaseWorker, public IThread { public: ThreadWorker(IThreadWorkerCallbacks *hooks); ThreadWorker(IThreadWorkerCallbacks *hooks, IThreader *pThreader, unsigned int thinktime=DEFAULT_THINK_TIME_MS); virtual ~ThreadWorker(); public: //IThread virtual void OnTerminate(IThreadHandle *pHandle, bool cancel); virtual void RunThread(IThreadHandle *pHandle); public: //IWorker //Controls the worker virtual bool Pause(); virtual bool Unpause(); virtual bool Start(); virtual bool Stop(bool flush_cancel); //returns status and number of threads in queue virtual WorkerState GetStatus(unsigned int *numThreads); public: //BaseWorker virtual void AddThreadToQueue(SWThreadHandle *pHandle); virtual SWThreadHandle *PopThreadFromQueue(); protected: IThreader *m_Threader; IMutex *m_QueueLock; IMutex *m_StateLock; IEventSignal *m_PauseSignal; IEventSignal *m_AddSignal; IThreadHandle *me; unsigned int m_think_time; volatile bool m_Waiting; volatile bool m_FlushType; }; #endif //_INCLUDE_SOURCEMOD_THREADWORKER_H
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 71 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ] ] ]
d717419845a584a728f197b6dbf259b05e84751b
028d6009f3beceba80316daa84b628496a210f8d
/uidesigner/com.nokia.sdt.series60.componentlibrary/templates/tutorials/YahooImageSearch/src/SearchResults.cpp
94e9a9ca6b8f426786e62812bc942dbf0c1f7cc3
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,226
cpp
/* ======================================================================== Name : SearchResults.cpp Description: 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 the License "Eclipse Public License v1.0" which accompanies this distribution, and is available at the URL "http://www.eclipse.org/legal/epl-v10.html". Contributors: Nokia Corporation - initial contribution. ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] #include <barsread.h> #include <stringloader.h> #include <aknlists.h> #include <eikenv.h> #include <akniconarray.h> #include <eikclbd.h> #include <aknviewappui.h> #include <eikappui.h> #include <$(baseName).rsg> #include <$(baseName)_mbm.mbg> // ]]] end generated region [Generated System Includes] // [[[ begin generated region: do not modify [Generated User Includes] #include "SearchResults.h" #include "$(baseName).hrh" #include "SearchResults.hrh" // ]]] end generated region [Generated User Includes] #include "SearchResultsView.h" // [[[ begin generated region: do not modify [Generated Constants] _LIT( K$(baseName$titlelower)_mbmFile, "\\resource\\apps\\$(baseName)_mbm.mbm" ); // ]]] end generated region [Generated Constants] /** * First phase of Symbian two-phase construction. Should not * contain any code that could leave. */ CSearchResults::CSearchResults() { // [[[ begin generated region: do not modify [Generated Contents] iListBox = NULL; // ]]] end generated region [Generated Contents] } /** * Destroy child controls. */ CSearchResults::~CSearchResults() { // [[[ begin generated region: do not modify [Generated Contents] delete iListBox; iListBoxEventDispatch.Close(); // ]]] end generated region [Generated Contents] } /** * Construct the control (first phase). * Creates an instance and initializes it. * Instance is not left on cleanup stack. * @param aRect bounding rectangle * @param aParent owning parent, or NULL * @param aCommandObserver command observer * @return initialized instance of CSearchResults */ CSearchResults* CSearchResults::NewL( const TRect& aRect, const CCoeControl* aParent, MEikCommandObserver* aCommandObserver ) { CSearchResults* self = CSearchResults::NewLC( aRect, aParent, aCommandObserver ); CleanupStack::Pop( self ); return self; } /** * Construct the control (first phase). * Creates an instance and initializes it. * Instance is left on cleanup stack. * @param aRect The rectangle for this window * @param aParent owning parent, or NULL * @param aCommandObserver command observer * @return new instance of CSearchResults */ CSearchResults* CSearchResults::NewLC( const TRect& aRect, const CCoeControl* aParent, MEikCommandObserver* aCommandObserver ) { CSearchResults* self = new (ELeave) CSearchResults(); CleanupStack::PushL( self ); self->ConstructL( aRect, aParent, aCommandObserver ); return self; } /** * Construct the control (second phase). * Creates a window to contain the controls and activates it. * @param aRect bounding rectangle * @param aCommandObserver command observer * @param aParent owning parent, or NULL */ void CSearchResults::ConstructL( const TRect& aRect, const CCoeControl* aParent, MEikCommandObserver* aCommandObserver ) { if ( !aParent ) { CreateWindowL(); } else { SetContainerWindowL( *aParent ); } iFocusControl = NULL; iCommandObserver = aCommandObserver; InitializeControlsL(); HBufC *prompt = StringLoader::LoadLC(R_SEARCH_LIST_EMPTY_PROMPT); iListBox->View()->SetListEmptyTextL(*prompt); CleanupStack::PopAndDestroy(prompt); SetRect( aRect ); ActivateL(); // [[[ begin generated region: do not modify [Post-ActivateL initializations] // ]]] end generated region [Post-ActivateL initializations] } /** * Return the number of controls in the container (override) * @return count */ TInt CSearchResults::CountComponentControls() const { return (int) ELastControl; } /** * Get the control with the given index (override) * @param aIndex Control index [0...n) (limited by #CountComponentControls) * @return Pointer to control */ CCoeControl* CSearchResults::ComponentControl( TInt aIndex ) const { // [[[ begin generated region: do not modify [Generated Contents] switch ( aIndex ) { case EListBox: return iListBox; } // ]]] end generated region [Generated Contents] // handle any user controls here... return NULL; } /** * Handle resizing of the container. This implementation will lay out * full-sized controls like list boxes for any screen size, and will layout * labels, editors, etc. to the size they were given in the UI designer. * This code will need to be modified to adjust arbitrary controls to * any screen size. */ void CSearchResults::SizeChanged() { CCoeControl::SizeChanged(); LayoutControls(); // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } // [[[ begin generated function: do not modify /** * Layout components as specified in the UI Designer */ void CSearchResults::LayoutControls() { iListBox->SetExtent( TPoint( 0, 0 ), iListBox->MinimumSize() ); } // ]]] end generated function /** * Handle key events. */ TKeyResponse CSearchResults::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ) { // [[[ begin generated region: do not modify [Generated Contents] if ( ( aKeyEvent.iCode == EKeyLeftArrow ) || ( aKeyEvent.iCode == EKeyRightArrow ) ) { // Listbox takes all events even if it doesn't use them return EKeyWasNotConsumed; } // ]]] end generated region [Generated Contents] if ( iFocusControl && iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed ) return EKeyWasConsumed; return CCoeControl::OfferKeyEventL( aKeyEvent, aType ); } // [[[ begin generated function: do not modify /** * Initialize each control upon creation. */ void CSearchResults::InitializeControlsL() { iListBox = new (ELeave) CAknDoubleStyleListBox; iListBox->SetContainerWindowL( *this ); { TResourceReader reader; iEikonEnv->CreateResourceReaderLC( reader, R_SEARCH_RESULTS_LIST_BOX ); iListBox->ConstructFromResourceL( reader ); CleanupStack::PopAndDestroy(); // reader internal state } // the listbox owns the items in the list and will free them iListBox->Model()->SetOwnershipType( ELbmOwnsItemArray ); // setup the icon array so graphics-style boxes work SetupListBoxIconsL(); iListBox->SetListBoxObserver( this ); AddListBoxEventHandlerL( iListBox, EEventEnterKeyPressed, &CSearchResults::HandleListBoxEnterKeyPressedL ); // add list items iListBox->SetFocus( ETrue ); iFocusControl = iListBox; } // ]]] end generated function /** * Handle global resource changes, such as scalable UI or skin events (override) */ void CSearchResults::HandleResourceChange( TInt aType ) { CCoeControl::HandleResourceChange( aType ); SetRect( iAvkonViewAppUi->View( TUid::Uid( ESearchResultsViewId ) )->ClientRect() ); // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } /** * Draw container contents. */ void CSearchResults::Draw( const TRect& aRect ) const { // [[[ begin generated region: do not modify [Generated Contents] CWindowGc& gc = SystemGc(); gc.Clear( aRect ); // ]]] end generated region [Generated Contents] } /** * Add a list box item to a list. */ void CSearchResults::AddListBoxItemL( CEikTextListBox* aListBox, const TDesC& aString ) { CTextListBoxModel* model = aListBox->Model(); CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() ); itemArray->AppendL( aString ); aListBox->HandleItemAdditionL(); } void CSearchResults::ResetListL() { CTextListBoxModel* model = iListBox->Model(); CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() ); itemArray->Reset(); iListBox->HandleItemRemovalL(); } /** * Get the array of selected item indices, with respect to the list model. * The array is sorted in ascending order. * The array should be destroyed with two calls to CleanupStack::PopAndDestroy(), * the first with no argument (referring to the internal resource) and the * second with the array pointer. * @return newly allocated array, which is left on the cleanup stack; * or NULL for empty list. */ RArray< TInt >* CSearchResults::GetSelectedListBoxItemsLC( CEikTextListBox* aListBox ) { CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() ); if ( model->NumberOfItems() == 0 ) return NULL; // get currently selected indices const CListBoxView::CSelectionIndexArray* selectionIndexes = aListBox->SelectionIndexes(); TInt selectedIndexesCount = selectionIndexes->Count(); if ( selectedIndexesCount == 0 ) return NULL; // copy the indices and sort numerically RArray<TInt>* orderedSelectedIndices = new (ELeave) RArray< TInt >( selectedIndexesCount ); // push the allocated array CleanupStack::PushL( orderedSelectedIndices ); // dispose the array resource CleanupClosePushL( *orderedSelectedIndices ); // see if the search field is enabled CAknListBoxFilterItems* filter = model->Filter(); if ( filter != NULL ) { // when filtering enabled, translate indices back to underlying model for ( TInt idx = 0; idx < selectedIndexesCount; idx++ ) { TInt filteredItem = ( *selectionIndexes ) [ idx ]; TInt actualItem = filter->FilteredItemIndex ( filteredItem ); orderedSelectedIndices->InsertInOrder( actualItem ); } } else { // the selection indices refer directly to the model for ( TInt idx = 0; idx < selectedIndexesCount; idx++ ) orderedSelectedIndices->InsertInOrder( ( *selectionIndexes ) [ idx ] ); } return orderedSelectedIndices; } /** * Delete the selected item or items from the list box. */ void CSearchResults::DeleteSelectedListBoxItemsL( CEikTextListBox* aListBox ) { CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() ); if ( model->NumberOfItems() == 0 ) return; RArray< TInt >* orderedSelectedIndices = GetSelectedListBoxItemsLC( aListBox ); if ( !orderedSelectedIndices ) return; // Delete selected items from bottom up so indices don't change on us CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() ); TInt currentItem = 0; for ( TInt idx = orderedSelectedIndices->Count(); idx-- > 0; ) { currentItem = ( *orderedSelectedIndices )[ idx ]; itemArray->Delete ( currentItem ); } // dispose the array resources CleanupStack::PopAndDestroy(); // dispose the array pointer CleanupStack::PopAndDestroy( orderedSelectedIndices ); // refresh listbox's cursor now that items are deleted AknListBoxUtils::HandleItemRemovalAndPositionHighlightL( aListBox, currentItem, ETrue ); } // [[[ begin generated function: do not modify /** * Get the listbox. */ CAknDoubleStyleListBox* CSearchResults::ListBox() { return iListBox; } // ]]] end generated function // [[[ begin generated function: do not modify /** * Create a list box item with the given column values. */ void CSearchResults::CreateListBoxItemL( TDes& aBuffer, const TDesC& aMainText, const TDesC& aSecondaryText ) { _LIT ( KStringHeader, "\t%S\t%S" ); aBuffer.Format( KStringHeader(), &aMainText, &aSecondaryText ); } // ]]] end generated function // [[[ begin generated function: do not modify /** * Add an item to the list by reading the text items from the array resource * and setting a single image property (if available) from an index * in the list box's icon array. * @param aResourceId id of an ARRAY resource containing the textual * items in the columns * */ void CSearchResults::AddListBoxResourceArrayItemL( TInt aResourceId ) { CDesCArray* array = iCoeEnv->ReadDesCArrayResourceL( aResourceId ); CleanupStack::PushL( array ); // This is intended to be large enough, but if you get // a USER 11 panic, consider reducing string sizes. TBuf<512> listString; CreateListBoxItemL( listString, ( *array ) [ 0 ], ( *array ) [ 1 ] ); AddListBoxItemL( iListBox, listString ); CleanupStack::PopAndDestroy( array ); } // ]]] end generated function /** * Set up the list's icon array. This should be called before * activating the container. */ void CSearchResults::SetupListBoxIconsL() { CArrayPtr< CGulIcon >* icons = NULL; icons = new (ELeave) CAknIconArray( 1 ); CleanupStack::PushL( icons ); CGulIcon* icon; // for EListBox$(baseName$titlelower)_mbmList_iconIndex icon = LoadAndScaleIconL( K$(baseName$titlelower)_mbmFile, EMbm$(baseName$titlelower)_mbmList_icon, EMbm$(baseName$titlelower)_mbmList_icon_mask, NULL, EAspectRatioPreserved ); CleanupStack::PushL( icon ); icons->AppendL( icon ); CleanupStack::Pop( icon ); CleanupStack::Pop( icons ); if ( icons != NULL ) { iListBox->ItemDrawer()->ColumnData()->SetIconArray( icons ); } } /** * Handle commands relating to markable lists. */ TBool CSearchResults::HandleMarkableListCommandL( TInt aCommand ) { return EFalse; } // [[[ begin generated function: do not modify /** * This routine loads and scales a bitmap or icon. * * @param aFileName the MBM or MIF filename * @param aBitmapId the bitmap id * @param aMaskId the mask id or -1 for none * @param aSize the TSize for the icon, or NULL to use real size * @param aScaleMode one of the EAspectRatio* enums when scaling * */ CGulIcon* CSearchResults::LoadAndScaleIconL( const TDesC& aFileName, TInt aBitmapId, TInt aMaskId, TSize* aSize, TScaleMode aScaleMode ) { CFbsBitmap *bitmap, *mask; AknIconUtils::CreateIconL( bitmap, mask, aFileName, aBitmapId, aMaskId ); TSize size; if ( !aSize ) { // Use size from the image header. In case of SVG, // we preserve the image data for a while longer, since ordinarily // it is disposed at the first GetContentDimensions() or SetSize() call. AknIconUtils::PreserveIconData( bitmap ); AknIconUtils::GetContentDimensions( bitmap, size ); } else size = *aSize; AknIconUtils::SetSize( bitmap, size, aScaleMode ); AknIconUtils::SetSize( mask, size, aScaleMode ); if ( !aSize ) AknIconUtils::DestroyIconData( bitmap ); return CGulIcon::NewL( bitmap, mask ); } // ]]] end generated function /** * Override of the HandleListBoxEventL virtual function */ void CSearchResults::HandleListBoxEventL( CEikListBox *aListBox, TListBoxEvent anEventType ) { for (int i = 0; i < iListBoxEventDispatch.Count(); i++) { const TListBoxEventDispatch& currEntry = iListBoxEventDispatch[i]; if (currEntry.src == aListBox && currEntry.event == anEventType) { (this->*currEntry.handler)( aListBox, anEventType ); break; } } } /** * Helper function to register MEikListBoxObserver event handlers */ void CSearchResults::AddListBoxEventHandlerL( CEikListBox *aListBox, TListBoxEvent anEvent, ListBoxEventHandler aHandler ) { TListBoxEventDispatch entry; entry.src = aListBox; entry.event = anEvent; entry.handler = aHandler; iListBoxEventDispatch.AppendL( entry ); } /** * Handle the EEventEnterKeyPressed event. */ void CSearchResults::HandleListBoxEnterKeyPressedL( CEikListBox* /* aListBox */, TListBoxEvent /* anEventType */ ) { CSearchResultsView *view = static_cast<CSearchResultsView*>(iCommandObserver); view->ShowSelectedImageL(); }
[ [ [ 1, 535 ] ] ]
f1131d2c3486fc443e61b4359d60ab1ed2c877b2
38763b01d06c87ff1164877f57fc22d0da2927e4
/src/imageb_player/DB25PP.h
aba23e4a2681a664b61f16d9c12140e717f72d61
[]
no_license
JPSGoncalves/ImageB
48b31b83bb1c032394c14e1df5ed90e2a285a521
135ccb9847f9e3394f2391417885d753a5b3a930
refs/heads/master
2023-03-17T03:57:10.299812
2011-07-20T16:59:41
2011-07-20T16:59:41
null
0
0
null
null
null
null
IBM852
C++
false
false
1,561
h
#ifndef DB25PORT_H #define DB25PORT_H #include <QLibrary> #include <iostream> #include <windows.h> #include <time.h> /* Definitions in the build of inpout32.dll are: */ /* short _stdcall Inp32(short PortAddress); */ /* void _stdcall Out32(short PortAddress, short data); */ /* prototype (function typedef) for DLL function Inp32: */ typedef short _stdcall (*inpfuncPtr)(short portaddr); typedef void _stdcall (*oupfuncPtr)(short portaddr, short datum); //typedef void (*oupfuncPtr)(short,short); //typedef short (*inpfuncPtr)(short portaddr); using namespace std; class DB25PP: public QObject { Q_OBJECT public: DB25PP(); virtual ~DB25PP(); void clear(); //seta todos os bits para zero void reset(); //seta o bit 8 void nextBit(); //vai para o proximo bit void firstBit();//vai para o primeiro bit void lastBit(); //vai para o ultimo bit void nextChannel(); int read(); void write(int); void writeBit(int); void setBit(int,bool); //seta um bit para ativo/inativo private: QLibrary *lib; inpfuncPtr inp32; oupfuncPtr oup32; int rst_bit; //indicacao de bit de reset int act_bit; //indicacao de bit efetivo (envia dado ao multiplex) int pport_addr; //enderešo da paralela 0x378 int curr_bit; //bit corrente int bit[8]; int sleep_time; void sleep(unsigned int mseconds); }; #endif
[ [ [ 1, 66 ] ] ]
6880ad276b21a5eb6947fb53e8866623047aed87
8ecc762aa0716342b64f8f60664659a2f1dd19aa
/third_party/boost/sandbox/boost/property_tree/detail/ptree_implementation.hpp
69e5ea48c8fd92921b69ce56220931511a9e8dc1
[ "MIT", "BSL-1.0" ]
permissive
gbucknell/fsc-sdk
71993dcf48c6f8dbb6379c929e22a7ecb2d41503
11b7cda4eea35ec53effbe37382f4b28020cd59d
refs/heads/master
2021-01-10T11:16:58.310281
2009-01-23T16:31:12
2009-01-23T16:31:12
54,295,008
0
0
null
null
null
null
UTF-8
C++
false
false
22,838
hpp
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef BOOST_PROPERTY_TREE_DETAIL_PTREE_IMPLEMENTATION_HPP_INCLUDED #define BOOST_PROPERTY_TREE_DETAIL_PTREE_IMPLEMENTATION_HPP_INCLUDED ////////////////////////////////////////////////////////////////////////////// // Debug macros #ifdef BOOST_PROPERTY_TREE_DEBUG // Increment instances counter #define BOOST_PROPERTY_TREE_DEBUG_INCREMENT_INSTANCES_COUNT() \ { \ typedef boost::detail::lightweight_mutex::scoped_lock lock; \ lock l(debug_mutex); \ ++debug_instances_count; \ } // Decrement instances counter #define BOOST_PROPERTY_TREE_DEBUG_DECREMENT_INSTANCES_COUNT() \ { \ typedef boost::detail::lightweight_mutex::scoped_lock lock; \ lock l(debug_mutex); \ BOOST_ASSERT(debug_instances_count > 0); \ --debug_instances_count; \ } #else // BOOST_PROPERTY_TREE_DEBUG #define BOOST_PROPERTY_TREE_DEBUG_INCREMENT_INSTANCES_COUNT() static_cast<void>(0) #define BOOST_PROPERTY_TREE_DEBUG_DECREMENT_INSTANCES_COUNT() static_cast<void>(0) #endif // BOOST_PROPERTY_TREE_DEBUG namespace boost { namespace property_tree { /////////////////////////////////////////////////////////////////////////// // Construction & destruction template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X>::basic_ptree() { BOOST_PROPERTY_TREE_DEBUG_INCREMENT_INSTANCES_COUNT(); } template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X>::basic_ptree(const data_type &rhs): m_data(rhs) { BOOST_PROPERTY_TREE_DEBUG_INCREMENT_INSTANCES_COUNT(); } template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X>::basic_ptree(const basic_ptree<C, K, P, D, X> &rhs) { m_data = rhs.m_data; insert(end(), rhs.begin(), rhs.end()); BOOST_PROPERTY_TREE_DEBUG_INCREMENT_INSTANCES_COUNT(); } template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X>::~basic_ptree() { BOOST_PROPERTY_TREE_DEBUG_DECREMENT_INSTANCES_COUNT(); } /////////////////////////////////////////////////////////////////////////// // Iterator access template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::begin() { return m_container.begin(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::const_iterator basic_ptree<C, K, P, D, X>::begin() const { return m_container.begin(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::end() { return m_container.end(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::const_iterator basic_ptree<C, K, P, D, X>::end() const { return m_container.end(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::reverse_iterator basic_ptree<C, K, P, D, X>::rbegin() { return m_container.rbegin(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::const_reverse_iterator basic_ptree<C, K, P, D, X>::rbegin() const { return m_container.rbegin(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::reverse_iterator basic_ptree<C, K, P, D, X>::rend() { return m_container.rend(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::const_reverse_iterator basic_ptree<C, K, P, D, X>::rend() const { return m_container.rend(); } /////////////////////////////////////////////////////////////////////////// // Data access template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::size_type basic_ptree<C, K, P, D, X>::size() const { return m_container.size(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::size_type basic_ptree<C, K, P, D, X>::max_size() const { return m_container.max_size(); } template<class C, class K, class P, class D, class X> bool basic_ptree<C, K, P, D, X>::empty() const { return m_container.empty(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::data_type & basic_ptree<C, K, P, D, X>::data() { return m_data; } template<class C, class K, class P, class D, class X> const typename basic_ptree<C, K, P, D, X>::data_type & basic_ptree<C, K, P, D, X>::data() const { return m_data; } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::value_type & basic_ptree<C, K, P, D, X>::front() { return m_container.front(); } template<class C, class K, class P, class D, class X> const typename basic_ptree<C, K, P, D, X>::value_type & basic_ptree<C, K, P, D, X>::front() const { return m_container.front(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::value_type & basic_ptree<C, K, P, D, X>::back() { return m_container.back(); } template<class C, class K, class P, class D, class X> const typename basic_ptree<C, K, P, D, X>::value_type & basic_ptree<C, K, P, D, X>::back() const { return m_container.back(); } /////////////////////////////////////////////////////////////////////////// // Operators template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::operator =(const basic_ptree<C, K, P, D, X> &rhs) { if (&rhs != this) { clear(); data() = rhs.data(); insert(end(), rhs.begin(), rhs.end()); } return *this; } template<class C, class K, class P, class D, class X> bool basic_ptree<C, K, P, D, X>::operator ==(const basic_ptree<C, K, P, D, X> &rhs) const { // Data and sizes must be equal if (size() != rhs.size() || data() != rhs.data()) return false; // Keys and children must be equal C comp; const_iterator it = begin(); const_iterator it_rhs = rhs.begin(); const_iterator it_end = end(); for (; it != it_end; ++it, ++it_rhs) if (comp(it->first, it_rhs->first) || comp(it_rhs->first, it->first) || it->second != it_rhs->second) { return false; } // Equal return true; } template<class C, class K, class P, class D, class X> bool basic_ptree<C, K, P, D, X>::operator !=(const basic_ptree<C, K, P, D, X> &rhs) const { return !operator ==(rhs); } /////////////////////////////////////////////////////////////////////////// // Container operations template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::find(const key_type &key) { C comp; for (iterator it = begin(); it != end(); ++it) if (!comp(it->first, key) && !comp(key, it->first)) return it; return end(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::const_iterator basic_ptree<C, K, P, D, X>::find(const key_type &key) const { C comp; for (const_iterator it = begin(); it != end(); ++it) if (!comp(it->first, key) && !comp(key, it->first)) return it; return end(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::size_type basic_ptree<C, K, P, D, X>::count(const key_type &key) const { C comp; size_type count = 0; for (const_iterator it = begin(); it != end(); ++it) if (!comp(it->first, key) && !comp(key, it->first)) ++count; return count; } template<class C, class K, class P, class D, class X> void basic_ptree<C, K, P, D, X>::clear() { m_data = data_type(); m_container.clear(); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::insert(iterator where, const value_type &value) { return m_container.insert(where, value); } template<class C, class K, class P, class D, class X> template<class It> void basic_ptree<C, K, P, D, X>::insert(iterator where, It first, It last) { for (; first != last; ++first, ++where) where = insert(where, value_type(first->first, first->second)); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::erase(iterator where) { return m_container.erase(where); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::size_type basic_ptree<C, K, P, D, X>::erase(const key_type &key) { C comp; size_type count = 0; iterator it = m_container.begin(); while (it != m_container.end()) { if (!comp(it->first, key) && !comp(key, it->first)) { it = erase(it); ++count; } else ++it; } return count; } template<class C, class K, class P, class D, class X> template<class It> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::erase(It first, It last) { while (first != last) first = erase(first); return first; } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::push_front(const value_type &value) { return insert(begin(), value); } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::iterator basic_ptree<C, K, P, D, X>::push_back(const value_type &value) { return insert(end(), value); } template<class C, class K, class P, class D, class X> void basic_ptree<C, K, P, D, X>::pop_front() { erase(begin()); } template<class C, class K, class P, class D, class X> void basic_ptree<C, K, P, D, X>::pop_back() { iterator last = end(); --last; erase(last); } template<class C, class K, class P, class D, class X> void basic_ptree<C, K, P, D, X>::swap(basic_ptree<C, K, P, D, X> &rhs) { m_data.swap(rhs.m_data); m_container.swap(rhs.m_container); } template<class C, class K, class P, class D, class X> void basic_ptree<C, K, P, D, X>::reverse() { m_container.reverse(); } template<class C, class K, class P, class D, class X> template<class SortTr> void basic_ptree<C, K, P, D, X>::sort(SortTr tr) { m_container.sort(tr); } /////////////////////////////////////////////////////////////////////////// // ptree operations // Get child ptree template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::get_child(const path_type &path) { self_type *child = path.get_child(*this); if (child) return *child; else BOOST_PROPERTY_TREE_THROW(ptree_bad_path("path does not exist", path)); } // Get child ptree template<class C, class K, class P, class D, class X> const basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::get_child(const path_type &path) const { self_type *nc_this = const_cast<self_type *>(this); return nc_this->get_child(path); } // Get child ptree template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::get_child(const path_type &path, basic_ptree<C, K, P, D, X> &default_value) { self_type *child = path.get_child(*this); if (child) return *child; else return default_value; } // Get child ptree template<class C, class K, class P, class D, class X> const basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::get_child(const path_type &path, const basic_ptree<C, K, P, D, X> &default_value) const { self_type *nc_this = const_cast<self_type *>(this); self_type &nc_default_value = const_cast<self_type &>(default_value); return nc_this->get_child(path, nc_default_value); } // Get child ptree template<class C, class K, class P, class D, class X> optional<basic_ptree<C, K, P, D, X> &> basic_ptree<C, K, P, D, X>::get_child_optional(const path_type &path) { self_type *child = path.get_child(*this); if (child) return optional<self_type &>(*child); else return optional<self_type &>(); } // Get child ptree template<class C, class K, class P, class D, class X> optional<const basic_ptree<C, K, P, D, X> &> basic_ptree<C, K, P, D, X>::get_child_optional(const path_type &path) const { self_type *nc_this = const_cast<self_type *>(this); optional<self_type &> tmp = nc_this->get_child_optional(path); if (tmp) return optional<const self_type &>(tmp.get()); else return optional<const self_type &>(); } // Put child ptree template<class C, class K, class P, class D, class X> basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::put_child(const path_type &path, const basic_ptree<C, K, P, D, X> &value, bool do_not_replace) { self_type *child = path.put_child(*this, value, do_not_replace); if (child) return *child; else BOOST_PROPERTY_TREE_THROW(ptree_bad_path("path does not exist", path)); } // Get value from data of ptree template<class C, class K, class P, class D, class X> template<class Type> Type basic_ptree<C, K, P, D, X>::get_value(const translator_type &x) const { BOOST_STATIC_ASSERT(boost::is_pointer<Type>::value == false); // Disallow pointer types, they are unsafe Type value; if (x.get_value(*this, value)) return value; else BOOST_PROPERTY_TREE_THROW(ptree_bad_data(std::string("conversion of data into type \"") + typeid(Type).name() + "\" failed", data())); } // Get value from data of ptree template<class C, class K, class P, class D, class X> template<class Type> Type basic_ptree<C, K, P, D, X>::get_value(const Type &default_value, const translator_type &x) const { BOOST_STATIC_ASSERT(boost::is_pointer<Type>::value == false); // Disallow pointer types, they are unsafe Type value; if (x.get_value(*this, value)) return value; else return default_value; } // Get value from data of ptree template<class C, class K, class P, class D, class X> template<class CharType> std::basic_string<CharType> basic_ptree<C, K, P, D, X>::get_value(const CharType *default_value, const translator_type &x) const { return get_value(std::basic_string<CharType>(default_value), x); } // Get value from data of ptree template<class C, class K, class P, class D, class X> template<class Type> optional<Type> basic_ptree<C, K, P, D, X>::get_value_optional(const translator_type &x) const { BOOST_STATIC_ASSERT(boost::is_pointer<Type>::value == false); // Disallow pointer types, they are unsafe Type value; if (x.get_value(*this, value)) return optional<Type>(value); else return optional<Type>(); } // Get value from data of child ptree template<class C, class K, class P, class D, class X> template<class Type> Type basic_ptree<C, K, P, D, X>::get(const path_type &path, const translator_type &x) const { return get_child(path).get_value<Type>(x); } // Get value from data of child ptree template<class C, class K, class P, class D, class X> template<class Type> Type basic_ptree<C, K, P, D, X>::get(const path_type &path, const Type &default_value, const translator_type &x) const { if (optional<Type> result = get_optional<Type>(path, x)) return *result; else return default_value; } // Get value from data of child ptree template<class C, class K, class P, class D, class X> template<class CharType> std::basic_string<CharType> basic_ptree<C, K, P, D, X>::get(const path_type &path, const CharType *default_value, const translator_type &x) const { return get(path, std::basic_string<CharType>(default_value), x); } // Get value from data of child ptree template<class C, class K, class P, class D, class X> template<class Type> optional<Type> basic_ptree<C, K, P, D, X>::get_optional(const path_type &path, const translator_type &x) const { if (optional<const basic_ptree<C, K, P, D, X> &> child = get_child_optional(path)) return child.get().get_value_optional<Type>(x); else return optional<Type>(); } // Put value in data of ptree template<class C, class K, class P, class D, class X> template<class Type> void basic_ptree<C, K, P, D, X>::put_value(const Type &value, const translator_type &x) { if (!x.put_value(*this, value)) BOOST_PROPERTY_TREE_THROW(ptree_bad_data(std::string("conversion of type \"") + typeid(Type).name() + "\" into data failed", boost::any())); } // Put value in data of child ptree template<class C, class K, class P, class D, class X> template<class Type> basic_ptree<C, K, P, D, X> & basic_ptree<C, K, P, D, X>::put(const path_type &path, const Type &value, bool do_not_replace, const translator_type &x) { optional<self_type &> child; if (!do_not_replace && (child = get_child_optional(path))) { child.get().put_value(value, x); return *child; } else { self_type &child2 = put_child(path, empty_ptree<self_type>(), do_not_replace); child2.put_value(value, x); return child2; } } //////////////////////////////////////////////////////////////////////////// // Debugging #ifdef BOOST_PROPERTY_TREE_DEBUG template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::size_type basic_ptree<C, K, P, D, X>::debug_get_instances_count() { empty_ptree<basic_ptree<C, K, P, D, X> >(); // Make sure empty ptree exists return debug_instances_count - 1; // Do not count empty ptree } template<class C, class K, class P, class D, class X> typename basic_ptree<C, K, P, D, X>::size_type basic_ptree<C, K, P, D, X>::debug_instances_count; template<class C, class K, class P, class D, class X> boost::detail::lightweight_mutex basic_ptree<C, K, P, D, X>::debug_mutex; #endif /////////////////////////////////////////////////////////////////////////// // Free functions template<class Ptree> inline const Ptree &empty_ptree() { static Ptree pt; return pt; } template<class C, class K, class P, class D, class X> inline void swap(basic_ptree<C, K, P, D, X> &pt1, basic_ptree<C, K, P, D, X> &pt2) { pt1.swap(pt2); } } } // Undefine debug macros #ifdef BOOST_PROPERTY_TREE_DEBUG # undef BOOST_PROPERTY_TREE_DEBUG_INCREMENT_INSTANCES_COUNT # undef BOOST_PROPERTY_TREE_DEBUG_DECREMENT_INSTANCES_COUNT #endif #endif
[ "samuel.debionne@8ae27fb2-a4e6-11dd-9bad-6bc74a82fd44" ]
[ [ [ 1, 658 ] ] ]
c1cbc792ded7fb6e995a23eb57af3d1efbfd957e
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizer/ExpLockIn.h
fe72d6e1eb5cc2a7df7922c1a060230ecfdf0d6f
[ "LicenseRef-scancode-public-domain" ]
permissive
nist-ionstorage/ionizer
f42706207c4fb962061796dbbc1afbff19026e09
70b52abfdee19e3fb7acdf6b4709deea29d25b15
refs/heads/master
2021-01-16T21:45:36.502297
2010-05-14T01:05:09
2010-05-14T01:05:09
20,006,050
5
0
null
null
null
null
UTF-8
C++
false
false
2,811
h
#pragma once #include "InputParametersGUI.h" #include "ScanObject.h" /* general lock in servo */ /* template<class T> class ExpLockIn : public T, public LockInParams { public: ExpLockIn(const std::string& sPageName, ExperimentsSheet* pSheet, unsigned exp_id, const std::string& unit, const std::string& lock_variable_name) : T(sPageName, pSheet, exp_id), Modulation ("Modulation " + unit, T::GetTxtParams(), "0", T::GetParamsVector()), Gain ("Gain", T::GetTxtParams(), "0", T::GetParamsVector()), Center ("Lock-in center " + unit, T::GetTxtParams(), "0", T::GetParamsVector(), true), RunModulo ("Run modulo", T::GetTxtParams(), "1", T::GetParamsVector()), unit(unit), lock_variable_name(lock_variable_name) { Center.setPrecision(6); } virtual ~ExpLockIn() {} virtual ScanSource* getLockVariable() { return T::currentScanSource(); } virtual void InitializeScan() { RecalculateModulation(); Center.SetValue(GetInitialCenter()); T::InitializeScan(); } virtual void DefaultExperimentState() { T::DefaultExperimentState(); getLockVariable()->setDefaultValue(); } virtual bool RecalculateModulation() { return false; } virtual void AddDataChannels(DataFeed& data_feed) { T::AddDataChannels(data_feed); if(T::pSignalChannel) T::pSignalChannel->SetPlot(!scans::IsLockInScan(T::ScanType)); } protected: // enum direction {LEFT, CENTER, RIGHT}; //LockInParams overrides virtual void modulateOutput(double d) { SetOutput(GetCenter()+d); } virtual void SetOutput(double d) { return getLockVariable()->SetScanOutput(d); } virtual double GetOutput() { return getLockVariable()->getNonScanningValue(); } virtual double GetModulation() { return Modulation; } virtual void ShiftCenter(double d) { SetCenter(GetCenter()+d); } virtual void SetCenter(double d) { return getLockVariable()->setNonScanningValue(d); Center.SetValue(d); Center.PostUpdateGUI(); } virtual double GetCenter() { return getLockVariable()->getNonScanningValue(); } virtual double GetGain() { return Gain; } virtual double GetSignal() { return T::pSignalChannel->GetAverage(); } virtual std::string GetLockVariableName() { return lock_variable_name; } virtual int GetRunModulo() { return RunModulo.Value(); } virtual void SetRunModulo(int rm) { RunModulo.SetValue(rm); } virtual double GetInitialCenter() { return GetCenter(); } protected: GUI_double Modulation; GUI_double Gain; GUI_double Center; GUI_int RunModulo; protected: const std::string unit; const std::string lock_variable_name; }; */
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 83 ] ] ]
da86d423e10938db58f7810ecc7b6ef4dbdd43c4
8b68ff41fd39c9cf20d27922bb9f8b9d2a1c68e9
/TWL/capbtn/CaptionButton/tme.cpp
1d47b38205378bb136e60e93a52490f3f7c816d0
[]
no_license
dandycheung/dandy-twl
2ec6d500273b3cb7dd6ab9e5a3412740d73219ae
991220b02f31e4ec82760ece9cd974103c7f9213
refs/heads/master
2020-12-24T15:06:06.260650
2009-05-20T14:46:07
2009-05-20T14:46:07
32,625,192
0
0
null
null
null
null
UTF-8
C++
false
false
8,618
cpp
#include <windows.h> #include "tme.h" #define SetSystemTimer SetTimer #define KillSystemTimer KillTimer #ifndef VK_XBUTTON1 #define VK_XBUTTON1 0x05 /* NOT contiguous with L & RBUTTON */ #define VK_XBUTTON2 0x06 /* NOT contiguous with L & RBUTTON */ #define MK_XBUTTON1 0x0020 #define MK_XBUTTON2 0x0040 #endif // VK_XBUTTON1 #define WARNING sizeof typedef struct __TRACKINGLIST { TRACKMOUSEEVENT tme; POINT pt; // center of hover rectangle } _TRACKINGLIST; // FIXME: move tracking stuff into a per thread data static _TRACKINGLIST g_trackingInfo; static UINT_PTR g_trackingTimer; static WORD GetButtonState() { WORD wRet = 0; if(GetSystemMetrics(SM_SWAPBUTTON)) { if(GetKeyState(VK_RBUTTON) < 0) wRet |= MK_LBUTTON; if(GetKeyState(VK_LBUTTON) < 0) wRet |= MK_RBUTTON; } else { if(GetKeyState(VK_LBUTTON) < 0) wRet |= MK_LBUTTON; if(GetKeyState(VK_RBUTTON) < 0) wRet |= MK_RBUTTON; } if(GetKeyState(VK_MBUTTON) < 0) wRet |= MK_MBUTTON; if(GetKeyState(VK_SHIFT) < 0) wRet |= MK_SHIFT; if(GetKeyState(VK_CONTROL) < 0) wRet |= MK_CONTROL; if(GetKeyState(VK_XBUTTON1) < 0) wRet |= MK_XBUTTON1; if(GetKeyState(VK_XBUTTON2) < 0) wRet |= MK_XBUTTON2; return wRet; } static HWND WindowFromPointEx(POINT pt, PINT piHitCode) { HWND hwnd = WindowFromPoint(pt); if(!hwnd) { if(piHitCode) *piHitCode = HTNOWHERE; return NULL; } if(piHitCode) *piHitCode = SendMessage(hwnd, WM_NCHITTEST, 0, MAKELPARAM((SHORT)pt.x, (SHORT)pt.y)); return hwnd; } static void CheckMouseLeave(HWND hwnd, int hittest) { if(g_trackingInfo.tme.hwndTrack != hwnd) { if(g_trackingInfo.tme.dwFlags & TME_NONCLIENT) PostMessage(g_trackingInfo.tme.hwndTrack, WM_NCMOUSELEAVE, 0, 0); else PostMessage(g_trackingInfo.tme.hwndTrack, WM_MOUSELEAVE, 0, 0); // remove the TME_LEAVE flag g_trackingInfo.tme.dwFlags &= ~TME_LEAVE; } else { if(hittest == HTCLIENT) { if(g_trackingInfo.tme.dwFlags & TME_NONCLIENT) { PostMessage(g_trackingInfo.tme.hwndTrack, WM_NCMOUSELEAVE, 0, 0); // remove the TME_LEAVE flag g_trackingInfo.tme.dwFlags &= ~TME_LEAVE; } } else { if(!(g_trackingInfo.tme.dwFlags & TME_NONCLIENT)) { PostMessage(g_trackingInfo.tme.hwndTrack, WM_MOUSELEAVE, 0, 0); // remove the TME_LEAVE flag g_trackingInfo.tme.dwFlags &= ~TME_LEAVE; } } } } static void CALLBACK TrackMouseEventProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { POINT pt; INT iHoverWidth = 0, iHoverHeight = 0; INT hittest; GetCursorPos(&pt); hwnd = WindowFromPointEx(pt, &hittest); SystemParametersInfo(SPI_GETMOUSEHOVERWIDTH, 0, &iHoverWidth, 0); SystemParametersInfo(SPI_GETMOUSEHOVERHEIGHT, 0, &iHoverHeight, 0); // see if this tracking event is looking for TME_LEAVE and that the mouse has left the window if(g_trackingInfo.tme.dwFlags & TME_LEAVE) CheckMouseLeave(hwnd, hittest); // mouse is gone, stop tracking mouse hover if(g_trackingInfo.tme.hwndTrack != hwnd) g_trackingInfo.tme.dwFlags &= ~TME_HOVER; // see if we are tracking hovering for this hwnd if(g_trackingInfo.tme.dwFlags & TME_HOVER) { // has the cursor moved outside the rectangle centered around pt? if((abs(pt.x - g_trackingInfo.pt.x) > (iHoverWidth / 2)) || (abs(pt.y - g_trackingInfo.pt.y) > (iHoverHeight / 2))) { // record this new position as the current position g_trackingInfo.pt = pt; } else { if(hittest == HTCLIENT) { ScreenToClient(hwnd, &pt); PostMessage(g_trackingInfo.tme.hwndTrack, WM_MOUSEHOVER, GetButtonState(), MAKELPARAM(pt.x, pt.y)); } else { if(g_trackingInfo.tme.dwFlags & TME_NONCLIENT) PostMessage(g_trackingInfo.tme.hwndTrack, WM_NCMOUSEHOVER, hittest, MAKELPARAM(pt.x, pt.y)); } // stop tracking mouse hover g_trackingInfo.tme.dwFlags &= ~TME_HOVER; } } // stop the g_trackingTimer if the tracking list is empty if(!(g_trackingInfo.tme.dwFlags & (TME_HOVER | TME_LEAVE))) { KillSystemTimer(g_trackingInfo.tme.hwndTrack, g_trackingTimer); g_trackingTimer = 0; g_trackingInfo.tme.hwndTrack = 0; g_trackingInfo.tme.dwFlags = 0; g_trackingInfo.tme.dwHoverTime = 0; } } /* * During mouse tracking WM_MOUSEHOVER or WM_MOUSELEAVE events are posted * to the hwnd specified in the ptme structure. After the event message * is posted to the hwnd, the entry in the queue is removed. * * If the current hwnd isn't ptme->hwndTrack the TME_HOVER flag is completely * ignored. The TME_LEAVE flag results in a WM_MOUSELEAVE message being posted * immediately and the TME_LEAVE flag being ignored. * */ BOOL WINAPI TrackMouseEvent(TRACKMOUSEEVENT* ptme) { HWND hwnd; POINT pt; DWORD dwHoverTime; INT hittest; if(ptme->cbSize != sizeof(TRACKMOUSEEVENT)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } // fill the TRACKMOUSEEVENT struct with the current tracking for the given hwnd if(ptme->dwFlags & TME_QUERY) { *ptme = g_trackingInfo.tme; // set cbSize in the case it's not initialized yet ptme->cbSize = sizeof(TRACKMOUSEEVENT); return TRUE; // return here, TME_QUERY is retrieving information } if(!IsWindow(ptme->hwndTrack)) { SetLastError(ERROR_INVALID_WINDOW_HANDLE); return FALSE; } dwHoverTime = ptme->dwHoverTime; // if HOVER_DEFAULT was specified replace this with the systems current value. // TME_LEAVE doesn't need to specify hover time so use default if(dwHoverTime == HOVER_DEFAULT || dwHoverTime == 0 || !(ptme->dwHoverTime & TME_HOVER)) SystemParametersInfo(SPI_GETMOUSEHOVERTIME, 0, &dwHoverTime, 0); GetCursorPos(&pt); hwnd = WindowFromPointEx(pt, &hittest); if(ptme->dwFlags & ~(TME_CANCEL | TME_HOVER | TME_LEAVE | TME_NONCLIENT)) WARNING("Unknown flag(s) %08x\n", ptme->dwFlags & ~(TME_CANCEL | TME_HOVER | TME_LEAVE | TME_NONCLIENT)); if(ptme->dwFlags & TME_CANCEL) { if(g_trackingInfo.tme.hwndTrack == ptme->hwndTrack) { g_trackingInfo.tme.dwFlags &= ~(ptme->dwFlags & ~TME_CANCEL); // if we aren't tracking on hover or leave remove this entry if(!(g_trackingInfo.tme.dwFlags & (TME_HOVER | TME_LEAVE))) { KillSystemTimer(g_trackingInfo.tme.hwndTrack, g_trackingTimer); g_trackingTimer = 0; g_trackingInfo.tme.hwndTrack = 0; g_trackingInfo.tme.dwFlags = 0; g_trackingInfo.tme.dwHoverTime = 0; } } } else { // In our implementation it's possible that another window will receive a // WM_MOUSEMOVE and call TrackMouseEvent before TrackMouseEventProc is // called. In such a situation post the WM_MOUSELEAVE now if(g_trackingInfo.tme.dwFlags & TME_LEAVE && g_trackingInfo.tme.hwndTrack != NULL) CheckMouseLeave(hwnd, hittest); if(g_trackingTimer) { KillSystemTimer(g_trackingInfo.tme.hwndTrack, g_trackingTimer); g_trackingTimer = 0; g_trackingInfo.tme.hwndTrack = 0; g_trackingInfo.tme.dwFlags = 0; g_trackingInfo.tme.dwHoverTime = 0; } if(ptme->hwndTrack == hwnd) { // Adding new mouse event to the tracking list g_trackingInfo.tme = *ptme; g_trackingInfo.tme.dwHoverTime = dwHoverTime; // Initialize HoverInfo variables even if not hover tracking g_trackingInfo.pt = pt; g_trackingTimer = SetSystemTimer(g_trackingInfo.tme.hwndTrack, (UINT_PTR)&g_trackingInfo.tme, dwHoverTime, TrackMouseEventProc); } } return TRUE; }
[ "dandycheung@9b253700-4547-11de-82b9-170f4fd74ac7" ]
[ [ [ 1, 284 ] ] ]
1922e70920214d3bc5cc984881c6748c2f265407
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/wave.hpp
ec9ddeaf53b9656c07ae1d34b6040caff520afd3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
889
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2007 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(WAVE_HPP_DCA0EA51_EF5B_4BF1_88A8_461DBC5F292B_INCLUDED) #define WAVE_HPP_DCA0EA51_EF5B_4BF1_88A8_461DBC5F292B_INCLUDED #include <boost/wave/wave_config.hpp> #include <boost/wave/cpp_exceptions.hpp> #include <boost/wave/cpplexer/cpplexer_exceptions.hpp> #include <boost/wave/token_ids.hpp> #include <boost/wave/cpp_context.hpp> #endif // !defined(WAVE_HPP_DCA0EA51_EF5B_4BF1_88A8_461DBC5F292B_INCLUDED)
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 21 ] ] ]
f2e39a0e1dc6877e725ba1d2d5cc5ec165a956c0
b5ab57edece8c14a67cc98e745c7d51449defcff
/Captain's Log/MainGame/Source/GameObjects/CScout.cpp
6567603281e23d919740bf7b9a3756862162c54b
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
7,501
cpp
#include "precompiled_header.h" #include "CScout.h" #include "CAbilities.h" CScout::CScout() { Type(OBJ_PLAYER); SubType(PLAYER_SCOUT); PosX(0); PosY(0); VelX(0); VelY(0); Width(32); Height(32); CurHealth(80); MaxHealth(80); AttackSpeed(3); AttackDamage(60); AttackTimer(0); AttackRange(250); SightRange(AttackRange() + 100); Armor(15); Cloaked(false); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Walk-N")); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Walk-NE")); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Walk-E")); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Walk-SE")); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Walk-S")); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Idle")); Animations()->push_back(CAnimationManager::GetInstance()->GetAnimationID("Ghost-Fire")); Abilities()->push_back(new CAbility_Cloak(this)); Abilities()->push_back(new CAbility_PinningShot()); } void CScout::Update( float fElapsedTime ) { CPlayerUnit::Update(fElapsedTime); if(VelX() == 0.0f && VelY() < 0.0f) { CurDirection(0); } else if(VelX() > 0.0f && VelY() < 0.0f) { CurDirection(1); } else if(VelX() > 0.0f && VelY() == 0.0f) { CurDirection(2); } else if(VelX() > 0.0f && VelY() > 0.0f) { CurDirection(3); } else if(VelX() == 0.0f && VelY() > 0.0f) { CurDirection(4); } else if(VelX() < 0.0f && VelY() > 0.0f) { CurDirection(5); } else if(VelX() < 0.0f && VelY() == 0.0f) { CurDirection(6); } else if(VelX() < 0.0f && VelY() < 0.0f) { CurDirection(7); } if (CurDirection() < 5) { CAnimationManager::GetInstance()->GetAnimation((*Animations())[CurDirection()])->anAnimation.Update(fElapsedTime); } else if (CurDirection() == 5) { CAnimationManager::GetInstance()->GetAnimation((*Animations())[3])->anAnimation.Update(fElapsedTime); } else if (CurDirection() == 6) { CAnimationManager::GetInstance()->GetAnimation((*Animations())[2])->anAnimation.Update(fElapsedTime); } else { CAnimationManager::GetInstance()->GetAnimation((*Animations())[1])->anAnimation.Update(fElapsedTime); } } void CScout::Initialize() { } void CScout::Render() { CUnit::Render(); bool flipped = false; if (State() == 0 || State() == 3) { switch (CurDirection()) { case 0: CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(0); break; case 1: CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(1); break; case 2: CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(2); break; case 3: CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(3); break; case 4: CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(4); break; case 5: flipped = true; CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(3); break; case 6: flipped = true; CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(2); break; case 7: flipped = true; CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.CurFrame(1); break; } if (Cloaked()) { CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.Render((int)PosX() - (int)CGame::GetInstance()->GetCamera()->GetX(), (int)PosY() - (int)CGame::GetInstance()->GetCamera()->GetY(), flipped, 2.0f, D3DCOLOR_ARGB(128, 255, 255, 255)); } else { CAnimationManager::GetInstance()->GetAnimation((*Animations())[5])->anAnimation.Render((int)PosX() - (int)CGame::GetInstance()->GetCamera()->GetX(), (int)PosY() - (int)CGame::GetInstance()->GetCamera()->GetY(), flipped, 2.0f); } } else if (State() == 1 || State() == 2) { int nAnim = -1; switch (CurDirection()) { case 0: CAnimationManager::GetInstance()->GetAnimation((*Animations())[0])->anAnimation.Play(); nAnim = 0; break; case 1: CAnimationManager::GetInstance()->GetAnimation((*Animations())[1])->anAnimation.Play(); nAnim = 1; break; case 2: CAnimationManager::GetInstance()->GetAnimation((*Animations())[2])->anAnimation.Play(); nAnim = 2; break; case 3: CAnimationManager::GetInstance()->GetAnimation((*Animations())[3])->anAnimation.Play(); nAnim = 3; break; case 4: CAnimationManager::GetInstance()->GetAnimation((*Animations())[4])->anAnimation.Play(); nAnim = 4; break; case 5: CAnimationManager::GetInstance()->GetAnimation((*Animations())[3])->anAnimation.Play(); flipped = true; nAnim = 3; break; case 6: CAnimationManager::GetInstance()->GetAnimation((*Animations())[2])->anAnimation.Play(); flipped = true; nAnim = 2; break; case 7: CAnimationManager::GetInstance()->GetAnimation((*Animations())[1])->anAnimation.Play(); flipped = true; nAnim = 1; break; } if (Cloaked()) { CAnimationManager::GetInstance()->GetAnimation((*Animations())[nAnim])->anAnimation.Render((int)PosX() - (int)CGame::GetInstance()->GetCamera()->GetX(), (int)PosY() - (int)CGame::GetInstance()->GetCamera()->GetY(), flipped, 2.0f, D3DCOLOR_ARGB(128, 255, 255, 255)); } else { CAnimationManager::GetInstance()->GetAnimation((*Animations())[nAnim])->anAnimation.Render((int)PosX() - (int)CGame::GetInstance()->GetCamera()->GetX(), (int)PosY() - (int)CGame::GetInstance()->GetCamera()->GetY(), flipped, 2.0f); } } else if (State() == 4) { switch (CurDirection()) { case 0: CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(0); break; case 1: CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(1); break; case 2: CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(2); break; case 3: CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(3); break; case 4: CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(4); break; case 5: flipped = true; CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(3); break; case 6: flipped = true; CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(2); break; case 7: flipped = true; CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.CurFrame(1); break; } if (Cloaked()) { CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.Render((int)PosX() - (int)CGame::GetInstance()->GetCamera()->GetX(), (int)PosY() - (int)CGame::GetInstance()->GetCamera()->GetY(), flipped, 2.0f, D3DCOLOR_ARGB(128, 255, 255, 255)); } else { CAnimationManager::GetInstance()->GetAnimation((*Animations())[6])->anAnimation.Render((int)PosX() - (int)CGame::GetInstance()->GetCamera()->GetX(), (int)PosY() - (int)CGame::GetInstance()->GetCamera()->GetY(), flipped, 2.0f); } } }
[ "notserp007@34577012-8437-c882-6fb8-056151eb068d", "tabu34@34577012-8437-c882-6fb8-056151eb068d", "dpmakin@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 2 ], [ 4, 4 ], [ 37, 38 ], [ 90, 96 ] ], [ [ 3, 3 ], [ 8, 10 ], [ 13, 16 ], [ 18, 18 ], [ 22, 23 ], [ 32, 34 ], [ 103, 103 ], [ 135, 142 ], [ 146, 146 ], [ 151, 151 ], [ 155, 155 ], [ 159, 159 ], [ 163, 163 ], [ 167, 167 ], [ 172, 172 ], [ 177, 177 ], [ 182, 182 ], [ 185, 192 ], [ 194, 194 ], [ 226, 233 ] ], [ [ 5, 7 ], [ 11, 12 ], [ 17, 17 ], [ 19, 21 ], [ 24, 31 ], [ 35, 36 ], [ 39, 89 ], [ 97, 102 ], [ 104, 134 ], [ 143, 145 ], [ 147, 150 ], [ 152, 154 ], [ 156, 158 ], [ 160, 162 ], [ 164, 166 ], [ 168, 171 ], [ 173, 176 ], [ 178, 181 ], [ 183, 184 ], [ 193, 193 ], [ 195, 225 ], [ 234, 235 ] ] ]
0c18c7c6dd9a1b40e79e73d76fc24a615589e499
c06e9971452d8183196ea30eec3fe2455cfd2cf2
/scrolls/Mandelbrot-threaded/TextureRenderer.h
4a735f8bb5aecd24a9103fe986589a28be80b461
[]
no_license
Spaxe/Scrollbook
f9e73773b3f69045129ab577f34e9ac64782ad4c
80212354b00cf3bb58e09ed93c9f83da3764e7c9
refs/heads/master
2016-09-05T19:12:54.638509
2011-09-22T15:06:51
2011-09-22T15:06:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,999
h
/// /// Author: Xavier Ho ([email protected]) /// /// Provides a simple interface to draw texture to the screen via a fullscreen /// quad. This renderer assumes 3 8-bit BGR channels in the texture, tightly packed. #pragma once #ifdef _WIN32 #include "GL/glew.h" #include "GL/glfw.h" #else #include <GL/glew.h> #include <GL/glfw.h> #endif #include "Timer.h" #include "Threading.h" /// Simple renderer that draws a fullscreen quad with a texture. /// /// Multithreading is supported. Override this: /// /// void thread_action(int index) /// /// In addition, if you want to have more than ESC to quit, override: /// /// void handle_inputs() (optional) /// /// See Threading.h for more information. class TextureRenderer : public Threading { unsigned int texture_id; /// Internal texture id tracker Timer timer; /// Performance tracker /// Thread synchronisation stuff. Messy, could use some refactoring pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; volatile int resources; /// Number of threads completed; for synchronisation protected: double elapsed_time; /// Total time took to render one frame, in ms /// True upon running. Set to false when you want the program to finish. bool running; unsigned char * data; /// Texture data int width, height; /// Texture resolution public: TextureRenderer(int width, int height); virtual ~TextureRenderer(); void set_window_title(const char * text); void set_window_size(int width, int height); /// Starts a multi-threaded program with additional count threads void start_threaded(int count); private: void __start(); void __set_texture(); void render(); protected: /// Override this method to handle user inputs. virtual void handle_inputs(); /// Thread synchronisation. Call in thread_action() to signal finish. void thread_signal_and_wait(); };
[ [ [ 1, 67 ] ] ]
2dcb08325a504ca53cbca09ad6516b60673b1fe3
554a3b859473dc4dfebc6a31b16dfd14c84ffd09
/ui/sxgo_ram_window.hpp
41a61c0fd6f099258b148c350681353eabfcd245
[ "BSL-1.0" ]
permissive
DannyHavenith/sxsim
c0fbaf016fc7dcae7535e152ae9e33f3386d3792
e3d5ad1f6f75157397d03c191b4b4b0af00ebb60
refs/heads/master
2021-01-19T11:22:20.615306
2011-05-30T22:11:18
2011-05-30T22:11:18
1,822,817
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
hpp
// Copyright Danny Havenith 2006 - 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #if !defined( SXGO_RAM_WINDOW_HPP) #define SXGO_RAM_WINDOW_HPP #include "sx_simulator.hpp" #include "wx/grid.h" DECLARE_EVENT_TYPE(EVT_CHANGE_RAMVALUE, -1) DECLARE_EVENT_TYPE(EVT_TOGGLE_RAM_BREAKPOINT, -1) class sxgo_ram_window : public wxGrid { public: explicit sxgo_ram_window( wxWindow *parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxWANTS_CHARS, const wxString& name = wxT("Listing")); void Update( const sx_simulator::state &state); void ChangeValue( wxGridEvent &event); void ToggleBreakpoint( wxGridEvent &event); DECLARE_EVENT_TABLE() }; #endif //SXGO_RAM_WINDOW_HPP
[ "danny@3a7aa2ed-2c50-d14e-a1b9-f07bebb4988c" ]
[ [ [ 1, 33 ] ] ]
7adc24938de3c7e39de2e823efe3b9cd8c68676b
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkExtractSelectedLocations.h
dced686d2ddc0642f37de4a847935b5bd2e9294a
[]
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,252
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkExtractSelectedLocations.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. =========================================================================*/ // .NAME vtkExtractSelectedLocations - extract cells within a dataset that // contain the locations listen in the vtkSelection. // .SECTION Description // vtkExtractSelectedLocations extracts all cells whose volume contain at least // one point listed in the LOCATIONS content of the vtkSelection. This filter // adds a scalar array called vtkOriginalCellIds that says what input cell // produced each output cell. This is an example of a Pedigree ID which helps // to trace back results. // .SECTION See Also // vtkSelection vtkExtractSelection #ifndef __vtkExtractSelectedLocations_h #define __vtkExtractSelectedLocations_h #include "vtkExtractSelectionBase.h" class vtkSelection; class VTK_GRAPHICS_EXPORT vtkExtractSelectedLocations : public vtkExtractSelectionBase { public: static vtkExtractSelectedLocations *New(); vtkTypeRevisionMacro(vtkExtractSelectedLocations, vtkExtractSelectionBase); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkExtractSelectedLocations(); ~vtkExtractSelectedLocations(); // Usual data generation method int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); int ExtractCells(vtkSelection *sel, vtkDataSet *input, vtkDataSet *output); int ExtractPoints(vtkSelection *sel, vtkDataSet *input, vtkDataSet *output); private: vtkExtractSelectedLocations(const vtkExtractSelectedLocations&); // Not implemented. void operator=(const vtkExtractSelectedLocations&); // Not implemented. }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 59 ] ] ]
7530e582f2491e133f6af48980c375caa7033764
d2fc16640fb0156afb6528e744867e2be4eec02c
/src/Images/jpg.cpp
ee394836542a08d1b4c0d2f1ac73c9a6a3aec2ed
[]
no_license
wlschmidt/lcdmiscellany
8cd93b5403f9c62a127ddd00c8c5dd577cf72e2f
6623ca05cd978d91580673e6d183f2242bb8eb24
refs/heads/master
2021-01-19T02:30:05.104179
2011-11-02T21:52:07
2011-11-02T21:52:07
48,021,331
1
1
null
2016-07-23T09:08:48
2015-12-15T05:20:15
C++
UTF-8
C++
false
false
18,606
cpp
#include "jpg.h" //#include <malloc.h> //#include <string.h> //#include <math.h> #include <string.h> #include "..\\malloc.h" #define SOI 0xD8 #define EOI 0xD9 #define SOF0 0xC0 #define SOS 0xDA #define APP0 0xE0 #define COM 0xFE #define DNL 0xDC #define DRI 0xDD #define DQT 0xDB #define DHT 0xC4 #define DAC 0xCC struct HuffmanTable { int numCodes[16]; unsigned short minCode[16]; unsigned short maxCode[16]; unsigned char values[256]; }; struct Section { float v[64]; }; struct Component { int id, vertFactor, horizFactor, qt; }; #define PI 3.141592654 struct ComponentScan { int id, AC, DC; }; int reorder[] = { 0, 1, 5, 6,14,15,27,28, 2, 4, 7,13,16,26,29,42, 3, 8,12,17,25,30,41,43, 9,11,18,24,31,40,44,53, 10,19,23,32,39,45,52,54, 20,22,33,38,46,51,55,60, 21,34,37,47,50,56,59,61, 35,36,48,49,57,58,62,63}; inline void __fastcall MoveJunk(int len, int &offset, int &pos, unsigned int &ndata, unsigned char *data, int bytes) { offset += bytes; ndata <<= bytes; while (offset>=8) { if (pos>=len) { offset-=8; pos++; } else if (data[pos]==0xFF) { if (pos+1>=len) { // Help! offset = 0; return; } else if (data[pos+1]==0) { offset-=8; ndata += (data[pos]<<offset); pos+=2; } else if (data[pos+1] == 0xd0 || data[pos+1] == 0xd1 || data[pos+1] == 0xd2 || data[pos+1] == 0xd3 || data[pos+1] == 0xd4 || data[pos+1] == 0xd5 || data[pos+1] == 0xd6 || data[pos+1] == 0xd7 || data[pos+1] == 0x01 || data[pos+1] == EOI) pos+=2; else { pos+=2; if (pos+1>=len) { // help! continue; } int len2 = Flip(&data[pos]); pos+=len2; } } else { offset-=8; ndata += (data[pos++]<<offset); } } } template <class PixelFormat> void ResampleBilinear(GenericImage<PixelFormat> *in, GenericImage<PixelFormat> *out) { float scalex = (in->width)/(float)(out->width); float scaley = (in->height)/(float)(out->height); float xoffset = 0.5f - 0.5f * scalex; float yoffset = 0.5f - 0.5f * scaley; int u, v1; int x, y; float rx, ry; float yWeight[2]; float *xWeights = (float*) alloca(sizeof(float)*out->width*2 + sizeof(int)*out->width); int *xvals = (int*) &xWeights[out->width*2]; for (x=0; x<(int)out->width; x++) { rx = x*scalex-xoffset; if (rx<0) rx = 0; if (rx>in->height-1) { u = in->height-1; rx = (float) u; xvals[x] = u; xWeights[2*x] = 1; xWeights[2*x+1] = 0; } else { u = (int) rx; xvals[x] = u; xWeights[2*x] = (u+1)-rx; xWeights[2*x+1] = 1-xWeights[2*x]; } } PixelFormat *p = out->pixels; for (y=0; y<(int)out->height; y++) { ry = y*scaley-yoffset; if (ry<0) { v1=0; yWeight[0]=1; yWeight[1] = 0; } else if (ry>in->height-1) { //ry = (float)(in->height-1); v1 = (in->height-1)*in->width; yWeight[0]=1; } else { v1 = (int)ry; yWeight[0] = (v1+1)-ry; yWeight[1] = 1-yWeight[0]; v1 *= in->width; } PixelFormat *pixels = &in->pixels[v1]; PixelFormat *pixels2 = &pixels[in->width]; if (yWeight[0]==1) { for (x=0; x<(int)out->width; x++) { u = xvals[x]; if (xWeights[2*x+1]==0) { p++[0] = pixels[u]; } else { p++[0] = xWeights[2*x] * pixels[u] + xWeights[2*x+1] * pixels[u+1]; } } } else { for (x=0; x<(int)out->width; x++) { u = xvals[x]; if (xWeights[2*x+1]==0) { p++[0] = xWeights[2*x] * (yWeight[0]*pixels[u] + yWeight[1]*pixels2[u]); } else { p++[0] = xWeights[2*x] * (yWeight[0]*pixels[u] + yWeight[1]*pixels2[u]) + xWeights[2*x+1] * (yWeight[0]*pixels[u+1] + yWeight[1]*pixels2[u+1]); } /* PixelFormat sum = in->pixels[u+in->width*v]; if (rx-u>0.005f) { sum*= (u+1)-rx; sum+= in->pixels[u+1+in->width*v] * (rx-u); if (ry-v > 0.0005f) { sum*= (v+1)-ry; sum+= (ry-v) * (in->pixels[u +in->width*(v+1)] * ((u+1)-rx) + in->pixels[u+1+in->width*(v+1)] * (rx-u)); } } else if (ry-v > 0.0005f) { sum*= (v+1)-ry; sum+= in->pixels[u+in->width*(v+1)] * (ry-v); }//*/ //p++[0] = sum; /* rx = x*scalex-xoffset; if (rx<0) rx = 0; if (rx>in->height-1) rx = (float) (in->height-1); u = (int) rx; PixelFormat sum = yWeight[0]*in->pixels[u+v1] + yWeight[1]*in->pixels[u+v2]; if (rx-u>0.005f) { sum*= (u+1)-rx; sum+= (rx-u)*(yWeight[0]*in->pixels[u+1+v1] + yWeight[1]*in->pixels[u+1+v2]); }*/ } } } //free(xWeights); } inline void __fastcall Decode(int len, int &offset, int &pos, unsigned int &ndata, unsigned char *data, float &start, float *out, HuffmanTable &htAC, HuffmanTable &htDC) { int i; unsigned short s = ndata>>16; unsigned int p=0; for (i=0; i<16; i++) { if (htDC.maxCode[i] > s && htDC.minCode[i] <= s) { p+=((s - htDC.minCode[i])>>(15-i)); break; } p += htDC.numCodes[i]; } int len2 = htDC.values[p]; MoveJunk(len, offset, pos, ndata, data, i+1); int negMask[16] = {0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF}; int val; if (len2!=0) { val = ndata>>(32-len2); if (0 == (val & (1<<(len2-1)))) { val = -(val^negMask[len2]); } out[0] = start+(float)val; start = out[0]; MoveJunk(len, offset, pos, ndata, data, len2); } else { out[0] = start; } memset(out+1, 0, sizeof(float)*63); int vpos = 1; while (vpos < 64) { p=0; s = ndata>>16; for (i=0; i<16; i++) { if (htAC.maxCode[i] > s && htAC.minCode[i] <= s) { p+=((s - htAC.minCode[i])>>(15-i)); break; } p += htAC.numCodes[i]; } p = htAC.values[p]; MoveJunk(len, offset, pos, ndata, data, i+1); int jump = p>>4; len2 = p & 0xF; vpos+=jump; if (len2==0) { if (jump==0) break; vpos++; continue; } else { val = ndata>>(32-len2); } if (0 == (val & (1<<(len2-1)))) { val = -(val^negMask[len2]); } out[vpos++] = (float)val; MoveJunk(len, offset, pos, ndata, data, len2); } } inline void ReorderAndIDCT(float *out, float *qt) { int *order = reorder; float yvals[8][8]; float tmp10, tmp11, tmp13, z10, z11, z12, z13, z5; float tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; float *working = yvals[0]; while (working<yvals[1]) { if (!out[order[8 ]] && !out[order[16]] && !out[order[24]] && !out[order[32]] && !out[order[40]] && !out[order[48]] && !out[order[56]]) { working[ 0] = out[order++[0]] * qt++[0]; working[ 8] = working[0]; working[16] = working[0]; working[24] = working[0]; working[32] = working[0]; working[40] = working[0]; working[48] = working[0]; working[56] = working[0]; } else { tmp0 = out[order[ 0]] * qt[0]; tmp1 = out[order[16]] * qt[16]; tmp2 = out[order[32]] * qt[32]; tmp3 = out[order[48]] * qt[48]; tmp10 = tmp0 + tmp2;// phase 3 tmp11 = tmp0 - tmp2; tmp13 = tmp1 + tmp3;// phases 5-3 z5 = (tmp1 - tmp3) * 1.414213562f - tmp13; // 2*c4 tmp0 = tmp10 + tmp13; tmp3 = tmp10 - tmp13; tmp1 = tmp11 + z5; tmp2 = tmp11 - z5; tmp4 = out[order[8 ]] * qt[8 ]; tmp5 = out[order[24]] * qt[24]; tmp6 = out[order[40]] * qt[40]; tmp7 = out[order++[56]] * qt++[56]; z13 = tmp6 + tmp5; z10 = tmp6 - tmp5; z11 = tmp4 + tmp7; z12 = tmp4 - tmp7; tmp7 = z11 + z13; tmp11= (z11 - z13) * 1.414213562f; z5 = (z10 + z12) * 1.847759065f; tmp10 = 1.082392200f * z12 - z5; tmp6 = -2.613125930f * z10 + z5 - tmp7; tmp5 = tmp11 - tmp6; tmp4 = tmp10 + tmp5; working[ 0] = tmp0 + tmp7; working[ 8] = tmp1 + tmp6; working[16] = tmp2 + tmp5; working[24] = tmp3 - tmp4; working[32] = tmp3 + tmp4; working[40] = tmp2 - tmp5; working[48] = tmp1 - tmp6; working[56] = tmp0 - tmp7; } working++; } working = yvals[0]; float *data = out; while (working<yvals[8]) { tmp10 = working[0] + working[4]; tmp11 = working[0] - working[4]; tmp13 = working[2] + working[6]; z5 = (working[2] - working[6]) * 1.414213562f-tmp13; tmp0 = tmp10+tmp13; tmp3 = tmp10-tmp13; tmp1 = tmp11+z5; tmp2 = tmp11-z5; z13 = working[5] + working[3]; z10 = working[5] - working[3]; z11 = working[1] + working[7]; z12 = working[1] - working[7]; tmp7 = z11+z13; tmp11 = (z11-z13) * 1.414213562f; z5 = (z10 + z12) * 1.847759065f; tmp10 = 1.082392200f * z12 - z5; tmp6 = -2.613125930f * z10 + z5 - tmp7; tmp5 = tmp11 - tmp6; tmp4 = tmp10 + tmp5; data[0] = tmp0 + tmp7; data[1] = tmp1 + tmp6; data[2] = tmp2 + tmp5; data[3] = tmp3 - tmp4; data[4] = tmp3 + tmp4; data[5] = tmp2 - tmp5; data[6] = tmp1 - tmp6; data[7] = tmp0 - tmp7; working+=8; data+=8; } } int LoadJpeg(ScriptValue &sv, unsigned char *data, int len) { int u, v; int ready=0; HuffmanTable htDC[4]; HuffmanTable htAC[4]; if (len<18) return 0; if (data[0]!=0xFF || data[1]!=SOI) return 0; float qt[4][64]; memset(qt, 0, sizeof(qt)); data += 2; len-=2; int len2, pos=0; int RestartInterval=0; int i, j, k; int height=0, width=0; Component components[10]; ComponentScan componentScans[10]; int pos2; while (pos < len-1) { unsigned char c = data[pos++]; if (c!=0xFF) continue; c = data[pos++]; if (c==0xFF || c==0x01 || c==0xd0 || c==0xd1 || c==0xd2 || c==0xd3 || c==0xd4 || c==0xd5 || c==0xd6 || c==0xd7) { continue; } if (c==EOI) break; if (c==DAC) return 0; if (pos>=len-1) continue; len2 = Flip(&data[pos]); if (pos+len2 > len) { pos += len2; continue; } if (c == DQT) { pos2 = pos+2; while (pos2<pos+len2) { int num = data[pos2]&0xF; int bits = data[pos2]>>4; if (num>=4) return 0; pos2++; long qtTemp[64]; memset(qtTemp,0,sizeof(qtTemp)); for (j=0; j<64; j++) { for (k=0; k<=bits; k++) { if (pos2>len) continue; qtTemp[j] += (data[pos2++]<<((bits-k-1)<<8)); } } for (j=0; j<64; j++) { const float scalefactor[8]={1.0f/2.828427125f, 1.387039845f/2.828427125f, 1.306562965f/2.828427125f, 1.175875602f/2.828427125f, 1.0f/2.828427125f, 0.785694958f/2.828427125f, 0.541196100f/2.828427125f, 0.275899379f/2.828427125f}; qt[num][j] = qtTemp[reorder[j]] * scalefactor[j/8] * scalefactor[j%8]; } } ready|=8; } else if (c == DHT) { pos2 = pos+2; while (pos2<pos+len2) { int num = data[pos2]&0xF; int type = (data[pos2]>>4)&1; if (data[pos2]>>5) return 0; pos2++; HuffmanTable *h; if (type) h = &htAC[num]; else h = &htDC[num]; memset(h->values, 0, sizeof(h->values)); unsigned short min=0; unsigned short inc = 0x8000; for (j=0; j<16; j++) { if (pos2>len) return 0; h->minCode[j] = min; unsigned short codes = data[pos2++]; h->maxCode[j] = min+(codes)*inc; min = h->maxCode[j]; h->numCodes[j] = codes; inc>>=1; } //h->values[0]=0; min = 0; inc = 0x8000; i=0; for (j=0; j<16; j++) { while (h->maxCode[j]>min) { if (pos2>len) return 0; h->values[i++] = ((unsigned char*) data)[pos2++]; min += inc; } inc>>=1; } } ready|=4; } else if (c == DRI) { if (len2!=4) continue; RestartInterval = Flip(&data[pos+2]); } else if (c == SOF0) { if (len2<11) return 0; pos2 = pos+2; int bytes = data[pos2++]; //if (bytes!=8) return 0; height = Flip(&data[pos2]); width = Flip(&data[pos2+2]); pos2+=4; //Note that these are technically signed, and I'm too lazy to mess with it if (width>20000 || height > 20000) return 0; int numComponents = data[pos2++]; if (len2<numComponents*3+8 || numComponents>4) return 0; for (i=0; i<numComponents; i++) { components[i].id = data[pos2++]; if (components[i].id>=4 || components[i].id<1) return 0; components[i].vertFactor = data[pos2]&0xF; components[i].horizFactor = data[pos2++]>>4; if (components[i].horizFactor==0) return 0; if (components[i].vertFactor==0) return 0; components[i].qt = data[pos2++]; } components[i].id=0; ready|=2; } else if (c == SOS) { if (len2<6) return 0; pos2 = pos+2; int numComponents = data[pos2++]; if (len2<6+numComponents) return 0; for (i=0; i<numComponents; i++) { componentScans[i].id = data[pos2++]; if (componentScans[i].id>=4 || componentScans[i].id<1) return 0; componentScans[i].AC = data[pos2]&0xF; componentScans[i].DC = data[pos2++]>>4; } componentScans[i].id=0; pos += len2; ready|=1; break; } else if (c == EOI) { return 0; } else if ((c&0xF0) == 0xC0){ return 0; } //else { //pos=pos; //} pos += len2; } if (ready!=0xF) return 0; i=0; int maxV=1; int maxH=1; while (componentScans[i].id || components[i].id) { if (componentScans[i].id != components[i].id) return 0; if (componentScans[i].id!=1 && componentScans[i].id!=2 && componentScans[i].id!=3) return 0; if (components[i].horizFactor > maxH) maxH = components[i].horizFactor; if (components[i].vertFactor > maxV) maxV = components[i].vertFactor; i++; } int numComponents = i; float start[5] = {0}; int x, y; if (!MakeGenericImage<unsigned char>(sv, width, height, 4)) return 0; GenericImage<unsigned char> *image = (GenericImage<unsigned char> *) sv.stringVal->value; //Section * out = (Section*) malloc(sizeof(Section)*width*height); float * out = (float*) malloc(64*3*sizeof(float)*maxH*maxV); GenericImage<float> out2; out2.pixels = (float*) malloc(64*3*sizeof(float)*maxH*maxV); GenericImage<float> in2; in2.width = in2.height = 8; in2.pixels = (float*) malloc(64*3*sizeof(float)*maxH*maxV); if (!out || !out2.pixels || !in2.pixels) { sv.stringVal->Release(); free(out); free(out2.pixels); free(in2.pixels); return 0; } //in2.pixels = ins->v; int offset = 0; unsigned int ndata; ndata = (data[pos]<<24) + (data[pos+1]<<16) + (data[pos+2]<<8) + data[pos+3]; pos+=4; //memset(out, 0, sizeof(Section)*width*height); //memset(image->pixels, 255, width*height*sizeof(Color)); int pieces = 0; maxH*=8; maxV*=8; for (y=0; y<height; y += maxV) { for (x=0; x<width; x += maxH) { for (u=maxH*maxV*3-1; u>=0; u--) { out[u]=0.5f; } for (i=0; i<numComponents; i++) { //Section *s = &ins[0]; //int upscalex = maxH/components[i].horizFactor; //int upscaley = maxV/components[i].vertFactor; //float downscalex = (components[i].horizFactor*8-1)/(float)(maxH*8-1); //float downscaley = (components[i].vertFactor*8-1)/(float)(maxV*8-1); out2.width = maxH/components[i].horizFactor; out2.height = maxV/components[i].vertFactor; for (int ly = 0; ly<maxV; ly+=out2.height) { for (int lx = 0; lx<maxH; lx+=out2.width) { Decode(len, offset, pos, ndata, data, start[i], in2.pixels, htAC[componentScans[i].AC], htDC[componentScans[i].DC]); ReorderAndIDCT(in2.pixels, qt[components[i].qt]); for (int j=0; j<64; j++) { if (in2.pixels[j]<-128) in2.pixels[j] = -128; else if (in2.pixels[j]>127) in2.pixels[j] = 127; } if (out2.width != 8 || out2.height != 8) { //ResampleBilinear(&in2, &out2); ResampleBilinear(&in2, &out2); } else { float *temp = out2.pixels; out2.pixels = in2.pixels; in2.pixels = temp; //out2.pixels = ins; } int endy = ly+out2.height; int endx = lx+out2.width; //int temp = float *f = out2.pixels; float *dest = &out[3*(lx+maxH*ly)]; if (components[i].id == 1) { for (int y2 = ly; y2<endy; y2++) { //int temp = out2.width*(y2-ly) - lx; //float *dest = &out[3*(lx+maxH*y2)]; for (int x2 = lx; x2<endx; x2++) { //float sum = out2.pixels[x2 + temp]+128; float sum = f[0]+128; dest[0] += sum; dest[1] += sum; dest[2] += sum; dest+=3; f++; } dest += 3*(maxH-out2.width); } } else if (components[i].id == 2) { for (int y2 = ly; y2<endy; y2++) { //int temp = out2.width*(y2-ly) - lx; //float *dest = &out[3*(lx+maxH*y2)]; for (int x2 = lx; x2<endx; x2++) { //float sum = f[0]+128; //float sum = out2.pixels[x2 + temp]; dest[1] -= 0.34414f * f[0]; dest[2] += 1.772f * f[0]; dest+=3; f++; } dest += 3*(maxH-out2.width); } } else { for (int y2 = ly; y2<endy; y2++) { //int temp = out2.width*(y2-ly) - lx; //float *dest = &out[3*(lx+maxH*y2)]; for (int x2 = lx; x2<endx; x2++) { //float sum = out2.pixels[x2 + temp]; dest[0] += 1.402f * f[0]; dest[1] -= 0.71414f * f[0]; dest+=3; f++; } dest += 3*(maxH-out2.width); } } } } } if (++pieces == RestartInterval) { if (offset) { ndata <<= (8-offset); offset = 8; } memset(start, 0, sizeof(start)); pieces=0; } float *temp = out; Color4 *c = (Color4*)(&image->pixels[4*x+y*image->memWidth]); int mu = maxV; if (y+mu>=height) mu = height-y; int mv = maxH; if (x+mv>=width) mv = width-x; for (u=0; u<mu; u++) { for (v=0; v<mv; v++) { if (temp[0]<0) c->r = 0; else if (temp[0]>255) c->r = 255; else c->r = (unsigned char) temp[0]; if (temp[1]<0) c->g = 0; else if (temp[1]>255) c->g = 255; else c->g = (unsigned char) temp[1]; if (temp[2]<0) c->b = 0; else if (temp[2]>255) c->b = 255; else c->b = (unsigned char) temp[2]; c->a = 255; temp+=3; c++; } c+=image->memWidth/4-mv; temp+=(maxH-mv)*3; } } } free(in2.pixels); free(out); free(out2.pixels); return 1; }
[ "mattmenke@88352c64-7129-11de-90d8-1fdda9445408" ]
[ [ [ 1, 748 ] ] ]
28655082a5fcc3558d321aeb8644ba10e732104e
85ee7e4ebdc4323939a5381ef0ec1d296412533b
/source/Filesystem/Archive.cpp
cdc4949fa923c54c38c922a43ccdac0daa138ac6
[ "MIT" ]
permissive
hyperiris/praetoriansmapeditor
af71ab5d9174dfed1f4d8a4c751d92275eb541f2
e6f7c7bc913fb911632a738a557b5f2eb4d4fc57
refs/heads/master
2016-08-10T22:40:11.230823
2008-10-24T05:09:54
2008-10-24T05:09:54
43,621,569
0
0
null
null
null
null
UTF-8
C++
false
false
6,441
cpp
#include "Archive.h" #include "../zlib/zlib.h" #include "../Math/MathUtils.h" #include "../Tools/Logger.h" enum ZipState { ENCRYPTED, NOT_ENCRYPTED, NOT_RECOGNIZED }; Archive::Archive(const char* name) { archivename = name; } bool Archive::open(const char* path) { ZipDirectory zd; ZipEntry zde; ArchivedFile cendir; ArchivedFile dirent; unsigned int sig; unsigned char entryname[256]; if (!archiveMap.createMapping(path)) return false; //CENTRAL DIRECTORY archiveMap.createView("cendir", archiveMap.getFileSize() - 22, 22, &cendir); cendir.read(&sig, 4); if (NOT_RECOGNIZED == (state = verifyZip(sig))) { archiveMap.close(); return false; } cendir.seek(4, SEEKD); cendir.read(&zd.zipentrcnt, 2); cendir.read(&zd.zipentrtot, 2); cendir.read(&zd.zipdirsize, 4); cendir.read(&zd.zipdirdata, 4); if (ENCRYPTED == state) { decryptulong(zd.zipdirsize); decryptulong(zd.zipdirdata); decryptushort(zd.zipentrcnt); decryptushort(zd.zipentrtot); } if (zd.zipentrcnt == 0) { archiveMap.close(); return false; } archiveMap.unmapView(&cendir); //DIRECTORY ENTRIES archiveMap.createView("zipdirent", zd.zipdirdata, zd.zipdirsize, &dirent); for (int i = 0; i < zd.zipentrcnt; i++) { dirent.seek(10, SEEKD); dirent.read(&zde.zipcomp, 2); dirent.seek(8, SEEKD); dirent.read(&zde.zipsize, 4); dirent.read(&zde.zipuncmp, 4); dirent.read(&zde.zipfnln, 2); dirent.read(&zde.zipxtraln, 2); dirent.seek(6, SEEKD); dirent.read(&zde.zipattr, 4); dirent.read(&zde.zipdata, 4); if (ENCRYPTED == state) { decryptulong(zde.zipsize); decryptulong(zde.zipdata); decryptulong(zde.zipattr); decryptulong(zde.zipuncmp); decryptushort(zde.zipcomp); decryptushort(zde.zipfnln); decryptushort(zde.zipxtraln); } dirent.read(entryname, zde.zipfnln); if (ENCRYPTED == state) for (int j = 0; j < zde.zipfnln; j++) decryptuchar(entryname[j]); entryname[zde.zipfnln] = '\0'; zde.zipname = ICString((char*)entryname); if ((zde.zipattr & ZipEntry::FILE) && !(zde.zipattr & ZipEntry::DIRECTORY)) entries.insertKeyAndValue(zde.zipname, zde); if (zde.zipattr & ZipEntry::DIRECTORY) directories.append(zde.zipname); dirent.seek(zde.zipxtraln, SEEKD); } archiveMap.unmapView(&dirent); return true; } bool Archive::findEntry(const char* name, ZipEntry* entry) { if (!name || !entry) return false; if (entries.findValue(name, *entry)) return true; for (unsigned int i = 0; i < directories.length(); i++) if (entries.findValue(directories(i) + name, *entry)) return true; ICString::size_type i; AVLTreeTIterator <ICString, ZipEntry, 4> iter(entries); while (iter.next()) { i = iter.key().find(name); if (i != ICString::npos) if (iter.key().substr(i) == name) { *entry = iter.value(); return true; } } return false; } bool Archive::containsEntry(const char* name) { if (!name) return false; if (entries.contains(name)) return true; for (unsigned int i = 0; i < directories.length(); i++) if (entries.contains(directories(i) + name)) return true; ICString::size_type i; AVLTreeTIterator <ICString, ZipEntry, 4> iter(entries); while (iter.next()) { i = iter.key().find(name); if (i != ICString::npos) if (iter.key().substr(i) == name) return true; } return false; } unsigned int Archive::verifyZip(unsigned int sig) { return (sig == 0x06054b50) ? NOT_ENCRYPTED : ((sig ^ 0xabababab) == 0x06054b50) ? ENCRYPTED : NOT_RECOGNIZED; } bool Archive::unpackEntry(ZipEntry* entry, unsigned char* out) { if (!entry || !out) return false; ArchivedFile ent; unsigned short xtra; unsigned char* data; bool success = false; //begin hack archiveMap.createView(entry->zipname.c_str(), entry->zipdata, entry->zipsize + 30 + entry->zipfnln + entry->zipxtraln, &ent); ent.seek(28, SEEKD); ent.read(&xtra, 2); if (ENCRYPTED == state) decryptushort(xtra); ent.seek(entry->zipfnln + xtra, SEEKD); //end hack if (entry->zipcomp == 0x0000) { ent.read(out, entry->zipsize); if (ENCRYPTED == state) for (unsigned int j = 0; j < entry->zipsize; j++)// <-- ? decryptuchar(out[j]); success = true; } else if (entry->zipcomp == 0x0008) { data = new unsigned char[entry->zipsize]; memset(data, 0, entry->zipsize); ent.read(data, entry->zipsize); if (ENCRYPTED == state) for (unsigned int j = 0; j < entry->zipsize; j++) decryptuchar(data[j]); z_stream inst; inst.next_in = (Bytef*)data; inst.next_out = (Bytef*)out; inst.avail_out = (uInt)entry->zipuncmp; inst.avail_in = (uInt)entry->zipsize; inst.zalloc = (alloc_func)0; inst.zfree = (free_func)0; //if (Z_OK == inflateInit2(&inst, -MAX_WBITS)) // if (Z_STREAM_END == inflate(&inst, Z_FINISH)) // success = true; inflateInit2(&inst, -MAX_WBITS); int err = inflate(&inst, Z_FINISH); inflateEnd(&inst); success = true; deleteArray(data); } archiveMap.unmapView(&ent); return success; } void Archive::decryptulong(unsigned int& v) { v ^= 0xabababab; } void Archive::decryptuchar(unsigned char& v) { v ^= 0xab; } void Archive::decryptushort(unsigned short& v) { v ^= 0xabab; } void Archive::printAllPaths() { if (!archivename.getLength()) return; for (unsigned int i = 0; i < directories.length(); i++) Logger::writeInfoLog(directories(i).c_str()); } void Archive::printAllEntries() { if (!archivename.getLength()) return; AVLTreeTIterator <ICString, ZipEntry, 4> iter(entries); while (iter.next()) Logger::writeInfoLog(iter.key().c_str()); } void Archive::close() { archiveMap.close(); } Archive::~Archive() { close(); }
[ "kwantum26@d2fd1b2e-92ce-11dd-9977-cddf1a87921b" ]
[ [ [ 1, 287 ] ] ]
57d069dd02c840d6b78186e1a6cd6ce8170216dc
22c832011ad5ef675ca84d656a74e06a1a1766ce
/smokeGL/src/Smoke/smokeGL.cpp
5fcc17a777efadfb3989ad42a7ca139a1c0d368e
[]
no_license
kayhman/cudaHairSimulator
0af4fa0c5071dea5bb9a75e933b6c3687a26eec1
bdba6287e39717fa070dac401f83c557b67ccd2b
refs/heads/master
2016-09-05T11:44:50.724792
2011-07-01T17:19:24
2011-07-01T17:19:24
1,948,199
0
0
null
null
null
null
UTF-8
C++
false
false
13,477
cpp
#include "smokelib.h" #include "Cimg.h" #include <windows.h> #include <gl\gl.h> #include <gl\glu.h> #include "objLoader.h" HDC hDC=NULL; HGLRC hRC=NULL; HWND hWnd=NULL; HINSTANCE hInstance; bool keys[256]; bool active=TRUE; bool fullscreen=TRUE; GLfloat rtri; GLfloat rquad; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); GLvoid ReSizeGLScene(GLsizei width, GLsizei height) { if (height==0) { height=1; } glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int InitGL(GLvoid) { glClearColor (0.0, 0.0, 0.0, 0.0); GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glShadeModel (GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return TRUE; } int DrawGLScene(GLvoid) { const float hxy = 0.01; const float hz = 0.15; const float dt = 1e-2; const int hairLenght = 30; const int gridX = 128; const int gridY = 128; static SmokeRenderer smoke; static bool init = false; if(!init) smoke.initSmoke(); init = true; smoke.render(); std::vector<float> density = smoke.getDensity(); std::vector<float> radiance = smoke.getRadiance(); //CImg<unsigned char> visu(256,256,1, 1); //CImgDisplay draw_disp(visu,"smoke"); //while (!draw_disp.is_closed()) //{ // int s = t % 256; // // //visu(128, 128, 0) = 1.0; // draw_disp.display(visu); // t++; //} glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.f,0.f,-32.0f); //glRotatef(rtri,0.0f,1.0f,0.0f); { GLfloat mat_ambient[] = { 1.0, 0.0, 0.0, 1.0 }; GLfloat mat_specular[] = { 0.2, 0.15, 0.15, 1.0 }; GLfloat mat_emissive[] = { 1.0, 0.0, 0.0, 1.0 }; glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_EMISSION, mat_emissive); } for(int s = 0 ; s < 256 ; ++s) { glBegin(GL_QUADS); for(int i = 0 ; i < 256-1 ; ++i) { for(int j = 0 ; j < 256-1 ; ++j) { //unsigned char tmp = density[i + j* 256* 256 + s * 256] * 255.0; //visu(j, i, 0) = tmp; //glNormal3f( Anx, Any, Anz); glVertexf((j+0) * hz ,(i+0)*hz , s* hz); glColor4f(radiance[(i+0) + (j+0) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256]); glVertex3f((j+0) * hz ,(i+1)*hz , s* hz); glColor4f(radiance[(i+1) + (j+0) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256]); glVertex3f((j+1) * hz ,(i+1)*hz , s* hz); glColor4f(radiance[(i+1) + (j+1) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256]); glVertex3f((j+1) * hz ,(i+0)*hz , s* hz); glColor4f(radiance[(i+0) + (j+1) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256], radiance[(i+0) + (j+0) * 256 * 256 + s*256]); } } glEnd(); } rtri+=0.2f; return TRUE; } GLvoid KillGLWindow(GLvoid) { if (fullscreen) { ChangeDisplaySettings(NULL,0); ShowCursor(TRUE); } if (hRC) { if (!wglMakeCurrent(NULL,NULL)) { MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC? { MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } hRC=NULL; // Set RC To NULL } if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC { MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hDC=NULL; // Set DC To NULL } if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window? { MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hWnd=NULL; // Set hWnd To NULL } if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class { MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hInstance=NULL; // Set hInstance To NULL } } BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; RECT WindowRect; WindowRect.left=(long)0; WindowRect.right=(long)width; WindowRect.top=(long)0; WindowRect.bottom=(long)height; fullscreen=fullscreenflag; hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL"; if (!RegisterClass(&wc)) { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (fullscreen) { DEVMODE dmScreenSettings; memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); dmScreenSettings.dmSize=sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = bits; dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (fullscreen) { dwExStyle=WS_EX_APPWINDOW; dwStyle=WS_POPUP; ShowCursor(FALSE); } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle=WS_OVERLAPPEDWINDOW; } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, "OpenGL", title, dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top, NULL, NULL, hInstance, NULL))) { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, bits, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; if (!(hDC=GetDC(hWnd))) { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd,SW_SHOW); SetForegroundWindow(hWnd); SetFocus(hWnd); ReSizeGLScene(width, height); if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success } LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_ACTIVATE: { // LoWord Can Be WA_INACTIVE, WA_ACTIVE, WA_CLICKACTIVE, // The High-Order Word Specifies The Minimized State Of The Window Being Activated Or Deactivated. // A NonZero Value Indicates The Window Is Minimized. if ((LOWORD(wParam) != WA_INACTIVE) && !((BOOL)HIWORD(wParam))) active=TRUE; else active=FALSE; return 0; } case WM_SYSCOMMAND: { switch (wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; } case WM_CLOSE: { PostQuitMessage(0); return 0; } case WM_KEYDOWN: { keys[wParam] = TRUE; return 0; } case WM_KEYUP: { keys[wParam] = FALSE; return 0; } case WM_SIZE: { ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; BOOL done=FALSE; // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("NeHe's Solid Object Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message==WM_QUIT) { done=TRUE; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; } else { SwapBuffers(hDC); } if (keys[VK_F1]) { keys[VK_F1]=FALSE; KillGLWindow(); fullscreen=!fullscreen; // Recreate Our OpenGL Window if (!CreateGLWindow("NeHe's Solid Object Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program } using namespace cimg_library; int main() { SmokeRenderer smoke; smoke.initSmoke(); smoke.render(); std::vector<float> density = smoke.getDensity(); std::vector<float> radiance = smoke.getRadiance(); CImg<unsigned char> visu(256,256,1, 1); CImgDisplay draw_disp(visu,"smoke"); int t = 0; while (!draw_disp.is_closed()) { int s = t % 256; for(int i = 0 ; i < 256 ; ++i) { for(int j = 0 ; j < 256 ; ++j) { unsigned char tmp = density[i + j* 256* 256 + s * 256] * 255.0; visu(j, i, 0) = tmp; } } //visu(128, 128, 0) = 1.0; draw_disp.display(visu); t++; } return 0; }
[ "Student@Starcraft.(none)" ]
[ [ [ 1, 524 ] ] ]
30d3340ae2573f7d014a2cf3acf58e1797516540
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/applications/newtonDemos/sdkDemos/demos/SimpleConvexShatter.cpp
62d376170422a4bce9e318e5569039672a06df0e
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
18,132
cpp
/* Copyright (c) <2009> <Newton Game Dynamics> * * 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 */ #include <toolbox_stdafx.h> #include "SkyBox.h" #include "TargaToOpenGl.h" #include "../DemoMesh.h" #include "../DemoEntityManager.h" #include "../DemoCamera.h" #include "../PhysicsUtils.h" #define INITIAL_DELAY 1000 //#define INITIAL_DELAY 0 #define NUMBER_OF_ITERNAL_PARTS 10 #define BREAK_FORCE_IN_GRAVITIES 10 //#define BREAK_FORCE_IN_GRAVITIES 1 #if 0 static void CreateSimpleVoronoiShatter (DemoEntityManager* const scene) { // create a collision primitive // dVector size (2.0f, 2.0f, 2.0f); // dVector size = dVector (10.0f, 0.5f, 10.0f, 0.0f); dVector size = dVector (5.0f, 5.0f, 5.0f, 0.0f); NewtonWorld* const world = scene->GetNewton(); // NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _BOX_PRIMITIVE, 0); NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _CAPSULE_PRIMITIVE, 0); // NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _SPHERE_PRIMITIVE, 0); // NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _REGULAR_CONVEX_HULL_PRIMITIVE, 0); // NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _RANDOM_CONVEX_HULL_PRIMITIVE, 0); // create a newton mesh from the collision primitive NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision); // apply a simple Box Mapping int tex0 = LoadTexture("reljef.tga"); NewtonMeshApplyBoxMapping(mesh, tex0, tex0, tex0); // pepper the bing box of the mesh with random points dVector points[NUMBER_OF_ITERNAL_PARTS + 100]; int count = 0; while (count < NUMBER_OF_ITERNAL_PARTS) { dFloat x = RandomVariable(size.m_x); dFloat y = RandomVariable(size.m_y); dFloat z = RandomVariable(size.m_z); if ((x <= size.m_x) && (x >= -size.m_x) && (y <= size.m_y) && (y >= -size.m_y) && (z <= size.m_z) && (z >= -size.m_z)){ points[count] = dVector (x, y, z); count ++; } } count = 4; // Create the array of convex pieces from the mesh int interior = LoadTexture("KAMEN-stup.tga"); // int interior = LoadTexture("camo.tga"); dMatrix textureMatrix (GetIdentityMatrix()); textureMatrix[0][0] = 1.0f / size.m_x; textureMatrix[1][1] = 1.0f / size.m_y; NewtonMesh* const convexParts = NewtonMeshVoronoiDecomposition (mesh, count, sizeof (dVector), &points[0].m_x, interior, &textureMatrix[0][0]); // NewtonMesh* const convexParts = NewtonMeshConvexDecomposition (mesh, 1000000); #if 1 dScene xxxx(world); dScene::dTreeNode* const modelNode = xxxx.CreateSceneNode(xxxx.GetRootNode()); dScene::dTreeNode* const meshNode = xxxx.CreateMeshNode(modelNode); dMeshNodeInfo* const modelMesh = (dMeshNodeInfo*)xxxx.GetInfoFromNode(meshNode); modelMesh->ReplaceMesh (convexParts); xxxx.Serialize("../../../media/xxx.ngd"); #endif DemoEntity* const entity = new DemoEntity(NULL); entity->SetMatrix(*scene, dQuaternion(), dVector (0, 10, 0, 0)); entity->InterpolateMatrix (*scene, 1.0f); scene->Append (entity); DemoMesh* const mesh1 = new DemoMesh(convexParts); entity->SetMesh(mesh1); mesh1->Release(); /* DemoEntity* const entity2 = new DemoEntity(NULL); entity2->SetMatrix(*scene, dQuaternion(), dVector (0, 10, 0, 0)); entity2->InterpolateMatrix (*scene, 1.0f); scene->Append (entity2); DemoMesh* const mesh2 = new DemoMesh(mesh); entity2->SetMesh(mesh2); mesh2->Release(); */ // make sure the assets are released before leaving the function if (convexParts) { NewtonMeshDestroy (convexParts); } NewtonMeshDestroy (mesh); NewtonReleaseCollision(world, collision); } #endif class ShatterAtom { public: DemoMesh* m_mesh; NewtonCollision* m_collision; dVector m_centerOfMass; dVector m_momentOfInirtia; dFloat m_massFraction; }; class ShatterEffect: public dList<ShatterAtom> { public: ShatterEffect(NewtonWorld* const world, NewtonMesh* const mesh, int interiorMaterial) :dList<ShatterAtom>(), m_world (world) { // first we populate the bounding Box area with few random point to get some interior subdivisions. // the subdivision are local to the point placement, by placing these points visual ally with a 3d tool // and have precise control of how the debris are created. // the number of pieces is equal to the number of point inside the Mesh plus the number of point on the mesh dVector size; dMatrix matrix(GetIdentityMatrix()); NewtonMeshCalculateOOBB(mesh, &matrix[0][0], &size.m_x, &size.m_y, &size.m_z); // pepper the inside of the BBox box of the mesh with random points int count = 0; dVector points[NUMBER_OF_ITERNAL_PARTS + 1]; while (count < NUMBER_OF_ITERNAL_PARTS) { dFloat x = RandomVariable(size.m_x); dFloat y = RandomVariable(size.m_y); dFloat z = RandomVariable(size.m_z); if ((x <= size.m_x) && (x >= -size.m_x) && (y <= size.m_y) && (y >= -size.m_y) && (z <= size.m_z) && (z >= -size.m_z)){ points[count] = dVector (x, y, z); count ++; } } // create a texture matrix, for applying the material's UV to all internal faces dMatrix textureMatrix (GetIdentityMatrix()); textureMatrix[0][0] = 1.0f / size.m_x; textureMatrix[1][1] = 1.0f / size.m_y; // now we call create we decompose the mesh into several convex pieces NewtonMesh* const debriMeshPieces = NewtonMeshVoronoiDecomposition (mesh, count, sizeof (dVector), &points[0].m_x, interiorMaterial, &textureMatrix[0][0]); // Get the volume of the original mesh NewtonCollision* const collision = NewtonCreateConvexHullFromMesh (m_world, mesh, 0.0f, 0); dFloat volume = NewtonConvexCollisionCalculateVolume (collision); NewtonReleaseCollision(m_world, collision); // now we iterate over each pieces and for each one we create a visual entity and a rigid body NewtonMesh* nextDebri; for (NewtonMesh* debri = NewtonMeshCreateFirstLayer (debriMeshPieces); debri; debri = nextDebri) { nextDebri = NewtonMeshCreateNextLayer (debriMeshPieces, debri); NewtonCollision* const collision = NewtonCreateConvexHullFromMesh (m_world, debri, 0.0f, 0); if (collision) { ShatterAtom& atom = Append()->GetInfo(); atom.m_mesh = new DemoMesh(debri); atom.m_collision = collision; NewtonConvexCollisionCalculateInertialMatrix (atom.m_collision, &atom.m_momentOfInirtia[0], &atom.m_centerOfMass[0]); dFloat debriVolume = NewtonConvexCollisionCalculateVolume (atom.m_collision); atom.m_massFraction = debriVolume / volume; } NewtonMeshDestroy(debri); } NewtonMeshDestroy(debriMeshPieces); } ShatterEffect (const ShatterEffect& list) :dList<ShatterAtom>(), m_world(list.m_world) { for (dListNode* node = list.GetFirst(); node; node = node->GetNext()) { ShatterAtom& atom = Append(node->GetInfo())->GetInfo(); atom.m_mesh->AddRef(); NewtonAddCollisionReference (atom.m_collision); } } ~ShatterEffect() { for (dListNode* node = GetFirst(); node; node = node->GetNext()) { ShatterAtom& atom = node->GetInfo(); NewtonReleaseCollision (m_world, atom.m_collision); atom.m_mesh->Release(); } } NewtonWorld* m_world; }; class SimpleShatterEffectEntity: public DemoEntity { public: SimpleShatterEffectEntity (DemoMesh* const mesh, const ShatterEffect& columnDebris) :DemoEntity (NULL), m_delay (INITIAL_DELAY), m_effect(columnDebris), m_myBody(NULL) { SetMesh(mesh); } ~SimpleShatterEffectEntity () { } void SimulationLister(DemoEntityManager* const scene, DemoEntityManager::dListNode* const mynode, dFloat timeStep) { m_delay --; if (m_delay > 0) { return; } // see if the net force on the body comes fr a high impact collision dFloat maxInternalForce = 0.0f; for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint(m_myBody); joint; joint = NewtonBodyGetNextContactJoint(m_myBody, joint)) { for (void* contact = NewtonContactJointGetFirstContact (joint); contact; contact = NewtonContactJointGetNextContact (joint, contact)) { //dVector point; //dVector normal; dVector contactForce; NewtonMaterial* const material = NewtonContactGetMaterial (contact); //NewtonMaterialGetContactPositionAndNormal (material, &point.m_x, &normal.m_x); NewtonMaterialGetContactForce(material, m_myBody, &contactForce[0]); dFloat forceMag = contactForce % contactForce; if (forceMag > maxInternalForce) { maxInternalForce = forceMag; } } } // if the force is bigger than 4 Gravities, It is considered a collision force dFloat maxForce = BREAK_FORCE_IN_GRAVITIES * m_myweight; if (maxInternalForce > (maxForce * maxForce)) { NewtonWorld* const world = NewtonBodyGetWorld(m_myBody); dFloat Ixx; dFloat Iyy; dFloat Izz; dFloat mass; NewtonBodyGetMassMatrix(m_myBody, &mass, &Ixx, &Iyy, &Izz); dVector com; dVector veloc; dVector omega; dMatrix bodyMatrix; NewtonBodyGetVelocity(m_myBody, &veloc[0]); NewtonBodyGetOmega(m_myBody, &omega[0]); NewtonBodyGetCentreOfMass(m_myBody, &com[0]); NewtonBodyGetMatrix(m_myBody, &bodyMatrix[0][0]); com = bodyMatrix.TransformVector (com); dMatrix matrix (GetCurrentMatrix()); dQuaternion rotation (matrix); for (ShatterEffect::dListNode* node = m_effect.GetFirst(); node; node = node->GetNext()) { ShatterAtom& atom = node->GetInfo(); DemoEntity* const entity = new DemoEntity (NULL); entity->SetMesh (atom.m_mesh); entity->SetMatrix(*scene, rotation, matrix.m_posit); entity->InterpolateMatrix (*scene, 1.0f); scene->Append(entity); int materialId = 0; dFloat debriMass = mass * atom.m_massFraction; dFloat Ixx = debriMass * atom.m_momentOfInirtia.m_x; dFloat Iyy = debriMass * atom.m_momentOfInirtia.m_y; dFloat Izz = debriMass * atom.m_momentOfInirtia.m_z; //create the rigid body NewtonBody* const rigidBody = NewtonCreateBody (world, atom.m_collision, &matrix[0][0]); // set the correct center of gravity for this body NewtonBodySetCentreOfMass (rigidBody, &atom.m_centerOfMass[0]); // calculate the center of mas of the debris dVector center (matrix.TransformVector(atom.m_centerOfMass)); // calculate debris initial velocity dVector v (veloc + omega * (center - com)); // set initial velocity NewtonBodySetVelocity(rigidBody, &v[0]); NewtonBodySetOmega(rigidBody, &omega[0]); // set the debrie center of mass NewtonBodySetCentreOfMass (rigidBody, &atom.m_centerOfMass[0]); // set the mass matrix NewtonBodySetMassMatrix (rigidBody, debriMass, Ixx, Iyy, Izz); // activate // NewtonBodyCoriolisForcesMode (blockBoxBody, 1); // save the pointer to the graphic object with the body. NewtonBodySetUserData (rigidBody, entity); // assign the wood id NewtonBodySetMaterialGroupID (rigidBody, materialId); // set continue collision mode // NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode); // set a destructor for this rigid body NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor); // set the transform call back function NewtonBodySetTransformCallback (rigidBody, DemoEntity::SetTransformCallback); // set the force and torque call back function NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce); } NewtonDestroyBody(world, m_myBody); scene->RemoveEntity (mynode); } }; int m_delay; ShatterEffect m_effect; NewtonBody* m_myBody; dFloat m_myweight; }; static void AddShatterEntity (DemoEntityManager* const scene, DemoMesh* const visualMesh, NewtonCollision* const collision, const ShatterEffect& shatterEffect, dVector location) { dQuaternion rotation; SimpleShatterEffectEntity* const entity = new SimpleShatterEffectEntity (visualMesh, shatterEffect); entity->SetMatrix(*scene, rotation, location); entity->InterpolateMatrix (*scene, 1.0f); scene->Append(entity); dVector origin; dVector inertia; NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]); float mass = 10.0f; int materialId = 0; dFloat Ixx = mass * inertia[0]; dFloat Iyy = mass * inertia[1]; dFloat Izz = mass * inertia[2]; //create the rigid body dMatrix matrix (GetIdentityMatrix()); matrix.m_posit = location; NewtonWorld* const world = scene->GetNewton(); NewtonBody* const rigidBody = NewtonCreateBody (world, collision, &matrix[0][0]); entity->m_myBody = rigidBody; entity->m_myweight = dAbs (mass * DEMO_GRAVITY); // set the correct center of gravity for this body NewtonBodySetCentreOfMass (rigidBody, &origin[0]); // set the mass matrix NewtonBodySetMassMatrix (rigidBody, mass, Ixx, Iyy, Izz); // activate // NewtonBodyCoriolisForcesMode (blockBoxBody, 1); // save the pointer to the graphic object with the body. NewtonBodySetUserData (rigidBody, entity); // assign the wood id NewtonBodySetMaterialGroupID (rigidBody, materialId); // set continue collision mode // NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode); // set a destructor for this rigid body NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor); // set the transform call back function NewtonBodySetTransformCallback (rigidBody, DemoEntity::SetTransformCallback); // set the force and torque call back function NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce); } static void AddShatterPrimitive (DemoEntityManager* const scene, dFloat mass, const dVector& origin, const dVector& size, int xCount, int zCount, dFloat spacing, PrimitiveType type, int materialID) { dMatrix matrix (GetIdentityMatrix()); // create the shape and visual mesh as a common data to be re used NewtonWorld* const world = scene->GetNewton(); NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, type, materialID); // create a newton mesh from the collision primitive NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision); // apply a material map int externalMaterial = LoadTexture("reljef.tga"); int internalMaterial = LoadTexture("KAMEN-stup.tga"); NewtonMeshApplyBoxMapping(mesh, externalMaterial, externalMaterial, externalMaterial); // create a newton mesh from the collision primitive ShatterEffect shatter (world, mesh, internalMaterial); DemoMesh* const visualMesh = new DemoMesh(mesh); for (int i = 0; i < xCount; i ++) { dFloat x = origin.m_x + (i - xCount / 2) * spacing; for (int j = 0; j < zCount; j ++) { dFloat z = origin.m_z + (j - zCount / 2) * spacing; matrix.m_posit.m_x = x; matrix.m_posit.m_z = z; matrix.m_posit.m_y = FindFloor (world, x, z) + 4.0f; AddShatterEntity (scene, visualMesh, collision, shatter, matrix.m_posit); } } // do not forget to release the assets NewtonMeshDestroy (mesh); visualMesh->Release(); NewtonReleaseCollision(world, collision); } void xxxxx (NewtonWorld* const world) { NewtonCollision* const collision = NewtonCreateTreeCollision(world, 0); NewtonTreeCollisionBeginBuild(collision); float faces[] = { 32.000000, 26.000000, -1.000000, // Quad 0 32.000000, 26.000000, 0.000000, 32.000000, 25.000000, 0.000000, 32.000000, 25.000000, -1.000000}; NewtonTreeCollisionAddFace(collision, 4, &faces[0], 3 * sizeof (float), 0); NewtonTreeCollisionEndBuild(collision, 0); NewtonReleaseCollision(world, collision); } void SimpleConvexShatter (DemoEntityManager* const scene) { // suspend simulation before making changes to the physics world scene->StopsExecution (); // load the skybox scene->Append(new SkyBox()); xxxxx(scene->GetNewton()); // load the scene from and alchemedia file format CreateLevelMesh (scene, "flatPlane.ngd", false); // CreateLevelMesh (scene, "sponza.ngd", false); // CreateLevelMesh (scene, "sponza.ngd", true); // create a shattered mesh array //CreateSimpleVoronoiShatter (scene); int defaultMaterialID = NewtonMaterialGetDefaultGroupID (scene->GetNewton()); dVector location (0.0f, 0.0f, 0.0f, 0.0f); dVector size (0.5f, 0.5f, 0.5f, 0.0f); int count = 5; AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _BOX_PRIMITIVE, defaultMaterialID); AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _REGULAR_CONVEX_HULL_PRIMITIVE, defaultMaterialID); AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _RANDOM_CONVEX_HULL_PRIMITIVE, defaultMaterialID); AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _SPHERE_PRIMITIVE, defaultMaterialID); AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _CYLINDER_PRIMITIVE, defaultMaterialID); AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _CONE_PRIMITIVE, defaultMaterialID); AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _CAPSULE_PRIMITIVE, defaultMaterialID); //for (int i = 0; i < 1; i ++) //AddShatterPrimitive(scene, 10.0f, location, size, count, count, 1.7f, _REGULAR_CONVEX_HULL_PRIMITIVE, defaultMaterialID); // place camera into position dQuaternion rot; // dVector origin (-40.0f, 10.0f, 0.0f, 0.0f); dVector origin (-15.0f, 10.0f, 0.0f, 0.0f); scene->SetCameraMatrix(rot, origin); // resume the simulation scene->ContinueExecution(); }
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 518 ] ] ]
e88aabe41ab3cb8a9a75bb5fc036b1a70e1267e2
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Main/SceneManager.cpp
63f8077cbb8f4f1ec9876af3be34ab4645596847
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
23,891
cpp
#include "SceneManager.h" #include "Camera.h" #include "SceneNode.h" #include "Cell.h" #include "SectorNode.h" #include "BoundingBox.h" #include "Portal.h" #include "SceneCuller.h" #include "LightCuller.h" #include "RenderQueue.h" #include "Renderer.h" #include "RenderTarget.h" #include "RenderWindow.h" #include "Light.h" #include "AnimEntity.h" #include "DataCenter.h" #include "ResourceManager.h" namespace Flagship { SceneManager * SceneManager::m_pSceneManager = NULL; SceneManager::SceneManager() { m_pRootNode = NULL; m_pSceneCuller = new SceneCuller; m_pLightCuller = new LightCuller; m_dwCurFrame = 0; m_szNodeName = L"SceneNode"; m_iCurIndexX = 0; m_iCurIndexZ = 0; m_iHeight = 0; m_iSizeX = 0; m_iSizeZ = 0; } SceneManager::~SceneManager() { SAFE_DELETE( m_pRootNode ); SAFE_DELETE( m_pSceneCuller ); SAFE_DELETE( m_pLightCuller ); SAFE_DELETE( m_pSceneManager ); for ( int i = 0; i < m_iSizeX; i++ ) { SAFE_DELETE_ARRAY( m_ppCell[i] ); } } SceneManager * SceneManager::GetSingleton() { if ( m_pSceneManager == NULL ) { m_pSceneManager = new SceneManager; } return m_pSceneManager; } void SceneManager::SetThreadInfo( HANDLE hThread, DWORD dwThreadID ) { m_hThread = hThread; m_dwThreadID = dwThreadID; } void SceneManager::BuildScene( int iSizeX, int iSizeZ, int iHeight ) { m_iHeight = iHeight; m_iSizeX = iSizeX; m_iSizeZ = iSizeZ; m_ppCell = new Cell * [iSizeX]; for ( int i = 0; i < iSizeX; i++ ) { m_ppCell[i] = new Cell [iSizeZ]; for ( int j = 0; j < iSizeZ; j++ ) { Vector3f vCenter( ( i + 0.5f ) * CELL_SIZE, 0.0f, ( j + 0.5f ) * CELL_SIZE ); Vector3f avAxis[3] = { Vector3f::UNIT_X, Vector3f::UNIT_Y, Vector3f::UNIT_Z }; float afExtent[3] = { CELL_SIZE / 2.0f, (float) iHeight, CELL_SIZE / 2.0f }; BoundingBox kBox( vCenter, avAxis, afExtent ); wchar_t szI[8]; wchar_t szJ[8]; wsprintf( szI, L"%d", i ); wsprintf( szJ, L"%d", j ); wstring szCellName = L"Cell_"; szCellName += szI; szCellName += L'_'; szCellName += szJ; m_ppCell[i][j].SetName( szCellName ); m_ppCell[i][j].SetIndex( i, j ); m_ppCell[i][j].SetBound( &kBox ); } } m_pRootNode = _SplitScene( CELL_VIEW, CELL_SIZE * CELL_VIEW / 2, CELL_SIZE * CELL_VIEW / 2 ); } bool SceneManager::PreLoad( Camera * pCamera ) { // 获取当前摄像机位置的单元 Vector4f * pPos = DataCenter::GetSingleton()->GetVectorData( pCamera, pCamera->GetClassType(), CameraData::Vector4_Position )->Read(); int iIndexX = ( (int) pPos->X() + CELL_SIZE / 2 ) / CELL_SIZE; int iIndexZ = ( (int) pPos->Z() + CELL_SIZE / 2 ) / CELL_SIZE; // 判断位置是否合法 if ( iIndexX < CELL_VIEW / 2 ) { iIndexX = CELL_VIEW / 2; } if ( iIndexX > m_iSizeX - CELL_VIEW / 2 ) { iIndexX = m_iSizeX - CELL_VIEW / 2; } if ( iIndexZ < CELL_VIEW / 2 ) { iIndexZ = CELL_VIEW / 2; } if ( iIndexZ > m_iSizeZ - CELL_VIEW / 2 ) { iIndexZ = m_iSizeZ - CELL_VIEW / 2; } // 设置当前索引 m_iCurIndexX = iIndexX; m_iCurIndexZ = iIndexZ; // 加载资源 for ( int i = 0; i < CELL_VIEW; i++ ) { for ( int j = 0; j < CELL_VIEW; j++ ) { int iOffsetX = iIndexX - CELL_VIEW / 2 + i; int iOffsetZ = iIndexZ - CELL_VIEW / 2 + j; m_ppCell[iOffsetX][iOffsetZ].Load(); } } // 重建场景树 map< Vector2f, SceneNode * >::iterator LeafIt = m_mLeafNode.begin(); while ( LeafIt != m_mLeafNode.end() ) { (*LeafIt).second->ClearChild(); LeafIt++; } // 更新包围盒位置 m_pRootNode->UpdateBound( Vector2f( (float) ( iIndexX - CELL_VIEW / 2 ) * CELL_SIZE, (float) ( iIndexZ - CELL_VIEW / 2 ) * CELL_SIZE ) ); for ( int i = 0; i < CELL_VIEW; i++ ) { for ( int j = 0; j < CELL_VIEW; j++ ) { int iOffsetX = iIndexX - CELL_VIEW / 2 + i; int iOffsetZ = iIndexZ - CELL_VIEW / 2 + j; m_mLeafNode[Vector2f( (float) i, (float) j )]->AttechChild( &( m_ppCell[iOffsetX][iOffsetZ] ) ); } } return true; } void SceneManager::SetCuller( SceneCuller * pSceneCuller, LightCuller * pLightCuller ) { m_pSceneCuller = pSceneCuller; m_pLightCuller = pLightCuller; } void SceneManager::_UpdateScene() { // 获取当前摄像机位置的单元 Vector4f * pPos = DataCenter::GetSingleton()->GetVectorData( RenderTarget::GetActiveCamera() , RenderTarget::GetActiveCamera()->GetClassType(), CameraData::Vector4_Position )->Read(); int iIndexX = ( (int) pPos->X() + CELL_SIZE / 2 ) / CELL_SIZE; int iIndexZ = ( (int) pPos->Z() + CELL_SIZE / 2 ) / CELL_SIZE; // 判断位置是否合法 if ( iIndexX < CELL_VIEW / 2 ) { iIndexX = CELL_VIEW / 2; } if ( iIndexX > m_iSizeX - CELL_VIEW / 2 ) { iIndexX = m_iSizeX - CELL_VIEW / 2; } if ( iIndexZ < CELL_VIEW / 2 ) { iIndexZ = CELL_VIEW / 2; } if ( iIndexZ > m_iSizeZ - CELL_VIEW / 2 ) { iIndexZ = m_iSizeZ - CELL_VIEW / 2; } // 当前单元未变,不必更新 if ( m_iCurIndexX == iIndexX && m_iCurIndexZ == iIndexZ ) { return; } // 更新资源 if ( ! _ResourceTravel( Vector2f( pPos->X(), pPos->Z() ) ) ) { return; } // 重建场景树 map< Vector2f, SceneNode * >::iterator LeafIt = m_mLeafNode.begin(); while ( LeafIt != m_mLeafNode.end() ) { (*LeafIt).second->ClearChild(); LeafIt++; } // 更新包围盒位置 m_pRootNode->UpdateBound( Vector2f( (float) ( iIndexX - CELL_VIEW / 2 ) * CELL_SIZE, (float) ( iIndexZ - CELL_VIEW / 2 ) * CELL_SIZE ) ); for ( int i = 0; i < CELL_VIEW; i++ ) { for ( int j = 0; j < CELL_VIEW; j++ ) { int iOffsetX = iIndexX - CELL_VIEW / 2 + i; int iOffsetZ = iIndexZ - CELL_VIEW / 2 + j; m_mLeafNode[Vector2f( (float) i, (float) j )]->AttechChild( &( m_ppCell[iOffsetX][iOffsetZ] ) ); } } } void SceneManager::TravelScene() { // 查询当前渲染器 Renderer * pRenderer = RenderTarget::GetActiveRenderTarget()->GetRenderer(); m_dwCurFrame ++; // 更新场景树 if ( RenderTarget::GetActiveRenderTarget()->GetClassType() == Base::RenderTarget_Window ) { _UpdateScene(); } // 从根节点开始遍历 if ( m_pRootNode != NULL && m_pSceneCuller != NULL && m_pLightCuller != NULL && pRenderer != NULL ) { // 初始化裁剪器 m_pSceneCuller->Clear(); m_pSceneCuller->Initialize( RenderTarget::GetActiveCamera() ); // 遍历场景树 _VisibleTravel( m_pRootNode, pRenderer ); // 遮挡剪裁 _CollideTravel( pRenderer ); if ( pRenderer->GetRenderType() != Renderer::RenderType_Shadow ) { multimap< float, Entity * > * pVisibleList = pRenderer->GetRenderQueue( Renderer::RenderQueue_Light )->GetEntityList(); multimap< float, Entity * >::iterator it; int iTempCount = 0; for ( it = pVisibleList->begin(); it != pVisibleList->end(); it++ ) { if ( iTempCount >= MAX_LIGHT ) { break; } Light * pCurLight = (Light *) (*it).second; // 初始化剪裁器 m_pLightCuller->Clear(); m_pLightCuller->Initialize( pCurLight ); pRenderer->GetRenderQueue( Renderer::RenderQueue_Bright )->Clear(); pCurLight->GetEntityList()->clear(); // 遍历场景树 _LightTravel( m_pRootNode, pRenderer, (Light *) (*it).second ); // 遮挡剪裁 _BrightTravel( pRenderer, (Light *) (*it).second ); iTempCount++; } } } } Cell * SceneManager::_FindCell( Cell * pParent, Vector3f& vPos ) { map<Key, SceneNode* > * pChildMap = pParent->GetChildMap(); if ( pChildMap->size() == 0 ) { return pParent; } map<Key, SceneNode* >::iterator ChildIt; for ( ChildIt = pChildMap->begin(); ChildIt != pChildMap->end(); ChildIt++ ) { if ( (*ChildIt).second->GetBound()->IsInBound( vPos ) ) { return _FindCell( (Cell *) (*ChildIt).second, vPos ); } } return NULL; } Cell * SceneManager::GetCell( Vector3f& vPos ) { int iIndexX = (int) vPos.X() / CELL_SIZE; int iIndexZ = (int) vPos.Z() / CELL_SIZE; return _FindCell( &m_ppCell[iIndexX][iIndexZ], vPos ); } void SceneManager::AddEntity( Entity * pEntity, Matrix4f& matWorld, bool bInit ) { switch ( pEntity->GetClassType() ) { case Base::Class_Entity: { ( (MatrixData *) ( (EntityData *) pEntity->GetSharedData() )->m_pData[EntityData::Matrix4_World] )->Write( matWorld ); break; } case Base::Entity_AnimEntity: { ( (MatrixData *) ( (AnimEntityData *) pEntity->GetSharedData() )->m_pData[AnimEntityData::Matrix4_World] )->Write( matWorld ); break; } case Base::Entity_Light: { ( (MatrixData *) ( (LightData *) pEntity->GetSharedData() )->m_pData[LightData::Matrix4_World] )->Write( matWorld ); break; } } if ( bInit ) { pEntity->UpdateScene(); } else { PostThreadMessage( GetThreadID(), WM_ADDENTITY, (WPARAM) pEntity, 0 ); } } void SceneManager::DelEntity( Entity * pEntity ) { PostThreadMessage( GetThreadID(), WM_DELENTITY, (WPARAM) pEntity, 0 ); } bool SceneManager::MessageProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch ( uMsg ) { case WM_ADDENTITY: { ( (Entity *) wParam )->Load(); ( (Entity *) wParam )->UpdateScene(); break; } case WM_UPDATEENTITY: { ( (Entity *) wParam )->UpdateScene(); break; } case WM_DELENTITY: { Entity * pEntity = (Entity *) wParam; if ( ! pEntity->IsReady() ) { return false; } else { Cell * pCell = ( pEntity )->GetParent(); pCell->DetachEntity( pEntity ); SAFE_DELETE( pEntity ); } break; } default: { break; } } return true; } SceneNode * SceneManager::_SplitScene( int iSize, int iPosX, int iPosZ ) { if ( iSize == 2 ) { int iIndexX = iPosX / CELL_SIZE; int iIndexZ = iPosZ / CELL_SIZE; SceneNode * pLeafNode = new SceneNode( m_szNodeName ); ( (BoundingBox *) ( pLeafNode->GetBound() ) )->SetCenter( Vector3f( (float) iPosX, 0.0f, (float) iPosZ ) ); float fExtent[3] = { (float) CELL_SIZE, (float) m_iHeight, (float) CELL_SIZE }; ( (BoundingBox *) ( pLeafNode->GetBound() ) )->SetExtent( fExtent ); m_mLeafNode[Vector2f( (float) ( iIndexX - 1 ), (float) ( iIndexZ - 1 ) )] = pLeafNode; m_mLeafNode[Vector2f( (float) ( iIndexX - 1 ), (float) iIndexZ )] = pLeafNode; m_mLeafNode[Vector2f( (float) iIndexX, (float) ( iIndexZ - 1 ) )] = pLeafNode; m_mLeafNode[Vector2f( (float) iIndexX, (float) iIndexZ )] = pLeafNode; return pLeafNode; } SceneNode * pNewNode = new SceneNode( m_szNodeName ); SceneNode * pSplitNode[4]; m_szNodeName += L"_0"; pSplitNode[0] = _SplitScene( iSize / 2, iPosX / 2, iPosZ / 2 ); m_szNodeName.erase( m_szNodeName.length() - 2, 2 ); m_szNodeName += L"_1"; pSplitNode[1] = _SplitScene( iSize / 2, iPosX / 2, iPosZ + iPosZ / 2 ); m_szNodeName.erase( m_szNodeName.length() - 2, 2 ); m_szNodeName += L"_2"; pSplitNode[2] = _SplitScene( iSize / 2, iPosX + iPosX / 2, iPosZ / 2 ); m_szNodeName.erase( m_szNodeName.length() - 2, 2 ); m_szNodeName += L"_3"; pSplitNode[3] = _SplitScene( iSize / 2, iPosX + iPosX / 2, iPosZ + iPosZ / 2 ); m_szNodeName.erase( m_szNodeName.length() - 2, 2 ); for ( int i = 0; i < 4; i++ ) { pNewNode->AttechChild( pSplitNode[i] ); } ( (BoundingBox *) ( pNewNode->GetBound() ) )->SetCenter( Vector3f( (float) iPosX, 0.0f, (float) iPosZ ) ); float fExtent[3] = { (float) iSize * CELL_SIZE / 2, (float) m_iHeight, (float) iSize * CELL_SIZE / 2 }; ( (BoundingBox *) ( pNewNode->GetBound() ) )->SetExtent( fExtent ); return pNewNode; } bool SceneManager::_ResourceTravel( Vector2f& vPos ) { Vector2f vCurCenter( (float) m_iCurIndexX * CELL_SIZE, (float) m_iCurIndexZ * CELL_SIZE ); Vector2f vOffset( vPos.X() - vCurCenter.X(), vPos.Y() - vCurCenter.Y() ); vector< Cell * > pLoadCell; vector< Cell * > pDelCell; // 右上角单元 if ( (int) vOffset.X() > CELL_SIZE && (int) vOffset.Y() > CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadZ = m_iCurIndexZ - CELL_VIEW / 2 + i; m_ppCell[m_iCurIndexX + CELL_VIEW / 2][iLoadZ + 1].Load(); m_ppCell[m_iCurIndexX - CELL_VIEW / 2][iLoadZ].Release(); } for ( int i = 0; i < CELL_VIEW - 1; i++ ) { int iLoadX = m_iCurIndexX - CELL_VIEW / 2 + i; m_ppCell[iLoadX + 1][m_iCurIndexZ + CELL_VIEW / 2].Load(); m_ppCell[iLoadX + 1][m_iCurIndexZ - CELL_VIEW / 2].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 右下角单元 if ( (int) vOffset.X() > CELL_SIZE && (int) vOffset.Y() < - CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadZ = m_iCurIndexZ - CELL_VIEW / 2 + i; m_ppCell[m_iCurIndexX + CELL_VIEW / 2][iLoadZ - 1].Load(); m_ppCell[m_iCurIndexX - CELL_VIEW / 2][iLoadZ].Release(); } for ( int i = 0; i < CELL_VIEW - 1; i++ ) { int iLoadX = m_iCurIndexX - CELL_VIEW / 2 + i; m_ppCell[iLoadX + 1][m_iCurIndexZ - CELL_VIEW / 2 - 1].Load(); m_ppCell[iLoadX + 1][m_iCurIndexZ + CELL_VIEW / 2 - 1].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 左下角单元 if ( (int) vOffset.X() < - CELL_SIZE && (int) vOffset.Y() < - CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadZ = m_iCurIndexZ - CELL_VIEW / 2 + i; m_ppCell[m_iCurIndexX - CELL_VIEW / 2 - 1][iLoadZ - 1].Load(); m_ppCell[m_iCurIndexX + CELL_VIEW / 2 - 1][iLoadZ].Release(); } for ( int i = 0; i < CELL_VIEW - 1; i++ ) { int iLoadX = m_iCurIndexX - CELL_VIEW / 2 + i; m_ppCell[iLoadX][m_iCurIndexZ - CELL_VIEW / 2 - 1].Load(); m_ppCell[iLoadX][m_iCurIndexZ + CELL_VIEW / 2 - 1].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 左上角单元 if ( (int) vOffset.X() < - CELL_SIZE && (int) vOffset.Y() > CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadZ = m_iCurIndexZ - CELL_VIEW / 2 + i; m_ppCell[m_iCurIndexX - CELL_VIEW / 2][iLoadZ + 1].Load(); m_ppCell[m_iCurIndexX + CELL_VIEW / 2][iLoadZ].Release(); } for ( int i = 0; i < CELL_VIEW - 1; i++ ) { int iLoadX = m_iCurIndexX - CELL_VIEW / 2 + i; m_ppCell[iLoadX][m_iCurIndexZ + CELL_VIEW / 2 - 1].Load(); m_ppCell[iLoadX][m_iCurIndexZ - CELL_VIEW / 2 - 1].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 右侧单元 if ( (int) vOffset.X() > CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadZ = m_iCurIndexZ - CELL_VIEW / 2 + i; m_ppCell[m_iCurIndexX + CELL_VIEW / 2][iLoadZ].Load(); m_ppCell[m_iCurIndexX - CELL_VIEW / 2][iLoadZ].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 左侧单元 if ( (int) vOffset.X() < - CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadZ = m_iCurIndexZ - CELL_VIEW / 2 + i; m_ppCell[m_iCurIndexX - CELL_VIEW / 2 - 1][iLoadZ].Load(); m_ppCell[m_iCurIndexX + CELL_VIEW / 2 - 1][iLoadZ].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 上方单元 if ( (int) vOffset.Y() > CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadX = m_iCurIndexX - CELL_VIEW / 2 + i; m_ppCell[iLoadX][m_iCurIndexZ + CELL_VIEW / 2].Load(); m_ppCell[iLoadX][m_iCurIndexZ - CELL_VIEW / 2].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } // 下方单元 if ( (int) vOffset.Y() < - CELL_SIZE ) { for ( int i = 0; i < CELL_VIEW; i++ ) { int iLoadX = m_iCurIndexX - CELL_VIEW / 2 + i; m_ppCell[iLoadX][m_iCurIndexZ - CELL_VIEW / 2 - 1].Load(); m_ppCell[iLoadX][m_iCurIndexZ + CELL_VIEW / 2 - 1].Release(); } m_iCurIndexX = ( (int) vPos.X() + CELL_SIZE / 2 ) / CELL_SIZE; m_iCurIndexZ = ( (int) vPos.Y() + CELL_SIZE / 2 ) / CELL_SIZE; return true; } return false; } void SceneManager::_VisibleTravel( SceneNode * pSceneNode, Renderer * pRenderer ) { // 获取场景类型 int iSceneType = pSceneNode->GetClassType(); if ( iSceneType == Base::Class_SceneNode ) { // 查询节点的所有子节点 map< Key, SceneNode * >::iterator NodeIt; for ( NodeIt = pSceneNode->GetChildMap()->begin(); NodeIt != pSceneNode->GetChildMap()->end(); ++NodeIt ) { if ( m_pSceneCuller->IsVisible( (*NodeIt).second->GetBound() ) ) { _VisibleTravel( (*NodeIt).second, pRenderer ); } } } if ( iSceneType == Base::SceneNode_Cell || iSceneType == Base::SceneNode_Sector ) { // 实体可见性判断 map< Key, Entity * >::iterator EntityIt; for ( EntityIt = pSceneNode->GetEntityMap()->begin(); EntityIt != pSceneNode->GetEntityMap()->end(); ++EntityIt ) { int iEntityType = (*EntityIt).second->GetClassType(); if ( iEntityType == Base::Entity_Light ) { Light * pLight = (Light *) ( (*EntityIt).second ); if ( pLight->GetOn() && m_pSceneCuller->IsVisible( pLight->GetBound() ) ) { pRenderer->GetRenderQueue( Renderer::RenderQueue_Light )->InsertEntity( pLight ); } } if ( m_pSceneCuller->IsVisible( (*EntityIt).second->GetBound() ) ) { // 加入主渲染队列 pRenderer->GetRenderQueue( Renderer::RenderQueue_General )->InsertEntity( (*EntityIt).second ); } } // 查询节点的所有子节点 map< Key, SceneNode * >::iterator NodeIt; for ( NodeIt = pSceneNode->GetChildMap()->begin(); NodeIt != pSceneNode->GetChildMap()->end(); ++NodeIt ) { if ( m_pSceneCuller->IsVisible( (*NodeIt).second->GetBound() ) ) { _VisibleTravel( (*NodeIt).second, pRenderer ); } } } if ( iSceneType == Base::SceneNode_Sector ) { // 室内节点 SectorNode * pSectorNode = (SectorNode *) pSceneNode; map< Key, Portal * >::iterator PortalIt; for ( PortalIt = pSectorNode->GetPortalMap()->begin(); PortalIt != pSectorNode->GetPortalMap()->end(); ++PortalIt ) { if ( (*PortalIt).second->GetOpen() && m_pSceneCuller->IsVisible( (*PortalIt).second->GetBound() ) ) { // 开始入口剪裁 m_pSceneCuller->PushPortal( (*PortalIt).second ); _VisibleTravel( (*PortalIt).second->GetOppositeNode( pSceneNode ), pRenderer ); // 结束入口剪裁 m_pSceneCuller->PopPortal( 1 ); } } } } void SceneManager::_CollideTravel( Renderer * pRenderer ) { RenderQueue * pQueue = pRenderer->GetRenderQueue( Renderer::RenderQueue_General ); multimap< float, Entity * >::iterator GeneralIt = pQueue->GetEntityList()->begin(); while ( GeneralIt != pQueue->GetEntityList()->end() ) { if ( m_pSceneCuller->IsVisible( (*GeneralIt).second->GetBound() ) ) { if ( (*GeneralIt).second->IsReady() ) { // 加入主渲染队列 pRenderer->GetRenderQueue( Renderer::RenderQueue_Visible )->InsertEntity( (*GeneralIt).second ); (*GeneralIt).second->UpdateFrame(); // 遮挡剪裁 if ( (*GeneralIt).second->GetInnerBound() != NULL ) { m_pSceneCuller->PushEntity( (*GeneralIt).second ); } } else { // 异步加载 (*GeneralIt).second->Load(); } } GeneralIt++; } } void SceneManager::_LightTravel( SceneNode * pSceneNode, Renderer * pRenderer, Light * pLight ) { // 获取场景类型 int iSceneType = pSceneNode->GetClassType(); if ( iSceneType == Base::Class_SceneNode ) { // 查询节点的所有子节点 map< Key, SceneNode * >::iterator NodeIt; for ( NodeIt = pSceneNode->GetChildMap()->begin(); NodeIt != pSceneNode->GetChildMap()->end(); ++NodeIt ) { if ( m_pLightCuller->IsVisible( (*NodeIt).second->GetBound() ) ) { _LightTravel( (*NodeIt).second, pRenderer, pLight ); } } } if ( iSceneType == Base::SceneNode_Cell || iSceneType == Base::SceneNode_Sector ) { // 实体可见性判断 Cell * pCell = (Cell *) pSceneNode; map< Key, Entity * >::iterator EntityIt; for ( EntityIt = pCell->GetEntityMap()->begin(); EntityIt != pCell->GetEntityMap()->end(); ++EntityIt ) { if ( (*EntityIt).second == pLight ) { continue; } if ( (*EntityIt).second->IsReady() && (*EntityIt).second->IsAffectByLight() && m_pLightCuller->IsVisible( (*EntityIt).second->GetBound() ) && (*EntityIt).second->GetLastFrame() == RenderWindow::GetActiveRenderWindow()->GetCurrentFrame() ) { Matrix4f * pLightMatrix = DataCenter::GetSingleton()->GetMatrixData( pLight, pLight->GetClassType(), EntityData::Matrix4_World )->Read(); Vector4f vLightPos = pLightMatrix->GetColumn( 3 ); pRenderer->GetRenderQueue( Renderer::RenderQueue_Bright )->InsertEntity( vLightPos, (*EntityIt).second ); } } // 查询节点的所有子节点 map< Key, SceneNode * >::iterator NodeIt; for ( NodeIt = pCell->GetChildMap()->begin(); NodeIt != pCell->GetChildMap()->end(); ++NodeIt ) { if ( m_pLightCuller->IsVisible( (*NodeIt).second->GetBound() ) ) { _LightTravel( (*NodeIt).second, pRenderer, pLight ); } } } if ( iSceneType == Base::SceneNode_Sector ) { // 室内节点 SectorNode * pSectorNode = (SectorNode *) pSceneNode; map< Key, Portal * >::iterator PortalIt; for ( PortalIt = pSectorNode->GetPortalMap()->begin(); PortalIt != pSectorNode->GetPortalMap()->end(); ++PortalIt ) { if ( (*PortalIt).second->GetOpen() && m_pSceneCuller->IsVisible( (*PortalIt).second->GetBound() ) ) { // 开始入口剪裁 m_pLightCuller->PushPortal( (*PortalIt).second ); _LightTravel( (*PortalIt).second->GetOppositeNode( pSceneNode ), pRenderer, pLight ); // 结束入口剪裁 m_pLightCuller->PopPortal( 1 ); } } } } void SceneManager::_BrightTravel( Renderer * pRenderer, Light * pLight ) { RenderQueue * pQueue = pRenderer->GetRenderQueue( Renderer::RenderQueue_Bright ); multimap< float, Entity * >::iterator BrightIt = pQueue->GetEntityList()->begin(); while ( BrightIt != pQueue->GetEntityList()->end() ) { if ( m_pLightCuller->IsVisible( (*BrightIt).second->GetBound() ) ) { if ( (*BrightIt).second->IsReady() ) { pLight->AttachEntity( (*BrightIt).second ); // 遮挡剪裁 if ( (*BrightIt).second->GetInnerBound() != NULL ) { m_pLightCuller->PushEntity( (*BrightIt).second ); } } } BrightIt++; } } }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 818 ] ] ]
d5b1fe570c9872f3ad86841b917e0ba9ca647100
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ui/src/MovementControlState.cpp
12c143da68ee8774db416f170d4550df06f87ba1
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
60,158
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" #include "MovementControlState.h" #include <utility> #include "AbstractMovement.h" #include "Actor.h" #include "ActorManager.h" #include "CameraObject.h" #include "CommandMapper.h" #include "ConfigurationManager.h" #include "CoreSubsystem.h" #include "Creature.h" #include "CreatureControllerManager.h" #include "DebugWindow.h" #include "Exception.h" #include "GameObjectManager.h" #include "InputManager.h" #include "Logger.h" #include "MeshObject.h" #include "MeshAnimation.h" #include "MovementControlState.h" #include "PhysicsManager.h" #include "PhysicsMaterialRaycast.h" #include "PhysicalThing.h" #include "RulesMessages.h" #include "World.h" #include "LineSetPrimitive.h" #include "WindowFactory.h" #include "AnimationManager.h" #include "UiSubsystem.h" #include "WindowManager.h" #include <numeric> using namespace Ogre; namespace rl { Ogre::String MovementControlState::msDebugWindowPageName = "MovementControlState"; MovementControlState::CharacterState::CharacterState() : mCurrentMovementState(MOVE_NONE), mLastMovementState(MOVE_NONE) { } MovementControlState::MovementControlState(CommandMapper* cmdMapper, Actor* camera, Creature* character) : ControlState(cmdMapper, camera, character, CST_MOVEMENT), mController(NULL), mCharacterState(), mDesiredDistance(2.00), mDistanceRange(0.60, 7.00), mCamYaw(0), mCamVirtualYaw(0), mNewCamVirtualYaw(0), mPitch(20), mRoll(0), mPitchRange(Degree(-75), Degree(85)), mLinearSpringK(400.0f), mLinearDampingK(Math::NEG_INFINITY), mCamMoveAwayVelocity(4.0f), mCamMoveAwayStartTime(0.25f), mCamMoveAwayRange(8.0f), mLookAtOffset(), mRotationSpeed(Degree(120.0f)), mMouseSensitivity(4.0f), mViewMode(VM_THIRD_PERSON), mRaycast(new PhysicsMaterialRaycast()), mConvexcast(new PhysicsMaterialConvexcast()), mCameraCastCollision(NULL), mSelector(CoreSubsystem::getSingleton().getWorld()->getSceneManager()), mCombatSelector(CoreSubsystem::getSingleton().getWorld()->getSceneManager(), QUERYFLAG_CREATURE), mCharPositionsBuffer(100), mCharPositionsBufferIdx(-1), mCharacterOccludedTime(0), mCharacterOccludedFrameCount(0), mLastDistance(0.0f), mTimeOfLastCollision(0.0f), mIsPathfinding (false), mLastReachableBufPos(1), mLastCameraCollision(0) { DebugWindow::getSingleton().registerPage(msDebugWindowPageName); mMouseSensitivity = ConfigurationManager::getSingleton().getIntSetting("Input", "Mouse Sensitivity"); mInvertedMouse = ConfigurationManager::getSingleton().getBoolSetting("Input", "Mouse Invert"); // The relationCoefficient determines the relation between spring accel in target direction // and damping in velocity direction. 1.0 means equilibrium is reached in optimal time // smaller 1.0 means spring accel is stronger and thus cam shoots over the target, resulting // in a damped ozillation before reaching equilibrium. // Values greater than 1.0 mean damping is stronger and thus camera takes a detour. Real relationCoefficient = 0.8f; mLinearDampingK = relationCoefficient * 2.0f * Math::Sqrt(mLinearSpringK); // Offset for the look at point, // so the cam does look at the characters head instead of the feet. MeshObject* charMesh = dynamic_cast<MeshObject*>( mCharacterActor->getControlledObject()); AxisAlignedBox aabb = charMesh->getDefaultSize(); // this will be recalculated in calculateOptimalCameraPosition mLookAtOffset = Vector3(0, (aabb.getMaximum() - aabb.getMinimum()).y * 0.45f, 0); CreatureSelectionFilter* filter = new CreatureSelectionFilter(); filter->setAlignmentMask(Creature::ALIGNMENT_ENEMY); mCombatSelector.setFilter(filter); mSelector.setFilter(new InSceneSelectionFilter()); mMessageType_GameObjectsLoaded_Handler = MessagePump::getSingleton().addMessageHandler<MessageType_GameObjectsLoaded>( boost::bind(&MovementControlState::updateAfterGameObjectLoading, this)); mMessageType_SaveGameLoading_Handler = MessagePump::getSingleton().addMessageHandler<MessageType_SaveGameLoading>( boost::bind(&MovementControlState::beforeLoadingSaveGame, this)); // Kamera-Groesse beziehen CameraObject* ogreCam = static_cast<CameraObject*>( mCameraActor->getControlledObject()); AxisAlignedBox camAabb = ogreCam->getDefaultSize(); // Radius berechnen Real camRadius = (camAabb.getMaximum().z - camAabb.getMinimum().z) / 2.0f; camRadius *= 1.1f; Vector3 verts[80]; int k = 0; for(int i = 0; i < 16; i++) { int n; n = abs(abs(i-8)-8)+1; for(int j = 0; j < n; j++) { Real h = (i-7.5f)/7.5f; Degree angle(360.0f/(n+1)*j); Real rad = Math::Sqrt(1-h*h); verts[k++] = camRadius*Vector3(rad*Math::Cos(angle),rad*Math::Sin(angle),h); } } //! TODO: remove this workaround (newton-bug: "spheres don't cast"!) mCameraCastCollision = new OgreNewt::CollisionPrimitives::ConvexHull(mCamBody->getWorld(), verts, 80); //mCameraCastCollision = new OgreNewt::CollisionPrimitives::Ellipsoid(mCamBody->getWorld(), Vector3::UNIT_SCALE * camRadius); } //------------------------------------------------------------------------ MovementControlState::~MovementControlState() { delete mCombatSelector.getFilter(); mCombatSelector.setFilter(NULL); delete mSelector.getFilter(); mSelector.setFilter(NULL); delete mRaycast; delete mConvexcast; delete mCameraCastCollision; if (DebugWindow::getSingletonPtr()) { DebugWindow::getSingletonPtr()->unregisterPage(msDebugWindowPageName); } // Remove debug scene node from character node, if debugview was used. if (mSceneNode != NULL && mSceneNode->getParent() != NULL) { mCharacterActor->_getSceneNode()->removeChild(mSceneNode); } } //------------------------------------------------------------------------ void MovementControlState::pause() { mController = NULL; // actors aren't controlled anymore mCameraActor->getPhysicalThing()->setPhysicsController(NULL); mCameraActor->getPhysicalThing()->freeze(); // cam<->Level collision back to default PhysicsManager::getSingleton().resetMaterialPair( PhysicsManager::getSingleton().getMaterialID("camera"), PhysicsManager::getSingleton().getMaterialID("default")); // cam<->Default collision back to default PhysicsManager::getSingleton().resetMaterialPair( PhysicsManager::getSingleton().getMaterialID("camera"), PhysicsManager::getSingleton().getMaterialID("level")); PhysicsManager::getSingleton().resetMaterialPair( PhysicsManager::getSingleton().getMaterialID("camera"), PhysicsManager::getSingleton().getMaterialID("character")); // Unhighlight selected object, if any. GameObject* go = mSelector.getFirstSelectedObject(); if (go != NULL && go->isHighlighted()) { go->setHighlighted(false); } } //------------------------------------------------------------------------ void MovementControlState::resume() { if (mController == NULL ) { mController = CreatureControllerManager::getSingleton().getCreatureController(mCharacter); } // We want to check for visibility from char's POV. mSelector.setCheckVisibility(true, mCharacter); mSelector.track(mCharacter); mSelector.setRadius(3.0); // Same for combat selector mCombatSelector.setCheckVisibility(true, mCharacter); mCombatSelector.track(mCharacter); mCombatSelector.setRadius(10.0); // control camera mCameraActor->getPhysicalThing()->setMaterialID( PhysicsManager::getSingleton().getMaterialID("camera")); mCameraActor->getPhysicalThing()->unfreeze(); mCameraActor->getPhysicalThing()->setPhysicsController(this); mCameraActor->getPhysicalThing()->setUpConstraint(Vector3::ZERO); // We also handle cam<->level, cam<->default cam<->char collision from now on OgreNewt::MaterialPair* mat_pair = NULL; mat_pair = PhysicsManager::getSingleton().createMaterialPair( PhysicsManager::getSingleton().getMaterialID("camera"), PhysicsManager::getSingleton().getMaterialID("default")); mat_pair->setContactCallback(this); mat_pair->setDefaultCollidable(1); mat_pair->setDefaultFriction(0,0); mat_pair->setDefaultSoftness(0.8f); mat_pair->setDefaultElasticity(0.4f); mat_pair = PhysicsManager::getSingleton().createMaterialPair( PhysicsManager::getSingleton().getMaterialID("camera"), PhysicsManager::getSingleton().getMaterialID("level")); mat_pair->setContactCallback(this); mat_pair->setDefaultCollidable(1); mat_pair->setDefaultFriction(0,0); mat_pair->setDefaultSoftness(0.8f); mat_pair->setDefaultElasticity(0.4f); mat_pair = PhysicsManager::getSingleton().createMaterialPair( PhysicsManager::getSingleton().getMaterialID("camera"), PhysicsManager::getSingleton().getMaterialID("character")); mat_pair->setContactCallback(this); mat_pair->setDefaultCollidable(1); mat_pair->setDefaultFriction(0,0); mat_pair->setDefaultSoftness(0.8f); mat_pair->setDefaultElasticity(0.4f); mCharacterState.mCurrentMovementState = MOVE_NONE; setViewMode(VM_THIRD_PERSON); } //------------------------------------------------------------------------ void MovementControlState::run(Real elapsedTime) { InputManager* im = InputManager::getSingletonPtr(); updateCharacter(elapsedTime); updateCameraLookAt(elapsedTime); updateSelection(); // camera pitch if (!isMouseUsedByCegui() ) { if (mInvertedMouse) mPitch -= 0.5 * mMouseSensitivity * Degree(im->getMouseRelativeY() / 10); else mPitch += 0.5 * mMouseSensitivity * Degree(im->getMouseRelativeY() / 10); if (mPitch < mPitchRange.first) mPitch = mPitchRange.first; if (mPitch > mPitchRange.second) mPitch = mPitchRange.second; } mCharacterState.mLastMovementState = mCharacterState.mCurrentMovementState; if (isEnemyNear() && !(mCharacter->getLifeState() & Effect::LS_NO_COMBAT)) { InputManager::getSingleton().pushControlState(CST_COMBAT); } } //------------------------------------------------------------------------ void MovementControlState::updateCharacter(Ogre::Real elapsedTime) { InputManager* im = InputManager::getSingletonPtr(); if( mController != NULL ) { int movement = mCharacterState.mCurrentMovementState; Degree rotation(0); AbstractMovement *drehen = mController->getMovementFromId(CreatureController::MT_DREHEN); Real baseVelocity = 0; if( drehen->calculateBaseVelocity(baseVelocity) ) { if( !(movement & MOVE_RIGHT || movement & MOVE_LEFT) ) { Degree baseVel(baseVelocity*360); if( mViewMode != VM_PNYX_MODE ) { if (movement & TURN_LEFT) rotation = elapsedTime * baseVel; if (movement & TURN_RIGHT) rotation = -elapsedTime * baseVel; } // mouse if( !isMouseUsedByCegui() ) { if (mViewMode == VM_FIRST_PERSON || mViewMode == VM_THIRD_PERSON ) { if( !(movement & TURN_LEFT || movement & TURN_RIGHT) ) { rotation = -mMouseSensitivity/3.0f * Degree(im->getMouseRelativeX())/200.0 * baseVel; } } } } if( mViewMode != VM_PNYX_MODE && mViewMode != VM_FIRST_PERSON ) { // virtual yaw if( mCamVirtualYaw != mNewCamVirtualYaw ) { mCamVirtualYaw = mNewCamVirtualYaw; } if( ((movement & MOVE_FORWARD) && (movement & MOVE_RIGHT) && !(movement & MOVE_LEFT)) || ((movement & MOVE_BACKWARD) && (movement & MOVE_LEFT) && !(movement & MOVE_RIGHT)) ) { mNewCamVirtualYaw = Degree(45); } else if( ((movement & MOVE_FORWARD) && (movement & MOVE_LEFT) && !(movement & MOVE_RIGHT)) || ((movement & MOVE_BACKWARD) && (movement & MOVE_RIGHT) && !(movement & MOVE_LEFT)) ) { mNewCamVirtualYaw = Degree(-45); } else { mNewCamVirtualYaw =Degree(0); } if( mCamVirtualYaw != mNewCamVirtualYaw ) { rotation += mCamVirtualYaw - mNewCamVirtualYaw; } } if( mViewMode == VM_FIRST_PERSON ) { if( ((movement & MOVE_FORWARD) && (movement & MOVE_RIGHT) && !(movement & MOVE_LEFT)) || ((movement & MOVE_BACKWARD) && (movement & MOVE_RIGHT) && !(movement & MOVE_LEFT)) ) { mCamVirtualYaw -= Degree(270)*elapsedTime; if( mCamVirtualYaw <= Degree(-90) ) mCamVirtualYaw = Degree(-90); } else if( ((movement & MOVE_FORWARD) && (movement & MOVE_LEFT) && !(movement & MOVE_RIGHT)) || ((movement & MOVE_BACKWARD) && (movement & MOVE_LEFT) && !(movement & MOVE_RIGHT)) ) { mCamVirtualYaw += Degree(270)*elapsedTime; if( mCamVirtualYaw >= Degree(90) ) mCamVirtualYaw = Degree(90); } else { if( mCamVirtualYaw > Degree(0) ) { mCamVirtualYaw -= Degree(270)*elapsedTime; if( mCamVirtualYaw <= Degree(0) ) mCamVirtualYaw = Degree(0); } else if( mCamVirtualYaw < Degree(0) ) { mCamVirtualYaw += Degree(270)*elapsedTime; if( mCamVirtualYaw >= Degree(0) ) mCamVirtualYaw = Degree(0); } } } } if( mViewMode != VM_PNYX_MODE ) { if( mController->getMovementId() == CreatureController::MT_HOCHSPRUNG ) { // move forward or backward if wanted Vector3 direction = Vector3::UNIT_Y; if( movement & MOVE_FORWARD ) direction += Vector3::NEGATIVE_UNIT_Z; else if( movement & MOVE_BACKWARD ) direction += Vector3::UNIT_Z; mController->setMovement( CreatureController::MT_HOCHSPRUNG, direction, Vector3(0, rotation.valueRadians(), 0) ); } else if( movement & MOVE_SNEAK ) { Vector3 direction(Vector3::ZERO); if (movement & MOVE_FORWARD) direction.z = -1; else if( movement & MOVE_BACKWARD) direction.z = 1; mController->setMovement( CreatureController::MT_SCHLEICHEN, direction, Vector3(0, rotation.valueRadians(), 0) ); } else if( movement & MOVE_JUMP && mController->getMovementFromId(CreatureController::MT_HOCHSPRUNG)->isPossible() ) { CreatureController::MovementType type = CreatureController::MT_HOCHSPRUNG; Vector3 direction = Vector3::UNIT_Y; if( movement & MOVE_FORWARD ) { type = CreatureController::MT_WEITSPRUNG; direction += Vector3::NEGATIVE_UNIT_Z; } mController->setMovement( type, direction, Vector3(0, rotation.valueRadians(), 0) ); } else if( movement & MOVE_FORWARD ) { CreatureController::MovementType type = CreatureController::MT_GEHEN; if( movement & MOVE_RUN_LOCK ) { if( movement & MOVE_RUN ) type = CreatureController::MT_RENNEN; else type = CreatureController::MT_LAUFEN; } else { if( movement & MOVE_RUN ) type = CreatureController::MT_GEHEN; else type = CreatureController::MT_JOGGEN; } mController->setMovement( type, Vector3(0,0,-1), Vector3(0, rotation.valueRadians(), 0) ); } else if (movement & MOVE_BACKWARD ) { CreatureController::MovementType type = CreatureController::MT_RUECKWAERTS_GEHEN; if( !(movement & MOVE_RUN) ) type = CreatureController::MT_RUECKWAERTS_JOGGEN; mController->setMovement( type, Vector3(0,0,1), Vector3(0, rotation.valueRadians(), 0) ); } else if (movement & MOVE_LEFT || movement & MOVE_RIGHT) { Vector3 direction = Vector3::UNIT_X; if( movement & MOVE_LEFT ) direction = Vector3::NEGATIVE_UNIT_X; mController->setMovement( CreatureController::MT_SEITWAERTS_GEHEN, direction, Vector3(0, rotation.valueRadians(), 0) ); } else { mController->setMovement( CreatureController::MT_STEHEN, Vector3(0,0,0), Vector3(0, rotation.valueRadians(), 0) ); } } else // VM_PNYX_MODE { // turn to the direction entered if( movement & MOVE_FORWARD || movement & MOVE_BACKWARD || movement & MOVE_LEFT || movement & MOVE_RIGHT ) { // direction to turn to int direction = movement & (MOVE_FORWARD | MOVE_BACKWARD | MOVE_RIGHT | MOVE_LEFT); Degree yaw(0); switch(direction) { case MOVE_FORWARD: yaw = Degree(0); break; case MOVE_FORWARD | MOVE_LEFT: yaw = Degree(45); break; case MOVE_FORWARD | MOVE_RIGHT: yaw = Degree(-45); break; case MOVE_RIGHT: yaw = Degree(-90); break; case MOVE_LEFT: yaw = Degree(90); break; case MOVE_BACKWARD: yaw = Degree(180); break; case MOVE_BACKWARD | MOVE_LEFT: yaw = Degree(-225); break; case MOVE_BACKWARD | MOVE_RIGHT: yaw = Degree(225); break; default: break; } yaw+=mCamYaw; CreatureController::MovementType type = CreatureController::MT_JOGGEN; if( movement & MOVE_SNEAK ) type = CreatureController::MT_SCHLEICHEN; else { if( movement & MOVE_JUMP ) type = CreatureController::MT_WEITSPRUNG; else { switch( movement & (MOVE_RUN | MOVE_RUN_LOCK) ) { case MOVE_RUN: type = CreatureController::MT_GEHEN; break; case MOVE_RUN_LOCK: type = CreatureController::MT_LAUFEN; break; case MOVE_RUN | MOVE_RUN_LOCK: type = CreatureController::MT_RENNEN; break; default: break; } } } mController->setMovement( type, Vector3::NEGATIVE_UNIT_Z, Vector3::UNIT_Y * (yaw-mController->getYaw()).valueRadians()); } else { // don't move CreatureController::MovementType type = CreatureController::MT_STEHEN; if( movement & MOVE_SNEAK ) type = CreatureController::MT_SCHLEICHEN; else if( movement & MOVE_JUMP ) type = CreatureController::MT_HOCHSPRUNG; mController->setMovement( type, Vector3::ZERO, Vector3::ZERO); } } } } // ------------------------------------------------------------------------ void MovementControlState::updateCameraLookAt(Ogre::Real elapsedTime) { InputManager* im = InputManager::getSingletonPtr(); // camera position (distance) if ( !isMouseUsedByCegui() ) { mDesiredDistance -= im->getMouseRelativeZ() * 0.002; if (mDesiredDistance < mDistanceRange.first) { mDesiredDistance = mDistanceRange.first; } if (mDesiredDistance > mDistanceRange.second) { mDesiredDistance = mDistanceRange.second; } if( mViewMode == VM_FREE_CAMERA || mViewMode == VM_PNYX_MODE ) { mCamYaw -= 2 * mMouseSensitivity / 4.0 * mRotationSpeed * Degree(im->getMouseRelativeX() / 15); while (mCamYaw.valueDegrees() > 360.0f) mCamYaw -= Degree(360.0f); while (mCamYaw.valueDegrees() < -360.0f) mCamYaw += Degree(360.0f); } } SceneNode* cameraNode = mCameraActor->_getSceneNode(); Vector3 charPos; charPos = mCharacter->getActor()->getWorldPosition(); Quaternion charOri = mCharacter->getActor()->getWorldOrientation(); Quaternion virtualCamOri; virtualCamOri.FromAngleAxis(mCamVirtualYaw, Vector3::UNIT_Y); // Kamera-Gr�e beziehen CameraObject* ogreCam = static_cast<CameraObject*>( mCameraActor->getControlledObject()); AxisAlignedBox aabb = ogreCam->getDefaultSize(); // Radius berechnen Real radius = (aabb.getMaximum()-aabb.getMinimum()).length() / 2.0f; if( mViewMode == VM_FIRST_PERSON) { Quaternion camOri; camOri.FromAngleAxis(mPitch, Vector3::NEGATIVE_UNIT_X); cameraNode->lookAt( charPos + charOri * virtualCamOri * mLookAtOffset + charOri * camOri * virtualCamOri * (-Vector3::UNIT_Z), Node::TS_WORLD); } else if( mViewMode == VM_THIRD_PERSON ) { cameraNode->lookAt( charPos + charOri * /* virtualCamOri * */ mLookAtOffset + charOri * /* virtualCamOri * */ (-Vector3::UNIT_Z*radius), // doesn't work smoothly with strafe+forward Node::TS_WORLD); } else if( mViewMode == VM_FREE_CAMERA || mViewMode == VM_PNYX_MODE ) { Quaternion camOri; camOri.FromAngleAxis(mCamYaw, Vector3::UNIT_Y); Real dist = (mCameraActor->getPosition() - charPos).length(); cameraNode->lookAt( charPos + camOri * virtualCamOri * mLookAtOffset + camOri * (-Vector3::UNIT_Z*radius), Node::TS_WORLD); } // Character ausblenden, wenn Kamera zu nah. if( mViewMode != VM_FIRST_PERSON ) { // here the real charOri of the object is needed Vector3 charPos; Quaternion charOri; mCharBody->getPositionOrientation(charPos, charOri); Vector3 camPos; Quaternion camOri; mCamBody->getPositionOrientation(camPos, camOri); Vector3 camPoint, charPoint, normal; int collisionPoints = OgreNewt::CollisionTools::CollisionClosestPoint( PhysicsManager::getSingleton()._getNewtonWorld(), mCamBody->getCollision(), camOri, camPos, mCharBody->getCollision(), charOri, charPos, camPoint, charPoint, normal, 0 // set threadindex to 0, I hope this is ok! ); if( collisionPoints == 0 ) mCharacterActor->setVisible(false); else { // eigentlich muss hier transparent gemacht werden! mCharacterActor->setVisible(true); } } mCameraActor->setOrientation(cameraNode->getOrientation()); } int MovementControlState::onAABBOverlap( OgreNewt::Body* body0, OgreNewt::Body* body1, int threadIndex ) { if( mViewMode == VM_FIRST_PERSON ) return 0; // test if this is cam-player-collide if( ( body0 == mCamBody && body1 == mCharacterActor->getPhysicalThing()->_getBody() ) || ( body1 == mCamBody && body0 == mCharacterActor->getPhysicalThing()->_getBody() ) ) { return 0; } return 1; } void MovementControlState::userProcess(OgreNewt::ContactJoint &contactJoint, Real timestep, int) { mLastCameraCollision = 0; } //------------------------------------------------------------------------ // character callback moved to CreatureController void MovementControlState::OnApplyForceAndTorque(PhysicalThing* thing, float timestep) { OgreNewt::World* world = PhysicsManager::getSingleton()._getNewtonWorld(); calculateCamera(timestep); ///@todo move to CreatureController? SceneNode* node = mCharacterActor->_getSceneNode(); std::ostringstream ss; Vector3 bodpos, playpos = node->getPosition(); Quaternion egal; mCamBody->getPositionOrientation(bodpos,egal); ss << "scene node : " << playpos << std::endl << "player velocity : " << -mController->getVelocity().z << std::endl << "player orientation : " << mController->getCreature()->getActor()->getOrientation() << std::endl << "camera posder : " << static_cast<Camera*>( mCameraActor->_getMovableObject())->getDerivedPosition() << std::endl << "camera orientation : " << mCameraActor->getWorldOrientation() << std::endl << "camera pos : " << bodpos << std::endl << "camera distance : " << mLastDistance << " ( " << mDesiredDistance << " ) " << std::endl << "is airborne: " << (mController->getAbstractLocation() == CreatureController::AL_AIRBORNE ? "true" : "false") << std::endl; LOG_DEBUG(Logger::UI, ss.str()); DebugWindow::getSingleton().setPageText(msDebugWindowPageName, ss.str()); } //------------------------------------------------------------------------ void MovementControlState::calculateCamera(const Ogre::Real& timestep) { mLastCameraCollision += timestep; Vector3 charPos = mCharacter->getActor()->getWorldPosition(); Quaternion charOri = mCharacter->getActor()->getWorldOrientation(); Quaternion virtualCamOri; virtualCamOri.FromAngleAxis(mCamVirtualYaw, Vector3::UNIT_Y); Vector3 camPos; Quaternion camOri; mCamBody->getPositionOrientation(camPos, camOri); SceneNode* cameraNode = mCameraActor->_getSceneNode(); Vector3 optimalCamPos = calculateOptimalCameraPosition(true, timestep); charPos = charPos + charOri * virtualCamOri * mLookAtOffset; // Ringbuffer mit Positionen des Characters mCharPositionsBufferIdx = (mCharPositionsBufferIdx + 1) % mCharPositionsBuffer.size(); mCharPositionsBuffer[mCharPositionsBufferIdx] = charPos; // Kamera-Gr�e beziehen CameraObject* ogreCam = static_cast<CameraObject*>( mCameraActor->getControlledObject()); AxisAlignedBox camAabb = ogreCam->getDefaultSize(); // Radius berechnen Real camRadius = (camAabb.getMaximum().z - camAabb.getMinimum().z) / 2.0f; if (mViewMode == VM_THIRD_PERSON || mViewMode == VM_FREE_CAMERA || mViewMode == VM_PNYX_MODE) { // wir machen ein paar Raycasts um herauszufinden, ob wir von der jetzigen Position // so zur optimalen kommen const OgreNewt::MaterialID *charMaterialId = mCharBody->getMaterialGroupID(); const OgreNewt::MaterialID *camMaterialId = mCamBody->getMaterialGroupID(); PhysicsMaterialRaycast::MaterialVector materialVector; materialVector.push_back(charMaterialId); materialVector.push_back(camMaterialId); // PhysicsManager::getSingleton()._getLevelMaterialID(); OgreNewt::World *world = PhysicsManager::getSingleton()._getNewtonWorld(); Vector3 normToOptCamPos = (optimalCamPos - charPos); normToOptCamPos.normalise(); RaycastInfo infoCastOptPos = mRaycast->execute( world, &materialVector, camPos + camRadius * normToOptCamPos, // Gr�e der Kamera einbeziehen optimalCamPos + camRadius * normToOptCamPos, true); // Gr�e der Kamera einbeziehen RaycastInfo infoCastChar = mRaycast->execute( world, &materialVector, camPos, charPos, true); // reset the camera if the character is to far away or cannot be seen any more (Raycast) Real maxdistance = Math::Pow(1.5f * mDesiredDistance + 1.4f, 2); if( infoCastChar.mBody || (camPos - charPos).squaredLength() > maxdistance) { mCharacterOccludedTime += timestep; mCharacterOccludedFrameCount++; // falls zu lange, Kamera resetten: if( mCharacterOccludedTime > 0.250f && mCharacterOccludedFrameCount > 5 ) { resetCamera(); return; } } else { mCharacterOccludedTime = 0; mCharacterOccludedFrameCount = 0; } if( infoCastOptPos.mBody && !infoCastChar.mBody ) { // andere Position ermitteln, die ziwschen optimaler und Character liegt // und erreichbar ist Real lenToOptCamPos = (optimalCamPos - charPos).length(); RaycastInfo infoCastNewPos; Real delta = lenToOptCamPos/2.0f; Vector3 temp = charPos + delta * normToOptCamPos; // Annaeherung in Schritten, an den Punkt, der von der aktuellen Position aus erreicht werden kann! while( delta > 0.05 ) // genauigkeit des gefundenen Punktes { infoCastNewPos = mRaycast->execute( world, &materialVector, camPos + camRadius * normToOptCamPos, // Groesse der Kamera! temp, true); delta = delta/2.0f; if( infoCastNewPos.mBody ) // Hindernis gefunden, naeher an Char ran { temp = temp - delta * normToOptCamPos; } else // kein Hindernis gefunden, weiter von Char weg { temp = temp + delta * normToOptCamPos; } } // Jetzt koennen wir sicher sein, dass diese Stelle erreichbar ist: temp = temp - 0.05 * normToOptCamPos; // Groesse der Kamera einbeziehen optimalCamPos = temp - camRadius * normToOptCamPos; // so ab hier kann ganz normal weiter gerechnet werden! } // gibt an, ob schon gebufferte Daten fuer den // neuen Weg existieren und dort weitergemacht werden kann, // oder ob neu nach einem Weg gesucht werden muss! if( infoCastChar.mBody && infoCastOptPos.mBody ) // neue Position und Character nicht erreichbar { // anderen Weg finden // hier werden erstmal nur alte Player-Positionen betrachtet // es wird davon ausgegangen, dass diese "nah" genug aneinanderliegen // und durch "Geraden" miteinander verbunden werden koennen // durch das spring-Acc-Damping System sollten die Bewegungen trotzdem fluessig // und weich (keine scharfen Kurven) erscheinen size_t buffSize = mCharPositionsBuffer.size(); if( !mIsPathfinding ) { LOG_DEBUG(Logger::UI, " Pathfinding der Kamera sollte jetzt anfangen!"); // letzte Character - Position suchen, die erreichbar ist... // Ist vermutlicherweise ja die letzte, davor war ja noch alles ok! unsigned int delta = 1; while ( delta < buffSize ) { RaycastInfo info = mRaycast->execute( world, &materialVector, camPos, mCharPositionsBuffer[ (mCharPositionsBufferIdx - delta) % buffSize ], true); if( !info.mBody ) break; delta++; } if( delta >= buffSize ) { // is wohl irgendwas schiefgegangen! LOG_MESSAGE(Logger::UI, " Der Ringbuffer mit den Player-Positionen scheint zu klein zu sein; Pathfinding der Kamera fehlgeschlagen! "); mIsPathfinding = false; resetCamera(); return; } mLastReachableBufPos = delta; // auf zu der ermittelten Position! optimalCamPos = mCharPositionsBuffer[ (mCharPositionsBufferIdx - mLastReachableBufPos) % buffSize ]; } else { LOG_DEBUG(Logger::UI, " Pathfinding der Kamera sollte weitergefhrt werden!"); // suche von lastReachableBufPos aus der letzten Frame nach neuen erreichbaren Buffer-Positionen unsigned int delta = mLastReachableBufPos; // das ist die von der letzten Frame! while ( delta > 0 ) // delta = 0 braucht nicht ueberprft zu werden, wurde oben schon ausgeschlossen! { RaycastInfo info = mRaycast->execute( world, &materialVector, camPos, mCharPositionsBuffer[ (mCharPositionsBufferIdx - delta) % buffSize ], true); if( info.mBody ) break; delta--; } mLastReachableBufPos = delta + 1; // auf zu der ermittelten Position! optimalCamPos = mCharPositionsBuffer[ (mCharPositionsBufferIdx - mLastReachableBufPos) % buffSize ]; } mIsPathfinding = true; // so zum Testen noch keine Optimierung (doppelte Prfung gleicher sachen) } else { mIsPathfinding = false; } Vector3 diff = camPos - optimalCamPos; Vector3 cameraVelocity; cameraVelocity = mCamBody->getVelocity(); // spring velocity Vector3 springAcc = -mLinearSpringK*diff - mLinearDampingK * cameraVelocity; // get the camera mass Real mass; Vector3 inertia; mCamBody->getMassMatrix(mass, inertia); //mCamBody->setPositionOrientation(newCamPos, camOri); mCamBody->setForce(springAcc * mass); } else if( mViewMode == VM_FIRST_PERSON ) { mCamBody->setPositionOrientation(optimalCamPos, camOri); } } //------------------------------------------------------------------------ Ogre::Vector3 MovementControlState::calculateOptimalCameraPosition(bool slowlyMoveBackward, const Real &timestep) { Vector3 targetCamPos; Vector3 charPos = mCharacter->getActor()->getWorldPosition(); //Quaternion charOri = mCharacter->getActor()->getWorldOrientation(); Quaternion charOri (mController->getYaw(), Vector3::UNIT_Y); Quaternion virtualCamOri; virtualCamOri.FromAngleAxis(mCamVirtualYaw, Vector3::UNIT_Y); // get camera size CameraObject* ogreCam = static_cast<CameraObject*>( mCameraActor->getControlledObject()); AxisAlignedBox camAabb = ogreCam->getDefaultSize(); Real camRadius = (camAabb.getMaximum().z - camAabb.getMinimum().z) / 2.0f; if( mViewMode == VM_THIRD_PERSON || mViewMode == VM_FREE_CAMERA || mViewMode == VM_PNYX_MODE) { charPos = charPos + charOri * mLookAtOffset; if(mViewMode == VM_PNYX_MODE) { Quaternion camOri; camOri.FromAngleAxis(mCamYaw, Vector3::UNIT_Y); targetCamPos = charPos + camOri * virtualCamOri * Vector3( 0, Math::Sin(mPitch) * mDesiredDistance, Math::Cos(mPitch) * mDesiredDistance); } else if(mViewMode == VM_THIRD_PERSON) { targetCamPos = charPos + charOri * virtualCamOri * Vector3( 0, Math::Sin(mPitch) * mDesiredDistance, Math::Cos(mPitch) * mDesiredDistance); } else { Quaternion camOri; camOri.FromAngleAxis(mCamYaw, Vector3::UNIT_Y); targetCamPos = charPos + charOri * camOri * virtualCamOri * Vector3( 0, Math::Sin(mPitch) * mDesiredDistance, Math::Cos(mPitch) * mDesiredDistance); } Vector3 diff = targetCamPos - charPos; // Convexcast PhysicsMaterialConvexcast::MaterialVector materialVector; materialVector.push_back( mCharBody->getMaterialGroupID() ); materialVector.push_back( mCamBody->getMaterialGroupID() ); OgreNewt::World *world = PhysicsManager::getSingleton()._getNewtonWorld(); ConvexcastInfo info = mConvexcast->execute( world, &materialVector, mCameraCastCollision, charPos, Quaternion::IDENTITY, targetCamPos, true); bool CollisionFound = false; if( info.mBody ) { CollisionFound = true; Real hitBodyVel = info.mBody->getVelocity().dotProduct(diff.normalisedCopy()); hitBodyVel = std::min(0.0f, hitBodyVel); // if the body moves, try to avoid it Real dist = std::max(info.mDistance + (hitBodyVel*timestep - 0.01)/diff.length(), 0.0); diff *= dist; mLastCameraCollision = 0; } // Langsames Entfernen vom Char: if( CollisionFound ) mTimeOfLastCollision = 0.0f; else mTimeOfLastCollision += timestep; Real desiredDistance = diff.length(); Vector3 camPos; Quaternion camOri; mCamBody->getPositionOrientation(camPos, camOri); if( slowlyMoveBackward && desiredDistance > mLastDistance ) { diff.normalise(); Real newDistance; Vector3 actDiff = camPos - charPos; actDiff.normalise(); if( mLastCameraCollision <= 0.5 ) // there was a cam collision 0.5 seconds ago { newDistance = mLastDistance; } else if( mTimeOfLastCollision > mCamMoveAwayStartTime || diff.directionEquals(actDiff, mCamMoveAwayRange*timestep) ) newDistance = mLastDistance + mCamMoveAwayVelocity*timestep; else newDistance = mLastDistance; if( newDistance > desiredDistance ) newDistance = desiredDistance; diff = diff*newDistance; mLastDistance = newDistance; } else mLastDistance = desiredDistance; targetCamPos = charPos + diff; } else // FIRST_PERSON { // determine the optimal target position of the camera targetCamPos = charPos + charOri * virtualCamOri * mLookAtOffset + charOri * virtualCamOri * Vector3( 0, Math::Sin(mPitch) * mDesiredDistance, Math::Cos(mPitch) * mDesiredDistance); } return targetCamPos; } //------------------------------------------------------------------------ bool MovementControlState::isEnemyNear() { mCombatSelector.updateSelection(); const Selector::GameObjectVector& gov = mCombatSelector.getAllSelectedObjects(); for (size_t i = 0, end = gov.size(); i < end; ++i) { Creature* creature = dynamic_cast<Creature*>(gov.at(i)); if (creature && creature->getAlignment() == Creature::ALIGNMENT_ENEMY && (creature->getLifeState() & Effect::LS_NO_COMBAT) == 0) { return true; } } return false; } //------------------------------------------------------------------------ void MovementControlState::updateSelection() { if ( isMouseUsedByCegui() ) return; InputManager* im = InputManager::getSingletonPtr(); GameObject* oldGo = mSelector.getFirstSelectedObject(); mSelector.updateSelection(); GameObject* newGo = mSelector.getFirstSelectedObject(); if (oldGo != NULL && oldGo != newGo) { oldGo->setHighlighted(false); } if (newGo != NULL && newGo != oldGo) { newGo->setHighlighted(true); } /* // Optionen anzeigen if (im->isMouseButtonDown(OIS::MB_Right) && newGo != NULL) { WindowFactory::getSingleton().showActionChoice(newGo); } else if (im->isMouseButtonDown(OIS::MB_Left) && newGo != NULL) { newGo->doDefaultAction(mCharacter, NULL); } */ } void MovementControlState::setViewMode(ViewMode mode) { mViewMode = mode; MeshObject* charMesh = dynamic_cast<MeshObject*>(mCharacterActor->getControlledObject()); AxisAlignedBox aabb; try { aabb = charMesh->getPoseSize(mCharacter->getAnimation("stehen").first); } catch(...) { aabb = charMesh->getDefaultSize(); } if (mode == VM_FIRST_PERSON) { mLookAtOffset = Vector3( 0, (aabb.getMaximum().y - aabb.getMinimum().y) * 0.90f, (aabb.getMaximum().z - aabb.getMinimum().z) * (-0.3f) ); mDistanceRange.first = 0.0; mDistanceRange.second = 0.0; mDesiredDistance = 0.0; mPitchRange.first = Degree(-85); mPitchRange.second = Degree(85); mPitch = 0; LOG_MESSAGE(Logger::UI, "Switch to 1st person view"); resetCamera(); } else if(mode == VM_THIRD_PERSON) { mLookAtOffset = Vector3(0, (aabb.getMaximum() - aabb.getMinimum()).y * 0.90f, 0); mDistanceRange.first = 0.60; mDistanceRange.second = 7.00; mDesiredDistance = 2.0; mPitchRange.first = Degree(-75); mPitchRange.second = Degree(85); mPitch = Degree(30); LOG_MESSAGE(Logger::UI, "Switch to 3rd person view"); resetCamera(); } else if(mode == VM_FREE_CAMERA) { mLookAtOffset = Vector3(0, (aabb.getMaximum() - aabb.getMinimum()).y * 0.80f, 0); mDistanceRange.first = 0.60; mDistanceRange.second = 7.00; mDesiredDistance = 2.0; mPitchRange.first = Degree(-75); mPitchRange.second = Degree(85); mPitch = Degree(30); mCamYaw = mCharacter->getActor()->getWorldOrientation().getYaw(); LOG_MESSAGE(Logger::UI, "Switch to free camera view"); resetCamera(); } else // mode == VM_PNYX_MODE { mLookAtOffset = Vector3(0, (aabb.getMaximum() - aabb.getMinimum()).y * 0.80f, 0); mDistanceRange.first = 0.60; mDistanceRange.second = 7.00; mDesiredDistance = 2.5; mPitchRange.first = Degree(-75); mPitchRange.second = Degree(85); mPitch = Degree(30); mCamYaw = mCharacter->getActor()->getWorldOrientation().getYaw(); LOG_MESSAGE(Logger::UI, "Switch to pnyx mode movementcontroller"); resetCamera(); } } //------------------------------------------------------------------------ /* // not used at the moment! void MovementControlState::interpolateAnimationLookAtOffset(std::string actAnim, std::string newAnim, Ogre::Real factor) { AxisAlignedBox aab; Vector3 size[2]; Vector3 interpolatedSize; // Die Gr�e der beiden Animationen abfragen MeshObject* mesh = dynamic_cast<MeshObject*>(mCharacterActor->getControlledObject()); aab = mesh->getPoseSize(actAnim); size[0] = aab.getMaximum() - aab.getMinimum(); aab = mesh->getPoseSize(newAnim); size[1] = aab.getMaximum() - aab.getMinimum(); // interpolierte Gr�e (linear) berechnen interpolatedSize = size[0] + factor*(size[1] - size[0]); // LookAtOffset berechnen! switch(mViewMode) { case VM_FIRST_PERSON: mLookAtOffset = Vector3(0, interpolatedSize.y * 0.90f, interpolatedSize.z * (-0.3f) ); break; case VM_THIRD_PERSON: mLookAtOffset = Vector3(0, interpolatedSize.y * 0.90f, 0); break; case VM_FREE_CAMERA: default: mLookAtOffset = Vector3(0, interpolatedSize.y * 0.80f, 0); } } */ //------------------------------------------------------------------------ MovementControlState::ViewMode MovementControlState::getViewMode() { return mViewMode; } //------------------------------------------------------------------------ void MovementControlState::toggleViewMode() { if (getViewMode() == VM_THIRD_PERSON) setViewMode(VM_FIRST_PERSON); else if(getViewMode() == VM_FIRST_PERSON) setViewMode(VM_FREE_CAMERA); else if(getViewMode() == VM_FREE_CAMERA) setViewMode(VM_PNYX_MODE); else setViewMode(VM_THIRD_PERSON); } //------------------------------------------------------------------------ void MovementControlState::resetCamera() { Vector3 camPos; Quaternion camOri; mCamBody->getPositionOrientation(camPos, camOri); mCamBody->setPositionOrientation(calculateOptimalCameraPosition(false, 0.0f), camOri); mCamVirtualYaw = Degree(0); mNewCamVirtualYaw = Degree(0); mLastCameraCollision = 0; if(mViewMode == VM_FIRST_PERSON) mCharacterActor->setVisible(false); else mCharacterActor->setVisible(true); LOG_MESSAGE(Logger::UI, "Camera resetted."); } //------------------------------------------------------------------------ bool MovementControlState::keyPressed(const OIS::KeyEvent& evt, bool handled) { bool retval = false; if( !handled ) { int code = CommandMapper::encodeKey(evt.key, InputManager::getSingleton().getModifierCode()); // First see, if a control state action is defined CeGuiString command = mCommandMapper->getControlStateAction(code, mType); if (command == "") { // No. So try global actions. command = mCommandMapper->getGlobalAction(code); } else if (command == "freeflight_mode") { InputManager::getSingleton().pushControlState(CST_FREEFLIGHT); retval = true; } else if (command == "reset_camera") { resetCamera(); retval = true; } else if (command == "toggle_view_mode") { toggleViewMode(); retval = true; } else if( startAction(command, mCharacter) ) retval = true; if( !retval ) { int movement = mCommandMapper->getMovement(evt.key); if (movement & MOVE_RUN_LOCK) // dieses einrasten lassen { mCharacterState.mCurrentMovementState ^= MOVE_RUN_LOCK; movement &= ~MOVE_RUN_LOCK; retval = true; } if (movement != MOVE_NONE) { mCharacterState.mCurrentMovementState |= movement; retval = true; } } } if( ControlState::keyPressed(evt, handled || retval ) ) retval = true; return retval; } //------------------------------------------------------------------------ bool MovementControlState::keyReleased(const OIS::KeyEvent& evt, bool handled) { bool retval = false; int movement = mCommandMapper->getMovement(evt.key); if (movement != MOVE_NONE) { mCharacterState.mCurrentMovementState &= (~movement | MOVE_RUN_LOCK); retval = true; } if( ControlState::keyReleased(evt, retval) ) retval = true; return retval; } //------------------------------------------------------------------------ bool MovementControlState::mouseReleased(const OIS::MouseEvent& evt, OIS::MouseButtonID id, bool handled) { handled = handled || ControlState::mouseReleased(evt, id, handled); /* if( !handled ) { InputManager* im = InputManager::getSingletonPtr(); int mouseButtonMask = CommandMapper::encodeKey(id, im->getModifierCode()); return startAction(mCommandMapper->getControlStateAction(mouseButtonMask, CST_MOVEMENT), mCharacter); } */ return false; } //------------------------------------------------------------------------ bool MovementControlState::mousePressed(const OIS::MouseEvent& evt, OIS::MouseButtonID id, bool handled) { handled = handled || ControlState::mouseReleased(evt, id, handled); // default action und action-selektor, falls object selected GameObject* newGo = mSelector.getFirstSelectedObject(); if( newGo != NULL && !isMouseUsedByCegui() ) { if( id == OIS::MB_Left ) { if( newGo->getDefaultAction(mCharacter) != NULL ) { newGo->doDefaultAction(mCharacter, NULL); handled = true; } } else if( id == OIS::MB_Right ) { WindowFactory::getSingleton().showActionChoice(newGo); handled = true; } } if( !handled ) { InputManager* im = InputManager::getSingletonPtr(); int mouseButtonMask = CommandMapper::encodeKey(id, im->getModifierCode()); return startAction(mCommandMapper->getControlStateAction(mouseButtonMask, CST_MOVEMENT), mCharacter); } return false; } //------------------------------------------------------------------------ DebugVisualisableFlag MovementControlState::getFlag() const { return DVF_CONTROL; } //------------------------------------------------------------------------ void MovementControlState::updatePrimitive() { if (mSceneNode->getParent() == NULL) { mCharacterActor->_getSceneNode()->addChild(mSceneNode); } LineSetPrimitive* lineSet = static_cast<LineSetPrimitive*>(mPrimitive); lineSet->clear(); lineSet->addLine(mLookAtOffset, mLookAtOffset + Vector3(0, 1.2, 0), ColourValue::Red); } //------------------------------------------------------------------------ void MovementControlState::doCreatePrimitive() { mPrimitive = new LineSetPrimitive(); } bool MovementControlState::updateAfterGameObjectLoading() { resume(); //saving/loading only possible in movement state //// We want to check for visibility from char's POV. //mSelector.setCheckVisibility(true, GameObjectManager::getSingleton().getGameObject(mCharacterId)); //mSelector.track(mCharacter); //mSelector.setRadius(3.0); //// Same for combat selector //mCombatSelector.setCheckVisibility(true, GameObjectManager::getSingleton().getGameObject(mCharacterId)); //mCombatSelector.track(mCharacter); //mCombatSelector.setRadius(10.0); return false; } bool MovementControlState::beforeLoadingSaveGame() //unhighlight selected go { if(mSelector.getFirstSelectedObject()) { mSelector.getFirstSelectedObject()->setHighlighted(false); } pause(); //saving/loading only possible in movement state return false; } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 1498 ] ] ]
1754c8ec947b813d2b6066f1cff2d1a7436958a0
acb1b178a62de7a55a47dc87a7148a8f7a4618ea
/SettlersOfCatanMainProject/SettlersOfCatanGame/map.h
5ffa53e1ea069c438e64b50f8d4086eebc058994
[]
no_license
EddyReyes/gsp360-settlersofcatan
1e05996052aef6a60b4279b2db95dec67866d6f4
8cc8e7194abba801f69b22fc06a2d985c3ecd98e
refs/heads/master
2021-05-29T12:13:51.043295
2011-02-26T00:44:36
2011-02-26T00:44:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,394
h
#pragma once // yo dawg, I heard you will need a Game class. so I'm putting a Game class before the Game class so you can declare before you declare. class Game; class TradeBank; #include "sdl/sdl.h" #include "sdl/sdl_ttf.h" #include <iostream> #include <ctime> #include <windows.h> #include <string> #include "dice.h" #include "edge.h" #include "node.h" #include "center.h" #include "stndrd.h" #include "player.h" #include "game.h" #include "tradebank.h" using namespace std; class map { private: //===surfaces used for images=============== SDL_Surface *playerTag; SDL_Surface *SettlersWinner; SDL_Surface *resourceListMsg[5]; SDL_Surface *tradeCard; SDL_Surface *buildCard; SDL_Surface *resourceCard; SDL_Surface *background1; SDL_Surface *roadTile[4]; SDL_Surface *settlementTile[4]; SDL_Surface *cityTile[4]; SDL_Surface *testSelect; SDL_Surface *hexTile; SDL_Surface *DevHand; SDL_Surface *woodTile; SDL_Surface *sheepTile; SDL_Surface *brickTile; SDL_Surface *stoneTile; SDL_Surface *wheatTile; SDL_Surface *chitTile[10]; SDL_Surface *thief; SDL_Surface *pickToTrade; SDL_Surface *standardLegend; SDL_Surface *cancelLegend; SDL_Surface *extraTradeRules; //=== map-only load_image and apply_surface SDL_Surface *load_image( std::string filename ); void apply_surface(int x, int y,SDL_Surface* source, SDL_Surface* destination, SDL_Rect *clip); public: //============Trade stuff===================== TradeBank* tradebank; //============PLACEHOLDER NUM FOR FREE TWO ROADS AND FREE TWO RESOURCES int placeholderFREE; int soundQueue; // ============== DICE STUFF ========================= Dice dice; int dice1; int dice2; bool rolledDice; //=== the map is initialized with an internal resourceDeck and developmentDeck rsc rsc; dvc dvc; // =============== MAPSTATES (THEY ARE PUBLIC BECAUSE GAME.CPP NEEDS THEM SOMETIMES ==================== int mapState; static const int BEGINTURN = 0; // start state to trigger dice roll and such; static const int MAP = 1; // play state static const int BUILDCARD = 2; // play state static const int RESOURCELIST = 3; // play state static const int DEVHAND = 4; // play state //static const int TRADE = 5; // play state static const int BUILDROAD = 6; // play state static const int BUILDSETTLEMENT = 7; // play state static const int BUILDCITY = 8; // play state static const int TURNONESETTLEMENT = 9; static const int TURNONEROAD = 10; static const int TURNTWOSETTLEMENT = 11; static const int TURNTWOROAD = 12; static const int FREETWOROADS = 13; static const int FREETWORESOURCES = 14; static const int PICKMONOPOLY = 15; static const int SETTHETHIEF = 16; static const int TRADETARGET = 17; static const int TRADEPLAYERSCREEN = 18; static const int TRADEBANKHARBORSCREEN = 19; static const int SOMEONEWON = 20; static const int ENDTURN = 99; // play state (mainly to trigger the changing of players in game.cpp) static const int NOT_A_PLAYER = 4; // play state (mainly to trigger the changing of players in game.cpp) //==============MAP INITIALIZERS SETUP IN THE map.cpp FILE=========== int overallTurn; Edge myEdges[144]; Node myNodes[54]; Center myCenters[19]; int myChits[18]; map::map(); Node * getNode(Node * population, int popCount, int ID); int getEdge(Edge * population, int popCount, int start, Node * from); int getEdgeFromCount(Edge * population, int popCount, Node * from); char randomHarbor(int resource[]); void setHarbor(Node* harbor); void initializeCenters(void); map::~map(); //====CONSTRUCTION DEVICS HANDLED IN THE mapConstruct.cpp FILE============= int nodeSelectron; int roadSelectron; int centerSelectron; void map::whichNodeIsWithin(int const & x, int const & y, int radius); void map::whichRoadIsWithin(int const & x, int const & y, int radius); void map::whichCenterIsWithin(int const & x, int const & y, int radius); bool map::constructRoadOnMap(Game * g); bool map::constructSettlementOnMap(Game * g); bool map::constructSettlementOnMapAnywhere(Game * g); bool map::constructCityOnMap(Game * g); bool map::constructThiefOnMap(Game * g); //=======DRAW FUNCTIONS HANDLED IN THE mapImage.cpp FILE=============== void map::draw(SDL_Surface * screen, Game * g); void map::loadImages(void); void map::initializeImages(void); void map::drawDiceRoll(SDL_Surface * screen, Game * g); void map::drawtradeCard(SDL_Surface * screen, Game* g); void map::drawDevHand(SDL_Surface * screen, Game * g); void map::drawResourceList(SDL_Surface * screen, Game * g); void map::drawBuildCard(SDL_Surface * screen); void map::drawNodeSelectron(SDL_Surface * screen); void map::drawRoadSelectron(SDL_Surface * screen); void map::drawBoard(SDL_Surface * screen); void map::drawPlayerTag(SDL_Surface * screen, Game * g); void map::drawWinScreen(SDL_Surface * screen); void map::drawResourceGrab(SDL_Surface * screen); void map::drawCenterSelectron(SDL_Surface * screen); void map::drawPickTradeTarget(SDL_Surface * screen, Game * g); void map::drawThiefExplanation(SDL_Surface * screen, Game * g); void map::drawCancelInstructions(SDL_Surface * screen, Game * g); void map::drawStandardInstructions(SDL_Surface * screen, Game * g); void map::drawInstructions(SDL_Surface * screen, Game * g); void map::drawFreeSettlementInstructions(SDL_Surface * screen, Game * g); void map::drawFreeRoadInstructions(SDL_Surface * screen, Game * g); void map::drawExtraTradeRules(SDL_Surface * screen, Game * g); void map::drawVictoryPoints(SDL_Surface * screen, Game * g); void map::shutdownImages(void); //========HANDLE INPUTS, ALL IN THE mapInput.cpp FILE================ void map::handleInput(SDL_Event e, Game * g); void map::handleInput_BEGINTURN(SDL_Event e, Game * g); void map::handleInput_MAP(SDL_Event e, Game * g); void map::handleInput_BUILDCARD(SDL_Event e, Game * g); void map::handleInput_RESOURCELIST(SDL_Event e, Game * g); void map::handleInput_DEVHAND(SDL_Event e, Game * g); void map::handleInput_BUILDROAD(SDL_Event e, Game * g); void map::handleInput_BUILDSETTLEMENT(SDL_Event e, Game * g); void map::handleInput_BUILDCITY(SDL_Event e, Game * g); void map::handleInput_TURNONESETTLEMENT(SDL_Event e, Game * g); void map::handleInput_TURNONEROAD(SDL_Event e, Game * g); void map::handleInput_TURNTWOSETTLEMENT(SDL_Event e, Game * g); void map::handleInput_TURNTWOROAD(SDL_Event e, Game * g); void map::handleInput_FREETWOROADS(SDL_Event e, Game * g); void map::handleInput_FREETWORESOURCES(SDL_Event e, Game * g); void map::handleInput_PICKMONOPOLY(SDL_Event e, Game * g); void map::handleInput_SETTHETHIEF(SDL_Event e, Game * g); void map::handleInput_TRADETARGET(SDL_Event e, Game * g); void map::handleInput_TRADEPLAYERSCREEN(SDL_Event e, Game * g); void map::handleInput_TRADEBANKHARBORSCREEN(SDL_Event e, Game * g); //=======MAP TTFs==================== TTF_Font *font; SDL_Color textColor; //mapGameplay.cpp bool map::calculateVictoryPoints(Game* g); bool map::calculateLongestRoad(Game* g); void map::thiefIsRolled(Game* g); void map::steal(Game* g, int victim); void map::calcLargestArmy(Game* g); void map::playMonopolyCard(char type, Game * g); };
[ "ikyle620@d3192985-ef62-ff69-2b9f-3971aa3a1032", "randy.hatakeda@d3192985-ef62-ff69-2b9f-3971aa3a1032", "Anarkin002@d3192985-ef62-ff69-2b9f-3971aa3a1032", "anarkin002@d3192985-ef62-ff69-2b9f-3971aa3a1032", "90jmlg@d3192985-ef62-ff69-2b9f-3971aa3a1032" ]
[ [ [ 1, 4 ], [ 6, 12 ], [ 14, 19 ], [ 21, 28 ], [ 30, 33 ], [ 35, 39 ], [ 41, 51 ], [ 53, 59 ], [ 62, 72 ], [ 77, 84 ], [ 86, 114 ], [ 116, 118 ], [ 121, 141 ], [ 143, 193 ], [ 201, 201 ], [ 203, 203 ] ], [ [ 5, 5 ], [ 20, 20 ], [ 52, 52 ], [ 60, 61 ], [ 73, 76 ], [ 119, 120 ], [ 142, 142 ], [ 194, 200 ], [ 202, 202 ] ], [ [ 13, 13 ], [ 40, 40 ] ], [ [ 29, 29 ], [ 34, 34 ], [ 85, 85 ] ], [ [ 115, 115 ] ] ]
2a70bef14d21719dd987d1f81c4beef4cb120456
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/AIGoalGetBackup.cpp
ddccbbbd745f4d63fdcbdcc74d3ecee9268222cf
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
10,258
cpp
// ----------------------------------------------------------------------- // // // MODULE : AIGoalGetBackup.cpp // // PURPOSE : AIGoalGetBackup implementation // // CREATED : 7/30/01 // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // ----------------------------------------------------------------------- // #include "stdafx.h" #include "AIGoalGetBackup.h" #include "AIHumanState.h" #include "AINodeMgr.h" #include "AISenseRecorderAbstract.h" #include "AIGoalMgr.h" #include "AI.h" #include "AIStimulusMgr.h" #include "AITarget.h" DEFINE_AI_FACTORY_CLASS_SPECIFIC(Goal, CAIGoalGetBackup, kGoal_GetBackup); // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::Con/destructor // // PURPOSE: Factory Con/destructor // // ----------------------------------------------------------------------- // CAIGoalGetBackup::CAIGoalGetBackup() { m_hNodeBackup = LTNULL; m_hFailedNode = NULL; m_eStimulusID = kStimID_Unset; } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::Save / Load // // PURPOSE: Save / Load // // ----------------------------------------------------------------------- // void CAIGoalGetBackup::Save(ILTMessage_Write *pMsg) { super::Save(pMsg); SAVE_HOBJECT(m_hNodeBackup); SAVE_HOBJECT(m_hFailedNode); SAVE_VECTOR(m_vEnemySeenPos); SAVE_DWORD(m_eStimulusID); } void CAIGoalGetBackup::Load(ILTMessage_Read *pMsg) { super::Load(pMsg); LOAD_HOBJECT(m_hNodeBackup); LOAD_HOBJECT(m_hFailedNode); LOAD_VECTOR(m_vEnemySeenPos); LOAD_DWORD_CAST(m_eStimulusID, EnumAIStimulusID); } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::ActivateGoal // // PURPOSE: Activate goal. // // ----------------------------------------------------------------------- // void CAIGoalGetBackup::ActivateGoal() { super::ActivateGoal(); AIASSERT(m_hNodeBackup != LTNULL, m_pAI->m_hObject, "CAIGoalGetBackup::ActivateGoal: AINodeBackup is NULL."); if( m_pAI->GetState()->GetStateType() != kState_HumanGetBackup ) { // Ignore all senses. m_pAI->SetCurSenseFlags(kSense_None); m_pGoalMgr->LockGoal(this); AINodeBackup* pNode = (AINodeBackup*)g_pLTServer->HandleToObject(m_hNodeBackup); AIASSERT( pNode, m_pAI->m_hObject, "CAIGoalGetBackup::ActivateGoal: Node is NULL" ); if( pNode ) { m_pAI->SetState( kState_HumanGetBackup ); CAIHumanStateGetBackup* pStateGetBackup = (CAIHumanStateGetBackup*)(m_pAI->GetState()); pStateGetBackup->SetDest( pNode ); pStateGetBackup->SetEnemySeenPos( m_vEnemySeenPos ); if( m_eStimulusID ) { // Remove the stimulus. g_pAIStimulusMgr->RemoveStimulus( m_eStimulusID ); } m_eStimulusID = g_pAIStimulusMgr->RegisterStimulus( kStim_AllyDistressVisible, m_pAI->m_hObject, pNode->m_hObject, CAIStimulusRecord::kDynamicPos_TrackTarget, pNode->GetStimulusRadius() ); } } } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::DeactivateGoal // // PURPOSE: Deactivate goal. // // ----------------------------------------------------------------------- // void CAIGoalGetBackup::DeactivateGoal() { super::DeactivateGoal(); if( m_eStimulusID ) { // Remove the stimulus. g_pAIStimulusMgr->RemoveStimulus( m_eStimulusID ); m_eStimulusID = kStimID_Unset; } } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::UpdateGoal // // PURPOSE: Update goal. // // ----------------------------------------------------------------------- // void CAIGoalGetBackup::UpdateGoal() { CAIState* pState = m_pAI->GetState(); switch(pState->GetStateType()) { case kState_HumanGetBackup: HandleStateGetBackup(); break; case kState_HumanGoto: HandleStateGoto(); break; case kState_HumanSearch: HandleStateSearch(); break; case kState_HumanDraw: HandleStateDraw(); break; case kState_HumanAware: break; // Unexpected State. default: AIASSERT(0, m_pAI->m_hObject, "CAIGoalGetBackup::UpdateGoal: Unexpected State."); } } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::HandleStateGetBackup // // PURPOSE: Determine what to do when in state GetBackup. // // ----------------------------------------------------------------------- // void CAIGoalGetBackup::HandleStateGetBackup() { switch( m_pAI->GetState()->GetStateStatus() ) { case kSStat_Initialized: { // Bail if target gets in the way of the path to the node. AINodeBackup* pNodeBackup = (AINodeBackup*)g_pLTServer->HandleToObject( m_hNodeBackup ); if( ( !pNodeBackup ) || ( pNodeBackup->GetStatus( m_pAI->GetPosition(), m_pAI->GetTarget()->GetObject() ) != kStatus_Ok ) ) { m_fCurImportance = 0.f; } } break; case kSStat_FailedComplete: m_hFailedNode = m_hNodeBackup; m_fCurImportance = 0.f; break; case kSStat_StateComplete: { AINodeBackup* pNodeBackup = (AINodeBackup*)g_pLTServer->HandleToObject( m_hNodeBackup ); if( pNodeBackup ) { pNodeBackup->IncrementArrivalCount(); } m_hNodeBackup = LTNULL; uint32 cResponders = g_pAIStimulusMgr->GetNumResponders( m_eStimulusID ); if( cResponders == 0 ) { m_pAI->PlaySound( kAIS_BackupFail, LTFALSE ); } else { m_pAI->PlaySound( kAIS_OrderBackup, LTFALSE ); } // Only pay attention to really important senses. m_pAI->SetCurSenseFlags( kSense_SeeEnemy | kSense_HearEnemyWeaponFire | kSense_HearEnemyWeaponImpact | kSense_HearAllyWeaponFire | kSense_HearAllyPain | kSense_SeeDangerousProjectile | kSense_SeeCatchableProjectile); // Run back to where enemy was last seen. m_pAI->SetState( kState_HumanGoto ); CAIHumanStateGoto* pStateGoto = (CAIHumanStateGoto*)(m_pAI->GetState()); pStateGoto->SetDest( m_vEnemySeenPos ); pStateGoto->SetMovement( kAP_Run ); pStateGoto->SetWeaponPosition( kAP_Up ); } break; // Unexpected StateStatus. default: AIASSERT(0, m_pAI->m_hObject, "CAIGoalGetBackup::HandleStateGetBackup: Unexpected State Status."); } } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::HandleStateGoto // // PURPOSE: Determine what to do when in state Goto. // // ----------------------------------------------------------------------- // void CAIGoalGetBackup::HandleStateGoto() { switch( m_pAI->GetState()->GetStateStatus() ) { case kSStat_Initialized: break; case kSStat_StateComplete: if(m_pAI->CanSearch()) { SetStateSearch(); } else { m_pGoalMgr->UnlockGoal(this); m_pAI->SetState( kState_HumanAware ); } break; // Unexpected StateStatus. default: AIASSERT(0, m_pAI->m_hObject, "CAIGoalGetBackup::HandleStateGoto: Unexpected State Status."); } } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::SelectTriggeredAISound // // PURPOSE: Select appropriate AI sound. // // ----------------------------------------------------------------------- // LTBOOL CAIGoalGetBackup::SelectTriggeredAISound(EnumAISoundType* peAISoundType) { *peAISoundType = kAIS_FindBackup; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::HandleGoalAttractors // // PURPOSE: React to an attractor. // // ----------------------------------------------------------------------- // AINode* CAIGoalGetBackup::HandleGoalAttractors() { AINode* pNode = LTNULL; if(m_hStimulusSource != LTNULL) { if(m_hNodeBackup == LTNULL) { // Lock the failed cover node, so that we don't try to use it again. BlockAttractorNodeFromSearch( m_hFailedNode ); // Look for a backup node. // If one is found, this goal activates. pNode = super::HandleGoalAttractors(); if(pNode != LTNULL) { // Do not go to a backup node if we are already in its inner radius. AINodeBackup* pNodeBackup = (AINodeBackup*)pNode; if( ( pNodeBackup->GetStimulusRadiusSqr() > pNodeBackup->GetPos().DistSqr( m_pAI->GetPosition() ) ) || ( pNodeBackup->GetStatus( m_pAI->GetPosition(), m_hStimulusSource ) != kStatus_Ok ) ) { m_fCurImportance = 0.f; m_hNodeBackup = LTNULL; pNode = LTNULL; } else { m_hNodeBackup = pNode->m_hObject; m_hStimulusSource = LTNULL; } } // If we locked a node prior to the search, unlock it. UnblockAttractorNodeFromSearch( m_hFailedNode ); } } return pNode; } // ----------------------------------------------------------------------- // // // ROUTINE: CAIGoalGetBackup::HandleSense // // PURPOSE: React to a sense. // // ----------------------------------------------------------------------- // LTBOOL CAIGoalGetBackup::HandleGoalSenseTrigger(AISenseRecord* pSenseRecord) { // If this is already the current goal, and we've already reached our backup // node, exit the goal if anything is sensed. if( m_pGoalMgr->IsCurGoal(this) && ( m_pAI->GetState()->GetStateType() != kState_HumanGetBackup ) && ( pSenseRecord->nLastStimulusAlarmLevel >= 10 ) ) { m_pGoalMgr->UnlockGoal(this); m_fCurImportance = 0.f; } else if(super::HandleGoalSenseTrigger(pSenseRecord)) { m_pAI->IncrementAlarmLevel( pSenseRecord->nLastStimulusAlarmLevel ); // Record the AIs position, because we know we can find a path to here. m_vEnemySeenPos = m_pAI->GetPosition(); // Force an extra immediate call to HandleGoalAtractors. // This is because HandleGoalAtractors will not get called // if another goal is currently locked. if( HandleGoalAttractors() != LTNULL ) { return LTTRUE; } } return LTFALSE; }
[ [ [ 1, 380 ] ] ]
8d3b4318ea9ea78dfe8f8976a83a18bf7653ba88
dd5c8920aa0ea96607f2498701c81bb1af2b3c96
/multicrewcore/multicrewcore.cpp
56d1a843d7a57472e192f08a784d1d8ac1e80445
[]
no_license
BackupTheBerlios/multicrew-svn
913279401e9cf886476a3c912ecd3d2b8d28344c
5087f07a100f82c37d2b85134ccc9125342c58d1
refs/heads/master
2021-01-23T13:36:03.990862
2005-06-10T16:52:32
2005-06-10T16:52:32
40,747,367
0
0
null
null
null
null
UTF-8
C++
false
false
6,301
cpp
/* Multicrew Copyright (C) 2004,2005 Stefan Schimanski 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. */ #pragma warning (disable : 4786) #include "common.h" #define _WIN32_DCOM #include <objbase.h> #include <list> #include <deque> #include <map> #include <set> #include <vector> #include <sstream> #include "../stlplus/source/string_utilities.hpp" #include "streams.h" #include "signals.h" #include "multicrewcore.h" #include "position.h" #include "log.h" #include "config.h" #include "fsuipcmodule.h" /*********************************************************************/ class MulticrewCoreImpl : public MulticrewCore { public: MulticrewCoreImpl(); virtual ~MulticrewCoreImpl(); void createModules(); void start( bool host, SmartPtr<Connection> con ); void stop(); void log( std::string line ); double time(); void callbackAsync(); void triggerAsyncCallback( AsyncCallee *callee ); void ackNewFrame(); void registerModule( MulticrewModule *module ); void unregisterModule( MulticrewModule *module ); struct Data; Data *d; }; struct MulticrewCoreImpl::Data { /* modules */ std::map<std::string, MulticrewModule*> modules; SmartPtr<PositionModule> posModule; SmartPtr<FsuipcModule> fsuipcModule; std::set<AsyncCallee*> asyncCallees; /* timing */ __int64 perfTimerFreq; __int64 startTime; CRITICAL_SECTION critSect; }; static MulticrewCoreImpl *multicrewCore = 0; SmartPtr<MulticrewCore> MulticrewCore::multicrewCore() { if( ::multicrewCore==0 ) { ::multicrewCore = new MulticrewCoreImpl(); ::multicrewCore->createModules(); } // dout << "MulticrewCore::multicrewCore()" << std::endl; return ::multicrewCore; } MulticrewCoreImpl::MulticrewCoreImpl() { d = new Data; CoInitializeEx( NULL, COINIT_MULTITHREADED ); dout << "MulticrewCore" << std::endl; InitializeCriticalSection( &d->critSect ); /* initialize timing stuff */ if( !QueryPerformanceFrequency((LARGE_INTEGER*)&d->perfTimerFreq) ) dlog << "No performance timer available" << std::endl; QueryPerformanceCounter( (LARGE_INTEGER*)&d->startTime ); } MulticrewCoreImpl::~MulticrewCoreImpl() { dout << "~MulticrewCore" << std::endl; d->modules.clear(); ::multicrewCore = 0; CoUninitialize(); DeleteCriticalSection( &d->critSect ); delete d; } void MulticrewCoreImpl::createModules() { d->posModule = new PositionModule(); d->fsuipcModule = new FsuipcModule(); } double MulticrewCoreImpl::time() { __int64 now; QueryPerformanceCounter( (LARGE_INTEGER*)&now ); return ((double)now-d->startTime)/d->perfTimerFreq; } void MulticrewCoreImpl::ackNewFrame() { //dout << "frame callback" << std::endl; frameSignal.emit(); } void MulticrewCoreImpl::registerModule( MulticrewModule *module ) { dout << "module " << module->id() << " registered" << std::endl; // register module d->modules[module->id().c_str()] = module; // setup fsuipc watches if( !d->fsuipcModule.isNull() ) { SmartPtr<FileConfig> config = module->config(); for( int i=1; ; i++ ) { std::ostringstream num; num << i; // get fsuipc line std::string line = config->stringValue( "fsuipc", num.str(), "" ); if( line.length()==0 ) break; // break line into components std::vector<std::string> tokens = split( line, "," ); if( tokens.size()!=3 ) dlog << "invalid fsuipc for " << module->id << " id " << num << std::endl; // convert into datatypes int id = (int)to_uint( trim(tokens[0]) ); int len = (int)to_uint( trim(tokens[1]) ); bool safe = to_bool( trim(tokens[2]) ); dout << "fsuipc watch " << id << " len=" << len << " safe=" << safe << std::endl; // add to watches d->fsuipcModule->watch( id, len, safe ); } } } void MulticrewCoreImpl::unregisterModule( MulticrewModule *module ) { dout << "module " << module->id() << " unregistered" << std::endl; // find and remove module from module list std::map<std::string, MulticrewModule*>::iterator res = d->modules.find( module->id().c_str() ); if( res!=d->modules.end() ) { d->modules.erase( res ); } } void MulticrewCoreImpl::start( bool host, SmartPtr<Connection> con ) { d->fsuipcModule->start(); d->posModule->start(); ChannelProtocol::start( host, con ); } void MulticrewCoreImpl::stop() { d->fsuipcModule->stop(); d->posModule->stop(); ChannelProtocol::stop(); } void MulticrewCoreImpl::log( std::string line ) { logged.emit( line.c_str() ); } void MulticrewCoreImpl::triggerAsyncCallback( AsyncCallee *callee ) { EnterCriticalSection( &d->critSect ); bool first = d->asyncCallees.size()==0; //dout << "triggering async (first" << first << ")" << std::endl; // add callee to list of callback requesters d->asyncCallees.insert( callee ); // let async callback handler know about the new callback if( first ) initAsyncCallback.emit(); LeaveCriticalSection( &d->critSect ); } void MulticrewCoreImpl::callbackAsync() { EnterCriticalSection( &d->critSect ); for( std::set<AsyncCallee*>::iterator it = d->asyncCallees.begin(); it!=d->asyncCallees.end(); it++ ) { // do callback (*it)->asyncCallback(); } d->asyncCallees.clear(); LeaveCriticalSection( &d->critSect ); } /*********************************************************************************/ void AsyncCallee::triggerAsyncCallback() { //dout << "triggering async" << std::endl; MulticrewCore::multicrewCore()->triggerAsyncCallback( this ); }
[ "schimmi@cb9ff89a-abed-0310-8fc6-a4cabe7d48c9" ]
[ [ [ 1, 242 ] ] ]
d2306cd7312808caef31a43029054472134aa79f
1caba14ec096b36815b587f719dda8c963d60134
/branches/smxgroup/smx/libsmx/math.cpp
ca6962a2a440e3b50dfb5b6ac177ccddb15e9724
[]
no_license
BackupTheBerlios/smx-svn
0502dff1e494cffeb1c4a79ae8eaa5db647e5056
7955bd611e88b76851987338b12e47a97a327eaf
refs/heads/master
2021-01-10T19:54:39.450497
2009-03-01T12:24:56
2009-03-01T12:24:56
40,749,397
0
0
null
null
null
null
UTF-8
C++
false
false
15,303
cpp
// Copyright (C) 1999 by Prime Data Corp. All Rights Reserved. // For information contact [email protected] #include "stdafx.h" #include <ctype.h> #include <math.h> #include <time.h> #include "qstr.h" #include "qobj.h" #include "qctx.h" #include "util.h" #ifdef unix #include "unix.h" #endif class qObjLVal { qCtx *myCtx; qObjDbl *myObj; CStr myName; public: qObjLVal(qCtx *ctx) {myObj = 0; myCtx = ctx;} double Set(double val) { if (this) if (!myObj) { if (myName) myObj = (qObjDbl*) (void *) myCtx->MapObj(val, myName); } else { myObj->Set(val); } return val; } void Map(CStr name) {if (this) {myName = name; myObj = 0;}} }; double ParseExpr(const char *&p, qCtx *ctx, qObjLVal*lval); inline void PutDbl(double num, qStr* out) { out->PutN(num); } void EvalAdd(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = 0; for (i = 0; i < args->Count(); ++i) { acc += ParseDbl((*args)[i]); } PutDbl(acc, out); } void EvalSub(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = ParseDbl((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc -= ParseDbl((*args)[i]); } PutDbl(acc, out); } void EvalDiv(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = ParseDbl((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc /= ParseDbl((*args)[i]); } PutDbl(acc, out); } void EvalMult(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = ParseDbl((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc *= ParseDbl((*args)[i]); } PutDbl(acc, out); } void EvalIncr(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = 0; for (i = 0; i < args->Count(); ++i) { qObj *obj; if (ctx->Find(&obj, args->GetAt(i))) { qStrBuf tmp; char *ep; obj->Eval(ctx, &tmp); acc = strtod(tmp.GetS(), &ep) + 1; } else acc = 1; ctx->MapObjLet(ctx->CreateObj(acc), args->GetAt(i)); } } void EvalDecr(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = 0; for (i = 0; i < args->Count(); ++i) { qObj *obj; if (ctx->Find(&obj, args->GetAt(i))) { qStrBuf tmp; char *ep; obj->Eval(ctx, &tmp); acc = strtod(tmp.GetS(), &ep) - 1; } else acc = -1; ctx->MapObjLet(ctx->CreateObj(acc), args->GetAt(i)); } } void EvalAddX(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc; qObj *obj = NULL; CStr var = (*args)[0]; if (ctx->Find(&obj, var)) { qStrBuf tmp; char *ep; obj->Eval(ctx, &tmp); acc = strtod(tmp.GetS(), &ep); } else acc = 0; if (args->Count() > 0) { for (i = 1; i < args->Count(); ++i) { acc += ParseDbl((*args)[i]); } } if (obj) ctx->MapObjLet(ctx->CreateObj(acc), var); else ctx->MapObj(ctx->CreateObj(acc), var); } void EvalSubX(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc; qObj *obj; CStr var = (*args)[0]; if (ctx->Find(&obj, var)) { qStrBuf tmp; char *ep; obj->Eval(ctx, &tmp); acc = strtod(tmp.GetS(), &ep); } else acc = 0; if (args->Count() > 0) { for (i = 1; i < args->Count(); ++i) { acc -= ParseDbl((*args)[i]); } } if (obj) ctx->MapObjLet(ctx->CreateObj(acc), var); else ctx->MapObj(ctx->CreateObj(acc), var); } void EvalIAdd(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; int acc = 0; for (i = 0; i < args->Count(); ++i) { acc += ParseInt((*args)[i]); } out->PutN(acc); } void EvalISub(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; int acc = ParseInt((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc -= ParseInt((*args)[i]); } out->PutN(acc); } void EvalIDiv(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; int acc = ParseInt((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc /= ParseInt((*args)[i]); } out->PutN(acc); } void EvalIMult(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; int acc = ParseInt((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc *= ParseInt((*args)[i]); } out->PutN(acc); } void EvalIMod(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("imod", 2, 2); int v1 = ParseInt((*args)[0]); int v2 = ParseInt((*args)[1]); out->PutN(v1%v2); } void EvalMax(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { if (args->Count() == 0 ) return; int i; double acc = ParseDbl((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc = max(acc, ParseDbl((*args)[i])); } PutDbl(acc, out); } void EvalMin(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { if (args->Count() == 0 ) return; int i; double acc = ParseDbl((*args)[0]); for (i = 1; i < args->Count(); ++i) { acc = min(acc, ParseDbl((*args)[i])); } PutDbl(acc, out); } double ParseDbl(const char *&p) { char *e; double val = strtod(p, &e); p = e; return val; } void ParseExprArgs(const char *&p, qCtx *ctx, qArgAry *ary) { ++p; while (*p) { if (!isspace(*p)){ const char *b = p; while (*p && *p != ',' && *p != ')') { ++p; } ary->Add(CStr(b, p - b)); if (*p ==')') { ++p; return; } else if (*p ==',') ++p; } else ++p; } } double ParseExprVar(const char *&p, qCtx *ctx, qObjLVal *lval) { const char *n = p; while ( *p ) { if (!(__iscsym(*p) || *p == '-' || *p == '/')) { break; } ++p; } qObj *obj; CStr name(n, p - n); lval->Map(name); if (ctx->Find(&obj, name)) { qArgAry ary; while(isspace(*p)) ++p; if (*p == '(') { ParseExprArgs(p, ctx, &ary); } qStrBuf out; obj->Eval(ctx, &out, &ary); const char *t = out; return ::ParseDbl(t); } else { return 0.0; } } double ParseExprTop(const char *&p, qCtx *ctx, qObjLVal *lval); double ParseExprL2(const char *&p, qCtx *ctx, qObjLVal *lval); double ParseExprBinOp2(const char *&p, qCtx *ctx, double v1, qObjLVal *lval) { while ( *p ) { if (isspace(*p)) ++p; else switch(*p) { case '/' : { if (p[1]=='=') { v1 /= ParseExprTop(p+=2, ctx, 0); if (lval) lval->Set(v1); } else { v1 /= ParseExprL2(p+=1, ctx, 0); } break; } case '*' : { if (p[1]=='=') { v1 *= ParseExprTop(p+=2, ctx, 0); if (lval) lval->Set(v1); } else { v1 *= ParseExprL2(p+=1, ctx, 0); } break; } case '^' : { if (p[1]=='=') { v1 = pow(v1,ParseExprTop(p+=2, ctx, 0)); if (lval) return lval->Set(v1); } else { v1 = pow(v1,ParseExprL2(p+=1, ctx, 0)); } break; } default : { return v1; } } } return v1; } double ParseExprBinOp(const char *&p, qCtx *ctx, double v1, qObjLVal *lval) { while ( *p ) { if (isspace(*p)) ++p; else switch(*p) { case '=' : { if (p[1] == '=') { v1 = (v1 == ParseExprTop(p+=2, ctx, 0)); } else { v1 = ParseExprTop(p+=1, ctx, 0); if (lval) lval->Set(v1); } break; } case '+' : { if (p[1]=='=') { v1 += ParseExprTop(p+=2, ctx, 0); if (lval) lval->Set(v1); } else { v1 += ParseExprL2(p+=1, ctx, 0); } break; } case '-' : { if (p[1]=='=') { v1 -= ParseExprTop(p+=2, ctx, 0); if (lval) lval->Set(v1); } else { v1 -= ParseExprL2(p+=1, ctx, 0); } break; } case ')' : { return v1; } default : { const char * t = p; v1 = ParseExprBinOp2(p, ctx, v1, lval); if (t == p) return v1; } } } return v1; } double ParseExprTop(const char *&p, qCtx *ctx, qObjLVal *lval) { double val = ParseExpr(p, ctx, lval); return ParseExprBinOp(p, ctx, val, lval); } double ParseExprL2(const char *&p, qCtx *ctx, qObjLVal *lval) { double val = ParseExpr(p, ctx, lval); return ParseExprBinOp2(p, ctx, val, lval); } double ParseExprGroup(const char *&p, qCtx *ctx, qObjLVal *lval) { ++p; double val = ParseExprTop(p, ctx, lval); while(isspace(*p)) ++p; if (*p == ')') { ++p; } return val; } double ParseExprLV(const char *&p, qCtx *ctx, qObjLVal *lval) { while(isspace(*p)) ++p; if (*p == '(') return ParseExprGroup(p, ctx, lval); else return ParseExprVar(p, ctx, lval); } double ParseExpr(const char *&p, qCtx *ctx, qObjLVal *lval) { double val; CStr name; while ( *p ) { if (__iscsymf(*p)) { qObjLVal var(ctx); return val = ParseExprVar(p, ctx, &var); } else if (isdigit(*p)) { return val = ::ParseDbl(p); } else if (*p == '(') { return val = ParseExprGroup(p, ctx, lval); } else if (*p == '-') { if (p[1] == '-') { qObjLVal var(ctx); val = ParseExprLV(p+=2, ctx, &var); return var.Set(--val); } else { return -ParseExpr(++p, ctx, lval); } } else if (*p == '+') { if (p[1] == '+') { qObjLVal var(ctx); val = ParseExprLV(p+=2, ctx, &var); return var.Set(++val); } else { return ParseExpr(++p, ctx, lval); } } else if (*p == '!') { return ParseExpr(++p, ctx, lval) != 0.0; } if (*p) { ++p; } } return 0.0; } void EvalExpr(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("expr", 1, 1); CStr expr = (*args)[0]; const char *p = (const char *) expr; double v = ParseExprTop(p, ctx, 0); PutDbl(v, out); } void EvalRand(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("rand", 0, 1); int range; if (args->Count() > 0) { range = (int) ParseInt((*args)[0]); out->PutN((int) ((((unsigned long)rand())<<16)|(((unsigned long)rand()))) % range); } else { out->PutN(rand()); } } void EvalRound(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("round", 1, 2); double val = ParseDbl((*args)[0]); int num = 0; int dec; int sig; if (args->Count() == 2) { num = ParseInt((*args)[1]); } char *buf = _fcvt(val, num, &dec, &sig); if (sig) out->PutC('-'); if (dec <= 0) { if (*buf) { out->PutC('.'); for ( ; dec < 0; ++dec) { out->PutC('0'); } out->PutS(buf); } else out->PutC('0'); } else { for ( ; *buf && dec > 0; dec--) { out->PutC(*buf++); } if (!*buf) { for ( ; dec > 0; dec--) { out->PutC('0'); } } else { out->PutC('.'); out->PutS(buf); } } } void EvalTrunc(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("trunc", 1, 1); int r = ParseInt((*args)[0]); out->PutN(r); } void EvalAbs(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { out->PutN(fabs(ParseDbl((*args)[0]))); } void EvalIAbs(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { out->PutN(abs(ParseInt((*args)[0]))); } void EvalAsc(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { out->PutC(ParseInt((*args)[0])); } void EvalOrd(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { CStr p = (*args)[0]; if (!p.IsEmpty()) { out->PutN(*(unsigned char*)(p.Data())); } } void EvalAvg(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int i; double acc = 0; for (i = 0; i < args->Count(); ++i) { acc += ParseDbl((*args)[i]); } PutDbl(acc/args->Count(), out); } void EvalINot(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { out->PutN(~ParseInt((*args)[0])); } void EvalIXor(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int r = ParseInt((*args)[0]); int i; for (i = 1; i < args->Count(); ++i){ r ^= ParseInt((*args)[i]); } out->PutN(r); } void EvalIOr(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int r = ParseInt((*args)[0]); int i; for (i = 1; i < args->Count(); ++i){ r |= ParseInt((*args)[i]); } out->PutN(r); } void EvalIAnd(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { int r = ParseInt((*args)[0]); int i; for (i = 1; i < args->Count(); ++i){ r &= ParseInt((*args)[i]); } out->PutN(r); } void EvalLShift(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("lshift", 2, 2); int r = ParseInt((*args)[0]); int s = ParseInt((*args)[1]); out->PutN(r<<s); } void EvalRShift(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("rshift", 2, 2); int r = ParseInt((*args)[0]); int s = ParseInt((*args)[1]); out->PutN(r>>s); } void EvalRadix(qCtx *ctx, qStr *out, CStr s, int r, int b) { if (b <= 0) { ctx->Throw(out, 649, "Radix base must be > 0"); return; } char *e; unsigned long n = strtoul(s, &e, b); char tmp[sizeof(long) + 2]; out->PutS(_ultoa(n,tmp,r)); } void EvalHex(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { EvalRadix(ctx, out, (*args)[0], 16, ParseInt((*args)[1])); } void EvalOct(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { EvalRadix(ctx, out, (*args)[0], 8, ParseInt((*args)[1])); } void EvalBin(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { EvalRadix(ctx, out, (*args)[0], 2, ParseInt((*args)[1])); } void EvalRadix(const void *data, qCtx *ctx, qStr *out, qArgAry *args) { VALID_ARGC("radix", 2, 2); EvalRadix(ctx, out, (*args)[0],ParseInt((*args)[1]),ParseInt((*args)[2])); } static bool gLoaded = false; void LoadMath(qCtx *ctx) { //math if (!gLoaded) { gLoaded = true; time_t t = time(&t); #ifdef WIN32 clock_t c = clock(); DWORD pid = GetCurrentProcessId(); DWORD tid = GetCurrentThreadId(); srand(c + _rotl(t,24) + _rotl(pid,8) + _rotl(tid,16)); #else srand(t); #endif } ctx->MapObj(EvalMax, "max"); ctx->MapObj(EvalMin, "min"); ctx->MapObj(EvalAvg, "avg"); ctx->MapObj(EvalAdd, "add"); ctx->MapObj(EvalAdd, "+"); ctx->MapObj(EvalSub, "sub"); ctx->MapObj(EvalSub, "-"); ctx->MapObj(EvalDiv, "div"); ctx->MapObj(EvalDiv, "/"); ctx->MapObj(EvalMult, "mult"); ctx->MapObj(EvalMult, "*"); ctx->MapObj(EvalIAdd, "iadd"); ctx->MapObj(EvalISub, "isub"); ctx->MapObj(EvalIDiv, "idiv"); ctx->MapObj(EvalIMult, "imult"); ctx->MapObj(EvalIMod, "mod"); ctx->MapObj(EvalIMod, "imod"); ctx->MapObj(EvalIOr, "ior"); ctx->MapObj(EvalIOr, "|"); ctx->MapObj(EvalINot, "inot"); ctx->MapObj(EvalINot, "~"); ctx->MapObj(EvalIAnd, "iand"); ctx->MapObj(EvalIAnd, "&"); ctx->MapObj(EvalIXor, "ixor"); ctx->MapObj(EvalLShift, "lshift"); ctx->MapObj(EvalRShift, "rshift"); ctx->MapObj(EvalIncr, "incr"); ctx->MapObj(EvalIncr, "++"); ctx->MapObj(EvalAddX, "+="); ctx->MapObj(EvalSubX, "-="); ctx->MapObj(EvalDecr, "decr"); ctx->MapObj(EvalDecr, "--"); ctx->MapObj(EvalAbs, "abs"); ctx->MapObj(EvalIAbs, "iabs"); ctx->MapObj(EvalAsc, "asc"); ctx->MapObj(EvalOrd, "ord"); ctx->MapObj(EvalExpr, "expr"); ctx->MapObj(EvalRand, "rand"); ctx->MapObj(EvalRound, "round"); ctx->MapObj(EvalTrunc, "trunc"); ctx->MapObj(EvalHex, "hex"); ctx->MapObj(EvalOct, "oct"); ctx->MapObj(EvalBin, "bin"); ctx->MapObj(EvalRadix, "radix"); }
[ "simul@407f561b-fe63-0410-8234-8332a1beff53" ]
[ [ [ 1, 671 ] ] ]
6c6352e8881433dae97b9c48b57a7ad47021b3e1
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/core/src/GameLoop.cpp
2ad0df4f67a70fd82b00522d1fb0bed10074bbcc
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,368
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" //precompiled header #include "GameLoop.h" #include "GameTask.h" #include "CoreSubsystem.h" #include "FixRubyHeaders.h" #include "Exception.h" #include <numeric> using namespace Ogre; template<> rl::GameLoop* Singleton<rl::GameLoop>::ms_Singleton = 0; namespace rl { GameLoop::GameLoop() : mTaskLists(), mAddedTasks(), mRemovedTasks(), mTimer(NULL), mGameTime(0), mLastTimes(), mSmoothedFrames(3), mMaxFrameTime(0.1f), mMinFrameTime(1.0/60), mQuitRequested(false), mPaused(false) { // create five task lists, one for each taskgroup mTaskLists.push_back(new GameTaskList()); mTaskLists.push_back(new GameTaskList()); mTaskLists.push_back(new GameTaskList()); mTaskLists.push_back(new GameTaskList()); mTaskLists.push_back(new GameTaskList()); mTimer = new Timer(); } GameLoop::~GameLoop() { for (size_t i = 0; i < mTaskLists.size(); ++i) { delete mTaskLists[i]; } mTaskLists.clear(); delete mTimer; } void GameLoop::addTask(GameTask* task, TaskGroup group) { RlAssert1(task != NULL); GameTaskEntry entry = {task, true}; mAddedTasks.push_back(std::make_pair(group, entry)); } void GameLoop::removeTask(GameTask* task) { // find the removed task entry, and set it to invalid. for (size_t i = 0; i < mTaskLists.size(); ++i) { GameTaskList* tasks = mTaskLists[i]; GameTaskList::iterator find_it = std::find_if(tasks->begin(), tasks->end(), std::bind2nd(FindEntryByTask(), task)); if (find_it != tasks->end()) { find_it->valid = false; break; } } // Add it to the removed list, so we can find it faster in updateTaskList(). GameTaskEntry entry = {task, false}; mRemovedTasks.push_back(entry); } void GameLoop::quitGame() { mQuitRequested = true; } void GameLoop::loop() { // A sensible start value mGameTime = mTimer->getMilliseconds() - 50; // Loop until game exit is requested. while (!mQuitRequested && !CoreSubsystem::getSingleton().getRenderWindow()->isClosed()) { _executeOneRenderLoop(); } } bool GameLoop::isPaused() const { return mPaused; } void GameLoop::setPaused(bool paused) { mPaused = paused; } void GameLoop::setTimeFactor(Ogre::Real timeFactor) { for (size_t i = 0; i < mTaskLists.size(); ++i) { for (std::list<GameTaskEntry>::iterator it = mTaskLists[i]->begin(); it != mTaskLists[i]->end(); ++it) { it->task->setTimeFactor(timeFactor); } } } void GameLoop::_executeOneRenderLoop(bool executeTasks) { // Calculate frame time. This time is smoothed and capped. unsigned long elapsedTime = mTimer->getMilliseconds(); unsigned long unsmoothedFrameTime = elapsedTime - mGameTime; if( elapsedTime < mGameTime ) unsmoothedFrameTime = 1; if( unsmoothedFrameTime < mMinFrameTime*1000 ) { usleep(floor(1000*(mMinFrameTime*1000 - unsmoothedFrameTime))); elapsedTime = mTimer->getMilliseconds(); unsmoothedFrameTime = elapsedTime - mGameTime; if( elapsedTime < mGameTime ) unsmoothedFrameTime = 1; } if( unsmoothedFrameTime > mMaxFrameTime*1000 ) { LOG_DEBUG(Logger::CORE, "The current frame time was truncated at maximum."); unsmoothedFrameTime = mMaxFrameTime*1000; } Real frameTime = 0.001f * (Real) smoothFrameTime(unsmoothedFrameTime); mGameTime = elapsedTime; // Let Ogre handle Windows/XServer events. WindowEventUtilities::messagePump(); // Render the next frame Root::getSingleton().renderOneFrame(); // Execute all tasks in order. for (size_t i = 0; i < mTaskLists.size() && executeTasks; ++i) { GameTaskList* tasks = mTaskLists[i]; for (GameTaskList::iterator it = tasks->begin(); it != tasks->end(); ++it) { if (it->valid && !it->task->isPaused() && !(isPaused() && it->task->isInterruptable())) { it->task->run(frameTime); } } } // Update task list, if needed. updateTaskList(); } void GameLoop::updateTaskList() { // Remove removed tasks. for (GameTaskList::iterator it = mRemovedTasks.begin(); it != mRemovedTasks.end(); ++it) { for (size_t i = 0; i < mTaskLists.size(); ++i) { GameTaskList* tasks = mTaskLists[i]; GameTaskList::iterator find_it = std::find(tasks->begin(), tasks->end(), *it); if (find_it != tasks->end()) { tasks->erase(find_it); break; } } } mRemovedTasks.clear(); // Add new ones. for (GroupTaskList::iterator it = mAddedTasks.begin(); it != mAddedTasks.end(); ++it) { mTaskLists[(*it).first]->push_back((*it).second); } mAddedTasks.clear(); } // Idea taken from Ogre, but implementation by us. // fixed number of smoothed frames unsigned long GameLoop::smoothFrameTime(unsigned long time) { // remove the last frame, if enough frame-times are saved if( mLastTimes.size() >= std::max(mSmoothedFrames,(unsigned long)1) ) mLastTimes.pop_front(); // First add time for this frame mLastTimes.push_back(time); // Return the mean of the remaining times. // Do not return zero if( mLastTimes.size() == 0 ) return time; else { unsigned long smoothedTime = (long double)(std::accumulate(mLastTimes.begin(), mLastTimes.end(), 0)) / std::max(mLastTimes.size(), (size_t)1) + 0.5; // round correctly with +.5 return smoothedTime; } } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 234 ] ] ]
4f74dc43c58392d4b10273d17d80cbf95a6a08c5
6397eabfb8610d3b56c49f7d61bfc6f8636e6e09
/classes/VideoCallReceiver.cpp
444467728ab672d0eb817cbcda4ab08c7ba5fac2
[]
no_license
ForjaOMF/OMF-WindowsMFCSDK
947638d047f352ec958623a03d6ab470eae9cedd
cb6e6d1b6b90f91cb3668bc2bc831119b38b0011
refs/heads/master
2020-04-06T06:40:54.080051
2009-10-27T12:22:40
2009-10-27T12:22:40
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,929
cpp
// VideoCallReceiver.cpp: archivo de implementación // #include "stdafx.h" #include "VideoCallReceiver.h" #include "SIPSocket.h" #include "Frame263.h" #include "WriteAvi.h" #include "MD5Checksum.h" #include "decoder\tmndec.h" CVideoCallReceiver::CVideoCallReceiver(CString csLogin, CString csPassword, CString csLocalIP, CString csPath, DWORD dwCookie) { m_csLogin=csLogin; m_csPassword=csPassword; m_csLocalIP=csLocalIP; m_csPath=csPath; m_dwCookie=dwCookie; m_bRegistered=false; m_nRegisterAttempts=1; m_pStartCall=NULL; m_pEndCall=NULL; bool bRes; m_pSocket=new CSIPSocket(OnEvent,(DWORD)this); if(csLocalIP.IsEmpty()) { bRes=m_pSocket->Create(5061,SOCK_DGRAM,FD_READ|FD_WRITE); CString csHost; UINT nPort; m_pSocket->GetSockNameEx(csHost, nPort); hostent* pRemoteHost = gethostbyname(csHost.GetBuffer()); if(pRemoteHost) { in_addr addr; addr.s_addr = *(u_long *) pRemoteHost->h_addr_list[0]; m_csLocalIP=inet_ntoa(addr); } } else { bRes=m_pSocket->Create(5061,SOCK_DGRAM,FD_READ|FD_WRITE,m_csLocalIP); } } CVideoCallReceiver::~CVideoCallReceiver() { if(m_pSocket) { m_pSocket->Close(); delete m_pSocket; m_pSocket=NULL; } } void CVideoCallReceiver::OnReceiveData(char* pBufData,DWORD dwLenData,int nErrorCode) { char strData[65000]; memset(strData,0,65000); memcpy(strData,pBufData,dwLenData); CString csData=strData; int nPos401=csData.Find("401 Unauthorized"); if (nPos401!=-1) { if(m_bRegistered) ReRegister(csData,0); else ReRegister(csData,3600); } int nPos200=csData.Find("200 OK"); if (nPos200!=-1) { if(!m_bRegistered) AfxMessageBox("Conectado"); m_bRegistered = true; SetTimer(AfxGetMainWnd()->m_hWnd,(UINT)this,45000,TimerProc); // Registrado!! } if(csData.Left(6)=="INVITE") { AcceptInvitation(csData); } else if(csData.Left(3)=="ACK") { SendMultimediaData(csData); } else if(csData.Left(3)=="BYE") { AckBye(csData); } } void CVideoCallReceiver::OnEvent(DWORD dwCookie,UINT nCode,char* pBufData,DWORD dwLenData,int nErrorCode) { CVideoCallReceiver* pThis=(CVideoCallReceiver*)dwCookie; if(pThis) { switch(nCode) { case FSOCK_RECEIVE: pThis->OnReceiveData(pBufData,dwLenData,nErrorCode); break; case FSOCK_ACCEPT: break; case FSOCK_CLOSE: //pThis->OnCloseSocket(nErrorCode); break; } } } void CVideoCallReceiver::RegisterAttempt() { CString csRegister1; csRegister1.Format( "REGISTER sip:195.76.180.160 SIP/2.0\r\n" "Via: SIP/2.0/UDP %s:5061;rport;branch=z9hG4bK21898\r\n" "From: <sip:%[email protected]>;tag=13939\r\n" "To: <sip:%[email protected]>\r\n" "Call-ID: 9979@%s\r\n" "CSeq: %d REGISTER\r\n" "Contact: <sip:%s@%s:5061>\r\n" "Max-Forwards: 70\r\n" "Expires: 3600\r\n" "Allow-Events: presence\r\n" "Event: registration\r\n" "User-Agent: Intellivic/PC\r\n" "Allow: ACK, BYE, CANCEL, INVITE, MESSAGE, OPTIONS, REFER, PRACK\r\n" "Content-Length: 0\r\n\r\n", m_csLocalIP, m_csLogin, m_csLogin, m_csLocalIP, m_nRegisterAttempts++, m_csLogin, m_csLocalIP); if(m_pSocket) m_pSocket->SendTo((void*)csRegister1.GetBuffer(0),csRegister1.GetLength(), 5060, "195.76.180.160"); } void CVideoCallReceiver::AcceptInvitation(CString csInvitation) { CString csCallId=GetCallId(csInvitation); COleDateTime odtNow=COleDateTime::GetCurrentTime(); CString csStartTime=odtNow.Format("%Y-%m-%d %H.%M.%S"); CString csFrom=GetFrom(csInvitation); CString csBranch=GetBranch(csInvitation); CString csFromTag=GetFromTag(csInvitation); CString csTrying; csTrying.Format( "SIP/2.0 100 Trying\r\n" "Via: SIP/2.0/UDP 195.76.180.160:5060;branch=%s\r\n" "From: <sip:%[email protected]>;tag=%s\r\n" "To: <sip:%[email protected]:5060;user=phone>\r\n" "Call-Id: %s\r\n" "CSeq: 1 INVITE\r\n" "Content-Length: 0\r\n\r\n", csBranch, csFrom, csFromTag, m_csLogin, csCallId); if(m_pSocket) m_pSocket->SendTo((void*)csTrying.GetBuffer(0),csTrying.GetLength(), 5060, "195.76.180.160"); int nToTag=10000*rand()/RAND_MAX; CString csRinging; csRinging.Format( "SIP/2.0 180 Ringing\r\n" "Via: SIP/2.0/UDP 195.76.180.160:5060;branch=%s\r\n" "From: <sip:%[email protected]>;tag=%s\r\n" "To: <sip:%[email protected]:5060;user=phone>;tag=%d\r\n" "Call-Id: %s\r\n" "CSeq: 1 INVITE\r\n" "Contact: <sip:%s@%s:5061>\r\n" "Content-Length: 0\r\n\r\n", csBranch, csFrom, csFromTag, m_csLogin, nToTag, csCallId, m_csLogin, m_csLocalIP); if(m_pSocket) m_pSocket->SendTo((void*)csRinging.GetBuffer(0),csRinging.GetLength(), 5060, "195.76.180.160"); // Añadir llamada a la lista CVideoCall* pVCall=new CVideoCall(csStartTime, csFrom, m_csLocalIP, m_csPath, csCallId, csBranch, csFromTag, nToTag); if(m_pStartCall) m_pStartCall(m_dwCookie,pVCall); m_msoCalls.SetAt(csCallId,pVCall); pVCall->CreateSockets(); int nRnd1=30000*rand()/RAND_MAX; int nRnd2=30000*rand()/RAND_MAX; CString csContent; csContent.Format( "v=0\r\n" "o=- %d %d IN IP4 %s\r\n" "s=-\r\n" "c=IN IP4 %s\r\n" "t=0 0\r\n" "m=audio %d RTP/AVP 101 99 0 8 104\r\n" "a=rtpmap:101 speex/16000\r\n" "a=fmtp:101 vbr=on;mode=6\r\n" "a=rtpmap:99 speex/8000\r\n" "a=fmtp:99 vbr=on;mode=3\r\n" "a=rtpmap:0 PCMU/8000\r\n" "a=rtpmap:8 PCMA/8000\r\n" "a=rtpmap:104 telephone-event/8000\r\n" "a=fmtp:104 0-15\r\n" "m=video %d RTP/AVP 97 34\r\n" "a=rtpmap:97 MP4V-ES/90000\r\n" "a=fmtp:97 profile-level-id=1\r\n" "a=rtpmap:34 H263/90000\r\n" "a=fmtp:34 QCIF=2 SQCIF=2/MaxBR=560\r\n" ,nRnd1,nRnd2,m_csLocalIP,m_csLocalIP,pVCall->GetAudioPort(),pVCall->GetVideoPort()); CString csSDP; csSDP.Format( "SIP/2.0 200 OK\r\n" "Via: SIP/2.0/UDP 195.76.180.160:5060;branch=%s\r\n" "From: <sip:%[email protected]>;tag=%s\r\n" "To: <sip:%[email protected]:5060;user=phone>;tag=%d\r\n" "Call-Id: %s\r\n" "CSeq: 1 INVITE\r\n" "Contact: <sip:%s@%s:5061>\r\n" "User-Agent: Intellivic/PC\r\n" "Supported: replaces\r\n" "Allow: ACK, BYE, CANCEL, INVITE, OPTIONS\r\n" "Content-Type: application/sdp\r\n" "Accept: application/sdp, application/media_control+xml, application/dtmf-relay\r\n" "Content-Length: %d\r\n\r\n%s", csBranch, csFrom, csFromTag, m_csLogin, nToTag , csCallId, m_csLogin, m_csLocalIP, csContent.GetLength(),csContent); if(m_pSocket) m_pSocket->SendTo((void*)csSDP.GetBuffer(0),csSDP.GetLength(), 5060, "195.76.180.160"); //Register(3600); } void CVideoCallReceiver::SendMultimediaData(CString csAckData) { CString csCallId=GetCallId(csAckData); CVideoCall* pVCall=NULL; m_msoCalls.Lookup(csCallId,(CObject*&)pVCall); if(pVCall) pVCall->SendMultimediaData(csAckData); } void CVideoCallReceiver::ReRegister(CString cs401, long lExpires) { int nPosNonce=cs401.Find("nonce=\""); if(nPosNonce!=-1) { int nPosNonceEnd=cs401.Find("\"",nPosNonce+8); if(nPosNonceEnd!=-1) m_csNonce=cs401.Mid(nPosNonce+7,nPosNonceEnd-nPosNonce-7); else m_csNonce=cs401.Left(nPosNonce+7); } Register(lExpires); } void CVideoCallReceiver::Register(long lExpires) { CMD5Checksum* pmd5=new CMD5Checksum(); CString csLine1; csLine1.Format("%s:movistar.es:%s",m_csLogin,m_csPassword); CString csHA1=pmd5->GetMD5((BYTE*)csLine1.GetBuffer(0),csLine1.GetLength()); CString csLine2="REGISTER:sip:195.76.180.160"; CString csHA2=pmd5->GetMD5((BYTE*)csLine2.GetBuffer(0),csLine2.GetLength()); CString csLine3; csLine3.Format("%s:%s:00000001:473:auth:%s",csHA1,m_csNonce,csHA2); CString csResponse=pmd5->GetMD5((BYTE*)csLine3.GetBuffer(0),csLine3.GetLength()); delete pmd5; int nTag=32000*rand()/RAND_MAX; int nCallId=10000*rand()/RAND_MAX; CString csRegister2; csRegister2.Format( "REGISTER sip:195.76.180.160 SIP/2.0\r\n" "Via: SIP/2.0/UDP %s:5061;rport;branch=z9hG4bK23080\r\n" "From: <sip:%[email protected]>;tag=%d\r\n" "To: <sip:%[email protected]>\r\n" "Call-ID: %d@%s\r\n" "CSeq: %d REGISTER\r\n" "Contact: <sip:%s@%s:5061>\r\n" "Authorization: digest username=\"%s\", realm=\"movistar.es\", nonce=\"%s\", uri=\"sip:195.76.180.160\", response=\"%s\", algorithm=md5, cnonce=\"473\", qop=auth, nc=00000001\r\n" "Max-Forwards: 70\r\n" "Expires: %d\r\n" "Allow-Events: presence\r\n" "Event: registration\r\n" "User-Agent: Intellivic/PC\r\n" "Allow: ACK, BYE, CANCEL, INVITE, MESSAGE, OPTIONS, REFER, PRACK\r\n" "Content-Length: 0\r\n\r\n", m_csLocalIP, m_csLogin, nTag, m_csLogin, nCallId, m_csLocalIP, m_nRegisterAttempts++, m_csLogin, m_csLocalIP, m_csLogin, m_csNonce, csResponse, lExpires); if(m_pSocket) m_pSocket->SendTo((void*)csRegister2.GetBuffer(0),csRegister2.GetLength(), 5060, "195.76.180.160"); } void CVideoCallReceiver::AckBye(CString csBye) { CString csCallId=GetCallId(csBye); CVideoCall* pVCall=NULL; m_msoCalls.Lookup(csCallId,(CObject*&)pVCall); if(pVCall) { if(m_pEndCall) m_pEndCall(m_dwCookie,pVCall); m_msoCalls.RemoveKey(csCallId); pVCall->Terminate(); CString csBranch=GetBranch(csBye); CString csByeAck; csByeAck.Format( "SIP/2.0 200 OK\r\n" "Via: SIP/2.0/UDP 195.76.180.160:5060;branch=%s\r\n" "From: <sip:%[email protected]>;tag=%s\r\n" "To: <sip:%[email protected]:5060;user=phone>;tag=%d\r\n" "Call-Id: %s\r\n" "CSeq: 2 Bye\r\n" "Content-Length: 0\r\n\r\n", csBranch, pVCall->GetFrom(), pVCall->GetFromTag(), m_csLogin, pVCall->GetToTag(), pVCall->GetCallId()); if(m_pSocket) m_pSocket->SendTo((void*)csByeAck.GetBuffer(0),csByeAck.GetLength(), 5060, "195.76.180.160"); delete pVCall; pVCall=NULL; } //Register(3600); } void CVideoCallReceiver::Unregister() { KillTimer(AfxGetMainWnd()->m_hWnd,(UINT)this); Register(0); } CString CVideoCallReceiver::GetCallId(CString csData) { CString csCallId; int nPosCallId=csData.Find("Call-ID: "); if(nPosCallId!=-1) { int nPosCallIdEnd=csData.Find("\r\n",nPosCallId+10); if(nPosCallIdEnd!=-1) csCallId=csData.Mid(nPosCallId+9,nPosCallIdEnd-nPosCallId-9); else csCallId=csData.Left(nPosCallId+9); } return csCallId; } CString CVideoCallReceiver::GetBranch(CString csData) { CString csBranch; int nPosBranch=csData.Find("branch="); if(nPosBranch!=-1) { int nPosBranchEnd=csData.Find("\r\n",nPosBranch+8); if(nPosBranchEnd!=-1) csBranch=csData.Mid(nPosBranch+7,nPosBranchEnd-nPosBranch-7); else csBranch=csData.Left(nPosBranch+7); } return csBranch; } CString CVideoCallReceiver::GetFrom(CString csData) { CString csFrom; int nPosFrom=csData.Find("From: <sip:"); if(nPosFrom!=-1) { int nPosFromEnd=csData.Find("@",nPosFrom+11); if(nPosFromEnd!=-1) csFrom=csData.Mid(nPosFrom+11,nPosFromEnd-nPosFrom-11); else csFrom=csData.Left(nPosFrom+11); } return csFrom; } CString CVideoCallReceiver::GetFromTag(CString csData) { CString csFrom=GetFrom(csData); CString csSearch; csSearch.Format("From: <sip:%[email protected]>;tag=",csFrom); CString csFromTag; int nPosTag=csData.Find(csSearch); if(nPosTag!=-1) { int nPosTagEnd=csData.Find("\r\n",nPosTag+csSearch.GetLength()+1); if(nPosTagEnd!=-1) csFromTag=csData.Mid(nPosTag+csSearch.GetLength(),nPosTagEnd-nPosTag-csSearch.GetLength()); else csFromTag=csData.Left(nPosTag+csSearch.GetLength()); } return csFromTag; } void WINAPI CVideoCallReceiver::TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { if(uMsg==WM_TIMER) { // Lanzar Registro CVideoCallReceiver* pThis=(CVideoCallReceiver*)idEvent; KillTimer(AfxGetMainWnd()->m_hWnd,(UINT)pThis); pThis->Register(3600); SetTimer(AfxGetMainWnd()->m_hWnd,idEvent,45000,TimerProc); } }
[ [ [ 1, 436 ] ] ]
acfbf82be7153595460f926231a94535608efcdd
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWTypes.h
3d4663affbcb5ad9b133a12469f40f7496d7ce14
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
UTF-8
C++
false
false
17,616
h
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADAFramework. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADAFW_TYPES_H__ #define __COLLADAFW_TYPES_H__ #include "COLLADAFWPrerequisites.h" #include "COLLADAFWArrayPrimitiveType.h" namespace COLLADAFW { /** An array of unsigned int values. */ typedef ArrayPrimitiveType<unsigned int> UIntValuesArray; typedef ArrayPrimitiveType<int> IntValuesArray; typedef ArrayPrimitiveType<unsigned long long> ULongLongValuesArray; typedef ArrayPrimitiveType<long long> LongLongValuesArray; typedef ArrayPrimitiveType<float> FloatArray; typedef ArrayPrimitiveType<double> DoubleArray; // typedef xsNCName String; typedef int ClassId; typedef unsigned long long ObjectId; typedef unsigned long MaterialId; typedef unsigned long TextureMapId; /** Data type to reference sampler. Used by texture.*/ typedef size_t SamplerID; // Element Type Enum namespace COLLADA_TYPE { const ClassId NO_TYPE = 0, ANY = 1, INPUTGLOBAL = 2, INPUTLOCAL = 3, INPUTLOCALOFFSET = 4, INSTANCEWITHEXTRA = 5, TARGETABLEFLOAT = 6, TARGETABLEFLOAT3 = 7, FX_SURFACE_FORMAT_HINT_COMMON = 8, CHANNELS = 9, RANGE = 10, PRECISION = 11, OPTION = 12, FX_SURFACE_INIT_PLANAR_COMMON = 13, ALL = 14, FX_SURFACE_INIT_VOLUME_COMMON = 15, PRIMARY = 16, FX_SURFACE_INIT_CUBE_COMMON = 17, ORDER = 18, FACE = 19, FX_SURFACE_INIT_FROM_COMMON = 20, FX_SURFACE_COMMON = 21, FORMAT = 22, SIZE = 23, VIEWPORT_RATIO = 24, MIP_LEVELS = 25, MIPMAP_GENERATE = 26, FX_SAMPLER1D_COMMON = 27, SOURCE = 28, WRAP_S = 29, MINFILTER = 30, MAGFILTER = 31, MIPFILTER = 32, BORDER_COLOR = 33, MIPMAP_MAXLEVEL = 34, MIPMAP_BIAS = 35, FX_SAMPLER2D_COMMON = 36, WRAP_T = 37, FX_SAMPLER3D_COMMON = 38, WRAP_P = 39, FX_SAMPLERCUBE_COMMON = 40, FX_SAMPLERRECT_COMMON = 41, FX_SAMPLERDEPTH_COMMON = 42, FX_COLORTARGET_COMMON = 43, FX_DEPTHTARGET_COMMON = 44, FX_STENCILTARGET_COMMON = 45, FX_CLEARCOLOR_COMMON = 46, FX_CLEARDEPTH_COMMON = 47, FX_CLEARSTENCIL_COMMON = 48, FX_ANNOTATE_COMMON = 49, FX_INCLUDE_COMMON = 50, FX_NEWPARAM_COMMON = 51, SEMANTIC = 52, MODIFIER = 53, FX_CODE_PROFILE = 54, GL_SAMPLER1D = 55, GL_SAMPLER2D = 56, GL_SAMPLER3D = 57, GL_SAMPLERCUBE = 58, GL_SAMPLERRECT = 59, GL_SAMPLERDEPTH = 60, GLSL_NEWARRAY_TYPE = 61, GLSL_SETARRAY_TYPE = 62, GLSL_SURFACE_TYPE = 63, GENERATOR = 64, NAME = 65, GLSL_NEWPARAM = 66, GLSL_SETPARAM_SIMPLE = 67, GLSL_SETPARAM = 68, COMMON_FLOAT_OR_PARAM_TYPE = 69, FLOAT = 70, PARAM = 71, COMMON_COLOR_OR_TEXTURE_TYPE = 72, COLOR = 73, TEXTURE = 74, COMMON_TRANSPARENT_TYPE = 75, COMMON_NEWPARAM_TYPE = 76, FLOAT2 = 77, FLOAT3 = 78, FLOAT4 = 79, CG_SAMPLER1D = 80, CG_SAMPLER2D = 81, CG_SAMPLER3D = 82, CG_SAMPLERCUBE = 83, CG_SAMPLERRECT = 84, CG_SAMPLERDEPTH = 85, CG_CONNECT_PARAM = 86, CG_NEWARRAY_TYPE = 87, CG_SETARRAY_TYPE = 88, CG_SETUSER_TYPE = 89, CG_SURFACE_TYPE = 90, CG_NEWPARAM = 91, CG_SETPARAM_SIMPLE = 92, CG_SETPARAM = 93, GLES_TEXTURE_CONSTANT_TYPE = 94, GLES_TEXENV_COMMAND_TYPE = 95, GLES_TEXCOMBINER_ARGUMENTRGB_TYPE = 96, GLES_TEXCOMBINER_ARGUMENTALPHA_TYPE = 97, GLES_TEXCOMBINER_COMMANDRGB_TYPE = 98, GLES_TEXCOMBINER_COMMANDALPHA_TYPE = 99, GLES_TEXCOMBINER_COMMAND_TYPE = 100, GLES_TEXTURE_PIPELINE = 101, GLES_TEXTURE_UNIT = 102, SURFACE = 103, SAMPLER_STATE = 104, TEXCOORD = 105, GLES_SAMPLER_STATE = 106, GLES_NEWPARAM = 107, FX_SURFACE_INIT_COMMON = 108, INIT_AS_NULL = 109, INIT_AS_TARGET = 110, FX_ANNOTATE_TYPE_COMMON = 111, BOOL = 112, BOOL2 = 113, BOOL3 = 114, BOOL4 = 115, INT = 116, INT2 = 117, INT3 = 118, INT4 = 119, FLOAT2X2 = 120, FLOAT3X3 = 121, FLOAT4X4 = 122, STRING = 123, FX_BASIC_TYPE_COMMON = 124, FLOAT1X1 = 125, FLOAT1X2 = 126, FLOAT1X3 = 127, FLOAT1X4 = 128, FLOAT2X1 = 129, FLOAT2X3 = 130, FLOAT2X4 = 131, FLOAT3X1 = 132, FLOAT3X2 = 133, FLOAT3X4 = 134, FLOAT4X1 = 135, FLOAT4X2 = 136, FLOAT4X3 = 137, ENUM = 138, GL_PIPELINE_SETTINGS = 139, ALPHA_FUNC = 140, FUNC = 141, VALUE = 142, BLEND_FUNC = 143, SRC = 144, DEST = 145, BLEND_FUNC_SEPARATE = 146, SRC_RGB = 147, DEST_RGB = 148, SRC_ALPHA = 149, DEST_ALPHA = 150, BLEND_EQUATION = 151, BLEND_EQUATION_SEPARATE = 152, RGB = 153, ALPHA = 154, COLOR_MATERIAL = 155, MODE = 156, CULL_FACE = 157, DEPTH_FUNC = 158, FOG_MODE = 159, FOG_COORD_SRC = 160, FRONT_FACE = 161, LIGHT_MODEL_COLOR_CONTROL = 162, LOGIC_OP = 163, POLYGON_MODE = 164, SHADE_MODEL = 165, STENCIL_FUNC = 166, REF = 167, MASK = 168, STENCIL_OP = 169, FAIL = 170, ZFAIL = 171, ZPASS = 172, STENCIL_FUNC_SEPARATE = 173, FRONT = 174, BACK = 175, STENCIL_OP_SEPARATE = 176, STENCIL_MASK_SEPARATE = 177, LIGHT_ENABLE = 178, LIGHT_AMBIENT = 179, LIGHT_DIFFUSE = 180, LIGHT_SPECULAR = 181, LIGHT_POSITION = 182, LIGHT_CONSTANT_ATTENUATION = 183, LIGHT_LINEAR_ATTENUATION = 184, LIGHT_QUADRATIC_ATTENUATION = 185, LIGHT_SPOT_CUTOFF = 186, LIGHT_SPOT_DIRECTION = 187, LIGHT_SPOT_EXPONENT = 188, TEXTURE1D = 189, TEXTURE2D = 190, TEXTURE3D = 191, TEXTURECUBE = 192, TEXTURERECT = 193, TEXTUREDEPTH = 194, TEXTURE1D_ENABLE = 195, TEXTURE2D_ENABLE = 196, TEXTURE3D_ENABLE = 197, TEXTURECUBE_ENABLE = 198, TEXTURERECT_ENABLE = 199, TEXTUREDEPTH_ENABLE = 200, TEXTURE_ENV_COLOR = 201, TEXTURE_ENV_MODE = 202, CLIP_PLANE = 203, CLIP_PLANE_ENABLE = 204, BLEND_COLOR = 205, CLEAR_COLOR = 206, CLEAR_STENCIL = 207, CLEAR_DEPTH = 208, COLOR_MASK = 209, DEPTH_BOUNDS = 210, DEPTH_MASK = 211, DEPTH_RANGE = 212, FOG_DENSITY = 213, FOG_START = 214, FOG_END = 215, FOG_COLOR = 216, LIGHT_MODEL_AMBIENT = 217, LIGHTING_ENABLE = 218, LINE_STIPPLE = 219, LINE_WIDTH = 220, MATERIAL_AMBIENT = 221, MATERIAL_DIFFUSE = 222, MATERIAL_EMISSION = 223, MATERIAL_SHININESS = 224, MATERIAL_SPECULAR = 225, MODEL_VIEW_MATRIX = 226, POINT_DISTANCE_ATTENUATION = 227, POINT_FADE_THRESHOLD_SIZE = 228, POINT_SIZE = 229, POINT_SIZE_MIN = 230, POINT_SIZE_MAX = 231, POLYGON_OFFSET = 232, PROJECTION_MATRIX = 233, SCISSOR = 234, STENCIL_MASK = 235, ALPHA_TEST_ENABLE = 236, AUTO_NORMAL_ENABLE = 237, BLEND_ENABLE = 238, COLOR_LOGIC_OP_ENABLE = 239, COLOR_MATERIAL_ENABLE = 240, CULL_FACE_ENABLE = 241, DEPTH_BOUNDS_ENABLE = 242, DEPTH_CLAMP_ENABLE = 243, DEPTH_TEST_ENABLE = 244, DITHER_ENABLE = 245, FOG_ENABLE = 246, LIGHT_MODEL_LOCAL_VIEWER_ENABLE = 247, LIGHT_MODEL_TWO_SIDE_ENABLE = 248, LINE_SMOOTH_ENABLE = 249, LINE_STIPPLE_ENABLE = 250, LOGIC_OP_ENABLE = 251, MULTISAMPLE_ENABLE = 252, NORMALIZE_ENABLE = 253, POINT_SMOOTH_ENABLE = 254, POLYGON_OFFSET_FILL_ENABLE = 255, POLYGON_OFFSET_LINE_ENABLE = 256, POLYGON_OFFSET_POINT_ENABLE = 257, POLYGON_SMOOTH_ENABLE = 258, POLYGON_STIPPLE_ENABLE = 259, RESCALE_NORMAL_ENABLE = 260, SAMPLE_ALPHA_TO_COVERAGE_ENABLE = 261, SAMPLE_ALPHA_TO_ONE_ENABLE = 262, SAMPLE_COVERAGE_ENABLE = 263, SCISSOR_TEST_ENABLE = 264, STENCIL_TEST_ENABLE = 265, GLSL_PARAM_TYPE = 266, CG_PARAM_TYPE = 267, BOOL1 = 268, BOOL1X1 = 269, BOOL1X2 = 270, BOOL1X3 = 271, BOOL1X4 = 272, BOOL2X1 = 273, BOOL2X2 = 274, BOOL2X3 = 275, BOOL2X4 = 276, BOOL3X1 = 277, BOOL3X2 = 278, BOOL3X3 = 279, BOOL3X4 = 280, BOOL4X1 = 281, BOOL4X2 = 282, BOOL4X3 = 283, BOOL4X4 = 284, FLOAT1 = 285, INT1 = 286, INT1X1 = 287, INT1X2 = 288, INT1X3 = 289, INT1X4 = 290, INT2X1 = 291, INT2X2 = 292, INT2X3 = 293, INT2X4 = 294, INT3X1 = 295, INT3X2 = 296, INT3X3 = 297, INT3X4 = 298, INT4X1 = 299, INT4X2 = 300, INT4X3 = 301, INT4X4 = 302, HALF = 303, HALF1 = 304, HALF2 = 305, HALF3 = 306, HALF4 = 307, HALF1X1 = 308, HALF1X2 = 309, HALF1X3 = 310, HALF1X4 = 311, HALF2X1 = 312, HALF2X2 = 313, HALF2X3 = 314, HALF2X4 = 315, HALF3X1 = 316, HALF3X2 = 317, HALF3X3 = 318, HALF3X4 = 319, HALF4X1 = 320, HALF4X2 = 321, HALF4X3 = 322, HALF4X4 = 323, FIXED = 324, FIXED1 = 325, FIXED2 = 326, FIXED3 = 327, FIXED4 = 328, FIXED1X1 = 329, FIXED1X2 = 330, FIXED1X3 = 331, FIXED1X4 = 332, FIXED2X1 = 333, FIXED2X2 = 334, FIXED2X3 = 335, FIXED2X4 = 336, FIXED3X1 = 337, FIXED3X2 = 338, FIXED3X3 = 339, FIXED3X4 = 340, FIXED4X1 = 341, FIXED4X2 = 342, FIXED4X3 = 343, FIXED4X4 = 344, GLES_PIPELINE_SETTINGS = 345, TEXTURE_PIPELINE = 346, LIGHT_LINEAR_ATTENUTATION = 347, TEXTURE_PIPELINE_ENABLE = 348, GLES_BASIC_TYPE_COMMON = 349, COLLADA = 350, SCENE = 351, IDREF_ARRAY = 352, NAME_ARRAY = 353, BOOL_ARRAY = 354, FLOAT_ARRAY = 355, INT_ARRAY = 356, ACCESSOR = 357, TECHNIQUE_COMMON = 358, GEOMETRY = 359, MESH = 360, SPLINE = 361, CONTROL_VERTICES = 362, P = 363, LINES = 364, LINESTRIPS = 365, POLYGONS = 366, PH = 367, H = 368, POLYLIST = 369, VCOUNT = 370, TRIANGLES = 371, TRIFANS = 372, TRISTRIPS = 373, VERTICES = 374, LOOKAT = 375, MATRIX = 376, ROTATE = 377, SCALE = 378, SKEW = 379, TRANSLATE = 380, IMAGE = 381, DATA = 382, INIT_FROM = 383, LIGHT = 384, AMBIENT = 385, DIRECTIONAL = 386, POINT = 387, SPOT = 388, MATERIAL = 389, CAMERA = 390, OPTICS = 391, ORTHOGRAPHIC = 392, PERSPECTIVE = 393, IMAGER = 394, ANIMATION = 395, ANIMATION_CLIP = 396, CHANNEL = 397, SAMPLER = 398, CONTROLLER = 399, SKIN = 400, BIND_SHAPE_MATRIX = 401, JOINTS = 402, VERTEX_WEIGHTS = 403, V = 404, MORPH = 405, TARGETS = 406, ASSET = 407, CONTRIBUTOR = 408, AUTHOR = 409, AUTHORING_TOOL = 410, COMMENTS = 411, COPYRIGHT = 412, SOURCE_DATA = 413, CREATED = 414, KEYWORDS = 415, MODIFIED = 416, REVISION = 417, SUBJECT = 418, TITLE = 419, UNIT = 420, UP_AXIS = 421, EXTRA = 422, TECHNIQUE = 423, NODE = 424, VISUAL_SCENE = 425, EVALUATE_SCENE = 426, RENDER = 427, LAYER = 428, BIND_MATERIAL = 429, INSTANCE_CAMERA = 430, INSTANCE_CONTROLLER = 431, SKELETON = 432, INSTANCE_EFFECT = 433, TECHNIQUE_HINT = 434, SETPARAM = 435, INSTANCE_FORCE_FIELD = 436, INSTANCE_GEOMETRY = 437, INSTANCE_LIGHT = 438, INSTANCE_MATERIAL = 439, BIND = 440, BIND_VERTEX_INPUT = 441, INSTANCE_NODE = 442, INSTANCE_PHYSICS_MATERIAL = 443, INSTANCE_PHYSICS_MODEL = 444, INSTANCE_RIGID_BODY = 445, ANGULAR_VELOCITY = 446, VELOCITY = 447, DYNAMIC = 448, MASS_FRAME = 449, SHAPE = 450, HOLLOW = 451, INSTANCE_RIGID_CONSTRAINT = 452, LIBRARY_ANIMATIONS = 453, LIBRARY_ANIMATION_CLIPS = 454, LIBRARY_CAMERAS = 455, LIBRARY_CONTROLLERS = 456, LIBRARY_GEOMETRIES = 457, LIBRARY_EFFECTS = 458, LIBRARY_FORCE_FIELDS = 459, LIBRARY_IMAGES = 460, LIBRARY_LIGHTS = 461, LIBRARY_MATERIALS = 462, LIBRARY_NODES = 463, LIBRARY_PHYSICS_MATERIALS = 464, LIBRARY_PHYSICS_MODELS = 465, LIBRARY_PHYSICS_SCENES = 466, LIBRARY_VISUAL_SCENES = 467, FX_PROFILE_ABSTRACT = 468, EFFECT = 469, GL_HOOK_ABSTRACT = 470, PROFILE_GLSL = 471, PASS = 472, DRAW = 473, SHADER = 474, COMPILER_TARGET = 475, COMPILER_OPTIONS = 476, PROFILE_COMMON = 477, CONSTANT = 478, LAMBERT = 479, PHONG = 480, BLINN = 481, PROFILE_CG = 482, PROFILE_GLES = 483, COLOR_TARGET = 484, DEPTH_TARGET = 485, STENCIL_TARGET = 486, COLOR_CLEAR = 487, DEPTH_CLEAR = 488, STENCIL_CLEAR = 489, BOX = 490, HALF_EXTENTS = 491, PLANE = 492, EQUATION = 493, SPHERE = 494, RADIUS = 495, ELLIPSOID = 496, CYLINDER = 497, HEIGHT = 498, TAPERED_CYLINDER = 499, RADIUS1 = 500, RADIUS2 = 501, CAPSULE = 502, TAPERED_CAPSULE = 503, CONVEX_MESH = 504, FORCE_FIELD = 505, PHYSICS_MATERIAL = 506, PHYSICS_SCENE = 507, RIGID_BODY = 508, RIGID_CONSTRAINT = 509, REF_ATTACHMENT = 510, ATTACHMENT = 511, ENABLED = 512, INTERPENETRATE = 513, LIMITS = 514, SWING_CONE_AND_TWIST = 515, LINEAR = 516, SPRING = 517, ANGULAR = 518, PHYSICS_MODEL = 519; } } #endif // __COLLADAFW_TYPES_H__
[ [ [ 1, 573 ] ] ]
362e1b877c429b54143a19e768da8244db0653b6
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Material/D3D10HDR.cpp
0dd1d3a46f787261158426a136acc62594784abb
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
41,899
cpp
#include "D3D10HDR.h" #include "HDRGlareDef.h" #include "../Main/DataCenter.h" #include "../Main/ResourceManager.h" #include "../Main/Camera.h" #include "../Renderer/D3D10RenderWindow.h" #include "../Renderer/D3D10Renderer.h" #include "../Renderer/D3D10Texture.h" #include "../Renderer/D3D10Effect.h" namespace Flagship { D3D10HDR::D3D10HDR() { m_mParamMap.clear(); m_mTechniqueMap.clear(); m_eGlareType = GLT_FILTER_CROSSSCREEN; // 材质类型 m_iClassType = Base::Material_PostProcess; m_pSceneTexture = NULL; m_pSceneScaled = NULL; m_pBrightTexture = NULL; m_pStarSource = NULL; m_pBloomSource = NULL; m_pCurLuminance = NULL; m_pLastLuminance = NULL; m_pStarTexture = NULL; m_pBloomTexture = NULL; m_pToneMapTexture = NULL; } D3D10HDR::~D3D10HDR() { SAFE_DELETE( m_pEffect ); SAFE_DELETE( m_pGlareDef ); SAFE_DELETE( m_pSceneTexture ); SAFE_DELETE( m_pSceneScaled ); SAFE_DELETE( m_pBrightTexture ); SAFE_DELETE( m_pStarSource ); SAFE_DELETE( m_pBloomSource ); SAFE_DELETE( m_pCurLuminance ); SAFE_DELETE( m_pLastLuminance ); SAFE_DELETE_ARRAY( m_pStarTexture ); SAFE_DELETE_ARRAY( m_pBloomTexture ); SAFE_DELETE_ARRAY( m_pToneMapTexture ); } bool D3D10HDR::Initialize() { // 创建D3D9Effect对象 wchar_t szPath[MAX_PATH]; GetCurrentDirectory( MAX_PATH, szPath ); wstring szEffectPath = szPath; szEffectPath += L"\\Effect\\D3D10HDR.fx"; D3D10EffectHandle hEffectHandle; hEffectHandle.SetPath( szEffectPath ); m_pEffect = hEffectHandle.GetImpliment(); m_pEffect->Load(); BuildParamMap(); // 初始化对象 m_pSceneTexture = new D3D10Texture; m_pSceneScaled = new D3D10Texture; m_pBrightTexture = new D3D10Texture; m_pStarSource = new D3D10Texture; m_pBloomSource = new D3D10Texture; m_pCurLuminance = new D3D10Texture; m_pLastLuminance = new D3D10Texture; m_pStarTexture = new D3D10Texture[NUM_STAR_TEXTURES]; m_pBloomTexture = new D3D10Texture[NUM_BLOOM_TEXTURES]; m_pToneMapTexture = new D3D10Texture[NUM_TONEMAP_TEXTURES]; m_pGlareDef = new CGlareDef; m_pGlareDef->Initialize( m_eGlareType ); return Reset(); } bool D3D10HDR::Reset() { // 重置资源 m_pSceneTexture->Release(); m_pSceneScaled->Release(); m_pBrightTexture->Release(); m_pStarSource->Release(); m_pBloomSource->Release(); m_pCurLuminance->Release(); m_pLastLuminance->Release(); for ( int i = 0; i < NUM_STAR_TEXTURES; i++ ) { m_pStarTexture[i].Release(); } for ( int i = 0; i < NUM_BLOOM_TEXTURES; i++ ) { m_pBloomTexture[i].Release(); } for ( int i = 0; i < NUM_TONEMAP_TEXTURES; i++ ) { m_pToneMapTexture[i].Release(); } // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); m_dwCropWidth = pRenderWindow->GetWidth() - pRenderWindow->GetWidth() % 8; m_dwCropHeight = pRenderWindow->GetHeight() - pRenderWindow->GetHeight() % 8; // Create the HDR scene texture if ( ! m_pSceneTexture->CreateRenderTarget( pRenderWindow->GetWidth(), pRenderWindow->GetHeight(), DXGI_FORMAT_R16G16B16A16_FLOAT ) ) { return false; } // Scaled version of the HDR scene texture if ( ! m_pSceneScaled->CreateRenderTarget( m_dwCropWidth / 4, m_dwCropHeight / 4, DXGI_FORMAT_R16G16B16A16_FLOAT ) ) { return false; } // Create the bright-pass filter texture. if ( ! m_pBrightTexture->CreateRenderTarget( m_dwCropWidth / 4 + 2, m_dwCropHeight / 4 + 2, DXGI_FORMAT_R8G8B8A8_UNORM ) ) { return false; } // Create a texture to be used as the source for the star effect if ( ! m_pStarSource->CreateRenderTarget( m_dwCropWidth / 4 + 2, m_dwCropHeight / 4 + 2, DXGI_FORMAT_R8G8B8A8_UNORM ) ) { return false; } // Create a texture to be used as the source for the bloom effect if ( ! m_pBloomSource->CreateRenderTarget( m_dwCropWidth / 8 + 2, m_dwCropHeight / 8 + 2, DXGI_FORMAT_R8G8B8A8_UNORM ) ) { return false; } // Create a 2 textures to hold the luminance that the user is currently adapted if ( ! m_pCurLuminance->CreateRenderTarget( 1, 1, DXGI_FORMAT_R32_FLOAT ) ) { return false; } if ( ! m_pLastLuminance->CreateRenderTarget( 1, 1, DXGI_FORMAT_R32_FLOAT ) ) { return false; } // For each scale stage, create a texture to hold the intermediate results of the luminance calculation for( int i = 0; i < NUM_TONEMAP_TEXTURES; i++ ) { int iSampleLen = 1 << ( 2 * i ); if ( ! m_pToneMapTexture[i].CreateRenderTarget( iSampleLen, iSampleLen, DXGI_FORMAT_R32_FLOAT ) ) { return false; } } // Create the temporary blooming effect textures for( int i = 1; i < NUM_BLOOM_TEXTURES; i++ ) { if ( ! m_pBloomTexture[i].CreateRenderTarget( m_dwCropWidth / 8 + 2, m_dwCropHeight / 8 + 2, DXGI_FORMAT_R8G8B8A8_UNORM ) ) { return false; } } // Create the final blooming effect texture if ( ! m_pBloomTexture[0].CreateRenderTarget( m_dwCropWidth / 8, m_dwCropHeight / 8, DXGI_FORMAT_R8G8B8A8_UNORM ) ) { return false; } // Create the star effect textures for( int i = 0; i < NUM_STAR_TEXTURES; i++ ) { if ( ! m_pStarTexture[i].CreateRenderTarget( m_dwCropWidth / 4, m_dwCropHeight / 4, DXGI_FORMAT_R8G8B8A8_UNORM ) ) { return false; } } m_pCurLuminance->ClearTexture(); m_pLastLuminance->ClearTexture(); return true; } void D3D10HDR::BuildParamMap() { // 建立参数表 m_kProj.SetName( wstring( L"g_mProjection" ) ); m_kBloomScale.SetName( wstring( L"g_fBloomScale" ) ); m_kStarScale.SetName( wstring( L"g_fStarScale" ) ); m_kMiddleGray.SetName( wstring( L"g_fMiddleGray" ) ); m_kSampleOffsets.SetName( wstring( L"g_avSampleOffsets" ) ); m_kSampleWeights.SetName( wstring( L"g_avSampleWeights" ) ); m_kElapsedTime.SetName( wstring( L"g_fElapsedTime" ) ); m_kTexture[0].SetName( wstring( L"g_Texture0" ) ); m_kTexture[1].SetName( wstring( L"g_Texture1" ) ); m_kTexture[2].SetName( wstring( L"g_Texture2" ) ); m_kTexture[3].SetName( wstring( L"g_Texture3" ) ); m_kTexture[4].SetName( wstring( L"g_Texture4" ) ); m_kTexture[5].SetName( wstring( L"g_Texture5" ) ); m_kTexture[6].SetName( wstring( L"g_Texture6" ) ); m_kTexture[7].SetName( wstring( L"g_Texture7" ) ); m_pEffect->AddParamHandle( Effect::Param_Matrix, m_kProj ); m_pEffect->AddParamHandle( Effect::Param_Float, m_kBloomScale ); m_pEffect->AddParamHandle( Effect::Param_Float, m_kStarScale ); m_pEffect->AddParamHandle( Effect::Param_Float, m_kMiddleGray ); m_pEffect->AddParamHandle( Effect::Param_Value, m_kSampleOffsets ); m_pEffect->AddParamHandle( Effect::Param_Value, m_kSampleWeights ); m_pEffect->AddParamHandle( Effect::Param_Float, m_kElapsedTime ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[0] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[1] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[2] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[3] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[4] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[5] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[6] ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kTexture[7] ); // 建立科技表 m_kFinalScenePass.SetName( wstring( L"FinalScenePass" ) ); m_kDownScale4x4.SetName( wstring( L"DownScale4x4" ) ); m_kBrightPassFilter.SetName( wstring( L"BrightPassFilter" ) ); m_kGaussBlur5x5.SetName( wstring( L"GaussBlur5x5" ) ); m_kDownScale2x2.SetName( wstring( L"DownScale2x2" ) ); m_kSampleAvgLum.SetName( wstring( L"SampleAvgLum" ) ); m_kResampleAvgLum.SetName( wstring( L"ResampleAvgLum" ) ); m_kResampleAvgLumExp.SetName( wstring( L"ResampleAvgLumExp" ) ); m_kCalculateAdaptedLum.SetName( wstring( L"CalculateAdaptedLum" ) ); m_kStar.SetName( wstring( L"Star" ) ); m_kBloom.SetName( wstring( L"Bloom" ) ); m_kMergeTextures[0].SetName( wstring( L"MergeTextures_1" ) ); m_kMergeTextures[1].SetName( wstring( L"MergeTextures_2" ) ); m_kMergeTextures[2].SetName( wstring( L"MergeTextures_3" ) ); m_kMergeTextures[3].SetName( wstring( L"MergeTextures_4" ) ); m_kMergeTextures[4].SetName( wstring( L"MergeTextures_5" ) ); m_kMergeTextures[5].SetName( wstring( L"MergeTextures_6" ) ); m_kMergeTextures[6].SetName( wstring( L"MergeTextures_7" ) ); m_kMergeTextures[7].SetName( wstring( L"MergeTextures_8" ) ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kFinalScenePass ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kDownScale4x4 ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kBrightPassFilter ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kGaussBlur5x5 ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kDownScale2x2 ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kSampleAvgLum ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kResampleAvgLum ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kResampleAvgLumExp ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kCalculateAdaptedLum ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kStar ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kBloom ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[0] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[1] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[2] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[3] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[4] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[5] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[6] ); m_pEffect->AddParamHandle( Effect::Param_Technique, m_kMergeTextures[7] ); } bool D3D10HDR::BeginPass( UINT uiPass ) { return true; } bool D3D10HDR::EndPass() { return true; } void D3D10HDR::PostProcess() { // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); // 设置HDR渲染表面 pD3D10Device->CopyResource( m_pSceneTexture->GetImpliment(), pRenderWindow->GetRenderTarget() ); ID3D10RenderTargetView * pView = m_pSceneTexture->GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pSceneScaled->ClearTexture(); m_pBloomSource->ClearTexture(); m_pBrightTexture->ClearTexture(); m_pStarSource->ClearTexture(); for ( int i = 0; i < NUM_TONEMAP_TEXTURES; i++ ) { m_pToneMapTexture[i].ClearTexture(); } for( int i = 0; i < NUM_BLOOM_TEXTURES; i++ ) { m_pBloomTexture[i].ClearTexture(); } for ( int i = 0; i < NUM_STAR_TEXTURES; i++ ) { m_pStarTexture[i].ClearTexture(); } // Create a scaled copy of the scene Scene_To_SceneScaled(); // Setup tone mapping technique MeasureLuminance(); // Calculate the current luminance adaptation level CalculateAdaptation(); // Now that luminance information has been gathered, the scene can be bright-pass filtered // to remove everything except bright lights and reflections. SceneScaled_To_BrightPass(); // Blur the bright-pass filtered image to create the source texture for the star effect BrightPass_To_StarSource(); // Scale-down the source texture for the star effect to create the source texture // for the bloom effect StarSource_To_BloomSource(); // Render post-process lighting effects RenderBloom(); RenderStar(); // Draw the high dynamic range scene texture to the low dynamic range // back buffer. As part of this final pass, the scene will be tone-mapped // using the user's current adapted luminance, blue shift will occur // if the scene is determined to be very dark, and the post-process lighting // effect textures will be added to the scene. m_pEffect->SetTechnique( m_kFinalScenePass ); float fMiddleGray = 0.5f; float fBloomScale = 0.5f; float fStarScale = 0.5f; m_pEffect->SetFloat( m_kMiddleGray, &fMiddleGray ); m_pEffect->SetFloat( m_kBloomScale, &fBloomScale ); m_pEffect->SetFloat( m_kStarScale, &fStarScale ); ( (D3D10RenderWindow *) RenderWindow::GetActiveRenderWindow() )->RestoreRenderTarget(); m_pEffect->SetTexture( m_kTexture[0], m_pSceneTexture ); m_pEffect->SetTexture( m_kTexture[1], &( m_pBloomTexture[0] ) ); m_pEffect->SetTexture( m_kTexture[2], &( m_pStarTexture[0] ) ); m_pEffect->SetTexture( m_kTexture[3], m_pCurLuminance ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); } bool D3D10HDR::Scene_To_SceneScaled() { D3DXVECTOR2 avSampleOffsets[MAX_SAMPLES]; // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); // Create a 1/4 x 1/4 scale copy of the HDR texture. Since bloom textures // are 1/8 x 1/8 scale, border texels of the HDR texture will be discarded // to keep the dimensions evenly divisible by 8; this allows for precise // control over sampling inside pixel shaders. m_pEffect->SetTechnique( m_kDownScale4x4 ); // Place the rectangle in the center of the back buffer surface RECT rectSrc; rectSrc.left = ( pRenderWindow->GetWidth() - m_dwCropWidth ) / 2; rectSrc.top = ( pRenderWindow->GetHeight() - m_dwCropHeight ) / 2; rectSrc.right = rectSrc.left + m_dwCropWidth; rectSrc.bottom = rectSrc.top + m_dwCropHeight; // Get the texture coordinates for the render target CoordRect coords; GetTextureCoords( m_pSceneTexture->GetImpliment(), &rectSrc, m_pSceneScaled->GetImpliment(), NULL, &coords ); // Get the sample offsets used within the pixel shader GetSampleOffsets_DownScale4x4( pRenderWindow->GetWidth(), pRenderWindow->GetHeight(), avSampleOffsets ); m_pEffect->SetValue( m_kSampleOffsets, (void *) avSampleOffsets, sizeof(avSampleOffsets) ); ID3D10RenderTargetView * pView = m_pSceneScaled->GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], m_pSceneTexture ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, coords.fLeftU, coords.fTopV, coords.fRightU, coords.fBottomV ); return true; } bool D3D10HDR::SceneScaled_To_BrightPass() { D3DXVECTOR2 avSampleOffsets[MAX_SAMPLES]; D3DXVECTOR4 avSampleWeights[MAX_SAMPLES]; // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); // Get the rectangle describing the sampled portion of the source texture. // Decrease the rectangle to adjust for the single pixel black border. RECT rectSrc; GetTextureRect( m_pSceneScaled->GetImpliment(), &rectSrc ); InflateRect( &rectSrc, -1, -1 ); // Get the destination rectangle. // Decrease the rectangle to adjust for the single pixel black border. RECT rectDest; GetTextureRect( m_pBrightTexture->GetImpliment(), &rectDest ); InflateRect( &rectDest, -1, -1 ); // Get the correct texture coordinates to apply to the rendered quad in order // to sample from the source rectangle and render into the destination rectangle CoordRect coords; GetTextureCoords( m_pSceneScaled->GetImpliment(), &rectSrc, m_pBrightTexture->GetImpliment(), &rectDest, &coords ); // The bright-pass filter removes everything from the scene except lights and // bright reflections m_pEffect->SetTechnique( m_kBrightPassFilter ); ID3D10RenderTargetView * pView = m_pBrightTexture->GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); float fValue = 0.5f; m_pEffect->SetFloat( m_kMiddleGray, &fValue ); m_pEffect->SetTexture( m_kTexture[0], m_pSceneScaled ); m_pEffect->SetTexture( m_kTexture[1], m_pCurLuminance ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); // pD3D10Device->SetScissorRect( &rectDest ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, coords.fLeftU, coords.fTopV, coords.fRightU, coords.fBottomV ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, FALSE ); return true; } bool D3D10HDR::BrightPass_To_StarSource() { D3DXVECTOR4 avSampleOffsets[MAX_SAMPLES]; D3DXVECTOR4 avSampleWeights[MAX_SAMPLES]; // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); // Get the destination rectangle. // Decrease the rectangle to adjust for the single pixel black border. RECT rectDest; GetTextureRect( m_pStarSource->GetImpliment(), &rectDest ); InflateRect( &rectDest, -1, -1 ); // Get the correct texture coordinates to apply to the rendered quad in order // to sample from the source rectangle and render into the destination rectangle CoordRect coords; GetTextureCoords( m_pBrightTexture->GetImpliment(), NULL, m_pStarSource->GetImpliment(), &rectDest, &coords ); // Get the sample offsets used within the pixel shader RECT desc; GetTextureRect( m_pBrightTexture->GetImpliment(), &desc ); GetSampleOffsets_GaussBlur5x5( desc.right, desc.bottom, avSampleOffsets, avSampleWeights ); m_pEffect->SetValue( m_kSampleOffsets, (void *) avSampleOffsets, sizeof(avSampleOffsets) ); m_pEffect->SetValue( m_kSampleWeights, (void *) avSampleWeights, sizeof(avSampleWeights) ); // The gaussian blur smooths out rough edges to avoid aliasing effects // when the star effect is run m_pEffect->SetTechnique( m_kGaussBlur5x5 ); ID3D10RenderTargetView * pView = m_pStarSource->GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], m_pBrightTexture ); // pD3D10Device->SetScissorRect( &rectDest ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, coords.fLeftU, coords.fTopV, coords.fRightU, coords.fBottomV ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, FALSE ); return true; } bool D3D10HDR::StarSource_To_BloomSource() { D3DXVECTOR2 avSampleOffsets[MAX_SAMPLES]; // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); // Get the rectangle describing the sampled portion of the source texture. // Decrease the rectangle to adjust for the single pixel black border. RECT rectSrc; GetTextureRect( m_pStarSource->GetImpliment(), &rectSrc ); InflateRect( &rectSrc, -1, -1 ); // Get the destination rectangle. // Decrease the rectangle to adjust for the single pixel black border. RECT rectDest; GetTextureRect( m_pBloomSource->GetImpliment(), &rectDest ); InflateRect( &rectDest, -1, -1 ); // Get the correct texture coordinates to apply to the rendered quad in order // to sample from the source rectangle and render into the destination rectangle CoordRect coords; GetTextureCoords( m_pStarSource->GetImpliment(), &rectSrc, m_pBloomSource->GetImpliment(), &rectDest, &coords ); // Get the sample offsets used within the pixel shader RECT desc; GetTextureRect( m_pBrightTexture->GetImpliment(), &desc ); GetSampleOffsets_DownScale2x2( desc.right, desc.bottom, avSampleOffsets ); m_pEffect->SetValue( m_kSampleOffsets, (void *) avSampleOffsets, sizeof(avSampleOffsets) ); // Create an exact 1/2 x 1/2 copy of the source texture m_pEffect->SetTechnique( m_kDownScale2x2 ); ID3D10RenderTargetView * pView = m_pBloomSource->GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], m_pStarSource ); // pD3D10Device->SetScissorRect( &rectDest ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, coords.fLeftU, coords.fTopV, coords.fRightU, coords.fBottomV ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, FALSE ); return true; } bool D3D10HDR::MeasureLuminance() { int x, y, index; D3DXVECTOR2 avSampleOffsets[MAX_SAMPLES]; DWORD dwCurTexture = NUM_TONEMAP_TEXTURES - 1; // 获取D3D10设备指针 D3D10RenderWindow * pRenderWindow = ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow(); ID3D10Device * pD3D10Device = pRenderWindow->GetDevice(); RECT desc; GetTextureRect( m_pToneMapTexture[dwCurTexture].GetImpliment(), &desc ); // Initialize the sample offsets for the initial luminance pass. float tU, tV; tU = 1.0f / ( 3.0f * desc.right ); tV = 1.0f / ( 3.0f * desc.bottom ); index = 0; for( x = -1; x <= 1; x++ ) { for( y = -1; y <= 1; y++ ) { avSampleOffsets[index].x = x * tU; avSampleOffsets[index].y = y * tV; index++; } } // After this pass, the g_apTexToneMap[NUM_TONEMAP_TEXTURES-1] texture will contain // a scaled, grayscale copy of the HDR scene. Individual texels contain the log // of average luminance values for points sampled on the HDR texture. m_pEffect->SetTechnique( m_kSampleAvgLum ); m_pEffect->SetValue( m_kSampleOffsets, (void *) avSampleOffsets, sizeof(avSampleOffsets) ); ID3D10RenderTargetView * pView = m_pToneMapTexture[dwCurTexture].GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], m_pSceneScaled ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); dwCurTexture--; // Initialize the sample offsets for the iterative luminance passes while( dwCurTexture > 0 ) { GetTextureRect( m_pToneMapTexture[dwCurTexture + 1].GetImpliment(), &desc ); GetSampleOffsets_DownScale4x4( desc.right, desc.bottom, avSampleOffsets ); // Each of these passes continue to scale down the log of average // luminance texture created above, storing intermediate results in // g_apTexToneMap[1] through g_apTexToneMap[NUM_TONEMAP_TEXTURES-1]. m_pEffect->SetTechnique( m_kResampleAvgLum ); m_pEffect->SetValue( m_kSampleOffsets, (void *)avSampleOffsets, sizeof(avSampleOffsets) ); ID3D10RenderTargetView * pView = m_pToneMapTexture[dwCurTexture].GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], &( m_pToneMapTexture[dwCurTexture + 1] ) ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); dwCurTexture--; } // Downsample to 1x1 GetTextureRect( m_pToneMapTexture[1].GetImpliment(), &desc ); GetSampleOffsets_DownScale4x4( desc.right, desc.bottom, avSampleOffsets ); // Perform the final pass of the average luminance calculation. This pass // scales the 4x4 log of average luminance texture from above and performs // an exp() operation to return a single texel cooresponding to the average // luminance of the scene in g_apTexToneMap[0]. m_pEffect->SetTechnique( m_kResampleAvgLumExp ); m_pEffect->SetValue( m_kSampleOffsets, (void *)avSampleOffsets, sizeof(avSampleOffsets) ); pView = m_pToneMapTexture[0].GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], &( m_pToneMapTexture[1] ) ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); return true; } bool D3D10HDR::CalculateAdaptation() { HRESULT hr = S_OK; // 获取D3D10设备指针 ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice(); // Swap current & last luminance D3D10Texture * pTexSwap = m_pLastLuminance; m_pLastLuminance = m_pCurLuminance; m_pCurLuminance = pTexSwap; // This simulates the light adaptation that occurs when moving from a // dark area to a bright area, or vice versa. The g_pTexAdaptedLuminance // texture stores a single texel cooresponding to the user's adapted // level. m_pEffect->SetTechnique( m_kCalculateAdaptedLum ); float fElapsedTime = RenderWindow::GetActiveRenderWindow()->GetElapsedTime(); m_pEffect->SetFloat( m_kElapsedTime, &fElapsedTime ); ID3D10RenderTargetView * pView = m_pCurLuminance->GetRenderTargetView(); pD3D10Device->OMSetRenderTargets( 1, &pView, NULL ); m_pEffect->SetTexture( m_kTexture[0], m_pLastLuminance ); m_pEffect->SetTexture( m_kTexture[1], &( m_pToneMapTexture[0] ) ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); // m_pCurLuminance = &( m_pToneMapTexture[0] ); return true; } bool D3D10HDR::RenderStar() { int i, d, p, s; // Loop variables // 获取D3D10设备指针 ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice(); // Avoid rendering the star if it's not being used in the current glare if ( m_pGlareDef->m_fGlareLuminance <= 0.0f || m_pGlareDef->m_fStarLuminance <= 0.0f ) { return true; } // Initialize the constants used during the effect const CStarDef& starDef = m_pGlareDef->m_starDef ; const float fTanFoV = atanf(D3DX_PI/8) ; const D3DXVECTOR4 vWhite( 1.0f, 1.0f, 1.0f, 1.0f ); static const int s_maxPasses = 3 ; static const int nSamples = 8 ; static D3DXVECTOR4 s_aaColor[s_maxPasses][8] ; static const D3DXCOLOR s_colorWhite(0.63f, 0.63f, 0.63f, 0.0f) ; D3DXVECTOR4 avSampleWeights[MAX_SAMPLES]; D3DXVECTOR2 avSampleOffsets[MAX_SAMPLES]; ID3D10RenderTargetView * pSurfDest = NULL; // Set aside all the star texture surfaces as a convenience ID3D10RenderTargetView * apSurfStar[NUM_STAR_TEXTURES] = {0}; for( i=0; i < NUM_STAR_TEXTURES; i++ ) { apSurfStar[i] = m_pStarTexture[i].GetRenderTargetView(); } RECT desc; GetTextureRect( m_pStarSource->GetImpliment(), &desc ); float srcW; srcW = (FLOAT) desc.right; float srcH; srcH= (FLOAT) desc.bottom; for ( p = 0; p < s_maxPasses; p++ ) { float ratio; ratio = (float)(p + 1) / (float)s_maxPasses ; for (s = 0 ; s < nSamples ; s ++) { D3DXCOLOR chromaticAberrColor ; D3DXColorLerp( &chromaticAberrColor, &( CStarDef::GetChromaticAberrationColor(s) ), &s_colorWhite, ratio ); D3DXColorLerp( (D3DXCOLOR*)&( s_aaColor[p][s] ), &s_colorWhite, &chromaticAberrColor, m_pGlareDef->m_fChromaticAberration ); } } float radOffset; radOffset = m_pGlareDef->m_fStarInclination + starDef.m_fInclination ; D3D10Texture * pTexSource; // Direction loop for (d = 0 ; d < starDef.m_nStarLines ; d ++) { const STARLINE& starLine = starDef.m_pStarLine[d]; pTexSource = m_pStarSource; float rad; rad = radOffset + starLine.fInclination ; float sn, cs; sn = sinf(rad), cs = cosf(rad) ; D3DXVECTOR2 vtStepUV; vtStepUV.x = sn / srcW * starLine.fSampleLength ; vtStepUV.y = cs / srcH * starLine.fSampleLength ; float attnPowScale; attnPowScale = ( fTanFoV + 0.1f ) * 1.0f * (160.0f + 120.0f) / ( srcW + srcH ) * 1.2f ; int iWorkTexture; iWorkTexture = 1 ; for ( p = 0; p < starLine.nPasses; p ++ ) { if ( p == starLine.nPasses - 1 ) { // Last pass move to other work buffer pSurfDest = apSurfStar[d + 4]; } else { pSurfDest = apSurfStar[iWorkTexture]; } // Sampling configration for each stage for ( i = 0; i < nSamples; i++ ) { float lum; lum = powf( starLine.fAttenuation, attnPowScale * i ); avSampleWeights[i] = s_aaColor[starLine.nPasses - 1 - p][i] * lum * ( p + 1.0f ) * 0.5f ; // Offset of sampling coordinate avSampleOffsets[i].x = vtStepUV.x * i; avSampleOffsets[i].y = vtStepUV.y * i; if ( fabs( avSampleOffsets[i].x ) >= 0.9f || fabs( avSampleOffsets[i].y ) >= 0.9f ) { avSampleOffsets[i].x = 0.0f ; avSampleOffsets[i].y = 0.0f ; avSampleWeights[i] *= 0.0f ; } } m_pEffect->SetTechnique( m_kStar ); D3DXVECTOR4 pvOffsets[nSamples]; for ( i = 0; i < nSamples; i++ ) { pvOffsets[i] = D3DXVECTOR4( avSampleOffsets[i][0], avSampleOffsets[i][1], 0.0f, 0.0f ); } m_pEffect->SetValue( m_kSampleOffsets, pvOffsets, sizeof(pvOffsets) ); m_pEffect->SetValue( m_kSampleWeights, avSampleWeights, sizeof(avSampleWeights) ); // m_pEffect->SetVectorArray( m_kSampleWeights, pvWeights, nSamples ); pD3D10Device->OMSetRenderTargets( 1, &pSurfDest, NULL ); m_pEffect->SetTexture( m_kTexture[0], pTexSource ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); // Setup next expansion vtStepUV *= nSamples ; attnPowScale *= nSamples ; // Set the work drawn just before to next texture source. pTexSource = &( m_pStarTexture[iWorkTexture] ); iWorkTexture += 1 ; if ( iWorkTexture > 2 ) { iWorkTexture = 1 ; } } } pSurfDest = apSurfStar[0]; for( i = 0; i < starDef.m_nStarLines; i++ ) { m_pEffect->SetTexture( m_kTexture[i], &( m_pStarTexture[i + 4] ) ); avSampleWeights[i] = vWhite * 1.0f / (FLOAT) starDef.m_nStarLines; } m_pEffect->SetTechnique( m_kMergeTextures[starDef.m_nStarLines - 1] ); m_pEffect->SetValue( m_kSampleWeights, avSampleWeights, sizeof(avSampleWeights) ); // m_pEffect->SetVectorArray( m_kSampleWeights, pvWeights2, starDef.m_nStarLines ); pD3D10Device->OMSetRenderTargets( 1, &pSurfDest, NULL ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); return true; } bool D3D10HDR::RenderBloom() { int i = 0; D3DXVECTOR4 avSampleOffsets[MAX_SAMPLES]; float afSampleOffsets[MAX_SAMPLES]; D3DXVECTOR4 avSampleWeights[MAX_SAMPLES]; // 获取D3D10设备指针 ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice(); ID3D10RenderTargetView * pSurfScaledHDR; pSurfScaledHDR = m_pSceneScaled->GetRenderTargetView(); ID3D10RenderTargetView * pSurfBloom; pSurfBloom = m_pBloomTexture[0].GetRenderTargetView(); ID3D10RenderTargetView * pSurfHDR; pSurfHDR = m_pSceneTexture->GetRenderTargetView(); ID3D10RenderTargetView * pSurfTempBloom; pSurfTempBloom = m_pBloomTexture[1].GetRenderTargetView(); ID3D10RenderTargetView * pSurfBloomSource; pSurfBloomSource = m_pBloomTexture[2].GetRenderTargetView(); // Clear the bloom texture float ClearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; pD3D10Device->ClearRenderTargetView( pSurfBloom, ClearColor ); if ( m_pGlareDef->m_fGlareLuminance <= 0.0f || m_pGlareDef->m_fBloomLuminance <= 0.0f) { return true; } RECT rectSrc; GetTextureRect( m_pBloomSource->GetImpliment(), &rectSrc ); // InflateRect( &rectSrc, -1, -1 ); RECT rectDest; GetTextureRect( m_pBloomTexture[2].GetImpliment(), &rectDest ); // InflateRect( &rectDest, -1, -1 ); CoordRect coords; GetTextureCoords( m_pBloomSource->GetImpliment(), &rectSrc, m_pBloomTexture[2].GetImpliment(), &rectDest, &coords ); RECT desc; GetTextureRect( m_pBloomSource->GetImpliment(), &desc ); m_pEffect->SetTechnique( m_kGaussBlur5x5 ); GetSampleOffsets_GaussBlur5x5( desc.right, desc.bottom, avSampleOffsets, avSampleWeights, 1.0f ); m_pEffect->SetValue( m_kSampleOffsets, avSampleOffsets, sizeof(avSampleOffsets) ); m_pEffect->SetValue( m_kSampleWeights, avSampleWeights, sizeof(avSampleWeights) ); pD3D10Device->OMSetRenderTargets( 1, &pSurfBloomSource, NULL ); m_pEffect->SetTexture( m_kTexture[0], m_pBloomSource ); // pD3D10Device->SetScissorRect( &rectDest ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, FALSE ); GetTextureRect( m_pBloomTexture[2].GetImpliment(), &desc ); GetSampleOffsets_Bloom( desc.right, afSampleOffsets, avSampleWeights, 3.0f, 2.0f ); for( i = 0; i < MAX_SAMPLES; i++ ) { avSampleOffsets[i] = D3DXVECTOR4( afSampleOffsets[i], 0.0f, 1.0f, 1.0f ); } m_pEffect->SetTechnique( m_kBloom ); m_pEffect->SetValue( m_kSampleOffsets, avSampleOffsets, sizeof(avSampleOffsets) ); m_pEffect->SetValue( m_kSampleWeights, avSampleWeights, sizeof(avSampleWeights) ); pD3D10Device->OMSetRenderTargets( 1, &pSurfTempBloom, NULL ); m_pEffect->SetTexture( m_kTexture[0], &( m_pBloomTexture[2] ) ); // pD3D10Device->SetScissorRect( &rectDest ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); // pD3D10Device->SetRenderState( D3DRS_SCISSORTESTENABLE, FALSE ); GetTextureRect( m_pBloomTexture[1].GetImpliment(), &desc ); GetSampleOffsets_Bloom( desc.bottom, afSampleOffsets, avSampleWeights, 3.0f, 2.0f ); for( i = 0; i < MAX_SAMPLES; i++ ) { avSampleOffsets[i] = D3DXVECTOR4( 0.0f, afSampleOffsets[i], 0.0f, 0.0f ); } GetTextureRect( m_pBloomTexture[1].GetImpliment(), &rectSrc ); // InflateRect( &rectSrc, -1, -1 ); GetTextureCoords( m_pBloomTexture[1].GetImpliment(), &rectSrc, m_pBloomTexture[0].GetImpliment(), NULL, &coords ); m_pEffect->SetTechnique( m_kBloom ); m_pEffect->SetValue( m_kSampleOffsets, avSampleOffsets, sizeof(avSampleOffsets) ); m_pEffect->SetValue( m_kSampleWeights, avSampleWeights, sizeof(avSampleWeights) ); pD3D10Device->OMSetRenderTargets( 1, &pSurfBloom, NULL ); m_pEffect->SetTexture( m_kTexture[0], &( m_pBloomTexture[1] ) ); RenderWindow::GetActiveRenderWindow()->GetRenderer()->RenderQuad( m_pEffect, 0.0f, 0.0f, 1.0f, 1.0f ); return true; } bool D3D10HDR::GetTextureRect( ID3D10Texture2D * pTexture, RECT * pRect ) { if( pTexture == NULL || pRect == NULL ) { return false; } D3D10_TEXTURE2D_DESC desc; pTexture->GetDesc( &desc ); pRect->left = 0; pRect->top = 0; pRect->right = desc.Width; pRect->bottom = desc.Height; return true; } bool D3D10HDR::GetTextureCoords( ID3D10Texture2D * pTexSrc, RECT * pRectSrc, ID3D10Texture2D * pTexDest, RECT * pRectDest, CoordRect * pCoords ) { D3D10_TEXTURE2D_DESC desc; float tU, tV; // Validate arguments if( pTexSrc == NULL || pTexDest == NULL || pCoords == NULL ) { return false; } // Start with a default mapping of the complete source surface to complete // destination surface pCoords->fLeftU = 0.0f; pCoords->fTopV = 0.0f; pCoords->fRightU = 1.0f; pCoords->fBottomV = 1.0f; // If not using the complete source surface, adjust the coordinates if( pRectSrc != NULL ) { // Get destination texture description pTexSrc->GetDesc( &desc ); // These delta values are the distance between source texel centers in // texture address space tU = 1.0f / desc.Width; tV = 1.0f / desc.Height; pCoords->fLeftU += pRectSrc->left * tU; pCoords->fTopV += pRectSrc->top * tV; pCoords->fRightU -= (desc.Width - pRectSrc->right) * tU; pCoords->fBottomV -= (desc.Height - pRectSrc->bottom) * tV; } // If not drawing to the complete destination surface, adjust the coordinates if( pRectDest != NULL ) { // Get source texture description pTexDest->GetDesc( &desc ); // These delta values are the distance between source texel centers in // texture address space tU = 1.0f / desc.Width; tV = 1.0f / desc.Height; pCoords->fLeftU -= pRectDest->left * tU; pCoords->fTopV -= pRectDest->top * tV; pCoords->fRightU += (desc.Width - pRectDest->right) * tU; pCoords->fBottomV += (desc.Height - pRectDest->bottom) * tV; } return true; } float D3D10HDR::GaussianDistribution( float x, float y, float rho ) { float g = 1.0f / sqrtf( 2.0f * D3DX_PI * rho * rho ); g *= expf( -(x*x + y*y)/(2*rho*rho) ); return g; } bool D3D10HDR::GetSampleOffsets_GaussBlur5x5( DWORD dwD3DTexWidth, DWORD dwD3DTexHeight, D3DXVECTOR4 * avTexCoordOffset, D3DXVECTOR4 * avSampleWeights, float fMultiplier ) { float tu = 1.0f / (float)dwD3DTexWidth ; float tv = 1.0f / (float)dwD3DTexHeight ; D3DXVECTOR4 vWhite( 1.0f, 1.0f, 1.0f, 1.0f ); float totalWeight = 0.0f; int index=0; for( int x = -2; x <= 2; x++ ) { for( int y = -2; y <= 2; y++ ) { // Exclude pixels with a block distance greater than 2. This will // create a kernel which approximates a 5x5 kernel using only 13 // sample points instead of 25; this is necessary since 2.0 shaders // only support 16 texture grabs. if( abs(x) + abs(y) > 2 ) continue; // Get the unscaled Gaussian intensity for this offset avTexCoordOffset[index] = D3DXVECTOR4( x * tu, y * tv, 0.0f, 0.0f ); avSampleWeights[index] = vWhite * GaussianDistribution( (float)x, (float)y, 1.0f ); totalWeight += avSampleWeights[index].x; index++; } } // Divide the current weight by the total weight of all the samples; Gaussian // blur kernels add to 1.0f to ensure that the intensity of the image isn't // changed when the blur occurs. An optional multiplier variable is used to // add or remove image intensity during the blur. for( int i=0; i < index; i++ ) { avSampleWeights[i] /= totalWeight; avSampleWeights[i] *= fMultiplier; } return true; } bool D3D10HDR::GetSampleOffsets_Bloom( DWORD dwD3DTexSize, float afTexCoordOffset[15], D3DXVECTOR4 * avColorWeight, float fDeviation, float fMultiplier ) { int i=0; float tu = 1.0f / (float)dwD3DTexSize; // Fill the center texel float weight = fMultiplier * GaussianDistribution( 0, 0, fDeviation ); avColorWeight[0] = D3DXVECTOR4( weight, weight, weight, 1.0f ); afTexCoordOffset[0] = 0.0f; // Fill the first half for( i=1; i < 8; i++ ) { // Get the Gaussian intensity for this offset weight = fMultiplier * GaussianDistribution( (float)i, 0, fDeviation ); afTexCoordOffset[i] = i * tu; avColorWeight[i] = D3DXVECTOR4( weight, weight, weight, 1.0f ); } // Mirror to the second half for( i=8; i < 15; i++ ) { avColorWeight[i] = avColorWeight[i-7]; afTexCoordOffset[i] = -afTexCoordOffset[i-7]; } return true; } bool D3D10HDR::GetSampleOffsets_Star(DWORD dwD3DTexSize, float afTexCoordOffset[15], D3DXVECTOR4 * avColorWeight, float fDeviation) { int i=0; float tu = 1.0f / (float)dwD3DTexSize; // Fill the center texel float weight = 1.0f * GaussianDistribution( 0, 0, fDeviation ); avColorWeight[0] = D3DXVECTOR4( weight, weight, weight, 1.0f ); afTexCoordOffset[0] = 0.0f; // Fill the first half for( i=1; i < 8; i++ ) { // Get the Gaussian intensity for this offset weight = 1.0f * GaussianDistribution( (float)i, 0, fDeviation ); afTexCoordOffset[i] = i * tu; avColorWeight[i] = D3DXVECTOR4( weight, weight, weight, 1.0f ); } // Mirror to the second half for( i=8; i < 15; i++ ) { avColorWeight[i] = avColorWeight[i-7]; afTexCoordOffset[i] = -afTexCoordOffset[i-7]; } return true; } bool D3D10HDR::GetSampleOffsets_DownScale4x4( DWORD dwWidth, DWORD dwHeight, D3DXVECTOR2 avSampleOffsets[] ) { if( NULL == avSampleOffsets ) { return false; } float tU = 1.0f / dwWidth; float tV = 1.0f / dwHeight; // Sample from the 16 surrounding points. Since the center point will be in // the exact center of 16 texels, a 0.5f offset is needed to specify a texel // center. int index=0; for( int y=0; y < 4; y++ ) { for( int x=0; x < 4; x++ ) { avSampleOffsets[ index ].x = (x - 1.5f) * tU; avSampleOffsets[ index ].y = (y - 1.5f) * tV; index++; } } return true; } bool D3D10HDR::GetSampleOffsets_DownScale2x2( DWORD dwWidth, DWORD dwHeight, D3DXVECTOR2 avSampleOffsets[] ) { if( NULL == avSampleOffsets ) { return false; } float tU = 1.0f / dwWidth; float tV = 1.0f / dwHeight; // Sample from the 4 surrounding points. Since the center point will be in // the exact center of 4 texels, a 0.5f offset is needed to specify a texel // center. int index=0; for( int y=0; y < 2; y++ ) { for( int x=0; x < 2; x++ ) { avSampleOffsets[ index ].x = (x - 0.5f) * tU; avSampleOffsets[ index ].y = (y - 0.5f) * tV; index++; } } return true; } }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 1152 ] ] ]
d54a7233ca77d43a75a336de70a72ce90e405a8b
4ac19e8642b3005d702a1112a722811c8b3cc7c6
/src/a_cgi.cpp
f5436dba9f0214c5221936027c5565576abce33d
[ "BSD-3-Clause" ]
permissive
amreisa/freeCGI
5ab00029e86fad79a2580262c04afa3ae442e127
84c047c4790eaabbc9d2284242a44c204fe674ea
refs/heads/master
2022-04-27T19:51:11.690512
2011-02-28T22:33:34
2011-02-28T22:33:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,264
cpp
#include "freeCGI.h" #ifdef WIN32 #pragma message( "Compiling " __FILE__ ) #endif #define READ_BUFFER_SIZE 1536 //a_Some read buffer size #ifdef _DEBUG_DUMP_ void ACGI::dump() { cout << endl << "---START: ACGI::dump()---"; AHTML::dump(); AFormList::dump(); cout << endl << "---END: ACGI::dump()---" << endl; } #endif int ACGI::cgiGetQueryStringItems(const char *pccInput) { int iRet = 0x0; if (!pccInput) { //a_Try to get the QueryString #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::cgiGetQueryStringItems(const char *)=" << cgiGetQueryString() << "-->"; #endif if (!strstr(cgiGetQueryString(), NULL_STRING)) { //a_Something is in there iRet = flGenerateList(cgiGetQueryString()); } } else { #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::cgiGetQueryStringItems(const char *)=" << pccInput << "-->"; #endif iRet = flGenerateList(pccInput); } return iRet; } int ACGI::cgiGetFormItems(istream *pisInput) { #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::cgiGetFormItems(istream *)-->"; #endif return _cgiDoFormItems(pisInput); } int ACGI::cgiGetFormItems(const char *pccInput) { #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::cgiGetFormItems(const char *)-->"; #endif if (pccInput) return flGenerateList(pccInput); return _cgiDoFormItems(); } int ACGI::_cgiDoFormItems(istream *pisInput) { if (pisInput) { //a_Another stream used for inputing #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::_cgiDoFormItems: istream-->"; #endif return flGenerateList(pisInput, -1); } else { if (cgiIsGET()) { #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::_cgiDoFormItems: GET-->"; #endif return flGenerateList(cgiGetQueryString()); } else { if (cgiIsPOST()) { #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::_cgiDoFormItems: POST and GET-->"; #endif return flGenerateList(&cin, atoi(cgiGetContentLength())) + flGenerateList(cgiGetQueryString());; } else { //a_Not a POST or a GET (hmm... HEAD, PUT, LINK, UNLINK, DELETE and FILE not yet supported (inadequate documentation)) #ifdef _DEBUG_DUMP_ cout << "<!--ACGI::_cgiDoFormItems: Neither POST nor GET-->"; #endif } } } return 0x0; } //a_Checks for EMail in the form of [email protected] and has no HTML tags embedded int ACGI::cgiIsValidEMail(const char *pccTest) { if (pccTest && cgiIsNotValidHTMLLine(pccTest)) { const char *pccX = strchr(pccTest, '@'); if (!pccX) return 0x0; //a_Must have name@address //a_Domain must have at least 1 period if {com, edu, net, org, gov, mil, int, us, etc} pccX = strchr(pccX, '.'); if (!pccX) return 0x0; //a_Missing a mandatory period } return 0x1; //a_Passed all tests } int ACGI::cgiIsWithoutMetaChar(const char *pccTest, int iStrict) { //a_NULL string or no string if (!pccTest || *pccTest == '\x0') return 0x0; //a_Strict form doesn't allow double-quotes const char *pTestSet = (iStrict ? ";<>|&?*$#\'\"" : ";<>&?*|$#\'"); register int iX = strlen(pccTest); while (--iX >= 0x0) { //a_Control characters are not accepted (signed < 0x0 is non-ASCII) if (*(pccTest +iX) < 0x20) return 0x0; //a_Search for invalid shell metacharacters (these should not be in an image URL) if (strchr(pTestSet, *(pccTest + iX))) return 0x0; } return 0x1; //a_No meta characters that can cause problems } //a_Checks for invalid metacharacters and quote pairs int ACGI::cgiIsValidHTMLTag(const char *pccTest) { //a_NULL string or no string if (!pccTest || *pccTest == '\x0') return 0x0; //a_Check for metacharacters if (!cgiIsWithoutMetaChar(pccTest)) return 0x0; //a_(Check for quote pairs!!!) register int iX; const char *pccX = strchr(pccTest, '\"'); if (pccX) { //Found one quote iX = 0x1; while ((pccX = strchr(++pccX, '\"'))) { iX++; } if ((iX % 0x2) != 0x0) return 0x0; //a_Uneven # of quotes } return 0x1; //a_Valid it seems } //a_Checks for valid URL (Usually after decoding if neccessary) //a_ 0: NULL, empty string or meta character contained //a_ 1: http:// 2: ftp:// 3: gopher:// //a_ 4: mailto: 5: news: int ACGI::cgiIsValidURLProtocol(const char *pccTest) { //a_NULL string or no string if (!pccTest || *pccTest == '\x0') return 0x0; //a_Check for metacharacters, strict test if (!cgiIsWithoutMetaChar(pccTest, 0x1)) return 0x0; AURL urlTest(pccTest); return urlTest.urlIsValidProtocol(); } //a_Checks if the URL is "valid" int ACGI::cgiIsValidURL(const char *pccTest) { //a_NULL string or no string if (!pccTest || *pccTest == '\x0') return 0x0; //a_Check for metacharacters, strict test if (!cgiIsWithoutMetaChar(pccTest, 0x1)) return 0x0; AURL urlTest(pccTest); return urlTest.urlIsValidURL(); } //a_Scans the string for HTML entries that may be questionable //a_Usually these will cause problems if embedded into HTML int ACGI::cgiIsNotValidHTMLLine(const char *pccTest) { //a_NULL string or no string if (!pccTest || *pccTest == '\x0') return 0x0; const int iiBC = 22; const char *sBadCodes[iiBC] = { ".exe", ".cgi", ".pl", "<html", "</html", "<body", "</body", "<head", "</head", "<script", "<form", "#exec", "cmd=", "<meta", "</title", "<title", "!-", "<base", "<link", "applet=", "app=", "command=", }; int iX = 0x0, iLength = strlen(pccTest); char *pcTest = aStrDup(pccTest); if (pcTest) { for(iX = 0x0; iX < iLength; iX++) *(pcTest + iX) = tolower(*(pcTest + iX)); for (iX = 0x0; iX < iiBC; iX++) { if (strstr(pcTest, sBadCodes[iX])) { iX = 0x0; break; } } } return (iX == iiBC ? 0x0 : iX); //a_If end of list, then it is valid } //a_Gets acharacter string, if it finds unacceptable code it replaces the //a_ entire <TAG> with <!--> so it is ignored by the browser //a_This is used to validate input from a user that may be imbedded into a dynamic page char *ACGI::cgiValidateHTMLLine(char *pcLine) { if (!pcLine) return NULL; //a_Checks that the line is of valid type char *pcStart = pcLine, *pcEnd = NULL; //a_1 letter: Italic, Bold, Underline, Strikeout, Quote, Anchor //a_2 letter: EMphasis, TeleType, line BReak, AUthor //a_3 letter: BIG, IMaGe, SUPerscript, SUBscript, KeyBoarD, PREformatted //a_4 letter: CODE, FONT //a_5 letter: SMALL //a_6 letter: STRONG, STRIKE const int iiTagSize = 0x6; const char *psTags[iiTagSize] = { "ibusqa", "emttbrau", "bigimgsupsubkbdpre", "codefont", "small", "strongstrike" }; //a_Search for tags and verify they are ok... int iOK; //a_Not tested while ((pcStart = strchr(pcStart, '<'))) { iOK = -1; //a_Start of test if (!(pcEnd = strchr(pcStart, '>'))) //a_Where the tag ends { //a_Kill the rest of the message, all tags must be closed (eg. <TAG>, not. <TAG ) *pcStart = 0x0; return pcLine; } pcStart++; //a_Go inside the tag //a_Make lower inside tag for(char *pc = pcStart; pc < pcEnd; ++pc) *(pc) = tolower(*pc); //a_First check for unacceptable characters char cAfter = *(pcEnd + 0x1); //a_Work one tag at a time *(pcEnd) = ' '; //a_Back from '>' to ' ' for testing *(pcEnd + 0x1) = 0x0; if (cgiIsValidHTMLTag(pcStart)) { if (*pcStart == '/') pcStart++; //a_Skip the end of tag marker if (iOK < 0x0) { //a_No decision yet, check HTML formatting char sTest[0x8]; const char *pSet; for (int iN = 0x0; iN < iiTagSize; iN ++) { //a_Check N character tags *(sTest + iN + 0x1) = ' '; *(sTest + iN + 0x2) = 0x0; pSet = psTags[iN]; while (*pSet) { strncpy(sTest, pSet, iN + 1); if (pcStart == strstr(pcStart, sTest)) { iOK = iN + 0x1; //a_Found a valid tag break; } pSet += (iN + 0x1); //a_Advance as many characters } if (iOK > 0x0) break; //a_Already found, out of the for() loop } if (iOK < 0x0) iOK = 0x0; //a_No decision at the end is a failure } } else iOK = 0x0; *(pcEnd) = '>'; //a_Back from NULL to '>' *(pcEnd + 0x1) = cAfter; //a_Restore the one after //a_If at least one correct tag was found then this will be equal to the value of its size if (iOK <= 0x0) { //a_This current tag is invalid, fill it with a comment :) *(pcStart++) = '!'; while (pcStart < pcEnd) *(pcStart++) = '-'; } } return pcLine; //a_No problems if it got this far... } void ACGI::cgiEncodeAndOutputURL(const char *pccSource, int iLength) { char *pcOut = g_aCrypto.convertoEncodeURL(pccSource, iLength); if (pcOut) outString(pcOut); delete []pcOut; } void ACGI::cgiEnvironmentDump(int iFullDump) { htmlTag("br"); htmlTag("hr", "size=\"4\""); htmlTag("br"); htmlDoTag("h1", "Environment Dump"); htmlDoTag("h2", "HTTP Specific"); htmlStartTag("table", "width=\"100%\" border=\"2\""); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Accept"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPAccept()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Accept-Encoding"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPAcceptEncoding()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Accept-Language"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPAcceptLanguage()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Accept-Charset"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPAcceptCharset()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Authorization"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPAuthorization()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ContentType"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetContentType()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ContentLength"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetContentLength()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Cookie"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPCookie()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "From"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPFrom()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "If-Match"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPIfMatch()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "If-Modified-Since"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPIfModifiedSince()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "If-None-Match"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPIfNoneMatch()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "If-Range"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPIfRange()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "If-Unmodified-Since"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPIfUnmodifiedSince()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Max-Forwards"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPMaxForwards()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Proxy-Authorization"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPProxyAuthorization()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Pragma"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPPragma()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "QueryString"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetQueryString()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Range"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPRange()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Referer"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPReferer()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "RequestMethod"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetRequestMethod()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "TE"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPTE()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "User-Agent"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHTTPUserAgent()); htmlEndTag("tr"); htmlEndTag("table"); htmlDoTag("h2", "FORM data"); htmlStartTag("table", "width=\"100%\" border=\"2\""); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "FORM data (body of request)"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", getSafeFormData()); htmlEndTag("tr"); htmlEndTag("table"); htmlDoTag("h2", "Server Specific"); htmlStartTag("table", "width=\"100%\" border=\"2\""); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Annot. Server"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetAnnotationServer()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ServerName"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetServerName()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ServerSoftware"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetServerSoftware()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ServerPort"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetServerPort()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ServerProtocol"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetServerProtocol()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "GatewayInt"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetGatewayInterface()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "RemoteAddress"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetRemoteAddress()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "RemoteHost"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetRemoteHost()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "RemoteIdent"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetRemoteIdent()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Path"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetPath()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "PathInfo"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetPathInfo()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "PathTranslated= "); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetPathTranslated()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "ScriptName"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetScriptName()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "SHLVL"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetSHLVL()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "PWD"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetPWD()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "LogName"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetLogName()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "User"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetUser()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "Host"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHost()); htmlEndTag("tr"); htmlStartTag("tr"); htmlDoTagEx("th", "align=\"right\"", "HostType"); htmlDoTagEx("td", "bgcolor=\"#404040\" style=\"color: rgb(248,248,220)\"", cgiGetHostType()); htmlEndTag("tr"); htmlEndTag("table"); htmlTag("br"); htmlTag("hr", "size=\"4\""); htmlTag("br"); if (iFullDump) { htmlStartTag("pre"); #ifdef _DEBUG_DUMP_ outStringN("FORM and QueryString structure dump<br/>"); dump(); #else outStringCRN("<i>#define _DEBUG_DUMP_</i> and rebuild freeCGI for a full dump..."); #endif htmlEndTag("pre"); } } void ACGI::cgiStartFORM(const char *pccAction, const char *pccMethod) { outStringN("<FORM ACTION=\""); if (pccAction) outString(pccAction); else cgiGetScriptName(0x1); outStringN("\" METHOD="); if (pccMethod) outStringQ(pccMethod); else outStringQ("POST"); outStringCRN(">"); } void ACGI::_cgiDoInputType(int iType) { outStringN("<input type=\""); switch(iType) { case FORMINPUT_HIDDEN : outStringN("hidden\" "); break; case FORMINPUT_CHECKBOX : outStringN("checkbox\" "); break; case FORMINPUT_RADIO : outStringN("radio\" "); break; case FORMINPUT_TEXT : outStringN("text\" "); break; case FORMINPUT_PASSWORD : outStringN("password\" "); break; case FORMINPUT_RANGE : outStringN("range\" "); break; case FORMINPUT_SUBMIT : outStringN("submit\" "); break; case FORMINPUT_RESET : outStringN("reset\" "); break; case FORMINPUT_TEXTAREA : outStringN("textarea\" "); break; case FORMINPUT_IMAGE : outStringN("image\" "); break; case FORMINPUT_SCRIBBLE : outStringN("scribble\" "); break; case FORMINPUT_FILE : outStringN("file\" "); break; default : assert(0x0); //a_Unknown INPUT type! } } void ACGI::cgiDoFORMInput(int iType, AElementPairList &eplItems, const char *pccContent, const char *pccExtra) { //a_Output the input type first _cgiDoInputType(iType); eplItems.doOut(this); //a_Output the parameter list for this input item //a_Extra tag info if (pccExtra) outStringN(pccExtra); switch(iType) { case FORMINPUT_TEXTAREA: outStringCRN(">"); break; default: outStringCRN("/>"); break; } //a_Content goes after the tag if (pccContent) { outStringCR(pccContent); //a_Content string useful in <input type=...>{pccContent} ... } //a_Special case for TEXTAREA switch(iType) { case FORMINPUT_TEXTAREA: outStringCRN("</TEXTAREA>"); break; } } void ACGI::cgiDoFORMInput(int iType, const char *pccName, const char *pccValue, const char *pccContent, const char *pccExtra) { //a_Output the input type first _cgiDoInputType(iType); //a_Do the NAME items if (pccName) { outStringN("name="); outStringQ(pccName); } //a_Do the VALUE items if (pccValue) { outStringN(" value="); outStringQ(pccValue); } //a_Extra tag info if (pccExtra) outStringN(pccExtra); switch(iType) { case FORMINPUT_TEXTAREA: outStringCRN(">"); break; default: outStringCRN("/>"); break; } //a_Content goes after the tag if (pccContent) { outStringCR(pccContent); //a_Content string useful in <INPUT TYPE=...>{pccContent} ... } //a_Special case for TEXTAREA switch(iType) { case FORMINPUT_TEXTAREA : outStringCRN("</TEXTAREA>"); } } DWORD ACGI::cgiGetIP(const char *pccIP) { if (!pccIP) pccIP = cgiGetRemoteAddress(); char sWork[4]; DWORD dwRet = 0x0; for (register int iX = 0x0; iX < 0x4; iX++) { int iC = 0x0; while (*pccIP && *pccIP != '.' && iC < 0x4) sWork[iC++] = *pccIP++; if (iC >= 0x4) { assert(0x0); break; } //a_Something went wrong else if (*pccIP == '.') pccIP++; //a_Advance beyond the '.' sWork[iC] = '\x0'; DWORD dwTemp = (DWORD((atoi(sWork))) << (0x18 - 0x8 * iX)); dwRet |= dwTemp; } return dwRet; } int ACGI::cgiOutputBinary(const char *pccMIMEType, const char *pccMIMESubType, const char *pccFilePath) { if (m_posOut && pccMIMEType && pccMIMESubType && pccFilePath) { #ifdef _MSC_VER ifstream ifBinary(pccFilePath, ios::in|ios::binary); #elif defined(__BORLANDC__) ifstream ifBinary(pccFilePath, ios::in|ios::bin); #else //a_UNIX and others don't need the processing ifstream ifBinary(pccFilePath, ios::in); #endif #if defined(__BORLANDC__) || defined(__unix) if ((ifBinary.rdbuf())->is_open()) #else if (ifBinary.is_open()) #endif { //a_Get the length of the file ifBinary.seekg(0x0, ios::end); int iBytesRead = ifBinary.tellg(); //a_MIME output mimeOut(pccMIMEType, pccMIMESubType, iBytesRead); //a_Rewind the file ifBinary.seekg(0x0, ios::beg); //a_Set stream to binary #if defined(_MSC_VER) *this << ios::binary; #elif defined(__BORLANDC__) m_posOut.setf(ios::binary); #else //Probably UNIX and we do not care, everything is binary! #endif //Output the file char sBuffer[READ_BUFFER_SIZE]; while (!ifBinary.eof()) { ifBinary.read(sBuffer, READ_BUFFER_SIZE); iBytesRead = ifBinary.gcount(); if (iBytesRead > 0x0) m_posOut->write(sBuffer, iBytesRead); } ifBinary.close(); m_posOut->flush(); } else { #ifdef _DEBUG_DUMP_ mimeOut("text", "plain"); outStringN("Filename: "); outString(pccFilePath); outStringN(" connot be opened!"); #endif return 0x0; } } else { //a_You have to specify the MIME type/subtype for the binary output //a_and/or a non-NULL file path //a_and/or output stream variable is NULL assert(0x0); return 0x0; } return 0x1; }
[ "[email protected]", "this@OCEAN.(none)" ]
[ [ [ 1, 115 ], [ 117, 129 ], [ 131, 132 ], [ 134, 137 ], [ 140, 162 ], [ 164, 166 ], [ 168, 214 ], [ 216, 250 ], [ 252, 256 ], [ 258, 269 ], [ 271, 281 ], [ 283, 288 ], [ 290, 314 ], [ 316, 341 ], [ 343, 362 ], [ 364, 367 ], [ 369, 372 ], [ 374, 377 ], [ 379, 382 ], [ 384, 387 ], [ 389, 392 ], [ 394, 395 ], [ 397, 397 ], [ 399, 402 ], [ 404, 407 ], [ 409, 412 ], [ 414, 417 ], [ 419, 422 ], [ 424, 427 ], [ 429, 432 ], [ 434, 437 ], [ 439, 442 ], [ 444, 447 ], [ 449, 452 ], [ 454, 457 ], [ 459, 462 ], [ 464, 467 ], [ 469, 488 ], [ 490, 493 ], [ 495, 498 ], [ 500, 503 ], [ 505, 508 ], [ 510, 513 ], [ 515, 518 ], [ 520, 523 ], [ 525, 528 ], [ 530, 533 ], [ 535, 538 ], [ 540, 543 ], [ 545, 548 ], [ 550, 553 ], [ 555, 558 ], [ 560, 563 ], [ 565, 568 ], [ 570, 573 ], [ 575, 633 ], [ 635, 671 ], [ 673, 726 ], [ 728, 729 ], [ 731, 753 ], [ 755, 767 ], [ 769, 786 ], [ 788, 807 ], [ 810, 814 ] ], [ [ 116, 116 ], [ 130, 130 ], [ 133, 133 ], [ 138, 139 ], [ 163, 163 ], [ 167, 167 ], [ 215, 215 ], [ 251, 251 ], [ 257, 257 ], [ 270, 270 ], [ 282, 282 ], [ 289, 289 ], [ 315, 315 ], [ 342, 342 ], [ 363, 363 ], [ 368, 368 ], [ 373, 373 ], [ 378, 378 ], [ 383, 383 ], [ 388, 388 ], [ 393, 393 ], [ 396, 396 ], [ 398, 398 ], [ 403, 403 ], [ 408, 408 ], [ 413, 413 ], [ 418, 418 ], [ 423, 423 ], [ 428, 428 ], [ 433, 433 ], [ 438, 438 ], [ 443, 443 ], [ 448, 448 ], [ 453, 453 ], [ 458, 458 ], [ 463, 463 ], [ 468, 468 ], [ 489, 489 ], [ 494, 494 ], [ 499, 499 ], [ 504, 504 ], [ 509, 509 ], [ 514, 514 ], [ 519, 519 ], [ 524, 524 ], [ 529, 529 ], [ 534, 534 ], [ 539, 539 ], [ 544, 544 ], [ 549, 549 ], [ 554, 554 ], [ 559, 559 ], [ 564, 564 ], [ 569, 569 ], [ 574, 574 ], [ 634, 634 ], [ 672, 672 ], [ 727, 727 ], [ 730, 730 ], [ 754, 754 ], [ 768, 768 ], [ 787, 787 ], [ 808, 809 ] ] ]
ed689761e18c63adc8550e9f96d0b13dea30b649
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/open.hpp
1b697a7bd18ee5e145566ad1e056efc8abf6cdee
[]
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,369
hpp
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_OPEN_HPP_INCLUDED #define LUABIND_OPEN_HPP_INCLUDED #include <luabind/config.hpp> namespace luabind { LUABIND_API void open( lua_State* L ); } #endif // LUABIND_OPEN_HPP_INCLUDED
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 37 ] ] ]
cb689d15542214a63525e516a508d56c1edac95f
45c0d7927220c0607531d6a0d7ce49e6399c8785
/GlobeFactory/src/useful/launch_options_loader.hh
9a3145607a3ac4cacae738075e69539c4c8e3c45
[]
no_license
wavs/pfe-2011-scia
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
refs/heads/master
2021-01-25T07:08:36.552423
2011-01-17T20:23:43
2011-01-17T20:23:43
39,025,134
0
0
null
null
null
null
UTF-8
C++
false
false
2,489
hh
//////////////////////////////////////////////////////////////////////////////// // Filename : launch_options_loader.hh // Authors : Creteur Clement // Last edit : 02/10/09 - 19h34 // Comment : Singleton to help to read the arguments given to the software. //////////////////////////////////////////////////////////////////////////////// #ifndef USEFUL_LAUNCH_OPTIONS_LOADER_HH #define USEFUL_LAUNCH_OPTIONS_LOADER_HH #include <sstream> #include <string> #include <map> #include <vector> #include "singleton.hh" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ enum ELaunchOption { LOPT_FULLSCREEN = 0, LOPT_RESOLUTION = 1, LOPT_DEBUG = 2, LOPT_COUNT = 3 }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ const std::string LaunchOptionStr[] = { "-fullscreen", "-resolution", "-debug", }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ class LaunchOptionsLoader : public Singleton<LaunchOptionsLoader> { friend class Singleton<LaunchOptionsLoader>; public: void Initialize(int argc, char* argv[]); bool HasOption(ELaunchOption parOpt) const; bool HasOptionParam(ELaunchOption parOpt, unsigned parIth) const; bool HasOptionParamInteger(ELaunchOption parOpt, unsigned parIth) const; const std::string& GetParam(ELaunchOption parOpt, unsigned parIth) const; int GetParamInteger(ELaunchOption parOpt, unsigned parIth) const; private: LaunchOptionsLoader(); ~LaunchOptionsLoader(); void Parse(); ELaunchOption StrToEnum(const std::string& parStr); struct TParam { TParam(const std::string& parStr) : string(parStr), integer(0), isInteger(false) { } std::string string; int integer; bool isInteger; }; std::vector<std::string> MArgs; std::map<ELaunchOption, std::vector<TParam> > MOptions; int MCurArg; }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #endif
[ "creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc" ]
[ [ [ 1, 83 ] ] ]
8db81df4d67baba3bb0fa75b1bcc6a2f1659bcc8
9756190964e5121271a44aba29a5649b6f95f506
/SimpleParam/Param/src/MainWindow/CrossParameter.h
7424c0903327d2d615eb6a797369db9365a2e03c
[]
no_license
feengg/Parameterization
40f71bedd1adc7d2ccbbc45cc0c3bf0e1d0b1103
f8d2f26ff83d6f53ac8a6abb4c38d9b59db1d507
refs/heads/master
2020-03-23T05:18:25.675256
2011-01-21T15:19:08
2011-01-21T15:19:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
398
h
#ifndef CROSSPARAMETER_H_ #define CROSSPARAMETER_H_ //#include "../Param/CrossParam.h" #include "../Param/QuadParameter.h" class CrossParamWrapper { public: CrossParamWrapper(); ~CrossParamWrapper(); void ComputeUnitedDistortion(); public: //PARAM::QuadParameter m_param_1; //PARAM::QuadParameter m_param_2; private: //PARAM::CrossParam m_cross_param; }; #endif
[ [ [ 1, 24 ] ] ]
928b02747776ee4104b861d50f46335c1d25753b
845083c2ab45d9f913bba4aed7d76944acbe0eee
/Source/SADStepProgram/GraphicsTimer.cc
9ef1b177a3011981ca6fa7a5e9e29fe5940d1469
[]
no_license
smaudet/sadstep
8fdb51229b6415fab06528e0063c6a821141b137
7854693083f6cd31f6a26c738d0c054d9af5161e
refs/heads/master
2020-06-04T21:22:12.444714
2010-11-06T20:26:21
2010-11-06T20:26:21
32,900,819
0
0
null
null
null
null
UTF-8
C++
false
false
127
cc
#include "GraphicsTimer.h" GraphicsTimer::GraphicsTimer(int interval, int offset) { setInterval(interval-offset); }
[ "smaudet2@da972e84-c3cd-11de-84d4-09c59dc0309f" ]
[ [ [ 1, 6 ] ] ]
d06ca4494e975083196ea3b026efc649a5ba7e8b
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/completed/Cards.cpp
96c136ff1bcc1283371f746973d36b0bc8289178
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
3,269
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "Cards.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() class Cards { public: vector <string> deal(int nP, string deck) { vector <string> ret(nP); int n=(int)deck.size(); if(n==0 || (nP>n)){ return ret; } for(int j=0;j<(int)(n-n%nP);++j){ ret[j%nP] += deck[j]; } return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arg0 = 6; string Arg1 = "012345012345012345"; string Arr2[] = {"000", "111", "222", "333", "444", "555" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, deal(Arg0, Arg1)); } void test_case_1() { int Arg0 = 4; string Arg1 = "111122223333"; string Arr2[] = {"123", "123", "123", "123" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, deal(Arg0, Arg1)); } void test_case_2() { int Arg0 = 1; string Arg1 = "012345012345012345"; string Arr2[] = {"012345012345012345" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, deal(Arg0, Arg1)); } void test_case_3() { int Arg0 = 6; string Arg1 = "01234"; string Arr2[] = {"", "", "", "", "", "" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, deal(Arg0, Arg1)); } void test_case_4() { int Arg0 = 2; string Arg1 = ""; string Arr2[] = {"", "" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, deal(Arg0, Arg1)); } void test_case_5() { int Arg0 = 6; string Arg1 = "01234501234501234"; string Arr2[] = {"00", "11", "22", "33", "44", "55" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(5, Arg2, deal(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Cards ___test; ___test.run_test(-1); } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 69 ] ] ]
0513905838aa302962c00ad1718a4933843b373e
59166d9d1eea9b034ac331d9c5590362ab942a8f
/Forest/xmlRoot/xmlBranch/xmlBranchSave.h
004be0118c1b124198d0c79338410921820cb5bc
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
617
h
#ifndef _XML_BRANCH_SAVE_H_ #define _XML_BRANCH_SAVE_H_ #include "../../binData/dataBranch.h" #include "../../tinyXML/tinyxml.h" class xmlBranchSave { public: xmlBranchSave(); ~xmlBranchSave(); //получить xml тег с сформированными данными TiXmlElement* GetXmlData(); private: //заполнить данными о координатах void FillVertex( const dataBranch &_data , TiXmlElement* root ); //заполнить индексами void FillIndexes( const dataBranch &_data , TiXmlElement* root ); }; #endif //_XML_BRANCH_SAVE_H_
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 26 ] ] ]
d26479a150ab8e3acaa98e94fd8a749665c3c964
f177993b13e97f9fecfc0e751602153824dfef7e
/ImProSln/MyLib/ARCalibDS.h
870fcc3ea46d822961cca548a93b27b09eaa7242
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
2,151
h
#pragma once #include "DSBaseClass.h" #include "CameraDS.h" #include <InitGuid.h> #include "IARLayoutFilter.h" #include "IDXRenderer.h" #include "IHomoWarpFilter.h" #include "IARTagFilter.h" #include "IProjectSettingFilter.h" class DSBASECLASSES_API ARCalibDS : public CCameraDS { public: // ARLayout -> Warp -> Render // Cam -> Warp -> ARTag -> Render CComPtr<IBaseFilter> m_pARLayoutFilter; CComPtr<IARLayoutDXFilter> m_pIARLayoutFilter; CComPtr<IPin> m_pARLayoutOutputPin; CComPtr<IBaseFilter> m_pDXCamRenderFilter; CComPtr<IDXRenderer> m_pIDXCamRenderFilter; CComPtr<IPin> m_pDXCamRenderInputPin; CComPtr<IBaseFilter> m_pDXARRenderFilter; CComPtr<IDXRenderer> m_pIDXARRenderFilter; CComPtr<IPin> m_pDXARRenderInputPin; CComPtr<IBaseFilter> m_pCamFilter; CComPtr<IPin> m_pCamOutputPin; CComPtr<IBaseFilter> m_pCamWarpFilter; CComPtr<IHomoWarpFilter> m_pICamWarpFilter; CComPtr<IPin> m_pCamWarpInputPin; CComPtr<IPin> m_pCamWarpOutputPin; CComPtr<IBaseFilter> m_pARWarpFilter; CComPtr<IHomoWarpFilter> m_pIARWarpFilter; CComPtr<IPin> m_pARWarpInputPin; CComPtr<IPin> m_pARWarpOutputPin; CComPtr<IBaseFilter> m_pARTagFilter; CComPtr<IARTagFilter> m_pIARTagFilter; CComPtr<IPin> m_pARTagInputPin; CComPtr<IPin> m_pARTagOutputPin; CComPtr<IBaseFilter> m_pProjSetFilter; CComPtr<IProjectSettingFilter> m_pIProjSetFilter ; //overwrite CCameraDS function virtual HRESULT ConnectGraph(); virtual HRESULT CreateFilters(int nCamID, bool bDisplayProperties, int nWidth, int nHeight); virtual HRESULT ConfigFilters(); public: virtual void CloseCamera(); virtual HRESULT ShowDXCamRenderProp(); virtual HRESULT ShowDXARRenderProp(); virtual HRESULT ShowARProp(); virtual HRESULT ShowARWarpProp(); virtual HRESULT ShowCamWarpProp(); virtual HRESULT ShowCamProp(); virtual HRESULT ShowCamPinProp(); virtual HRESULT ShowARTagProp() ; virtual HRESULT ShowProjSetProp() ; public: ARCalibDS(void); virtual ~ARCalibDS(void); virtual BOOL SetARCallback(IARTagFilter::CallbackFuncPtr pcallback, int argc, void* argv[]); };
[ "claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 77 ] ] ]
3b53ec4541f52a18b11c96dadcb7dda039378eaf
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleEmitters/ParticleUniverseCircleEmitter.h
6ed8977781efeacb181848a52c90bdbf4ecfe2fb
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,564
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_CIRCLE_EMITTER_H__ #define __PU_CIRCLE_EMITTER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseSystem.h" #include "ParticleUniverseEmitter.h" namespace ParticleUniverse { /** The CircleEmitter is a ParticleEmitter that emits particles on a circle shape. Particle can be emitted random on the circle, but it can also follow the circles' contours. */ class _ParticleUniverseExport CircleEmitter : public ParticleEmitter { protected: Ogre::Real mRadius; Ogre::Real mCircleAngle; Ogre::Real mOriginalCircleAngle; Ogre::Real mStep; Ogre::Real mX; Ogre::Real mZ; bool mRandom; Ogre::Quaternion mOrientation; Ogre::Vector3 mNormal; public: // Constants static const Ogre::Real DEFAULT_RADIUS; static const Ogre::Real DEFAULT_STEP; static const Ogre::Real DEFAULT_ANGLE; static const bool DEFAULT_RANDOM; static const Ogre::Vector3 DEFAULT_NORMAL; CircleEmitter(void); virtual ~CircleEmitter(void) {}; /** */ const Ogre::Real getRadius(void) const; void setRadius(const Ogre::Real radius); /** */ const Ogre::Real getCircleAngle(void) const; void setCircleAngle(const Ogre::Real circleAngle); /** */ const Ogre::Real getStep(void) const; void setStep(const Ogre::Real step); /** */ const bool isRandom(void) const; void setRandom(const bool random); /* */ const Ogre::Quaternion& getOrientation(void) const; const Ogre::Vector3& getNormal(void) const; void setNormal(const Ogre::Vector3 &normal); /** See ParticleEmiter */ void _notifyStart(void); /** Determine a particle position on the circle. */ virtual void _initParticlePosition(Particle* particle); /** Determine the particle direction. */ virtual void _initParticleDirection(Particle* particle); /** */ virtual void copyAttributesTo (ParticleEmitter* emitter); }; } #endif
[ [ [ 1, 92 ] ] ]
9f9c97184c43547b63a18f921e34142fcec7cfc9
4b30b09448549ffbe73c2346447e249713c1a463
/Sources/cgi_admin/cgi_admin.cpp
9abb41b6df51771445123062cf05ab94a9c28e1f
[]
no_license
dblock/agnes
551fba6af6fcccfe863a1a36aad9fb066a2eaeae
3b3608eba8e7ee6a731f0d5a3191eceb0c012dd5
refs/heads/master
2023-09-05T22:32:10.661399
2009-10-29T11:23:28
2009-10-29T11:23:28
1,998,777
1
1
null
null
null
null
UTF-8
C++
false
false
3,490
cpp
#include <agnespch.hpp> cgi_admin_manager * current_cgi_admin_manager = 0; void output_current_admins(cgiOutStream& CGIStream){ if (current_cgi_admin_manager) current_cgi_admin_manager->output_admins(CGIStream); else { current_cgi_admin_manager = new cgi_admin_manager(); current_cgi_admin_manager->output_admins(CGIStream); } } cgi_admin_manager::cgi_admin_manager(void){ current_cgi_admin_manager = this; fill_admin(); } cgi_admin_manager::~cgi_admin_manager(void){ if (current_cgi_admin_manager == this) current_cgi_admin_manager = 0; } int cgi_admin_manager::admin(const CString& class_name, const CString& category){ if (!(entry_manager::get_value(category, class_name).StrLength())) return 0; else return 1; } void cgi_admin_manager::output_admins(cgiOutStream& CGIStream){ CGIStream << hr_ << "retreiving administration equivalence structures:" << hr_; for (int i=0;i<entry_manager::class_count();i++){ CGIStream << entry_manager::get_class(i); for (int j=0;j<entry_manager::class_count(i);j++) { CGIStream << " : " << entry_manager::get_name(i, j); } CGIStream << elf; } } void cgi_admin_manager::add_admin(const CString& class_, const CString& category){ if (class_.StrLength()&&(class_[0]!='#')) { CVector<CString> Tokens; category.Tokenizer('+',Tokens); for (int i=0;i<Tokens.Count();i++){ entry_manager::add_value(Tokens[i], class_, Tokens[i]); } } } void cgi_admin_manager::fill_admin(void){ equiv_file = entry_manager::make_equiv_path("admin.struct"); nextgen_v2 hfile(equiv_file); CVector<CString> Tokens; CString s; while (!hfile.feofc()) { s = hfile.read_line(); s.StrTrim32(); s.Tokenizer(',', Tokens); if (Tokens.Count() == 2) add_admin(Tokens[0], Tokens[1]); } } int cgi_admin_manager::write_full_admin(const CString& AdminClass, const CString& Equiv){ if ((!AdminClass.StrLength())||(!Equiv.StrLength())) return 0; if (!equiv_file.StrLength()) { current_cgi_admin_manager = this; equiv_file = entry_manager::make_equiv_path("admin.struct"); } #ifndef ANSI chmod(equiv_file.asString(), _S_IREAD | _S_IWRITE); #endif int hfile2 = v_open(equiv_file.asString(), O_WRONLY | O_APPEND | O_CREAT, S_IRWXU); if (hfile2 == -1) { perror("<br>Error writing admin.struct:"); return 0; } write(hfile2, AdminClass.asString(), AdminClass.StrLength()); write(hfile2, ",", strlen(",")); write(hfile2, Equiv.asString(), Equiv.StrLength()); write(hfile2, "\n", strlen("\n")); close(hfile2); return 1; } int cgi_admin_manager::cgi_admin_write(void){ return cgi_admin_write(entry_manager::make_equiv_path("admin.struct")); } int cgi_admin_manager::cgi_admin_write(const CString& container){ #ifndef ANSI chmod(equiv_file.asString(), _S_IREAD | _S_IWRITE); #endif int hfile2 = v_open(container.asString(), O_WRONLY | O_TRUNC | O_CREAT, S_IRWXU); if (hfile2 == -1) { perror("<br>Error writing admin.struct:"); return 0; } for (int i=0;i<entry_manager::class_count();i++){ for (int j=0;j<entry_manager::class_count(i);j++) { write(hfile2, entry_manager::get_name(i, j).asString(), entry_manager::get_name(i, j).StrLength()); write(hfile2, ",", strlen(",")); write(hfile2, entry_manager::get_class(i).asString(), entry_manager::get_class(i).StrLength()); write(hfile2, "\n", strlen("\n")); } } close(hfile2); return 1; }
[ [ [ 1, 117 ] ] ]
8fa40b07fd8546fb6bbb63477c665ab22d78fef3
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestsearchfield/src/bctestsearchfieldapp.cpp
21795bd6af3c7411855b206ff17ae7fea60a8ca4
[]
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
1,994
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: Implement BC test searchfield application * */ #include <eikstart.h> #include "bctestsearchfieldapp.h" #include "bctestsearchfielddocument.h" // ================= MEMBER FUNCTIONS ========================================= // ---------------------------------------------------------------------------- // TUid CBCTestSearchFieldApp::AppDllUid() // Returns application UID. // ---------------------------------------------------------------------------- // TUid CBCTestSearchFieldApp::AppDllUid() const { return KUidBCTestSearchField; } // ---------------------------------------------------------------------------- // CApaDocument* CBCTestSearchFieldApp::CreateDocumentL() // Creates CBCTestSearchFieldDocument object. // ---------------------------------------------------------------------------- // CApaDocument* CBCTestSearchFieldApp::CreateDocumentL() { return CBCTestSearchFieldDocument::NewL( *this ); } // ================= OTHER EXPORTED FUNCTIONS ================================= // // ---------------------------------------------------------------------------- // CApaApplication* NewApplication() // Constructs CBCTestSearchFieldApp. // Returns: CApaDocument*: created application object // ---------------------------------------------------------------------------- // LOCAL_C CApaApplication* NewApplication() { return new CBCTestSearchFieldApp; } GLDEF_C TInt E32Main() { return EikStart::RunApplication(NewApplication); }
[ "none@none" ]
[ [ [ 1, 63 ] ] ]
8c8daf5913eb56b903a935595be894d54e7d1d68
6caf1a340711c6c818efc7075cc953b2f1387c04
/client/DlgWait.h
2bb5fcc8cc9521de1cddcedb8adb07c62802dff4
[]
no_license
lbrucher/timelis
35c68061bea68cc31ce1c68e3adbc23cb7f930b1
0fa9f8f5ef28fe02ca620c441783a1ff3fc17bde
refs/heads/master
2021-01-01T18:18:37.988944
2011-08-18T19:39:19
2011-08-18T19:39:19
2,229,915
2
1
null
null
null
null
UTF-8
C++
false
false
1,185
h
#if !defined(AFX_DLGWAIT_H__D9DD794C_934D_4B43_9A2D_82FAC07546A8__INCLUDED_) #define AFX_DLGWAIT_H__D9DD794C_934D_4B43_9A2D_82FAC07546A8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DlgWait.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDlgWait dialog class CDlgWait : public CDialog { // Construction public: CDlgWait(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDlgWait) enum { IDD = IDD_WAIT }; CString m_sMessage; //}}AFX_DATA CString m_sTitle; // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDlgWait) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDlgWait) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGWAIT_H__D9DD794C_934D_4B43_9A2D_82FAC07546A8__INCLUDED_)
[ [ [ 1, 47 ] ] ]
9c09478b0db9f502a58221e5bb4be2350a79caa7
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Utilities/Collide/Filter/GroupFilter/hkpGroupFilterUtil.h
2124c568bb25bf11b2675e414e5396151654651a
[]
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
2,355
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_UTILS_GROUP_FILTER_UTIL_H #define HK_UTILS_GROUP_FILTER_UTIL_H #include <Common/Base/hkBase.h> /// A collection of helper utilities for setting up the group filter class hkpGroupFilterUtil { public: /// This utility class helps setting up hkpCollidable::m_collisionFilterInfo for the group filter. /// The purpose is to disable collisions between object pairs which are connected by a constraint. /// This class only works if all the rigid bodies and constraints /// can be organized in a hierarchy and the input constraints are sorted /// so that the root bodies come first. /// \param groupFilterSystemGroup is a unique identifier for this constraint system you can get by /// calling hkpGroupFilter::getNewSystemGroup(). This system group will by applied to the m_collisionFilterInfo /// of all involved bodies. If the bodies already have a system group assigned to, this function will assert. static void HK_CALL disableCollisionsBetweenConstraintBodies( const class hkpConstraintInstance*const* constraints, int numConstraints, int groupFilterSystemGroup ); }; #endif // HK_UTILS_GROUP_FILTER_UTIL_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, 46 ] ] ]
b42aa3209a6656060f5d977291b8b53b2c466e53
7ccf42cf95c94b3d18766451d5641c55cb37bc30
/src/serializer.h
6eff8c0b531f9588e2fe3cd5c339221ce2e6a99d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yoshin4444/bjne
4b8846e69bb4b6735091296489183996fa80a844
d00e1e401a31e3f716453b267e531199071f63d6
refs/heads/master
2021-01-22T19:54:34.318633
2010-03-14T23:20:53
2010-03-14T23:20:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,666
h
#ifndef _SERIALIZER_H #define _SERIALIZER_H #include "types.h" #include <map> #include <vector> #include <fstream> #include <iostream> using namespace std; class chunk{ friend class state_data; public: enum mode{ READ,WRITE }; chunk(){ cur_mode=WRITE; read_pos=0; } ~chunk(){ } void set_mode(mode m) { cur_mode=m; } template <class T> chunk &operator<<(T &dat){ if (cur_mode==READ) read(dat); else write(dat); return *this; } template <class T> chunk &operator<<(const T &dat){ if (cur_mode==READ) throw "invalid operation"; else write(dat); return *this; } private: void load(ifstream &is){ u32 size=(u8)is.get(); size|=((u8)is.get())<<8; size|=((u8)is.get())<<16; size|=((u8)is.get())<<24; dat.resize(size); for (int i=0;i<size;i++) dat[i]=(u8)is.get(); } void save(ofstream &os){ u32 size=dat.size(); os.put((u8)size); os.put((u8)(size>>8)); os.put((u8)(size>>16)); os.put((u8)(size>>24)); for (int i=0;i<size;i++) os.put(dat[i]); } void write(const bool &d){ dat.push_back(d?1:0); } void write(const u8 &d){ dat.push_back(d); } void write(const u16 &d){ dat.push_back((u8)d); dat.push_back((u8)(d>>8)); } void write(const u32 &d){ dat.push_back((u8)d); dat.push_back((u8)(d>>8)); dat.push_back((u8)(d>>16)); dat.push_back((u8)(d>>24)); } void write(const s64 &d){ dat.push_back((u8)d); dat.push_back((u8)(d>>8)); dat.push_back((u8)(d>>16)); dat.push_back((u8)(d>>24)); dat.push_back((u8)(d>>32)); dat.push_back((u8)(d>>40)); dat.push_back((u8)(d>>48)); dat.push_back((u8)(d>>56)); } void write(const int &d) { write((const u32&)d); } void read(bool &d){ d=readb()!=0; } void read(u8 &d){ d=readb(); } void read(u16 &d){ d=readb(); d|=readb()<<8; } void read(u32 &d){ d=readb(); d|=readb()<<8; d|=readb()<<16; d|=readb()<<24; } void read(s64 &d){ d=readb(); d|=(u64)(readb())<<8; d|=(u64)(readb())<<16; d|=(u64)(readb())<<24; d|=(u64)(readb())<<32; d|=(u64)(readb())<<40; d|=(u64)(readb())<<48; d|=(u64)(readb())<<56; } void read(int &d) { read((u32&)d); } u8 readb(){ if (read_pos>=dat.size()) throw "out of bound"; return dat[read_pos++]; } vector<u8> dat; mode cur_mode; int read_pos; }; class state_data{ public: state_data(ifstream &is){ load(is); set_mode(chunk::READ); } state_data(){ } ~state_data(){ } void set_mode(chunk::mode m){ for (map<string,chunk>::iterator p=dat.begin(); p!=dat.end();p++) p->second.set_mode(m); } bool is_reading(){ return !(dat.empty()||dat.begin()->second.cur_mode==chunk::WRITE); } #define FILE_SIG "bjne save data 1.0.0" void load(ifstream &is){ string sig=read_str(is); if (sig!=FILE_SIG) throw "invalid signature"; for (;;){ string tag=read_str(is); if (tag=="") break; dat[tag].load(is); } } void save(ofstream &os){ os<<FILE_SIG<<'\0'; for (map<string,chunk>::iterator p=dat.begin(); p!=dat.end();p++){ os<<p->first<<'\0'; p->second.save(os); } } chunk &operator[](const string &s){ return dat[s]; } private: string read_str(ifstream &is){ string ret; char c; while(is.get(c)&&c!='\0') ret+=c; return ret; } map<string,chunk> dat; }; #endif
[ [ [ 1, 180 ] ] ]
6923aed6454b0d384ba23565563f6cc4762a12a7
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Framework/PreethamScatter.cpp
43b5e1864c687d35866851aecc397164005c71ed
[]
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
15,086
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: PreethamScatter.cpp Version: 0.05 --------------------------------------------------------------------------- */ #include "Material.h" #include "MaterialLibrary.h" #include "MaterialManager.h" #include "Maths.h" #include "PreethamScatter.h" #if _MSC_VER < 1500 #include "omp.h" #endif namespace nGENE { namespace Nature { // Initialize static members const double PreethamScatter::s_xDC[5][2] = { { -0.0193, -0.2592 }, { -0.0665, 0.0008 }, { -0.0004, 0.2125 }, { -0.0641, -0.8989 }, { -0.0033, 0.0452 } }; const double PreethamScatter::s_yDC[5][2] = { { -0.0167, -0.2608 }, { -0.0950, 0.0092 }, { -0.0079, 0.2102 }, { -0.0441, -1.6537 }, { -0.0109, 0.0529 } }; const double PreethamScatter::s_YDC[5][2] = { { 0.1787, -1.4630 }, { -0.3554, 0.4275 }, { -0.0227, 5.3251 }, { 0.1206, -2.5771 }, { -0.0670, 0.3703 } }; const double PreethamScatter::s_xZC[3][4] = { { 0.00166, -0.00375, 0.00209, 0.00000 }, { -0.02903, 0.06377, -0.03203, 0.00394 }, { 0.11693, -0.21196, 0.06052, 0.25886 } }; const double PreethamScatter::s_yZC[3][4] = { { 0.00275, -0.00610, 0.00317, 0.00000 }, { -0.04214, 0.08970, -0.04153, 0.00516 }, { 0.15346, -0.26756, 0.06670, 0.26688 } }; const double PreethamScatter::s_CIE_300_800[107][3] = { #include "Scattering/ciexyz31_300_800.table" }; const double PreethamScatter::s_CIE_350_800[97][3] = { #include "Scattering/ciexyz31_350_800.table" }; const double PreethamScatter::s_neta[] = { #include "Scattering/neta.table" }; const double PreethamScatter::s_K[] = { #include "Scattering/K.table" }; const double PreethamScatter::s_N21[] = { #include "Scattering/N21.table" }; const double PreethamScatter::s_Ko[] = { #include "Scattering/Ko.table" }; const double PreethamScatter::s_Kg[] = { #include "Scattering/Kg.table" }; const double PreethamScatter::s_Kwa[] = { #include "Scattering/Kwa.table" }; const double PreethamScatter::s_sol[] = { #include "Scattering/Sol.table" }; const double PreethamScatter::s_V = 4.0; const double PreethamScatter::s_anisCor = 1.06; const double PreethamScatter::s_N = 2.545e25; const double PreethamScatter::s_dAlpha1 = 0.83331810215394e-3; const double PreethamScatter::s_dAlpha2 = 0.11360016092149e-3; PreethamScatter::PreethamScatter(): ThetaBins(5), PhiBins(5) { m_Sun.theta = -1.0f; m_Sun.phi = -1.0f; m_dSunSpectralRad = 0.25 * Maths::PI * 1.39 * 1.39 / (150.0 * 150.0); setTurbidity(2.0f); for(uint i = 0; i < 1801; ++i) { m_aNetaTable[i].set(static_cast<float>(s_neta[i * 3 + 0]), static_cast<float>(s_neta[i * 3 + 1]), static_cast<float>(s_neta[i * 3 + 2])); } m_fExposure = 0.1f; m_fInscatter = 0.007f; } //---------------------------------------------------------------------- PreethamScatter::~PreethamScatter() { } //---------------------------------------------------------------------- void PreethamScatter::setTurbidity(double _turbidity) { m_fTurbidity = _turbidity; m_Ax = s_xDC[0][0] * m_fTurbidity + s_xDC[0][1]; m_Bx = s_xDC[1][0] * m_fTurbidity + s_xDC[1][1]; m_Cx = s_xDC[2][0] * m_fTurbidity + s_xDC[2][1]; m_Dx = s_xDC[3][0] * m_fTurbidity + s_xDC[3][1]; m_Ex = s_xDC[4][0] * m_fTurbidity + s_xDC[4][1]; m_Ay = s_yDC[0][0] * m_fTurbidity + s_yDC[0][1]; m_By = s_yDC[1][0] * m_fTurbidity + s_yDC[1][1]; m_Cy = s_yDC[2][0] * m_fTurbidity + s_yDC[2][1]; m_Dy = s_yDC[3][0] * m_fTurbidity + s_yDC[3][1]; m_Ey = s_yDC[4][0] * m_fTurbidity + s_yDC[4][1]; m_AY = s_YDC[0][0] * m_fTurbidity + s_YDC[0][1]; m_BY = s_YDC[1][0] * m_fTurbidity + s_YDC[1][1]; m_CY = s_YDC[2][0] * m_fTurbidity + s_YDC[2][1]; m_DY = s_YDC[3][0] * m_fTurbidity + s_YDC[3][1]; m_EY = s_YDC[4][0] * m_fTurbidity + s_YDC[4][1]; // Calculate Mie and Rayleigh scattering coefficients double b_m[101], b_p[101]; double b_m_ang_prefix[101]; double b_p_ang_prefix[101]; double c = (0.06544204545455 * m_fTurbidity - 0.06509886363636) * 1e-15; m_vecRayleighFactor.set(0.0f, 0.0f, 0.0f); m_vecMieFactor.set(0.0f, 0.0f, 0.0f); m_vecRayleighFactorAng.set(0.0f, 0.0f, 0.0f); m_vecMieFactorAng.set(0.0f, 0.0f, 0.0f); double lambda = 0.0f; int i = 0; for(lambda = 300.0, i = 0; lambda <= 800.0; lambda += 5.0, ++i) { double lambdasi = lambda * 1e-9; double Nlambda4 = s_N * lambdasi * lambdasi * lambdasi * lambdasi; double n2_1 = s_N21[i]; double K = s_K[i]; b_m[i] = 8.0 * Maths::PI * Maths::PI * Maths::PI * n2_1 * s_anisCor / (3.0 * Nlambda4); b_p[i] = 0.434 * Maths::PI * c * pow(2.0 * Maths::PI / lambdasi, s_V - 2.0) * K * pow(0.01, s_V - 3.0); b_m_ang_prefix[i] = 2.0 * Maths::PI * Maths::PI * n2_1 * s_anisCor * 0.7629 / (3.0 * Nlambda4); b_p_ang_prefix[i] = 0.217 * c * pow(2.0 * Maths::PI / lambdasi, s_V - 2.0) * pow(0.01,s_V - 3.0); // Convert spectral curves to CIE XYZ m_vecRayleighFactor.x += static_cast<double>(b_m[i] * s_CIE_300_800[i][0]); m_vecRayleighFactor.y += static_cast<double>(b_m[i] * s_CIE_300_800[i][1]); m_vecRayleighFactor.z += static_cast<double>(b_m[i] * s_CIE_300_800[i][2]); m_vecMieFactor.x += static_cast<double>(b_p[i] * s_CIE_300_800[i][0]); m_vecMieFactor.y += static_cast<double>(b_p[i] * s_CIE_300_800[i][1]); m_vecMieFactor.z += static_cast<double>(b_p[i] * s_CIE_300_800[i][2]); m_vecRayleighFactorAng.x += static_cast<double>(b_m_ang_prefix[i] * s_CIE_300_800[i][0]); m_vecRayleighFactorAng.y += static_cast<double>(b_m_ang_prefix[i] * s_CIE_300_800[i][1]); m_vecRayleighFactorAng.z += static_cast<double>(b_m_ang_prefix[i] * s_CIE_300_800[i][2]); m_vecMieFactorAng.x += static_cast<double>(b_p_ang_prefix[i] * s_CIE_300_800[i][0]); m_vecMieFactorAng.y += static_cast<double>(b_p_ang_prefix[i] * s_CIE_300_800[i][1]); m_vecMieFactorAng.z += static_cast<double>(b_p_ang_prefix[i] * s_CIE_300_800[i][2]); } computeAttenuatedSunlight(); } //---------------------------------------------------------------------- double PreethamScatter::computeChromaticity(const double m[][4]) const { double T2 = m_fTurbidity * m_fTurbidity; double t2 = m_Sun.theta * m_Sun.theta; double t3 = t2 * m_Sun.theta; return (T2 * m[0][0] + m_fTurbidity * m[1][0] + m[2][0]) * t3 + (T2 * m[0][1] + m_fTurbidity * m[1][1] + m[2][1]) * t2 + (T2 * m[0][2] + m_fTurbidity * m[1][2] + m[2][2]) * m_Sun.theta + (T2 * m[0][3] + m_fTurbidity * m[1][3] + m[2][3]); } //---------------------------------------------------------------------- double PreethamScatter::perezFunction(const double _A, const double _B, const double _C, const double _D, const double _E, const double _theta, const double _gamma) const { double e0 = _B / cos(_theta); double e1 = _D * _gamma; double e2 = cos(_gamma); e2 *= e2; double f1 = (1 + _A * exp(e0)) * (1 + _C * exp(e1) + _E * e2); e0 = _B; e1 = _D * m_Sun.theta; e2 = cos(m_Sun.theta); e2 *= e2; double f2 = (1 + _A * exp( e0 )) * (1 + _C * exp(e1) + _E * e2); return f1 / f2; } //---------------------------------------------------------------------- void PreethamScatter::computeAttenuatedSunlight() { double data[91]; double beta = 0.04608365822050 * m_fTurbidity - 0.04586025928522; double m = 1.0 / (cos(m_Sun.theta) + 0.15 * pow(93.885 - Maths::radToDeg(m_Sun.theta), -1.253)); double lambda; m_vecSunSpectralRad.set(0.0f, 0.0f, 0.0f); uint i = 0; for(i = 0, lambda = 350.0; i < 91; ++i, lambda += 5.0) { double tauR = exp(-m * 0.008735 * pow(lambda / 1000.0, -4.08)); double alpha = 1.3; double tauA = exp(-m * beta * pow(lambda / 1000.0, -alpha)); double ozone = 0.35; double tauO = exp(-m * s_Ko[i] * ozone); double tauG = exp(-1.41 * s_Kg[i] * m / pow( 1.0 + 118.93 * s_Kg[i] * m, 0.45)); double w = 2.0; double tauWA = exp(-0.2385 * s_Kwa[i] * w * m / pow(1.0 + 20.07 * s_Kwa[i] * w * m, 0.45)); data[i] = 100.0 * s_sol[i] * tauR * tauA * tauO * tauG * tauWA; // 100 comes from solCurve being in wrong units. // Convert spectral curve to CIE XYZ m_vecSunSpectralRad.x += static_cast<float>(data[i] * s_CIE_350_800[i][0]); m_vecSunSpectralRad.y += static_cast<float>(data[i] * s_CIE_350_800[i][1]); m_vecSunSpectralRad.z += static_cast<float>(data[i] * s_CIE_350_800[i][2]); } } //---------------------------------------------------------------------- void PreethamScatter::setSunAngle(float _angle) { m_Sun.theta = acos(sin(_angle)); m_Sun.phi = atan2((double)0.0, (double)cos(_angle)); m_Sun.direction.set(cos(_angle), sin(_angle), 0.0f); updateSun(); } //---------------------------------------------------------------------- void PreethamScatter::updateSun() { // Calculate sun luminance and chromaticity values double dChi = (4.0 / 9.0 - m_fTurbidity / 120.0) * (Maths::PI - 2.0 * m_Sun.theta); m_YZenith = (4.0453 * m_fTurbidity - 4.9710) * tan( dChi ) - 0.2155 * m_fTurbidity + 2.4192; if(m_YZenith < 0.0) m_YZenith = -m_YZenith; m_xZenith = computeChromaticity(s_xZC); m_yZenith = computeChromaticity(s_yZC); computeAttenuatedSunlight(); double theta, phi; double delTheta = Maths::PI / ThetaBins; double delPhi = 2.0 * Maths::PI / PhiBins; uint i, j; for(i = 0, theta = 0; theta <= Maths::PI; theta += delTheta, ++i) { for(j = 0, phi = 0; phi <= Maths::PI_DOUBLE; phi+= delPhi, ++j) { computeS0(theta, phi, m_aS0Mie[i * (ThetaBins + 1) + j], m_aS0Rayleigh[i * (ThetaBins + 1) + j]); } } } //---------------------------------------------------------------------- void PreethamScatter::getNeta(const double _theta, const double _v, Vector3& _neta) const { double theta = Maths::radToDeg(_theta) * 10.0; double u = theta - (int)theta; if(theta < 0.0 || theta > 1801.0) { _neta.set(0.0f, 0.0f, 0.0f); return; } if(theta > 1800.0f) { _neta = m_aNetaTable[1800]; return; } _neta = (1.0f - (float)u) * m_aNetaTable[FastFloat::floatToInt(theta)] + (float)u * m_aNetaTable[FastFloat::floatToInt(theta) + 1]; } //---------------------------------------------------------------------- void PreethamScatter::computeS0(const double _thetav, const double _phiv, Vector3& _mie, Vector3& _ray) const { double phiDelta = Maths::PI / 20.0; double thetaDelta = Maths::PI / 2.0 / 20.0; double thetaUpper = Maths::PI / 2.0; double psi = 0.0f; Vector3 skyRad; Vector3 beta_ang_1, beta_ang_2; Vector3 neta; int countTheta = FastFloat::floatToInt(thetaUpper / thetaDelta); int countPhi = FastFloat::floatToInt(Maths::PI_DOUBLE / phiDelta); double theta = 0.0f; double phi = 0.0f; int i = 0; int j = 0; float skyAmb_1_x = 0.0f, skyAmb_1_y = 0.0f, skyAmb_1_z = 0.0f; float skyAmb_2_x = 0.0f, skyAmb_2_y = 0.0f, skyAmb_2_z = 0.0f; #pragma omp parallel for firstprivate(j) lastprivate(i) private(theta) private(phi) private(skyRad) private(beta_ang_1) private(beta_ang_2) private(neta) private(psi) reduction(+: skyAmb_1_x) reduction(+: skyAmb_1_y) reduction(+: skyAmb_1_z) reduction(+: skyAmb_2_x) reduction(+: skyAmb_2_y) reduction(+: skyAmb_2_z) for(i = 0; i < countTheta; ++i) { for(j = 0; j < countPhi; ++j) { theta = (double)i * thetaDelta; phi = (double)j * phiDelta; getSkySpectralRadiance(skyRad, theta, phi); psi = angleBetween(_thetav, _phiv, theta, phi); getNeta(psi, s_V, neta); beta_ang_1 = Vector3(m_vecMieFactorAng.x * neta.x, m_vecMieFactorAng.y * neta.y, m_vecMieFactorAng.z * neta.z); beta_ang_2 = m_vecRayleighFactorAng * static_cast<float>((1.0f + 0.9324f * cos(psi) * cos(psi))); Vector3 temp1(Vector3(skyRad.x * beta_ang_1.x, skyRad.y * beta_ang_1.y, skyRad.z * beta_ang_1.z) * static_cast<float>(sin(theta) * thetaDelta * phiDelta)); Vector3 temp2(Vector3(skyRad.x * beta_ang_2.x, skyRad.y * beta_ang_2.y, skyRad.z * beta_ang_2.z) * static_cast<float>(sin(theta) * thetaDelta * phiDelta)); skyAmb_1_x += temp1.x; skyAmb_1_y += temp1.y; skyAmb_1_z += temp1.z; skyAmb_2_x += temp2.x; skyAmb_2_y += temp2.y; skyAmb_2_z += temp2.z; } } Vector3 skyAmb_1(skyAmb_1_x, skyAmb_1_y, skyAmb_1_z); Vector3 skyAmb_2(skyAmb_2_x, skyAmb_2_y, skyAmb_2_z); psi = angleBetween(_thetav, _phiv, m_Sun.theta, m_Sun.phi); getNeta(psi, s_V, neta); beta_ang_1 = Vector3(m_vecMieFactorAng.x * neta.x, m_vecMieFactorAng.y * neta.y, m_vecMieFactorAng.z * neta.z); beta_ang_2 = m_vecRayleighFactorAng * static_cast<float>((1.0f + 0.9324f * cos(psi) * cos(psi))); Vector3 sunAmb_1 = Vector3(m_vecSunSpectralRad.x * beta_ang_1.x, m_vecSunSpectralRad.y * beta_ang_1.y, m_vecSunSpectralRad.z * beta_ang_1.z) * static_cast<float>(m_dSunSpectralRad); Vector3 sunAmb_2 = Vector3(m_vecSunSpectralRad.x * beta_ang_2.x, m_vecSunSpectralRad.y * beta_ang_2.y, m_vecSunSpectralRad.z * beta_ang_2.z) * static_cast<float>(m_dSunSpectralRad); _mie = sunAmb_1 + skyAmb_1; _ray = sunAmb_2 + skyAmb_2; } //---------------------------------------------------------------------- void PreethamScatter::getSkySpectralRadiance(Vector3& _color, const double _theta, const double _phi) const { double gamma = angleBetween(_theta, _phi, m_Sun.theta, m_Sun.phi); double x = 0.0f; double y = 0.0f; double Y = 0.0f; //#pragma omp parallel sections { //#pragma omp section x = m_xZenith * perezFunction(m_Ax, m_Bx, m_Cx, m_Dx, m_Ex, _theta, gamma); //#pragma omp section y = m_yZenith * perezFunction(m_Ay, m_By, m_Cy, m_Dy, m_Ey, _theta, gamma); //#pragma omp section Y = m_YZenith * perezFunction(m_AY, m_BY, m_CY, m_DY, m_EY, _theta, gamma); } double X = (x / y) * Y; double Z = ((1.0 - x - y) / y) * Y; _color.set(static_cast<float>(X), static_cast<float>(Y), static_cast<float>(Z)); } //---------------------------------------------------------------------- double PreethamScatter::angleBetween(const double& _thetav, const double& _phiv, const double& _theta, const double& _phi) const { double cospsi = sin(_thetav ) * sin(_theta ) * cos(_phi - _phiv) + cos(_thetav) * cos(_theta); if(cospsi > 1.0) return 0.0; if(cospsi < -1.0) return Maths::PI; return acos(cospsi); } //---------------------------------------------------------------------- } }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 459 ] ] ]
4418183bedd4c0d75aff2184e63a9bbe36b5f614
3128346a72b842c6dd94f2b854170d5daeeedc6f
/src/CoreTexture.cpp
4845da268abe041abb3f586b36b49c4a5ace6811
[]
no_license
Valrandir/Core512
42c3ed02f3f5455a9e0d722c014c80bb2bae17ab
af6b45aa2eded3f32964339ffebdab3491b08561
refs/heads/master
2021-01-22T04:57:15.719013
2011-11-11T05:16:30
2011-11-11T05:16:30
2,607,600
1
1
null
null
null
null
UTF-8
C++
false
false
679
cpp
#include "CoreDefs.h" #include "CoreErrExit.h" #include "CoreTexture.h" CoreTexture::CoreTexture(const char* ResPath) : Width(w), Height(h), WidthF(wf), HeightF(hf), TextureHandle(hTexture) { Stackit; TryH(hTexture = CoreSys.Hge->Texture_Load(ResPath)); w = CoreSys.Hge->Texture_GetWidth(hTexture); h = CoreSys.Hge->Texture_GetHeight(hTexture); wf = (float)w; hf = (float)h; } CoreTexture::~CoreTexture() { if(hTexture) CoreSys.Hge->Texture_Free(hTexture); } void CoreTexture::UseOriginalSize() { w = CoreSys.Hge->Texture_GetWidth(hTexture, true); h = CoreSys.Hge->Texture_GetHeight(hTexture, true); wf = (float)w; hf = (float)h; }
[ [ [ 1, 29 ] ] ]
55888246eb31d7866bb37cacfa51ae4653feafd3
04fec4cbb69789d44717aace6c8c5490f2cdfa47
/include/Poco/Data/BulkExtraction.h
f9a3644bfe795d2d78f3c3bec73629fa4dacec1f
[]
no_license
aaryanapps/whiteTiger
04f39b00946376c273bcbd323414f0a0b675d49d
65ed8ffd530f20198280b8a9ea79cb22a6a47acd
refs/heads/master
2021-01-17T12:07:15.264788
2010-10-11T20:20:26
2010-10-11T20:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,393
h
// // BulkExtraction.h // // $Id: //poco/Main/Data/include/Poco/Data/BulkExtraction.h#9 $ // // Library: Data // Package: DataCore // Module: BulkExtraction // // Definition of the BulkExtraction class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_BulkExtraction_INCLUDED #define Data_BulkExtraction_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractExtraction.h" #include "Poco/Data/Bulk.h" #include "Poco/Data/Prepare.h" #include <vector> namespace Poco { namespace Data { template <class C> class BulkExtraction: public AbstractExtraction /// Specialization for bulk extraction of values from a query result set. /// Bulk extraction support is provided only for following STL containers: /// - std::vector /// - std::deque /// - std::list { public: typedef typename C::value_type T; BulkExtraction(C& result, Poco::UInt32 limit, const Position& pos = Position(0)): AbstractExtraction(limit, pos.value(), true), _rResult(result), _default() { if (static_cast<Poco::UInt32>(result.size()) != limit) result.resize(limit); } BulkExtraction(C& result, const T& def, Poco::UInt32 limit, const Position& pos = Position(0)): AbstractExtraction(limit, pos.value(), true), _rResult(result), _default(def) { if (static_cast<Poco::UInt32>(result.size()) != limit) result.resize(limit); } virtual ~BulkExtraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler<C>::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } bool isNull(std::size_t row) const { try { return _nulls.at(row); }catch (std::out_of_range& ex) { throw RangeException(ex.what()); } } std::size_t extract(std::size_t col) { AbstractExtractor* pExt = getExtractor(); TypeHandler<C>::extract(col, _rResult, _default, pExt); typename C::iterator it = _rResult.begin(); typename C::iterator end = _rResult.end(); for (int row = 0; it !=end; ++it, ++row) _nulls.push_back(pExt->isNull(col, row)); return _rResult.size(); } virtual void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t col) { Poco::UInt32 limit = getLimit(); if (limit != _rResult.size()) _rResult.resize(limit); pPrep->setLength(limit); pPrep->setBulk(true); return new Prepare<C>(pPrep, col, _rResult); } protected: const C& result() const { return _rResult; } private: C& _rResult; T _default; std::deque<bool> _nulls; }; template <class C> class InternalBulkExtraction: public BulkExtraction<C> /// Container Data Type specialization extension for extraction of values from a query result set. /// /// This class is intended for PocoData internal use - it is used by StatementImpl /// to automaticaly create internal BulkExtraction in cases when statement returns data and no external storage /// was supplied. It is later used by RecordSet to retrieve the fetched data after statement execution. /// It takes ownership of the Column pointer supplied as constructor argument. Column object, in turn /// owns the data container pointer. /// /// InternalBulkExtraction objects can not be copied or assigned. { public: typedef typename C::value_type T; explicit InternalBulkExtraction(C& result, Column<C>* pColumn, Poco::UInt32 limit, const Position& pos = Position(0)): BulkExtraction<C>(result, T(), limit, pos), _pColumn(pColumn) /// Creates InternalBulkExtraction. { } ~InternalBulkExtraction() /// Destroys InternalBulkExtraction. { delete _pColumn; } void reset() { _pColumn->reset(); } const T& value(int index) const { try { return BulkExtraction<C>::result().at(index); } catch (std::out_of_range& ex) { throw RangeException(ex.what()); } } bool isNull(std::size_t row) const { return BulkExtraction<C>::isNull(row); } const Column<C>& column() const { return *_pColumn; } private: InternalBulkExtraction(); InternalBulkExtraction(const InternalBulkExtraction&); InternalBulkExtraction& operator = (const InternalBulkExtraction&); Column<C>* _pColumn; }; namespace Keywords { template <typename T> BulkExtraction<std::vector<T> >* into(std::vector<T>& t, const Bulk& bulk, const Position& pos = Position(0)) /// Convenience function to allow for a more compact creation of an extraction object /// with std::vector bulk extraction support. { return new BulkExtraction<std::vector<T> >(t, bulk.size(), pos); } template <typename T> BulkExtraction<std::vector<T> >* into(std::vector<T>& t, BulkFnType, const Position& pos = Position(0)) /// Convenience function to allow for a more compact creation of an extraction object /// with std::vector bulk extraction support. { Poco::UInt32 size = static_cast<Poco::UInt32>(t.size()); if (0 == size) throw InvalidArgumentException("Zero length not allowed."); return new BulkExtraction<std::vector<T> >(t, size, pos); } template <typename T> BulkExtraction<std::deque<T> >* into(std::deque<T>& t, const Bulk& bulk, const Position& pos = Position(0)) /// Convenience function to allow for a more compact creation of an extraction object /// with std::deque bulk extraction support. { return new BulkExtraction<std::deque<T> >(t, bulk.size(), pos); } template <typename T> BulkExtraction<std::deque<T> >* into(std::deque<T>& t, BulkFnType, const Position& pos = Position(0)) /// Convenience function to allow for a more compact creation of an extraction object /// with std::deque bulk extraction support. { Poco::UInt32 size = static_cast<Poco::UInt32>(t.size()); if (0 == size) throw InvalidArgumentException("Zero length not allowed."); return new BulkExtraction<std::deque<T> >(t, size, pos); } template <typename T> BulkExtraction<std::list<T> >* into(std::list<T>& t, const Bulk& bulk, const Position& pos = Position(0)) /// Convenience function to allow for a more compact creation of an extraction object /// with std::list bulk extraction support. { return new BulkExtraction<std::list<T> >(t, bulk.size(), pos); } template <typename T> BulkExtraction<std::list<T> >* into(std::list<T>& t, BulkFnType, const Position& pos = Position(0)) /// Convenience function to allow for a more compact creation of an extraction object /// with std::list bulk extraction support. { Poco::UInt32 size = static_cast<Poco::UInt32>(t.size()); if (0 == size) throw InvalidArgumentException("Zero length not allowed."); return new BulkExtraction<std::list<T> >(t, size, pos); } } // namespace Keywords } } // namespace Poco::Data #endif // Data_BulkExtraction_INCLUDED
[ [ [ 1, 287 ] ] ]
5a9b20d8fe866544f1e6996ac9d28ca9c8cd50a9
975d45994f670a7f284b0dc88d3a0ebe44458a82
/cliente/Source/Setup/GameSetup.h
e2da2ffa7cdb0f5ac74cf97a2ee65f91b6a1e730
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,038
h
#pragma once //----------------------------------------------------------------------------------------- // Includes genéricos //----------------------------------------------------------------------------------------- #include <WinSock2.h> // Sempre antes do Windows.h #include <windows.h> #include <iostream> #include <fstream> #include <stdlib.h> #include <string.h> #include <math.h> #include "irrlicht.h" #include "irrklang.h" //----------------------------------------------------------------------------------------- // Namespaces //----------------------------------------------------------------------------------------- using namespace std; using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; using namespace irrklang; //----------------------------------------------------------------------------------------- // Inclusão de libs //----------------------------------------------------------------------------------------- #pragma comment(lib, "Irrlicht.lib") #pragma comment(lib, "irrKlang.lib") #pragma comment(lib, "dsvt.lib") //----------------------------------------------------------------------------------------- // Constantes //----------------------------------------------------------------------------------------- // Cenario const int MAXPORTAIS = 4; // Número de portais por cenário const int MAPMAXLIN = 50; // Número máximo de linhas por cenário const int MAPMAXCOL = 50; // Número máximo de colunas por cenário const int TAMQUADRANTE = 44; // Tamanho de cada quadrante em pixels const int NUMCENARIOS = 10; // Número de cenários no jogo const int NUMPROPS = 50; // Número de props do jogo (arvore, templos, flores, etc..) const int NUMPARTICLETYPES = 1; // Número de tipos de partículas (fogo, fumaça,...) // Bolsa const int BOLSAMAXITENS = 9; // Número máximo de itens na bolsa de um personagem const int BOLSA_ID_OFFSET = 1000000; // para nao colidir com id de personagens no nó de cena // Personagens const int INVENTARIOMAXITENS = 12; // Número máximo de itens no inventário const int RACASMAX = 5; // Número máximo de raças jogáveis const int NUMRACES = 20; // Número de raças disponíveis no jogo const int NUMCLASSES = 8; // Número de classes para cada raça const int NUMPODERES = 3; // Número de poderes de cada personagem const int NUMBUFFERS = 15; // Número de buffs de cada personagem const int MAXITENSVENDEDOR = 30; // Número máximo de itens do vendedor // Menu const int NUMMENUCENA = 3; // número de menus com cenas irr a carregar const int MAXSLOTPERSONAGEM = 2; // número máximo de slots de personagem de um jogador // Hud const int NUMROLETAOPCOES = 6; // número de opções na roleta const int NUMSFXHUD = 10; // efeitos sonoros do HUD const int NUMFLAGSMENU = 20; // número de flags de menu const int NUMHUDFONTS = 2; // número de fonts no menu // Pathfinding const int LARGURABUSCA = 10; // largura de busca 10 quadrantes const int AREABUSCA = LARGURABUSCA*LARGURABUSCA; // área de busca 10x10 quadrantes // Game Data const int NUM3DITENS = 26; // Número de itens 3D no jogo const int NUM3DPERS = 44; // Número de personagens 3D no jogo const int NUM2DOBJS = 39; // Número de objetos 2D no jogo const int NUMMENUHUDS = 3; // Número de huds nos menus const int NUMMUSICAS = 4; // Número de músicas do jogo // Irrlicht const E_DRIVER_TYPE defDriver = EDT_OPENGL/*EDT_DIRECT3D9*/; const dimension2d <s32> defDimension = dimension2d <s32>( 1024, 768 ); const u8 defBits = 32; const bool defFullScreen = true; const bool defStencilBuffer = true; const bool defVsync = true; const bool defAntiAlias = true; const bool defAlphaChannel = true; const bool defHiPrecisionFpu = false; const bool defIgnoreInput = false; const u8 defZBufferBits = 16; // IrrKlang const f32 defSFXVol = 1.0; const f32 defMusicVol = 1.0; //----------------------------------------------------------------------------------------- // Enumerators //----------------------------------------------------------------------------------------- // Inicialização enum TypeReturn { ERRO_CONTINUE, ERRO_SAIR, SUCESSO, PING_REQUEST, FINAL_PACOTES }; // Menu enum TypeMenuID { MN_ABERTURA, MN_LOGIN, MN_SELECAOPERSONAGEM, MN_CRIACAOPERSONAGEM, MN_JOGO, MN_CREDITOS, MN_COUNT, MN_SAIDA, MN_ERRO }; enum TypeLoadStage { LS_PERSONAGENS, LS_ITENS, LS_TXPERSONAGENS, LS_TXITENS, LS_HUDITENS, LS_HUDS, LS_COUNT }; enum TypeMenuFlag { HUDUPDATED, OBJSELECTED, INVENTARIOON, CHATON, STATUSON, MAPAON, TRADEON, EQUIPON, SHOPON, BOLSAON, ALERTON, CONFIGON, FLAG_COUNT }; enum TypeFontSize { FONT_PEQUENA, FONT_GRANDE, FONT_COUNT }; enum TypeMenuSCene { MC_LOGIN, MC_SELECAO, MC_CRIACAO, MC_COUNT }; enum TypeMenuMusic { MM_LOGIN, MM_SELECAO, MM_CRIACAO, MM_JOGO, MM_COUNT }; enum TypeMenuSfx { MFX_BOTAO, MFX_OPENWINDOW, MFX_CLOSEWINDOW, MFX_SLIDEBAR, MFX_CASH, MFX_PICKUP, MFX_COUNT }; enum TypeCutScene { CS_ABERTURA, CS_CREDITOS, CS_TRANSICAO, CS_COUNT }; enum TypeHudSkin { HS_NONE, HS_PADRAO, HS_ARANHA, HS_BESOURO, HS_ESCORPIAO, HS_LOUVADEUS, HS_VESPA, HS_COUNT }; // Cenario enum TypeMoon { MOON_OBLIVION, MOON_TYPHOONA, MOON_MABILOG, MOON_ABGRUNDI, MOON_RESPLANDORA, MOON_SAMARA, MOON_COUNT }; enum TypeTxScenes { TXCENA_0, TXCENA_1, TXCENA_2, TXCENA_3, TXCENA_4, TXCENA_5, TXCENA_6, TXCENA_7, TXCENA_BUMP, TXCENA_COUNT }; enum TypeGameScene { GAMESCENE_00, GAMESCENE_01, GAMESCENE_02, GAMESCENE_03, GAMESCENE_04, GAMESCENE_05, GAMESCENE_06, GAMESCENE_07, GAMESCENE_08, GAMESCENE_09, GAMESCENE_COUNT }; enum TypeParticle { P_FOGO }; // Personagem enum TypePersonagemSelecao { S_ARANHA, S_BESOURO, S_ESCORPIAO, S_LOUVADEUS, S_VESPA, S_COUNT }; enum TypeRaceChars { NONERACE, ALLRACE, ARANHA, BESOURO, ESCORPIAO, LOUVADEUS, VESPA, CUPIM, FORMIGA, BARBEIRO, BARATA, TATUBOLINHA, LIBELULA, PERCEVEJO, ABELHA, LAGARTIXA, CALANGO, SAPO, JOANINHA, CAMALEAO }; enum TypeClassChars { NONECLASS, ALLCLASS, JOGADOR, SOLDADO, LIDER, VENDEDOR, MAE, FILHOTE }; enum TypeModelos { M_NONE, M_ARANHA_LIDER, M_ARANHA_JOGADOR, M_ARANHA_SOLDADO, M_ARANHA_VENDEDOR, M_ARANHA_MAE, M_ARANHA_FILHOTE, M_BESOURO_LIDER, M_BESOURO_JOGADOR, M_BESOURO_SOLDADO, M_BESOURO_VENDEDOR, M_BESOURO_MAE, M_BESOURO_FILHOTE, M_ESCORPIAO_LIDER, M_ESCORPIAO_JOGADOR, M_ESCORPIAO_SOLDADO, M_ESCORPIAO_VENDEDOR, M_ESCORPIAO_MAE, M_ESCORPIAO_FILHOTE, M_LOUVADEUS_LIDER, M_LOUVADEUS_JOGADOR, M_LOUVADEUS_SOLDADO, M_LOUVADEUS_VENDEDOR, M_LOUVADEUS_MAE, M_LOUVADEUS_FILHOTE, M_VESPA_LIDER, M_VESPA_JOGADOR, M_VESPA_SOLDADO, M_VESPA_VENDEDOR, M_VESPA_MAE, M_VESPA_FILHOTE, M_CUPIM, M_FORMIGA, M_BARBEIRO, M_BARATA, M_TATUBOLINHA, M_LIBELULA, M_PERCEVEJO, M_ABELHA, M_LAGARTIXA, M_CALANGO, M_SAPO, M_JOANINHA, M_CAMALEAO, M_TANDAN }; enum TypeBuff { BUFF_NORMAL, BUFF_DESESPERO, BUFF_VENENO, BUFF_DADIVA, BUFF_BERSERKER, BUFF_STRIKE, BUFF_BACKSTAB, BUFF_LENTO, BUFF_PIERCESHOT, BUFF_STUN, BUFF_ATORDOADO, BUFF_ESCUDO, BUFF_CHI, BUFF_INVISIVEL, BUFF_MOON_TYPHOONA, BUFF_MOON_MABILOG, BUFF_MOON_ABGRUNDI, BUFF_MOON_RESPLANDORA, BUFF_MOON_SAMARA, BUFF_COUNT }; // Item enum TypeItens { I_NONE, I_BUZINA, I_VARINHA, I_SOCO, I_BAZUCA, I_MARTELO_GUERRA, I_METRALHADORA, I_MARTELO_CONAN, I_KATANA, I_LANÇADOR_DARDOS, I_MACHADO, I_PALITO_FOSFORO, I_VASSOURA, I_PU_DAO, I_ESPINGARDA, I_MAMONA, I_ESTILINGUE, I_CARTOLA, I_TENIS, I_ELMO_HERCULES, I_ELMO_BARBARO, I_OCULOS_ESCUROS, I_GORRO, I_CHACHI, I_CHAPEU_PALHA, I_OCULOS_AVIADOR, I_MASCARA_GAS, I_PASSAPORTE, I_POLPA_FORMIGA, I_POLPA_CUPIM, I_POLPA_BARATA, I_POLPA_TATU, I_ASA_LIBELULA, I_PERFUME_PERCEVEJO, I_MEL_ABELHA, I_TESOURA_BARBEIRO, I_RABO_CALANGO, I_OVO_LAGARTIXA, I_LINGUA_SAPO, I_LINGUA_CAMALEAO }; enum TypeBtnHuds { H_NONE, H_BUZINA, H_VARINHA, H_SOCO, H_BAZUCA, H_MARTELO_GUERRA, H_METRALHADORA, H_MARTELO_CONAN, H_KATANA, H_LANÇADOR_DARDOS, H_MACHADO, H_PALITO_FOSFORO, H_VASSOURA, H_PU_DAO, H_ESPINGARDA, H_MAMONA, H_ESTILINGUE, H_CARTOLA, H_TENIS, H_ELMO_HERCULES, H_ELMO_BARBARO, H_OCULOS_ESCUROS, H_GORRO, H_CHACHI, H_CHAPEU_PALHA, H_OCULOS_AVIADOR, H_MASCARA_GAS, H_PASSAPORTE, H_POLPA_FORMIGA, H_POLPA_CUPIM, H_POLPA_BARATA, H_POLPA_TATU, H_ASA_LIBELULA, H_PERFUME_PERCEVEJO, H_MEL_ABELHA, H_TESOURA_BARBEIRO, H_RABO_CALANGO, H_OVO_LAGARTIXA, H_LINGUA_SAPO, H_LINGUA_CAMALEAO, H_CONECTAR, H_CRIAR, H_REMOVER, H_JOGAR, H_MEONMAP, H_LEFT, H_RIGHT, H_LEFT_MINI, H_RIGHT_MINI, H_DROP, H_COMPRAR, H_VENDER, H_ROLETA, H_CADEADO, H_EQUIP, H_MOLDURA, H_SEMENTE, H_MOON_HUD, H_MOON_NONE, H_MOON_ARANHA, H_MOON_BESOURO, H_MOON_ESCORPIAO, H_MOON_LOUVA, H_MOON_VESPA, H_CLOSE_WINDOW, H_INVENTARIO, H_TRADE, H_SHOP, H_ALERT, H_STATUS, H_CONFIG, H_EXIT, H_PEACEMODE, H_WARMODE, H_QUEST_NONE, H_QUEST_OPENED, H_QUEST_CLOSED, H_ROLETA_MASK, H_FACE_NONE, H_FACE_ARANHA, H_FACE_BESOURO, H_FACE_ESCORPIAO, H_FACE_LOUVA, H_FACE_VESPA, H_FACE_BESOURO_LIDER, H_FACE_BESOURO_GUARDA, H_FACE_BESOURO_VENDEDOR, H_FACE_VESPA_LIDER, H_FACE_VESPA_GUARDA, H_FACE_VESPA_VENDEDOR, H_FACE_FORMIGA, H_FACE_CUPIM, H_FACE_SAPO, H_FACE_CAMALEAO, H_FACE_BARBEIRO, H_FACE_JOANINHA, H_FACE_CALANGO, H_FACE_LAGARTIXA, H_FACE_TANDAN, H_ROLETA_POWER1_ARANHA, H_ROLETA_POWER2_ARANHA, H_ROLETA_POWER3_ARANHA, H_ROLETA_POWER1_BESOURO, H_ROLETA_POWER2_BESOURO, H_ROLETA_POWER3_BESOURO, H_ROLETA_POWER1_ESCORPIAO, H_ROLETA_POWER2_ESCORPIAO, H_ROLETA_POWER3_ESCORPIAO, H_ROLETA_POWER1_LOUVA, H_ROLETA_POWER2_LOUVA, H_ROLETA_POWER3_LOUVA, H_ROLETA_POWER1_VESPA, H_ROLETA_POWER2_VESPA, H_ROLETA_POWER3_VESPA, H_ROLETA_POLPA_FORMIGA, H_ROLETA_POLPA_CUPIM, H_ROLETA_POLPA_BARATA, H_ROLETA_POLPA_TATU, H_COUNT }; enum TypeDirecao { D_LEFT, D_SOUTH, D_DOWN, D_EAST, D_RIGHT, D_NORTH, D_UP, D_WEST }; enum TypeAnimState { PARADO, SAUDACAO, CORRENDO, ATAQUE1, ATAQUE2, ATAQUE3, ATAQUE4, PODER1, PODER2, PODER3, BUFF_BOM, BUFF_RUIM, APANHANDO, MORRENDO };
[ [ [ 1, 580 ] ] ]
86d50e5659db7add7de50cc6f8c496404855383a
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/util/celltreebuilder.cc
2ad1629454c028f7105587b473074ee0b064ed4d
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,619
cc
//------------------------------------------------------------------------------ // util/celltreebuilder.cc // (C) 2005 Radon Labs GmbH //------------------------------------------------------------------------------ #include "util/celltreebuilder.h" #include "util/nquadtree.h" #include "graphics/level.h" #include "graphics/cell.h" #include "foundation/factory.h" namespace Util { //------------------------------------------------------------------------------ /** */ CellTreeBuilder::CellTreeBuilder() : numCellsBuilt(0) { // empty } //------------------------------------------------------------------------------ /** Create a quad tree of Graphics::Cells and attach them to the provided level. */ void CellTreeBuilder::BuildQuadTree(Graphics::Level* level, uint depth, const bbox3& box) { // construct a Nebula2 quad tree object this->quadTree.Initialize(depth, box); this->numCellsBuilt = 0; // walk the tree and construct cells Ptr<Graphics::Cell> rootCell = this->CreateQuadTreeCell(0, 0, 0, 0); level->SetRootCell(rootCell); } //------------------------------------------------------------------------------ /** Initialize one quad tree level. Will be called recursively. */ Graphics::Cell* CellTreeBuilder::CreateQuadTreeCell(Graphics::Cell* parentCell, uint curLevel, uint curCol, uint curRow) { // create a new cell Graphics::Cell* cell = Graphics::Cell::Create(); int nodeIndex = this->quadTree.GetNodeIndex(curLevel, curCol, curRow); const nQuadTree::Node& node = this->quadTree.GetNodeByIndex(nodeIndex); matrix44 cellTransform; cellTransform.translate(node.GetBoundingBox().center()); cell->SetTransform(cellTransform); cell->SetBox(node.GetBoundingBox()); this->numCellsBuilt++; // create child cells uint childLevel = curLevel + 1; if (childLevel < this->quadTree.GetDepth()) { cell->BeginChildCells(4); for (int i = 0; i < 4; i++) { uint childCol = 2 * curCol + (i & 1); uint childRow = 2 * curRow + ((i & 2) >> 1); Ptr<Graphics::Cell> childCell = this->CreateQuadTreeCell(cell, childLevel, childCol, childRow); cell->AddChildCell(i, childCell); } cell->EndChildCells(); } return cell; } //------------------------------------------------------------------------------ /** Returns the number of cells that have been created. */ int CellTreeBuilder::GetNumCellsBuilt() const { return this->numCellsBuilt; } }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 84 ] ] ]
014b7fb942d43b1b6f52a0cbd03ca15976780c2c
ed9ecdcba4932c1adacac9218c83e19f71695658
/CJEngine_2010/CJEngine/CJEngine/EffectNode.h
60f006ab58c2d0ffe1d01b1b0b47f669a7df1d59
[]
no_license
karansapra/futurattack
59cc71d2cc6564a066a8e2f18e2edfc140f7c4ab
81e46a33ec58b258161f0dd71757a499263aaa62
refs/heads/master
2021-01-10T08:47:01.902600
2010-09-20T20:25:04
2010-09-20T20:25:04
45,804,375
0
0
null
null
null
null
UTF-8
C++
false
false
332
h
#pragma once #include "./SceneNode.h" #include "./FX.h" class SceneGraphManager; class EffectNode : public SceneNode { friend class SceneGraphManager; FX * fx_; protected: EffectNode(void); ~EffectNode(void); public: void BeginRealization(); void EndRealization(); void SetEffect(const FX & fx); };
[ "clems71@52ecbd26-af3e-11de-a2ab-0da4ed5138bb" ]
[ [ [ 1, 21 ] ] ]
ce8325b8e8bce2fd938015152a9ae8d10c48a81c
d1bd1841896c1258db2dec354006faf8e8915984
/src/ItemButton.cpp
d4b83c505f8079bf4d5c70dfb7329e60b7038a63
[]
no_license
crawford/Drink-Client
99740b894a5f2ec1e335fb964fd5116ea7bc351f
6c1a7c5a77b097b057ef93c46b6320df0fea5a53
refs/heads/master
2021-01-18T19:18:17.920447
2010-08-29T14:31:30
2010-08-29T14:31:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,212
cpp
#include "ItemButton.h" #include <QStylePainter> #include <QStyleOptionButton> ItemButton::ItemButton(QWidget *parent) : QAbstractButton(parent) { description = ""; price = ""; marked = false; setContentsMargins(9, 9, 9, 9); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); setMinimumHeight(getMinSize()); } ItemButton::ItemButton(QString nTitle, QString nDescription, QString nPrice, QIcon nIcon, QWidget *parent) : QAbstractButton(parent) { setText(nTitle); description = nDescription; price = nPrice; setIcon(nIcon); marked = false; setContentsMargins(9, 9, 9, 9); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); setMinimumHeight(getMinSize()); } int ItemButton::getMinSize() { //return fontInfo().pixelSize()*4; return 48;//iconSize().height(); } void ItemButton::setDescription(QString nDescription) { description = nDescription; update(); updateGeometry(); } QString ItemButton::getDescription() { return description; } void ItemButton::setPrice(QString nPrice) { price = nPrice; update(); updateGeometry(); } QString ItemButton::getPrice() { return price; } void ItemButton::mark() { marked = true; } void ItemButton::unmark() { marked = false; } bool ItemButton::isMarked() { return marked; } void ItemButton::paintEvent(QPaintEvent *event) { QStylePainter p(this); QStyleOptionButton option; QRect margins = contentsRect(); QFontMetrics fontMetrics(p.font()); int textHeight = 0; int textWidth = 0; int priceWidth = fontMetrics.boundingRect(price).width(); option.initFrom(this); if (isDown()) option.state |= QStyle::State_Sunken; else option.state |= QStyle::State_Raised; if (isChecked()) option.state |= QStyle::State_On; //Draw button p.drawControl(QStyle::CE_PushButtonBevel, option); //Draw icon if(isEnabled()) p.drawPixmap(margins.left(), (margins.height() - iconSize().height())/2 + margins.top(), icon().pixmap(iconSize(), QIcon::Normal)); else p.drawPixmap(margins.left(), (margins.height() - iconSize().height())/2 + margins.top(), icon().pixmap(iconSize(), QIcon::Disabled)); //Draw title text textHeight = fontMetrics.boundingRect(text()).height(); textWidth = fontMetrics.boundingRect(text()).width(); p.drawText(QRect(margins.left()*2 + iconSize().width(), margins.top(), margins.width() - priceWidth, textHeight), Qt::AlignLeft|Qt::TextSingleLine, text()); //Draw price text p.drawText(QRect(margins.right() - priceWidth, margins.top(), priceWidth, margins.height()), Qt::AlignRight|Qt::TextSingleLine|Qt::AlignVCenter, price); //Resize font QFont font = p.font(); //font.setPixelSize((int)(font.pixelSize() * 0.75)); font.setPointSizeF((font.pointSizeF() * 0.75)); p.setFont(font); //Draw description text fontMetrics = QFontMetrics(p.font()); textHeight = fontMetrics.boundingRect(description).height(); textWidth = fontMetrics.boundingRect(description).width(); p.drawText(QRect(margins.left()*2 + iconSize().width(), margins.bottom() - textHeight, margins.width() - priceWidth, textHeight), Qt::AlignLeft|Qt::TextSingleLine, description); }
[ [ [ 1, 113 ] ] ]
ac483c6d61229919476eaf8b426d3e74e847090c
9ac9e5d4512050113b7b1dd31a0e438d7f0f56c8
/scratch/simple.h
1e85ac1119ff828bf1b931ae4768ec0c2aaffb85
[]
no_license
BackupTheBerlios/titanium-svn
803eaf2df351cb234cbbad03eba9766af888ef79
b6eb5af7aea0a27871074d26782b1ba95c6969be
refs/heads/master
2020-07-26T23:30:22.607793
2009-02-08T17:42:46
2009-02-08T17:42:46
40,800,242
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
#include <wx/wxprec.h> #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP // Include your minimal set of headers here, or wx.h #endif #include <wx/wx.h> #include <wx/listctrl.h> class Simple : public wxFrame { public: Simple(const wxString& title); wxListCtrl* evtList; };
[ "dasuraga@ae6d8690-0e5c-0410-9b8a-a18a871dc406" ]
[ [ [ 1, 15 ] ] ]
e84d00dc2cfb78a77e116ea3eb29b8350d77c4fd
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Graphics/Effect.h
90d592e38d353c3cb5f86af167799d66b603b5d8
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
3,735
h
#ifndef __SLON_ENGINE_GRAPHICS_EFFECT_H__ #define __SLON_ENGINE_GRAPHICS_EFFECT_H__ #include "../Database/Serializable.h" #include "../Utility/hash_string.hpp" #include "ParameterBinding.h" namespace slon { namespace graphics { // Forward class Pass; typedef unsigned render_group_handle; typedef unsigned render_pass_handle; typedef hash_string parameter_handle; typedef hash_string attribute_handle; /** Effect unify effects that share states and(or) shaders. * Traditionally rendering can be represented as followed: * \code * Pass* passes[Effect::MAX_NUM_PASSES]; * int nPasses = effect->present(renderGroup, renderPass, passes); * for (int i = 0; i<nPasses; ++i) * { * passes[i]->begin(); // begin using effect, remember states * someDrawable->render(); * passes[i]->end(); // restore states * } * \uncode */ class SLON_PUBLIC Effect : public Referenced, public database::Serializable { public: static const int MAX_NUM_PASSES = 5; /// maximum number of passes allowed for effect per render pass public: // Override serializable const char* serialize(database::OArchive& ar) const { return "Effect"; } void deserialize(database::IArchive& ar) {} /** Present effect in the render pass. Get technique used to render objects. * Render passes are grouped in render groups for convenience and some performance speed up. * E.g. ForwardRenderer have render group "Reflect" for rendering scene into reflect texture with * simplified states and front face culling. * @param renderGroup - current render group index. * @param renderPass - current render pass index. * @param passes [out] - array of the techniques for rendering object * @return number of passes for rendering object. */ virtual int present(render_group_handle renderGroup, render_pass_handle renderPass, Pass** passes) = 0; /** Get parameter binding. * @see bindParameter */ virtual const abstract_parameter_binding* getParameter(parameter_handle name) const = 0; /** Bind material parameter parameter to arbitrary get function. * @param name - parameter name. * @param binder - parameter binding. * List of default semantics: * \li \c ("worldMatrix", Matrix4x4f&) - object world matrix. * \li \c ("boneMatrices", Matrix4x4f*) - bone transformation matrices. * \li \c ("boneRotations", Vector4f*) - bone rotation quaternions. * \li \c ("boneTranslations", Vector3f*) - bone translations. * \li \c ("projectedGridCorners", Vector3f*) - four corners projected on the plane using projected grid. */ virtual bool bindParameter(parameter_handle name, const abstract_parameter_binding* binding) = 0; /** Get index of the named attribute. You must bind all the queried attributes, * otherwise effect behaviour will be undefined. May change effect behaviour so * it is not const. * @return attribute index or -1 if effect doesn't support queried attribute. * List of default attributes: * \li \c ("position", Vector4f) * \li \c ("weights", Vector4f) * \li \c ("normal", Vector3f) * \li \c ("tangent", Vector3f) * \li \c ("binormal", Vector3f) * \li \c ("texcoord", Vector2f) */ virtual int queryAttribute(attribute_handle name) = 0; virtual ~Effect() {} }; typedef boost::intrusive_ptr<Effect> effect_ptr; typedef boost::intrusive_ptr<const Effect> const_effect_ptr; } // namespace graphics } // namespace slon #endif // __SLON_ENGINE_GRAPHICS_EFFECT_H__
[ "devnull@localhost" ]
[ [ [ 1, 96 ] ] ]
f52a4d3ef1486918ab6b691dd66d300408115781
1724fb22a0b715c4597c5056ce571f0fbdb1cc46
/opengta2/font.cpp
0346d071b42c07db0bef883d74006e9b99ec5af4
[]
no_license
basecq/OpenGTA2
71127e333b7b6c6a60388ad8b4fb5c4408aa5bdd
2266c354a638397b84ca4766c69e3a50f4e367de
refs/heads/master
2020-04-06T05:25:34.926813
2010-01-27T02:35:09
2010-01-27T02:35:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,544
cpp
#include "opengta_cl.h" #include "stdarg.h" Font_Manager Fonts; int concmd_cl_font_list(int numParams, int* paramType, int* params) { logWrite("Font list:"); for (uint i = 0; i < Fonts.fontEntries.Count; i++) { logWrite("#%d: %s [%d chars]", i, Fonts.fontEntries[i]->FontName, Fonts.fontEntries[i]->numCharacters); } return 0; } void concmdw_cl_message_font(int numParams, int* paramType, int* params) { if (numParams > 0) { uint fontID = 0; if (paramType[0] == CONVAR_FLOAT) { fontID = (uint)((float*)params)[0]; } if (paramType[0] == CONVAR_INT) { fontID = ((uint*)params)[0]; } if (fontID < Fonts.fontEntries.Count) { Fonts.Message = fontID; Console.consoleFont = Fonts.Message; } } } int concmdr_cl_message_font(int numParams, int* paramType, int* params) { paramType[0] = CONVAR_INT; ((int*)params)[0] = Fonts.Message; return 1; } void Font_Manager::Initialize() { fontEntries.Preallocate(MAX_FONT_ENTRIES); fontScale = 1.0f; fontAlign = 0; Convar.Create("r_list_fonts",concmd_cl_font_list,0); Convar.Create("r_msg_font",concmdr_cl_message_font,concmdw_cl_message_font); } void Font_Manager::Deinitialize() { for (uint i = 0; i < fontEntries.Count; i++) { mem.free(fontEntries[i]->characterTextureID); } fontEntries.Release(); } void Font_Manager::shrinkFontEntries() { fontEntries.Shrink(); //Fixme MissionTitle = getFontID("GTA2FONT_0"); Message = getFontID("CONSOLEFONT_0"); } FontID Font_Manager::getFontID(const char* FontName) { for (uint i = 0; i < fontEntries.Count; i++) { if (strncmp(fontEntries[i]->FontName,FontName,strlen(FontName)) == 0) return i; } logWrite("Font not found: %s",FontName); return BAD_ID; } float Font_Manager::TextWidth(FontID fontID, char const* text) { float textWidth; TextDimensions(fontID, text, &textWidth, 0); return textWidth; } float Font_Manager::TextHeight(FontID fontID, char const* text) { float textHeight; TextDimensions(fontID, text, 0, &textHeight); return textHeight; } void Font_Manager::SetScale(float scale) { fontScale = scale; } void Font_Manager::SetAlign(int align) { fontAlign = align; } void Font_Manager::Reset() { fontScale = 1.0f; fontAlign = 0; } void Font_Manager::printf(FontID fontID, Vector2f pos, const char *fmt, ...) { char buf[16384]; va_list ap; va_start(ap,fmt); vsnprintf(buf,16384,fmt,ap); va_end(ap); print(fontID,pos,buf); } void Font_Manager::TextDimensions(FontID fontID, char const* text, float* textWidth, float* textHeight) { if (textWidth) *textWidth = 0; if (textHeight) *textHeight = 0; if (fontID == BAD_ID) return; float lineHeight,charWidth; Vector2f textPos; int firstChar = UTF8_GET_CHAR(text); int textureID = fontEntries[fontID]->getCharacter(firstChar); if (textureID != BAD_ID) { texture_entry* tex = Graphics.GetTextureEntryByID(textureID); lineHeight = tex->Height; charWidth = tex->Width; } else { lineHeight = 16.0f; charWidth = 16.0f; } textPos = Vector2f(0,0); while (*text) { int currentCharacter = UTF8_GET_CHAR(text); if (!UTF8_SEQ_VALID(text)) { //if (currentCharacter < 0) { currentCharacter = 0x25A1; text += 1; } else { text += UTF8_CHAR_LENGTH(currentCharacter); } textureID = BAD_ID; if (currentCharacter == '\n') { textPos.x = 0; textPos.y = textPos.y + lineHeight; } else if (currentCharacter == '\r') { textPos.x = 0; } else if (currentCharacter == ' ') { textureID = fontEntries[fontID]->getCharacter('I'); } else if (currentCharacter == '\t') { textureID = fontEntries[fontID]->getCharacter('I'); } else { textureID = fontEntries[fontID]->getCharacter(currentCharacter); } if (textureID == BAD_ID) { //Print a rectangle instead of invalid non-special-code character if (currentCharacter >= 0x20) textureID = fontEntries[fontID]->getCharacter(0x25A1); } if (textureID != BAD_ID) { texture_entry* tex = Graphics.GetTextureEntryByID(textureID); float w = tex->Width*fontScale; float h = tex->Height*fontScale; if (currentCharacter == '\t') { w = w * 6; } textPos.x += w; if (h > lineHeight) h = lineHeight; if (textWidth) *textWidth = max(*textWidth,textPos.x); if (textHeight) *textHeight = max(*textHeight,textPos.y+h); } else { if ((currentCharacter != '\n') && (currentCharacter != '\r')) { textPos.x += charWidth; if (textWidth) *textWidth = max(*textWidth,textPos.x); } } } } void Font_Manager::print(FontID fontID, Vector2f pos, char const* text) { if (fontID == BAD_ID) return; if (!fontFastRender) Screen.Start2D(); float lineHeight,charWidth; Vector2f textPos,textOffset; int firstChar = UTF8_GET_CHAR(text); int textureID = fontEntries[fontID]->getCharacter(firstChar); if (textureID != BAD_ID) { texture_entry* tex = Graphics.GetTextureEntryByID(textureID); lineHeight = tex->Height; charWidth = tex->Width; } else { lineHeight = 25.0f; charWidth = 9.0f; } textPos = pos; textOffset = Vector2f(0,0); if (fontAlign > 0) { float textWidth,textHeight; TextDimensions(fontID, text, &textWidth, &textHeight); switch (fontAlign) { case FONTALIGN_CENTER: textOffset = Vector2f(-0.5f * textWidth, 0.0f ); break; case FONTALIGN_RIGHT: textOffset = Vector2f(-1.0f * textWidth, 0.0f ); break; case FONTALIGN_ABOVE: textOffset = Vector2f(-0.5f * textWidth, -1.0f * textHeight); break; case FONTALIGN_ABOVELEFT: textOffset = Vector2f( 0.0f , -1.0f * textHeight); break; case FONTALIGN_ABOVERIGHT: textOffset = Vector2f(-1.0f * textWidth, -1.0f * textHeight); break; } } while (*text) { int currentCharacter = UTF8_GET_CHAR(text); if (!UTF8_SEQ_VALID(text)) { //if (currentCharacter < 0) { currentCharacter = 0x25A1; text += 1; } else { text += UTF8_CHAR_LENGTH(currentCharacter); } textureID = BAD_ID; if (currentCharacter == '\n') { textPos.x = pos.x; textPos.y = textPos.y + lineHeight; } else if (currentCharacter == '\r') { textPos.x = pos.x; } else if (currentCharacter == ' ') { textureID = fontEntries[fontID]->getCharacter('I'); } else if (currentCharacter == '\t') { textureID = fontEntries[fontID]->getCharacter('I'); } else { textureID = fontEntries[fontID]->getCharacter(currentCharacter); } if (textureID == BAD_ID) { //Print a rectangle instead of invalid non-special-code character if (currentCharacter >= 0x20) textureID = fontEntries[fontID]->getCharacter(0x25A1); } if (textureID != BAD_ID) { texture_entry* tex = Graphics.GetTextureEntryByID(textureID); float w = tex->Width*fontScale; float h = tex->Height*fontScale; if (currentCharacter == '\t') { w = w * 6; } if ((currentCharacter != ' ') && (currentCharacter != '\t')) { Draw.Sprite2D(textureID, Vector2f(floor(textPos.x+textOffset.x), floor(textPos.y+textOffset.y)),fontScale); } textPos.x += w; if (h > lineHeight) h = lineHeight; } else { if ((currentCharacter != '\n') && (currentCharacter != '\r')) { textPos.x += charWidth; } } } if (!fontFastRender) { //Finish drawing sprites Draw.FlushSprites(); Screen.End2D(); } }
[ [ [ 1, 267 ] ] ]
62281696baa4d484d4d3681ab955c0f0236a6de3
cd3cb866cf33bdd9584d08f4d5904123c7d93da6
/records/tmxrecord.cpp
33e2a434f1152383b32430f112a6cb51d301dd56
[]
no_license
benkopolis/conflict-resolver
d910aa0e771be2a1108203a3fd6da06ebdca5680
d4185a15e5c2ac42034931913ca97714b21a977c
refs/heads/master
2021-01-01T17:16:59.418070
2011-01-29T17:49:27
2011-01-29T17:49:27
32,231,168
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
cpp
#include "tmxrecord.h" TMXRecord::TMXRecord(QObject *parent) : TMRecord(parent) { } QString TMXRecord::toListString() const { QString ret; // ret.append(_date.toString(QString("yyyy.MM.dd"))); // ret.append(QString(" | ")); // ret.append(_time.toString(QString("hh:mm:ss"))); // ret.append(QString(" | ")); ret.append(_sourceCode); ret.append(QString(" | ")); ret.append(source()); ret.append(QString(" | ")); ret.append(_targetCode); ret.append(QString(" | ")); ret.append(target()); return ret; } QString TMXRecord::toRecordString() const { QString ret; ret.append(_date.toString(QString("yyyyMMdd"))); ret.append(QChar('~')); ret.append(_time.toString(QString("hhmmss"))); ret.append(QChar('\t')); ret.append(this->_author); ret.append(QChar('\t')); ret.append(this->_authorId); ret.append(QChar('\t')); ret.append(_sourceCode); ret.append(QChar('\t')); ret.append(source()); ret.append(QChar('\t')); ret.append(_targetCode); ret.append(QChar('\t')); ret.append(target()); return ret; } QString TMXRecord::toReversedRecordString() const { QString ret; ret.append(_date.toString(QString("yyyyMMdd"))); ret.append(QChar('~')); ret.append(_time.toString(QString("hhmmss"))); ret.append(QChar('\t')); ret.append(this->_author); ret.append(QChar('\t')); ret.append(this->_authorId); ret.append(QChar('\t')); ret.append(_targetCode); // ret.append(QChar('\t')); // switched ret.append(target()); // ret.append(QChar('\t')); ret.append(_sourceCode); // ret.append(QChar('\t')); // with this ret.append(source()); // return ret; }
[ "benkopolis@ce349ab3-abbd-076b-ff20-4646c42d6692" ]
[ [ [ 1, 62 ] ] ]
b03a08dbc7827391611705299a23db8d37633622
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/srpc/test/DummyStreamBuffer.h
a430c73706d7bfe5c8cf63e319302f2593087162
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
h
#ifndef SRPC_DUMMYSTREAMBUFFER_H #define SRPC_DUMMYSTREAMBUFFER_H #ifdef _MSC_VER # pragma once #endif #include <srpc/detail/VectorStreamBuffer.h> #include <srpc/Exception.h> /** * @class DummyStreamBuffer */ class DummyStreamBuffer : public srpc::VectorStreamBuffer { public: DummyStreamBuffer() : isPushError_(false) {} virtual void push(Item item) { if (isPushError_) { throw srpc::StreamingException(__FILE__, __LINE__, "push error"); } else { srpc::VectorStreamBuffer::push(item); } } virtual void copyFrom(const Item* buffer, size_t bufferSize) { if (isPushError_) { throw srpc::StreamingException( __FILE__, __LINE__, "copyFrom error"); } else { srpc::VectorStreamBuffer::copyFrom(buffer, bufferSize); } } void setPushError() { isPushError_ = true; } private: bool isPushError_; }; #endif // SRPC_DUMMYSTREAMBUFFER_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 46 ] ] ]
6d927ec4d8083e58671fbfd29ab8709c893d5e85
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/TexturedQuadViewer/tqvPCH.h
e50ac543967fe5befcca9f69c76300f8843204fd
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
1,571
h
#pragma once #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <string> #include <vector> #include <list> #include <map> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <set> #ifdef WIN32 #include <memory> #else #include <tr1/memory> #endif #ifdef WIN32 #include <SDL.h> #include <SDL_opengl.h> #include <SDL_syswm.h> #else #define GL_GLEXT_PROTOTYPES #include <SDL/SDL.h> #include <SDL/SDL_opengl.h> #endif #include "ft2build.h" #include FT_FREETYPE_H // // ODE // #include <ode/ode.h> // // Boost C++ // #include <boost/foreach.hpp> #include <boost/array.hpp> #include <boost/circular_buffer.hpp> #define foreach BOOST_FOREACH // // Aran // #include "AranApi.h" #include "VideoManGl.h" #include "AranGl.h" #include "ArnTextureGl.h" #include "ArnGlExt.h" #include "AranPhy.h" #include "ArnPhyBox.h" #include "SimWorld.h" #include "GeneralJoint.h" #include "AranIk.h" #include "ArnIkSolver.h" #include "ArnPlane.h" #include "ArnBone.h" #include "Tree.h" #include "Jacobian.h" #include "Node.h" struct HitRecord { GLuint numNames; // Number of names in the name stack for this hit record GLuint minDepth; // Minimum depth value of primitives (range 0 to 2^32-1) GLuint maxDepth; // Maximum depth value of primitives (range 0 to 2^32-1) GLuint contents; // Name stack contents }; enum MessageHandleResult { MHR_DO_NOTHING, MHR_EXIT_APP, MHR_PREV_SCENE, MHR_NEXT_SCENE, MHR_RELOAD_SCENE };
[ [ [ 1, 84 ] ] ]
076643cd8e496abdd598e76a5804459288cd9ec8
de1224b9b4c1870b376aca583af2ab50911b452f
/Class_1/Homework/integer.cpp
9379337f1bb639bd538f0d6e2064d45ce5dc0fd8
[]
no_license
williamrh/Cpp
32e633d354134b848a857c3a68fcf9377240d431
4b6b372f02bad4036037bd9d4105ce5a2ea0ddb9
refs/heads/master
2021-01-06T20:46:57.563844
2011-10-31T21:32:09
2011-10-31T21:32:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
cpp
#include <cstdlib> #include <iostream> #include <cmath> #include <cstring> using namespace std; int main() { double value,down,years,interest; char ask[4]; cout << "Welcome to the Mortgage Calculator!\nWhat is the purchase price of the home you would like to purchase?: "; if ( ! (cin >> value) ) { cout << "That is not a valid number!\n"; exit(1); } cout << "What is your interest rate? (%): "; if ( ! (cin >> interest) ) { cout << "That is not a valid number!\n"; exit(1); } cout << "How much will is your down payment?: "; if ( ! (cin >> down) ) { cout << "That is not a valid number!\n"; exit(1); } cout << "Finally, How many years is this loan for?: "; if ( ! (cin >> years) ) { cout << "That is not a valid number!\n"; exit(1); } const double quotient = interest / 100 / 12; const double power = pow(1 + quotient, years * 12); const double P = (value - down) * quotient * power / (power - 1); cout.precision(2); cout << "Your Monthly Payment is $"<< fixed << P << "\n\n"; cout << "Would you like to know how much interest you'd pay the bank over the course of the mortgage? (Yes/No): "; cin >> ask; if ( strstr(ask,"Y") ) { double t_interest = ( P * (years*12) ) - ( value - down ) ; cout << "OK!\nYour total interest paid is $" << t_interest << "\n"; }else{ cout << "Fine! I didn't want to tell you anyway!\n\n"; } return 0; }
[ [ [ 1, 66 ] ] ]
03dfce27f9f3228674aff80464346f839abe7d15
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/numeric/ublas/test6/test6.hpp
26b224a8c83c2f8d13cbbf51b6a8b0fa5c27f1c5
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
2,577
hpp
// // Copyright (c) 2000-2002 // Joerg Walter, Mathias Koch // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. The authors make no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. // // The authors gratefully acknowledge the support of // GeNeSys mbH & Co. KG in producing this work. // #ifndef TEST6_H #define TEST6_H #include <iostream> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/symmetric.hpp> #include <boost/numeric/ublas/io.hpp> namespace ublas = boost::numeric::ublas; template<class V> void initialize_vector (V &v) { int size = v.size (); for (int i = 0; i < size; ++ i) v [i] = i + 1.f; } template<class M> void initialize_matrix (M &m, ublas::lower_tag) { int size1 = m.size1 (); // int size2 = m.size2 (); for (int i = 0; i < size1; ++ i) { int j = 0; for (; j <= i; ++ j) m (i, j) = i * size1 + j + 1.f; // for (; j < size2; ++ j) // m (i, j) = 0.f; } } template<class M> void initialize_matrix (M &m, ublas::upper_tag) { int size1 = m.size1 (); int size2 = m.size2 (); for (int i = 0; i < size1; ++ i) { int j = 0; // for (; j < i; ++ j) // m (i, j) = 0.f; for (; j < size2; ++ j) m (i, j) = i * size1 + j + 1.f; } } template<class M> void initialize_matrix (M &m) { int size1 = m.size1 (); int size2 = m.size2 (); for (int i = 0; i < size1; ++ i) for (int j = 0; j < size2; ++ j) m (i, j) = i * size1 + j + 1.f; } void test_matrix_vector (); void test_matrix (); // Disable some tests for truly broken compilers // MSVC Version 6.0 & 7.0 have problems compiling with std::complex #if defined(BOOST_MSVC) && (BOOST_MSVC <= 1300) #undef USE_STD_COMPLEX #endif // Intel for Windows fails to link when a std::complex is returned! #if defined(BOOST_INTEL_CXX_VERSION) && (BOOST_INTEL_CXX_VERSION <= 800) && defined(__ICL) #undef USE_STD_COMPLEX #endif #endif
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 87 ] ] ]
20e7cbd430befb857b05d5da9846c40e16e16d1e
f7ddec2c1659cf8db57e8f80e01fa99bfee8ccd8
/ll.cpp
d9943df72e7150109c3a435514cfd751c107af6c
[ "MIT" ]
permissive
bloopletech/c_apps
b0a7e311019b60b183a9c762c549f2d39af1c790
1ae758daf3f155c7e4e356a5e13031fe7c578127
refs/heads/master
2020-04-13T16:51:14.128560
2009-09-13T15:34:51
2009-09-13T15:34:51
305,796
7
0
null
null
null
null
UTF-8
C++
false
false
273
cpp
ll:ll(void* inEle, type inType) { e = inEle; t = inType; } void ll::~ll() { prev.next = next; next.prev = prev; free(e); } //adds supplied node to end of this node void add(ll* newnode) { next = newnode; newnode.prev = this; }
[ [ [ 1, 21 ] ] ]
bcfe55a7a7e98fddb43f0d0fb2e18b4cf3abff0e
9d6d89a97c85abbfce7e2533d133816480ba8e11
/src/Engine/Loader/Loader.h
965525d1cdb711bee85ada67b53fc261b44528a3
[]
no_license
polycraft/Bomberman-like-reseau
1963b79b9cf5d99f1846a7b60507977ba544c680
27361a47bd1aa4ffea972c85b3407c3c97fe6b8e
refs/heads/master
2020-05-16T22:36:22.182021
2011-06-09T07:37:01
2011-06-09T07:37:01
1,564,502
1
2
null
null
null
null
UTF-8
C++
false
false
557
h
#ifndef LOADER_H #define LOADER_H #include <string> #include "../Ressource.h" using namespace std; namespace Engine { /** Interface d'un loader **/ class Loader { public: /** Charge une ressource **/ virtual Ressource *load(string &name)=0; /** Libere une ressource **/ virtual void free(Ressource &ressource) throw(ExceptionBadRessource) =0 ; virtual ~Loader(){}; protected: Loader(){};//Classe abstraite }; } #endif // LOADER_H
[ [ [ 1, 2 ], [ 10, 10 ], [ 13, 15 ], [ 26, 27 ], [ 29, 29 ], [ 31, 32 ] ], [ [ 3, 9 ], [ 11, 12 ], [ 16, 25 ], [ 28, 28 ], [ 30, 30 ], [ 33, 33 ] ] ]
e5aa2222f83b3e905f2f24734d688da96518a07f
e3f815578cddc697693b7b8c8820a3bbba80872f
/source/Presentation/OdfPowerPointAddinShim/ConnectProxy.cpp
a97bda3648fe5b5b8c82518e77972aaf5ec11405
[]
no_license
zhf1127/zlib123
e9b9490fc2e3093f5541dc3bf4bee8d811936ad4
a678ee41d1d8676383dfea17b35f5a31df88e111
refs/heads/master
2020-12-09T19:47:56.108101
2010-06-16T11:59:17
2010-06-16T11:59:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,118
cpp
// ConnectProxy.cpp #include "stdafx.h" #include "CLRLoader.h" #include "ConnectProxy.h" #include "Config.h" CConnectProxy::CConnectProxy() : m_pConnect(NULL), m_pCLRLoader(NULL), m_pUnknownInner(NULL) { } HRESULT CConnectProxy::FinalConstruct() { HRESULT hr = S_OK; IUnknown* pUnkThis = NULL; // Instantiate the CLR-loader object. m_pCLRLoader = new (std::nothrow) CCLRLoader(); IfNullGo( m_pCLRLoader ); IfFailGo( this->QueryInterface(IID_IUnknown, (LPVOID*)&pUnkThis) ); // Load the CLR, create an AppDomain, and instantiate the target add-in // and the inner aggregated object of the shim. IfFailGo( m_pCLRLoader->CreateAggregatedAddIn( pUnkThis, szAddInAssemblyName, szConnectClassName, szAssemblyConfigName) ); // Extract the IDTExtensibility2 interface pointer from the target add-in. IfFailGo( m_pUnknownInner->QueryInterface( __uuidof(IDTExtensibility2), (LPVOID*)&this->m_pConnect) ); Error: if (pUnkThis != NULL) pUnkThis->Release(); return hr; } // Cache the pointer to the aggregated innner object, and make sure // we increment the refcount on it. HRESULT __stdcall CConnectProxy::SetInnerPointer(IUnknown* pUnkInner) { if (pUnkInner == NULL) { return E_POINTER; } if (m_pUnknownInner != NULL) { return E_UNEXPECTED; } m_pUnknownInner = pUnkInner; m_pUnknownInner->AddRef(); return S_OK; } // IDTExtensibility2 implementation: OnConnection, OnAddInsUpdate and // OnStartupComplete are simple pass-throughs to the proxied managed // add-in. We only need to wrap IDTExtensibility2 because we need to // add behavior to the OnBeginShutdown and OnDisconnection methods. HRESULT __stdcall CConnectProxy::OnConnection( IDispatch * Application, ext_ConnectMode ConnectMode, IDispatch *AddInInst, SAFEARRAY **custom) { return m_pConnect->OnConnection( Application, ConnectMode, AddInInst, custom); } HRESULT __stdcall CConnectProxy::OnAddInsUpdate(SAFEARRAY **custom) { return m_pConnect->OnAddInsUpdate(custom); } HRESULT __stdcall CConnectProxy::OnStartupComplete(SAFEARRAY **custom) { return m_pConnect->OnStartupComplete(custom); } // When the host application shuts down, it calls OnBeginShutdown, // and then OnDisconnection. We must be careful to test that the add-in // pointer is not null, to allow for the case where the add-in was // previously disconnected prior to app shutdown. HRESULT __stdcall CConnectProxy::OnBeginShutdown(SAFEARRAY **custom) { HRESULT hr = S_OK; if (m_pConnect) { hr = m_pConnect->OnBeginShutdown(custom); } return hr; } // OnDisconnection is called if the user disconnects the add-in via the COM // add-ins dialog. We wrap this so that we can make sure we can clean up // the reference we're holding to the inner object. We must also allow for // the possibility that the user has disconnected the add-in via the COM // add-ins dialog or programmatically: in this scenario, OnDisconnection is // called first, and this add-in never gets the OnBeginShutdown call // (because it has already been disconnected by then). HRESULT __stdcall CConnectProxy::OnDisconnection( ext_DisconnectMode RemoveMode, SAFEARRAY **custom) { HRESULT hr = S_OK; hr = m_pConnect->OnDisconnection(RemoveMode, custom); if (SUCCEEDED(hr)) { m_pConnect->Release(); m_pConnect = NULL; } return hr; } // Make sure we unload the AppDomain, and clean up our references. // FinalRelease will be the last thing called in the shim/add-in, after // OnBeginShutdown and OnDisconnection. void CConnectProxy::FinalRelease() { // Release the aggregated inner object. if (m_pUnknownInner) { m_pUnknownInner->Release(); } // Unload the AppDomain, and clean up. if (m_pCLRLoader) { m_pCLRLoader->Unload(); delete m_pCLRLoader; m_pCLRLoader = NULL; } }
[ "satish_son@24c45a59-3718-0410-950f-d1d872dd8675" ]
[ [ [ 1, 132 ] ] ]
4bff3628dad0f18e1573a272ce0076ecef326ae0
2ba3bfd31fa7e7d4ca9bd2657c607f57993e3316
/about.cpp
d564e13901232246c534db00782c01ba5daa6a76
[]
no_license
DTTKillASmallScale/kbsizer
d5a870b2239038f44aacc11e704a998a829b891a
52323ec22fb3948e9fa7fa8c9df938990598b97d
refs/heads/master
2021-01-17T11:35:40.259654
2007-11-02T07:00:15
2007-11-02T07:00:15
38,954,920
1
0
null
2015-07-12T08:21:46
2015-07-12T08:21:46
C++
UTF-8
C++
false
false
278
cpp
#include "kbSizer.h" #include <shlwapi.h> #include "version.h" void ShowAbout(HWND /*hwndParent*/) { TCHAR content[256] = {0}; wnsprintf(content, 256, TEXT("kbSizer %s\n\[email protected]"), VERSION); MessageBox(NULL, content, TEXT("kbSizer"), MB_OK); }
[ "wctang@41ce1f99-ec3d-0410-8b29-7d57c04839ee" ]
[ [ [ 1, 10 ] ] ]
bb513d4a3903716857eaead37612cb95195fb8cc
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/stdlith/helpers.cpp
7c3828665bc4817fc80f9430e080aa27318f70e5
[]
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
5,356
cpp
//------------------------------------------------------------------ // // FILE : Helpers.cpp // // PURPOSE : Implements the CHelpers class. // // CREATED : November 26 1996 // // COPYRIGHT : Microsoft 1996 All Rights Reserved // //------------------------------------------------------------------ // Includes.... #ifdef _WINDOWS #include <windows.h> #endif #include <ctype.h> #include "helpers.h" #include "stdlithdefs.h" static char g_UpperTable[256]; static CHelpers g_Helpers; CHelpers::CHelpers() { for( uint32 i=0; i < 256; i++ ) g_UpperTable[i] = (char)toupper( i ); } LTBOOL CHelpers::UpperStrcmp( const char *pInputString1, const char *pInputString2 ) { int curPos=0; unsigned char *pStr1 = (unsigned char*)pInputString1, *pStr2 = (unsigned char*)pInputString2; while(1) { if( g_UpperTable[pStr1[curPos]] != g_UpperTable[pStr2[curPos]] ) return FALSE; if( pStr1[curPos] == 0 ) return TRUE; ++curPos; } return FALSE; } #ifdef _WINDOWS LTBOOL CHelpers::ExtractFullPath( const char *pInPath, char *pOutPath, uint32 outPathLen ) { char *pFilePart; if( ::GetFullPathName(pInPath, outPathLen, pOutPath, &pFilePart) == 0 ) strcpy( pOutPath, pInPath ); return TRUE; } #endif LTBOOL CHelpers::ExtractPathAndFileName( const char *pInputPath, char *pPathName, char *pFileName ) { char delimiters[2]; int i, len, lastDelimiter; delimiters[0] = '\\'; delimiters[1] = '/'; pPathName[0] = pFileName[0] = 0; len = strlen(pInputPath); lastDelimiter = -1; for( i=0; i < len; i++ ) { if( pInputPath[i] == delimiters[0] || pInputPath[i] == delimiters[1] ) { lastDelimiter = i; } } if( lastDelimiter == -1 ) { pPathName[0] = 0; strcpy( pFileName, pInputPath ); } else { memcpy( pPathName, pInputPath, lastDelimiter ); pPathName[lastDelimiter] = 0; memcpy( pFileName, &pInputPath[lastDelimiter+1], len-lastDelimiter ); pFileName[len-lastDelimiter] = 0; } return TRUE; } LTBOOL CHelpers::ExtractFileNameAndExtension( const char *pInputFilename, char *pFilename, char *pExtension ) { int i, len, lastDot; char delimiter = '.'; len = strlen(pInputFilename); lastDot = len; for( i=0; i < len; i++ ) { if( pInputFilename[i] == delimiter ) { lastDot = i; } } memcpy( pFilename, pInputFilename, lastDot ); pFilename[lastDot] = 0; memcpy( pExtension, &pInputFilename[lastDot+1], len-lastDot ); pExtension[len-lastDot] = 0; return TRUE; } LTBOOL CHelpers::ExtractNames( const char *pFullPath, char *pPathname, char *pFilename, char *pFileTitle, char *pExt ) { char pathName[256], fileName[256], fileTitle[256], ext[256]; ExtractPathAndFileName( pFullPath, pathName, fileName ); ExtractFileNameAndExtension( fileName, fileTitle, ext ); if( pPathname ) strcpy( pPathname, pathName ); if( pFilename ) strcpy( pFilename, fileName ); if( pFileTitle ) strcpy( pFileTitle, fileTitle ); if( pExt ) strcpy( pExt, ext ); return TRUE; } char* CHelpers::GetNextDirName( char *pIn, char *pOut ) { uint32 len = strlen(pIn); uint32 inPos=0, outPos=0; // Skip \ characters. while( (pIn[inPos] == '/') || (pIn[inPos] == '\\') ) inPos++; if( pIn[inPos] == 0 ) return NULL; while( (pIn[inPos] != '/') && (pIn[inPos] != '\\') && (pIn[inPos] != 0) ) pOut[outPos++] = pIn[inPos++]; pOut[outPos] = 0; return &pIn[inPos]; } //determines if the file is relative, or is an absolute path (uses the : as a key) LTBOOL CHelpers::IsFileAbsolute(const char* pFilename) { for(uint32 nCurrChar = 0; (pFilename[nCurrChar] != '\0') && (pFilename[nCurrChar] != '\\') && (pFilename[nCurrChar] != '/'); nCurrChar++) { //we hit a colon before the slash or end of the string, //this means that it is absolute if(pFilename[nCurrChar] == ':') { return TRUE; } } return FALSE; } //takes a filename, and removes the extension from it (including the .) void CHelpers::RemoveExtension(char* pFilename) { //go to the very end of the string int32 nCurrPos = strlen(pFilename) - 1; //now we go backwards looking for a dot, or a slash for(;nCurrPos >= 0; nCurrPos--) { //if we have hit a . we need to truncate there if(pFilename[nCurrPos] == '.') { pFilename[nCurrPos] = '\0'; } //see if we have hit a slash and need to end if( (pFilename[nCurrPos] == '\\') || (pFilename[nCurrPos] == '/')) { break; } } } // ---------------------------------------------------------------- // FormatFilename( in-name, out-name, out-name-length ) // // Convert all the dos like path delimiters to unix like on unix // platform and vis-versa on winX platforms. // ---------------------------------------------------------------- void CHelpers::FormatFilename(const char *pFilename, char *pOut, int outLen) { if( !pFilename ) { pOut[0] = '\0'; return; } strncpy(pOut, pFilename, outLen); pOut[outLen-1] = 0; #if defined(__LINUX) while(*pOut != 0) { *pOut = tolower(*pOut); if(*pOut == '\\') *pOut = '/'; ++pOut; } #else strupr(pOut); while(*pOut != 0) { if(*pOut == '/') *pOut = '\\'; ++pOut; } #endif }
[ [ [ 1, 254 ] ] ]
7894cd052994d6609994d86fd1d9aa5dfc95dfd1
e537c879c7f7777d649121eee4b3f1fbff1e07c8
/modules/LogManServer/LogManServer_SocketTimeOutNotify.h
fe3633e7fb8f43f46483755c5fd0dadccf63980e
[]
no_license
SymbiSoft/logman-for-symbian
1181007a28a6d798496bb7e1107d1bce366becdd
cd0de1cf1afef03df09622e3d1db6c8bddbd324b
refs/heads/master
2021-01-10T15:04:55.032082
2010-05-11T13:26:07
2010-05-11T13:26:07
48,182,126
0
0
null
null
null
null
UTF-8
C++
false
false
238
h
#ifndef MSOCKET_TIMEOUTNOTIFY_H #define MSOCKET_TIMEOUTNOTIFY_H /** * Interface for notifing timer's timeout. */ class MSocketTimeOutNotify { public: virtual void TimerExpired() = 0; }; #endif // MSOCKET_TIMEOUTNOTIFY_H
[ "jtoivola@localhost" ]
[ [ [ 1, 13 ] ] ]
d16c73aba91ec219cc878994e3ae18853c34297e
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleSocial/IPad/IPadSocialNetworkingPlatform_AGONOnline.h
3b200ee0038158d84b9066a711a068a5a3dbd661
[]
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
1,423
h
/* * IPadSocialNetworkingPlatform_AGONOnline.h * TootleSocial * * Created by Duane Bradbury on 28/08/2009. * Copyright 2009 Tootle. All rights reserved. * */ // If you use this you will also need to link with the AGON library. // To do that add the following to your project build settings: // Other Linker Flags // Debug - "-lagond" // Release - "-lagon" // Library Search Paths // All - "../../../Tootle/Code/TootleSocial/IPod/libagon/lib/$(SDK_NAME)" // // Additionally you will need to add some bundles to your project resources: // AgonData.bundle - found in the libagon/resources directory // AgonPackage.bundle - project specific and is downloaded from the AGON online developer site. #pragma once #include <TootleCore/TLTypes.h> #include <TootleCore/TString.h> #include <TootleCore/TLMessaging.h> namespace TLSocial { namespace Platform { // Social Networking platform policy AGON Online class SocialNetworkingPlatform_AGONOnline { public: Bool CreateSession(TLMessaging::TMessage& InitMessage); void DestroySession(); void BeginSession(); void EndSession(); void OpenDashboard(); void OpenLeaderboard(); void SubmitScore(const s32& Score, const TString& Format, const s32& LeaderboardID); protected: ~SocialNetworkingPlatform_AGONOnline() {} }; } }
[ [ [ 1, 55 ] ] ]
9a2445b5934ebf6180e11ca201b37b735439a065
079eb7911ed82cf38743cf8a9ac5ccf94e526144
/lib/line.h
8e303f700e09a4c0f8e951f629a2bba599ffeace
[]
no_license
petcomputacaoufrgs/robopet
c2d380e548807e9ac22e4b0ad86a9db813e842ed
509142eb7ab2c5530ab517b212c6c79aedc87442
refs/heads/master
2021-01-01T16:06:01.149835
2011-10-31T15:10:49
2011-10-31T15:10:49
32,540,402
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
h
#ifndef _RETA_H_ #define _RETA_H_ #include "vector.h" #include "point.h" #define ANGULO_ZERO 0.0000001 using RP::Line; /** * Represents a line in the plane * \ingroup RoboPETLib * */ class Line { public: Line(); Line(Vector v); Line(Vector v, Point p); Line(Point p1, Point p2); Line(double a, double b); //----- Getters ----- inline Vector getVector() const { return _vector; } inline Point getPoint() const { return _point; } double getAngularCoefficient() const; double getLinearCoefficient() const; //----- Setters ----- inline void setVector(const Vector &v) { _vector = v; } inline void setPoint(Point p) { _point = p; } void setAngularCoefficient(double a); void setLinearCoefficient(double b); //----- Others ----- /** *@return The line perpendicular to this one.*/ Line getPerpendicular() const; /** *Determinate if two lines intersect themselves*/ bool intersects(const Line &r) const; /** *@return The intersection point between two lines*/ Point intersection(const Line &r) const; /** *Determines if two lines are parallel*/ bool parallel(const Line &r) const; /** *Determines the smallest non-negative angle between two lines (in radians)*/ double angle(const Line &r) const; /** *Determines if two lines are perpendicular each other */ bool perpendicular(const Line &r) const; /** *Determines if the line contains a point */ bool contains(const Point &p) const; /** *Determines if a line is vertical*/ bool vertical() const; /** *Determines if a line is horizontal*/ bool horizontal() const; /** Determines the image (y) of a value in line @param x value*/ double image(double x) const; /** Determines the pre-image (x) of a value on the line @param y value*/ double preImage(double y) const; /** Determines the distance between a point and a line @param p point*/ double distance(const Point &p) const; /** Determines the distance between two lines @param r another straight*/ double distance(const Line &r) const; bool operator==(const Line &r) const; private: Vector _vector; Point _point; }; #endif // _LINE_H_
[ "ninja.dalbem@b2abf0a2-074e-11df-beaf-bb271b2086c6", "Miller.Biazus@b2abf0a2-074e-11df-beaf-bb271b2086c6", "dennisgiovani@b2abf0a2-074e-11df-beaf-bb271b2086c6" ]
[ [ [ 1, 9 ], [ 15, 33 ], [ 35, 43 ], [ 46, 46 ], [ 50, 50 ], [ 54, 54 ], [ 58, 58 ], [ 62, 62 ], [ 66, 66 ], [ 70, 70 ], [ 74, 75 ], [ 79, 80 ], [ 84, 85 ], [ 89, 90 ], [ 94, 99 ], [ 101, 108 ] ], [ [ 10, 14 ], [ 76, 77 ], [ 81, 82 ], [ 86, 87 ], [ 91, 92 ], [ 100, 100 ] ], [ [ 34, 34 ], [ 44, 45 ], [ 47, 49 ], [ 51, 53 ], [ 55, 57 ], [ 59, 61 ], [ 63, 65 ], [ 67, 69 ], [ 71, 73 ], [ 78, 78 ], [ 83, 83 ], [ 88, 88 ], [ 93, 93 ] ] ]
1a09384efc09621f503a82cc9bafa4d2701b233f
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/queue/queue_sort_1.h
a77e17629fe68ad249d9c3a748d752aff87c9403
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
5,226
h
// Copyright (C) 2003 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_QUEUE_SORt_1_ #define DLIB_QUEUE_SORt_1_ #include "queue_sort_abstract.h" #include "../algs.h" #include <vector> #include "../sort.h" namespace dlib { template < typename queue_base > class queue_sort_1 : public queue_base { typedef typename queue_base::type T; public: /*! This implementation uses the QuickSort algorithm and when the quicksort depth goes too high it uses the dlib::qsort_array() function on the data. !*/ void sort ( ); template <typename compare_type> void sort ( const compare_type& compare ) { if (this->size() > 1) { sort_this_queue(*this,0,compare); } } private: template <typename compare_type> void sort_this_queue ( queue_base& queue, long depth, const compare_type& compare ) /*! ensures each element in the queue is < the element behind it according to compare !*/ { if (queue.size() <= 1) { // already sorted } else if (queue.size() <= 29) { T vect[29]; const unsigned long size = queue.size(); for (unsigned long i = 0; i < size; ++i) { queue.dequeue(vect[i]); } isort_array(vect,0,size-1,compare); for (unsigned long i = 0; i < size; ++i) { queue.enqueue(vect[i]); } } else if (depth > 50) { std::vector<T> vect(queue.size()); for (unsigned long i = 0; i < vect.size(); ++i) { queue.dequeue(vect[i]); } hsort_array(vect,0,vect.size()-1,compare); for (unsigned long i = 0; i < vect.size(); ++i) { queue.enqueue(vect[i]); } } else { queue_base left, right; T partition_element; T temp; // do this just to avoid a compiler warning assign_zero_if_built_in_scalar_type(temp); assign_zero_if_built_in_scalar_type(partition_element); queue.dequeue(partition_element); // partition queue into left and right while (queue.size() > 0) { queue.dequeue(temp); if (compare(temp , partition_element)) { left.enqueue(temp); } else { right.enqueue(temp); } } long ratio; if (left.size() > right.size()) ratio = left.size()/(right.size()+1); // add 1 so we can't divide by zero else ratio = right.size()/(left.size()+1); sort_this_queue(left,ratio+depth,compare); sort_this_queue(right,ratio+depth,compare); // combine the two queues left.swap(queue); queue.enqueue(partition_element); queue.cat(right); } } }; template < typename queue_base > inline void swap ( queue_sort_1<queue_base>& a, queue_sort_1<queue_base>& b ) { a.swap(b); } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // member function definitions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename queue_base > void queue_sort_1<queue_base>:: sort ( ) { if (this->size() > 1) { sort_this_queue(*this,0,std::less<typename queue_base::type>()); } } // ---------------------------------------------------------------------------------------- } #endif // DLIB_QUEUE_SORt_1_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 165 ] ] ]
c82f49f27d9bf8dc2ec967c1897b886e47383348
41371839eaa16ada179d580f7b2c1878600b718e
/SUB-REGIONAL/2006/circuito.cpp
a64c6d0152f1ab90fe8c1f776712e40a8907da8c
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
#include <cstdio> #define P 1024 int p, n, c; int b[P], d[P]; int ans; int main(void) { int i; while(scanf("%d %d %d", &p, &n, &c)) { if(p == 0 && n == 0 && c == 0) break; for(i = 0; i < p; i++) d[i] = 0; ans = 0; while(n--) { for(i = 0; i < p; i++) { scanf("%d", &b[i]); if(b[i]) d[i]++; else { if(d[i] >= c) ans++; d[i] = 0; } } } for(i = 0; i < p; i++) if(d[i] >= c) ans++; printf("%d\n", ans); } return 0; }
[ [ [ 1, 35 ] ] ]
3c123dc287aed1ac57d0979acef4c80e17587411
ffb363eadafafb4b656355b881395f8d59270f55
/my/ode_example/hodgkin_huxley/main.cpp
301cb31dd5ec8c2bd41146b7841ca9a8a7a1e30c
[ "MIT" ]
permissive
hanji/matrix
1c28830eb4fdb7eefe21b2f415a9ec354e18f168
9f3424628ab182d249c62aeaf4beb4fb2d073518
refs/heads/master
2023-08-08T07:36:26.581667
2009-12-03T06:25:24
2009-12-03T06:25:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
#include <iostream> #include "my/vector.hpp" #include "ode/runge_kutta.hpp" #include "hodgkin_huxley.hpp" int main() { ODE::RK4(hh::f, hh::init(), hh::T0, hh::T_MAX, hh::STEP_SIZE); return 0; }
[ "[email protected]@2159fae2-c2cd-11de-acfc-b766374499fb" ]
[ [ [ 1, 15 ] ] ]
8712adb3ceba8d6bf16137128f410842fbf3103c
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Core/EventSubscriber.cpp
487eb3bcc059600f7e2067d45c3a2f0e24d90e00
[]
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
554
cpp
#include "EventSubscriber.hpp" #include "EventData.hpp" using namespace Spiral; void EventSubscriber::AddCallback( EventCallbackFunc func ) { m_callBacks.push_back( func ); } void EventSubscriber::Recieve( const detail::EventData& data ) const { typedef std::list< EventCallbackFunc >::const_iterator const_itr; for( const_itr itr = m_callBacks.begin(); itr != m_callBacks.end(); ++itr ) { (*itr)( data.event, data.data ); } } EventSubscriber::EventSubscriber( const Event& event ): m_event( event ), m_callBacks() { }
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 25 ] ] ]
5fd5d70e56bfb973fb1ee35c087b691a206b02b1
dd5c8920aa0ea96607f2498701c81bb1af2b3c96
/multicrewui/main.cpp
ad0ca372093d465201ebacd3ab01b08cd4fc1890
[]
no_license
BackupTheBerlios/multicrew-svn
913279401e9cf886476a3c912ecd3d2b8d28344c
5087f07a100f82c37d2b85134ccc9125342c58d1
refs/heads/master
2021-01-23T13:36:03.990862
2005-06-10T16:52:32
2005-06-10T16:52:32
40,747,367
0
0
null
null
null
null
UTF-8
C++
false
false
5,605
cpp
/* Microsoft Flight Simulator 2004 Module Example. * * Copyright (c) 2004, Cyril Hruscak. * You may freely redistribute and/or modify this code provided this copyright * notice remains unchanged. Usage of the code is at your own risk. I accept * no liability for any possible damage using this code. * * It shows how to create a module dll ("Modules" directory of the main * FS directory) that can be loaded by the FS2004. It also shows how to add * a new menu entry to the main flight simulator menu. */ #include "common.h" #include <wx/wx.h> #include <windows.h> #include "multicrewui.h" #include "../multicrewgauge/GAUGES.h" #include "../multicrewcore/thread.h" /************************** gauge/module linkage ****************************/ void FSAPI module_init(void) { } void FSAPI module_deinit(void) { } GAUGESLINKAGE Linkage = { 0x00000000, module_init, module_deinit, 0, 0, 0x0900, // FS2004 version (use 0x0800 for FS2002) NULL }; GAUGESIMPORT ImportTable; /*************************** Win32 window management *************************/ class wxDLLApp : public wxApp { bool OnInit() { return true; } }; IMPLEMENT_APP_NO_MAIN(wxDLLApp) WNDPROC oldWndProc; HWND hFSimWindow; HINSTANCE gInstance; #define MENU_ENTRY "Multi&crew" LRESULT CALLBACK FSimWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); /*************************** ui thread ***************************************/ class UIThread : public Thread { public: UIThread() { startThread( 0 ); // load multicrewgauge.dll (it mustn't be unloaded because then // the hooks get invalid and might produce crashes) dout << "Loading multicrewgauge.dll" << std::endl; hMulticrewGauge = LoadLibrary( "multicrew\\multicrewgauge.dll" ); } virtual ~UIThread() { // stop ui thread postThreadMessage( WM_QUIT, 0, 0 ); stopThread(); } virtual unsigned threadProc( void *param ) { // setup wx wxEntry( gInstance, 0, NULL, 0, false ); // setup ui dout << "Creating MulticrewUI" << std::endl; ui = new MulticrewUI( hFSimWindow ); // hook FS window oldWndProc = (WNDPROC)SetWindowLong( hFSimWindow, GWL_WNDPROC, (LONG)FSimWindowProc ); // thread message queue MSG msg; BOOL ret; dout << "Starting MulticrewUI thread" << std::endl; while( (ret=GetMessage( &msg, NULL, 0, 0 ))!=0 ) { //dout << "MulticrewUI thread message " << msg.message << std::endl; switch( msg.message ) { case WM_COMMAND: { //dout << "message was WM_COMMAND " << LOWORD(msg.wParam) << std::endl; switch( LOWORD(msg.wParam) ) { case ID_HOST_MENUITEM: ui->host(); break; case ID_CONNECT_MENUITEM: ui->connect(); break; case ID_DISCONNECT_MENUITEM: ui->disconnect(); break; case ID_STATUS_MENUITEM: ui->status(); break; case ID_LOG: ui->log(); break; //case ID_ASYNC: ui->async(); break; } } break; } DispatchMessage(&msg); } // shutdown ui dout << "Shutting down MulticrewUI" << std::endl; delete ui; // shutdown wx wxGetApp().OnExit(); wxApp::CleanUp(); //wxEntryCleanup(); // crashes :( //wxUninitialize(); return true; } MulticrewUI *ui; HMODULE hMulticrewGauge; }; UIThread *uiThread; /*****************************************************************************/ LRESULT CALLBACK FSimWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_NCPAINT: { // add a menu to the fs window HMENU hFSMenu; hFSMenu = GetMenu(hwnd); if( hFSMenu!=NULL ) { int i; // Look for our menu entry in the main menu. for( i=0; i<GetMenuItemCount(hFSMenu); i++ ) { char buf[128]; GetMenuString( hFSMenu, i, buf, 128, MF_BYPOSITION ); if( strcmp(buf, MENU_ENTRY)==0 ) { // It is already here, we do not need to add it again break; } } if( i<GetMenuItemCount(hFSMenu) ) { // It is already here, we do not need to add it again break; } /* Create new menu. NOTE: It seems that this will be * reached more times, so we cannot save the handle, because * in such case it could be destroyed and we will not have * any access to it in the simulator. */ // add the created menu to the main menu AppendMenu(hFSMenu, MF_STRING | MF_POPUP, (UINT_PTR)uiThread->ui->newMenu(), MENU_ENTRY); } }break; case WM_COMMAND: { if( LOWORD(wParam)>=ID_FIRST && LOWORD(wParam)<=ID_LAST ) uiThread->postThreadMessage( uMsg, wParam, lParam ); else switch( LOWORD(wParam) ) { case ID_ASYNC: uiThread->ui->async(); //dout << "async" << std::endl; break; } } break; } // Call the original window procedure to handle all other messages return CallWindowProc(oldWndProc, hwnd, uMsg, wParam, lParam); } /*****************************************************************************/ BOOL WINAPI DllMain( HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved ) { switch( fdwReason ) { case DLL_PROCESS_ATTACH: { OutputDebugString( "Loading MulticrewUI\n" ); hFSimWindow = FindWindow("FS98MAIN", NULL); gInstance = hInstDLL; uiThread = new UIThread(); OutputDebugString( "Loaded MulticrewUI\n" ); } break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: { OutputDebugString( "Unloading MulticrewUI\n" ); delete uiThread; OutputDebugString( "Unloaded MulticrewUI\n" ); } break; } return TRUE; }
[ "schimmi@cb9ff89a-abed-0310-8fc6-a4cabe7d48c9" ]
[ [ [ 1, 206 ] ] ]
b698b4265d4f524c3b0b10e34ec3a396692a8704
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/imglib/inc/h_utl.h
da7b7ca5d9f5d418fd40fba478dd35f2a8809f27
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,795
h
/* * Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #if !defined(__H_UTL_H__) #define __H_UTL_H__ // #include <stdio.h> #ifdef _MSC_VER #if (_MSC_VER > 1200) //!__MSVCDOTNET__ #define __MSVCDOTNET__ 1 #include <iostream> #include <sstream> #include <fstream> using namespace std; #else //!__MSVCDOTNET__ #include <iostream.h> #include <strstrea.h> #include <fstream.h> #endif //__MSVCDOTNET__ #else //!__VC32__ #ifdef __TOOLS2__ #include <fstream> #include <iostream> #include <sstream> #include <iomanip> using namespace std; #else // !__TOOLS2__ OR __VC32__ OR __MSVCDOTNET__ #include <iostream.h> #include <strstream.h> #include <fstream.h> #endif #endif #ifdef __LINUX__ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <ctype.h> #define _close close #define _filelength filelength #define _lseek lseek #define _read read #define _snprintf snprintf #define _vsnprintf vsnprintf // linux case insensitive stromg comparisons have different names #define stricmp strcasecmp #define _stricmp strcasecmp #define strnicmp strncasecmp // to fix the linux problem: memcpy does not work with overlapped areas. #define memcpy memmove #define SLASH_CHAR '/' // hand-rolled strupr function for converting a string to all uppercase char* strupr(char *a); // return the length of a file off_t filelength (int filedes); #else #define SLASH_CHAR '\\' #endif #include <e32cmn.h> #include <e32def.h> #define ALIGN4K(a) ((a+0xfff)&0xfffff000) #define ALIGN4(a) ((a+0x3)&0xfffffffc) #ifdef HEAPCHK #define NOIMAGE #define WIN32_LEAN_AND_MEAN #include <windows.h> void HeapCheck(); #endif #define Print H.PrintString // const TInt KMaxStringLength=0x800; // class HFile { public: static TBool Open(const char* aFileName, TInt32 * const aFileHandle); static TBool Read(const TInt32 aFileHandle, TAny * const aBuffer, const TUint32 aCount); static TBool Seek(const TInt32 aFileHandle, const TUint32 aOffset); static TUint32 GetPos(const TInt32 aFileHandle); static TAny Close(const TInt32 aFileHandle); static TUint32 GetLength(const TInt32 aFileHandle); static TUint32 GetLength(const char* aName); static TUint32 Read(const char* aName, TAny *someMem); }; // //inline TAny* operator new(TUint /*aSize*/, TAny* aBase) // {return aBase;} class HMem { public: static TAny *Alloc(TAny * const aBaseAddress,const TUint32 aImageSize); static void Free(TAny * const aMem); static void Copy(TAny * const aDestAddr,const TAny * const aSourceAddr,const TUint32 aLength); static void Move(TAny * const aDestAddr,const TAny * const aSourceAddr,const TUint32 aLength); static void Set(TAny * const aDestAddr, const TUint8 aFillChar, const TUint32 aLength); static void FillZ(TAny * const aDestAddr, const TUint32 aLength); static TUint CheckSum(TUint *aPtr, TInt aSize); static TUint CheckSum8(TUint8 *aPtr, TInt aSize); static TUint CheckSumOdd8(TUint8 *aPtr, TInt aSize); static TUint CheckSumEven8(TUint8 *aPtr, TInt aSize); static void Crc32(TUint32& aCrc, const TAny* aPtr, TInt aLength); }; // enum TPrintType {EAlways, EScreen, ELog, EWarning, EError, EPeError, ESevereError, EDiagnostic}; // class HPrint { public: ~HPrint(); void SetLogFile(const char* aFileName); void CloseLogFile(); // Added to close intermediate log files. TInt PrintString(TPrintType aType,const char *aFmt,...); public: char iText[KMaxStringLength]; TBool iVerbose; private: ofstream iLogFile; }; // extern HPrint H; extern TBool PVerbose; // TAny *operator new(TUint aSize); void operator delete(TAny *aPtr); // #if defined(__TOOLS2__) || defined(__MSVCDOTNET__) istringstream &operator>>(istringstream &is, TVersion &aVersion); #else istrstream &operator>>(istrstream &is, TVersion &aVersion); #endif // TInt StringToTime(TInt64 &aTime, char *aString); void ByteSwap(TUint &aVal); void ByteSwap(TUint16 &aVal); void ByteSwap(TUint *aPtr, TInt aSize); extern TBool gLittleEndian; /** Convert string to number. */ template <class T> TInt Val(T& aVal, const char* aStr) { T x; #if defined(__TOOLS2__) || defined(__MSVCDOTNET__) istringstream val(aStr); #else istrstream val((char*)aStr,strlen(aStr)); #endif #if defined (__TOOLS2__) || defined(__MSVCDOTNET__) val >> setbase(0); #endif //__MSVCDOTNET__ val >> x; if (!val.eof() || val.fail()) return KErrGeneral; aVal=x; return KErrNone; } // Filename decompose routines enum TDecomposeFlag { EUidPresent=1, EVerPresent=2 }; class TFileNameInfo { public: TFileNameInfo(const char* aFileName, TBool aLookForUid); const char* iFileName; TInt iTotalLength; TInt iBaseLength; TInt iExtPos; TUint32 iUid3; TUint32 iModuleVersion; TUint32 iFlags; }; extern char* NormaliseFileName(const char* aName); extern char* SplitFileName(const char* aName, TUint32& aUid, TUint32& aModuleVersion, TUint32& aFlags); extern char* SplitFileName(const char* aName, TUint32& aModuleVersion, TUint32& aFlags); extern TInt ParseCapabilitiesArg(SCapabilitySet& aCapabilities, const char *aText); extern TInt ParseBoolArg(TBool& aValue, const char *aText); extern TBool IsValidNumber(const char* aStr); #endif
[ "none@none", "[email protected]" ]
[ [ [ 1, 23 ], [ 27, 27 ], [ 29, 96 ], [ 98, 154 ], [ 156, 176 ], [ 178, 181 ], [ 183, 220 ] ], [ [ 24, 26 ], [ 28, 28 ], [ 97, 97 ], [ 155, 155 ], [ 177, 177 ], [ 182, 182 ] ] ]
3c720e9cb9adf9cdc0558a18404b203271df9e6f
0c930838cc851594c9eceab6d3bafe2ceb62500d
/include/jflib/python/numpy/all.hpp
513710797a1f82acb89dbe408b442afd05b2836a
[ "BSD-3-Clause" ]
permissive
quantmind/jflib
377a394c17733be9294bbf7056dd8082675cc111
cc240d2982f1f1e7e9a8629a5db3be434d0f207d
refs/heads/master
2021-01-19T07:42:43.692197
2010-04-19T22:04:51
2010-04-19T22:04:51
439,289
4
3
null
null
null
null
UTF-8
C++
false
false
206
hpp
#ifndef __JFLIB_NUMPY_ALL_HPP_ #define __JFLIB_NUMPY_ALL_HPP_ namespace jflib { namespace python { namespace numpy { void numpy_expose_converters(); }}} #endif // __JFLIB_NUMPY_ALL_HPP_
[ [ [ 1, 12 ] ] ]
d122d84af4ea357f3f55d4da3d0dced7ae69039e
b0a384b23ac73a66eda9de62be291657bcf1e4c2
/main.cpp
d45f30822d913d84585c58491d3c49a1d0f45c4e
[]
no_license
alrock/awans-thread-safe
348d3906be4389cd74ceec7d64d6fec0c04a7750
775db56483bb724e5f916ad1936a089ed4bf140f
refs/heads/master
2021-01-01T05:38:01.439403
2010-09-23T13:18:18
2010-09-23T13:18:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
cpp
#include <QtCore/QCoreApplication> #include <QString> #include <QDebug> #include <QThreadPool> #include <QRunnable> #include <QSharedPointer> #include "threadsafe.h" QString data1; QSharedPointer<QString> data(&data1); QString *tmp = new QString; class C { public: C() {;} void run1(){ for(int i=0; i<40; i++) { *data = "A"; qDebug() << "A -" << *data; } } void run2(){ for(int i=0; i<40; i++) { *data = "B"; qDebug() << "B -" << *data; } } }; C test_; ThreadSafe<C> test(&test_); ThreadSafe<C> ololo = test; class A: public QRunnable { public: void run() { ThreadLock<C> lock = ololo.lock(); lock = test.lock(); test.lock()->run1(); ololo.lock()->run1(); test.lock()->run1(); ololo.lock()->run1(); /* for(int i=0; i<40; i++) { *data = "A"; qDebug() << "A -" << *data; } */ } }; class B: public QRunnable { public: void run() { test.lock()->run2(); /* for(int i=0; i<40; i++) { *data = "B"; qDebug() << "B -"<< *data; } */ } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QThreadPool pool; test = ololo; pool.start(new A); pool.start(new B); return a.exec(); }
[ [ [ 1, 82 ] ] ]
0c81732ca927c14f605d2b997f3ac733ce13814b
67298ca8528b753930a3dc043972dceab5e45d6a
/FileSharing/src/Mutex.hpp
6305d8b98ceffe61508da531959e85d4d04480eb
[]
no_license
WhyKay92/cs260assignment3
3cf28dd92b9956b2cd4f850652651cb11f25c753
77ad90cd2dc0b44f3ba0a396dc8399021de4faa5
refs/heads/master
2021-05-30T14:59:21.297733
2010-12-13T09:18:17
2010-12-13T09:18:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,343
hpp
/*! * @File Mutex.hpp * @Author Steven Liss and Westley Hennigh * @Date 25 Feb 2010, 20 Oct 2010 * @Brief Mutex interface, wraps critical section. */ #pragma once class Lock; // forward declare for mutex /* Create a mutex (which will wrap up a critical section). When you need to use shared data, create a lock with the mutex you created. The lock will enter the critical section upon construction and then leave upon destruction (so no need to remember to unlock). */ class Mutex { public: Mutex () { InitializeCriticalSection (&CriticalSection); } ~Mutex () { DeleteCriticalSection (&CriticalSection); } private: // Acquire and release will be called by the lock only, there is no // external access. void Acquire () { EnterCriticalSection (&CriticalSection); } void Release () { LeaveCriticalSection (&CriticalSection); } CRITICAL_SECTION CriticalSection; // the critical section for this mutex friend class Lock; template < typename T > friend class SecureObject; }; class Lock { public: // Acquire the semaphore Lock ( Mutex& mutex_ ) : mutex(mutex_) { mutex.Acquire(); } // Release the semaphore ~Lock () { mutex.Release(); } private: Mutex& mutex; // DO NOT CALL Lock& operator = ( Lock& ); };
[ [ [ 1, 69 ] ] ]
4550d51a5767a9c559f3b07295a1fff76bef6e3c
c6311b5096eeed35f7b8cdb5c228de915075eb71
/tp3/Tp_3_Mundial2010v1/TestResultsDialog.h
52344d8faa9ad975fd5301bb32c07069dff08e83
[]
no_license
kevinalle/metnum2010
5dccdba68bb4d3065c6a696f02836e7119eba657
142a5464429e564c13aabd339a7b01800ea9023e
refs/heads/master
2020-05-28T05:01:34.835358
2010-07-23T19:19:27
2010-07-23T19:19:27
32,120,707
0
0
null
null
null
null
UTF-8
C++
false
false
3,436
h
/** \file \author Pablo Haramburu Copyright: Copyright (C)2010 Pablo Haramburu. License: This file is part of mundial2010. mundial2010 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. mundial2010 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 mundial2010. If not, see <http://www.gnu.org/licenses/>. */ // Generated by DialogBlocks (unregistered), 01/06/2010 01:49:44 #ifndef _TESTRESULTSDIALOG_H_ #define _TESTRESULTSDIALOG_H_ /*! * Includes */ ////@begin includes #include "wx/listctrl.h" ////@end includes /*! * Forward declarations */ ////@begin forward declarations class wxListCtrl; ////@end forward declarations /*! * Control identifiers */ ////@begin control identifiers #define ID_TESTRESULTSDIALOG 10006 #define ID_LISTCTRL1 10007 #define ID_LISTCTRL2 10008 #define SYMBOL_TESTRESULTSDIALOG_STYLE wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxMAXIMIZE_BOX|wxMINIMIZE_BOX|wxTAB_TRAVERSAL #define SYMBOL_TESTRESULTSDIALOG_TITLE _("Resultado de las pruebas") #define SYMBOL_TESTRESULTSDIALOG_IDNAME ID_TESTRESULTSDIALOG #define SYMBOL_TESTRESULTSDIALOG_SIZE wxSize(400, 300) #define SYMBOL_TESTRESULTSDIALOG_POSITION wxDefaultPosition ////@end control identifiers /*! * TestResultsDialog class declaration */ class TestResultsDialog: public wxDialog { DECLARE_DYNAMIC_CLASS( TestResultsDialog ) DECLARE_EVENT_TABLE() public: /// Constructors TestResultsDialog(); TestResultsDialog( wxWindow* parent, wxWindowID id = SYMBOL_TESTRESULTSDIALOG_IDNAME, const wxString& caption = SYMBOL_TESTRESULTSDIALOG_TITLE, const wxPoint& pos = SYMBOL_TESTRESULTSDIALOG_POSITION, const wxSize& size = SYMBOL_TESTRESULTSDIALOG_SIZE, long style = SYMBOL_TESTRESULTSDIALOG_STYLE ); /// Creation bool Create( wxWindow* parent, wxWindowID id = SYMBOL_TESTRESULTSDIALOG_IDNAME, const wxString& caption = SYMBOL_TESTRESULTSDIALOG_TITLE, const wxPoint& pos = SYMBOL_TESTRESULTSDIALOG_POSITION, const wxSize& size = SYMBOL_TESTRESULTSDIALOG_SIZE, long style = SYMBOL_TESTRESULTSDIALOG_STYLE ); /// Destructor ~TestResultsDialog(); /// Initialises member variables void Init(); /// Creates the controls and sizers void CreateControls(); ////@begin TestResultsDialog event handler declarations ////@end TestResultsDialog event handler declarations ////@begin TestResultsDialog member function declarations /// Retrieves bitmap resources wxBitmap GetBitmapResource( const wxString& name ); /// Retrieves icon resources wxIcon GetIconResource( const wxString& name ); ////@end TestResultsDialog member function declarations /// Should we show tooltips? static bool ShowToolTips(); ////@begin TestResultsDialog member variables wxListCtrl* m_results; wxListCtrl* m_summary; wxButton* m_cancelBtn; ////@end TestResultsDialog member variables }; #endif // _TESTRESULTSDIALOG_H_
[ "kevinalle@8062f241-9d54-ddaa-24e5-4d4b1e181026" ]
[ [ [ 1, 111 ] ] ]
91d2a144f372fe21ce681e21953b1cd732e68d18
6c8c4728e608a4badd88de181910a294be56953a
/UiModule/Inworld/Notifications/InputNotification.h
1bcd2170e36e64a8f39a7293fb42193dc0873d57
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
826
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_UiModule_InputNotification_h #define incl_UiModule_InputNotification_h #include "NotificationBaseWidget.h" #include "UiModuleApi.h" class QPlainTextEdit; class QLineEdit; class QPushButton; namespace UiServices { class UI_MODULE_API InputNotification : public CoreUi::NotificationBaseWidget { Q_OBJECT public: InputNotification(QString message, QString button_title = "Answer", int hide_in_msec = 5000); signals: void InputRecieved(QString user_input); private slots: void ParseAndEmitInput(); private: QPlainTextEdit *message_box_; QLineEdit *answer_line_edit_; QPushButton *answer_button_; }; } #endif
[ "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 37 ] ] ]
81b397bd4dfae8bb6469a184cfb9b589ab973306
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/DOMImplementation.hpp
ee0ed4b5d68de9f065a3f5d49c21b3ad6e05f7ae
[ "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
11,825
hpp
#ifndef DOMImplementation_HEADER_GUARD_ #define DOMImplementation_HEADER_GUARD_ /* * Copyright 2001-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: DOMImplementation.hpp,v 1.14 2004/09/08 13:55:39 peiyongz Exp $ */ #include <xercesc/dom/DOMImplementationLS.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMRangeException.hpp> #include <xercesc/util/PlatformUtils.hpp> XERCES_CPP_NAMESPACE_BEGIN class DOMDocument; class DOMDocumentType; /** * The <code>DOMImplementation</code> interface provides a number of methods * for performing operations that are independent of any particular instance * of the document object model. */ class CDOM_EXPORT DOMImplementation : public DOMImplementationLS { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMImplementation() {}; // no plain constructor //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented constructors and operators */ //@{ DOMImplementation(const DOMImplementation &); // no copy construtor. DOMImplementation & operator = (const DOMImplementation &); // No Assignment //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMImplementation() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMImplementation interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 1 */ //@{ /** * Test if the DOM implementation implements a specific feature. * @param feature The name of the feature to test (case-insensitive). The * values used by DOM features are defined throughout the DOM Level 2 * specifications and listed in the section. The name must be an XML * name. To avoid possible conflicts, as a convention, names referring * to features defined outside the DOM specification should be made * unique. * @param version This is the version number of the feature to test. In * Level 2, the string can be either "2.0" or "1.0". If the version is * not specified, supporting any version of the feature causes the * method to return <code>true</code>. * @return <code>true</code> if the feature is implemented in the * specified version, <code>false</code> otherwise. * @since DOM Level 1 */ virtual bool hasFeature(const XMLCh *feature, const XMLCh *version) const = 0; //@} // ----------------------------------------------------------------------- // Functions introduced in DOM Level 2 // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 2 */ //@{ /** * Creates an empty <code>DOMDocumentType</code> node. Entity declarations * and notations are not made available. Entity reference expansions and * default attribute additions do not occur. It is expected that a * future version of the DOM will provide a way for populating a * <code>DOMDocumentType</code>. * @param qualifiedName The qualified name of the document type to be * created. * @param publicId The external subset public identifier. * @param systemId The external subset system identifier. * @return A new <code>DOMDocumentType</code> node with * <code>ownerDocument</code> set to <code>null</code>. * @exception DOMException * INVALID_CHARACTER_ERR: Raised if the specified qualified name * contains an illegal character. * <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is * malformed. * <br>NOT_SUPPORTED_ERR: May be raised by DOM implementations which do * not support the <code>"XML"</code> feature, if they choose not to * support this method. Other features introduced in the future, by * the DOM WG or in extensions defined by other groups, may also * demand support for this method; please consult the definition of * the feature to see if it requires this method. * @since DOM Level 2 */ virtual DOMDocumentType *createDocumentType(const XMLCh *qualifiedName, const XMLCh *publicId, const XMLCh *systemId) = 0; /** * Creates a DOMDocument object of the specified type with its document * element. * @param namespaceURI The namespace URI of the document element to * create. * @param qualifiedName The qualified name of the document element to be * created. * @param doctype The type of document to be created or <code>null</code>. * When <code>doctype</code> is not <code>null</code>, its * <code>ownerDocument</code> attribute is set to the document * being created. * @param manager Pointer to the memory manager to be used to * allocate objects. * @return A new <code>DOMDocument</code> object. * @exception DOMException * INVALID_CHARACTER_ERR: Raised if the specified qualified name * contains an illegal character. * <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is * malformed, if the <code>qualifiedName</code> has a prefix and the * <code>namespaceURI</code> is <code>null</code>, or if the * <code>qualifiedName</code> has a prefix that is "xml" and the * <code>namespaceURI</code> is different from " * http://www.w3.org/XML/1998/namespace" , or if the DOM * implementation does not support the <code>"XML"</code> feature but * a non-null namespace URI was provided, since namespaces were * defined by XML. * <br>WRONG_DOCUMENT_ERR: Raised if <code>doctype</code> has already * been used with a different document or was created from a different * implementation. * <br>NOT_SUPPORTED_ERR: May be raised by DOM implementations which do * not support the "XML" feature, if they choose not to support this * method. Other features introduced in the future, by the DOM WG or * in extensions defined by other groups, may also demand support for * this method; please consult the definition of the feature to see if * it requires this method. * @since DOM Level 2 */ virtual DOMDocument *createDocument(const XMLCh *namespaceURI, const XMLCh *qualifiedName, DOMDocumentType *doctype, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) = 0; //@} // ----------------------------------------------------------------------- // Functions introduced in DOM Level 3 // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 3 */ //@{ /** * This method makes available a <code>DOMImplementation</code>'s * specialized interface (see ). * * <p><b>"Experimental - subject to change"</b></p> * * @param feature The name of the feature requested (case-insensitive). * @return Returns an alternate <code>DOMImplementation</code> which * implements the specialized APIs of the specified feature, if any, * or <code>null</code> if there is no alternate * <code>DOMImplementation</code> object which implements interfaces * associated with that feature. Any alternate * <code>DOMImplementation</code> returned by this method must * delegate to the primary core <code>DOMImplementation</code> and not * return results inconsistent with the primary * <code>DOMImplementation</code> * @since DOM Level 3 */ virtual DOMImplementation* getInterface(const XMLCh* feature) = 0; //@} // ----------------------------------------------------------------------- // Non-standard extension // ----------------------------------------------------------------------- /** @name Non-standard extension */ //@{ /** * Non-standard extension * * Create a completely empty document that has neither a root element or a doctype node. */ virtual DOMDocument *createDocument(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) = 0; /** * Non-standard extension * * Factory method for getting a DOMImplementation object. * The DOM implementation retains ownership of the returned object. * Application code should NOT delete it. */ static DOMImplementation *getImplementation(); /** * Non-standard extension * * Load the default error text message for DOMException. * @param msgToLoad The DOM ExceptionCode id to be processed * @param toFill The buffer that will hold the output on return. The * size of this buffer should at least be 'maxChars + 1'. * @param maxChars The maximum number of output characters that can be * accepted. If the result will not fit, it is an error. * @return <code>true</code> if the message is successfully loaded */ static bool loadDOMExceptionMsg ( const DOMException::ExceptionCode msgToLoad , XMLCh* const toFill , const unsigned int maxChars ); /** * Non-standard extension * * Load the default error text message for DOMRangeException. * @param msgToLoad The DOM RangeExceptionCode id to be processed * @param toFill The buffer that will hold the output on return. The * size of this buffer should at least be 'maxChars + 1'. * @param maxChars The maximum number of output characters that can be * accepted. If the result will not fit, it is an error. * @return <code>true</code> if the message is successfully loaded */ static bool loadDOMExceptionMsg ( const DOMRangeException::RangeExceptionCode msgToLoad , XMLCh* const toFill , const unsigned int maxChars ); //@} }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 267 ] ] ]
a0f05c011f42d9c53ac883801eed3fe33e86e798
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/AranIk_Test/BwPch.h
38676e4a8644d9117582615fbbe5efdb69f6a0cd
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
1,782
h
#ifndef __BWPCH_H__ #define __BWPCH_H__ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <string> #include <vector> #include <list> #include <map> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <set> #ifdef WIN32 #include <windows.h> #include <memory> #else #include <tr1/memory> #endif #include <GL/glew.h> //#include <GL/glxew.h> #include <GL/gl.h> #include <GL/glu.h> #include "glext.h" #ifndef WIN32 #include "ft2build.h" #include FT_FREETYPE_H #endif // // ODE // #include <ode/ode.h> // // Boost C++ // #include <boost/foreach.hpp> #include <boost/array.hpp> #include <boost/circular_buffer.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #define foreach BOOST_FOREACH // // Aran // #include "AranApi.h" #include "VideoManGl.h" #include "AranGl.h" #include "ArnTextureGl.h" #include "ArnGlExt.h" #include "AranPhy.h" #include "ArnPhyBox.h" #include "SimWorld.h" #include "GeneralJoint.h" #include "AranIk.h" #include "ArnIkSolver.h" #include "ArnPlane.h" #include "ArnBone.h" #include "Tree.h" #include "Jacobian.h" #include "Node.h" #include "fltkcustomization.h" #include <FL/Fl.H> #include <FL/Fl_Window.H> #include <FL/Fl_Hor_Slider.H> #include <FL/Fl_Toggle_Button.H> #include <FL/Fl_Light_Button.H> #include <FL/Fl_Check_Button.H> #include <FL/Fl_Select_Browser.H> #include <FL/Fl_Check_Browser.H> #include <FL/Fl_Gl_Window.H> #include <FL/Fl_Text_Display.H> #include <FL/Fl_Value_Slider.H> #include <FL/Fl_Int_Input.H> #include <FL/Fl_Float_Input.H> #include <FL/Fl_Slider.H> #include <FL/gl.h> #include <FL/math.h> #include <FL/fl_draw.H> #endif // #ifndef __BWPCH_H__
[ [ [ 1, 89 ] ] ]
4834c72fcadf0887203af321fffe600091e5a947
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/eprom.h
53a64e3969cc9c8d1c156ce0c43a59752153b6de
[]
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
728
h
/************************************************************************* Atari Escape hardware *************************************************************************/ #include "machine/atarigen.h" class eprom_state : public atarigen_state { public: eprom_state(running_machine &machine, const driver_device_config_base &config) : atarigen_state(machine, config) { } int m_screen_intensity; int m_video_disable; UINT16 * m_sync_data; int m_last_offset; }; /*----------- defined in video/eprom.c -----------*/ VIDEO_START( eprom ); SCREEN_UPDATE( eprom ); VIDEO_START( guts ); SCREEN_UPDATE( guts ); void eprom_scanline_update(screen_device &screen, int scanline);
[ "Mike@localhost" ]
[ [ [ 1, 30 ] ] ]
b7e7165261acae858d988dcb391119613ccd110f
5ed707de9f3de6044543886ea91bde39879bfae6
/ASFantasy/IsapiTester/Source/ASFantasyIsapiDllTester.cpp
8c5a2298757149f742cf9fcc06796e4ab09544f9
[]
no_license
grtvd/asifantasysports
9e472632bedeec0f2d734aa798b7ff00148e7f19
76df32c77c76a76078152c77e582faa097f127a8
refs/heads/master
2020-03-19T02:25:23.901618
1999-12-31T16:00:00
2018-05-31T19:48:19
135,627,290
0
0
null
null
null
null
UTF-8
C++
false
false
13,915
cpp
/* ASFantasyIsapiDllTester.h */ /******************************************************************************/ /******************************************************************************/ #include "CBldVCL.h" #pragma hdrstop #include "PasswordEncode.h" #include "ASMemberType.h" #include "ASFantasyIsapiDllTester.h" #include "ASFantasyPlayerScoutRqst.h" #include "ASFantasyLeagueSignupRqst.h" using namespace tag; using namespace asmember; namespace asfantasy { /******************************************************************************/ static const char* gAllPagesStrs[] = { " 1. Hub 51. URL Draft Ranking Query Request\n", " 2. League Sign-up 52. URL Draft Ranking Update Request\n", " 3. Teams 53. URL Player Scout Request\n", " 4. Draft Rankings 54. URL League Signup Request\n", " 5. Draft Results 55. URL Signup League List Request\n", " 6. Schedule 56. URL Draft Result Request\n", " 7. Lineup \n", " 8. Game Results \n", " 9. Standings 57. URL Schedule Request\n", "10. Free Agents 58. URL Lineup Query Request\n", "11. Trades 59. URL Lineup Update Request\n", "12. Playoffs \n", "13. Sign-Up Intro Get \n", "14. Sign-Up Which Get \n", "15. Sign-Up New Member Premium Get 60. URL Game Results Request\n", "16. Sign-Up New Member Premium Post 61. URL Standings Request\n", "17. Sign-Up New Partic Premium Get 62. URL Free Agent Query Request\n", "18. Sign-Up New Partic Premium Post 63. URL Free Agent Update Request\n", " \n", " 66. URL Trade Propose Query Request\n", " 67. URL Trade Propose Team Request\n", " 68. URL Trade Propose Update Request\n", " 69. URL Trade Receive Update Request\n", " 70. URL Trade Protest Update Request\n", " \n", " 80. URL Playoff Request\n", }; static int gNumAllPagesStrs = sizeof(gAllPagesStrs) / sizeof(*gAllPagesStrs); /******************************************************************************/ void ASFantasyIsapiDllLoader::printAllPages() const { int i; for(i = 0; i < gNumAllPagesStrs; i++) printf(gAllPagesStrs[i]); } /******************************************************************************/ const char* ASFantasyIsapiDllLoader::getPageName(int pageNo) const { switch(pageNo) { case 1: return("Hub"); case 2: return("LeagueSignup"); case 3: return("Teams"); case 4: return("DraftRankings"); case 5: return("DraftResults"); case 6: return("Schedule"); case 7: return("Lineup"); case 8: return("GameResults"); case 9: return("Standings"); case 10: return("FreeAgent"); case 11: return("Trade"); case 12: return("Playoff"); case 13: return("Signup"); case 14: return("SignupWhichGet"); case 15: return("NewMemberSignupPremiumGet"); case 16: return("NewMemberSignupPost"); case 17: return("NewParticSignupPremiumGet"); case 18: return("NewParticSignupPost"); default: break; } return("Unknown"); } /******************************************************************************/ bool ASFantasyIsapiDllLoader::isPageDataBinary(int pageNo) const { return(pageNo >= 50); } /******************************************************************************/ const char* ASFantasyIsapiDllLoader::promptOther(int pageNo,bool repeatLast) const { static CStrVar result; result.clear(); switch(pageNo) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 9: case 10: result.copy(promptUserID()); break; case 8: { char temp[256]; result.copy(promptUserID()); printf("Enter Game Date (x=none): "); scanf("%s",temp); if(stricmp(temp,"x") != 0) result.concatVarg("&GameDate=%s",temp); } break; case 11: { char temp[256]; result.copy(promptUserID()); printf("Enter TradeID (x=none): "); scanf("%s",temp); if(stricmp(temp,"x") != 0) result.concatVarg("&TradeID=%s",temp); } break; case 12: result.copy(promptUserID()); break; case 13: result.copyVarg("&Source=Affinity"); break; case 14: result.copyVarg("&Source=Affinity&PrizeEligible=T"); break; case 15: result.copyVarg("&Source=Affinity&PrizeEligible=T"); break; case 16: result.copy("&Source=Affinity&PrizeEligible=T&GameLevel=P&GamePrice=14.95"); result.concat("&UserNameTxt=comp10200"); result.concat("&UserPasswordTxt=bobbob"); result.concat("&UserRePasswordTxt=bobbob"); result.concat("&FirstNameTxt=Bob"); result.concat("&LastNameTxt=Davidson"); result.concat("&Street1Txt=xxx"); result.concat("&CityTxt=yyy"); result.concat("&StateTxt=pa"); result.concat("&ZipCodeTxt=12345"); result.concat("&CountryTxt=usa"); result.concat("&EmailTxt=theref"); result.concat("&ManagerNameTxt=Bob"); result.concat("&RegionNameTxt=South Bronx"); result.concat("&TeamNameTxt=Losers"); result.concat("&CCardTypeSel=VS"); result.concat("&CCardNumberTxt=1234-5678-9012-3456"); result.concat("&CCardExpDateMonSel=10"); result.concat("&CCardExpDateYearSel=1999"); result.concat("&CCardNameOnTxt=Joe"); break; case 17: result.copyVarg("&Source=Affinity&PrizeEligible=T"); break; case 18: result.copyVarg("&Source=Affinity&PrizeEligible=T&GameLevel=P&GamePrice=12.95"); result.concat("&FirstNameTxt=Bob"); result.concat("&LastNameTxt=Davidson"); result.concat("&Street1Txt=xxx"); result.concat("&CityTxt=yyy"); result.concat("&StateTxt=pa"); result.concat("&ZipCodeTxt=12345"); result.concat("&CountryTxt=usa"); result.concat("&EmailTxt=theref"); result.concat("&ManagerNameTxt=Bob"); result.concat("&RegionNameTxt=South Bronx"); result.concat("&TeamNameTxt=Losers"); result.concat("&CCardTypeSel=VS"); result.concat("&CCardNumberTxt=1234"); result.concat("&CCardExpDateMonSel=10"); result.concat("&CCardExpDateYearSel=1999"); result.concat("&CCardNameOnTxt=Joe"); break; default: break; } return(result); } /******************************************************************************/ const char* ASFantasyIsapiDllLoader::promptUserID() const { static CStr127 result; char particID[18]; char password[12]; TEncodedParticID encodedParticID; printf("Enter ParticID: (x=<none>)"); scanf("%s",particID); if(stricmp(particID,"x") == 0) return(""); printf("Enter Password: "); scanf("%s",password); EncodeUserIDPasswordType<TEncodedParticID>(particID,password,encodedParticID); result.CopyVarg("&User=%s",encodedParticID.c_str()); return(result); } /******************************************************************************/ CStrVar ASFantasyIsapiDllLoader::promptEncodedPartic() const { char particID[18]; char password[12]; TEncodedParticID encodedParticID; printf("Enter ParticID: "); scanf("%s",particID); printf("Enter Password: "); scanf("%s",password); EncodeUserIDPasswordType<TEncodedParticID>(particID,password,encodedParticID); return(encodedParticID.c_str()); } /******************************************************************************/ void ASFantasyIsapiDllLoader::promptBinaryFiler(int pageNo,TBinaryFiler &filer) { char temp[256]; switch(pageNo) { case 51: filer.writeString("DraftRankingQueryRqst"); filer.writeString(promptEncodedPartic().c_str()); break; case 52: filer.writeString("DraftRankingUpdateRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeShort(3); // numPlayers filer.writeLong(4344); filer.writeLong(4267); filer.writeLong(3866); break; case 53: filer.writeString("PlayerScoutRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeString(""); // PartialPlayerLastName filer.writeString(""); // ProfTeamAbbr // PositionVector filer.writeByte(1); // numItems filer.writeByte(1); //position // StatVector filer.writeByte(3); // numItems filer.writeByte(1); // statType filer.writeByte(syr_LastYear); // statYearType filer.writeByte(2); // statType filer.writeByte(syr_LastYear); // statYearType filer.writeByte(3); // statType filer.writeByte(syr_LastYear); // statYearType filer.writeShort(25); // SelectNumPlayers filer.writeByte(1); // SelectByStat filer.writeBoolean(false); // SelectByStatAsc filer.writeBoolean(false); // IsFreeAgentRequest filer.writeBoolean(false); // ShowRanked filer.writeBoolean(false); // ShowDrafted filer.writeBoolean(true); // ShowMyTeamPlayers filer.writeBoolean(false); // ShowOtherTeamsPlayers break; case 54: filer.writeString("LeagueSignupRqst"); filer.writeShort(lst_JoinOpenPublic); //fLst filer.writeString(promptEncodedPartic().c_str()); #if 1 //lst_JoinOpenPublic #elif 0 //lst_CreatePrivate filer.writeString("kickbutt"); //fLeaguePassword #else //lst_JoinPrivate filer.writeLong(101); //fLeagueID filer.writeString("kickbutt"); //fLeaguePassword #endif break; case 55: filer.writeString("SignupLeagueListRqst"); printf("Enter Partial League Name (x=none): "); scanf("%s",temp); if(stricmp(temp,"x") == 0) memset(temp,0,sizeof(temp)); filer.writeString(temp); break; case 56: filer.writeString("DraftResultRqst"); filer.writeString(promptEncodedPartic().c_str()); break; case 57: filer.writeString("ScheduleRqst"); filer.writeString(promptEncodedPartic().c_str()); break; case 58: filer.writeString("LineupQueryRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeLong(0); break; case 59: filer.writeString("LineupUpdateRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeShort(2); // numLineups filer.writeShort(2); // numPlayers filer.writeLong(4902); filer.writeLong(3901); filer.writeShort(2); // numPlayers filer.writeLong(5845); filer.writeLong(4715); break; case 60: filer.writeString("GameResultsRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeString(""); //fGameDate MM/DD/YYYY filer.writeLong(0); //fHomeTeamID break; case 61: filer.writeString("StandingsRqst"); filer.writeString(promptEncodedPartic().c_str()); break; case 62: filer.writeString("FreeAgentQueryRqst"); filer.writeString(promptEncodedPartic().c_str()); break; case 63: filer.writeString("FreeAgentUpdateRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeLong(6197); //fClaimPlayerID filer.writeLong(4398); //fReleasePlayerID break; case 66: filer.writeString("TradeProposeQueryRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeLong(0); //fTradeID break; case 67: filer.writeString("TradeProposeTeamRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeLong(1004); //fProposeToTeamID break; case 68: filer.writeString("TradeProposeUpdateRqst"); filer.writeString(promptEncodedPartic().c_str()); #if 1 //clear filer.writeLong(1); //fTradeID filer.writeLong(0); //fProposeToTeamID //fGetPlayerIDVector filer.writeShort(0); //numPlayers //fGivePlayerIDVector filer.writeShort(0); //numPlayers //fReleasePlayerIDVector filer.writeShort(0); //numPlayers #else //new filer.writeLong(0); //fTradeID filer.writeLong(1004); //fProposeToTeamID //fGetPlayerIDVector filer.writeShort(1); //numPlayers filer.writeLong(4362); //fGivePlayerIDVector filer.writeShort(1); //numPlayers filer.writeLong(4267); //fReleasePlayerIDVector filer.writeShort(0); //numPlayers #endif break; case 69: filer.writeString("TradeReceiveUpdateRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeLong(1); //fTradeID filer.writeBoolean(true); //fAccept //fReleasePlayerIDVector filer.writeShort(0); //numPlayers break; case 70: filer.writeString("TradeProtestUpdateRqst"); filer.writeString(promptEncodedPartic().c_str()); filer.writeLong(1); //fTradeID break; case 80: filer.writeString("PlayoffRqst"); filer.writeString(promptEncodedPartic().c_str()); break; default: break; } } /******************************************************************************/ ulong ASFantasyIsapiDllLoader::promptBinaryData(int pageNo,void* lpbDataBuffer, ulong lpbDataBufferSize) { char* data = (char*)lpbDataBuffer; ulong dataSize = 0; switch(pageNo) { default: return(IsapiDllLoader::promptBinaryData(pageNo,lpbDataBuffer, lpbDataBufferSize)); } return(dataSize); } /******************************************************************************/ }; //namespace asfantasy /******************************************************************************/ /******************************************************************************/
[ [ [ 1, 487 ] ] ]
57ad0ab555a187cb84c8fdd5b7067dce6c83e350
4711cae65505af5a33baf4f4652e757bfbf54b78
/RSEngine/Check/CheckGameApp.h
7ec115be715c300372b976c1795a7b2cb2812759
[]
no_license
ashishlijhara/RSEngine
19ad68844df952abe8682777d3281dbf46ff913c
cac48b492597d119fc9c7364088c1930314a923c
refs/heads/master
2016-09-10T10:12:49.781187
2011-05-31T12:34:49
2011-05-31T12:34:49
1,822,577
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
#ifndef _CHECKGAMEAPP_H_ #define _CHECKGAMEAPP_H_ #include "RSEngine.h" #include "CheckScene.h" using namespace RSE; namespace Check{ class CheckGameApp: public IBaseGameApp{ public: CheckGameApp(){ m_pScene = dynamic_cast<IScene*>(new Check::CheckScene()); } ~CheckGameApp(){ } FResult VInit(); FResult VRender(); FResult VRenderPaused(); FResult VSetPaused(const bool &paused); FResult VUpdate(const float &delTime); FResult VCleanup(); }; } #endif
[ [ [ 1, 38 ] ] ]
d64220048ca5b145133761ac753a74a5439177a5
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Main/Culler.h
4961e96476ae47bd84e46744537116898640985a
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
1,898
h
#ifndef _CULLER_H_ #define _CULLER_H_ #include <Common/Prerequisites.h> #include "BoundingVolume.h" namespace Flagship { class Entity; class Portal; struct Segment { Vector4f vPoint1; Vector4f vPoint2; Segment& operator = ( const Segment& rSegment ) { vPoint1 = rSegment.vPoint1; vPoint2 = rSegment.vPoint2; return *this; } bool operator == ( const Segment& rSegment ) { if ( ( rSegment.vPoint1 == vPoint1 && rSegment.vPoint2 == vPoint2 ) || ( rSegment.vPoint2 == vPoint1 && rSegment.vPoint1 == vPoint2 ) ) { return true; } return false; } }; struct Frustum { vector< Plane3f * > pPlaneList; Frustum() { pPlaneList.clear(); } ~Frustum() { for ( int i = 0; i < (int) pPlaneList.size(); i++ ) { SAFE_DELETE( pPlaneList[i] ); } pPlaneList.clear(); } }; class _DLL_Export Culler { public: Culler(); virtual ~Culler(); // 加入剪裁面 void PushPlane( Plane3f * pkPlane ); // 踢出剪裁面 void PopPlane(); // 加入模型 void PushEntity( Entity * pEntity ); // 踢出模型 void PopEntity( int iNum ); // 加入视口 void PushPortal( Portal * pPortal ); // 踢出视口 void PopPortal( int iNum ); // 清空 void Clear(); public: // 包围体测试 virtual bool IsVisible( BoundingVolume * pBound ); protected: // 平面列表 list< Plane3f * > m_pkPlaneList; // 场景遮挡列表 list< Frustum * > m_pkCollideList; // 场景视口列表 list< Frustum * > m_pkPortalList; private: // 边缘检测临时列表 list< Segment > m_pSegmentList; }; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 104 ] ] ]
ae7230b23dc04d2b76d9d78638ac81d744a8ca57
28476e6f67b37670a87bfaed30fbeabaa5f773a2
/src/UnitTest/win/ChildView.cpp
82e9b646a4f017140a15f7d16aac10a74a9ffd8f
[]
no_license
rdmenezes/autumnframework
d1aeb657cd470b67616dfcf0aacdb173ac1e96e1
d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d
refs/heads/master
2021-01-20T13:48:52.187425
2008-07-17T18:25:19
2008-07-17T18:25:19
32,969,073
1
1
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
// ChildView.cpp : implementation of the CChildView class // #include "stdafx.h" #include "UnitTest.h" #include "ChildView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildView CChildView::CChildView() { } CChildView::~CChildView() { } BEGIN_MESSAGE_MAP(CChildView,CWnd ) //{{AFX_MSG_MAP(CChildView) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildView message handlers BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) { if (!CWnd::PreCreateWindow(cs)) return FALSE; cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1), NULL); return TRUE; } void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: Add your message handler code here // Do not call CWnd::OnPaint() for painting messages }
[ "sharplog@c16174ff-a625-0410-88e5-87db5789ed7d" ]
[ [ [ 1, 57 ] ] ]
f952955f2e5d1e7cfa5844d18856702cc8db53a3
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-shared/Database/CreateInterface.cpp
6265ff3054f6b83cd4c574723212dff592441e94
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
#include "DatabaseEnv.h" #include "../CrashHandler.h" #include "../NGLog.h" #if defined(ENABLE_DATABASE_MYSQL) #include "MySQLDatabase.h" #endif #if defined(ENABLE_DATABASE_POSTGRES) #include "PostgresDatabase.h" #endif #if defined(ENABLE_DATABASE_SQLITE) #include "SQLiteDatabase.h" #endif void Database::CleanupLibs() { #if defined(ENABLE_DATABASE_MYSQL) mysql_library_end(); #endif } Database * Database::CreateDatabaseInterface(uint32 uType) { switch(uType) { #if defined(ENABLE_DATABASE_MYSQL) case 1: // MYSQL return new MySQLDatabase(); break; #endif #if defined(ENABLE_DATABASE_POSTGRES) case 2: // POSTGRES return new PostgresDatabase(); break; #endif #if defined(ENABLE_DATABASE_SQLITE) case 3: // SQLITE return new SQLiteDatabase(); break; #endif } Log.LargeErrorMessage(LARGERRORMESSAGE_ERROR, "You have attempted to connect to a database that is unsupported or nonexistant.\nCheck your config and try again."); abort(); return NULL; }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 23 ], [ 25, 51 ] ], [ [ 24, 24 ] ] ]
bd229e6f1e297ac1c12392cdf1c21608c6c03ab5
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/WorkLayer/ED2KLink.h
224f22c9b699bf1e5acb85ea8e96744c2eaf8d83
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,982
h
//this file is part of eMule // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #include "shahashset.h" class CSafeMemFile; struct SUnresolvedHostname { SUnresolvedHostname() { nPort = 0; } CStringA strHostname; uint16 nPort; CString strURL; }; class CED2KLink { public: static CED2KLink* CreateLinkFromUrl(const TCHAR* url); virtual ~CED2KLink(); typedef enum { kServerList, kServer , kFile , kInvalid } LinkType; virtual LinkType GetKind() const = 0; virtual void GetLink(CString& lnk) const = 0; virtual class CED2KServerListLink* GetServerListLink() = 0; virtual class CED2KServerLink* GetServerLink() = 0; virtual class CED2KFileLink* GetFileLink() = 0; }; class CED2KServerLink : public CED2KLink { public: CED2KServerLink(const TCHAR* ip,const TCHAR* port); virtual ~CED2KServerLink(); virtual LinkType GetKind() const; virtual void GetLink(CString& lnk) const; virtual CED2KServerListLink* GetServerListLink(); virtual CED2KServerLink* GetServerLink(); virtual CED2KFileLink* GetFileLink(); const CString& GetAddress() const { return m_strAddress; } uint16 GetPort() const { return m_port;} void GetDefaultName(CString& defName) const { defName = m_defaultName; } private: CED2KServerLink(); CED2KServerLink(const CED2KServerLink&); CED2KServerLink& operator=(const CED2KServerLink&); CString m_strAddress; uint16 m_port; CString m_defaultName; }; class CED2KFileLink : public CED2KLink { public: CED2KFileLink(const TCHAR* pszName, const TCHAR* pszSize, const TCHAR* pszHash, const CStringArray& param, const TCHAR* pszSources); virtual ~CED2KFileLink(); virtual LinkType GetKind() const; virtual void GetLink(CString& lnk) const; virtual CED2KServerListLink* GetServerListLink(); virtual CED2KServerLink* GetServerLink(); virtual CED2KFileLink* GetFileLink(); const TCHAR* GetName() const { return m_name; } const uchar* GetHashKey() const { return m_hash;} const CAICHHash& GetAICHHash() const { return m_AICHHash;} EMFileSize GetSize() const { return (uint64)_tstoi64(m_size); } bool HasValidSources() const { return (SourcesList != NULL); } bool HasHostnameSources() const { return (!m_HostnameSourcesList.IsEmpty()); } bool HasValidAICHHash() const { return m_bAICHHashValid; } CSafeMemFile* SourcesList; CSafeMemFile* m_hashset; CTypedPtrList<CPtrList, SUnresolvedHostname*> m_HostnameSourcesList; CString m_strFilepath; private: CED2KFileLink(); CED2KFileLink(const CED2KFileLink&); CED2KFileLink& operator=(const CED2KFileLink&); CString m_name; CString m_size; uchar m_hash[16]; bool m_bAICHHashValid; CAICHHash m_AICHHash; }; class CED2KServerListLink : public CED2KLink { public: CED2KServerListLink(const TCHAR* pszAddress); virtual ~CED2KServerListLink(); virtual LinkType GetKind() const; virtual void GetLink(CString& lnk) const; virtual CED2KServerListLink* GetServerListLink(); virtual CED2KServerLink* GetServerLink(); virtual CED2KFileLink* GetFileLink(); const TCHAR* GetAddress() const { return m_address; } private: CED2KServerListLink(); CED2KServerListLink(const CED2KFileLink&); CED2KServerListLink& operator=(const CED2KFileLink&); CString m_address; };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 133 ] ] ]
b70a9bc62efe08922c8da70e58defce16b3fceb5
d6eba554d0c3db3b2252ad34ffce74669fa49c58
/Source/Objects/objFactory.cpp
3414207f77c0ca28575d32000e193f7fa48a172e
[]
no_license
nbucciarelli/Polarity-Shift
e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10
8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017
refs/heads/master
2016-09-11T00:24:32.906933
2008-09-26T18:01:01
2008-09-26T18:01:01
3,408,115
1
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
#include "objFactory.h" #include "baseObj.h" objFactory::objFactory(void) { } objFactory::~objFactory(void) { unregisterAll(); } objFactory* objFactory::getInstance() { static objFactory Camino; return &Camino; } void objFactory::unregisterClass(IDType id) { for(vector<creationEntry>::iterator iter = creationList.begin(); iter != creationList.end(); iter++) { if ((*iter).id == id) { if((*iter)._template) iter->_template->release(); creationList.erase(iter); break; } } } void objFactory::unregisterAll() { for(vector<creationEntry>::iterator iter = creationList.begin(); iter != creationList.end(); iter++) { if(iter->_template) iter->_template->release(); //delete iter->_template; } creationList.clear(); } baseObj* objFactory::spawn(IDType id) { for(vector<creationEntry>::iterator iter = creationList.begin(); iter != creationList.end(); iter++) { if ((*iter).id == id) { return (*iter).creator((*iter)._template); } } return NULL; }
[ [ [ 1, 58 ] ] ]
935250aca4e6fee5ef37d580f6c9fdff93e99b26
2fb8c63d1ee7108c00bc9af656cd6ecf7174ae1b
/src/decomp/lzham_lzdecompbase.cpp
6c3f1dcd64a228f93a4022195e7c75ca129439a8
[ "MIT" ]
permissive
raedwulf/liblzham
542aca151a21837c14666f1d16957e61ba9c095d
01ce0ec2d78f4fda767122baa02ba612ed966440
refs/heads/master
2021-01-10T19:58:22.981658
2011-08-24T11:55:26
2011-08-24T11:55:26
2,227,012
3
0
null
null
null
null
UTF-8
C++
false
false
1,356
cpp
// File: lzham_lzdecompbase.cpp // See Copyright Notice and license at the end of include/lzham.h #include "lzham_core.h" #include "lzham_lzdecompbase.h" namespace lzham { void CLZDecompBase::init_position_slots(uint dict_size_log2) { m_dict_size_log2 = dict_size_log2; m_dict_size = 1U << dict_size_log2; int i, j; for (i = 0, j = 0; i < cLZXMaxPositionSlots; i += 2) { m_lzx_position_extra_bits[i] = (uint8)j; m_lzx_position_extra_bits[i + 1] = (uint8)j; if ((i != 0) && (j < 25)) j++; } for (i = 0, j = 0; i < cLZXMaxPositionSlots; i++) { m_lzx_position_base[i] = j; m_lzx_position_extra_mask[i] = (1 << m_lzx_position_extra_bits[i]) - 1; j += (1 << m_lzx_position_extra_bits[i]); } m_num_lzx_slots = 0; const uint largest_dist = m_dict_size - 1; for (int i = 0; i < cLZXMaxPositionSlots; i++) { if ( (largest_dist >= m_lzx_position_base[i]) && (largest_dist < (m_lzx_position_base[i] + (1 << m_lzx_position_extra_bits[i])) ) ) { m_num_lzx_slots = i + 1; break; } } LZHAM_VERIFY(m_num_lzx_slots); } } //namespace lzham
[ [ [ 1, 46 ] ] ]
0dafccf0007d3851a7a07177ed5885db11c454a3
45c0d7927220c0607531d6a0d7ce49e6399c8785
/GlobeFactory/src/useful/const.hh
f135a742a215d684ad3a6999034be57597700da6
[]
no_license
wavs/pfe-2011-scia
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
refs/heads/master
2021-01-25T07:08:36.552423
2011-01-17T20:23:43
2011-01-17T20:23:43
39,025,134
0
0
null
null
null
null
UTF-8
C++
false
false
735
hh
//////////////////////////////////////////////////////////////////////////////// // Filename : const.hh // Authors : Creteur Clement // Last edit : 19/05/10 - 23h54 // Comment : //////////////////////////////////////////////////////////////////////////////// #ifndef USEFUL_CONST_HH #define USEFUL_CONST_HH #include <string> //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace constVar { const std::string EMPTY_STRING; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #endif
[ "creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc" ]
[ [ [ 1, 23 ] ] ]
5148bcb4b6bf1cb3be6d3fdc47727e1a5e5a10fd
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/SkinEditor/TestWindow.h
24fd9ab2fc8aed9bdbbc1a1a626c5338b6fdb070
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
917
h
/*! @file @author Albert Semenov @date 09/2008 */ #ifndef __TEST_WINDOW_H__ #define __TEST_WINDOW_H__ #include <MyGUI.h> #include "Dialog.h" #include "BackgroundControl.h" #include "SkinItem.h" namespace tools { class TestWindow : public Dialog { public: TestWindow(); virtual ~TestWindow(); void setSkinItem(SkinItem* _item); protected: virtual void onDoModal(); virtual void onEndModal(); private: void notifyWindowButtonPressed(MyGUI::Window* _sender, const std::string& _name); void notifyMouseButtonPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id); void createSkin(); void deleteSkin(); void generateSkin(); private: BackgroundControl* mBackgroundControl; SkinItem* mSkinItem; MyGUI::Button* mSkinButton; MyGUI::UString mSkinName; }; } // namespace tools #endif // __TEST_WINDOW_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 48 ] ] ]
8bcd1e9a1eba88e746bb59788d0e392e0f0a98ec
621cce176ba0cce5df41d4120c1d0bfdbeda48cd
/prog/ex4/ex4b.cc
a3b52cc4d5b3a58212ae5756aa36b19c12ee0b24
[]
no_license
AndreyShamis/perviygodmodul
9d65675217abad7fee2e3f833b89e299578550f4
09f0f425a536fab1bca2241dc9b8b071942f5aa6
refs/heads/master
2021-01-10T19:30:29.670776
2010-01-04T19:47:15
2010-01-04T19:47:15
32,789,934
0
0
null
null
null
null
UTF-8
C++
false
false
2,714
cc
/* * EX4B :: U.S. President selection system * ============================================================= * Writen by: Andrey Shamis, id: 321470882, login:andreysh * Each country is allocated a fixed number in the United States of Alktorim. * "Winner in that country 'won' every 'Halktorim" of that country. * Winning the general election is accumulated more Alktorim * (even if in practice he gained fewer votes of his * colleagues among the voters, as indeed happened Kennedy against Nixon). * to assume that interest if any in his bag, then none of the candidates * does not get Balktorim of that country. */ //--------------- including section ------------- #include <iostream> //--------------- using section ------------- using std::cout; using std::cin; using std::endl; //--------------- main ------------- int main() { const int NUM_OF_STATES=6; // max lentgh of array int electoral[NUM_OF_STATES], // array of electorals voters[NUM_OF_STATES][2], // array of voters voters_sum[2], // arr sum of voters by electoral A:B electoral_sum[2]; // arr electoral sum A:B for(int j=0;j<2;j++) { // set the default variables voters_sum[j] = 0; // sum to voters electoral_sum[j] = 0; // sum to electorats } for(int i=0;i<NUM_OF_STATES;i++) cin >> electoral[i]; // Putting lentgh of lectorats in all coutry for(int i=0;i<NUM_OF_STATES;i++) { for(int j=0;j<2;j++) { cin >> voters[i][j]; // Getting voters in all country by group voters_sum[j] += voters[i][j];//Sum voters in all country by group } if(voters[i][0] > voters[i][1]) electoral_sum[0] += electoral[i]; // sum electorats to A; else if(voters[i][1] > voters[i][0]) electoral_sum[1] += electoral[i]; // sum electorats to B; } // printing data cout << electoral_sum[0] << " " // printing Electorats sum for A << electoral_sum[1] << " " // printing Electorats sum for B << voters_sum[0] << " " // printing Voters sum for A << voters_sum[1] << " "; // printing Voters sum for B // Printing results of group or A or B or DRAW if(electoral_sum[0] > electoral_sum[1]) cout << "A"; // print A! else if(electoral_sum[0] < electoral_sum[1]) cout << "B"; // print B! else cout << "draw"; // print DRAW! cout << endl; // print end-of-line (EOL)! return(0); }
[ "lolnik@465b2a2a-c3d4-11de-a006-439b9ae3df91" ]
[ [ [ 1, 71 ] ] ]
f5eec8df83529f69072bf84dfce2c49ffef78ed4
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/test/integral_wrapper_test.hpp
510ea67b5b5f91d3efb8f8902a0151a877261a6d
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,129
hpp
// Copyright Aleksey Gurtovoy 2001-2006 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/test/integral_wrapper_test.hpp,v $ // $Date: 2006/11/20 17:59:29 $ // $Revision: 1.4.2.1 $ #include <boost/mpl/next_prior.hpp> #include <boost/mpl/aux_/test.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #include <cassert> #if !BOOST_WORKAROUND(__BORLANDC__, < 0x600) # define INTEGRAL_WRAPPER_RUNTIME_TEST(i, T) \ BOOST_TEST(( WRAPPER(T,i)() == i )); \ BOOST_TEST(( WRAPPER(T,i)::value == i )); \ /**/ #else # define INTEGRAL_WRAPPER_RUNTIME_TEST(i, T) \ BOOST_TEST(( WRAPPER(T,i)::value == i )); \ /**/ #endif #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) // agurt 20/nov/06: see http://article.gmane.org/gmane.comp.lib.boost.devel/151065 #define INTEGRAL_WRAPPER_TEST(unused1, i, T) \ { \ typedef WRAPPER(T,i) borland_tested_type; \ { typedef is_same< borland_tested_type::value_type, T > borland_test_type; \ MPL_ASSERT(( borland_test_type )); } \ { MPL_ASSERT(( is_same< borland_tested_type::type, WRAPPER(T,i) > )); } \ { MPL_ASSERT(( is_same< next< borland_tested_type >::type, WRAPPER(T,i+1) > )); } \ { MPL_ASSERT(( is_same< prior< borland_tested_type >::type, WRAPPER(T,i-1) > )); } \ { MPL_ASSERT_RELATION( (borland_tested_type::value), ==, i ); } \ INTEGRAL_WRAPPER_RUNTIME_TEST(i, T) \ } \ /**/ #else #define INTEGRAL_WRAPPER_TEST(unused1, i, T) \ { MPL_ASSERT(( is_same< WRAPPER(T,i)::value_type, T > )); } \ { MPL_ASSERT(( is_same< WRAPPER(T,i)::type, WRAPPER(T,i) > )); } \ { MPL_ASSERT(( is_same< next< WRAPPER(T,i) >::type, WRAPPER(T,i+1) > )); } \ { MPL_ASSERT(( is_same< prior< WRAPPER(T,i) >::type, WRAPPER(T,i-1) > )); } \ { MPL_ASSERT_RELATION( (WRAPPER(T,i)::value), ==, i ); } \ INTEGRAL_WRAPPER_RUNTIME_TEST(i, T) \ /**/ #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 55 ] ] ]
81c75dee491e80ac85fac14bb6135fa3d65aa592
61903bd16177bb048a5482b2dd28d5ad2e12cf99
/Core/ChronProcInfo.cpp
0d00f7ab4e7278f5b92e8fa4e70a3cddf73b3e99
[]
no_license
superymk/icepoint
df623457e2356e97629dfefb6e6136873e6b6597
71dcc3cdc06c0b3e25b09a6c44dea443545bdd6f
refs/heads/master
2020-06-06T12:57:37.954224
2010-08-11T05:40:49
2010-08-11T05:40:49
32,418,597
3
1
null
null
null
null
UTF-8
C++
false
false
2,690
cpp
#include <windows.h> #include <TlHelp32.h> #include <stdio.h> #include <string.h> #include <winnt.h> #include <stddef.h> #include <psapi.h> #include <iostream> #include <fstream> #include "ChronProcInfo.h" using namespace std; static PVOID GetFileGlobalSegVA(const char * path, DWORD* vSize); static const char* GetFileNameViaPID(DWORD pid); static const char* FormatPath(char* filePath); /* return NULL on error */ PVOID GetProcGlobalSegVA(DWORD pid, DWORD* vSize, char * formatPath) { const char* filePath = FormatPath((char*)GetFileNameViaPID(pid)); if(formatPath) memcpy(formatPath, filePath, MAX_PATH); return GetFileGlobalSegVA(filePath, vSize); } static const char* FormatPath(char* filePath) { static char formatPath[MAX_PATH] = {0}; for( int i = 0; i < strlen(filePath); i++) if (filePath[i] == '\\') formatPath[i] = '/'; else formatPath[i] = filePath[i]; return formatPath; } static PVOID GetFileGlobalSegVA(const char * path, DWORD* vSize) { static BYTE buffer[8192] = {0}; ifstream in(path, ios::in); IMAGE_DOS_HEADER mzh; PIMAGE_DOS_HEADER pmzh = &mzh; IMAGE_NT_HEADERS nth; PIMAGE_NT_HEADERS pnth = &nth; IMAGE_SECTION_HEADER sec; PIMAGE_SECTION_HEADER psec = &sec; DWORD section_count, nth_loc, file_size, base_addr; DWORD gsVA = 0; in.seekg(0, ios::beg); in.read((char*)pmzh, sizeof(IMAGE_DOS_HEADER)); in.seekg(nth_loc = pmzh->e_lfanew, ios::beg); in.read((char*)pnth, sizeof(IMAGE_NT_HEADERS)); section_count = pnth->FileHeader.NumberOfSections; base_addr = pnth->OptionalHeader.ImageBase; for (int i = 0; i < section_count; ++i) { in.seekg(nth_loc + offsetof(IMAGE_NT_HEADERS, OptionalHeader) + pnth->FileHeader.SizeOfOptionalHeader + i*sizeof(IMAGE_SECTION_HEADER), ios::beg); in.read((char*)psec, sizeof(IMAGE_SECTION_HEADER)); if (!strncmp((const char*)psec->Name, ".data", 6)) { gsVA = psec->VirtualAddress + base_addr; if (vSize) *vSize = psec->Misc.VirtualSize; return (PVOID) gsVA; } } return NULL; } static const char* GetFileNameViaPID(DWORD pid) { static char szProcessName[MAX_PATH] = "unknown "; // Get a handle to the process. HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid ); // Get the process name. if (hProcess) { HMODULE hMod; DWORD cbNeeded; if (EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded)) GetModuleFileNameEx(hProcess, hMod, szProcessName, sizeof(szProcessName)); } CloseHandle( hProcess); return szProcessName; }
[ "superymk@aed0a244-e263-7813-4a31-8d1341b6dc4e" ]
[ [ [ 1, 99 ] ] ]