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
f1cb0783391b757e66bcf6e64c9aaf443b0942c2
a7eff8a49855a81c2649cd329a2adc7e82016dee
/.LibReader/f_Register.cpp
5478d96cabce0b2880fb1177a038e15ec1da874d
[]
no_license
szavalishin/Libs
2f16a6498f1181eee4d2f59ab96bbf5f43e285b4
bdb9d482cd12a28eec4233d773fd2b9b0131d510
refs/heads/master
2020-04-15T16:08:29.104347
2011-12-16T19:32:29
2011-12-16T19:32:29
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,203
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "f_Main.h" #include "f_Register.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TfRegister *fRegister; //--------------------------------------------------------------------------- __fastcall TfRegister::TfRegister(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TfRegister::btnRegisterClick(TObject *Sender) { if(leLogin->Text == ""){ ShowMessage("Введите логин"); return; } if(lePass->Text == ""){ ShowMessage("Введите пароль"); return; } if(lePass->Text != lePassConfirm->Text){ ShowMessage("Проверьте правильность введённого пароля"); return; } fMain->leLogin->Text = leLogin->Text; fMain->lePass->Text = lePass->Text; fMain->cbRememberPass->Checked = cbRememberPass->Checked; fRegister->Close(); } //---------------------------------------------------------------------------
[ [ [ 1, 41 ] ] ]
aa6e086da5fddbb99c61de2bfdf98b72d591fa3f
b23a27888195014aa5bc123d7910515e9a75959c
/Main/V1.0/3rdLib/OPCClientToolKit/OPCGroup.cpp
23059c275be687443a97e5fe3c5f49cf18eaadde
[]
no_license
fostrock/connectspot
c54bb5484538e8dd7c96b76d3096dad011279774
1197a196d9762942c0d61e2438c4a3bca513c4c8
refs/heads/master
2021-01-10T11:39:56.096336
2010-08-17T05:46:51
2010-08-17T05:46:51
50,015,788
1
0
null
null
null
null
UTF-8
C++
false
false
10,707
cpp
/* OPCClientToolKit Copyright (C) 2005 Mark C. Beharrell This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "OPCServer.h" #include "OPCGroup.h" #include "OPCItem.h" /** * Handles OPC (DCOM) callbacks at the group level. It deals with the receipt of data from asynchronous operations. * This is a fake COM object. */ class CAsynchDataCallback : public IOPCDataCallback { private: DWORD mRefCount; /** * group this is a callback for */ COPCGroup &callbacksGroup; /** * Enter the OPC items data that resulted from an operation */ static void updateOPCData(COPCItem_DataMap &opcData, DWORD count, OPCHANDLE * clienthandles, VARIANT* values, WORD * quality,FILETIME * time, HRESULT * errors){ // see page 136 - returned arrays may be out of order for (unsigned i = 0; i < count; i++){ // TODO this is bad - server could corrupt address - need to use look up table COPCItem * item = (COPCItem *)clienthandles[i]; CAtlMap<COPCItem *, OPCItemData *>::CPair* pair = opcData.Lookup(item); OPCItemData * data = NULL; if (FAILED(errors[i])){ data = new OPCItemData(errors[i]); } else { data = new OPCItemData(time[i],quality[i],values[i],errors[i]); } if (pair == NULL){ opcData.SetAt(item,data); } else { opcData.SetValueAt(pair,data); } } } public: CAsynchDataCallback(COPCGroup &group):callbacksGroup(group){ mRefCount = 0; } ~CAsynchDataCallback(){ } /** * Functions associated with IUNKNOWN */ STDMETHODIMP QueryInterface( REFIID iid, LPVOID* ppInterface){ if ( ppInterface == NULL){ return E_INVALIDARG; } if ( iid == IID_IUnknown ){ *ppInterface = (IUnknown*) this; } else if ( iid == IID_IOPCDataCallback){ *ppInterface = (IOPCDataCallback*) this; } else { *ppInterface = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } STDMETHODIMP_(ULONG) AddRef(){ return ++mRefCount; } STDMETHODIMP_(ULONG) Release(){ --mRefCount; if ( mRefCount == 0){ delete this; } return mRefCount; } /** * Functions associated with IOPCDataCallback */ STDMETHODIMP OnDataChange(DWORD Transid, OPCHANDLE grphandle, HRESULT masterquality, HRESULT mastererror, DWORD count, OPCHANDLE * clienthandles, VARIANT * values, WORD * quality, FILETIME * time, HRESULT * errors) { IAsynchDataCallback * usrHandler = callbacksGroup.getUsrAsynchHandler(); if (Transid != 0){ // it is a result of a refresh (see p106 of spec) CTransaction & trans = *(CTransaction *)Transid; updateOPCData(trans.opcData, count, clienthandles, values,quality,time,errors); trans.setCompleted(); return S_OK; } if (usrHandler){ COPCItem_DataMap dataChanges; updateOPCData(dataChanges, count, clienthandles, values,quality,time,errors); usrHandler->OnDataChange(callbacksGroup, dataChanges); } return S_OK; } STDMETHODIMP OnReadComplete(DWORD Transid, OPCHANDLE grphandle, HRESULT masterquality, HRESULT mastererror, DWORD count, OPCHANDLE * clienthandles, VARIANT* values, WORD * quality, FILETIME * time, HRESULT * errors) { // TODO this is bad - server could corrupt address - need to use look up table CTransaction & trans = *(CTransaction *)Transid; updateOPCData(trans.opcData, count, clienthandles, values,quality,time,errors); trans.setCompleted(); return S_OK; } STDMETHODIMP OnWriteComplete(DWORD Transid, OPCHANDLE grphandle, HRESULT mastererr, DWORD count, OPCHANDLE * clienthandles, HRESULT * errors) { // TODO this is bad - server could corrupt address - need to use look up table CTransaction & trans = *(CTransaction *)Transid; // see page 145 - number of items returned may be less than sent for (unsigned i = 0; i < count; i++){ // TODO this is bad - server could corrupt address - need to use look up table COPCItem * item = (COPCItem *)clienthandles[i]; trans.setItemError(item, errors[i]); // this records error state - may be good } trans.setCompleted(); return S_OK; } STDMETHODIMP OnCancelComplete(DWORD transid, OPCHANDLE grphandle){ printf("OnCancelComplete: Transid=%ld GrpHandle=%ld\n", transid, grphandle); return S_OK; } }; COPCGroup::COPCGroup(const CString & groupName, bool active, unsigned long reqUpdateRate_ms, unsigned long &revisedUpdateRate_ms, float deadBand, COPCServer &server): name(groupName), opcServer(server) { USES_CONVERSION; WCHAR* wideName = T2OLE(groupName); HRESULT result = opcServer.getServerInterface()->AddGroup(wideName, active, reqUpdateRate_ms, 0, 0, &deadBand, 0, &groupHandle, &revisedUpdateRate_ms, IID_IOPCGroupStateMgt, (LPUNKNOWN*)&iStateManagement); if (FAILED(result)) { throw OPCException("Failed to Add group"); } result = iStateManagement->QueryInterface(IID_IOPCSyncIO, (void**)&iSychIO); if (FAILED(result)){ throw OPCException("Failed to get IID_IOPCSyncIO"); } result = iStateManagement->QueryInterface(IID_IOPCAsyncIO2, (void**)&iAsych2IO); if (FAILED(result)){ throw OPCException("Failed to get IID_IOPCAsyncIO2"); } result = iStateManagement->QueryInterface(IID_IOPCItemMgt, (void**)&iItemManagement); if (FAILED(result)){ throw OPCException("Failed to get IID_IOPCItemMgt"); } } COPCGroup::~COPCGroup() { opcServer.getServerInterface()->RemoveGroup(groupHandle, FALSE); } void COPCGroup::readSync(int noItems, COPCItem **items, OPCItemData data[], HRESULT errors[], OPCDATASOURCE source){ OPCHANDLE *handles = new OPCHANDLE[noItems]; for (int i = 0; i < noItems; i++){ if ((items[i]->getAccessRights() && OPC_READABLE) != OPC_READABLE){ throw OPCException("Item is not readable"); } handles[i] = items[i]->getHandle(); } HRESULT *itemResult; OPCITEMSTATE *itemState; HRESULT result = iSychIO->Read(source, noItems, handles, &itemState, &itemResult); if (FAILED(result)) { throw OPCException("Read failed"); } for (i = 0; i < noItems; i++){ errors[i] = itemResult[i]; if (!FAILED(itemResult[i])){ data[i].set(itemState[i]); VariantClear(&itemState[i].vDataValue); } } COPCClient::comFree(itemResult); COPCClient::comFree(itemState); } CTransaction * COPCGroup::refresh(OPCDATASOURCE source, ITransactionComplete *transactionCB){ DWORD cancelID; CTransaction * trans = new CTransaction(items, transactionCB); HRESULT result = iAsych2IO->Refresh2(source, (DWORD)trans, &cancelID); if (FAILED(result)){ delete trans; throw OPCException("refresh failed"); } return trans; } COPCItem * COPCGroup::addItem(CString &itemName, bool active) { COPCItem * item = new COPCItem(itemName, active, *this); items.Add(item); return item; } int COPCGroup::addItems(CAtlArray<CString>& itemName, CAtlArray<COPCItem *>& itemsCreated, bool active){ // TODO - this does not work at the moment OPCITEMDEF *itemDef = new OPCITEMDEF[itemName.GetCount()]; for (unsigned i = 0; i < itemName.GetCount(); i++){ USES_CONVERSION; WCHAR* wideName = T2OLE(itemName[i]); itemDef[i].szItemID = wideName; itemDef[i].szAccessPath = wideName; itemDef[i].bActive = active; itemDef[i].hClient = (DWORD)this; itemDef[i].dwBlobSize = 0; itemDef[i].pBlob = NULL; itemDef[i].vtRequestedDataType = VT_EMPTY; } HRESULT *itemResult; OPCITEMRESULT *itemDetails; HRESULT result = getItemManagementInterface()->AddItems(itemName.GetCount(), itemDef, &itemDetails, &itemResult); if (FAILED(result)){ throw OPCException("Failed to add items"); } int errorCount = 0; for (i = 0; i < itemName.GetCount(); i++){ if(itemDetails[i].pBlob){ COPCClient::comFree(itemDetails[0].pBlob); } if (FAILED(itemResult[i])){ errorCount++; } OPCHANDLE serversItemHandle = itemDetails[i].hServer; VARTYPE vtCanonicalDataType = itemDetails[i].vtCanonicalDataType; DWORD dwAccessRights = itemDetails[i].dwAccessRights; } COPCClient::comFree(itemDetails); COPCClient::comFree(itemResult); return errorCount; } void COPCGroup::enableAsynch(IAsynchDataCallback &handler){ if (!asynchDataCallBackHandler == false){ throw OPCException("Asynch already enabled"); } ATL::CComPtr<IConnectionPointContainer> iConnectionPointContainer = 0; HRESULT result = iStateManagement->QueryInterface(IID_IConnectionPointContainer, (void**)&iConnectionPointContainer); if (FAILED(result)) { throw OPCException("Could not get IID_IConnectionPointContainer"); } result = iConnectionPointContainer->FindConnectionPoint(IID_IOPCDataCallback, &iAsynchDataCallbackConnectionPoint); if (FAILED(result)) { throw OPCException("Could not get IID_IOPCDataCallback"); } asynchDataCallBackHandler = new CAsynchDataCallback(*this); result = iAsynchDataCallbackConnectionPoint->Advise(asynchDataCallBackHandler, &callbackHandle); if (FAILED(result)) { iAsynchDataCallbackConnectionPoint = NULL; asynchDataCallBackHandler = NULL; throw OPCException("Failed to set DataCallbackConnectionPoint"); } userAsynchCBHandler = &handler; } void COPCGroup::setState(DWORD reqUpdateRate_ms, DWORD &returnedUpdateRate_ms, float deadBand, BOOL active){ HRESULT result = iStateManagement->SetState(&reqUpdateRate_ms, &returnedUpdateRate_ms, &active,0, &deadBand,0,0); if (FAILED(result)) { throw OPCException("Failed to set group state"); } } void COPCGroup::disableAsynch(){ if (asynchDataCallBackHandler == NULL){ throw OPCException("Asynch is not exabled"); } iAsynchDataCallbackConnectionPoint->Unadvise(callbackHandle); iAsynchDataCallbackConnectionPoint = NULL; asynchDataCallBackHandler = NULL;// WE DO NOT DELETE callbackHandler, let the COM ref counting take care of that userAsynchCBHandler = NULL; }
[ [ [ 1, 401 ] ] ]
7558f8cca3aa0bfa771592e7217dbc1a150dd907
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/FLVGServer/ControlPropertiesTreeCtrl.cpp
a76147bf332a2034aedd36977413ee0295a26cb4
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
// ControlPropertiesTreeCtrl.cpp : implementation file // #include "stdafx.h" #include "XDigitalLifeServerApp.h" #include "ControlPropertiesTreeCtrl.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CControlPropertiesTreeCtrl CControlPropertiesTreeCtrl::CControlPropertiesTreeCtrl() { } CControlPropertiesTreeCtrl::~CControlPropertiesTreeCtrl() { } BEGIN_MESSAGE_MAP(CControlPropertiesTreeCtrl, CXTTreeCtrl) //{{AFX_MSG_MAP(CControlPropertiesTreeCtrl) // NOTE - the ClassWizard will add and remove mapping macros here. ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnSelchanged) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CControlPropertiesTreeCtrl message handlers void CControlPropertiesTreeCtrl::OnSelchanged(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; AfxGetMainWnd()->SendMessage(WM_CONTROLPROPERTIESTREE_SELECTED, (WPARAM)pNMHDR); *pResult = 0; }
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 42 ] ] ]
efb7e18a532498b3fe2c239c77a316d373939630
29f0a6c56e3c4528f64c3a1ad18fc5f074ae1146
/Praktikum Info2/Aufgabenblock_3/AktivesVO.cpp
73f6e623fdf53ceb6eea57daf842af96d4aab3a1
[]
no_license
JohN-D/Info-2-Praktikum
8ccb0348bedf38a619a39b17b0425d6b4c16a72d
c11a274e9c4469a31f40d0abec2365545344b534
refs/heads/master
2021-01-01T18:34:31.347062
2011-10-19T20:18:47
2011-10-19T20:18:47
2,608,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,568
cpp
#include "AktivesVO.h" using namespace std; map<string, AktivesVO*> AktivesVO::VOMap; //damit auch statisch zugegriffen werden kann AktivesVO::AktivesVO(void) { vInitialisierung(); //cout << "AktivesVO(void)" << endl; } AktivesVO::~AktivesVO(void) { } ostream& AktivesVO::ostreamAusgabe(ostream& Ausgabe) { Ausgabe << setw(2) << setiosflags(ios::right) << p_iID; Ausgabe << setw(2) << " "; Ausgabe << resetiosflags(ios::right); Ausgabe << setiosflags(ios::left); Ausgabe << setw(7) << p_sName; Ausgabe << setw(3) << ":"; Ausgabe << resetiosflags(ios::left); return Ausgabe; } istream& AktivesVO::istreamEingabe(istream& in) { if(p_sName != "") { throw "Name bereits definiert"; } else { in>>p_sName; } vAnmeldung(); return in; } ostream& operator<<(ostream& out, AktivesVO& objekt) { objekt.ostreamAusgabe(out); return out; } istream& operator>>(istream& in, AktivesVO& objekt) { objekt.istreamEingabe(in); return in; } void AktivesVO::vInitialisierung() { p_sName = ""; p_iMaxID++; p_iID = p_iMaxID; p_dGesamtZeit = 0; p_dZeit = 0; } string AktivesVO::getName(void) { return p_sName; } void AktivesVO::vAnmeldung(void) { if(VOMap.find(p_sName) != VOMap.end()) { throw "Name bereits vergeben"; } else { VOMap[p_sName] = this; } cout<< "ANMELDE: "<<this->p_sName<<endl; } AktivesVO* AktivesVO::ptObjekt(string name) { if(!VOMap.count(name)) throw ("Element in VOMap nicht vorhanden"); return VOMap.find(name)->second; }
[ [ [ 1, 87 ] ] ]
88eabefc72ee1021afff329ad555ffa1bb123b00
6d25f0b33ccaadd65b35f77c442b80097a2fce8e
/gbt/cart_imp.h
d6d1ea7559b64cd46ba166174eefeb80dab1b48f
[]
no_license
zhongyunuestc/felix-academic-project
8b282d3a783aa48a6b56ff6ca73dc967f13fd6cf
cc71c44fba50a5936b79f7d75b5112d247af17fe
refs/heads/master
2021-01-24T10:28:38.604955
2010-03-20T08:33:59
2010-03-20T08:33:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,357
h
#ifndef __CART__IMPL #define __CART__IMPL #include <cstdlib> #include <cassert> #include <iostream> #include <algorithm> #include <functional> #include <utility> #include <ext/hash_set> //#include <unordered_set> #include <ext/algorithm> #include <cmath> #include <boost/timer.hpp> #include "common.h" typedef __gnu_cxx::hash_set<int> IntSet; template <typename VecType> FeatureIndex* buildFeatureIndex(const std::vector<VecType>& x, int nd) { using std::cout; using std::endl; using std::cerr; FeatureIndex *res = new FeatureIndex(x.size(), nd); for(int p=0;p<res->nDims;p++) { int* pd = res->getDim(p); for(size_t i=0;i<res->nDatas;i++) pd[i] = i; std::sort(pd, pd+res->nDatas, FeatureComp<VecType>(p, x)); } return res; } inline FeatureIndex* FeatureIndex::getSample(const ints_t& sampleList) const { assert(ind!=NULL); int2int_t sample(sampleList.size()); for(size_t i=0;i<sampleList.size();i++) sample.insert(std::make_pair(sampleList[i], i)); FeatureIndex *res = new FeatureIndex(sampleList.size(), nDims); for(int p=0;p<nDims;p++) { const int* pAll = getDim(p); int* pd = res->getDim(p); size_t j = 0; for(size_t i=0;i<nDatas;i++) { int2int_t::const_iterator it = sample.find(pAll[i]); if(it!=sample.end()) { // assert(it->second>=0 && it->second<res.nDatas); pd[j++] = it->second; } } assert(j==sampleList.size()); } return res; } // requirement: begin < end template <typename VecType1, typename VecType2, typename VecType3, typename VecType4> void Cart<VecType1, VecType2, VecType3, VecType4>::splitNode( const Cart<VecType1, VecType2, VecType3, VecType4>::Features& feature, const VecType3& y, const VecType2& weight, int begin, int end, Node& node, NodeSplit& split) { int i, p, pi; double leftSum, rightSum, temp, best, bestvalue = 0.0, splitNum; double sumw, leftW; int besti = -1, bestp = -1; using std::cout; using std::endl; // cout << "[" << begin << "," << end << "]" << endl; splitNum = (int)(cartParam.splitRate*(end-begin)); if(splitNum<cartParam.minNode) splitNum = cartParam.minNode; for(p=0;p<nDims;p++) { const int bufOffset = p*nDatas; FeatureComp<VecType1> fc(p, feature); /* cout << " " << p; for(int i=begin+1;i<end;i++) { if(feature[pind[bufOffset+i-1]][p]>feature[pind[bufOffset+i]][p]) { cout << "Error i = " << i << " " << feature[pind[bufOffset+i-1]][p] << " " << feature[pind[bufOffset+i]][p] << endl; } } */ assert(__gnu_cxx::is_sorted(pind+bufOffset+begin, pind+bufOffset+end, fc)); } // cout << endl; for(node.ymeans=sumw=0,i=begin;i<end;i++) { // cout << weight[pind[0][i]] << " " << y[pind[0][i]] << endl; node.ymeans+=weight[pind[i]]*y[pind[i]]; sumw += weight[pind[i]]; } assert(dcmp(sumw)!=0 && std::isfinite(sumw)); if(dcmp(sumw)==0) { node.ymeans = 0.0; node.attribute = -1; split.improve = 0.0; split.begin = begin; split.end = end; split.bound = -1; return; } node.ymeans/=sumw; // cout << "ymeans = " << node.ymeans << " " << sumw << endl; for(node.var=0,i=begin;i<end;i++) { node.var += weight[pind[i]]*(y[pind[i]]-node.ymeans)*(y[pind[i]]-node.ymeans); } node.var/=sumw; node.size = end-begin; if(end-begin<splitNum*2) { node.attribute = -1; split.improve = 0.0; split.begin = begin; split.end = end; split.bound = -1; return; } std::random_shuffle(find.begin(), find.end()); best = 0.0; for(pi=0;pi<nFeatures;pi++) { p = find[pi]; const int bufOffset = p*nDatas; FeatureComp<VecType1> cp(p, feature); leftSum = weight[pind[bufOffset+begin]]*y[pind[bufOffset+begin]]; leftW = weight[pind[bufOffset+begin]]; for(rightSum=0.0,i=begin+1;i<end;i++) rightSum+=weight[pind[bufOffset+i]]*y[pind[bufOffset+i]]; for(i=begin+1;i<end;i++) { if(i>begin+splitNum && i<end-splitNum && dcmp(leftW)!=0 && dcmp(sumw-leftW)!=0) { if(cp(pind[bufOffset+i-1], pind[bufOffset+i])) { temp = leftSum*leftSum/leftW+rightSum*rightSum/(sumw-leftW); if(std::isfinite(temp) && dcmp(best-temp)<0) { best = temp; besti = i; // be careful ! bestp = p; bestvalue = (feature[pind[bufOffset+i-1]][bestp]+feature[pind[bufOffset+i]][bestp])/2; } } } leftSum += weight[pind[bufOffset+i]]*y[pind[bufOffset+i]]; rightSum -= weight[pind[bufOffset+i]]*y[pind[bufOffset+i]]; leftW += weight[pind[bufOffset+i]]; } } // assert(std::isfinite(best)); // assert(std::isfinite(node.ymeans)); split.begin = begin; split.end = end; split.bound = -1; split.improve = best-node.ymeans*node.ymeans*sumw; // cout << "best = " << best << " ymeans = " << node.ymeans << " sumw = " << sumw << endl; node.improve =split.improve; assert(std::isfinite(split.improve)); if(dcmp(split.improve)>0) { assert(besti>=0); node.attribute = bestp; FeatureComp<VecType1> cp(bestp, feature); IntSet leftSet; const int bestpOffset = bestp*nDatas; for(i=begin;i<besti;i++) leftSet.insert(pind[bestpOffset+i]); int* tempInd = new int[end-begin]; for(p=0;p<nDims;p++) if(p!=bestp) { const int bufOffset = p*nDatas; int count1 = 0, count2 = besti-begin; for(i=begin;i<end;i++) { if(leftSet.find(pind[bufOffset+i])!=leftSet.end()) { tempInd[count1++] = pind[bufOffset+i]; } else { tempInd[count2++] = pind[bufOffset+i]; } } assert(count1==besti-begin); assert(count2==end-begin); std::copy(tempInd, tempInd+(end-begin), pind+bufOffset+begin); } split.bound = besti; delete[] tempInd; node.value = bestvalue; } } template <typename VecType1, typename VecType2, typename VecType3, typename VecType4> Node* Cart<VecType1, VecType2, VecType3, VecType4>::fit( const Cart<VecType1, VecType2, VecType3, VecType4>::Features& x, int nd, const VecType2& w, const VecType3& target, VecType4& fit_target, FeatureIndex& buf) { using std::cout; using std::cerr; using std::endl; nDatas = x.size(); nDims = nd; nFeatures = (int)floor(nDims*cartParam.sample); if(nFeatures>nDims) nFeatures = nDims; int i, j, k, bestnode=-1; double bestimprove; Node *root = new Node(); Node **leafNode = new Node*[cartParam.nLeafNodes]; NodeSplit *nodeSplit = new NodeSplit[cartParam.nLeafNodes]; ints_t depth(cartParam.nLeafNodes); find.resize(nDims); for(i=0;i<nDims;i++) find[i] = i; // init pind for each dimemnsion pind = buf.ind; // init root node; leafNode[0] = root; depth[0] = 1; splitNode(x, target, w, 0, nDatas, *(leafNode[0]), nodeSplit[0]); for(i=0;i<cartParam.nLeafNodes-1;i++) { // printf("i = %d\n", i); for(bestimprove=0,j=0;j<=i;j++) { if(depth[j]<=cartParam.maxDepth&&dcmp(nodeSplit[j].improve-bestimprove)>0) { bestimprove = nodeSplit[j].improve; bestnode = j; } } if(dcmp(bestimprove)==0) { // printf("heheh %d\n", i); break; } // fprintf(stderr, "split attr %d improve %lf\n", leafNode[bestnode]->attribute, bestimprove); leafNode[bestnode]->right = new Node(); leafNode[bestnode]->left = new Node(); splitNode(x, target, w, nodeSplit[bestnode].bound, nodeSplit[bestnode].end, *(leafNode[bestnode]->right), nodeSplit[i+1]); //fprintf(stderr, "jejhe %d \n", i); splitNode(x, target, w, nodeSplit[bestnode].begin, nodeSplit[bestnode].bound, *(leafNode[bestnode]->left), nodeSplit[bestnode]); //fprintf(stderr, "jejhe\n"); leafNode[i+1] = leafNode[bestnode]->right; depth[i+1] = depth[bestnode]+1; leafNode[bestnode] = leafNode[bestnode]->left; depth[bestnode] = depth[bestnode]+1; } fit_target.resize(nDatas); for(j=0;j<=i&&j<cartParam.nLeafNodes;j++) { // printf("%d %.4lf %.4lf, ", nodeSplit[j].end-nodeSplit[j].begin, leafNode[j]->var, nodeSplit[j].improve); for(k=nodeSplit[j].begin;k<nodeSplit[j].end;k++) { fit_target[pind[k]] = leafNode[j]->ymeans; } } // printf("\n"); delete []nodeSplit; delete []leafNode; // fprintf(stderr, "fit_cart out\n"); return root; } #endif
[ "Felix.Guozq@fe1a0076-fbb2-11de-b7cb-b1160b2c2156" ]
[ [ [ 1, 259 ] ] ]
69c72115e44f36a527b7a9c69f8ad6bb797cd407
e31046aee3ad2d4600c7f35aaeeba76ee2b99039
/trunk/libs/bullet/includes/LinearMath/btTransform.h
07c9b2e00d7692aa5fb00137bb1094ff171da500
[]
no_license
BackupTheBerlios/trinitas-svn
ddea265cf47aff3e8853bf6d46861e0ed3031ea1
7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca
refs/heads/master
2021-01-23T08:14:44.215249
2009-02-18T19:37:51
2009-02-18T19:37:51
40,749,519
0
0
null
null
null
null
UTF-8
C++
false
false
5,165
h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef btTransform_H #define btTransform_H #include "btVector3.h" #include "btMatrix3x3.h" ///The btTransform class supports rigid transforms with only translation and rotation and no scaling/shear. ///It can be used in combination with btVector3, btQuaternion and btMatrix3x3 linear algebra classes. class btTransform { public: btTransform() {} explicit SIMD_FORCE_INLINE btTransform(const btQuaternion& q, const btVector3& c = btVector3(btScalar(0), btScalar(0), btScalar(0))) : m_basis(q), m_origin(c) {} explicit SIMD_FORCE_INLINE btTransform(const btMatrix3x3& b, const btVector3& c = btVector3(btScalar(0), btScalar(0), btScalar(0))) : m_basis(b), m_origin(c) {} SIMD_FORCE_INLINE btTransform (const btTransform& other) : m_basis(other.m_basis), m_origin(other.m_origin) { } SIMD_FORCE_INLINE btTransform& operator=(const btTransform& other) { m_basis = other.m_basis; m_origin = other.m_origin; return *this; } SIMD_FORCE_INLINE void mult(const btTransform& t1, const btTransform& t2) { m_basis = t1.m_basis * t2.m_basis; m_origin = t1(t2.m_origin); } /* void multInverseLeft(const btTransform& t1, const btTransform& t2) { btVector3 v = t2.m_origin - t1.m_origin; m_basis = btMultTransposeLeft(t1.m_basis, t2.m_basis); m_origin = v * t1.m_basis; } */ SIMD_FORCE_INLINE btVector3 operator()(const btVector3& x) const { return btVector3(m_basis[0].dot(x) + m_origin.x(), m_basis[1].dot(x) + m_origin.y(), m_basis[2].dot(x) + m_origin.z()); } SIMD_FORCE_INLINE btVector3 operator*(const btVector3& x) const { return (*this)(x); } SIMD_FORCE_INLINE btMatrix3x3& getBasis() { return m_basis; } SIMD_FORCE_INLINE const btMatrix3x3& getBasis() const { return m_basis; } SIMD_FORCE_INLINE btVector3& getOrigin() { return m_origin; } SIMD_FORCE_INLINE const btVector3& getOrigin() const { return m_origin; } btQuaternion getRotation() const { btQuaternion q; m_basis.getRotation(q); return q; } void setFromOpenGLMatrix(const btScalar *m) { m_basis.setFromOpenGLSubMatrix(m); m_origin.setValue(m[12],m[13],m[14]); } void getOpenGLMatrix(btScalar *m) const { m_basis.getOpenGLSubMatrix(m); m[12] = m_origin.x(); m[13] = m_origin.y(); m[14] = m_origin.z(); m[15] = btScalar(1.0); } SIMD_FORCE_INLINE void setOrigin(const btVector3& origin) { m_origin = origin; } SIMD_FORCE_INLINE btVector3 invXform(const btVector3& inVec) const; SIMD_FORCE_INLINE void setBasis(const btMatrix3x3& basis) { m_basis = basis; } SIMD_FORCE_INLINE void setRotation(const btQuaternion& q) { m_basis.setRotation(q); } void setIdentity() { m_basis.setIdentity(); m_origin.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); } btTransform& operator*=(const btTransform& t) { m_origin += m_basis * t.m_origin; m_basis *= t.m_basis; return *this; } btTransform inverse() const { btMatrix3x3 inv = m_basis.transpose(); return btTransform(inv, inv * -m_origin); } btTransform inverseTimes(const btTransform& t) const; btTransform operator*(const btTransform& t) const; static btTransform getIdentity() { btTransform tr; tr.setIdentity(); return tr; } private: btMatrix3x3 m_basis; btVector3 m_origin; }; SIMD_FORCE_INLINE btVector3 btTransform::invXform(const btVector3& inVec) const { btVector3 v = inVec - m_origin; return (m_basis.transpose() * v); } SIMD_FORCE_INLINE btTransform btTransform::inverseTimes(const btTransform& t) const { btVector3 v = t.getOrigin() - m_origin; return btTransform(m_basis.transposeTimes(t.m_basis), v * m_basis); } SIMD_FORCE_INLINE btTransform btTransform::operator*(const btTransform& t) const { return btTransform(m_basis * t.m_basis, (*this)(t.m_origin)); } SIMD_FORCE_INLINE bool operator==(const btTransform& t1, const btTransform& t2) { return ( t1.getBasis() == t2.getBasis() && t1.getOrigin() == t2.getOrigin() ); } #endif
[ "paradoxon@ab3bda7c-5b37-0410-9911-e7f4556ba333" ]
[ [ [ 1, 207 ] ] ]
5b048f7a0cc11d524af7a6a925145f9b9907a20a
9420f67e448d4990326fd19841dd3266a96601c3
/ mcvr/mcvr/LookbackCall.h
0b8df2a86514c0f7c866b834602d7f7b3e99b609
[]
no_license
xrr/mcvr
4d8d7880c2fd50e41352fae1b9ede0231cf970a2
b8d3b3c46cfddee281e099945cee8d844cea4e23
refs/heads/master
2020-06-05T11:59:27.857504
2010-02-24T19:32:21
2010-02-24T19:32:21
32,275,830
0
0
null
null
null
null
UTF-8
C++
false
false
186
h
#pragma once #include "Payoff.h" class LookbackCall : public Payoff { public: double K; LookbackCall(double=110); ~LookbackCall(void); double operator()(Trajectory*); };
[ "romain.rousseau@fa0ec5f0-0fe6-11df-8179-3f26cfb4ba5f" ]
[ [ [ 1, 12 ] ] ]
f9a4601b7aefed8e387976c51cae9971e0664200
e46cae4635b79c4016ad85562018214a8305de97
/WinArena/Inventory.cpp
c4464e53240cca3bfae032101c04af361583a179
[]
no_license
basecq/opentesarenapp
febea5fddab920d5987f8067420d0b410aa95656
4b6d097d7c40352c62f9f95068e89df44e323832
refs/heads/master
2021-01-18T01:10:14.561315
2009-10-12T14:32:01
2009-10-12T14:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
308
cpp
///////////////////////////////////////////////////////////////////////////// // // $Header: /WinArena/Inventory.cpp 1 12/31/06 11:28a Lee $ // // File: Inventory.cpp // ///////////////////////////////////////////////////////////////////////////// #include "WinArena.h" #include "Inventory.h"
[ [ [ 1, 11 ] ] ]
3591c9cd1afee368123229150297960a10524f31
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/248.cpp
e142f74b934243f4e8fdd68a31082b604b98652f
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
6,905
cpp
///////////////////////////////////////////////////////////////////// // Mapper 248 void NES_mapper248_Init() { g_NESmapper.Reset = NES_mapper248_Reset; g_NESmapper.MemoryWriteSaveRAM = NES_mapper248_MemoryWriteSaveRAM; g_NESmapper.MemoryWrite = NES_mapper248_MemoryWrite; g_NESmapper.HSync = NES_mapper248_HSync; } void NES_mapper248_Reset() { // clear registers FIRST!!! int i; for(i = 0; i < 8; i++) g_NESmapper.Mapper248.regs[i] = 0x00; // set CPU bank pointers g_NESmapper.Mapper248.prg0 = 0; g_NESmapper.Mapper248.prg1 = 1; NES_mapper248_MMC3_set_CPU_banks(); // set VROM banks g_NESmapper.Mapper248.chr01 = 0; g_NESmapper.Mapper248.chr23 = 2; g_NESmapper.Mapper248.chr4 = 4; g_NESmapper.Mapper248.chr5 = 5; g_NESmapper.Mapper248.chr6 = 6; g_NESmapper.Mapper248.chr7 = 7; NES_mapper248_MMC3_set_PPU_banks(); g_NESmapper.Mapper248.irq_enabled = 0; g_NESmapper.Mapper248.irq_counter = 0; g_NESmapper.Mapper248.irq_latch = 0; } void NES_mapper248_MemoryWriteSaveRAM(uint32 addr, uint8 data) { g_NESmapper.set_CPU_banks4(2*data,2*data+1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); } void NES_mapper248_MemoryWrite(uint32 addr, uint8 data) { switch(addr & 0xE001) { case 0x8000: { g_NESmapper.Mapper248.regs[0] = data; NES_mapper248_MMC3_set_PPU_banks(); NES_mapper248_MMC3_set_CPU_banks(); } break; case 0x8001: { uint32 bank_num; g_NESmapper.Mapper248.regs[1] = data; bank_num = g_NESmapper.Mapper248.regs[1]; switch(g_NESmapper.Mapper248.regs[0] & 0x07) { case 0x00: { //if(g_NESmapper.num_1k_VROM_banks) { bank_num &= 0xfe; g_NESmapper.Mapper248.chr01 = bank_num; NES_mapper248_MMC3_set_PPU_banks(); } } break; case 0x01: { //if(g_NESmapper.num_1k_VROM_banks) { bank_num &= 0xfe; g_NESmapper.Mapper248.chr23 = bank_num; NES_mapper248_MMC3_set_PPU_banks(); } } break; case 0x02: { //if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper248.chr4 = bank_num; NES_mapper248_MMC3_set_PPU_banks(); } } break; case 0x03: { //if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper248.chr5 = bank_num; NES_mapper248_MMC3_set_PPU_banks(); } } break; case 0x04: { //if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper248.chr6 = bank_num; NES_mapper248_MMC3_set_PPU_banks(); } } break; case 0x05: { //if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper248.chr7 = bank_num; NES_mapper248_MMC3_set_PPU_banks(); } } break; case 0x06: { g_NESmapper.Mapper248.prg0 = bank_num; NES_mapper248_MMC3_set_CPU_banks(); } break; case 0x07: { g_NESmapper.Mapper248.prg1 = bank_num; NES_mapper248_MMC3_set_CPU_banks(); } break; } } break; case 0xA000: { g_NESmapper.Mapper248.regs[2] = data; if(NES_ROM_get_mirroring() != NES_PPU_MIRROR_FOUR_SCREEN) { if(data & 0x01) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } } } break; case 0xA001: { if(data & 0x80) { // enable save RAM $6000-$7FFF } else { // disable save RAM $6000-$7FFF } } break; case 0xC000: { g_NESmapper.Mapper248.irq_counter = g_NESmapper.Mapper248.irq_latch = 0xbe; g_NESmapper.Mapper248.irq_enabled = 0; } break; case 0xC001: { g_NESmapper.Mapper248.irq_counter = g_NESmapper.Mapper248.irq_latch = 0xbe; g_NESmapper.Mapper248.irq_enabled = 1; } break; case 0xE000: { g_NESmapper.Mapper248.irq_enabled = 0; } break; case 0xE001: { g_NESmapper.Mapper248.irq_enabled = 1; } break; } } void NES_mapper248_HSync(uint32 scanline) { if(g_NESmapper.Mapper248.irq_enabled) { if((scanline >= 0) && (scanline <= 239)) { if(NES_PPU_spr_enabled() || NES_PPU_bg_enabled()) { if(!(g_NESmapper.Mapper248.irq_counter--)) { g_NESmapper.Mapper248.irq_counter = g_NESmapper.Mapper248.irq_latch; NES6502_DoIRQ(); } } } } } void NES_mapper248_MMC3_set_CPU_banks() { if(g_NESmapper.Mapper248.regs[0] & 0x40) { g_NESmapper.set_CPU_banks4(g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.Mapper248.prg1,g_NESmapper.Mapper248.prg0,g_NESmapper.num_8k_ROM_banks-1); } else { g_NESmapper.set_CPU_banks4(g_NESmapper.Mapper248.prg0,g_NESmapper.Mapper248.prg1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); } } void NES_mapper248_MMC3_set_PPU_banks() { if(g_NESmapper.Mapper248.regs[0] & 0x80) { g_NESmapper.set_PPU_banks8(g_NESmapper.Mapper248.chr4,g_NESmapper.Mapper248.chr5,g_NESmapper.Mapper248.chr6,g_NESmapper.Mapper248.chr7,g_NESmapper.Mapper248.chr01,g_NESmapper.Mapper248.chr01+1,g_NESmapper.Mapper248.chr23,g_NESmapper.Mapper248.chr23+1); } else { g_NESmapper.set_PPU_banks8(g_NESmapper.Mapper248.chr01,g_NESmapper.Mapper248.chr01+1,g_NESmapper.Mapper248.chr23,g_NESmapper.Mapper248.chr23+1,g_NESmapper.Mapper248.chr4,g_NESmapper.Mapper248.chr5,g_NESmapper.Mapper248.chr6,g_NESmapper.Mapper248.chr7); } } #define MAP248_ROM(ptr) (((ptr)-NES_ROM_get_ROM_banks()) >> 13) #define MAP248_VROM(ptr) (((ptr)-NES_ROM_get_VROM_banks()) >> 10) void NES_mapper248_SNSS_fixup() // HACK HACK HACK HACK { nes6502_context context; NES6502_GetContext(&context); g_NESmapper.Mapper248.prg0 = MAP248_ROM(context.mem_page[(g_NESmapper.Mapper248.regs[0] & 0x40) ? 6 : 4]); g_NESmapper.Mapper248.prg1 = MAP248_ROM(context.mem_page[5]); if(g_NESmapper.Mapper248.regs[0] & 0x80) { g_NESmapper.Mapper248.chr01 = MAP248_VROM(g_PPU.PPU_VRAM_banks[4]); g_NESmapper.Mapper248.chr23 = MAP248_VROM(g_PPU.PPU_VRAM_banks[6]); g_NESmapper.Mapper248.chr4 = MAP248_VROM(g_PPU.PPU_VRAM_banks[0]); g_NESmapper.Mapper248.chr5 = MAP248_VROM(g_PPU.PPU_VRAM_banks[1]); g_NESmapper.Mapper248.chr6 = MAP248_VROM(g_PPU.PPU_VRAM_banks[2]); g_NESmapper.Mapper248.chr7 = MAP248_VROM(g_PPU.PPU_VRAM_banks[3]); } else { g_NESmapper.Mapper248.chr01 = MAP248_VROM(g_PPU.PPU_VRAM_banks[0]); g_NESmapper.Mapper248.chr23 = MAP248_VROM(g_PPU.PPU_VRAM_banks[2]); g_NESmapper.Mapper248.chr4 = MAP248_VROM(g_PPU.PPU_VRAM_banks[4]); g_NESmapper.Mapper248.chr5 = MAP248_VROM(g_PPU.PPU_VRAM_banks[5]); g_NESmapper.Mapper248.chr6 = MAP248_VROM(g_PPU.PPU_VRAM_banks[6]); g_NESmapper.Mapper248.chr7 = MAP248_VROM(g_PPU.PPU_VRAM_banks[7]); } } /////////////////////////////////////////////////////////////////////
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 274 ] ] ]
6ba30c63b6c495db305783a9f3a43d0be80826df
3d677d3bcbd5322bd814adae4d6c6cf45dc67666
/JuceLibraryCode/modules/juce_core/text/juce_String.cpp
e6ce77e93d02cbbd1a8d15b7648af0a9030ed36f
[]
no_license
sonic59/JuceS2Text
281e5fc7fa31e715b4d7b1459181637e4f684974
e116dc0dfc20222028bab0180f6b93b2f8a2c40c
refs/heads/master
2016-09-10T18:40:38.239670
2011-11-25T17:37:21
2011-11-25T17:37:21
2,850,515
0
0
null
null
null
null
UTF-8
C++
false
false
82,228
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #if JUCE_MSVC #pragma warning (push) #pragma warning (disable: 4514 4996) #endif #include <locale> BEGIN_JUCE_NAMESPACE NewLine newLine; #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default." #endif #if JUCE_NATIVE_WCHAR_IS_UTF8 typedef CharPointer_UTF8 CharPointer_wchar_t; #elif JUCE_NATIVE_WCHAR_IS_UTF16 typedef CharPointer_UTF16 CharPointer_wchar_t; #else typedef CharPointer_UTF32 CharPointer_wchar_t; #endif static inline CharPointer_wchar_t castToCharPointer_wchar_t (const void* t) noexcept { return CharPointer_wchar_t (static_cast <const CharPointer_wchar_t::CharType*> (t)); } //============================================================================== class StringHolder { public: StringHolder() : refCount (0x3fffffff), allocatedNumBytes (sizeof (*text)) { text[0] = 0; } typedef String::CharPointerType CharPointerType; typedef String::CharPointerType::CharType CharType; //============================================================================== static const CharPointerType createUninitialisedBytes (const size_t numBytes) { StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) - sizeof (CharType) + numBytes]); s->refCount.value = 0; s->allocatedNumBytes = numBytes; return CharPointerType (s->text); } template <class CharPointer> static const CharPointerType createFromCharPointer (const CharPointer& text) { if (text.getAddress() == nullptr || text.isEmpty()) return getEmpty(); CharPointer t (text); size_t bytesNeeded = sizeof (CharType); while (! t.isEmpty()) bytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance()); const CharPointerType dest (createUninitialisedBytes (bytesNeeded)); CharPointerType (dest).writeAll (text); return dest; } template <class CharPointer> static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars) { if (text.getAddress() == nullptr || text.isEmpty() || maxChars == 0) return getEmpty(); CharPointer end (text); size_t numChars = 0; size_t bytesNeeded = sizeof (CharType); while (numChars < maxChars && ! end.isEmpty()) { bytesNeeded += CharPointerType::getBytesRequiredFor (end.getAndAdvance()); ++numChars; } const CharPointerType dest (createUninitialisedBytes (bytesNeeded)); CharPointerType (dest).writeWithCharLimit (text, (int) numChars + 1); return dest; } template <class CharPointer> static const CharPointerType createFromCharPointer (const CharPointer& start, const CharPointer& end) { if (start.getAddress() == nullptr || start.isEmpty()) return getEmpty(); CharPointer e (start); int numChars = 0; size_t bytesNeeded = sizeof (CharType); while (e < end && ! e.isEmpty()) { bytesNeeded += CharPointerType::getBytesRequiredFor (e.getAndAdvance()); ++numChars; } const CharPointerType dest (createUninitialisedBytes (bytesNeeded)); CharPointerType (dest).writeWithCharLimit (start, numChars + 1); return dest; } static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars) { const CharPointerType dest (createUninitialisedBytes (numChars * sizeof (CharType) + sizeof (CharType))); CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1)); return dest; } static inline const CharPointerType getEmpty() noexcept { return CharPointerType (empty.text); } //============================================================================== static void retain (const CharPointerType& text) noexcept { ++(bufferFromText (text)->refCount); } static inline void release (StringHolder* const b) noexcept { if (--(b->refCount) == -1 && b != &empty) delete[] reinterpret_cast <char*> (b); } static void release (const CharPointerType& text) noexcept { release (bufferFromText (text)); } //============================================================================== static CharPointerType makeUnique (const CharPointerType& text) { StringHolder* const b = bufferFromText (text); if (b->refCount.get() <= 0) return text; CharPointerType newText (createUninitialisedBytes (b->allocatedNumBytes)); memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes); release (b); return newText; } static CharPointerType makeUniqueWithByteSize (const CharPointerType& text, size_t numBytes) { StringHolder* const b = bufferFromText (text); if (b->refCount.get() <= 0 && b->allocatedNumBytes >= numBytes) return text; CharPointerType newText (createUninitialisedBytes (jmax (b->allocatedNumBytes, numBytes))); memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes); release (b); return newText; } static size_t getAllocatedNumBytes (const CharPointerType& text) noexcept { return bufferFromText (text)->allocatedNumBytes; } //============================================================================== Atomic<int> refCount; size_t allocatedNumBytes; CharType text[1]; static StringHolder empty; private: static inline StringHolder* bufferFromText (const CharPointerType& text) noexcept { // (Can't use offsetof() here because of warnings about this not being a POD) return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress()) - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1)); } void compileTimeChecks() { // Let me know if any of these assertions fail on your system! #if JUCE_NATIVE_WCHAR_IS_UTF8 static_jassert (sizeof (wchar_t) == 1); #elif JUCE_NATIVE_WCHAR_IS_UTF16 static_jassert (sizeof (wchar_t) == 2); #elif JUCE_NATIVE_WCHAR_IS_UTF32 static_jassert (sizeof (wchar_t) == 4); #else #error "native wchar_t size is unknown" #endif } }; StringHolder StringHolder::empty; const String String::empty; //============================================================================== void String::preallocateBytes (const size_t numBytesNeeded) { text = StringHolder::makeUniqueWithByteSize (text, numBytesNeeded + sizeof (CharPointerType::CharType)); } //============================================================================== String::String() noexcept : text (StringHolder::getEmpty()) { } String::~String() noexcept { StringHolder::release (text); } String::String (const String& other) noexcept : text (other.text) { StringHolder::retain (text); } void String::swapWith (String& other) noexcept { std::swap (text, other.text); } String& String::operator= (const String& other) noexcept { StringHolder::retain (other.text); StringHolder::release (text.atomicSwap (other.text)); return *this; } #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS String::String (String&& other) noexcept : text (other.text) { other.text = StringHolder::getEmpty(); } String& String::operator= (String&& other) noexcept { std::swap (text, other.text); return *this; } #endif inline String::PreallocationBytes::PreallocationBytes (const size_t numBytes_) : numBytes (numBytes_) {} String::String (const PreallocationBytes& preallocationSize) : text (StringHolder::createUninitialisedBytes (preallocationSize.numBytes + sizeof (CharPointerType::CharType))) { } //============================================================================== String::String (const char* const t) : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t))) { /* If you get an assertion here, then you're trying to create a string from 8-bit data that contains values greater than 127. These can NOT be correctly converted to unicode because there's no way for the String class to know what encoding was used to create them. The source data could be UTF-8, ASCII or one of many local code-pages. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit string to the String class - so for example if your source data is actually UTF-8, you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to correctly convert the multi-byte characters to unicode. It's *highly* recommended that you use UTF-8 with escape characters in your source code to represent extended characters, because there's no other way to represent these strings in a way that isn't dependent on the compiler, source code editor and platform. */ jassert (t == nullptr || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max())); } String::String (const char* const t, const size_t maxChars) : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars)) { /* If you get an assertion here, then you're trying to create a string from 8-bit data that contains values greater than 127. These can NOT be correctly converted to unicode because there's no way for the String class to know what encoding was used to create them. The source data could be UTF-8, ASCII or one of many local code-pages. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit string to the String class - so for example if your source data is actually UTF-8, you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to correctly convert the multi-byte characters to unicode. It's *highly* recommended that you use UTF-8 with escape characters in your source code to represent extended characters, because there's no other way to represent these strings in a way that isn't dependent on the compiler, source code editor and platform. */ jassert (t == nullptr || CharPointer_ASCII::isValidString (t, (int) maxChars)); } String::String (const wchar_t* const t) : text (StringHolder::createFromCharPointer (castToCharPointer_wchar_t (t))) {} String::String (const CharPointer_UTF8& t) : text (StringHolder::createFromCharPointer (t)) {} String::String (const CharPointer_UTF16& t) : text (StringHolder::createFromCharPointer (t)) {} String::String (const CharPointer_UTF32& t) : text (StringHolder::createFromCharPointer (t)) {} String::String (const CharPointer_ASCII& t) : text (StringHolder::createFromCharPointer (t)) {} String::String (const CharPointer_UTF8& t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {} String::String (const CharPointer_UTF16& t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {} String::String (const CharPointer_UTF32& t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {} String::String (const wchar_t* const t, size_t maxChars) : text (StringHolder::createFromCharPointer (castToCharPointer_wchar_t (t), maxChars)) {} String::String (const CharPointer_UTF8& start, const CharPointer_UTF8& end) : text (StringHolder::createFromCharPointer (start, end)) {} String::String (const CharPointer_UTF16& start, const CharPointer_UTF16& end) : text (StringHolder::createFromCharPointer (start, end)) {} String::String (const CharPointer_UTF32& start, const CharPointer_UTF32& end) : text (StringHolder::createFromCharPointer (start, end)) {} String String::charToString (const juce_wchar character) { String result (PreallocationBytes (CharPointerType::getBytesRequiredFor (character))); CharPointerType t (result.text); t.write (character); t.writeNull(); return result; } //============================================================================== namespace NumberToStringConverters { // pass in a pointer to the END of a buffer.. char* numberToString (char* t, const int64 n) noexcept { *--t = 0; int64 v = (n >= 0) ? n : -n; do { *--t = (char) ('0' + (int) (v % 10)); v /= 10; } while (v > 0); if (n < 0) *--t = '-'; return t; } char* numberToString (char* t, uint64 v) noexcept { *--t = 0; do { *--t = (char) ('0' + (int) (v % 10)); v /= 10; } while (v > 0); return t; } char* numberToString (char* t, const int n) noexcept { if (n == (int) 0x80000000) // (would cause an overflow) return numberToString (t, (int64) n); *--t = 0; int v = abs (n); do { *--t = (char) ('0' + (v % 10)); v /= 10; } while (v > 0); if (n < 0) *--t = '-'; return t; } char* numberToString (char* t, unsigned int v) noexcept { *--t = 0; do { *--t = (char) ('0' + (v % 10)); v /= 10; } while (v > 0); return t; } char getDecimalPoint() { static char dp = (char) #if JUCE_VC7_OR_EARLIER std::_USE (std::locale(), std::numpunct <char>).decimal_point(); #else std::use_facet <std::numpunct <char> > (std::locale()).decimal_point(); #endif return dp; } char* doubleToString (char* buffer, const int numChars, double n, int numDecPlaces, size_t& len) noexcept { if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20) { char* const end = buffer + numChars; char* t = end; int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5); *--t = (char) 0; while (numDecPlaces >= 0 || v > 0) { if (numDecPlaces == 0) *--t = (char) getDecimalPoint(); *--t = (char) ('0' + (v % 10)); v /= 10; --numDecPlaces; } if (n < 0) *--t = '-'; len = (size_t) (end - t - 1); return t; } else { len = (size_t) sprintf (buffer, "%.9g", n); return buffer; } } template <typename IntegerType> const String::CharPointerType createFromInteger (const IntegerType number) { char buffer [32]; char* const end = buffer + numElementsInArray (buffer); char* const start = numberToString (end, number); return StringHolder::createFromFixedLength (start, (size_t) (end - start - 1)); } const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces) { char buffer [48]; size_t len; char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len); return StringHolder::createFromFixedLength (start, len); } } //============================================================================== String::String (const int number) : text (NumberToStringConverters::createFromInteger (number)) {} String::String (const unsigned int number) : text (NumberToStringConverters::createFromInteger (number)) {} String::String (const short number) : text (NumberToStringConverters::createFromInteger ((int) number)) {} String::String (const unsigned short number) : text (NumberToStringConverters::createFromInteger ((unsigned int) number)) {} String::String (const int64 number) : text (NumberToStringConverters::createFromInteger (number)) {} String::String (const uint64 number) : text (NumberToStringConverters::createFromInteger (number)) {} String::String (const float number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces)) {} String::String (const double number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces)) {} //============================================================================== int String::length() const noexcept { return (int) text.length(); } size_t String::getByteOffsetOfEnd() const noexcept { return (size_t) (((char*) text.findTerminatingNull().getAddress()) - (char*) text.getAddress()); } const juce_wchar String::operator[] (int index) const noexcept { jassert (index == 0 || (index > 0 && index <= (int) text.lengthUpTo ((size_t) index + 1))); return text [index]; } int String::hashCode() const noexcept { CharPointerType t (text); int result = 0; while (! t.isEmpty()) result = 31 * result + (int) t.getAndAdvance(); return result; } int64 String::hashCode64() const noexcept { CharPointerType t (text); int64 result = 0; while (! t.isEmpty()) result = 101 * result + t.getAndAdvance(); return result; } //============================================================================== JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; } JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const char* const s2) noexcept { return s1.compare (s2) == 0; } JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) == 0; } JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF8& s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF16& s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF32& s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; } JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const char* const s2) noexcept { return s1.compare (s2) != 0; } JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) != 0; } JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF8& s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF16& s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF32& s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } JUCE_API bool JUCE_CALLTYPE operator> (const String& s1, const String& s2) noexcept { return s1.compare (s2) > 0; } JUCE_API bool JUCE_CALLTYPE operator< (const String& s1, const String& s2) noexcept { return s1.compare (s2) < 0; } JUCE_API bool JUCE_CALLTYPE operator>= (const String& s1, const String& s2) noexcept { return s1.compare (s2) >= 0; } JUCE_API bool JUCE_CALLTYPE operator<= (const String& s1, const String& s2) noexcept { return s1.compare (s2) <= 0; } bool String::equalsIgnoreCase (const wchar_t* const t) const noexcept { return t != nullptr ? text.compareIgnoreCase (castToCharPointer_wchar_t (t)) == 0 : isEmpty(); } bool String::equalsIgnoreCase (const char* const t) const noexcept { return t != nullptr ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0 : isEmpty(); } bool String::equalsIgnoreCase (const String& other) const noexcept { return text == other.text || text.compareIgnoreCase (other.text) == 0; } int String::compare (const String& other) const noexcept { return (text == other.text) ? 0 : text.compare (other.text); } int String::compare (const char* const other) const noexcept { return text.compare (CharPointer_UTF8 (other)); } int String::compare (const wchar_t* const other) const noexcept { return text.compare (castToCharPointer_wchar_t (other)); } int String::compareIgnoreCase (const String& other) const noexcept { return (text == other.text) ? 0 : text.compareIgnoreCase (other.text); } int String::compareLexicographically (const String& other) const noexcept { CharPointerType s1 (text); while (! (s1.isEmpty() || s1.isLetterOrDigit())) ++s1; CharPointerType s2 (other.text); while (! (s2.isEmpty() || s2.isLetterOrDigit())) ++s2; return s1.compareIgnoreCase (s2); } //============================================================================== void String::append (const String& textToAppend, size_t maxCharsToTake) { appendCharPointer (textToAppend.text, maxCharsToTake); } String& String::operator+= (const wchar_t* const t) { appendCharPointer (castToCharPointer_wchar_t (t)); return *this; } String& String::operator+= (const char* const t) { /* If you get an assertion here, then you're trying to create a string from 8-bit data that contains values greater than 127. These can NOT be correctly converted to unicode because there's no way for the String class to know what encoding was used to create them. The source data could be UTF-8, ASCII or one of many local code-pages. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit string to the String class - so for example if your source data is actually UTF-8, you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to correctly convert the multi-byte characters to unicode. It's *highly* recommended that you use UTF-8 with escape characters in your source code to represent extended characters, because there's no other way to represent these strings in a way that isn't dependent on the compiler, source code editor and platform. */ jassert (t == nullptr || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max())); appendCharPointer (CharPointer_ASCII (t)); return *this; } String& String::operator+= (const String& other) { if (isEmpty()) return operator= (other); appendCharPointer (other.text); return *this; } String& String::operator+= (const char ch) { const char asString[] = { ch, 0 }; return operator+= (asString); } String& String::operator+= (const wchar_t ch) { const wchar_t asString[] = { ch, 0 }; return operator+= (asString); } #if ! JUCE_NATIVE_WCHAR_IS_UTF32 String& String::operator+= (const juce_wchar ch) { const juce_wchar asString[] = { ch, 0 }; appendCharPointer (CharPointer_UTF32 (asString)); return *this; } #endif String& String::operator+= (const int number) { char buffer [16]; char* const end = buffer + numElementsInArray (buffer); char* const start = NumberToStringConverters::numberToString (end, number); const int numExtraChars = (int) (end - start); if (numExtraChars > 0) { const size_t byteOffsetOfNull = getByteOffsetOfEnd(); const size_t newBytesNeeded = sizeof (CharPointerType::CharType) + byteOffsetOfNull + sizeof (CharPointerType::CharType) * numExtraChars; text = StringHolder::makeUniqueWithByteSize (text, newBytesNeeded); CharPointerType newEnd (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)); newEnd.writeWithCharLimit (CharPointer_ASCII (start), numExtraChars); } return *this; } //============================================================================== JUCE_API String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2) { String s (string1); return s += string2; } JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* const string1, const String& string2) { String s (string1); return s += string2; } JUCE_API String JUCE_CALLTYPE operator+ (const char s1, const String& s2) { return String::charToString ((juce_wchar) (uint8) s1) + s2; } JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t s1, const String& s2) { return String::charToString (s1) + s2; } #if ! JUCE_NATIVE_WCHAR_IS_UTF32 JUCE_API String JUCE_CALLTYPE operator+ (const juce_wchar s1, const String& s2) { return String::charToString (s1) + s2; } #endif JUCE_API String JUCE_CALLTYPE operator+ (String s1, const String& s2) { return s1 += s2; } JUCE_API String JUCE_CALLTYPE operator+ (String s1, const char* const s2) { return s1 += s2; } JUCE_API String JUCE_CALLTYPE operator+ (String s1, const wchar_t* s2) { return s1 += s2; } JUCE_API String JUCE_CALLTYPE operator+ (String s1, const char s2) { return s1 += s2; } JUCE_API String JUCE_CALLTYPE operator+ (String s1, const wchar_t s2) { return s1 += s2; } #if ! JUCE_NATIVE_WCHAR_IS_UTF32 JUCE_API String JUCE_CALLTYPE operator+ (String s1, const juce_wchar s2) { return s1 += s2; } #endif JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const char s2) { return s1 += s2; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const wchar_t s2) { return s1 += s2; } #if ! JUCE_NATIVE_WCHAR_IS_UTF32 JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const juce_wchar s2) { return s1 += s2; } #endif JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const char* const s2) { return s1 += s2; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const wchar_t* const s2) { return s1 += s2; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const String& s2) { return s1 += s2; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const short number) { return s1 += (int) number; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const int number) { return s1 += number; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const long number) { return s1 += (int) number; } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const float number) { return s1 += String (number); } JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const double number) { return s1 += String (number); } JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text) { const int numBytes = text.getNumBytesAsUTF8(); #if (JUCE_STRING_UTF_TYPE == 8) stream.write (text.getCharPointer().getAddress(), numBytes); #else // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind // if lots of large, persistent strings were to be written to streams). HeapBlock<char> temp (numBytes + 1); CharPointer_UTF8 (temp).writeAll (text.getCharPointer()); stream.write (temp, numBytes); #endif return stream; } JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&) { return string1 += NewLine::getDefault(); } //============================================================================== int String::indexOfChar (const juce_wchar character) const noexcept { return text.indexOf (character); } int String::indexOfChar (const int startIndex, const juce_wchar character) const noexcept { CharPointerType t (text); for (int i = 0; ! t.isEmpty(); ++i) { if (i >= startIndex) { if (t.getAndAdvance() == character) return i; } else { ++t; } } return -1; } int String::lastIndexOfChar (const juce_wchar character) const noexcept { CharPointerType t (text); int last = -1; for (int i = 0; ! t.isEmpty(); ++i) if (t.getAndAdvance() == character) last = i; return last; } int String::indexOfAnyOf (const String& charactersToLookFor, const int startIndex, const bool ignoreCase) const noexcept { CharPointerType t (text); for (int i = 0; ! t.isEmpty(); ++i) { if (i >= startIndex) { if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0) return i; } else { ++t; } } return -1; } int String::indexOf (const String& other) const noexcept { return other.isEmpty() ? 0 : text.indexOf (other.text); } int String::indexOfIgnoreCase (const String& other) const noexcept { return other.isEmpty() ? 0 : CharacterFunctions::indexOfIgnoreCase (text, other.text); } int String::indexOf (const int startIndex, const String& other) const noexcept { if (other.isEmpty()) return -1; CharPointerType t (text); for (int i = startIndex; --i >= 0;) { if (t.isEmpty()) return -1; ++t; } int found = t.indexOf (other.text); if (found >= 0) found += startIndex; return found; } int String::indexOfIgnoreCase (const int startIndex, const String& other) const noexcept { if (other.isEmpty()) return -1; CharPointerType t (text); for (int i = startIndex; --i >= 0;) { if (t.isEmpty()) return -1; ++t; } int found = CharacterFunctions::indexOfIgnoreCase (t, other.text); if (found >= 0) found += startIndex; return found; } int String::lastIndexOf (const String& other) const noexcept { if (other.isNotEmpty()) { const int len = other.length(); int i = length() - len; if (i >= 0) { CharPointerType n (text + i); while (i >= 0) { if (n.compareUpTo (other.text, len) == 0) return i; --n; --i; } } } return -1; } int String::lastIndexOfIgnoreCase (const String& other) const noexcept { if (other.isNotEmpty()) { const int len = other.length(); int i = length() - len; if (i >= 0) { CharPointerType n (text + i); while (i >= 0) { if (n.compareIgnoreCaseUpTo (other.text, len) == 0) return i; --n; --i; } } } return -1; } int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const noexcept { CharPointerType t (text); int last = -1; for (int i = 0; ! t.isEmpty(); ++i) if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0) last = i; return last; } bool String::contains (const String& other) const noexcept { return indexOf (other) >= 0; } bool String::containsChar (const juce_wchar character) const noexcept { return text.indexOf (character) >= 0; } bool String::containsIgnoreCase (const String& t) const noexcept { return indexOfIgnoreCase (t) >= 0; } int String::indexOfWholeWord (const String& word) const noexcept { if (word.isNotEmpty()) { CharPointerType t (text); const int wordLen = word.length(); const int end = (int) t.length() - wordLen; for (int i = 0; i <= end; ++i) { if (t.compareUpTo (word.text, wordLen) == 0 && (i == 0 || ! (t - 1).isLetterOrDigit()) && ! (t + wordLen).isLetterOrDigit()) return i; ++t; } } return -1; } int String::indexOfWholeWordIgnoreCase (const String& word) const noexcept { if (word.isNotEmpty()) { CharPointerType t (text); const int wordLen = word.length(); const int end = (int) t.length() - wordLen; for (int i = 0; i <= end; ++i) { if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0 && (i == 0 || ! (t - 1).isLetterOrDigit()) && ! (t + wordLen).isLetterOrDigit()) return i; ++t; } } return -1; } bool String::containsWholeWord (const String& wordToLookFor) const noexcept { return indexOfWholeWord (wordToLookFor) >= 0; } bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept { return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0; } //============================================================================== template <typename CharPointer> struct WildCardMatcher { static bool matches (CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept { for (;;) { const juce_wchar wc = wildcard.getAndAdvance(); if (wc == '*') return wildcard.isEmpty() || matchesAnywhere (wildcard, test, ignoreCase); if (! characterMatches (wc, test.getAndAdvance(), ignoreCase)) return false; if (wc == 0) return true; } } static bool characterMatches (const juce_wchar wc, const juce_wchar tc, const bool ignoreCase) noexcept { return (wc == tc) || (wc == '?' && tc != 0) || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (tc)); } static bool matchesAnywhere (const CharPointer& wildcard, CharPointer test, const bool ignoreCase) noexcept { for (; ! test.isEmpty(); ++test) if (matches (wildcard, test, ignoreCase)) return true; return false; } }; bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const noexcept { return WildCardMatcher<CharPointerType>::matches (wildcard.text, text, ignoreCase); } //============================================================================== String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat) { if (numberOfTimesToRepeat <= 0) return empty; String result (PreallocationBytes (stringToRepeat.getByteOffsetOfEnd() * numberOfTimesToRepeat)); CharPointerType n (result.text); while (--numberOfTimesToRepeat >= 0) n.writeAll (stringToRepeat.text); return result; } String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const { jassert (padCharacter != 0); int extraChars = minimumLength; CharPointerType end (text); while (! end.isEmpty()) { --extraChars; ++end; } if (extraChars <= 0 || padCharacter == 0) return *this; const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress()); String result (PreallocationBytes (currentByteSize + extraChars * CharPointerType::getBytesRequiredFor (padCharacter))); CharPointerType n (result.text); while (--extraChars >= 0) n.write (padCharacter); n.writeAll (text); return result; } String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const { jassert (padCharacter != 0); int extraChars = minimumLength; CharPointerType end (text); while (! end.isEmpty()) { --extraChars; ++end; } if (extraChars <= 0 || padCharacter == 0) return *this; const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress()); String result (PreallocationBytes (currentByteSize + extraChars * CharPointerType::getBytesRequiredFor (padCharacter))); CharPointerType n (result.text); n.writeAll (text); while (--extraChars >= 0) n.write (padCharacter); n.writeNull(); return result; } //============================================================================== String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const { if (index < 0) { // a negative index to replace from? jassertfalse; index = 0; } if (numCharsToReplace < 0) { // replacing a negative number of characters? numCharsToReplace = 0; jassertfalse; } int i = 0; CharPointerType insertPoint (text); while (i < index) { if (insertPoint.isEmpty()) { // replacing beyond the end of the string? jassertfalse; return *this + stringToInsert; } ++insertPoint; ++i; } CharPointerType startOfRemainder (insertPoint); i = 0; while (i < numCharsToReplace && ! startOfRemainder.isEmpty()) { ++startOfRemainder; ++i; } if (insertPoint == text && startOfRemainder.isEmpty()) return stringToInsert; const size_t initialBytes = (size_t) (((char*) insertPoint.getAddress()) - (char*) text.getAddress()); const size_t newStringBytes = stringToInsert.getByteOffsetOfEnd(); const size_t remainderBytes = (size_t) (((char*) startOfRemainder.findTerminatingNull().getAddress()) - (char*) startOfRemainder.getAddress()); const size_t newTotalBytes = initialBytes + newStringBytes + remainderBytes; if (newTotalBytes <= 0) return String::empty; String result (PreallocationBytes ((size_t) newTotalBytes)); char* dest = (char*) result.text.getAddress(); memcpy (dest, text.getAddress(), initialBytes); dest += initialBytes; memcpy (dest, stringToInsert.text.getAddress(), newStringBytes); dest += newStringBytes; memcpy (dest, startOfRemainder.getAddress(), remainderBytes); dest += remainderBytes; CharPointerType ((CharPointerType::CharType*) dest).writeNull(); return result; } String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const { const int stringToReplaceLen = stringToReplace.length(); const int stringToInsertLen = stringToInsert.length(); int i = 0; String result (*this); while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace) : result.indexOf (i, stringToReplace))) >= 0) { result = result.replaceSection (i, stringToReplaceLen, stringToInsert); i += stringToInsertLen; } return result; } class StringCreationHelper { public: StringCreationHelper (const size_t initialBytes) : source (nullptr), dest (nullptr), allocatedBytes (initialBytes), bytesWritten (0) { result.preallocateBytes (allocatedBytes); dest = result.getCharPointer(); } StringCreationHelper (const String::CharPointerType& source_) : source (source_), dest (nullptr), allocatedBytes (StringHolder::getAllocatedNumBytes (source)), bytesWritten (0) { result.preallocateBytes (allocatedBytes); dest = result.getCharPointer(); } void write (juce_wchar c) { bytesWritten += String::CharPointerType::getBytesRequiredFor (c); if (bytesWritten > allocatedBytes) { allocatedBytes += jmax ((size_t) 8, allocatedBytes / 16); const size_t destOffset = (size_t) (((char*) dest.getAddress()) - (char*) result.getCharPointer().getAddress()); result.preallocateBytes (allocatedBytes); dest = addBytesToPointer (result.getCharPointer().getAddress(), (int) destOffset); } dest.write (c); } String result; String::CharPointerType source; private: String::CharPointerType dest; size_t allocatedBytes, bytesWritten; }; String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const { if (! containsChar (charToReplace)) return *this; StringCreationHelper builder (text); for (;;) { juce_wchar c = builder.source.getAndAdvance(); if (c == charToReplace) c = charToInsert; builder.write (c); if (c == 0) break; } return builder.result; } String String::replaceCharacters (const String& charactersToReplace, const String& charactersToInsertInstead) const { StringCreationHelper builder (text); for (;;) { juce_wchar c = builder.source.getAndAdvance(); const int index = charactersToReplace.indexOfChar (c); if (index >= 0) c = charactersToInsertInstead [index]; builder.write (c); if (c == 0) break; } return builder.result; } //============================================================================== bool String::startsWith (const String& other) const noexcept { return text.compareUpTo (other.text, other.length()) == 0; } bool String::startsWithIgnoreCase (const String& other) const noexcept { return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0; } bool String::startsWithChar (const juce_wchar character) const noexcept { jassert (character != 0); // strings can't contain a null character! return *text == character; } bool String::endsWithChar (const juce_wchar character) const noexcept { jassert (character != 0); // strings can't contain a null character! if (text.isEmpty()) return false; CharPointerType t (text.findTerminatingNull()); return *--t == character; } bool String::endsWith (const String& other) const noexcept { CharPointerType end (text.findTerminatingNull()); CharPointerType otherEnd (other.text.findTerminatingNull()); while (end > text && otherEnd > other.text) { --end; --otherEnd; if (*end != *otherEnd) return false; } return otherEnd == other.text; } bool String::endsWithIgnoreCase (const String& other) const noexcept { CharPointerType end (text.findTerminatingNull()); CharPointerType otherEnd (other.text.findTerminatingNull()); while (end > text && otherEnd > other.text) { --end; --otherEnd; if (end.toLowerCase() != otherEnd.toLowerCase()) return false; } return otherEnd == other.text; } //============================================================================== String String::toUpperCase() const { StringCreationHelper builder (text); for (;;) { const juce_wchar c = builder.source.toUpperCase(); ++(builder.source); builder.write (c); if (c == 0) break; } return builder.result; } String String::toLowerCase() const { StringCreationHelper builder (text); for (;;) { const juce_wchar c = builder.source.toLowerCase(); ++(builder.source); builder.write (c); if (c == 0) break; } return builder.result; } //============================================================================== juce_wchar String::getLastCharacter() const noexcept { return isEmpty() ? juce_wchar() : text [length() - 1]; } String String::substring (int start, const int end) const { if (start < 0) start = 0; if (end <= start) return empty; int i = 0; CharPointerType t1 (text); while (i < start) { if (t1.isEmpty()) return empty; ++i; ++t1; } CharPointerType t2 (t1); while (i < end) { if (t2.isEmpty()) { if (start == 0) return *this; break; } ++i; ++t2; } return String (t1, t2); } String String::substring (int start) const { if (start <= 0) return *this; CharPointerType t (text); while (--start >= 0) { if (t.isEmpty()) return empty; ++t; } return String (t); } String String::dropLastCharacters (const int numberToDrop) const { return String (text, (size_t) jmax (0, length() - numberToDrop)); } String String::getLastCharacters (const int numCharacters) const { return String (text + jmax (0, length() - jmax (0, numCharacters))); } String String::fromFirstOccurrenceOf (const String& sub, const bool includeSubString, const bool ignoreCase) const { const int i = ignoreCase ? indexOfIgnoreCase (sub) : indexOf (sub); if (i < 0) return empty; return substring (includeSubString ? i : i + sub.length()); } String String::fromLastOccurrenceOf (const String& sub, const bool includeSubString, const bool ignoreCase) const { const int i = ignoreCase ? lastIndexOfIgnoreCase (sub) : lastIndexOf (sub); if (i < 0) return *this; return substring (includeSubString ? i : i + sub.length()); } String String::upToFirstOccurrenceOf (const String& sub, const bool includeSubString, const bool ignoreCase) const { const int i = ignoreCase ? indexOfIgnoreCase (sub) : indexOf (sub); if (i < 0) return *this; return substring (0, includeSubString ? i + sub.length() : i); } String String::upToLastOccurrenceOf (const String& sub, const bool includeSubString, const bool ignoreCase) const { const int i = ignoreCase ? lastIndexOfIgnoreCase (sub) : lastIndexOf (sub); if (i < 0) return *this; return substring (0, includeSubString ? i + sub.length() : i); } bool String::isQuotedString() const { const String trimmed (trimStart()); return trimmed[0] == '"' || trimmed[0] == '\''; } String String::unquoted() const { const int len = length(); if (len == 0) return empty; const juce_wchar lastChar = text [len - 1]; const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0; const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0; return substring (dropAtStart, len - dropAtEnd); } String String::quoted (const juce_wchar quoteCharacter) const { if (isEmpty()) return charToString (quoteCharacter) + quoteCharacter; String t (*this); if (! t.startsWithChar (quoteCharacter)) t = charToString (quoteCharacter) + t; if (! t.endsWithChar (quoteCharacter)) t += quoteCharacter; return t; } //============================================================================== static String::CharPointerType findTrimmedEnd (const String::CharPointerType& start, String::CharPointerType end) { while (end > start) { if (! (--end).isWhitespace()) { ++end; break; } } return end; } String String::trim() const { if (isNotEmpty()) { CharPointerType start (text.findEndOfWhitespace()); const CharPointerType end (start.findTerminatingNull()); CharPointerType trimmedEnd (findTrimmedEnd (start, end)); if (trimmedEnd <= start) return empty; else if (text < start || trimmedEnd < end) return String (start, trimmedEnd); } return *this; } String String::trimStart() const { if (isNotEmpty()) { const CharPointerType t (text.findEndOfWhitespace()); if (t != text) return String (t); } return *this; } String String::trimEnd() const { if (isNotEmpty()) { const CharPointerType end (text.findTerminatingNull()); CharPointerType trimmedEnd (findTrimmedEnd (text, end)); if (trimmedEnd < end) return String (text, trimmedEnd); } return *this; } String String::trimCharactersAtStart (const String& charactersToTrim) const { CharPointerType t (text); while (charactersToTrim.containsChar (*t)) ++t; return t == text ? *this : String (t); } String String::trimCharactersAtEnd (const String& charactersToTrim) const { if (isNotEmpty()) { const CharPointerType end (text.findTerminatingNull()); CharPointerType trimmedEnd (end); while (trimmedEnd > text) { if (! charactersToTrim.containsChar (*--trimmedEnd)) { ++trimmedEnd; break; } } if (trimmedEnd < end) return String (text, trimmedEnd); } return *this; } //============================================================================== String String::retainCharacters (const String& charactersToRetain) const { if (isEmpty()) return empty; StringCreationHelper builder (text); for (;;) { juce_wchar c = builder.source.getAndAdvance(); if (charactersToRetain.containsChar (c)) builder.write (c); if (c == 0) break; } builder.write (0); return builder.result; } String String::removeCharacters (const String& charactersToRemove) const { if (isEmpty()) return empty; StringCreationHelper builder (text); for (;;) { juce_wchar c = builder.source.getAndAdvance(); if (! charactersToRemove.containsChar (c)) builder.write (c); if (c == 0) break; } return builder.result; } String String::initialSectionContainingOnly (const String& permittedCharacters) const { CharPointerType t (text); while (! t.isEmpty()) { if (! permittedCharacters.containsChar (*t)) return String (text, t); ++t; } return *this; } String String::initialSectionNotContaining (const String& charactersToStopAt) const { CharPointerType t (text); while (! t.isEmpty()) { if (charactersToStopAt.containsChar (*t)) return String (text, t); ++t; } return *this; } bool String::containsOnly (const String& chars) const noexcept { CharPointerType t (text); while (! t.isEmpty()) if (! chars.containsChar (t.getAndAdvance())) return false; return true; } bool String::containsAnyOf (const String& chars) const noexcept { CharPointerType t (text); while (! t.isEmpty()) if (chars.containsChar (t.getAndAdvance())) return true; return false; } bool String::containsNonWhitespaceChars() const noexcept { CharPointerType t (text); while (! t.isEmpty()) { if (! t.isWhitespace()) return true; ++t; } return false; } // Note! The format parameter here MUST NOT be a reference, otherwise MS's va_start macro fails to work (but still compiles). String String::formatted (const String pf, ... ) { size_t bufferSize = 256; for (;;) { va_list args; va_start (args, pf); #if JUCE_WINDOWS HeapBlock <wchar_t> temp (bufferSize); const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, pf.toWideCharPointer(), args); #elif JUCE_ANDROID HeapBlock <char> temp (bufferSize); const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, pf.toUTF8(), args); #else HeapBlock <wchar_t> temp (bufferSize); const int num = (int) vswprintf (temp.getData(), bufferSize - 1, pf.toWideCharPointer(), args); #endif va_end (args); if (num > 0) return String (temp); bufferSize += 256; if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly break; // returns -1 because of an error rather than because it needs more space. } return empty; } //============================================================================== int String::getIntValue() const noexcept { return text.getIntValue32(); } int String::getTrailingIntValue() const noexcept { int n = 0; int mult = 1; CharPointerType t (text.findTerminatingNull()); while (--t >= text) { if (! t.isDigit()) { if (*t == '-') n = -n; break; } n += mult * (*t - '0'); mult *= 10; } return n; } int64 String::getLargeIntValue() const noexcept { return text.getIntValue64(); } float String::getFloatValue() const noexcept { return (float) getDoubleValue(); } double String::getDoubleValue() const noexcept { return text.getDoubleValue(); } static const char hexDigits[] = "0123456789abcdef"; template <typename Type> struct HexConverter { static String hexToString (Type v) { char buffer[32]; char* const end = buffer + 32; char* t = end; *--t = 0; do { *--t = hexDigits [(int) (v & 15)]; v >>= 4; } while (v != 0); return String (t, (size_t) (end - t) - 1); } static Type stringToHex (String::CharPointerType t) noexcept { Type result = 0; while (! t.isEmpty()) { const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance()); if (hexValue >= 0) result = (result << 4) | hexValue; } return result; } }; String String::toHexString (const int number) { return HexConverter <unsigned int>::hexToString ((unsigned int) number); } String String::toHexString (const int64 number) { return HexConverter <uint64>::hexToString ((uint64) number); } String String::toHexString (const short number) { return toHexString ((int) (unsigned short) number); } String String::toHexString (const void* const d, const int size, const int groupSize) { if (size <= 0) return empty; int numChars = (size * 2) + 2; if (groupSize > 0) numChars += size / groupSize; String s (PreallocationBytes (sizeof (CharPointerType::CharType) * (size_t) numChars)); const unsigned char* data = static_cast <const unsigned char*> (d); CharPointerType dest (s.text); for (int i = 0; i < size; ++i) { const unsigned char nextByte = *data++; dest.write ((juce_wchar) hexDigits [nextByte >> 4]); dest.write ((juce_wchar) hexDigits [nextByte & 0xf]); if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1)) dest.write ((juce_wchar) ' '); } dest.writeNull(); return s; } int String::getHexValue32() const noexcept { return HexConverter<int>::stringToHex (text); } int64 String::getHexValue64() const noexcept { return HexConverter<int64>::stringToHex (text); } //============================================================================== String String::createStringFromData (const void* const data_, const int size) { const uint8* const data = static_cast <const uint8*> (data_); if (size <= 0 || data == nullptr) { return empty; } else if (size == 1) { return charToString ((juce_wchar) data[0]); } else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2) || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE2)) { const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1); const int numChars = size / 2 - 1; StringCreationHelper builder ((size_t) numChars); const uint16* const src = (const uint16*) (data + 2); if (bigEndian) { for (int i = 0; i < numChars; ++i) builder.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i])); } else { for (int i = 0; i < numChars; ++i) builder.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i])); } builder.write (0); return builder.result; } else { const uint8* start = data; const uint8* end = data + size; if (size >= 3 && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1 && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2 && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3) start += 3; return String (CharPointer_UTF8 ((const char*) start), CharPointer_UTF8 ((const char*) end)); } } //============================================================================== static const juce_wchar emptyChar = 0; template <class CharPointerType_Src, class CharPointerType_Dest> struct StringEncodingConverter { static CharPointerType_Dest convert (const String& s) { String& source = const_cast <String&> (s); typedef typename CharPointerType_Dest::CharType DestChar; if (source.isEmpty()) return CharPointerType_Dest (reinterpret_cast <const DestChar*> (&emptyChar)); CharPointerType_Src text (source.getCharPointer()); const size_t extraBytesNeeded = CharPointerType_Dest::getBytesRequiredFor (text); const size_t endOffset = (text.sizeInBytes() + 3) & ~3; // the new string must be word-aligned or many Windows // functions will fail to read it correctly! source.preallocateBytes (endOffset + extraBytesNeeded); text = source.getCharPointer(); void* const newSpace = addBytesToPointer (text.getAddress(), (int) endOffset); const CharPointerType_Dest extraSpace (static_cast <DestChar*> (newSpace)); #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..) const int bytesToClear = jmin ((int) extraBytesNeeded, 4); zeromem (addBytesToPointer (newSpace, (int) (extraBytesNeeded - bytesToClear)), (size_t) bytesToClear); #endif CharPointerType_Dest (extraSpace).writeAll (text); return extraSpace; } }; template <> struct StringEncodingConverter <CharPointer_UTF8, CharPointer_UTF8> { static CharPointer_UTF8 convert (const String& source) noexcept { return CharPointer_UTF8 ((CharPointer_UTF8::CharType*) source.getCharPointer().getAddress()); } }; template <> struct StringEncodingConverter <CharPointer_UTF16, CharPointer_UTF16> { static CharPointer_UTF16 convert (const String& source) noexcept { return CharPointer_UTF16 ((CharPointer_UTF16::CharType*) source.getCharPointer().getAddress()); } }; template <> struct StringEncodingConverter <CharPointer_UTF32, CharPointer_UTF32> { static CharPointer_UTF32 convert (const String& source) noexcept { return CharPointer_UTF32 ((CharPointer_UTF32::CharType*) source.getCharPointer().getAddress()); } }; CharPointer_UTF8 String::toUTF8() const { return StringEncodingConverter <CharPointerType, CharPointer_UTF8 >::convert (*this); } CharPointer_UTF16 String::toUTF16() const { return StringEncodingConverter <CharPointerType, CharPointer_UTF16>::convert (*this); } CharPointer_UTF32 String::toUTF32() const { return StringEncodingConverter <CharPointerType, CharPointer_UTF32>::convert (*this); } const wchar_t* String::toWideCharPointer() const { return StringEncodingConverter <CharPointerType, CharPointer_wchar_t>::convert (*this).getAddress(); } //============================================================================== template <class CharPointerType_Src, class CharPointerType_Dest> struct StringCopier { static int copyToBuffer (const CharPointerType_Src& source, typename CharPointerType_Dest::CharType* const buffer, const int maxBufferSizeBytes) { jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied! if (buffer == nullptr) return (int) (CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType)); return CharPointerType_Dest (buffer).writeWithDestByteLimit (source, maxBufferSizeBytes); } }; int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const noexcept { return StringCopier <CharPointerType, CharPointer_UTF8>::copyToBuffer (text, buffer, maxBufferSizeBytes); } int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const noexcept { return StringCopier <CharPointerType, CharPointer_UTF16>::copyToBuffer (text, buffer, maxBufferSizeBytes); } int String::copyToUTF32 (CharPointer_UTF32::CharType* const buffer, int maxBufferSizeBytes) const noexcept { return StringCopier <CharPointerType, CharPointer_UTF32>::copyToBuffer (text, buffer, maxBufferSizeBytes); } //============================================================================== int String::getNumBytesAsUTF8() const noexcept { return (int) CharPointer_UTF8::getBytesRequiredFor (text); } String String::fromUTF8 (const char* const buffer, int bufferSizeBytes) { if (buffer != nullptr) { if (bufferSizeBytes < 0) return String (CharPointer_UTF8 (buffer)); else if (bufferSizeBytes > 0) return String (CharPointer_UTF8 (buffer), CharPointer_UTF8 (buffer + bufferSizeBytes)); } return String::empty; } #if JUCE_MSVC #pragma warning (pop) #endif //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS class StringTests : public UnitTest { public: StringTests() : UnitTest ("String class") {} template <class CharPointerType> struct TestUTFConversion { static void test (UnitTest& test) { String s (createRandomWideCharString()); typename CharPointerType::CharType buffer [300]; memset (buffer, 0xff, sizeof (buffer)); CharPointerType (buffer).writeAll (s.toUTF32()); test.expectEquals (String (CharPointerType (buffer)), s); memset (buffer, 0xff, sizeof (buffer)); CharPointerType (buffer).writeAll (s.toUTF16()); test.expectEquals (String (CharPointerType (buffer)), s); memset (buffer, 0xff, sizeof (buffer)); CharPointerType (buffer).writeAll (s.toUTF8()); test.expectEquals (String (CharPointerType (buffer)), s); } }; static String createRandomWideCharString() { juce_wchar buffer[50] = { 0 }; Random r; for (int i = 0; i < numElementsInArray (buffer) - 1; ++i) { if (r.nextBool()) { do { buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1)); } while (! CharPointer_UTF16::canRepresent (buffer[i])); } else buffer[i] = (juce_wchar) (1 + r.nextInt (0xff)); } return CharPointer_UTF32 (buffer); } void runTest() { { beginTest ("Basics"); expect (String().length() == 0); expect (String() == String::empty); String s1, s2 ("abcd"); expect (s1.isEmpty() && ! s1.isNotEmpty()); expect (s2.isNotEmpty() && ! s2.isEmpty()); expect (s2.length() == 4); s1 = "abcd"; expect (s2 == s1 && s1 == s2); expect (s1 == "abcd" && s1 == L"abcd"); expect (String ("abcd") == String (L"abcd")); expect (String ("abcdefg", 4) == L"abcd"); expect (String ("abcdefg", 4) == String (L"abcdefg", 4)); expect (String::charToString ('x') == "x"); expect (String::charToString (0) == String::empty); expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde"); expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde"); expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb"); expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde")); expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD")); expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd")); expectEquals (s1.indexOf (String::empty), 0); expectEquals (s1.indexOfIgnoreCase (String::empty), 0); expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty)); expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd")); expect (s1.containsChar ('a')); expect (! s1.containsChar ('x')); expect (! s1.containsChar (0)); expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc")); } { beginTest ("Operations"); String s ("012345678"); expect (s.hashCode() != 0); expect (s.hashCode64() != 0); expect (s.hashCode() != (s + s).hashCode()); expect (s.hashCode64() != (s + s).hashCode64()); expect (s.compare (String ("012345678")) == 0); expect (s.compare (String ("012345679")) < 0); expect (s.compare (String ("012345676")) > 0); expect (s.substring (2, 3) == String::charToString (s[2])); expect (s.substring (0, 1) == String::charToString (s[0])); expect (s.getLastCharacter() == s [s.length() - 1]); expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1)); expect (s.substring (0, 3) == L"012"); expect (s.substring (0, 100) == s); expect (s.substring (-1, 100) == s); expect (s.substring (3) == "345678"); expect (s.indexOf (L"45") == 4); expect (String ("444445").indexOf ("45") == 4); expect (String ("444445").lastIndexOfChar ('4') == 4); expect (String ("45454545x").lastIndexOf (L"45") == 6); expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7); expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8); expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6); expect (s.indexOfChar (L'4') == 4); expect (s + s == "012345678012345678"); expect (s.startsWith (s)); expect (s.startsWith (s.substring (0, 4))); expect (s.startsWith (s.dropLastCharacters (4))); expect (s.endsWith (s.substring (5))); expect (s.endsWith (s)); expect (s.contains (s.substring (3, 6))); expect (s.contains (s.substring (3))); expect (s.startsWithChar (s[0])); expect (s.endsWithChar (s.getLastCharacter())); expect (s [s.length()] == 0); expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh")); expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH")); String s2 ("123"); s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0'; s2 += "xyz"; expect (s2 == "1234567890xyz"); beginTest ("Numeric conversions"); expect (String::empty.getIntValue() == 0); expect (String::empty.getDoubleValue() == 0.0); expect (String::empty.getFloatValue() == 0.0f); expect (s.getIntValue() == 12345678); expect (s.getLargeIntValue() == (int64) 12345678); expect (s.getDoubleValue() == 12345678.0); expect (s.getFloatValue() == 12345678.0f); expect (String (-1234).getIntValue() == -1234); expect (String ((int64) -1234).getLargeIntValue() == -1234); expect (String (-1234.56).getDoubleValue() == -1234.56); expect (String (-1234.56f).getFloatValue() == -1234.56f); expect (("xyz" + s).getTrailingIntValue() == s.getIntValue()); expect (s.getHexValue32() == 0x12345678); expect (s.getHexValue64() == (int64) 0x12345678); expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd")); expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd")); expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab")); unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd }; expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d")); expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d")); expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d")); beginTest ("Subsections"); String s3; s3 = "abcdeFGHIJ"; expect (s3.equalsIgnoreCase ("ABCdeFGhiJ")); expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0); expect (s3.containsIgnoreCase (s3.substring (3))); expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5); expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1); expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5); expect (s3.containsAnyOf (L"zzzFs")); expect (s3.startsWith ("abcd")); expect (s3.startsWithIgnoreCase (L"abCD")); expect (s3.startsWith (String::empty)); expect (s3.startsWithChar ('a')); expect (s3.endsWith (String ("HIJ"))); expect (s3.endsWithIgnoreCase (L"Hij")); expect (s3.endsWith (String::empty)); expect (s3.endsWithChar (L'J')); expect (s3.indexOf ("HIJ") == 7); expect (s3.indexOf (L"HIJK") == -1); expect (s3.indexOfIgnoreCase ("hij") == 7); expect (s3.indexOfIgnoreCase (L"hijk") == -1); String s4 (s3); s4.append (String ("xyz123"), 3); expect (s4 == s3 + "xyz"); expect (String (1234) < String (1235)); expect (String (1235) > String (1234)); expect (String (1234) >= String (1234)); expect (String (1234) <= String (1234)); expect (String (1235) >= String (1234)); expect (String (1234) <= String (1235)); String s5 ("word word2 word3"); expect (s5.containsWholeWord (String ("word2"))); expect (s5.indexOfWholeWord ("word2") == 5); expect (s5.containsWholeWord (L"word")); expect (s5.containsWholeWord ("word3")); expect (s5.containsWholeWord (s5)); expect (s5.containsWholeWordIgnoreCase (L"Word2")); expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5); expect (s5.containsWholeWordIgnoreCase (L"Word")); expect (s5.containsWholeWordIgnoreCase ("Word3")); expect (! s5.containsWholeWordIgnoreCase (L"Wordx")); expect (!s5.containsWholeWordIgnoreCase ("xWord2")); expect (s5.containsNonWhitespaceChars()); expect (s5.containsOnly ("ordw23 ")); expect (! String (" \n\r\t").containsNonWhitespaceChars()); expect (s5.matchesWildcard (L"wor*", false)); expect (s5.matchesWildcard ("wOr*", true)); expect (s5.matchesWildcard (L"*word3", true)); expect (s5.matchesWildcard ("*word?", true)); expect (s5.matchesWildcard (L"Word*3", true)); expect (! s5.matchesWildcard (L"*34", true)); expect (String ("xx**y").matchesWildcard ("*y", true)); expect (String ("xx**y").matchesWildcard ("x*y", true)); expect (String ("xx**y").matchesWildcard ("xx*y", true)); expect (String ("xx**y").matchesWildcard ("xx*", true)); expect (String ("xx?y").matchesWildcard ("x??y", true)); expect (String ("xx?y").matchesWildcard ("xx?y", true)); expect (! String ("xx?y").matchesWildcard ("xx?y?", true)); expect (String ("xx?y").matchesWildcard ("xx??", true)); expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5); expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100)); expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5)); expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5)); expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6)); expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6)); expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5); expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5); expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5)); expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5)); expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1)); expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1)); expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty()); expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5); expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10)); expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10)); expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5)); expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5)); expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5); expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5); expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1)); expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1)); expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1)); expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5)); expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5)); expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3")); expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3"); expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz"); expect (s5.replace ("Word", "", true) == " 2 3"); expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3")); expect (s5.replaceCharacter (L'w', 'x') != s5); expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5); expect (s5.replaceCharacters ("wo", "xy") != s5); expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5); expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword")); expect (s5.retainCharacters (String::empty).isEmpty()); expect (s5.removeCharacters ("1wordxya") == " 2 3"); expectEquals (s5.removeCharacters (String::empty), s5); expect (s5.initialSectionContainingOnly ("word") == L"word"); expect (String ("word").initialSectionContainingOnly ("word") == L"word"); expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word")); expectEquals (s5.initialSectionNotContaining (String (";[:'/")), s5); expect (! s5.isQuotedString()); expect (s5.quoted().isQuotedString()); expect (! s5.quoted().unquoted().isQuotedString()); expect (! String ("x'").isQuotedString()); expect (String ("'x").isQuotedString()); String s6 (" \t xyz \t\r\n"); expectEquals (s6.trim(), String ("xyz")); expect (s6.trim().trim() == "xyz"); expectEquals (s5.trim(), s5); expectEquals (s6.trimStart().trimEnd(), s6.trim()); expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart()); expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart()); expect (s6.trimStart() != s6.trimEnd()); expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim()); expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz"); } { beginTest ("UTF conversions"); TestUTFConversion <CharPointer_UTF32>::test (*this); TestUTFConversion <CharPointer_UTF8>::test (*this); TestUTFConversion <CharPointer_UTF16>::test (*this); } { beginTest ("StringArray"); StringArray s; s.addTokens ("4,3,2,1,0", ";,", "x"); expectEquals (s.size(), 5); expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0")); s.remove (2); expectEquals (s.joinIntoString ("--"), String ("4--3--1--0")); expectEquals (s.joinIntoString (String::empty), String ("4310")); s.clear(); expectEquals (s.joinIntoString ("x"), String::empty); StringArray toks; toks.addTokens ("x,,", ";,", ""); expectEquals (toks.size(), 3); expectEquals (toks.joinIntoString ("-"), String ("x--")); toks.clear(); toks.addTokens (",x,", ";,", ""); expectEquals (toks.size(), 3); expectEquals (toks.joinIntoString ("-"), String ("-x-")); toks.clear(); toks.addTokens ("x,'y,z',", ";,", "'"); expectEquals (toks.size(), 3); expectEquals (toks.joinIntoString ("-"), String ("x-'y,z'-")); } } }; static StringTests stringUnitTests; #endif END_JUCE_NAMESPACE
[ [ [ 1, 2398 ] ] ]
a27cb4de92d2f97c54d229e680117a88df6e639c
1d693dd1b12b23c72dd0bb12a3fc29ed88a7e2d5
/src/nbpflcompiler/pdlparser.h
0e74bec0dc82f7eb32167352aeb60ba776508f2a
[]
no_license
rrdenicol/Netbee
8765ebc2db4ba9bd27c2263483741b409da8300a
38edb4ffa78b8fb7a4167a5d04f40f8f4466be3e
refs/heads/master
2021-01-16T18:42:17.961177
2011-12-26T20:27:03
2011-12-26T20:27:03
3,053,086
0
0
null
null
null
null
UTF-8
C++
false
false
6,568
h
/*****************************************************************************/ /* */ /* Copyright notice: please read file license.txt in the NetBee root folder. */ /* */ /*****************************************************************************/ #pragma once #include "defs.h" #include "symbols.h" #include "ircodegen.h" #include <nbprotodb.h> #include "globalsymbols.h" #include "treeoptimize.h" #include "compilerconsts.h" #include "filtersubgraph.h" #include "errors.h" #include <utility> using namespace std; // use this define to visit or not next-proto candidate instructions #define VISIT_CANDIDATE_PROTO // use this define to consider not supported protocols as next proto //#define VISIT_NEXT_PROTO_DEFINED_ONLY // use this define to execute the 'before' code as soon as you find a protocol #define EXEC_BEFORE_AS_SOON_AS_FOUND enum { PARSER_VISIT_ENCAP = true, PARSER_NO_VISIT_ENCAP = false }; /*! \brief */ class PDLParser { private: struct FilterInfo { SymbolLabel *FilterFalse; FilterSubGraph &SubGraph; FilterInfo(SymbolLabel *filterFalse, FilterSubGraph &subGraph) :FilterFalse(filterFalse), SubGraph(subGraph){} }; typedef list<IRCodeGen*> CodeGenStack_t; struct SwitchCaseLess : public std::binary_function<_nbNetPDLElementCase *, _nbNetPDLElementCase *, bool> { bool operator()(_nbNetPDLElementCase * left, _nbNetPDLElementCase * right) const { if(left->ValueNumber < right->ValueNumber) return true; else return false; }; }; _nbNetPDLDatabase *m_ProtoDB; //!<Pointer to the NetPDL protocol database GlobalSymbols &m_GlobalSymbols; ErrorRecorder &m_ErrorRecorder; //FldScopeStack_t *m_FieldScopes; IRCodeGen *m_CodeGen; SymbolProto *m_CurrProtoSym; uint32 m_LoopCount; uint32 m_IfCount; uint32 m_SwCount; // list<LoopInfo> m_LoopStack; bool m_IsEncapsulation; SymbolFieldContainer *m_ParentUnionField; // [ds] parsing a field requires to save the current field and try parsing inner fields uint32 m_BitFldCount; uint32 m_ScopeLevel; FilterInfo *m_FilterInfo; CompilerConsts *m_CompilerConsts; EncapGraph *m_ProtoGraph; GlobalInfo *m_GlobalInfo; //ParsingSection m_CurrentParsingSection; SymbolVarInt *m_nextProtoCandidate; //!< ID of the next candidate resolved SymbolLabel *m_ResolveCandidateLabel; list<int> m_CandidateProtoToResolve; bool m_ConvertingToInt; CodeGenStack_t m_CodeGenStack; bool m_InnerElementsNotDefined; void ParseFieldDef(_nbNetPDLElementFieldBase *fieldElement); void ParseAssign(_nbNetPDLElementAssignVariable *assignElement); void ParseLoop(_nbNetPDLElementLoop *loopElement); Node *ParseExpressionInt(_nbNetPDLExprBase *expr); Node *ParseExpressionStr(_nbNetPDLExprBase *expr); Node *ParseOperandStr(_nbNetPDLExprBase *expr); Node *ParseOperandInt(_nbNetPDLExprBase *expr); void ParseRTVarDecl(_nbNetPDLElementVariable *variable); void ParseElement(_nbNetPDLElementBase *element); void ParseElements(_nbNetPDLElementBase *firstElement); void ParseEncapsulation(_nbNetPDLElementBase *firstElement); void ParseExecSection(_nbNetPDLElementExecuteX *execSection); // void EnterLoop(SymbolLabel *start, SymbolLabel *exit); // void ExitLoop(void); void EnterSwitch(SymbolLabel *next); void ExitSwitch(void); // LoopInfo &GetLoopInfo(void); void ParseLoopCtrl(_nbNetPDLElementLoopCtrl *loopCtrlElement); void ParseIf(_nbNetPDLElementIf *ifElement); void ParseVerify(_nbNetPDLElementExecuteX *verifySection); void ParseSwitch(_nbNetPDLElementSwitch *switchElement); void ParseBoolExpression(_nbNetPDLExprBase *expr); void ParseNextProto(_nbNetPDLElementNextProto *element); void ParseNextProtoCandidate(_nbNetPDLElementNextProto *element); void ParseLookupTable(_nbNetPDLElementLookupTable *table); void ParseLookupTableUpdate(_nbNetPDLElementUpdateLookupTable *element); Node *ParseLookupTableSelect(uint16 op, string tableName, SymbolLookupTableKeysList *keys); void ParseLookupTableAssign(_nbNetPDLElementAssignLookupTable *element); Node *ParseLookupTableItem(string tableName, string itemName, Node *offsetStart, Node *offsetSize); void CheckVerifyResult(uint32 nextProtoID); bool CheckAllowedElement(_nbNetPDLElementBase *element); //void StoreFieldInScope(const string name, SymbolField *fieldSymbol); //FieldsList_t *LookUpFieldInScope(const string name); SymbolField *StoreFieldSym(SymbolField *fieldSymbol); SymbolField *StoreFieldSym(SymbolField *fieldSymbol, bool force); SymbolField *LookUpFieldSym(const string name); SymbolField *LookUpFieldSym(const SymbolField *field); //void EnterFldScope(void); //void ExitFldScope(void); char *GetProtoName(struct _nbNetPDLExprBase *expr); void ChangeCodeGen(IRCodeGen &codeGen); void RestoreCodeGen(void); void GenProtoEntryCode(SymbolProto &protoSymbol); void VisitNextProto(_nbNetPDLElementNextProto *element); void VisitElement(_nbNetPDLElementBase *element); void VisitElements(_nbNetPDLElementBase *firstElement); void VisitEncapsulation(_nbNetPDLElementBase *firstElement); void VisitSwitch(_nbNetPDLElementSwitch *switchElem); void VisitIf(_nbNetPDLElementIf *ifElement); //void ParseStartProto(IRCodeGen &IRCodeGen); // [ds] added functions to generate debug information, warnings and errors void GenerateInfo(string message, char *file, char *function, int line, int requiredDebugLevel, int indentation); void GenerateWarning(string message, char *file, char *function, int line, int requiredDebugLevel, int indentation); void GenerateError(string message, char *file, char *function, int line, int requiredDebugLevel, int indentation); public: //constructor PDLParser(_nbNetPDLDatabase &protoDB, GlobalSymbols &globalSymbols, ErrorRecorder &errRecorder); ~PDLParser(void) { } void ParseStartProto(IRCodeGen &IRCodeGen, bool visitEncap); void ParseProtocol(SymbolProto &protoSymbol, IRCodeGen &IRCodeGen, bool visitEncap); void ParseEncapsulation(SymbolProto &protoSymbol, FilterSubGraph &subGraph, SymbolLabel *filterFalse, IRCodeGen &IRCodeGen); void ParseExecBefore(SymbolProto &protoSymbol, FilterSubGraph &subGraph, SymbolLabel *filterFalse, IRCodeGen &IRCodeGen); };
[ [ [ 1, 191 ] ] ]
e5d3a6a8acae0712ca678d984bd1e49947ddc079
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/wiseml/examples/wiseml_example_processor.cpp
5847533e7ec48ac04061952aaa11fb3be501616e
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,111
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "apps/wiseml/examples/wiseml_example_processor.h" #ifdef ENABLE_WISEML #ifdef ENABLE_EXAMPLES #include "apps/examples/processor/helloworld_processor.h" #include "apps/examples/processor/helloworld_message.h" #include "sys/node.h" #include "apps/wiseml/sensors/wiseml_string_sensor_factory.h" #include "sys/simulation/simulation_controller.h" #include "apps/wiseml/writer/wiseml_data_keeper.h" #include "apps/wiseml/writer/wiseml_trace_collector.h" #include "sys/misc/random/basic_random.h" #include "sys/logging/logging.h" #include <iostream> using namespace std; using namespace shawn; namespace wiseml { WisemlExampleProcessor:: WisemlExampleProcessor() : old_value_(""), some_sensor_(NULL), writer_battery_(100) { } // ---------------------------------------------------------------------- WisemlExampleProcessor:: ~WisemlExampleProcessor() {} // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- void WisemlExampleProcessor:: boot( void ) throw() { last_time_of_receive_ = simulation_round(); send( new helloworld::HelloworldMessage ); sim_controller_ = &owner_w().world_w().simulation_controller_w(); some_sensor_ = get_string_sensor("battery"); if(some_sensor_ != NULL) old_value_ = some_sensor_->value(); if(owner().id()==0) { //Add capability test: WisemlDataKeeper *keeper = sim_controller_->keeper_by_name_w<WisemlDataKeeper>( "wiseml_data_keeper"); if(keeper != NULL) { Capability cap; cap.datatype = "double"; cap.unit = "degree"; cap.name = "temperature"; cap.def_value = "22.0"; keeper->setup().add_capability(owner().label(), cap); keeper->setup().set_bool_param("gateway", true, owner().label()); } } } // ---------------------------------------------------------------------- void WisemlExampleProcessor:: work( void ) throw() { // Wiseml trace writer example: bool worked = (shawn::uniform_random_0i_1i() >= 0.5); if(worked && writer_battery_ > 0) { writer_battery_--; value_changed(); } // Wiseml sensor example: if(some_sensor_ != NULL) { string cur_value = some_sensor_->value(); if(cur_value != old_value_) { old_value_ = cur_value; cout << owner().label() << ":Battery = " << cur_value << endl; } } } // ---------------------------------------------------------------------- WisemlStringSensor* WisemlExampleProcessor::get_string_sensor(std::string capability) { sensor_keeper_ = sim_controller_-> keeper_by_name_w<reading::SensorKeeper>("SensorKeeper"); try { reading::SensorFactory *factory = sensor_keeper_->find_w("wiseml_string_sensor").get(); WisemlStringSensorFactory *string_factory = dynamic_cast<WisemlStringSensorFactory*>(factory); WisemlStringSensor* sensor = string_factory->create(capability, owner_w()); return sensor; } catch(std::runtime_error e) { WARN("WisemlExampleProcessor", "wiseml_string_sensor not registered?"); } return NULL; } // ---------------------------------------------------------------------- void WisemlExampleProcessor::value_changed() { WisemlDataKeeper *keeper = sim_controller_->keeper_by_name_w<WisemlDataKeeper>( "wiseml_data_keeper"); if(keeper != NULL) { try { std::stringstream valstr; valstr << writer_battery_; // Getting the Trace WisemlTraceCollector &trace = keeper->trace("example_trace"); // Committing the value change to the trace trace.capability_value(owner().label(), "battery", valstr.str()); } catch(std::runtime_error er) { WARN("WisemlExampleProcessor", "WisemlTraceCollector not found!"); } } } // ---------------------------------------------------------------------- } #endif #endif
[ [ [ 1, 161 ] ] ]
e6120e3a1c75f17dc79f6c9d2aedf78f352838e9
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/SRC/ProtoBase/droppdu.cc
469a36adf1fb54ff23d6926d1f2172e6884b0626
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
2,452
cc
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: // Georgia Tech Network Simulator - PDU Header for Dropped Packet Logging // George F. Riley. Georgia Tech, Spring 2002 #include "droppdu.h" DropPDU::~DropPDU() { } PDU* DropPDU::Copy() const { // Make a copy of this PDU return new DropPDU(*this); } void DropPDU::Trace(Tfstream& tos, Bitmap_t b, Packet*, const char*) { // Trace the contents of this pdu tos << " D-" << reason; tos << " " << uid; }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 66 ] ] ]
83907f4641a3d9a5215623f95ae09029934eca09
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/CPUInfo.cpp
f82fe12bb987a786ec482ba3ba5ad19bd839c268
[]
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
4,462
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: CPUInfo.cpp Version: 0.03 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "CPUInfo.h" namespace nGENE { CPUInfo::CPUInfo(): m_nCores(0), m_bSSE(false), m_bSSE2(false), m_bSSE3(false), m_b3DNow(false), m_bMMX(false), m_bExt(false), m_bMMXEX(false), m_b3DNowEX(false), m_bHyperThreading(false), m_bSystemSupport(false) { } //---------------------------------------------------------------------- CPUInfo::~CPUInfo() { } //---------------------------------------------------------------------- void CPUInfo::getCPUInfo() { char* pVendor = m_acVendor; bool* sse3 = &m_bSSE3; bool* sse2 = &m_bSSE2; bool* sse = &m_bSSE; bool* mmx = &m_bMMX; bool* ext = &m_bExt; bool* now3d= &m_b3DNow; __try { __asm { xor eax, eax // get vendor name CPUID mov esi, pVendor mov [esi], ebx mov [esi+4], edx mov [esi+8], ecx mov eax, 1 // get processor feature-list CPUID test ecx, 00000001h // test for SSE3 support jz _NOSSE3 mov esi, sse3 mov [esi], 1 _NOSSE3: test edx, 04000000h // test for SSE2 support jz _NOSSE2 mov esi, sse2 mov [esi], 1 _NOSSE2: test edx, 02000000h // test for SSE support jz _NOSSE mov esi, sse mov [esi], 1 _NOSSE: test edx, 00800000h // test for MMX support jz _EXIT mov esi, mmx mov [esi], 1 _EXIT: // no extensions are available } } __except(EXCEPTION_EXECUTE_HANDLER) { if(_exception_code() == STATUS_ILLEGAL_INSTRUCTION) return; } __asm { mov eax, 80000000h CPUID cmp eax, 80000000h jbe _EXIT2 mov esi, ext mov [esi], 1 mov eax, 80000001h CPUID test edx, 80000000h jz _EXIT2 mov esi, now3d mov [esi], 1 _EXIT2: } // Check for Hyper-Threading technology support bool* ht = &m_bHyperThreading; __asm { mov eax, 1 CPUID test edx, 10000000h jz _NO_HT mov esi, ht mov [esi], 1 _NO_HT: } // Check number of physical cores uint* cores = &m_nCores; __asm { xor eax, eax CPUID cmp eax, 4 jl _NO_MULTICORE mov eax, 4 CPUID and eax, 0xfc000000 shr eax, 26 add eax, 1 mov esi, cores mov [esi], eax _NO_MULTICORE: } pVendor[12] = '\0'; getCPUBrandName(); } //---------------------------------------------------------------------- void CPUInfo::getOSInfo() { __try { __asm xorps xmm0, xmm0 } __except(EXCEPTION_EXECUTE_HANDLER) { m_bSystemSupport = false; } m_bSystemSupport = true; } //---------------------------------------------------------------------- void CPUInfo::getCPUBrandName() { bool* now3dex = &m_b3DNowEX; bool* mmxex= &m_bMMXEX; int n = 1; int* pn = &n; if(m_bExt) { if(strncmp(m_acVendor, "GenuineIntel", 12) == 0) { m_acName[48] = '\0'; char* pName = m_acName; __asm { mov esi, pName mov eax, 80000002h CPUID mov [esi], eax mov [esi+4], ebx mov [esi+8], ecx mov [esi+12], edx mov eax, 80000003h CPUID mov [esi+16], eax mov [esi+20], ebx mov [esi+24], ecx mov [esi+28], edx mov eax, 80000004h CPUID mov [esi+32], eax mov [esi+36], ebx mov [esi+40], ecx mov [esi+44], edx } } else if(strncmp(m_acVendor, "AuthenticAMD", 12) == 0) { __asm { mov eax, 1 CPUID mov esi, pn mov [esi], eax mov eax, 0x80000001 CPUID test edx, 0x40000000 jz _AMD1 mov esi, now3dex mov [esi], 1 _AMD1: test edx, 0x00400000 jz _AMD2 mov esi, mmxex mov [esi], 1 _AMD2: } } } } //---------------------------------------------------------------------- bool CPUInfo::isSIMDSupported() const { return ((m_bSSE || m_b3DNow || m_bMMX) && (m_bSystemSupport)); } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 240 ] ] ]
5eb03d3eb223af3071748696667afcb761f17205
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Renderer/D3D10Metal.h
8110cbe52f7712044f7bfbc5dcbc78bb05066580
[]
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
986
h
#ifndef _D3D10METAL_H_ #define _D3D10METAL_H_ #include <Common/Prerequisites.h> #include "../Main/Material.h" namespace Flagship { class Camera; class D3D10Renderer; class D3D10RenderCubeTexture; class _DLL_Export D3D10Metal : public Material { public: D3D10Metal(); virtual ~D3D10Metal(); public: // 初始化 virtual bool Initialize(); // 建立参数表 virtual void BuildParamMap(); // 更新材质参数 virtual void Update( Renderable * pParent ); // 更新材质参数 virtual void Update( Resource * pParent ); protected: // 渲染贴图摄像机 Camera * m_pRenderCamera; // 贴图渲染器 D3D10Renderer * m_pCubeTextureRenderer; // 渲染贴图 D3D10RenderCubeTexture * m_pRenderCubeTexture; // 参数键值 Key m_kRenderCubeTexture; private: }; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 50 ] ] ]
68ff9ab43980a581886a238aa774a61f419fc6f0
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlTerrainVertex.inl
7d7c5f30351b4a204b4782d9246dc3e1eb913bb7
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,071
inl
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. //---------------------------------------------------------------------------- inline void TerrainVertex::SetDependent (int i, TerrainVertex* pkDependent) { assert( 0 <= i && i <= 1 ); m_akDependent[i] = pkDependent; } //---------------------------------------------------------------------------- inline TerrainVertex* TerrainVertex::GetDependent (int i) { assert( 0 <= i && i <= 1 ); return m_akDependent[i]; } //---------------------------------------------------------------------------- inline bool TerrainVertex::GetEnabled () const { return m_bEnabled; } //----------------------------------------------------------------------------
[ [ [ 1, 28 ] ] ]
c401de15a530299e63213e1c410bcfcc7e65c6fc
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/C++/练习/Visual C++程序设计与应用教程/Li3_6/Li3_6View.cpp
2d5ee88a8388ed90aaedc66e395b7a90a79ba77f
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
GB18030
C++
false
false
3,244
cpp
// Li3_6View.cpp : CLi3_6View 类的实现 // #include "stdafx.h" #include "Li3_6.h" #include "Li3_6Doc.h" #include "Li3_6View.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CLi3_6View IMPLEMENT_DYNCREATE(CLi3_6View, CView) BEGIN_MESSAGE_MAP(CLi3_6View, CView) // 标准打印命令 ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) ON_COMMAND(ID_32771, &CLi3_6View::On32771) ON_COMMAND(ID_32772, &CLi3_6View::On32772) ON_WM_TIMER() END_MESSAGE_MAP() // CLi3_6View 构造/析构 CLi3_6View::CLi3_6View() : x(0) , y(0) , m_string(_T("")) { // TODO: 在此处添加构造代码 } CLi3_6View::~CLi3_6View() { } BOOL CLi3_6View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return CView::PreCreateWindow(cs); } // CLi3_6View 绘制 void CLi3_6View::OnDraw(CDC* pDC) { CLi3_6Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: 在此处为本机数据添加绘制代码 } // CLi3_6View 打印 BOOL CLi3_6View::OnPreparePrinting(CPrintInfo* pInfo) { // 默认准备 return DoPreparePrinting(pInfo); } void CLi3_6View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 添加额外的打印前进行的初始化过程 } void CLi3_6View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 添加打印后进行的清理过程 } // CLi3_6View 诊断 #ifdef _DEBUG void CLi3_6View::AssertValid() const { CView::AssertValid(); } void CLi3_6View::Dump(CDumpContext& dc) const { CView::Dump(dc); } CLi3_6Doc* CLi3_6View::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLi3_6Doc))); return (CLi3_6Doc*)m_pDocument; } #endif //_DEBUG // CLi3_6View 消息处理程序 void CLi3_6View::On32771() { // TODO: 在此添加命令处理程序代码 CClientDC pDC(this); LOGFONT lf; //字体属性对象 CFont NewFont,*OldFont; CBrush NewBrush, *OldBrush; //获取字体参数 pDC.GetCurrentFont()->GetLogFont(&lf); lf.lfCharSet=DEFAULT_CHARSET; lf.lfHeight=-120; lf.lfWidth=0; strcpy(lf.lfFaceName,"隶书"); NewFont.CreateFontIndirect(&lf); OldFont=pDC.SelectObject(&NewFont); pDC.SetBkMode(TRANSPARENT); CBitmap bitmap; bitmap.LoadBitmap(IDB_BITMAP1); NewBrush.CreatePatternBrush(&bitmap); OldBrush=pDC.SelectObject(&NewBrush); pDC.BeginPath(); pDC.TextOutA(20,180,"位图文本"); pDC.EndPath(); pDC.StrokeAndFillPath(); pDC.SelectObject(OldBrush); pDC.SelectObject(OldFont); NewBrush.DeleteObject(); NewFont.DeleteObject(); } void CLi3_6View::On32772() { // TODO: 在此添加命令处理程序代码 SetTimer(1,100,NULL); x=300; y=300; m_string="这是滚动文本"; } void CLi3_6View::OnTimer(UINT_PTR nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CClientDC dc(this); x-=10; if(x<0) x=600; dc.TextOutA(x,y,m_string); dc.TextOutA(x,y,m_string); CView::OnTimer(nIDEvent); }
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 160 ] ] ]
77de9624d1068bb292d7d1635e115744bc5c41a7
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPRibbonCommandsListBox.h
ae400f3dabca4a69487ba631420176c6f598e5ef
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
2,853
h
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPRibbonCommandsListBox.h : header file // #if !defined(AFX_BCGPRIBBONCOMMANDSLISTBOX_H__86D859ED_7417_446D_9177_83DDA4245C08__INCLUDED_) #define AFX_BCGPRIBBONCOMMANDSLISTBOX_H__86D859ED_7417_446D_9177_83DDA4245C08__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BCGCBPro.h" #ifndef BCGP_EXCLUDE_RIBBON class CBCGPRibbonBar; class CBCGPBaseRibbonElement; class CBCGPRibbonCategory; class CBCGPRibbonSeparator; ///////////////////////////////////////////////////////////////////////////// // CBCGPRibbonCommandsListBox window class BCGCBPRODLLEXPORT CBCGPRibbonCommandsListBox : public CListBox { // Construction public: CBCGPRibbonCommandsListBox( CBCGPRibbonBar* pRibbonBar, BOOL bIncludeSeparator = TRUE, BOOL bDrawDefaultIcon = FALSE); // Attributes public: CBCGPBaseRibbonElement* GetSelected () const; CBCGPBaseRibbonElement* GetCommand (int nIndex) const; int GetCommandIndex (UINT uiID) const; protected: CBCGPRibbonBar* m_pRibbonBar; int m_nTextOffset; CBCGPRibbonSeparator* m_pSeparator; BOOL m_bDrawDefaultIcon; // Operations public: void FillFromCategory (CBCGPRibbonCategory* pCategory); void FillFromIDs (const CList<UINT,UINT>& lstCommands, BOOL bDeep); void FillFromArray ( const CArray<CBCGPBaseRibbonElement*, CBCGPBaseRibbonElement*>& arElements, BOOL bDeep, BOOL bIgnoreSeparators); void FillAll (); BOOL AddCommand (CBCGPBaseRibbonElement* pCmd, BOOL bSelect = TRUE, BOOL bDeep = TRUE); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPRibbonCommandsListBox) //}}AFX_VIRTUAL // Implementation public: virtual ~CBCGPRibbonCommandsListBox(); // Generated message map functions protected: //{{AFX_MSG(CBCGPRibbonCommandsListBox) afx_msg void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // BCGP_EXCLUDE_RIBBON ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BCGPRIBBONCOMMANDSLISTBOX_H__86D859ED_7417_446D_9177_83DDA4245C08__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 92 ] ] ]
340d57fa109d6a0b0e2189d49fb64c674efb9872
b3b0c727bbafdb33619dedb0b61b6419692e03d3
/Source/WindowsPowerLW/WindowsPowerLW/TestWinPwr.cpp
acdfd0c40d109189dd00fa4cee7c106602c07132
[]
no_license
testzzzz/hwccnet
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
refs/heads/master
2021-01-10T02:59:32.527961
2009-11-04T03:39:39
2009-11-04T03:39:39
45,688,112
0
1
null
null
null
null
GB18030
C++
false
false
3,102
cpp
////////////////////////////////////////////////////////// /// /// @file TestWinPwr.cpp /// /// @brief 调用WindowsPowerLW类中的函数,实现查看和修改电源使用方案,这是个测试程序 /// /// @version 1.0 /// /// @author 甘先志 /// /// @date 2009-09-16 /// /// <修改日期> <修改者> <修改描述>\n /// 2009-09-16 甘先志 创建 /// 2009-09-17 甘先志 完善注释和部分功能 /// //////////////////////////////////////////////////////////// #include "WindowsPowerLW.h" //////////////////////////////////////////////////////////// /// /// @brief 获取当前Windows下的电源使用方案,和电源的情况 /// /// @param int argc -未使用 /// @param char* argv[] -未使用 /// /// @return int /// /// @retval 0 正常系统 /// //////////////////////////////////////////////////////////// int main(int argc,char*argv[]) { UNREFERENCED(argc); UNREFERENCED(argv); HRESULT Error = S_OK; WindowsPowerLW *pWinPwrLW = new WindowsPowerLW(); // UINT nIndex = 0; ///< 电源使用方案索引 // POWER_POLICY pwrPolicy; ///< 系统电源使用方案 // SYSTEM_POWER_STATUS SystemPowerStatus; ///< 系统电源状态 bool cuwpsFlag = true; Error = pWinPwrLW->CanUserWritePowerScheme(&cuwpsFlag); if (FAILED(Error)) { cout << "CanUserWritePowerScheme Error " << endl; goto exit; } if (!cuwpsFlag) { cout << "cannot Write power scheme! " <<endl; goto exit; } Error = pWinPwrLW->GetCurrentPowerScheme(); if (FAILED(Error)) { cout << "GetCurrentPowerScheme Error " << endl; goto exit; } pWinPwrLW->UpdateCurrentPowerScheme(0,0,0,0); Error = pWinPwrLW->GetCurrentPowerScheme( ); if (FAILED(Error)) { cout << "GetCurrentPowerScheme Error " << endl; goto exit; } ULONG nStandby = 0; ULONG nHibernate = 0; ULONG nVideoOffTime = 0; ULONG nSpindownTime = 0; Error = pWinPwrLW->GetSuspendTime( nStandby, nHibernate ); if (FAILED(Error)) { cout << "GetSuspendTime Error " << endl; goto exit; } Error = pWinPwrLW->GetDiskSpindownTime( nSpindownTime ); if (FAILED(Error)) { cout << "GetDiskSpindownTime Error" << endl; goto exit; } Error = pWinPwrLW->GetVideoOffTime( nVideoOffTime ); if (FAILED(Error)) { cout << "GetVideoOffTime Error" << endl; goto exit; } cout << "nStandby = " << nStandby << "\n" << "nHibernate = " << nHibernate << "\n" << "nSpindownTime = " << nSpindownTime << "\n" << "nVideoOffTime = " << nVideoOffTime << "\n"; exit: delete pWinPwrLW; system("pause"); return 0; }
[ [ [ 1, 36 ], [ 41, 54 ], [ 56, 61 ], [ 70, 77 ], [ 80, 86 ], [ 88, 95 ], [ 97, 109 ], [ 111, 113 ] ], [ [ 37, 40 ], [ 55, 55 ], [ 62, 69 ], [ 78, 79 ], [ 87, 87 ], [ 96, 96 ], [ 110, 110 ] ] ]
4b2f9c542c6a5c7b8d55d13045a020e6e4746b60
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/ButtonVE.h
5167b14940f6d807834e5db33b0ee9249d00a61e
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
23,517
h
#if _MSC_VER>=1600 // // CButtonVE Owner Drawn WinXP/Vista themes aware button implementation... // // Rev 1.0 - Apr 24th - Original Release // Rev 1.1 - Apr 27th - Hans Dietrich noticed problem with default state on WinXP. // Jerry Evans pointed out inadequate handling of uistate. // Also improved transitions. // Rev 1.2 - - Added support for checkbox style pushbutton mode if BS_PUSHLIKE style set. // Fixed rare & hard to reproduce screen flicker in animated default state. // #ifndef _BUTTONVE_H_ #define _BUTTONVE_H_ #include "VisualStylesXP.h" #include "ButtonVE_Helper.h" // Need library containing AlphaBlend function... #pragma comment (lib,"msimg32.lib") // Add few defines if missing from SDK... #ifndef WM_QUERYUISTATE #define WM_QUERYUISTATE 0x129 #define WM_UPDATEUISTATE 0x128 #define UISF_HIDEFOCUS 0x1 #define UISF_HIDEACCEL 0x2 #define UISF_ACTIVE 0x4 #define DT_HIDEPREFIX 0x00100000 #endif #ifndef BUTTONVE_TIMER #define BUTTONVE_TIMER 200 #endif class CButtonVE_Menu; class CButtonVE_Image; class CButtonVE_Task; ///////////////////////////////////////////////////////////////////////////// // // CButtonVE owner-drawn button class... // class CButtonVE : public CButton, public CButtonVE_Helper { DECLARE_DYNAMIC(CButtonVE) friend CButtonVE_Menu; friend CButtonVE_Image; friend CButtonVE_Task; // // Attributes... // public: BOOL m_vista_test; // If TRUE, running on Vista. BOOL m_timer_active; // Timer has been initialized. BOOL m_self_delete; // Track if we should self-delete. BOOL m_button_hot; // Mouse hovering over button. BOOL m_button_default; // Button is the current default. CSize m_content_margin; // Minimum margin between border & text. HWND m_owner; // Receives control messages from menu int m_stateid; // Current button state. int m_defaultbutton_tickcount; // # of timer ticks remaining for transition. int m_check_state; // If pushbutton checkbox, our current state. CBitmap *m_oldstate_bitmap; // Bitmap of previous button state. int m_transition_tickcount; // # of timer ticks remaining for transition. int m_transition_tickscale; // Alpha multipler for timer ticks. BOOL m_bgcolor_valid; // User specified a desired background color. COLORREF m_bgcolor; HBRUSH m_parent_hBrush; // // Constructor/Destructor... // public: CButtonVE() : CButton() { m_vista_test=-1; m_timer_active=FALSE; m_self_delete=FALSE; m_button_hot = FALSE; m_button_default = FALSE; m_content_margin = CSize(0,0); m_owner = NULL; m_stateid = -1; m_defaultbutton_tickcount=0; m_oldstate_bitmap = NULL; m_transition_tickcount=0; m_transition_tickscale=25; m_check_state = BST_UNCHECKED; m_bgcolor_valid = FALSE; m_bgcolor = ::GetSysColor(COLOR_BTNFACE); m_parent_hBrush = NULL; } virtual ~CButtonVE(){} // // Configuration Operations... // public: // Indicate who receives command messages... void SetOwner(CWnd *owner) {m_owner = owner->GetSafeHwnd();} void SetOwner(HWND owner) {m_owner = owner;} // Set content horizontal position. Valid param: BS_LEFT, BS_RIGHT, BS_CENTER void SetContentHorz (DWORD horzpos) { ModifyStyle(BS_CENTER, horzpos & BS_CENTER); Invalidate(); } // Set content vertical position. Valid param: BS_TOP, BS_BOTTOM, BS_VCENTER void SetContentVert (DWORD vertpos) { ModifyStyle(BS_VCENTER, vertpos & BS_VCENTER); Invalidate(); } // Set spacing between button content & border... void SetContentMargin(CSize margin) {m_content_margin = margin;} // Permit easy setting of non-theme default background color... void SetBackgroundColor(COLORREF bgcolor) { m_bgcolor_valid = (bgcolor != -1); m_bgcolor = (m_bgcolor_valid) ? bgcolor : ::GetSysColor(COLOR_BTNFACE); } // // Internal Operations... // private: // Return TRUE if running on Vista... BOOL UseVistaEffects() { if (m_vista_test<0) { OSVERSIONINFO osvi; memset (&osvi,0,sizeof(osvi)); osvi.dwOSVersionInfoSize = sizeof(osvi); m_vista_test = GetVersionEx(&osvi) ? (osvi.dwPlatformId==VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion>=6) : FALSE; } return m_vista_test; } // Detect if mouse floating over button... BOOL HitTest() { HWND hWnd = GetSafeHwnd(); if (hWnd==NULL) return FALSE; // If mouse captured by someone other than us, indicate no hit... CWnd *capWnd = GetCapture(); if ((capWnd != NULL) && (capWnd != this)) return FALSE; // Quit if mouse not over us... CPoint pt; ::GetCursorPos(&pt); CRect rw; GetWindowRect(&rw); if (!rw.PtInRect(pt)) return FALSE; // Get the top-level window that is under the mouse cursor... HWND hWndMouse = ::WindowFromPoint(pt); if (!::IsWindowEnabled(hWndMouse)) return FALSE; if (hWndMouse==hWnd) return TRUE; // Convert (x,y) from screen to parent window's client coordinates... ::ScreenToClient(hWndMouse, &pt); // Verify child window (if any) is under the mouse cursor is us... return (::ChildWindowFromPointEx(hWndMouse, pt, CWP_ALL)==hWnd); } // Return pixel size of text (single or multiline)... virtual CSize GetTextSize(CDC &dc, CString button_text, CRect textrc, int text_format) { // Remove any non-visible ampersand characters... CString filter_text; int textlen = button_text.GetLength(); BOOL got_ampersand = FALSE; for (int i=0; i<textlen; i++) { TCHAR newchar = button_text[i]; if (newchar == _T('&')) { if (got_ampersand) {filter_text += newchar;} got_ampersand = !got_ampersand; } else { filter_text += newchar; got_ampersand = FALSE; } } CSize textsize(0,0); if (!filter_text.IsEmpty()) if ((filter_text.Find(_T("\n"))<0) || (text_format & DT_SINGLELINE)) // single line string... textsize = dc.GetTextExtent(filter_text); else { CString temp; int textlen = filter_text.GetLength(); for (int i=0; i<textlen; i++) { TCHAR newchar = filter_text.GetAt(i); if (newchar == _T('\n')) { if (!temp.IsEmpty()) { CSize tempsize = dc.GetTextExtent(temp); if (tempsize.cx > textsize.cx) textsize.cx = tempsize.cx; } temp.Empty(); } else temp += newchar; } if (!temp.IsEmpty()) { CSize tempsize = dc.GetTextExtent(temp); if (tempsize.cx > textsize.cx) textsize.cx = tempsize.cx; } CRect sizerc(textrc); dc.DrawText(filter_text, sizerc, DT_CALCRECT); textsize.cy = sizerc.Height(); } return textsize; } // // Overrideable... // private: // Draw button text content... virtual void DrawTextContent ( CDC &dc, // Drawing context HTHEME hTheme, // XP/Vista theme (if available). Use g_xpStyle global var for drawing. int uistate, // Windows keyboard/mouse ui styles. If UISF_HIDEACCEL set, should hide underscores. CRect /*rclient*/, // Button outline rectangle. CRect /*border*/, // Content rectangle (specified by theme API). CRect textrc, // Text rectangle. int text_format, // DrawText API formatting. BOOL enabled, // Set if button enabled CString button_text) { int oldmode = dc.SetBkMode(TRANSPARENT); // Adjust coordinates for multiline text... CRect textsize(textrc); dc.DrawText(button_text, textsize, DT_CALCRECT | (DT_SINGLELINE & text_format)); if (text_format & DT_VCENTER) { textrc.top += (textrc.Height()-textsize.Height())/2; text_format = (text_format & ~DT_VCENTER) | DT_TOP; } if (text_format & DT_BOTTOM) { textrc.top = textrc.bottom - textsize.Height(); text_format = (text_format & ~DT_BOTTOM) | DT_TOP; } if (text_format & DT_SINGLELINE) // remove any newlines button_text.Replace(_T("\n"),_T(" ")); if (uistate & UISF_HIDEACCEL) text_format |= DT_HIDEPREFIX; if (hTheme) { int button_textlen = button_text.GetLength(); if (button_textlen) { #ifdef UNICODE g_xpStyle.DrawThemeText(hTheme, dc, BP_PUSHBUTTON, m_stateid, button_text, button_textlen, text_format, NULL, &textrc); #else int widelen = MultiByteToWideChar(CP_ACP, 0, button_text, button_textlen+1, NULL, 0); WCHAR *pszWideText = new WCHAR[widelen+1]; if (pszWideText) { MultiByteToWideChar(CP_ACP, 0, button_text, button_textlen, pszWideText, widelen); g_xpStyle.DrawThemeText(hTheme, dc, BP_PUSHBUTTON, m_stateid, pszWideText, button_textlen, text_format, NULL, &textrc); delete [] pszWideText; } #endif } } else { dc.SetBkColor(m_bgcolor); if (enabled) { dc.SetTextColor(::GetSysColor(COLOR_BTNTEXT)); dc.DrawText(button_text, textrc, text_format); } else { dc.SetTextColor(::GetSysColor(COLOR_BTNHIGHLIGHT)); dc.DrawText(button_text, textrc+CPoint(1,1), text_format); dc.SetTextColor(::GetSysColor(COLOR_BTNSHADOW)); dc.DrawText(button_text, textrc, text_format); } } dc.SetBkMode(oldmode); } // Draw button content (after background prepared)... virtual void DrawContent ( CDC &dc, // Drawing context HTHEME hTheme, // XP/Vista theme (if available). Use g_xpStyle global var for drawing. int uistate, // Windows keyboard/mouse ui styles. If UISF_HIDEACCEL set, should hide underscores. CRect rclient, // Button outline rectangle. CRect border, // Content rectangle (specified by theme API). CRect textrc, // Text rectangle. int text_format, // DrawText API formatting. BOOL enabled) // Set if button enabled. { CString button_text; GetWindowText(button_text); CFont *oldfont = (CFont*)dc.SelectObject(GetFont()); DrawTextContent (dc, hTheme, uistate, rclient, border, textrc, text_format, enabled, button_text); dc.SelectObject(oldfont); } // Draw themed button background... virtual void DrawThemedButtonBackground(HDC /*hDC*/, CDC &mDC, HTHEME hTheme, int stateid, CRect &rc, CRect &border) { // Fill background with button face to avoid nasty border around buttons mDC.FillSolidRect(rc, m_bgcolor); // Draw themed button background... if (g_xpStyle.IsThemeBackgroundPartiallyTransparent(hTheme, BP_PUSHBUTTON, stateid)) g_xpStyle.DrawThemeParentBackground(m_hWnd, mDC, &rc); g_xpStyle.DrawThemeBackground (hTheme, mDC, BP_PUSHBUTTON, stateid, &rc, NULL); // Get rect for content... border = rc; g_xpStyle.GetThemeBackgroundContentRect (hTheme, mDC, BP_PUSHBUTTON, stateid, &border, &border); } // Modify button background into transition state... virtual void DrawThemedVistaEffects(HDC hDC, CDC &mDC, HTHEME hTheme, int stateid, CRect &rc, CRect &border) { // Simulate Vista button effects... if (UseVistaEffects() && (m_transition_tickcount>0)) { // transitioning into new state... CDCBitmap tempDC(hDC,m_oldstate_bitmap); AlphaBlt (mDC, rc, tempDC, rc, m_transition_tickcount*m_transition_tickscale); m_defaultbutton_tickcount=0; } // Simulate pulsing Vista default button... if (UseVistaEffects() && (m_transition_tickcount==0) && (stateid == PBS_DEFAULTED)) { // Copy "default" button state to temp bitmap... CBitmap tempbmp; tempbmp.CreateCompatibleBitmap(CDC::FromHandle(hDC),rc.Width(),rc.Height()); CDCBitmap tempDC(mDC,tempbmp); AlphaBlt (tempDC, rc, mDC, rc, 255); // Compute "glow" alpha... 0->250->0 over 40 ticks. int alpha = (int)(m_defaultbutton_tickcount*12.5); if (m_defaultbutton_tickcount>=20) alpha = 500-alpha; // Thicken content border... CRect rect(border); rect.InflateRect(1,1); AlphaBlt (mDC, border, tempDC, rect, alpha/2); // Render hot button state... CRect temprc; DrawThemedButtonBackground(hDC, tempDC, hTheme, PBS_HOT, rc, temprc); // Blend the hot-state content area... border.DeflateRect(1,1); AlphaBlt (mDC, border, tempDC, border, alpha); border.InflateRect(1,1); } } // Draw non-themed button background... virtual void DrawNonThemedButtonBackground(HDC /*hDC*/, CDC &mDC, BOOL button_focus, UINT state, CRect rc, CRect &border) { CRect rcback(border); if (!m_bgcolor_valid && m_parent_hBrush) mDC.FillRect(border, CBrush::FromHandle(m_parent_hBrush)); else mDC.FillSolidRect(border,m_bgcolor); if (button_focus & ((state & DFCS_PUSHED)==0)) rcback.DeflateRect(1,1); mDC.DrawFrameControl(rcback,DFC_BUTTON,state); // Hardcoded the edge style to match other parts of eMule on no theme mDC.DrawEdge(rcback, EDGE_ETCHED, BF_FLAT | BF_MONO | BF_RECT); COLORREF btntext = ::GetSysColor(COLOR_BTNTEXT); if (button_focus) mDC.Draw3dRect(rc,btntext,btntext); border.DeflateRect(4,4); } // Called by CButton::OnChildNotify handler for owner drawn buttons. Works great, // as long as parent window reflects notify messages back to the button. virtual void DrawItem(LPDRAWITEMSTRUCT di) { if (!m_timer_active) { m_timer_active = TRUE; ::SetTimer(m_hWnd,BUTTONVE_TIMER,50,NULL); } if (di->CtlType != ODT_BUTTON) return; // Create memory drawing context... CRect rc, textrc; GetClientRect(&rc); CDCBitmap mDC(di->hDC,rc); CRect border(rc); // Colors... //COLORREF btntext = ::GetSysColor(COLOR_BTNTEXT); // unused COLORREF btnface = m_bgcolor; // Query parent for background color with WM_CTLCOLOR message... m_parent_hBrush = NULL; CWnd *parent = GetParent(); if (parent) m_parent_hBrush = (HBRUSH)(parent->SendMessage( WM_CTLCOLORBTN, (WPARAM)di->hDC, (LPARAM)GetSafeHwnd())); // Get Win2k/XP UI state... Controls if focus rectangle is // hidden, making things cleaner unless keyboard nav used. int uistate = SendMessage(WM_QUERYUISTATE,0,0); if (uistate<0) uistate=0; UINT btnstate = GetState(); DWORD btn_style = GetStyle(); m_button_hot = HitTest(); BOOL button_pressed = (btnstate & 4); BOOL button_focus = GetFocus()==this; BOOL draw_pressed = button_pressed || ((btn_style & BS_PUSHLIKE) && m_check_state); // If not enabled, make sure to cleanup any left-over "pressed" state indications... BOOL enabled = IsWindowEnabled(); if (!enabled) { button_pressed = FALSE; draw_pressed = FALSE; m_button_default = FALSE; m_button_hot = FALSE; } // Get theme handle... HTHEME hTheme = NULL; if (g_xpStyle.IsAppThemed() && g_xpStyle.IsThemeActive()) hTheme = g_xpStyle.OpenThemeData (m_hWnd, L"Button"); if (hTheme) { int old_stateid = m_stateid; if (!enabled) m_stateid = PBS_DISABLED; else if (draw_pressed) m_stateid = PBS_PRESSED; else if (m_button_hot) m_stateid = PBS_HOT; else if (m_button_default) m_stateid = PBS_DEFAULTED; else m_stateid = PBS_NORMAL; if (old_stateid<0) old_stateid = m_stateid; // Create bitmap of button in its "hot" state. This is used to simulate // a pulsing default button (ala Vista)... if (UseVistaEffects() && (m_stateid != old_stateid)) { // Get snapshot of button in old state... CBitmap *new_snapshot = new CBitmap; new_snapshot->CreateBitmap(rc.Width(),rc.Height(),1,32,NULL); CDCBitmap tempDC(di->hDC, new_snapshot); DrawThemedButtonBackground(di->hDC, tempDC, hTheme, old_stateid, rc, border); DrawThemedVistaEffects(di->hDC, tempDC, hTheme, old_stateid, rc, border); if (m_oldstate_bitmap) delete m_oldstate_bitmap; m_oldstate_bitmap = new_snapshot; // Select number of 50ms ticks transition should occur over. Some are faster than others... switch (m_stateid) { case PBS_HOT : m_transition_tickcount = (old_stateid==PBS_PRESSED) ? 4 : 2; break; case PBS_NORMAL : m_transition_tickcount = (old_stateid==PBS_HOT) ? 20 : 4; break; case PBS_PRESSED : m_transition_tickcount = 2; break; case PBS_DEFAULTED : m_transition_tickcount = (old_stateid==PBS_HOT) ? 20 : 2; break; default : m_transition_tickcount = 4; break; } m_transition_tickscale = 250/m_transition_tickcount; } DrawThemedButtonBackground(di->hDC, mDC, hTheme, m_stateid, rc, border); DrawThemedVistaEffects(di->hDC, mDC, hTheme, m_stateid, rc, border); textrc = border; } else { // draw non-themed background... UINT state = DFCS_BUTTONPUSH; if (!enabled) state |= DFCS_INACTIVE; else if (draw_pressed) state |= DFCS_PUSHED; if (!button_pressed && (btn_style & BS_PUSHLIKE) && m_check_state) state |= DFCS_CHECKED; // Draw button frame... DrawNonThemedButtonBackground(di->hDC, mDC, button_focus, state, rc, border); textrc = border; if (button_pressed) textrc += CPoint(1,1); textrc.top--; } textrc.DeflateRect(m_content_margin.cx, m_content_margin.cy); // Convert button style into text-format... int text_format=0; switch (btn_style & BS_CENTER) { case BS_LEFT : text_format |= DT_LEFT; break; case BS_RIGHT : text_format |= DT_RIGHT; break; default : text_format |= DT_CENTER; break; } switch (btn_style & BS_VCENTER) { case BS_TOP : text_format |= DT_TOP; break; case BS_BOTTOM : text_format |= DT_BOTTOM; break; default : text_format |= DT_VCENTER; break; } if ((btn_style & BS_MULTILINE)==0) text_format |= DT_SINGLELINE; // Draw contents of button... DrawContent (mDC, hTheme, uistate, rc, border, textrc, text_format, enabled); // Draw focus rectangle... if ((uistate & UISF_HIDEFOCUS)==0) if (button_focus) { mDC.SetBkColor(btnface); if (hTheme) mDC.DrawFocusRect(border); else { rc.DeflateRect(4,4); mDC.DrawFocusRect(rc); } } // Done with themes... if (hTheme) g_xpStyle.CloseThemeData(hTheme); } // // Message map functions... // protected: // Creating button window. Not called if created by dialog resource. afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; m_self_delete = TRUE; return 0; } // Cleanup button window... afx_msg void OnDestroy() { if (m_timer_active) {::KillTimer(m_hWnd,BUTTONVE_TIMER); m_timer_active = FALSE;} if (m_oldstate_bitmap) {delete m_oldstate_bitmap; m_oldstate_bitmap=NULL;} CButton::OnDestroy(); } afx_msg void OnNcDestroy() { CWnd::OnNcDestroy(); // Make sure the window was destroyed. ASSERT(m_hWnd == NULL); // Delete object because it won't be destroyed otherwise. if (m_self_delete) delete this; } // Redraw if the colors change... afx_msg void OnSysColorChange() { CWnd::OnSysColorChange(); if (m_oldstate_bitmap) {delete m_oldstate_bitmap; m_oldstate_bitmap=NULL;} if (!m_bgcolor_valid) m_bgcolor = ::GetSysColor(COLOR_BTNFACE); Invalidate(); UpdateWindow(); } // Timer events... afx_msg void OnTimer(UINT nIDEvent) { // Track if mouse floating over button... BOOL hit = HitTest(); if (hit != m_button_hot) { m_button_hot = hit; Invalidate(); } // Timer support for Vista transition effects... if (UseVistaEffects()) if (m_transition_tickcount>0) { m_transition_tickcount--; Invalidate(); } else if (m_stateid == PBS_DEFAULTED) { m_defaultbutton_tickcount++; if (m_defaultbutton_tickcount>40) m_defaultbutton_tickcount=0; if ((m_defaultbutton_tickcount>=0) && ((m_defaultbutton_tickcount%2)==0)) Invalidate(); } CButton::OnTimer(nIDEvent); } // Stop Windows erasing the background... afx_msg BOOL OnEraseBkgnd(CDC* /*pDC*/) {return TRUE;} // Let Windows know we're a push button (so default button status works as expected)... afx_msg UINT OnGetDlgCode() { UINT result = DLGC_BUTTON; if (IsWindowEnabled()) result |= (m_button_default) ? DLGC_DEFPUSHBUTTON : DLGC_UNDEFPUSHBUTTON; return result; } // Hack to stop Windows reseting BS_OWNERDRAW style... afx_msg LRESULT OnSetStyle(WPARAM wParam, LPARAM lParam) { BOOL new_button_default = (wParam & 0xF) == BS_DEFPUSHBUTTON; if (new_button_default != m_button_default) Invalidate(); m_button_default = new_button_default; return DefWindowProc(BM_SETSTYLE, (wParam & 0xFFFFFFF0) | BS_OWNERDRAW, lParam); } // Redraw when we loose focus... afx_msg void OnKillFocus(CWnd* pNewWnd) { Invalidate(); CButton::OnKillFocus(pNewWnd); } // Toggle check state if BS_PUSHLIKE style... afx_msg void OnLButtonDown(UINT nFlags, CPoint point) { CButton::OnLButtonDown(nFlags, point); } // Reroute double clicks... afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point) { SendMessage(WM_LBUTTONDOWN, (WPARAM)nFlags, (LPARAM)((point.y<<16)|point.x)); CWnd::OnLButtonDblClk(nFlags, point); } // Send message clicks to override owner... afx_msg void OnLButtonUp(UINT nFlags, CPoint point) { BOOL button_pressed = GetState()&4; if (button_pressed) m_check_state = (GetStyle() & BS_PUSHLIKE) ? !m_check_state : 0; if (m_owner) if ((m_owner != ::GetParent(GetSafeHwnd())) && button_pressed) if ((GetStyle() & BS_NOTIFY)>0) ::SendMessage(m_owner, WM_COMMAND,(WPARAM)((BN_DOUBLECLICKED<<16)|GetDlgCtrlID()),(LPARAM)GetSafeHwnd()); else ::SendMessage(m_owner, WM_COMMAND,(WPARAM)((BN_CLICKED<<16)|GetDlgCtrlID()),(LPARAM)GetSafeHwnd()); CWnd::OnLButtonUp(nFlags, point); } // Update button when ALT key clicked... virtual LRESULT OnUpdateUIState(WPARAM uistate, LPARAM lParam) { Invalidate(); return DefWindowProc(WM_UPDATEUISTATE,uistate,lParam); } // Checkbox style button states... afx_msg LRESULT OnSetCheck(WPARAM wParam, LPARAM /*lParam*/) { m_check_state = wParam; Invalidate(); return 0; } afx_msg LRESULT OnGetCheck(WPARAM /*wParam*/, LPARAM /*lParam*/) { return m_check_state; } DECLARE_MESSAGE_MAP() }; #endif // define _BUTTONVE_H_ #endif
[ "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 671 ] ] ]
33ade750f115ecb920d5a5e1d1769cd18abd001a
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/Modules/Infrastructure/MotionRobotHealthProvider.cpp
74126b32ef15614d6582c5d116593b877f8e5c5a
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,624
cpp
/** * @file Modules/Infrastructure/MotionRobotHealthProvider.h * This file implements a module that provides information about the robot's health. * @author <a href="mailto:[email protected]">Tim Laue</a> */ #include "MotionRobotHealthProvider.h" void MotionRobotHealthProvider::update(MotionRobotHealth& motionRobotHealth) { // Compute frame rate of motion process: timeBuffer.add(SystemCall::getCurrentSystemTime()); unsigned timeDiffSum(0); int numOfTimeDiffs(0); for(int i=0; i < timeBuffer.getNumberOfEntries() - 1; ++i) { timeDiffSum += (timeBuffer[i] - timeBuffer[i+1]); ++numOfTimeDiffs; } motionRobotHealth.motionFrameRate = timeDiffSum ? 1000.0F / (static_cast<float>(timeDiffSum)/numOfTimeDiffs) : 0.0F; /* // Compute the number of frames from robot which have been received within the last second: if(sensorTimeBuffer.getNumberOfEntries() == 0 && theFilteredSensorData.timeStamp != 0) sensorTimeBuffer.add(theFilteredSensorData.timeStamp); else if(theFilteredSensorData.timeStamp != sensorTimeBuffer[0]) sensorTimeBuffer.add(theFilteredSensorData.timeStamp); if(sensorTimeBuffer.getNumberOfEntries()) { unsigned timeDiff = SystemCall::getCurrentSystemTime() - sensorTimeBuffer[sensorTimeBuffer.getNumberOfEntries()-1]; motionRobotHealth.robotFramesPerSecond = static_cast<float>(sensorTimeBuffer.getNumberOfEntries()) / timeDiff; motionRobotHealth.robotFramesPerSecond *= 1000; } else motionRobotHealth.robotFramesPerSecond = 0.0F; */ } MAKE_MODULE(MotionRobotHealthProvider, Infrastructure)
[ "alon@rogue.(none)" ]
[ [ [ 1, 39 ] ] ]
a7286f8a9a7eb082022ef8b27fef64402410ebc2
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Applications/Physics/BouncingSpheres/BouncingSpheres.cpp
0db9bd9369e30c60acbcbec099160b133217a286
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
20,206
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Game Physics source code is supplied under the terms of the license // agreement http://www.magic-software.com/License/GamePhysics.pdf and may not // be copied or disclosed except in accordance with the terms of that // agreement. #include "BouncingSpheres.h" using namespace std; BouncingSpheres g_kTheApp; //---------------------------------------------------------------------------- BouncingSpheres::BouncingSpheres () : Application("BouncingSpheres",0,0,640,480,ColorRGB(1.0f,1.0f,1.0f)) { m_fSimTime = 0.0f; m_fSimDelta = 1.0f/10.0f; } //---------------------------------------------------------------------------- bool BouncingSpheres::OnInitialize () { if ( !Application::OnInitialize() ) return false; // set up camera ms_spkCamera->SetFrustum(1.0f,1000.0f,-0.55f,0.55f,0.4125f,-0.4125f); float fAngle = 0.02f*Mathf::PI; float fCos = Mathf::Cos(fAngle), fSin = Mathf::Sin(fAngle); Vector3f kCUp(-fSin,0.0f,fCos); Vector3f kCDir(-fCos,0.0f,-fSin); Vector3f kCLeft = kCUp.Cross(kCDir); Vector3f kCLoc(27.5f,8.0f,8.9f); ms_spkCamera->SetFrame(kCLoc,kCLeft,kCUp,kCDir); // create scene components CreateBalls(); CreateFloor(); CreateBackWall(); CreateSideWall1(); CreateSideWall2(); // ** layout of scene graph ** // scene // room // backwall // floor // sidewall1 // sidewall2 // balls m_spkScene = new Node(2); Node* pkRoom = new Node(4); Node* pkBalls = new Node(NUM_BALLS); m_spkScene->AttachChild(pkRoom); pkRoom->AttachChild(m_spkFloor); pkRoom->AttachChild(m_spkSideWall1); pkRoom->AttachChild(m_spkSideWall2); pkRoom->AttachChild(m_spkBackWall); m_spkScene->AttachChild(pkBalls); int i; for (i = 0; i < NUM_BALLS; i++) pkBalls->AttachChild(m_aspkBall[i]); // wireframe m_spkWireframeState = new WireframeState; m_spkScene->SetRenderState(m_spkWireframeState); // depth buffer m_spkZBufferState = new ZBufferState; m_spkZBufferState->Enabled() = true; m_spkZBufferState->Writeable() = true; m_spkZBufferState->Compare() = ZBufferState::CF_LEQUAL; m_spkScene->SetRenderState(m_spkZBufferState); // initial update of objects ms_spkCamera->Update(); m_spkScene->UpdateGS(0.0f); m_spkScene->UpdateRS(); // The balls are constrained to bounce around in a rectangular solid // region. The six defining planes are defined to be immovable rigid // bodies. The boundaries are parallel to coordinate axes and pass // through the points indicated by the value other than +-100. That is, // the back wall is at x = 1, the left wall is at y = 2, the floor is at // z = 1, the right wall is at y = 15, the ceiling is at z = 17, and the // front wall is at x = 9. The ceiling and front wall are invisible // objects (not rendered), but you will see balls bouncing against it // and reflecting away from it towards the back wall. m_akBLocation[0] = Vector3f(1.0,-100.0,-100.0); m_akBNormal[0] = Vector3f(1.0,0,0); m_akBLocation[1] = Vector3f(-100.0,2.0,-100.0); m_akBNormal[1] = Vector3f(0,1.0,0); m_akBLocation[2] = Vector3f( -100.0,-100.0,1.0); m_akBNormal[2] = Vector3f(0,0,1.0); m_akBLocation[3] = Vector3f( 100.0,15.0,100.0); m_akBNormal[3] = Vector3f(0,-1.0,0); m_akBLocation[4] = Vector3f( 100.0,100.0,17.0); m_akBNormal[4] = Vector3f(0,0,-1.0); m_akBLocation[5] = Vector3f( 8.0,100.0,100.0); m_akBNormal[5] = Vector3f(-1.0,0,0); for (i = 0; i < 6; i++) { m_akBoundary[i].SetMass(0.0f); m_akBoundary[i].SetPosition(m_akBLocation[i]); } // initialize ball with correct transformations DoPhysical(); return true; } //---------------------------------------------------------------------------- void BouncingSpheres::OnTerminate() { for (int i = 0; i < NUM_BALLS; i++) { delete m_apkBall[i]; m_aspkBall[i] = NULL; } m_spkFloor = NULL; m_spkSideWall1 = NULL; m_spkSideWall2 = NULL; m_spkBackWall = NULL; m_spkWireframeState = NULL; m_spkZBufferState = NULL; m_spkScene = NULL; Application::OnTerminate(); } //---------------------------------------------------------------------------- void BouncingSpheres::OnIdle () { MeasureTime(); DoPhysical(); DoVisual(); UpdateClicks(); } //---------------------------------------------------------------------------- void BouncingSpheres::OnKeyDown (unsigned char ucKey, int, int) { if ( ucKey == 'q' || ucKey == 'Q' || ucKey == KEY_ESCAPE ) { RequestTermination(); return; } switch ( ucKey ) { case 't': // turn simulation on/off { static float fSimDelta = 0.0f; if ( fSimDelta == 0.0f ) { fSimDelta = m_fSimDelta; m_fSimDelta = 0.0f; } else { m_fSimDelta = fSimDelta; fSimDelta = 0.0f; } break; } case 'w': // toggle wireframe m_spkWireframeState->Enabled() = !m_spkWireframeState->Enabled(); break; } } //---------------------------------------------------------------------------- void BouncingSpheres::CreateBalls () { // TO DO. Adjust this so that the physics simulation runs with the // real clock. m_fSimDelta = 0.001f; Vector3f kPos, kLinMom; float fMass = 2.0f; for (int i = 0; i < NUM_BALLS; i++) { m_apkBall[i] = new RigidBall(Mathf::IntervalRandom(0.25f,1.0f)); RigidBall& rkBall = *m_apkBall[i]; m_aspkBall[i] = new Node(1); m_aspkBall[i]->AttachChild(rkBall.Mesh()); fMass += 1.2f; if ( i > 3 ) { kPos = Vector3f(5.0f,4.0f,13.0f) - 1.0f*((float)(i-4))*Vector3f::UNIT_Z + 2.0f*((float)(i-4))*Vector3f::UNIT_Y; } else { kPos = Vector3f(3.0f,4.0f,10.0f) - 2.0f*((float)i)*Vector3f::UNIT_Z+ 2.0f*((float)i)*Vector3f::UNIT_Y; } kLinMom = Vector3f(2.0f,2.0f,-1.2f) + 50.0f*(Mathf::SymmetricRandom())*Vector3f::UNIT_X + 50.0f*(Mathf::SymmetricRandom())*Vector3f::UNIT_Y + 50.0f*(Mathf::SymmetricRandom())*Vector3f::UNIT_Z ; rkBall.SetMass(fMass); rkBall.SetPosition(kPos); rkBall.SetLinearMomentum(kLinMom); rkBall.Force = Force; rkBall.Torque = Torque; rkBall.SetInternalForce(10.0f*Vector3f::UNIT_Z); rkBall.SetInternalTorque(Vector3f::ZERO); rkBall.SetExternalForce(Vector3f::ZERO); rkBall.SetExternalTorque(Vector3f::ZERO); } } //---------------------------------------------------------------------------- void BouncingSpheres::CreateFloor () { Vector3f* akVertex = new Vector3f[4]; akVertex[0] = Vector3f(1.0f,1.0f,1.0f); akVertex[1] = Vector3f(17.0f,1.0f,1.0f); akVertex[2] = Vector3f(17.0f,20.0f,1.0f); akVertex[3] = Vector3f(1.0f,20.0f,1.0f); ColorRGB kFloorColor(155.0f/255.0f,177.0f/255.0f,164.0f/255.0f); ColorRGB* akColor = new ColorRGB[4]; akColor[0] = kFloorColor; akColor[1] = kFloorColor; akColor[2] = kFloorColor; akColor[3] = kFloorColor; int* aiConnect = new int[6]; aiConnect[0] = 0; aiConnect[1] = 1; aiConnect[2] = 2; aiConnect[3] = 0; aiConnect[4] = 2; aiConnect[5] = 3; m_spkFloor = new TriMesh(4,akVertex,NULL,akColor,NULL,2,aiConnect); } //---------------------------------------------------------------------------- void BouncingSpheres::CreateSideWall1 () { Vector3f* akVertex = new Vector3f[4]; akVertex[0] = Vector3f(1.0f,15.0f,1.0f); akVertex[1] = Vector3f(17.0f,15.0f,1.0f); akVertex[2] = Vector3f(17.0f,15.0f,17.0f); akVertex[3] = Vector3f(1.0f,15.0f,17.0f); ColorRGB kSideWall1Color(170.0f/255.0f,187.0f/255.0f,219.0f/255.0f); ColorRGB* akColor = new ColorRGB[4]; akColor[0] = kSideWall1Color; akColor[1] = kSideWall1Color; akColor[2] = kSideWall1Color; akColor[3] = kSideWall1Color; int* aiConnect = new int[6]; aiConnect[0] = 0; aiConnect[1] = 1; aiConnect[2] = 2; aiConnect[3] = 0; aiConnect[4] = 2; aiConnect[5] = 3; m_spkSideWall1 = new TriMesh(4,akVertex,NULL,akColor,NULL,2,aiConnect); } //---------------------------------------------------------------------------- void BouncingSpheres::CreateSideWall2 () { Vector3f* akVertex = new Vector3f[4]; akVertex[0] = Vector3f(17.0f,2.0f,1.0f); akVertex[1] = Vector3f(1.0f,2.0f,1.0f); akVertex[2] = Vector3f(1.0f,2.0f,17.0f); akVertex[3] = Vector3f(17.0f,2.0f,17.0f); ColorRGB kSideWall2Color(170.0f/255.0f,187.0f/255.0f,219.0f/255.0f); ColorRGB* akColor = new ColorRGB[4]; akColor[0] = kSideWall2Color; akColor[1] = kSideWall2Color; akColor[2] = kSideWall2Color; akColor[3] = kSideWall2Color; int* aiConnect = new int[6]; aiConnect[0] = 0; aiConnect[1] = 1; aiConnect[2] = 2; aiConnect[3] = 0; aiConnect[4] = 2; aiConnect[5] = 3; m_spkSideWall2 = new TriMesh(4,akVertex,NULL,akColor,NULL,2,aiConnect); } //---------------------------------------------------------------------------- void BouncingSpheres::CreateBackWall () { Vector3f* akVertex = new Vector3f[4]; akVertex[0] = Vector3f(1.0f,1.0f,1.0f); akVertex[1] = Vector3f(1.0f,20.0f,1.0f); akVertex[2] = Vector3f(1.0f,20.0f,17.0f); akVertex[3] = Vector3f(1.0f,1.0f,17.0f); ColorRGB kBackWallColor(209.0f/255.0f,204.0f/255.0f,180.0f/255.0f); ColorRGB* akColor = new ColorRGB[4]; akColor[0] = kBackWallColor; akColor[1] = kBackWallColor; akColor[2] = kBackWallColor; akColor[3] = kBackWallColor; int* aiConnect = new int[6]; aiConnect[0] = 0; aiConnect[1] = 1; aiConnect[2] = 2; aiConnect[3] = 0; aiConnect[4] = 2; aiConnect[5] = 3; m_spkBackWall = new TriMesh(4,akVertex,NULL,akColor,NULL,2,aiConnect); } //---------------------------------------------------------------------------- void BouncingSpheres::DoPhysical () { DoCollisionDetection(); DoCollisionResponse(); // update the scene graph for (int i = 0; i < NUM_BALLS; i++) m_aspkBall[i]->Translate() = m_apkBall[i]->GetPosition(); m_spkScene->UpdateGS(0.0f); // next simulation time m_fSimTime += m_fSimDelta; } //---------------------------------------------------------------------------- void BouncingSpheres::DoVisual () { ms_spkRenderer->ClearBuffers(); if ( ms_spkRenderer->BeginScene() ) { ms_spkRenderer->Draw(m_spkScene); DrawFrameRate(8,GetHeight()-8,ColorRGB::BLACK); char acMsg[256]; sprintf(acMsg,"Time = %5.2f",m_fSimTime); ms_spkRenderer->Draw(90,GetHeight()-8,ColorRGB::BLACK,acMsg); ms_spkRenderer->EndScene(); } ms_spkRenderer->DisplayBackBuffer(); } //---------------------------------------------------------------------------- void BouncingSpheres::DoCollisionDetection () { m_kBContact.clear(); // collisions with boundaries Contact kContact; int i; for (i = 0; i < NUM_BALLS; i++) { Vector3f kPos = m_apkBall[i]->GetPosition(); float fRadius = m_apkBall[i]->GetRadius(); m_apkBall[i]->Moved() = false; m_akBlocked[i].clear(); // These checks are done in pairs under the assumption that the ball // radii are smaller than the separation of opposite boundaries, hence // only one of each opposite pair of boundaries may be touched at any // time. // rear [0] and front[5] boundaries if ( kPos.X() < m_akBLocation[0].X() + fRadius ) SetBoundaryContact(i,0,kPos,fRadius,kContact); else if ( kPos.X() > m_akBLocation[5].X() - fRadius ) SetBoundaryContact(i,5,kPos,fRadius,kContact); // left [1] and right [3] boundaries if ( kPos.Y() < m_akBLocation[1].Y() + fRadius ) SetBoundaryContact(i,1,kPos,fRadius,kContact); else if ( kPos.Y() > m_akBLocation[3].Y() - fRadius ) SetBoundaryContact(i,3,kPos,fRadius,kContact); // bottom [2] and top [4] boundaries if ( kPos.Z() < m_akBLocation[2].Z() + fRadius ) SetBoundaryContact(i,2,kPos,fRadius,kContact); else if ( kPos.Z() > m_akBLocation[4].Z() - fRadius ) SetBoundaryContact(i,4,kPos,fRadius,kContact); } // collisions between balls for (i = 0; i < NUM_BALLS-1; i++) { for (int j = i + 1; j < NUM_BALLS; j++) { Vector3f kDiff = m_apkBall[j]->GetPosition() - m_apkBall[i]->GetPosition(); float fDiffLen = kDiff.Length(); float fRadiusI = m_apkBall[i]->GetRadius(); float fRadiusJ = m_apkBall[j]->GetRadius(); float fMagnitude = fDiffLen - fRadiusI - fRadiusJ; if ( fMagnitude < 0.0f ) { kContact.A = m_apkBall[i]; kContact.B = m_apkBall[j]; kContact.N = kDiff/fDiffLen; Vector3f kDeltaPos = fMagnitude*kContact.N; if ( m_apkBall[i]->Moved() && !m_apkBall[j]->Moved() ) { // i moved but j not m_apkBall[j]->Position() -= kDeltaPos; } else if ( !m_apkBall[i]->Moved() && m_apkBall[j]->Moved() ) { // j moved but i not m_apkBall[i]->Position() += kDeltaPos; } else { // neither or both moved already kDeltaPos *= 0.5f; m_apkBall[j]->Position() -= kDeltaPos; m_apkBall[i]->Position() += kDeltaPos; } kContact.P = m_apkBall[i]->Position() + fRadiusI*kContact.N; m_kBContact.push_back(kContact); } } } m_iNumContacts = (int)m_kBContact.size(); } //---------------------------------------------------------------------------- void BouncingSpheres::SetBoundaryContact (int i, int iBIndex, const Vector3f& rkPos, float fRadius, Contact& rkContact) { rkContact.B = m_apkBall[i]; rkContact.A = &m_akBoundary[iBIndex]; rkContact.N = m_akBNormal[iBIndex]; rkContact.P = rkPos; m_akBlocked[i].push_back(-rkContact.N); m_kBContact.push_back(rkContact); Vector3f kBPos = m_akBoundary[iBIndex].GetPosition(); switch ( iBIndex ) { case 0: rkContact.B->Position().X() = kBPos.X() + fRadius; break; case 1: rkContact.B->Position().Y() = kBPos.Y() + fRadius; break; case 2: rkContact.B->Position().Z() = kBPos.Z() + fRadius; break; case 3: rkContact.B->Position().Y() = kBPos.Y() - fRadius; break; case 4: rkContact.B->Position().Z() = kBPos.Z() - fRadius; break; case 5: rkContact.B->Position().X() = kBPos.X() - fRadius; break; default: assert(false); } rkContact.B->Moved() = true; } //---------------------------------------------------------------------------- void BouncingSpheres::DoCollisionResponse () { if ( m_iNumContacts > 0 ) { float* afPreRelVel = new float[m_iNumContacts]; float* afImpulseMag = new float[m_iNumContacts]; ComputePreimpulseVelocity(afPreRelVel); ComputeImpulseMagnitude(afPreRelVel,afImpulseMag); DoImpulse(afImpulseMag); delete[] afPreRelVel; delete[] afImpulseMag; } DoMotion(); } //---------------------------------------------------------------------------- void BouncingSpheres::ComputeImpulseMagnitude (float* afPreRelVel, float* afImpulseMag) { // coefficient of restitution const float fRestitution = 0.8f; Vector3f kLinVelDiff, kRelA, kRelB; Vector3f kAxN, kBxN, kJInvAxN, kJInvBxN; for (int i = 0; i < m_iNumContacts; i++) { const Contact& rkContact = m_kBContact[i]; const RigidBodyf& rkBodyA = *rkContact.A; const RigidBodyf& rkBodyB = *rkContact.B; if ( afPreRelVel[i] < 0.0f ) { kLinVelDiff = rkBodyA.GetLinearVelocity() - rkBodyB.GetLinearVelocity(); kRelA = rkContact.P - rkBodyA.GetPosition(); kRelB = rkContact.P - rkBodyB.GetPosition(); kAxN = kRelA.Cross(rkContact.N); kBxN = kRelB.Cross(rkContact.N); kJInvAxN = rkBodyA.GetWorldInverseInertia()*kAxN; kJInvBxN = rkBodyB.GetWorldInverseInertia()*kBxN; float fNumer = -(1.0f+fRestitution)*(rkContact.N.Dot(kLinVelDiff) + rkBodyA.GetAngularVelocity().Dot(kAxN) - rkBodyB.GetAngularVelocity().Dot(kBxN)); float fDenom = rkBodyA.GetInverseMass() + rkBodyB.GetInverseMass() + kAxN.Dot(kJInvAxN) + kBxN.Dot(kJInvBxN); afImpulseMag[i] = fNumer/fDenom; } else { afImpulseMag[i] = 0.0f; } } } //---------------------------------------------------------------------------- void BouncingSpheres::ComputePreimpulseVelocity (float* afPreRelVel) { for (int i = 0; i < m_iNumContacts; i++) { const Contact& rkContact = m_kBContact[i]; const RigidBodyf& rkBodyA = *rkContact.A; const RigidBodyf& rkBodyB = *rkContact.B; Vector3f kRelA = rkContact.P - rkBodyA.GetPosition(); Vector3f kRelB = rkContact.P - rkBodyB.GetPosition(); Vector3f kVelA = rkBodyA.GetLinearVelocity() + rkBodyA.GetAngularVelocity().Cross(kRelA); Vector3f kVelB = rkBodyB.GetLinearVelocity() + rkBodyB.GetAngularVelocity().Cross(kRelB); afPreRelVel[i] = rkContact.N.Dot(kVelB-kVelA); } } //---------------------------------------------------------------------------- void BouncingSpheres::DoImpulse (float* afImpulseMag) { for (int i = 0; i < m_iNumContacts; i++) { Contact& rkContact = m_kBContact[i]; RigidBodyf& rkBodyA = *rkContact.A; RigidBodyf& rkBodyB = *rkContact.B; // update linear/angular momentum Vector3f kImpulse = afImpulseMag[i]*rkContact.N; rkBodyA.SetLinearMomentum(rkBodyA.GetLinearMomentum() + kImpulse); rkBodyB.SetLinearMomentum(rkBodyB.GetLinearMomentum() - kImpulse); } } //---------------------------------------------------------------------------- void BouncingSpheres::DoMotion () { for (int i = 0; i < NUM_BALLS; i++) m_apkBall[i]->Update(m_fSimTime,m_fSimDelta); } //---------------------------------------------------------------------------- Vector3f BouncingSpheres::Force (float, float fMass, const Vector3f&, const Quaternionf&, const Vector3f&, const Vector3f&, const Matrix3f&, const Vector3f&, const Vector3f&) { const float fGravityConstant = 9.81f; // m/sec/sec const Vector3f kGravityDirection = Vector3f(0.0f,0.0f,-1.0f); return (fMass*fGravityConstant)*kGravityDirection; } //---------------------------------------------------------------------------- Vector3f BouncingSpheres::Torque (float, float, const Vector3f&, const Quaternionf&, const Vector3f&, const Vector3f&, const Matrix3f&, const Vector3f&, const Vector3f&) { return Vector3f::ZERO; } //----------------------------------------------------------------------------
[ [ [ 1, 564 ] ] ]
694eb5eaee848d628b1c14da03f96403d34f2f2d
43c8fd003f99a2764bcb39290520c1e9108afc99
/touchscreen/app/waveform.h
5c5133a0f69005c01ed666781328edf2d92f94aa
[]
no_license
undees/esc
0f09ffa05f37a588da4f8a0f284607a9e7334763
eef0ebee8159ab45323e86de6c6b5444c62e1a71
refs/heads/master
2016-08-05T08:27:29.511129
2010-06-08T00:45:46
2010-06-08T00:45:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
h
// waveform.h : main header file for the WAVEFORM application // #if !defined(AFX_WAVEFORM_H__BFA7BB23_1DD1_41FF_9765_3B0F23AA3730__INCLUDED_) #define AFX_WAVEFORM_H__BFA7BB23_1DD1_41FF_9765_3B0F23AA3730__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CWaveformApp: // See waveform.cpp for the implementation of this class // class CWaveformApp : public CWinApp { public: CWaveformApp(); // Overrides //{{AFX_VIRTUAL(CWaveformApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CWaveformApp) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} #endif // !defined(AFX_WAVEFORM_H__BFA7BB23_1DD1_41FF_9765_3B0F23AA3730__INCLUDED_)
[ [ [ 1, 45 ] ] ]
612dcea7e63289863aed524d83f09d5b4f6622eb
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qimage.h
4d383a8fb820fb2ed2d8e1209056dbc0bbca6ee0
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,179
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QIMAGE_H #define QIMAGE_H #include <QtGui/qtransform.h> #include <QtGui/qpaintdevice.h> #include <QtGui/qrgb.h> #include <QtCore/qbytearray.h> #include <QtCore/qrect.h> #include <QtCore/qstring.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QIODevice; class QStringList; class QMatrix; class QTransform; class QVariant; template <class T> class QList; template <class T> class QVector; struct QImageData; class QImageDataMisc; // internal #ifndef QT_NO_IMAGE_TEXT class Q_GUI_EXPORT QImageTextKeyLang { public: QImageTextKeyLang(const char* k, const char* l) : key(k), lang(l) { } QImageTextKeyLang() { } QByteArray key; QByteArray lang; bool operator< (const QImageTextKeyLang& other) const { return key < other.key || (key==other.key && lang < other.lang); } bool operator== (const QImageTextKeyLang& other) const { return key==other.key && lang==other.lang; } inline bool operator!= (const QImageTextKeyLang &other) const { return !operator==(other); } }; #endif //QT_NO_IMAGE_TEXT class Q_GUI_EXPORT QImage : public QPaintDevice { public: enum InvertMode { InvertRgb, InvertRgba }; enum Format { Format_Invalid, Format_Mono, Format_MonoLSB, Format_Indexed8, Format_RGB32, Format_ARGB32, Format_ARGB32_Premultiplied, Format_RGB16, Format_ARGB8565_Premultiplied, Format_RGB666, Format_ARGB6666_Premultiplied, Format_RGB555, Format_ARGB8555_Premultiplied, Format_RGB888, Format_RGB444, Format_ARGB4444_Premultiplied, #if 0 // reserved for future use Format_RGB15, Format_Grayscale16, Format_Grayscale8, Format_Grayscale4, Format_Grayscale4LSB, Format_Grayscale2, Format_Grayscale2LSB #endif #ifndef qdoc NImageFormats #endif }; QImage(); QImage(const QSize &size, Format format); QImage(int width, int height, Format format); QImage(uchar *data, int width, int height, Format format); QImage(const uchar *data, int width, int height, Format format); QImage(uchar *data, int width, int height, int bytesPerLine, Format format); QImage(const uchar *data, int width, int height, int bytesPerLine, Format format); #ifndef QT_NO_IMAGEFORMAT_XPM explicit QImage(const char * const xpm[]); #endif explicit QImage(const QString &fileName, const char *format = 0); #ifndef QT_NO_CAST_FROM_ASCII explicit QImage(const char *fileName, const char *format = 0); #endif QImage(const QImage &); ~QImage(); QImage &operator=(const QImage &); bool isNull() const; int devType() const; bool operator==(const QImage &) const; bool operator!=(const QImage &) const; operator QVariant() const; void detach(); bool isDetached() const; QImage copy(const QRect &rect = QRect()) const; inline QImage copy(int x, int y, int w, int h) const { return copy(QRect(x, y, w, h)); } Format format() const; QImage convertToFormat(Format f, Qt::ImageConversionFlags flags = Qt::AutoColor) const Q_REQUIRED_RESULT; QImage convertToFormat(Format f, const QVector<QRgb> &colorTable, Qt::ImageConversionFlags flags = Qt::AutoColor) const Q_REQUIRED_RESULT; int width() const; int height() const; QSize size() const; QRect rect() const; int depth() const; int numColors() const; QRgb color(int i) const; void setColor(int i, QRgb c); void setNumColors(int); bool allGray() const; bool isGrayscale() const; uchar *bits(); const uchar *bits() const; int numBytes() const; uchar *scanLine(int); const uchar *scanLine(int) const; int bytesPerLine() const; bool valid(int x, int y) const; bool valid(const QPoint &pt) const; int pixelIndex(int x, int y) const; int pixelIndex(const QPoint &pt) const; QRgb pixel(int x, int y) const; QRgb pixel(const QPoint &pt) const; void setPixel(int x, int y, uint index_or_rgb); void setPixel(const QPoint &pt, uint index_or_rgb); QVector<QRgb> colorTable() const; void setColorTable(const QVector<QRgb> colors); void fill(uint pixel); bool hasAlphaChannel() const; void setAlphaChannel(const QImage &alphaChannel); QImage alphaChannel() const; QImage createAlphaMask(Qt::ImageConversionFlags flags = Qt::AutoColor) const; #ifndef QT_NO_IMAGE_HEURISTIC_MASK QImage createHeuristicMask(bool clipTight = true) const; #endif QImage createMaskFromColor(QRgb color, Qt::MaskMode mode = Qt::MaskInColor) const; inline QImage scaled(int w, int h, Qt::AspectRatioMode aspectMode = Qt::IgnoreAspectRatio, Qt::TransformationMode mode = Qt::FastTransformation) const { return scaled(QSize(w, h), aspectMode, mode); } QImage scaled(const QSize &s, Qt::AspectRatioMode aspectMode = Qt::IgnoreAspectRatio, Qt::TransformationMode mode = Qt::FastTransformation) const; QImage scaledToWidth(int w, Qt::TransformationMode mode = Qt::FastTransformation) const; QImage scaledToHeight(int h, Qt::TransformationMode mode = Qt::FastTransformation) const; QImage transformed(const QMatrix &matrix, Qt::TransformationMode mode = Qt::FastTransformation) const; static QMatrix trueMatrix(const QMatrix &, int w, int h); QImage transformed(const QTransform &matrix, Qt::TransformationMode mode = Qt::FastTransformation) const; static QTransform trueMatrix(const QTransform &, int w, int h); QImage mirrored(bool horizontally = false, bool vertically = true) const; QImage rgbSwapped() const; void invertPixels(InvertMode = InvertRgb); bool load(QIODevice *device, const char* format); bool load(const QString &fileName, const char* format=0); bool loadFromData(const uchar *buf, int len, const char *format = 0); inline bool loadFromData(const QByteArray &data, const char* aformat=0) { return loadFromData(reinterpret_cast<const uchar *>(data.constData()), data.size(), aformat); } bool save(const QString &fileName, const char* format=0, int quality=-1) const; bool save(QIODevice *device, const char* format=0, int quality=-1) const; static QImage fromData(const uchar *data, int size, const char *format = 0); inline static QImage fromData(const QByteArray &data, const char *format = 0) { return fromData(reinterpret_cast<const uchar *>(data.constData()), data.size(), format); } int serialNumber() const; qint64 cacheKey() const; QPaintEngine *paintEngine() const; // Auxiliary data int dotsPerMeterX() const; int dotsPerMeterY() const; void setDotsPerMeterX(int); void setDotsPerMeterY(int); QPoint offset() const; void setOffset(const QPoint&); #ifndef QT_NO_IMAGE_TEXT QStringList textKeys() const; QString text(const QString &key = QString()) const; void setText(const QString &key, const QString &value); // The following functions are obsolete as of 4.1 QString text(const char* key, const char* lang=0) const; QList<QImageTextKeyLang> textList() const; QStringList textLanguages() const; QString text(const QImageTextKeyLang&) const; void setText(const char* key, const char* lang, const QString&); #endif #ifdef QT3_SUPPORT enum Endian { BigEndian, LittleEndian, IgnoreEndian }; QT3_SUPPORT_CONSTRUCTOR QImage(int width, int height, int depth, int numColors=0, Endian bitOrder=IgnoreEndian); QT3_SUPPORT_CONSTRUCTOR QImage(const QSize&, int depth, int numColors=0, Endian bitOrder=IgnoreEndian); QT3_SUPPORT_CONSTRUCTOR QImage(uchar *data, int w, int h, int depth, const QRgb *colortable, int numColors, Endian bitOrder); #ifdef Q_WS_QWS QT3_SUPPORT_CONSTRUCTOR QImage(uchar *data, int w, int h, int depth, int pbl, const QRgb *colortable, int numColors, Endian bitOrder); #endif inline QT3_SUPPORT Endian bitOrder() const { Format f = format(); return f == Format_Mono ? BigEndian : (f == Format_MonoLSB ? LittleEndian : IgnoreEndian); } QT3_SUPPORT QImage convertDepth(int, Qt::ImageConversionFlags flags = Qt::AutoColor) const; QT3_SUPPORT QImage convertDepthWithPalette(int, QRgb* p, int pc, Qt::ImageConversionFlags flags = Qt::AutoColor) const; QT3_SUPPORT QImage convertBitOrder(Endian) const; QT3_SUPPORT bool hasAlphaBuffer() const; QT3_SUPPORT void setAlphaBuffer(bool); QT3_SUPPORT uchar **jumpTable(); QT3_SUPPORT const uchar * const *jumpTable() const; inline QT3_SUPPORT void reset() { *this = QImage(); } static inline QT3_SUPPORT Endian systemByteOrder() { return QSysInfo::ByteOrder == QSysInfo::BigEndian ? BigEndian : LittleEndian; } inline QT3_SUPPORT QImage swapRGB() const { return rgbSwapped(); } inline QT3_SUPPORT QImage mirror(bool horizontally = false, bool vertically = true) const { return mirrored(horizontally, vertically); } QT3_SUPPORT bool create(const QSize&, int depth, int numColors=0, Endian bitOrder=IgnoreEndian); QT3_SUPPORT bool create(int width, int height, int depth, int numColors=0, Endian bitOrder=IgnoreEndian); inline QT3_SUPPORT QImage xForm(const QMatrix &matrix) const { return transformed(QTransform(matrix)); } inline QT3_SUPPORT QImage smoothScale(int w, int h, Qt::AspectRatioMode mode = Qt::IgnoreAspectRatio) const { return scaled(QSize(w, h), mode, Qt::SmoothTransformation); } inline QImage QT3_SUPPORT smoothScale(const QSize &s, Qt::AspectRatioMode mode = Qt::IgnoreAspectRatio) const { return scaled(s, mode, Qt::SmoothTransformation); } inline QT3_SUPPORT QImage scaleWidth(int w) const { return scaledToWidth(w); } inline QT3_SUPPORT QImage scaleHeight(int h) const { return scaledToHeight(h); } inline QT3_SUPPORT void invertPixels(bool invertAlpha) { invertAlpha ? invertPixels(InvertRgba) : invertPixels(InvertRgb); } inline QT3_SUPPORT QImage copy(int x, int y, int w, int h, Qt::ImageConversionFlags) const { return copy(QRect(x, y, w, h)); } inline QT3_SUPPORT QImage copy(const QRect &rect, Qt::ImageConversionFlags) const { return copy(rect); } static QT3_SUPPORT Endian systemBitOrder(); inline QT3_SUPPORT_CONSTRUCTOR QImage(const QByteArray &data) { d = 0; *this = QImage::fromData(data); } #endif protected: virtual int metric(PaintDeviceMetric metric) const; private: friend class QWSOnScreenSurface; QImageData *d; friend class QRasterPixmapData; friend class QDetachedPixmap; friend Q_GUI_EXPORT qint64 qt_image_id(const QImage &image); friend const QVector<QRgb> *qt_image_colortable(const QImage &image); public: typedef QImageData * DataPtr; inline DataPtr &data_ptr() { return d; } }; Q_DECLARE_SHARED(QImage) Q_DECLARE_TYPEINFO(QImage, Q_MOVABLE_TYPE); // Inline functions... Q_GUI_EXPORT_INLINE bool QImage::valid(const QPoint &pt) const { return valid(pt.x(), pt.y()); } Q_GUI_EXPORT_INLINE int QImage::pixelIndex(const QPoint &pt) const { return pixelIndex(pt.x(), pt.y());} Q_GUI_EXPORT_INLINE QRgb QImage::pixel(const QPoint &pt) const { return pixel(pt.x(), pt.y()); } Q_GUI_EXPORT_INLINE void QImage::setPixel(const QPoint &pt, uint index_or_rgb) { setPixel(pt.x(), pt.y(), index_or_rgb); } // QImage stream functions #if !defined(QT_NO_DATASTREAM) Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QImage &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QImage &); #endif #ifdef QT3_SUPPORT Q_GUI_EXPORT QT3_SUPPORT void bitBlt(QImage* dst, int dx, int dy, const QImage* src, int sx=0, int sy=0, int sw=-1, int sh=-1, Qt::ImageConversionFlags flags = Qt::AutoColor); #endif QT_END_NAMESPACE QT_END_HEADER #endif // QIMAGE_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 352 ] ] ]
9a65834def8a66ecdec0d720425f341bbe6d264c
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/RichEditCtrlX.h
13c97a5701985baaf12060b26ed826a4eb4d88c4
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
1,624
h
#pragma once ///////////////////////////////////////////////////////////////////////////// // CRichEditCtrlX window class CRichEditCtrlX : public CRichEditCtrl { public: CRichEditCtrlX(); virtual ~CRichEditCtrlX(); void SetDisableSelectOnFocus(bool bDisable = true); void SetSyntaxColoring(const LPCTSTR* ppszKeywords = NULL, LPCTSTR pszSeperators = NULL); CRichEditCtrlX& operator<<(LPCTSTR psz); CRichEditCtrlX& operator<<(char* psz); CRichEditCtrlX& operator<<(UINT uVal); CRichEditCtrlX& operator<<(int iVal); CRichEditCtrlX& operator<<(double fVal); void SetRTFText(const CStringA& rstrText); protected: bool m_bDisableSelectOnFocus; bool m_bSelfUpdate; bool m_bForceArrowCursor; HCURSOR m_hArrowCursor; CStringArray m_astrKeywords; CString m_strSeperators; CHARFORMAT m_cfDef; CHARFORMAT m_cfKeyword; void UpdateSyntaxColoring(); static DWORD CALLBACK StreamInCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb); virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() afx_msg UINT OnGetDlgCode(); afx_msg BOOL OnEnLink(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnEnChange(); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); // ==> XP Style Menu [Xanatos] - Stulle afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct); afx_msg LRESULT OnMenuChar(UINT nChar, UINT nFlags, CMenu* pMenu); // <== XP Style Menu [Xanatos] - Stulle };
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 49 ] ] ]
a000744322b0cdb16967298e50c06f81e5f1a48b
b4f709ac9299fe7a1d3fa538eb0714ba4461c027
/trunk/powertabfileheadertestsuite.h
7d6ed74bc1308179babc6183caef9adbec39ba68
[]
no_license
BackupTheBerlios/ptparser-svn
d953f916eba2ae398cc124e6e83f42e5bc4558f0
a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c
refs/heads/master
2020-05-27T12:26:21.811820
2005-11-06T14:23:18
2005-11-06T14:23:18
40,801,514
0
0
null
null
null
null
UTF-8
C++
false
false
2,249
h
///////////////////////////////////////////////////////////////////////////// // Name: powertabfileheadertestsuite.h // Purpose: Performs unit testing on the PowerTabFileHeader class // Author: Brad Larsen // Modified by: // Created: Dec 4, 2004 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #ifndef __POWERTABFILEHEADERTESTSUITE_H__ #define __POWERTABFILEHEADERTESTSUITE_H__ /// Performs unit testing on the PowerTabFileHeader class class PowerTabFileHeaderTestSuite : public TestSuite { DECLARE_DYNAMIC_CLASS(PowerTabFileHeaderTestSuite) public: // Constructor/Destructor PowerTabFileHeaderTestSuite(); ~PowerTabFileHeaderTestSuite(); // Overrides size_t GetTestCount() const; bool RunTestCases(); // Test Case Functions private: bool TestCaseConstructor(); bool TestCaseOperator(); bool TestCaseSerialize(); bool TestCasePowerTabFileMarker(); bool TestCaseFileVersion(); bool TestCaseFileType(); bool TestCaseSongContentType(); bool TestCaseSongTitle(); bool TestCaseSongArtist(); bool TestCaseSongReleaseType(); bool TestCaseSongAudioReleaseTitle(); bool TestCaseSongAudioReleaseYear(); bool TestCaseSongAudioReleaseLive(); bool TestCaseSongVideoReleaseTitle(); bool TestCaseSongVideoReleaseLive(); bool TestCaseSongBootlegTitle(); bool TestCaseSongBootlegDate(); bool TestCaseSongAuthorType(); bool TestCaseSongComposer(); bool TestCaseSongLyricist(); bool TestCaseSongArranger(); bool TestCaseSongGuitarScoreTranscriber(); bool TestCaseSongBassScoreTranscriber(); bool TestCaseSongCopyright(); bool TestCaseSongLyrics(); bool TestCaseSongGuitarScoreNotes(); bool TestCaseSongBassScoreNotes(); bool TestCaseLessonTitle(); bool TestCaseLessonSubtitle(); bool TestCaseLessonMusicStyle(); bool TestCaseLessonLevel(); bool TestCaseLessonAuthor(); bool TestCaseLessonNotes(); bool TestCaseLessonCopyright(); }; #endif
[ "blarsen@8c24db97-d402-0410-b267-f151a046c31a" ]
[ [ [ 1, 67 ] ] ]
3ad016dcd8542e5a39129c70c659ef1f6e929ab2
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/graphics/common/inc/TestServerBase.h
1a0e19a421e5cfac30c50719cb1376bcf5f92ee0
[]
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
764
h
/* * Copyright (c) 2008 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: * */ #if (!defined __TEST_SERVER_BASE__) #define __TEST_SERVER_BASE__ // EPOC includes #include <testserver2.h> class CTestServerBase : public CTestServer2 { public: // CTestServer implementation virtual CTestStep* CreateTestStep(const TDesC& aStepName); }; #endif /* __TEST_SERVER_BASE__ */
[ "none@none" ]
[ [ [ 1, 32 ] ] ]
f526bc19b21579c2df269e566555b7bbdce95a7b
2bf221bc84477471c79e47bdb758776176202e0a
/plc/bitmapy.h
da09f7c062e42d1fed14d18b7d93d79290e30244
[]
no_license
uraharasa/plc-programming-simulator
9613522711f6f9b477c5017e7e1dd0237316a3f4
a03e068db8b9fdee83ae4db8fe3666f0396000ef
refs/heads/master
2016-09-06T12:01:02.666354
2011-08-14T08:36:49
2011-08-14T08:36:49
34,528,882
0
1
null
null
null
null
UTF-8
C++
false
false
394
h
#ifndef bitmapy_h_included #define bitmapy_h_included #include <windows.h> #include <string> using namespace std; class bitmapa { private: int szer_mapy; int wys_mapy; HBITMAP mapa; HBITMAP maska; public: bitmapa(wstring nazwa_pliku); ~bitmapa(void); void wyswietl(HDC kontekst, int x, int y, int szer = -1, int wys = -1, int pocz_x = 0, int pocz_y = 0); }; #endif
[ "[email protected]@2c618d7f-f323-8192-d80b-44f770db81a5" ]
[ [ [ 1, 21 ] ] ]
274d2cc4a891423679d9b90fc2ccfdf7551d21d6
27b8c57bef3eb26b5e7b4b85803a8115e5453dcb
/branches/flatRL/lib/include/Plot/DrawLinePlot.h
d27a1b879ba61097c57a64ef268445831e9bd69c
[]
no_license
BackupTheBerlios/walker-svn
2576609a17eab7a08bb2437119ef162487444f19
66ae38b2c1210ac2f036e43b5f0a96013a8e3383
refs/heads/master
2020-05-30T11:30:48.193275
2011-03-24T17:10:17
2011-03-24T17:10:17
40,819,670
0
0
null
null
null
null
UTF-8
C++
false
false
3,382
h
#ifndef __WALKER_YARD_PLOT_DRAW_LINE_PLOT_H__ #define __WALKER_YARD_PLOT_DRAW_LINE_PLOT_H__ #include "LinePlot.h" #include <boost/circular_buffer.hpp> #define NOMINMAX #include <boost/thread/mutex.hpp> #include <sgl/Font.h> #include <slon/Graphics/Renderable/DebugMesh.h> #include <slon/Realm/Object.h> namespace plot { using namespace slon; /** Draws plot using debug render. */ template<int Dimension> class DrawLinePlot : public LinePlot<float, Dimension> { public: typedef DrawLinePlot<Dimension> this_type; typedef math::Matrix<float, Dimension, 1> point_type; typedef math::AABB<float, Dimension> bound_type; typedef boost::circular_buffer<point_type> point_buffer; private: friend class PlotDebugMesh; class PlotDebugMesh : public graphics::DebugMesh { public: typedef PlotDebugMesh this_type; typedef graphics::DebugMesh base_type; public: PlotDebugMesh(DrawLinePlot<Dimension>* plotter); // Override Entity void accept(scene::TransformVisitor& visitor); const math::AABBf& getBounds() const; private: DrawLinePlot<Dimension>* plotter; size_t numPlotted; }; typedef boost::intrusive_ptr<PlotDebugMesh> plot_debug_mesh_ptr; public: struct DESC { math::Vector4f axisColor; math::Vector4f lineColor; bool autoBounds; // determine bounds automatically bound_type bounds; // bounds of the plot point_type axisGranularity; // granularity of axis marks std::string axisName[Dimension]; // name of the axis size_t bufferSize; // maximum number of points in the line DESC() : axisColor(1.0f, 1.0f, 1.0f, 1.0f), lineColor(1.0f, 1.0f, 1.0f, 1.0f), autoBounds(true), bufferSize(1000) { bounds.reset_min(); } }; public: DrawLinePlot(const DESC& desc); ~DrawLinePlot(); /** Replot graphic with new plot description */ void reset(const DESC& desc); /** Setup position and size of the plot in window coordinates */ void setRegion(const math::Vector2i& position, const math::Vector2i& size); /** Hide or draw plot */ void hide(bool toggle = true); // Override LinePlot void plotBegin(); void plotEnd(); bool isPlotting() const { return plotting; } void plotPoint(const point_type& value); private: void plot(); private: DESC desc; math::Vector2i position; math::Vector2i size; bool plotting; bool dirty; bool hiding; point_buffer points; // mutex for accesing point buffer boost::mutex pointBufferMutex; // drawing plot_debug_mesh_ptr plotDebugMesh; realm::object_ptr plotObject; }; typedef DrawLinePlot<3> DrawLinePlot3D; typedef DrawLinePlot<2> DrawLinePlot2D; typedef boost::intrusive_ptr<DrawLinePlot2D> draw_line_plot_2d_ptr; typedef boost::intrusive_ptr<DrawLinePlot3D> draw_line_plot_3d_ptr; } // namespace plot #endif // __WALKER_YARD_PLOT_DRAW_LINE_PLOT_H__
[ "red-haired@9454499b-da03-4d27-8628-e94e5ff957f9" ]
[ [ [ 1, 117 ] ] ]
fc42ec50572bc87c20506341856a171527f0805a
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/chrome/chrome/src/cpp/include/v8/src/prettyprinter.h
95268b66bba61eec325aca50dc86554689486611
[ "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
4,384
h
// Copyright 2006-2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_PRETTYPRINTER_H_ #define V8_PRETTYPRINTER_H_ #include "ast.h" namespace v8 { namespace internal { #ifdef DEBUG class PrettyPrinter: public AstVisitor { public: PrettyPrinter(); virtual ~PrettyPrinter(); // The following routines print a node into a string. // The result string is alive as long as the PrettyPrinter is alive. const char* Print(Node* node); const char* PrintExpression(FunctionLiteral* program); const char* PrintProgram(FunctionLiteral* program); // Print a node to stdout. static void PrintOut(Node* node); // Individual nodes #define DEF_VISIT(type) \ virtual void Visit##type(type* node); NODE_LIST(DEF_VISIT) #undef DEF_VISIT private: char* output_; // output string buffer int size_; // output_ size int pos_; // current printing position protected: void Init(); void Print(const char* format, ...); const char* Output() const { return output_; } virtual void PrintStatements(ZoneList<Statement*>* statements); void PrintLabels(ZoneStringList* labels); virtual void PrintArguments(ZoneList<Expression*>* arguments); void PrintLiteral(Handle<Object> value, bool quote); void PrintParameters(Scope* scope); void PrintDeclarations(ZoneList<Declaration*>* declarations); void PrintFunctionLiteral(FunctionLiteral* function); void PrintCaseClause(CaseClause* clause); }; // Prints the AST structure class AstPrinter: public PrettyPrinter { public: AstPrinter(); virtual ~AstPrinter(); const char* PrintProgram(FunctionLiteral* program); // Individual nodes #define DEF_VISIT(type) \ virtual void Visit##type(type* node); NODE_LIST(DEF_VISIT) #undef DEF_VISIT private: friend class IndentedScope; void PrintIndented(const char* txt); void PrintIndentedVisit(const char* s, Node* node); void PrintStatements(ZoneList<Statement*>* statements); void PrintDeclarations(ZoneList<Declaration*>* declarations); void PrintParameters(Scope* scope); void PrintArguments(ZoneList<Expression*>* arguments); void PrintCaseClause(CaseClause* clause); void PrintLiteralIndented(const char* info, Handle<Object> value, bool quote); void PrintLiteralWithModeIndented(const char* info, Variable* var, Handle<Object> value, StaticType* type); void PrintLabelsIndented(const char* info, ZoneStringList* labels); void inc_indent() { indent_++; } void dec_indent() { indent_--; } static int indent_; }; #endif // DEBUG } } // namespace v8::internal #endif // V8_PRETTYPRINTER_H_
[ "noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 118 ] ] ]
0e72f1dedf256752e25575c067176d94dd1020d9
e4bad8b090b8f2fd1ea44b681e3ac41981f50220
/trunk/Abeetles/Abeetles/stdafx.cpp
5b0e174349e1e3e6607d99788369044e92abb001
[]
no_license
BackupTheBerlios/abeetles-svn
92d1ce228b8627116ae3104b4698fc5873466aff
803f916bab7148290f55542c20af29367ef2d125
refs/heads/master
2021-01-22T12:02:24.457339
2007-08-15T11:18:14
2007-08-15T11:18:14
40,670,857
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
// stdafx.cpp : source file that includes just the standard includes // Abeetles.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "ibart@60a5a0de-1a2f-0410-942a-f28f22aea592" ]
[ [ [ 1, 8 ] ] ]
0d3564c99dc37fd83c7650dcc6702267990ba7e7
191d4160cba9d00fce9041a1cc09f17b4b027df5
/ZeroLag2/KUILib/Include/kscbase/kscbase.h
deab148d62584a1028b1553c597b4680b87ff222
[]
no_license
zapline/zero-lag
f71d35efd7b2f884566a45b5c1dc6c7eec6577dd
1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4
refs/heads/master
2021-01-22T16:45:46.430952
2011-05-07T13:22:52
2011-05-07T13:22:52
32,774,187
3
2
null
null
null
null
UTF-8
C++
false
false
3,099
h
// Copyright (c) 2010 Kingsoft Corporation. All rights reserved. // Copyright (c) 2010 The KSafe Authors. All rights reserved. // // 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. /******************************************************************** created: 2010/03/08 created: 8:3:2010 9:38 filename: kppbase.h author: Jiang Fengbing purpose: *********************************************************************/ #ifndef KPPBASE_INC_ #define KPPBASE_INC_ ////////////////////////////////////////////////////////////////////////// #include <string> #include <vector> #include <tchar.h> #include <windows.h> ////////////////////////////////////////////////////////////////////////// template <typename T, size_t N> char (&ArraySizeHelper(const T (&array)[N]))[N]; #define arraysize(array) (sizeof(ArraySizeHelper(array))) ////////////////////////////////////////////////////////////////////////// inline bool GetModuleFileName(std::string& strFileName, HMODULE hModule) { bool retval = false; CHAR szFileName[MAX_PATH] = { 0 }; DWORD dwRetCode; dwRetCode = ::GetModuleFileNameA(hModule, szFileName, MAX_PATH); if (dwRetCode) goto clean0; strFileName = szFileName; retval = true; clean0: return retval; } ////////////////////////////////////////////////////////////////////////// inline bool GetModuleFileName(std::wstring& strFileName, HMODULE hModule) { bool retval = false; WCHAR szFileName[MAX_PATH] = { 0 }; DWORD dwRetCode; dwRetCode = ::GetModuleFileNameW(hModule, szFileName, MAX_PATH); if (dwRetCode) goto clean0; strFileName = szFileName; retval = true; clean0: return retval; } inline bool trims( const std::wstring& str, std::vector <std::wstring>& vcResult, TCHAR c) { size_t fst = str.find_first_not_of( c ); size_t lst = str.find_last_not_of( c ); if( fst != std::wstring::npos ) vcResult.push_back(str.substr(fst, lst - fst + 1)); return true; } inline int SplitCString(std::wstring strIn, std::vector<std::wstring>& vec_String, TCHAR division) { vec_String.clear(); if (!strIn.empty()) { size_t nIter = 0; size_t nLast = 0; std::wstring v; while (true) { nIter = strIn.find(division, nIter); trims(strIn.substr(nLast, nIter - nLast), vec_String, division); if( nIter == std::wstring::npos ) break; nLast = ++nIter; } } return (int)vec_String.size(); } ////////////////////////////////////////////////////////////////////////// #endif // KPPBASE_INC_
[ "Administrator@PC-200201010241" ]
[ [ [ 1, 116 ] ] ]
52b6fd50ff675084555d5b2ce99fae7fe1627a82
b6c9433cefda8cfe76c8cb6550bf92dde38e68a8
/epoc32/include/xmlentityreferences.h
e14c124584fc7dc80042717d3806d462333d0329
[]
no_license
fedor4ever/public-headers
667f8b9d0dc70aa3d52d553fd4cbd5b0a532835f
3666a83565a8de1b070f5ac0b22cc0cbd59117a4
refs/heads/master
2021-01-01T05:51:44.592006
2010-03-31T11:33:34
2010-03-31T11:33:34
33,378,397
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
// Autogenerated from epoc32/build/legacyminidomparser/c_212b04b63d6cae98/xmlparser_dll/xmlentityreferences.st by the stringtable tool - Do not edit #ifndef STRINGTABLE_XMLEntityReferences #define STRINGTABLE_XMLEntityReferences #include <stringpool.h> struct TStringTable; /** A String table */ class XMLEntityReferences { public: enum TStrings { /** &lt; < */ ELT, /** &amp; & */ EAmp, /** &gt; > */ EGt, /** &quot; \" */ EDbleQuote, /** &apos; ' */ ESingleQuote }; static const TStringTable Table; }; #endif // STRINGTABLE_XMLEntityReferences
[ [ [ 1, 31 ] ] ]
b574b1e015dbdf856a2f7bf53b7b1cdd4fb08a7c
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/validators/datatype/StringDatatypeValidator.hpp
dda3ef44b597fe4d442bd09ba3e67753f6be3b3b
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
5,202
hpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: StringDatatypeValidator.hpp,v 1.9 2004/09/08 13:56:53 peiyongz Exp $ * $Log: StringDatatypeValidator.hpp,v $ * Revision 1.9 2004/09/08 13:56:53 peiyongz * Apache License Version 2.0 * * Revision 1.8 2004/01/29 11:51:22 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.7 2003/12/17 00:18:39 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.6 2003/10/01 01:09:35 knoaman * Refactoring of some code to improve performance. * * Revision 1.5 2003/09/29 21:47:35 peiyongz * Implementation of Serialization/Deserialization * * Revision 1.4 2003/05/15 18:53:27 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.3 2002/12/18 14:17:55 gareth * Fix to bug #13438. When you eant a vector that calls delete[] on its members you should use RefArrayVectorOf. * * Revision 1.2 2002/11/04 14:53:28 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:42 peiyongz * sane_include * * Revision 1.10 2001/11/22 20:23:20 peiyongz * _declspec(dllimport) and inline warning C4273 * * Revision 1.9 2001/10/09 20:54:48 peiyongz * init(): removed * * Revision 1.8 2001/09/27 13:51:25 peiyongz * DTV Reorganization: ctor/init created to be used by derived class * * Revision 1.7 2001/09/24 21:39:12 peiyongz * DTV Reorganization: * * Revision 1.6 2001/09/24 15:31:13 peiyongz * DTV Reorganization: inherit from AbstractStringValidator * */ #if !defined(STRING_DATATYPEVALIDATOR_HPP) #define STRING_DATATYPEVALIDATOR_HPP #include <xercesc/validators/datatype/AbstractStringValidator.hpp> XERCES_CPP_NAMESPACE_BEGIN class VALIDATORS_EXPORT StringDatatypeValidator : public AbstractStringValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructors and Destructor */ //@{ StringDatatypeValidator ( MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); StringDatatypeValidator ( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); virtual ~StringDatatypeValidator(); //@} /** * Returns an instance of the base datatype validator class * Used by the DatatypeValidatorFactory. */ virtual DatatypeValidator* newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(StringDatatypeValidator) protected: // // ctor provided to be used by derived classes // StringDatatypeValidator ( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , const int finalSet , const ValidatorType type , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); virtual void assignAdditionalFacet(const XMLCh* const key , const XMLCh* const value , MemoryManager* const manager); virtual void inheritAdditionalFacet(); virtual void checkAdditionalFacetConstraints(MemoryManager* const manager) const; virtual void checkAdditionalFacet(const XMLCh* const content , MemoryManager* const manager) const; virtual void checkValueSpace(const XMLCh* const content , MemoryManager* const manager); private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- StringDatatypeValidator(const StringDatatypeValidator&); StringDatatypeValidator& operator=(const StringDatatypeValidator&); }; XERCES_CPP_NAMESPACE_END #endif /** * End of file StringDatatypeValidator.hpp */
[ [ [ 1, 156 ] ] ]
9b202987405308c25fa1e326be890b29a452160e
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WP_TimeSync/Base64.h
b8eec5c63698136eb48f57f9252713be5b81aa90
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
1,622
h
/* Module : Base64.h Purpose: Defines the interface for a simple base64 decoding class Created: PJN / 22-04-1999 Copyright (c) 1999 - 2004 by PJ Naughter. (Web: www.naughter.com, Email: [email protected]) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ /////////////////////////////// Defines /////////////////////////////////////// #ifndef __BASE64_H__ #define __BASE64_H__ #ifndef SOCKMFC_EXT_CLASS #define SOCKMFC_EXT_CLASS #endif /////////////////////////////// Classes /////////////////////////////////////// class SOCKMFC_EXT_CLASS CBase64 { public: //Defines #define BASE64_FLAG_NONE 0 #define BASE64_FLAG_NOPAD 1 #define BASE64_FLAG_NOCRLF 2 //Methods int DecodeGetRequiredLength(int nSrcLen); int EncodeGetRequiredLength(int nSrcLen, DWORD dwFlags = BASE64_FLAG_NONE); BOOL Encode(const BYTE* pbSrcData, int nSrcLen, LPSTR szDest, int* pnDestLen, DWORD dwFlags = BASE64_FLAG_NONE); BOOL Decode(LPCSTR szSrc, int nSrcLen, BYTE* pbDest, int* pnDestLen); protected: int DecodeChar(unsigned int ch); }; #endif //__BASE64_H__
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 52 ] ] ]
863568783a66f5611f0a6f6119dfb21838972718
9df2486e5d0489f83cc7dcfb3ccc43374ab2500c
/src/core/math/rect.h
fb7f7bd76f996c681ef1de8902557c317b9ddadb
[]
no_license
renardchien/Eta-Chronicles
27ad4ffb68385ecaafae4f12b0db67c096f62ad1
d77d54184ec916baeb1ab7cc00ac44005d4f5624
refs/heads/master
2021-01-10T19:28:28.394781
2011-09-05T14:40:38
2011-09-05T14:40:38
1,914,623
1
2
null
null
null
null
UTF-8
C++
false
false
4,072
h
/*************************************************************************** * rect.h - header for the corresponding cpp file * * Copyright (C) 2003 - 2009 Florian Richter ***************************************************************************/ /* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SMC_RECT_H #define SMC_RECT_H #include "../../core/global_game.h" #include "../../core/math/point.h" #include "../../core/math/utilities.h" #include "SDL.h" namespace SMC { /* *** *** *** *** *** *** *** GL_rect *** *** *** *** *** *** *** *** *** *** */ class GL_rect { public: GL_rect( void ) : m_x( 0 ), m_y( 0 ), m_w( 0 ), m_h( 0 ) {} GL_rect( const GL_rect *rect ) : m_x( rect->m_x ), m_y( rect->m_y ), m_w( rect->m_w ), m_h( rect->m_h ) {} GL_rect( float x, float y, float w, float h ) : m_x( x ), m_y( y ), m_w( w ), m_h( h ) {} // returns a SDL_Rect SDL_Rect Get_Rect( void ) const { SDL_Rect rect; rect.x = static_cast<Sint16>(m_x); rect.y = static_cast<Sint16>(m_y); rect.w = static_cast<Uint16>(m_w); rect.h = static_cast<Uint16>(m_h); return rect; } // returns this as SDL_Rect SDL_Rect Get_Rect_pos( float posx, float posy ) const { SDL_Rect rect; rect.x = static_cast<Sint16>(m_x + posx); rect.y = static_cast<Sint16>(m_y + posy); rect.w = static_cast<Uint16>(m_w); rect.h = static_cast<Uint16>(m_h); return rect; } // returns the point in the middle of the rect GL_point Get_pos_middle( void ) const { return GL_point( m_x + ( m_w / 2 ), m_y + ( m_h / 2 ) ); } // clears the data void clear( void ) { m_x = 0; m_y = 0; m_w = 0; m_h = 0; } // returns true if we intersect with the point bool Intersects( const float x, const float y ) const { if( x > m_x + m_w ) { return 0; } if( x < m_x ) { return 0; } if( y > m_y + m_h ) { return 0; } if( y < m_y ) { return 0; } // they intersect return 1; } // returns true if we intersect with the rect bool Intersects( const GL_rect &b ) const { if( b.m_x + b.m_w < m_x ) { return 0; } if( b.m_x > m_x + m_w ) { return 0; } if( b.m_y + b.m_h < m_y ) { return 0; } if( b.m_y > m_y + m_h ) { return 0; } // they intersect return 1; } // += operator inline void operator += ( const GL_rect &r ) { m_x += r.m_x; m_y += r.m_y; m_w += r.m_w; m_h += r.m_h; } // -= operator inline void operator -= ( const GL_rect &r ) { m_x -= r.m_x; m_y -= r.m_y; m_w -= r.m_w; m_h -= r.m_h; } // + operator inline GL_rect operator + ( const GL_rect &r ) const { return GL_rect( m_x + r.m_x, m_y + r.m_y, m_w + r.m_w, m_h + r.m_h ); } // - operator inline GL_rect operator - ( const GL_rect &r ) const { return GL_rect( m_x - r.m_x, m_y - r.m_y, m_w - r.m_w, m_h - r.m_h ); } // unary - operator inline GL_rect operator - () const { return GL_rect( -m_x, -m_y, -m_w, -m_h ); } // assignment operator inline GL_rect &operator = ( const GL_rect &r ) { m_x = r.m_x; m_y = r.m_y; m_w = r.m_w; m_h = r.m_h; return *this; } // compare inline bool operator == ( const GL_rect &r ) const { return ( Is_Float_Equal(m_x, r.m_x) && Is_Float_Equal(m_y, r.m_y) && Is_Float_Equal(m_w, r.m_w) && Is_Float_Equal(m_h, r.m_h) ); } inline bool operator != ( const GL_rect &r ) const { return !(operator == (r)); } float m_x, m_y; float m_w, m_h; }; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ } // namespace SMC #endif
[ [ [ 1, 195 ] ] ]
1ce7a7520c472f774a5cf4d59e4dcec0f29e65df
d94c6cce730a771c18a6d84c7991464129ed3556
/vp_plugins/auth_plugin/auth.h
6572b60a32cdf5c2054369f8aa3b6aec9f6da990
[]
no_license
S1aNT/cupsfilter
09afbcedb4f011744e670fae74d71fce4cebdd25
26ecc1e76eefecde2b00173dff9f91ebd92fb349
refs/heads/master
2021-01-02T09:26:27.015991
2011-03-15T06:43:47
2011-03-15T06:43:47
32,496,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,064
h
#ifndef AUTH_H #define AUTH_H #include <QObject> #if defined(Q_OS_WIN) #include <windows.h> #endif #include <stdio.h> #include "auth_plugin.h" #include "mytypes.h" using namespace VPrn; class QString; #if defined(Q_OS_WIN) #define PLUGIN_API __declspec(dllimport) typedef PLUGIN_API LPWSTR (*DLLGETCURRENTUSER)(void); typedef PLUGIN_API LPWSTR (*DLLGETCURRENTSECLABEL)(void); typedef PLUGIN_API bool (*DLLISAUTHUSER)(void); typedef PLUGIN_API LPCTSTR (*ABOUTPLUGIN)(void); #endif class Auth : public QObject, Auth_plugin { Q_OBJECT Q_INTERFACES(Auth_plugin) public: Auth(){} void init (const QString &mandat_filename); void init (); signals: void error(VPrn::AppErrorType errCode,QString error_message); void get_User_name_mandat(QString &userName,QString &userMandat); private: QString user_name; QString user_mandat; QString plugin_path; // Получить имя пользователя из реестра QString ask4System(); }; //! [0] #endif
[ [ [ 1, 51 ] ] ]
aac64ea0e13a8b424637762b1e76847e1851da8a
a3d70ef949478e1957e3a548d8db0fddb9efc125
/src/game/Spirit.h
0f3c75f56137180e852b305bee26f12508c184c4
[]
no_license
SakuraSinojun/ling
fc58afea7c4dfe536cbafa93c0c6e3a7612e5281
46907e5548008d7216543bdd5b9cc058421f4eb8
refs/heads/master
2021-01-23T06:54:30.049039
2011-01-16T12:23:24
2011-01-16T12:23:24
32,323,103
0
0
null
null
null
null
UTF-8
C++
false
false
121
h
#pragma once #ifndef __SPIRIT_H__ #define __SPIRIT_H__ class CSpirit { } #endif
[ "SakuraSinojun@f09d58f5-735d-f1c9-472e-e8791f25bd30" ]
[ [ [ 1, 24 ] ] ]
fe634c6446920e79e7f5c2226f24e3cffefbca19
2e3518a5507a35efafa32d5c14f990a2ba8efc64
/Utilities.cpp
6209b255f1fc731a5df6b10b83e82460918c862a
[]
no_license
alur/AlbumArt
8ea5383c565e198293ad31c0722f79d193ba872d
d8e429a1621b0b4f1865964c3eca6c5683d52b05
refs/heads/master
2020-12-24T13:36:26.791806
2011-01-17T07:19:49
2011-01-17T07:19:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,033
cpp
#include <id3/globals.h> #include "utilities.h" // Checks if a file exists bool Utilities::File_Exists (LPCSTR pszFilePath) { return GetFileAttributes(pszFilePath) != INVALID_FILE_ATTRIBUTES; } void Utilities::URLEncode(LPCSTR pszString, LPSTR pszEncoded, UINT cchLength) { for (UINT i = 0, iPos = 0; iPos < cchLength; i++) { if (pszString[i] == 0) { pszEncoded[iPos] = 0; break; } else if ((48 <= pszString[i] && pszString[i] <= 57) || (65 <= pszString[i] && pszString[i] <= 90) || (97 <= pszString[i] && pszString[i] <= 122) || pszString[i] == '~' || pszString[i] == '!' || pszString[i] == '*' || pszString[i] == '(' || pszString[i] == ')' || pszString[i] == '\'') { pszEncoded[iPos++] = pszString[i]; } else { // Work out ASCII values for the 2 hex digits char digit1 = (pszString[i] & 0xF0) >> 4, digit2 = (pszString[i] & 0x0F); digit1 += (digit1 < 10) ? 48 : 87; digit2 += (digit2 < 10) ? 48 : 87; pszEncoded[iPos++] = '%'; pszEncoded[iPos++] = digit1; pszEncoded[iPos++] = digit2; } } } bool Utilities::GetExtendedWinampFileInfo(LPCSTR pszFile, LPCSTR pszField, LPSTR pszOut, UINT cchLength) { HWND hwndWA2 = FindWindow("Winamp v1.x", NULL); if (hwndWA2 == NULL) return false; ULONG dWinamp; GetWindowThreadProcessId(hwndWA2, &dWinamp); HANDLE hWinamp; hWinamp = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, dWinamp); extendedFileInfoStruct exFIS = {0}; // Allocate some memory in winamps address space char *remBuf = (char *)VirtualAllocEx(hWinamp, NULL, cchLength, MEM_COMMIT, PAGE_READWRITE); char *remMetaDataBuf = (char *)VirtualAllocEx(hWinamp, NULL, 64, MEM_COMMIT, PAGE_READWRITE); char *remStruct = (char *)VirtualAllocEx(hWinamp, NULL, sizeof(exFIS), MEM_COMMIT, PAGE_READWRITE); char *remFileBuf = (char *)VirtualAllocEx(hWinamp, NULL, 512, MEM_COMMIT, PAGE_READWRITE); // Fill in the data for the extendedfileinfostruct exFIS.filename = remFileBuf; exFIS.metadata = remMetaDataBuf; exFIS.ret = remBuf; exFIS.retlen = cchLength; // Copy over the extendedfileinfostruct and it's data to winamps address space WriteProcessMemory(hWinamp, remFileBuf, pszFile, 512, NULL); WriteProcessMemory(hWinamp, remMetaDataBuf, pszField, 64, NULL); WriteProcessMemory(hWinamp, remStruct, &exFIS, sizeof(exFIS), NULL); // Have winamp read the extendedfileinfostruct and put the desired metadata in remBuf if (!SendMessage(hwndWA2, WM_USER, (WPARAM)remStruct, 296)) return false; // Copy remBuf to local memory ReadProcessMemory(hWinamp, remBuf, pszOut, cchLength, NULL); // Free up memory allocated in winamps address space VirtualFreeEx(hWinamp, remBuf, cchLength, MEM_DECOMMIT); VirtualFreeEx(hWinamp, remBuf, 0, MEM_RELEASE); VirtualFreeEx(hWinamp, remMetaDataBuf, 64, MEM_DECOMMIT); VirtualFreeEx(hWinamp, remMetaDataBuf, 0, MEM_RELEASE); VirtualFreeEx(hWinamp, remStruct, sizeof(exFIS), MEM_DECOMMIT); VirtualFreeEx(hWinamp, remStruct, 0, MEM_RELEASE); VirtualFreeEx(hWinamp, remFileBuf, 512, MEM_DECOMMIT); VirtualFreeEx(hWinamp, remFileBuf, 0, MEM_RELEASE); return true; } UCHAR Utilities::StringToParseType(LPCSTR szParse) { if (_stricmp(szParse, "Other") == 0) return ID3PT_OTHER; else if (_stricmp(szParse, "PNG32Icon") == 0) return ID3PT_PNG32ICON; else if (_stricmp(szParse, "OtherIcon") == 0) return ID3PT_OTHERICON; else if (_stricmp(szParse, "CoverFront") == 0) return ID3PT_COVERFRONT; else if (_stricmp(szParse, "CoverBack") == 0) return ID3PT_COVERBACK; else if (_stricmp(szParse, "LeafletPage") == 0) return ID3PT_LEAFLETPAGE; else if (_stricmp(szParse, "Media") == 0) return ID3PT_MEDIA; else if (_stricmp(szParse, "LeadArtist") == 0) return ID3PT_LEADARTIST; else if (_stricmp(szParse, "Artist") == 0) return ID3PT_ARTIST; else if (_stricmp(szParse, "Conductor") == 0) return ID3PT_CONDUCTOR; else if (_stricmp(szParse, "Band") == 0) return ID3PT_BAND; else if (_stricmp(szParse, "Composer") == 0) return ID3PT_COMPOSER; else if (_stricmp(szParse, "Lyricist") == 0) return ID3PT_LYRICIST; else if (_stricmp(szParse, "RecordingLocation") == 0) return ID3PT_REC_LOCATION; else if (_stricmp(szParse, "Recording") == 0) return ID3PT_RECORDING; else if (_stricmp(szParse, "Performance") == 0) return ID3PT_PERFORMANCE; else if (_stricmp(szParse, "Video") == 0) return ID3PT_VIDEO; else if (_stricmp(szParse, "Fish") == 0) return ID3PT_FISH; else if (_stricmp(szParse, "Illustration") == 0) return ID3PT_ILLUSTRATION; else if (_stricmp(szParse, "ArtistLogo") == 0) return ID3PT_ARTISTLOGO; else if (_stricmp(szParse, "PublisherLogo") == 0) return ID3PT_PUBLISHERLOGO; return ID3PT_COVERFRONT; } bool Utilities::String2Bool(LPCSTR pszBool) { return (lstrcmpi(pszBool, "off") && lstrcmpi(pszBool, "false") && lstrcmpi(pszBool, "no") && lstrcmpi(pszBool, "0")); }
[ [ [ 1, 142 ] ] ]
6a3875734e31bc656fcef0824e00de779ffcb00f
c524e82d892bc31ccb52abc91a46fcd9ce1d9241
/core/StdAfx.cpp
7d5eee17b3d35f5cd3a9eebdc6a3204a680e9e41
[]
no_license
wenmengzi/snooker
368fd1d341e48ed9a4cfc7acce6d8f0e02e7827b
16ce9a55f334fa24d156dc9a7a6ceffc78ebcfb5
refs/heads/master
2021-01-10T01:38:56.748246
2007-06-23T16:59:21
2007-06-23T16:59:21
54,390,281
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
// stdafx.cpp : source file that includes just the standard includes // core.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "rickone2007@05450a0b-ae31-0410-b12f-21406559f0cb" ]
[ [ [ 1, 8 ] ] ]
9ddc5883a6e829c2598b5b793cb143656c44c762
8be41f8425a39f7edc92efb3b73b6a8ca91150f3
/OMFrame/OpenGL/OpenGLDoc.cpp
829a04803ac42dad92dfc856bd4d5a64fd698e37
[]
no_license
SysMa/msq-summer-project
b497a061feef25cac1c892fe4dd19ebb30ae9a56
0ef171aa62ad584259913377eabded14f9f09e4b
refs/heads/master
2021-01-23T09:28:34.696908
2011-09-16T06:39:52
2011-09-16T06:39:52
34,208,886
0
1
null
null
null
null
GB18030
C++
false
false
1,075
cpp
// OpenGLDoc.cpp : COpenGLDoc 类的实现 // #include "stdafx.h" #include "OpenGL.h" #include "OpenGLDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // COpenGLDoc IMPLEMENT_DYNCREATE(COpenGLDoc, CDocument) BEGIN_MESSAGE_MAP(COpenGLDoc, CDocument) END_MESSAGE_MAP() // COpenGLDoc 构造/析构 COpenGLDoc::COpenGLDoc() { // TODO: 在此添加一次性构造代码 } COpenGLDoc::~COpenGLDoc() { } BOOL COpenGLDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // COpenGLDoc 序列化 void COpenGLDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: 在此添加存储代码 } else { // TODO: 在此添加加载代码 } } // COpenGLDoc 诊断 #ifdef _DEBUG void COpenGLDoc::AssertValid() const { CDocument::AssertValid(); } void COpenGLDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // COpenGLDoc 命令
[ "[email protected]@551f4f89-5e81-c284-84fc-d916aa359411" ]
[ [ [ 1, 78 ] ] ]
138144e202099601315aa3a90bf0accdd9a2acbd
14298a990afb4c8619eea10988f9c0854ec49d29
/PowerBill四川电信专用版本/ibill_source/FTPConfigFrm.cpp
df5ddefb6b5da9a8c947e8a3fe433ee4b9cb8b0c
[]
no_license
sridhar19091986/xmlconvertsql
066344074e932e919a69b818d0038f3d612e6f17
bbb5bbaecbb011420d701005e13efcd2265aa80e
refs/heads/master
2021-01-21T17:45:45.658884
2011-05-30T12:53:29
2011-05-30T12:53:29
42,693,560
0
0
null
null
null
null
GB18030
C++
false
false
8,430
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "FTPConfigFrm.h" #include "MainFrm.h" #include "EditFTPFrm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "RzPanel" #pragma link "RzButton" #pragma link "RzListVw" #pragma resource "*.dfm" TfrmFTPConfig *frmFTPConfig; //--------------------------------------------------------------------------- __fastcall TfrmFTPConfig::TfrmFTPConfig(TComponent* Owner,bool AForSelect) : TForm(Owner) { ForSelect = AForSelect; btnOk->Visible = ForSelect; TListItem * Item; for(int n = 0;n < frmMain->FTPConfig->GetFTPCount();n++) { Item = lvFTPServers->Items->Add(); Item->ImageIndex = 116; Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); FillListItem(Item); } } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::FillListItem(TListItem * Item) { AnsiString FTPName = frmMain->FTPConfig->GetFTPName(Item->Index); Item->SubItems->Strings[0] = FTPName; Item->SubItems->Strings[1] = frmMain->FTPConfig->GetFTPAttributeValue(FTPName,"Server"); Item->SubItems->Strings[2] = frmMain->FTPConfig->GetFTPAttributeValue(FTPName,"Port"); Item->SubItems->Strings[3] = frmMain->FTPConfig->GetFTPAttributeValue(FTPName,"UserName"); Item->SubItems->Strings[4] = frmMain->FTPConfig->GetFTPAttributeValue(FTPName,"Mode"); //Item->SubItems->Strings[5] = frmMain->FTPConfig->GetFTPAttributeValue(FTPName,"TimeOut"); } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::EditFTPConfig(TListItem * Item) { TfrmEditFTP * frmEditFTP = new TfrmEditFTP(this,true); frmEditFTP->OldFTPName = Item->SubItems->Strings[0]; frmEditFTP->txtServerName->Text = Item->SubItems->Strings[0]; frmEditFTP->txtServer->Text = Item->SubItems->Strings[1]; frmEditFTP->txtPort->Text = Item->SubItems->Strings[2]; frmEditFTP->txtUserName->Text = Item->SubItems->Strings[3]; frmEditFTP->txtPassword->Text = frmMain->FTPConfig->GetFTPAttributeValue( Item->SubItems->Strings[0],"Password",true); frmEditFTP->cbxMode->ItemIndex = frmEditFTP->cbxMode->Items->IndexOf(Item->SubItems->Strings[4]); //frmEditFTP->txtTimeOut->Text = Item->SubItems->Strings[5]; if(frmEditFTP->ShowModal() == mrOk) { FillListItem(Item); } delete frmEditFTP; } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::lvFTPServersDblClick(TObject *Sender) { TListItem * Item = lvFTPServers->Selected; if(Item == NULL) return; if(ForSelect) { ModalResult = mrOk; return; } else { EditFTPConfig(Item); } } void __fastcall TfrmFTPConfig::btnSaveClick(TObject *Sender) { SaveChanges(true); } bool __fastcall TfrmFTPConfig::SaveChanges(bool ShowHint) { if(!frmMain->FTPConfig->IsModified()) return true; if(ShowHint && MessageBox(Handle,"您要将所做的修改保存到配置文件吗?","问题",MB_YESNO | MB_ICONQUESTION) == IDNO) return false; if(!frmMain->FTPConfig->SaveChanges()) { MessageBox(Handle,frmMain->FTPConfig->LastErrorMessage.c_str(),"错误",MB_OK | MB_ICONSTOP); return false; } frmMain->FTPConfig->LoadConfig(frmMain->FTPConfig->ConfigFileName); MessageBox(Handle,"FTP服务器配置已保存!","信息",MB_OK | MB_ICONINFORMATION); return true; } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::FormClose(TObject *Sender, TCloseAction &Action) { if(frmMain->FTPConfig->IsModified()) { switch(MessageBox(Handle,"您已经修改了配置文件.是否保存这些修改?","问题",MB_YESNOCANCEL | MB_ICONQUESTION)) { case IDYES: if(!SaveChanges(false)) { Action = caNone; return; } break; case IDNO: frmMain->FTPConfig->Rollback(); break; default: Action = caNone; throw new Exception(""); } } } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::PopupMenu1Popup(TObject *Sender) { menuDelete->Enabled = lvFTPServers->Selected != NULL; menuEdit->Enabled = menuDelete->Enabled; } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::menuDeleteClick(TObject *Sender) { TListItem * Item = lvFTPServers->Selected; if(Item == NULL) return; if(MessageBox(Handle,("您要删除FTP服务器 " + Item->SubItems->Strings[0] + " 吗?").c_str(), "警告",MB_YESNO | MB_ICONWARNING) == IDNO) return; if(frmMain->FTPConfig->DeleteFTPNode(Item->SubItems->Strings[0])) { lvFTPServers->Items->Delete(Item->Index); } } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::menuAddNewClick(TObject *Sender) { TfrmEditFTP * frmEditFTP = new TfrmEditFTP(this,false); if(frmEditFTP->ShowModal() == mrOk) { TListItem * Item = lvFTPServers->Items->Add(); Item->ImageIndex = 116; Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); Item->SubItems->Add(""); FillListItem(Item); } delete frmEditFTP; } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::menuEditClick(TObject *Sender) { TListItem * Item = lvFTPServers->Selected; if(Item == NULL) return; EditFTPConfig(Item); } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::btnOkClick(TObject *Sender) { TListItem * Item = lvFTPServers->Selected; if(Item == NULL) return; ModalResult = mrOk; } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::lvFTPServersDragOver(TObject *Sender, TObject *Source, int X, int Y, TDragState State, bool &Accept) { TListItem * DestItem = lvFTPServers->GetItemAt(X,Y); Accept = DestItem != NULL && DestItem != lvFTPServers->Selected; } //--------------------------------------------------------------------------- void __fastcall TfrmFTPConfig::lvFTPServersDragDrop(TObject *Sender, TObject *Source, int X, int Y) { TListItem * DestItem = lvFTPServers->GetItemAt(X,Y); TListItem * Item = lvFTPServers->Selected; int SourIndex,DestIndex; SourIndex = Item->Index; DestIndex = DestItem->Index; TListItem * NewItem; if(SourIndex < DestIndex) NewItem = lvFTPServers->Items->Insert(DestIndex + 1); else NewItem = lvFTPServers->Items->Insert(DestIndex); NewItem->Assign(Item); _di_IXMLNode SourNode = frmMain->FTPConfig->GetFTPNode(Item->SubItems->Strings[0]); _di_IXMLNode DestNode = frmMain->FTPConfig->GetFTPNode(DestItem->SubItems->Strings[0]); _di_IXMLNode TmpNode = SourNode->CloneNode(true); //frmMain->FTPConfig->RootNode->ChildNodes->Remove(DestNode); //frmMain->FTPConfig->RootNode->ChildNodes->Insert(DestIndex,TmpNode); frmMain->FTPConfig->RootNode->ChildNodes->Remove(SourNode); frmMain->FTPConfig->RootNode->ChildNodes->Insert(DestIndex,TmpNode); lvFTPServers->Items->Delete(Item->Index); /*TListItem * DestItem = lvFTPServers->GetItemAt(X,Y); TListItem * Item = lvFTPServers->Selected; int OldIndex = Item->Index; TListItem * NewItem = lvFTPServers->Items->Insert(DestItem->Index); int NewIndex = NewItem->Index; if(OldIndex < NewIndex) NewIndex -= 1; _di_IXMLNode OldNode = frmMain->FTPConfig->GetFTPNode(Item->SubItems->Strings[0]); _di_IXMLNode NewNode = OldNode->CloneNode(true); frmMain->FTPConfig->RootNode->ChildNodes->Delete(OldIndex); frmMain->FTPConfig->RootNode->ChildNodes->Insert(NewIndex,NewNode); NewItem->Assign(Item); lvFTPServers->Items->Delete(Item->Index);*/ } //---------------------------------------------------------------------------
[ "cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99" ]
[ [ [ 1, 233 ] ] ]
ea74d8df1c02c688ec7fbf4aeb18c4c37039e48f
54319da8732c447b8f196de5e98293083d3acf10
/qt4_src/test/fxeditor/fxInputFace.cpp
165bf710821146e2109e57e87c70a7d7483e05ef
[ "curl" ]
permissive
libfetion/libfetion-gui
6c0ed30f9b31669048347352b292fbe02e5505f3
a5912c7ac301830c2953378e58a4d923bc0a0a8d
refs/heads/master
2021-01-13T02:16:46.031301
2010-09-19T10:42:37
2010-09-19T10:42:37
32,465,618
2
0
null
null
null
null
GB18030
C++
false
false
7,667
cpp
/*************************************************************************** * Copyright (C) 2008 by DDD * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <QLabel> #include <QtGui> #include "fxmsgwindow.h" #include "fxmytabwidget.h" #include "fxInputFace.h" static FACES_INFO _faces_info[] = { {"&gt;:)", MyRect(80, 229, 118, 259), QObject::tr("naughty")}, //淘气的 {"o:)", MyRect(280, 191, 318, 227), QObject::tr("angel")}, //天使 {"*-:)", MyRect(160, 153, 198, 189), QObject::tr("idea")}, //想法 // {":)", MyRect(1, 2, 38, 39)}, {":-d", MyRect(40, 2, 78, 39), QObject::tr("yuk")}, //大笑, {";)", MyRect(80, 2, 118, 39), QObject::tr("blink")}, //眨眼, {":-o", MyRect(120, 2, 158, 39), QObject::tr("surprise")}, //惊讶, {":-p", MyRect(160, 2, 198, 39), QObject::tr("spit_tongue_smile")}, //吐舌笑脸, {"(h)", MyRect(200, 2, 238, 39), QObject::tr("fiery_smile")}, //热烈笑脸,, {":-@", MyRect(240, 2, 278, 39), QObject::tr("Angry")}, //生气 {":(", MyRect(280, 2, 318, 39), QObject::tr("sadness")}, //悲伤, {":'(", MyRect(1, 40, 39, 77), QObject::tr("blubber")}, //哭泣, {":\"&gt;", MyRect(40, 40, 78, 77), QObject::tr("embarrass")}, //尴尬 {"^o)", MyRect(80, 40, 118, 77), QObject::tr("Ironically")}, //讽刺, //{":&amp;", MyRect(120, 40, 158, 77)}, {":&", MyRect(120, 40, 158, 77), QObject::tr("Sick")}, //生病, {"8o|", MyRect(160, 40, 198, 77), QObject::tr("Yaoyaqiechi")}, //咬牙切齿 {"|-)", MyRect(200, 40, 238, 77), QObject::tr("sleepy")}, //困 {":-#", MyRect(240, 40, 278, 77), QObject::tr("Privacy")}, //保密 {"8-)", MyRect(280, 40, 318, 77), QObject::tr("MomentisEyess")}, //转动的眼睛 {"(s)", MyRect(1, 78, 39, 113), QObject::tr("sleepyMoon")}, //沉睡的月亮 {"(st)", MyRect(40, 78, 78, 113), QObject::tr("rain")}, //下雨 {"(o)", MyRect(80, 78, 118, 113), QObject::tr("clock")}, //时钟 {"(l)", MyRect(120, 78, 158, 113), QObject::tr("hearts")}, //红心 {"(u)", MyRect(160, 78, 198, 113), QObject::tr("crackedhearts")}, //破碎的心 {"(@)", MyRect(200, 78, 238, 113), QObject::tr("catfaces")}, //猫脸 {"(&)", MyRect(240, 78, 278, 113), QObject::tr("dogfaces")}, //狗脸 {"(sn)", MyRect(280, 78, 318, 113), QObject::tr("snail")}, //蜗牛 {"(*)",MyRect(1, 115, 39, 151), QObject::tr("star")}, //星星 {"(#)",MyRect(40, 115, 78, 151), QObject::tr("sun")}, //太阳 {"(r)",MyRect(80, 115, 118, 151), QObject::tr("rainbow")}, //彩虹 {"(})",MyRect(120, 115, 158, 151), QObject::tr("leftembrace")}, //左拥抱, {"({)",MyRect(160, 115, 198, 151), QObject::tr("rightembrace")}, //右拥抱, {"(k)",MyRect(200, 115, 238, 151), QObject::tr("lip")}, //红唇 {"(f)", MyRect(240, 115, 278, 151), QObject::tr("rose")}, //红玫瑰 {"(w)", MyRect(280, 115, 318, 151), QObject::tr("emarcidrose")}, //凋谢的玫瑰 {"(g)", MyRect(1, 153, 39, 189), QObject::tr("giftbox")}, //礼品盒 {"(^)", MyRect(40, 153, 78, 189), QObject::tr("Birthdaycake")}, //生日蛋糕 {"-8", MyRect(80, 153, 118, 189), QObject::tr("music")}, //音乐 {"(i)", MyRect(120, 153, 158, 189), QObject::tr("bulb")}, //灯泡, // {"*-:)", MyRect(160, 153, 198, 189)}, {"(c)", MyRect(200, 153, 238, 189), QObject::tr("coffee")}, //咖啡 {"(um)", MyRect(240, 153, 278, 189), QObject::tr("bumbershoot")}, //雨伞 {"b)", MyRect(280, 153, 318, 189), QObject::tr("withsunglass")}, //带着太阳镜 {"(mp)",MyRect(1, 191, 39, 227), QObject::tr("mobiletelephone")}, //手机 {"(co)",MyRect(40, 191, 78, 227), QObject::tr("computer")}, //计算机 {":-|", MyRect(80, 191, 118, 227), QObject::tr("despair")}, //失望 {":-/", MyRect(120, 191, 158, 227), QObject::tr("confused")}, //困惑的 {":-s", MyRect(160, 191, 198, 227), QObject::tr("afraid")}, //担心 {")-|", MyRect(200, 191, 238, 227), QObject::tr("drink")}, //饮料 {"(d)", MyRect(240, 191, 278, 227), QObject::tr("goblet")}, //高脚杯 //{"o:)", MyRect(280, 191, 318, 227)}, {":-?", MyRect(1, 229, 39, 259), QObject::tr("meditation")}, //沉思 {"(y)", MyRect(40, 229, 78, 259), QObject::tr("Praised")}, //太棒了 //{"&gt;:)", MyRect(80, 229, 118, 259)}, {":-b", MyRect(120, 229, 158, 259), QObject::tr("spoony")}, //笨瓜 {":)", MyRect(1, 2, 38, 39) , QObject::tr("smile")}, //微笑 }; bool FxInputFace::getFaces(int x, int y, QString &face, QString &str) { int i; for (i = 0; i < sizeof(_faces_info)/sizeof(_faces_info[0]); i++) if (_faces_info[i].rect.contains (x, y)) { face = _faces_info[i].face; str = _faces_info[i].str; return true; } face = ""; str = ""; return false; } FxInputFace::FxInputFace(QWidget *parent) : QDialog(parent) { msgWind = NULL; } FxInputFace::~FxInputFace() { } void FxInputFace::setMsgWindow(FxMsgWindow *Wind) { msgWind = Wind; // add by iptton. setFocusProxy(Wind); } #if MAC_OS static bool shouldHide = false; #endif void FxInputFace::focusOutEvent ( QFocusEvent * event ) { #if MAC_OS if (shouldHide) { shouldHide = false; hide(); return; } shouldHide = true; #else hide(); #endif } void FxInputFace::mouseReleaseEvent ( QMouseEvent * event ) { #if MAC_OS shouldHide = false; #endif hide(); //releaseMouse(); if (!msgWind) return; FxMyTabWidget *tabWidget = msgWind->tabWidget; if (!tabWidget) return; AccountTab *accountTab = (AccountTab*)(tabWidget->widget(tabWidget->currentIndex())); if (!accountTab) return; /* QString symbol; QString str; QString face = getFaces (event->x(), event->y()); */ QString face; QString str; if (!getFaces (event->x(), event->y(), face, str)) return; /* this will broke the user's edit(because the cursor changed) QString msg = accountTab->msgSend->MsgEdit->toPlainText(); QString newmsg = msg + face; accountTab->msgSend->MsgEdit->setText(newmsg); accountTab->msgSend->MsgEdit->moveCursor(QTextCursor::End); */ // try this and use setFocusProxy instead of setFocus() accountTab->msgSend->MsgEdit->textCursor().insertText(face); } void FxInputFace::mouseMoveEvent(QMouseEvent *event) { QString face; QString str; if (!getFaces (event->x(), event->y(), face, str)) return; QString text = str + " " + face; QToolTip::showText(event->globalPos(), text, this); }
[ "libfetion@3dff0f8e-6350-0410-ad39-8374e07577ec" ]
[ [ [ 1, 207 ] ] ]
2653354b9de0b91cebc3489c92f56cf4f097cae1
30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff
/c/cc.h
05b6173dbbca027db5c8f4869350a90322e9faec
[]
no_license
inspirer/history
ed158ef5c04cdf95270821663820cf613b5c8de0
6df0145cd28477b23748b1b50e4264a67441daae
refs/heads/master
2021-01-01T17:22:46.101365
2011-06-12T00:58:37
2011-06-12T00:58:37
1,882,931
1
0
null
null
null
null
UTF-8
C++
false
false
2,301
h
/* cc.h * * C Compiler project (cc) * Copyright (C) 2002-03 Eugeniy Gryaznov ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef cc_h_included #define cc_h_included #define SUPPORT64 /* * Common headers and types. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <string.h> /* * Place structure is redefinition of lapg_place structure. */ struct Place { int line; }; #define LOC "%i: " // compiler-specific types #ifdef SUPPORT64 typedef signed __int64 llong; typedef unsigned __int64 ullong; #else typedef signed long llong; typedef unsigned long ullong; #endif // target addressing mode typedef unsigned long word; // general types declaration struct type; struct sym; struct node; struct expr; struct Init; struct Namespace; class Compiler; typedef const struct type *Type; typedef const struct sym *Sym; typedef const struct node *Node; typedef struct expr *Expr; #include "types.h" #include "stmt.h" #include "il.h" #include "slab.h" #define ASSERT(x) assert(x) #define TODO() ASSERT(0); class Compiler { private: char b[1025], *l, *end; slab m_perm, m_func; char *identifier( char *token, int *n, int tnID ); void set_backend( Backend *be ); public: type *basic[t_basiccnt]; Namespace *current, global, *func; Backend *be; public: Compiler(); void *allocate( int permanent, int size ); void error( char *r, ... ); int parse(); void fillb(); }; #endif
[ [ [ 1, 106 ] ] ]
694c3d332f73ad7db91f695d41c2fe99f3e45b0b
225746972ca1a832bfd4b15824dbea1823e029cf
/marcc/src/symboltable.cpp
8707e646d8673fea557adef09bdd48a13f4b98bb
[]
no_license
endeav0r/endeavormac
a2d76e525eefb5b176e669403acbc4c96dbd20bd
44a2fa9bb34130558882e23ac6bee68b41da81a5
refs/heads/master
2016-08-11T07:54:01.377822
2011-04-05T14:41:08
2011-04-05T14:41:08
52,758,001
0
0
null
null
null
null
UTF-8
C++
false
false
3,012
cpp
#include "symboltable.hpp" SymbolTable :: SymbolTable () { int i; for (i = 0; i < GENERAL_PURPOSE_REGISTERS; i++) this->registers[i].s_id(i+1); this->previous = NULL; this->next = NULL; this->last = this; this->next_free_offset = 0; } int SymbolTable :: get_free_register () { int i; // first find a register without a symbol for (i = 0; i < GENERAL_PURPOSE_REGISTERS; i++) { if ((this->registers[i].g_free()) && (this->registers[i].has_symbol() == false)) return i+1; } // find any free register for (i = 0; i < GENERAL_PURPOSE_REGISTERS; i++) { if ((this->registers[i].g_free()) && (this->registers[i].has_symbol() == false)) return i+1; } throw Exception("no registers free"); return -1; } void SymbolTable :: use_register (int reg) { if (! this->registers[reg - 1].g_free()) throw Exception("tried to use an already used register"); this->registers[reg - 1].use(); } void SymbolTable :: free_register (int reg) { if (this->registers[reg - 1].g_free()) throw Exception("tried to free already free register"); this->registers[reg - 1].free(); } void SymbolTable :: push () { SymbolTable * next = this; while (next->next != NULL) { next = next->next; } next->next = new SymbolTable(); next->next->previous = next; this->last = next->next; } void SymbolTable :: pop () { SymbolTable * tmp; if (this->last == this) throw Exception("tried to pop top layer of symbol table"); tmp = this->last; this->last = this->last->previous; this->last->next = NULL; delete tmp; } int SymbolTable :: add_symbol (std::string name, bool absolute) { if (! absolute) { this->symbols[name] = Symbol(name); this->symbols[name].s_absolute(false); this->symbols[name].s_offset(this->next_free_offset); this->next_free_offset++; return 1; } return 0; } bool SymbolTable :: symbol_exists (std::string name) { // is it in the last table, IE the stack table? // static variables not implemented yet if (this->last->symbols.count(name) == 1) return true; return false; } int SymbolTable :: g_symbol_offset (std::string name) { return this->symbols[name].g_offset(); } bool SymbolTable :: g_symbol_absolute (std::string name) { return this->symbols[name].g_absolute(); } int SymbolTable :: g_symbol_address (std::string name) { return this->symbols[name].g_address(); } Symbol & SymbolTable :: g_symbol (std::string name) { return this->symbols[name]; } Register * SymbolTable :: g_register_ptr (int reg) { return &(this->registers[reg - 1]); }
[ "[email protected]", "endeavormac@94cf5504-edb0-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 4 ], [ 8, 14 ], [ 50, 95 ] ], [ [ 5, 7 ], [ 15, 49 ], [ 96, 109 ] ] ]
26ec1b349f37509fc819464bffdb9475bd9973f4
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpWorldSnapshotViewer.h
7b306cb286d41d0ea6535745b932df8813ebb7b8
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
2,789
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_UTILITIES2_WORLD_SNAPSHOT_VIEWER_H #define HK_UTILITIES2_WORLD_SNAPSHOT_VIEWER_H #include <Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpWorldViewerBase.h> #include <Common/Base/DebugUtil/StatisticsCollector/Stream/hkStreamStatisticsCollector.h> class hkDebugDisplayHandler; class hkpWorld; class hkListener; /// Sends the memory used by the Worlds to the VDB clients to inspect class hkpWorldSnapshotViewer : public hkpWorldViewerBase { public: enum Command // for serialization { HK_SNAPSHOT = 0xD0, }; HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VDB); /// Creates a hkpWorldSnapshotViewer. static hkProcess* HK_CALL createNative(const hkArray<hkProcessContext*>& contexts); static hkProcess* HK_CALL createPC(const hkArray<hkProcessContext*>& contexts); /// Registers the hkpWorldSnapshotViewer with the hkViewerFactory. static void HK_CALL registerViewer(); /// Gets the tag associated with this viewer type virtual int getProcessTag() { return m_convert? m_tagPC : m_tagNative; } virtual void init(); virtual void step( hkReal frameTimeInMs ); static inline const char* HK_CALL getNameNative() { return "* Grab World Snapshot Native"; } static inline const char* HK_CALL getNamePC() { return "* Grab World Snapshot PC"; } protected: hkpWorldSnapshotViewer(const hkArray<hkProcessContext*>& contexts, bool convertToPC ); virtual ~hkpWorldSnapshotViewer(); protected: bool m_convert; static int m_tagPC; static int m_tagNative; }; #endif // HK_UTILITIES2_WORLD_SNAPSHOT_VIEWER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 75 ] ] ]
9abfe5075642b9c984ef281001aad3bb4a67df8d
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Serialize/Serialize/Xml/hkXmlObjectWriter.h
900f04fa71679e15b60ab3f8dd06ea6d87636a9f
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,972
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_SERIALIZE_XML_OBJECT_WRITER_H #define HK_SERIALIZE_XML_OBJECT_WRITER_H #include <Common/Serialize/Serialize/hkObjectWriter.h> #include <Common/Base/Container/PointerMap/hkPointerMap.h> class hkStreamWriter; class hkClass; /// Writes a single object to an XML stream. class hkXmlObjectWriter : public hkObjectWriter { public: /// Callback for naming pointers. struct NameFromAddress { virtual ~NameFromAddress() { } virtual int nameFromAddress( const void* addr, char* buf, int bufSize ) = 0; }; /// Numbers each pointer sequentially from 1. struct SequentialNameFromAddress : public NameFromAddress { virtual int nameFromAddress( const void* addr, char* buf, int bufSize ); hkPointerMap<const void*, int> m_map; }; /// Create an xml object writer. /// The nameFromAddress object must remain valid for the lifetime /// of this writer. hkXmlObjectWriter(NameFromAddress& nameFromAddress); /// Opens a new element with optional attributes. /// "attributes" is a optional null-terminated array of attribute name value pairs. /// The indentation is increased by one. /// Optionally write a newline before the tag if prefixNewline is true. void beginElement(hkStreamWriter* writer, const char* name, const char*const* attributes=HK_NULL, hkBool prefixNewline=true); /// End an element. Optionally write a newline before the tag if prefixNewline is true. void endElement(hkStreamWriter* writer, const char* name, hkBool prefixNewline=true); /// Convenience wrapper for beginElement, writeObject, endElement. /// "attributes" is a optional null-terminated array of attribute name value pairs. virtual hkResult writeObjectWithElement(hkStreamWriter* writer, const void* data, const hkClass& klass, const char* name, const char*const* attributes=HK_NULL); /// Save object data, using class information klass. /// Note that this writer does not supply relocations, since /// these must be computed at load time on the host. virtual hkResult writeObject(hkStreamWriter* writer, const void* data, const hkClass& klass, hkRelocationInfo& reloc); /// Write a raw binary chunk. virtual hkResult writeRaw(hkStreamWriter* writer, const void* buf, int len ); /// Change the indentation level by delta tabstops. void adjustIndent( int delta ); /// Forwards to m_nameFromAddress. int nameFromAddress( const void* addr, char* buf, int bufSize ) { return m_nameFromAddress.nameFromAddress(addr,buf,bufSize); } public: static hkResult HK_CALL base64write( hkStreamWriter* w, const void* buf, int len ); private: hkInplaceArray<char,16> m_indent; NameFromAddress& m_nameFromAddress; }; #endif //HK_SERIALIZE_XML_OBJECT_WRITER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 92 ] ] ]
ca5d0f8298a2f1f4ef55e6e04c9b12f25c72d756
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Graphics/Bitmaps/Bitmap.cpp
12f3d202e4b02e326bd66cc985770362f46c9f3f
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
7,537
cpp
// Bitmap.cpp // // Copyright (c) 2000-2005 Symbian Software Ltd. All rights reserved. #include "BitmapsGraphicsControl.h" #include <grbmap.mbg> _LIT(KTxtCDrive,"C:"); _LIT(KTxtZDrive,"Z:"); void CBitmapControl::LoadBitmapL(CFbsBitmap* aBitMap, const TDesC& aPathAndFile, TInt aId, TBool aShareIfLoaded) { TParse mbfn; mbfn.Set(aPathAndFile, &KTxtCDrive, NULL); if (!aBitMap->Load(mbfn.FullName(), aId, aShareIfLoaded)) { return; } mbfn.Set(aPathAndFile, &KTxtZDrive, NULL); User::LeaveIfError(aBitMap->Load(mbfn.FullName(), aId, aShareIfLoaded)); return; } // Text printed to the console _LIT(KTxtCase1, "draw piece of bitmap using block transfer"); _LIT(KTxtCase2, "draw bitmap described in twips using DrawBitmap()"); _LIT(KTxtCase3, "draw stretched bitmap"); _LIT(KTxtCase4, "tile rectangle, using bitmap as the brush pattern"); _LIT(KTxtCase5, "tile rectangle, tiling around center of screen"); _LIT(KTxtCase6, "masks: the problem of drawing a bitmap on different backgrounds"); _LIT(KTxtCase7, "masks: using a mask to give a bitmap a transparent background"); // The name of the multi-bitmap file containing the bitmap // and bitmap mask files. _LIT(KMbmName, "\\resource\\apps\\grbmap.mbm"); void CBitmapControl::UpdateModelL() { // set up name for bitmap sharing TBool shareIfLoaded(ETrue); switch (Phase()) { case 0: { // load the bitmap and mask bitmap iBitmap = new (ELeave) CFbsBitmap(); LoadBitmapL(iBitmap, KMbmName, EMbmGrbmapSmiley, shareIfLoaded); iMaskBitmap = new (ELeave) CFbsBitmap(); LoadBitmapL(iMaskBitmap, KMbmName, EMbmGrbmapSmilmask, shareIfLoaded); _LIT(KTxtCase0, "draw bitmap, centered on screen using block transfer"); iGraphObserver->NotifyStatus(KTxtCase0); } break; case 1: { iGraphObserver->NotifyStatus(KTxtCase1); } break; case 2: { iGraphObserver->NotifyStatus(KTxtCase2); } break; case 3: { iGraphObserver->NotifyStatus(KTxtCase3); } break; case 4: { iGraphObserver->NotifyStatus(KTxtCase4); } break; case 5: { iGraphObserver->NotifyStatus(KTxtCase5); } break; case 6: { iGraphObserver->NotifyStatus(KTxtCase6); } break; case 7: { iGraphObserver->NotifyStatus(KTxtCase7); } break; } } void CBitmapControl::Draw(const TRect& /* aRect */) const { // draw surrounding rectangle CWindowGc& gc = SystemGc(); // graphics context we draw to gc.UseFont(iMessageFont); // use the system message font gc.Clear(); // clear the area to be drawn to gc.DrawRect(Rect()); // surrounding rectangle to draw into switch (Phase()) { case 0: { CaseBitBlt(gc); } break; case 1: { CaseBitBltPiece(gc); } break; case 2: { CaseDrawBitmapTopLeft(gc); } break; case 3: { CaseDrawBitmapRect(gc); } break; case 4: { CaseBrushPattern(gc); } break; case 5: { CaseBrushPatternOrigin(gc); } break; case 6: { CaseDiffBackground(gc); } break; case 7: { CaseDiffBackgroundDetailed(gc); } break; default: break; } } TPoint CBitmapControl::DeltaPos(TSize aBmpSize, TSize aCtrlSize) const { // calculate position for top left of bitmap so it is centered TInt xDelta = (aCtrlSize.iWidth - aBmpSize.iWidth) / 2; TInt yDelta = (aCtrlSize.iHeight - aBmpSize.iHeight) / 2; return TPoint(xDelta, yDelta); } void CBitmapControl::CaseBitBlt(CWindowGc &aGc) const { // draw a whole bitmap centered on the screen, // using bitmap block transfer TPoint pos = Position() + DeltaPos(iBitmap->SizeInPixels(), Size()); aGc.BitBlt(pos, iBitmap); } void CBitmapControl::CaseBitBltPiece(CWindowGc& aGc) const { // draw a rectangular piece of a bitmap, centered on the screen, // using bitmap block transfer // calculate bitmap piece, half size from center of source bitmap TSize bmpSize = iBitmap->SizeInPixels(); TSize bmpPieceSize(bmpSize.iWidth * 2 / 3, bmpSize.iHeight * 2 / 3); TPoint pos = Position() + DeltaPos(bmpPieceSize, Size()); TRect bmpPieceRect(TPoint(0, 0), bmpPieceSize); aGc.BitBlt(pos, iBitmap, bmpPieceRect); // using bitmap piece } void CBitmapControl::CaseDrawBitmapTopLeft(CWindowGc& aGc) const { // draw a bitmap to a defined size in twips // in the top left corner the rectangle, // using the GDI DrawBitmap() function TSize bmpSizeInTwips(600, 600); // must set twips size, default (0,0) iBitmap->SetSizeInTwips(bmpSizeInTwips); aGc.DrawBitmap(Position(), iBitmap); } void CBitmapControl::CaseDrawBitmapRect(CWindowGc& aGc) const { // draw a stretched bitmap inside the rectangle, // using the GDI DrawBitmap() function aGc.DrawBitmap(Rect(), iBitmap); } void CBitmapControl::CaseBrushPattern(CWindowGc& aGc) const { // use bitmap as brush pattern, tiling from top left of rectangle // set brush pattern and style to use the bitmap aGc.UseBrushPattern(iBitmap); aGc.SetBrushStyle(CGraphicsContext::EPatternedBrush); aGc.DrawRect(Rect()); aGc.DiscardBrushPattern(); } void CBitmapControl::CaseBrushPatternOrigin(CWindowGc& aGc) const { // use bitmap as brush pattern, tiling around center of screen // set brush pattern and style to use the bitmap' aGc.SetBrushOrigin(Rect().Center()); aGc.UseBrushPattern(iBitmap); aGc.SetBrushStyle(CGraphicsContext::EPatternedBrush); aGc.DrawRect(Rect()); aGc.DiscardBrushPattern(); } void CBitmapControl::CaseDiffBackground(CWindowGc& aGc) const { // bisect screen into two different colourred recsts TSize biSize; biSize.iWidth = Size().iWidth / 2; biSize.iHeight = Size().iHeight; TRect leftRect(Position(), biSize); TRect rightRect((Position() + TPoint(biSize.iWidth, 0)), biSize); aGc.SetBrushColor(KRgbDarkGray); aGc.Clear(leftRect); aGc.SetBrushColor(KRgbBlack); aGc.Clear(rightRect); // center bitmap on left TPoint pos1 = leftRect.iTl + DeltaPos(iBitmap->SizeInPixels(), leftRect.Size()); aGc.BitBlt(pos1, iBitmap); // center bitmap on right TPoint pos2 = rightRect.iTl + DeltaPos(iBitmap->SizeInPixels(), rightRect.Size()); aGc.BitBlt(pos2, iBitmap); } void CBitmapControl::CaseDiffBackgroundDetailed(CWindowGc& aGc) const { // bisect screen into two different colourred recsts TSize biSize; biSize.iWidth = Size().iWidth / 2; biSize.iHeight = Size().iHeight; TRect leftRect((Position() + TPoint(0, 50)), biSize); TRect rightRect(leftRect.iTl + TPoint(biSize.iWidth, 0), biSize); aGc.SetBrushColor(KRgbDarkGray); aGc.Clear(leftRect); aGc.SetBrushColor(KRgbBlack); aGc.Clear(rightRect); TRect bmpRect(TPoint(0, 0), iBitmap->SizeInPixels()); // center bitmap on left TPoint pos1 = leftRect.iTl + DeltaPos(iBitmap->SizeInPixels(), leftRect.Size()); aGc.BitBltMasked(pos1, iBitmap, bmpRect, iMaskBitmap, EFalse); // center bitmap on right TPoint pos2 = rightRect.iTl + DeltaPos(iBitmap->SizeInPixels(), rightRect.Size()); aGc.BitBltMasked(pos2, iBitmap, bmpRect, iMaskBitmap, EFalse); _LIT(KTxtTheBitmap, "The bitmap:"); _LIT(KTxtBitmapMask, "The bitmap's mask:"); aGc.DrawText(KTxtTheBitmap, TPoint(5, 20)); aGc.BitBlt(TPoint(130, 0), iBitmap); aGc.DrawText(KTxtBitmapMask, TPoint(197, 20)); aGc.BitBlt(TPoint(400, 0), iMaskBitmap); }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 293 ] ] ]
15cd6c257807cd78b91bed44b3c17f0217f994d6
b83c990328347a0a2130716fd99788c49c29621e
/include/boost/proto/transform/make.hpp
576c625f5a89dcb0258028cd2c3df4a935b74e2c
[]
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
19,628
hpp
#ifndef BOOST_PP_IS_ITERATING /////////////////////////////////////////////////////////////////////////////// /// \file make.hpp /// Contains definition of the make<> transform. // // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PROTO_TRANSFORM_MAKE_HPP_EAN_12_02_2007 #define BOOST_PROTO_TRANSFORM_MAKE_HPP_EAN_12_02_2007 #include <boost/proto/detail/prefix.hpp> #include <boost/detail/workaround.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/repeat_from_to.hpp> #include <boost/preprocessor/facilities/intercept.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/selection/max.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #include <boost/mpl/aux_/has_type.hpp> #include <boost/mpl/aux_/template_arity.hpp> #include <boost/mpl/aux_/lambda_arity_param.hpp> #include <boost/utility/result_of.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/proto/proto_fwd.hpp> #include <boost/proto/traits.hpp> #include <boost/proto/args.hpp> #include <boost/proto/transform/impl.hpp> #include <boost/proto/detail/as_lvalue.hpp> #include <boost/proto/detail/ignore_unused.hpp> #include <boost/proto/detail/suffix.hpp> namespace boost { namespace proto { namespace detail { template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_PROTO_MAX_ARITY, typename A, void)> struct typelist { typedef void type; }; template<typename T, bool HasType = mpl::aux::has_type<T>::value> struct nested_type { typedef typename T::type type; }; template<typename T> struct nested_type<T, false> { typedef T type; }; template<typename T, typename Args, typename Void = void> struct nested_type_if : nested_type<T> {}; template<typename R, typename Expr, typename State, typename Data , bool IsTransform = is_callable<R>::value > struct make_if_; template<typename R, typename Expr, typename State, typename Data BOOST_MPL_AUX_LAMBDA_ARITY_PARAM(long Arity = mpl::aux::template_arity<R>::value) > struct make_ { typedef R type; typedef void not_applied_; }; template<typename R, typename Expr, typename State, typename Data> struct make_if_<R, Expr, State, Data, false> : make_<R, Expr, State, Data> {}; #if BOOST_WORKAROUND(__GNUC__, == 3) || (__GNUC__ == 4 && __GNUC_MINOR__ == 0) // work around GCC bug template<typename Tag, typename Args, long N, typename Expr, typename State, typename Data> struct make_if_<proto::expr<Tag, Args, N>, Expr, State, Data, false> { typedef proto::expr<Tag, Args, N> type; typedef void not_applied_; }; #endif // TODO could optimize this if R is a transform template<typename R, typename Expr, typename State, typename Data> struct make_if_<R, Expr, State, Data, true> : remove_const<typename remove_reference< typename boost::result_of<R(Expr, State, Data)>::type >::type> {}; template<typename Type, bool IsAggregate = is_aggregate<Type>::value> struct construct_ { typedef Type result_type; Type operator ()() const { return Type(); } #define TMP(Z, N, DATA) \ template<BOOST_PP_ENUM_PARAMS_Z(Z, N, typename A)> \ Type operator ()(BOOST_PP_ENUM_BINARY_PARAMS_Z(Z, N, A, &a)) const \ { \ return Type(BOOST_PP_ENUM_PARAMS_Z(Z, N, a)); \ } BOOST_PP_REPEAT_FROM_TO(1, BOOST_PP_INC(BOOST_PROTO_MAX_ARITY), TMP, ~) #undef TMP }; template<typename Type> struct construct_<Type, true> { typedef Type result_type; Type operator ()() const { return Type(); } #define TMP(Z, N, DATA) \ template<BOOST_PP_ENUM_PARAMS_Z(Z, N, typename A)> \ Type operator ()(BOOST_PP_ENUM_BINARY_PARAMS_Z(Z, N, A, &a)) const \ { \ Type that = {BOOST_PP_ENUM_PARAMS_Z(Z, N, a)}; \ return that; \ } BOOST_PP_REPEAT_FROM_TO(1, BOOST_PP_INC(BOOST_PROTO_MAX_ARITY), TMP, ~) #undef TMP }; #define TMP(Z, N, DATA) \ template<typename Type BOOST_PP_ENUM_TRAILING_PARAMS_Z(Z, N, typename A)> \ Type construct(BOOST_PP_ENUM_BINARY_PARAMS_Z(Z, N, A, &a)) \ { \ return construct_<Type>()(BOOST_PP_ENUM_PARAMS_Z(Z, N, a)); \ } BOOST_PP_REPEAT(BOOST_PROTO_MAX_ARITY, TMP, ~) #undef TMP } /// \brief A PrimitiveTransform which prevents another PrimitiveTransform /// from being applied in an \c ObjectTransform. /// /// When building higher order transforms with <tt>make\<\></tt> or /// <tt>lazy\<\></tt>, you sometimes would like to build types that /// are parameterized with Proto transforms. In such lambda-style /// transforms, Proto will unhelpfully find all nested transforms /// and apply them, even if you don't want them to be applied. Consider /// the following transform, which will replace the \c _ in /// <tt>Bar<_>()</tt> with <tt>proto::terminal\<int\>::type</tt>: /// /// \code /// template<typename T> /// struct Bar /// {}; /// /// struct Foo /// : proto::when<_, Bar<_>() > /// {}; /// /// proto::terminal<int>::type i = {0}; /// /// int main() /// { /// Foo()(i); /// std::cout << typeid(Foo()(i)).name() << std::endl; /// } /// \endcode /// /// If you actually wanted to default-construct an object of type /// <tt>Bar\<_\></tt>, you would have to protect the \c _ to prevent /// it from being applied. You can use <tt>proto::protect\<\></tt> /// as follows: /// /// \code /// // OK: replace anything with Bar<_>() /// struct Foo /// : proto::when<_, Bar<protect<_> >() > /// {}; /// \endcode template<typename PrimitiveTransform> struct protect : transform<protect<PrimitiveTransform> > { template<typename, typename, typename> struct impl { typedef PrimitiveTransform result_type; }; }; /// \brief A PrimitiveTransform which computes a type by evaluating any /// nested transforms and then constructs an object of that type. /// /// The <tt>make\<\></tt> transform checks to see if \c Object is a template. /// If it is, the template type is disassembled to find nested transforms. /// Proto considers the following types to represent transforms: /// /// \li Function types /// \li Function pointer types /// \li Types for which <tt>proto::is_callable\< type \>::::value</tt> is \c true /// /// <tt>make\<T\<X0,X1,...\> \>::::result\<void(Expr, State, Data)\>::::type</tt> /// is evaluated as follows. For each \c X in <tt>X0,X1,...</tt>, do: /// /// \li If \c X is a template like <tt>U\<Y0,Y1,...\></tt>, then let <tt>X'</tt> /// be <tt>make\<U\<Y0,Y1,...\> \>::::result\<void(Expr, State, Data)\>::::type</tt> /// (which evaluates this procedure recursively). Note whether any /// substitutions took place during this operation. /// \li Otherwise, if \c X is a transform, then let <tt>X'</tt> be /// <tt>when\<_, X\>::::result\<void(Expr, State, Data)\>::::type</tt>. /// Note that a substitution took place. /// \li Otherwise, let <tt>X'</tt> be \c X, and note that no substitution /// took place. /// \li If any substitutions took place in any of the above steps and /// <tt>T\<X0',X1',...\></tt> has a nested <tt>::type</tt> typedef, /// the result type is <tt>T\<X0',X1',...\>::::type</tt>. /// \li Otherwise, the result type is <tt>T\<X0',X1',...\></tt>. /// /// Note that <tt>when\<\></tt> is implemented in terms of <tt>call\<\></tt> /// and <tt>make\<\></tt>, so the above procedure is evaluated recursively. template<typename Object> struct make : transform<make<Object> > { template<typename Expr, typename State, typename Data> struct impl : transform_impl<Expr, State, Data> { typedef typename detail::make_if_<Object, Expr, State, Data>::type result_type; /// \return <tt>result_type()</tt> result_type operator ()( typename impl::expr_param , typename impl::state_param , typename impl::data_param ) const { return result_type(); } }; }; #define BOOST_PP_ITERATION_PARAMS_1 (3, (0, BOOST_PROTO_MAX_ARITY, <boost/proto/transform/make.hpp>)) #include BOOST_PP_ITERATE() /// INTERNAL ONLY /// template<typename Object> struct is_callable<make<Object> > : mpl::true_ {}; /// INTERNAL ONLY /// template<typename PrimitiveTransform> struct is_callable<protect<PrimitiveTransform> > : mpl::true_ {}; }} #endif #else #define N BOOST_PP_ITERATION() namespace detail { #if N > 0 template<typename T BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)> struct nested_type_if< T , typelist<BOOST_PP_ENUM_PARAMS(N, A)> , typename typelist< BOOST_PP_ENUM_BINARY_PARAMS(N, typename A, ::not_applied_ BOOST_PP_INTERCEPT) >::type > { typedef T type; typedef void not_applied_; }; #define TMP0(Z, M, DATA) make_if_<BOOST_PP_CAT(A, M), Expr, State, Data> #define TMP1(Z, M, DATA) typename TMP0(Z, M, DATA) ::type template< template<BOOST_PP_ENUM_PARAMS(N, typename BOOST_PP_INTERCEPT)> class R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A) , typename Expr, typename State, typename Data > struct make_<R<BOOST_PP_ENUM_PARAMS(N, A)>, Expr, State, Data BOOST_MPL_AUX_LAMBDA_ARITY_PARAM(N) > : nested_type_if< R<BOOST_PP_ENUM(N, TMP1, ~)> , typelist<BOOST_PP_ENUM(N, TMP0, ~) > > {}; template< template<BOOST_PP_ENUM_PARAMS(N, typename BOOST_PP_INTERCEPT)> class R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A) , typename Expr, typename State, typename Data > struct make_<noinvoke<R<BOOST_PP_ENUM_PARAMS(N, A)> >, Expr, State, Data BOOST_MPL_AUX_LAMBDA_ARITY_PARAM(N) > { typedef R<BOOST_PP_ENUM(N, TMP1, ~)> type; }; #undef TMP0 #undef TMP1 #endif template< typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A) , typename Expr, typename State, typename Data > struct make_if_<R(BOOST_PP_ENUM_PARAMS(N, A)), Expr, State, Data, false> { typedef typename remove_const< typename remove_reference< typename when<_, R(BOOST_PP_ENUM_PARAMS(N, A))> ::template impl<Expr, State, Data>::result_type >::type >::type type; }; template< typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A) , typename Expr, typename State, typename Data > struct make_if_<R(*)(BOOST_PP_ENUM_PARAMS(N, A)), Expr, State, Data, false> { typedef typename remove_const< typename remove_reference< typename when<_, R(BOOST_PP_ENUM_PARAMS(N, A))> ::template impl<Expr, State, Data>::result_type >::type >::type type; }; template<typename T, typename A> struct construct_<proto::expr<T, A, N>, true> { typedef proto::expr<T, A, N> result_type; template<BOOST_PP_ENUM_PARAMS(BOOST_PP_MAX(N, 1), typename A)> result_type operator ()(BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_MAX(N, 1), A, &a)) const { return result_type::make(BOOST_PP_ENUM_PARAMS(BOOST_PP_MAX(N, 1), a)); } }; } /// \brief A PrimitiveTransform which computes a type by evaluating any /// nested transforms and then constructs an object of that type with the /// current expression, state and data, transformed according /// to \c A0 through \c AN. template<typename Object BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)> struct make<Object(BOOST_PP_ENUM_PARAMS(N, A))> : transform<make<Object(BOOST_PP_ENUM_PARAMS(N, A))> > { template<typename Expr, typename State, typename Data> struct impl : transform_impl<Expr, State, Data> { /// \brief <tt>make\<Object\>::::result\<void(Expr, State, Data)\>::::type</tt> typedef typename detail::make_if_<Object, Expr, State, Data>::type result_type; //typedef typename detail::make_<Object, Expr, State, Data>::type result_type; /// Let \c ax be <tt>when\<_, Ax\>()(e, s, d)</tt> /// for each \c x in <tt>[0,N]</tt>. /// Let \c T be <tt>result\<void(Expr, State, Data)\>::::type</tt>. /// Return <tt>T(a0, a1,... aN)</tt>. /// /// \param e The current expression /// \param s The current state /// \param d An arbitrary data result_type operator ()( typename impl::expr_param e , typename impl::state_param s , typename impl::data_param d ) const { proto::detail::ignore_unused(e); proto::detail::ignore_unused(s); proto::detail::ignore_unused(d); return detail::construct<result_type>( #define TMP(Z, M, DATA) \ detail::as_lvalue( \ typename when<_, BOOST_PP_CAT(A, M)> \ ::template impl<Expr, State, Data>()(e, s, d) \ ) BOOST_PP_ENUM(N, TMP, DATA) #undef TMP ); } }; }; #if BOOST_WORKAROUND(__GNUC__, == 3) || (__GNUC__ == 4 && __GNUC_MINOR__ == 0) // work around GCC bug template<typename Tag, typename Args, long Arity BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)> struct make<proto::expr<Tag, Args, Arity>(BOOST_PP_ENUM_PARAMS(N, A))> : transform<make<proto::expr<Tag, Args, Arity>(BOOST_PP_ENUM_PARAMS(N, A))> > { template<typename Expr, typename State, typename Data> struct impl : transform_impl<Expr, State, Data> { typedef proto::expr<Tag, Args, Arity> result_type; result_type operator ()( typename impl::expr_param e , typename impl::state_param s , typename impl::data_param d ) const { return proto::expr<Tag, Args, Arity>::make( #define TMP(Z, M, DATA) \ detail::as_lvalue( \ typename when<_, BOOST_PP_CAT(A, M)> \ ::template impl<Expr, State, Data>()(e, s, d) \ ) BOOST_PP_ENUM(N, TMP, DATA) #undef TMP ); } }; }; #endif #undef N #endif
[ [ [ 1, 453 ] ] ]
946e0f103bd1ca94054b93ceb081b6f3de81b035
8de934041a2416f97542d3a30defd31545485b65
/cpp/TX_232.cpp
96e5dc487a5a87c32e245d30ca4cdb87afb60a0f
[]
no_license
deccico/lib
0b93aea15d97c890dd9d22787deedc4ef1b392b9
073e21b7b6a4d5423b0ea05fa4a58b32bfcf2c48
refs/heads/master
2023-07-28T04:56:33.466613
2008-03-09T23:07:21
2008-03-09T23:07:21
403,967,299
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,547
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "TX_232.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- //transmite el caracter hasta que se vacie en el buffer segun //condiciones de transmision //pre HANDLE (puerto serie) y caracter valido //post caracter transmitido en el puerto => return 0; o error => return < 0 int __fastcall T232::mTransmitir(HANDLE hhand, int ncaracter) { int ntries=SEND; //nro de intentos de transmisión del caracter .INI int nresult=0; //resultado de la operacion de transmision AnsiString sError; //reemplazar por un label que indique estado de conexión if (!hhand) //chequea conexión al puerto { Beep(); ShowMessage("Error opening serial port"); return -1; } while ( (nresult == 0) && (ntries != 0) ) {ntries--; nresult=TransmitCommChar(hhand, ncaracter); if(!TimerTx->Enabled) TimerTx->Enabled=true; } if (ntries==0) sError = "Time Out"; if (nresult == 0) sError=sError+" Byte not transmited"; if (ntries==0 || nresult == 0) {Beep(); ShowMessage(sError); return -2; } return 0; //funcion terminada coorectamente } //---------------------------------------------------------------------------
[ [ [ 1, 47 ] ] ]
698e46ee1ffe99e3873c0424ea4dbbdfdc701c0a
3449de09f841146a804930f2a51ccafbc4afa804
/C++/MpegMux/system/SystemHeader.cpp
a63c31de9f07e4898655174fabe1fa6fc242b487
[]
no_license
davies/daviescode
0c244f4aebee1eb909ec3de0e4e77db3a5bbacee
bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd
refs/heads/master
2020-06-04T23:32:27.360979
2007-08-19T06:31:49
2007-08-19T06:31:49
32,641,672
1
1
null
null
null
null
GB18030
C++
false
false
2,814
cpp
#include "systemHeader.h" #pragma warning(disable:4800) /* * System Header */ SystemHeader::SystemHeader() { rate_bound = 0; audio_bound = 0; video_bound = 0; system_audio_lock_flag = true; system_video_lock_flag = true; fixed_flag = false; CSPS_flag = false; header_length = 6; //最少的字节数 stream_count = 0; for( int i=0;i<STREAM_COUNT;i++){ stream_id[i] = 0; PSTD_buffer_bound_scale[i] = 0; PSTD_buffer_size_bound[i] = 0; } } bool SystemHeader::parse(BitStream &bs) { if ( bs.getbits(32) != SYSTEM_HEADER_START_CODE ) { return false; } header_length = bs.getbits(16); bs.get1bit(); rate_bound = bs.getbits(22); bs.get1bit(); audio_bound = bs.getbits(6); fixed_flag = bs.get1bit(); CSPS_flag = bs.get1bit(); system_audio_lock_flag = bs.get1bit(); system_video_lock_flag = bs.get1bit(); bs.get1bit(); video_bound = bs.getbits(5); bs.getbits(8); stream_count = 0; while ( bs.nextbits(1) == 1) { stream_id[stream_count] = bs.getbits(8); bs.getbits(2); PSTD_buffer_bound_scale[stream_count] = bs.get1bit(); PSTD_buffer_size_bound[stream_count] = bs.getbits(13); stream_count ++; } return true; } bool SystemHeader::addStreamInfo(unsigned char _stream_id, unsigned char _PSTD_buffer_bound_scale, unsigned short _PSTD_buffer_size_bound) { stream_id[stream_count] = _stream_id; PSTD_buffer_bound_scale[stream_count] = _PSTD_buffer_bound_scale; PSTD_buffer_size_bound[stream_count] = _PSTD_buffer_size_bound; stream_count ++; header_length += 3; if( _stream_id >= AUDIO_STREAM_0 && _stream_id <= AUDIO_STREAM_1F){ audio_bound ++; } if ( _stream_id >= VIDEO_STREAM_0 && _stream_id <= VIDEO_STREAM_F ) { video_bound ++; } return true; } unsigned int SystemHeader::getVideoBufferBound() { for(int i=0;i<stream_count;i++){ if( stream_id[i] == 0xB9 || stream_id[i] >= VIDEO_STREAM_0 && stream_id[i] <= VIDEO_STREAM_F){ return PSTD_buffer_size_bound[i]; } } return 0; } void SystemHeader::setRateBound(unsigned int _rate_bound) { rate_bound = _rate_bound; } int SystemHeader::length() { return header_length + 4 +2; } bool SystemHeader::encode(BitStream &bs) { bs.setbits(SYSTEM_HEADER_START_CODE,32); bs.setbits(header_length,16); bs.set1bit(); bs.setbits(rate_bound,22); bs.set1bit(); bs.setbits(audio_bound,6); bs.set1bit(fixed_flag); bs.set1bit(CSPS_flag); bs.set1bit(system_audio_lock_flag); bs.set1bit(system_video_lock_flag); bs.set1bit(); bs.setbits(video_bound,5); bs.setbits(0xff,8); for(int i=0;i< stream_count;i++){ bs.setbits(stream_id[i],8); bs.setbits(3,2); bs.set1bit(PSTD_buffer_bound_scale[i]); bs.setbits(PSTD_buffer_size_bound[i],13); } return true; }
[ "davies.liu@32811f3b-991a-0410-9d68-c977761b5317" ]
[ [ [ 1, 124 ] ] ]
18a786f84e8dc6d03db7ef230661df487f9a0192
df070aa6eb5225412ebf0c3916b41449edfa16ac
/AVS_Transcoder_SDK/kernel/video/tavs/avs_enc/src/slice.cpp
a49f5886aa4324bcf1f3a368602f774456c27ad4
[]
no_license
numericalBoy/avs-transcoder
659b584cc5bbc4598a3ec9beb6e28801d3d33f8d
56a3238b34ec4e0bf3a810cedc31284ac65361c5
refs/heads/master
2020-04-28T21:08:55.048442
2010-03-10T13:28:18
2010-03-10T13:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,073
cpp
/* ***************************************************************************** * COPYRIGHT AND WARRANTY INFORMATION * * Copyright 2003, Advanced Audio Video Coding Standard, Part II * * DISCLAIMER OF WARRANTY * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations under * the License. * * THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY. * The AVS Working Group doesn't represent or warrant that the programs * furnished here under are free of infringement of any third-party patents. * Commercial implementations of AVS, including shareware, may be * subject to royalty fees to patent holders. Information regarding * the AVS patent policy for standardization procedure is available at * AVS Web site http://www.avs.org.cn. Patent Licensing is outside * of AVS Working Group. * * THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY. ************************************************************************ */ /* ************************************************************************************* * File name: * Function: * ************************************************************************************* */ #include <string.h> #include <math.h> #include <time.h> #include <sys/timeb.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "global.h" void c_avs_enc:: stuffing_byte(int_32_t n) { int_32_t i; Bitstream *currStream; currStream = currBitStream; for(i=0; i<n; i++) { currStream->streamBuffer[currStream->byte_pos++] = 0x80; currStream->bits_to_go = 8; currStream->byte_buf = 0; } } int_32_t c_avs_enc:: start_slice() { Bitstream *currStream; currStream = currBitStream; if (currStream->bits_to_go !=8 ) { currStream->byte_buf <<= currStream->bits_to_go; currStream->byte_buf |= ( 1 << (currStream->bits_to_go - 1) ); currStream->streamBuffer[currStream->byte_pos++] = currStream->byte_buf; currStream->bits_to_go = 8; currStream->byte_buf = 0; } else { currStream->streamBuffer[currStream->byte_pos++] = 0x80; currStream->bits_to_go = 8; currStream->byte_buf = 0; } return 0; } /* ************************************************************************* * Function:This function terminates a picture * Input: * Output: * Return: 0 if OK, \n 1 in case of error * Attention: ************************************************************************* */ int_32_t c_avs_enc::terminate_picture() { Bitstream *currStream; currStream = currBitStream; currStream->byte_buf <<= currStream->bits_to_go; currStream->byte_buf |= (1 << (currStream->bits_to_go - 1) ); currStream->streamBuffer[currStream->byte_pos++] = currStream->byte_buf; currStream->bits_to_go = 8; currStream->byte_buf = 0; return 0; } void c_avs_enc:: picture_data( ) { myboolean end_of_picture = myfalse; int_32_t CurrentMbNumber=0; int_32_t MBRowSize = img->img_width_in_mb; int_32_t slice_nr = 0; int_32_t slice_qp = img->qp; int_32_t len, i; //init the intra pred mode for(i=0; i<img->width/B8_SIZE+100; i++) { memset(img->ipredmode[i], -1, (img->height/B8_SIZE+100)*sizeof(int_32_t)); } for(i=0; i<img->total_number_mb; i++) { img->mb_data[i].slice_nr = -1; } if (input->rdopt) { switch(img->type) { case INTRA_IMG: encode_one_macroblock = &c_avs_enc::encode_one_intra_macroblock_rdo; break; case INTER_IMG: encode_one_macroblock = &c_avs_enc::encode_one_inter_macroblock_rdo; break; case B_IMG: encode_one_macroblock = &c_avs_enc::encode_one_b_frame_macroblock_rdo; break; } } else { // xzhao //img->type=INTRA_IMG; switch(img->type) { case INTRA_IMG: encode_one_macroblock = &c_avs_enc::encode_one_intra_macroblock_not_rdo; break; case INTER_IMG: encode_one_macroblock = &c_avs_enc::encode_one_inter_macroblock_not_rdo; break; case B_IMG: encode_one_macroblock = &c_avs_enc::encode_one_b_frame_macroblock_not_rdo; break; } } while (end_of_picture == myfalse) // loop over macroblocks { set_MB_parameters(CurrentMbNumber); if (input->slice_row_nr && (img->current_mb_nr ==0 ||(img->current_mb_nr>0 && img->mb_data[img->current_mb_nr].slice_nr != img->mb_data[img->current_mb_nr-1].slice_nr))) { #ifdef _ME_FOR_RATE_CONTROL_ if (glb_me_for_rate_control_flag) { start_slice (); } #else start_slice (); #endif img->current_slice_qp = img->qp; img->current_slice_start_mb = img->current_mb_nr; len = SliceHeader(slice_nr, slice_qp); img->current_slice_nr = slice_nr; stat->bit_slice += len; slice_nr++; } start_macroblock(); (this->*encode_one_macroblock)(); write_one_macroblock(1); terminate_macroblock (&end_of_picture); proceed2nextMacroblock (); CurrentMbNumber++; } terminate_picture (); DeblockFrame (img, imgY, imgUV); } void c_avs_enc:: top_field(Picture *pic) { myboolean end_of_picture = myfalse; int_32_t CurrentMbNumber=0; int_32_t MBRowSize = img->width / MB_BLOCK_SIZE; int_32_t slice_nr =0; int_32_t slice_qp = img->qp; int_32_t len; img->top_bot = 0; // Yulj 2004.07.20 while (end_of_picture == myfalse) // loop over macroblocks { set_MB_parameters (CurrentMbNumber); if (input->slice_row_nr && (img->current_mb_nr ==0 ||(img->current_mb_nr>0 && img->mb_data[img->current_mb_nr].slice_nr != img->mb_data[img->current_mb_nr-1].slice_nr))) { // slice header start jlzheng 7.1 start_slice (); img->current_slice_qp = img->qp; img->current_slice_start_mb = img->current_mb_nr; len = SliceHeader(slice_nr, slice_qp); stat->bit_slice += len; slice_nr++; // slice header end } img->current_mb_nr_fld = img->current_mb_nr; start_macroblock (); (this->*encode_one_macroblock) (); write_one_macroblock (1); terminate_macroblock (&end_of_picture); proceed2nextMacroblock (); CurrentMbNumber++; } if(!input->loop_filter_disable) DeblockFrame (img, imgY, imgUV); //rate control pic->bits_per_picture = 8 * (currBitStream->byte_pos); } void c_avs_enc:: bot_field(Picture *pic) { myboolean end_of_picture = myfalse; int_32_t CurrentMbNumber=0; int_32_t MBRowSize = img->width / MB_BLOCK_SIZE; int_32_t slice_nr =0; int_32_t slice_qp = img->qp; int_32_t len; img->top_bot = 1; //Yulj 2004.07.20 while (end_of_picture == myfalse) // loop over macroblocks { set_MB_parameters (CurrentMbNumber); if (input->slice_row_nr && (img->current_mb_nr ==0 ||(img->current_mb_nr>0 && img->mb_data[img->current_mb_nr].slice_nr != img->mb_data[img->current_mb_nr-1].slice_nr))) { // slice header start jlzheng 7.11 start_slice (); img->current_slice_qp = img->qp; img->current_slice_start_mb = img->current_mb_nr; len = SliceHeader(slice_nr, slice_qp); stat->bit_slice += len; slice_nr++; // slice header end } img->current_mb_nr_fld = img->current_mb_nr+img->total_number_mb; start_macroblock (); (this->*encode_one_macroblock) (); write_one_macroblock (1); terminate_macroblock (&end_of_picture); proceed2nextMacroblock (); CurrentMbNumber++; } terminate_picture (); if(!input->loop_filter_disable) DeblockFrame (img, imgY, imgUV); pic->bits_per_picture = 8 * (currBitStream->byte_pos); } void c_avs_enc::store_field_MV () { int_32_t i, j; if (img->type != B_IMG) //all I- and P-frames { if (!img->picture_structure) { for (i = 0; i < img->width / 8 + 4; i++) { for (j = 0; j < img->height / 16; j++) { tmp_mv_frm[0][2 * j][i] = tmp_mv_frm[0][2 * j + 1][i] = tmp_mv_top[0][j][i]; tmp_mv_frm[0][2 * j][i] = tmp_mv_frm[0][2 * j + 1][i] = tmp_mv_top[0][j][i]; // ?? tmp_mv_frm[1][2 * j][i] = tmp_mv_frm[1][2 * j + 1][i] = tmp_mv_top[1][j][i] * 2; tmp_mv_frm[1][2 * j][i] = tmp_mv_frm[1][2 * j + 1][i] = tmp_mv_top[1][j][i] * 2; // ?? if (refFrArr_top[j][i] == -1) { refFrArr_frm[2 * j][i] = refFrArr_frm[2 * j + 1][i] = -1; } else { refFrArr_frm[2 * j][i] = refFrArr_frm[2 * j + 1][i] = (int_32_t) (refFrArr_top[j][i] / 2); } } } } else { for (i = 0; i < img->width / 8 + 4; i++) { for (j = 0; j < img->height / 16; j++) { tmp_mv_top[0][j][i] = tmp_mv_bot[0][j][i] = (int_32_t) (tmp_mv_frm[0][2 * j][i]); tmp_mv_top[1][j][i] = tmp_mv_bot[1][j][i] = (int_32_t) ((tmp_mv_frm[1][2 * j][i]) / 2); if (refFrArr_frm[2 * j][i] == -1) { refFrArr_top[j][i] = refFrArr_bot[j][i] = -1; } else { refFrArr_top[j][i] = refFrArr_bot[j][i] = refFrArr_frm[2 * j][i] * 2; } } } } } } /* ************************************************************************* * Function: allocates the memory for the coded picture data * Input: * Output: * Return: * Attention: ************************************************************************* */ void c_avs_enc:: AllocateBitstream() { const int_32_t buffer_size = (bytes_y << 2); if ((currBitStream = (Bitstream *) calloc(1, sizeof(Bitstream))) == NULL) no_mem_exit ("malloc_slice: Bitstream"); if ((currBitStream->streamBuffer = (byte *) calloc(buffer_size, sizeof(byte))) == NULL) no_mem_exit ("malloc_slice: StreamBuffer"); currBitStream->bits_to_go = 8; } /* ************************************************************************* * Function:free the allocated memory for the coded picture data * Input: * Output: * Return: ************************************************************************* */ void c_avs_enc:: FreeBitstream() { const int_32_t buffer_size = (img->width * img->height * 4); if (currBitStream->streamBuffer) free(currBitStream->streamBuffer); if (currBitStream) free(currBitStream); }
[ "zhihang.wang@6c8d3a4c-d4d5-11dd-b6b4-918b84bbd919" ]
[ [ [ 1, 376 ] ] ]
a352db052a370ff817abf83bd1030b56909de0fe
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/dial/dialgadgetconfiguration.h
609033e18d2b42ddbefeaf5d70e5c4ec34c5135b
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,971
h
/** ****************************************************************************** * * @file dialgadgetconfiguration.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup DialPlugin Dial Plugin * @{ * @brief Plots flight information rotary style dials *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef DIALGADGETCONFIGURATION_H #define DIALGADGETCONFIGURATION_H #include <coreplugin/iuavgadgetconfiguration.h> using namespace Core; /* Despite its name, this is actually a generic analog dial supporting up to two rotating "needle" indicators. */ class DialGadgetConfiguration : public IUAVGadgetConfiguration { Q_OBJECT public: explicit DialGadgetConfiguration(QString classId, QSettings* qSettings = 0, QObject *parent = 0); //set dial configuration functions void setDialFile(QString dialFile){m_defaultDial=dialFile;} void setDialBackgroundID(QString elementID) { dialBackgroundID = elementID;} void setDialForegroundID(QString elementID) { dialForegroundID = elementID;} void setDialNeedleID1(QString elementID) { dialNeedleID1 = elementID;} void setDialNeedleID2(QString elementID) { dialNeedleID2 = elementID;} void setDialNeedleID3(QString elementID) { dialNeedleID3 = elementID;} void setN1Min(double val) { needle1MinValue = val;} void setN2Min(double val) { needle2MinValue = val;} void setN3Min(double val) { needle3MinValue = val;} void setN1Max(double val) { needle1MaxValue = val;} void setN2Max(double val) { needle2MaxValue = val;} void setN3Max(double val) { needle3MaxValue = val;} void setN1Factor(double val) { needle1Factor = val;} void setN2Factor(double val) { needle2Factor = val;} void setN3Factor(double val) { needle3Factor = val;} void setN1DataObject(QString text) {needle1DataObject = text; } void setN2DataObject(QString text){ needle2DataObject = text; } void setN3DataObject(QString text){ needle3DataObject = text; } void setN1ObjField(QString text) { needle1ObjectField = text; } void setN2ObjField(QString text) { needle2ObjectField = text; } void setN3ObjField(QString text) { needle3ObjectField = text; } void setN1Move( QString move) { needle1Move = move; } void setN2Move( QString move) { needle2Move = move; } void setN3Move( QString move) { needle3Move = move; } void setFont(QString text) { font = text; } //get dial configuration functions QString dialFile() {return m_defaultDial;} QString dialBackground() {return dialBackgroundID;} QString dialForeground() {return dialForegroundID;} QString dialNeedle1() {return dialNeedleID1;} QString dialNeedle2() {return dialNeedleID2;} QString dialNeedle3() {return dialNeedleID3;} double getN1Min() { return needle1MinValue;} double getN2Min() { return needle2MinValue;} double getN3Min() { return needle3MinValue;} double getN1Max() { return needle1MaxValue;} double getN2Max() { return needle2MaxValue;} double getN3Max() { return needle3MaxValue;} double getN1Factor() { return needle1Factor;} double getN2Factor() { return needle2Factor;} double getN3Factor() { return needle3Factor;} QString getN1DataObject() { return needle1DataObject; } QString getN2DataObject() { return needle2DataObject; } QString getN3DataObject() { return needle3DataObject; } QString getN1ObjField() { return needle1ObjectField; } QString getN2ObjField() { return needle2ObjectField; } QString getN3ObjField() { return needle3ObjectField; } QString getN1Move() { return needle1Move; } QString getN2Move() { return needle2Move; } QString getN3Move() { return needle3Move; } QString getFont() { return font;} void saveConfig(QSettings* settings) const; IUAVGadgetConfiguration *clone(); private: QString m_defaultDial; // The name of the dial's SVG source file QString dialBackgroundID; // SVG elementID of the background QString dialForegroundID; // ... of the foreground QString dialNeedleID1; // ... and the first needle QString dialNeedleID2; // ... and the second QString dialNeedleID3; // ... and the third // Note: MinValue not used at the moment! double needle1MinValue; // Value corresponding to a 0 degree angle; double needle1MaxValue; // Value corresponding to a 360 degree angle; double needle2MinValue; double needle2MaxValue; double needle3MinValue; double needle3MaxValue; double needle1Factor; double needle2Factor; double needle3Factor; // The font used for the dial QString font; QString needle1DataObject; QString needle1ObjectField; QString needle2DataObject; QString needle2ObjectField; QString needle3DataObject; QString needle3ObjectField; // How the two dials move: QString needle1Move; QString needle2Move; QString needle3Move; }; #endif // DIALGADGETCONFIGURATION_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 139 ] ] ]
76f84f8b29a3aa03c7808074ecc2a912510ff738
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Source/Nuclex/Video/TextureCache.cpp
047dd292ebe35f7c554160883937dedfcc47077a
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
12,917
cpp
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## TextureCache.cpp - Texture cache  // // ### # # ###  // // # ### # ### Caches images and smaller textures onto intermediary  // // # ## # # ## ## textures to reduce temporary objects and texture switching  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #include "Nuclex/Video/TextureCache.h" #include "ScopeGuard/ScopeGuard.h" using namespace Nuclex; using namespace Nuclex::Video; // ############################################################################################# // // # Nuclex::Video::TextureCache::TextureCache() Constructor # // // ############################################################################################# // /** Initializes a texture cache. The texture cache will immediately create its first cache texture, thus taking up some video memory @param spVideoDevice Video device for which the cache is intended */ TextureCache::TextureCache(const shared_ptr<VideoDevice> &spVideoDevice) : m_spVideoDevice(spVideoDevice), m_Resolution(spVideoDevice->getMaxTextureSize()) { // Calculate the optimal cache texture size for the chosen device if(spVideoDevice->getVideoMemorySize() < 64) m_Resolution = Point2<size_t>( std::min<size_t>(m_Resolution.X, 512), std::min<size_t>(m_Resolution.Y, 512) ); // Max of 1 MB per texture else if(spVideoDevice->getVideoMemorySize() < 256) m_Resolution = Point2<size_t>( std::min<size_t>(m_Resolution.X, 1024), std::min<size_t>(m_Resolution.Y, 1024) ); // Max of 4 MB per texture else m_Resolution = Point2<size_t>( std::min<size_t>(m_Resolution.X, 2048), std::min<size_t>(m_Resolution.Y, 2048) ); // Max of 16 MB per texture // Create the first shared texture here - saves us an additional check when caching appendSharedTexture(); } // ############################################################################################# // // # Nuclex::Video::TextureCache::cache() # // // ############################################################################################# // /** Caches a texture. If the texture is larger than a quarter of the cache's texture resolution, cache returns an uncached. @param spSurface Surface to be cached @return A cache slot specifying which texture to use and the location of the cached surface on that texture */ TextureCache::CacheSlot TextureCache::cache(const shared_ptr<Texture> &spTexture) { // Look for the texture in the cache CacheEntryMap::iterator CacheEntryIt = m_CacheEntries.find(spTexture->getUniqueID()); if(CacheEntryIt == m_CacheEntries.end()) { // Textures larger than one forth of the cache are just passed through if((spTexture->getSize().X > m_Resolution.X / 2) || (spTexture->getSize().Y > m_Resolution.Y / 2)) return CacheSlot(spTexture, Box2<float>(0,0, 1,1)); // Everything else gets placed in the cache else CacheEntryIt = addToCache(spTexture); } // Return a valid cache slot return CacheSlot(CacheEntryIt->second.spCacheTexture, CacheEntryIt->second.Location); } // ############################################################################################# // // # Nuclex::Video::TextureCache::cache() # // // ############################################################################################# // /** Caches a surface @param spSurface Surface to be cached @return A cache slot specifying which texture to use and the location of the cached surface on that texture */ TextureCache::CacheSlot TextureCache::cache( Cacheable::CacheID ID, const Point2<size_t> Size, UpdateCacheSlot UpdateCallback ) { // Look for the object in the cache CacheEntryMap::iterator CacheEntryIt = m_CacheEntries.find(ID); if(CacheEntryIt == m_CacheEntries.end()) { // Textures larger than one forth of the cache are just passed through if((Size.X > m_Resolution.X) || (Size.Y > m_Resolution.Y)) { throw FailedException( "Nuclex::Video::TextureCache::cache()", "Object is too large to fit in the cache" ); // Everything else gets placed in the cache } else { // Find a free location for the surface within the current cache texture Point2<size_t> Location = m_spCurrentTexture->Packer.placeRectangle(Size); if(Location == m_Resolution) { // If it doesn't fit anymore, try using a new cache texture appendSharedTexture(); Location = m_spCurrentTexture->Packer.placeRectangle(Size); } { Surface::LockInfo LockedSurface = m_spCurrentTexture->spTexture->lock( Surface::LM_WRITE, Box2<long>(Location, Location + Size) ); ScopeGuard Unlock_Dest = ::MakeObjGuard( *m_spCurrentTexture->spTexture.get(), &Surface::unlock ); UpdateCallback(LockedSurface); } // Add the cache entry into the internet list and return its the iterator CacheEntryIt = m_CacheEntries.insert(CacheEntryMap::value_type( ID, CacheEntry( shared_ptr<Surface>(), m_spCurrentTexture->spTexture, Box2<float>( Point2<float>(Location, StaticCastTag()) / Point2<float>(m_Resolution, StaticCastTag()), Point2<float>(Location + Size, StaticCastTag()) / Point2<float>(m_Resolution, StaticCastTag()) ) ) )).first; } } // Return a valid cache slot return CacheSlot(CacheEntryIt->second.spCacheTexture, CacheEntryIt->second.Location); } // ############################################################################################# // // # Nuclex::Video::TextureCache::cache() # // // ############################################################################################# // /** Caches a surface @param spSurface Surface to be cached @return A cache slot specifying which texture to use and the location of the cached surface on that texture */ TextureCache::CacheSlot TextureCache::cache(const shared_ptr<Surface> &spSurface) { // Look for the surface in the cache CacheEntryMap::iterator CacheEntryIt = m_CacheEntries.find(spSurface->getUniqueID()); if(CacheEntryIt == m_CacheEntries.end()) { // If it is too large, we have no option but to give up and throw if((spSurface->getSize().X > m_Resolution.X) || (spSurface->getSize().Y > m_Resolution.Y)) throw FailedException( "Nuclex::Video::TextureCache::cache()", "Surface is too large to fit in the cache" ); // If it fits, place it in the cache else CacheEntryIt = addToCache(spSurface); } // Return a valid cache slot return CacheSlot(CacheEntryIt->second.spCacheTexture, CacheEntryIt->second.Location); } // ############################################################################################# // // # Nuclex::Video::TextureCache::flush() # // // ############################################################################################# // /** Cleans the cache, throwing out any objects not needed anymore @todo Cache textures with a use_count of 1 after cleaning should be destroyed @todo Maybe even the textures should be removed and the cache list be cleared ? */ void TextureCache::flush() { m_CacheEntries.clear(); m_CacheTextures.clear(); appendSharedTexture(); } // ############################################################################################# // // # Nuclex::Video::TextureCache::addToCache() # // // ############################################################################################# // /** Adds the specified surface into the cache and returns an iterator to the newly generated cache entry for the surface @param spSurface Surface to be cached @return An iterator to the CacheEntry containing the surface */ TextureCache::CacheEntryMap::iterator TextureCache::addToCache( const shared_ptr<Surface> &spSurface ) { // Find a free location for the surface within the current cache texture Point2<size_t> Location = m_spCurrentTexture->Packer.placeRectangle(spSurface->getSize()); if(Location == m_Resolution) { // If it doesn't fit anymore, try using a new cache texture appendSharedTexture(); Location = m_spCurrentTexture->Packer.placeRectangle(spSurface->getSize()); } // Copy the surface pixels onto the cache texture spSurface->blitTo(m_spCurrentTexture->spTexture, Location); // Add the cache entry into the internet list and return its the iterator return m_CacheEntries.insert(CacheEntryMap::value_type( spSurface->getUniqueID(), CacheEntry( spSurface, m_spCurrentTexture->spTexture, Box2<float>( Point2<float>(Location, StaticCastTag()) / Point2<float>(m_Resolution, StaticCastTag()), Point2<float>(Location + spSurface->getSize(), StaticCastTag()) / Point2<float>(m_Resolution, StaticCastTag()) ) ) )).first; } // ############################################################################################# // // # Nuclex::Video::TextureCache::appendSharedTexture() # // // ############################################################################################# // /** Appends a new shared texture to the cache. Called when the current cache texture is full and another texture is required to place a new object on */ void TextureCache::appendSharedTexture() { m_CacheTextures.push_back( shared_ptr<SharedTexture>(new SharedTexture( m_spVideoDevice->createTexture(m_Resolution, VideoDevice::AC_BLEND) )) ); m_spCurrentTexture = m_CacheTextures.back(); } // ############################################################################################# // // # Nuclex::Video::TextureCache::SharedTexture::RectanglePacker::RectanglePacker() # // // ############################################################################################# // /** Initializes a rectangle packer @param Size Total size of packing area */ TextureCache::SharedTexture::RectanglePacker::RectanglePacker(const Point2<size_t> &Size) : m_Size(Size), m_lCurrentLine(0), m_lMaxHeight(0), m_lXPosition(0) {} // ############################################################################################# // // # Nuclex::Video::TextureCache::SharedTexture::RectanglePacker::placeRectangle() # // // ############################################################################################# // /** Places a rectangle in the packing area. If the packing area is too full to place the rectangle, the size of the packing area will be returned to indicate that a new shared texture should be created by the cache @param Size Size of the rectangle to put in the packing area @return The location at which the rectangle was placed */ Point2<size_t> TextureCache::SharedTexture::RectanglePacker::placeRectangle( const Point2<size_t> &Size ) { // Filtering out rectangles that are too large should be handled by our owner assert((Size.X <= m_Size.X) && (Size.Y <= m_Size.Y)); // Do we have to start a new line ? if((m_lXPosition + Size.X) > m_Size.X) { size_t NewLine = m_lCurrentLine + m_lMaxHeight; // Check if it will fit then if((NewLine + Size.Y) > m_Size.Y) return m_Size; // If it fits in the new line, make the advancement to the next line m_lCurrentLine = NewLine; m_lMaxHeight = 0; m_lXPosition = 0; } // Save the placement of the rectangle and advance to the right Point2<long> Position(static_cast<long>(m_lXPosition), static_cast<long>(m_lCurrentLine)); m_lXPosition += Size.X; if(Size.Y > m_lMaxHeight) m_lMaxHeight = Size.Y; return Position; }
[ [ [ 1, 289 ] ] ]
00195c368157e92091aedc12dbe2bdadeece1253
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/gui/app/static/Color_map.h
3fca8a1db91466585bf4d96ffdbe1092c8a9b24c
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,347
h
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * $Id: Color_map.h 388 2008-12-12 18:17:06Z miklosb $ */ #ifndef COLOR_MAP_H #define COLOR_MAP_H #include <vector> #include <QtCore/QString> #include <QtCore/QDir> #include <QtGui/QPixmap> #include <QtGui/QColor> #ifdef MESECINA_BRIDGE #define API __declspec( dllexport ) #else #define API __declspec( dllimport ) #endif class API Color_map { public: Color_map(); Color_map(const QString& map_path, const QString& name); QPixmap* get_thumbnail(); QBrush* get_brush(); QString get_name(); // void set_scale_min(float min); // void set_scale_max(float max); void set_scale_range(float min, float max); float get_scale_min() { return min; } float get_scale_max() { return max; } QColor get_color(float value); protected: float min, max; QPixmap* thumbnail; QBrush* brush; QString name; std::vector<double> color_data; }; class API Random_color_map : public Color_map { public: Random_color_map(); Random_color_map(const int map_resolution, const QString& name); }; #endif //COLOR_MAP_H
[ "balint.miklos@localhost" ]
[ [ [ 1, 59 ] ] ]
4887777aa08f107b8be4c06c92356844ec3ff7e2
789bfae90cbb728db537b24eb9ab21c88bda2786
/source/MenuVanishStateClass.cpp
a16367993aae7859416c4c94f4f29162e0ae36f4
[ "MIT" ]
permissive
Izhido/bitsweeper
b89db2c2050cbc82ea60d31d2f31b041a1e913a3
a37902c5b9ae9c25ee30694c2ba0974fd235090e
refs/heads/master
2021-01-23T11:49:21.723909
2011-12-24T22:43:30
2011-12-24T22:43:30
34,614,275
0
2
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
#include "MenuVanishStateClass.h" #include "CommonDataClass.h" #include "StateMachineClass.h" #include "StartButtonAppearStateClass.h" #include "OperationsClass.h" MenuVanishStateClass::MenuVanishStateClass() : StateClass() { } void MenuVanishStateClass::Start(CommonDataClass* CommonData) { Vanishing.SetLength(2); Vanishing.Start[0] = -0.05; Vanishing.Start[1] = 0.05; Vanishing.Finish[0] = 0; Vanishing.Finish[1] = 0; Vanishing.SetMax(10); } void MenuVanishStateClass::Run(CommonDataClass* CommonData) { Vanishing.Step(); if(Vanishing.Finished()) { CommonData->StateMachine->Switch(START_BUTTON_APPEAR_STATE); }; } void MenuVanishStateClass::Draw(CommonDataClass* CommonData) { Operations::DrawLargeCenteredLogo(CommonData); glBindTexture(0, CommonData->Textures[MENU_IMG]); glBegin(GL_QUADS); glTexCoord2t16(inttot16(0), inttot16(0)); glVertex3f(Vanishing.Value[0], 0.0, -0.05); glTexCoord2t16(inttot16(0), inttot16(128)); glVertex3f(Vanishing.Value[0], 0.0, -0.15); glTexCoord2t16(inttot16(128), inttot16(128)); glVertex3f(Vanishing.Value[1], 0.0, -0.15); glTexCoord2t16(inttot16(128), inttot16(0)); glVertex3f(Vanishing.Value[1], 0.0, -0.05); glEnd(); }
[ "[email protected]@66f87ebb-1a6f-337b-3a26-6cadc16acdcf" ]
[ [ [ 1, 45 ] ] ]
6ccab7659c80fc8b275bd7eec21e544f178dabc2
4497c10f3b01b7ff259f3eb45d0c094c81337db6
/Retargeting/Shifmap/Version01/LabelMapper.h
5f1638f85a3769f9666a020e9a18f89ff815da71
[]
no_license
liuguoyou/retarget-toolkit
ebda70ad13ab03a003b52bddce0313f0feb4b0d6
d2d94653b66ea3d4fa4861e1bd8313b93cf4877a
refs/heads/master
2020-12-28T21:39:38.350998
2010-12-23T16:16:59
2010-12-23T16:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
455
h
#pragma once #include "Common3D.h" #include "MappingCubic.h" // provide which point3D is mapped to which point3D class LabelMapper { public: LabelMapper(void); ~LabelMapper(void); protected: MappingCubic* _mappingCubicData; MappingCubic* _mappingCubicShift; public: void SetMappingCubic(MappingCubic* data, MappingCubic* shift); virtual Point3D GetMappedPoint(int labelId, int pixelId); virtual Point3D GetPoint(int pixelId); };
[ "kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a" ]
[ [ [ 1, 18 ] ] ]
21567a71251062754ef9830bdede6f27e638854b
6131815bf1b62accfc529c2bc9db21194c7ba545
/FrameworkApp/App/GUI/UISlider.cpp
796c057eace65f6f186a9311e03263610e4d3142
[]
no_license
dconefourseven/honoursproject
b2ee664ccfc880c008f29d89aad03d9458480fc8
f26b967fda8eb6937f574fd6f3eb76c8fecf072a
refs/heads/master
2021-05-29T07:14:35.261586
2011-05-15T18:27:49
2011-05-15T18:27:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,884
cpp
#include "UISlider.h" #include <stdio.h> UISlider::UISlider(IDirect3DDevice9* Device, LONG top, LONG left, LONG right, LONG bottom, D3DXVECTOR3* center, D3DXVECTOR3* position, char* string, float stringPos, float minX, float maxX, float minRange, float maxRange) : UIElement(Device, top, left, right, bottom, center, position) { mString = string; //Create the font used to render the frame counter D3DXCreateFont( pDevice, 18, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Courier New"), &mFont ); //Initialise the position of the slider mPosRect = new RECT(); mPosRect->bottom = bottom + (LONG)position->y; mPosRect->right = right + (LONG)position->x; mPosRect->top = (LONG)position->y; mPosRect->left = (LONG)position->x; //Initialise the font rectangle mFontRect = new RECT(); mFontRect->bottom = bottom + (LONG)position->y; mFontRect->right = right + (LONG)stringPos + 150; mFontRect->top = (LONG)position->y; mFontRect->left = (LONG)stringPos; //Set the width and the cursor mCursorWidth = right; //Zero the clicked variable mIsClicked = false; //Set the minimum and maximum screen positions for the cursor mMinX = minX; mMaxX = maxX; //Set the minimum and maximum range values that the slider can go between mMinRange = minRange; mMaxRange = maxRange; //Zero the two results of the slider PercentageOnScreen = 0; PercentageOnSlider = 0; //Set up the background sprite and rectangle mBackground = new Sprite(); mBackgroundRect = new RECT(); //The background has the same positions as the font *mBackgroundRect = *mFontRect; mBackgroundPosition = new D3DXVECTOR3((float)mBackgroundRect->left, (float)mBackgroundRect->top, 0); //Load the font //Initialise(); } UISlider::~UISlider() { } bool UISlider::IsHovered(float mouseX, float mouseY) { //If the mouse is around the range of the cursor, this is done to give the cursor a little room to maneuvre if(mouseX < mPosRect->left - 25) return false; if(mouseX > mPosRect->right + 25) return false; //If the mouse is within the boundaries of the cursor if(mouseY < mPosRect->top) return false; if(mouseY > mPosRect->bottom) return false; return true; } bool UISlider::IsClicked(float mouseX, float mouseY, bool isButtonClicked) { //If the button is being held down if(!isButtonClicked) { mIsClicked = false; return false; } //If the cursor is in position if(!IsHovered(mouseX, mouseY)) { mIsClicked = false; return false; } //Set the click to true mIsClicked = true; return true; } float UISlider::CalculatePercentageOnScreen() { //Calculate the range that the slider goes between on screen float OnScreenRange; OnScreenRange = mMaxX - mMinX; //Calculate the percentage that the cursor is at on the slider float PercentageValue; //Calculate the cursors position from 0 to OnScreenRange float CursorPositionX = UIElement::mPosition->x - mMinX; //Calculate the percentage on the screen PercentageValue = (CursorPositionX / OnScreenRange) * 100; //Return that value PercentageOnScreen = PercentageValue; return PercentageValue; } float UISlider::CalculatePercentageOnSlider() { //Calculate the range that the slider goes between on screen float SliderRange; SliderRange = mMaxRange - mMinRange; //Calculate the percentage that the cursor is at on the slider float PercentageValue; PercentageValue = PercentageOnScreen / 100 * SliderRange; //Return that value PercentageOnSlider = PercentageValue + mMinRange; return PercentageOnSlider; } void UISlider::Initialise() { //Initialise the base sprite UIElement::Initialise(); //Load the background sprite unique to the slider D3DXCreateSprite(pDevice, &mBackground->mSprite); D3DXCreateTextureFromFile(pDevice, "Textures/template.jpg", &mBackground->mSpriteTexture); } void UISlider::Update(float MouseX) { //Calculate the values the slider is at CalculatePercentageOnScreen(); CalculatePercentageOnSlider(); //Update the base UIElement::Update(); //Move the cursor if(mIsClicked) { if(MouseX > mMinX && MouseX < mMaxX) { if(UIElement::mPosition->x > mMinX && UIElement::mPosition->x < mMaxX) { UIElement::mPosition->x = MouseX - mCursorWidth/2; //Remember to move the rectangle along for collision detection mPosRect->right = (LONG)(mCursorWidth + UIElement::mPosition->x); mPosRect->left = (LONG)UIElement::mPosition->x; } //if it's out of range, reset it else if (UIElement::mPosition->x > mMinX) { UIElement::mPosition->x = mMaxX - 1 - mCursorWidth/2; mPosRect->right = (LONG)(mCursorWidth + UIElement::mPosition->x); mPosRect->left = (LONG)UIElement::mPosition->x; } else if (UIElement::mPosition->x < mMaxX) { UIElement::mPosition->x = mMinX + 1; mPosRect->right = (LONG)(mCursorWidth + UIElement::mPosition->x); mPosRect->left = (LONG)UIElement::mPosition->x; } } } sprintf_s(mFinalString, sizeof(mFinalString), "%s: %f", mString, CalculatePercentageOnSlider()); } void UISlider::Draw() { //Begin, draw and end mBackground->mSprite->Begin(0); mBackground->mSprite->Draw(mBackground->mSpriteTexture, mBackgroundRect, mCenter, mBackgroundPosition, 0x006495ED); mBackground->mSprite->End(); UIElement::Draw(mIsClicked); mFont->DrawText(0, mFinalString, -1, mFontRect, DT_TOP | DT_LEFT /*draw in the top left corner*/, 0xFFFFFF00);// yellow text } void UISlider::Release() { //Make sure to release everything, not just what's in the base class UIElement::Release(); mFont->Release(); mBackground->mSprite->Release(); mBackground->mSpriteTexture->Release(); }
[ "davidclarke1990@fa56ba20-0011-6cdf-49b4-5b20436119f6" ]
[ [ [ 1, 202 ] ] ]
d02af0f9b1f9d2de16b3d6de28c7c93d6a576cdd
81d715e8253e54d64940ab48621d97cd1097ec11
/include/videoInput.h
5e11824dfb8e89460f20fd06b61a15cd9b270810
[]
no_license
pratikac/freekick
57da6ea59ca3f848cfd64c688bc0286036d31d34
2c2ce6b7bb22b7ce43edca1b2eabe8def65d9cc5
refs/heads/master
2016-09-06T17:24:33.796161
2010-01-20T14:46:05
2010-01-20T14:46:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,002
h
#ifndef _VIDEOINPUT #define _VIDEOINPUT //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. ////////////////////////////////////////////////////////// //Written by Theodore Watson - [email protected] // //Do whatever you want with this code but if you find // //a bug or make an improvement I would love to know! // // // //Warning This code is experimental // //use at your own risk :) // ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// /* Shoutouts Thanks to: Dillip Kumar Kara for crossbar code. Zachary Lieberman for getting me into this stuff and for being so generous with time and code. The guys at Potion Design for helping me with VC++ Josh Fisher for being a serious C++ nerd :) Golan Levin for helping me debug the strangest and slowest bug in the world! And all the people using this library who send in bugs, suggestions and improvements who keep me working on the next version - yeah thanks a lot ;) */ ///////////////////////////////////////////////////////// #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <wchar.h> //this is for TryEnterCriticalSection #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x400 #endif #include <windows.h> //Example Usage /* //create a videoInput object videoInput VI; //Prints out a list of available devices and returns num of devices found int numDevices = VI.listDevices(); int device1 = 0; //this could be any deviceID that shows up in listDevices int device2 = 1; //this could be any deviceID that shows up in listDevices //setup the first device - there are a number of options: VI.setupDevice(device1); //setup the first device with the default settings //VI.setupDevice(device1, VI_COMPOSITE); //or setup device with specific connection type //VI.setupDevice(device1, 320, 240); //or setup device with specified video size //VI.setupDevice(device1, 320, 240, VI_COMPOSITE); //or setup device with video size and connection type //VI.setFormat(device1, VI_NTSC_M); //if your card doesn't remember what format it should be //call this with the appropriate format listed above //NOTE: must be called after setupDevice! //optionally setup a second (or third, fourth ...) device - same options as above VI.setupDevice(device2); //As requested width and height can not always be accomodated //make sure to check the size once the device is setup int width = VI.getWidth(device1); int height = VI.getHeight(device1); int size = VI.getSize(device1); unsigned char * yourBuffer1 = new unsigned char[size]; unsigned char * yourBuffer2 = new unsigned char[size]; //to get the data from the device first check if the data is new if(VI.isFrameNew(device1)){ VI.getPixels(device1, yourBuffer1, false, false); //fills pixels as a BGR (for openCV) unsigned char array - no flipping VI.getPixels(device1, yourBuffer2, true, true); //fills pixels as a RGB (for openGL) unsigned char array - flipping! } //same applies to device2 etc //to get a settings dialog for the device VI.showSettingsWindow(device1); //Shut down devices properly VI.stopDevice(device1); VI.stopDevice(device2); */ ////////////////////////////////////// VARS AND DEFS ////////////////////////////////// //STUFF YOU CAN CHANGE //change for verbose debug info //static bool verbose = true; // Kartik - to remove compile-time warning //STUFF YOU DON'T CHANGE //videoInput defines #define VI_VERSION 0.1991 #define VI_MAX_CAMERAS 20 #define VI_NUM_TYPES 18 //DON'T TOUCH #define VI_NUM_FORMATS 18 //DON'T TOUCH //defines for setPhyCon #define VI_COMPOSITE 0 #define VI_S_VIDEO 1 #define VI_TUNER 2 #define VI_USB 3 //defines for formats #define VI_NTSC_M 0 #define VI_PAL_B 1 #define VI_PAL_D 2 #define VI_PAL_G 3 #define VI_PAL_H 4 #define VI_PAL_I 5 #define VI_PAL_M 6 #define VI_PAL_N 7 #define VI_PAL_NC 8 #define VI_SECAM_B 9 #define VI_SECAM_D 10 #define VI_SECAM_G 11 #define VI_SECAM_H 12 #define VI_SECAM_K 13 #define VI_SECAM_K1 14 #define VI_SECAM_L 15 #define VI_NTSC_M_J 16 #define VI_NTSC_433 17 //allows us to directShow classes here with the includes in the cpp struct ICaptureGraphBuilder2; struct IGraphBuilder; struct IBaseFilter; struct IAMCrossbar; struct IMediaControl; struct ISampleGrabber; struct IMediaEventEx; struct IAMStreamConfig; struct _AMMediaType; class SampleGrabberCallback; typedef _AMMediaType AM_MEDIA_TYPE; //keeps track of how many instances of VI are being used //don't touch //static int comInitCount = 0; // Kartik - to remove compile-time warning //////////////////////////////////////// VIDEO DEVICE /////////////////////////////////// class videoDevice{ public: videoDevice(); void setSize(int w, int h); void NukeDownstream(IBaseFilter *pBF); void destroyGraph(); ~videoDevice(); int videoSize; int width; int height; int tryWidth; int tryHeight; ICaptureGraphBuilder2 *pCaptureGraph; // Capture graph builder object IGraphBuilder *pGraph; // Graph builder object IMediaControl *pControl; // Media control object IBaseFilter *pVideoInputFilter; // Video Capture filter IBaseFilter *pGrabberF; IBaseFilter * pDestFilter; IAMStreamConfig *streamConf; ISampleGrabber * pGrabber; // Grabs frame AM_MEDIA_TYPE * pAmMediaType; IMediaEventEx * pMediaEvent; GUID videoType; long formatType; SampleGrabberCallback * sgCallback; bool tryDiffSize; bool useCrossbar; bool readyToCapture; bool sizeSet; bool setupStarted; bool specificFormat; int connection; int storeConn; int myID; char nDeviceName[255]; WCHAR wDeviceName[255]; unsigned char * pixels; char * pBuffer; }; ////////////////////////////////////// VIDEO INPUT ///////////////////////////////////// class videoInput{ public: videoInput(); ~videoInput(); //turns off console messages - default is to print messages static void setVerbose(bool _verbose); //Functions in rough order they should be used. static int listDevices(bool silent = false); //choose to use callback based capture - or single threaded void setUseCallback(bool useCallback); //Choose one of these four to setup your device bool setupDevice(int deviceID); bool setupDevice(int deviceID, int w, int h); //If you need to you can set your NTSC/PAL/SECAM //preference here. if it is available it will be used. //see #defines above for available formats - eg VI_NTSC_M or VI_PAL_B //should be called after setupDevice //can be called multiple times bool setFormat(int deviceNumber, int format); //These two are only for capture cards //USB and Firewire cameras souldn't specify connection bool setupDevice(int deviceID, int connection); bool setupDevice(int deviceID, int w, int h, int connection); //Tells you when a new frame has arrived bool isFrameNew(int deviceID); bool isDeviceSetup(int deviceID); //Returns the pixels - flipRedAndBlue toggles RGB/BGR flipping - and you can flip the image too unsigned char * getPixels(int deviceID, bool flipRedAndBlue = true, bool flipImage = false); //Or pass in a buffer for getPixels to fill returns true if successful. bool getPixels(int id, unsigned char * pixels, bool flipRedAndBlue = true, bool flipImage = false); //Launches a pop up settings window //For some reason in GLUT you have to call it twice each time. void showSettingsWindow(int deviceID); //get width, height and number of pixels int getWidth(int deviceID); int getHeight(int deviceID); int getSize(int deviceID); //completely stops and frees a device void stopDevice(int deviceID); //as above but then sets it up with same settings bool restartDevice(int deviceID); //number of devices available int devicesFound; private: void setPhyCon(int deviceID, int conn); void setAttemptCaptureSize(int deviceID, int w, int h); bool setup(int deviceID); void processPixels(unsigned char * src, unsigned char * dst, int width, int height, bool bRGB, bool bFlip); int start(int deviceID, videoDevice * VD); int getDeviceCount(); HRESULT getDevice(IBaseFilter **pSrcFilter, int deviceID, WCHAR * wDeviceName, char * nDeviceName); static HRESULT ShowFilterPropertyPages(IBaseFilter *pFilter); HRESULT SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath); HRESULT routeCrossbar(ICaptureGraphBuilder2 **ppBuild, IBaseFilter **pVidInFilter, int conType, GUID captureMode); //don't touch static bool comInit(); static bool comUnInit(); int connection; int callbackSetCount; bool bCallback; GUID CAPTURE_MODE; //Extra video subtypes GUID MEDIASUBTYPE_Y800; GUID MEDIASUBTYPE_Y8; GUID MEDIASUBTYPE_GREY; videoDevice * VDList[VI_MAX_CAMERAS]; GUID mediaSubtypes[VI_NUM_TYPES]; long formatTypes[VI_NUM_FORMATS]; static void __cdecl basicThread(void * objPtr); }; #endif
[ "pratik.ac@26ac5a0a-5c52-4786-9981-c9e7b4f08508" ]
[ [ [ 1, 327 ] ] ]
abfe0549ae3dba8acdd2b6d5a556991c522074b7
0f7af923b9d3a833f70dd5ab6f9927536ac8e31c
/ elistestserver/MySocket.cpp
7c47c2918638796170b518775fd08783f3513a89
[]
no_license
empiredan/elistestserver
c422079f860f166dd3fcda3ced5240d24efbd954
cfc665293731de94ff308697f43c179a4a2fc2bb
refs/heads/master
2016-08-06T07:24:59.046295
2010-01-25T16:40:32
2010-01-25T16:40:32
32,509,805
0
0
null
null
null
null
UTF-8
C++
false
false
1,562
cpp
// MySocket.cpp : implementation file // #include "stdafx.h" #include "ELISTestServer.h" #include "ELISTestServerDlg.h" #include "MySocket.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // MySocket MySocket::MySocket() { this->m_pELISTestServerDlg=NULL; } MySocket::~MySocket() { this->m_pELISTestServerDlg=NULL; } // Do not edit the following lines, which are needed by ClassWizard. #if 0 BEGIN_MESSAGE_MAP(MySocket, CAsyncSocket) //{{AFX_MSG_MAP(MySocket) //}}AFX_MSG_MAP END_MESSAGE_MAP() #endif // 0 ///////////////////////////////////////////////////////////////////////////// // MySocket member functions void MySocket::SetParent(CELISTestServerDlg* pDlg) { m_pELISTestServerDlg=pDlg; } void MySocket::OnAccept(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class if(nErrorCode==0) this->m_pELISTestServerDlg->OnAccept(); CAsyncSocket::OnAccept(nErrorCode); } void MySocket::OnReceive(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class if(nErrorCode==0) this->m_pELISTestServerDlg->OnReceive(); CAsyncSocket::OnReceive(nErrorCode); } void MySocket::OnClose(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class //if(nErrorCode==0) //this->Close(); //this->m_pELISTestServerDlg->OnClose(); CAsyncSocket::OnClose(nErrorCode); }
[ "zwusheng@3065b396-e208-11de-81d3-db62269da9c1", "EmpireDaniel@3065b396-e208-11de-81d3-db62269da9c1" ]
[ [ [ 1, 62 ], [ 65, 67 ] ], [ [ 63, 64 ] ] ]
c7234801ea8c6d6ea2bc12408b17e1392a4b0d77
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/include/QxDataMember/IxDataMemberX.h
b48db36d20f915ff412ba5eb03474c3e708f87d4
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
3,129
h
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** 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. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ #ifndef _IX_DATA_MEMBER_X_H_ #define _IX_DATA_MEMBER_X_H_ #ifdef _MSC_VER #pragma once #endif #include <QxDataMember/IxDataMember.h> #include <QxCollection/QxCollection.h> #define QX_TABLE_PER_CLASS 1 #define QX_TABLE_PER_HIERARCHY 2 namespace qx { class IxClass; class QX_DLL_EXPORT IxDataMemberX { protected: QxCollection<QString, IxDataMember *> m_lstDataMember; // Collection of 'IxDataMember' IxClass * m_pClass; // Class definition protected: IxDataMemberX() : m_pClass(NULL) { ; } virtual ~IxDataMemberX() { deleteAllIxDataMember(); } public: inline IxClass * getClass() const { return m_pClass; } inline void setClass(IxClass * p) { m_pClass = p; } QString getName() const; const char * getNamePtr() const; QString getDescription() const; long getVersion() const; long getDaoStrategy() const; inline long count() const { return m_lstDataMember.count(); } inline long size() const { return this->count(); } inline bool exist(const QString & sKey) const { return m_lstDataMember.exist(sKey); } inline IxDataMember * get(long l) const { return m_lstDataMember.getByIndex(l); } inline IxDataMember * get(const QString & s) const { return m_lstDataMember.getByKey(s); } virtual IxDataMember * getId() const = 0; virtual long count_WithDaoStrategy() const = 0; virtual bool exist_WithDaoStrategy(const QString & sKey) const = 0; virtual IxDataMember * get_WithDaoStrategy(long lIndex) const = 0; virtual IxDataMember * get_WithDaoStrategy(const QString & sKey) const = 0; virtual IxDataMember * getId_WithDaoStrategy() const = 0; private: inline void deleteAllIxDataMember() { _foreach(IxDataMember * p, m_lstDataMember) { delete p; }; } }; typedef boost::shared_ptr<IxDataMemberX> IxDataMemberX_ptr; } // namespace qx #endif // _IX_DATA_MEMBER_X_H_
[ [ [ 1, 91 ] ] ]
30a5edfff72db65b0cdfadcb019a389dc827ea8e
8e4d21a99d0ce5413eab7a083544aff9f944b26f
/include/NthMouseController.h
fa9d931bae231883e64f6050c38edff699886f69
[]
no_license
wangjunbao/nontouchsdk
957612b238b8b221b4284efb377db220bd41186a
81ab8519ea1af45dbb7ff66c6784961f14f9930c
refs/heads/master
2021-01-23T13:57:20.020732
2010-10-31T12:03:49
2010-10-31T12:03:49
34,656,556
0
0
null
null
null
null
UTF-8
C++
false
false
408
h
/* * NthMouseController.h * CopyRight @South China Institute of Software Engineering,.GZU * Author: * 2010/10/20 */ #ifndef NTHMOUSECONTROLLER_H #define NTHMOUSECONTROLLER_H #ifdef DLL_FILE class _declspec(dllexport) NthMouseController #else class _declspec(dllimport) NthMouseController #endif { public: NthMouseController(void); ~NthMouseController(void); }; #endif
[ "tinya0913@6b3f5b0f-ac10-96f7-b72e-cc4b20d3e213" ]
[ [ [ 1, 24 ] ] ]
24071008c03905fc3241515082da4b81e78a2ca5
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/ComputationalGeometry/Wm4TRVector.inl
6339de691661d47c093e61dfa66ba33e8ed68fa0
[]
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
UTF-8
C++
false
false
8,280
inl
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>::TRVector () { // For efficiency in construction of large arrays of vectors, the // default constructor does not initialize the vector. } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>::TRVector (const TRVector& rkV) { for (int i = 0; i < VSIZE; i++) { m_akTuple[i] = rkV.m_akTuple[i]; } } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>::operator const TRational<ISIZE>* () const { return m_akTuple; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>::operator TRational<ISIZE>* () { return m_akTuple; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRational<ISIZE> TRVector<VSIZE,ISIZE>::operator[] (int i) const { assert(0 <= i && i < VSIZE); return m_akTuple[i]; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRational<ISIZE>& TRVector<VSIZE,ISIZE>::operator[] (int i) { assert(0 <= i && i < VSIZE); return m_akTuple[i]; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>& TRVector<VSIZE,ISIZE>::operator= (const TRVector& rkV) { for (int i = 0; i < VSIZE; i++) { m_akTuple[i] = rkV.m_akTuple[i]; } return *this; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> bool TRVector<VSIZE,ISIZE>::operator== (const TRVector& rkV) const { for (int i = 0; i < VSIZE; i++) { if (m_akTuple[i] != rkV.m_akTuple[i]) { return false; } } return true; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> bool TRVector<VSIZE,ISIZE>::operator!= (const TRVector& rkV) const { return !operator==(rkV); } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> int TRVector<VSIZE,ISIZE>::CompareArrays (const TRVector& rkV) const { for (int i = 0; i < VSIZE; i++) { if (m_akTuple[i] < rkV.m_akTuple[i]) { return -1; } if (m_akTuple[i] > rkV.m_akTuple[i]) { return +1; } } return 0; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> bool TRVector<VSIZE,ISIZE>::operator< (const TRVector& rkV) const { return CompareArrays(rkV) < 0; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> bool TRVector<VSIZE,ISIZE>::operator<= (const TRVector& rkV) const { return CompareArrays(rkV) <= 0; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> bool TRVector<VSIZE,ISIZE>::operator> (const TRVector& rkV) const { return CompareArrays(rkV) > 0; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> bool TRVector<VSIZE,ISIZE>::operator>= (const TRVector& rkV) const { return CompareArrays(rkV) >= 0; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE> TRVector<VSIZE,ISIZE>::operator+ (const TRVector& rkV) const { TRVector<VSIZE,ISIZE> kSum; for (int i = 0; i < VSIZE; i++) { kSum.m_akTuple[i] = m_akTuple[i] + rkV.m_akTuple[i]; } return kSum; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE> TRVector<VSIZE,ISIZE>::operator- (const TRVector& rkV) const { TRVector<VSIZE,ISIZE> kDiff; for (int i = 0; i < VSIZE; i++) { kDiff.m_akTuple[i] = m_akTuple[i] - rkV.m_akTuple[i]; } return kDiff; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE> TRVector<VSIZE,ISIZE>::operator* (const TRational<ISIZE>& rkR) const { TRVector<VSIZE,ISIZE> kProd; for (int i = 0; i < VSIZE; i++) { kProd.m_akTuple[i] = rkR*m_akTuple[i]; } return kProd; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE> TRVector<VSIZE,ISIZE>::operator/ (const TRational<ISIZE>& rkR) const { assert(rkR != 0); TRVector<VSIZE,ISIZE> kProd; for (int i = 0; i < VSIZE; i++) { kProd.m_akTuple[i] = m_akTuple[i]/rkR; } return kProd; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE> TRVector<VSIZE,ISIZE>::operator- () const { TRVector<VSIZE,ISIZE> kNeg; for (int i = 0; i < VSIZE; i++) { kNeg.m_akTuple[i] = -m_akTuple[i]; } return kNeg; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE> operator* (const TRational<ISIZE>& rkR, const TRVector<VSIZE,ISIZE>& rkV) { TRVector<VSIZE,ISIZE> kProd; for (int i = 0; i < VSIZE; i++) { kProd[i] = rkR*rkV[i]; } return kProd; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>& TRVector<VSIZE,ISIZE>::operator+= (const TRVector& rkV) { for (int i = 0; i < VSIZE; i++) { m_akTuple[i] += rkV.m_akTuple[i]; } return *this; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>& TRVector<VSIZE,ISIZE>::operator-= (const TRVector& rkV) { for (int i = 0; i < VSIZE; i++) { m_akTuple[i] -= rkV.m_akTuple[i]; } return *this; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>& TRVector<VSIZE,ISIZE>::operator*= (const TRational<ISIZE>& rkR) { for (int i = 0; i < VSIZE; i++) { m_akTuple[i] *= rkR; } return *this; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRVector<VSIZE,ISIZE>& TRVector<VSIZE,ISIZE>::operator/= (const TRational<ISIZE>& rkR) { assert(rkR != 0); for (int i = 0; i < VSIZE; i++) { m_akTuple[i] /= rkR; } return *this; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRational<ISIZE> TRVector<VSIZE,ISIZE>::SquaredLength () const { TRational<ISIZE> kSqrLen = 0; for (int i = 0; i < VSIZE; i++) { kSqrLen += m_akTuple[i]*m_akTuple[i]; } return kSqrLen; } //---------------------------------------------------------------------------- template <int VSIZE, int ISIZE> TRational<ISIZE> TRVector<VSIZE,ISIZE>::Dot (const TRVector& rkV) const { TRational<ISIZE> kDot = 0; for (int i = 0; i < VSIZE; i++) { kDot += m_akTuple[i]*rkV.m_akTuple[i]; } return kDot; } //----------------------------------------------------------------------------
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 262 ] ] ]
5950c75cb2fad7d83571707a0914a0339d4fbc68
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootlePhysics/TJoint.cpp
07c93e9060f3a76c0443a489b1ec59eec31cfa9f
[]
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,928
cpp
#include "TJoint.h" #include "TPhysicsNode.h" #include "TPhysicsgraph.h" #include <box2d/include/box2d.h> TLPhysics::TJoint::TJoint() : m_CollisionBetweenNodes ( FALSE ), m_pJoint ( NULL ) { } //---------------------------------------------------------- // create joint in box2d world - returns WAIT if a node is missing //---------------------------------------------------------- SyncBool TLPhysics::TJoint::CreateJoint(b2World& World,TPhysicsgraph& PhysicsGraph) { // get the bodies of the nodes TPhysicsNode* pNodeA = PhysicsGraph.FindNode( m_NodeA ); TPhysicsNode* pNodeB = PhysicsGraph.FindNode( m_NodeB ); b2Body* pBodyA = pNodeA ? pNodeA->GetBody() : NULL; b2Body* pBodyB = pNodeB ? pNodeB->GetBody() : NULL; // missing body/node[s] if ( !pBodyA || !pBodyB ) { // gr: probably waiting for node to be initialised with a shape //TLDebug_Break("Missing nodes/bodies when creating a joint"); return SyncWait; } // init definition b2DistanceJointDef JointDef; JointDef.collideConnected = m_CollisionBetweenNodes; b2Vec2 WorldAnchor1 = pBodyA->GetWorldPoint( b2Vec2( m_JointPosA.x, m_JointPosA.y ) ); b2Vec2 WorldAnchor2 = pBodyB->GetWorldPoint( b2Vec2( m_JointPosB.x, m_JointPosB.y ) ); JointDef.Initialize( pBodyA, pBodyB, WorldAnchor1, WorldAnchor2 ); // JointDef.dampingRatio = 1.0f; // JointDef.frequencyHz = 0.9f; JointDef.dampingRatio = 0.0f; JointDef.frequencyHz = 0.0f; // instance joint m_pJoint = World.CreateJoint( &JointDef ); // failed to create joint if ( !m_pJoint ) return SyncFalse; return SyncTrue; } //---------------------------------------------------------- // remove joint from box2d world //---------------------------------------------------------- void TLPhysics::TJoint::DestroyJoint(b2World& World) { if ( m_pJoint ) { World.DestroyJoint( m_pJoint ); m_pJoint = NULL; } }
[ [ [ 1, 68 ] ] ]
e86cd9b8192c70e971f099c26fb5cc935c414d93
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Game/GameObject/GameObjectCarnivorousPlant.cpp
c9963d355011d0c7088821ac71e9b39bc8fe56a7
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
5,710
cpp
#include "OUAN_Precompiled.h" #include "GameObjectCarnivorousPlant.h" #include "../GameWorldManager.h" #include "../../Event/Event.h" using namespace OUAN; GameObjectCarnivorousPlant::GameObjectCarnivorousPlant(const std::string& name) :GameObject(name,GAME_OBJECT_TYPE_CARNIVOROUSPLANT) { } GameObjectCarnivorousPlant::~GameObjectCarnivorousPlant() { } /// Set logic component void GameObjectCarnivorousPlant::setLogicComponentEnemy(LogicComponentEnemyPtr logicComponentEnemy) { mLogicComponentEnemy=logicComponentEnemy; } /// return logic component LogicComponentEnemyPtr GameObjectCarnivorousPlant::getLogicComponentEnemy() { return mLogicComponentEnemy; } void GameObjectCarnivorousPlant::setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional) { mRenderComponentPositional=pRenderComponentPositional; } void GameObjectCarnivorousPlant::setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial) { mRenderComponentInitial=pRenderComponentInitial; } RenderComponentPositionalPtr GameObjectCarnivorousPlant::getRenderComponentPositional() const { return mRenderComponentPositional; } RenderComponentInitialPtr GameObjectCarnivorousPlant::getRenderComponentInitial() const { return mRenderComponentInitial; } void GameObjectCarnivorousPlant::setRenderComponentEntityDreams(RenderComponentEntityPtr pRenderComponentEntity) { mRenderComponentEntityDreams=pRenderComponentEntity; } void GameObjectCarnivorousPlant::setRenderComponentEntityNightmares(RenderComponentEntityPtr pRenderComponentEntity) { mRenderComponentEntityNightmares=pRenderComponentEntity; } RenderComponentEntityPtr GameObjectCarnivorousPlant::getRenderComponentEntityDreams() const { return mRenderComponentEntityDreams; } RenderComponentEntityPtr GameObjectCarnivorousPlant::getRenderComponentEntityNightmares() const { return mRenderComponentEntityNightmares; } void GameObjectCarnivorousPlant::setPhysicsComponentCharacter(PhysicsComponentCharacterPtr pPhysicsComponentCharacter) { mPhysicsComponentCharacter=pPhysicsComponentCharacter; } PhysicsComponentCharacterPtr GameObjectCarnivorousPlant::getPhysicsComponentCharacter() const { return mPhysicsComponentCharacter; } void GameObjectCarnivorousPlant::update(double elapsedSeconds) { GameObject::update(elapsedSeconds); } void GameObjectCarnivorousPlant::reset() { GameObject::reset(); if (mPhysicsComponentCharacter.get() && mPhysicsComponentCharacter->isInUse()) { mPhysicsComponentCharacter->reset(); mPhysicsComponentCharacter->getNxOgreController()->setPosition(mRenderComponentInitial->getPosition()); mPhysicsComponentCharacter->getNxOgreController()->setDisplayYaw(mRenderComponentInitial->getOrientation().getYaw().valueDegrees()); } else { mPhysicsComponentCharacter->getSceneNode()->setPosition(mRenderComponentInitial->getPosition()); mPhysicsComponentCharacter->getSceneNode()->setOrientation(mRenderComponentInitial->getOrientation()); } } void GameObjectCarnivorousPlant::changeWorldFinished(int newWorld) { if (!isEnabled()) return; switch(newWorld) { case DREAMS: mRenderComponentEntityDreams->setVisible(true); mRenderComponentEntityNightmares->setVisible(false); break; case NIGHTMARES: mRenderComponentEntityDreams->setVisible(false); mRenderComponentEntityNightmares->setVisible(true); break; default:break; } } void GameObjectCarnivorousPlant::changeWorldStarted(int newWorld) { if (!isEnabled()) return; switch(newWorld) { case DREAMS: break; case NIGHTMARES: break; default: break; } } void GameObjectCarnivorousPlant::changeToWorld(int newWorld, double perc) { if (!isEnabled()) return; switch(newWorld) { case DREAMS: break; case NIGHTMARES: break; default: break; } } bool GameObjectCarnivorousPlant::hasPositionalComponent() const { return true; } RenderComponentPositionalPtr GameObjectCarnivorousPlant::getPositionalComponent() const { return getRenderComponentPositional(); } bool GameObjectCarnivorousPlant::hasPhysicsComponent() const { return true; } PhysicsComponentPtr GameObjectCarnivorousPlant::getPhysicsComponent() const { return getPhysicsComponentCharacter(); } void GameObjectCarnivorousPlant::processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal) { if (mLogicComponentEnemy.get()) { mLogicComponentEnemy->processCollision(pGameObject, pNormal); } } void GameObjectCarnivorousPlant::processEnterTrigger(GameObjectPtr pGameObject) { if (mLogicComponentEnemy.get()) { mLogicComponentEnemy->processEnterTrigger(pGameObject); } } void GameObjectCarnivorousPlant::processExitTrigger(GameObjectPtr pGameObject) { if (mLogicComponentEnemy.get()) { mLogicComponentEnemy->processExitTrigger(pGameObject); } } bool GameObjectCarnivorousPlant::hasRenderComponentEntity() const { return true; } RenderComponentEntityPtr GameObjectCarnivorousPlant::getEntityComponent() const { return (mWorld==DREAMS)?mRenderComponentEntityDreams:mRenderComponentEntityNightmares; } bool GameObjectCarnivorousPlant::hasLogicComponent() const { return true; } LogicComponentPtr GameObjectCarnivorousPlant::getLogicComponent() const { return mLogicComponentEnemy; } //------------------------------------------------------------------------------------------- TGameObjectCarnivorousPlantParameters::TGameObjectCarnivorousPlantParameters() : TGameObjectParameters() { } TGameObjectCarnivorousPlantParameters::~TGameObjectCarnivorousPlantParameters() { }
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039", "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 2 ], [ 151, 154 ], [ 156, 159 ], [ 194, 199 ], [ 201, 205 ], [ 207, 209 ] ], [ [ 3, 34 ], [ 40, 44 ], [ 50, 81 ], [ 83, 84 ], [ 91, 91 ], [ 93, 93 ], [ 102, 103 ], [ 106, 107 ], [ 117, 149 ], [ 160, 170 ], [ 172, 174 ], [ 176, 193 ], [ 200, 200 ], [ 206, 206 ], [ 210, 219 ] ], [ [ 35, 39 ], [ 45, 49 ], [ 82, 82 ], [ 85, 90 ], [ 92, 92 ], [ 94, 101 ], [ 104, 105 ], [ 108, 116 ], [ 150, 150 ], [ 155, 155 ], [ 171, 171 ], [ 175, 175 ] ] ]
c417564aae4762f1f78f1408fea9905cf55ee3bb
60b362ba672a29bedf3d44abf11138dd71742c5d
/ex1-ilia/ex1/line.cpp
ad8d96eecc502ca0b108af1c9fa5fa1fde854f47
[]
no_license
AndreyShamis/oop1
9e04882ab6969cc542e99422b84114157d4b20f3
861da0e7a70eba21e4b7ee39e355c21a864ce8b1
refs/heads/master
2016-09-06T14:15:47.867525
2011-03-16T22:20:04
2011-03-16T22:20:04
32,789,848
0
0
null
null
null
null
UTF-8
C++
false
false
4,644
cpp
#include "line.h" Line::Line(Vertex ends0, Vertex ends1){ if(chekLimit(ends0) && chekLimit(ends0)) { _start = ends0; _end = ends1; } else { setDefault(); } } Line::Line(Vertex ends[2]){ if(chekLimit(ends[0]) && chekLimit(ends[1])) { _start = ends[0]; _end = ends[1]; } else { setDefault(); } } Line::Line(float x0, float y0, float x1, float y1){ if(chekLimit(x0,MAX_X)&& chekLimit(y0,MAX_Y)&& chekLimit(x1,MAX_X)&& chekLimit(y1,MAX_Y)) { _start._x = x0; _start._y = y0; _end._x = x1; _end._y = y1; } else { setDefault(); } } /* Line::Line(Vertex start, float length, float angle){ if(!chekLimit(start)) { setDefault(); return; } _length = length; _angle = angle; } */ Vertex Line::getEnd1(){ return _start; } Vertex Line::getEnd2(){ return _end; } // float Line::getLength(){ // return _length; // } /* Draws a line between two points p1(p1x,p1y) and p2(p2x,p2y). This function is based on the Bresenham's line algorithm and is highly optimized to be able to draw lines very quickly. There is no floating point arithmetic nor multiplications and divisions involved. Only addition, subtraction and bit shifting are used. */ void Line::draw(bool board[][MAX_Y + 1] ){ int F, x, y; int p1x = (int)_start._x; int p1y = (int)_start._y; int p2x = (int)_end._x; int p2y = (int)_end._y; if (p1x > p2x) // Swap points if p1 is on the right of p2 { swap(p1x, p2x); swap(p1y, p2y); } // Handle trivial cases separately for algorithm speed up. // Trivial case 1: m = +/-INF (Vertical line) if (p1x == p2x) { if (p1y > p2y) // Swap y-coordinates if p1 is above p2 { swap(p1y, p2y); } x = p1x; y = p1y; while (y <= p2y) { board[x+1][y+1] = true; y++; } return; } // Trivial case 2: m = 0 (Horizontal line) else if (p1y == p2y) { x = p1x; y = p1y; while (x <= p2x) { board[x+1][y+1] = true; x++; } return; } int dy = p2y - p1y; // y-increment from p1 to p2 int dx = p2x - p1x; // x-increment from p1 to p2 int dy2 = (dy << 1); // dy << 1 == 2*dy int dx2 = (dx << 1); int dy2_minus_dx2 = dy2 - dx2; // precompute constant for speed up int dy2_plus_dx2 = dy2 + dx2; if (dy >= 0) // m >= 0 { // Case 1: 0 <= m <= 1 (Original case) if (dy <= dx) { F = dy2 - dx; // initial F x = p1x; y = p1y; while (x <= p2x) { board[x+1][y+1] = true; if (F <= 0) { F += dy2; } else { y++; F += dy2_minus_dx2; } x++; } } // Case 2: 1 < m < INF (Mirror about y=x line // replace all dy by dx and dx by dy) else { F = dx2 - dy; // initial F y = p1y; x = p1x; while (y <= p2y) { board[x+1][y+1] = true; if (F <= 0) { F += dx2; } else { x++; F -= dy2_minus_dx2; } y++; } } } else // m < 0 { // Case 3: -1 <= m < 0 (Mirror about x-axis, replace all dy by -dy) if (dx >= -dy) { F = -dy2 - dx; // initial F x = p1x; y = p1y; while (x <= p2x) { board[x+1][y+1] = true; if (F <= 0) { F -= dy2; } else { y--; F -= dy2_plus_dx2; } x++; } } // Case 4: -INF < m < -1 (Mirror about x-axis and mirror // about y=x line, replace all dx by -dy and dy by dx) else { F = dx2 + dy; // initial F y = p1y; x = p1x; while (y >= p2y) { board[x+1][y+1] = true; if (F <= 0) { F += dx2; } else { x++; F += dy2_plus_dx2; } y--; } } } } bool Line::chekLimit(Vertex coordinate){ return (chekLimit(coordinate._x, MAX_X) && chekLimit(coordinate._y, MAX_Y)); } bool Line::chekLimit(float coordinate, int limit){ if(coordinate >= limit || coordinate < 0) return false; return true; } void Line::setDefault(){ _start._x = DEFAULT_MIN_X; _start._y = DEFAULT_MIN_X; _end._x = DEFAULT_MAX_X; _end._y = DEFAULT_MAX_Y; } void Line::swap(int &a, int &b){ int temp = a; a = b; b = temp; return; }
[ "[email protected]@915c7e4a-0830-d67a-7742-9bd6d4e428b7" ]
[ [ [ 1, 282 ] ] ]
ec4315e35cb462c4def164900d6e3d8b7c18b84c
6dfee96a4a2fd190321b37f757a04d6039e365be
/Weibo.sdk/WeiBo SDK/test/option.cpp
3f654c46866e69be48a1d2ec04b6c03c54648a1f
[]
no_license
skyui-cdel/MyFirstGit
4d0172e9058f2dbc54c8fe1f9a142ed7e262b977
9f62707e7a0624767c36e99038268a4dd2cb4791
refs/heads/master
2018-12-28T00:01:42.206089
2011-05-27T05:37:23
2011-05-27T05:37:23
2,252,774
0
0
null
null
null
null
GB18030
C++
false
false
7,688
cpp
#include "stdafx.h" #include "option.h" #include <libweibo/weibo.h> struct tagOption { int iOpt; char text[255]; }; #define WEIBO_OPTION_MAP(opt) {WEIBO_OPTION(opt),#opt} static const tagOption _option_map[] = { WEIBO_OPTION_MAP(UNK), WEIBO_OPTION_MAP(BASE), //1 //获取下行数据集(timeline) WEIBO_OPTION_MAP(GETSTATUSES_PUBLIC_TIMELINE), //2 获取最新更新的公共微博消息 WEIBO_OPTION_MAP(GETSTATUSES_FRIENDS_TIMELINE), //3 获取当前用户所关注用户的最新微博信息 (别名: statuses/home_timeline) WEIBO_OPTION_MAP(GETSTATUSES_USE_TIMELINE), //4 获取用户发布的微博信息列表 WEIBO_OPTION_MAP(GETSTATUSES_MENTIONS), //5 获取@当前用户的微博列表 WEIBO_OPTION_MAP(GETSTATUSES_COMMENTS_TIMELINE), //6 获取当前用户发送及收到的评论列表 WEIBO_OPTION_MAP(GETSTATUSES_COMMENTS_BYME), //7 获取当前用户发出的评论 WEIBO_OPTION_MAP(GETSTATUSES_COMMENTS_TOME), //7 获取当前用户收到的评论 WEIBO_OPTION_MAP(GETSTATUSES_COMMENTS_LIST), //8 获取指定微博的评论列表 WEIBO_OPTION_MAP(GETSTATUSES_COMMENTS_COUNTS), //9 批量获取一组微博的评论数及转发数 WEIBO_OPTION_MAP(GETSTATUSES_UNREAD), //10 获取当前用户未读消息数 WEIBO_OPTION_MAP(PUTSTATUSES_RESET_COUNT),//未读消息数清零接口 //微博访问 WEIBO_OPTION_MAP(GETSTATUSES_SHOW), //11 根据ID获取单条微博信息内容 WEIBO_OPTION_MAP(GOTOSTATUSES_ID),//12 根据微博ID和用户ID跳转到单条微博页面 WEIBO_OPTION_MAP(PUTSTATUSES_UPDATE),//13 发布一条微博信息 WEIBO_OPTION_MAP(PUTSTATUSES_UPLOAD),//14 上传图片并发布一条微博信息 WEIBO_OPTION_MAP(PUTSTATUSES_DESTROY),//15 删除一条微博信息 WEIBO_OPTION_MAP(PUTSTATUSES_REPOST),//16 转发一条微博信息(可加评论) WEIBO_OPTION_MAP(PUTSTATUSES_COMMENT),//17 对一条微博信息进行评论 WEIBO_OPTION_MAP(PUTSTATUSES_COMMENT_DESTROY),//18 删除当前用户的微博评论信息 WEIBO_OPTION_MAP(PUTSTATUSES_REPLY),//19 回复微博评论信息 //用户 WEIBO_OPTION_MAP(GETUSER_INFO),//20 根据用户ID获取用户资料(授权用户) WEIBO_OPTION_MAP(GETFRINDS_LIST),//21 获取当前用户关注对象列表及最新一条微博信息 WEIBO_OPTION_MAP(GETFOLLOWERS_LIST),//22 获取当前用户粉丝列表及最新一条微博信息 //私信 WEIBO_OPTION_MAP(GETDIRECTMSG),//23 获取当前用户最新私信列表 WEIBO_OPTION_MAP(GETDIRESTMSG_SENT),//24 获取当前用户发送的最新私信列表 WEIBO_OPTION_MAP(PUTDIRECTMSG_NEW),//25 发送一条私信 WEIBO_OPTION_MAP(PUTDIRECTMSG_DESTROY),//26 删除一条私信 WEIBO_OPTION_MAP(GETDIRECTMSG_WITH),//往来私信列表 //关注 WEIBO_OPTION_MAP(PUTFRIENDSHIPS_CREATE),//27 关注某用户 WEIBO_OPTION_MAP(PUTFRIENDSHIPS_CREATE_BATCH),//批量关注 WEIBO_OPTION_MAP(PUTFRIENDSHIPS_DESTROY),//28 取消关注 WEIBO_OPTION_MAP(GETFRIENDSHIPS_EXISTS),//29 判断两个用户是否有关注关系,返回两个用户关系的详细情况 WEIBO_OPTION_MAP(GETFRIENDSHIPS_BATCH_EXISTS),// //Social Graph WEIBO_OPTION_MAP(GETFRIEND_IDS),//30 关注列表 WEIBO_OPTION_MAP(GETFOLLOWER_IDS),//31 粉丝列表 //账号 WEIBO_OPTION_MAP(GETACCOUNT_VERIFY),//32 验证当前用户身份是否合法 WEIBO_OPTION_MAP(GETACCOUNT_RATELIMIT),//33 获取当前用户API访问频率限制 WEIBO_OPTION_MAP(PUTACCOUNT_QUITSESSION),//34 当前用户退出登录 WEIBO_OPTION_MAP(PUTACCOUNT_UPDATE_PROFILEIMAGE),//35 更改头像 WEIBO_OPTION_MAP(PUTACCOUNT_UPDATE_PROFILE),//36 更改资料 WEIBO_OPTION_MAP(PUTACCOUNT_REGISTER),//37 // 收藏 WEIBO_OPTION_MAP(GETFAVORITES),// 38获取当前用户的收藏列表 WEIBO_OPTION_MAP(PUTFAVORITES_CREATE),// 39添加收藏 WEIBO_OPTION_MAP(PUTFAVORITES_DESTROY),// 40删除当前用户收藏的微博信息 //登录/OAuth WEIBO_OPTION_MAP(OAUTH_REQUEST_TOKEN),// 41获取未授权的Request Token WEIBO_OPTION_MAP(OAUTH_AUTHORIZE),// 42请求用户授权Token WEIBO_OPTION_MAP(OAUTH_ACCESS_TOKEN),// 43获取授权过的Access Token // 表情 WEIBO_OPTION_MAP(GET_EMOTIONS),// 44 返回新浪微博官方所有表情、魔法表情的相关信息。包括短语、表情类型、表情分类,是否热门等。 // 用户搜索 WEIBO_OPTION_MAP(GET_USERS_SEARCH),// 45 搜索微博用户,返回关键字匹配的微博用户,(仅对新浪合作开发者开放) // 微博搜索 WEIBO_OPTION_MAP(GET_WB_SEARCH),// 46 返回关键字匹配的微博,(仅对新浪合作开发者开放) WEIBO_OPTION_MAP(GET_STATUSES_SEARCH),//47 搜索微博(多条件组合) (仅对合作开发者开放) WEIBO_OPTION_MAP(GET_PROVINCES), // 48 省份城市编码表 WEIBO_OPTION_MAP(COOKIE),// 50 cookie WEIBO_OPTION_MAP(UPDATETGT), // 51 更新cookie //自定义URL WEIBO_OPTION_MAP(CUSTOM),// WEIBO_OPTION_MAP(GET_USERS_HOT),// 获取系统推荐用户 WEIBO_OPTION_MAP(POST_USERS_REMARK),//更新修改当前登录用户所关注的某个好友的备注信息New! WEIBO_OPTION_MAP(GET_USERS_SUGGESTIONS), //Users/suggestions 返回当前用户可能感兴趣的用户 // 话题接口 ,by welbon,2011-01-10 WEIBO_OPTION_MAP(GET_TRENDS),//trends 获取某人的话题 WEIBO_OPTION_MAP(GET_TRENDS_STATUSES),//trends/statuses 获取某一话题下的微博 WEIBO_OPTION_MAP(POST_TRENDS_FOLLOW),//trends/follow 关注某一个话题 WEIBO_OPTION_MAP(DELETE_TRENDS_DESTROY),//trends/destroy 取消关注的某一个话题 WEIBO_OPTION_MAP(GET_TRENDS_HOURLY),//trends/destroy 按小时返回热门话题 WEIBO_OPTION_MAP(GET_TRENDS_DAYLIY),//trends/daily 按日期返回热门话题。返回某一日期的话题 WEIBO_OPTION_MAP(GET_TRENDS_WEEKLIY),//trends/weekly 按周返回热门话题。返回某一日期之前某一周的话题 // 黑名单接口 ,by welbon,2011-01-10 WEIBO_OPTION_MAP(POST_BLOCKS_CREATE),//将某用户加入黑名单 WEIBO_OPTION_MAP(POST_BLOCKS_DESTROY),//将某用户移出黑名单 WEIBO_OPTION_MAP(GET_BLOCKS_EXISTS),//检测某用户是否是黑名单用户 WEIBO_OPTION_MAP(GET_BLOCKS_BLOCKING),//列出黑名单用户(输出用户详细信息) WEIBO_OPTION_MAP(GET_BLOCKS_BLOCKING_IDS),//列出分页黑名单用户(只输出id) //用户标签接口 ,by welbon,2011-01-10 WEIBO_OPTION_MAP(GET_TAGS),//tags 返回指定用户的标签列表 WEIBO_OPTION_MAP(POST_TAGS_CREATE),//tags/create 添加用户标签 WEIBO_OPTION_MAP(GET_TAGS_SUGGESTIONS),//tags/suggestions 返回用户感兴趣的标签 WEIBO_OPTION_MAP(POST_TAGS_DESTROY),//tags/destroy 删除标签 WEIBO_OPTION_MAP(POST_TAGS_DESTROY_BATCH),//tags/destroy_batch 批量删除标签 // 邀请接口 WEIBO_OPTION_MAP(POST_INVITE_MAILCONTACT),//邀请邮箱联系人 WEIBO_OPTION_MAP(POST_INVITE_MSNCONTACT), //邀请MSN联系人 WEIBO_OPTION_MAP(POST_INVITE_SENDMAILS), //发送邀请邮件 // Media WEIBO_OPTION_MAP(GET_MEDIA_SHORTURL_BATCH), //批量获取SHORTURL //登录/XAuth WEIBO_OPTION(XAUTH_ACCESS_TOKEN),//获取授权过的Access Token }; extern void print_weibo_command_list() { printf("\r\nCommand list :\r\n"); for( int i = 0; i < sizeof(_option_map)/sizeof(_option_map[0]); ++ i ){ printf("value :%d,option:%s , \r\n",_option_map[i].iOpt,_option_map[i].text); } } extern int convert_key_to_number(const char* key) { for( int i = 0; i < sizeof(_option_map)/sizeof(_option_map[0]); ++ i ){ return (strcmp(key,_option_map[i].text) == 0) ? _option_map[i].iOpt : 0 ; } return 0; }
[ "[email protected]@6d9c6d06-b0b6-dbdc-3531-a27e122abd9f" ]
[ [ [ 1, 156 ] ] ]
00797364c1eabc81132050f8d89c486b1962bd1b
4d54b591fcefe7a728f1549392c95786700c3b91
/OgreFramework.cpp
90628bd74b360ee004b8af5b4ca19eddd481716a
[]
no_license
nayyden/openUberShader
e51780242a5db95700d35c827614d4a97b0582b2
3ad5e5aacc2637ff3cef4f66b842fffac5604bf3
refs/heads/master
2021-01-13T01:55:59.143401
2011-05-18T22:40:29
2011-05-18T22:40:29
1,611,367
2
0
null
null
null
null
UTF-8
C++
false
false
13,048
cpp
//||||||||||||||||||||||||||||||||||||||||||||||| #include "OgreFramework.hpp" //||||||||||||||||||||||||||||||||||||||||||||||| using namespace Ogre; //||||||||||||||||||||||||||||||||||||||||||||||| template<> OgreFramework* Ogre::Singleton<OgreFramework>::ms_Singleton = 0; //||||||||||||||||||||||||||||||||||||||||||||||| OgreFramework::OgreFramework() { m_MoveSpeed = 0.1f; m_RotateSpeed = 0.3f; m_bShutDownOgre = false; m_iNumScreenShots = 0; m_pRoot = 0; m_pSceneMgr = 0; m_pRenderWnd = 0; m_pCamera = 0; m_pViewport = 0; m_pLog = 0; m_pTimer = 0; m_pInputMgr = 0; m_pKeyboard = 0; m_pMouse = 0; m_pTrayMgr = 0; m_FrameEvent = Ogre::FrameEvent(); } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MouseListener *pMouseListener) { Ogre::LogManager* logMgr = new Ogre::LogManager(); m_pLog = Ogre::LogManager::getSingleton().createLog("OgreLogfile.log", true, true, false); m_pLog->setDebugOutputEnabled(true); m_pRoot = new Ogre::Root(""); #if OGRE_PLATFORM == PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WIN32 m_pRoot->loadPlugin("./RenderSystem_GL.dll"); #else m_pRoot->loadPlugin("/usr/lib/OGRE/RenderSystem_GL.so"); #endif if(!m_pRoot->showConfigDialog()) return false; m_pRenderWnd = m_pRoot->initialise(true, wndTitle); m_pSceneMgr = m_pRoot->createSceneManager(ST_GENERIC, "SceneManager"); m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f)); m_pCamera = m_pSceneMgr->createCamera("Camera"); m_pCamera->setPosition(Vector3(0, 60, 60)); m_pCamera->lookAt(Vector3(0, 0, 0)); m_pCamera->setNearClipDistance(1); m_pViewport = m_pRenderWnd->addViewport(m_pCamera); m_pViewport->setBackgroundColour(ColourValue(0.8f, 0.7f, 0.6f, 1.0f)); m_pCamera->setAspectRatio(Real(m_pViewport->getActualWidth()) / Real(m_pViewport->getActualHeight())); m_pViewport->setCamera(m_pCamera); unsigned long hWnd = 0; OIS::ParamList paramList; m_pRenderWnd->getCustomAttribute("WINDOW", &hWnd); paramList.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd))); m_pInputMgr = OIS::InputManager::createInputSystem(paramList); m_pKeyboard = static_cast<OIS::Keyboard*>(m_pInputMgr->createInputObject(OIS::OISKeyboard, true)); m_pMouse = static_cast<OIS::Mouse*>(m_pInputMgr->createInputObject(OIS::OISMouse, true)); m_pMouse->getMouseState().height = m_pRenderWnd->getHeight(); m_pMouse->getMouseState().width = m_pRenderWnd->getWidth(); if(pKeyListener == 0) m_pKeyboard->setEventCallback(this); else m_pKeyboard->setEventCallback(pKeyListener); if(pMouseListener == 0) m_pMouse->setEventCallback(this); else m_pMouse->setEventCallback(pMouseListener); Ogre::String secName, typeName, archName; Ogre::ConfigFile cf; cf.load("resources.cfg"); Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); } } Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); m_pTimer = new Ogre::Timer(); m_pTimer->reset(); m_pTrayMgr = new OgreBites::SdkTrayManager("TrayMgr", m_pRenderWnd, m_pMouse, this); m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); m_pTrayMgr->hideTrays(); this->guiVisible = false; //m_pTrayMgr->hideCursor(); m_pRenderWnd->setActive(true); cameraManager = new OgreBites::SdkCameraMan(m_pCamera); cameraCenter = m_pSceneMgr->getRootSceneNode()->createChildSceneNode("cameraCenter"); cameraCenter ->setPosition(Ogre::Vector3(0,0,0)); cameraManager->setTarget(cameraCenter); cameraManager->setStyle(OgreBites::CS_ORBIT); return true; } //||||||||||||||||||||||||||||||||||||||||||||||| void OgreFramework::setUpGUI() { this->currentLight = "Light1"; Ogre::StringVector strVec; strVec.push_back("Light1"); strVec.push_back("Light2"); OgreBites::SelectMenu *menu = m_pTrayMgr->createLongSelectMenu(OgreBites::TL_TOPRIGHT, "Lights", "Lights", 200, 100, 2, strVec); menu->selectItem(0, false); enableLight = m_pTrayMgr->createCheckBox(OgreBites::TL_TOPRIGHT, "EnableLight", "Enable"); enableLight->setChecked(true, false); enableLight->hide(); lightPosx = m_pTrayMgr->createLongSlider(OgreBites::TL_TOPRIGHT, "LightX", "LightX", 100, 60, -400.0f, 400.0f, 256); lightPosy = m_pTrayMgr->createLongSlider(OgreBites::TL_TOPRIGHT, "LightY", "LightY", 100, 60, -400.0f, 400.0f, 256); lightPosz = m_pTrayMgr->createLongSlider(OgreBites::TL_TOPRIGHT, "LightZ", "LightZ", 100, 60, -400.0f, 400.0f, 256); m_pTrayMgr->createCheckBox(OgreBites::TL_BOTTOMRIGHT, "MatSwitch", "TurnBumpMap"); m_pTrayMgr->createCheckBox(OgreBites::TL_BOTTOMRIGHT, "MultiLights", "Multiple Lights")->setChecked(true, false); } //||||||||||||||||||||||||||||||||||||||||||||||| OgreFramework::~OgreFramework() { if(m_pInputMgr) OIS::InputManager::destroyInputSystem(m_pInputMgr); if(m_pTrayMgr) delete m_pTrayMgr; if(m_pRoot) delete m_pRoot; if(cameraManager) delete cameraManager; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::keyPressed(const OIS::KeyEvent &keyEventRef) { if(m_pKeyboard->isKeyDown(OIS::KC_ESCAPE)) { m_bShutDownOgre = true; return true; } if(m_pKeyboard->isKeyDown(OIS::KC_SYSRQ)) { m_pRenderWnd->writeContentsToTimestampedFile("BOF_Screenshot_", ".jpg"); return true; } if(m_pKeyboard->isKeyDown(OIS::KC_M)) { static int mode = 0; if(mode == 2) { m_pCamera->setPolygonMode(PM_SOLID); mode = 0; } else if(mode == 0) { m_pCamera->setPolygonMode(PM_WIREFRAME); mode = 1; } else if(mode == 1) { m_pCamera->setPolygonMode(PM_POINTS); mode = 2; } } if(m_pKeyboard->isKeyDown(OIS::KC_O)) { if(m_pTrayMgr->isLogoVisible()) { m_pTrayMgr->hideLogo(); m_pTrayMgr->hideFrameStats(); } else { m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); } } if(m_pKeyboard->isKeyDown(OIS::KC_P)) { if(this->guiVisible) { m_pTrayMgr->hideTrays(); this->guiVisible = false; } else { m_pTrayMgr->showTrays(); this->guiVisible = true; } } return true; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::keyReleased(const OIS::KeyEvent &keyEventRef) { return true; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::mouseMoved(const OIS::MouseEvent &evt) { /* For the GUI ? */ if(m_pTrayMgr->injectMouseMove(evt)) return true; /* If not for the GUI */ cameraManager->injectMouseMove(evt); return true; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { /* For the GUI ? */ if(m_pTrayMgr->injectMouseDown(evt, id)) return true; /* If not for the GUI */ cameraManager->injectMouseDown(evt, id); return true; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { /* For the GUI ? */ if(m_pTrayMgr->injectMouseUp(evt, id)) return true; /* If not for the GUI */ cameraManager->injectMouseUp(evt, id); return true; } //||||||||||||||||||||||||||||||||||||||||||||||| void OgreFramework::updateOgre(double timeSinceLastFrame) { m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame; m_pTrayMgr->frameRenderingQueued(m_FrameEvent); } //||||||||||||||||||||||||||||||||||||||||||||||| void OgreFramework::setUpShaderParams() { Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingletonPtr()->getByName("Bump_Lambert"); vertexShaderParams = mat->getTechnique(0)->getPass(0)->getVertexProgramParameters(); fragmentShaderParams = mat->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); } //||||||||||||||||||||||||||||||||||||||||||||||| void OgreFramework::sliderMoved(OgreBites::Slider* slider) { if(slider->getName() == "LightX") { float xPos = slider->getValue(); Ogre::Vector3 lightPos = this->m_pSceneMgr->getLight(currentLight)->getPosition(); this->m_pSceneMgr->getLight(currentLight)->setPosition(xPos, lightPos.y, lightPos.z); } if(slider->getName() == "LightY") { float yPos = slider->getValue(); Ogre::Vector3 lightPos = this->m_pSceneMgr->getLight(currentLight)->getPosition(); this->m_pSceneMgr->getLight(currentLight)->setPosition(lightPos.x, yPos, lightPos.z); } if(slider->getName() == "LightZ") { float zPos = slider->getValue(); Ogre::Vector3 lightPos = this->m_pSceneMgr->getLight(currentLight)->getPosition(); this->m_pSceneMgr->getLight(currentLight)->setPosition(lightPos.x, lightPos.y, zPos); } } void OgreFramework::checkBoxToggled(OgreBites::CheckBox *checkBox) { if(checkBox->getName() == "MatSwitch") { if(checkBox->isChecked()) { Ogre::MaterialPtr bumpMat = Ogre::MaterialManager::getSingletonPtr()->getByName("Bump_Lambert"); Ogre::Entity *ent = this->m_pSceneMgr->getEntity("Cube"); ent->setMaterial(bumpMat); } else if(!checkBox->isChecked()) { Ogre::MaterialPtr simpleMat = Ogre::MaterialManager::getSingletonPtr()->getByName("Simple"); Ogre::Entity *ent = this->m_pSceneMgr->getEntity("Cube"); ent->setMaterial(simpleMat); } } if(checkBox->getName() == "EnableLight") { Ogre::Light *l = this->m_pSceneMgr->getLight(currentLight); if(checkBox->isChecked()) { l->setVisible(true); return; } else { l->setVisible(false); return; } } if(checkBox->getName() == "MultiLights") { Ogre::Light *light = this->m_pSceneMgr->getLight("Light1"); if(checkBox->isChecked()) { if(!light->isVisible()) light->setVisible(true); updateLightVis(); this->vertexShaderParams->setNamedConstant("multiLight", 1); this->fragmentShaderParams->setNamedConstant("multiLight", 1); } else { if(light->isVisible()) light->setVisible(false); updateLightVis(); this->vertexShaderParams->setNamedConstant("multiLight", 0); this->fragmentShaderParams->setNamedConstant("multiLight", 0); } } } void OgreFramework::updateLightVis() { Ogre::Light *light = this->m_pSceneMgr->getLight(currentLight); if(light->isVisible()) { enableLight->setChecked(true, false); return; } else { enableLight->setChecked(false, false); return; } } void OgreFramework::updateLightPos() { Ogre::Light *light = this->m_pSceneMgr->getLight(currentLight); Ogre::Vector3 lightPos = light->getPosition(); lightPosx->setValue(lightPos.x); lightPosy->setValue(lightPos.y); lightPosz->setValue(lightPos.z); } void OgreFramework::itemSelected(OgreBites::SelectMenu *menu) { int choice = menu->getSelectionIndex(); if(choice == 0) { this->currentLight = "Light1"; updateLightPos(); updateLightVis(); return; } else if(choice == 1) { this->currentLight = "Light2"; updateLightPos(); updateLightVis(); } return ; }
[ [ [ 1, 123 ], [ 127, 141 ], [ 168, 172 ], [ 175, 226 ], [ 238, 241 ], [ 243, 253 ], [ 259, 259 ], [ 261, 266 ], [ 272, 279 ], [ 285, 298 ], [ 310, 311 ], [ 415, 416 ] ], [ [ 124, 126 ], [ 142, 167 ], [ 173, 174 ], [ 227, 237 ], [ 242, 242 ], [ 254, 258 ], [ 260, 260 ], [ 267, 271 ], [ 280, 284 ], [ 299, 309 ], [ 312, 414 ] ] ]
2315ca6a5e549ea4ccb035f369eff7d35c0bf60c
3a577d02f876776b22e2bf1c0db12a083f49086d
/vba-minimum/trunk/src/gba/Mode1.cpp
4a261e94777c3ecbd9075c3ddb1ad4d9e18c0f4d
[]
no_license
xiaoluoyuan/VisualBoyAdvance-2
d19565617b26e1771f437842dba5f0131d774e73
cadd2193ba48e1846b45f87ff7c36246cd61b6ee
refs/heads/master
2021-01-10T01:19:23.884491
2010-05-12T09:59:37
2010-05-12T09:59:37
46,539,728
0
0
null
null
null
null
UTF-8
C++
false
false
11,189
cpp
#include "GBA.h" #include "GBAGfx.h" void mode1RenderLine() { u16 *palette = (u16 *)paletteRAM; if(DISPCNT & 0x80) { for(int x = 0; x < 240; x++) { lineMix[x] = 0x7fff; } gfxLastVCOUNT = VCOUNT; return; } if(layerEnable & 0x0100) { gfxDrawTextScreen(BG0CNT, BG0HOFS, BG0VOFS, line0); } if(layerEnable & 0x0200) { gfxDrawTextScreen(BG1CNT, BG1HOFS, BG1VOFS, line1); } if(layerEnable & 0x0400) { int changed = gfxBG2Changed; if(gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(BG2CNT, BG2X_L, BG2X_H, BG2Y_L, BG2Y_H, BG2PA, BG2PB, BG2PC, BG2PD, gfxBG2X, gfxBG2Y, changed, line2); } gfxDrawSprites(lineOBJ); u32 backdrop; backdrop = (READ16LE(&palette[0]) | 0x30000000); for(int x = 0; x < 240; x++) { u32 color = backdrop; u8 top = 0x20; if(line0[x] < color) { color = line0[x]; top = 0x01; } if((u8)(line1[x]>>24) < (u8)(color >> 24)) { color = line1[x]; top = 0x02; } if((u8)(line2[x]>>24) < (u8)(color >> 24)) { color = line2[x]; top = 0x04; } if((u8)(lineOBJ[x]>>24) < (u8)(color >> 24)) { color = lineOBJ[x]; top = 0x10; } if((top & 0x10) && (color & 0x00010000)) { // semi-transparent OBJ u32 back = backdrop; u8 top2 = 0x20; if((u8)(line0[x]>>24) < (u8)(back >> 24)) { back = line0[x]; top2 = 0x01; } if((u8)(line1[x]>>24) < (u8)(back >> 24)) { back = line1[x]; top2 = 0x02; } if((u8)(line2[x]>>24) < (u8)(back >> 24)) { back = line2[x]; top2 = 0x04; } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); else { switch((BLDMOD >> 6) & 3) { case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } } lineMix[x] = color; } gfxBG2Changed = 0; gfxLastVCOUNT = VCOUNT; } void mode1RenderLineNoWindow() { u16 *palette = (u16 *)paletteRAM; if(DISPCNT & 0x80) { for(int x = 0; x < 240; x++) { lineMix[x] = 0x7fff; } gfxLastVCOUNT = VCOUNT; return; } if(layerEnable & 0x0100) { gfxDrawTextScreen(BG0CNT, BG0HOFS, BG0VOFS, line0); } if(layerEnable & 0x0200) { gfxDrawTextScreen(BG1CNT, BG1HOFS, BG1VOFS, line1); } if(layerEnable & 0x0400) { int changed = gfxBG2Changed; if(gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(BG2CNT, BG2X_L, BG2X_H, BG2Y_L, BG2Y_H, BG2PA, BG2PB, BG2PC, BG2PD, gfxBG2X, gfxBG2Y, changed, line2); } gfxDrawSprites(lineOBJ); u32 backdrop; backdrop = (READ16LE(&palette[0]) | 0x30000000); for(int x = 0; x < 240; x++) { u32 color = backdrop; u8 top = 0x20; if(line0[x] < color) { color = line0[x]; top = 0x01; } if((u8)(line1[x]>>24) < (u8)(color >> 24)) { color = line1[x]; top = 0x02; } if((u8)(line2[x]>>24) < (u8)(color >> 24)) { color = line2[x]; top = 0x04; } if((u8)(lineOBJ[x]>>24) < (u8)(color >> 24)) { color = lineOBJ[x]; top = 0x10; } if(!(color & 0x00010000)) { switch((BLDMOD >> 6) & 3) { case 0: break; case 1: { if(top & BLDMOD) { u32 back = backdrop; u8 top2 = 0x20; if((u8)(line0[x]>>24) < (u8)(back >> 24)) { if(top != 0x01) { back = line0[x]; top2 = 0x01; } } if((u8)(line1[x]>>24) < (u8)(back >> 24)) { if(top != 0x02) { back = line1[x]; top2 = 0x02; } } if((u8)(line2[x]>>24) < (u8)(back >> 24)) { if(top != 0x04) { back = line2[x]; top2 = 0x04; } } if((u8)(lineOBJ[x]>>24) < (u8)(back >> 24)) { if(top != 0x10) { back = lineOBJ[x]; top2 = 0x10; } } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); } } break; case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } else { // semi-transparent OBJ u32 back = backdrop; u8 top2 = 0x20; if((u8)(line0[x]>>24) < (u8)(back >> 24)) { back = line0[x]; top2 = 0x01; } if((u8)(line1[x]>>24) < (u8)(back >> 24)) { back = line1[x]; top2 = 0x02; } if((u8)(line2[x]>>24) < (u8)(back >> 24)) { back = line2[x]; top2 = 0x04; } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); else { switch((BLDMOD >> 6) & 3) { case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } } lineMix[x] = color; } gfxBG2Changed = 0; gfxLastVCOUNT = VCOUNT; } void mode1RenderLineAll() { u16 *palette = (u16 *)paletteRAM; if(DISPCNT & 0x80) { for(int x = 0; x < 240; x++) { lineMix[x] = 0x7fff; } gfxLastVCOUNT = VCOUNT; return; } bool inWindow0 = false; bool inWindow1 = false; if(layerEnable & 0x2000) { u8 v0 = WIN0V >> 8; u8 v1 = WIN0V & 255; inWindow0 = ((v0 == v1) && (v0 >= 0xe8)); if(v1 >= v0) inWindow0 |= (VCOUNT >= v0 && VCOUNT < v1); else inWindow0 |= (VCOUNT >= v0 || VCOUNT < v1); } if(layerEnable & 0x4000) { u8 v0 = WIN1V >> 8; u8 v1 = WIN1V & 255; inWindow1 = ((v0 == v1) && (v0 >= 0xe8)); if(v1 >= v0) inWindow1 |= (VCOUNT >= v0 && VCOUNT < v1); else inWindow1 |= (VCOUNT >= v0 || VCOUNT < v1); } if(layerEnable & 0x0100) { gfxDrawTextScreen(BG0CNT, BG0HOFS, BG0VOFS, line0); } if(layerEnable & 0x0200) { gfxDrawTextScreen(BG1CNT, BG1HOFS, BG1VOFS, line1); } if(layerEnable & 0x0400) { int changed = gfxBG2Changed; if(gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(BG2CNT, BG2X_L, BG2X_H, BG2Y_L, BG2Y_H, BG2PA, BG2PB, BG2PC, BG2PD, gfxBG2X, gfxBG2Y, changed, line2); } gfxDrawSprites(lineOBJ); gfxDrawOBJWin(lineOBJWin); u32 backdrop; backdrop = (READ16LE(&palette[0]) | 0x30000000); u8 inWin0Mask = WININ & 0xFF; u8 inWin1Mask = WININ >> 8; u8 outMask = WINOUT & 0xFF; for(int x = 0; x < 240; x++) { u32 color = backdrop; u8 top = 0x20; u8 mask = outMask; if(!(lineOBJWin[x] & 0x80000000)) { mask = WINOUT >> 8; } if(inWindow1) { if(gfxInWin1[x]) mask = inWin1Mask; } if(inWindow0) { if(gfxInWin0[x]) { mask = inWin0Mask; } } if(line0[x] < color && (mask & 1)) { color = line0[x]; top = 0x01; } if((u8)(line1[x]>>24) < (u8)(color >> 24) && (mask & 2)) { color = line1[x]; top = 0x02; } if((u8)(line2[x]>>24) < (u8)(color >> 24) && (mask & 4)) { color = line2[x]; top = 0x04; } if((u8)(lineOBJ[x]>>24) < (u8)(color >> 24) && (mask & 16)) { color = lineOBJ[x]; top = 0x10; } if(color & 0x00010000) { // semi-transparent OBJ u32 back = backdrop; u8 top2 = 0x20; if((mask & 1) && (u8)(line0[x]>>24) < (u8)(back >> 24)) { back = line0[x]; top2 = 0x01; } if((mask & 2) && (u8)(line1[x]>>24) < (u8)(back >> 24)) { back = line1[x]; top2 = 0x02; } if((mask & 4) && (u8)(line2[x]>>24) < (u8)(back >> 24)) { back = line2[x]; top2 = 0x04; } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); else { switch((BLDMOD >> 6) & 3) { case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } } else if(mask & 32) { // special FX on the window switch((BLDMOD >> 6) & 3) { case 0: break; case 1: { if(top & BLDMOD) { u32 back = backdrop; u8 top2 = 0x20; if((mask & 1) && (u8)(line0[x]>>24) < (u8)(back >> 24)) { if(top != 0x01) { back = line0[x]; top2 = 0x01; } } if((mask & 2) && (u8)(line1[x]>>24) < (u8)(back >> 24)) { if(top != 0x02) { back = line1[x]; top2 = 0x02; } } if((mask & 4) && (u8)(line2[x]>>24) < (u8)(back >> 24)) { if(top != 0x04) { back = line2[x]; top2 = 0x04; } } if((mask & 16) && (u8)(lineOBJ[x]>>24) < (u8)(back >> 24)) { if(top != 0x10) { back = lineOBJ[x]; top2 = 0x10; } } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); } } break; case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } lineMix[x] = color; } gfxBG2Changed = 0; gfxLastVCOUNT = VCOUNT; }
[ "spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0" ]
[ [ [ 1, 460 ] ] ]
5ae3afe0adc80e5a2718625d210e4a4a597f267a
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/gui/layer_management/Popup_scalar_controls_frame.h
299fdaedf3a952c2039a4e6a00970e74db737745
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,476
h
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * $Id: Popup_scalar_controls_frame.h 255 2007-12-03 23:01:56Z miklosb $ */ #ifndef POPUP_SCALAR_CONTROLS_FRAME_H #define POPUP_SCALAR_CONTROLS_FRAME_H #include <QtGui/QWidgetAction> #include <QtGui/QLineEdit> #include <QtGui/QSlider> #include <QtGui/QHBoxLayout> #include <QtGui/QVBoxLayout> #include <QtGui/QDoubleValidator> class Popup_scalar_controls_frame : public QWidgetAction { Q_OBJECT public: Popup_scalar_controls_frame(QWidget* parent); // destructor might be needed because we are are allocating memory in constructor QVBoxLayout *layout; QHBoxLayout *min_layout, *max_layout, *color_layout; QSlider *min_slider, *max_slider; QLineEdit *min_line_edit, *max_line_edit; QAction *solid_color; void set_range(float min, float max); float min_value_to_float(); void set_min_float_value(float val); float max_value_to_float(); void set_max_float_value(float val); void set_color_map(QString name); public slots: void min_slider_value_changed(int value); void max_slider_value_changed(int value); void min_value_entered(); void max_value_entered(); private: float min, max; QDoubleValidator *min_validator, *max_validator; }; #endif //POPUP_SCALAR_CONTROLS_FRAME_H
[ "balint.miklos@localhost" ]
[ [ [ 1, 53 ] ] ]
47503d217b2477d0472d1dd6655c9a4a45d677ea
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/meta.inl
aa31ab7ec219b6fb7887eb34d2bd6f21d1a32f70
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
4,506
inl
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__META_INL #define AOSLCPP_AOSL__META_INL // Begin prologue. // // // End prologue. #include "aosl/version.hpp" #include "aosl/version.inl" #include "aosl/list_author.hpp" #include "aosl/list_author.inl" #include "aosl/list_target.hpp" #include "aosl/list_target.inl" #include "aosl/extension.hpp" #include "aosl/extension.inl" namespace aosl { // Meta // inline const Meta::VersionOptional& Meta:: version () const { return this->version_; } inline Meta::VersionOptional& Meta:: version () { return this->version_; } inline void Meta:: version (const VersionType& x) { this->version_.set (x); } inline void Meta:: version (const VersionOptional& x) { this->version_ = x; } inline void Meta:: version (::std::auto_ptr< VersionType > x) { this->version_.set (x); } inline const Meta::AuthorsOptional& Meta:: authors () const { return this->authors_; } inline Meta::AuthorsOptional& Meta:: authors () { return this->authors_; } inline void Meta:: authors (const AuthorsType& x) { this->authors_.set (x); } inline void Meta:: authors (const AuthorsOptional& x) { this->authors_ = x; } inline void Meta:: authors (::std::auto_ptr< AuthorsType > x) { this->authors_.set (x); } inline const Meta::DescriptionOptional& Meta:: description () const { return this->description_; } inline Meta::DescriptionOptional& Meta:: description () { return this->description_; } inline void Meta:: description (const DescriptionType& x) { this->description_.set (x); } inline void Meta:: description (const DescriptionOptional& x) { this->description_ = x; } inline void Meta:: description (::std::auto_ptr< DescriptionType > x) { this->description_.set (x); } inline const Meta::WebsiteOptional& Meta:: website () const { return this->website_; } inline Meta::WebsiteOptional& Meta:: website () { return this->website_; } inline void Meta:: website (const WebsiteType& x) { this->website_.set (x); } inline void Meta:: website (const WebsiteOptional& x) { this->website_ = x; } inline void Meta:: website (::std::auto_ptr< WebsiteType > x) { this->website_.set (x); } inline const Meta::LicenceOptional& Meta:: licence () const { return this->licence_; } inline Meta::LicenceOptional& Meta:: licence () { return this->licence_; } inline void Meta:: licence (const LicenceType& x) { this->licence_.set (x); } inline void Meta:: licence (const LicenceOptional& x) { this->licence_ = x; } inline void Meta:: licence (::std::auto_ptr< LicenceType > x) { this->licence_.set (x); } inline const Meta::TargetsOptional& Meta:: targets () const { return this->targets_; } inline Meta::TargetsOptional& Meta:: targets () { return this->targets_; } inline void Meta:: targets (const TargetsType& x) { this->targets_.set (x); } inline void Meta:: targets (const TargetsOptional& x) { this->targets_ = x; } inline void Meta:: targets (::std::auto_ptr< TargetsType > x) { this->targets_.set (x); } inline const Meta::InfosOptional& Meta:: infos () const { return this->infos_; } inline Meta::InfosOptional& Meta:: infos () { return this->infos_; } inline void Meta:: infos (const InfosType& x) { this->infos_.set (x); } inline void Meta:: infos (const InfosOptional& x) { this->infos_ = x; } inline void Meta:: infos (::std::auto_ptr< InfosType > x) { this->infos_.set (x); } } // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__META_INL
[ "klaim@localhost" ]
[ [ [ 1, 286 ] ] ]
915e67a1d169d16e4e9287e60ee339558bfabda9
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Graphics/WmlParticleController.cpp
a46101192d1b1d9765eb6bbe03eafc165efefbbe
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
11,297
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlParticleController.h" #include "WmlParticles.h" using namespace Wml; WmlImplementRTTI(ParticleController,Controller); WmlImplementStream(ParticleController); //---------------------------------------------------------------------------- ParticleController::ParticleController () { m_fSystemLinearSpeed = 0.0f; m_fSystemAngularSpeed = 0.0f; m_kSystemLinearAxis = Vector3f::UNIT_Z; m_kSystemAngularAxis = Vector3f::UNIT_Z; m_afPointLinearSpeed = NULL; m_afPointAngularSpeed = NULL; m_akPointLinearAxis = NULL; m_akPointAngularAxis = NULL; m_fSystemSizeChange = 0.0f; m_afPointSizeChange = NULL; } //---------------------------------------------------------------------------- ParticleController::~ParticleController () { delete[] m_afPointLinearSpeed; delete[] m_afPointAngularSpeed; delete[] m_akPointLinearAxis; delete[] m_akPointAngularAxis; delete[] m_afPointSizeChange; } //---------------------------------------------------------------------------- void ParticleController::Reallocate (int iVertexQuantity) { m_fSystemLinearSpeed = 0.0f; m_fSystemAngularSpeed = 0.0f; m_kSystemLinearAxis = Vector3f::UNIT_Z; m_kSystemAngularAxis = Vector3f::UNIT_Z; m_fSystemSizeChange = 0.0f; delete[] m_afPointLinearSpeed; delete[] m_afPointAngularSpeed; delete[] m_akPointLinearAxis; delete[] m_akPointAngularAxis; delete[] m_afPointSizeChange; if ( iVertexQuantity > 0 ) { m_afPointLinearSpeed = new float[iVertexQuantity]; m_afPointAngularSpeed = new float[iVertexQuantity]; m_akPointLinearAxis = new Vector3f[iVertexQuantity]; m_akPointAngularAxis = new Vector3f[iVertexQuantity]; m_afPointSizeChange = new float[iVertexQuantity]; memset(m_afPointLinearSpeed,0,iVertexQuantity*sizeof(float)); memset(m_afPointAngularSpeed,0,iVertexQuantity*sizeof(float)); for (int i = 0; i < iVertexQuantity; i++) { m_akPointLinearAxis[i] = Vector3f::UNIT_Z; m_akPointAngularAxis[i] = Vector3f::UNIT_Z; } memset(m_afPointSizeChange,0,iVertexQuantity*sizeof(float)); } else { m_afPointLinearSpeed = NULL; m_afPointAngularSpeed = NULL; m_akPointLinearAxis = NULL; m_akPointAngularAxis = NULL; m_afPointSizeChange = NULL; } } //---------------------------------------------------------------------------- void ParticleController::SetObject (Object* pkObject) { assert( WmlIsDerivedFromClass(Particles,pkObject) ); Controller::SetObject(pkObject); if ( pkObject ) Reallocate(((Particles*)pkObject)->GetVertexQuantity()); else Reallocate(0); } //---------------------------------------------------------------------------- void ParticleController::UpdateSystemMotion (float fCtrlTime) { Particles* pkParticle = (Particles*) m_pkObject; float fDSize = fCtrlTime*m_fSystemSizeChange; pkParticle->SizeAdjust() += fDSize; if ( pkParticle->SizeAdjust() < 0.0f ) pkParticle->SizeAdjust() = 0.0f; float fDistance = fCtrlTime*m_fSystemLinearSpeed; Vector3f kDTrn = fDistance*m_kSystemLinearAxis; pkParticle->Translate() += kDTrn; float fAngle = fCtrlTime*m_fSystemAngularSpeed; Matrix3f kDRot(m_kSystemAngularAxis,fAngle); pkParticle->Rotate() = kDRot*pkParticle->Rotate(); } //---------------------------------------------------------------------------- void ParticleController::UpdatePointMotion (float fCtrlTime) { Particles* pkParticle = (Particles*) m_pkObject; int i, iVertexQuantity = pkParticle->GetActiveQuantity(); float* afSize = pkParticle->Sizes(); for (i = 0; i < iVertexQuantity; i++) { float fDSize = fCtrlTime*m_afPointSizeChange[i]; afSize[i] += fDSize; } Vector3f* akVertex = pkParticle->Vertices(); for (i = 0; i < iVertexQuantity; i++) { float fDistance = fCtrlTime*m_afPointLinearSpeed[i]; Vector3f kDTrn = fDistance*m_akPointLinearAxis[i]; akVertex[i] += kDTrn; } Vector3f* akNormal = pkParticle->Normals(); if ( akNormal ) { for (i = 0; i < iVertexQuantity; i++) { float fAngle = fCtrlTime*m_afPointAngularSpeed[i]; Matrix3f kDRot(m_akPointAngularAxis[i],fAngle); akNormal[i] = kDRot*akNormal[i]; // TO DO. Since the normals are being updated in-place, after a // few rotations the numerical errors might build up. The // unitizing is designed to fix the errors in length. Arrange // for this to happen on a less frequent basis. akNormal[i].Normalize(); } } } //---------------------------------------------------------------------------- bool ParticleController::Update (float fAppTime) { if ( !Active() ) { // controller does not compute world transform return false; } float fCtrlTime = GetControlTime(fAppTime); UpdateSystemMotion(fCtrlTime); UpdatePointMotion(fCtrlTime); // controller does not compute world transform return false; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // streaming //---------------------------------------------------------------------------- Object* ParticleController::Factory (Stream& rkStream) { ParticleController* pkObject = new ParticleController; Stream::Link* pkLink = new Stream::Link(pkObject); pkObject->Load(rkStream,pkLink); return pkObject; } //---------------------------------------------------------------------------- void ParticleController::Load (Stream& rkStream, Stream::Link* pkLink) { Controller::Load(rkStream,pkLink); // NOTE. ParticleController was derived from PointController. The // PointController::Save wrote various quantities to disk that are now // managed by ParticleController. These quantities are written to disk // in the same order, so no special handling must occur here based on the // stream version number. // native data StreamRead(rkStream,m_fSystemLinearSpeed); StreamRead(rkStream,m_fSystemAngularSpeed); StreamRead(rkStream,m_kSystemLinearAxis); StreamRead(rkStream,m_kSystemAngularAxis); int iVertexQuantity; StreamRead(rkStream,iVertexQuantity); Reallocate(iVertexQuantity); StreamRead(rkStream,m_afPointLinearSpeed,iVertexQuantity); StreamRead(rkStream,m_afPointAngularSpeed,iVertexQuantity); StreamRead(rkStream,m_akPointLinearAxis,iVertexQuantity); StreamRead(rkStream,m_akPointAngularAxis,iVertexQuantity); StreamRead(rkStream,m_fSystemSizeChange); if ( rkStream.GetVersion() < Version(1,4) ) { // The vertex quantity had been written to disk twice, once by // PointController and once by ParticleController. Read it and // discard since it was loaded above. int iDiscard; StreamRead(rkStream,iDiscard); } StreamRead(rkStream,m_afPointSizeChange,iVertexQuantity); } //---------------------------------------------------------------------------- void ParticleController::Link (Stream& rkStream, Stream::Link* pkLink) { Controller::Link(rkStream,pkLink); } //---------------------------------------------------------------------------- bool ParticleController::Register (Stream& rkStream) { return Controller::Register(rkStream); } //---------------------------------------------------------------------------- void ParticleController::Save (Stream& rkStream) { Controller::Save(rkStream); // native data StreamWrite(rkStream,m_fSystemLinearSpeed); StreamWrite(rkStream,m_fSystemAngularSpeed); StreamWrite(rkStream,m_kSystemLinearAxis); StreamWrite(rkStream,m_kSystemAngularAxis); // Write this to disk so that Load does not have to wait until the // controlled object is loaded and linked in order to allocate the // arrays. Particles* pkParticle = (Particles*)m_pkObject; int iVertexQuantity = pkParticle->GetVertexQuantity(); StreamWrite(rkStream,iVertexQuantity); StreamWrite(rkStream,m_afPointLinearSpeed,iVertexQuantity); StreamWrite(rkStream,m_afPointAngularSpeed,iVertexQuantity); StreamWrite(rkStream,m_akPointLinearAxis,iVertexQuantity); StreamWrite(rkStream,m_akPointAngularAxis,iVertexQuantity); StreamWrite(rkStream,m_fSystemSizeChange); StreamWrite(rkStream,m_afPointSizeChange,iVertexQuantity); } //---------------------------------------------------------------------------- StringTree* ParticleController::SaveStrings () { // TO DO. Finish implementation. StringTree* pkTree = new StringTree(1,0,1,0); pkTree->SetString(0,MakeString(&ms_kRTTI,GetName())); pkTree->SetChild(0,Controller::SaveStrings()); return pkTree; } //---------------------------------------------------------------------------- int ParticleController::GetMemoryUsed () const { int iBaseSize = sizeof(ParticleController) - sizeof(Controller); Particles* pkParticle = (Particles*) m_pkObject; int iVertexQuantity = pkParticle->GetVertexQuantity(); int iDynaSize = iVertexQuantity*sizeof(m_afPointLinearSpeed[0]); iDynaSize += iVertexQuantity*sizeof(m_afPointAngularSpeed[0]); iDynaSize += iVertexQuantity*sizeof(m_akPointLinearAxis[0]); iDynaSize += iVertexQuantity*sizeof(m_akPointAngularAxis[0]); iDynaSize += iVertexQuantity*sizeof(m_afPointSizeChange[0]); int iTotalSize = iBaseSize + iDynaSize + Controller::GetMemoryUsed(); return iTotalSize; } //---------------------------------------------------------------------------- int ParticleController::GetDiskUsed () const { int iSize = Controller::GetDiskUsed() + sizeof(m_fSystemLinearSpeed) + sizeof(m_fSystemAngularSpeed) + sizeof(m_kSystemLinearAxis) + sizeof(m_kSystemAngularAxis) + sizeof(m_fSystemSizeChange); Particles* pkParticle = (Particles*) m_pkObject; int iVertexQuantity = pkParticle->GetVertexQuantity(); iSize += sizeof(iVertexQuantity); iSize += iVertexQuantity*sizeof(m_afPointLinearSpeed[0]); iSize += iVertexQuantity*sizeof(m_afPointAngularSpeed[0]); iSize += iVertexQuantity*sizeof(m_akPointLinearAxis[0]); iSize += iVertexQuantity*sizeof(m_akPointAngularAxis[0]); iSize += iVertexQuantity*sizeof(m_afPointSizeChange[0]); return iSize; } //----------------------------------------------------------------------------
[ [ [ 1, 299 ] ] ]
bd5c4262d321cf56ef18919b80697df4b8a6e81d
fe122f81ca7d6dff899945987f69305ada995cd7
/developlib/vc60include/FillLinearButton.h
1787a02315d83f8187d22f1b5569bb8ca24038a3
[]
no_license
myeverytime/chtdependstoreroom
ddb9f4f98a6a403521aaf403d0b5f2dc5213f346
64a4d1e2d32abffaab0376f6377e10448b3c5bc3
refs/heads/master
2021-01-10T06:53:35.455736
2010-06-23T10:21:44
2010-06-23T10:21:44
50,168,936
0
0
null
null
null
null
UTF-8
C++
false
false
1,619
h
#if !defined(AFX_FILLLINEARBUTTON_H__7A18922E_964C_4AEC_8995_C69F23B4FEDC__INCLUDED_) #define AFX_FILLLINEARBUTTON_H__7A18922E_964C_4AEC_8995_C69F23B4FEDC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // FillLinearButton.h : header file // #include "enum.h" ///////////////////////////////////////////////////////////////////////////// // CFillLinearButton window class CFillLinearButton : public CXTButton { // Construction public: CFillLinearButton(); LinearGradientMode m_LinerStyle; void SetStyle(LinearGradientMode LinerStyle); void SetStyleEx(StyleExEnum styleEx); void SetStartColor(COLORREF color); void SetEndColor(COLORREF color); COLORREF m_clrStart, m_clrEnd; COLORREF m_clrEx1,m_clrEx2,m_clrEx3,m_clrEx4,m_clrEx5; // Attributes public: StyleExEnum m_StyleEx; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFillLinearButton) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); //}}AFX_VIRTUAL // Implementation public: virtual ~CFillLinearButton(); // Generated message map functions protected: //{{AFX_MSG(CFillLinearButton) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FILLLINEARBUTTON_H__7A18922E_964C_4AEC_8995_C69F23B4FEDC__INCLUDED_)
[ "robustwell@bd7e636a-136b-06c9-ecb0-b59307166256" ]
[ [ [ 1, 56 ] ] ]
04a1968df267909fb8ed7811d7fce24b5421a2b7
bf19f77fdef85e76a7ebdedfa04a207ba7afcada
/NewAlpha/TMNT Tactics Tech Demo/Source/Box.h
53c9e4b0f1cc69356066cc335989c60619c990dd
[]
no_license
marvelman610/tmntactis
2aa3176d913a72ed985709843634933b80d7cb4a
a4e290960510e5f23ff7dbc1e805e130ee9bb57d
refs/heads/master
2020-12-24T13:36:54.332385
2010-07-12T08:08:12
2010-07-12T08:08:12
39,046,976
0
0
null
null
null
null
UTF-8
C++
false
false
5,954
h
////////////////////////////////////////////////////////////////////////// // Filename : Box.h // // Author : Ramon Johannessen (RJ) // // Purpose : To dynamically create menu boxes and populate them with // specific information. ////////////////////////////////////////////////////////////////////////// #ifndef BOX_H #define BOX_H #include <windows.h> #include <string> #include "Timer.h" using std::string; class CBitmapFont; class CAssets; class CSGD_TextureManager; class CSGD_FModManager; class CSGD_DirectInput; class CSGD_Direct3D; enum {BOX_NO_BACK, BOX_WITH_BACK, }; // boxType enum {BTN_SPECIAL, BTN_ITEM, BTN_ENDTURN, BTN_ENTER = 99, BTN_BACK = 100, }; // buttons class CBox { struct MY_POINT_FLOAT { float x; float y; MY_POINT_FLOAT& operator= (MY_POINT_FLOAT& pt) { x = pt.x; y = pt.y; return *this; } MY_POINT_FLOAT& operator= (POINT& pt) { x = (float)pt.x; y = (float)pt.y; return *this; } bool operator != (POINT& pt) { if ((float)pt.x != x || (float)pt.y != y) return true; return false; } }; // // which image is currently being used for the BG int m_nCurrImage; int m_BoxType; bool m_bAcceptInput; bool m_bCenterText; bool m_bCenterBox; // size/position variables int m_nLongestString; int m_nBoxWidth; int m_nBoxHeight; int m_nBoxRight; int m_nBoxBottom; int m_nPosX; int m_nPosY; float m_fPosZ; int m_nSpacing; int m_nStartXOriginal; int m_nStartYOriginal; int m_nStartTextY; int m_nStartTextX; float m_fScaleX; float m_fScaleY; float m_fTextZ; int m_nAlpha; int r; int g; int b; // menu items (buttons) bool m_bHasTitle; bool m_bEnterText; int m_nTitleWidth; string* m_sItems; string* m_sOriginal; // when accepting input float m_fTextScale; int m_nNumItems; DWORD m_dwColor; // mouse selection (buttons being hovered over/pressed) int m_nCurrSelectedIndex; int m_nCurrInputIndex; bool m_bMadeNew; bool m_bOverwrote; bool m_bIsMsgBox; bool m_bIsActive; bool m_bIsMouseInBox; int m_nBackType; MY_POINT_FLOAT m_ptOldMouse; // input (keys) string m_sInput; CTimer m_Timer; CSGD_TextureManager* m_pTM; CBitmapFont* m_pBM; CAssets* m_pAssets; CSGD_Direct3D* m_pD3D; CSGD_DirectInput* m_pDI; CSGD_FModManager* m_pFMOD; ////////////////////////////////////////////////////////////////////////// // Function : "CheckMouse" // // Purpose : Determine if the mouse is over the box, if so, which // index (button) is it over? ////////////////////////////////////////////////////////////////////////// void CheckMouse(POINT mousePt); ////////////////////////////////////////////////////////////////////////// // Function : "CheckKeysInputBox" // // Purpose : Handle keyboard input for an input box ////////////////////////////////////////////////////////////////////////// void CheckKeysInputBox(); ////////////////////////////////////////////////////////////////////////// // Function : "CheckKeys" // // Purpose : Handle keyboard input for menu selection ////////////////////////////////////////////////////////////////////////// void CheckKeys(); public: CBox(int numItems, string* sItems, int posX, int posY, float posZ = 0.11f, bool bhasTitle = false, int spacing = 35, int startX = 35, int startY = 25, int imageID = -1, float fTextScale = 1.0f, int red = 0, int green = 0, int blue = 0); ~CBox(); ////////////////////////////////////////////////////////////////////////// // Function : "Render" // // Purpose : Draws the drawing of the box and it's contents ////////////////////////////////////////////////////////////////////////// void Render(); ////////////////////////////////////////////////////////////////////////// // Function : "Input" // // Purpose : Handles user input, selections and such ////////////////////////////////////////////////////////////////////////// int Input(POINT mousePt, float felapsed); ////////////////////////////////////////////////////////////////////////// // Accessors / Mutators ////////////////////////////////////////////////////////////////////////// int CurrImage() const { return m_nCurrImage; } void CurrImage(int val) { m_nCurrImage = val; } bool AcceptInput() const { return m_bAcceptInput; } void AcceptInput(bool val = true) { m_bAcceptInput = val; } int GetInputIndex() const {return m_nCurrInputIndex;} void SetAlpha(int alpha) {m_nAlpha = alpha;} float PosZ() const { return m_fPosZ; } void PosZ(float val) { m_fPosZ = val; } int PosY() const { return m_nPosY; } void PosY(int val) { m_nPosY = val; } int PosX() const { return m_nPosX; } void PosX(int val) { m_nPosX = val; } void SetScale(float scale) {m_fScaleY = m_fScaleX = scale;} void SetScaleX(float xScale) {m_fScaleX = xScale;} void SetScaleY(float yScale) {m_fScaleY = yScale;} int BoxHeight() const { return m_nBoxHeight; } void BoxHeight(int val) { m_nBoxHeight = val; } int BoxWidth() const { return m_nBoxWidth; } void BoxWidth(int val) { m_nBoxWidth = val; } bool IsActiveBox() const { return m_bIsActive; } void SetActive(bool IsActive = true); void SetType(int type) {m_nBackType = type;} int BoxType() const { return m_BoxType; } void BoxType(int val = -1) { m_BoxType = val; } int BoxRight() {return m_nBoxRight;} bool IsMouseInBox() const { if (this != NULL)return m_bIsMouseInBox; else return 0;} void IsMouseInBox(bool val) { m_bIsMouseInBox = val; } bool IsMsgBox() const { return m_bIsMsgBox; } void IsMsgBox(bool val) { m_bIsMsgBox = val; if(val) m_nCurrSelectedIndex = -1;} string* GetItems() {return m_sItems;} bool GetMadeNew() {return m_bMadeNew;} bool GetOverwrote() {return m_bOverwrote;} void CenterText(bool center=true) {m_bCenterText = center;} void CenterBox(); }; #endif
[ "AllThingsCandid@7dc79cba-3e6d-11de-b8bc-ddcf2599578a", "marvelman610@7dc79cba-3e6d-11de-b8bc-ddcf2599578a" ]
[ [ [ 1, 8 ], [ 11, 191 ] ], [ [ 9, 10 ], [ 192, 194 ] ] ]
ccd29c098d73240c288467bffccd622d7c0e27fd
f83137ab7ba3ed9f8d89f84c415a6d8a03f99c2f
/APMShared/APMLogger.cpp
5ad0a75b64338c2e51149764401e129659827f1a
[]
no_license
NobodysNightmare/APM-Meter
0ab0438a773f90efc4836cab00c9980d3e2dce89
32bb96618bb1ce8e34db4270459aa0eb8577f6b6
refs/heads/master
2021-01-19T08:48:54.951073
2010-12-03T18:58:11
2010-12-03T18:58:11
1,023,406
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
#include "APMLogger.h" #include <stdio.h> APMLogger::APMLogger(LPCTSTR filename) { hFile = CreateFile(filename, GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) printf("\r\nCould not open log-file\r\n"); else { //FIXME size is hard-coded because memory-structures may align // should be fixed in later versions //set basic header info APMLogHeader* head = new APMLogHeader(); head->file_id[0] = 'A'; head->file_id[1] = 'P'; head->file_id[2] = 'M'; head->version = (char)1; head->header_size = 207; //set time-info SYSTEMTIME now; GetLocalTime(&now); head->year = now.wYear; head->month = now.wMonth; head->day = now.wDay; head->hour = now.wHour; head->minute = now.wMinute; //write the header DWORD written = 0; WriteFile(hFile, head, 207, &written, NULL); delete head; } } APMLogger::~APMLogger() { CloseHandle(hFile); } void APMLogger::addEntry(APMLoggableSnapshot snap) { if(!snap.valid) return; DWORD written = 0; if(!WriteFile(hFile, &(snap.snap), sizeof(APMSnapshot), &written, NULL)) printf("#%d#\r\n", GetLastError()); }
[ "Jan@.(none)", "[email protected]" ]
[ [ [ 1, 6 ], [ 34, 39 ], [ 43, 43 ], [ 46, 46 ] ], [ [ 7, 33 ], [ 40, 42 ], [ 44, 45 ] ] ]
6e5ac2906f3b824939ef60874819950ddb404ff8
2f72d621e6ec03b9ea243a96e8dd947a952da087
/src/dotSceneObject.cpp
9ea6d7cad79e1b67f338e16055a6105562fdb417
[]
no_license
gspu/lol4fg
752358c3c3431026ed025e8cb8777e4807eed7a0
12a08f3ef1126ce679ea05293fe35525065ab253
refs/heads/master
2023-04-30T05:32:03.826238
2011-07-23T23:35:14
2011-07-23T23:35:14
364,193,504
0
0
null
null
null
null
UTF-8
C++
false
false
24,168
cpp
#include "dotSceneObject.h" #include "tinyxml.h" #include "functions.h" dotSceneObject::dotSceneObject(Ogre::String filename, Level *lvl, Ogre::Vector3 pos, Ogre::Quaternion orient, Ogre::Vector3 scale) { TiXmlDocument *XMLDoc = 0; TiXmlElement *XMLRoot; mLevel = lvl; ID = filename; baseScale = Vector3::UNIT_SCALE; positionOffset = Vector3::ZERO; //OrientationOffset = Quatermion:: // collisionParams = Vector3::UNIT_SCALE; colType = CT_TREECOLLISIONSCENE; m_sGroupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME; type = GameObject::otDotScene; /*String uName;*/ try { DataStreamPtr pStream = ResourceGroupManager::getSingleton(). openResource( filename,m_sGroupName ); String data = pStream->getAsString(); // Open the .scene File XMLDoc = new TiXmlDocument(); XMLDoc->Parse( data.c_str() ); pStream->close(); pStream.setNull(); if( XMLDoc->Error() ) { //We'll just log, and continue on gracefully LogManager::getSingleton().logMessage("[dotSceneObject] The TiXmlDocument reported an error"); delete XMLDoc; //return; throw EX_CONSTR_FAILED; } } catch(...) { //We'll just log, and continue on gracefully LogManager::getSingleton().logMessage("[dotSceneObject] Error creating TiXmlDocument"); delete XMLDoc; //return; throw EX_CONSTR_FAILED; } // Validate the File XMLRoot = XMLDoc->RootElement(); if( String( XMLRoot->Value()) != "scene" ) { LogManager::getSingleton().logMessage( "[dotSceneObject] Error: Invalid .scene File. Missing <scene>" ); delete XMLDoc; //return; throw EX_CONSTR_FAILED; } mNode = mLevel->getSceneManager()->getRootSceneNode()->createChildSceneNode(); // Process the scene processScene(XMLRoot); mNode->scale(scale); // Close the XML File delete XMLDoc; mBody = makeBody(mLevel->getWorld(),colType,0, Vector3::ZERO,mNode); //if(colType != CT_TREECOLLISION && colType != CT_TREECOLLISIONSCENE) // mBody->setCustomForceAndTorqueCallback<Level>(&Level::LevelForceCallback,mLevel); // add the previous defined callback function as the body custom force and torque callback mBody->setPositionOrientation(pos,orient); mLevel->registerObject(this); } void dotSceneObject::finishConstructor() { } dotSceneObject::~dotSceneObject() { mLevel->unregisterObject(this); delete mBody; //destroyNode(mLevel->getSceneManager(),mNode); if(mArt) delete mArt; mSceneMgr->destroySceneNode(mNode->getName()); } void dotSceneObject::processScene(TiXmlElement *XMLRoot) { // Process the scene parameters String version = getAttrib(XMLRoot, "formatVersion", "unknown"); String message = "[dotSceneObject] Parsing dotScene file with version " + version; if(XMLRoot->Attribute("ID")) message += ", id " + String(XMLRoot->Attribute("ID")); if(XMLRoot->Attribute("sceneManager")) message += ", scene manager " + String(XMLRoot->Attribute("sceneManager")); if(XMLRoot->Attribute("minOgreVersion")) message += ", min. Ogre version " + String(XMLRoot->Attribute("minOgreVersion")); if(XMLRoot->Attribute("author")) message += ", author " + String(XMLRoot->Attribute("author")); LogManager::getSingleton().logMessage(message); TiXmlElement *pElement; // Process nodes (?) pElement = XMLRoot->FirstChildElement("nodes"); if(pElement) processNodes(pElement); // Process externals (?) pElement = XMLRoot->FirstChildElement("externals"); if(pElement) processExternals(pElement); // Process environment (?) pElement = XMLRoot->FirstChildElement("environment"); if(pElement) processEnvironment(pElement); // Process terrain (?) pElement = XMLRoot->FirstChildElement("terrain"); if(pElement) processTerrain(pElement); // Process userDataReference (?) pElement = XMLRoot->FirstChildElement("userDataReference"); if(pElement) processUserDataReference(pElement); // Process octree (?) pElement = XMLRoot->FirstChildElement("octree"); if(pElement) processOctree(pElement); // Process light (?) pElement = XMLRoot->FirstChildElement("light"); if(pElement) processLight(pElement); // Process camera (?) pElement = XMLRoot->FirstChildElement("camera"); if(pElement) processCamera(pElement); } void dotSceneObject::processNodes(TiXmlElement *XMLNode) { TiXmlElement *pElement; // Process node (*) pElement = XMLNode->FirstChildElement("node"); while(pElement) { processNode(pElement); pElement = pElement->NextSiblingElement("node"); } // Process position (?) pElement = XMLNode->FirstChildElement("position"); if(pElement) { //mAttachNode->setPosition(parseVector3(pElement)); positionOffset = parseVector3(pElement); //mAttachNode->setInitialState(); //mNode->setInitialState(); } // Process rotation (?) pElement = XMLNode->FirstChildElement("rotation"); if(pElement) { //mAttachNode->setOrientation(parseQuaternion(pElement)); //mAttachNode->setInitialState(); mNode->setOrientation(parseQuaternion(pElement)); mNode->setInitialState(); } // Process scale (?) pElement = XMLNode->FirstChildElement("scale"); if(pElement) { mNode->setScale(parseVector3(pElement)); mNode->setInitialState(); } } void dotSceneObject::processExternals(TiXmlElement *XMLNode) { //! @todo Implement this } void dotSceneObject::processEnvironment(TiXmlElement *XMLNode) { TiXmlElement *pElement; // Process fog (?) pElement = XMLNode->FirstChildElement("fog"); if(pElement) processFog(pElement); // Process skyBox (?) pElement = XMLNode->FirstChildElement("skyBox"); if(pElement) processSkyBox(pElement); // Process skyDome (?) pElement = XMLNode->FirstChildElement("skyDome"); if(pElement) processSkyDome(pElement); // Process skyPlane (?) pElement = XMLNode->FirstChildElement("skyPlane"); if(pElement) processSkyPlane(pElement); // Process clipping (?) pElement = XMLNode->FirstChildElement("clipping"); if(pElement) processClipping(pElement); // Process colourAmbient (?) pElement = XMLNode->FirstChildElement("colourAmbient"); if(pElement) mLevel->getSceneManager()->setAmbientLight(parseColour(pElement)); //// Process colourBackground (?) ////! @todo Set the background colour of all viewports (RenderWindow has to be provided then) //pElement = XMLNode->FirstChildElement("colourBackground"); //if(pElement) // ;//mLevel->getSceneManager()->set(parseColour(pElement)); // Process userDataReference (?) pElement = XMLNode->FirstChildElement("userDataReference"); if(pElement) processUserDataReference(pElement); } void dotSceneObject::processTerrain(TiXmlElement *XMLNode) { //! @todo Implement this } void dotSceneObject::processUserDataReference(TiXmlElement *XMLNode, SceneNode *pParent) { //! @todo Implement this } void dotSceneObject::processOctree(TiXmlElement *XMLNode) { //! @todo Implement this } void dotSceneObject::processLight(TiXmlElement *XMLNode, SceneNode *pParent) { // Process attributes String name = getAttrib(XMLNode, "name"); String id = getAttrib(XMLNode, "id"); // Create the light Light *pLight = mLevel->getSceneManager()->createLight(name); if(pParent) pParent->attachObject(pLight); else mNode->attachObject(pLight); String sValue = getAttrib(XMLNode, "type"); if(sValue == "point") pLight->setType(Light::LT_POINT); else if(sValue == "directional") pLight->setType(Light::LT_DIRECTIONAL); else if(sValue == "spot") pLight->setType(Light::LT_SPOTLIGHT); else if(sValue == "radPoint") pLight->setType(Light::LT_POINT); pLight->setVisible(getAttribBool(XMLNode, "visible", true)); pLight->setCastShadows(getAttribBool(XMLNode, "castShadows", true)); TiXmlElement *pElement; // Process position (?) pElement = XMLNode->FirstChildElement("position"); if(pElement) pLight->setPosition(parseVector3(pElement)); // Process normal (?) pElement = XMLNode->FirstChildElement("normal"); if(pElement) pLight->setDirection(parseVector3(pElement)); // Process colourDiffuse (?) pElement = XMLNode->FirstChildElement("colourDiffuse"); if(pElement) pLight->setDiffuseColour(parseColour(pElement)); // Process colourSpecular (?) pElement = XMLNode->FirstChildElement("colourSpecular"); if(pElement) pLight->setSpecularColour(parseColour(pElement)); // Process lightRange (?) pElement = XMLNode->FirstChildElement("lightRange"); if(pElement) processLightRange(pElement, pLight); // Process lightAttenuation (?) pElement = XMLNode->FirstChildElement("lightAttenuation"); if(pElement) processLightAttenuation(pElement, pLight); pLight->setUserAny(Any((GameObject*)this)); //// Process userDataReference (?) //pElement = XMLNode->FirstChildElement("userDataReference"); //if(pElement) // ;//processUserDataReference(pElement, pLight); } void dotSceneObject::processCamera(TiXmlElement *XMLNode, SceneNode *pParent) { //! @todo Implement this } void dotSceneObject::processNode(TiXmlElement *XMLNode, SceneNode *pParent) { // Construct the node's name String name = m_sPrependNode + getAttrib(XMLNode, "name"); // Create the scene node SceneNode *pNode; if(name.empty()) { // Let Ogre choose the name if(pParent) pNode = pParent->createChildSceneNode(); else pNode = mNode->createChildSceneNode(); } else { // Provide the name if(pParent) pNode = pParent->createChildSceneNode(name); else pNode = mNode->createChildSceneNode(name); } // Process other attributes String id = getAttrib(XMLNode, "id"); bool isTarget = getAttribBool(XMLNode, "isTarget"); TiXmlElement *pElement; // Process position (?) pElement = XMLNode->FirstChildElement("position"); if(pElement) { pNode->setPosition(parseVector3(pElement)); pNode->setInitialState(); } // Process rotation (?) pElement = XMLNode->FirstChildElement("rotation"); if(pElement) { pNode->setOrientation(parseQuaternion(pElement)); pNode->setInitialState(); } // Process scale (?) pElement = XMLNode->FirstChildElement("scale"); if(pElement) { pNode->setScale(parseVector3(pElement)); pNode->setInitialState(); } // Process lookTarget (?) pElement = XMLNode->FirstChildElement("lookTarget"); if(pElement) processLookTarget(pElement, pNode); // Process trackTarget (?) pElement = XMLNode->FirstChildElement("trackTarget"); if(pElement) processTrackTarget(pElement, pNode); // Process node (*) pElement = XMLNode->FirstChildElement("node"); while(pElement) { processNode(pElement, pNode); pElement = pElement->NextSiblingElement("node"); } // Process entity (*) pElement = XMLNode->FirstChildElement("entity"); while(pElement) { processEntity(pElement, pNode); pElement = pElement->NextSiblingElement("entity"); } // Process light (*) pElement = XMLNode->FirstChildElement("light"); while(pElement) { processLight(pElement, pNode); pElement = pElement->NextSiblingElement("light"); } // Process camera (*) pElement = XMLNode->FirstChildElement("camera"); while(pElement) { processCamera(pElement, pNode); pElement = pElement->NextSiblingElement("camera"); } // Process particleSystem (*) pElement = XMLNode->FirstChildElement("particleSystem"); while(pElement) { processParticleSystem(pElement, pNode); pElement = pElement->NextSiblingElement("particleSystem"); } // Process billboardSet (*) pElement = XMLNode->FirstChildElement("billboardSet"); while(pElement) { processBillboardSet(pElement, pNode); pElement = pElement->NextSiblingElement("billboardSet"); } // Process plane (*) pElement = XMLNode->FirstChildElement("plane"); while(pElement) { processPlane(pElement, pNode); pElement = pElement->NextSiblingElement("plane"); } // Process userDataReference (?) pElement = XMLNode->FirstChildElement("userDataReference"); if(pElement) processUserDataReference(pElement, pNode); } void dotSceneObject::processLookTarget(TiXmlElement *XMLNode, SceneNode *pParent) { //! @todo Is this correct? Cause I don't have a clue actually // Process attributes String nodeName = getAttrib(XMLNode, "nodeName"); Node::TransformSpace relativeTo = Node::TS_PARENT; String sValue = getAttrib(XMLNode, "relativeTo"); if(sValue == "local") relativeTo = Node::TS_LOCAL; else if(sValue == "parent") relativeTo = Node::TS_PARENT; else if(sValue == "world") relativeTo = Node::TS_WORLD; TiXmlElement *pElement; // Process position (?) Vector3 position; pElement = XMLNode->FirstChildElement("position"); if(pElement) position = parseVector3(pElement); // Process localDirection (?) Vector3 localDirection = Vector3::NEGATIVE_UNIT_Z; pElement = XMLNode->FirstChildElement("localDirection"); if(pElement) localDirection = parseVector3(pElement); // Setup the look target try { if(!nodeName.empty()) { SceneNode *pLookNode = mLevel->getSceneManager()->getSceneNode(nodeName); position = pLookNode->_getDerivedPosition(); } pParent->lookAt(position, relativeTo, localDirection); } catch(Ogre::Exception &/*e*/) { LogManager::getSingleton().logMessage("[dotSceneObject] Error processing a look target!"); } } void dotSceneObject::processTrackTarget(TiXmlElement *XMLNode, SceneNode *pParent) { // Process attributes String nodeName = getAttrib(XMLNode, "nodeName"); TiXmlElement *pElement; // Process localDirection (?) Vector3 localDirection = Vector3::NEGATIVE_UNIT_Z; pElement = XMLNode->FirstChildElement("localDirection"); if(pElement) localDirection = parseVector3(pElement); // Process offset (?) Vector3 offset = Vector3::ZERO; pElement = XMLNode->FirstChildElement("offset"); if(pElement) offset = parseVector3(pElement); // Setup the track target try { SceneNode *pTrackNode = mLevel->getSceneManager()->getSceneNode(nodeName); pParent->setAutoTracking(true, pTrackNode, localDirection, offset); } catch(Ogre::Exception &/*e*/) { LogManager::getSingleton().logMessage("[dotSceneObject] Error processing a track target!"); } } void dotSceneObject::processEntity(TiXmlElement *XMLNode, SceneNode *pParent) { // Process attributes String name = getAttrib(XMLNode, "name"); String id = getAttrib(XMLNode, "id"); String meshFile = getAttrib(XMLNode, "meshFile"); String materialFile = getAttrib(XMLNode, "materialFile"); bool isStatic = getAttribBool(XMLNode, "static", false);; bool castShadows = getAttribBool(XMLNode, "castShadows", true); // TEMP: Maintain a list of static and dynamic objects /*if(isStatic) staticObjects.push_back(name); else dynamicObjects.push_back(name);*/ TiXmlElement *pElement; // Process vertexBuffer (?) //pElement = XMLNode->FirstChildElement("vertexBuffer"); //if(pElement) // ;//processVertexBuffer(pElement); //// Process indexBuffer (?) //pElement = XMLNode->FirstChildElement("indexBuffer"); //if(pElement) // ;//processIndexBuffer(pElement); // Create the entity Entity *pEntity = 0; try { MeshManager::getSingleton().load(meshFile , m_sGroupName); pEntity = mLevel->getSceneManager()->createEntity(name, meshFile); pEntity->setCastShadows(castShadows); pParent->attachObject(pEntity); pEntity->setUserAny(Any((GameObject*)this)); if(!materialFile.empty()) pEntity->setMaterialName(materialFile); } catch(Ogre::Exception &/*e*/) { LogManager::getSingleton().logMessage("[dotSceneObject] Error loading an entity!"); } // Process userDataReference (?) pElement = XMLNode->FirstChildElement("userDataReference"); if(pElement) processUserDataReference(pElement, pEntity); pEntity->setUserAny(Any((GameObject*)this)); } void dotSceneObject::processParticleSystem(TiXmlElement *XMLNode, SceneNode *pParent) { // Process attributes String name = getAttrib(XMLNode, "name"); String id = getAttrib(XMLNode, "id"); String file = getAttrib(XMLNode, "file"); // Create the particle system try { ParticleSystem *pParticles = mLevel->getSceneManager()->createParticleSystem(name, file); pParent->attachObject(pParticles); pParticles->setUserAny(Any((GameObject*)this)); } catch(Ogre::Exception &/*e*/) { LogManager::getSingleton().logMessage("[dotSceneObject] Error creating a particle system!"); } } void dotSceneObject::processBillboardSet(TiXmlElement *XMLNode, SceneNode *pParent) { //! @todo Implement this } void dotSceneObject::processPlane(TiXmlElement *XMLNode, SceneNode *pParent) { //! @todo Implement this } void dotSceneObject::processFog(TiXmlElement *XMLNode) { //// Process attributes //Real expDensity = getAttribReal(XMLNode, "expDensity", 0.001); //Real linearStart = getAttribReal(XMLNode, "linearStart", 0.0); //Real linearEnd = getAttribReal(XMLNode, "linearEnd", 1.0); //FogMode mode = FOG_NONE; //String sMode = getAttrib(XMLNode, "mode"); //if(sMode == "none") // mode = FOG_NONE; //else if(sMode == "exp") // mode = FOG_EXP; //else if(sMode == "exp2") // mode = FOG_EXP2; //else if(sMode == "linear") // mode = FOG_LINEAR; //TiXmlElement *pElement; //// Process colourDiffuse (?) //ColourValue colourDiffuse = ColourValue::White; //pElement = XMLNode->FirstChildElement("colourDiffuse"); //if(pElement) // colourDiffuse = parseColour(pElement); //// Setup the fog //mLevel->getSceneManager()->setFog(mode, colourDiffuse, expDensity, linearStart, linearEnd); } void dotSceneObject::processSkyBox(TiXmlElement *XMLNode) { //// Process attributes //String material = getAttrib(XMLNode, "material"); //Real distance = getAttribReal(XMLNode, "distance", 5000); //bool drawFirst = getAttribBool(XMLNode, "drawFirst", true); //TiXmlElement *pElement; //// Process rotation (?) //Quaternion rotation = Quaternion::IDENTITY; //pElement = XMLNode->FirstChildElement("rotation"); //if(pElement) // rotation = parseQuaternion(pElement); //// Setup the sky box //mLevel->getSceneManager()->setSkyBox(true, material, distance, drawFirst, rotation, m_sGroupName); } void dotSceneObject::processSkyDome(TiXmlElement *XMLNode) { //// Process attributes //String material = XMLNode->Attribute("material"); //Real curvature = getAttribReal(XMLNode, "curvature", 10); //Real tiling = getAttribReal(XMLNode, "tiling", 8); //Real distance = getAttribReal(XMLNode, "distance", 4000); //bool drawFirst = getAttribBool(XMLNode, "drawFirst", true); //TiXmlElement *pElement; //// Process rotation (?) //Quaternion rotation = Quaternion::IDENTITY; //pElement = XMLNode->FirstChildElement("rotation"); //if(pElement) // rotation = parseQuaternion(pElement); //// Setup the sky dome //mLevel->getSceneManager()->setSkyDome(true, material, curvature, tiling, distance, drawFirst, rotation, 16, 16, -1, m_sGroupName); } void dotSceneObject::processSkyPlane(TiXmlElement *XMLNode) { //// Process attributes //String material = getAttrib(XMLNode, "material"); //Real planeX = getAttribReal(XMLNode, "planeX", 0); //Real planeY = getAttribReal(XMLNode, "planeY", -1); //Real planeZ = getAttribReal(XMLNode, "planeX", 0); //Real planeD = getAttribReal(XMLNode, "planeD", 5000); //Real scale = getAttribReal(XMLNode, "scale", 1000); //Real bow = getAttribReal(XMLNode, "bow", 0); //Real tiling = getAttribReal(XMLNode, "tiling", 10); //bool drawFirst = getAttribBool(XMLNode, "drawFirst", true); //// Setup the sky plane //Plane plane; //plane.normal = Vector3(planeX, planeY, planeZ); //plane.d = planeD; //mLevel->getSceneManager()->setSkyPlane(true, plane, material, scale, tiling, drawFirst, bow, 1, 1, m_sGroupName); } void dotSceneObject::processClipping(TiXmlElement *XMLNode) { //! @todo Implement this // Process attributes Real fNear = getAttribReal(XMLNode, "near", 0); Real fFar = getAttribReal(XMLNode, "far", 1); } void dotSceneObject::processLightRange(TiXmlElement *XMLNode, Light *pLight) { // Process attributes Real inner = getAttribReal(XMLNode, "inner"); Real outer = getAttribReal(XMLNode, "outer"); Real falloff = getAttribReal(XMLNode, "falloff", 1.0); // Setup the light range pLight->setSpotlightRange(Angle(inner), Angle(outer), falloff); } void dotSceneObject::processLightAttenuation(TiXmlElement *XMLNode, Light *pLight) { // Process attributes Real range = getAttribReal(XMLNode, "range"); Real constant = getAttribReal(XMLNode, "constant"); Real linear = getAttribReal(XMLNode, "linear"); Real quadratic = getAttribReal(XMLNode, "quadratic"); // Setup the light attenuation pLight->setAttenuation(range, constant, linear, quadratic); } String dotSceneObject::getAttrib(TiXmlElement *XMLNode, const String &attrib, const String &defaultValue) { if(XMLNode->Attribute(attrib.c_str())) return XMLNode->Attribute(attrib.c_str()); else return defaultValue; } Real dotSceneObject::getAttribReal(TiXmlElement *XMLNode, const String &attrib, Real defaultValue) { if(XMLNode->Attribute(attrib.c_str())) return StringConverter::parseReal(XMLNode->Attribute(attrib.c_str())); else return defaultValue; } bool dotSceneObject::getAttribBool(TiXmlElement *XMLNode, const String &attrib, bool defaultValue) { if(!XMLNode->Attribute(attrib.c_str())) return defaultValue; if(String(XMLNode->Attribute(attrib.c_str())) == "true") return true; return false; } Vector3 dotSceneObject::parseVector3(TiXmlElement *XMLNode) { return Vector3( StringConverter::parseReal(XMLNode->Attribute("x")), StringConverter::parseReal(XMLNode->Attribute("y")), StringConverter::parseReal(XMLNode->Attribute("z")) ); } Quaternion dotSceneObject::parseQuaternion(TiXmlElement *XMLNode) { //! @todo Fix this shit! Quaternion orientation; if(XMLNode->Attribute("qx")) { orientation.x = StringConverter::parseReal(XMLNode->Attribute("qx")); orientation.y = StringConverter::parseReal(XMLNode->Attribute("qy")); orientation.z = StringConverter::parseReal(XMLNode->Attribute("qz")); orientation.w = StringConverter::parseReal(XMLNode->Attribute("qw")); } else if(XMLNode->Attribute("axisX")) { Vector3 axis; axis.x = StringConverter::parseReal(XMLNode->Attribute("axisX")); axis.y = StringConverter::parseReal(XMLNode->Attribute("axisY")); axis.z = StringConverter::parseReal(XMLNode->Attribute("axisZ")); Real angle = StringConverter::parseReal(XMLNode->Attribute("angle"));; orientation.FromAngleAxis(Ogre::Angle(angle), axis); } else if(XMLNode->Attribute("angleX")) { Vector3 axis; axis.x = StringConverter::parseReal(XMLNode->Attribute("angleX")); axis.y = StringConverter::parseReal(XMLNode->Attribute("angleY")); axis.z = StringConverter::parseReal(XMLNode->Attribute("angleZ")); //orientation.FromAxes(&axis); //orientation.F } return orientation; } ColourValue dotSceneObject::parseColour(TiXmlElement *XMLNode) { return ColourValue( StringConverter::parseReal(XMLNode->Attribute("r")), StringConverter::parseReal(XMLNode->Attribute("g")), StringConverter::parseReal(XMLNode->Attribute("b")), XMLNode->Attribute("a") != NULL ? StringConverter::parseReal(XMLNode->Attribute("a")) : 1 ); } //String dotSceneObject::getProperty(const String &ndNm, const String &prop) //{ // for ( unsigned int i = 0 ; i < nodeProperties.size(); i++ ) // { // if ( nodeProperties[i].nodeName == ndNm && nodeProperties[i].propertyNm == prop ) // { // return nodeProperties[i].valueName; // } // } // // return ""; //} void dotSceneObject::processUserDataReference(TiXmlElement *XMLNode, Entity *pEntity) { String str = XMLNode->Attribute("id"); pEntity->setUserAny(Any(str)); }
[ "praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac" ]
[ [ [ 1, 849 ] ] ]
71325854d90258327ecd88b5f59d6814de3deb44
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/skin/test/kPad_src/stdafx.cpp
7643def94a9771fd3b425e2df85b6edf6640831f
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
// stdafx.cpp : source file that includes just the standard includes // kPad.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #include <atlimpl.cpp>
[ "zhongzeng@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 7 ] ] ]
886b95b7920a31c078729ab3ce671ef570070ac2
41c264ec05b297caa2a6e05e4476ce0576a8d7a9
/OpenHoldem/DialogSAPrefs4.h
1c3397626f78ec7951ef04578c8523d8db92f0ff
[]
no_license
seawei/openholdem
cf19a90911903d7f4d07f956756bd7e521609af3
ba408c835b71dc1a9d674eee32958b69090fb86c
refs/heads/master
2020-12-25T05:40:09.628277
2009-01-25T01:17:10
2009-01-25T01:17:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
#ifndef INC_DIALOGSAPREFS4_H #define INC_DIALOGSAPREFS4_H #include "resource.h" // CDlgSAPrefs4 dialog class CDlgSAPrefs4 : public CSAPrefsSubDlg { DECLARE_DYNAMIC(CDlgSAPrefs4) public: CDlgSAPrefs4(CWnd* pParent = NULL); // standard constructor virtual ~CDlgSAPrefs4(); // Dialog Data enum { IDD = IDD_SAPREFS4 }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: CEdit m_ScrapeDelay; CSpinButtonCtrl m_ScrapeDelay_Spin; virtual BOOL OnInitDialog(); protected: virtual void OnOK(); public: afx_msg void OnDeltaposScrapedelaySpin(NMHDR *pNMHDR, LRESULT *pResult); }; #endif //INC_DIALOGSAPREFS4_H
[ [ [ 1, 36 ] ] ]
3fc9714253dd82c5b7f62ffd4536ac14f25ced96
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-wx/Plugins/FBIdePlugin/LexFreeBasic_tmp.cxx
f7ffd09fa1fba15a67bfe0be42df716a4258c651
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,286
cxx
/* * This file is part of FBIde project * * FBIde 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. * * FBIde 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 FBIde. If not, see <http://www.gnu.org/licenses/>. * * Author: Albert Varaksin <[email protected]> * Copyright (C) The FBIde development team */ /** * @todo When macro or asm block is closed line is highlighted to the end * of the line. However ':' character should revert to previous * section style * * @todo asm /' ... \n ... '/ should decide is there a single line * asm block or multiline. Implement methods "ResolveMultiLineComment" * * @todo Reseolve line continuation for ASM blocks * asm _ \n could be either one liner or a multiline * * @todo end (asm|if|while|...) matching. in keyword list have end+asm * or something * * @todo end /' ... \n ... '/ asm should work. as well as * end _ \n asm * * @todo asm and macro block nesting * * @todo highlight code blocks that have background based on * indentation. (looks mich nicer with nested blocks) * * @todo implement options to disable certain highlighting features * escape sequences, block highlighting, ... */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #include "wx_pch.h" #include "LexFreeBasic.hxx" using namespace LEX; /** * Allowed URI Schemes inside comments. * case insensitive. */ static const char * URI_SCHEMES[] = { "http://", "https://", "ftp://", "www.", 0 }; /** * Allowed (2 char long) escape codes inside strings * preceded by \ * case sensitive! */ const char ESCAPE_CODES[] = { 'a', // beep 'b', // backspace 'f', // formfeed 'l', 'n', // new line 'r', // carriage return 't', // tab 'v', // vertical tab '\\', // backslash '"', // double quote '\'', // single quote 0 }; // Set bit flags static inline void SET_FLAG (int & value, int flag) { value |= flag; } // unset bit flags static inline void UNSET_FLAG (int & value, int flag) { value &= (~flag); } // toggle bit flags static inline void TOGGLE_FLAG (int & value, int flag) { value ^= flag; } /** * Highlight fb source code */ struct CFbSourceLexer { /** * Construct the lexer object */ CFbSourceLexer (StyleContext &sc, Accessor &styler, WordList *keywords[]) : m_sc(sc), m_styler(styler), m_keywords(keywords), m_section(0), m_lineState(0), m_curNcLevel(0), m_curNppLevel(0), m_visibleChars(0), m_skipForward(false) { // setup the state m_dialect = styler.GetPropertyInt("dialect", LEX::DIALECT_FB); m_curLine = styler.GetLine(m_sc.currentPos); // if not the first line then get the state of // the previous line. if (m_curLine > 0) { m_lineState = m_styler.GetLineState(m_curLine-1); m_curNcLevel = m_lineState & 0xFF; m_curNppLevel= (m_lineState >> 8) & 0xFF; } // Colorise the document Parse (); } /** * Parse the syntax */ void Parse () { // iterate through the text while (m_sc.More()) { // handle line starts if (m_sc.atLineStart) { m_curLine = m_styler.GetLine(m_sc.currentPos); m_lineState = m_curLine ? m_styler.GetLineState(m_curLine-1) : 0; m_section = GetSectionType (m_sc.state); ParseLineStart (); // do not reset if is a multiline comment if (m_curNcLevel == 0) m_visibleChars = 0; } // handle non default states (comments, strings, ...) if (!IsInDefaultSection(m_sc.state)) { m_section = GetSectionType (m_sc.state); ParseState (); } // handle default states (fb, asm, pp) if (IsInDefaultSection(m_sc.state)) { m_section = GetSectionType (m_sc.state); ParseDefault (); } // handle line ends. if (m_sc.atLineEnd) { m_section = GetSectionType (m_sc.state); ParseLineEnd (); } else { if (!IsInAnyComment(m_sc.state) && !IsASpaceOrTab(m_sc.ch)) m_visibleChars++; } // skip call to m_sc.Forward() ? if (m_skipForward) { m_skipForward = false; continue; } m_sc.Forward(); } // finalize m_sc.Complete(); } /** * Handle the line beginning */ void ParseLineStart () { Log("<<< ParseLineStart : m_section=%d", m_section); Log("<<< ParseLineStart : m_lineState=%d", m_lineState); if (m_curNcLevel > 0) { m_sc.SetState(m_section + FB_COMMENT); } else if (IsInComment(m_sc.state)) { m_sc.SetState(m_section); } else if (m_section == PP_DEFAULT) { if (m_lineState & LINESTATE_LINE_CONTINUATION) { UNSET_FLAG(m_lineState, LINESTATE_LINE_CONTINUATION); m_sc.SetState(PP_DEFAULT); } else { if (m_curNppLevel==0) m_sc.SetState(GetPrevSectionType()); } } else if (m_lineState & LINESTATE_MULTILINE_ASM) { m_sc.SetState(ASM_DEFAULT); } else if (m_section == ASM_DEFAULT) { if (m_lineState & LINESTATE_LINE_CONTINUATION) { UNSET_FLAG(m_lineState, LINESTATE_LINE_CONTINUATION); m_sc.SetState(ASM_DEFAULT); } else { m_sc.SetState(GetPrevSectionType()); } } else m_sc.SetState(FB_DEFAULT); } /** * Parse the state indicated in m_sc.state * that is not default */ void ParseState () { // multiline comment if (IsInAnyComment(m_sc.state)) ParseComment(); else if (IsInString(m_sc.state)) ParseString(); } /** * Parse default state */ void ParseDefault () { // a single line comment. at line start may be followed // by QB style metacommand if (m_sc.ch == '\'') { m_sc.SetState(m_section + FB_COMMENT); if (m_visibleChars==0) { m_sc.Forward(); SkipSpacesAndTabs(); ParseSingleLineComment(); } } // single line comment using REM keyword. At line start // can be followed by metacommand else if (!IsAWordChar(m_sc.GetRelative(3)) && m_sc.Match("rem")) { m_sc.SetState(m_section + GetFbKeywordType("rem", FB_COMMENT)); m_sc.Forward(3); m_sc.SetState(m_section + FB_COMMENT); if (m_visibleChars==0 && IsASpaceOrTab(m_sc.ch)) { SkipSpacesAndTabs(); m_sc.SetState(m_section + FB_COMMENT); ParseSingleLineComment(); } } // multiline comment. Can be nested! else if (m_sc.Match('/', '\'')) { m_sc.SetState(m_section + FB_COMMENT); m_curNcLevel++; m_sc.Forward(); } // string literals else if (m_sc.ch == '"') { if (m_dialect <= DIALECT_LITE) { if (m_styler.GetPropertyInt("option.escape", false)) { m_lineState |= LINESTATE_ESCAPE_STRING; } } m_sc.SetState(m_section + FB_STRING); } // explicitly NON escaped string literal else if (m_sc.Match('$', '"')) { m_sc.SetState(m_section + FB_STRING); m_sc.Forward(); } // explicitly escaped string literal else if (m_sc.Match('!', '"')) { m_lineState |= LINESTATE_ESCAPE_STRING; m_sc.SetState(m_section + FB_STRING); m_sc.Forward(); } // macro else if (m_sc.Match('#') && m_visibleChars == 0) { ParsePreprocessor (); } // decimal or floating point number else if (IsADigit(m_sc.ch) || (m_sc.ch == '.' && IsADigit(m_sc.chNext) && !IsADigit(m_sc.chPrev)) ) { ParseNumber(10); } // hex number else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'h') { m_sc.Forward(2); ParseNumber(16); } // octal number else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'o') { m_sc.Forward(2); ParseNumber(8); } // binary number else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'b') { m_sc.Forward(2); ParseNumber(2); } // is a asm block start ? else if (m_section != ASM_DEFAULT && !IsAWordChar(m_sc.GetRelative(3)) && m_sc.Match("asm")) { m_skipForward = true; m_sc.SetState(ASM_DEFAULT + GetFbKeywordType("asm")); m_sc.Forward(3); m_sc.SetState(ASM_DEFAULT); m_visibleChars+=3; SkipSpacesAndTabs(); if (!m_sc.atLineEnd) m_skipForward = true; if (!IsAWordChar(m_sc.ch) && (!m_sc.MatchIgnoreCase("rem") || !IsAWordChar(m_sc.GetRelative(3)) )) { m_lineState |= LINESTATE_MULTILINE_ASM; } } // is a asm block start ? else if (m_section == ASM_DEFAULT && (m_lineState & LINESTATE_MULTILINE_ASM) && !IsAWordChar(m_sc.GetRelative(3)) && m_sc.Match("end")) { char nw[4]; GetNextInput(m_sc.currentPos+4, nw, 4); if (GetNextInput(m_sc.currentPos+4, nw, 4) && (strcmpi(nw, "asm") == 0)) { m_sc.SetState(m_section + GetFbKeywordType("end")); m_sc.Forward(3); m_sc.SetState(m_section); SkipSpacesAndTabs(); m_sc.SetState(m_section + GetFbKeywordType("asm")); m_sc.Forward(3); m_sc.SetState(m_section); UNSET_FLAG(m_lineState, LINESTATE_MULTILINE_ASM); } } // Is a line continuation else if (m_sc.ch == '_' && !IsAWordChar(m_sc.chNext) && !IsAWordChar(m_sc.chPrev) ) { //m_visibleChars = 0; m_lineState |= LINESTATE_LINE_CONTINUATION; m_sc.SetState(m_section); // if (m_section == PP_DEFAULT) } // command seperator else if (m_sc.ch == ':') { // set to minus one because it will be incremented // at next at next iteration anyway m_visibleChars = -1; m_sc.SetState(m_section); } // a keyword or an identifier else if (IsAWordChar(m_sc.ch)) { // m_sc.SetState(PP_DEFAULT); int curPos = m_sc.currentPos; // skip the word chars? while (!m_sc.atLineEnd && IsAWordChar(m_sc.ch)) { m_sc.Forward(); m_skipForward = true; m_visibleChars++; } char s[25]; getRange(curPos, m_sc.currentPos-1, s, sizeof(s)); if (m_section == ASM_DEFAULT) { m_sc.ChangeState(GetAsmKeywordType(s)); } else { if (m_section == PP_DEFAULT && strcmpi(s, "once") == 0) { m_sc.ChangeState(GetPpKeywordStyle("once")); } else { m_sc.ChangeState(m_section + GetFbKeywordType(s)); } } m_sc.SetState(m_section); } else if (IsOperator(m_sc.ch)) { m_sc.SetState(m_section + FB_OPERATOR); while ( IsOperator(m_sc.ch) && !m_sc.Match('/', '\'') && (m_sc.ch != '.' || !IsADigit(m_sc.chNext, 10)) ) { m_sc.Forward(); m_skipForward = true; m_visibleChars++; } m_sc.SetState(m_section); } } /** * Handle the line end */ void ParseLineEnd () { // set to default section so proper section background // colour could fill the screen as needed. // in case of multiline non-default styles they // will be continued in ParseLineStart if (!IsInComment(m_sc.state)) m_sc.SetState(m_section); Log(">>> ParseLineEnd : m_section=%d", m_section); Log(">>> ParseLineEnd : m_lineState=%d", m_lineState); // set comment nest level m_lineState = (m_lineState & 0xFFFFFF00) | m_curNcLevel; m_lineState = (m_lineState & 0xFFFF00FF) | (m_curNppLevel<<8); // set current line state m_styler.SetLineState(m_curLine, m_lineState); } /** * Check if the char is a valid FB operator */ bool IsOperator (int ch) { return ch == '&' || ch == '*' || ch == '(' || ch == ')' || ch == '-' || ch == '+' || ch == '=' || ch == '{' || ch == '}' || ch == '[' || ch == ']' || ch == ':' || ch == ';' || ch == '@' || ch == '#' || ch == '\\' || ch == ',' || ch == '<' || ch == '>' || ch == '.' || ch == '/' || ch == '?' ; } /** * Parse number */ bool ParseNumber (int base) { // m_sc.SetState(PP_DEFAULT); int curPos = m_sc.currentPos; int fpCount = 0; // skip the word chars? while (!m_sc.atLineEnd && (IsADigit(m_sc.ch, base) || (m_sc.ch == '.' && base == 10 && !(fpCount++))) ) { m_sc.Forward(); m_skipForward = true; m_visibleChars++; } char s[25]; getRange(curPos, m_sc.currentPos-1, s, sizeof(s)); m_sc.ChangeState(m_section + FB_NUMBER); m_sc.SetState(m_section); return true; } /** * Retreave a range of characters into a string */ void getRange(unsigned int start, unsigned int end, char *s, unsigned int len) { unsigned int i = 0; while ((i < end - start + 1) && (i < len-1)) { s[i] = static_cast<char>(tolower(m_styler[start + i])); i++; } s[i] = '\0'; } /** * Get non whitespace range for the lenght * skip any spaces or tabs and return when hitting first * non-printable character (space, tab, newline) */ bool GetNextInput (unsigned int start, char *s, unsigned int len) { unsigned int i = 0; s[i] = '\0'; // skip any spaces or tabs for ( ; ; start++) { char ch = m_styler[start]; if (IsAWordChar(ch)) break; if (ch == '\n' || ch == '\r') return false; } getRange (start, start + len, s, len); return true; } /** * Parse preprocessor block beginning. */ void ParsePreprocessor () { m_sc.SetState(PP_DEFAULT); m_sc.Forward(); SkipSpacesAndTabs(); if (m_sc.atLineEnd) return; m_skipForward = true; // macro's can nest and cover multiple lines if (m_sc.MatchIgnoreCase("macro")) { m_curNppLevel++; m_sc.ChangeState(GetPpKeywordStyle("macro")); m_sc.Forward(5); m_sc.SetState(PP_DEFAULT); } else if (m_sc.MatchIgnoreCase("endmacro")) { if (m_curNppLevel) m_curNppLevel--; m_sc.ChangeState(GetPpKeywordStyle("endmacro")); m_sc.Forward(8); if (m_curNppLevel) { m_sc.SetState(PP_DEFAULT); // try to style till the end of the line. // looks better. } else { /// @todo figure out if it is inside ASM block or not //m_sc.SetState(FB_DEFAULT); // try to style till the end of the line. // looks better. m_sc.SetState(PP_DEFAULT); } m_skipForward = true; } else if (IsAWordChar(m_sc.ch)) { // m_sc.SetState(PP_DEFAULT); int curPos = m_sc.currentPos; // skip the word chars? while (!m_sc.atLineEnd && IsAWordChar(m_sc.ch)) { m_sc.Forward(); } char s[25]; // m_sc.GetCurrent(s, sizeof(s)); getRange(curPos, m_sc.currentPos-1, s, sizeof(s)); m_sc.ChangeState(GetPpKeywordStyle(s)); m_sc.SetState(PP_DEFAULT); } } /** * Parse string literals */ void ParseString () { if (m_sc.Match('"', '"')) { m_sc.SetState(m_section+FB_STRING_ESCAPE); m_sc.Forward(2); m_sc.SetState(m_section+FB_STRING); } else if (m_sc.Match('"')) { m_sc.Forward(); m_sc.SetState(m_section); m_lineState &= (~LINESTATE_ESCAPE_STRING); return; } // not an escape code int indStart = m_sc.currentPos; bool matched = false; if (m_sc.ch != '\\' || !(m_lineState & LINESTATE_ESCAPE_STRING)) return; m_sc.SetState(m_section+FB_STRING_ESCAPE); m_sc.Forward(); // Simple sequences (case sensitive!) if (FindMatch(ESCAPE_CODES)) { m_sc.ForwardSetState(m_section+FB_STRING); matched = true; } // unicode char in hex \uFFFF else if (tolower(m_sc.ch) == 'u' && IsNumberRange(1, 4, 16)) { m_sc.ForwardSetState(m_section+FB_NUMBER); m_sc.Forward(4); matched = true; } // ascii char in decimal \123 else if (IsNumberRange(0, 3, 10)) { m_sc.SetState(m_section+FB_NUMBER); m_sc.Forward(3); matched = true; } // ascii escape sequence in FB style oct, bin or hex else if (m_sc.ch == '&') { m_sc.SetState(m_section+FB_NUMBER); m_sc.Forward(); // ascii char in hex \&hFF if (tolower(m_sc.ch) == 'h' && IsNumberRange(1, 2, 16)) { m_sc.Forward(3); matched = true; } // ascii char in octal \&o777 else if (tolower(m_sc.ch) == 'o' && IsNumberRange(1, 3, 8)) { m_sc.Forward(4); matched = true; } // ascii char in binary \&b11111111 else if (tolower(m_sc.ch) == 'b' && IsNumberRange(1, 8, 2)) { m_sc.Forward(9); matched = true; } else { m_sc.ChangeState(m_section+FB_STRING); } } // clear or set error indicator m_styler.IndicatorFill(indStart, m_sc.currentPos, 0, matched ? 0 : 1); // set back to string m_sc.SetState(m_section+FB_STRING); m_skipForward = true; } /** * Check if range of characters are numbers of the base */ bool IsNumberRange (int startPos, int count, int base) { for (--count; count>=0; count--) { Log("count=%d", count); if (!IsADigit(m_sc.GetRelative(startPos+count), base)) return false; } return true; } /** * Parses single line qomment and checks if contains * any meta keywords (lang, dynamic, static, ...) * if yes then set style to PP_DEFAULT, highlight the keyword * and return true. */ void ParseSingleLineComment () { // check if is valid start ? if (m_sc.atLineEnd || m_sc.ch != '$') goto meta_error; // mov forth and skip any spaces m_sc.Forward(); SkipSpacesAndTabs (); if (m_sc.atLineEnd) goto meta_error; // check if this is a valid meta statament if (HighlightMetaKeyword("lang", 4)) return; // allowed only in QB and LITE if (m_dialect > DIALECT_LITE) goto meta_error; // include if (HighlightMetaKeyword("include", 7)) return; // dynamic if (HighlightMetaKeyword("dynamic", 7)) return; // static if (HighlightMetaKeyword("static", 6)) return; // avoid call to Forward by Parse() since we already // moved forward. meta_error: m_skipForward = true; return; } /** * Parse the comments and look for urls inside */ void ParseComment () { // if this is a nested comment check if it ends ? if (m_curNcLevel) { if (m_sc.Match('\'', '/')) { if (m_curNcLevel) m_curNcLevel--; m_sc.Forward(2); if (m_curNcLevel == 0) { //SkipSpacesAndTabs(); //if (!m_sc.atLineEnd) //{ m_sc.SetState(m_section); //} return; } } else if (m_sc.Match('/', '\'')) { m_curNcLevel++; m_sc.Forward(2); } } if (IsInCommentUrl(m_sc.state)) { if (IsASpaceOrTab(m_sc.ch) || m_sc.atLineEnd) m_sc.SetState(m_section + FB_COMMENT); } else { // needs a non word char infornt if (IsAWordChar(m_sc.chPrev)) return; // match uri schemes. if matched then set state if (int len = FindMatch(URI_SCHEMES)) { m_sc.SetState(m_section + FB_COMMENT_URL); m_sc.Forward(len); } } } /** * Hightlight a QB style metakeyword inside single * line comments if matches * return true if matched. */ bool HighlightMetaKeyword (const char * kw, int len) { // return if not matches or next char is a word char if (IsAWordChar(m_sc.GetRelative(len)) || !m_sc.MatchIgnoreCase(kw)) return false; // colorise m_sc.Forward(len); m_sc.ChangeState(GetPpKeywordStyle(kw)); m_sc.SetState(PP_DEFAULT); return true; } /** * If the given keyword is a preprocessor keyword then * highlight it to appropriate PP keyword style */ int GetPpKeywordStyle (const char * kw) { if (m_keywords[KEYWORD_PP_ONE]->InList(kw)) return PP_KEYWORD_ONE; else if (m_keywords[KEYWORD_PP_ONE]->InList(kw)) return PP_KEYWORD_TWO; return PP_IDENTIFIER; } /** * Get FB keyword type. If not found FB_IDENTIFIER is returned */ int GetFbKeywordType (const char * kw, int defStyle = FB_IDENTIFIER) { if (m_keywords[KEYWORD_ONE]->InList(kw)) return FB_KEYWORD_ONE; else if (m_keywords[KEYWORD_TWO]->InList(kw)) return FB_KEYWORD_TWO; else if (m_keywords[KEYWORD_THREE]->InList(kw)) return FB_KEYWORD_THREE; else if (m_keywords[KEYWORD_FOUR]->InList(kw)) return FB_KEYWORD_FOUR; return defStyle; } /** * Get ASM block keyword type */ int GetAsmKeywordType (const char * kw, int defStyle = ASM_IDENTIFIER) { if (m_keywords[KEYWORD_ASM_ONE]->InList(kw)) return ASM_KEYWORD_ONE; else if (m_keywords[KEYWORD_ASM_TWO]->InList(kw)) return ASM_KEYWORD_TWO; return defStyle; } /** * Printf compatible function that will output to wxMessageLog */ void Log (const char * msg, ...) __attribute__((format(printf, 2, 3))) { // do thr printf va_list ap; va_start(ap, msg); char temp[4096]; vsnprintf (temp, 4096, msg, ap); va_end(ap); // output the wxLog wxString logMsg(temp, wxConvUTF8); wxLogMessage(logMsg); } /** * Get Section type */ int GetSectionType (int style) { if (style <= FB_SECTION_LAST) return SECTION_FB; if (style <= ASM_SECTION_LAST) return SECTION_ASM; if (style <= PP_SECTION_LAST) return SECTION_PP; return SECTION_FB; } /** * Find previous section */ int GetPrevSectionType () { int p = m_sc.currentPos; if (!p) return FB_DEFAULT; while (--p) { int prevSection = GetSectionType(m_styler.StyleAt(p)); if (prevSection != m_section) return prevSection; } return SECTION_FB; } /** * Skip the tabs and spaces * but stop at anything else */ void SkipSpacesAndTabs () { while (!m_sc.atLineEnd && IsASpaceOrTab(m_sc.ch)) m_sc.Forward(); } /** * Extended to accept accented characters */ bool IsAWordChar(int ch) { return ch >= 0x80 || (isalnum(ch) || ch == '.' || ch == '_'); } /** * Find the string from an array that matches * and return it's length * or 0 if none */ int FindMatch (const char * matches[]) { for (int i = 0; matches[i]; i++) if (m_sc.MatchIgnoreCase(matches[i])) return strlen(matches[i]); return 0; } /** * Check if any of the chars matches ? * return char that matches or a 0 */ char FindMatch(const char matches[]) { for (int i = 0; matches[i]; i++) if (m_sc.ch == matches[i]) return matches[i]; return 0; } // style context StyleContext & m_sc; // Accessor Accessor & m_styler; // keywords WordList ** m_keywords; // current section int m_section; // current line int m_curLine; // current line state int m_lineState; // current nested comment level int m_curNcLevel; // nested pp level int m_curNppLevel; // count visible characters int m_visibleChars; // current FB dialect int m_dialect; // Force to skip default call to Forward() bool m_skipForward; }; /** * Colorise FB document */ static void ColouriseFB ( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler ) { // Styler styler.StartAt(startPos, 63); StyleContext sc (startPos, length, initStyle, styler, 63); // Fb source lexer CFbSourceLexer l (sc, styler, keywordlists); l.Log(">>>> styled from: %d, length: %d\n---------------------------------------------------------------", startPos, length); } /** * Keywords */ static const char * const fbWordListDesc[] = { "FB_kw1", "FB_kw2", "FB_kw3", "FB_kw4", "FB_pp1", "FB_pp2", "FB_asm1", "FB_asm2", 0 }; // Add the lexer module LexerModule lmFB( FREEBASIC, // identifier ColouriseFB, // colorise proc "FreeBASIC", // name NULL, // fold proc fbWordListDesc, // keywords descriptor 6 // number of style bits used );
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 1087 ] ] ]
0078e0e93ee7e8545fb4a9f88bd982711cf29be8
1b36851aa24e5c9703dab5f4e6cf634e376b0b74
/list.cc
443a159079abe03694b4da2b1af66f83f8b2988a
[]
no_license
huangyingw/List
1d7e06a6210fad4cd31d538cf8732ce46b6f2ab8
ffc5057302e3235d1aeb10a7bd6883be4092961c
refs/heads/master
2016-09-01T23:20:20.465483
2011-11-12T13:19:10
2011-11-12T13:19:10
583,411
0
0
null
null
null
null
UTF-8
C++
false
false
556
cc
// List.cpp : Defines the entry point for the console application. // #include <iostream> #include <fstream> #include"list.h" int main() { List list1,list2; //cin>>list1; list1.InsertAtLast('4'-48); list1.InsertAtLast('3'-48); list1.InsertAtLast('2'-48); list1.InsertAtLast('1'-48); cout<<list1<<endl; /* cin>>list2; cout<<MergeCreateNew(list1,list2); cout<<endl; MergeList(list1,list2); */ list1.first=list1.RevListWithRecursion(list1.first); cout<<list1<<endl; return 0; }
[ [ [ 1, 29 ] ] ]
31ef3675116dbe238e620dea4e53242c93224755
ef25bd96604141839b178a2db2c008c7da20c535
/src/src/AIToolkit/AIManager.cpp
0498b1b59862b931479c529066f9f1195e25da4e
[]
no_license
OtterOrder/crock-rising
fddd471971477c397e783dc6dd1a81efb5dc852c
543dc542bb313e1f5e34866bd58985775acf375a
refs/heads/master
2020-12-24T14:57:06.743092
2009-07-15T17:15:24
2009-07-15T17:15:24
32,115,272
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,228
cpp
#include "AIManager.h" #include "../Engine/Core/Macros.h" AIManager::AIManager( bool spawn, int comportementAI, int nbMaxEnemy, int fovEnemy, int rangeAttack, int scaleMap, int precision ) : nbGroup(0), spawnInfini(spawn), typeAI(comportementAI), newPos(Vector3f(0,0,0)), newAngle(0), fieldOfView(fovEnemy), attackRange(rangeAttack), nbEnemy(nbMaxEnemy), scaleCurrMap(scaleMap), precCurrMap(precision), timeEnemy(0.f) { initRandom(); aiEnemy = new AIEnemy(scaleMap, precision); } AIManager::~AIManager() { if (aiEnemy) delete aiEnemy; std::list<Enemy*>::iterator it = Enemy::RefList.begin(); while( !Enemy::RefList.empty() ) { Enemy* enemy = Enemy::RefList.back() ; releaseFromList( Enemy::RefList, enemy); } } void AIManager::update( Hero* const pHero, float elapsedTime ) { // Pour calcul la distance que doit effectuer les ennemies en fct du temps aiEnemy->setElapsedTime(elapsedTime); Vector3f posPlayer = pHero->getSceneObjectAnimated()->GetPosition(); // Gère les états et transitions list<Enemy*>::iterator it = Enemy::RefList.begin(); while( it != Enemy::RefList.end() ) { Enemy* pEnemy = (*it); SceneObjectAnimated* pObj = pEnemy->getSceneObjectAnimated(); if(pObj) { newPos = pEnemy->getSceneObjectAnimated()->GetPosition(); distance = aiEnemy->calculDistance( posPlayer, newPos ); newPos = Vector3f(0,0,0); newAngle = 0; if ( distance <= attackRange ) { if (pEnemy->getLife() >= 30 || AI_ONLY_ATTACK && !AI_ONLY_EVADE) { aiEnemy->enemyAIAttack( posPlayer, pEnemy->getSceneObjectAnimated()->GetPosition(), newAngle ); pEnemy->changeState(Perso::ATTACK); } else { aiEnemy->enemyAIEvade( posPlayer ); pEnemy->changeState(Perso::RUN); } } else if ( distance <= fieldOfView ) { if (pEnemy->getLife() >= 30 || AI_ONLY_ATTACK && !AI_ONLY_EVADE) { aiEnemy->enemyAIMoveTo( posPlayer, pEnemy->getSceneObjectAnimated()->GetPosition(), newPos, newAngle); pEnemy->changeState(Perso::RUN); } else { aiEnemy->enemyAIEvade( posPlayer ); pEnemy->changeState(Perso::RUN); } } else { timeEnemy = pEnemy->timeSinceLastPath; aiEnemy->enemyAIPatrol( posPlayer, newPos, newAngle, timeEnemy); pEnemy->changeState(Perso::RUN); pEnemy->timeSinceLastPath = timeEnemy; } //(*it)->getSceneObjectAnimated()->SetTranslation(newPos.x, 0, newPos.z); //(*it)->getSceneObjectAnimated()->SetRotation(0, (float)newAngle, 0); Vector3f oldPos = pEnemy->getSceneObjectAnimated()->GetPosition(); pEnemy->getSceneObjectAnimated()->SetPosition( oldPos.x+newPos.x, 0, oldPos.z+newPos.z ); pEnemy->getSceneObjectAnimated()->SetRotation( 0, newAngle, 0 ); NxActor* a = pEnemy->getArme()->getActor(); if( a ) a->clearBodyFlag( NX_BF_FROZEN_ROT_Y ); pEnemy->getArme()->SetRotation( 0.f, -newAngle, 0.f ); if( a ) a->raiseBodyFlag( NX_BF_FROZEN_ROT_Y ); a=NULL; it++; pEnemy->update( ); } } // Gère les respawn updateSpawn(pHero); } void AIManager::updateSpawn( Hero* const pHero ) { // Recrée les enemies si le spawn est infini et qu'on a pas atteind le nombre maximal d'ennemies if ( spawnInfini ) { // Creer les ennemis manquants while ((int)Enemy::RefList.size() < nbEnemy) { // Position aléatoire par rapport a la AIMap pair<int,int> posSpawn = aiEnemy->getPtrAStar()->randomSpawn(); // Transpose les coordonnées de la AI map en coordonnées de jeu float spawnX = floor(float((posSpawn.first*scaleCurrMap)/precCurrMap)-scaleCurrMap/2); float spawnZ = floor(float((posSpawn.second*scaleCurrMap)/precCurrMap)-scaleCurrMap/2); Enemy* enemy = NULL; /*if ( random( 0, 1 )) enemy = new Alien( Vector3f(spawnX, 8.f, spawnZ) ); else */enemy = new MmeGrise( Vector3f(spawnX, 8.f, spawnZ) ); enemy->Init(); enemy->getSceneObjectAnimated()->SetControledCharacter(3.f, 7.f, enemy ); physX::Link( pHero->getArme(), enemy->getSceneObjectAnimated() ); physX::Link( enemy->getArme(), pHero->getSceneObjectAnimated() ); } } }
[ "olivier.levaque@7c6770cc-a6a4-11dd-91bf-632da8b6e10b", "berenger.mantoue@7c6770cc-a6a4-11dd-91bf-632da8b6e10b", "mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b" ]
[ [ [ 1, 1 ], [ 5, 8 ], [ 11, 11 ], [ 14, 18 ], [ 25, 27 ], [ 29, 31 ], [ 33, 34 ], [ 37, 37 ], [ 41, 41 ], [ 83, 83 ], [ 101, 103 ], [ 105, 107 ], [ 109, 113 ], [ 115, 122 ], [ 132, 134 ] ], [ [ 2, 2 ], [ 10, 10 ], [ 12, 12 ], [ 19, 24 ], [ 28, 28 ], [ 32, 32 ], [ 35, 36 ], [ 38, 40 ], [ 42, 82 ], [ 84, 100 ], [ 104, 104 ], [ 108, 108 ], [ 114, 114 ], [ 123, 131 ] ], [ [ 3, 4 ], [ 9, 9 ], [ 13, 13 ] ] ]
c63885eb3ec2555be46e3e6bd905b9193db33123
fab77712e8dfd19aea9716b74314f998093093e2
/ESDataServer/PacketPool.h
ff226969345b2f585982c74568bcdbdd22d3f097
[]
no_license
alandigi/tsfriend
95f98b123ae52f1f515ab4a909de9af3724b138d
b8f246a51f01afde40a352248065a6a42f0bcbf8
refs/heads/master
2016-08-12T07:09:23.928793
2011-11-13T15:12:54
2011-11-13T15:12:54
45,849,814
0
2
null
null
null
null
UTF-8
C++
false
false
655
h
#pragma once #include "typedefine.h" #define POOL_SIZE 2000 class CPoolNode { public: CPoolNode(void); ~CPoolNode(void); public: CPacket * PoolAddr; u32 AllocCount; CPoolNode * pNext; }; class CPacketPool { private: u32 PoolCunt; CPoolNode * pPoolHead; CPoolNode * pPoolTail; protected: u32 PacketCount; public: CPacketPool(void); ~CPacketPool(void); CPacket * NewPacket(void); CPacket * GetPacket(u32 PacketIndex); u32 GetPacketCunt(void); void FreeAllPackets(void); void CopyFromAnotherPool(CPacketPool & pAp); private: CPoolNode * NewPoolNode(void); };
[ [ [ 1, 41 ] ] ]
1d17f49660f4b49c0e20d524d942d99183bc8529
bd89d3607e32d7ebb8898f5e2d3445d524010850
/connectivitylayer/isce/isirouter_dll/inc/misirouterchannelif.h
2a4e3cf610cc13f35441266986bb5bb3dba29cac
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
IBM852
C++
false
false
1,522
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef __ISIROUTERCHANNELIF_H__ #define __ISIROUTERCHANNELIF_H__ #include <e32def.h> // For TInt, TAny /* * Abstract interface for router to use channel services. */ class MISIRouterChannelIf { public: /* * Enques channel request completing DFC. * Called in P2P router ext thread context. * @param aRequest, request to be completed * @param aStatusToComplete, status to complete to client. */ virtual void EnqueChannelRequestCompleteDfc( TInt aRequest, TInt aStatusToComplete ) = 0; /* * Receive a message from router. * Responsibility to deallocate the message is transferred to channel. * Can be called in 1..N thread contextes. * Cat no be called with FM held. * Same restrÝctions than in IST API (see from MTrxMuxIf). * @param aMessage, message to receive */ virtual void ReceiveMsg( const TDesC8& aMessage ) = 0; }; #endif /* __ISIROUTERCHANNELIF_H__ */
[ "dalarub@localhost" ]
[ [ [ 1, 55 ] ] ]
caf0a53e3f7cca5fd081b70baeb3f652068a8195
bd89d3607e32d7ebb8898f5e2d3445d524010850
/adaptationlayer/tsy/nokiatsy_dll/src/cmmsmscache.cpp
262fa4a5079e60af4d78c42b3eb0dca2d09aaaf4
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,017
cpp
/* * Copyright (c) 2007-2008 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: * */ // EXTERNAL RESOURCES // Include Files #include <ctsy/rmmcustomapi.h> #include "cmmsmscache.h" #include "tsylogger.h" #include "tisi.h" #include <smsisi.h> #include "OstTraceDefinitions.h" #ifdef OST_TRACE_COMPILER_IN_USE #include "cmmsmscacheTraces.h" #endif // External Data Structures // none // External Function Prototypes // none // LOCAL CONSTANTS AND MACROS // none // MODULE DATA STRUCTURES // Local Data Structures // none // Local Function Prototypes // none // LOCAL FUNCTIONS // none // MEMBER FUNCTIONS //============================================================================= // ----------------------------------------------------------------------------- // CMmSmsCache::CMmSmsCache // Creates new CMmSmsCache object // ----------------------------------------------------------------------------- // CMmSmsCache::CMmSmsCache() { TFLOGSTRING("TSY: CMmSmsCache::CMmSmsCache"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_CMMSMSCACHE_TD, "CMmSmsCache::CMmSmsCache" ); Reset(); // If SIM is offline,then won't get // sim ready completion and cache error state stays as // KErrNotFound. If user accesses SIM SMS --> immediate complete // with KErrNotFound SetStatus( KErrNotFound ); } // ----------------------------------------------------------------------------- // CMmSmsCache::~CMmSmsCache // delete CMmSmsCache // ----------------------------------------------------------------------------- // CMmSmsCache::~CMmSmsCache() { TFLOGSTRING("TSY: CMmSmsCache::~CMmSmsCache"); OstTrace0( TRACE_NORMAL, DUP1_CMMSMSCACHE_CMMSMSCACHE_TD, "CMmSmsCache::~CMmSmsCache" ); Reset(); } // ----------------------------------------------------------------------------- // CMmSmsCache::Reset // reset cache to not ready state // ----------------------------------------------------------------------------- // void CMmSmsCache::Reset() { TFLOGSTRING("TSY: CMmSmsCache::Reset"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_RESET_TD, "CMmSmsCache::Reset" ); iError = KErrNotReady; iDeleteLocation = 0; for ( TInt i = 0; i < iElements.Count(); i++ ) { delete iElements[i]; iElements[i] = NULL; } iElements.Reset(); } // ----------------------------------------------------------------------------- // CMmSmsCache::UsedEntries // get the number of used entries from cache // ----------------------------------------------------------------------------- // TInt CMmSmsCache::UsedEntries() { TFLOGSTRING("TSY: CMmSmsCache::UsedEntries"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_USEDENTRIES_TD, "CMmSmsCache::UsedEntries" ); TInt count( 0 ); for ( TInt i = 0; i < iElements.Count(); i++ ) { if ( iElements[i] ) { count++; } } return count; } // ----------------------------------------------------------------------------- // CMmSmsCache::TotalEntries // get the total number of entries in SIM // ----------------------------------------------------------------------------- // TInt CMmSmsCache::TotalEntries() { TFLOGSTRING2("TSY: CMmSmsCache::TotalEntries: %d",iElements.Count()); OstTrace1( TRACE_NORMAL, CMMSMSCACHE_TOTALENTRIES_TD, "CMmSmsCache::TotalEntries;iElements.Count=%d", iElements.Count() ); return iElements.Count(); } // ----------------------------------------------------------------------------- // CMmSmsCache::Status // Returns cache status, this can be KErrNotReady (cache is being read) // KErrNone (cache is ok and can be used) // any other (cache is in error state and is unusable) // ----------------------------------------------------------------------------- // TInt CMmSmsCache::Status() { TFLOGSTRING("TSY: CMmSmsCache::Status"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_STATUS_TD, "CMmSmsCache::Status" ); return iError; } // ----------------------------------------------------------------------------- // CMmSmsCache::SetStatus // set cache error state // ----------------------------------------------------------------------------- // void CMmSmsCache::SetStatus( TInt aError ) { TFLOGSTRING2("TSY: CMmSmsCache::SetStatus %d", aError); OstTrace1( TRACE_NORMAL, CMMSMSCACHE_SETSTATUS_TD, "CMmSmsCache::SetStatus;aError=%d", aError ); iError = aError; } // ----------------------------------------------------------------------------- // CMmSmsCache::SetTotalEntriesL // initialize cache to contain aTotal number of empty entries // it is assumed that cache is Reset before call to this.. // ----------------------------------------------------------------------------- // void CMmSmsCache::SetTotalEntriesL( TInt aTotal ) { TFLOGSTRING2("TSY: CMmSmsCache::SetTotalEntriesL %d", aTotal); OstTrace1( TRACE_NORMAL, CMMSMSCACHE_SETTOTALENTRIESL_TD, "CMmSmsCache::SetTotalEntriesL;aTotal=%d", aTotal ); RMobileSmsStore::TMobileGsmSmsEntryV1* element = NULL; for ( TInt i = 0; i < aTotal; i++ ) { iElements.AppendL( element ); } } // ----------------------------------------------------------------------------- // CMmSmsCache::AddEntryL // adds new entry to cache, if the cause of isi msg is not // ok, then we add just a null pointer (to save space) // returns true if element was cache and false // if cache location is empty // ----------------------------------------------------------------------------- // TBool CMmSmsCache::AddEntryL( const RMobileSmsStore::TMobileGsmSmsEntryV1* aEntry, const TUint8 aRecordId ) { TFLOGSTRING("TSY: CMmSmsCache::AddEntryL"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_ADDENTRYL_TD, "CMmSmsCache::AddEntryL" ); if ( 0 < iElements.Count() ) { delete iElements[aRecordId - 1]; iElements[aRecordId - 1] = NULL; } // If the location is non-empty (filled with 0xFF (3GPP TS 31.102 // 4.2.25 EFSMS (Short messages))) if ( EMPTY_LOCATION != aEntry->iMsgStatus ) { // Make a copy of the received SIM SMS. // Reserve heap memory; can leave if out of mem. RMobileSmsStore::TMobileGsmSmsEntryV1* tmpBuf = new( ELeave ) RMobileSmsStore::TMobileGsmSmsEntryV1; *tmpBuf = *aEntry; // copy data iElements[aRecordId - 1] = tmpBuf; return ETrue; } return EFalse; } // ----------------------------------------------------------------------------- // CMmSmsCache::GetEntry // get entry from cache, returns null if cache doesn't c;ontain // valid entry in the given location location range is in range // [1... max sim sms slots] // ----------------------------------------------------------------------------- // RMobileSmsStore::TMobileGsmSmsEntryV1* CMmSmsCache::GetEntry( TInt aLocation ) { TFLOGSTRING2("TSY: CMmSmsCache::GetEntry - location: %d", aLocation); OstTrace1( TRACE_NORMAL, CMMSMSCACHE_GETENTRY_TD, "CMmSmsCache::GetEntry;aLocation=%d", aLocation ); RMobileSmsStore::TMobileGsmSmsEntryV1* smsData = NULL; if ( aLocation <= iElements.Count() && aLocation >= 1 ) { if ( iElements[aLocation-1] ) { RMobileSmsStore::TMobileGsmSmsEntryV1* tempHBuf( iElements[aLocation-1] ); smsData = tempHBuf; } } return smsData; } // ----------------------------------------------------------------------------- // CMmSmsCache::FirstFreeLocation // return first free location in range [1... max sim sms slots] // or zero if no free slots are found // ----------------------------------------------------------------------------- // TUint CMmSmsCache::FirstFreeLocation() { TFLOGSTRING("TSY: CMmSmsCache::FirstFreeLocation"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_FIRSTFREELOCATION_TD, "CMmSmsCache::FirstFreeLocation" ); TInt location( 0 ); for ( TInt i = 0; i < iElements.Count(); i++ ) { if ( !iElements[i] ) { location = i + 1; i = iElements.Count(); // exit loop } } TFLOGSTRING2("TSY: CMmSmsCache::FirstFreeLocation - found location: %d", location); OstTrace0( TRACE_NORMAL, DUP1_CMMSMSCACHE_FIRSTFREELOCATION_TD, "CMmSmsCache::FirstFreeLocation" ); return location; } // ----------------------------------------------------------------------------- // CMmSmsCache::SetDeleteLocation // set the location to delete by Delete() // ----------------------------------------------------------------------------- // void CMmSmsCache::SetDeleteLocation( TInt aLocation ) { TFLOGSTRING2("TSY: CMmSmsCache::SetDeleteLocation %d", aLocation); OstTrace1( TRACE_NORMAL, CMMSMSCACHE_SETDELETELOCATION_TD, "CMmSmsCache::SetDeleteLocation;aLocation=%d", aLocation ); iDeleteLocation = aLocation; } // ----------------------------------------------------------------------------- // CMmSmsCache::Delete // if flush location is set, then flush it // ----------------------------------------------------------------------------- // void CMmSmsCache::Delete() { TFLOGSTRING("TSY: CMmSmsCache::Delete"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_DELETE_TD, "CMmSmsCache::Delete" ); if ( iDeleteLocation!=0 ) { Delete( iDeleteLocation ); iDeleteLocation = NULL; } } // ----------------------------------------------------------------------------- // CMmSmsCache::Delete // Delete an element from cache // ----------------------------------------------------------------------------- // void CMmSmsCache::Delete( TInt aLocation ) { TFLOGSTRING2("TSY: CMmSmsCache::Delete %d", aLocation); OstTrace1( TRACE_NORMAL, DUP1_CMMSMSCACHE_DELETE_TD, "CMmSmsCache::Delete;aLocation=%d", aLocation ); if ( aLocation <= iElements.Count() && aLocation >= 1 ) { delete iElements[aLocation-1]; iElements[aLocation-1] = NULL; } } // ----------------------------------------------------------------------------- // CMmSmsCache::DeleteAll // empty all of cache // ----------------------------------------------------------------------------- // void CMmSmsCache::DeleteAll() { TFLOGSTRING("TSY: CMmSmsCache::DeleteAll"); OstTrace0( TRACE_NORMAL, CMMSMSCACHE_DELETEALL_TD, "CMmSmsCache::DeleteAll" ); for ( TInt i = 0; i < iElements.Count(); i++ ) { delete iElements[i]; iElements[i] = NULL; } } // ----------------------------------------------------------------------------- // CMmSmsCache::SetStorageStatus // Changes the storage status of a cached entry (TS 31.102, clause 4.2.25) // ----------------------------------------------------------------------------- // void CMmSmsCache::SetStorageStatus( TInt aLocation, RMobileSmsStore::TMobileSmsStoreStatus aMsgStatus ) { TFLOGSTRING2("TSY: CMmSmsCache::SetStorageStatus(loc=%d)", aLocation); OstTrace1( TRACE_NORMAL, CMMSMSCACHE_SETSTORAGESTATUS_TD, "CMmSmsCache::SetStorageStatus;aLocation=%d", aLocation ); if ( aLocation <= iElements.Count() && aLocation >= 1 && iElements[aLocation-1] ) { // Entry exists, update status. iElements[aLocation-1]->iMsgStatus = aMsgStatus; } } // End of File
[ "dalarub@localhost", "[email protected]", "mikaruus@localhost" ]
[ [ [ 1, 27 ], [ 29, 29 ], [ 31, 64 ], [ 66, 81 ], [ 83, 93 ], [ 95, 114 ], [ 116, 134 ], [ 136, 148 ], [ 150, 160 ], [ 162, 173 ], [ 175, 195 ], [ 197, 231 ], [ 233, 254 ], [ 256, 265 ], [ 267, 277 ], [ 279, 289 ], [ 291, 305 ], [ 307, 322 ], [ 324, 330 ], [ 351, 351 ] ], [ [ 28, 28 ], [ 30, 30 ], [ 331, 340 ], [ 342, 350 ] ], [ [ 65, 65 ], [ 82, 82 ], [ 94, 94 ], [ 115, 115 ], [ 135, 135 ], [ 149, 149 ], [ 161, 161 ], [ 174, 174 ], [ 196, 196 ], [ 232, 232 ], [ 255, 255 ], [ 266, 266 ], [ 278, 278 ], [ 290, 290 ], [ 306, 306 ], [ 323, 323 ], [ 341, 341 ] ] ]
5a4d40a78a5d715cf369577a759c089a98ec9c9f
b7c9a0c9ef8ad8d7275ebfa24ba21d55caec3f77
/samples/demo6/test.cpp
86b38fc6f43c4e6193fcc81c2b7f032b257d4765
[]
no_license
KapLex/libnge2
bde1aaf683c1501a298e038cd4d3df3ffa98e21f
bdccf1f01d93bf46241625e29a57cba84c0c5be5
refs/heads/master
2021-05-29T18:11:12.642465
2011-10-15T10:15:21
2011-10-15T10:15:21
null
0
0
null
null
null
null
GB18030
C++
false
false
2,331
cpp
#include "libnge2.h" #include <stdio.h> /** * nge_gif:显示一张gif图片 */ //退出标识 int game_quit = 0; //背景图片 image_p p_bg = NULL; //logo图片 image_p p_logo = NULL; enum{ SCREEN_1X= 0,//原图显示 SCREEN_FULL, //满屏显示 SCREEN_2X //二倍显示 }; gif_desc_p pgif = NULL; int display_flag = SCREEN_1X; void btn_down(int keycode) { switch(keycode) { case PSP_BUTTON_UP: break; case PSP_BUTTON_DOWN: break; case PSP_BUTTON_LEFT: break; case PSP_BUTTON_RIGHT: break; case PSP_BUTTON_TRIANGLE: display_flag = SCREEN_2X; break; case PSP_BUTTON_CIRCLE: display_flag = SCREEN_FULL; break; case PSP_BUTTON_CROSS: display_flag = SCREEN_1X; break; case PSP_BUTTON_SQUARE: break; case PSP_BUTTON_SELECT: //按下选择键退出 game_quit = 1; break; case PSP_BUTTON_START: //按下开始键退出 game_quit = 1; break; } } void DrawScene() { BeginScene(1); ImageToScreen(p_bg,0,0); switch(display_flag) { case SCREEN_FULL: DrawGifAnimation(pgif,0,0,0,0,0,0,480,272); break; case SCREEN_1X: GifAnimationToScreen(pgif,0,0); break; case SCREEN_2X: RenderGifAnimation(pgif,0,0,0,0,0,0,2,2,0,pgif->gif_image_chains->pimage->mask); break; default: break; } EndScene(); } extern "C" int main(int argc, char* argv[]) { //初始化NGE分为VIDEO,AUDIO,这里是只初始化VIDEO,如果初始化所有用INIT_VIDEO|INIT_AUDIO,或者INIT_ALL NGE_Init(INIT_VIDEO); //初始化按键处理btn_down是按下响应,后面是弹起时的响应,0是让nge处理home消息(直接退出),填1就是让PSP系统处理 //home消息,通常填1正常退出(1.50版的自制程序需要填0) InitInput(btn_down,NULL,1); //最后一个参数是psp swizzle优化,通常填1 p_bg = image_load("images/demo0.jpg",DISPLAY_PIXEL_FORMAT_8888,1); if(p_bg == NULL) printf("can not open file\n"); pgif = gif_animation_load("images/simple.gif",DISPLAY_PIXEL_FORMAT_5551,1); if(pgif == NULL) printf("can not open file\n"); while ( !game_quit ) { ShowFps(); InputProc(); DrawScene(); LimitFps(60); } image_free(p_bg); image_free(p_logo); gif_animation_free(pgif); NGE_Quit(); return 0; }
[ [ [ 1, 1 ], [ 3, 110 ] ], [ [ 2, 2 ] ] ]
be0c9d53d12dc856e5b763d572cf84e26d1a8e81
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/test/testSetting/stdafx.h
a7efd69f757b9beb9c23302cc995dbe23fba6676
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
480
h
// stdafx.h : 标准系统包含文件的包含文件, // 或是常用但不常更改的项目特定的包含文件 // #ifndef _SETTING_STDAFX_H__ #define _SETTING_STDAFX_H__ #include <iostream> #include <tchar.h> #include <objbase.h> #include <windows.h> #include <comdef.h> #ifdef _DEBUG # pragma comment(lib, "settingd.lib") #else # pragma comment(lib, "setting.lib") #endif #pragma comment(lib, "ws2_32.lib") #endif // _SETTING_STDAFX_H__
[ "ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b", "[email protected]" ]
[ [ [ 1, 16 ], [ 18, 26 ] ], [ [ 17, 17 ] ] ]
831f0a3820813ea942c59e90c0b45782d45d458b
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/System/Io/OArchive/hkOArchive.h
23c228a0621b7974c5cec531a7cf835f8412c191
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
4,646
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_BASE_OARCHIVE_H #define HK_BASE_OARCHIVE_H class hkStreamWriter; /// Endian-aware binary formatted data writer. /// Outputs all data in little endian format and converts on the fly if necessary. class hkOArchive: public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_STREAM); /// Create with the specified hkStreamWriter. hkOArchive(hkStreamWriter* sb, hkBool byteswap=HK_ENDIAN_BIG); /// Create with a stream from the hkStreamWriter factory. /// The file is truncated. hkOArchive(const char* filename, hkBool byteswap=HK_ENDIAN_BIG); /// Create with a memory block. 'mem' must exist for the lifetime of this object. hkOArchive(void* mem, int memSize, hkBool byteswap=HK_ENDIAN_BIG); /// Creates with an expanding memory block. 'arr' must exist for the lifetime of this object. hkOArchive(hkArray<char>& arr, hkBool byteswap=HK_ENDIAN_BIG); /// Destructor. ~hkOArchive(); // // Write single elements. // /// Writes 8 bits. void write8(hkChar c); /// Writes 8 bits. void write8u(hkUchar u); /// Writes 16 bits. void write16(hkInt16 i); /// Writes 16 bits. void write16u(hkUint16 u); /// Writes 32 bits. void write32(hkInt32 i); /// Writes 32 bits. void write32u(hkUint32 u); /// Write 64 bits. void write64(hkInt64 i); /// Writes 64 bits. void write64u(hkUint64 u); /// Writes 32 bit IEEE floats. void writeFloat32(hkFloat32 f); /// Writes 64 bit IEEE doubles. void writeDouble64(hkDouble64 d); // // Write array elements. // /// Writes array of 8 byte data. void writeArray8(const hkInt8* buf, int nelem); /// Writes array of 8 byte data. void writeArray8u(const hkUint8* buf, int nelem); /// Writes array of 16 byte data. void writeArray16(const hkInt16* buf, int nelem); /// Writes array of 16 byte data. void writeArray16u(const hkUint16* buf, int nelem); /// Writes array of 32 byte data. void writeArray32(const hkInt32* buf, int nelem); /// Writes array of 32 byte data. void writeArray32u(const hkUint32* buf, int nelem); /// Writes array of 64 byte data. void writeArray64(const hkInt64* buf, int nelem); /// Writes array of 64 byte data. void writeArray64u(const hkUint64* buf, int nelem); /// Writes array of 32 byte float data. void writeArrayFloat32(const hkFloat32* buf, int nelem); /// Writes array of 64 byte float data. void writeArrayDouble64(const hkDouble64* buf, int nelem); /// Writes array of sizeelem byte data. void writeArrayGeneric(const void* buf, int sizeelem, int nelem); // // Other. // /// Writes raw data. int writeRaw(const void* buf, int nbytes); /// Set byteswapping. void setByteSwap(hkBool on); /// Set byteswapping. hkBool getByteSwap() const; /// Returns the current error status of the stream. hkBool isOk() const; /// Returns the underlying hkStreamWriter used by this hkOArchive. hkStreamWriter* getStreamWriter(); /// Set the underlying hkStreamWriter for this hkOArchive void setStreamWriter(hkStreamWriter* writer); protected: /// The underlying hkStreamWriter. hkStreamWriter* m_writer; /// Should we byteswap. hkBool m_byteSwap; }; typedef hkOArchive hkOfArchive; #endif // HK_BASE_OARCHIVE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 162 ] ] ]
90e7d56a82c81d9518569c22e93e8104cad0f95b
e6abea92f59a1031d94bbcb3cee828da264c04cf
/NppPlugins/NppPlugin_ExtLexer/src/NppExtLexer_MYUSERLANG.h
befb259e517960fd4c9e3fc04e305003d003efe7
[]
no_license
bruderstein/nppifacelib_mob
5b0ad8d47a19a14a9815f6b480fd3a56fe2c5a39
a34ff8b5a64e237372b939106463989b227aa3b7
refs/heads/master
2021-01-15T18:59:12.300763
2009-08-13T19:57:24
2009-08-13T19:57:24
285,922
0
1
null
null
null
null
UTF-8
C++
false
false
4,464
h
#ifndef NPPEXTLEXER_MYUSERLANG_H #define NPPEXTLEXER_MYUSERLANG_H // NppExtLexer_MYUSERLANG.h // This file is part of the Notepad++ External Lexers Plugin. // Copyright 2008 - 2009 Thell Fowler ([email protected]) // // This program is free software; you can redistribute it and/or modify it under the terms of // the GNU General Public License as published by the Free Software Foundation; either version // 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. /////////////////////////////////////////////////////////////////////////////////////////////// // Example Lexer Definition of Conversion from User Defined Language // for use with Notepad++ External Lexers Plugin /////////////////////////////////////////////////////////////////////////////////////////////// /*** * * Some interesting notes for other NPP lexer writers: * * > Notepad ++ reads up to 31 styles per language from the styling xml language node * which are available in the style preferences dialog for configuration. * * > Scintilla can use 255 styles with styles 32 to 39 reserved for itself. * * > Scintilla also allows for a maximum of 31 indicators to be used, with the first 7 * set aside for lexers. * * To have indicator color values set from the preferences dialog a style ID needs to be * created for it, so they must also be within the first 31 styles. * * Also, to clarify the difference between indicator and highlight, an indicator does not * need to be a highlight, it can be an underline, a cross-out line, or others. * ***/ /* * One other note: You don't even need to add much to get a lexer functioning, just the * style definitions, your Colourise/Fold routine logic, and the one liner lexer * registration line in the NppExtLexer_Plugin.cpp DLLMAIN function. * */ /////////////////////////////////////////////////////////////////////////////////////////////// // Include Directives #include "NppPlugin.h" // Provides all of the interface, messaging definitions, // and namespace aliases. /////////////////////////////////////////////////////////////////////////////////////////////// // Language Specific definitions namespace NppExtLexer_MYUSERLANG { //********************************************************************************************* // Global ( within the namespace ) constants. //********************************************************************************************* // Nested namespace to place only the style state IDs namespace Styles { const int DEFAULT = 0; const int COMMENT = 1; const int COMMENTLINE = 2; const int NUMBER = 4; const int WORD1 = 5; const int WORD2 = 6; const int WORD3 = 7; const int WORD4 = 8; const int OPERATOR = 10; const int IDENTIFIER = 11; const int BLOCK_OPERATOR_OPEN = 12; const int BLOCK_OPERATOR_CLOSE = 13; const int DELIMITER1 = 14; const int DELIMITER2 = 15; const int DELIMITER3 = 16; }; // End namespace Style //********************************************************************************************* // Lexer Function Delarations. /* * Place any special class, structs, lexer specific function declarations here. * */ //--------------------------------------------------------------------------------------------- // Generic Externally called functions. // These are the functions registered in the ExtLexer_Plugin's DLLMAIN routine. // This is the entry point called by the external lexer interface. void LexOrFold(bool LexorFold, unsigned int startPos, int length, int initStyle, char *words[], WindowID window, char *props); // This is the menu dialog function item that shows up in the Notepad++ 'Plugins' menu under // your lexer's name. void menuDlg(); } // End: namespace NppExtLexer_MYUSERLANG. #endif // End: Include guard.
[ "T B Fowler@2fa2a738-4fc5-9a49-b7e4-8bd4648edc6b" ]
[ [ [ 1, 116 ] ] ]
f3188b910083e94e7de12a19866a7e7c3e888031
016774685beb74919bb4245d4d626708228e745e
/lib/Collide/ozcollide/intr_lineline.cpp
e07d0aa82d7210526229de0d3872b7ed95ea1579
[]
no_license
sutuglon/Motor
10ec08954d45565675c9b53f642f52f404cb5d4d
16f667b181b1516dc83adc0710f8f5a63b00cc75
refs/heads/master
2020-12-24T16:59:23.348677
2011-12-20T20:44:19
2011-12-20T20:44:19
1,925,770
1
0
null
null
null
null
UTF-8
C++
false
false
1,415
cpp
/* OZCollide - Collision Detection Library Copyright (C) 2006 Igor Kravtchenko This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact the author: [email protected] */ #include <ozcollide/ozcollide.h> #ifndef OZCOLLIDE_PCH #include <ozcollide/intr_lineline.h> #include <ozcollide/vec2f.h> #endif ENTER_NAMESPACE_OZCOLLIDE bool testIntersectionLineLine(const Vec2f &_p1, const Vec2f &_p2, const Vec2f &_p3, const Vec2f &_p4, float *_t) { Vec2f d1 = _p2 - _p1; Vec2f d2 = _p3 - _p4; float denom = d2.y*d1.x - d2.x*d1.y; if (!denom) return false; if (_t) { float dist = d2.x*(_p1.y-_p3.y) - d2.y*(_p1.x-_p3.x); dist /= denom; *_t = dist; } return true; } LEAVE_NAMESPACE
[ [ [ 1, 51 ] ] ]
13167f73c2e9e3067ff8f4cb521996ffb18279ed
3182b05c41f13237825f1ee59d7a0eba09632cd5
/add/RPGPack/RPGBaseData.h
cb91ee17ff374a54f0f8c80001682e622f8480a5
[]
no_license
adhistac/ee-client-2-0
856e8e6ce84bfba32ddd8b790115956a763eec96
d225fc835fa13cb51c3e0655cb025eba24a8cdac
refs/heads/master
2021-01-17T17:13:48.618988
2010-01-04T17:35:12
2010-01-04T17:35:12
null
0
0
null
null
null
null
GB18030
C++
false
false
1,333
h
#ifndef __RPGBASEDATA_H__ #define __RPGBASEDATA_H__ #include "T3D/gameBase.h" #include "RPGDefs.h" class GameConnection; class RPGBook; class RPGBaseData : public GameBaseData , public RPGDefs { typedef GameBaseData Parent; S32 _nDescIdx; S8 _nRPGType; StringTableEntry _icon_name; public: RPGBaseData(); void packData(BitStream*); void unpackData(BitStream*); static void initPersistFields(); //icon name StringTableEntry getIconName(); //获得这个rpgdata的类型 const U8 & getRPGDataType(); //当一个item被激活,如果能够激活,error返回0 //U32返回冷却时间,0表示无冷却时间,单位MS,-1表示永远执行 virtual U32 onActivate(ERRORS & error , const U32 & casterSimID = 0, const U32 & targetSimID = 0); //当一个item被激活后,又被反激活,如果能够反激活,则返回true,否则返回false virtual bool onDeActivate(ERRORS & error , const U32 & casterSimID = 0, const U32 & targetSimID = 0); //当这个item被从一个地方移动到另一个地方时,会被调用 //已经从srcBook移动到了destBook virtual void onItemMoved(RPGBook * pSrcBook, S32 srcIdx, RPGBook * pDestBook, S32 destIdx); DECLARE_CONOBJECT(RPGBaseData); }; DECLARE_CONSOLETYPE(RPGBaseData); #endif
[ [ [ 1, 36 ] ] ]
7752360cdc68cd7c7798ba67093e64422a5b7819
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Dynamics/Collide/ContactListener/hkpCollisionEvent.inl
d6fe4c3a0a9300adb8f171626f68e6e109bd192c
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ hkpRigidBody* hkpCollisionEvent::getBody( int bodyIdx ) const { HK_ASSERT2( 0x4e66ea80, bodyIdx == 0 || bodyIdx == 1, "The bodyIdx must be 0 or 1." ); return m_bodies[bodyIdx]; } hkpCollisionEvent::hkpCollisionEvent( CallbackSource source, hkpRigidBody* bodyA, hkpRigidBody* bodyB, hkpSimpleConstraintContactMgr* mgr ) : m_source( source ), m_contactMgr( mgr ) { m_bodies[0] = bodyA; m_bodies[1] = bodyB; } hkpSimulationIsland* hkpCollisionEvent::getSimulationIsland() const { // There should be no event in which both entities are fixed. hkpSimulationIsland* island = m_bodies[0]->getSimulationIsland(); if ( island->isFixed() ) { island = m_bodies[1]->getSimulationIsland(); } return island; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 46 ] ] ]
993b07ddb898b07ddc14e8d82a94106a276f805b
59066f5944bffb953431bdae0482a2abfb75f49a
/trunk/ogreopcode/include/OgreTriangle.h
fdd829e5ad4693adf9373310d1731410201dd33d
[]
no_license
BackupTheBerlios/conglomerate-svn
5b1afdea5fbcdd8b3cdcc189770b1ad0f8027c58
bbecac90353dca2ae2114d40f5a6697b18c435e5
refs/heads/master
2021-01-01T18:37:56.730293
2006-05-21T03:12:39
2006-05-21T03:12:39
40,668,508
0
0
null
null
null
null
UTF-8
C++
false
false
5,921
h
/////////////////////////////////////////////////////////////////////////////// /// @file OgreTriangle.h /// @brief This class represents a Triangle, which is composed by /// /// @author The OgreOpcode Team @date 23-02-2005 /// /////////////////////////////////////////////////////////////////////////////// /// /// This file is part of OgreOpcode. /// /// A lot of the code is based on the Nebula Opcode Collision module, see docs/Nebula_license.txt /// /// OgreOpcode is free software; you can redistribute it and/or /// modify it under the terms of the GNU Lesser General Public /// License as published by the Free Software Foundation; either /// version 2.1 of the License, or (at your option) any later version. /// /// OgreOpcode is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU /// Lesser General Public License for more details. /// /// You should have received a copy of the GNU Lesser General Public /// License along with OgreOpcode; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /////////////////////////////////////////////////////////////////////////////// #ifndef __OgreOpcodeTriangle_h__ #define __OgreOpcodeTriangle_h__ namespace OgreOpcode { namespace Details { /// Represents a Triangle defined by three points (vertices). /// This class is <em>strongly</em> based on OPCODE's triangle class, but is /// designed to work with Ogre's vectors and haves more utility methods. /// There are methods for computing distances and for intersection detection. /// Most code is inlined. INL files implementing the inlided methods can be added later, /// allowing for easier reading of this class. class _OgreOpcode_Export Triangle { public: /** Fast, but <em>unsafe</em> default constructor */ Triangle() { } /** Constructor */ Triangle( const Vector3& p0, const Vector3& p1, const Vector3& p2 ) { vertices[0] = p0; vertices[1] = p1; vertices[2] = p2; } /** Copy-constructor */ Triangle( const Triangle& tri ) { vertices[0] = tri.vertices[0]; vertices[1] = tri.vertices[1]; vertices[2] = tri.vertices[2]; } /// Dummy destructor :P ~Triangle() {} /** Flips the orientation of this triangle. */ void flip() { Vector3 temp = vertices[2]; vertices[2] = vertices[1]; vertices[1] = temp; } /** Computes the area of this triangle */ Real area() const { const Vector3& v0 = vertices[0]; const Vector3& v1 = vertices[1]; const Vector3& v2 = vertices[2]; return (v1 - v0).crossProduct((v2 - v0)).length() * 0.5; } /** Computes the perimeter of this triangle */ Real perimeter() const { Vector3 d0 = vertices[0] - vertices[1]; Vector3 d1 = vertices[1] - vertices[2]; Vector3 d2 = vertices[2] - vertices[0]; return d0.length() + d1.length() + d2.length(); } /** Computes the normal of this triangle. * @param N Output vector to hold the computed normal * @param normalize Boolean flag telling whether the normal must be normalized */ void normal( Vector3& N, bool normalize = true ) const { const Vector3& v0 = vertices[0]; const Vector3& v1 = vertices[1]; const Vector3& v2 = vertices[2]; N = (v1 - v0).crossProduct((v2 - v0)); // normalizes the vector, if required if( normalize ) N.normalise(); } /** Computes the center of this triangle * @param center Output vector parameter to hold the result */ void center( Vector3& center ) const { center = (vertices[0] + vertices[1] + vertices[2])/3.0; } /** Gets the plane where this triangle lies on. * @param plane Output parameter */ Plane plane() const { return Plane(vertices[0],vertices[1],vertices[2]); }; /** Gets the point with given baricentric uv coordinates */ Vector3 getPoint( Real U, Real V ) const { const Vector3& v0 = vertices[0]; const Vector3& v1 = vertices[1]; const Vector3& v2 = vertices[2]; // convex combination return (1.0 - U - V)*v0 + U*v1 + V*v2; } /** Inflates this triangle in order to produce a larger one with the same center * @param rate The rate this triangle will be inflated. * @param isRelative When this flag is set to true, the triangle will be inflated * proprotional to its size. */ void inflate( Real rate, bool isRelative = false ) { Vector3 center = (vertices[0] + vertices[1] + vertices[2])/3.0; for( int i=0;i<3;++i) { Vector3 delta = vertices[i] - center; if( !isRelative ) delta.normalise(); vertices[i] += rate*delta; } } /** Computes the <em>squared</em> distance from this triangle to a given point * @remarks Follows code from Magic-Software at http://www.magic-software.com */ Real squaredDistance( const Vector3& point ) const; /** Computes the distance from this triangle to a given point */ Real distance( const Vector3& point ) const { return Math::Sqrt( squaredDistance(point) ); } /** Checks collision against a sphere. * @param center The sphere's center * @param radius The sphere's radius */ bool overlapsSphere( const Vector3& center, Real radius ) { return squaredDistance(center) <= radius*radius; } /// The three vertices defining this triangle Vector3 vertices[3]; }; } } #endif
[ "gilvanmaia@4fa2dde5-35f3-0310-a95e-e112236e8438" ]
[ [ [ 1, 192 ] ] ]
eddedfca3d9a21276641e7418ef5e24bfbf4a12a
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/TO2/ScreenMulti.h
a203cb17e72de29ddccaabb9bc0c971b43b1972f
[]
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
1,717
h
// ----------------------------------------------------------------------- // // // MODULE : ScreenMulti.h // // PURPOSE : Interface screen for hosting and joining multi player games // // (c) 1999-2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef _SCREEN_MULTI_H_ #define _SCREEN_MULTI_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BaseScreen.h" class CScreenMulti : public CBaseScreen { public: CScreenMulti(); virtual ~CScreenMulti(); // Build the screen LTBOOL Build(); LTBOOL Render(HSURFACE hDestSurf); void OnFocus(LTBOOL bFocus); protected: uint32 OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2); uint32 HandleCallback(uint32 dwParam1, uint32 dwParam2); void ChangeCDKey(); void RequestMOTD(); void RequestValidate(); LTBOOL LaunchSierraUp(); void CreateDMMissionFile(); // void CreateTDMMissionFile(); void CreateDDMissionFile(); void Update(); CLTGUIColumnCtrl* m_pCDKeyCtrl; std::string m_sCurCDKey; std::string m_sLastValidCDKey; std::string m_sGameMOTD; std::string m_sSysMOTD; enum EState { eState_Startup, eState_VersionCheck, eState_NoCDKey, eState_ValidateCDKey, eState_MOTD, eState_Ready, }; EState m_eCurState; CLTGUIWindow* m_pWait; CLTGUICtrl* m_pJoin; CLTGUICtrl* m_pHost; CLTGUITextCtrl* m_pStatusCtrl; CLTGUITextCtrl* m_pUpdate; CLTGUILargeText* m_pSysMOTD; CLTGUIFrame* m_pSysFrame; CLTGUILargeText* m_pGameMOTD; CLTGUIFrame* m_pGameFrame; CLTGUITextCtrl* m_pWaitText; }; #endif // _SCREEN_MULTI_H_
[ [ [ 1, 78 ] ] ]
ba0092b21a566b6612d63f590ec26b39f05c53e8
d906f5ffd6d2c563b52c27ce491e056268be2ce3
/Parallax Occlusion Mapping Tech Demo/Source Files/Player.cpp
7b074702e6f47402a3f1b89a5f6949b1422401da
[]
no_license
vksoon/directxhlslproject
5df86d15c62711023f56f63d6098aceaaa9c2528
09e33f699cec98880dec71e8c67b8ce327a16f0c
refs/heads/master
2021-01-10T01:30:41.783049
2011-05-16T17:42:39
2011-05-16T17:42:39
36,427,148
0
0
null
null
null
null
UTF-8
C++
false
false
8,593
cpp
#include "../Headers/Player.h" bool Player::Load(File * pFile) { std::string id; std::string meshFile, shaderConfigFile; float xrot,yrot,zrot,xpos,ypos,zpos,xscale,yscale,zscale, uniformscale; pFile->GetString(&id); pFile->GetString(&meshFile); pFile->GetString(&shaderConfigFile); pFile->GetFloat(&xrot); pFile->GetFloat(&yrot); pFile->GetFloat(&zrot); pFile->GetFloat(&xscale); pFile->GetFloat(&yscale); pFile->GetFloat(&zscale); pFile->GetFloat(&xpos); pFile->GetFloat(&ypos); pFile->GetFloat(&zpos); pFile->GetFloat(&uniformscale); SetXRotation(xrot); SetYRotation(yrot); SetZRotation(zrot); SetXPosition(xpos); SetYPosition(ypos); SetZPosition(zpos); SetXScale(xscale); SetYScale(yscale); SetZScale(zscale); SetOverallScale(uniformscale); m_id = id; armorBump = NULL; bodyBump = NULL; headBump = NULL; headgearBump = NULL; helmetBump = NULL; packBump = NULL; weaponsBump = NULL; // Create an Effect Factory and Register some Creator Objects Factory<Effect> EffectFactory; EffectFactory.Register("BumpMapEffect", new Creator<BumpMapEffect, Effect>); // Create the Lighting Effect file m_pBumpMapEffect = EffectFactory.Create("BumpMapEffect"); assert(!_stricmp(m_pBumpMapEffect->GetClassName(), "BumpMapEffect")); // Check the class name exists m_pBumpMapEffect->Load("Shaders/BumpMapping.fx"); m_pBumpMapEffect->LoadValuesFromConfig(shaderConfigFile); /* Adding bump map textures to .x didn't seem to be possible as it only supports one texture per material, so I added an array of bump map textures that are applied in the same order as the textures loaded from the .x file */ D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/Armor_bumpmap.dds", &armorBump); D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/Body_bumpmap.dds", &bodyBump); D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/DwarfHead_bumpmap.dds", &headBump); D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/Headgear_bumpmap.dds", &headgearBump); D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/Helmet_bumpmap.dds", &helmetBump); D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/Pack_bumpmap.dds", &packBump); D3DXCreateTextureFromFile(D3DObj::Instance()->GetDeviceClass(), "Assets/Dwarf/Weapons_bumpmap.dds", &weaponsBump); m_bumpTextures[0] = weaponsBump; m_bumpTextures[1] = packBump; m_bumpTextures[2] = bodyBump; m_bumpTextures[3] = bodyBump; m_bumpTextures[4] = bodyBump; m_bumpTextures[5] = bodyBump; m_bumpTextures[6] = armorBump; m_bumpTextures[7] = headgearBump; m_bumpTextures[8] = headBump; // Vertex Declaration // Easier than hacking tangents into FVF structures D3DVERTEXELEMENT9 decl[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, 32, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, 44, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, D3DDECL_END() }; D3DObj::Instance()->GetDeviceClass()->CreateVertexDeclaration(decl, &m_pVertexDeclaration); // Create the material buffer for textures from the .x file LPD3DXBUFFER pD3DXMtrlBuffer; // Load the mesh from the specified file if( FAILED(D3DXLoadMeshFromX( meshFile.c_str(), D3DXMESH_MANAGED, D3DObj::Instance()->GetDeviceClass(), NULL, &pD3DXMtrlBuffer, NULL, &m_dwNumMaterials, &m_pMesh ))) { MessageBox(NULL, "Could not find player mesh file!", "Mesh Loading", MB_OK); } LPD3DXMESH tempMesh; DWORD* rgdwAdjacency = NULL; rgdwAdjacency = new DWORD[ m_pMesh->GetNumFaces() * 3]; m_pMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ); D3DXCleanMesh(D3DXCLEAN_BOWTIES, m_pMesh, rgdwAdjacency, &tempMesh, rgdwAdjacency, NULL); m_pMesh = tempMesh; tempMesh->Release(); LPD3DXMESH clonedMesh, newMesh; m_pMesh->CloneMesh(D3DXMESH_VB_MANAGED, decl, D3DObj::Instance()->GetDeviceClass(), &clonedMesh); m_pMesh->Release(); D3DXComputeNormals(clonedMesh, rgdwAdjacency); D3DXComputeTangentFrameEx(clonedMesh, D3DDECLUSAGE_TEXCOORD, 0, D3DDECLUSAGE_TANGENT, 0, D3DDECLUSAGE_BINORMAL, 0, D3DDECLUSAGE_NORMAL, 0, 0, rgdwAdjacency, -1.01f, -0.01f, -1.01f, &newMesh, NULL ); clonedMesh->Release(); m_pMesh = newMesh; newMesh = 0; // We need to extract the material properties and texture names from the // pD3DXMtrlBuffer D3DXMATERIAL* d3dxMaterials = ( D3DXMATERIAL* )pD3DXMtrlBuffer->GetBufferPointer(); m_pMeshMaterials = new D3DMATERIAL9[m_dwNumMaterials]; m_pMeshTextures = new LPDIRECT3DTEXTURE9[m_dwNumMaterials]; for( DWORD i = 0; i < m_dwNumMaterials; i++ ) { // Copy the material m_pMeshMaterials[i] = d3dxMaterials[i].MatD3D; // Set the ambient color for the material (D3DX does not do this) m_pMeshMaterials[i].Ambient = m_pMeshMaterials[i].Diffuse; m_pMeshTextures[i] = NULL; if( d3dxMaterials[i].pTextureFilename != NULL && lstrlenA( d3dxMaterials[i].pTextureFilename ) > 0 ) { D3DXCreateTextureFromFileA( D3DObj::Instance()->GetDeviceClass(), d3dxMaterials[i].pTextureFilename, &m_pMeshTextures[i]); } } pD3DXMtrlBuffer->Release(); return true; } void Player::Draw() { D3DXMatrixTranslation(&m_matTranslate, this->GetXPosition(), this->GetYPosition(), this->GetZPosition()); D3DXMatrixScaling(&m_matScaling, this->GetXScale(), this->GetYScale(), this->GetZScale()); D3DXMatrixRotationX(&m_matRotationX, this->GetXRotation()); D3DXMatrixRotationY(&m_matRotationY, this->GetYRotation()); D3DXMatrixRotationZ(&m_matRotationZ, this->GetZRotation()); D3DXMATRIXA16 mWorld; D3DXMATRIXA16 mWVP; D3DXMATRIXA16 mWV; D3DXMatrixMultiply(&m_matRot,&m_matRotationX, &m_matRotationY); D3DXMatrixMultiply(&m_matRot,&m_matRot, &m_matRotationZ); D3DXMatrixMultiply(&m_matRot,&m_matRot, &m_matScaling); D3DXMatrixMultiply(&mWorld, &m_matRot, &m_matTranslate); D3DObj::Instance()->GetDeviceClass()->SetVertexDeclaration(m_pVertexDeclaration); // select the vertex buffer to display D3DObj::Instance()->GetDeviceClass()->SetStreamSource(0, m_pVBuffer, 0, sizeof(CUSTOMVERTEX)); D3DXMATRIXA16 mView; D3DXMATRIXA16 mProjection; mView = CameraObj::Instance()->GetViewMatrix(); mProjection = CameraObj::Instance()->GetProjectionMatrix(); D3DXMatrixMultiply(&mWV, &mWorld, &mView); D3DXMatrixMultiply(&mWVP, &mWV, &mProjection); D3DXMATRIX EyePoint = CameraObj::Instance()->GetEyePoint(); m_pBumpMapEffect->Get()->SetValue("ViewVector", &EyePoint, sizeof(EyePoint)); m_pBumpMapEffect->Get()->SetValue("World", &mWorld, sizeof(mWorld)); m_pBumpMapEffect->Get()->SetValue("Projection", &mProjection, sizeof(mProjection)); m_pBumpMapEffect->Get()->SetValue("View", &mView, sizeof(mView)); // Get Inverse Transpose of World Matrix D3DXMATRIX m; D3DXMatrixInverse(&m, NULL, &mWorld); D3DXMATRIX j; D3DXMatrixTranspose(&j, &m ); D3DXMATRIX inv = j; m_pBumpMapEffect->Get()->SetMatrix("WorldInverseTranspose", &inv); m_pBumpMapEffect->Get()->SetTechnique("BumpMapped"); UINT iPass, cPasses; m_pBumpMapEffect->Get()->Begin(&cPasses,0); for(iPass = 0; iPass < cPasses; iPass++) { m_pBumpMapEffect->Get()->BeginPass(iPass); for (DWORD i=0; i < m_dwNumMaterials; i++) { // Set the material and texture for this subset D3DObj::Instance()->GetDeviceClass()->SetMaterial(&m_pMeshMaterials[i]); D3DObj::Instance()->GetDeviceClass()->SetTexture(0,m_pMeshTextures[i]); m_pBumpMapEffect->Get()->SetTexture("ModelTexture", m_pMeshTextures[i]); m_pBumpMapEffect->Get()->CommitChanges(); m_pBumpMapEffect->Get()->SetTexture("NormalMap", m_bumpTextures[i]); m_pBumpMapEffect->Get()->CommitChanges(); // Draw the mesh subset m_pMesh->DrawSubset( i ); } m_pBumpMapEffect->Get()->EndPass(); } m_pBumpMapEffect->Get()->End(); } void Player::Update(float dt) { GameObject::Update(dt); } void Player::Clean() { for( DWORD i = 0; i < m_dwNumMaterials; i++ ) { m_pMeshTextures[i]->Release(); } m_pMesh->Release(); } Effect* Player::GetEffect() { return m_pBumpMapEffect; }
[ [ [ 1, 276 ] ] ]
34dc35ff14a4d8f2213b22091aaa9ffe9553af99
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Utilities/PhysXTriggerEntityController.cpp
3245138c13a7ed711015c95a883ff6324ea006ee
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
cpp
#define __DONT_INCLUDE_MEM_LEAKS__ #include "PhysicActor.h" #include "PhysicsManager.h" #include "EntityDefines.h" #include "ComponentTrigger.h" #include "PhysXTriggerEntityController.h" #include "Utils\MemLeaks.h" //---CPhysicTrigger Interface--- void CPhysXTriggerEntityController::OnEnter(CPhysicUserData* entity_trigger1, CPhysicUserData* other_shape) { CGameEntity* m_pEntityTrigger = entity_trigger1->GetEntity(); CGameEntity* m_pOtherEntity = other_shape->GetEntity(); if(m_pEntityTrigger && m_pOtherEntity) { CComponentTrigger *l_pCompTrigger = m_pEntityTrigger->GetComponent<CComponentTrigger>(CBaseComponent::ECT_TRIGGER); if(l_pCompTrigger) { l_pCompTrigger->OnEnter(m_pOtherEntity); } } } void CPhysXTriggerEntityController::OnLeave(CPhysicUserData* entity_trigger1, CPhysicUserData* other_shape) { CGameEntity* m_pEntityTrigger = entity_trigger1->GetEntity(); CGameEntity* m_pOtherEntity = other_shape->GetEntity(); if(m_pEntityTrigger && m_pOtherEntity) { CComponentTrigger *l_pCompTrigger = m_pEntityTrigger->GetComponent<CComponentTrigger>(CBaseComponent::ECT_TRIGGER); if(l_pCompTrigger) { l_pCompTrigger->OnExit(m_pOtherEntity); } } }
[ "atridas87@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 39 ] ] ]
39621084e0bf2665588551d435f8fff5f19cb30f
241124cd0bacf546f76ae8fa0c0de345aa896b09
/tp1/entregable/code/printFuncs.cpp
f68685f46e4f701f1b22d1d8db0688a92adeb039
[]
no_license
mtqp/metnum-11
fa1dd8ef61cd77b7ef1ef8536686b2e901615db8
2738659f491ffdda289701807d6eb692e068cd5e
refs/heads/master
2021-01-10T06:50:18.092416
2011-07-15T18:43:01
2011-07-15T18:43:01
36,199,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,265
cpp
#include "printFuncs.h" void printInt(ullInt rocker){ char * desmond = (char *) & rocker; int i; cout << "int representation --> " << rocker << endl; printNotacion(); unsigned char* bits = (unsigned char*) malloc(sizeof(unsigned char)*8); for (i=sizeof(ullInt)-1; i>=0; i--) { printCharsetInBits(desmond[i], bits); printf ("%s ", bits); } printf ("\n"); } void printDouble(double decker){ char * desmond = (char *) & decker; int i; cout << "double representation (of type 'double' from C++)--> " << decker << endl; printNotacion(); unsigned char* bits = (unsigned char*) malloc(sizeof(unsigned char)*8); for (i=sizeof(double)-1; i>=0; i--) { printCharsetInBits(desmond[i], bits); printf ("%s ", bits); } printf ("\n"); } void printCharsetInBits(char set, unsigned char* bits){ unsigned char pot = 128; unsigned char data = (unsigned char) set; for(int i=0; i<8; ++i) { if((data/pot)%2){ bits[i] = '1'; } else { bits[i] = '0'; } pot /= 2; } } void printNotacion(){ cout << "Notacion:" << endl; cout << " izq = + significativa" << endl; cout << " der = - significativa" << endl; }
[ "marian.sabianaa@70280701-655c-5af6-a42b-ffe49c2aa791" ]
[ [ [ 1, 57 ] ] ]
188a76c8da062e7b51aed91a5e136f689aae24c9
5527467df8db4e127247ee4a1bb0e81be3b6b914
/src/EventInterface/EventHandlerInterface.h
626da3293f4be82e1129cc3ccbe73c502735bacf
[]
no_license
hywei/PatchEditor
bb9978c294a79d7dd1818a83557962d62273c6ef
a00d3ea685def0b9ad719b8a51ef54f52b0df4b3
refs/heads/master
2021-01-19T04:56:20.849381
2011-07-06T13:50:19
2011-07-06T13:50:19
1,481,431
0
1
null
null
null
null
UTF-8
C++
false
false
1,384
h
#ifndef EVENT_INTERFACE_H #define EVENT_INTERFACE_H #include <string> typedef std::string handler_key; class ViewerQT; typedef enum { MOUSE_MODE_UNDEFINED, MOUSE_MODE_MOVE, MOUSE_MODE_SPIN, MOUSE_MODE_ZOOM, MOUSE_MODE_SELECT_VERTEX, MOUSE_MODE_SELECT_PATCH } MouseMode; typedef enum { KEY_MODE_UNDEFINED } KeyMode; class EventHandlerInterface { public: virtual ~EventHandlerInterface(){}; public: virtual void Init(ViewerQT* _qtViewer) = 0; virtual bool OnLButtonDown(unsigned int nFlags, int point_x, int point_y) {return true;} virtual bool OnLButtonUp(unsigned int nFlags, int point_x, int point_y) {return true;} virtual bool OnRButtonDown(unsigned int nFlags, int point_x, int point_y) {return true;} virtual bool OnRButtonUp(unsigned int nFlags, int point_x, int point_y) {return true;} virtual bool OnMouseMove(unsigned int nFlags, int point_x, int point_y) {return true;} virtual bool OnMouseWheel(unsigned int nFlags, short zDelta, int point_x, int point_y) {return true;} virtual bool OnKeyDown(unsigned int nChar) {return true;} virtual handler_key HandlerKey() {return "";} virtual bool IsMouseNeedHandle(MouseMode mouse_mode) {return false;} virtual bool IsKeyNeedHandle(KeyMode key_mode) {return false;} protected: MouseMode m_MouseMode; KeyMode m_KeyMode; ViewerQT* qt_viewer; }; #endif
[ [ [ 1, 46 ] ] ]
ca501fc08da3b1ba8f7209c4d0b6219954bc054b
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlWireframeState.h
bba1f637e875bd9d25146b89f5613872d08c8c07
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
925
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLWIREFRAMESTATE_H #define WMLWIREFRAMESTATE_H #include "WmlRenderState.h" namespace Wml { WmlSmartPointer(WireframeState); class WML_ITEM WireframeState : public RenderState { WmlDeclareDefaultState(WireframeState); WmlDeclareRTTI; WmlDeclareStream; public: WireframeState (); virtual Type GetType () const; bool& Enabled (); // default: false protected: bool m_bEnabled; }; WmlRegisterStream(WireframeState); #include "WmlWireframeState.inl" } #endif
[ [ [ 1, 42 ] ] ]
b9755b0a116122608b5ae0e9148a6ac6f5cf351a
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/AssimpCExport.cpp
90e3276680e01a9ea47704d6cf2c291c22ac362b
[ "BSD-3-Clause" ]
permissive
spring/assimp
fb53b91228843f7677fe8ec18b61d7b5886a6fd3
db29c9a20d0dfa9f98c8fd473824bba5a895ae9e
refs/heads/master
2021-01-17T23:19:56.511185
2011-11-08T12:15:18
2011-11-08T12:15:18
2,017,841
1
1
null
null
null
null
UTF-8
C++
false
false
4,243
cpp
/* --------------------------------------------------------------------------- Open Asset Import Library (ASSIMP) --------------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file AssimpCExport.cpp Assimp C export interface. See Exporter.cpp for some notes. */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_EXPORT #include "CInterfaceIOWrapper.h" #include "SceneCombiner.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ ASSIMP_API size_t aiGetExportFormatCount(void) { return Exporter().GetExportFormatCount(); } // ------------------------------------------------------------------------------------------------ ASSIMP_API const aiExportFormatDesc* aiGetExportFormatDescription( size_t pIndex) { return Exporter().GetExportFormatDescription(pIndex); } // ------------------------------------------------------------------------------------------------ ASSIMP_API void aiCopyScene(const aiScene* pIn, aiScene** pOut) { if (!pOut || !pIn) { return; } SceneCombiner::CopyScene(pOut,pIn,false); } // ------------------------------------------------------------------------------------------------ ASSIMP_API aiReturn aiExportScene( const aiScene* pScene, const char* pFormatId, const char* pFileName, unsigned int pPreprocessing ) { return ::aiExportSceneEx(pScene,pFormatId,pFileName,NULL,pPreprocessing); } // ------------------------------------------------------------------------------------------------ ASSIMP_API aiReturn aiExportSceneEx( const aiScene* pScene, const char* pFormatId, const char* pFileName, aiFileIO* pIO, unsigned int pPreprocessing ) { Exporter exp; if (pIO) { exp.SetIOHandler(new CIOSystemWrapper(pIO)); } return exp.Export(pScene,pFormatId,pFileName,pPreprocessing); } // ------------------------------------------------------------------------------------------------ ASSIMP_API const C_STRUCT aiExportDataBlob* aiExportSceneToBlob( const aiScene* pScene, const char* pFormatId, unsigned int pPreprocessing ) { Exporter exp; if (!exp.ExportToBlob(pScene,pFormatId,pPreprocessing)) { return NULL; } const aiExportDataBlob* blob = exp.GetOrphanedBlob(); ai_assert(blob); return blob; } // ------------------------------------------------------------------------------------------------ ASSIMP_API C_STRUCT void aiReleaseExportBlob( const aiExportDataBlob* pData ) { delete pData; } #endif // !ASSIMP_BUILD_NO_EXPORT
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 115 ] ] ]
07fb5d915235a66f0bf839f9b6633de9bcce1ccf
ed2f2f743085b3f9cc3ca820dbff620b783fc577
/blobTest/fileMapping.h
1f0329b185df429ebf9a8bcf6b997b0b4125071a
[]
no_license
littlewingsoft/test-sqlite-blob
ae7b745fe8bcc5aac57480e9132807545c31efc1
796359fcd34fee39eff999bc179bf3194ac6f847
refs/heads/master
2019-01-19T17:50:40.792433
2011-08-22T12:03:10
2011-08-22T12:03:10
32,302,166
0
0
null
null
null
null
UTF-8
C++
false
false
544
h
#ifndef __FILEMAPPING__ #define __FILEMAPPING__ #include <windows.h> class fileMapping { private: HANDLE hMap; HANDLE hf; BYTE* pkBuff ; public: fileMapping():hMap(INVALID_HANDLE_VALUE), hf(INVALID_HANDLE_VALUE),pkBuff(0) {} fileMapping(const wchar_t* szFileName); ~fileMapping() { UnmapViewOfFile( pkBuff ); CloseHandle( hMap); CloseHandle( hf ); } template<class T> T* GetBuffer() { return (T*)pkBuff ; } unsigned long GetBufferSize() { return GetFileSize(hf,NULL); } }; #endif
[ "jungmoona@e98d6a08-3d45-9aa4-e100-60898896f941" ]
[ [ [ 1, 35 ] ] ]