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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c1179b2a37382969f61d03347e8150b0fac7c1ef | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /trunk/engine/src/RandomProjections.h | 1af7cef4b5e73ee287aef16c16262fad9944870d | []
| no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,334 | h | #ifndef _SeedSearcher_RandomProjections_h
#define _SeedSearcher_RandomProjections_h
//
// File : $RCSfile: $
// $Workfile: RandomProjections.h $
// Version : $Revision: 16 $
// $Author: Aviad $
// $Date: 13/10/04 3:33 $
// Description :
// Concrete classes for creating and retrieving random projections
// from given <l,d> parameters
//
// Author:
// Aviad Rozenhek (mailto:[email protected]) 2003-2004
//
// written for the SeedSearcher program.
// for details see www.huji.ac.il/~hoan
// and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html
//
// this file and as well as its library are released for academic research
// only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license
// as well as any other restrictions as posed by the computational biology lab
// and the library authors appliy.
// see http://www.cs.huji.ac.il/labs/compbio/LibB/LICENSE
//
#include "Assignment.h"
#include "AssignmentFormat.h"
#include <boost/shared_ptr.hpp>
namespace seed {
class ProjectionGenerator {
public:
virtual ~ProjectionGenerator () {
}
virtual const Assignment& getAssignment (int index) const = 0;
virtual int numOfProjections () const = 0;
};
class RandomProjections : public ProjectionGenerator {
public:
enum All {
all
};
RandomProjections ( All, // create all possible projections
int length, // length of the assignment to create
int numOfPositions, // number of positions to select in each assignment
bool allowOuterWildcards,
boost::shared_ptr <Langauge>
);
RandomProjections ( int numOfProjections,// num of assignments to generate
int length, // length of the assignment to create
int numOfPositions, // number of positions to select in each assignment
bool allowOuterWildcards,
boost::shared_ptr <Langauge>
);
RandomProjections ( int numOfProjections, // num of assignments to generate
const Assignment& base, // background assignment on which to project
int numOfPositions, // number of positions to select in each assignment
boost::shared_ptr <Langauge>
);
virtual ~RandomProjections () {
}
//
// returns how many different projections actually created
virtual int numOfProjections () const {
return _vector.size ();
}
int maxPossibleProjections () const {
return _maxPossibleProjections;
}
static int numOfProjections (bool exhaustive, int requestedProjections,
int length, int numOfPositions, bool allowOuterPositions);
//
// returns the length of each projection
int length () const {
return _length;
}
//
// returns the number of random positions inside each projection
int numOfPositions () const {
return _numOfPositions;
}
virtual const Assignment& getAssignment (int index) const;
typedef Vec <int> RandomPositions;
typedef Vec <RandomPositions> RandomPositionsVector;
typedef Vec <Assignment> AssignmentVector;
static void srand (unsigned int seed);
protected:
virtual const Assignment& getBaseAssignment (Assignment& outBase) const {
outBase = Assignment (_langauge->wildcard (assg_discrete), _length);
return outBase;
}
protected:
Assignment _base;
int _length;
int _numOfPositions;
int _maxPossibleProjections;
RandomPositionsVector _vector;
AssignmentVector _assignments;
boost::shared_ptr <Langauge> _langauge;
};
//
// random projections with a midsection of wildcards
class MidsectionRandomProjections : public RandomProjections {
public:
MidsectionRandomProjections (
All, // create all possible projections
int length, // length of the assignment to create
int numOfPositions, // number of positions to select in each assignment
int midsection,
bool allowOuterWildcards,
boost::shared_ptr <Langauge> lang
)
: RandomProjections (all, length - midsection, numOfPositions, allowOuterWildcards, lang),
_midsection (midsection)
{
}
MidsectionRandomProjections (
int numOfProjections,// num of assignments to generate
int length, // length of the assignment to create
int numOfPositions, // number of positions to select in each assignment
int midsection,
bool allowOuterWildcards,
boost::shared_ptr <Langauge> lang
)
: RandomProjections (numOfProjections,
length - midsection,
numOfPositions,
allowOuterWildcards,
lang),
_midsection (midsection)
{
}
virtual const Assignment& getAssignment (int index) const {
Assignment& out = const_cast <Assignment&> (
RandomProjections::getAssignment (index));
if (_midsection > 0) {
//
// now add the midsection
out.addPositionAt ( out.length () / 2,
_langauge->wildcard (assg_together),
_midsection);
}
return out;
}
private:
int _midsection;
};
class SpecificProjectionGenerator : public RandomProjections {
//
// The purpose of this class is to produce projections
// on a given assignment.
public:
SpecificProjectionGenerator (
All, // create all possible projections
const Str& base, // base assignment on which to project
int numOfPositions, // number of positions to select in each assignment
bool allowOuterPositions, // this usually should be set to true
boost::shared_ptr <Langauge> lang
)
: RandomProjections ( all,
base.length (),
numOfPositions,
allowOuterPositions,
lang)
{
_langauge->stringToAssignment (_base, base);
}
SpecificProjectionGenerator (
int numOfProjections,// num of assignments to generate
const Str& base, // base assignment on which to project
int numOfPositions, // number of positions to select in each assignment
bool allowOuterPositions, // this usually should be set to true
boost::shared_ptr <Langauge> lang
)
: RandomProjections ( numOfProjections,
base.length (),
numOfPositions,
allowOuterPositions,
lang)
{
_langauge->stringToAssignment (_base, base);
}
virtual ~SpecificProjectionGenerator () {
}
protected:
virtual const Assignment& getBaseAssignment (Assignment& outBase) const {
outBase = _base;
return outBase;
}
protected:
Assignment _base;
};
}
#endif // _SeedSearcher_RandomProjections_h
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
]
| [
[
[
1,
228
]
]
]
|
bea317ff49c74f38c7639130d7f250630f0730e9 | ffe0a7d058b07d8f806d610fc242d1027314da23 | /V3e/dummy/ServerSocket.cpp | 33df41f71ee5a36b95b4d9ef15846beae33dbda9 | []
| no_license | Cybie/mangchat | 27bdcd886894f8fdf2c8956444450422ea853211 | 2303d126245a2b4778d80dda124df8eff614e80e | refs/heads/master | 2016-09-11T13:03:57.386786 | 2009-12-13T22:09:37 | 2009-12-13T22:09:37 | 32,145,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | cpp | #include "ServerSocket.h"
ServerSocket::ServerSocket()
{
}
ServerSocket::ServerSocket(int _port)
{
_Create(SOCK_STREAM, IPPROTO_TCP);
_SetOptions(1);
_Bind("", _port);
_Listen(26);
}
ServerSocket::~ServerSocket()
{
}
ClientSocket* ServerSocket::_Accept()
{
SOCK_TYPE NewConn;
if ((NewConn = ::accept(sock_id, NULL, 0)) < 0)
return (NULL);
return new ClientSocket(NewConn);
}
| [
"cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd"
]
| [
[
[
1,
26
]
]
]
|
56eac0e8e66d6928ce90fbaeeb697e261bf6967d | ed2a1c83681d8ed2d08f8a74707536791e5cd057 | /d3d8.DLL/Built-in Extension Files/Computron Files/Computron.h | f2e4cd5bb58cd32123f4e1825614e8ef39a9827a | [
"Apache-2.0"
]
| permissive | MartinMReed/XenDLL | e33d5c27187e58fd4401b2dbcaae3ebab8279bc2 | 51a05c3cec7b2142f704f2ea131202a72de843ec | refs/heads/master | 2021-01-10T19:10:40.492482 | 2007-10-31T16:38:00 | 2007-10-31T16:38:00 | 12,150,175 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,410 | h | #ifndef Computron_H
#define Computron_H
#pragma once
#define SCRIPT_VERSION 2
#include <atltime.h>
#include <wininet.h>
#include <string>
using namespace std;
#include "Instruction.h"
class Computron;
class JReturnStack;
extern Computron* g_Computron;
//-------------------------------------------------------
//
//-------------------------------------------------------
class Computron
{
public:
bool initialized;
bool Initialize(void);
Computron(void);
~Computron(void);
// direct 3d device hook calls
void IncrementSurfaceCount(UINT _count)
{
if (initialized == false) return;
surfCount += _count;
}
// direct 3d device hook calls
void ResetSurfaceCount(void)
{
if (initialized == false) return;
surfSaved = surfCount;
surfCount = 0;
}
// thread calls
void MemoryCheckProc(void);
void ScriptCycleProc(void);
// extension calls
void Render(void);
bool HandleKeyboard(void);
private:
bool logout;
BYTE* g_progressHP;
BYTE* g_progressMP;
BYTE* g_progressXP;
DWORD* g_locationX;
DWORD* g_locationY;
float progressHP;
float progressMP;
float progressXP;
int locationX;
int locationY;
BYTE pauseRestartKey;
BYTE pauseResumeKey;
HGNodeList* extComputron;
HGOImage* panel1;
HGOTextBar* p1TextBar1;
HGOListViewer* p1ListViewer1;
HGOListViewer* p1ListViewer2;
HINTERNET g_hInet;
HINTERNET g_hInetConnection;
bool captureScreen;
bool zeroPause;
bool okayHP;
bool okayMP;
bool checkconUsed;
bool jjump;
bool minuteJumpTriggered;
bool transform;
int surfCount;
int surfSaved;
int countTotal;
int countSpecial;
int countNormal;
int ranTimes;
float screenSizeA;
float screenSizeB;
bool useHealthKey;
int healthPercentTrigger;
BYTE healthMonitorKey;
bool useManaKey;
int manaPercentTrigger;
BYTE manaMonitorKey;
float totalPerc;
float lastXP;
float hrTillHundert;
float percPerHr;
float initPerc;
float startPerc;
float endPerc;
char* scriptFilename;
char* scriptHandle;
char* scriptPassword;
char* networkAdapter;
float pauseLength;
float pauseStart;
Instruction* instrucHeader;
Instruction* instrucCurrent;
Instruction* instrucPrevious;
JReturnStack* jreturnStack;
string ReceiveData(char* _url);
void DrawCursor(void);
void SendCap(char* _file, char* _adapter, char* _s);
void UseWarnings(char* _str, bool _justText = false, int _position = 0);
void AddWarnLog(int _position, char* _log);
void ClearWarnLog(void);
void ContinCheckProc(void);
void GetPause(int _i = 1);
void NextNormalInstruction(void);
void ClearInstructions(void);
void ClearJReturnStack(void);
void ResetTransform(void);
void ReadScriptFile(void);
bool Uninitialize(void);
};
//-------------------------------------------------------
//
//-------------------------------------------------------
class JReturnStack
{
public:
JReturnStack (JReturnStack* _next, int _jreturnFrom, Instruction* _jreturn)
{
next = _next;
jreturnFrom = _jreturnFrom;
jreturn = _jreturn;
}
JReturnStack* next;
JReturnStack* GetNext(void) { return next; }
int jreturnFrom;
int GetJReturnFrom(void) { return jreturnFrom; }
Instruction* jreturn;
Instruction* GetJReturn(void) { return jreturn; }
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
189
]
]
]
|
572a98b55012f31898db8a774a2b7bfe93acb0be | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/DevLibs/DevLib/BBSurge.cpp | a5ac6bc8ff4c58a7a72f07bb308da3c897d0dbba | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,162 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "sc_defs.h"
#define __BBSURGE_CPP
#include "BBSurge.h"
//====================================================================================
//XID xidModelMethod = MdlBsXID(10010);
//====================================================================================
//define Input/Output connections
const byte ioidFeed0 = 0;
const byte ioidFeed1 = 1;
const byte ioidFeed2 = 2;
const byte ioidProd0 = 3;
const byte ioidProd1 = 4;
const byte ioidProd2 = 5;
const byte ioidProd3 = 6;
const byte ioidProd4 = 7;
static IOAreaRec BBSurgeIOAreaList[] = {
{"", "Feed0" , ioidFeed0, LIO_In0 , nc_MLnk, 1, 10, 0, 0.0F},
{"", "Feed1" , ioidFeed1, LIO_In1 , nc_MLnk, 0, 10, 0, 0.0F},
{"", "Feed2" , ioidFeed2, LIO_In2 , nc_MLnk, 0, 10, 0, 0.0F},
{"", "Product0" , ioidProd0, LIO_Out0, nc_MLnk, 1, 1, 0, 0.0F},
{"", "Product1" , ioidProd1, LIO_Out1, nc_MLnk, 0, 1, 0, 0.0F},
{"", "Product2" , ioidProd2, LIO_Out2, nc_MLnk, 0, 1, 0, 0.0F},
{"", "Product3" , ioidProd3, LIO_Out , nc_MLnk, 0, 1, 0, 0.0F},
{"", "Product4" , ioidProd4, LIO_Out , nc_MLnk, 0, 1, 0, 0.0F},
{NULL} };
//define default graphic symbol
static double Drw_BBSurge[] = { DD_Poly, -10,-9, -10,9, 10,9, 10,-9, -10,-9,
DD_End };
//===========================================================================
//#include "optoff.h"
IMPLEMENT_MODELUNIT(CBBSurge, "CBBSurge", "", Drw_BBSurge, "Tank", "BBS", TOC_ALL|TOC_DYNAMICFLOW|TOC_GRP_GENERAL|TOC_SMDKRUNTIME,
"Black Box - Surge",
"Custom Black Box Models containing Surge capacity")
CBBSurge::CBBSurge (pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) :
MN_Surge(pClass_, TagIn, pAttach, eAttach), CBBBase(this)
{
AttachClassInfo(nc_Process, BBSurgeIOAreaList);
Contents.SetClosed(False);
//ChangeMethod(1);
}
//--------------------------------------------------------------------------
CBBSurge::~CBBSurge()
{
}
//--------------------------------------------------------------------------
void CBBSurge::SetSubClass(pchar MdlName)
{
delete m_pMethod;
m_pMethod=NULL; // new ....
if (Class()->SubConstruct())
{
m_pMethod=dynamic_cast<MBaseMethod*>(Class()->SubConstruct()->Construct(this));
m_pMethod->Init(this);
m_pMethod->Init();
MN_Surge::SetSubClass(MdlName);
CBBBase::SetSubClass(MdlName);
}
else
m_bSubClassOK=false;
};
//--------------------------------------------------------------------------
void CBBSurge::BuildDataDefn(DataDefnBlk & DDB)
{
DDB.BeginStruct(this);
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
BuildDataDefnElevation(DDB);
DDB.Text ("");
DDB.Double ("Pressure", "P", DC_P, "kPag", xidPMean, this, isResult|noFile|noSnap);
DDB.Double ("Temperature", "T", DC_T, "C", xidTemp, this, isResult|noFile|noSnap);
DDB.Double ("Density", "Rho", DC_Rho, "kg/m^3", xidRho, this, isResult|noFile|noSnap);
DDB.Double ("Level", "Lvl", DC_Frac, "%", xidLevel, this, isResult|noFile|noSnap);
DDB.Text("");
DDB.Visibility();
if (m_pMethod)
{
if (MethodImpl.m_dwMethOptions & MO_ShowIOs)
BuildDataDefnShowIOs(DDB);
if (MethodImpl.m_dwMethOptions & MO_ShowIOOpts)
BuildDataDefnIOOpts(DDB);
if (NetDynamicMethod() && (MethodImpl.m_dwMethOptions & MO_ShowContents))
DDB.Object(&Contents, this, NULL, NULL, DDB_RqdPage);
DoBuildDataDefn(DDB);
}
DDB.EndStruct();
}
//--------------------------------------------------------------------------
flag CBBSurge::DataXchg(DataChangeBlk & DCB)
{
if (m_pMethod && DoDataXchg(DCB))
return 1;
if (MN_Surge::DataXchg(DCB))
return 1;
return 0;
}
//--------------------------------------------------------------------------
flag CBBSurge::ValidateData(ValidateDataBlk & VDB)
{
flag OK = MN_Surge::ValidateData(VDB);
OK = DoValidateData(VDB) && OK;
return OK;
}
//--------------------------------------------------------------------------
void CBBSurge::PostConnect(int IONo)
{
MN_Surge::PostConnect(IONo);
IOFB(IONo,0)->AssignFlwEqnGroup(PipeEntryGroup, PipeEntryGroup.Default(), this);
DoPostConnect(IONo);
};
//---------------------------------------------------------------------------
void CBBSurge::PreDisConnect(int IONo)
{
DoPreDisConnect(IONo);
MN_Surge::PreDisConnect(IONo);
}
//--------------------------------------------------------------------------
void CBBSurge::SetDatums(int Pass, CFlwNodeIndexList & List, int IOIn)
{
CSetDatumsData SDD[10+1]=
{
// {First64IOIds, &Contents},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0}
};
DoSetDatums(SDD, 10);
SetDatums_Node(Pass, List, IOIn, SDD);
};
//--------------------------------------------------------------------------
void CBBSurge::SetDatumsDone()
{
MN_Surge::SetDatumsDone();
// SortSurgeIOData SDD[]=
// {
// {First64IOIds, &Contents, &ContentHgtOrd},
// {0}
// };
// SortSurgeIO(SDD);
};
//--------------------------------------------------------------------------
flag CBBSurge::Set_Sizes()
{
for (long i=0; i<NoFlwIOs(); i++)
if (IOPipeEntry_Self(i))
{
double A=IOFB_Rmt(i,0)->Area();
IOFB(i,0)->SetArea(A);
IOFB(i,0)->SetActLength(0.0);
IOFB(i,0)->SetFitLength(0.0);
}
return True;
};
//--------------------------------------------------------------------------
flag CBBSurge::PreStartCheck()
{
if (!MN_Surge::PreStartCheck())
return false;
return DoPreStartCheck();
}
//--------------------------------------------------------------------------
void CBBSurge::StartSolution() { DoStartSolution(); }
void CBBSurge::StartStep() { DoStartStep(); }
// ---------------------------------------------------------------------------
flag CBBSurge::InitialiseSolution()
{
MN_Surge::InitialiseSolution();
DoInitialiseSolution();
return 1;
};
//--------------------------------------------------------------------------
bool CBBSurge::PropagateNetInfo(CPropagateNetInfoCtrl & Ctrl, long IONo)
{
_asm int 3;
//if (!m_pMethod)
// return false;
//return Method.PropagateNetInfo(Task, Info, Start);
};
//---------------------------------------------------------------------------
void CBBSurge::ConfigureJoins()
{
if (!DoConfigureJoins())
MN_Surge::ConfigureJoins();
}
//--------------------------------------------------------------------------
void CBBSurge::EvalPBMakeUpReqd(long JoinMask)
{
DoEvalPBMakeUpReqd(JoinMask);
};
//--------------------------------------------------------------------------
void CBBSurge::EvalPBMakeUpAvail(long JoinMask)
{
DoEvalPBMakeUpAvail(JoinMask);
};
//--------------------------------------------------------------------------
void CBBSurge::EvalJoinPressures(long JoinMask)
{
if (!DoEvalJoinPressures(JoinMask))
MN_Surge::EvalJoinPressures(JoinMask);
};
//--------------------------------------------------------------------------
void CBBSurge::EvalJoinFlows(int JoinNo)
{
if (!DoEvalJoinFlows(JoinNo))
MN_Surge::EvalJoinFlows(JoinNo);
};
//--------------------------------------------------------------------------
CSpPropInfo* CBBSurge::IOGetNetProps(int i, double Qm)
{
// MUST Call through to Method
return NULL; // must improve
};
//--------------------------------------------------------------------------
flag CBBSurge::EvalFlowEquations(eScdFlwEqnTasks Task, CSpPropInfo *pProps, int IONo, int FE, int LnkNo)
{
//IOFB(0,FE)->SetRegulator(m_FRB.What());
//return IOFB(IONo,FE)->EvaluateFlwEqn(pProps, VPB.ActualPosition(this), &IOFBFlng_Rmt(0)->PhD(), &IOFBFlng_Rmt(1)->PhD());//, IOP_Flng(0), IOP_Flng(1));
return DoEvalFlowEquations(Task, /*pProps,*/ IONo, FE, LnkNo);
}
//--------------------------------------------------------------------------
void CBBSurge::EvalProducts(CNodeEvalIndex & NEI)
{
//MN_Surge::EvalProducts(JoinMask);
DoEvalProducts(NEI);
}
//--------------------------------------------------------------------------
void CBBSurge::EvalIntegral(CNodeEvalIndex & NEI)
{
DoEvalIntegral(NEI);
SetIntegralDone(true);
}
//--------------------------------------------------------------------------
void CBBSurge::EvalDiscrete() { DoEvalDiscrete(); }
void CBBSurge::EvalCtrlInitialise(eScdCtrlTasks Tasks) { DoEvalCtrlInitialise(Tasks); }
void CBBSurge::EvalCtrlActions(eScdCtrlTasks Tasks) { DoEvalCtrlActions(Tasks); }
void CBBSurge::EvalCtrlStrategy(eScdCtrlTasks Tasks) { DoEvalCtrlStrategy(Tasks); }
void CBBSurge::EvalCtrlTerminate(eScdCtrlTasks Tasks) { DoEvalCtrlTerminate(Tasks); }
void CBBSurge::EvalStatistics(eScdCtrlTasks Tasks) { DoEvalStatistics(Tasks); }
void CBBSurge::EvalPowerAvailable() { DoEvalPowerAvailable(); }
void CBBSurge::EvalPowerRequired() { DoEvalPowerRequired(); }
void CBBSurge::EvalState() { DoEvalState(); }
void CBBSurge::SetState(eScdMdlStateActs RqdState) { DoSetState(RqdState); }
//--------------------------------------------------------------------------
void CBBSurge::ClosureInfo()
{
if (m_Closure.DoFlows() || m_Closure.DoContent())
{
CClosureInfo &CI=m_Closure[0];
if (NoFlwIOs()>0)
MN_Surge::ClosureInfo();
MVector RefVec(CI.m_pRefMdl);
MClosureInfo MI(m_Closure, RefVec);
DoClosureInfo(MI);
}
};
//--------------------------------------------------------------------------
void CBBSurge::OnAppActivate(BOOL bActive)
{
if (bActive)
{
DoOnAppActivate(bActive);
MdlNode::OnAppActivate(bActive);
}
};
//--------------------------------------------------------------------------
int CBBSurge::FilesUsed(CFilesUsedArray & Files)
{
DoFilesUsed(Files);
MdlNode::FilesUsed(Files);
return Files.GetCount();
};
//--------------------------------------------------------------------------
dword CBBSurge::ModelStatus()
{
dword Status=MN_Surge::ModelStatus();
//if (NoFlwIOs()>1)
// {
// const long iIn = (IOQmEst_In(0)>0.0 ? 0 : 1);
// Status |= (IOConduit(iIn)->QMass()>gs_DisplayZeroFlow ? FNS_UFlw : FNS_UNoFlw);
// }
//else if (NoFlwIOs()==1)
// Status |= FNS_Error;
return Status;
}
//--------------------------------------------------------------------------
flag CBBSurge::GetModelAction(CMdlActionArray & Acts)
{
return DoGetModelAction(Acts);
};
flag CBBSurge::SetModelAction(CMdlAction & Act)
{
return DoSetModelAction(Act);
};
//--------------------------------------------------------------------------
flag CBBSurge::GetModelGraphic(CMdlGraphicArray & Grfs)
{
return DoGetModelGraphic(Grfs);
};
flag CBBSurge::OperateModelGraphic(CMdlGraphicWnd & Wnd, CMdlGraphic & Grf)
{
return DoOperateModelGraphic(Wnd, Grf);
};
//--------------------------------------------------------------------------
void CBBSurge::MacroMdlEvaluate(eScdMacroMdlEvals Eval) { DoMacroMdlEvaluate(Eval); };
flag CBBSurge::MacroMdlValidNd(int iIONo) { return DoMacroMdlValidNd(iIONo); };
void CBBSurge::MacroMdlAddNd(int iIONo) { DoMacroMdlAddNd(iIONo); };
void CBBSurge::MacroMdlRemoveNd(int iIONo) { DoMacroMdlRemoveNd(iIONo); };
CMacroMdlBase* CBBSurge::MacroMdlActivate() { return DoMacroMdlActivate(); };
void CBBSurge::MacroMdlDeactivate() { DoMacroMdlDeactivate(); };
//--------------------------------------------------------------------------
flag CBBSurge::CIStrng(int No, pchar & pS)
{
switch (No-CBContext())
{
case 1: pS="E\tIncorrect feed stream connection!"; return 1;
case 2: pS="E\tIncorrect product stream connection!"; return 1;
case 3: pS="E\tRequired product stream not connected!"; return 1;
case 4: pS="W\tNo Size distributions defined"; return 1;
case 5: pS="E\tTotal Size mass does NOT equal corresponding specie mass"; return 1;
default:
return MN_Surge::CIStrng(No, pS);
}
}
//===========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
44
],
[
46,
70
],
[
82,
89
],
[
91,
106
],
[
108,
155
],
[
157,
173
],
[
175,
231
],
[
233,
296
],
[
298,
299
],
[
301,
304
],
[
306,
306
],
[
308,
313
],
[
319,
343
],
[
349,
354
],
[
358,
367
],
[
369,
376
],
[
399,
423
]
],
[
[
45,
45
]
],
[
[
71,
81
],
[
90,
90
],
[
107,
107
],
[
156,
156
],
[
174,
174
],
[
232,
232
],
[
297,
297
],
[
300,
300
],
[
305,
305
],
[
307,
307
],
[
314,
318
],
[
344,
348
],
[
355,
357
],
[
368,
368
],
[
377,
398
]
]
]
|
108733f4a2f77a07683ab7bb84e4e3810f794169 | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/GUI/Resolution.cpp | 05a50b3b142b08c162b09452366ada04101fd03f | []
| no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cpp | #include "Resolution.h"
namespace HovUni {
Resolution::Resolution(int width, int height, bool relWidth, bool relHeight)
: IResolution(), mWidth(width), mHeight(height), mRelativeWidth(relWidth), mRelativeHeight(relHeight) {
}
int Resolution::getWidth() {
if (!isWidthRelative()) {
return mWidth;
} else {
//Is the parent resolution set?
if (mParentResolution.get() == 0) {
THROW(NoParentResolutionException, "A scaled resolution can only be calculated if the parent resolution is set");
}
return (int) ((mWidth / 100.0f) * mParentResolution->getWidth()); //Return percentage
}
}
int Resolution::getHeight() {
if (!isHeightRelative()) {
return mHeight;
} else {
//Is the parent resolution set?
if (mParentResolution.get() == 0) {
THROW(NoParentResolutionException, "A scaled resolution can only be calculated if the parent resolution is set");
}
return (int) ((mHeight / 100.0f) * mParentResolution->getHeight()); //Return percentage
}
}
} | [
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
]
| [
[
[
1,
35
]
]
]
|
8b282170629769235bd5c43ea11ba840201ec23b | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/change_activate_forward.hpp | e0514508a4ba18b5d57552497d885d304b9a4ae9 | []
| 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 | 14,598 | hpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
#ifndef AOSLCPP_AOSL__CHANGE_ACTIVATE_FORWARD_HPP
#define AOSLCPP_AOSL__CHANGE_ACTIVATE_FORWARD_HPP
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/version.hxx>
#if (XSD_INT_VERSION != 3030000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
#include <xsd/cxx/xml/dom/serialization-header.hxx>
#include <xsd/cxx/tree/serialization.hxx>
#include <xsd/cxx/tree/serialization/byte.hxx>
#include <xsd/cxx/tree/serialization/unsigned-byte.hxx>
#include <xsd/cxx/tree/serialization/short.hxx>
#include <xsd/cxx/tree/serialization/unsigned-short.hxx>
#include <xsd/cxx/tree/serialization/int.hxx>
#include <xsd/cxx/tree/serialization/unsigned-int.hxx>
#include <xsd/cxx/tree/serialization/long.hxx>
#include <xsd/cxx/tree/serialization/unsigned-long.hxx>
#include <xsd/cxx/tree/serialization/boolean.hxx>
#include <xsd/cxx/tree/serialization/float.hxx>
#include <xsd/cxx/tree/serialization/double.hxx>
#include <xsd/cxx/tree/serialization/decimal.hxx>
#include <xsd/cxx/tree/std-ostream-operators.hxx>
/**
* @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema
* schema namespace.
*/
namespace xml_schema
{
// anyType and anySimpleType.
//
/**
* @brief C++ type corresponding to the anyType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::type Type;
/**
* @brief C++ type corresponding to the anySimpleType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::simple_type< Type > SimpleType;
/**
* @brief Alias for the anyType type.
*/
typedef ::xsd::cxx::tree::type Container;
// 8-bit
//
/**
* @brief C++ type corresponding to the byte XML Schema
* built-in type.
*/
typedef signed char Byte;
/**
* @brief C++ type corresponding to the unsignedByte XML Schema
* built-in type.
*/
typedef unsigned char UnsignedByte;
// 16-bit
//
/**
* @brief C++ type corresponding to the short XML Schema
* built-in type.
*/
typedef short Short;
/**
* @brief C++ type corresponding to the unsignedShort XML Schema
* built-in type.
*/
typedef unsigned short UnsignedShort;
// 32-bit
//
/**
* @brief C++ type corresponding to the int XML Schema
* built-in type.
*/
typedef int Int;
/**
* @brief C++ type corresponding to the unsignedInt XML Schema
* built-in type.
*/
typedef unsigned int UnsignedInt;
// 64-bit
//
/**
* @brief C++ type corresponding to the long XML Schema
* built-in type.
*/
typedef long long Long;
/**
* @brief C++ type corresponding to the unsignedLong XML Schema
* built-in type.
*/
typedef unsigned long long UnsignedLong;
// Supposed to be arbitrary-length integral types.
//
/**
* @brief C++ type corresponding to the integer XML Schema
* built-in type.
*/
typedef long long Integer;
/**
* @brief C++ type corresponding to the nonPositiveInteger XML Schema
* built-in type.
*/
typedef long long NonPositiveInteger;
/**
* @brief C++ type corresponding to the nonNegativeInteger XML Schema
* built-in type.
*/
typedef unsigned long long NonNegativeInteger;
/**
* @brief C++ type corresponding to the positiveInteger XML Schema
* built-in type.
*/
typedef unsigned long long PositiveInteger;
/**
* @brief C++ type corresponding to the negativeInteger XML Schema
* built-in type.
*/
typedef long long NegativeInteger;
// Boolean.
//
/**
* @brief C++ type corresponding to the boolean XML Schema
* built-in type.
*/
typedef bool Boolean;
// Floating-point types.
//
/**
* @brief C++ type corresponding to the float XML Schema
* built-in type.
*/
typedef float Float;
/**
* @brief C++ type corresponding to the double XML Schema
* built-in type.
*/
typedef double Double;
/**
* @brief C++ type corresponding to the decimal XML Schema
* built-in type.
*/
typedef double Decimal;
// String types.
//
/**
* @brief C++ type corresponding to the string XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::string< char, SimpleType > String;
/**
* @brief C++ type corresponding to the normalizedString XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString;
/**
* @brief C++ type corresponding to the token XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::token< char, NormalizedString > Token;
/**
* @brief C++ type corresponding to the Name XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::name< char, Token > Name;
/**
* @brief C++ type corresponding to the NMTOKEN XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken;
/**
* @brief C++ type corresponding to the NMTOKENS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens;
/**
* @brief C++ type corresponding to the NCName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::ncname< char, Name > Ncname;
/**
* @brief C++ type corresponding to the language XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::language< char, Token > Language;
// ID/IDREF.
//
/**
* @brief C++ type corresponding to the ID XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::id< char, Ncname > Id;
/**
* @brief C++ type corresponding to the IDREF XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref;
/**
* @brief C++ type corresponding to the IDREFS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs;
// URI.
//
/**
* @brief C++ type corresponding to the anyURI XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri;
// Qualified name.
//
/**
* @brief C++ type corresponding to the QName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname;
// Binary.
//
/**
* @brief Binary buffer type.
*/
typedef ::xsd::cxx::tree::buffer< char > Buffer;
/**
* @brief C++ type corresponding to the base64Binary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary;
/**
* @brief C++ type corresponding to the hexBinary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary;
// Date/time.
//
/**
* @brief Time zone type.
*/
typedef ::xsd::cxx::tree::time_zone TimeZone;
/**
* @brief C++ type corresponding to the date XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date< char, SimpleType > Date;
/**
* @brief C++ type corresponding to the dateTime XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime;
/**
* @brief C++ type corresponding to the duration XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration;
/**
* @brief C++ type corresponding to the gDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday;
/**
* @brief C++ type corresponding to the gMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth;
/**
* @brief C++ type corresponding to the gMonthDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay;
/**
* @brief C++ type corresponding to the gYear XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear;
/**
* @brief C++ type corresponding to the gYearMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth;
/**
* @brief C++ type corresponding to the time XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::time< char, SimpleType > Time;
// Entity.
//
/**
* @brief C++ type corresponding to the ENTITY XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entity< char, Ncname > Entity;
/**
* @brief C++ type corresponding to the ENTITIES XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities;
// Namespace information and list stream. Used in
// serialization functions.
//
/**
* @brief Namespace serialization information.
*/
typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo;
/**
* @brief Namespace serialization information map.
*/
typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap;
/**
* @brief List serialization stream.
*/
typedef ::xsd::cxx::tree::list_stream< char > ListStream;
/**
* @brief Serialization wrapper for the %double type.
*/
typedef ::xsd::cxx::tree::as_double< Double > AsDouble;
/**
* @brief Serialization wrapper for the %decimal type.
*/
typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal;
/**
* @brief Simple type facet.
*/
typedef ::xsd::cxx::tree::facet Facet;
// Flags and properties.
//
/**
* @brief Parsing and serialization flags.
*/
typedef ::xsd::cxx::tree::flags Flags;
/**
* @brief Parsing properties.
*/
typedef ::xsd::cxx::tree::properties< char > Properties;
// Parsing/serialization diagnostics.
//
/**
* @brief Error severity.
*/
typedef ::xsd::cxx::tree::severity Severity;
/**
* @brief Error condition.
*/
typedef ::xsd::cxx::tree::error< char > Error;
/**
* @brief List of %error conditions.
*/
typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics;
// Exceptions.
//
/**
* @brief Root of the C++/Tree %exception hierarchy.
*/
typedef ::xsd::cxx::tree::exception< char > Exception;
/**
* @brief Exception indicating that the size argument exceeds
* the capacity argument.
*/
typedef ::xsd::cxx::tree::bounds< char > Bounds;
/**
* @brief Exception indicating that a duplicate ID value
* was encountered in the object model.
*/
typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId;
/**
* @brief Exception indicating a parsing failure.
*/
typedef ::xsd::cxx::tree::parsing< char > Parsing;
/**
* @brief Exception indicating that an expected element
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement;
/**
* @brief Exception indicating that an unexpected element
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement;
/**
* @brief Exception indicating that an expected attribute
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute;
/**
* @brief Exception indicating that an unexpected enumerator
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator;
/**
* @brief Exception indicating that the text content was
* expected for an element.
*/
typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent;
/**
* @brief Exception indicating that a prefix-namespace
* mapping was not provided.
*/
typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping;
/**
* @brief Exception indicating that the type information
* is not available for a type.
*/
typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo;
/**
* @brief Exception indicating that the types are not
* related by inheritance.
*/
typedef ::xsd::cxx::tree::not_derived< char > NotDerived;
/**
* @brief Exception indicating a serialization failure.
*/
typedef ::xsd::cxx::tree::serialization< char > Serialization;
/**
* @brief Error handler callback interface.
*/
typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler;
/**
* @brief DOM interaction.
*/
namespace dom
{
/**
* @brief Automatic pointer for DOMDocument.
*/
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
/**
* @brief DOM user data key for back pointers to tree nodes.
*/
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
#include "aosl/change_forward.hpp"
// Forward declarations.
//
namespace aosl
{
class Change_activate;
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__CHANGE_ACTIVATE_FORWARD_HPP
| [
"klaim@localhost"
]
| [
[
[
1,
610
]
]
]
|
78d3123d55674d59dfe6dde289cc4008d327f527 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/Listener.h | 229eba58c1a09e2d636bd86f28a61275e5ea63ed | []
| no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | h | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of the author.
*/
#pragma once
class CEventManager;
class CListener
{
private:
CEventManager *m_pEventManager;
public:
CListener(CEventManager *pEventManager);
// you must call Start() if your derived class instance
// uses this constructor
CListener(void);
~CListener(void);
void Start(CEventManager *pEventManager);
void Stop(void);
virtual void OnEvent(int EventID, void *pData) = 0;
};
| [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
]
| [
[
[
1,
50
]
]
]
|
1974e9cb46ff8a008960bc8eb932b9a98ea45481 | 61fc00b53ce93f09a6a586a48ae9e484b74b6655 | /src/tool/src/rendering/drawsimpleobject.cpp | 35703b2a8f2e7122e55e4f03ea33df8cf4b38dca | []
| no_license | mickaelgadroy/wmavo | 4162c5c7c8d9082060be91e774893e9b2b23099b | db4a986d345d0792991d0e3a3d728a4905362a26 | refs/heads/master | 2021-01-04T22:33:25.103444 | 2011-11-04T10:44:50 | 2011-11-04T10:44:50 | 1,381,704 | 2 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 22,325 | cpp |
/*******************************************************************************
Copyright (C) 2011 Mickael Gadroy, University of Reims Champagne-Ardenne (Fr)
Project managers: Eric Henon and Michael Krajecki
Financial support: Region Champagne-Ardenne (Fr)
This file is part of WmAvo (WiiChem project)
WmAvo - Integrate the Wiimote and the Nunchuk in Avogadro software for the
handling of the atoms and the camera.
For more informations, see the README file.
WmAvo is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
WmAvo 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 WmAvo. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "drawsimpleobject.h"
const Eigen::Vector3d DrawSimpleObject::m_vect3d0(0,0,0) ;
const double DrawSimpleObject::m_PI=103993.0/33102.0 ; // PI approximation.
DrawSimpleObject::DrawSimpleObject( Avogadro::GLWidget *widget )
: m_widget(widget), m_painter(NULL), m_qglwidget(NULL)
{
if( m_widget != NULL )
{
m_painter = widget->painter() ;
m_qglwidget = dynamic_cast<QGLWidget*>(m_widget) ;
// Initiate my projection matrix.
double w=(double)(m_widget->width()) ;
double h=(double)(m_widget->height()) ;
GLdouble fovy=m_widget->camera()->angleOfViewY() ;
GLdouble aspect=w/h ;
GLdouble nearPlan=1.0 ;
GLdouble farPlan=100.0 ;
glMatrixMode( GL_PROJECTION ) ;
glPushMatrix() ;
glLoadIdentity() ;
gluPerspective( fovy, aspect, nearPlan, farPlan ) ;
glGetFloatv( GL_MODELVIEW_MATRIX, m_projectionMatrix ) ;
glPopMatrix() ;
glMatrixMode(GL_MODELVIEW) ;
}
else
{
for( int i=0 ; i<16 ; i++ )
m_projectionMatrix[i] = 0 ;
}
m_gluQuadricGluLine = gluNewQuadric() ;
gluQuadricDrawStyle( m_gluQuadricGluLine, GLU_LINE ) ;
m_gluQuadricGluFill = gluNewQuadric() ;
gluQuadricDrawStyle( m_gluQuadricGluFill, GLU_FILL ) ;
}
DrawSimpleObject::~DrawSimpleObject()
{
gluDeleteQuadric( m_gluQuadricGluLine ) ;
gluDeleteQuadric( m_gluQuadricGluFill ) ;
}
/**
* Get the orientation directions of XYZ-axis.
* @param rightX_out X component of X-axis.
* @param rightY_out Y component of X-axis.
* @param rightZ_out Z component of X-axis.
* @param upX_out X component of Y-axis.
* @param upY_out Y component of Y-axis.
* @param upZ_out Z component of Y-axis.
* @param dirX_out X component of Z-axis.
* @param dirY_out Y component of Z-axis.
* @param dirZ_out Z component of Z-axis.
*/
void DrawSimpleObject::getRightUpDirectionCamera
( double &rightX_out, double &rightY_out, double &rightZ_out,
double &upX_out, double &upY_out, double &upZ_out,
double &dirX_out, double &dirY_out, double &dirZ_out )
{
GLdouble modelview[16] ; // Where The 16 Doubles Of The Modelview Matrix Are To Be Stored
glGetDoublev( GL_MODELVIEW_MATRIX, modelview ) ; // Retrieve The Modelview Matrix
rightX_out = modelview[0] ;
rightY_out = modelview[4] ;
rightZ_out = modelview[8] ;
upX_out = modelview[1] ;
upY_out = modelview[5] ;
upZ_out = modelview[9] ;
dirX_out = -modelview[2] ;
dirY_out = -modelview[6] ;
dirZ_out = -modelview[10] ;
}
/**
* Convert a screen position to an openGl position on the near plan.
* @param p_in The screen position in input.
* @param X_out The X component position in ouput.
* @param Y_out The Y component position in ouput.
* @param Z_out The Z component position in ouput.
*/
void DrawSimpleObject::getPosScreenToPosOpenGL
( const QPoint &p_in, double &X_out, double &Y_out, double &Z_out )
{
GLint viewport[4] ; // Where The Viewport Values Will Be Stored
GLdouble modelview[16] ; // Where The 16 Doubles Of The Modelview Matrix Are To Be Stored
GLdouble projection[16] ; // Where The 16 Doubles Of The Projection Matrix Are To Be Stored
glGetDoublev( GL_MODELVIEW_MATRIX, modelview ) ; // Retrieve The Modelview Matrix
glGetDoublev( GL_PROJECTION_MATRIX, projection ) ; // Retrieve The Projection Matrix
glGetIntegerv( GL_VIEWPORT, viewport ) ; // Retrieves The Viewport Values (X, Y, Width, Height)
QPoint p=m_widget->mapFromGlobal(p_in) ;
GLfloat winX=(float)p.x() ;
GLfloat winY=(float)viewport[3] - (float)p.y() ;
GLfloat winZ=0 ;
// Get the 1st intersection with the openGL object.
//glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
// Widget position to openGL position.
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &X_out, &Y_out, &Z_out);
}
/**
* Print the last openGL error in a terminal.
*/
void DrawSimpleObject::printOpenGLError()
{
GLenum errCode ;
const GLubyte *errString ;
if( (errCode=glGetError()) != GL_NO_ERROR )
{
errString = gluErrorString( errCode ) ;
fprintf (stderr, "OpenGL Error: %s\n", errString);
}
}
/**
* Print the modelview and projection matrix in a terminal.
*/
void DrawSimpleObject::printModelviewAndProjectionMatrix()
{
GLdouble modelview[16] ; // Where The 16 Doubles Of The Modelview Matrix Are To Be Stored
GLdouble projection[16] ; // Where The 16 Doubles Of The Projection Matrix Are To Be Stored
glGetDoublev( GL_MODELVIEW_MATRIX, modelview ) ; // Retrieve The Modelview Matrix
glGetDoublev( GL_PROJECTION_MATRIX, projection ) ; // Retrieve The Projection Matrix
printf( "modelview: " ) ;
for( int i=0 ; i<16 ; i++ )
printf( " %.3lf", modelview[i] ) ;
printf( "\n" ) ;
printf( "projection:" ) ;
for( int i=0 ; i<16 ; i++ )
printf( " %.3lf", projection[i] ) ;
printf( "\n" ) ;
}
/**
* Print the 3D stereoscopic possibilities of the software and the hardware.
*/
void DrawSimpleObject::print3DStereoPossibilities()
{
// 1
QGLFormat fmt ;
fmt.setStereo( true ) ;
printf( "3D Stereo by QGLFormat:%d\n", (int)(fmt.stereo()) ) ;
// 2
GLboolean hasStereo[1] ;
glGetBooleanv(GL_STEREO, hasStereo) ;
printf( "3D Stereo by glGetBooleanv:%d\n", (int)(hasStereo[0]) ) ;
printOpenGLError() ;
// 3
if( m_widget == NULL )
{
printf( "DrawSimpleObject::print3DStereoPossibilities: m_widget==NULL !\n" ) ;
}
else
{
QGLFormat fmt2=m_widget->format() ;
fmt2.setStereo(true) ;
m_widget->setFormat(fmt) ;
bool hasStereo2=m_widget->format().stereo() ;
printf( "3D Stereo by m_widget.QGLFormat:%d\n", (int)(hasStereo2) ) ;
if( !hasStereo2 )
{
// ok, goggles off
if (!m_widget->format().hasOverlay())
printf( "Cool hardware required !!!\n" ) ;
else
printf( "Cool hardware OK !\n" ) ;
}
}
}
/**
* Draw a line.
* @param begin Position on one side.
* @param end Position on the other side.
* @param colorBegin Color of the line (on one side).
* @param colorEnd Color of the line (on the other side).
* @param lineWidth Width of the line.
*/
void DrawSimpleObject::drawLine( const Eigen::Vector3d& begin, const Eigen::Vector3d& end, const QColor &colorBegin, const QColor &colorEnd, float lineWidth )
{
unsigned char r, g, b, a ;
unsigned char r2, g2, b2, a2 ;
r = (unsigned char)( colorBegin.red() ) ;
g = (unsigned char)( colorBegin.green() ) ;
b = (unsigned char)( colorBegin.blue() ) ;
a = (unsigned char)( colorBegin.alpha() ) ;
r2 = (unsigned char)( colorEnd.red() ) ;
g2 = (unsigned char)( colorEnd.green() ) ;
b2 = (unsigned char)( colorEnd.blue() ) ;
a2 = (unsigned char)( colorEnd.alpha() ) ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
// If active, do not paint the atom !!!
// glLoadIdentity();
// If no active, do not change color !!!
glDisable( GL_LIGHTING ) ;
glLineWidth( lineWidth ) ;
glBegin( GL_LINES ) ;
glColor4ub( r, g, b, a ) ;
glVertex3d( begin[0], begin[1], begin[2] ) ;
glColor4ub( r2, g2, b2, a2 ) ;
glVertex3d( end[0], end[1], end[2] ) ;
glEnd() ;
glPopAttrib() ;
}
/**
* Draw a rectangle in the render zone. If color==NULL, the inverse color of the
* background is used.
* @param p1 The up/left position of the rectangle.
* @param p2 The bottom/right position of the rectangle.
* @param color RGBA components.
*/
void DrawSimpleObject::drawRect( const QPoint &p1, const QPoint &p2, const QColor* color )
{
drawRect( (float)p1.x(), (float)p1.y(), (float)p2.x(), (float)p2.y(), color ) ;
}
/**
* Draw a rectangle in the render zone. If color==NULL, the inverse color of the
* background is used.
* @param sx The up/left position in x of the rectangle.
* @param sy The up/left position in y of the rectangle.
* @param ex The bottom/right position in x of the rectangle.
* @param ey The bottom/right position in y of the rectangle.
* @param color RGBA components.
*/
void DrawSimpleObject::drawRect( float sx, float sy, float ex, float ey, const QColor* color )
{
unsigned char rBg=0, gBg=0, bBg=0, aBg=0 ;
unsigned char rLimit=0, gLimit=0, bLimit=0 ;
QColor bgColor=m_widget->background() ;
unsigned char rWBg=0, gWBg=0, bWBg=0 ;
rWBg = (unsigned char)(bgColor.red()) ;
gWBg = (unsigned char)(bgColor.green()) ;
bWBg = (unsigned char)(bgColor.blue()) ;
if( color == NULL )
{ // Calculate the inverse color.
rBg = 255 - rWBg ;
gBg = 255 - gWBg ;
bBg = 255 - bWBg ;
aBg = 150 ;
}
else
{
rBg=(unsigned char)(color->red()) ; bBg=(unsigned char)(color->blue()) ;
gBg=(unsigned char)(color->green()) ; aBg=(unsigned char)(color->alpha()) ;
}
//printf( "%d %d %d - %d %d %d\n", rBg, gBg, bBg, bgColor.red(), bgColor.green(), bgColor.blue() ) ;
rLimit = ( rBg>=rWBg ? rBg-rWBg : rWBg-rBg ) >> 1 ; // /2
gLimit = ( gBg>=gWBg ? gBg-gWBg : gWBg-gBg ) >> 1 ;
bLimit = ( bBg>=bWBg ? bBg-bWBg : bWBg-bBg ) >> 1 ;
glPushMatrix();
glLoadIdentity();
GLdouble projection[16];
glGetDoublev(GL_PROJECTION_MATRIX,projection);
GLdouble modelview[16];
glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
GLdouble startPos[3], endPos[3] ;
gluUnProject( double(sx), double(viewport[3])-double(sy), 0.1,
modelview, projection, viewport,
&startPos[0], &startPos[1], &startPos[2] ) ;
gluUnProject( double(ex), double(viewport[3])-double(ey), 0.1,
modelview, projection, viewport,
&endPos[0], &endPos[1], &endPos[2] ) ;
glPushAttrib(GL_ALL_ATTRIB_BITS) ;
glPushMatrix() ;
glLoadIdentity() ;
glEnable(GL_BLEND) ;
glDisable(GL_LIGHTING) ;
glDisable(GL_CULL_FACE) ;
glColor4ub( rBg, gBg, bBg, aBg ) ;
glBegin(GL_POLYGON);
glVertex3d(startPos[0],startPos[1],startPos[2]);
glVertex3d(startPos[0],endPos[1],startPos[2]);
glVertex3d(endPos[0],endPos[1],startPos[2]);
glVertex3d(endPos[0],startPos[1],startPos[2]);
glEnd();
startPos[2] += 0.0001;
glDisable(GL_BLEND);
glColor3ub( rLimit, gLimit, bLimit ) ;
glBegin(GL_LINE_LOOP);
glVertex3d(startPos[0],startPos[1],startPos[2]);
glVertex3d(startPos[0],endPos[1],startPos[2]);
glVertex3d(endPos[0],endPos[1],startPos[2]);
glVertex3d(endPos[0],startPos[1],startPos[2]);
glEnd();
glPopMatrix();
glPopAttrib();
glPopMatrix();
}
/**
* Draw a circle.
* param posX X-axis position component
* param posY Y-axis position component
* param posZ Z-axis position component
* param rightX X-axis right component
* param rightY Y-axis right component
* param rightZ Z-axis right component
* param upX X-axis up component
* param upY Y-axis up component
* param upZ Z-axis up component
* param dirX X-axis direction component
* param dirY Y-axis direction component
* param dirZ Z-axis direction component
* param radius The radius of the circle
* param color The color of the circle
*/
void DrawSimpleObject::drawCircle( double posX, double posY, double posZ,
double rightX, double rightY, double rightZ,
double upX, double upY, double upZ,
double dirX, double dirY, double dirZ,
float radius, const QColor color )
{
float maxCircle=(float)(2.0*m_PI);
float step=(float)(m_PI/10.0) ;
double a=0, b=0, x=0, y=0, z=0 ;
unsigned char red, green, blue , alpha ;
red = (unsigned char)( color.red() ) ;
green = (unsigned char)( color.green() ) ;
blue = (unsigned char)( color.blue() ) ;
alpha = (unsigned char)( color.alpha() ) ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor4ub( red, green, blue, alpha ) ;
glBegin( GL_LINE_LOOP ) ;
for( float i=0 ; i<maxCircle ; i+=step )
{
a = radius * cosf(i) ;
b = radius * sinf(i) ;
x = posX + rightX * a + upX * b + -1.0*dirX ;
y = posY + rightY * a + upY * b + -1.0*dirY ;
z = posZ + rightZ * a + upZ * b + -1.0*dirZ ;
glVertex3d( x, y, z ) ;
}
glEnd() ;
glPopAttrib();
}
/**
* Draw a "line sphere" in the render zone.
* @param radius Radius of the sphere.
* @param from The position of the sphere.
* @param color RGBA components.
*/
void DrawSimpleObject::drawSphereLine( float radius, const Eigen::Vector3d& from, const QColor &color )
{
this->drawSphere( m_gluQuadricGluLine, radius, from, color ) ;
}
/**
* Draw a "fill sphere" in the render zone.
* @param radius Radius of the sphere.
* @param from The position of the sphere.
* @param color RGBA components.
*/
void DrawSimpleObject::drawSphereFill( float radius, const Eigen::Vector3d& from, const QColor &color )
{
this->drawSphere( m_gluQuadricGluFill, radius, from, color, 5, 5 ) ;
}
/**
* Draw a sphere in the render zone.
* @param radius Radius of the sphere.
* @param from The position of the sphere.
* @param color RGBA components.
* @param slices Number of sphere slices
* @param stacks Number of sphere stacks
*/
void DrawSimpleObject::drawSphere( GLUquadric* type, float radius, const Eigen::Vector3d& from, const QColor &color, int slices, int stacks )
{
unsigned char r, g, b, a ;
r = (unsigned char)( color.red() ) ;
g = (unsigned char)( color.green() ) ;
b = (unsigned char)( color.blue() ) ;
a = (unsigned char)( color.alpha() ) ;
// Init & Save.
glPushMatrix() ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
// If active, do not paint the atom !!!
// glLoadIdentity();
// If no active, do not change color !!!
glDisable(GL_LIGHTING) ;
glColor4ub( r, g, b, a ) ;
glTranslated( from[0], from[1], from[2] ) ;
glRotatef( 22, 1, 0 , 0 ) ; // Just not to see the sphere at the bottom ...
gluSphere( type, radius, slices, stacks ) ;
// type : GLUquadric = options
// radius : radius : rayon de la sphère.
// 10 : slices : lontitudes.
// 10 : stacks : latitudes.
glPopAttrib();
glPopMatrix() ;
}
/**
* Draw a text in the render zone on XYZ-axis (based on OpenGL-coordinate).
* @param pos The position of text
* @param msg Message to display
* @param font Font ...
* @param color RGBA components.
*/
void DrawSimpleObject::drawTextOnXYZ( const QPoint& pos, const QString &msg, const QFont &font, const QColor &color )
{
if( m_widget!=NULL )
{
unsigned char r, g, b, a ;
r = (unsigned char)( color.red() ) ;
g = (unsigned char)( color.green() ) ;
b = (unsigned char)( color.blue() ) ;
a = (unsigned char)( color.alpha() ) ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor4ub( r, g, b, a ) ;
if( m_qglwidget != NULL )
m_qglwidget->renderText( pos.x(), pos.y(), 0, msg, font ) ;
else
m_painter->drawText( pos, msg ) ;
glPopAttrib() ;
}
}
/**
* Draw a sphere in the render zone on XYZ-axis (based on OpenGL-coordinate).
* @param pos The position of text.
* @param msg Message to display
* @param font Font ...
* @param color RGBA components.
*/
void DrawSimpleObject::drawTextOnXYZ( const Eigen::Vector3d& pos, const QString &msg, const QFont &font, const QColor &color )
{
if( m_widget!=NULL )
{
unsigned char r, g, b, a ;
r = (unsigned char)( color.red() ) ;
g = (unsigned char)( color.green() ) ;
b = (unsigned char)( color.blue() ) ;
a = (unsigned char)( color.alpha() ) ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor4ub( r, g, b, a ) ;
if( m_qglwidget != NULL )
m_qglwidget->renderText( pos[0], pos[1], pos[2], msg, font ) ;
else
m_painter->drawText( pos, msg ) ;
glPopAttrib() ;
}
}
/**
* Draw a sphere in the render zone on XY-axis (based on screen-coordinate).
* Using the Qt method, change the size with the font size.
* @param pos The position of text.
* @param msg Message to display
* @param font Font ...
* @param color RGBA components.
*/
void DrawSimpleObject::drawTextOnXY( const QPoint& pos, const QString &msg, const QFont &font, const QColor &color )
{
if( m_widget != NULL )
{
unsigned char r, g, b, a ;
r = (unsigned char)( color.red() ) ;
g = (unsigned char)( color.green() ) ;
b = (unsigned char)( color.blue() ) ;
a = (unsigned char)( color.alpha() ) ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor4ub( r, g, b, a ) ;
if( m_qglwidget != NULL )
m_qglwidget->renderText( pos.x(), pos.y(), msg, font ) ;
else
m_painter->drawText( pos, msg ) ;
glPopAttrib() ;
}
}
/**
* Draw a sphere in the render zone on XY-axis (based on screen-coordinate).
* @param pos The position of text.
* @param msg Message to display.
* @param font Font ...
* @param color RGBA components.
*/
void DrawSimpleObject::drawTextOnXY( const Eigen::Vector3d& pos, const QString &msg, const QFont &font, const QColor &color )
{
if( m_widget!=NULL )
{
unsigned char r, g, b, a ;
r = (unsigned char)( color.red() ) ;
g = (unsigned char)( color.green() ) ;
b = (unsigned char)( color.blue() ) ;
a = (unsigned char)( color.alpha() ) ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor4ub( r, g, b, a ) ;
if( m_qglwidget!=NULL )
{
Eigen::Vector3d proj=m_widget->camera()->project(pos) ;
QPoint p( (int)proj[0], (int)proj[1] ) ;
m_qglwidget->renderText( (int)pos.x(), (int)pos.y(), msg, font ) ;
}
else
m_painter->drawText( pos, msg ) ;
glPopAttrib() ;
}
}
/**
* All method to render/draw text in the render zone.
*/
void DrawSimpleObject::drawTestAllMethod()
{
if( m_widget!=NULL )
{
QString msg ;
QFont myFont( "Times", 32, QFont::Bold ) ;
// 1, Origin : Up/left screen. Nothing change during a camera movement.
Avogadro::Painter *painter=m_widget->painter() ;
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor3f( 1.0, 1.0, 1.0 ) ;
msg="Painter : DrawText() 1" ;
painter->drawText( 150, 10, msg ) ;
painter->drawText( QPoint(150,30), msg ) ;
glPopAttrib() ;
// 2 Change with the camera like a point in the 3D-space
// ! Works sometime ... Realize 2 calls of this method => don't work ...
//glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
//glColor3f( 1.0, 1.0, 1.0 ) ;
//msg="Painter : DrawText() 2" ;
// Origin : center screen.
//painter->drawText( Eigen::Vector3d(0,0,0), msg, myFont ) ;
//glPopAttrib() ;
// 3.0 ! Painter class isn't a derived class of QPainter.
//QPainter *myQPainter=dynamic_cast<QPainter*>(painter) ;
// 3.1, Display, but in black ... Be carefull of the background color.
//glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
//glPushMatrix() ;
//glColor3f( 1.0, 1.0, 1.0 ) ;
//QPainter myQPainter ;
//myQPainter.begin(m_widget) ;
//msg = "Qt::QPainter : DrawText() 3.1" ;
//myQPainter.drawText( QPoint(150,70), msg ) ;
//msg = "Qt::QPainter : DrawText() 3.2" ;
//myQPainter.drawText( 150, 80, 150, 150, Qt::AlignLeft, msg ) ;
//myQPainter.end() ;
//glPopMatrix() ;
//glPopAttrib() ;
// 3.2 No tested ... I do not understand when use it to "gain" performance.
//QStaticText test ;
//myQPainter.drawStaticText( 150, 130, ) ;
//myQPainter.end() ;
//glPopAttrib() ;
// 4 Works sometime, The font size change with zoom.
// Problem with others visual feature like the blue selection ...
//glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
//glColor3f( 1.0, 1.0, 1.0 ) ;
//msg="QWidget : renderText() 4" ;
//m_widget->renderText( 40, 200, 0, msg, myFont ) ;
//glPopAttrib() ;
// 5 Nothing change during a camera movement.
glPushAttrib( GL_ALL_ATTRIB_BITS ) ;
glColor3f( 1.0, 1.0, 1.0 ) ;
QGLWidget *myWidget=dynamic_cast<QGLWidget*>(m_widget) ;
if( myWidget != NULL )
{
msg="Qt::QWidget : renderText() 5" ;
myWidget->renderText( 40, 40, msg, myFont ) ;
msg="Qt::QWidget : renderText() 5.1" ;
// Sometime below the previous message, sometime in the 3D-space coordonate.
myWidget->renderText( 80, 80, 0, msg, myFont ) ;
msg="Qt::QWidget : renderText() 5.2" ;
myWidget->renderText( -6.879, 0.298, 0.51, msg, myFont ) ;
}
else
{
msg="Qt::QWidget : renderText() 5 FALSE" ;
painter->drawText( 100, 140, msg ) ;
}
glPopAttrib() ;
}
}
| [
"[email protected]"
]
| [
[
[
1,
701
]
]
]
|
f6478593320f90a3aeeaf03c1387619bbcf95147 | a0d4f557ddaf4351957e310478e183dac45d77a1 | /src/Utils/TextureMan.cpp | 74e33c3cbec1ae23abc542b8b2c281363ab43864 | []
| no_license | houpcz/Houp-s-level-editor | 1f6216e8ad8da393e1ee151e36fc37246279bfed | c762c9f5ed064ba893bf34887293a73dd35a06f8 | refs/heads/master | 2016-09-11T11:03:34.560524 | 2011-08-09T11:37:49 | 2011-08-09T11:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,386 | cpp | #include "TextureMan.h"
#include "TexturePNG.h"
#include "TextureTGA.h"
#include "TextureBMP.h"
#include <stdlib.h>
#include <iterator>
C_TextureMan * C_TextureMan::inst = NULL;
C_TextureMan* C_TextureMan::Inst()
{
if (inst == NULL)
{
inst = new C_TextureMan;
}
return inst;
}
C_TextureMan::C_TextureMan()
{
loader[C_TextureTGA().GetSufix()] = new C_TextureTGA();
loader[C_TexturePNG().GetSufix()] = new C_TexturePNG();
loader[C_TextureBMP().GetSufix()] = new C_TextureBMP();
}
C_TextureMan::~C_TextureMan()
{
map<string, C_TextureLoader *>::iterator itVec;
for(itVec = loader.begin(); itVec != loader.end(); itVec++)
{
delete itVec->second;
}
ClearTextures();
}
void C_TextureMan::ClearTextures()
{
map<string, S_Texture *>::iterator it;
for(it = texture.begin(); it != texture.end(); it++)
{
delete it->second;
}
texture.clear();
}
S_Texture * C_TextureMan::GetTexture(string src)
{
if(texture.find(src) == texture.end())
{
S_Texture * s_texture = new S_Texture;
if(LoadTexture(s_texture, src.c_str()))
{
texture[src] = s_texture;
} else {
delete s_texture;
return NULL;
}
}
return texture[src];
}
void C_TextureMan::MakeTexture(S_Texture * texture) {
glGenTextures(1, &(*texture).texID);
glBindTexture(GL_TEXTURE_2D, (*texture).texID);
glTexImage2D(GL_TEXTURE_2D, 0, (*texture).bpp / 8, (*texture).width, (*texture).height, 0, (*texture).type, GL_UNSIGNED_BYTE, (*texture).imageData);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
if ((*texture).imageData) {
free((*texture).imageData);
}
}
bool C_TextureMan::LoadTexture(S_Texture * text, const char * src)
{
C_TextureLoader * load = NULL;
string srcString = string(src);
string srcSufix = srcString.substr(srcString.length() - 3, 3);
load = loader[srcSufix];
if(load == NULL)
{
fprintf(stderr, "There is no loader for images with sufix %s", srcSufix.c_str());
return false;
}
if(load->Load(text, src))
{
MakeTexture(text);
return true;
}
else
return false;
}
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
26d2351ac16204aac03d8a7f7a73c45c4d372ffe | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/geometries/witness_2/Witness_landmark_set_2.h | c85d3eaa35554371d6a8cf467aa0dc0329a48bf7 | []
| 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 | WINDOWS-1252 | C++ | false | false | 10,574 | 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 Armin Häberling, ETH Zurich
*
* $Id: Witness_Landmark_set_2.h 342 2008-02-29 10:51:56Z arminha $
*/
#ifndef MESECINA_WITNESS_LANDMARK_SET_2_H
#define MESECINA_WITNESS_LANDMARK_SET_2_H
#include "Witness_vertex_base_2.h"
#include "Witness_complex_triangulation_2.h"
#include <constants.h>
#include <cassert>
#include <set>
#include <vector>
#include <map>
#include <utility>
#include <CGAL/Point_set_2.h>
#include <CGAL/Triangulation_data_structure_2.h>
#include <CGAL/squared_distance_2.h>
/**
* Manages the witness point set and the landmarks set, which is a subset of the witness points.
* For the witness points the lists of N-nearest landmarks for each point are maintained.
*
* The ::nearest_k_landmarks queriy is limited to k <= N+1.
*
* The ::next_landmark_max_min query returns the witness point farthest from the current landmarks.
*
* The ::next_landmark_alpha determines the next landmark in an adaptive manner.
*/
template <class K, int N>
class Witness_landmark_set_2 {
public:
typedef CGAL::Point_set_2 <K,
CGAL::Triangulation_data_structure_2 <
Witness_vertex_base_2 <K, N>
>
> Witness_triangulation;
typedef typename Witness_triangulation::Point Point;
typedef typename K::Vector_2 Vector;
typedef typename Witness_triangulation::Finite_vertices_iterator Witness_iterator;
typedef typename Witness_triangulation::Vertex_handle Witness_handle;
typedef typename std::list<Point> Landmark_list;
typedef typename std::list<Witness_handle> Witness_list;
typedef typename K::FT Coord_type;
typedef Witness_complex_triangulation_2<K> Witness_complex_triangulation;
/**
* Warning: this constructor clears the static Witness_triangulation witness_tri.
* Use the copy constructor to get a new Witness_Landmark_set_2 without erasing the witnesses.
*/
Witness_landmark_set_2() : complex_tri() {
witness_tri.clear();
landmarks.clear();
}
Witness_handle add_witness(const Point& witness) {
Witness_handle vh = witness_tri.insert(witness);
clear_landmarks();
return vh;
}
void remove_witness(Witness_handle witness) {
witness_tri.remove(witness);
clear_landmarks();
}
/**
* Adds a witness point to the landmark set and update the witness complex.
*/
void add_landmark(Witness_handle landmark) {
if (complex_tri.number_of_vertices() == 0) {
// we are adding the first landmark
// clean the additional data in the witness triangulation first
// so we start with clean data
std::cout << PROGRESS_STATUS << "Initializing Witness data" << std::endl;
std::cout << PROGRESS_MINIMUM << "0" << std::endl;
std::cout << PROGRESS_MAXIMUM << witness_tri.number_of_vertices() << std::endl;
Witness_iterator v_it, v_end = witness_end();
int i = 0;
for (v_it = witness_begin(); v_it != v_end; v_it++,i++) {
v_it->nearest_k_landmarks().clear();
v_it->set_landmark(false);
}
std::cout << PROGRESS_DONE << std::endl;
}
landmarks.push_back(landmark->point());
landmark->set_landmark(true);
// update witness complex
//std::cout << PROGRESS_STATUS << "Updating Witness Complex" << std::endl;
//std::cout << PROGRESS_MINIMUM << "0" << std::endl;
// update k nearest landmarks for the witnesses
Witness_list witnesses_to_be_processed = update_k_nearest_landmarks(landmark);
//std::cout << PROGRESS_MAXIMUM << witnesses_to_be_processed.size()-1 << std::endl;
Point p = landmark->point();
complex_tri.insert(p);
Witness_list::iterator w_it, w_end = witnesses_to_be_processed.end();
int i = 0;
for (w_it = witnesses_to_be_processed.begin(); w_it != w_end; w_it++, i++) {
std::vector<Point> nl = nearest_k_landmarks(*w_it,3);
std::vector<Point> nl_old;
int p_ind = 0;
std::vector<Point>::iterator nl_it, nl_end = nl.end();
for (nl_it = nl.begin(); nl_it != nl_end; nl_it++) {
if (*nl_it == p) {
p_ind = nl_it - nl.begin();
} else {
nl_old.push_back(*nl_it);
}
}
// add/remove edges
if (p_ind < N)
{
const int s = std::min<double>(N-1, (int) nl_old.size());
// add new edges with p
complex_tri.add_edge_witness(p, nl_old.begin(), nl_old.begin() + s);
if (nl_old.size() >= N)
{
// remove edges with q
const Point q = nl_old[N-1];
complex_tri.remove_edge_witness(q, nl_old.begin(), nl_old.begin() + (N-1));
}
}
}
//std::cout << PROGRESS_DONE << std::endl;
}
void clear_landmarks() {
landmarks.clear();
complex_tri.clear();
}
void clear_all() {
witness_tri.clear();
clear_landmarks();
}
Witness_iterator witness_begin() {
return witness_tri.finite_vertices_begin();
}
Witness_iterator witness_end() {
return witness_tri.finite_vertices_end();
}
size_t number_of_witnesses() const {
return witness_tri.number_of_vertices();
}
Witness_handle nearest_witness(Point p) {
return witness_tri.nearest_vertex(p);
}
Witness_triangulation * witness_triangulation() {
return &witness_tri;
}
Witness_complex_triangulation * witness_complex_triangulation() {
return &complex_tri;
}
Landmark_list& landmark_list() {
return landmarks;
}
Point nearest_landmark(Witness_handle witness) {
return witness->nearest_k_landmarks()[0];
}
std::vector<Point> nearest_k_landmarks(Witness_handle witness, int k) {
std::vector<Point> nkl = witness->nearest_k_landmarks();
int i;
int n = min(k, (int) nkl.size());
std::vector<Point> res(n);
for (i = 0; i < n; i++) {
res[i] = nkl[i];
}
return res;
}
/**
* determines the next landmark in a max-min fashion.
*
* i.e.
*
* p = argmax_{w in W} d(w,L)
where
d(w,L) = min_{v in L} d(w,v)$
*/
Witness_handle next_landmark_max_min() {
if (landmarks.empty()) {
// add an arbitrary witness as first landmark
return witness_begin();
}
// std::cout << "Searching next landmark..." << std::endl;
// std::cout << PROGRESS_STATUS << "Searching next landmark" << std::endl;
// std::cout << PROGRESS_MINIMUM << "0" << std::endl;
// std::cout << PROGRESS_MAXIMUM << number_of_witnesses()-1 << std::endl;
Coord_type max_dist = 0;
Witness_handle res;
Witness_iterator w_it, w_end = witness_end();
int i = 0;
for (w_it = witness_begin(); w_it != w_end; w_it++, i++) {
// std::cout << PROGRESS_VALUE << i << std::endl;
if (!w_it->is_landmark()) {
const Point & nl = nearest_landmark(w_it);
const Coord_type dist = CGAL::squared_distance(w_it->point(),nl);
if (dist > max_dist) {
max_dist = dist;
res = w_it;
}
}
}
// std::cout << PROGRESS_DONE << std::endl;
// std::cout << "epsilon = " << sqrt(max_dist) << std::endl;
epsilon = sqrt(CGAL::To_double<Coord_type>()(max_dist));
// std::cout << "Done." << std::endl;
return res;
}
/**
* Return the maximal value epsilon for which the landmarks are an epsilon-sparse sample
*/
double get_epsilon() {
return epsilon;
}
Witness_handle next_landmark_alpha(Coord_type alpha) {
typedef typename Witness_triangulation::Vertex_circulator Vertex_circulator;
if (landmarks.empty()) {
// add an arbitrary witness as first landmark
return witness_begin();
}
std::cout << "Searching next landmark..." << std::endl;
std::cout << PROGRESS_STATUS << "Searching next landmark" << std::endl;
std::cout << PROGRESS_MINIMUM << "0" << std::endl;
std::cout << PROGRESS_MAXIMUM << number_of_witnesses()-1 << std::endl;
Coord_type max_dist = -1;
Witness_handle res;
Witness_iterator w_it, w_end = witness_end();
int i = 0;
for (w_it = witness_begin(); w_it != w_end; w_it++, i++) {
std::cout << PROGRESS_VALUE << i << std::endl;
if (!w_it->is_landmark()) {
Point nl = nearest_landmark(w_it);
Coord_type dist = CGAL::squared_distance(w_it->point(),nl);
// add penalty
Witness_handle nn;
Vertex_circulator nn_it, nn_begin = witness_tri.incident_vertices(w_it);
if (nn_begin != 0) {
Coord_type nn_dist = CGAL::squared_distance(w_it->point(), nn_begin->point());
nn_it = nn_begin;
nn_it++;
for (; nn_it != nn_begin; nn_it++) {
nn_dist = min(nn_dist, CGAL::squared_distance(w_it->point(), nn_it->point()));
}
dist -= alpha * nn_dist;
}
if (dist > max_dist || max_dist < -1) {
max_dist = dist;
res = w_it;
}
}
}
std::cout << PROGRESS_DONE << std::endl;
std::cout << "Done." << std::endl;
return res;
}
private:
Landmark_list landmarks;
/*static */Witness_triangulation witness_tri;
Witness_complex_triangulation complex_tri;
double epsilon;
Witness_list update_k_nearest_landmarks(Witness_handle ph) {
typedef typename Witness_triangulation::Vertex_circulator Vertex_circulator;
Witness_list res;
Point p = ph->point();
// init marks
witness_tri.init_vertex_marks();
witness_tri.mark_vertex(witness_tri.infinite_vertex());
witness_tri.mark_vertex(ph);
ph->add_landmark(p);
res.push_back(ph);
std::queue<Witness_handle> process;
process.push(ph);
while (!process.empty()) {
Witness_handle vh = process.front();
process.pop();
// iterate through all delaunay neighbours of vh
Vertex_circulator n_begin = witness_tri.incident_vertices(vh);
Vertex_circulator n_it = n_begin;
if (n_it != 0) {
do {
Witness_handle nh = n_it.base();
//if (! this->is_infinite(nh)) {
if (! witness_tri.is_marked(nh)) {
witness_tri.mark_vertex(nh);
if (nh->add_landmark(p)) {
// p is in the k nearest landmarks
process.push(nh);
res.push_back(nh);
}
}
//}
n_it++;
} while (n_it != n_begin);
}
}
return res;
}
};
//template < class K, int N>
//CGAL::Point_set_2 <K, CGAL::Triangulation_data_structure_2 <Witness_vertex_base_2 <K, N> > > Witness_Landmark_set_2<K, N>::witness_tri =
// CGAL::Point_set_2 <K, CGAL::Triangulation_data_structure_2 <Witness_vertex_base_2 <K, N> > >();
#endif // MESECINA_WITNESS_LANDMARK_SET_2_H
| [
"balint.miklos@localhost"
]
| [
[
[
1,
355
]
]
]
|
256ccade6e6e50978bbf018c2b0a396c84f66f7e | d4a7bdadb66cb90ff25c033c50485bf1d5c7dfa3 | /src/Mesh.h | 381aaf76c1b33218229b2e3311871a38c0c61fc1 | []
| no_license | atrzaska/rwgltest | 5c1be4105a11f5d66524eb95023f6ce743ab31f8 | a857773db90cc7028b6197036cd3604c39cedb36 | refs/heads/master | 2021-05-28T16:48:06.128199 | 2011-12-22T22:22:21 | 2011-12-22T22:22:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | h | /* Copyright (C) 2011 Andrzej Trzaska
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef MESH_H_
#define MESH_H_
#include <string>
#include <vector>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
using namespace std;
struct Vertex {
float x, y, z;
};
struct Normal {
float x, y, z;
};
struct TexCoord {
float u, v;
};
struct Face {
GLuint Vertex[3];
GLuint Normal[3];
GLuint TexCoord[3];
GLuint TextureNo;
};
struct Material {
string name;
GLfloat ambient[3];
GLfloat diffuse[3];
GLfloat specular[3];
GLbyte illum;
GLuint matId;
};
class Mesh {
protected:
string name;
vector<Vertex> VertexArray;
vector<Normal> NormalArray;
vector<TexCoord> TexCoordArray;
vector<Face> FaceArray;
vector<Material> Materials;
};
#endif /* MESH_H_ */
| [
"[email protected]@6fd63c64-eb38-cfd0-a5bf-51302b3bf559"
]
| [
[
[
1,
75
]
]
]
|
3e89a06a36c54c58e07f22180ffccf6f76c8bc94 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/windows/handle.test.cpp | bd2b1e7ea19d69be5eee984f87a3c0049fe02d84 | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,198 | cpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cbear.berlios.de/windows/handle.hpp>
int main()
{
}
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
27
]
]
]
|
4c77fdc71728eac9d35dff2c4b3d987041b511a1 | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/SmartWires/SystemUtils/Asserts/SmartAsserts.cpp | c3fe10376c07538238819220b3b6711984800e04 | []
| 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 | WINDOWS-1251 | C++ | false | false | 3,513 | cpp | // Достаточно добавить этот файл в проект и все!!
// После этого все ассерты будут выдавать ошибку с полным стеком вызова в особый файл
// - "debughelper.log" в корне упавшей программы
// Только для работы будет требоваться debughelper.dll и pdb файлы
// Без pdb файлов в лог тоже будет писаться информация из стека, правда без названий функций
#ifdef _DEBUG
#ifndef _SMARTASSERT_H_
#define _SMARTASSERT_H_
#include <afx.h>
#include <afxwin.h>
#include <afxext.h>
#ifndef DEBUG_NEW
// Для поиска утечек памяти
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
// Нужно чтобы компилировалось один раз - в stdafx.cpp
#define DEBUG_HELPER "debughelper"
#define DA_USEDEFAULTS 0x0000
#define DA_SHOWMSGBOX 0x0001
#define DA_SHOWODS 0x0002
#define DA_SHOWSTACKTRACE 0x0004
// Prototype...
int DebugHelper(int nRptType, char *szMsg, int *retVal);
typedef BOOL (FAR WINAPI *FARDA_PROC)(DWORD dwOverrideOpts, LPCTSTR szMsg, char* pOutBuf, long lOutBufSize);
// Class...
class CAssertWrapper
{
HINSTANCE m_hInstance;
public:
CAssertWrapper()
{
// Грузим длл
m_hInstance=LoadLibrary(DEBUG_HELPER".dll");
if(m_hInstance){
// Устанавливаем хук на ассерты
_CrtSetReportHook(DebugHelper);
}
};
~CAssertWrapper()
{
_CrtSetReportHook(NULL);
if(m_hInstance){
FreeLibrary(m_hInstance);
m_hInstance=NULL;
}
};
BOOL WriteAssert(const char* szText)
{
if(!m_hInstance){
m_hInstance=LoadLibrary(DEBUG_HELPER".dll");
}
BOOL bRes=FALSE;
if(m_hInstance){
char szStackData[4096]="Stack gathering failed";
FARDA_PROC fp=(FARDA_PROC)GetProcAddress(m_hInstance,"DiagAssert");
if(fp){
int iBoxRes=(*fp)(DA_SHOWSTACKTRACE|DA_SHOWMSGBOX, szText , szStackData, sizeof(szStackData));
if(::GetAsyncKeyState(VK_SHIFT)<0){
AfxMessageBox(szStackData);
}
// Сохраняем!!! - после мессадж бокса, так как текст сохранения идет именно из него
HANDLE pFile=CreateFile(
"debughelp.log",
GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH,
NULL);
if(pFile){
SetFilePointer(pFile,-2,0,FILE_END);
DWORD dwWritten=0;
WriteFile(pFile, szStackData, strlen(szStackData), &dwWritten, NULL);
CloseHandle(pFile);
// Все ок
bRes=TRUE;
}
if (iBoxRes == IDRETRY){
DebugBreak();
}
if (iBoxRes == IDABORT){
ExitProcess ( (UINT)-1 ) ;
}
}else{
m_hInstance=NULL;
}
}
return bRes;
}
};
#pragma message("\nWarning: Including SmartAssert!! <---------------------\n\n")
__declspec ( dllexport ) CAssertWrapper assertWrapperObject;
int DebugHelper(int nRptType, char *szMsg, int *retVal)
{
BOOL bHandled=FALSE;
if(nRptType!=_CRT_WARN){//_CRT_ERROR,_CRT_ASSERT
_CrtSetReportHook(NULL);// Чтобы небыло супер циклов..
bHandled=assertWrapperObject.WriteAssert(szMsg);
_CrtSetReportHook(DebugHelper);
}
return bHandled;
}
#endif
#endif | [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
]
| [
[
[
1,
116
]
]
]
|
ec8637ff546ce144d8e95fd89ce8d802d1b227c5 | c58f258a699cc866ce889dc81af046cf3bff6530 | /src/qmlib/tools/numpy.cpp | 72e3d777ef8fbc383f64ae74fe8981e011b02f29 | []
| no_license | KoWunnaKo/qmlib | db03e6227d4fff4ad90b19275cc03e35d6d10d0b | b874501b6f9e537035cabe3a19d61eed7196174c | refs/heads/master | 2021-05-27T21:59:56.698613 | 2010-02-18T08:27:51 | 2010-02-18T08:27:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cpp |
#include <qmlib/python/numpy.hpp>
QM_NAMESPACE2(python)
using namespace boost::python;
QM_NAMESPACE_END2 | [
"[email protected]"
]
| [
[
[
1,
15
]
]
]
|
bb813a4884aecb0c28d200da1ba3b3a371f763c0 | 30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff | /jmail/config.cpp | 80fe5c95985b124973a3bcb2bea355648c946586 | []
| 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 | 8,415 | cpp | // config.cpp
#include "stdafx.h"
#define var(c) ((c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='_')
#define num(c) (c>='0'&&c<='9')
const static char* keywords[] = {
"address","sysop","bbsname","phone","place",
"flags","timezone","inbound","inboundunsec","log",
"chat_log","comport","baudrate","min_baud_in","min_baud_out",
"waitmdmanswer","modem_delay","init_interval","init1","init2",
"ok","busy","connect","no_dial","ring",
"ncarrier","dial_terminate","dial_prefix","dial_suffix","onhook",
"modem_answer","error_correction","time_dial","call_tries","circle",
"call_time","answer","emsi_oh","answer_ring","wait_carrier",
"protocol_use",""
};
class errorsCfg {
public: char err[80];
errorsCfg(const char *l){ strcpy(err,l); }
};
static int getfromint(char *val)
{
int i = 0;
while(num(*val)){ i*=10;i+=*val-'0';val++;}
if (*val) throw errorsCfg("invalid number");
return i;
}
static CString getfromCString(char *val)
{
if(*val!='"'||val[1]==0||val[strlen(val)-1]!='"') throw errorsCfg("wrong string");
val[strlen(val)-1]=0;return CString(val+1);
}
void config::defvar(int varn,char *value)
{
switch(varn){
case 0: address=getfromCString(value);break;
case 1: sysop=getfromCString(value);break;
case 2: bbsname=getfromCString(value);break;
case 3: phone=getfromCString(value);break;
case 4: place=getfromCString(value);break;
case 5: flags=getfromCString(value);break;
case 6: timezone=getfromint(value);break;
case 7: inbound=getfromCString(value);break;
case 8: inboundunsec=getfromCString(value);break;
case 9: log=getfromCString(value);break;
case 10: chat_log=getfromCString(value);break;
case 11: comport=getfromCString(value);break;
case 12: baudrate=getfromint(value);break;
case 13: min_baud_in=getfromint(value);break;
case 14: min_baud_out=getfromint(value);break;
case 15: waitmdmanswer=getfromint(value);break;
case 16: modem_delay=getfromint(value);break;
case 17: init_interval=getfromint(value);break;
case 18: init1=getfromCString(value);break;
case 19: init2=getfromCString(value);break;
case 20: ok=getfromCString(value);break;
case 21: busy=getfromCString(value);break;
case 22: connect=getfromCString(value);break;
case 23: no_dial=getfromCString(value);break;
case 24: ring=getfromCString(value);break;
case 25: ncarrier=getfromCString(value);break;
case 26: dial_terminate=getfromCString(value);break;
case 27: dial_prefix=getfromCString(value);break;
case 28: dial_suffix=getfromCString(value);break;
case 29: onhook=getfromCString(value);break;
case 30: modem_answer=getfromCString(value);break;
case 31: error_correction=getfromCString(value);break;
case 32: time_dial=getfromint(value);break;
case 33: call_tries=getfromint(value);break;
case 34: circle=getfromint(value);break;
case 35: call_time=getfromCString(value);break;
case 36: answer=getfromCString(value);break;
case 37: emsi_oh=getfromCString(value);break;
case 38: answer_ring=getfromint(value);break;
case 39: wait_carrier=getfromint(value);break;
case 40:
if (!strcmp(value,"hydra")) protocol_use=pr_hydra;
else if (!strcmp(value,"zmodem")) protocol_use=pr_zmodem;
else throw errorsCfg("invalid value");break;
}
}
void config::readconfig(const char *n,const char *section)
{
FILE *f;
char s[128],*h,*l;
DWORD lines = 0,i,e,q=0;
defaults();
if ((f=fopen(n,"r"))==NULL){
sprintf(s,"`%s' not found",n);
throw errors(s);
}
while (fgets(s,128,f)!=NULL){
lines++;h=s;
while(*h) if (*h=='#'||*h=='\n') *h=0;else h++;
h=s;while(*h==' ') h++;
if (!*h) continue;
if (*h=='['){
l=h;while(*l) if (*l==']') *l=0;else l++;
q=!strcmp(h+1,section);continue;
}
if(!q) continue;
l=h;while(*l) l++;l--;
while(l>h&&*l==' ') *l--=0;
if (!var(*h)){
sprintf(s,"%s(%i): wrong line",n,lines);
throw errors(s);
}
l=h;while(var(*l)) l++;
if (*l=='=') *l++=0;
else {
*l++=0;
while(*l&&*l!='=') l++;
if (!*l){
sprintf(s,"%s(%i): wrong line",n,lines);
throw errors(s);
}
*l++=0;
}
while(*l==' ') l++;
for(i=e=0;*keywords[i];i++) if(!strcmp(h,keywords[i])){
try {
e=1;defvar(i,l);
}
catch(errorsCfg& e){
sprintf(s,"%s(%i): %s",n,lines,e.err);
throw errors(s);
}
}
if (!e){
sprintf(s,"%s(%i): unknown parameter `%s'",n,lines,h);
throw errors(s);
}
}
fclose(f);
}
void config::writeconfig(const char *n,const char *section)
{
FILE *f,*old=NULL;
char s[30],w[128],*h;
if(!rename(n,"jMail.tmp"))
old=fopen("jMail.tmp","r");
if ((f=fopen(n,"w"))==NULL){
sprintf(w,"`%s' not created",n);
throw errors(w);
}
if (old){
while(fgets(w,128,old)!=NULL){
h=w;while(*h) if (*h=='\n') *h=0;else h++;
if (*w=='['){ h=w;while(*h) if (*h==']') *h=0;else h++; }
if (*w=='['&&(!strcmp(w+1,section))){
while(fgets(w,128,old)!=NULL){
if (*w=='[') break;*w=0;
}
break;
} else { fprintf(f,"%s\n",w);}
}
fprintf(f,"[%s]\n",section);
} else {
fprintf(f,"# %s\n\n[%s]\n",n,section);
}
fprintf(f,"\n");
fprintf(f,"address=\"%s\"\n",address);
fprintf(f,"sysop=\"%s\"\n",sysop);
fprintf(f,"bbsname=\"%s\"\n",bbsname);
fprintf(f,"phone=\"%s\"\n",phone);
fprintf(f,"place=\"%s\"\n",place);
fprintf(f,"flags=\"%s\"\n",flags);
fprintf(f,"timezone=%i\n",timezone);
fprintf(f,"inbound=\"%s\"\n",inbound);
fprintf(f,"inboundunsec=\"%s\"\n",inboundunsec);
fprintf(f,"log=\"%s\"\n",log);
fprintf(f,"chat_log=\"%s\"\n",chat_log);
fprintf(f,"\n");
fprintf(f,"comport=\"%s\"\n",comport);
fprintf(f,"baudrate=%i\n",baudrate);
fprintf(f,"min_baud_in=%i\n",min_baud_in);
fprintf(f,"min_baud_out=%i\n",min_baud_out);
fprintf(f,"waitmdmanswer=%i\n",waitmdmanswer);
fprintf(f,"modem_delay=%i\n",modem_delay);
fprintf(f,"init_interval=%i\n",init_interval);
fprintf(f,"init1=\"%s\"\n",init1);
fprintf(f,"init2=\"%s\"\n",init2);
fprintf(f,"ok=\"%s\"\n",ok);
fprintf(f,"busy=\"%s\"\n",busy);
fprintf(f,"connect=\"%s\"\n",connect);
fprintf(f,"no_dial=\"%s\"\n",no_dial);
fprintf(f,"ring=\"%s\"\n",ring);
fprintf(f,"ncarrier=\"%s\"\n",ncarrier);
fprintf(f,"dial_terminate=\"%s\"\n",dial_terminate);
fprintf(f,"dial_prefix=\"%s\"\n",dial_prefix);
fprintf(f,"dial_suffix=\"%s\"\n",dial_suffix);
fprintf(f,"onhook=\"%s\"\n",onhook);
fprintf(f,"modem_answer=\"%s\"\n",modem_answer);
fprintf(f,"error_correction=\"%s\"\n",error_correction);
fprintf(f,"\n");
fprintf(f,"time_dial=%i\n",time_dial);
fprintf(f,"call_tries=%i\n",call_tries);
fprintf(f,"circle=%i\n",circle);
fprintf(f,"call_time=\"%s\"\n",call_time);
fprintf(f,"\n");
fprintf(f,"answer=\"%s\"\n",answer);
fprintf(f,"emsi_oh=\"%s\"\n",emsi_oh);
fprintf(f,"answer_ring=%i\n",answer_ring);
fprintf(f,"wait_carrier=%i\n",wait_carrier);
switch(protocol_use){
case pr_hydra: strcpy(s,"hydra");break;
case pr_zmodem: strcpy(s,"zmodem");break;
} fprintf(f,"protocol_use=%s\n",s);
if(old){
fprintf(f,"\n");
if (*w) fprintf(f,"%s",w);
while (fgets(w,128,old)!=NULL) fprintf(f,"%s",w);
fclose(old);
unlink("jMail.tmp");
}
fclose(f);
}
void config::defaults()
{
address="unknown";
sysop="unknown";
bbsname="bbs";
phone="-Unpublished-";
place="unknown";
flags="";
timezone=0;
inbound="";
inboundunsec="";
log="";
chat_log="";
comport="com2";
baudrate=57600;
min_baud_in=9600;
min_baud_out=9600;
waitmdmanswer=4;
modem_delay=2;
init_interval=20;
init1="ATZ|";
init2="";
ok="OK";
busy="BUSY";
connect="CONNECT";
no_dial="NO DIAL TONE";
ring="RING";
ncarrier="NO CARRIER";
dial_terminate="v\''^\'|";
dial_prefix="ATD";
dial_suffix="|";
onhook="~v~~^~ATH0|";
modem_answer="ATA|";
error_correction="V42|MNP|COMP";
time_dial=60;
call_tries=15;
circle=10;
call_time="0:00-24:00";
answer="";
emsi_oh="0:00-0:00";
answer_ring=0;
wait_carrier=50;
protocol_use=pr_hydra;
}
| [
"[email protected]"
]
| [
[
[
1,
280
]
]
]
|
698452ce1a152b99f7069e43617bfea728bbe36a | ade08cd4a76f2c4b9b5fdbb9b9edfbc7996b1bbc | /computer_graphics/lab4/Src/Application/grid.h | 1717a81a29159eb53c84f6689f8ae457d9f7e369 | []
| no_license | smi13/semester07 | 6789be72d74d8d502f0a0d919dca07ad5cbaed0d | 4d1079a446269646e1a0e3fe12e8c5e74c9bb409 | refs/heads/master | 2021-01-25T09:53:45.424234 | 2011-01-07T16:08:11 | 2011-01-07T16:08:11 | 859,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,268 | h | #ifndef _grid_h
#define _grid_h
#include <d3dx9.h>
#include "object.h"
namespace cg_labs
{
class Grid : public Object
{
public:
Grid( const char *name, D3DXVECTOR3 (*func)( float u, float v ),
D3DXVECTOR3 (*funcNormal)( D3DXVECTOR3 vec ), int M, int N, DWORD color,
bool lightenup = true, bool to_render = true );
void setFunction( D3DXVECTOR3 (*_func)( float u, float v ) );
void setColor( DWORD color );
virtual D3DPRIMITIVETYPE getPrimitiveType();
virtual void render();
virtual ~Grid();
private:
Grid();
void _buildObject();
DWORD _color;
int _m, _n;
D3DXVECTOR3 (*_func)( float u, float v );
D3DXVECTOR3 (*_funcNormal)( D3DXVECTOR3 vec );
};
namespace grid_functions
{
D3DXVECTOR3 plane( float u, float v );
D3DXVECTOR3 torus( float u, float v );
D3DXVECTOR3 sphere( float u, float v );
D3DXVECTOR3 cylinder( float u, float v );
D3DXVECTOR3 cone( float u, float v );
D3DXVECTOR3 moebius_strip( float u, float v );
D3DXVECTOR3 planeNormal( D3DXVECTOR3 vec );
D3DXVECTOR3 sphereNormal( D3DXVECTOR3 vec );
}
}
#endif /* _grid_h */ | [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
be3b8f4dba29cb693ea130e3420b7c33e4c609da | 4b116281b895732989336f45dc65e95deb69917b | /Code Base/GSP410-Project2/Star.h | 1685625c6f2312038ff3155b006f3c3d88eb477f | []
| no_license | Pavani565/gsp410-spaceshooter | 1f192ca16b41e8afdcc25645f950508a6f9a92c6 | c299b03d285e676874f72aa062d76b186918b146 | refs/heads/master | 2021-01-10T00:59:18.499288 | 2011-12-12T16:59:51 | 2011-12-12T16:59:51 | 33,170,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 126 | h | #pragma once
#include "Unit.h"
#include "Definitions.h"
class CStar : public CUnit
{
public:
CStar();
~CStar();
}; | [
"[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7"
]
| [
[
[
1,
10
]
]
]
|
1d9ce4f3cb574bc090b2d0b519b0ceecad8a79a1 | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /trunk/engine/src/SeqWeight.cpp | 47d4b00c13cd88aafc331330ca580d95f0bd2679 | []
| no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,505 | cpp | #include "SeqWeight.h"
#include "Sequence.h"
#include "SequenceDB.h"
#include "core/FixedStr.h"
#include "persistance/TextReader.h"
#include "persistance/StdInputStream.h"
#include <boost/algorithm/string.hpp>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cassert>
using namespace seed;
double SeqWeightDB::PositionalWeight::getPositionWeight (int index) const
{
debug_mustbe (index >= 0);
//
// we can use find_if because I don't expect more than
// 10 hot-spots in a sequence, and in this range
// find_if performs better than binary_search
Positions::const_iterator it = _positions.begin ();
for (; it != _positions.end () ; ++it) {
Entry* entry = (*it);
if (index < entry->_startIndex){
it = _positions.end ();
break;
}
else if (index < entry->_startIndex + entry->_length)
break;
}
if (it == _positions.end ())
return _weight;
else {
Entry* entry = (*it);
debug_mustbe (entry->_startIndex <= index && index < entry->_startIndex + entry->_length);
return entry->_weight;
}
}
double SeqWeightDB::PositionalWeight::getAveragePositionWeight (int index, int length) const
{
if (length <= 0)
return 0;
double weight = 0;
PositionalWeight::Iterator it (*this, index);
debug_mustbe (it.position ()<= index);
debug_mustbe (index <= it.position ()+ length);
for (int i=0 ; i<length ; ++i, it.advance (1)) {
weight += it.weight();
}
weight = weight / length;
return weight;
}
SeqWeightDB::PositionalWeight::Positions::const_iterator
SeqWeightDB::PositionalWeight::find (int position) const
{
if (_positions.size () <= 0)
return _positions.end ();
IndexEntryOrder predicate;
Positions::const_iterator result = std::upper_bound(_positions.begin (), _positions.end (), position, predicate);
debug_only (
if (result != _positions.end ()) {
debug_mustbe (!fitsEntry (**result, position));
debug_mustbe ((*result)->_startIndex > position);
}
);
if (result != _positions.begin ()) {
--result;
debug_mustbe ((*result)->_startIndex <= position);
if (fitsEntry (**result, position))
return result;
}
return _positions.end ();
}
//
//
// Format:
// >SeqName1 Wgt1
// >SeqName2 Wgt2
// ...
//
// example:
//
// >YFL048C 0.991742546801741
// >YOL116W 0.991742546801741
struct WeightsReader {
virtual ~WeightsReader () {
}
void read (const char* fname) {
std::ifstream in (fname);
if (! in.is_open()) {
mmustfail (
FixedStrBuffer<4 * 1024> ("unable to open weight file %s", fname)
);
}
read (in);
}
void read (std::istream& in) {
std::string name, s;
while (true) {
s.resize (0);
name.resize (0);
bool ok = true;
while (ok && s.size()==0) {
std::istream::sentry _ok(in);
if (ok = _ok)
in>>s;// skip empty lines;
}
if (!ok)
break;
// here we handle cases in which the ">" is/isn't separated from the name of the gene.
if (s ==">")
in>>name;
else {
assert(s[0]=='>');
name = s.substr(1);
}
/// remove trailing whitespace
boost::trim (name);
/// check if the name is unique in the weight file
std::pair <NameSet::iterator, bool> result = _entryNames.insert (name);
if (!result.second) {
/// we have already seen this sequence name
throw BaseException (
StrBuffer (Str ("The sequence named \""), Str (name), Str ("\" appears more than once in the weight file"))
);
}
readValue(in, Str (name));
}
}
virtual void readValue (std::istream& in, const Str&) = 0;
protected:
typedef std::set <std::string> NameSet;
NameSet _entryNames;
};
/*
AutoPtr <SeqWeightDB::Name2Weight>
SeqWeightDB::readWgtFile (const char* wgtFileName)
{
//
// we are not expected to deal with more than
struct SeqWeightsReader : public WeightsReader, AutoPtr <Name2Weight> {
SeqWeightsReader () {
set (new Name2Weight (_default_db_size));
}
virtual void readValue (std::ifstream& in,
const Str& name)
{
double val;
in>>val;
get ()->add(new SeqWeightDB::Name2Weight::Node(Str (name), val));
}
} reader;
reader.read (wgtFileName);
return reader.release();
}
*/
AutoPtr <SeqWeightDB::ID2Weight>
SeqWeightDB::computeWeightIndex (
const Name2Weight& weights, const SequenceDB& db)
{
AutoPtr <ID2Weight> id2weight = new ID2Weight;
Name2Weight::const_iterator it = weights.begin ();
for (;it != weights.end () ; ++it) {
Sequence* seq = db.getSequence(it->first);
debug_mustbe (seq);
if (seq) {
PositionalWeight_var weight = it->second;
if (seq->id () >= static_cast <Sequence::ID> (id2weight->size ())) {
/// make sure capacity is increased at least two fold
id2weight->reserve ((seq->id ()+1) * 2);
id2weight->resize (seq->id ()+1);
}
(*id2weight)[seq->id ()] = weight;
}
}
return id2weight;
}
//
// Positional weights:
//
//
// Format:
// >SeqName1 Wgt1 = [index1a, index1b] {Tab} Wgt2 = [index2a, index2b] {Tab}...
// ...
//
// example:
//
// >YFL048C 0.5 = [0, 100] 2.4 = [250, 300] 0.5 = [760, 900]
// >YOL116W 0.5 =[0, 70] 0.67 = [560, 700]
struct PosWeightsReader : public WeightsReader
{
PosWeightsReader ()
{
_posweights = new SeqWeightDB::Name2Weight;
_entries.reserve (10);
}
virtual void readValue (std::istream& sin, const Str& name)
{
double seqWeight;
sin>>seqWeight;
std::string buffer;
std::getline (sin, buffer);
readValue (buffer, name, seqWeight);
}
void readValue (const std::string& lineBuffer, const Str& name, double seqWeight) {
Str buffer = Str (lineBuffer).trimmedSubstring();
_entries.clear ();
while (!buffer.empty ()) {
double w;
int i1, i2;
int count = sscanf (buffer.getChars (), "%lf = [%d, %d]", &w, &i1, &i2);
Str::Index next = buffer.indexOf(']');
if ((next == Str::badIndex) || (count != 3) || (!(i1 <= i2) && (w>=0) && (w<=1) && (i1 >= 0))){
throw BaseException (
StrBuffer (
Str ("bad positional-weight format in "), name,
Str (":\nUnexpected "), buffer
)
);
}
/// this is a new entry
_entries.push_back(new SeqWeightDB::PositionalWeight::Entry (i1, i2-i1 + 1, seqWeight * w));
buffer = buffer.substring (next + 1);
buffer = buffer.trimmedSubstring();
}
_temp = name;
SeqWeightDB::PositionalWeight_var posWeight (
new SeqWeightDB::PositionalWeight (seqWeight, _entries)
);
_posweights->insert (
SeqWeightDB::Name2Weight::value_type (_temp, posWeight)
);
}
virtual void readValue (Persistance::TextReader& reader, const Str& name, double seqWeight)
{
_temp.setLength (0);
reader.readln (_temp);
}
StrBuffer _temp;
AutoPtr <SeqWeightDB::Name2Weight> _posweights;
SeqWeightDB::PositionalWeight::Positions _entries;
};
AutoPtr <SeqWeightDB::Name2Weight>
SeqWeightDB::readWgtFromFile (const char* weightFileName)
{
PosWeightsReader reader;
reader.read (weightFileName);
return reader._posweights;
}
AutoPtr <SeqWeightDB::Name2Weight>
SeqWeightDB::readWgtFromStream (std::istream& in)
{
PosWeightsReader reader;
reader.read (in);
return reader._posweights;
}
AutoPtr <SeqWeightDB::Name2Weight>
SeqWeightDB::readWgtFromString (const std::string& wgtString)
{
std::istringstream stream (wgtString);
return readWgtFromStream (stream);
}
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
]
| [
[
[
1,
307
]
]
]
|
d23e6082fed44837dfb041d0bf98ae84fa42d6c9 | f6529b63d418f7d0563d33e817c4c3f6ec6c618d | /source/config.hpp | 3b94807065a07a39f90eef628af0071450032ae5 | []
| no_license | Captnoord/Wodeflow | b087659303bc4e6d7360714357167701a2f1e8da | 5c8d6cf837aee74dc4265e3ea971a335ba41a47c | refs/heads/master | 2020-12-24T14:45:43.854896 | 2011-07-25T14:15:53 | 2011-07-25T14:15:53 | 2,096,630 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,726 | hpp |
#ifndef __CONFIG_HPP
#define __CONFIG_HPP
#include <map>
#include <string>
#include "video.hpp"
#include "smartptr.hpp"
#include "wstringEx.hpp"
class CColor;
class Vector3D;
class Config
{
public:
Config(void);
void clear(void) { m_domains.clear(); }
bool load(const char *filename = 0);
void save(void);
bool loaded(void) const { return m_loaded; }
bool has(const std::string &domain, const std::string &key) const;
// Set
void setWString(const std::string &domain, const std::string &key, const wstringEx &val);
void setString(const std::string &domain, const std::string &key, const std::string &val);
void setBool(const std::string &domain, const std::string &key, bool val);
void setOptBool(const std::string &domain, const std::string &key, int val);
void setInt(const std::string &domain, const std::string &key, int val);
void setFloat(const std::string &domain, const std::string &key, float val);
void setVector3D(const std::string &domain, const std::string &key, const Vector3D &val);
void setColor(const std::string &domain, const std::string &key, const CColor &val);
// Get
wstringEx getWString(const std::string &domain, const std::string &key, const wstringEx &defVal = wstringEx());
std::string getString(const std::string &domain, const std::string &key, const std::string &defVal = std::string());
bool getBool(const std::string &domain, const std::string &key, bool defVal = false);
int getOptBool(const std::string &domain, const std::string &key, int defVal = 2);
bool testOptBool(const std::string &domain, const std::string &key, bool defVal);
int getInt(const std::string &domain, const std::string &key, int defVal = 0);
float getFloat(const std::string &domain, const std::string &key, float defVal = 0.f);
Vector3D getVector3D(const std::string &domain, const std::string &key, const Vector3D &defVal = Vector3D());
CColor getColor(const std::string &domain, const std::string &key, const CColor &defVal = CColor());
//
const std::string &firstDomain(void);
const std::string &nextDomain(void);
const std::string &nextDomain(const std::string &start) const;
const std::string &prevDomain(const std::string &start) const;
bool hasDomain(const std::string &domain) const;
void copyDomain(const std::string &dst, const std::string &src);
private:
typedef std::map<std::string, std::string> KeyMap;
typedef std::map<std::string, KeyMap> DomainMap;
private:
bool m_loaded;
DomainMap m_domains;
std::string m_filename;
DomainMap::iterator m_iter;
static const std::string emptyString;
private:
Config(const Config &);
Config &operator=(const Config &);
};
#endif // !defined(__CONFIG_HPP)
| [
"[email protected]@a6d911d2-2a6f-2b2f-592f-0469abc2858f",
"captnoord@a6d911d2-2a6f-2b2f-592f-0469abc2858f"
]
| [
[
[
1,
15
],
[
17,
64
]
],
[
[
16,
16
]
]
]
|
a19405b759904ee19d8b71ec60733bbb0cafc4b2 | 96f15c5b0f5a76c7f1374a4286bbdda5670587c7 | /example/src/testApp.cpp | 7f1b3120f3e0a43fa9b4ee21ab18e1b57e20356f | []
| no_license | Ajay013/ofxUeye | 09aa8edc86b4f2132485144f3b646cdd0b6ba806 | 7e0ce9da8cdbe7830f2e4a27ca8b9e7a41971710 | refs/heads/master | 2020-03-24T17:24:40.875530 | 2011-08-07T21:07:18 | 2011-08-07T21:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,265 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
ofSetVerticalSync(true);
ofAddListener(ueye.events.dimensionChanged, this, &testApp::ueyeDimensionChanged);
ueye.setVerbose(true);
ueye.listDevices();
if(ueye.init())
{
//cout << (IS_BINNING_8X_VERTICAL | IS_BINNING_8X_HORIZONTAL) << endl;
// Get full area of the sensor, but skipping every second pixel
ueye.setBinning(IS_BINNING_2X_VERTICAL | IS_BINNING_2X_HORIZONTAL); // difference from subsamplimg? (apparently same bandwith but smoother image)
// smooth the bad pixels (apparently they come from factory with bad pixels...)
//ueye.enableBadPixelsCorrection();
// Set AOI (always set AOI after binning, subsampling or scaler, otherwise you might not get the desired result)
ofRectangle fullHD;
fullHD.width = 1920;
fullHD.height = 1080;
fullHD.x = 0;
fullHD.y = (ueye.getAOIMax().height - fullHD.height) * 0.5;
ueye.setAOI(fullHD);
//ueye.setAOINormalized(ofRectangle(0,0, 0.6, 0.6));
// Start grabbing pixels
//ueye.enableLive();
settings.setup(&ueye);
}
}
//--------------------------------------------------------------
void testApp::ueyeDimensionChanged(ofxUeyeEventArgs &args){
// If we got here, bandwith has changed.
// Pixel Clock, FPS and Exposure should be adjusted.
//ueye.setPixelClock(ueye.getPixelClockMax());
//ueye.setFPS(ueye.getFPSMax());
//ueye.setFPS(60);
tex.clear();
tex.allocate(ueye.getWidth(), ueye.getHeight(),GL_RGB);
}
//--------------------------------------------------------------
void testApp::update(){
ueye.update();
if(ueye.isReady() && ueye.isFrameNew())
tex.loadData(ueye.getPixels(), ueye.getWidth(), ueye.getHeight(), GL_RGB);
}
//--------------------------------------------------------------
void testApp::draw(){
if(ueye.isReady())
tex.draw((ofGetWidth()-tex.getWidth())/2, (ofGetHeight()-tex.getHeight())/2);
settings.draw(20,20);
}
//--------------------------------------------------------------
void testApp::exit(){
ueye.close();
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
settings.keyPressed(key);
}
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
73551ed98d8e0f55415e0ad522c0073283fe9fd2 | faacd0003e0c749daea18398b064e16363ea8340 | /3rdparty/phonon/abstractaudiooutput.h | da1499eb71630158aac52e844456f1b8fbbfb271 | []
| no_license | yjfcool/lyxcar | 355f7a4df7e4f19fea733d2cd4fee968ffdf65af | 750be6c984de694d7c60b5a515c4eb02c3e8c723 | refs/heads/master | 2016-09-10T10:18:56.638922 | 2009-09-29T06:03:19 | 2009-09-29T06:03:19 | 42,575,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,976 | h | /* This file is part of the KDE project
Copyright (C) 2005-2006 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#ifndef Phonon_ABSTRACTAUDIOOUTPUTBASE_H
#define Phonon_ABSTRACTAUDIOOUTPUTBASE_H
#include "phonondefs.h"
#include "phonon_export.h"
#include "medianode.h"
#include <QtCore/QObject>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
namespace Phonon
{
class AbstractAudioOutputPrivate;
/** \class AbstractAudioOutput abstractaudiooutput.h Phonon/AbstractAudioOutput
* Common base class for all audio outputs.
*
* \see AudioOutput
*/
class PHONON_EXPORT AbstractAudioOutput : public QObject, public MediaNode
{
Q_OBJECT
K_DECLARE_PRIVATE(AbstractAudioOutput)
protected:
AbstractAudioOutput(AbstractAudioOutputPrivate &dd, QObject *parent);
public:
~AbstractAudioOutput();
};
} //namespace Phonon
QT_END_NAMESPACE
QT_END_HEADER
// vim: sw=4 ts=4 tw=80
#endif // Phonon_ABSTRACTAUDIOOUTPUTBASE_H
| [
"futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9"
]
| [
[
[
1,
57
]
]
]
|
0d25fef28cee23605646a3d3b68bb361fff26ede | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/3d/Mgl3dImage.h | adc235bf6e76a77b166bbbd32c52dcac6a0d4556 | []
| no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | h | #ifndef __Mgl3dImage_H__
#define __Mgl3dImage_H__
#include "mglafx.h"
/////////////////////////////////////////////////////////////////////////
#include "MglImage.h"
class DLL_EXP CMgl3dImage : public CMglTexture
{
protected:
MGL_SQUARE_VERTEXS m_vertexs;
void GetBmpVertexs3D( MGL_SQUARE_VERTEXS *pMglSqVertexs, float fScaleX=1.0f, float fScaleY=1.0f );
public:
void Draw(float x=0.0f, float y=0.0f, float z=0.0f, RECT* srcRect=NULL,
float fTexScaleX=1.0f, float fTexScaleY=1.0f, D3DCOLOR color=D3DCOLOR_WHITE);
void SetupVertexes(float x=0.0f, float y=0.0f, float z=0.0f, RECT* srcRect=NULL,
float fTexScaleX=1.0f, float fTexScaleY=1.0f, D3DCOLOR color=D3DCOLOR_WHITE);
};
#endif//__Mgl3dImage_H__
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
]
| [
[
[
1,
25
]
]
]
|
d67c246cb310a544f150792e539f4146a1092f96 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/ObjectRelationMgr.h | bfcd7ffeb58923666cac0be1f593b2940b1348df | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,273 | h | //----------------------------------------------------------------------------
//
// MODULE: ObjectRelationMgr.h
//
// PURPOSE: CObjectRelationMgr declaration
//
// CREATED: 21.01.2002
//
// (c) 2002 Monolith Productions, Inc. All Rights Reserved
//
//
// COMMENTS: -
//
//
//----------------------------------------------------------------------------
#ifndef __OBJECTRELATIONMGR_H__
#define __OBJECTRELATIONMGR_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// Includes
#include "RelationButeMgr.h"
// Forward declarations
class CCollectiveRelationMgr;
class CRelationUser;
class CDataUser;
class CCharacter;
class IRelationChangeReceiver;
// Globals
// Statics
//----------------------------------------------------------------------------
//
// CLASS: CObjectRelationMgr
//
// PURPOSE: Per instance class to manage a characters Relation
// information.
//
//----------------------------------------------------------------------------
class CObjectRelationMgr : public IMomentoUser, public ILTObjRefReceiver, public IRelationChangeSubject
{
public:
// Ctors/Dtors/etc
CObjectRelationMgr();
virtual ~CObjectRelationMgr();
CObjectRelationMgr& operator=( const ObjectRelationMgr_Template& );
virtual int Save(ILTMessage_Write* pMsg);
virtual int Load(ILTMessage_Read* pMsg);
// Initialization
void Init( HOBJECT, const char* const );
// Updating functions:
void Update(bool bCanRemoveExpiredDurationRelations);
void ClearRelationSystem(void);
// Collective Management
void SetCollectiveName(const char* const szCollective) { LTStrCpy( m_szCollectiveName, szCollective, sizeof(m_szCollectiveName) ); }
void SetCollective(CCollectiveRelationMgr* pCollective);
CCollectiveRelationMgr* GetCollective() { return m_pCollective; }
// Relation Handling:
void CommunicateMessage(CCharacter* pSender, const RelationDescription&, uint32 dRestrictionFlags);
virtual void ResetRelationTime(CObjectRelationMgr* pORM);
void AddRelation(const RelationDescription& RD);
// Mix of Aggregate accessors (poorly blobbed together -- ought to be used more cleanly)
const RelationData& GetData() const { return m_pDataUser->GetData(); }
RelationData& SetData() { return m_pDataUser->SetData(); }
const int GetTemplateID() const { return m_nTemplateID; }
// IMomento Interface functions:
virtual CRelationUser* GetRelationUser() { return m_pRelationUser; }
// ILTObjRefReceiver Interface functions:
void OnLinkBroken( LTObjRefNotifier *pRef, HOBJECT hObj )
{
m_hOwner = NULL;
}
// IRelationChangeReceiver Interface Functions
virtual void UnregisterObserver(RelationChangeNotifier*);
virtual void RegisterObserver(RelationChangeNotifier*);
LTObjRefNotifier& GetOwningHObject(){ return m_hOwner; }
protected:
// IMomento Interface functions:
friend RelationMomento;
virtual void RemoveRelationCallback(const RelationDescription& RD);
virtual void AddRelationCallback(const RelationDescription& RD);
private:
// Copy Constructor and Asignment Operator private to prevent
// automatic generation and inappropriate, unintentional use
CObjectRelationMgr(const CObjectRelationMgr& rhs) {}
CObjectRelationMgr& operator=(const CObjectRelationMgr& rhs ) {}
// Non Modifying:
const char* const GetCollectiveName() const { return m_szCollectiveName; }
bool HasCollective() const { return m_pCollective != NULL; }
bool HasCollectiveName() const { return ( strcmp( GetCollectiveName(), "" ) != 0 ); }
// Modifying Methods:
bool RecipientMeetsRestrictions(CCharacter* pSender, CCharacter* pReceiver, uint32 iRestrictionFlags);
// Save:
int m_nTemplateID;
char m_szCollectiveName[RELATION_VALUE_LENGTH];
char m_szDataSet[RELATION_VALUE_LENGTH];
char m_szRelationSet[RELATION_VALUE_LENGTH];
CRelationUser* m_pRelationUser;
CDataUser* m_pDataUser;
LTObjRefNotifier m_hOwner;
// Don't Save:
CCollectiveRelationMgr* m_pCollective;
std::list<RelationChangeNotifier*> listChangeReceivers;
};
#endif // __OBJECTRELATIONMGR_H__
| [
"[email protected]"
]
| [
[
[
1,
135
]
]
]
|
60193e3816511d7186fb648d92350858c3749ad8 | 724cded0e31f5fd52296d516b4c3d496f930fd19 | /source/P2POrderServer/MSSQLStore.cpp | 5f3b7349883a6658e8c52190b0047ded011b409f | []
| no_license | yubik9/p2pcenter | 0c85a38f2b3052adf90b113b2b8b5b312fefcb0a | fc4119f29625b1b1f4559ffbe81563e6fcd2b4ea | refs/heads/master | 2021-08-27T15:40:05.663872 | 2009-02-19T00:13:33 | 2009-02-19T00:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,062 | cpp | #include "StdAfx.h"
#include "Channel.h"
#include ".\mssqlstore.h"
#include <ATLComTime.h>
CMSSQLStore::CMSSQLStore(void)
{
}
CMSSQLStore::~CMSSQLStore(void)
{
}
bool CMSSQLStore::AppendChannelToDB( CChannel* pChannel)
{
if ( IsOpen())
{
try
{
char szSql[256];
sprintf( szSql, "SELECT * FROM Channel WHERE userid = %d AND filehash = '%s' AND filesize = '%s'",
pChannel->m_nUserID, pChannel->m_sChannelID.c_str(), pChannel->m_sFileSize.c_str());
HRESULT _hr = m_pRecordsetPtr->Open(
szSql,
_variant_t((IDispatch*)m_pLocalConnectPtr,true),
adOpenStatic,
adLockOptimistic,
adCmdText
);
if (FAILED(_hr))
{
m_pRecordsetPtr->Close();
return FALSE;
}
if( m_pRecordsetPtr->adoEOF)
{
m_pRecordsetPtr->AddNew();
m_pRecordsetPtr->PutCollect( "userid", _variant_t(pChannel->m_nUserID));
m_pRecordsetPtr->PutCollect( "filehash", _variant_t(pChannel->m_sChannelID.c_str()));
m_pRecordsetPtr->PutCollect( "filesize", _variant_t(pChannel->m_sFileSize.c_str()));
m_pRecordsetPtr->PutCollect( "appenddate", _variant_t(COleDateTime::GetCurrentTime()));
}
m_pRecordsetPtr->PutCollect( "agent", _variant_t(pChannel->m_sAgent.c_str()));
m_pRecordsetPtr->PutCollect( "upuserid", _variant_t(pChannel->m_nUpUserID));
m_pRecordsetPtr->PutCollect( "nodename", _variant_t(pChannel->m_sNodeName.c_str()));
m_pRecordsetPtr->PutCollect( "filename", _variant_t(pChannel->m_sFileName.c_str()));
m_pRecordsetPtr->PutCollect( "updatedate", _variant_t(COleDateTime::GetCurrentTime()));
_hr = m_pRecordsetPtr->Update();
if (FAILED(_hr))
{
m_pRecordsetPtr->Close();
return FALSE;
}
m_pRecordsetPtr->Close();
return true;
}
catch(_com_error e)
{
}
}
return false;
}
bool CMSSQLStore::UpdateChannelTick( CChannel* pChannel)
{
if ( IsOpen())
{
try
{
char szSql[256];
sprintf( szSql, "SELECT * FROM Channel WHERE userid = %d AND filehash = '%s' AND filesize = '%s'",
pChannel->m_nUserID, pChannel->m_sChannelID.c_str(), pChannel->m_sFileSize.c_str());
HRESULT _hr = m_pRecordsetPtr->Open(
szSql,
_variant_t((IDispatch*)m_pLocalConnectPtr,true),
adOpenStatic,
adLockOptimistic,
adCmdText
);
if (FAILED(_hr))
{
m_pRecordsetPtr->Close();
return FALSE;
}
if( !m_pRecordsetPtr->adoEOF)
{
m_pRecordsetPtr->PutCollect( "updatedate", _variant_t(COleDateTime::GetCurrentTime()));
_hr = m_pRecordsetPtr->Update();
if (FAILED(_hr))
{
m_pRecordsetPtr->Close();
return FALSE;
}
}
m_pRecordsetPtr->Close();
return true;
}
catch(_com_error e)
{
}
}
return false;
}
bool CMSSQLStore::RemoveChannelFromDB( CChannel* pChannel)
{
char szSql[256];
sprintf( szSql, "DELETE Channel WHERE userid = %d AND filehash = '%s'",
pChannel->m_nUserID, pChannel->m_sChannelID.c_str());
return Exec( szSql, NULL, 0);
}
| [
"fuwenke@b5bb1052-fe17-11dd-bc25-5f29055a2a2d"
]
| [
[
[
1,
129
]
]
]
|
6f43bbeb036ffc3bcbb3f1f43ce817d485a34c29 | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/system_xml_native_System_Xml_XmlReader.cpp | 2ee1cc21d7a22643f0f5592ff1c518e621148fd9 | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | cpp | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#include "system_xml_native.h"
#include "system_xml_native_System_Xml_XmlReader.h"
using namespace System::Xml;
LPCSTR XmlReader::LookupNamespace( CLR_RT_HeapBlock* pMngObj, LPCSTR param0, HRESULT &hr )
{
LPCSTR retVal = 0;
return retVal;
}
void XmlReader::Initialize( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr )
{
}
INT32 XmlReader::ReadInternal( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr )
{
INT32 retVal = 0;
return retVal;
}
INT8 XmlReader::StringRefEquals( LPCSTR param0, LPCSTR param1, HRESULT &hr )
{
INT8 retVal = 0;
return retVal;
}
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
3621e65e75c57197f9a61e7856daa472cfdc09d3 | 465943c5ffac075cd5a617c47fd25adfe496b8b4 | /HOLDINGP.H | 94d839c080116a0dc3fa78fd9d14d2b830b5f951 | []
| no_license | paulanthonywilson/airtrafficcontrol | 7467f9eb577b24b77306709d7b2bad77f1b231b7 | 6c579362f30ed5f81cabda27033f06e219796427 | refs/heads/master | 2016-08-08T00:43:32.006519 | 2009-04-09T21:33:22 | 2009-04-09T21:33:22 | 172,292 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | h | /* Class To desribe an plane at an airport awaiting take off.
Simon Hall
ver 0.0
08-04-96
*/
# ifndef _HOLDINGPLANE_H
# define _HOLDINGPLANE_H
# include "plane.h"
# include "airport.h"
# define MAXWAITINGUPDATES 30
class HoldingPlane {
private:
Plane *P_c;
Airport *At_c;
int UpdatesLeft_c;
public :
HoldingPlane (char pid, Vector3D &v,
Aircraft tp, Destination *des,
Airport *d){
P_c = new Plane(pid, v, tp, des);
At_c = d;
UpdatesLeft_c = MAXWAITINGUPDATES;
}
Plane *P(void){ return P_c; }
Airport *At(void){ return At_c; }
int UpdatesLeft(void){ return UpdatesLeft_c; }
void Step(void){ UpdatesLeft_c--; }
};
# endif _HOLDINGPLANE_H | [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
573fe8e8cd5ae8922d680646288d1e089e708d54 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Vector2Sequence.h | 813e07e055666c859ff38bbcd784a432d8ef9bbb | []
| no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,708 | h | #pragma once
#ifndef __HALAK_VECTOR2SEQUENCE_H__
#define __HALAK_VECTOR2SEQUENCE_H__
# include <Halak/FWD.h>
# include <Halak/Asset.h>
# include <Halak/Vector2.h>
namespace Halak
{
struct Vector2Keyframe
{
typedef Vector2 ValueType;
ValueType Value;
float Duration;
float StartTime;
Vector2Keyframe();
Vector2Keyframe(ValueType value, float duration);
static ValueType Interpolate(const Vector2Keyframe& k1, const Vector2Keyframe& k2, float t);
};
class Vector2Sequence : public Asset
{
public:
typedef Vector2Keyframe KeyframeType;
public:
Vector2Sequence();
virtual ~Vector2Sequence();
void AddKeyframe(const KeyframeType& item);
void InsertKeyframe(int index, const KeyframeType& item);
void InsertKeyframe(float time, const KeyframeType& item);
void RemoveKeyframe(int index);
void RemoveKeyframe(float time);
void RemoveAllKeyframes();
int GetNumberOfKeyframes();
const KeyframeType& GetKeyframe(int index);
const KeyframeType& GetKeyframe(float time);
int GetKeyframeIndex(float time);
int GetKeyframeIndex(float time, int startIndex);
void SetKeyframe(int index, const KeyframeType& item);
float GetDuration();
private:
SequenceTemplate<KeyframeType>* s;
};
}
#endif | [
"[email protected]"
]
| [
[
[
1,
55
]
]
]
|
ae9873878c0ff989fa84fd1441fbf23667135db7 | b6bad03a59ec436b60c30fc793bdcf687a21cf31 | /som2416/wince5/FIMGSE2D.h | 237b9fbcfbd9943327a0eaa0568ecb5b6500545a | []
| no_license | blackfa1con/openembed | 9697f99b12df16b1c5135e962890e8a3935be877 | 3029d7d8c181449723bb16d0a73ee87f63860864 | refs/heads/master | 2021-01-10T14:14:39.694809 | 2010-12-16T03:20:27 | 2010-12-16T03:20:27 | 52,422,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,534 | h | //
// Copyright (c) Samsung Electronics. Co. LTD. All rights reserved.
//
/*++
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
--*/
/**
* @file fimgse2d.h
* @brief defines for FIMGSE-2D Graphics Accelerator
* @author Jiwon Kim
*
* @note This version is made for FIMGSE-2D v2.0
*/
// Header to define the FIMGSE-2D class
#ifndef __FIMGSE2D_H__
#define __FIMGSE2D_H__
#include "regctrl_g2d.h"
#define Assert(a) {if (!(a)) {printf("\n %s(line %d) \n", __FILE__, __LINE__); }}
/**
* Define G2D Command processing and return type
*
**/
#define G2D_FASTRETURN 1 //< Currently, this mode has some bugs, with
#define G2D_INTERRUPT 2
#define G2D_BUSYWAITING 3
#define G2D_CMDPROCESSING (G2D_INTERRUPT)
/**
* Hardware Limitation Macro
*
**/
/// For Coordinate Register
#define G2D_MAX_WIDTH (1<<11) //< 2048
#define G2D_MAX_HEIGHT (1<<11) //< 2048
// ROP_REG (0x410)
#define G2D_TRANSPARENT_BIT (1<<9)
#define G2D_OPAQUE_BIT (0<<9)
#define G2D_NO_ALPHA_BIT (0<<10)
#define G2D_PP_ALPHA_SOURCE_BIT (1<<10)
#define G2D_ALPHA_BIT (2<<10)
//#define G2D_PP_ALPHA_THIRD_BIT (3<<10)
#define G2D_FADING_BIT (4<<10)
// Color_Mode_Reg (0x510[2:0])
#define G2D_COLOR_RGB_565 (0)
#define G2D_COLOR_RGBA_5551 (1)
#define G2D_COLOR_ARGB_1555 (2)
#define G2D_COLOR_RGBA_8888 (3)
#define G2D_COLOR_ARGB_8888 (4)
#define G2D_COLOR_XRGB_8888 (5)
#define G2D_COLOR_RGBX_8888 (6)
#define G2D_COLOR_UNUSED (7)
#define MS_NUM_SUPPORT_COLORMODE (10) //EGPEFormat
// CMD0_REG (Line) (0x100)
#define G2D_REND_POINT_BIT (1<<0)
#define G2D_REND_LINE_BIT (1<<1)
#define G2D_MAJOR_COORD_X_BIT (1<<8)
#define G2D_MAJOR_COORD_Y_BIT (0<<8)
#define G2D_NOT_DRAW_LAST_POINT_BIT (1<<9)
#define G2D_DRAW_LAST_POINT_BIT ~(1<<9)
// CMD1_REG (BitBlt) (0x104)
#define G2D_STRETCH_BITBLT_BIT (1<<1)
#define G2D_NORMAL_BITBLT_BIT (1<<0)
#define ABS(v) (((v)>=0) ? (v):(-(v)))
#define START_ASCII (0x20)
#define OPAQUE_ENABLE (0<<9)
// Set fading and alpha value
#define FADING_OFFSET_DISABLE (0x0<<8)
#define ALPHA_VALUE_DISABLE (0xff<<0)
#define HOST2SCREEN (0)
#define SCREEN2SCREEN (1)
// G2D Source 0xf0
// G2D Dest 0xcc
// G2D Pattern 0xaa
// MS ROP Pattern 0xf0
// MS ROP Source 0xcc
// MS ROP Dest 0xaa
// G2D MS
// SRC_ONLY 0xf0 0xcc // SRCCOPY : S
// DST_ONLY 0xcc 0xaa // DSTCOPY : D
// PAT_ONLY 0xaa 0xf0 // PATCOPY : P
// SRC_OR_DST 0xfc 0xee // SRCPAINT : S | D
// SRC_OR_PAT 0xfa 0xfc // P | S --> 0xF0008A
// DST_OR_PAT 0xee 0xfa // R2_MERGEPEN : P | D
// SRC_AND_DST 0xc0 0x88 // SRCAND : S & D
// SRC_AND_PAT 0xa0 0xc0 // MERGECOPY : S & P
// DST_AND_PAT 0x88 0xa0 // R2_MASKPEN : P & D
// SRC_XOR_DST 0x3c 0x66 // SRCINVERT : S ^ D
// SRC_XOR_PAT 0x5a 0x3c // X
// DST_XOR_PAT 0x66 0x5a // PATINVERT : P ^ D
// NOTSRCCOPY 0x0f 0x33 // NOTSRCCOPY : ~S
// DSTINVERT 0x33 0x55 // DSTINVERT : ~D
// R2_NOTCOPYPEN 0x55 0x0f // R2_NOTCOPYPEN : ~P
//
#define G2D_ROP_SRC_ONLY (0xf0)
#define G2D_ROP_PAT_ONLY (0xaa)
#define G2D_ROP_DST_ONLY (0xcc)
#define G2D_ROP_SRC_OR_DST (0xfc)
#define G2D_ROP_SRC_OR_PAT (0xfa)
#define G2D_ROP_DST_OR_PAT (0xee)
#define G2D_ROP_SRC_AND_DST (0xc0) //(pat==1)? src:dst
#define G2D_ROP_SRC_AND_PAT (0xa0)
#define G2D_ROP_DST_AND_PAT (0x88)
#define G2D_ROP_SRC_XOR_DST (0x3c)
#define G2D_ROP_SRC_XOR_PAT (0x5a)
#define G2D_ROP_DST_XOR_PAT (0x66)
#define G2D_ROP_NOTSRCCOPY (0x0f)
#define G2D_ROP_DSTINVERT (0x33)
#define G2D_ROP_R2_NOTCOPYPEN (0x55)
#define G2D_NUM_SUPPORT_ROP (15)
typedef struct
{
DWORD dwBaseaddr;
DWORD dwHoriRes;
DWORD dwVertRes;
DWORD dwColorMode;
} SURFACE_DESCRIPTOR, *PSURFACE_DESCRIPTOR;
typedef enum
{
ROP_SRC_ONLY = 0, //O
ROP_PAT_ONLY = 1, //O
ROP_DST_ONLY = 2, //O
ROP_SRC_OR_DST = 3, //O
ROP_SRC_OR_PAT = 4, //O
ROP_DST_OR_PAT = 5, //O
ROP_SRC_AND_DST = 6, //O
ROP_SRC_AND_PAT = 7, //O
ROP_DST_AND_PAT = 8, //N
ROP_SRC_XOR_DST = 9, //N
ROP_SRC_XOR_PAT = 10, //O
ROP_DST_XOR_PAT = 11, //N
ROP_NOTSRCCOPY = 12, //N
ROP_DSTINVERT = 13, //N
ROP_R2_NOTCOPYPEN = 14 //N
} G2D_ROP_TYPE;
typedef enum
{
G2D_NO_ALPHA_MODE,
G2D_PP_ALPHA_SOURCE_MODE,
G2D_ALPHA_MODE,
G2D_FADING_MODE
} G2D_ALPHA_BLENDING_MODE;
typedef enum
{
QCIF, CIF/*352x288*/,
QQVGA, QVGA, VGA, SVGA/*800x600*/, SXGA/*1280x1024*/, UXGA/*1600x1200*/, QXGA/*2048x1536*/,
WVGA/*854x480*/, HD720/*1280x720*/, HD1080/*1920x1080*/
} IMG_SIZE;
#define HASBIT_COND(var,cond) (((var&cond) == cond) ? TRUE : FALSE)
class FIMGSE2D : public RegCtrlG2D
{
private:
BYTE m_iROPMapper[G2D_NUM_SUPPORT_ROP];
LONG m_iColorModeMapper[MS_NUM_SUPPORT_COLORMODE];
/// Source Surface Descriptor
SURFACE_DESCRIPTOR m_descSrcSurface;
/// Destination Surface Descriptor
SURFACE_DESCRIPTOR m_descDstSurface;
// Max Window Size of clipping window
RECT m_rtClipWindow;
DWORD m_uMaxDx;
DWORD m_uMaxDy;
// Coordinate (X, Y) of clipping window
DWORD m_uCwX1, m_uCwY1;
DWORD m_uCwX2, m_uCwY2;
DWORD m_uFgColor;
DWORD m_uBgColor;
DWORD m_uBlueScreenColor;
DWORD m_uColorVal[8];
// Reference to Raster operation
DWORD m_uRopVal; // Raster operation value
DWORD m_uAlphaBlendMode;
DWORD m_uTransparentMode;
DWORD m_u3rdOprndSel;
// Reference to alpha value
DWORD m_uFadingOffsetVal;
DWORD m_uAlphaVal;
// Reference to image rotation
DWORD m_uRotOrgX, m_uRotOrgY;
DWORD m_uRotAngle;
// reference to pattern of bitblt
DWORD m_uPatternOffsetX, m_uPatternOffsetY;
DWORD m_uBytes;
BYTE m_ucAlphaVal;
bool m_bIsAlphaCall;
// true: BitBlt enable in Host-To-Screen Font Drawing
// false: BitBlt disable in Host-To-Screen Font Drawing
bool m_bIsBitBlt;
// DWORD m_uFontAddr;
bool m_bIsScr2Scr;
// N_24X24, B_24X24, N_16X16, T_8X16, N_8X8, N_8X15
BYTE* m_upFontType;
DWORD m_uFontWidth, m_uFontHeight;
// for Interrupt
DWORD m_dwSysIntr2D; // 2D SysIntr
HANDLE m_hInterrupt2D; // handle for 2D interrupt handler
public:
FIMGSE2D();
virtual ~FIMGSE2D();
/// G2D Method
/// For Initialization
void Init();
/// For Common Resource Setting
void SetRopEtype(G2D_ROP_TYPE eRopType);
/// For Rotation Setting
ROT_TYPE GetRotType(int m_iRotate) ;
void SetTransparentMode(bool bIsTransparent, DWORD uBsColor);
void SetColorKeyOn(DWORD uColorKey);
void SetColorKeyOff(void);
void SetFgColor(DWORD uFgColor);
void SetBgColor(DWORD uBgColor);
void SetBsColor(DWORD uBsColor);
void SetSrcSurface(PSURFACE_DESCRIPTOR desc_surface);
void SetDstSurface(PSURFACE_DESCRIPTOR desc_surface);
// void SetRotate(WORD usSrcX1, WORD usSrcY1, WORD usSrcX2, WORD usSrcY2, WORD usDestX1, WORD usDestY1, ROT_TYPE eRotDegree);
/// For Bitblt
void BitBlt(PRECTL prclSrc, PRECTL prclDst, ROT_TYPE m_iRotate);
void StretchBlt(PRECTL prclSrc, PRECTL prclDst, ROT_TYPE m_iRotate);
BOOL FlipBlt(PRECTL prclSrc, PRECTL prclDst, ROT_TYPE m_iRotate);
void FillRect(PRECTL prclDst, DWORD uColor); //< FillRect doesn't care about Rotation, just look at Destination
/// For Additional Effect Setting
void EnablePlaneAlphaBlending(BYTE ucAlphaVal);
void DisablePlaneAlphaBlending(void);
void EnablePixelAlphaBlending(void); // Only Support 24bpp
void DisablePixelAlphaBlending(void); // Only Support 24bpp
void EnableFadding(BYTE ucFadingVal);
void DisableFadding(void);
void SetAlphaMode(G2D_ALPHA_BLENDING_MODE eMode);
void SetAlphaValue(BYTE ucAlphaVal);
void SetFadingValue(BYTE ucFadeVal);
/// For Line Drawing
void PutPixel(DWORD uPosX, DWORD uPosY, DWORD uColor);
void PutLine(DWORD uPosX1, DWORD uPosY1, DWORD uPosX2, DWORD uPosY2, DWORD uColor, bool bIsDrawLastPoint);
/// Advanced Macro Function
void WaitForIdle() {WaitForEmptyFifo();}
//-- for NK interrupt process
BOOL InitializeInterrupt(void);
void DeinitInterrupt(void);
protected:
DWORD CalculateXYIncrFormat(DWORD uDividend, DWORD uDivisor);
void GetRotationOrgXY(WORD usSrcX1, WORD usSrcY1, WORD usSrcX2, WORD usSrcY2, WORD usDestX1, WORD usDestY1, ROT_TYPE eRotDegree, WORD* usOrgX, WORD* usOrgY);
void DisableEffect(void);
void SetStencilKey(DWORD uIsColorKeyOn, DWORD uIsInverseOn, DWORD uIsSwapOn);
void SetStencilMinMax(DWORD uRedMin, DWORD uRedMax, DWORD uGreenMin, DWORD uGreenMax, DWORD uBlueMin, DWORD uBlueMax);
void SetColorExpansionMethod(bool bIsScr2Scr);
void BlendingOut(DWORD uSrcData, DWORD uDstData, BYTE ucAlphaVal, bool bFading, BYTE ucFadingOffset, DWORD *uBlendingOut);
void Convert24bpp(DWORD uSrcData, EGPEFormat eBpp, bool bSwap, DWORD *uConvertedData);
void GetRotateCoordinate(DWORD uDstX, DWORD uDstY, DWORD uOrgX, DWORD uOrgY, DWORD uRType, DWORD *uRsltX, DWORD *uRsltY);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
326
]
]
]
|
da678003c4c1b7a1ab683f14dde2872254158b01 | ae2adbf262d2938684664e3195a3b71934f4448c | /trabalho 02/ImagemOperators.cpp | 4aa1ac2223e812b34e9cf0733b4b67209ad382c7 | []
| no_license | cmdalbem/saint-ende | e5e251a0b274e40c02233ed4963ca0c619ed31eb | b5aeeea978108d1e906fd168c0c24618a3d35882 | refs/heads/master | 2020-07-09T08:21:07.963803 | 2009-12-21T17:32:25 | 2009-12-21T17:32:25 | 32,224,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,756 | cpp | #include<stdlib.h>
#include<iostream>
#include "Imagem.h"
using namespace std;
Imagem Imagem::operator+=(Imagem aImage)
//buffer + original
{
for(int x=0; x < w; x++){
for(int y=0; y < h; y++) {
image(x,y)->Red = truncaValor( image(x,y)->Red + aImage.image(x,y)->Red );
image(x,y)->Blue = truncaValor( image(x,y)->Blue + aImage.image(x,y)->Blue );
image(x,y)->Green = truncaValor( image(x,y)->Green + aImage.image(x,y)->Green );
}
//gotoxy(1,wherey()); cout<<"Operando soma... "<<x*100/w +1<<"% ";
}
cout<<endl;
return *this;
}
Imagem Imagem::operator-=(Imagem aImage)
//buffer + original
{
for(int x=0; x < w; x++){
for(int y=0; y < h; y++) {
image(x,y)->Red = truncaValor( image(x,y)->Red - aImage.image(x,y)->Red );
image(x,y)->Blue = truncaValor( image(x,y)->Blue - aImage.image(x,y)->Blue );
image(x,y)->Green = truncaValor( image(x,y)->Green - aImage.image(x,y)->Green );
}
//gotoxy(1,wherey()); cout<<"Operando subtracao... "<<x*100/w +1<<"% ";
}
cout<<endl;
return *this;
}
Imagem& Imagem::operator=(Imagem aImage)
{
this->load( aImage.getImagePath() );
this->internalFrameX1 = aImage.internalFrameX1;
this->internalFrameX2 = aImage.internalFrameX2;
this->internalFrameY1 = aImage.internalFrameY1;
this->internalFrameY2 = aImage.internalFrameY2;
for(int x=0; x < w; x++)
for(int y=0; y < h; y++) {
this->image(x,y)->Red = aImage.image(x,y)->Red;
this->image(x,y)->Blue = aImage.image(x,y)->Blue;
this->image(x,y)->Green = aImage.image(x,y)->Green;
}
return *this;
}
| [
"lfzawacki@7df66274-e10c-11de-a155-4d945b6d75ec",
"lucapus@7df66274-e10c-11de-a155-4d945b6d75ec",
"ninja.dalbem@7df66274-e10c-11de-a155-4d945b6d75ec"
]
| [
[
[
1,
52
],
[
54,
56
],
[
61,
75
]
],
[
[
53,
53
]
],
[
[
57,
60
]
]
]
|
8f8d9cfc48bd9edf52a406c66c74121d9340fc33 | 14a00dfaf0619eb57f1f04bb784edd3126e10658 | /Lab1/SupportCode/Matrix4x4.h | 5fc4333c43c39d8dd3fc906181db9dfb884c4388 | []
| no_license | SHINOTECH/modanimation | 89f842262b1f552f1044d4aafb3d5a2ce4b587bd | 43d0fde55cf75df9d9a28a7681eddeb77460f97c | refs/heads/master | 2021-01-21T09:34:18.032922 | 2010-04-07T12:23:13 | 2010-04-07T12:23:13 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,510 | h | /*************************************************************************************************
*
* Modeling and animation (TNM079) 2007
* Code base for lab assignments. Copyright:
* Gunnar Johansson ([email protected])
* Ken Museth ([email protected])
* Michael Bang Nielsen ([email protected])
* Ola Nilsson ([email protected])
* Andreas Söderström ([email protected])
*
*************************************************************************************************/
#ifndef _matrix4x4_h
#define _matrix4x4_h
template <typename Real> class Vector3;
template <typename Real> class Vector4;
template <typename Real>
class Matrix4x4
{
public:
Matrix4x4();
Matrix4x4(const Real m[4][4]);
void toGLMatrix(float glMatrix[16]) const;
Matrix4x4 inverse() const;
// Input: i (row), j (column)
Real &operator()(unsigned int i, unsigned int j);
Real *operator[](unsigned int i) { return m[i]; }
Vector4<Real> operator*(const Vector4<Real>& vec4) const;
Matrix4x4 operator*(const Matrix4x4& m2) const;
// Static methods
static Matrix4x4 scale(Real scale);
static Matrix4x4 scale(Real sx, Real sy, Real sz);
// Angles in radians
static Matrix4x4 rotationXYZ(Real rx, Real ry, Real rz);
static Matrix4x4 translation(Real tx, Real ty, Real tz);
static Matrix4x4 identity();
protected:
Real m[4][4];
static Matrix4x4 identityMatrix;
};
#include "Matrix4x4_Impl.h"
#endif
| [
"jpjorge@da195381-492e-0410-b4d9-ef7979db4686"
]
| [
[
[
1,
49
]
]
]
|
8abc97130b67054e148a29cc7489a20fa64f96b0 | a8157564af47618589001d80f0f4571c6328f3e0 | /cador.h | 9853ce00e201d22c4956620a3c5abd581a871c51 | [
"MIT"
]
| permissive | dionyziz/cador | 83848185094c0198ec7b217fdaf2d94c39e541ba | ee939b5556aebdea692d3cea5badbe3c85b49a7d | refs/heads/master | 2020-06-06T07:11:55.517376 | 2011-11-23T21:45:58 | 2011-11-23T21:45:58 | 2,240,956 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 288 | h | #ifndef CADOR
#define CADOR
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <set>
#include "string.h"
#include "error.h"
#include "network.h"
#include "config.h"
#include "vilundo.h"
#include "conf.h"
#include "extension.h"
#endif
| [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
d0d655d437d5b6dbbe4b8234da7e9c60287554a0 | f9acc77870f5a372ee1955e5ac225399d6f841e7 | /lenguajes de Programacion/Archivos cpp Lenguajes/Untitled1.cpp | 908d4aa605b7e31c5dcd37f84490ec69f5f3185e | []
| no_license | sergiobuj/campari_royal | 3a713cff0fc86837bda4cd69c59f0d8146ffe0e5 | e653b170e5e3ab52e6148242a883b570f216d664 | refs/heads/master | 2016-09-05T21:32:21.092149 | 2011-10-18T22:09:30 | 2011-10-18T22:09:30 | 976,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | #include <iostream>
using namespace std;
int main(){
int aj;
cout << "hola";
cin>>aj;
}
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
627254f25653bba15884f07face37adfa6d0534d | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.3/cbear.berlios.de/windows/exception.hpp | 6bf8dcbd615e43cf46ae4e8c60e2a017dd69d43b | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,080 | hpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CBEAR_BERLIOS_DE_WINDOWS_EXCEPTION_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_EXCEPTION_HPP_INCLUDED
#include <cbear.berlios.de/windows/base.hpp>
namespace cbear_berlios_de
{
namespace windows
{
#pragma warning(push)
// 'type' : the copy constructor is inaccessible
#pragma warning(disable: 4671)
// throwing 'identifier' the following types will not be considered at the
// catch site
#pragma warning(disable: 4673)
// Exception.
class exception:
public std::exception, public policy::wrap<windows::exception, dword_t>
{
public:
typedef policy::wrap<windows::exception, dword_t> wrap_type;
static void throw_if(internal_type X)
{
if(X) throw windows::exception(X);
}
class scope_last_error: boost::noncopyable
{
public:
scope_last_error() { ::SetLastError(0); }
~scope_last_error()
{
internal_type LastError = ::GetLastError();
if(LastError) throw exception(LastError);
}
};
const char *what() const throw()
{
return this->Message.c_str();
}
private:
class buffer_policy: private policy::standard_policy<char *>
{
public:
typedef policy::standard_policy<char *> std_policy_type;
typedef std_policy_type::reference reference;
typedef std_policy_type::pointer pointer;
using std_policy_type::construct;
using std_policy_type::output;
static void destroy(char * &X)
{
if(X) ::LocalFree(X);
}
};
exception(internal_type X): wrap_type(X)
{
policy::std_wrap<char *, buffer_policy> Buffer;
::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
0,
X,
0,
(char *)&Buffer.internal(),
0,
NULL);
std::ostringstream O;
O <<
"cbear_berlios_de::windows::exception(0x" << std::hex << std::uppercase <<
this->internal() << "): " << std::endl << Buffer;
this->Message = O.str();
}
std::string Message;
};
#pragma warning(pop)
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
107
]
]
]
|
81e3c78b103b7a38b72bf04a1dc1037adef12ec6 | 6ec6ebbd57752e179c3c74cb2b5d2d3668e91110 | /rsase/SGBag/src/noyau/ElementActif.cpp | 0e9b7ab2a3d893b1b879040fe5cf86fa09f81eb6 | []
| no_license | padenot/usdp | 6e0562a18d2124f1970fb9f2029353c92fdc4fb4 | a3ded795e323e5a2e475ade08839b0f2f41b192b | refs/heads/master | 2016-09-05T15:24:53.368597 | 2010-11-25T16:13:47 | 2010-11-25T16:13:47 | 1,106,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,016 | cpp | #include "ElementActif.h"
//Begin section for file ElementActif.cpp
//TODO: Add definitions that you want preserved
//End section for file ElementActif.cpp
const double ElementActif::VITESSE_DEFAUT = 10; // m/s
const double ElementActif::VITESSE_MAX_DEFAUT = 20; // m/s
//@uml.annotationsderived_abstraction="platform:/resource/usdp/ModeleStructurel.emx#_Pu31cPGuEd-1y9a3HOSRUA?DEFCONSTRUCTOR"
//@generated "UML to C++ (com.ibm.xtools.transform.uml2.cpp.CPPTransformation)"
ElementActif::ElementActif(const XmlConfigFactory::IndexParamValeur& indexParamValeur) :
Element(indexParamValeur),
_vitesse (VITESSE_DEFAUT),
_vitesseMax (VITESSE_MAX_DEFAUT),
_estActif(true)
{
//TODO Auto-generated method stub
}
void ElementActif::init (const XmlConfigFactory::IndexParamValeur& indexParamValeur,
XmlConfigFactory& fabrique)
{
Element::init(indexParamValeur,fabrique);
}
//@uml.annotationsderived_abstraction="platform:/resource/usdp/ModeleStructurel.emx#_Pu31cPGuEd-1y9a3HOSRUA?DESTRUCTOR"
//@generated "UML to C++ (com.ibm.xtools.transform.uml2.cpp.CPPTransformation)"
ElementActif::~ElementActif()
{
//TODO Auto-generated method stub
}
/*void ElementActif::modifierVitesse(double nouvelleVitesse)
{
_vitesse = nouvelleVitesse;
}*/
void ElementActif::freiner()
{
if (_estActif)
{
_estActif = false;
emit activationModifiee(false);
}
}
void ElementActif::accelerer()
{
if (!_estActif)
{
_estActif = true;
emit activationModifiee(true);
}
}
void ElementActif::definirActivation (bool estActif)
{
_estActif = estActif;
}
void ElementActif::modifierVitesseMax(double nouvelleVitesseMax)
{
_vitesseMax = nouvelleVitesseMax;
}
bool ElementActif::estActif ()
{
return _estActif;
}
double ElementActif::vitesse() {
return _vitesse;
}
double ElementActif::vitesseMax ()
{
return _vitesseMax;
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
31
],
[
33,
33
],
[
35,
36
],
[
38,
38
],
[
40,
44
],
[
47,
61
],
[
63,
63
],
[
65,
71
],
[
76,
79
]
],
[
[
32,
32
],
[
34,
34
],
[
37,
37
],
[
39,
39
],
[
45,
46
],
[
62,
62
],
[
64,
64
]
],
[
[
72,
75
]
]
]
|
42edc00873b1083c708a0f3d37e2bd1a7e952ca1 | 5155ce0bfd77ae28dbf671deef6692220ac71aba | /main/src/common/CIniObject.cpp | d3bb802829fddce44275cf37be94d8834cfc136a | []
| no_license | OldRepoPreservation/taksi | 1ffcfbb0a100520ba4a050f571a15389ee9e9098 | 631c9080c14cf80d028b841ba41f8e884d252c8a | refs/heads/master | 2021-07-08T16:26:24.168833 | 2011-03-13T22:00:57 | 2011-03-13T22:00:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,855 | cpp | //
// CIniObject.cpp
// Copyright 1992 - 2006 Dennis Robinson (www.menasoft.com)
//
#include "stdafx.h"
#include "CIniObject.h"
#include "Common.h"
static int Str_FindTableHead( const char* pszFind, const char** pszTable )
{
ASSERT(pszFind);
pszFind = Str_SkipSpace(pszFind);
int iLen = 0;
for (;pszFind[iLen];iLen++)
{
char ch = toupper(pszFind[iLen]);
if ( ! isalnum(ch) && ch !='.' && ch !='_' )
break;
}
if ( iLen <= 0 )
return -1;
for (int i=0; pszTable[i]; i++ )
{
if ( ! _strnicmp( pszFind, pszTable[i], iLen ))
return i;
}
return -1;
}
bool CIniObject::PropSetName( const char* pszProp, const char* pszValue )
{
int eProp = Str_FindTableHead(pszProp,get_Props());
if ( eProp<0)
return false;
return PropSet(eProp,pszValue);
}
bool CIniObject::PropWrite( FILE* pFile, int eProp ) const
{
char szTmp[_MAX_PATH*2];
szTmp[0] = '\0';
if ( PropGet(eProp,szTmp,sizeof(szTmp)) < 0 )
return false;
const char* pszProp = get_Props()[eProp];
ASSERT(pszProp);
char szTmp2[_MAX_PATH*2];
_snprintf( szTmp2, sizeof(szTmp2)-1, "%s=%s" INI_CR, pszProp, szTmp );
fputs( szTmp2, pFile );
return true;
}
bool CIniObject::PropWriteName( FILE* pFile, const char* pszProp )
{
// Overwrite this prop.
int eProp = Str_FindTableHead(pszProp,get_Props());
if ( eProp < 0 )
return false;
if (m_dwWrittenMask & (1<<eProp)) // already written
return false;
PropWrite(pFile,eProp);
m_dwWrittenMask |= (1<<eProp);
return true;
}
void CIniObject::PropsWrite( FILE* pFile )
{
// Write out all that are not already written.
// Assume [HEADER] already written.
int iQty = get_PropQty();
for ( int i=0; i<iQty; i++ )
{
if (m_dwWrittenMask & (1<<i)) // was already written
continue;
PropWrite(pFile,i);
m_dwWrittenMask |= (1<<i);
}
}
| [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
e9b024324b5582c56301b332a82cfca3451e30d7 | 51d0aa420c539ad087ed1d32aa123d8fcefe2cb9 | /src/luanode_file_linux.h | de74956c6f880a7b9980fc173912c234739ccdc9 | [
"MIT"
]
| permissive | Sciumo/LuaNode | 1aae81a44d9ff1948499b2103b56c175e97d89da | 0611b4d5496bf67d336ac24e903a91e5d28f6f83 | refs/heads/master | 2021-01-18T00:01:13.841566 | 2011-08-01T22:15:50 | 2011-08-01T22:15:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | h | #pragma once
#include <lua.hpp>
#include "../deps/LuaCppBridge51/lcbHybridObjectWithProperties.h"
#include <boost/array.hpp>
namespace LuaNode {
namespace Fs {
void RegisterFunctions(lua_State* L);
int Open(lua_State* L);
int Read(lua_State* L);
class File : public LuaCppBridge::HybridObjectWithProperties<File>
{
public:
// Normal constructor
File(lua_State* L);
virtual ~File(void);
public:
LCB_HOWP_DECLARE_EXPORTABLE(File);
static int tostring_T(lua_State* L);
int Write(lua_State* L);
int Read(lua_State* L);
int Seek(lua_State* L);
int Close(lua_State* L);
private:
private:
lua_State* m_L;
const unsigned long m_fileId;
boost::array<char, 8192> m_inputArray; // agrandar esto y poolearlo (el test simple\test-http-upgrade-server necesita un buffer grande sino falla)
};
}
} | [
"[email protected]"
]
| [
[
[
1,
46
]
]
]
|
fe087e5d82afcb9573504d54fb13b2be1f4500bb | 10c14a95421b63a71c7c99adf73e305608c391bf | /gui/painting/qpaintengine_d3d.cpp | a1f6a50f3e69c7856e8a7ccbbbc05b61529baced | []
| no_license | eaglezzb/wtlcontrols | 73fccea541c6ef1f6db5600f5f7349f5c5236daa | 61b7fce28df1efe4a1d90c0678ec863b1fd7c81c | refs/heads/master | 2021-01-22T13:47:19.456110 | 2009-05-19T10:58:42 | 2009-05-19T10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149,530 | cpp | /****************************************************************************
**
** 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$
**
****************************************************************************/
#include <qdebug.h>
#include "qpaintengine_d3d_p.h"
#include "private/qdrawhelper_p.h"
#include "private/qfont_p.h"
#include "private/qfontengine_p.h"
#include "private/qpaintengine_p.h"
#include "private/qtessellator_p.h"
#include <private/qbezier_p.h>
#include <private/qpainter_p.h>
#include <private/qpixmap_raster_p.h>
#include <private/qpolygonclipper_p.h>
#include <qbuffer.h>
#include <qcache.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <qlibrary.h>
#include <qlibraryinfo.h>
#include <qmath.h>
#include <qpaintdevice.h>
#include <qpixmapcache.h>
#include <qwidget.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <mmintrin.h>
#include <xmmintrin.h>
QT_BEGIN_NAMESPACE
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define QD3D_MASK_MARGIN 1
#define QD3D_BATCH_SIZE 256
// for the ClearType detection stuff..
#ifndef SPI_GETFONTSMOOTHINGTYPE
#define SPI_GETFONTSMOOTHINGTYPE 0x200A
#endif
#ifndef FE_FONTSMOOTHINGCLEARTYPE
#define FE_FONTSMOOTHINGCLEARTYPE 0x0002
#endif
//#include <performance.h>
#define PM_INIT
#define PM_MEASURE(A)
#define PM_DISPLAY
//debugging
//#define QT_DEBUG_VERTEXBUFFER_ACCESS
//#define QT_DEBUG_D3D
//#define QT_DEBUG_D3D_CALLS
#define QD3D_SET_MARK(output) \
D3DPERF_SetMarker(0, QString(output).utf16());
#define QT_VERTEX_RESET_LIMIT 24576
#define QT_VERTEX_BUF_SIZE 32768
#define QD3DFVF_CSVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX2 | D3DFVF_TEXCOORDSIZE4(0) | D3DFVF_TEXCOORDSIZE4(1))
// this is a different usage of the effect framework than intended,
// but it's convenient for us to use (See effect file)
#define PASS_STENCIL_ODDEVEN 0
#define PASS_STENCIL_WINDING 1
#define PASS_STENCIL_DRAW 2
#define PASS_STENCIL_DRAW_DIRECT 3
#define PASS_STENCIL_CLIP 4
#define PASS_STENCIL_NOSTENCILCHECK 5
#define PASS_STENCIL_NOSTENCILCHECK_DIRECT 6
#define PASS_TEXT 7
#define PASS_CLEARTYPE_TEXT 8
#define PASS_ALIASED_LINES 9
#define PASS_ALIASED_LINES_DIRECT 10
#define PASS_AA_CREATEMASK 0
#define PASS_AA_DRAW 1
#define PASS_AA_DRAW_DIRECT 2
#define D3D_STAGE_COUNT 2
#define D3D_RENDER_STATES 210
#define D3D_TEXTURE_STATES 33
#define D3D_SAMPLE_STATES 14
typedef HRESULT (APIENTRY *PFND3DXCREATEBUFFER)(DWORD, LPD3DXBUFFER *);
typedef HRESULT (APIENTRY *PFND3DXCREATEEFFECT)(LPDIRECT3DDEVICE9, LPCVOID, UINT, CONST D3DXMACRO *,
LPD3DXINCLUDE, DWORD, LPD3DXEFFECTPOOL,
LPD3DXEFFECT *, LPD3DXBUFFER *);
typedef D3DXMATRIX *(APIENTRY *PFND3DXMATRIXORTHOOFFCENTERLH)(D3DMATRIX *, FLOAT, FLOAT,
FLOAT, FLOAT, FLOAT, FLOAT);
typedef IDirect3D9 *(APIENTRY *PFNDIRECT3DCREATE9)(uint);
static PFNDIRECT3DCREATE9 pDirect3DCreate9 = 0;
static PFND3DXCREATEBUFFER pD3DXCreateBuffer = 0;
static PFND3DXCREATEEFFECT pD3DXCreateEffect = 0;
static PFND3DXMATRIXORTHOOFFCENTERLH pD3DXMatrixOrthoOffCenterLH = 0;
class QD3DSurfaceManager : public QObject {
Q_OBJECT
public:
enum QD3DSurfaceManagerStatus {
NoStatus = 0,
NeedsResetting = 0x01,
MaxSizeChanged = 0x02
};
QD3DSurfaceManager();
~QD3DSurfaceManager();
void init(LPDIRECT3D9 object);
void setPaintDevice(QPaintDevice *pd);
int status() const;
void reset();
LPDIRECT3DSURFACE9 renderTarget();
LPDIRECT3DSURFACE9 surface(QPaintDevice *pd);
LPDIRECT3DSWAPCHAIN9 swapChain(QPaintDevice *pd);
void releasePaintDevice(QPaintDevice *pd);
LPDIRECT3DDEVICE9 device();
void cleanup();
QSize maxSize() const;
private:
struct D3DSwapChain {
QSize size;
LPDIRECT3DSWAPCHAIN9 swapchain;
LPDIRECT3DSURFACE9 surface;
};
void updateMaxSize();
void initPresentParameters(D3DPRESENT_PARAMETERS *params);
D3DSwapChain *createSwapChain(QWidget *w);
QSize m_max_size;
int m_status;
QMap<QPaintDevice *, D3DSwapChain *> m_swapchains;
LPDIRECT3DDEVICE9 m_device;
QPaintDevice *m_pd;
HWND m_dummy;
D3DSwapChain *m_current;
private Q_SLOTS:
void cleanupPaintDevice(QObject *);
};
struct vertex {
D3DVECTOR pos;
DWORD color;
FLOAT s0, t0, r0, q0;
FLOAT s1, t1, r1, q1;
};
struct QD3DMaskPosition {
int x, y, channel;
};
struct QD3DBatchItem {
enum QD3DBatchInfo {
BI_WINDING = 0x0001,
BI_AA = 0x0002,
BI_BRECT = 0x0004,
BI_MASKFULL = 0x0008,
BI_TEXT = 0x0010,
BI_MASK = 0x0020,
BI_CLIP = 0x0040,
BI_SCISSOR = 0x0080,
BI_PIXMAP = 0x0100,
BI_IMAGE = 0x0200,
BI_COMPLEXBRUSH = 0x0400,
BI_CLEARCLIP = 0x0800, // clip nothing (filling the clip mask with 0)
BI_TRANSFORM = 0x1000,
BI_MASKSCISSOR = 0x2000,
BI_FASTLINE = 0x4000,
BI_COSMETICPEN = 0x8000
};
int m_info;
int m_count;
int m_offset;
QD3DMaskPosition m_maskpos;
qreal m_xoffset;
qreal m_yoffset;
qreal m_opacity;
QPixmap m_pixmap;
QRectF m_brect;
QBrush m_brush;
IDirect3DTexture9 *m_texture;
qreal m_width;
qreal m_distance;
QTransform m_matrix;
QPainter::CompositionMode m_cmode;
QVector<int> m_pointstops;
};
struct QD3DBatch {
int m_item_index;
QD3DBatchItem items[QD3D_BATCH_SIZE];
};
class QD3DStateManager;
class QD3DFontCache;
class QD3DDrawHelper;
class QD3DGradientCache;
class QDirect3DPaintEnginePrivate : public QPaintEnginePrivate
{
Q_DECLARE_PUBLIC(QDirect3DPaintEngine)
public:
enum RenderTechnique {
RT_NoTechnique,
RT_Antialiased,
RT_Aliased,
};
QDirect3DPaintEnginePrivate()
: m_d3d_object(0)
, m_d3d_device(0)
, m_txop(QTransform::TxNone)
, m_effect(0)
, m_flush_on_end(0)
{ init(); }
~QDirect3DPaintEnginePrivate();
bool init();
void initDevice();
inline QD3DBatchItem *nextBatchItem();
QPolygonF brushCoordinates(const QRectF &r, bool stroke, qreal *fp) const;
void fillAliasedPath(QPainterPath path, const QRectF &brect, const QTransform &txform);
void fillAntialiasedPath(const QPainterPath &path, const QRectF &brect,
const QTransform &txform, bool stroke);
void fillPath(const QPainterPath &path, QRectF brect);
void strokePath(const QPainterPath &path, QRectF brect, bool simple = false);
QPainterPath strokePathFastPen(const QPainterPath &path);
void strokeAliasedPath(QPainterPath path, const QRectF &brect, const QTransform &txform);
void flushBatch();
int flushAntialiased(int offset);
void flushAliased(QD3DBatchItem *item, int offset);
void flushText(QD3DBatchItem *item, int offset);
void flushLines(QD3DBatchItem *item, int offset);
void updateTransform(const QTransform &matrix);
void updatePen(const QPen &pen);
void updateBrush(const QBrush &pen);
void updateClipRegion(const QRegion &clipregion, Qt::ClipOperation op = Qt::ReplaceClip);
void updateClipPath(const QPainterPath &clipregion, Qt::ClipOperation op = Qt::ReplaceClip);
void updateFont(const QFont &font);
void setRenderTechnique(RenderTechnique technique);
QPointF transformPoint(const QPointF &p, qreal *w) const;
bool prepareBatch(QD3DBatchItem *item, int offset);
void prepareItem(QD3DBatchItem *item);
void cleanupItem(QD3DBatchItem *item);
void setCompositionMode(QPainter::CompositionMode mode);
void verifyTexture(const QPixmap &pixmap);
bool isFastRect(const QRectF &rect);
void releaseDC();
void cleanup();
bool testCaps();
QPixmap getPattern(Qt::BrushStyle style) const;
// clipping
QPainterPath m_sysclip_path;
QPainterPath m_clip_path;
QRegion m_sysclip_region;
QRegion m_clip_region;
qreal m_opacity;
D3DCOLOR m_opacity_color;
int m_current_state;
ID3DXEffect* m_effect;
RenderTechnique m_current_technique;
QTransform m_matrix;
qreal m_inv_scale;
QPen m_pen;
Qt::BrushStyle m_pen_brush_style;
QTransform m_inv_pen_matrix;
D3DCOLOR m_pen_color;
qreal m_pen_width;
QBrush m_brush;
Qt::BrushStyle m_brush_style;
QTransform m_inv_brush_matrix;
D3DCOLOR m_brush_color;
QTransform m_brush_origin;
uint m_clipping_enabled : 1;
uint m_has_complex_clipping : 1;
uint m_cleartype_text: 1;
uint m_has_pen : 1;
uint m_has_cosmetic_pen : 1;
uint m_has_brush : 1;
uint m_has_fast_pen : 1;
uint m_has_aa_fast_pen : 1;
uint m_flush_on_end : 1;
uint m_supports_d3d : 1;
QTransform::TransformationType m_txop;
QPainter::CompositionMode m_cmode;
QD3DSurfaceManager m_surface_manager;
QSize m_surface_size;
LPDIRECT3D9 m_d3d_object;
LPDIRECT3DDEVICE9 m_d3d_device;
IDirect3DSurface9 *m_current_surface;
bool m_in_scene;
QD3DGradientCache *m_gradient_cache;
QD3DDrawHelper *m_draw_helper;
QD3DBatch m_batch;
QD3DStateManager *m_statemanager;
HDC m_dc;
IDirect3DSurface9 *m_dcsurface;
QMap<Qt::BrushStyle, QPixmap> m_patterns;
};
class QD3DStateManager : public ID3DXEffectStateManager {
public:
QD3DStateManager(LPDIRECT3DDEVICE9 pDevice, ID3DXEffect *effect);
void reset();
inline void startStateBlock();
inline void endStateBlock();
inline void setCosmeticPen(bool enabled);
inline void setBrushMode(int mode);
inline void setTexture(LPDIRECT3DBASETEXTURE9 pTexture);
inline void setTexture(LPDIRECT3DBASETEXTURE9 pTexture, QGradient::Spread spread);
inline void setTransformation(const QTransform *matrix = 0);
inline void setProjection(const D3DXMATRIX *pMatrix);
inline void setMaskChannel(int channel);
inline void setMaskOffset(qreal x, qreal y);
inline void setFocalDistance(const qreal &fd);
inline void beginPass(int pass);
inline void endPass();
STDMETHOD(QueryInterface)(REFIID iid, LPVOID *ppv);
STDMETHOD_(ULONG, AddRef)();
STDMETHOD_(ULONG, Release)();
STDMETHOD(SetTransform)(D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX *pMatrix);
STDMETHOD(SetMaterial)(CONST D3DMATERIAL9 *pMaterial);
STDMETHOD(SetLight)(DWORD Index, CONST D3DLIGHT9 *pLight);
STDMETHOD(LightEnable)(DWORD Index, BOOL Enable);
STDMETHOD(SetRenderState)(D3DRENDERSTATETYPE State, DWORD Value);
STDMETHOD(SetTexture)(DWORD Stage, LPDIRECT3DBASETEXTURE9 pTexture);
STDMETHOD(SetTextureStageState)(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value);
STDMETHOD(SetSamplerState)(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value);
STDMETHOD(SetNPatchMode)(FLOAT NumSegments);
STDMETHOD(SetFVF)(DWORD FVF);
STDMETHOD(SetVertexShader)(LPDIRECT3DVERTEXSHADER9 pShader);
STDMETHOD(SetVertexShaderConstantF)(UINT RegisterIndex, CONST FLOAT *pConstantData, UINT RegisterCount);
STDMETHOD(SetVertexShaderConstantI)(UINT RegisterIndex, CONST INT *pConstantData, UINT RegisterCount);
STDMETHOD(SetVertexShaderConstantB)(UINT RegisterIndex, CONST BOOL *pConstantData, UINT RegisterCount);
STDMETHOD(SetPixelShader)(LPDIRECT3DPIXELSHADER9 pShader);
STDMETHOD(SetPixelShaderConstantF)(UINT RegisterIndex, CONST FLOAT *pConstantData, UINT RegisterCount);
STDMETHOD(SetPixelShaderConstantI)(UINT RegisterIndex, CONST INT *pConstantData, UINT RegisterCount);
STDMETHOD(SetPixelShaderConstantB)(UINT RegisterIndex, CONST BOOL *pConstantData, UINT RegisterCount);
private:
LPDIRECT3DVERTEXSHADER9 m_vertexshader;
LPDIRECT3DPIXELSHADER9 m_pixelshader;
LPDIRECT3DBASETEXTURE9 m_textures[D3D_STAGE_COUNT];
DWORD m_texturestates[D3D_STAGE_COUNT][D3D_TEXTURE_STATES];
DWORD m_samplerstates[D3D_STAGE_COUNT][D3D_SAMPLE_STATES];
DWORD m_renderstate[D3D_RENDER_STATES];
qreal m_radgradfd;
bool m_cosmetic_pen;
int m_pass;
int m_maskchannel;
int m_brushmode;
LPDIRECT3DBASETEXTURE9 m_texture;
D3DXMATRIX m_projection;
D3DXMATRIX m_d3dIdentityMatrix;
bool m_isIdentity;
QTransform m_transformation;
LPDIRECT3DDEVICE9 m_pDevice;
ID3DXEffect *m_effect;
LONG m_refs;
bool m_changed;
qreal m_xoffset, m_yoffset;
static int m_mask_channels[4][4];
};
//
// font cache stuff
//
struct QD3DGlyphCoord {
// stores the offset and size of a glyph texture
qreal x;
qreal y;
qreal width;
qreal height;
qreal log_width;
qreal log_height;
QFixed x_offset;
QFixed y_offset;
};
struct QD3DFontTexture {
int x_offset; // current glyph offset within the texture
int y_offset;
int width;
int height;
IDirect3DTexture9 *texture;
};
typedef QHash<glyph_t, QD3DGlyphCoord*> QD3DGlyphHash;
typedef QHash<QFontEngine*, QD3DGlyphHash*> QD3DFontGlyphHash;
typedef QHash<quint64, QD3DFontTexture*> QD3DFontTexHash;
class QD3DGlyphCache : public QObject
{
Q_OBJECT
public:
QD3DGlyphCache()
: QObject(0)
, current_cache(0) {}
~QD3DGlyphCache();
QD3DGlyphCoord *lookup(QFontEngine *, glyph_t);
void cacheGlyphs(QDirect3DPaintEngine *, const QTextItemInt &, const QVarLengthArray<glyph_t> &,
bool);
void cleanCache();
inline QD3DFontTexture *fontTexture(QFontEngine *engine) {
return font_textures.constFind(reinterpret_cast<quint64>(engine)).value();
}
public slots:
void fontEngineDestroyed(QObject *);
private:
QImage clearTypeGlyph(QFontEngine *, glyph_t glyph);
QD3DGlyphHash *current_cache;
QD3DFontTexHash font_textures;
QD3DFontGlyphHash font_cache;
};
QD3DGlyphCache::~QD3DGlyphCache()
{
}
QD3DGlyphCoord *QD3DGlyphCache::lookup(QFontEngine *, glyph_t g)
{
Q_ASSERT(current_cache != 0);
QD3DGlyphHash::const_iterator it = current_cache->constFind(g);
if (it == current_cache->constEnd())
return 0;
return it.value();
}
void QD3DGlyphCache::cleanCache()
{
QList<quint64> keys = font_textures.keys();
for (int i=0; i<keys.size(); ++i)
font_textures.value(keys.at(i))->texture->Release();
qDeleteAll(font_textures);
qDeleteAll(font_cache);
font_textures.clear();
font_cache.clear();
current_cache = 0;
}
void QD3DGlyphCache::fontEngineDestroyed(QObject *object)
{
// qDebug() << "=> font engine destroyed: " << object;
QFontEngine *engine = static_cast<QFontEngine *>(object);
QD3DFontGlyphHash::iterator cache_it = font_cache.find(engine);
if (cache_it != font_cache.end()) {
QD3DGlyphHash *cache = font_cache.take(engine);
delete cache;
}
quint64 font_key = reinterpret_cast<quint64>(engine);
QD3DFontTexture *tex = font_textures.take(font_key);
if (tex) {
tex->texture->Release();
delete tex;
}
}
QImage QD3DGlyphCache::clearTypeGlyph(QFontEngine *engine, glyph_t glyph)
{
glyph_metrics_t gm = engine->boundingBox(glyph);
int glyph_x = qFloor(gm.x.toReal());
int glyph_y = qFloor(gm.y.toReal());
int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x + 2;
int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y + 2;
if (glyph_width + glyph_x <= 0 || glyph_height <= 0)
return QImage();
QImage im(glyph_width + glyph_x, glyph_height, QImage::Format_ARGB32_Premultiplied);
im.fill(0xff000000); // solid black
QPainter p(&im);
p.setPen(Qt::white);
p.setBrush(Qt::NoBrush);
QTextItemInt ti;
ti.ascent = engine->ascent();
ti.descent = engine->descent();
ti.width = glyph_width;
ti.fontEngine = engine;
QGlyphLayoutArray<1> glyphLayout;
ti.glyphs = glyphLayout;
ti.glyphs.glyphs[0] = glyph;
ti.glyphs.advances_x[0] = glyph_width;
p.drawTextItem(QPointF(-glyph_x, -glyph_y), ti);
p.end();
return im;
}
#if 0
static void dump_font_texture(QD3DFontTexture *tex)
{
QColor color(Qt::red);
D3DLOCKED_RECT rect;
if (FAILED(tex->texture->LockRect(0, &rect, 0, 0))) {
qDebug() << "debug: unable to lock texture rect.";
return;
}
// cleartype version
// uint *tex_data = (uint *) rect.pBits;
// QImage im(tex->width, tex->height, QImage::Format_ARGB32);
// for (int y=0; y<tex->height; ++y) {
// for (int x=0; x<tex->width; ++x) {
// im.setPixel(x, y, ((*(tex_data+x+y*tex->width))));
// }
// }
uchar *tex_data = (uchar *) rect.pBits;
QImage im(rect.Pitch, tex->height, QImage::Format_ARGB32);
for (int y=0; y<tex->height; ++y) {
for (int x=0; x<rect.Pitch; ++x) {
uchar val = ((*(tex_data+x+y*rect.Pitch)));
im.setPixel(x, y, 0xff000000 | (val << 16) | (val << 8) | val);
}
}
tex->texture->UnlockRect(0);
static int i= 0;
im.save(QString("tx%1.png").arg(i++));
}
#endif
void QD3DGlyphCache::cacheGlyphs(QDirect3DPaintEngine *engine, const QTextItemInt &ti,
const QVarLengthArray<glyph_t> &glyphs, bool clearType)
{
IDirect3DDevice9 *device = engine->d_func()->m_d3d_device;
QD3DFontGlyphHash::const_iterator cache_it = font_cache.constFind(ti.fontEngine);
QD3DGlyphHash *cache = 0;
if (cache_it == font_cache.constEnd()) {
cache = new QD3DGlyphHash;
font_cache.insert(ti.fontEngine, cache);
connect(ti.fontEngine, SIGNAL(destroyed(QObject *)), SLOT(fontEngineDestroyed(QObject *)));
} else {
cache = cache_it.value();
}
current_cache = cache;
D3DFORMAT tex_format = clearType ? D3DFMT_A8R8G8B8 : D3DFMT_A8;
quint64 font_key = reinterpret_cast<quint64>(ti.fontEngine);
QD3DFontTexHash::const_iterator it = font_textures.constFind(font_key);
QD3DFontTexture *font_tex = 0;
if (it == font_textures.constEnd()) {
// alloc a new texture, put it into the cache
int tex_height = qCeil(ti.ascent.toReal() + ti.descent.toReal()) + 5;
int tex_width = tex_height * 30; // ###
IDirect3DTexture9 *tex;
if (FAILED(device->CreateTexture(tex_width, tex_height, 1, 0,
tex_format, D3DPOOL_MANAGED, &tex, NULL)))
{
qWarning("QD3DGlyphCache::cacheGlyphs(): can't allocate font texture (%dx%d).",
tex_width, tex_height);
return;
} else {
// qDebug() << "=> new font texture: " << QSize(tex_width,tex_height);
font_tex = new QD3DFontTexture;
font_tex->texture = tex;
font_tex->x_offset = 0;
font_tex->y_offset = 0;
font_tex->width = tex_width;
font_tex->height = tex_height;
font_textures.insert(font_key, font_tex);
}
} else {
font_tex = it.value();
// make it current render target..
}
// cache each glyph
for (int i=0; i<glyphs.size(); ++i) {
QD3DGlyphHash::const_iterator it = cache->constFind(glyphs[i]);
if (it == cache->constEnd()) {
glyph_metrics_t metrics = ti.fontEngine->boundingBox(glyphs[i]);
int glyph_width = qCeil(metrics.width.toReal()) + 5;
int glyph_height = qCeil(ti.ascent.toReal() + ti.descent.toReal()) + 5;
if (font_tex->x_offset + glyph_width > font_tex->width) {
// no room on the current line, start new glyph strip
int strip_height = glyph_height;
font_tex->x_offset = 0;
font_tex->y_offset += strip_height;
if (font_tex->y_offset >= font_tex->height) {
// if no room in the current texture - realloc a larger texture
int old_tex_height = font_tex->height;
font_tex->height += strip_height;
IDirect3DTexture9 *new_tex;
if (FAILED(device->CreateTexture(font_tex->width, font_tex->height, 1, 0,
tex_format, D3DPOOL_MANAGED, &new_tex, NULL)))
{
qWarning("QD3DGlyphCache(): can't re-allocate font texture.");
return;
} else {
// qDebug() << " -> new glyph strip added:" << QSize(font_tex->width,font_tex->height);
D3DLOCKED_RECT new_rect, old_rect;
if (FAILED(font_tex->texture->LockRect(0, &old_rect, 0, D3DLOCK_READONLY))) {
qDebug() << "QD3DGlyphCache: unable to lock texture rect.";
return;
}
if (FAILED(new_tex->LockRect(0, &new_rect, 0, 0))) {
qDebug() << "QD3DGlyphCache: unable to lock texture rect.";
return;
}
memcpy(new_rect.pBits, old_rect.pBits, new_rect.Pitch * old_tex_height);
font_tex->texture->UnlockRect(0);
new_tex->UnlockRect(0);
engine->d_func()->flushBatch();
font_tex->texture->Release();
font_tex->texture = new_tex;
}
// update the texture coords and the y offset for the existing glyphs in
// the cache, because of the texture size change
QD3DGlyphHash::iterator it = cache->begin();
while (it != cache->end()) {
it.value()->height = (it.value()->height * old_tex_height) / font_tex->height;
it.value()->y = (it.value()->y * old_tex_height) / font_tex->height;
++it;
}
}
}
QD3DGlyphCoord *d3d_glyph = new QD3DGlyphCoord;
d3d_glyph->x = qreal(font_tex->x_offset) / font_tex->width;
d3d_glyph->y = qreal(font_tex->y_offset) / font_tex->height;
d3d_glyph->width = qreal(glyph_width) / font_tex->width;
d3d_glyph->height = qreal(glyph_height) / font_tex->height;
d3d_glyph->log_width = d3d_glyph->width * font_tex->width;
d3d_glyph->log_height = d3d_glyph->height * font_tex->height;
d3d_glyph->x_offset = -metrics.x;
d3d_glyph->y_offset = metrics.y;
QImage glyph_im;
if (clearType)
glyph_im = clearTypeGlyph(ti.fontEngine, glyphs[i]);
else
glyph_im = ti.fontEngine->alphaMapForGlyph(glyphs[i]).convertToFormat(QImage::Format_Indexed8);
// write glyph to texture
D3DLOCKED_RECT rect;
RECT glyph_rect = { font_tex->x_offset, font_tex->y_offset,
font_tex->x_offset + glyph_im.width(),
font_tex->y_offset + glyph_im.height() };
// qDebug() << " > new glyph char added:" << QSize(glyph_im.width(), glyph_im.height());
if (FAILED(font_tex->texture->LockRect(0, &rect, &glyph_rect, 0))) {
qDebug() << "QD3DGlyphCache: unable to lock texture rect.";
return;
}
// ### unify these loops
if (clearType) {
int ppl = rect.Pitch / 4;
uint *tex_data = (uint *) rect.pBits;
for (int y=0; y<glyph_im.height(); ++y) {
uint *s = (uint *) glyph_im.scanLine(y);
for (int x=0; x<glyph_im.width(); ++x) {
tex_data[ppl*y + x] = *s;
++s;
}
}
} else {
int ppl = rect.Pitch;
uchar *tex_data = (uchar *) rect.pBits;
for (int y=0; y<glyph_im.height(); ++y) {
uchar *s = (uchar *) glyph_im.scanLine(y);
for (int x=0; x<glyph_im.width(); ++x) {
tex_data[ppl*y + x] = *s;
++s;
}
}
}
font_tex->texture->UnlockRect(0);
// debug
// dump_font_texture(font_tex);
if (font_tex->x_offset + glyph_width > font_tex->width) {
font_tex->x_offset = 0;
font_tex->y_offset += glyph_height;
} else {
font_tex->x_offset += glyph_width;
}
cache->insert(glyphs[i], d3d_glyph);
}
}
}
Q_GLOBAL_STATIC(QD3DGlyphCache, qd3d_glyph_cache)
//
// end font caching stuff
//
//
// D3D image cache stuff
//
// ### keep the GL stuff in mind..
typedef void (*_qt_image_cleanup_hook_64)(qint64);
extern Q_GUI_EXPORT _qt_image_cleanup_hook_64 qt_image_cleanup_hook_64;
static void qd3d_image_cleanup(qint64 key);
class QD3DImage
{
public:
QD3DImage(IDirect3DDevice9 *device, const QImage &image);
~QD3DImage();
IDirect3DTexture9 *texture;
};
static QList<IDirect3DTexture9 *> qd3d_release_list;
QD3DImage::QD3DImage(IDirect3DDevice9 *device, const QImage &image)
{
texture = 0;
Q_ASSERT(device);
QImage im = image.convertToFormat(QImage::Format_ARGB32);
if (FAILED(device->CreateTexture(im.width(), im.height(), 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &texture, 0))) {
qWarning("QD3DImage(): unable to create Direct3D texture.");
return;
}
// qDebug(" -> created image texture: %p - 0x%08x%08x",texture,uint (image.cacheKey() >> 32),uint (image.cacheKey() & 0xffffffff));
D3DLOCKED_RECT rect;
if (FAILED(texture->LockRect(0, &rect, 0, 0))) {
qDebug() << "QD3DImage: unable to lock texture rect.";
return;
}
DWORD *dst = (DWORD *) rect.pBits;
DWORD *src = (DWORD *) im.scanLine(0);
Q_ASSERT((rect.Pitch/4) == (im.bytesPerLine()/4));
memcpy(dst, src, rect.Pitch*im.height());
texture->UnlockRect(0);
}
QD3DImage::~QD3DImage()
{
if (texture)
qd3d_release_list.append(texture);
}
static int qd3d_cache_limit = 64*1024; // cache ~64 MB worth of textures
typedef QCache<quint64, QD3DImage> QD3DImageCache;
class QD3DImageManager
{
public:
QD3DImageManager() {
// ### GL does the same!
qt_image_cleanup_hook_64 = qd3d_image_cleanup;
cache.setMaxCost(qd3d_cache_limit);
}
~QD3DImageManager() {
// qDebug() << "unhooking d3d image cache";
qt_image_cleanup_hook_64 = 0;
cache.clear();
}
IDirect3DTexture9 *lookup(IDirect3DDevice9 *device, const QImage &image);
void remove(quint64 key);
private:
QD3DImageCache cache;
};
IDirect3DTexture9 *QD3DImageManager::lookup(IDirect3DDevice9 *device, const QImage &image)
{
QD3DImage *tex_image = 0;
tex_image = cache.object(image.cacheKey());
if (!tex_image) {
// to avoid cache thrashing we remove images from the cache
// that have the same serial no as the cached image, since
// that image is most likely destoyed already, and we got a
// stale cache entry
uint serial = (uint) (image.cacheKey() >> 32);
QList<quint64> keys = cache.keys();
for (int i=0; i<keys.size(); ++i) {
if ((uint)(keys.at(i) >> 32) == serial) {
cache.remove(keys.at(i));
break;
}
}
// qDebug(" => cached: %d, adding cache image: 0x%08x%08x",cache.size(), uint (image.cacheKey() >> 32),uint (image.cacheKey() & 0xffffffff));
// add cache entry
int cost = image.width()*image.height()*4/1024;
if (cache.totalCost() + cost > cache.maxCost()) {
// no room for new entries? kick out half the cached images
int old_max_cost = cache.maxCost();
cache.setMaxCost(old_max_cost/2);
cache.setMaxCost(old_max_cost);
}
tex_image = new QD3DImage(device, image);
cache.insert(image.cacheKey(), tex_image, cost);
// qDebug() << "==> total cache cost: " << cache.totalCost() << cost;
}
return tex_image->texture;
}
void QD3DImageManager::remove(quint64 key)
{
// QList<quint64> keys = cache.keys();
// if (keys.contains(key))
// qDebug() << "entery removed from cache";
cache.remove(key);
}
Q_GLOBAL_STATIC(QD3DImageManager, qd3d_image_cache)
static void qd3d_image_cleanup(qint64 key)
{
// qDebug() << "qd3d_image_cleanup:";
// qDebug(" => key: 0x%08x%08x", (uint) (key >> 32), (uint)(key & 0xffffffff));
qd3d_image_cache()->remove(key);
}
//
// end D3D image cache stuff
//
class QD3DDrawHelper : public QTessellator
{
public:
QD3DDrawHelper(QDirect3DPaintEnginePrivate *pe);
~QD3DDrawHelper();
bool needsFlushing() const;
QD3DMaskPosition allocateMaskPosition(const QRectF &brect, bool *breakbatch);
void setClipPath(const QPainterPath &path, QD3DBatchItem **item);
void queueAntialiasedMask(const QPolygonF &poly, QD3DBatchItem **item, const QRectF &brect);
QRectF queueAliasedMask(const QPainterPath &path, QD3DBatchItem **item, D3DCOLOR color);
void queueRect(const QRectF &rect, QD3DBatchItem *item, D3DCOLOR color, const QPolygonF &trect);
void queueRect(const QRectF &rect, QD3DBatchItem *item, D3DCOLOR color);
void queueTextGlyph(const QRectF &rect, const qreal *tex_coords, QD3DBatchItem *item,
D3DCOLOR color);
void queueAntialiasedLines(const QPainterPath &path, QD3DBatchItem **item, const QRectF &brect);
void queueAliasedLines(const QLineF *lines, int lineCount, QD3DBatchItem **item);
int drawAntialiasedMask(int offset, int maxoffset);
void drawAliasedMask(int offset);
void drawAntialiasedBoundingRect(QD3DBatchItem *item);
void drawAliasedBoundingRect(QD3DBatchItem *item);
void drawTextItem(QD3DBatchItem *item);
void drawAliasedLines(QD3DBatchItem *item);
void setMaskSize(QSize size);
void beforeReset();
void afterReset();
IDirect3DSurface9 *freeMaskSurface();
inline void lockVertexBuffer();
inline void unlockVertexBuffer();
inline int index() { return m_index; }
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
enum VertexBufferAccess {
CLEAR = 0x00,
READ = 0x01,
WRITE = 0x02
};
int accesscontrol[QT_VERTEX_BUF_SIZE];
#endif
private:
void addTrap(const Trapezoid &trap);
void tessellate(const QPolygonF &poly);
inline void lineToStencil(qreal x, qreal y);
inline void curveToStencil(const QPointF &cp1, const QPointF &cp2, const QPointF &ep);
QRectF pathToVertexArrays(const QPainterPath &path);
void resetMask();
QDirect3DPaintEnginePrivate *m_pe;
qreal m_xoffset, m_yoffset;
int m_startindex;
int m_index;
int m_height, m_width;
LPDIRECT3DVERTEXBUFFER9 m_d3dvbuff;
vertex *m_vbuff;
QD3DBatchItem *m_item;
QRectF m_boundingRect;
qreal max_x;
qreal max_y;
qreal min_x;
qreal min_y;
qreal firstx;
qreal firsty;
QPointF tess_lastpoint;
int tess_index;
bool m_locked;
IDirect3DTexture9 *m_mask;
IDirect3DSurface9 *m_maskSurface;
IDirect3DSurface9 *m_depthStencilSurface;
D3DCOLOR m_color;
bool m_clearmask;
bool m_isLine;
bool m_firstPoint;
QD3DMaskPosition m_mask_position;
int m_mask_offsetX2;
int m_mask_offsetY2;
};
QD3DStateManager::QD3DStateManager(LPDIRECT3DDEVICE9 pDevice, ID3DXEffect *effect)
: m_pDevice(pDevice), m_effect(effect), m_refs(0)
{
if (FAILED(D3DXMatrixIdentity(&m_d3dIdentityMatrix))) {
qWarning("QDirect3DPaintEngine: D3DXMatrixIdentity failed");
}
reset();
}
void QD3DStateManager::reset()
{
m_radgradfd = -1;
m_cosmetic_pen = false;
m_pass = -1;
m_maskchannel = -1;
m_brushmode = -1;
m_texture = 0;
m_xoffset = INT_MAX;
m_yoffset = INT_MAX;
m_vertexshader = 0;
m_pixelshader = 0;
m_isIdentity = true;
m_transformation = QTransform();
m_effect->SetMatrix("g_mTransformation", &m_d3dIdentityMatrix);
ZeroMemory(&m_projection, sizeof(D3DMATRIX));
ZeroMemory(m_textures, sizeof(LPDIRECT3DBASETEXTURE9) * D3D_STAGE_COUNT);
FillMemory(m_samplerstates, sizeof(DWORD) * D3D_SAMPLE_STATES * D3D_STAGE_COUNT, 0xFFFFFFFE);
FillMemory(m_texturestates, sizeof(DWORD) * D3D_TEXTURE_STATES * D3D_STAGE_COUNT, 0xFFFFFFFE);
FillMemory(m_renderstate, sizeof(DWORD) * D3D_RENDER_STATES, 0xFFFFFFFE);
}
inline void QD3DStateManager::beginPass(int pass)
{
if (pass != m_pass) {
if (m_pass != -1)
m_effect->EndPass();
m_effect->BeginPass(pass);
m_pass = pass;
}
}
inline void QD3DStateManager::endPass()
{
if (m_pass != -1) {
m_pass = -1;
m_effect->EndPass();
}
}
inline void QD3DStateManager::startStateBlock() {
m_changed = false;
}
inline void QD3DStateManager::setCosmeticPen(bool enabled)
{
if (enabled != m_cosmetic_pen) {
m_effect->SetBool("g_mCosmeticPen", enabled);
m_cosmetic_pen = enabled;
m_changed = true;
}
}
inline void QD3DStateManager::setBrushMode(int mode)
{
if (mode != m_brushmode) {
m_effect->SetInt("g_mBrushMode", mode);
m_brushmode = mode;
m_changed = true;
}
}
inline void QD3DStateManager::setTexture(LPDIRECT3DBASETEXTURE9 pTexture)
{
SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER);
SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER);
if (pTexture != m_texture) {
m_texture = pTexture;
m_effect->SetTexture("g_mTexture", pTexture);
m_changed = true;
}
}
inline void QD3DStateManager::setTexture(LPDIRECT3DBASETEXTURE9 pTexture, QGradient::Spread spread)
{
switch(spread) {
case QGradient::RepeatSpread:
SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
break;
case QGradient::ReflectSpread:
SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_MIRROR);
SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_MIRROR);
break;
default:
SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
break;
};
if (pTexture != m_texture) {
m_texture = pTexture;
m_effect->SetTexture("g_mTexture", pTexture);
m_changed = true;
}
}
inline void QD3DStateManager::setTransformation(const QTransform *matrix)
{
if (matrix) {
if (*matrix != m_transformation) {
D3DXMATRIX dxmatrix(matrix->m11(), matrix->m12(), 0, matrix->m13(),
matrix->m21(), matrix->m22(), 0, matrix->m23(),
0, 0, 1, 0,
matrix->dx(), matrix->dy(), 0, 1);
m_effect->SetMatrix("g_mTransformation", &dxmatrix);
m_transformation = *matrix;
m_changed = true;
m_isIdentity = false;
}
} else if (!m_isIdentity) {
m_effect->SetMatrix("g_mTransformation", &m_d3dIdentityMatrix);
m_transformation = QTransform();
m_changed = true;
m_isIdentity = true;
}
}
inline void QD3DStateManager::setProjection(const D3DXMATRIX *pMatrix)
{
if (*pMatrix != m_projection) {
m_effect->SetMatrix("g_mViewProjection", pMatrix);
m_projection = *pMatrix;
m_changed = true;
}
}
inline void QD3DStateManager::setFocalDistance(const qreal &fd)
{
if (fd != m_radgradfd) {
m_effect->SetFloat("g_mFocalDist", fd);
m_changed = true;
m_radgradfd = fd;
}
}
inline void QD3DStateManager::setMaskOffset(qreal x, qreal y)
{
if (x != m_xoffset || y != m_yoffset) {
float offset[2] = {x, y};
m_effect->SetFloatArray("g_mMaskOffset", offset, 2);
m_xoffset = x;
m_yoffset = y;
m_changed = true;
}
}
inline void QD3DStateManager::setMaskChannel(int channel)
{
if (m_maskchannel != channel) {
m_effect->SetIntArray("g_mChannel", m_mask_channels[channel], 4);
m_maskchannel = channel;
m_changed = true;
}
}
inline void QD3DStateManager::endStateBlock()
{
if (m_changed) {
m_effect->CommitChanges();
m_changed = false;
}
}
STDMETHODIMP QD3DStateManager::QueryInterface(REFIID iid, LPVOID *ppv)
{
if(iid == IID_IUnknown || iid == IID_ID3DXEffectStateManager)
{
*ppv = this;
++m_refs;
return NOERROR;
}
*ppv = NULL;
return ResultFromScode(E_NOINTERFACE);
}
STDMETHODIMP_(ULONG) QD3DStateManager::AddRef(void)
{
return (ULONG)InterlockedIncrement( &m_refs );
}
STDMETHODIMP_(ULONG) QD3DStateManager::Release(void)
{
if( 0L == InterlockedDecrement( &m_refs ) ) {
delete this;
return 0L;
}
return m_refs;
}
STDMETHODIMP QD3DStateManager::SetTransform(D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX *pMatrix)
{
return m_pDevice->SetTransform(State, pMatrix);
}
STDMETHODIMP QD3DStateManager::SetMaterial(CONST D3DMATERIAL9 *pMaterial)
{
return m_pDevice->SetMaterial(pMaterial);
}
STDMETHODIMP QD3DStateManager::SetLight(DWORD Index, CONST D3DLIGHT9 *pLight)
{
return m_pDevice->SetLight(Index, pLight);
}
STDMETHODIMP QD3DStateManager::LightEnable(DWORD Index, BOOL Enable)
{
return m_pDevice->LightEnable(Index, Enable);
}
STDMETHODIMP QD3DStateManager::SetRenderState(D3DRENDERSTATETYPE State, DWORD Value)
{
if (State < D3D_RENDER_STATES) {
if (m_renderstate[State] == Value)
return S_OK;
m_renderstate[State] = Value;
}
return m_pDevice->SetRenderState(State, Value);
}
STDMETHODIMP QD3DStateManager::SetTexture(DWORD Stage, LPDIRECT3DBASETEXTURE9 pTexture)
{
if (Stage < D3D_STAGE_COUNT) {
if (m_textures[Stage] == pTexture)
return S_OK;
m_textures[Stage] = pTexture;
}
return m_pDevice->SetTexture(Stage, pTexture);
}
STDMETHODIMP QD3DStateManager::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
if (Stage < D3D_STAGE_COUNT && Type < D3D_TEXTURE_STATES) {
if (m_texturestates[Stage][Type] == Value)
return S_OK;
m_texturestates[Stage][Type] = Value;
}
return m_pDevice->SetTextureStageState(Stage, Type, Value);
}
STDMETHODIMP QD3DStateManager::SetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value)
{
if (Sampler < D3D_STAGE_COUNT && Type < D3D_SAMPLE_STATES) {
if (m_samplerstates[Sampler][Type] == Value)
return S_OK;
m_samplerstates[Sampler][Type] = Value;
}
return m_pDevice->SetSamplerState(Sampler, Type, Value);
}
STDMETHODIMP QD3DStateManager::SetNPatchMode(FLOAT NumSegments)
{
return m_pDevice->SetNPatchMode(NumSegments);
}
STDMETHODIMP QD3DStateManager::SetFVF(DWORD FVF)
{
return m_pDevice->SetFVF(FVF);
}
STDMETHODIMP QD3DStateManager::SetVertexShader(LPDIRECT3DVERTEXSHADER9 pShader)
{
if (m_vertexshader == pShader)
return S_OK;
m_vertexshader = pShader;
return m_pDevice->SetVertexShader(pShader);
}
STDMETHODIMP QD3DStateManager::SetVertexShaderConstantF(UINT RegisterIndex, CONST FLOAT *pConstantData, UINT RegisterCount)
{
return m_pDevice->SetVertexShaderConstantF(RegisterIndex, pConstantData, RegisterCount);
}
STDMETHODIMP QD3DStateManager::SetVertexShaderConstantI(UINT RegisterIndex, CONST INT *pConstantData, UINT RegisterCount)
{
return m_pDevice->SetVertexShaderConstantI(RegisterIndex, pConstantData, RegisterCount);
}
STDMETHODIMP QD3DStateManager::SetVertexShaderConstantB(UINT RegisterIndex, CONST BOOL *pConstantData, UINT RegisterCount)
{
return m_pDevice->SetVertexShaderConstantB(RegisterIndex, pConstantData, RegisterCount);
}
STDMETHODIMP QD3DStateManager::SetPixelShader(LPDIRECT3DPIXELSHADER9 pShader)
{
if (m_pixelshader == pShader)
return S_OK;
m_pixelshader = pShader;
return m_pDevice->SetPixelShader(pShader);
}
STDMETHODIMP QD3DStateManager::SetPixelShaderConstantF(UINT RegisterIndex, CONST FLOAT *pConstantData, UINT RegisterCount)
{
return m_pDevice->SetPixelShaderConstantF(RegisterIndex, pConstantData, RegisterCount);
}
STDMETHODIMP QD3DStateManager::SetPixelShaderConstantI(UINT RegisterIndex, CONST INT *pConstantData, UINT RegisterCount)
{
return m_pDevice->SetPixelShaderConstantI(RegisterIndex, pConstantData, RegisterCount);
}
STDMETHODIMP QD3DStateManager::SetPixelShaderConstantB(UINT RegisterIndex, CONST BOOL *pConstantData, UINT RegisterCount)
{
return m_pDevice->SetPixelShaderConstantB(RegisterIndex, pConstantData, RegisterCount);
}
#define QD3D_GRADIENT_CACHE_SIZE 60
#define QD3D_GRADIENT_PALETTE_SIZE 1024
class QD3DGradientCache
{
struct CacheInfo
{
inline CacheInfo(QGradientStops s, qreal op) :
stops(s), opacity(op) {}
IDirect3DTexture9 *texture;
QGradientStops stops;
qreal opacity;
};
typedef QMultiHash<quint64, CacheInfo> QD3DGradientColorTableHash;
public:
QD3DGradientCache(LPDIRECT3DDEVICE9 device);
~QD3DGradientCache();
inline IDirect3DTexture9 *getBuffer(const QGradientStops &stops, qreal opacity);
protected:
inline void generateGradientColorTable(const QGradientStops& s,
uint *colorTable,
int size, qreal opacity) const;
IDirect3DTexture9 *addCacheElement(quint64 hash_val, const QGradientStops &stops, qreal opacity);
void cleanCache();
QD3DGradientColorTableHash cache;
LPDIRECT3DDEVICE9 m_device;
};
QD3DGradientCache::QD3DGradientCache(LPDIRECT3DDEVICE9 device)
: m_device(device)
{
}
QD3DGradientCache::~QD3DGradientCache()
{
cleanCache();
}
inline IDirect3DTexture9 *QD3DGradientCache::getBuffer(const QGradientStops &stops, qreal opacity)
{
quint64 hash_val = 0;
for (int i = 0; i < stops.size() && i <= 2; i++)
hash_val += stops[i].second.rgba();
QD3DGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
if (it == cache.constEnd())
return addCacheElement(hash_val, stops, opacity);
else {
do {
const CacheInfo &cache_info = it.value();
if (cache_info.stops == stops && cache_info.opacity == opacity) {
return cache_info.texture;
}
++it;
} while (it != cache.constEnd() && it.key() == hash_val);
// an exact match for these stops and opacity was not found, create new cache
return addCacheElement(hash_val, stops, opacity);
}
}
void QD3DGradientCache::generateGradientColorTable(const QGradientStops& s, uint *colorTable, int size, qreal opacity) const
{
int pos = 0;
qreal fpos = 0.0;
qreal incr = 1.0 / qreal(size);
QVector<uint> colors(s.size());
for (int i = 0; i < s.size(); ++i)
colors[i] = s[i].second.rgba();
uint alpha = qRound(opacity * 255);
while (fpos < s.first().first) {
colorTable[pos] = ARGB_COMBINE_ALPHA(colors[0], alpha);
pos++;
fpos += incr;
}
for (int i = 0; i < s.size() - 1; ++i) {
qreal delta = 1/(s[i+1].first - s[i].first);
while (fpos < s[i+1].first && pos < size) {
int dist = int(256 * ((fpos - s[i].first) * delta));
int idist = 256 - dist;
uint current_color = ARGB_COMBINE_ALPHA(colors[i], alpha);
uint next_color = ARGB_COMBINE_ALPHA(colors[i+1], alpha);
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
colorTable[pos] = INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist);
#else
uint c = INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist);
colorTable[pos] = ( (c << 24) & 0xff000000)
| ((c >> 24) & 0x000000ff)
| ((c << 8) & 0x00ff0000)
| ((c >> 8) & 0x0000ff00);
#endif // Q_BYTE_ORDER
++pos;
fpos += incr;
}
}
for (;pos < size; ++pos)
colorTable[pos] = colors[s.size() - 1];
}
IDirect3DTexture9 *QD3DGradientCache::addCacheElement(quint64 hash_val, const QGradientStops &stops, qreal opacity)
{
if (cache.size() == QD3D_GRADIENT_CACHE_SIZE) {
int elem_to_remove = qrand() % QD3D_GRADIENT_CACHE_SIZE;
uint key = cache.keys()[elem_to_remove];
// need to call release on each removed cache entry:
QD3DGradientColorTableHash::const_iterator it = cache.constFind(key);
do {
it.value().texture->Release();
} while (++it != cache.constEnd() && it.key() == key);
cache.remove(key); // may remove more than 1, but OK
}
CacheInfo cache_entry(stops, opacity);
uint buffer[QD3D_GRADIENT_PALETTE_SIZE];
generateGradientColorTable(stops, buffer, QD3D_GRADIENT_PALETTE_SIZE, opacity);
if (FAILED(m_device->CreateTexture(QD3D_GRADIENT_PALETTE_SIZE, 1, 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &cache_entry.texture, 0))) {
qWarning("QD3DGradientCache::addCacheElement(): unable to create Direct3D texture.");
return 0;
}
D3DLOCKED_RECT rect;
if (FAILED(cache_entry.texture->LockRect(0, &rect, 0, 0))) {
qDebug() << "QD3DGradientCache::addCacheElement(): unable to lock texture rect.";
return 0;
}
memcpy(rect.pBits, buffer, rect.Pitch);
cache_entry.texture->UnlockRect(0);
return cache.insert(hash_val, cache_entry).value().texture;
}
void QD3DGradientCache::cleanCache()
{
QD3DGradientColorTableHash::const_iterator it = cache.constBegin();
for (; it != cache.constEnd(); ++it) {
const CacheInfo &cache_info = it.value();
cache_info.texture->Release();
}
cache.clear();
}
QD3DSurfaceManager::QD3DSurfaceManager() :
m_status(NoStatus), m_dummy(0), m_device(0), m_pd(0), m_current(0)
{
}
QD3DSurfaceManager::~QD3DSurfaceManager()
{
}
void QD3DSurfaceManager::setPaintDevice(QPaintDevice *pd)
{
m_status = NoStatus;
m_pd = pd;
m_current = 0;
if (m_device->TestCooperativeLevel() != D3D_OK) {
m_status = NeedsResetting;
return;
}
m_current = m_swapchains.value(pd, 0);
QWidget *w = static_cast<QWidget*>(pd);
if (m_current) {
if (m_current->size != w->size()) {
m_swapchains.remove(pd);
m_current->surface->Release();
m_current->swapchain->Release();
delete m_current;
m_current = 0;
}
}
if (!m_current) {
m_current = createSwapChain(w);
updateMaxSize();
}
}
int QD3DSurfaceManager::status() const
{
return m_status;
}
void QD3DSurfaceManager::reset()
{
QList<QPaintDevice *> pds = m_swapchains.keys();
QMap<QPaintDevice *, D3DSwapChain *>::const_iterator i = m_swapchains.constBegin();
while (i != m_swapchains.constEnd()) {
i.value()->surface->Release();
i.value()->swapchain->Release();
++i;
}
qDeleteAll(m_swapchains.values());
m_swapchains.clear();
D3DPRESENT_PARAMETERS params;
initPresentParameters(¶ms);
params.hDeviceWindow = m_dummy;
HRESULT res = m_device->Reset(¶ms);
if (FAILED(res)) {
switch (res) {
case D3DERR_DEVICELOST:
qWarning("QDirect3DPaintEngine: Reset failed (D3DERR_DEVICELOST)");
break;
case D3DERR_DRIVERINTERNALERROR:
qWarning("QDirect3DPaintEngine: Reset failed (D3DERR_DRIVERINTERNALERROR)");
break;
case D3DERR_OUTOFVIDEOMEMORY:
qWarning("QDirect3DPaintEngine: Reset failed (D3DERR_OUTOFVIDEOMEMORY)");
break;
default:
qWarning("QDirect3DPaintEngine: Reset failed");
};
}
for (int i=0; i<pds.count(); ++i) {
QWidget *w = static_cast<QWidget*>(pds.at(i));
createSwapChain(w);
}
// reset the mask as well
m_status = MaxSizeChanged;
setPaintDevice(m_pd);
updateMaxSize();
}
LPDIRECT3DSURFACE9 QD3DSurfaceManager::renderTarget()
{
return m_current ? m_current->surface : 0;
}
LPDIRECT3DSURFACE9 QD3DSurfaceManager::surface(QPaintDevice *pd)
{
D3DSwapChain *swapchain = m_swapchains.value(pd, 0);
return swapchain ? swapchain->surface : 0;
}
LPDIRECT3DSWAPCHAIN9 QD3DSurfaceManager::swapChain(QPaintDevice *pd)
{
D3DSwapChain *swapchain = m_swapchains.value(pd, 0);
return swapchain ? swapchain->swapchain : 0;
}
void QD3DSurfaceManager::releasePaintDevice(QPaintDevice *pd)
{
D3DSwapChain *swapchain = m_swapchains.take(pd);
if (swapchain) {
swapchain->surface->Release();
swapchain->swapchain->Release();
delete swapchain;
if (swapchain == m_current)
m_current = 0;
}
}
LPDIRECT3DDEVICE9 QD3DSurfaceManager::device()
{
return m_device;
}
void QD3DSurfaceManager::cleanup()
{
QPixmapCache::clear();
qd3d_glyph_cache()->cleanCache();
// release doomed textures
for (int k=0; k<qd3d_release_list.size(); ++k)
qd3d_release_list.at(k)->Release();
qd3d_release_list.clear();
QMap<QPaintDevice *, D3DSwapChain *>::const_iterator i = m_swapchains.constBegin();
while (i != m_swapchains.constEnd()) {
i.value()->surface->Release();
i.value()->swapchain->Release();
++i;
}
qDeleteAll(m_swapchains.values());
if (m_device)
m_device->Release();
DestroyWindow(m_dummy);
QString cname(QLatin1String("qt_d3d_dummy"));
QT_WA({
UnregisterClass((TCHAR*)cname.utf16(), (HINSTANCE)qWinAppInst());
} , {
UnregisterClassA(cname.toLatin1(), (HINSTANCE)qWinAppInst());
});
}
QSize QD3DSurfaceManager::maxSize() const
{
return m_max_size;
}
extern "C" {
LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
};
void QD3DSurfaceManager::init(LPDIRECT3D9 object)
{
QString cname(QLatin1String("qt_d3d_dummy"));
uint style = CS_DBLCLKS | CS_SAVEBITS;
ATOM atom;
QT_WA({
WNDCLASS wc;
wc.style = style;
wc.lpfnWndProc = (WNDPROC)QtWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = (HINSTANCE)qWinAppInst();
wc.hIcon = 0;
wc.hCursor = 0;
wc.hbrBackground = 0;
wc.lpszMenuName = 0;
wc.lpszClassName = (TCHAR*)cname.utf16();
atom = RegisterClass(&wc);
} , {
WNDCLASSA wc;
wc.style = style;
wc.lpfnWndProc = (WNDPROC)QtWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = (HINSTANCE)qWinAppInst();
wc.hIcon = 0;
wc.hCursor = 0;
wc.hbrBackground = 0;
wc.lpszMenuName = 0;
QByteArray tempArray = cname.toLatin1();
wc.lpszClassName = tempArray;
atom = RegisterClassA(&wc);
});
QT_WA({
const TCHAR *className = (TCHAR*)cname.utf16();
m_dummy = CreateWindow(className, className, 0,
0, 0, 1, 1,
0, 0, qWinAppInst(), 0);
} , {
m_dummy = CreateWindowA(cname.toLatin1(), cname.toLatin1(), 0,
0, 0, 1, 1,
0, 0, qWinAppInst(), 0);
});
D3DPRESENT_PARAMETERS params;
initPresentParameters(¶ms);
params.hDeviceWindow = m_dummy;
HRESULT res = object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, 0,
D3DCREATE_PUREDEVICE|D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_NOWINDOWCHANGES|D3DCREATE_FPU_PRESERVE,
¶ms, &m_device);
if (FAILED(res) || m_device == 0)
qWarning("QDirect3DPaintEngine: failed to create Direct3D device (error=0x%x).", res);
}
void QD3DSurfaceManager::updateMaxSize()
{
int w = 0, h = 0;
QMap<QPaintDevice *, D3DSwapChain *>::const_iterator i = m_swapchains.constBegin();
while (i != m_swapchains.constEnd()) {
int nw = i.key()->width();
if (nw > w)
w = nw;
int nh = i.key()->height();
if (nh > h)
h = nh;
++i;
}
QSize newsize = QSize(w, h);
if (newsize != m_max_size) {
m_status |= MaxSizeChanged;
m_max_size = newsize;
}
}
void QD3DSurfaceManager::initPresentParameters(D3DPRESENT_PARAMETERS *params)
{
ZeroMemory(params, sizeof(D3DPRESENT_PARAMETERS));
params->Windowed = true;
params->SwapEffect = D3DSWAPEFFECT_COPY;
params->BackBufferFormat = D3DFMT_UNKNOWN;
params->PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
params->Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
}
QD3DSurfaceManager::D3DSwapChain *QD3DSurfaceManager::createSwapChain(QWidget *w)
{
D3DPRESENT_PARAMETERS params;
initPresentParameters(¶ms);
params.hDeviceWindow = w->winId();
D3DSwapChain *swapchain = new D3DSwapChain();
swapchain->size = w->size();
if (FAILED(m_device->CreateAdditionalSwapChain(¶ms, &swapchain->swapchain)))
qWarning("QDirect3DPaintEngine: CreateAdditionalSwapChain failed");
if (FAILED(swapchain->swapchain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &swapchain->surface)))
qWarning("QDirect3DPaintEngine: GetBackBuffer failed");
m_swapchains.insert(w, swapchain);
connect(w, SIGNAL(destroyed(QObject *)), SLOT(cleanupPaintDevice(QObject *)));
// init with background color
QColor bg = w->palette().color(QPalette::Background);
m_device->ColorFill(swapchain->surface, 0, D3DCOLOR_ARGB(bg.alpha(), bg.red(),bg.green(),bg.blue()));
return swapchain;
}
void QD3DSurfaceManager::cleanupPaintDevice(QObject *object)
{
QWidget *w = static_cast<QWidget *>(object);
releasePaintDevice(w);
}
int QD3DStateManager::m_mask_channels[4][4] =
{{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}};
QD3DDrawHelper::QD3DDrawHelper(QDirect3DPaintEnginePrivate *pe)
: m_pe(pe), m_d3dvbuff(0), m_maskSurface(0), m_depthStencilSurface(0),
m_locked(false), m_mask(0), m_startindex(0), m_index(0), m_vbuff(0), m_clearmask(true),
m_isLine(false), m_firstPoint(true)
{
resetMask();
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
memset(accesscontrol, 0, QT_VERTEX_BUF_SIZE * sizeof(VertexBufferAccess));
#endif
// create vertex buffer
afterReset();
}
QD3DDrawHelper::~QD3DDrawHelper()
{
if (m_maskSurface)
m_maskSurface->Release();
if (m_mask)
m_mask->Release();
if (m_depthStencilSurface)
m_depthStencilSurface->Release();
if (m_d3dvbuff)
m_d3dvbuff->Release();
}
inline void QD3DDrawHelper::lockVertexBuffer()
{
if (!m_locked) {
DWORD lockflags = D3DLOCK_NOOVERWRITE;
if (m_startindex >= QT_VERTEX_RESET_LIMIT) {
m_startindex = 0;
m_index = 0;
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
for (int i=0; i<QT_VERTEX_BUF_SIZE; ++i) {
if (accesscontrol[i] != (WRITE|READ) && accesscontrol[i] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
}
memset(accesscontrol, 0, QT_VERTEX_BUF_SIZE * sizeof(VertexBufferAccess));
#endif
lockflags = D3DLOCK_DISCARD;
}
if (FAILED(m_d3dvbuff->Lock(0, 0, (void**)&m_vbuff, lockflags))) {
qWarning() << "QDirect3DPaintEngine: unable to lock vertex buffer.";
}
m_locked = true;
}
}
inline void QD3DDrawHelper::unlockVertexBuffer()
{
if (m_locked) {
if (FAILED(m_d3dvbuff->Unlock())) {
qWarning() << "QDirect3DPaintEngine: unable to unlock vertex buffer.";
}
m_locked = false;
}
}
void QD3DDrawHelper::setClipPath(const QPainterPath &path, QD3DBatchItem **item)
{
lockVertexBuffer();
m_item = *item;
m_item->m_maskpos.x = m_item->m_maskpos.y = 0;
m_item->m_maskpos.channel = 3;
m_item->m_info |= QD3DBatchItem::BI_CLIP;
bool winding = (path.fillRule() == Qt::WindingFill);
if (winding)
m_item->m_info |= QD3DBatchItem::BI_WINDING;
if (!path.isEmpty()) {
m_item->m_info |= QD3DBatchItem::BI_MASK;
m_item->m_info &= ~QD3DBatchItem::BI_AA;
m_color = 0;
QRectF brect = pathToVertexArrays(path);
queueRect(brect, m_item, 0);
}
*item = m_item;
}
void QD3DDrawHelper::queueAntialiasedMask(const QPolygonF &poly, QD3DBatchItem **item, const QRectF &brect)
{
lockVertexBuffer();
m_item = *item;
m_item->m_info |= QD3DBatchItem::BI_MASK;
setWinding(m_item->m_info & QD3DBatchItem::BI_WINDING);
int xoffset = m_item->m_maskpos.x;
int yoffset = m_item->m_maskpos.y;
int x = brect.left();
int y = brect.top();
m_item->m_xoffset = (xoffset - x) + 1;
m_item->m_yoffset = (yoffset - y) + 1;
m_boundingRect = brect;
tessellate(poly);
*item = m_item;
}
QRectF QD3DDrawHelper::queueAliasedMask(const QPainterPath &path, QD3DBatchItem **item, D3DCOLOR color)
{
lockVertexBuffer();
m_color = color;
m_item = *item;
m_item->m_info |= QD3DBatchItem::BI_MASK;
bool winding = (path.fillRule() == Qt::WindingFill);
if (winding)
m_item->m_info |= QD3DBatchItem::BI_WINDING;
QRectF result = pathToVertexArrays(path);
*item = m_item;
return result;
}
// used for drawing aliased transformed rects directly
// don't use for antialiased or masked drawing
void QD3DDrawHelper::queueRect(const QRectF &rect, QD3DBatchItem *item, D3DCOLOR color, const QPolygonF &trect)
{
lockVertexBuffer();
qreal zval = (item->m_info & QD3DBatchItem::BI_CLIP) ? 0.0f : 0.5f;
item->m_info |= QD3DBatchItem::BI_BRECT;
// if the item does not have a mask, the offset is different
if (!(item->m_info & QD3DBatchItem::BI_MASK)) {
item->m_offset = m_index;
item->m_count = (item->m_info & QD3DBatchItem::BI_AA) ? 0 : -2;
}
qreal x1 = rect.left();
qreal y1 = rect.top();
qreal x2 = rect.right();
qreal y2 = rect.bottom();
QPointF tc = trect.at(0);
vertex v1 = { {x1, y1, zval} , color,
tc.x(), tc.y(), 0.f, 0.f,
0.f , 0.f , 0.f, 0.f };
tc = trect.at(1);
vertex v2 = { {x2, y1, zval} , color,
tc.x(), tc.y(), 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
tc = trect.at(2);
vertex v3 = { {x2, y2, zval} , color,
tc.x(), tc.y(), 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};;
tc = trect.at(3);
vertex v4 = { {x1, y2, zval} , color,
tc.x(), tc.y(), 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
for (int i=m_index; i<(m_index + 4); ++i) {
if ((m_index + 4) > QT_VERTEX_BUF_SIZE)
qDebug() << "Vertex Buffer: Buffer overflow";
if (accesscontrol[i] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[i] |= WRITE;
}
#endif
m_vbuff[m_index++] = v1;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v3;
m_vbuff[m_index++] = v4;
m_startindex = m_index;
}
QD3DMaskPosition QD3DDrawHelper::allocateMaskPosition(const QRectF &brect, bool *breakbatch)
{
int w = brect.width();
int h = brect.height();
w += 3;
h += 3;
if (w > m_width)
w = m_width;
if (h > m_height)
h = m_height;
*breakbatch = false;
if ((m_height - m_mask_offsetY2) >= h && (m_width - m_mask_position.x) >= w) {
m_mask_position.y = m_mask_offsetY2;
} else if ((m_width - m_mask_offsetX2) >= w) {
m_mask_position.y = QD3D_MASK_MARGIN;
m_mask_position.x = m_mask_offsetX2;
} else if (m_mask_position.channel < 3) {
++m_mask_position.channel;
m_mask_position.x = m_mask_position.y = QD3D_MASK_MARGIN;
m_mask_offsetX2 = m_mask_offsetY2 = QD3D_MASK_MARGIN;
} else {
resetMask();
*breakbatch = true;
}
int newoffset = m_mask_position.x + w;
if (m_mask_offsetX2 < newoffset)
m_mask_offsetX2 = newoffset;
m_mask_offsetY2 = (m_mask_position.y + h);
return m_mask_position;
}
void QD3DDrawHelper::queueRect(const QRectF &rect, QD3DBatchItem *item, D3DCOLOR color)
{
lockVertexBuffer();
QRectF brect;
item->m_info |= QD3DBatchItem::BI_BRECT;
qreal zval = (item->m_info & QD3DBatchItem::BI_CLIP) ? 0.0f : 0.5f;
if (item->m_info & QD3DBatchItem::BI_AA) {
int xoffset = item->m_maskpos.x;
int yoffset = item->m_maskpos.y;
int x = rect.left();
int y = rect.top();
brect = QRectF(x, y, rect.width() + 1, rect.height() + 1);
item->m_xoffset = (xoffset - x) + 1;
item->m_yoffset = (yoffset - y) + 1;
// if the item does not have a mask, the offset is different
if (!(item->m_info & QD3DBatchItem::BI_MASK)) {
item->m_offset = m_index;
item->m_count = 0;
}
} else {
brect = rect;
if (!(item->m_info & QD3DBatchItem::BI_MASK)) {
item->m_offset = m_index;
item->m_count = -2;
}
}
qreal left = brect.left();
qreal right = brect.right();
qreal top = brect.top();
qreal bottom = brect.bottom();
vertex v1 = { {left, bottom, zval}, color,
0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f};
vertex v2 = { {left, top, zval}, color,
0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f};
vertex v3 = { {right, top, zval}, color,
0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f};
vertex v4 = { {right, bottom, zval}, color,
0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f};
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
for (int i=m_index; i<(m_index + 4); ++i) {
if ((m_index + 4) > QT_VERTEX_BUF_SIZE)
qDebug() << "Vertex Buffer: Buffer overflow";
if (accesscontrol[i] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[i] |= WRITE;
}
#endif
m_vbuff[m_index++] = v1;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v3;
m_vbuff[m_index++] = v4;
m_startindex = m_index;
}
void QD3DDrawHelper::queueAntialiasedLines(const QPainterPath &path, QD3DBatchItem **item, const QRectF &brect)
{
lockVertexBuffer();
m_item = *item;
m_item->m_info |= QD3DBatchItem::BI_MASK;
setWinding(m_item->m_info & QD3DBatchItem::BI_WINDING);
int xoffset = m_item->m_maskpos.x;
int yoffset = m_item->m_maskpos.y;
int x = brect.left();
int y = brect.top();
m_item->m_xoffset = (xoffset - x) + 1;
m_item->m_yoffset = (yoffset - y) + 1;
m_boundingRect = brect;
m_xoffset = (x - xoffset) + 0.5f;
m_yoffset = (y - yoffset) + 0.5f;
QPointF last;
for (int i = 0; i < path.elementCount(); ++i) {
QPainterPath::Element element = path.elementAt(i);
//Q_ASSERT(!element.isCurveTo());
if (element.isLineTo())
QTessellator::tessellateRect(last, element, m_item->m_width);
last = element;
}
m_item->m_offset = m_startindex;
m_item->m_count = ( m_index - m_startindex ) / 3;
m_startindex = m_index;
*item = m_item;
}
void QD3DDrawHelper::queueAliasedLines(const QLineF *lines, int lineCount, QD3DBatchItem **item)
{
lockVertexBuffer();
m_item = *item;
m_item->m_info |= QD3DBatchItem::BI_FASTLINE;
for (int i=0; i<lineCount; ++i) {
const QLineF line = lines[i];
qreal p1x = line.p1().x();
qreal p1y = line.p1().y();
qreal p2x = line.p2().x();
qreal p2y = line.p2().y();
vertex v1 = { {p1x, p1y, m_pe->m_pen_width} , m_pe->m_pen_color,
-1.f, -1.f, p2x, p2y,
0.f, 0.f, 0.f, 0.f };
vertex v2 = { {p1x, p1y, m_pe->m_pen_width} , m_pe->m_pen_color,
1.f, -1.f, p2x, p2y,
0.f, 0.f, 0.f, 0.f };
vertex v3 = { {p1x, p1y, m_pe->m_pen_width} , m_pe->m_pen_color,
1.f, 1.f, p2x, p2y,
0.f, 0.f, 0.f, 0.f };
vertex v4 = { {p1x, p1y, m_pe->m_pen_width} , m_pe->m_pen_color,
-1.f, 1.f, p2x, p2y,
0.f, 0.f, 0.f, 0.f };
m_vbuff[m_index++] = v1;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v4;
m_vbuff[m_index++] = v4;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v3;
if (m_index >= (QT_VERTEX_BUF_SIZE - 16)) {
m_item->m_offset = m_startindex;
m_item->m_count = ( m_index - m_startindex ) / 2;
m_startindex = m_index;
QD3DBatchItem itemcopy = *m_item;
m_item = m_pe->nextBatchItem();
*m_item = itemcopy;
lockVertexBuffer();
}
}
m_item->m_offset = m_startindex;
m_item->m_count = ( m_index - m_startindex ) - 2;
m_startindex = m_index;
*item = m_item;
}
void QD3DDrawHelper::queueTextGlyph(const QRectF &rect, const qreal *tex_coords,
QD3DBatchItem *item, D3DCOLOR color)
{
lockVertexBuffer();
qreal x1 = rect.left();
qreal y1 = rect.top();
qreal x2 = rect.right();
qreal y2 = rect.bottom();
vertex v1 = { {x1, y1, 0.5f}, color,
tex_coords[0], tex_coords[1], 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
vertex v2 = { {x2, y1, 0.5f}, color,
tex_coords[2], tex_coords[1], 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
vertex v3 = { {x2, y2, 0.5f}, color,
tex_coords[2], tex_coords[3], 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
vertex v4 = { {x1, y1, 0.5f}, color,
tex_coords[0], tex_coords[1], 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
vertex v5 = { {x2, y2, 0.5f}, color,
tex_coords[2], tex_coords[3], 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
vertex v6 = { {x1, y2, 0.5f}, color,
tex_coords[0], tex_coords[3], 0.f, 0.f,
0.f , 0.f , 0.f, 0.f};
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
for (int i=m_index; i<(m_index + 6); ++i) {
if ((m_index + 6) > QT_VERTEX_BUF_SIZE)
qDebug() << "Vertex Buffer: Buffer overflow";
if (accesscontrol[i] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[i] |= WRITE;
}
#endif
m_vbuff[m_index++] = v1;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v3;
m_vbuff[m_index++] = v4;
m_vbuff[m_index++] = v5;
m_vbuff[m_index++] = v6;
m_startindex = m_index;
++item->m_count;
}
bool QD3DDrawHelper::needsFlushing() const
{
return (m_pe->m_batch.m_item_index >= QD3D_BATCH_SIZE || m_startindex >= QT_VERTEX_RESET_LIMIT);
}
void QD3DDrawHelper::setMaskSize(QSize size)
{
m_width = size.width();
m_height = size.height();
if (m_maskSurface)
m_maskSurface->Release();
if (m_mask)
m_mask->Release();
if (FAILED(m_pe->m_d3d_device->CreateTexture(m_width, m_height, 1, D3DUSAGE_RENDERTARGET,
D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_mask, NULL))) {
qWarning() << "QDirect3DPaintEngine: CreateTexture() failed.";
}
if (m_depthStencilSurface)
m_depthStencilSurface->Release();
if (FAILED(m_pe->m_d3d_device->CreateDepthStencilSurface(m_width, m_height, D3DFMT_D24S8, D3DMULTISAMPLE_NONE, 0,
TRUE, &m_depthStencilSurface, NULL))) {
qWarning() << "QDirect3DPaintEngine: CreateDepthStencilSurface() failed.";
}
m_pe->m_d3d_device->SetDepthStencilSurface(m_depthStencilSurface);
m_pe->m_d3d_device->Clear(0, 0, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 0, 0.0f, 0);
if (FAILED(m_mask->GetSurfaceLevel(0, &m_maskSurface))) {
qWarning() << "QDirect3DPaintEngine: GetSurfaceLevel() failed.";
}
m_pe->m_d3d_device->ColorFill(m_maskSurface, 0, D3DCOLOR_ARGB(0,0,0,0));
D3DXMATRIX projMatrix;
pD3DXMatrixOrthoOffCenterLH(&projMatrix, 0, m_width, m_height, 0, 0, 1);
m_pe->m_effect->SetMatrix("g_mMaskProjection", &projMatrix);
m_pe->m_effect->SetTexture("g_mAAMask", m_mask);
}
void QD3DDrawHelper::beforeReset()
{
resetMask();
m_clearmask = true;
if (m_maskSurface) {
m_maskSurface->Release();
m_maskSurface = 0;
}
if (m_mask) {
m_mask->Release();
m_mask = 0;
}
if (m_depthStencilSurface) {
m_depthStencilSurface->Release();
m_depthStencilSurface = 0;
}
if (m_d3dvbuff)
m_d3dvbuff->Release();
}
void QD3DDrawHelper::afterReset()
{
if (FAILED(m_pe->m_d3d_device->CreateVertexBuffer(QT_VERTEX_BUF_SIZE*sizeof(vertex), D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
QD3DFVF_CSVERTEX,
D3DPOOL_DEFAULT, &m_d3dvbuff, NULL))) {
qWarning() << "QDirect3DPaintEngine: failed to create vertex buffer.";
}
m_pe->m_d3d_device->SetStreamSource(0, m_d3dvbuff, 0, sizeof(vertex));
m_pe->m_d3d_device->SetFVF(QD3DFVF_CSVERTEX);
m_startindex = 0;
m_index = 0;
}
IDirect3DSurface9 *QD3DDrawHelper::freeMaskSurface()
{
// we need to make sure the mask is cleared when it's used for something else
resetMask();
m_clearmask = true;
return m_maskSurface;
}
int QD3DDrawHelper::drawAntialiasedMask(int offset, int maxoffset)
{
int newoffset = offset;
QD3DBatchItem *item = &(m_pe->m_batch.items[offset]);
// set mask as render target
if (FAILED(m_pe->m_d3d_device->SetRenderTarget(0, m_maskSurface)))
qWarning() << "QDirect3DPaintEngine: SetRenderTarget failed!";
if (m_clearmask) {
m_pe->m_d3d_device->Clear(0, 0, D3DCLEAR_TARGET,D3DCOLOR_ARGB(0,0,0,0), 0, 0);
m_clearmask = false;
}
// fill the mask
m_pe->m_statemanager->beginPass(PASS_AA_CREATEMASK);
for (; newoffset<maxoffset; ++newoffset) {
item = &(m_pe->m_batch.items[newoffset]);
if (!(item->m_info & QD3DBatchItem::BI_AA) || !(item->m_info & QD3DBatchItem::BI_MASK)) {
break;
} else if (item->m_info & QD3DBatchItem::BI_MASKFULL) {
item->m_info &= ~QD3DBatchItem::BI_MASKFULL;
m_clearmask = true;
break;
}
m_pe->m_statemanager->startStateBlock();
if (item->m_info & QD3DBatchItem::BI_MASKSCISSOR) {
RECT rect;
QRectF srect = item->m_brect.adjusted(item->m_xoffset, item->m_yoffset,
item->m_xoffset, item->m_yoffset);
rect.left = qMax(qRound(srect.left()), 0);
rect.top = qMax(qRound(srect.top()), 0);
rect.bottom = qMin(m_height, qRound(srect.bottom()));
rect.right = qMin(m_width, qRound(srect.right()));
m_pe->m_d3d_device->SetScissorRect(&rect);
m_pe->m_statemanager->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
}
m_pe->m_statemanager->setMaskChannel(item->m_maskpos.channel);
m_pe->m_statemanager->endStateBlock();
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
int vbstart = item->m_offset;
for (int i=vbstart; i<(vbstart + (item->m_count * 3)); ++i) {
if (accesscontrol[i] != WRITE)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[i] |= READ;
}
#endif
m_pe->m_d3d_device->DrawPrimitive(D3DPT_TRIANGLELIST, item->m_offset, item->m_count);
if (item->m_info & QD3DBatchItem::BI_MASKSCISSOR) {
m_pe->m_statemanager->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
}
}
m_pe->m_statemanager->endPass();
return newoffset;
}
void QD3DDrawHelper::drawAliasedMask(int offset)
{
QD3DBatchItem *item = &(m_pe->m_batch.items[offset]);
if (item->m_info & QD3DBatchItem::BI_MASK) {
m_pe->m_statemanager->beginPass( (item->m_info & QD3DBatchItem::BI_WINDING) ? PASS_STENCIL_WINDING : PASS_STENCIL_ODDEVEN );
int prev_stop = 0;
for (int i=0; i<item->m_pointstops.count(); ++i) {
int stop = item->m_pointstops.at(i);
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
int vbstart = (item->m_offset + prev_stop);
for (int j=vbstart; j<(vbstart+(stop - prev_stop)); ++j) {
if (accesscontrol[j] != WRITE)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[j] |= READ;
}
#endif
m_pe->m_d3d_device->DrawPrimitive(D3DPT_TRIANGLEFAN, item->m_offset + prev_stop, (stop - prev_stop) - 2);
prev_stop = stop;
}
m_pe->m_statemanager->endPass();
}
}
void QD3DDrawHelper::drawTextItem(QD3DBatchItem *item)
{
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
int vbstart = item->m_offset;
for (int j=vbstart; j<(vbstart + ((item->m_count * 2) * 3)); ++j) {
if (accesscontrol[j] != WRITE)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[j] |= READ;
}
#endif
m_pe->m_d3d_device->DrawPrimitive(D3DPT_TRIANGLELIST, item->m_offset, item->m_count*2);
}
void QD3DDrawHelper::drawAliasedLines(QD3DBatchItem *item)
{
m_pe->m_statemanager->setCosmeticPen(item->m_info & QD3DBatchItem::BI_COSMETICPEN);
if (item->m_info & QD3DBatchItem::BI_TRANSFORM) {
m_pe->m_statemanager->setTransformation(&item->m_matrix);
} else {
m_pe->m_statemanager->setTransformation();
}
int pass = (item->m_info & QD3DBatchItem::BI_MASK)
? PASS_ALIASED_LINES
: PASS_ALIASED_LINES_DIRECT;
m_pe->m_statemanager->beginPass(pass);
m_pe->m_d3d_device->DrawPrimitive(D3DPT_TRIANGLELIST, item->m_offset, (item->m_count + 2) / 3);
m_pe->m_statemanager->endPass();
}
void QD3DDrawHelper::drawAntialiasedBoundingRect(QD3DBatchItem *item)
{
if (item->m_info & QD3DBatchItem::BI_SCISSOR) {
RECT rect;
rect.left = qMax(qRound(item->m_brect.left()), 0);
rect.top = qMax(qRound(item->m_brect.top()), 0);
rect.bottom = qMin(m_height, qRound(item->m_brect.bottom()));
rect.right = qMin(m_width, qRound(item->m_brect.right()));
m_pe->m_d3d_device->SetScissorRect(&rect);
m_pe->m_statemanager->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
}
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
int vbstart = item->m_offset + (item->m_count * 3);
for (int j=vbstart; j<(vbstart + 4); ++j) {
if (accesscontrol[j] != WRITE)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[j] |= READ;
}
#endif
m_pe->m_d3d_device->DrawPrimitive(D3DPT_TRIANGLEFAN, item->m_offset + (item->m_count * 3), 2);
if (item->m_info & QD3DBatchItem::BI_SCISSOR) {
m_pe->m_statemanager->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
}
}
void QD3DDrawHelper::drawAliasedBoundingRect(QD3DBatchItem *item)
{
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
int vbstart = (item->m_offset + item->m_count + 2);
for (int j=vbstart; j<(vbstart + 4); ++j) {
if (accesscontrol[j] != WRITE)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[j] |= READ;
}
#endif
m_pe->m_d3d_device->DrawPrimitive(D3DPT_TRIANGLEFAN, item->m_offset + item->m_count + 2, 2);
}
void QD3DDrawHelper::addTrap(const Trapezoid &trap)
{
qreal topLeftY = Q27Dot5ToDouble(trap.topLeft->y) - m_yoffset;
qreal topLeftX = Q27Dot5ToDouble(trap.topLeft->x) - m_xoffset;
qreal topRightY = Q27Dot5ToDouble(trap.topRight->y) - m_yoffset;
qreal topRightX = Q27Dot5ToDouble(trap.topRight->x) - m_xoffset;
qreal top = Q27Dot5ToDouble(trap.top) - m_yoffset;
qreal bottom = Q27Dot5ToDouble(trap.bottom) - m_yoffset;
Q27Dot5 _h = trap.topLeft->y - trap.bottomLeft->y;
Q27Dot5 _w = trap.topLeft->x - trap.bottomLeft->x;
qreal _leftA = (qreal)_w/_h;
qreal _leftB = topLeftX - _leftA * topLeftY;
_h = trap.topRight->y - trap.bottomRight->y;
_w = trap.topRight->x - trap.bottomRight->x;
qreal _rightA = (qreal)_w/_h;
qreal _rightB = topRightX - _rightA * topRightY;
qreal invLeftA = qFuzzyCompare(_leftA + 1, 1) ? 0.0 : 1.0 / _leftA;
qreal invRightA = qFuzzyCompare(_rightA + 1, 1) ? 0.0 : 1.0 / _rightA;
vertex v1 = { {1.f, top - 1.f, 0.5f}, 0.f,
top, bottom, invLeftA, -invRightA,
_leftA, _leftB, _rightA, _rightB};
vertex v2 = { {0.f, top - 1.f, 0.5f}, 0.f,
top, bottom, invLeftA, -invRightA,
_leftA, _leftB, _rightA, _rightB};
vertex v3 = { {0.f, bottom + 1.f, 0.5f}, 0.f,
top, bottom, invLeftA, -invRightA,
_leftA, _leftB, _rightA, _rightB};
vertex v4 = { {1.f, top - 1.f, 0.5f}, 0.f,
top, bottom, invLeftA, -invRightA,
_leftA, _leftB, _rightA, _rightB};
vertex v5 = { {0.f, bottom + 1.f, 0.5f}, 0.f,
top, bottom, invLeftA, -invRightA,
_leftA, _leftB, _rightA, _rightB};
vertex v6 = { {1.f, bottom + 1.f, 0.5f}, 0.f,
top, bottom, invLeftA, -invRightA,
_leftA, _leftB, _rightA, _rightB};
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
for (int i=m_index; i<(m_index + 6); ++i) {
if ((m_index + 6) > QT_VERTEX_BUF_SIZE)
qDebug() << "Vertex Buffer: Buffer overflow";
if (accesscontrol[i] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[i] |= WRITE;
}
#endif
m_vbuff[m_index++] = v1;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v3;
m_vbuff[m_index++] = v4;
m_vbuff[m_index++] = v5;
m_vbuff[m_index++] = v6;
// check if buffer is full
if (m_index >= (QT_VERTEX_BUF_SIZE - 16)) {
m_item->m_offset = m_startindex;
m_item->m_count = ( m_index - m_startindex ) / 3;
m_startindex = m_index;
QD3DBatchItem itemcopy = *m_item;
m_item = m_pe->nextBatchItem();
*m_item = itemcopy;
m_item->m_info &= ~QD3DBatchItem::BI_MASKFULL;
lockVertexBuffer();
}
}
void QD3DDrawHelper::tessellate(const QPolygonF &poly) {
int xoffset = m_item->m_maskpos.x;
int yoffset = m_item->m_maskpos.y;
int x = m_boundingRect.left();
int y = m_boundingRect.top();
m_xoffset = (x - xoffset) + 0.5f;
m_yoffset = (y - yoffset) + 0.5f;
QTessellator::tessellate(poly.data(), poly.count());
m_item->m_offset = m_startindex;
m_item->m_count = ( m_index - m_startindex ) / 3;
m_startindex = m_index;
}
inline void QD3DDrawHelper::lineToStencil(qreal x, qreal y)
{
QPointF lastPt = tess_lastpoint;
tess_lastpoint = QPointF(x, y);
if (m_isLine && m_firstPoint)
return;
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
if (m_index > QT_VERTEX_BUF_SIZE)
qDebug() << "Vertex Buffer: Buffer overflow";
if (accesscontrol[m_index] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[m_index] |= WRITE;
#endif
vertex v;
if (m_isLine) {
vertex v1 = { {lastPt.x(), lastPt.y(), m_pe->m_pen_width }, m_color,
-1.f, -1.f, x, y,
0.f, 0.f, 0.f, 0.f};
vertex v2 = { {lastPt.x(), lastPt.y(), m_pe->m_pen_width }, m_color,
1.f, -1.f, x, y,
0.f, 0.f, 0.f, 0.f};
vertex v3 = { {lastPt.x(), lastPt.y(), m_pe->m_pen_width }, m_color,
1.f, 1.f, x, y,
0.f, 0.f, 0.f, 0.f};
vertex v4 = { {lastPt.x(), lastPt.y(), m_pe->m_pen_width }, m_color,
-1.f, 1.f, x, y,
0.f, 0.f, 0.f, 0.f};
m_vbuff[m_index++] = v1;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v4;
m_vbuff[m_index++] = v4;
m_vbuff[m_index++] = v2;
m_vbuff[m_index++] = v3;
} else {
vertex v1 = { {x, y, 0.5f}, m_color,
0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f};
m_vbuff[m_index++] = v1;
v = v1;
}
++tess_index;
// check if buffer is full
if (m_index >= (QT_VERTEX_BUF_SIZE - 16)) {
int firstindex = m_startindex;
if (!m_item->m_pointstops.isEmpty())
firstindex = m_item->m_pointstops.last();
vertex first = m_vbuff[firstindex];
// finish current polygon
m_item->m_pointstops.append(tess_index);
m_item->m_offset = m_startindex;
m_startindex = m_index;
// copy item
QD3DBatchItem itemcopy = *m_item;
m_item = m_pe->nextBatchItem();
*m_item = itemcopy;
// start new polygon
lockVertexBuffer();
m_item->m_pointstops.clear();
if (!m_isLine) {
tess_index = 2;
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
if (accesscontrol[m_index] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[m_index] |= WRITE;
#endif
m_vbuff[m_index++] = first;
#ifdef QT_DEBUG_VERTEXBUFFER_ACCESS
if (accesscontrol[m_index] != CLEAR)
qDebug() << "Vertex Buffer: Access Error";
accesscontrol[m_index] |= WRITE;
#endif
m_vbuff[m_index++] = v;
} else {
tess_index = 0;
}
}
if (x > max_x)
max_x = x;
else if (x < min_x)
min_x = x;
if (y > max_y)
max_y = y;
else if (y < min_y)
min_y = y;
}
inline void QD3DDrawHelper::curveToStencil(const QPointF &cp1, const QPointF &cp2,
const QPointF &ep)
{
qreal inverseScale = 0.5f;
qreal inverseScaleHalf = inverseScale / 2;
QBezier beziers[32];
beziers[0] = QBezier::fromPoints(tess_lastpoint, cp1, cp2, ep);
QBezier *b = beziers;
while (b >= beziers) {
// check if we can pop the top bezier curve from the stack
qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
qreal d;
if (l > inverseScale) {
d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2) - (b->y4 - b->y1)*(b->x1 - b->x2) )
+ qAbs( (b->x4 - b->x1)*(b->y1 - b->y3) - (b->y4 - b->y1)*(b->x1 - b->x3) );
d /= l;
} else {
d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
}
if (d < inverseScaleHalf || b == beziers + 31) {
// good enough, we pop it off and add the endpoint
lineToStencil(b->x4, b->y4);
--b;
} else {
// split, second half of the polygon goes lower into the stack
b->split(b+1, b);
++b;
}
}
}
QRectF QD3DDrawHelper::pathToVertexArrays(const QPainterPath &path)
{
m_isLine = (m_item->m_info & QD3DBatchItem::BI_FASTLINE);
const QPainterPath::Element &first = path.elementAt(0);
firstx = first.x;
firsty = first.y;
min_x = max_x = firstx;
min_y = max_y = firsty;
m_firstPoint = true;
tess_index = 0;
m_item->m_pointstops.clear();
lineToStencil(firstx, firsty);
m_firstPoint = false;
for (int i=1; i<path.elementCount(); ++i) {
const QPainterPath::Element &e = path.elementAt(i);
switch (e.type) {
case QPainterPath::MoveToElement:
m_item->m_pointstops.append(tess_index);
m_firstPoint = true;
lineToStencil(e.x, e.y);
m_firstPoint = false;
break;
case QPainterPath::LineToElement:
lineToStencil(e.x, e.y);
break;
case QPainterPath::CurveToElement:
curveToStencil(e, path.elementAt(i+1), path.elementAt(i+2));
i+=2;
break;
default:
break;
}
}
if (!m_isLine)
lineToStencil(firstx, firsty);
m_item->m_pointstops.append(tess_index);
m_item->m_offset = m_startindex;
m_item->m_count = ( m_index - m_startindex ) - 2;
m_startindex = m_index;
QRectF result;
result.setLeft(min_x);
result.setRight(max_x);
result.setTop(min_y);
result.setBottom(max_y);
if (m_isLine)
result.adjust(0,0,1,1);
return result;
}
void QD3DDrawHelper::resetMask()
{
m_mask_position.x = m_mask_position.y = QD3D_MASK_MARGIN;
m_mask_position.channel = 0;
m_mask_offsetX2 = m_mask_offsetY2 = QD3D_MASK_MARGIN;
}
static inline QPainterPath strokeForPath(const QPainterPath &path, const QPen &cpen) {
QPainterPathStroker stroker;
if (cpen.style() == Qt::CustomDashLine)
stroker.setDashPattern(cpen.dashPattern());
else
stroker.setDashPattern(cpen.style());
stroker.setCapStyle(cpen.capStyle());
stroker.setJoinStyle(cpen.joinStyle());
stroker.setMiterLimit(cpen.miterLimit());
stroker.setWidth(cpen.widthF());
QPainterPath stroke = stroker.createStroke(path);
stroke.setFillRule(Qt::WindingFill);
return stroke;
}
QDirect3DPaintEnginePrivate::~QDirect3DPaintEnginePrivate()
{
}
void QDirect3DPaintEnginePrivate::updateClipPath(const QPainterPath &path, Qt::ClipOperation op)
{
//#### remove me
QRegion r(path.toFillPolygon().toPolygon(), path.fillRule());
updateClipRegion(r, op);
/* if (m_draw_helper->needsFlushing())
flushBatch();
if (op == Qt::IntersectClip && !has_clipping)
op = Qt::ReplaceClip;
// switch to paths
if (!m_has_complex_clipping) {
m_clip_path = QPainterPath();
m_clip_path.addRegion(m_clip_region);
m_clip_region = QRegion();
m_sysclip_path = QPainterPath();
m_sysclip_path.addRegion(m_sysclip_region);
m_sysclip_region = QRegion();
m_has_complex_clipping = true;
}
QPainterPath cpath = m_matrix.map(path);
QD3DBatchItem *item = &m_batch.items[m_batch.m_item_index++];
item->m_info = QD3DBatchItem::BI_COMPLEXCLIP;
switch (op) {
case Qt::UniteClip:
has_clipping = true;
m_clip_path = m_clip_path.united(cpath);
break;
case Qt::ReplaceClip:
has_clipping = true;
m_clip_path = cpath;
break;
case Qt::NoClip:
m_has_complex_clipping = false;
has_clipping = false;
item->m_info |= QD3DBatchItem::BI_CLEARCLIP;
break;
default: // intersect clip
has_clipping = true;
m_clip_path = m_clip_path.intersected(cpath);
break;
}
if (!m_sysclip_path.isEmpty()) {
item->m_info &= ~QD3DBatchItem::BI_CLEARCLIP;
if (has_clipping)
m_clip_path = m_clip_path.intersected(m_sysclip_path);
else
m_clip_path = m_sysclip_path;
}
// update the aliased clipping mask
m_draw_helper->setClipPath(m_clip_path, item);
// update the antialiased clipping mask
if (m_draw_helper->needsFlushing())
flushBatch();
QD3DBatchItem *aaitem = &m_batch.items[m_batch.m_item_index++];
aaitem->m_info = item->m_info|QD3DBatchItem::BI_AA;
m_draw_helper->setClipPath(m_clip_path, aaitem); */
}
extern QPainterPath qt_regionToPath(const QRegion ®ion);
void QDirect3DPaintEnginePrivate::updateClipRegion(const QRegion &clipregion, Qt::ClipOperation op)
{
if (m_draw_helper->needsFlushing())
flushBatch();
if (m_has_complex_clipping) {
QPainterPath path = qt_regionToPath(clipregion);
updateClipPath(path, op);
return;
}
if (op == Qt::IntersectClip && m_clip_region.isEmpty())
op = Qt::ReplaceClip;
QRegion cregion = m_matrix.map(clipregion);
QD3DBatchItem *item = nextBatchItem();
item->m_info &= ~QD3DBatchItem::BI_AA;
switch (op) {
case Qt::UniteClip:
m_clip_region = m_clip_region.united(cregion);
break;
case Qt::ReplaceClip:
m_clip_region = cregion;
break;
case Qt::NoClip:
m_clip_region = QRegion();
item->m_info |= QD3DBatchItem::BI_CLEARCLIP;
break;
default: // intersect clip
m_clip_region = m_clip_region.intersected(cregion);
break;
}
QRegion crgn = m_clip_region;
if (!m_sysclip_region.isEmpty()) {
item->m_info &= ~QD3DBatchItem::BI_CLEARCLIP;
if (!crgn.isEmpty())
crgn = crgn.intersected(m_sysclip_region);
else
crgn = m_sysclip_region;
}
QPainterPath path = qt_regionToPath(crgn);
m_draw_helper->setClipPath(path, &item);
}
void QDirect3DPaintEnginePrivate::updateFont(const QFont &)
{
}
void QDirect3DPaintEnginePrivate::setRenderTechnique(RenderTechnique technique)
{
if (m_current_technique != technique) {
if (m_current_technique != RT_NoTechnique)
m_effect->End();
if (technique == RT_Aliased) {
m_effect->SetTechnique("Aliased");
m_effect->Begin(0,D3DXFX_DONOTSAVESTATE);
} else if (technique == RT_Antialiased) {
m_effect->SetTechnique("Antialiased");
m_effect->Begin(0,D3DXFX_DONOTSAVESTATE);
}
}
m_current_technique = technique;
}
/*QPolygonF QDirect3DPaintEnginePrivate::transformedRect(const QRectF &brect) const
{
QPolygonF poly(brect);
return m_matrix.map(poly);
}
QPolygonF QDirect3DPaintEnginePrivate::calcTextureCoords(const QPolygonF &trect) const
{
QPolygonF result(4);
QRectF brect = trect.boundingRect();
qreal angle = atan(trect.at(0).x() -
}
QPolygonF QDirect3DPaintEnginePrivate::offsetTextureCoords(const QRectF &brect, const QPolygonF &trect) const
{
}*/
inline QD3DBatchItem *QDirect3DPaintEnginePrivate::nextBatchItem()
{
if (m_draw_helper->needsFlushing())
flushBatch();
QD3DBatchItem *item = &m_batch.items[m_batch.m_item_index++];
item->m_info = m_current_state;
item->m_cmode = m_cmode;
return item;
}
qreal calculateAngle(qreal dx, qreal dy)
{
qreal angle;
if (qFuzzyCompare(dx + 1, 1)) {
angle = (dy < 0) ? -M_PI/2 : M_PI/2;
} else {
angle = atanf(dy/dx);
if (dx < 0)
angle += M_PI;
}
return angle;
}
QPolygonF QDirect3DPaintEnginePrivate::brushCoordinates(const QRectF &r, bool stroke, qreal *fd) const
{
QBrush brush;
QTransform matrix;
Qt::BrushStyle style;
if (stroke) {
brush = m_pen.brush();
matrix = m_inv_pen_matrix;
style = m_pen_brush_style;
} else {
brush = m_brush;
matrix = m_inv_brush_matrix;
style = m_brush_style;
}
QPolygonF bpoly;
switch(style) {
case Qt::TexturePattern: {
QTransform totxcoords;
QRectF adj_brect = r.adjusted(-0.5f, -0.5f, -0.5f, -0.5f);
totxcoords.scale(1.0f/brush.texture().width(),
1.0f/brush.texture().height());
bpoly = matrix.map(QPolygonF(adj_brect));
bpoly = totxcoords.map(bpoly);
break; }
case Qt::LinearGradientPattern: {
const QLinearGradient *g = static_cast<const QLinearGradient *>(brush.gradient());
QPointF start = g->start();
QPointF stop = g->finalStop();
qreal dx = stop.x() - start.x();
qreal dy = stop.y() - start.y();
qreal length = sqrt(dx * dx + dy * dy);
qreal angle = calculateAngle(dx, dy);
QTransform totxcoords;
QRectF adj_brect = r.adjusted(-0.5f, -0.5f, -0.5f, -0.5f);
totxcoords.scale(1.0f/length, 1.0f/length);
totxcoords.rotateRadians(-angle);
totxcoords.translate(-start.x(), -start.y());
bpoly = matrix.map(QPolygonF(adj_brect));
bpoly = totxcoords.map(bpoly);
break; }
case Qt::ConicalGradientPattern: {
const QConicalGradient *g = static_cast<const QConicalGradient *>(brush.gradient());
QPointF center = g->center();
qreal angle = g->angle();
QTransform totxcoords;
totxcoords.rotate(angle);
totxcoords.translate(-center.x(), -center.y());
bpoly = matrix.map(QPolygonF(r));
bpoly = totxcoords.map(bpoly);
break; }
case Qt::RadialGradientPattern: {
const QRadialGradient *g = static_cast<const QRadialGradient *>(brush.gradient());
QPointF center = g->center();
QPointF focalpoint = g->focalPoint();
qreal dx = focalpoint.x() - center.x();
qreal dy = focalpoint.y() - center.y();
qreal radius = g->radius();
*fd = sqrt(dx * dx + dy * dy) / radius;
qreal angle = calculateAngle(dx, dy);
QTransform totxcoords;
totxcoords.scale(1.0f/radius, 1.0f/radius);
totxcoords.rotateRadians(-angle);
totxcoords.translate(-center.x(), -center.y());
bpoly = matrix.map(QPolygonF(r));
bpoly = totxcoords.map(bpoly);
break; }
default: {
QTransform totxcoords;
QRectF adj_brect = r.adjusted(-0.5f, -0.5f, -0.5f, -0.5f);
QPixmap pat = getPattern(style);
totxcoords.scale(1.0f/pat.width(),
1.0f/pat.height());
bpoly = matrix.map(QPolygonF(adj_brect));
bpoly = totxcoords.map(bpoly); }
};
return bpoly;
}
void QDirect3DPaintEnginePrivate::strokeAliasedPath(QPainterPath path, const QRectF &brect, const QTransform &txform)
{
D3DCOLOR solid_color;
QD3DBatchItem *item = nextBatchItem();
if (!txform.isIdentity())
path = txform.map(path);
QRectF trect;
QPolygonF txcoord;
solid_color = m_pen_color;
bool has_complex_brush = false;
if (m_pen_brush_style != Qt::SolidPattern) {
has_complex_brush = true;
item->m_brush = m_pen.brush();
item->m_info |= QD3DBatchItem::BI_COMPLEXBRUSH;
item->m_opacity = m_opacity;
}
if (m_has_fast_pen) {
item->m_info |= QD3DBatchItem::BI_FASTLINE;
if (m_pen_brush_style == Qt::SolidPattern) {
m_draw_helper->queueAliasedMask(path, &item, solid_color);
item->m_info &= ~QD3DBatchItem::BI_MASK; // bypass stencil buffer
return;
}
}
QRectF txrect = m_draw_helper->queueAliasedMask(path, &item, 0);
if (has_complex_brush) {
trect = brect;
txcoord = brushCoordinates(brect, true, &item->m_distance);
item->m_info |= QD3DBatchItem::BI_TRANSFORM;
item->m_matrix = m_matrix;
} else {
trect = txrect;
static const QPolygonF empty_poly(4);
txcoord = empty_poly;
}
m_draw_helper->queueRect(trect, item, solid_color, txcoord);
}
void QDirect3DPaintEnginePrivate::fillAliasedPath(QPainterPath path, const QRectF &brect, const QTransform &txform)
{
D3DCOLOR solid_color;
QD3DBatchItem *item = nextBatchItem();
if (!txform.isIdentity())
path = txform.map(path);
QRectF trect;
QPolygonF txcoord;
solid_color = m_brush_color;
bool has_complex_brush = false;
if (m_brush_style != Qt::SolidPattern) {
has_complex_brush = true;
item->m_brush = m_brush;
item->m_info |= QD3DBatchItem::BI_COMPLEXBRUSH;
item->m_opacity = m_opacity;
}
QRectF txrect = m_draw_helper->queueAliasedMask(path, &item, 0);
if (has_complex_brush) {
trect = brect;
txcoord = brushCoordinates(brect, false, &item->m_distance);
item->m_info |= QD3DBatchItem::BI_TRANSFORM;
item->m_matrix = m_matrix;
} else {
trect = txrect;
static const QPolygonF empty_poly(4);
txcoord = empty_poly;
}
m_draw_helper->queueRect(trect, item, solid_color, txcoord);
}
void QDirect3DPaintEnginePrivate::fillAntialiasedPath(const QPainterPath &path, const QRectF &brect,
const QTransform &txform, bool stroke)
{
D3DCOLOR solid_color;
bool winding = (path.fillRule() == Qt::WindingFill);
QPolygonF poly;
QRectF txrect;
QPainterPath tpath;
if (m_has_aa_fast_pen && stroke) {
tpath = txform.map(path);
txrect = tpath.controlPointRect();
txrect.adjust(-(m_pen_width/2),-(m_pen_width/2), m_pen_width, m_pen_width);
} else {
poly = path.toFillPolygon(txform);
txrect = poly.boundingRect();
}
// brect = approx. bounding rect before transformation
// txrect = exact bounding rect after transformation
// trect = the rectangle to be drawn
// txcoord = the texture coordinates
// adj_txrect = adjusted rect to include aliased outline
bool use_scissor = false;
if (txrect.left() < 0) {
txrect.adjust(-txrect.left(),0,0,0);
use_scissor = true;
}
if (txrect.top() < 0) {
txrect.adjust(0,-txrect.top(),0,0);
use_scissor = true;
}
if (!txrect.isValid())
return;
QD3DBatchItem *item = nextBatchItem();
QRectF adj_txrect = txrect.adjusted(-1,-1,1,1);
QRectF trect;
QPolygonF txcoord;
bool has_complex_brush = false;
if (stroke) {
solid_color = m_pen_color;
if (m_pen_brush_style != Qt::SolidPattern) {
has_complex_brush = true;
item->m_brush = m_pen.brush();
}
item->m_width = m_pen_width;
} else {
solid_color = m_brush_color;
if (m_brush_style != Qt::SolidPattern) {
has_complex_brush = true;
item->m_brush = m_brush;
}
}
qreal focaldist = 0;
if (has_complex_brush) {
trect = brect;
txcoord = brushCoordinates(brect, stroke, &focaldist);
} else {
trect = adj_txrect;
static const QPolygonF empty_poly(4);
txcoord = empty_poly;
}
bool maskfull;
item->m_maskpos = m_draw_helper->allocateMaskPosition(txrect, &maskfull);
if (maskfull)
item->m_info |= QD3DBatchItem::BI_MASKFULL;
item->m_distance = focaldist;
if (winding)
item->m_info |= QD3DBatchItem::BI_WINDING;
if (has_complex_brush) {
item->m_info |= QD3DBatchItem::BI_SCISSOR|QD3DBatchItem::BI_COMPLEXBRUSH|
QD3DBatchItem::BI_TRANSFORM;
item->m_brect = adj_txrect;
item->m_matrix = m_matrix;
item->m_opacity = m_opacity;
}
if (use_scissor) {
item->m_info |= QD3DBatchItem::BI_MASKSCISSOR;
item->m_brect = adj_txrect;
}
if (m_has_aa_fast_pen && stroke) {
m_draw_helper->queueAntialiasedLines(tpath, &item, txrect);
} else {
m_draw_helper->queueAntialiasedMask(poly, &item, txrect);
}
m_draw_helper->queueRect(trect, item, solid_color, txcoord);
}
QPainterPath QDirect3DPaintEnginePrivate::strokePathFastPen(const QPainterPath &path)
{
QPainterPath result;
QBezier beziers[32];
for (int i=0; i<path.elementCount(); ++i) {
const QPainterPath::Element &e = path.elementAt(i);
switch (e.type) {
case QPainterPath::MoveToElement:
result.moveTo(e.x, e.y);
break;
case QPainterPath::LineToElement:
result.lineTo(e.x, e.y);
break;
case QPainterPath::CurveToElement:
{
QPointF sp = path.elementAt(i-1);
QPointF cp2 = path.elementAt(i+1);
QPointF ep = path.elementAt(i+2);
i+=2;
qreal inverseScaleHalf = m_inv_scale / 2;
beziers[0] = QBezier::fromPoints(sp, e, cp2, ep);
QBezier *b = beziers;
while (b >= beziers) {
// check if we can pop the top bezier curve from the stack
qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
qreal d;
if (l > m_inv_scale) {
d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2)
- (b->y4 - b->y1)*(b->x1 - b->x2) )
+ qAbs( (b->x4 - b->x1)*(b->y1 - b->y3)
- (b->y4 - b->y1)*(b->x1 - b->x3) );
d /= l;
} else {
d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
}
if (d < inverseScaleHalf || b == beziers + 31) {
// good enough, we pop it off and add the endpoint
result.lineTo(b->x4, b->y4);
--b;
} else {
// split, second half of the polygon goes lower into the stack
b->split(b+1, b);
++b;
}
}
} // case CurveToElement
default:
break;
} // end of switch
}
return result;
}
void QDirect3DPaintEnginePrivate::strokePath(const QPainterPath &path, QRectF brect, bool simple)
{
QTransform txform;
QPainterPath tpath;
if (m_has_fast_pen || m_has_aa_fast_pen) {
if (!simple)
tpath = strokePathFastPen(path);
else
tpath = path; //already only lines
} else {
tpath = strokeForPath(path, m_pen);
}
if (tpath.isEmpty())
return;
//brect is null if the path is not transformed
if (brect.isNull())
txform = m_matrix;
if (!brect.isNull()) {
// brect is set when the path is transformed already,
// this is the case when we have a cosmetic pen.
brect.adjust(-(m_pen_width/2),-(m_pen_width/2), m_pen_width, m_pen_width);
}
if (brect.isNull())
brect = tpath.controlPointRect();
brect.adjust(-m_inv_scale,-m_inv_scale,m_inv_scale,m_inv_scale); //adjust for antialiasing
if (m_current_state & QD3DBatchItem::BI_AA) {
fillAntialiasedPath(tpath, brect, txform, true);
} else {
strokeAliasedPath(tpath, brect, txform);
}
}
void QDirect3DPaintEnginePrivate::fillPath(const QPainterPath &path, QRectF brect)
{
QTransform txform;
//brect is null if the path is not transformed
if (brect.isNull())
txform = m_matrix;
if (brect.isNull())
brect = path.controlPointRect();
brect.adjust(-m_inv_scale,-m_inv_scale,m_inv_scale,m_inv_scale); //adjust for antialiasing
if (m_current_state & QD3DBatchItem::BI_AA) {
fillAntialiasedPath(path, brect, txform, false);
} else {
fillAliasedPath(path, brect, txform);
}
}
bool QDirect3DPaintEnginePrivate::init()
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEnginePrivate::init()";
#endif
m_draw_helper = 0;
m_gradient_cache = 0;
m_dc = 0;
m_dcsurface = 0;
m_supports_d3d = false;
m_current_state = 0;
m_in_scene = false;
m_has_fast_pen = false;
m_has_aa_fast_pen = false;
m_has_pen = false;
m_has_brush = false;
m_pen_color = 0;
m_brush_color = 0;
m_current_surface = 0;
m_batch.m_item_index = 0;
m_current_technique = RT_NoTechnique;
if (!pDirect3DCreate9) {
QLibrary d3d_lib(QLatin1String("d3d9.dll"));
pDirect3DCreate9 = (PFNDIRECT3DCREATE9) d3d_lib.resolve("Direct3DCreate9");
if (!pDirect3DCreate9) {
qWarning("QDirect3DPaintEngine: failed to resolve symbols from d3d9.dll.\n"
"Make sure you have the DirectX run-time installed.");
return false;
}
}
if (!pD3DXCreateBuffer || !pD3DXCreateEffect || !pD3DXMatrixOrthoOffCenterLH) {
QLibrary d3dx_lib(QLatin1String("d3dx9_32.dll"));
pD3DXCreateBuffer = (PFND3DXCREATEBUFFER) d3dx_lib.resolve("D3DXCreateBuffer");
pD3DXCreateEffect = (PFND3DXCREATEEFFECT) d3dx_lib.resolve("D3DXCreateEffect");
pD3DXMatrixOrthoOffCenterLH = (PFND3DXMATRIXORTHOOFFCENTERLH)
d3dx_lib.resolve("D3DXMatrixOrthoOffCenterLH");
if (!(pD3DXCreateBuffer && pD3DXCreateEffect && pD3DXMatrixOrthoOffCenterLH)) {
qWarning("QDirect3DPaintEngine: failed to resolve symbols from d3dx9_32.dll.\n"
"Make sure you have the DirectX run-time installed.");
return false;
}
}
if (!m_d3d_object) {
m_d3d_object = pDirect3DCreate9(D3D_SDK_VERSION);
if (!m_d3d_object) {
qWarning("QDirect3DPaintEngine: failed to create Direct3D object.\n"
"Direct3D support in Qt will be disabled.");
return false;
}
}
m_supports_d3d = testCaps();
if (!m_supports_d3d)
return false;
m_surface_manager.init(m_d3d_object);
m_d3d_device = m_surface_manager.device();
if (!m_d3d_device)
return false;
/* load shaders */
QFile file(QLatin1String(":/qpaintengine_d3d.fx"));
QByteArray fxFile;
if (file.open(QFile::ReadOnly))
fxFile = file.readAll();
if (fxFile.size() > 0) {
LPD3DXBUFFER compout;
pD3DXCreateBuffer(4096, &compout);
DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE|D3DXFX_DONOTSAVESTATE|D3DXSHADER_OPTIMIZATION_LEVEL3;
if(FAILED(pD3DXCreateEffect(m_d3d_device, fxFile.constData(), fxFile.size(),
NULL, NULL, dwShaderFlags, NULL, &m_effect, &compout))) {
qWarning("QDirect3DPaintEngine: failed to compile effect file");
if (compout)
qWarning((char *)compout->GetBufferPointer());
m_supports_d3d = false;
return false;
}
if (m_effect) {
m_statemanager = new QD3DStateManager(m_d3d_device, m_effect);
m_effect->SetStateManager(m_statemanager);
m_draw_helper = new QD3DDrawHelper(this);
initDevice();
m_gradient_cache = new QD3DGradientCache(m_d3d_device);
}
} else {
return false;
}
return true;
}
QPixmap QDirect3DPaintEnginePrivate::getPattern(Qt::BrushStyle style) const
{
if (!m_patterns.contains(style)) {
QImage img(16,16,QImage::Format_ARGB32);
img.fill(0);
QPainter p(&img);
p.setBrush(QBrush(Qt::white, style));
p.setPen(Qt::NoPen);
p.drawRect(0,0,16,16);
p.end();
QPixmap pattern(QPixmap::fromImage(img));
QDirect3DPaintEnginePrivate *ct = const_cast<QDirect3DPaintEnginePrivate *>(this);
ct->verifyTexture(pattern);
ct->m_patterns.insert(style, pattern);
}
return m_patterns.value(style);
}
bool QDirect3DPaintEnginePrivate::testCaps()
{
D3DCAPS9 caps;
if (FAILED(m_d3d_object->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps)))
return false;
if ((caps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
&& (caps.DevCaps & D3DDEVCAPS_PUREDEVICE)
&& (caps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST)
&& (caps.StencilCaps & D3DSTENCILCAPS_TWOSIDED))
return true;
#if 0
qDebug() << "Direct3D caps:";
qDebug() << "D3DPRESENT_INTERVAL_IMMEDIATE:" << ((caps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE) != 0);
qDebug() << "D3DDEVCAPS_PUREDEVICE:" << ((caps.DevCaps & D3DDEVCAPS_PUREDEVICE) != 0);
qDebug() << "D3DPRASTERCAPS_SCISSORTEST:" << ((caps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST) != 0);
qDebug() << "D3DSTENCILCAPS_TWOSIDED:" << ((caps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) != 0);
#endif
return false;
}
void QDirect3DPaintEnginePrivate::initDevice()
{
m_statemanager->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
m_statemanager->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
m_statemanager->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
m_statemanager->SetRenderState(D3DRS_LIGHTING, FALSE);
m_statemanager->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_statemanager->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_statemanager->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_DESTALPHA);
}
void QDirect3DPaintEnginePrivate::updatePen(const QPen &pen)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::updatePen";
#endif
m_pen = pen;
m_has_cosmetic_pen = false;
m_has_pen = (m_pen.style() != Qt::NoPen);
if (m_has_pen) {
m_pen_brush_style = m_pen.brush().style();
if (m_pen_brush_style >= Qt::SolidPattern && m_pen_brush_style <= Qt::DiagCrossPattern) {
int a, r, g, b;
m_pen.color().getRgb(&r, &g, &b, &a);
m_pen_color = D3DCOLOR_ARGB((int)(a * m_opacity),r,g,b);
} else {
m_pen_color = m_opacity_color;
}
m_has_cosmetic_pen = m_pen.isCosmetic();
if (m_pen_brush_style != Qt::NoBrush &&
m_pen_brush_style != Qt::SolidPattern) {
bool ok;
m_inv_pen_matrix = m_pen.brush().transform().inverted(&ok);
if (!ok)
qWarning() << "QDirect3DPaintEngine: No inverse matix for pen brush matrix.";
}
m_pen_width = m_pen.widthF();
if (m_pen_width == 0.0f)
m_pen_width = 1.0f;
}
}
void QDirect3DPaintEnginePrivate::updateBrush(const QBrush &brush)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::updateBrush";
#endif
m_brush = brush;
m_brush_style = m_brush.style();
m_has_brush = (m_brush_style != Qt::NoBrush);
if (m_has_brush) {
if (m_brush_style >= Qt::SolidPattern && m_brush_style <= Qt::DiagCrossPattern) {
int a, r, g, b;
m_brush.color().getRgb(&r, &g, &b, &a);
m_brush_color = D3DCOLOR_ARGB((int)(a * m_opacity),r,g,b);
} else {
m_brush_color = m_opacity_color;
}
if (m_brush_style != Qt::SolidPattern) {
bool ok;
m_inv_brush_matrix = (m_brush.transform() * m_brush_origin).inverted(&ok);
if (!ok)
qWarning() << "QDirect3DPaintEngine: No inverse matix for brush matrix.";
// make sure the texture is loaded as a texture
if (m_brush_style == Qt::TexturePattern)
verifyTexture(m_brush.texture());
}
}
}
void QDirect3DPaintEnginePrivate::updateTransform(const QTransform &matrix)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::updateTransform";
#endif
m_matrix = matrix;
m_inv_scale = qMax(1 / qMax( qMax(qAbs(m_matrix.m11()), qAbs(m_matrix.m22())),
qMax(qAbs(m_matrix.m12()), qAbs(m_matrix.m21())) ), 0.0001);
m_txop = matrix.type();
}
int QDirect3DPaintEnginePrivate::flushAntialiased(int offset)
{
// fills the mask (returns number of items added to the mask)
int newoffset = m_draw_helper->drawAntialiasedMask(offset, m_batch.m_item_index);
// set the render target to the current output surface
if (FAILED(m_d3d_device->SetRenderTarget(0, m_current_surface)))
qWarning() << "QDirect3DPaintEngine: SetRenderTarget failed!";
// draw the bounding boxes (using the mask generated by drawAntialiasedMask)
for (int i=offset; i<newoffset; ++i) {
QD3DBatchItem *item = &(m_batch.items[i]);
int pass = (item->m_info & QD3DBatchItem::BI_COMPLEXBRUSH) ? PASS_AA_DRAW : PASS_AA_DRAW_DIRECT;
m_statemanager->beginPass(pass);
prepareItem(item);
if (item->m_info & QD3DBatchItem::BI_BRECT)
m_draw_helper->drawAntialiasedBoundingRect(item);
cleanupItem(item);
}
m_statemanager->endPass();
return newoffset;
}
bool QDirect3DPaintEnginePrivate::prepareBatch(QD3DBatchItem *item, int offset)
{
if (item->m_info & QD3DBatchItem::BI_CLIP) {
setRenderTechnique(RT_Aliased);
if (item->m_info & QD3DBatchItem::BI_CLEARCLIP) {
m_d3d_device->Clear(0, 0, D3DCLEAR_ZBUFFER, 0, 0.0f, 0);
return true;
}
m_draw_helper->drawAliasedMask(offset);
m_d3d_device->Clear(0, 0, D3DCLEAR_ZBUFFER, 0, 1.0f, 0);
if (item->m_info & QD3DBatchItem::BI_BRECT) {
m_statemanager->beginPass(PASS_STENCIL_CLIP);
m_draw_helper->drawAliasedBoundingRect(item);
m_statemanager->endPass();
}
return true;
}
if (item->m_info & QD3DBatchItem::BI_AA) {
setRenderTechnique(RT_Antialiased);
} else {
setRenderTechnique(RT_Aliased);
}
return false;
}
void QDirect3DPaintEnginePrivate::prepareItem(QD3DBatchItem *item) {
// pixmap
int brushmode = 0;
m_statemanager->startStateBlock();
if ((item->m_info & QD3DBatchItem::BI_PIXMAP) || (item->m_info & QD3DBatchItem::BI_IMAGE)) {
QRasterPixmapData *data = static_cast<QRasterPixmapData*>(item->m_pixmap.data);
IDirect3DTexture9 *tex = (item->m_info & QD3DBatchItem::BI_PIXMAP) ?
data->texture : item->m_texture;
m_statemanager->setTexture(tex);
brushmode = 5;
}
if (item->m_info & QD3DBatchItem::BI_AA) {
m_statemanager->setMaskChannel(item->m_maskpos.channel);
m_statemanager->setMaskOffset(item->m_xoffset, item->m_yoffset);
}
if (item->m_info & QD3DBatchItem::BI_COMPLEXBRUSH) {
const QBrush brush = item->m_brush;
switch (brush.style()) {
case Qt::TexturePattern: {
QRasterPixmapData *data = static_cast<QRasterPixmapData*>(brush.texture().data);
m_statemanager->setTexture(data->texture, QGradient::RepeatSpread);
brushmode = 1;
break;
}
case Qt::LinearGradientPattern:
m_statemanager->setTexture(m_gradient_cache->
getBuffer(brush.gradient()->stops(), item->m_opacity),
brush.gradient()->spread());
brushmode = 2;
break;
case Qt::ConicalGradientPattern:
m_statemanager->setTexture(m_gradient_cache->
getBuffer(brush.gradient()->stops(), item->m_opacity),
brush.gradient()->spread());
brushmode = 3;
break;
case Qt::RadialGradientPattern:
m_statemanager->setTexture(m_gradient_cache->
getBuffer(brush.gradient()->stops(), item->m_opacity),
brush.gradient()->spread());
m_statemanager->setFocalDistance(item->m_distance);
brushmode = 4;
break;
default: {
QRasterPixmapData *data = static_cast<QRasterPixmapData*>(getPattern(brush.style()).data);
m_statemanager->setTexture(data->texture, QGradient::RepeatSpread);
brushmode = 5;
}
};
}
if (item->m_info & QD3DBatchItem::BI_TRANSFORM) {
m_statemanager->setTransformation(&item->m_matrix);
} else {
m_statemanager->setTransformation();
}
m_statemanager->setBrushMode(brushmode);
setCompositionMode(item->m_cmode);
m_statemanager->endStateBlock();
}
void QDirect3DPaintEnginePrivate::releaseDC()
{
if (m_dc) {
m_dcsurface->ReleaseDC(m_dc);
m_dcsurface = 0;
m_dc = 0;
}
}
void QDirect3DPaintEnginePrivate::cleanupItem(QD3DBatchItem *item)
{
if (item->m_info & QD3DBatchItem::BI_PIXMAP)
item->m_pixmap = QPixmap();
item->m_brush = QBrush();
}
void QDirect3DPaintEnginePrivate::verifyTexture(const QPixmap &pm)
{
QRasterPixmapData *pmData = static_cast<QRasterPixmapData*>(pm.data);
if (!pmData->texture) {
QImage im = pmData->image;
// bitmaps are drawn with the current pen color
if (im.depth() == 1) {
QVector<QRgb> colors(2);
colors[0] = 0;
colors[1] = m_pen.color().rgba();
im.setColorTable(colors);
}
im = im.convertToFormat(QImage::Format_ARGB32);
if (FAILED(m_d3d_device->CreateTexture(im.width(), im.height(), 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &pmData->texture, 0)))
{
qWarning("QDirect3DPaintEngine: unable to create Direct3D texture from pixmap.");
return;
}
D3DLOCKED_RECT rect;
if (FAILED(pmData->texture->LockRect(0, &rect, 0, 0))) {
qDebug() << "QDirect3DPaintEngine: unable to lock texture rect.";
return;
}
DWORD *dst = (DWORD *) rect.pBits;
DWORD *src = (DWORD *) im.scanLine(0);
Q_ASSERT((rect.Pitch/4) == (im.bytesPerLine()/4));
memcpy(dst, src, rect.Pitch*im.height());
pmData->texture->UnlockRect(0);
}
}
bool QDirect3DPaintEnginePrivate::isFastRect(const QRectF &rect)
{
if (m_matrix.type() < QTransform::TxRotate) {
QRectF r = m_matrix.mapRect(rect);
return r.topLeft().toPoint() == r.topLeft()
&& r.bottomRight().toPoint() == r.bottomRight();
}
return false;
}
void QDirect3DPaintEnginePrivate::setCompositionMode(QPainter::CompositionMode mode)
{
switch(mode) {
case QPainter::CompositionMode_SourceOver:
default:
m_statemanager->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_statemanager->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
};
}
void QDirect3DPaintEnginePrivate::cleanup()
{
// clean batch
for(int i=0; i<QD3D_BATCH_SIZE; ++i) {
m_batch.items[i].m_brush = QBrush();
m_batch.items[i].m_pixmap = QPixmap();
}
m_surface_manager.cleanup();
m_patterns.clear();
delete m_gradient_cache;
delete m_draw_helper;
if (m_effect)
m_effect->Release();
if (m_d3d_object)
m_d3d_object->Release();
m_effect = 0;
m_d3d_object = 0;
m_gradient_cache = 0;
m_draw_helper = 0;
}
void QDirect3DPaintEnginePrivate::flushAliased(QD3DBatchItem *item, int offset)
{
m_draw_helper->drawAliasedMask(offset);
if (item->m_info & QD3DBatchItem::BI_BRECT) {
int pass = (item->m_info & QD3DBatchItem::BI_MASK) ? PASS_STENCIL_DRAW_DIRECT : PASS_STENCIL_NOSTENCILCHECK_DIRECT;
if (item->m_info & (QD3DBatchItem::BI_COMPLEXBRUSH|QD3DBatchItem::BI_IMAGE|QD3DBatchItem::BI_PIXMAP) )
pass = (item->m_info & QD3DBatchItem::BI_MASK) ? PASS_STENCIL_DRAW : PASS_STENCIL_NOSTENCILCHECK;
m_statemanager->beginPass(pass);
prepareItem(item);
m_draw_helper->drawAliasedBoundingRect(item);
cleanupItem(item);
m_statemanager->endPass();
}
}
void QDirect3DPaintEnginePrivate::flushText(QD3DBatchItem *item, int)
{
prepareItem(item);
m_statemanager->setTexture(item->m_texture);
m_statemanager->setBrushMode(1);
// m_statemanager->SetRenderState(D3DRS_BLENDFACTOR, item->m_brush.color().rgba());
m_statemanager->beginPass(m_cleartype_text ? PASS_CLEARTYPE_TEXT : PASS_TEXT);
m_draw_helper->drawTextItem(item);
m_statemanager->endPass();
cleanupItem(item);
}
void QDirect3DPaintEnginePrivate::flushLines(QD3DBatchItem *item, int)
{
m_draw_helper->drawAliasedLines(item);
if (item->m_info & QD3DBatchItem::BI_BRECT) {
int pass = (item->m_info & QD3DBatchItem::BI_COMPLEXBRUSH) ? PASS_STENCIL_DRAW : PASS_STENCIL_DRAW_DIRECT;
m_statemanager->beginPass(pass);
prepareItem(item);
m_draw_helper->drawAliasedBoundingRect(item);
cleanupItem(item);
m_statemanager->endPass();
}
}
void QDirect3DPaintEnginePrivate::flushBatch()
{
// static int dbgcounter = 0;
// ++dbgcounter;
// qDebug() << " -> flush" << dbgcounter;
int offset = 0;
m_draw_helper->unlockVertexBuffer();
releaseDC();
// iterate over all items in the batch
while (offset != m_batch.m_item_index) {
QD3DBatchItem *item = &(m_batch.items[offset]);
if (prepareBatch(item, offset)) {
++offset;
continue;
}
if (item->m_info & QD3DBatchItem::BI_FASTLINE) {
flushLines(item, offset++);
} else if (item->m_info & QD3DBatchItem::BI_AA) {
offset = flushAntialiased(offset);
} else if (item->m_info & QD3DBatchItem::BI_TEXT) {
flushText(item, offset++);
} else {
flushAliased(item, offset++);
}
}
// reset batch
m_batch.m_item_index = 0;
// release doomed textures
for (int i=0; i<qd3d_release_list.size(); ++i)
qd3d_release_list.at(i)->Release();
qd3d_release_list.clear();
}
QDirect3DPaintEngine::QDirect3DPaintEngine()
: QPaintEngine(*(new QDirect3DPaintEnginePrivate),
PaintEngineFeatures(AllFeatures & ~ObjectBoundingModeGradients))
{ }
QDirect3DPaintEngine::~QDirect3DPaintEngine()
{
}
bool QDirect3DPaintEngine::begin(QPaintDevice *device)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::begin";
#endif
Q_D(QDirect3DPaintEngine);
setActive(true);
QSize old_size = d->m_surface_size;
d->m_surface_size = QRect(0, 0, device->width(), device->height()).size();
d->m_current_state = 0;
d->m_inv_scale = 1;
d->m_opacity = 1.0f;
d->m_opacity_color = D3DCOLOR_ARGB(255,255,255,255);
d->m_matrix = QTransform();
d->m_brush_origin = QTransform();
d->m_txop = QTransform::TxNone;
d->m_cmode = QPainter::CompositionMode_SourceOver;
Q_ASSERT(device && device->devType() == QInternal::Widget);
if (d->m_d3d_device == 0) {
qWarning() << "QDirect3DPaintEngine: No Device!";
return false;
}
d->m_cleartype_text = false;
// QT_WA({
// UINT result;
// BOOL ok;
// ok = SystemParametersInfoW(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0);
// if (ok)
// d->m_cleartype_text = (result == FE_FONTSMOOTHINGCLEARTYPE);
// }, {
// UINT result;
// BOOL ok;
// ok = SystemParametersInfoA(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0);
// if (ok)
// d->m_cleartype_text = (result == FE_FONTSMOOTHINGCLEARTYPE);
// });
d->m_surface_manager.setPaintDevice(device);
int status = d->m_surface_manager.status();
if (status & QD3DSurfaceManager::NeedsResetting) {
d->m_effect->OnLostDevice();
d->m_draw_helper->beforeReset();
d->m_statemanager->reset();
d->m_surface_manager.reset();
d->m_draw_helper->afterReset();
d->m_effect->OnResetDevice();
d->initDevice();
}
LPDIRECT3DSURFACE9 newsurface = d->m_surface_manager.renderTarget();
if (d->m_current_surface != newsurface) {
d->m_current_surface = newsurface;
if (FAILED(d->m_d3d_device->SetRenderTarget(0, newsurface)))
qWarning() << "QDirect3DPaintEngine: SetRenderTarget failed!";
}
status = d->m_surface_manager.status();
if (status & QD3DSurfaceManager::MaxSizeChanged) {
QSize maxsize = d->m_surface_manager.maxSize();
d->m_draw_helper->setMaskSize(maxsize);
int masksize[2] = {maxsize.width(), maxsize.height()};
d->m_effect->SetIntArray("g_mMaskSize", masksize, 2);
}
if (old_size != d->m_surface_size) {
D3DXMATRIX projMatrix;
pD3DXMatrixOrthoOffCenterLH(&projMatrix, 0, d->m_surface_size.width(), d->m_surface_size.height(), 0, 0.0f, 1.0f);
d->m_statemanager->setProjection(&projMatrix);
}
if (!d->m_in_scene) {
if (FAILED(d->m_d3d_device->BeginScene())) {
qWarning() << "QDirect3DPaintEngine: BeginScene() failed.";
return false;
}
QWidget *widget = static_cast<QWidget *>(device);
if (widget->autoFillBackground() == true) {
QColor color = widget->palette().brush(widget->backgroundRole()).color();
RECT rect = {0, 0, widget->width(), widget->height()};
d->m_d3d_device->ColorFill(d->m_current_surface, &rect,
D3DCOLOR_ARGB(color.alpha(), color.red(), color.green(), color.blue()));
}
d->m_in_scene = true;
}
// set system clip
d->m_clipping_enabled = false;
d->m_has_complex_clipping = false;
d->m_sysclip_region = systemClip();
QVector<QRect> rects = d->m_sysclip_region.rects();
if (rects.count() == 1 && rects.at(0).size() == d->m_surface_size)
d->m_sysclip_region = QRegion();
d->updateClipRegion(QRegion(), Qt::NoClip);
return true;
}
void QDirect3DPaintEngine::drawEllipse(const QRectF &rect)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawEllipse (float)";
#endif
QPaintEngine::drawEllipse(rect);
}
void QDirect3DPaintEngine::drawEllipse(const QRect &rect)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawEllipse";
#endif
QPaintEngine::drawEllipse(rect);
}
void QDirect3DPaintEngine::drawImage(const QRectF &r, const QImage &image, const QRectF &sr,
Qt::ImageConversionFlags)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawImage";
#endif
Q_D(QDirect3DPaintEngine);
int width = image.width();
int height = image.height();
// transform rectangle
QPolygonF txrect(QRectF(sr.left() / width, sr.top() / height,
sr.width() / width, sr.height() / height));
QD3DBatchItem *item = d->nextBatchItem();
item->m_info = QD3DBatchItem::BI_IMAGE | QD3DBatchItem::BI_TRANSFORM;
item->m_texture = qd3d_image_cache()->lookup(d->m_d3d_device, image);
item->m_matrix = d->m_matrix;
d->m_draw_helper->queueRect(r.adjusted(-0.5f,-0.5f,-0.5f,-0.5f), item, d->m_opacity_color, txrect);
}
void QDirect3DPaintEngine::drawLines(const QLineF *lines, int lineCount)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawLines (float)";
#endif
Q_D(QDirect3DPaintEngine);
if (!d->m_has_pen)
return;
if (d->m_has_fast_pen && (d->m_pen_brush_style == Qt::SolidPattern)) {
QD3DBatchItem *item = d->nextBatchItem();
if (d->m_pen.isCosmetic())
item->m_info |= QD3DBatchItem::BI_COSMETICPEN;
item->m_info |= QD3DBatchItem::BI_TRANSFORM;
item->m_matrix = d->m_matrix;
d->m_draw_helper->queueAliasedLines(lines, lineCount, &item);
} else {
QRectF brect;
QPainterPath path;
// creates a path with the lines
path.moveTo(lines[0].x1(), lines[0].y1());
qreal lastx = lines[0].x2();
qreal lasty = lines[0].y2();
path.lineTo(lastx, lasty);
for (int i=1; i<lineCount; ++i) {
qreal x = lines[i].x1();
qreal y = lines[i].y1();
if (lastx != x || lasty != y) {
path.moveTo(x, y);
}
path.lineTo(lines[i].x2(), lines[i].y2());
}
if (d->m_has_cosmetic_pen) {
brect = path.controlPointRect();
path = d->m_matrix.map(path);
}
d->strokePath(path, brect, true);
}
}
void QDirect3DPaintEngine::drawLines(const QLine *lines, int lineCount)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawLines";
#endif
QPaintEngine::drawLines(lines, lineCount);
}
void QDirect3DPaintEngine::drawPath(const QPainterPath &path)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawPath";
#endif
Q_D(QDirect3DPaintEngine);
if (path.isEmpty())
return;
QRectF brect;
QPainterPath tpath;
if (d->m_has_cosmetic_pen) {
brect = path.controlPointRect();
tpath = d->m_matrix.map(path);
} else {
tpath = path;
}
if (d->m_has_brush)
d->fillPath(tpath, brect);
if (d->m_has_pen)
d->strokePath(tpath, brect);
}
QPointF QDirect3DPaintEnginePrivate::transformPoint(const QPointF &p, qreal *w) const
{
(*w) = 1.0f;
qreal fx = p.x();
qreal fy = p.y();
qreal nx = m_matrix.m11()*fx + m_matrix.m21()*fy + m_matrix.m31();
qreal ny = m_matrix.m12()*fx + m_matrix.m22()*fy + m_matrix.m32();
if (!m_matrix.isAffine()) {
*w = m_matrix.m13()*fx + m_matrix.m23()*fy + m_matrix.m33();
//*w = 1/(*w);
nx = nx/(*w);
ny = ny/(*w);
}
return QPointF(nx, ny);
}
void QDirect3DPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawPixmap";
#endif
Q_D(QDirect3DPaintEngine);
if (d->m_draw_helper->needsFlushing())
d->flushBatch();
int width = pm.width();
int height = pm.height();
// transform rectangle
QPolygonF txrect(QRectF(sr.left() / width, sr.top() / height,
sr.width() / width, sr.height() / height));
QD3DBatchItem *item = d->nextBatchItem();
item->m_info = QD3DBatchItem::BI_PIXMAP|QD3DBatchItem::BI_TRANSFORM;
item->m_pixmap = pm;
d->verifyTexture(item->m_pixmap);
item->m_matrix = d->m_matrix;
d->m_draw_helper->queueRect(r.adjusted(-0.5f,-0.5f,-0.5f,-0.5f), item, d->m_opacity_color, txrect);
}
void QDirect3DPaintEngine::drawPoints(const QPointF *points, int pointCount)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawPoints (float)";
#endif
QPaintEngine::drawPoints(points, pointCount);
}
void QDirect3DPaintEngine::drawPoints(const QPoint *points, int pointCount)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawPoints";
#endif
QPaintEngine::drawPoints(points, pointCount);
}
void QDirect3DPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawPolygon";
#endif
Q_D(QDirect3DPaintEngine);
if (d->m_has_brush && mode != PolylineMode) {
QPainterPath path;
path.setFillRule(mode == WindingMode ? Qt::WindingFill : Qt::OddEvenFill);
path.moveTo(points[0]);
for (int i=1; i<pointCount; ++i)
path.lineTo(points[i]);
if (path.isEmpty())
return;
d->fillPath(path, QRectF());
}
if (d->m_has_pen) {
QPainterPath path(points[0]);
for (int i = 1; i < pointCount; ++i)
path.lineTo(points[i]);
if (mode != PolylineMode)
path.lineTo(points[0]);
if (path.isEmpty())
return;
QRectF brect;
if (d->m_has_cosmetic_pen) {
brect = path.controlPointRect();
path = d->m_matrix.map(path);
}
d->strokePath(path, brect);
}
}
void QDirect3DPaintEngine::drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawPolygon";
#endif
QPaintEngine::drawPolygon(points, pointCount, mode);
}
void QDirect3DPaintEngine::drawRects(const QRectF *rects, int rectCount)
{
Q_D(QDirect3DPaintEngine);
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawRects (float)";
#endif
for (int i=0; i<rectCount; ++i) {
if ((d->m_brush_style == Qt::SolidPattern) &&
(!(d->m_current_state & QD3DBatchItem::BI_AA) || d->isFastRect(rects[i]))) {
QD3DBatchItem *item = d->nextBatchItem();
item->m_info |= QD3DBatchItem::BI_TRANSFORM;
item->m_info &= ~QD3DBatchItem::BI_AA;
item->m_matrix = d->m_matrix;
const QRectF rect = rects[i];
d->m_draw_helper->queueRect(rect, item, d->m_brush_color);
if (d->m_has_pen) {
if (d->m_has_fast_pen && (d->m_pen_brush_style == Qt::SolidPattern)) {
QLineF lines[4];
qreal x1 = rect.x();
qreal y1 = rect.y();
qreal x2 = rect.width() + x1;
qreal y2 = rect.height() + y1;
lines[0] = QLineF(x1, y1, x2, y1);
lines[1] = QLineF(x2, y1, x2, y2);
lines[2] = QLineF(x2, y2, x1, y2);
lines[3] = QLineF(x1, y2, x1, y1);
QD3DBatchItem *item = d->nextBatchItem();
if (d->m_pen.isCosmetic())
item->m_info |= QD3DBatchItem::BI_COSMETICPEN;
item->m_info |= QD3DBatchItem::BI_TRANSFORM;
item->m_matrix = d->m_matrix;
d->m_draw_helper->queueAliasedLines(lines, 4, &item);
} else {
QPainterPath path;
QRectF brect;
path.addRect(rects[i]);
if (d->m_has_cosmetic_pen) {
brect = path.controlPointRect();
path = d->m_matrix.map(path);
}
d->strokePath(path, brect, true);
}
}
} else {
QPainterPath path;
QRectF brect;
path.addRect(rects[i]);
if (d->m_has_cosmetic_pen) {
brect = path.controlPointRect();
path = d->m_matrix.map(path);
}
if (d->m_has_brush)
d->fillPath(path, brect);
if (d->m_has_pen)
d->strokePath(path, brect, true);
}
}
}
void QDirect3DPaintEngine::drawRects(const QRect *rects, int rectCount)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawRects";
#endif
QPaintEngine::drawRects(rects, rectCount);
}
void QDirect3DPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
{
Q_D(QDirect3DPaintEngine);
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawTextItem";
#endif
// if (d->m_matrix.isScaling() || (d->m_pen_brush_style >= Qt::LinearGradientPattern
// && d->m_pen_brush_style <= Qt::ConicalGradientPattern)) {
// QPaintEngine::drawTextItem(p, textItem);
// return;
// }
const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
QVarLengthArray<QFixedPoint> positions;
QVarLengthArray<glyph_t> glyphs;
QTransform matrix;
matrix.translate(p.x(), p.y());
ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
qd3d_glyph_cache()->cacheGlyphs(this, ti, glyphs, d->m_cleartype_text);
QD3DFontTexture *font_tex = qd3d_glyph_cache()->fontTexture(ti.fontEngine);
QD3DBatchItem *item = d->nextBatchItem();
d->m_draw_helper->lockVertexBuffer();
item->m_info = QD3DBatchItem::BI_TEXT
| (d->m_current_state & ~QD3DBatchItem::BI_AA) | QD3DBatchItem::BI_TRANSFORM;
item->m_texture = font_tex->texture;
item->m_offset = d->m_draw_helper->index();
item->m_matrix = d->m_matrix;
item->m_count = 0;
item->m_brush = d->m_pen.brush();
for (int i=0; i< glyphs.size(); ++i) {
QD3DGlyphCoord *g = qd3d_glyph_cache()->lookup(ti.fontEngine, glyphs[i]);
// we don't cache glyphs with no width/height
if (!g)
continue;
// texture coords
qreal tex_coords[] = { g->x, g->y, g->x + g->width, g->y + g->height };
QPointF logical_pos(qRound((positions[i].x - g->x_offset).toReal()) - 0.5f,
qRound((positions[i].y + g->y_offset).toReal()) - 0.5f);
QRectF glyph_rect(logical_pos, QSizeF(g->log_width, g->log_height));
d->m_draw_helper->queueTextGlyph(glyph_rect, tex_coords, item, d->m_pen_color);
}
}
void QDirect3DPaintEngine::drawTiledPixmap(const QRectF &rect, const QPixmap &pixmap, const QPointF &p)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::drawTiledPixmap";
#endif
QPaintEngine::drawTiledPixmap(rect, pixmap, p);
}
bool QDirect3DPaintEngine::end()
{
Q_D(QDirect3DPaintEngine);
d->flushBatch();
if (d->m_flush_on_end) {
QPaintDevice *pdev = paintDevice();
LPDIRECT3DSWAPCHAIN9 swapchain = swapChain(pdev);
QWidget *w = 0;
if (pdev->devType() == QInternal::Widget) {
w = static_cast<QWidget *>(pdev);
}
if (w && swapchain) {
QRect br = w->rect();
QRect wbr = br;//.translated(-w->pos());
RECT destrect;
destrect.left = wbr.x();
destrect.top = wbr.y();
destrect.right = destrect.left + wbr.width();
destrect.bottom = destrect.top + wbr.height();
RECT srcrect;
srcrect.left = br.x();// + w->x();
srcrect.top = br.y();// + w->y();
srcrect.right = wbr.width() + srcrect.left;
srcrect.bottom = wbr.height() + srcrect.top;
int devwidth = w->width();
int devheight = w->height();
if (devwidth <= srcrect.right) {
int diff = srcrect.right - devwidth;
srcrect.right -= diff;
destrect.right -= diff;
if (srcrect.right <= srcrect.left)
return false;
}
if (devheight <= srcrect.bottom) {
int diff = srcrect.bottom - devheight;
srcrect.bottom -= diff;
destrect.bottom -= diff;
if (srcrect.bottom <= srcrect.top)
return false;
}
if (FAILED(swapchain->Present(&srcrect, &destrect, w->winId(), 0, 0)))
qWarning("QDirect3DPaintEngine: failed to present back buffer.");
}
}
return true;
}
void QDirect3DPaintEngine::updateState(const QPaintEngineState &state)
{
#ifdef QT_DEBUG_D3D_CALLS
qDebug() << "QDirect3DPaintEngine::updateState";
#endif
Q_D(QDirect3DPaintEngine);
bool update_fast_pen = false;
DirtyFlags flags = state.state();
if (flags & DirtyOpacity) {
d->m_opacity = state.opacity();
if (d->m_opacity > 1.0f)
d->m_opacity = 1.0f;
if (d->m_opacity < 0.f)
d->m_opacity = 0.f;
uint c = (d->m_opacity * 255);
d->m_opacity_color = D3DCOLOR_ARGB(c,c,c,c);
flags |= (DirtyPen | DirtyBrush);
}
if (flags & DirtyCompositionMode) {
d->m_cmode = state.compositionMode();
}
if (flags & DirtyTransform) {
d->updateTransform(state.transform());
update_fast_pen = true;
}
if (flags & DirtyHints) {
if (state.renderHints() & QPainter::Antialiasing)
d->m_current_state |= QD3DBatchItem::BI_AA;
else
d->m_current_state &= ~QD3DBatchItem::BI_AA;
update_fast_pen = true;
}
if (flags & DirtyFont) {
d->updateFont(state.font());
}
if (state.state() & DirtyClipEnabled) {
if (state.isClipEnabled() && !d->m_clipping_enabled) {
d->m_clipping_enabled = true;
if (d->m_has_complex_clipping)
d->updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
else
d->updateClipRegion(painter()->clipRegion(), Qt::ReplaceClip);
} else if (!state.isClipEnabled() && d->m_clipping_enabled) {
d->m_clipping_enabled = false;
if (d->m_has_complex_clipping)
d->updateClipPath(QPainterPath(), Qt::NoClip);
else
d->updateClipRegion(QRegion(), Qt::NoClip);
}
}
if (flags & DirtyClipRegion) {
d->updateClipRegion(state.clipRegion(), state.clipOperation());
}
if (flags & DirtyClipPath) {
d->updateClipPath(state.clipPath(), state.clipOperation());
}
if (flags & DirtyBrushOrigin) {
d->m_brush_origin = QTransform();
d->m_brush_origin.translate(-state.brushOrigin().x(),
-state.brushOrigin().y());
flags |= DirtyBrush;
}
if (flags & DirtyPen) {
d->updatePen(state.pen());
update_fast_pen = true;
}
if (flags & DirtyBrush)
d->updateBrush(state.brush());
if (update_fast_pen && d->m_has_pen) {
if (d->m_current_state & QD3DBatchItem::BI_AA) {
d->m_has_fast_pen = false;
d->m_has_aa_fast_pen = ((d->m_txop <= QTransform::TxTranslate) || d->m_has_cosmetic_pen)
&& (d->m_pen_width <= 1.0f)
&& (d->m_pen.style() == Qt::SolidLine);
} else {
d->m_has_aa_fast_pen = false;
d->m_has_fast_pen = ((d->m_txop <= QTransform::TxTranslate) || d->m_has_cosmetic_pen)
&& (d->m_pen.style() == Qt::SolidLine)
&& (d->m_pen.capStyle() == Qt::SquareCap);
}
}
}
void QDirect3DPaintEngine::cleanup()
{
Q_D(QDirect3DPaintEngine);
d->cleanup();
}
void QDirect3DPaintEngine::scroll(QPaintDevice *pd, const RECT &srcrect, const RECT &destrect)
{
Q_D(QDirect3DPaintEngine);
LPDIRECT3DSURFACE9 srcsurf = d->m_surface_manager.surface(pd);
LPDIRECT3DSURFACE9 masksurf = d->m_draw_helper->freeMaskSurface();
if (FAILED(d->m_d3d_device->StretchRect(srcsurf, &srcrect, masksurf, &srcrect, D3DTEXF_NONE)))
qWarning("QDirect3DPaintEngine: StretchRect failed.");
if (FAILED(d->m_d3d_device->StretchRect(masksurf, &srcrect, srcsurf, &destrect, D3DTEXF_NONE)))
qWarning("QDirect3DPaintEngine: StretchRect failed.");
}
LPDIRECT3DSWAPCHAIN9 QDirect3DPaintEngine::swapChain(QPaintDevice *pd)
{
Q_D(QDirect3DPaintEngine);
if (d->m_in_scene) {
if (d->m_d3d_device == 0) {
qWarning("QDirect3DPaintEngine: No device!");
return false;
}
d->setRenderTechnique(QDirect3DPaintEnginePrivate::RT_NoTechnique);
if (FAILED(d->m_d3d_device->EndScene()))
qWarning("QDirect3DPaintEngine: failed to end scene.");
d->m_in_scene = false;
}
return d->m_surface_manager.swapChain(pd);
}
void QDirect3DPaintEngine::releaseSwapChain(QPaintDevice *pd)
{
Q_D(QDirect3DPaintEngine);
d->m_surface_manager.releasePaintDevice(pd);
}
HDC QDirect3DPaintEngine::getDC() const
{
QDirect3DPaintEnginePrivate *d = const_cast<QDirect3DPaintEnginePrivate *>(d_func());
if (!d->m_dc && d->m_current_surface) {
d->m_dcsurface = d->m_current_surface;
if (FAILED(d->m_current_surface->GetDC(&d->m_dc)))
qWarning() << "QDirect3DPaintEngine::getDC() failed!";
}
return d->m_dc;
}
void QDirect3DPaintEngine::setFlushOnEnd(bool flushOnEnd)
{
Q_D(QDirect3DPaintEngine);
d->m_flush_on_end = flushOnEnd;
}
bool QDirect3DPaintEngine::hasDirect3DSupport()
{
Q_D(QDirect3DPaintEngine);
return d->m_supports_d3d;
}
QT_END_NAMESPACE
#include "qpaintengine_d3d.moc"
| [
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
]
| [
[
[
1,
4576
]
]
]
|
67d7ae9f7644d93ae5ff546150633b637d0dbb2c | 460d5c0a45d3d377bfc4ce71de99f4abc517e2b6 | /Proj2/crazy8card.h | a06bd022315b53d0d4722935bc6710d6d404908f | []
| no_license | wilmer/CS211 | 3ba910e9cc265ca7e3ecea2c71cf1246d430f269 | 1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0 | refs/heads/master | 2020-12-25T09:38:34.633541 | 2011-03-06T04:53:54 | 2011-03-06T04:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | h | #ifndef CRAZY8CARD_H
#define CRAZY8CARD_H
#include "card.h"
using namespace std;
class crazy8card : public Card //inherits class Card
{
public:
bool bePlayed(crazy8card test, crazy8card discard) const;
bool isEight() const;
crazy8card copy (const crazy8card c1, crazy8card c2);
void operator =(const crazy8card& source);
};
std::ostream& operator << (std::ostream& outs, const crazy8card& c);
#endif
| [
"[email protected]"
]
| [
[
[
1,
19
]
]
]
|
678fc490502fbd55b3ce4dc2e68fb6d9b886b4db | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /src/Engine/Script/ExposeComponentContainer.h | c9873fbad42e4b0e6e7b4136f029b1271321ebdc | []
| no_license | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | #pragma once
#include <LuaPlus/LuaPlus.h>
#include <vector>
#include <Event/EventContainer.h>
#include <Event/Event.h>
namespace Engine
{
class CoreMgr;
class ExposeIEntity;
class ExposeComponent;
class ExposeComponentContainer
{
public:
ExposeComponentContainer(CoreMgr *coreMgr, ExposeIEntity *exposedEntity);
~ExposeComponentContainer();
LuaPlus::LuaObject &getLComps() { return lComponents; }
private:
void init();
void AddComponent(LuaPlus::LuaObject self, LuaPlus::LuaObject lName);
CoreMgr *coreMgr;
ExposeIEntity *exposedEntity;
LuaPlus::LuaObject lComponents;
std::vector<ExposeComponent*> exposedComponents;
void OnComponentAdded(const Events::Event &event);
Events::EventContainer engineEvents;
};
}
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
38
]
]
]
|
700b0913df9a7fd1bd068f178931811774b36e52 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/AlignmentPage.h | 398c4ac5f01ca248d3e3f18f8d7486afd4e5978b | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,152 | h | #ifndef ALIGNMENT_PAGE_H
#define ALIGNMENT_PAGE_H
#include "CalibrationPage.h"
class ExpQubit;
class ExpSCAN_Detect;
class AlignMirrorsPage : public CalibrationPage
{
public:
AlignMirrorsPage(const string& sPageName, ExperimentsSheet* pSheet);
void AddAvailableActions(std::vector<std::string>* p);
void on_action(const std::string& s);
virtual void DidCalibration(const calibration_item*, numerics::FitObject*);
virtual unsigned num_columns()
{
return 6;
}
virtual bool acceptCalibrationPlot(calibration_item* ci, data_plot*);
virtual data_plot* get_data_plot(calibration_item* ci, const std::string& sTitle);
virtual void PostCreateGUI();
virtual void InitExperimentStart();
virtual bool wantsPlotLegend()
{
return false;
}
protected:
int getPlotIndex(const calibration_item* ci);
virtual bool needsBottomSpacer()
{
return false;
}
protected:
GUI_int NumExp;
vector<GUI_double*> FitCenters;
vector<GUI_int*> Spans;
std::vector<calibration_item> cal;
ExpQubit* pCal;
std::vector<data_plot*> data_plots;
QGridLayout* plot_grid;
};
class AlignBfieldPage : public CalibrationPage
{
public:
AlignBfieldPage(const string& sPageName, ExperimentsSheet* pSheet);
void AddAvailableActions(std::vector<std::string>* p);
void on_action(const std::string& s);
virtual void DidCalibration(const calibration_item*, numerics::FitObject*);
virtual unsigned num_columns()
{
return 6;
}
virtual bool acceptCalibrationPlot(calibration_item* ci, data_plot*);
virtual data_plot* get_data_plot(calibration_item* ci, const std::string& sTitle);
virtual void PostCreateGUI();
virtual void InitExperimentStart();
virtual bool wantsPlotLegend()
{
return false;
}
protected:
int getPlotIndex(const calibration_item* ci);
virtual bool needsBottomSpacer()
{
return false;
}
protected:
vector<GUI_double*> FitCenters;
GUI_double Bx_start, Bx_stop, By_start, By_stop;
std::vector<calibration_item> cal;
ExpSCAN_Detect* pCal;
std::vector<data_plot*> data_plots;
QGridLayout* plot_grid;
unsigned nFields;
};
#endif //ALIGNMENT_PAGE_H
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
109
]
]
]
|
10a93eadc2b16940f36c9ea65e070e10f6d1e62d | d397b0d420dffcf45713596f5e3db269b0652dee | /src/Lib/ScriptEngine/Property.hpp | cd2548f50c54d93a7275bb7432d965d7b706b70b | []
| no_license | irov/Axe | 62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f | d3de329512a4251470cbc11264ed3868d9261d22 | refs/heads/master | 2021-01-22T20:35:54.710866 | 2010-09-15T14:36:43 | 2010-09-15T14:36:43 | 85,337,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | hpp | # pragma once
# include "EmbeddingProperty.hpp"
# include <AxeUtil/Shared.hpp>
namespace AxeScript
{
class Property
: virtual public AxeUtil::Shared
{
public:
Property( const EmbeddingPropertyPtr & _embedding, const boost::python::object & _value );
public:
void update( const boost::python::object & _value );
public:
std::size_t getRevision() const;
const boost::python::object & getValue() const;
protected:
std::size_t m_revision;
EmbeddingPropertyPtr m_embedding;
boost::python::object m_value;
};
typedef AxeHandle<Property> PropertyPtr;
}
| [
"yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0"
]
| [
[
[
1,
29
]
]
]
|
02ef56d4972f9e6c158c663da013a9825d319cab | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Dynamics/Phantom/hkpShapePhantom.inl | a02f78ff17af01c1ccd537dc97e77ee37dab73c4 | []
| 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,624 | 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.
*
*/
#define HK_PHANTOM_SHAPE_CHANGE_ERROR_TEXT "Setting the shape of a hkpShapePhantom while it is in the world is very dangerous!" \
"- If any hkCachingShapePhantoms also in the world overlap with this phantom, their cached agents will become invalid. " \
"You should remove this phantom from the world, change the shape, then re-add."
inline const hkTransform& hkpShapePhantom::getTransform() const
{
return m_motionState.getTransform();
}
/*
* 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.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
883f26b6023394adeedab4ef02698a65b92ba6a0 | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /Source/EduNetGames/obsolete/Tutorial_03/NetBoidConditionReplica.cpp | 567549c09e0c88ee57a9150a678c81b203bb0f4d | []
| no_license | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,744 | cpp | #include "NetBoidConditionReplica.h"
#include "BoidsPlugin.h"
//-----------------------------------------------------------------------------
RakNet::RM3SerializationResult NetBoidConditionReplica::Serialize(
RakNet::SerializeParameters *serializeParameters)
{
if(false == this->m_pBoidPlugin->WasBoundaryConditionChangedLocally())
{
return RakNet::RM3SR_DO_NOT_SERIALIZE;
}
RakNet::BitStream& kStream = serializeParameters->outputBitstream[0];
kStream.Write((int)this->m_pBoidPlugin->GetCurrentBoundaryCondition() );
return RakNet::RM3SR_BROADCAST_IDENTICALLY;
}
//-----------------------------------------------------------------------------
void NetBoidConditionReplica::Deserialize(
RakNet::DeserializeParameters *deserializeParameters)
{
int i;
RakNet::BitStream& kStream = deserializeParameters->serializationBitstream[0];
kStream.Read(i);
this->m_pBoidPlugin->SetCurrentBoundaryCondition(
(OpenSteer::EBoidConstraintType)i, false);
}
//-----------------------------------------------------------------------------
void NetBoidConditionReplica::SerializeConstructionExisting(
RakNet::BitStream *constructionBitstream,
RakNet::Connection_RM3 *destinationConnection)
{
constructionBitstream->Write(GetName() + RakNet::RakString(" SerializeConstructionExisting"));
}
//-----------------------------------------------------------------------------
void NetBoidConditionReplica::DeserializeConstructionExisting(
RakNet::BitStream *constructionBitstream,
RakNet::Connection_RM3 *sourceConnection)
{
PrintOutput(constructionBitstream);
}
//-----------------------------------------------------------------------------
void NetBoidConditionReplica::SerializeConstructionRequestAccepted(
RakNet::BitStream *serializationBitstream,
RakNet::Connection_RM3 *requestingConnection)
{
serializationBitstream->Write((int)this->m_pBoidPlugin->GetCurrentBoundaryCondition() );
}
//-----------------------------------------------------------------------------
void NetBoidConditionReplica::DeserializeConstructionRequestAccepted(
RakNet::BitStream *serializationBitstream,
RakNet::Connection_RM3 *acceptingConnection)
{
int i;
serializationBitstream->Read(i);
this->m_pBoidPlugin->SetCurrentBoundaryCondition(
(OpenSteer::EBoidConstraintType)i, false);
}
//-----------------------------------------------------------------------------
RakNet::RM3QuerySerializationResult NetBoidConditionReplica::QuerySerialization(
RakNet::Connection_RM3 *destinationConnection)
{
if(false == this->m_pBoidPlugin->WasBoundaryConditionChangedLocally())
{
return RakNet::RM3QSR_DO_NOT_CALL_SERIALIZE;
}
return RakNet::RM3QSR_CALL_SERIALIZE;
}
| [
"janfietz@localhost"
]
| [
[
[
1,
72
]
]
]
|
7f5b6de23f199c4f784cb09a58ce90fa62260adf | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/OLanguage/OLProjectFile.cpp | 0ce8fd92c63885e44a3786e40aaff33cfb787c63 | []
| no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 723 | cpp | #include "StdAfx.h"
#include "./olprojectfile.h"
#include "../Data/OLXMLProjectFile.h"
COLProjectFile::COLProjectFile(void)
{
}
COLProjectFile::~COLProjectFile(void)
{
}
bool COLProjectFile::CreateProjectFile(const char* pchFileName,bool bSave)
{
return COLXMLProjectFile::CreateProjectFile(pchFileName,bSave);
}
bool COLProjectFile::WriteProjectProperty(const char* pchFileName,COLProjectProperty* pProjectProperty)
{
return COLXMLProjectFile::WriteProjectProperty(pchFileName,pProjectProperty);
}
bool COLProjectFile::ReadProjectProperty(const char* pchFileName,COLProjectProperty* pProjectProperty)
{
return COLXMLProjectFile::ReadProjectProperty(pchFileName,pProjectProperty);
}
| [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
e9662d98f36d01646732a56809bf257a611588cb | 5d35825d03fbfe9885316ec7d757b7bcb8a6a975 | /src/NameFilter.cpp | be0a9d8e8c6c905a6b57bb731f4233fedc0c9e37 | []
| no_license | jjzhang166/3D-Landscape-linux | ce887d290b72ebcc23386782dd30bdd198db93ef | 4f87eab887750e3dc5edcb524b9e1ad99977bd94 | refs/heads/master | 2023-03-15T05:24:40.303445 | 2010-03-25T00:23:43 | 2010-03-25T00:23:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 133 | cpp | #include "NameFilter.h"
NameFilter::NameFilter(QString name)
: SearchFilter(name)
{
this->type = E_NAMEFILTER;
}
| [
"[email protected]"
]
| [
[
[
1,
7
]
]
]
|
8b5d5182d8099a31af78d12aa4624ea6e104ef85 | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/Plugins/hgeParticleSystem/hgerect.h | b276e07cdbbe7b1cebd9844aa822fa9addf3486c | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | h | /*
** Haaf's Game Engine 1.5
** Copyright (C) 2003-2004, Relish Games
** hge.relishgames.com
**
** hgeRect helper class
*/
#ifndef HGERECT_H
#define HGERECT_H
namespace HGE
{
class hgeRect
{
public:
float x1, y1, x2, y2;
hgeRect(float _x1, float _y1, float _x2, float _y2) {x1=_x1; y1=_y1; x2=_x2; y2=_y2; bClean=false; }
hgeRect() {bClean=true;}
void Clear() {bClean=true;}
bool IsClean() const {return bClean;}
void Set(float _x1, float _y1, float _x2, float _y2) { x1=_x1; x2=_x2; y1=_y1; y2=_y2; bClean=false; }
void SetRadius(float x, float y, float r) { x1=x-r; x2=x+r; y1=y-r; y2=y+r; bClean=false; }
void Encapsulate(float x, float y);
bool TestPoint(float x, float y) const;
bool Intersect(const hgeRect *rect) const;
private:
bool bClean;
};
}
#endif
| [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
38
]
]
]
|
64dd1b2f177bb1e070bbc407b95835aa08434af6 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /osgViewerSL/SilverLining/SkyDrawable.h | 1e20ddd0abe3522375d2c275299019f1033e3641 | []
| no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 961 | h | // Copyright (c) 2008 Sundog Software, LLC. All rights reserved worldwide.
#pragma once
#include <osg/Drawable>
#include <osgViewer/Viewer>
#include "SilverLining.h"
class AtmosphereReference;
class SkyDrawable : public osg::Drawable
{
public:
SkyDrawable();
SkyDrawable(osgViewer::Viewer* view);
virtual bool isSameKindAs(const Object* obj) const {
return dynamic_cast<const SkyDrawable*>(obj)!=NULL;
}
virtual Object* cloneType() const {
return new SkyDrawable();
}
virtual Object* clone(const osg::CopyOp& copyop) const {
return new SkyDrawable();
}
void setSkyboxSize(double size) {_skyboxSize = size;}
virtual void drawImplementation(osg::RenderInfo& renderInfo) const;
protected:
void setLighting(SilverLining::Atmosphere *atm) const;
void initializeSilverLining(AtmosphereReference *ar) const;
osgViewer::Viewer* _view;
double _skyboxSize;
};
| [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
]
| [
[
[
1,
37
]
]
]
|
a5f899ad1b5352ff13e5ffa5d12ca8e442fb82d9 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/VectorMapContainer.cpp | cef8089f1f37561df7b813a6650d1b01b01ec646 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108,426 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <eikapp.h>
#include <eikdoc.h>
#include <eikappui.h>
#include <eikenv.h>
#include <bautils.h>
#include <e32math.h>
#include <e32cmn.h>
#include <aknlists.h> // for avrell style listbox
#include <aknpopup.h> // for pop up menu
#ifndef NAV2_CLIENT_SERIES60_V3
#include <hal.h>
#endif
#include <eiklabel.h> // for labels
#include <eikedwin.h> // for labels
#include <aknutils.h> // for Fonts.
#ifdef NAV2_CLIENT_SERIES60_V5
# include <aknstyluspopupmenu.h>
#endif
#include "wficons.mbg"
#include "InterpolationHintConsumer.h"
#include "RsgInclude.h"
#include "userbitmap.h"
#include "BitmapControl.h"
#include "VectorMapContainer.h"
#include "MapView.h"
#include "TileMapControl.h"
#include "MapRenderer.h"
#include "MapMovingInterface.h"
#include "MapDrawingInterface.h"
#include "GlobeControl.h"
#include "CursorVisibilityAdapter.h"
#include "TileMapKeyHandler.h"
#include "SymbianTilemapToolkit.h"
#include "TileMapUtil.h"
#include "SharedDBufRequester.h"
#include "VectorMapConnection.h"
#include "WayFinderAppUi.h"
#include "GuiProt/GuiProtMess.h"
#include "RouteID.h"
#include "GuidePicture.h"
#include "DistancePrintingPolicy.h"
#include "DistanceBitmap.h"
#include "AnimatorFrame.h"
#include "MapTopBorderBar.h"
#include "BackgroundTextContainer.h"
//#include "PedestrianPositionControl.h"
#include "WFDRMUtil.h"
#include "SymbianTCPConnectionHandler.h"
#include "HttpClientConnection.h"
#include "SharedHttpDBufRequester.h"
#include "DirectedPolygon.h"
#include "MC2Point.h"
#include "UserDefinedBitMapFeature.h"
#include "UserDefinedScaleFeature.h"
#include "SymbianSprite.h"
#include "GuiProt/Favorite.h"
#include "MapFeatureHolder.h"
#include "Dialogs.h"
#include "PopUpList.h"
#include "LogFile.h"
#include "memlog.h"
#include "Log.h"
#include "LogMacros.h"
#include "SettingsData.h"
#include "TileMapTextSettings.h"
#include "MapInfoControl.h"
#include "MapMover.h"
#include "PathFinder.h"
#include "WFTextUtil.h"
#include "StringUtility.h"
#include "WayFinderSettings.h"
#include "ImageHandler.h"
#include "WFLayoutUtils.h"
/* #include "WFTimeUtils.h" */
#include "TileMapEvent.h"
#define ROTATE_NORTH_SCALE EScale7
using namespace std;
using namespace isab;
/* #define ONLY_LOCAL_TILEMAPS */
#ifndef NAV2_winscw_symbian_series60r3
# define USE_FILE_CACHE
#endif
/* error messages */
_LIT(KMsgGenericMsgTitle, "TMap : ");
_LIT(KMsgGenericErrorTitle, "TMap : Error :");
_LIT(KMsgHandlerError, "Err : TileMapHandler Allocation!");
_LIT(KWfAntiAlias, "_wfantialias");
_LIT(KEmptyDefaultText, "");
/* macros to display above messages */
#define SHOWMSGWIN(x) CEikonEnv::Static()->InfoWinL(KMsgGenericMsgTitle, x)
#define SHOWMSG(x) CEikonEnv::Static()->InfoMsgWithDuration(x, 1000000)
#define SHOWERRWIN(x) CEikonEnv::Static()->InfoWinL(KMsgGenericErrorTitle, x)
#define SHOWERR(x) CEikonEnv::Static()->InfoMsgWithDuration(x, 2000000)
#define SHOWBUSY(x) CEikonEnv::Static()->BusyMsgL(x)
#define CANCELBUSY() CEikonEnv::Static()->BusyMsgCancel()
#define X_PADDING 5
#define Y_PADDING 5
#define ZOOM_BUTTON_SIZE 0.2
#define COMPASS_POLY_HEIGHT 28 // set by arrowPoly in MapFeatureHolder.cpp
#define INFO_IMAGES_SIZE 24
#define BLUE_BAR_HEIGHT 36
#define GPS_POSITION_POLY_SCALE_IN_3D_VIEW 0.5
#define GPS_POSITION_POLY_SCALE_IN_2D_VIEW 1.0
#define PEDESTRIAN_POSITION_POLY_SCALE_BIGGER_SCREENS 0.024
#define PEDESTRIAN_POSITION_POLY_SCALE_SMALLER_SCREENS 0.032
/* How many drag events do we accept for a single tap? */
#define SINGLE_TAP_MAX_NR_DRAG_EVENTS 10
/* How far away from the original down event do we accept the up event to be to still interpret it as a single tap event?*/
#define SINGLE_TAP_MAX_DISTANCE 15
/* general key codes */
#define KEY_PEN_SHIFT_LEFT EStdKeyLeftShift
#define KEY_ABC_SHIFT_RIGHT EStdKeyRightShift
#define KEY0 0x30
#define KEY1 0x31
#define KEY2 0x32
#define KEY3 0x33
#define KEY4 0x34
#define KEY5 0x35
#define KEY6 0x36
#define KEY7 0x37
#define KEY8 0x38
#define KEY9 0x39
#define KEY_HASH EStdKeyHash
#ifdef __WINS__
#define KEY_STAR EStdKeyNkpAsterisk
#else
#define KEY_STAR 0x2a
#endif
#define KEY_SOFTKEY_LEFT EStdKeyDevice0
#define KEY_SOFTKEY_RIGHT EStdKeyDevice1
#define KEY_POWER EStdKeyDevice2
#define KEY_OK EStdKeyDevice3
#define KEY_MENU EStdKeyApplication0
#define KEY_GREEN_PHONE EStdKeyYes
#define KEY_RED_PHONE EStdKeyNo
#define ASCII_KEY_R TInt('R')
#define ASCII_KEY_T TInt('T')
#define ASCII_KEY_Y TInt('Y')
#define ASCII_KEY_U TInt('U')
#define ASCII_KEY_F TInt('F')
#define ASCII_KEY_G TInt('G')
#define ASCII_KEY_H TInt('H')
#define ASCII_KEY_J TInt('J')
#define ASCII_KEY_V TInt('V')
#define ASCII_KEY_B TInt('B')
#define ASCII_KEY_N TInt('N')
#define ASCII_KEY_M TInt('M')
#define ASCII_KEY_SPACE EStdKeySpace
#ifdef NAV2_CLIENT_SERIES60_V3
#define CURSOR_SCROLLING EMbmWficonsCursor_in_map_scrolling
#define CURSOR_SCROLLING_MASK EMbmWficonsCursor_in_map_scrolling_mask
#define CURSOR_MARKING EMbmWficonsCursor_in_map_marking
#define CURSOR_MARKING_MASK EMbmWficonsCursor_in_map_marking_mask
#else
#define CURSOR_SCROLLING EMbmWficonsS60_browse_up
#define CURSOR_SCROLLING_MASK EMbmWficonsS60_browse_up_m
#define CURSOR_MARKING EMbmWficonsS60_browse_on
#define CURSOR_MARKING_MASK EMbmWficonsS60_browse_on_m
#endif
// Key bindings for movement.
const CVectorMapContainer::key_array_pair_t
CVectorMapContainer::c_keyBindings[] = {
{ KEY2, TileMapKeyHandler::MOVE_UP_KEY },
{ ASCII_KEY_T, TileMapKeyHandler::MOVE_UP_KEY },
{ KEY1, TileMapKeyHandler::ZOOM_OUT_KEY },
{ ASCII_KEY_R, TileMapKeyHandler::ZOOM_OUT_KEY },
{ KEY3, TileMapKeyHandler::ZOOM_IN_KEY },
{ ASCII_KEY_Y, TileMapKeyHandler::ZOOM_IN_KEY },
{ KEY8, TileMapKeyHandler::MOVE_DOWN_KEY },
{ ASCII_KEY_B, TileMapKeyHandler::MOVE_DOWN_KEY },
{ KEY_STAR, TileMapKeyHandler::AUTO_ZOOM_KEY },
{ ASCII_KEY_U, TileMapKeyHandler::AUTO_ZOOM_KEY },
{ KEY4, TileMapKeyHandler::MOVE_LEFT_KEY },
{ ASCII_KEY_F, TileMapKeyHandler::MOVE_LEFT_KEY },
{ KEY6, TileMapKeyHandler::MOVE_RIGHT_KEY },
{ ASCII_KEY_H, TileMapKeyHandler::MOVE_RIGHT_KEY },
{ KEY7, TileMapKeyHandler::RESET_ROTATION_KEY },
{ ASCII_KEY_V, TileMapKeyHandler::RESET_ROTATION_KEY },
#ifndef AUTOMOVE_ON // Can be defined in TileMapKeyHandler.h
//{ KEY1, TileMapKeyHandler::HIGHLIGHT_NEXT_FEATURE_KEY },
//{ ASCII_KEY_R, TileMapKeyHandler::HIGHLIGHT_NEXT_FEATURE_KEY },
// { KEY1, TileMapKeyHandler::ROTATE_LEFT_KEY },
// { KEY3, TileMapKeyHandler::ROTATE_RIGHT_KEY },
//{ KEY3, TileMapKeyHandler::CENTER_MAP_AT_CURSOR_KEY },
//{ ASCII_KEY_Y, TileMapKeyHandler::CENTER_MAP_AT_CURSOR_KEY },
#else
// These keys can be used for automatic movement.
{ KEY1, TileMapKeyHandler::SLOW_TEST_KEY },
{ ASCII_KEY_R, TileMapKeyHandler::SLOW_TEST_KEY },
{ KEY3, TileMapKeyHandler::FAST_TEST_KEY },
{ ASCII_KEY_Y, TileMapKeyHandler::FAST_TEST_KEY },
#endif
// Only for fullscreen
{ EStdKeyDownArrow, TileMapKeyHandler::MOVE_CURSOR_DOWN_KEY },
{ EStdKeyRightArrow, TileMapKeyHandler::MOVE_CURSOR_RIGHT_KEY },
{ EStdKeyLeftArrow, TileMapKeyHandler::MOVE_CURSOR_LEFT_KEY },
{ EStdKeyUpArrow, TileMapKeyHandler::MOVE_CURSOR_UP_KEY },
};
const CVectorMapContainer::key_array_pair_t
CVectorMapContainer::c_landscapeKeyBindings[] = {
{ KEY2, TileMapKeyHandler::MOVE_LEFT_KEY },
{ KEY4, TileMapKeyHandler::MOVE_DOWN_KEY },
{ KEY6, TileMapKeyHandler::MOVE_UP_KEY },
{ KEY8, TileMapKeyHandler::MOVE_RIGHT_KEY },
};
const CVectorMapContainer::key_array_pair_t
CVectorMapContainer::c_portraitKeyBindings[] = {
{ KEY2, TileMapKeyHandler::MOVE_UP_KEY },
{ KEY4, TileMapKeyHandler::MOVE_LEFT_KEY },
{ KEY6, TileMapKeyHandler::MOVE_RIGHT_KEY },
{ KEY8, TileMapKeyHandler::MOVE_DOWN_KEY },
};
class CVectorMapContainerKeyHandlerCallBack
: public TileMapKeyHandlerCallback {
public:
CVectorMapContainerKeyHandlerCallBack(CVectorMapContainer* container) {
m_container = container;
}
~CVectorMapContainerKeyHandlerCallBack() {
m_container = NULL;
}
// Will not repaint if this returns false.
bool keyHandlerCallback() {
if(m_container) {
m_container->CheckFavoriteRedraw();
}
return false;
}
private:
CVectorMapContainer* m_container;
};
/* controls present */
enum {
EMapControl = 0,
#ifdef USE_GLOBE
EGlobeControl,
#endif
//EPedestrianPositionIndicator,
EMapInfoControl,
ETopBorderBitmap,
ENextStreetCtrl,
EPedestrianModeIndicator,
EConBitmap,
EDetourPicture,
ESpeedCamPicture,
EGpsIndicator,
EZoomInPicture,
EZoomOutPicture,
ENumControls
};
enum TTouchScreenControls {
EZoomIn,
EZoomOUt,
ENumTouchScreenControls
};
// Constructor
CVectorMapContainer::CVectorMapContainer( CMapView* aMapView, isab::Log* aLog )
: iLog(aLog), iConstructDone(EFalse), iNrDragEventsInARow(0),
iUpdateCursorAndInfoAtNextRedraw(EFalse)
{
iMapControl = NULL;
iIsConnected = EFalse;
iView = aMapView;
m_timerPeriod = 50000; // Note that this is microseconds.
iInfoTextShown = EFalse;
m_detailedInfoTextShown = false;
iInfoTextPersistant = EFalse;
//iCurrentTurn = ENoPicture;
m_keyHandler = NULL;
m_cursor = NULL;
m_cursorSprite = NULL;
m_highlightCursorSprite = NULL;
m_hideInfoTimerID = MAX_UINT32;
m_mapMover = NULL;
iConStatusPos = TPoint(-1, -1);
}
TInt
CVectorMapContainer::GetLogicalFont(enum TScalableFonts aFontId, TFontSpec& fontSpec)
{
#ifdef NAV2_CLIENT_SERIES60_V3
TInt fontId;
switch (aFontId) {
case EPrimaryLogicalFont:
fontId = EAknLogicalFontPrimaryFont;
break;
case EPrimarySmallLogicalFont:
fontId = EAknLogicalFontPrimarySmallFont;
break;
case ESecondaryLogicalFont:
fontId = EAknLogicalFontSecondaryFont;
break;
case ETitleLogicalFont:
fontId = EAknLogicalFontTitleFont;
break;
case EDigitalLogicalFont:
fontId = EAknLogicalFontDigitalFont;
break;
default:
return 0;
}
const CFbsFont* font = dynamic_cast <const CFbsFont *>(AknLayoutUtils::
FontFromId(fontId));
if (font && font->IsOpenFont()) {
TOpenFontFaceAttrib fontAttrib;
font->GetFaceAttrib(fontAttrib);
fontSpec = TFontSpec(fontAttrib.ShortFullName(), font->HeightInPixels());
return 1;
} else {
return 0;
}
#else
return 0;
#endif
}
void
CVectorMapContainer::setTileMapFonts()
{
// First in every pair is the street-width that triggers the
// change into a larger font.
// The fonts have been tested on a 6600 but without wide streets.
#ifdef NAV2_CLIENT_SERIES60_V3
TFontSpec primaryFont;
TileMapTextSettings::font_pair_t horizontalFont;
if (GetLogicalFont(EPrimaryLogicalFont, primaryFont)) {
TBuf<KMaxTypefaceNameLength+24> typeName;
typeName.Copy(primaryFont.iTypeface.iName);
typeName.Append(KWfAntiAlias);
horizontalFont = TileMapTextSettings::font_pair_t( typeName,
primaryFont.iHeight );
} else {
horizontalFont = TileMapTextSettings::font_pair_t ( "LatinBold19_wfantialias", 19 );
}
TFontSpec primarySmallFont;
TFontSpec secondaryFont;
map<int, TileMapTextSettings::font_pair_t> lineFonts;
TileMapTextSettings::font_pair_t roundRectFont;
TileMapTextSettings::font_pair_t insidePolygonFont;
TileMapTextSettings::font_pair_t copyrightFont;
TileMapTextSettings::font_pair_t progressIndicatorFont;
if (GetLogicalFont(EPrimarySmallLogicalFont, primarySmallFont)) {
lineFonts.insert(
make_pair( 16,
TileMapTextSettings::
font_pair_t( primaryFont.iTypeface.iName, 16 ) ) );
if (GetLogicalFont(EPrimaryLogicalFont, primaryFont)) {
lineFonts.insert(
make_pair( primaryFont.iHeight,
TileMapTextSettings::
font_pair_t( primaryFont.iTypeface.iName,
primaryFont.iHeight ) ) );
} else {
lineFonts.insert(
make_pair( 17,
TileMapTextSettings::
font_pair_t( primaryFont.iTypeface.iName, 17 ) ) );
}
lineFonts.insert(
make_pair( primarySmallFont.iHeight,
TileMapTextSettings::
font_pair_t( primarySmallFont.iTypeface.iName,
primarySmallFont.iHeight ) ) );
roundRectFont = TileMapTextSettings::
font_pair_t( primarySmallFont.iTypeface.iName,
primarySmallFont.iHeight );
insidePolygonFont = TileMapTextSettings::
font_pair_t( primarySmallFont.iTypeface.iName,
primarySmallFont.iHeight );
progressIndicatorFont = TileMapTextSettings::
font_pair_t ( primarySmallFont.iTypeface.iName,
primarySmallFont.iHeight );
if (GetLogicalFont(ESecondaryLogicalFont, secondaryFont)) {
copyrightFont = TileMapTextSettings::
font_pair_t( secondaryFont.iTypeface.iName,
secondaryFont.iHeight );
} else {
copyrightFont = TileMapTextSettings::
font_pair_t( "LatinBold17", 17 );
}
} else {
lineFonts.insert(
make_pair( 16,
TileMapTextSettings::
font_pair_t( "LatinBold16", 16 ) ) );
lineFonts.insert(
make_pair( 17,
TileMapTextSettings::
font_pair_t( "LatinBold17", 17 ) ) );
lineFonts.insert(
make_pair( 19,
TileMapTextSettings::
font_pair_t( "LatinBold19", 19 ) ) );
roundRectFont = TileMapTextSettings::
font_pair_t ( "LatinBold17", 17 );
insidePolygonFont = TileMapTextSettings::
font_pair_t ( "LatinBold17", 17 );
copyrightFont = TileMapTextSettings::
font_pair_t ( "LatinBold17", 17 );
progressIndicatorFont = TileMapTextSettings::
font_pair_t ( "LatinBold17", 17 );
}
#else
map<int, TileMapTextSettings::font_pair_t> lineFonts;
lineFonts.insert(
make_pair( 12,
TileMapTextSettings::font_pair_t( "LatinBold12", 12 ) ) );
lineFonts.insert(
make_pair( 17,
TileMapTextSettings::font_pair_t( "LatinBold17", 17 ) ) );
lineFonts.insert(
make_pair( 19,
TileMapTextSettings::font_pair_t( "LatinBold19", 19 ) ) );
TileMapTextSettings::font_pair_t horizontalFont( "LatinBold12", 12 );
TileMapTextSettings::font_pair_t roundRectFont( "LatinBold12", 12 );
TileMapTextSettings::font_pair_t insidePolygonFont( "LatinBold12", 12 );
TileMapTextSettings::font_pair_t
progressIndicatorFont( "LatinBold17", 17 );
TileMapTextSettings::font_pair_t copyrightFont( "LatinPlain12", 12 );
#endif
iMapControl->setTextSettings(
TileMapTextSettings( lineFonts,
horizontalFont,
roundRectFont,
insidePolygonFont,
progressIndicatorFont,
copyrightFont ) );
}
void
CVectorMapContainer::initKeyHandler()
{
/// Set the keyhandler
m_khCallBack = new CVectorMapContainerKeyHandlerCallBack(this);
// Enable cursor.
#define CURSOR
#ifdef CURSOR
// Get the center point.
MC2Point center( Size().iWidth >> 1, Size().iHeight >> 1 );
m_cursorSprite = SymbianSpriteHolder::createSymbianSpriteHolder(
ControlEnv()->WsSession(),
Window(),
TPoint( center.getX(), center.getY() ),
iView->GetMbmName(),
CURSOR_SCROLLING,
CURSOR_SCROLLING_MASK,
true ); // visible.
m_highlightCursorSprite = SymbianSpriteHolder::createSymbianSpriteHolder(
ControlEnv()->WsSession(),
Window(),
TPoint( center.getX(), center.getY() ),
iView->GetMbmName(),
CURSOR_MARKING,
CURSOR_MARKING_MASK,
false ); // not visible.
m_cursor = new CursorSprite( m_cursorSprite,
m_highlightCursorSprite );
m_keyHandler = new TileCursorKeyHandler(iMapMovingInterface,
iMapDrawingInterface,
iMapControl->getToolkit(),
m_cursor,
m_khCallBack,
this);
m_keyHandler->setStaticCursor(ETrue);
#else
// Just use the static crosshair.
m_keyHandler = new TileMapKeyHandler(iMapMovingInterface,
iMapDrawingInterface,
iMapControl->getToolkit(),
iMapControl,
m_khCallBack);
#endif
// This is probably not necessary.
m_keyHandler->setMapBox( iMapControl->Rect() );
iMapControl->setKeyHandlerAndOwnership( m_keyHandler );
}
void
CVectorMapContainer::ConstructL( const TRect& aRect,
CWayFinderAppUi* aWayFinderUI,
CTileMapControl** aMapControl,
CMapFeatureHolder** aFeatureHolder,
CMapInfoControl** aMapInfoControl,
CVectorMapConnection** aVectorMapConnection,
const TDesC& /*aResourcePath*/)
{
iWayFinderUI = aWayFinderUI;
CreateWindowL();
LogFile::Create();
iNormalRect = aRect;
TInt dpiCorrFact = WFLayoutUtils::CalculateDpiCorrectionFactor();
iXPadding = X_PADDING * dpiCorrFact;
iYPadding = Y_PADDING * dpiCorrFact;
/* If aRequester is NULL, that means that the saved variables */
/* are not set (they are created and deleted together). */
if( *aFeatureHolder == NULL) {
iFeatureHolder = new (ELeave) CMapFeatureHolder();
User::LeaveIfNull(iFeatureHolder);
iFeatureHolder->InitPolygons();
DistancePrintingPolicy::DistanceMode mode =
DistancePrintingPolicy::DistanceMode(iView->GetDistanceMode());
TFontSpec fontSpec;
char* fontName = NULL;
TInt fontSize = 0;
if (GetLogicalFont(ESecondaryLogicalFont, fontSpec)) {
fontName = WFTextUtil::TDesCToUtf8LC(fontSpec.iTypeface.iName);
fontSize = fontSpec.iHeight;
} else {
_LIT(KFontName, "LatinBold16");
fontName = WFTextUtil::TDesCToUtf8LC(KFontName);
fontSize = 16;
}
TInt dpiCorrectionFactor = WFLayoutUtils::CalculateDpiCorrectionFactor();
switch (mode) {
case DistancePrintingPolicy::ModeImperialFeet:
iFeatureHolder->iScaleFeature = new UserDefinedScaleFeature(
fontName, fontSize,
UserDefinedScaleFeature::getMilesFeetSettings(),
dpiCorrectionFactor);
CleanupStack::PopAndDestroy(fontName);
iFeatureHolder->iScaleFeature->rescalePoints();
break;
case DistancePrintingPolicy::ModeImperialYards:
iFeatureHolder->iScaleFeature = new UserDefinedScaleFeature(
fontName, fontSize,
UserDefinedScaleFeature::getMilesYardsSettings(),
dpiCorrectionFactor);
CleanupStack::PopAndDestroy(fontName);
iFeatureHolder->iScaleFeature->rescalePoints();
break;
case DistancePrintingPolicy::ModeMetric:
/* FALLTHROUGH */
default:
iFeatureHolder->iScaleFeature = new UserDefinedScaleFeature(
fontName, fontSize,
UserDefinedScaleFeature::getMeterSettings(),
dpiCorrectionFactor);
CleanupStack::PopAndDestroy(fontName);
iFeatureHolder->iScaleFeature->rescalePoints();
break;
}
// NEW
// Setup the connection where the maps are requested
CVectorMapConnection* vectorMapConnection =
new (ELeave) CVectorMapConnection( aWayFinderUI );
User::LeaveIfNull(vectorMapConnection);
// Create the TileMapControl with the vectormap connection.
iMapControl = CTileMapControl::NewL( vectorMapConnection,
aRect,
iView );
iMapControl->Handler().addEventListener(this);
#ifndef USE_GLOBE
iMapMovingInterface = &iMapControl->Handler();
iMapDrawingInterface = &iMapControl->Handler();
#endif
MapLib* mapLib = iMapControl->getMapLib();
#ifdef ENABLE_3D_OUTLINES
mapLib->setOutlinesIn3dEnabled( true );
#endif
// Set memcache size
mapLib->setMemoryCacheSize( getMemCacheSize() );
// #undef USE_FILE_CACHE
#ifdef USE_FILE_CACHE
// Add file cache
char* cache_path = WFTextUtil::TDesCToUtf8LC(iView->GetWritableAutoMapCachePath());
mapLib->addDiskCache( cache_path,
iView->GetMapCacheSize()*1024*1024 );
CleanupStack::PopAndDestroy( cache_path );
#endif
// END NEW
AddSfdCacheFiles();
// TODO calculate the correctin factor here, the calculation
// should actually be done in WFLayoutUtils but it shold
// be set here.
mapLib->setDPICorrectionFactor(dpiCorrFact);
m_mapInfoControl = new CMapInfoControl();
m_mapInfoControl->ConstructL( aRect );
m_mapInfoControl->SetContainerWindowL(*this);
iMapControl->SetContainerWindowL(*this);
iMapControl->Plotter().setBackgroundColor(255,255,255);
iMapControl->Plotter().clearScreen();
TFontSpec primaryFont;
if (GetLogicalFont(EPrimaryLogicalFont, primaryFont)) {
iMapControl->Plotter().setFont(primaryFont.iTypeface.iName,
primaryFont.iHeight );
} else {
iMapControl->Plotter().setFont(_L("LatinBold19"), 19);
}
iMapControl->Plotter().setPenColor(0,0,64);
TInt topBarHeight =
WFLayoutUtils::CalculateYValueUsingFullScreen(BLUE_BAR_HEIGHT);
TInt nextStreetBarHeight = m_mapInfoControl->getDefaultHeight() + 2;
HBufC* text =
CEikonEnv::Static()->AllocReadResourceLC(R_WAYFINDER_IAP_SEARCH2_MSG);
Rectangle textRectangle =
iMapControl->Plotter().getStringAsRectangle(*text, MC2Point(0, 0));
TInt textHeight = textRectangle.getHeight();
MC2Point point(aRect.Center().iX,
topBarHeight + nextStreetBarHeight + (textHeight/2) + 2);
iMapControl->Plotter().drawText(*text, point );
CleanupStack::PopAndDestroy(text);
*aFeatureHolder = iFeatureHolder;
*aVectorMapConnection = vectorMapConnection;
*aMapControl = iMapControl;
*aMapInfoControl = m_mapInfoControl;
iIsConnected = EFalse;
/* Load favorites. */
// iView->SearchForMapFiles(ETrue);
iView->FavoriteChanged();
iMapControl->Handler().setScreenSize( MC2Point( 176, 208));
if (iView->IsIronVersion()) {
iScale = EScaleGlobe;
} else {
iScale = EScale12;
}
iCenter = TPoint(DefaultVectorMapCenterLon, DefaultVectorMapCenterLat);
} else {
iFeatureHolder = *aFeatureHolder;
iMapControl = *aMapControl;
iMapControl->Handler().addEventListener(this);
#ifndef USE_GLOBE
iMapMovingInterface = &iMapControl->Handler();
iMapDrawingInterface = &iMapControl->Handler();
#endif
m_mapInfoControl = *aMapInfoControl;
iIsConnected = ETrue;
m_mapInfoControl->SetContainerWindowL(*this);
iMapControl->SetContainerWindowL(*this);
iScale = iView->GetScale();
iCenter = iView->GetCenter();
}
// Clear any old info texts.
m_mapInfoControl->setInfoText( NULL );
MapLib* mapLib = iMapControl->getMapLib();
mapLib->setCopyrightPos(MC2Point(iXPadding, aRect.Height() - iYPadding));
mapLib->showCopyright(ETrue);
//Convert to LangTypes::language_t via method in LangTypes.
//Then convert from language_t to const char* via getLangAsIso639.
// mapLib->setLanguageAsISO639(
// LangTypes::getLanguageAsISO639(
// LangTypes::getNavLangAsLanguage(aWayFinderUI->m_languageCode)));
mapLib->setLanguageAsISO639(
LangTypes::getLanguageAsISO639(
LangTypes::getNavLangAsLanguage(iView->GetLanguageCode())));
iMapControl->Handler().setUserDefinedFeatures(iFeatureHolder->GetUDFVector());
#ifdef USE_GLOBE
//The map switcher, which switches between vector map and globe.
//iGlobeComponent = GlobeCreator::createGlobe(*this);
TSize gbSize = iCoeEnv->ScreenDevice()->SizeInPixels();
TRect gbRect = TRect(gbSize);
HBufC* languageCode = iCoeEnv->AllocReadResourceL(
R_WAYFINDER_TWO_CAPITAL_CHARS_LANG_CODE );
HBufC* locationString = iCoeEnv->AllocReadResourceL(
R_EARTH_IM_IN );
char* languageCodeUtf8 = WFTextUtil::TDesCToUtf8L( languageCode->Des() );
char* locationStringUtf8 = WFTextUtil::TDesCToUtf8L( locationString->Des() );
char* pathUtf8 = WFTextUtil::TDesCToUtf8L( iView->GetCommonDataPath() );
iGlobeComponent =
GlobeCreator::createGlobe(*this,
pathUtf8,
gbRect,
locationStringUtf8,
languageCodeUtf8 );
delete locationString;
delete locationStringUtf8;
delete languageCode;
delete languageCodeUtf8;
iGlobeControl = &iGlobeComponent->getControl();
iGlobeControl->MakeVisible(false);
#endif
MapSwitcher::SwitcherNotice tilemapNotice;
#ifdef USE_GLOBE
tilemapNotice.m_scale = iGlobeComponent->getMinScale();
#else
tilemapNotice.m_scale = 2000000000;
#endif
tilemapNotice.m_mapMover = &iMapControl->Handler();
tilemapNotice.m_mapDrawer = &iMapControl->Handler();
tilemapNotice.m_hasStaticCursor = ETrue;
// Set the fonts in the TileMapHandler.
setTileMapFonts();
LayoutVisibilityAdaptersL(aRect, tilemapNotice);
#ifdef USE_GLOBE
MapSwitcher::SwitcherNotice globeNotice;
globeNotice.m_scale = 2000000000; // This ought to be enough.
globeNotice.m_mapMover = &iGlobeComponent->getMapMovingInterface();
globeNotice.m_mapDrawer = &iGlobeComponent->getMapDrawingInterface();
globeNotice.m_hasStaticCursor = true;
globeNotice.m_mapRect = &iGlobeComponent->getMapRectInterface();
iGlobeControlVisAdapter = new VisibilityAdapter<CCoeControl>(iGlobeControl);
iGlobeControlVisAdapter->setVisible(ETrue);
globeNotice.m_visibles.push_back(iGlobeControlVisAdapter);
#endif
vector<MapSwitcher::SwitcherNotice> selectorNotices;
selectorNotices.push_back(tilemapNotice);
#ifdef USE_GLOBE
selectorNotices.push_back(globeNotice);
#endif
iMapSwitcher = new MapSwitcher(selectorNotices, iScale);
#ifdef USE_GLOBE
iMapMovingInterface = iMapSwitcher;
iMapDrawingInterface = iMapSwitcher;
#endif
SetZoom(iScale);
SetCenter(iCenter.iY, iCenter.iX);
/* set to default values */
//deltaDefaults();
#ifdef USE_AUTO_TRACKING_TIMER
/* start the key timer */
m_autoTrackingOnTimer = CPeriodic::NewL(CActive::EPriorityLow);
#endif
/* iTurnPicture = new (ELeave) CGuidePicture( iLog ); */
/* LOGNEW(iTurnPicture, CGuidePicture); */
/* iTurnPicture->ConstructL( TRect( TPoint( 152, 0 ), TSize( 24, 24 ) ), this); */
// Create the keyhandler and the cursor.
initKeyHandler();
//Needed here since the keyHandler needs the mapSwitcher
//and the mapSwitcher needs the keyHandler.
iMapSwitcher->setCursorHandler(m_keyHandler);
iCursorVisAdapter->setControl(m_keyHandler);
m_mapMover = new MapMover( m_keyHandler,
iMapMovingInterface,
iFeatureHolder->iPositionPoly,
this );
m_mapMover->setGpsFeature( iFeatureHolder->iDarkShadePoly );
m_mapMover->setGpsFeature( iFeatureHolder->iLightshadePoly );
m_mapMover->setGpsFeature( iFeatureHolder->iPedPositionPoly );
m_mapMover->setGpsFeature( iFeatureHolder->iPedPositionFillPoly );
m_mapMover->setTrackingPoint( getTrackingPoint());
m_mapMover->setNonTrackingPoint( getNonTrackingPoint() );
/* set this control to get keyboard focus */
SetFocus(ETrue);
iMapControl->SetFocus( ETrue );
updateCursorVisibility();
ShowNorthArrow( !iView->MapAsPedestrianNavigation() );
// Insert the key bindings into the map
int nbrBindings = sizeof(c_keyBindings) / sizeof(c_keyBindings[0]);
for ( int i = nbrBindings - 1; i >= 0; --i ) {
m_keyMap.insert( make_pair( c_keyBindings[i].first,
c_keyBindings[i].second ) );
}
// Please to respond to my clickings.
EnableDragEvents();
if (iView->Get3dMode()) {
// No scale when in 3d mode
ShowScale( EFalse );
} else {
ShowScale( ETrue );
}
TInt& oldDpiCorrFact = iView->GetDpiCorrFact();
if(dpiCorrFact != oldDpiCorrFact) {
oldDpiCorrFact = dpiCorrFact;
mapLib->setDPICorrectionFactor(dpiCorrFact);
iFeatureHolder->RescalePolygons();
}
#ifdef NAV2_CLIENT_SERIES60_V5
iLongTapDetector = CAknLongTapDetector::NewL( this );
#endif
SetRect(aRect);
ActivateL();
UpdateRepaint();
iConstructDone = ETrue;
}
void CVectorMapContainer::LayoutVisibilityAdaptersL(const TRect& aRect,
MapSwitcher::SwitcherNotice& aTilemapNotice)
{
iMapControlVisAdapter = new VisibilityAdapter<CTileMapControl>(iMapControl);
iMapControlVisAdapter->setVisible(ETrue);
aTilemapNotice.m_visibles.push_back(iMapControlVisAdapter);
// Create the cursor
iCursorVisAdapter =
new CursorVisibilityAdapter(m_keyHandler);
// If map is in 3d mode, the cursor should not be visible
iCursorVisAdapter->setVisible(!(iView->MapAsGeneralNavigation() &&
iView->Get3dMode()));
aTilemapNotice.m_visibles.push_back(iCursorVisAdapter);
// Create the map border bar
TInt borderBarHeight =
WFLayoutUtils::CalculateYValueUsingFullScreen(BLUE_BAR_HEIGHT);
TRect borderBarRect(TPoint(aRect.iTl.iX, aRect.iTl.iY),
TSize(aRect.Width(), borderBarHeight));
iTopBorderVisAdapter =
new VisibilityAdapter<CMapTopBorderBar>
(CMapTopBorderBar::NewL(this, borderBarRect,
iView->GetMbmName(), KRgbBlack, TRgb(KForegroundTextColorNightRed,
KForegroundTextColorNightGreen,
KForegroundTextColorNightBlue)));
// Set the background color
iTopBorderVisAdapter->getControl()->SetBackgroundColors(TRgb(0x00ffffff, 170), TRgb(0x00424542, 220));
// Set the divider image
iTopBorderVisAdapter->getControl()->SetDividerImageL(EMbmWficonsTop_bar_divider,
EMbmWficonsTop_bar_divider_mask);
iTopBorderVisAdapter->setVisible(EFalse);
aTilemapNotice.m_visibles.push_back(iTopBorderVisAdapter);
// Create the next street label
TInt nextStreetCtrlHeight = m_mapInfoControl->getDefaultHeight() + 2;
TRect nextStreetCtrlRect(TPoint(aRect.iTl.iX, borderBarRect.iBr.iY),
TSize(aRect.Width(), nextStreetCtrlHeight));
iNextStreetVisAdapter =
new VisibilityAdapter<CBackGroundTextContainer>
(CBackGroundTextContainer::NewL(this,
nextStreetCtrlRect,
KEmptyDefaultText,
TRgb(0x00ffffff, 170),
TRgb(0x00424542, 220),
KRgbBlack,
TRgb(KForegroundTextColorNightRed,
KForegroundTextColorNightGreen,
KForegroundTextColorNightBlue)));
iNextStreetVisAdapter->getControl()->SetBorderEdges(
CBackGroundTextContainer::ETopEdge | CBackGroundTextContainer::EBottomEdge);
iNextStreetVisAdapter->setVisible(EFalse);
aTilemapNotice.m_visibles.push_back(iNextStreetVisAdapter);
// Initial setup of positions
TSize imgSize = WFLayoutUtils::CalculateSizeUsingMin(INFO_IMAGES_SIZE);
TPoint imgRPos = borderBarRect.iBr;
TPoint imgLPos = borderBarRect.iTl;
// Create the detour image
imgRPos.iX -= (imgSize.iWidth + WFLayoutUtils::CalculateXValue(X_PADDING));
imgRPos.iY = nextStreetCtrlRect.iBr.iY +
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
iDetourPictureVisAdapter = new VisibilityAdapter<CImageHandler>
(CImageHandler::NewL(TRect(imgRPos, imgSize)));
iDetourPictureVisAdapter->getControl()->SetShow(EFalse);
iDetourPictureVisAdapter->getControl()->
CreateIconL(iView->GetMbmName(),
EMbmWficonsDetour_square,
EMbmWficonsDetour_square_mask,
EAspectRatioPreservedAndUnusedSpaceRemoved);
// Create the speedcam image
imgRPos.iY += imgSize.iHeight +
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
iSpeedCamPictureVisAdapter = new VisibilityAdapter<CImageHandler>
(CImageHandler::NewL(TRect(imgRPos, imgSize)));
iSpeedCamPictureVisAdapter->getControl()->SetShow(EFalse);
iSpeedCamPictureVisAdapter->getControl()->
CreateIconL(iView->GetMbmName(),
EMbmWficonsSpeedcamera_square,
EMbmWficonsSpeedcamera_square,
EAspectRatioPreservedAndUnusedSpaceRemoved);
// Create the gps indicator image
iGpsIndicatorVisAdapter = new VisibilityAdapter<CImageHandler>
(CImageHandler::NewL(TRect(imgRPos, imgSize)));
iGpsIndicatorVisAdapter->getControl()->SetShow(EFalse);
PositionRightEdgeFloatingControls();
// Create the pedestrian indicator image
if (iNextStreetVisAdapter->isVisible()) {
imgLPos.iY = nextStreetCtrlRect.iBr.iY +
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
} else {
imgLPos.iY = WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
}
if (iFeatureHolder->iCompassPolyShown) {
// If the compass is shown center the image below the compass.
TInt dpiCorrectionFactor = WFLayoutUtils::CalculateDpiCorrectionFactor();
TInt xPos = (COMPASS_POLY_HEIGHT / 2) * dpiCorrectionFactor;
xPos += WFLayoutUtils::CalculateXValue(X_PADDING);
xPos -= imgSize.iWidth / 2;
imgLPos.iX += xPos;
imgLPos.iY +=
COMPASS_POLY_HEIGHT * dpiCorrectionFactor +
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
} else {
// If compass is not shown we position the images with padding instead.
imgLPos.iX += WFLayoutUtils::CalculateXValue(X_PADDING);
}
iPedestrianModeVisAdapter = new VisibilityAdapter<CImageHandler>
(CImageHandler::NewL(TRect(imgLPos, imgSize)));
iPedestrianModeVisAdapter->getControl()->
CreateIconL(iView->GetMbmName(),
EMbmWficonsPedestrian_mode,
EMbmWficonsPedestrian_mode_mask,
EAspectRatioPreservedAndUnusedSpaceRemoved);
iPedestrianModeVisAdapter->setVisible(iView->MapAsPedestrianNavigation());
aTilemapNotice.m_visibles.push_back(iPedestrianModeVisAdapter);
if (WFLayoutUtils::IsTouchScreen()) {
// Create the zoom buttons, the will be given the correct size and position
// in SizeChanged function.
iZoomInPictureVisAdapter = new VisibilityAdapter<CImageHandler>
(CImageHandler::NewL(TRect(0, 0, 0, 0)));
iZoomInPictureVisAdapter->getControl()->SetShow(ETrue);
iZoomInPictureVisAdapter->getControl()->CreateIconL(iView->GetMbmName(),
EMbmWficonsZoom_in,
EMbmWficonsZoom_in_mask);
iZoomOutPictureVisAdapter = new VisibilityAdapter<CImageHandler>
(CImageHandler::NewL(TRect(0, 0, 0, 0)));
iZoomOutPictureVisAdapter->getControl()->SetShow(ETrue);
iZoomOutPictureVisAdapter->getControl()->CreateIconL(iView->GetMbmName(),
EMbmWficonsZoom_out,
EMbmWficonsZoom_out_mask);
iZoomInPictureVisAdapter->setVisible(!iView->Get3dMode());
aTilemapNotice.m_visibles.push_back(iZoomInPictureVisAdapter);
iZoomOutPictureVisAdapter->setVisible(!iView->Get3dMode());
aTilemapNotice.m_visibles.push_back(iZoomOutPictureVisAdapter);
}
CBitmapControl* conBitmap = CBitmapControl::NewL(this, TPoint(0,0), NULL);
iConStatusVisAdapter =
new VisibilityAdapter<CBitmapControl>(conBitmap);
iDetourPictureVisAdapter->setVisible(EFalse);
aTilemapNotice.m_visibles.push_back(iDetourPictureVisAdapter);
iSpeedCamPictureVisAdapter->setVisible(EFalse);
aTilemapNotice.m_visibles.push_back(iSpeedCamPictureVisAdapter);
iConStatusVisAdapter->setVisible(EFalse);
aTilemapNotice.m_visibles.push_back(iConStatusVisAdapter);
iGpsIndicatorVisAdapter->setVisible(EFalse);
aTilemapNotice.m_visibles.push_back(iGpsIndicatorVisAdapter);
aTilemapNotice.m_mapRect = iMapControl;
}
// Destructor
CVectorMapContainer::~CVectorMapContainer()
{
// Cancel the hide info timer.
if ( iMapControl != NULL && m_hideInfoTimerID != MAX_UINT32 ) {
iMapControl->getToolkit()->cancelTimer( this, m_hideInfoTimerID );
}
ReleaseMapControlDependencies();
// Keyhandler is deleted by TileMapControl.
// delete m_keyHandler;
// Stop the timer and reset all keys that may otherwise be repeated
StopKeyHandler();
delete m_mapMover;
#ifdef USE_AUTO_TRACKING_TIMER
if ( m_autoTrackingOnTimer->IsActive() ) {
m_autoTrackingOnTimer->Cancel();
}
delete m_autoTrackingOnTimer;
m_autoTrackingOnTimer = NULL;
#endif
iMapControl = NULL;
/* LOGDEL(iTurnPicture); */
/* delete iTurnPicture; */
/* iTurnPicture = NULL; */
// Set the callback of the key handler to NULL so it does not
// attempt to use it, since it is deleted here below
m_keyHandler->cancelTileMapKeyHandlerCallback();
delete m_khCallBack;
m_khCallBack = NULL;
if (iTopBorderVisAdapter) {
delete iTopBorderVisAdapter->getControl();
delete iTopBorderVisAdapter;
iTopBorderVisAdapter = NULL;
}
if (iNextStreetVisAdapter) {
delete iNextStreetVisAdapter->getControl();
delete iNextStreetVisAdapter;
iNextStreetVisAdapter = NULL;
}
if (iConStatusVisAdapter) {
delete iConStatusVisAdapter->getControl();
delete iConStatusVisAdapter;
iConStatusVisAdapter = NULL;
}
if (iDetourPictureVisAdapter) {
delete iDetourPictureVisAdapter->getControl();
delete iDetourPictureVisAdapter;
iDetourPictureVisAdapter = NULL;
}
if (iSpeedCamPictureVisAdapter) {
delete iSpeedCamPictureVisAdapter->getControl();
delete iSpeedCamPictureVisAdapter;
iSpeedCamPictureVisAdapter = NULL;
}
if (iZoomInPictureVisAdapter) {
delete iZoomInPictureVisAdapter->getControl();
delete iZoomInPictureVisAdapter;
iZoomInPictureVisAdapter = NULL;
}
if (iZoomOutPictureVisAdapter) {
delete iZoomOutPictureVisAdapter->getControl();
delete iZoomOutPictureVisAdapter;
iZoomOutPictureVisAdapter = NULL;
}
delete iCursorVisAdapter;
delete iMapControlVisAdapter;
delete iGlobeControlVisAdapter;
delete iGlobeComponent;
delete iMapSwitcher;
delete m_cursorSprite;
delete m_highlightCursorSprite;
delete m_cursor;
#ifdef NAV2_CLIENT_SERIES60_V5
delete iLongTapDetector;
delete iPopUpMenu;
#endif
}
TBool CVectorMapContainer::ConstructDone()
{
return iConstructDone;
}
void CVectorMapContainer::PictureError( TInt /*aError*/ )
{
/* iTurnPicture->SetShow( EFalse ); */
/* iView->PictureError( aError ); */
}
void CVectorMapContainer::ScalingDone()
{
DrawNow();
}
void CVectorMapContainer::SizeChanged()
{
TRect rect = Rect();
TInt dpiCorrFact = WFLayoutUtils::CalculateDpiCorrectionFactor();
iXPadding = X_PADDING * dpiCorrFact;
iYPadding = Y_PADDING * dpiCorrFact;
// Recalc the bluebar rect
TInt borderBarHeight =
WFLayoutUtils::CalculateYValueUsingFullScreen(BLUE_BAR_HEIGHT);
TRect borderBarRect(TPoint(rect.iTl.iX, rect.iTl.iY),
TSize(rect.Width(), borderBarHeight));
iTopBorderVisAdapter->getControl()->SetRect(borderBarRect);
if (iMapControl && m_mapInfoControl) {
TPoint mapPos(rect.iTl);
MapLib* mapLib = iMapControl->getMapLib();
mapLib->setCopyrightPos(MC2Point(5, rect.Height() - 5 - mapPos.iY));
iMapControl->SetSize(TSize(rect.Width(), (rect.Height()-mapPos.iY)));
iMapControl->SetPosition(mapPos);
m_mapInfoControl->SetSize(TSize(rect.Width(),
(rect.Height()-mapPos.iY)));
m_mapInfoControl->SetPosition(mapPos);
}
// Use the same height for the next street bar as the map info control.
TInt nextStreetCtrlHeight = m_mapInfoControl->getDefaultHeight() + 2;
TRect nextStreetCtrlRect(TPoint(rect.iTl.iX, borderBarRect.iBr.iY),
TSize(rect.Width(), nextStreetCtrlHeight));
iNextStreetVisAdapter->getControl()->SetRect(nextStreetCtrlRect);
ResetNorthArrowPos();
// Initial setup of positions
TSize imgSize = WFLayoutUtils::CalculateSizeUsingMin(INFO_IMAGES_SIZE);
TPoint imgLPos = borderBarRect.iTl;
PositionRightEdgeFloatingControls();
// Position pedestrian indicator image
if (iNextStreetVisAdapter->isVisible()) {
imgLPos.iY = nextStreetCtrlRect.iBr.iY +
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
} else {
imgLPos.iY = WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
}
if (iFeatureHolder->iCompassPolyShown) {
// If the compass is shown center the image below the compass.
TInt dpiCorrectionFactor = WFLayoutUtils::CalculateDpiCorrectionFactor();
TInt xPos = (COMPASS_POLY_HEIGHT / 2) * dpiCorrectionFactor;
xPos += WFLayoutUtils::CalculateXValue(X_PADDING);
xPos -= imgSize.iWidth / 2;
imgLPos.iX += xPos;
imgLPos.iY +=
COMPASS_POLY_HEIGHT * dpiCorrectionFactor +
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
} else {
// If compass is not shown we position the images with padding instead.
imgLPos.iX += WFLayoutUtils::CalculateXValue(X_PADDING);
}
TRect newRect = TRect(imgLPos, imgSize);
iPedestrianModeVisAdapter->getControl()->SetImageRect(newRect);
if (WFLayoutUtils::IsTouchScreen()) {
// Calc the height of the zoom button, the image should be a square so
// the height is equal to the width
TInt imgHeight =
WFLayoutUtils::CalculateUnitsUsingMin(float(ZOOM_BUTTON_SIZE));
// Get the default height of the blue info note, one line height.
TInt blueInfoHeight = m_mapInfoControl->getDefaultHeight();
// Calc the top left of the zoom in picture. It should be above the blue info
// not with some padding in between.
TPoint topLeft(iXPadding, rect.iBr.iY - (blueInfoHeight + iYPadding + imgHeight));
// Set the postion and size of the zoom out button
iZoomOutPictureVisAdapter->getControl()->SetImageRect(TRect(topLeft, TSize(imgHeight, imgHeight)));
// the top left x position for the zoom out button should be on the right side of the
// screen
topLeft.iX = WFLayoutUtils::GetMainPaneRect().iBr.iX - ((iXPadding + imgHeight));
// Set the postion and size of the zoom in button
iZoomInPictureVisAdapter->getControl()->SetImageRect(TRect(topLeft, TSize(imgHeight, imgHeight)));
}
// Will trigger a repostioning of the con status image
iConStatusPos.iY = -1;
bool northUp = (iView->GetTrackingType() != ERotating);
if (iMapControl && m_keyHandler && m_mapMover) {
#ifdef USE_GLOBE
iMapSwitcher->updateSize();
#else
PixelBox mapBox(iMapControl->Rect());
m_keyHandler->setMapBox(mapBox);
#endif
iMapDrawingInterface->requestRepaint();
m_mapMover->statusChanged(getTrackingPoint(),
getNonTrackingPoint(true),
iView->IsTracking(),
northUp,
false );
updateCursorVisibility();
}
if (iView->Get3dMode()) {
//we have different scaling of the position polygon when in 3d view and when not.
if(iFeatureHolder) {
iFeatureHolder->SetPositionPolyScale(float(GPS_POSITION_POLY_SCALE_IN_3D_VIEW));
}
// No scale when in 3d mode
ShowScale( EFalse );
} else {
if(iFeatureHolder) {
iFeatureHolder->SetPositionPolyScale(float(GPS_POSITION_POLY_SCALE_IN_2D_VIEW));
}
ShowScale( ETrue );
}
if(iFeatureHolder) {
TSize screenSize;
AknLayoutUtils::LayoutMetricsSize(AknLayoutUtils::EScreen, screenSize);
if(screenSize.iWidth <= 320 || screenSize.iHeight <= 320) {
iFeatureHolder->SetPedestrianPositionPolyScale(float(PEDESTRIAN_POSITION_POLY_SCALE_SMALLER_SCREENS));
}
else {
iFeatureHolder->SetPedestrianPositionPolyScale(float(PEDESTRIAN_POSITION_POLY_SCALE_BIGGER_SCREENS));
}
}
}
bool
CVectorMapContainer::getCursorVisibility() const
{
bool visible =
IsFocused() &&
!(iView->IsTracking() && m_mapMover->gotValidGpsCoord()) &&
!m_detailedInfoTextShown &&
!(iView->MapAsGeneralNavigation() && iView->Get3dMode());
return visible;
}
void
CVectorMapContainer::updateCursorVisibility()
{
bool visible = getCursorVisibility();
iCursorVisAdapter->setVisible(visible);
}
void
CVectorMapContainer::notifyInfoNamesAvailable()
{
// Only get the feature name if the map didn't move since last call
// to getInfo.
const char* feature = m_mapMover->getInfo( true );
setInfoText( feature );
}
MC2Point
CVectorMapContainer::getActivePoint() const
{
if(iUsingLongPressPosition) {
return iLongPressPosition;
}
else {
return m_mapMover->getPoint();
}
}
void
CVectorMapContainer::FocusChanged( TDrawNow /* aDrawNow */ )
{
/* check if keys should be handled */
if(!IsFocused()) {
m_mapMover->stopKeyHandling();
}
updateCursorVisibility();
}
TInt CVectorMapContainer::CountComponentControls() const
{
if (WFLayoutUtils::IsTouchScreen()) {
return ENumControls;
}
return ENumControls - ENumTouchScreenControls;
}
CCoeControl* CVectorMapContainer::ComponentControl(TInt aIndex) const
{
switch ( aIndex )
{
case(EMapControl):
return iMapControl;
#ifdef USE_GLOBE
case(EGlobeControl):
return iGlobeControl;
#endif
case(EMapInfoControl):
return m_mapInfoControl;
case ETopBorderBitmap:
return iTopBorderVisAdapter->getControl();
case ENextStreetCtrl:
return iNextStreetVisAdapter->getControl();
case EPedestrianModeIndicator:
return iPedestrianModeVisAdapter->getControl();
case EConBitmap:
return iConStatusVisAdapter->getControl();
case EDetourPicture:
return iDetourPictureVisAdapter->getControl();
case ESpeedCamPicture:
return iSpeedCamPictureVisAdapter->getControl();
case EZoomInPicture:
return iZoomInPictureVisAdapter->getControl();
case EZoomOutPicture:
return iZoomOutPictureVisAdapter->getControl();
case EGpsIndicator:
return iGpsIndicatorVisAdapter->getControl();
default: break;
}
return NULL;
}
void CVectorMapContainer::Draw(const TRect& /*aRect*/) const
{
return;
}
void CVectorMapContainer::HandleControlEventL(
CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
{
}
static inline TileMapKeyHandler::kind_of_press_t
translateKeyEventType( TEventCode aType )
{
switch ( aType ) {
case EEventKeyDown:
return TileMapKeyHandler::KEY_DOWN_EVENT;
case EEventKeyUp:
return TileMapKeyHandler::KEY_UP_EVENT;
case EEventKey:
return TileMapKeyHandler::KEY_REPEAT_EVENT;
default:
return TileMapKeyHandler::KEY_UNKNOWN_EVENT;
}
return TileMapKeyHandler::KEY_UNKNOWN_EVENT;
}
static inline TileMapKeyHandler::kind_of_press_t
translatePointerEventType( const TPointerEvent::TType aType )
{
switch ( aType ) {
case TPointerEvent::EButton1Down:
case TPointerEvent::EButton2Down:
case TPointerEvent::EButton3Down:
return TileMapKeyHandler::KEY_DOWN_EVENT;
break;
case TPointerEvent::EButton1Up:
case TPointerEvent::EButton2Up:
case TPointerEvent::EButton3Up:
return TileMapKeyHandler::KEY_UP_EVENT;
break;
case TPointerEvent::EDrag:
return TileMapKeyHandler::KEY_REPEAT_EVENT;
break;
default:
return TileMapKeyHandler::KEY_UNKNOWN_EVENT;
}
return TileMapKeyHandler::KEY_UNKNOWN_EVENT;
}
void
CVectorMapContainer::HandlePointerEventL( const TPointerEvent& aPointerEvent )
{
iUsingLongPressPosition = EFalse;
if (iView->Get3dMode()) {
// if we're in 3d mode we dont accept pointer events.
return;
}
const char* info = NULL;
if (aPointerEvent.iType == TPointerEvent::EButton1Down &&
WFLayoutUtils::IsTouchScreen()) {
iView->SetTracking(EFalse);
if (iZoomInPictureVisAdapter->getControl()->GetRect().Contains(aPointerEvent.iPosition)) {
// User pressed on zoom in image
iOnZoomIn = ETrue;
iOnZoomOut = EFalse;
m_mapMover->handleKeyEvent(TileMapKeyHandler::ZOOM_IN_KEY,
TileMapKeyHandler::KEY_DOWN_EVENT,
info);
} else if (iZoomOutPictureVisAdapter->getControl()->GetRect().Contains(aPointerEvent.iPosition)) {
// User pressed on zoom out image
iOnZoomOut = ETrue;
iOnZoomIn = EFalse;
m_mapMover->handleKeyEvent( TileMapKeyHandler::ZOOM_OUT_KEY,
TileMapKeyHandler::KEY_DOWN_EVENT,
info );
}
} else if (aPointerEvent.iType == TPointerEvent::EDrag) {
if(iOnZoomIn && !iZoomInPictureVisAdapter->getControl()->
GetRect().Contains(aPointerEvent.iPosition)) {
// If the user has clicked on the zoom in button but have
// draged the finger or pen away from the image, send
// key up event to the map mover. This results in stop
// zooming.
m_mapMover->handleKeyEvent(TileMapKeyHandler::ZOOM_IN_KEY,
TileMapKeyHandler::KEY_UP_EVENT,
info);
return;
} else if (iOnZoomOut && !iZoomOutPictureVisAdapter->
getControl()->GetRect().Contains(aPointerEvent.iPosition)) {
// If the user has clicked on the zoom out button but have
// draged the finger or pen away from the image, send
// key up event to the map mover. This results in stop
// zooming.
m_mapMover->handleKeyEvent(TileMapKeyHandler::ZOOM_OUT_KEY,
TileMapKeyHandler::KEY_UP_EVENT,
info);
return;
}
}
if (!iOnZoomIn && !iOnZoomOut) {
MC2Point pos( aPointerEvent.iPosition );
TileMapKeyHandler::kind_of_press_t upOrDown =
translatePointerEventType(aPointerEvent.iType);
// The user doesn't do a "perfect" tap on a phone so we check the distance from
// the original down event as well as the number of drag events between the down
// and up event to decide if it shall be interpreted as a normal drag or a single tap.
TBool withinSingleTapRange = EFalse;
TSize distance(abs(iLastPointerDownEventPosition.iX - pos.iX),
abs(iLastPointerDownEventPosition.iY - pos.iY));
if(distance.iHeight < SINGLE_TAP_MAX_DISTANCE && distance.iWidth < SINGLE_TAP_MAX_DISTANCE) {
withinSingleTapRange = ETrue;
}
if(upOrDown == TileMapKeyHandler::KEY_UP_EVENT &&
iNrDragEventsInARow <= SINGLE_TAP_MAX_NR_DRAG_EVENTS &&
withinSingleTapRange) {
m_mapMover->handleKeyEvent(TileMapKeyHandler::CENTER_MAP_AT_POSITION_KEY,
translatePointerEventType( aPointerEvent.iType ),
info,
&pos );
iUpdateCursorAndInfoAtNextRedraw = ETrue;
}
else {
m_mapMover->handleKeyEvent(TileMapKeyHandler::DRAG_TO,
translatePointerEventType( aPointerEvent.iType ),
info,
&pos );
}
if (aPointerEvent.iType == TPointerEvent::EDrag) {
iNrDragEventsInARow++;
}
else {
iNrDragEventsInARow = 0;
if(upOrDown == TileMapKeyHandler::KEY_DOWN_EVENT) {
iLastPointerDownEventPosition = aPointerEvent.iPosition;
}
}
#ifdef NAV2_CLIENT_SERIES60_V5
if (!iView->MapAsGeneralNavigation() && AknLayoutUtils::PenEnabled()) {
iLongTapDetector->PointerEventL( aPointerEvent );
}
#endif
}
if (iOnZoomIn || iOnZoomOut) {
// If the cell position is being displayed it may need to be resized
// if we're zooming in or out.
UpdateCellIdIconDimensions();
}
if (aPointerEvent.iType == TPointerEvent::EButton1Up) {
if (iOnZoomIn) {
// User has clicked on zoom in and now stopped pressing,
// send key up to the map mover
m_mapMover->handleKeyEvent(TileMapKeyHandler::ZOOM_IN_KEY,
TileMapKeyHandler::KEY_UP_EVENT,
info);
iOnZoomIn = EFalse;
} else if (iOnZoomOut) {
// User has clicked on zoom out and now stopped pressing,
// send key up to the map mover
m_mapMover->handleKeyEvent(TileMapKeyHandler::ZOOM_OUT_KEY,
TileMapKeyHandler::KEY_UP_EVENT,
info);
iOnZoomOut = EFalse;
}
}
if ( info != NULL && ! iInfoTextPersistant ) {
setInfoText( info, NULL, NULL, EFalse, 3000 );
}
}
void CVectorMapContainer::HandleLongTapEventL( const TPoint& aPenEventLocation,
const TPoint& aPenEventScreenLocation )
{
#ifdef NAV2_CLIENT_SERIES60_V5
if ( !iPopUpMenu ) {
// Launch stylus popup menu here
// Construct the menu from resources
iPopUpMenu = CAknStylusPopUpMenu::NewL( iView, aPenEventScreenLocation, NULL );
TResourceReader reader;
iCoeEnv->CreateResourceReaderLC( reader , R_MAP_POP_UP_STYLUS_MENU );
iPopUpMenu->ConstructFromResourceL( reader );
CleanupStack::PopAndDestroy(); // reader
}
iPopUpMenu->SetPosition( aPenEventScreenLocation );
iLongPressPosition = aPenEventLocation;
iUsingLongPressPosition = ETrue;
// Hide/show set as origin depending on the view state.
iPopUpMenu->SetItemDimmed(EWayFinderCmdMapSetOrigin, !iView->SettingOrigin());
// Hide/show set as dest depending on the view state.
iPopUpMenu->SetItemDimmed(EWayFinderCmdMapSetDestination, !iView->SettingDestination());
// Hide/show navigate to depending on the view state, should not be visible when
// set as orig or set as dest is true.
iPopUpMenu->SetItemDimmed(EWayFinderCmdMapRouteTo, (iView->SettingOrigin() ||
iView->SettingDestination()));
iPopUpMenu->ShowMenu();
#endif
}
// key event handling method
TKeyResponse CVectorMapContainer::OfferKeyEventL(const TKeyEvent& aKeyEvent,
TEventCode aType)
{
/**
* Interpolation related debug keys
*/
// if( aType == EEventKeyUp &&
// ( aKeyEvent.iScanCode == '1' || aKeyEvent.iScanCode == '3' ) ) {
// switch( aKeyEvent.iScanCode ) {
// case '1':
// iMapControl->getMapLib()->getInterpolationHintConsumer()->
// cycleConfigurationBackward();
// break;
// case '3':
// iMapControl->getMapLib()->getInterpolationHintConsumer()->
// cycleConfigurationForward();
// break;
// }
// return EKeyWasConsumed;
// }
if (iWayFinderUI && iWayFinderUI->IsWaitingForRoute())
{
return EKeyWasConsumed;
}
/* if not a key event, return */
if(aType != EEventKeyUp && aType != EEventKeyDown && aType != EEventKey) {
return(EKeyWasNotConsumed);
}
if (iView->DontHandleAsterisk() && aKeyEvent.iScanCode == KEY_STAR) {
return EKeyWasNotConsumed;
}
// Turn off the autotracking timer
// Should only be done before starting the timer.
/*
if ( m_autoTrackingOnTimer->IsActive() ) {
m_autoTrackingOnTimer->Cancel();
}
*/
if (iView->Get3dMode() && !(aType == EEventKeyDown && aKeyEvent.iScanCode == KEY9)) {
return EKeyWasNotConsumed;
}
if (m_detailedInfoTextShown) {
/* The info text is shown. Check for softkey actions. */
if (aType == EEventKeyDown) {
if (aKeyEvent.iScanCode == KEY_SOFTKEY_RIGHT ||
aKeyEvent.iScanCode == EStdKeyDevice3) {
return (EKeyWasConsumed);
} else if (aKeyEvent.iScanCode == KEY_SOFTKEY_LEFT) {
/* Back. */
return (EKeyWasConsumed);
}
} else if (aType == EEventKeyUp) {
if (aKeyEvent.iScanCode == KEY_SOFTKEY_RIGHT ||
aKeyEvent.iScanCode == EStdKeyDevice3 ||
aKeyEvent.iScanCode == KEY_SOFTKEY_LEFT) {
return (EKeyWasConsumed);
}
} else if (aType == EEventKey) {
if (aKeyEvent.iScanCode == KEY_SOFTKEY_LEFT ||
aKeyEvent.iScanCode == EStdKeyDevice3) {
//iView->HandleCommandL(EWayFinderCmdMapShowInfo);
//Old way of doing it in a blocking popup dialog.
GetFeatureName();
ShowDetailedFeatureInfo(ETrue);
return (EKeyWasConsumed);
} else if (aKeyEvent.iScanCode == KEY_SOFTKEY_RIGHT) {
setInfoText(NULL);
return (EKeyWasConsumed);
}
}
}
if( iView->Get3dMode() ) {
if( aKeyEvent.iScanCode == KEY1 || aKeyEvent.iScanCode == ASCII_KEY_R ) {
if( aType != EEventKeyDown ) {
return EKeyWasNotConsumed;
} else {
ZoomIn3d();
return EKeyWasConsumed;
}
} else if( aKeyEvent.iScanCode == KEY3 || aKeyEvent.iScanCode == ASCII_KEY_Y ) {
if( aType != EEventKeyDown ) {
return EKeyWasNotConsumed;
} else {
ZoomOut3d();
return EKeyWasConsumed;
}
}
}
// Check for movement keys and call the keyhandler if appropriate.
map<int,int>::const_iterator it = m_keyMap.find( aKeyEvent.iScanCode );
if ( it != m_keyMap.end() ) {
if (it->second == TileMapKeyHandler::ZOOM_IN_KEY ||
it->second == TileMapKeyHandler::ZOOM_OUT_KEY) {
// If zooming in or out we need to update the size.
UpdateCellIdIconDimensions();
}
const char* info = NULL;
// Use the new call to the keyhandle once maplib is imported to ext-cvs.
bool handled =
m_mapMover->handleKeyEvent( TileMapKeyHandler::key_t( it->second ),
translateKeyEventType( aType ),
info );
// The key handler will return true if the key was consumed by it.
if ( handled || info != NULL ) {
if ( ! iInfoTextPersistant ) {
setInfoText( info, NULL, NULL, EFalse, 3000 );
}
}
if ( handled ) {
iView->SetTracking(EFalse);
#ifdef USE_AUTO_TRACKING_TIMER
if (aType == EEventKeyUp) {
/* Make sure the auto tracking on feature works. */
if ( !iView->IsTracking() &&
iView->IsGpsAllowed()) {
/* Set timer to reenable tracking. */
if ( m_autoTrackingOnTimer->IsActive() ) {
m_autoTrackingOnTimer->Cancel();
}
m_autoTrackingOnTimer->Start(8000000, 8000000 ,
TCallBack(KeyCallback,this));
}
}
#endif
return EKeyWasConsumed;
}
}
/* set the appropriate key in the framework array */
if(aType == EEventKeyDown) {
TBool removeInfoText = EFalse;
// if movement, then do the first one right now
if(aKeyEvent.iScanCode == KEY_GREEN_PHONE)
{
/* Call. */
iView->Call();
}
// No hash for you, for now anyway
// else if(aKeyEvent.iScanCode == EStdKeyHash)
// {
// if (iView->IsIronVersion()) {
// iView->HandleCommandL(EWayFinderCmdDestination);
// removeInfoText = ETrue;
// } else {
// iView->HandleCommandL(EWayFinderCmdGuide);
// removeInfoText = ETrue;
// }
// }
else if(aKeyEvent.iScanCode == KEY9)
{
if (iView->IsTracking() && !iView->Get3dMode()) {
iView->SetTracking(EFalse);
} else if (iView->IsGpsAllowed()) {
iView->SetTracking(ETrue);
}
removeInfoText = ETrue;
}
if (removeInfoText && !iInfoTextPersistant) {
setInfoText(NULL);
}
} else if ( aType == EEventKeyUp ) {
/* nothing for now */
/* since this event comes when entering the view. */
} else if( aType == EEventKey ){
/* feature name key */
if(aKeyEvent.iScanCode == EStdKeyDevice3) {
//Stop tracking
iView->SetTracking(EFalse);
GetFeatureName();
if( iView->SettingDestination() ){
iView->HandleCommandL( EWayFinderCmdMapSetDestination );
} else if( iView->SettingOrigin() ){
iView->HandleCommandL( EWayFinderCmdMapSetOrigin );
} else {
ShowDetailedFeatureInfo();
}
}
#ifdef USE_AUTO_TRACKING_TIMER
if (!iView->IsTracking() && iView->IsGpsAllowed()
&& !(aKeyEvent.iScanCode == KEY9)) {
/* Set timer to reenable tracking. */
if (m_autoTrackingOnTimer->IsActive()) {
m_autoTrackingOnTimer->Cancel();
}
m_autoTrackingOnTimer->Start(8000000, 8000000,
TCallBack(KeyCallback, this));
}
#endif
}
return EKeyWasConsumed;
}
void
CVectorMapContainer::SetConStatusImage(CFbsBitmap* aConStatusBitmap,
CFbsBitmap* aConStatusMask)
{
if (iConStatusVisAdapter) {
if (aConStatusBitmap &&
(iConStatusPos.iY == -1 || iConStatusImageHeight !=
aConStatusBitmap->SizeInPixels().iHeight)) {
// Something has changed or is not set, set the pos again.
if (WFLayoutUtils::IsTouchScreen() && !iView->Get3dMode()) {
// The phone has a touch screen, the con status image should be positioned above
// the zoom in button
TInt iZoomButtonTl = iZoomInPictureVisAdapter->getControl()->
GetRect().iTl.iY;
iConStatusImageHeight = aConStatusBitmap->SizeInPixels().iHeight;
TInt zoomButtonLeftX = iZoomOutPictureVisAdapter->getControl()->
GetRect().iTl.iX;
TInt zoomButtonWidth = iZoomOutPictureVisAdapter->getControl()->
GetRect().Width();
iConStatusPos.iX = zoomButtonLeftX + ((zoomButtonWidth >> 1) -
(aConStatusBitmap->SizeInPixels().iWidth >> 1));
iConStatusPos.iY = iZoomButtonTl - (iYPadding + iConStatusImageHeight);
} else {
iConStatusImageHeight = aConStatusBitmap->SizeInPixels().iHeight;
iConStatusPos.iX = WFLayoutUtils::CalculateXValue(X_PADDING);
iConStatusPos.iY = Rect().iBr.iY -
m_mapInfoControl->getDefaultHeight() -
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING) -
iConStatusImageHeight;
}
}
iConStatusVisAdapter->setVisible(ETrue);
iConStatusVisAdapter->getControl()->SetBitmap(iConStatusPos,
aConStatusBitmap,
aConStatusMask);
}
}
void
CVectorMapContainer::SetGpsStatusImage(TInt aImgId, TInt aImgMaskId)
{
if (aImgId != iGpsImgId) {
iGpsImgId = aImgId;
iGpsIndicatorVisAdapter->getControl()->
CreateIconL(iView->GetMbmName(), aImgId,aImgMaskId);
}
}
void CVectorMapContainer::MakeGpsIndicatorVisible(bool aVisible) {
if(iGpsIndicatorVisAdapter) {
if(iGpsIndicatorVisAdapter->isVisible() != aVisible) {
iGpsIndicatorVisAdapter->setVisible(aVisible);
PositionRightEdgeFloatingControls();
}
}
}
void CVectorMapContainer::SetTopBorder()
{
if (iView->IsIronVersion()) {
iTopBorderVisAdapter->setVisible(EFalse);
} else {
if (!iTopBorderVisAdapter->isVisible()) {
iTopBorderVisAdapter->setVisible(ETrue);
//iTopBorderVisAdapter->getControl()->SetNightModeL( iView->IsNightMode() );
SizeChanged();
}
}
}
void CVectorMapContainer::HideTopBorder()
{
if (iTopBorderVisAdapter->isVisible()) {
iTopBorderVisAdapter->setVisible(EFalse);
SizeChanged();
}
}
void CVectorMapContainer::UpdatePedestrianModeIndicator()
{
if (iPedestrianModeVisAdapter) {
iPedestrianModeVisAdapter->setVisible(iView->MapAsPedestrianNavigation());
}
}
void CVectorMapContainer::NextStreetCtrlMakeVisible(TBool aMakeVisible)
{
iNextStreetVisAdapter->setVisible(aMakeVisible);
}
void CVectorMapContainer::SetTurnPictureL( TInt aMbmIndex, TInt aMbmMaskIndex )
{
iTopBorderVisAdapter->getControl()->SetTurnImageL(aMbmIndex, aMbmMaskIndex);
}
void CVectorMapContainer::SetExitCountPictureL(TInt aMbmIndex,
TInt aMbmMaskIndex)
{
iTopBorderVisAdapter->getControl()->SetExitCountImageL(aMbmIndex,
aMbmMaskIndex);
}
/*
void CVectorMapContainer::HideTurnPicture()
{
SetTurnImage(NULL, NULL);
iDistanceBitmap->SetDistanceL(NULL);
}
*/
void
CVectorMapContainer::SetDetourPicture(TInt on)
{
if(iDetourPictureVisAdapter->isVisible() != (on == 1)) {
iDetourPictureVisAdapter->getControl()->SetShow(on == 1);
iDetourPictureVisAdapter->setVisible(on == 1);
PositionRightEdgeFloatingControls();
}
}
void
CVectorMapContainer::SetSpeedCamPicture(TInt on)
{
if(iSpeedCamPictureVisAdapter->isVisible() != (on == 1)) {
iSpeedCamPictureVisAdapter->getControl()->SetShow(on == 1);
iSpeedCamPictureVisAdapter->setVisible(on == 1);
PositionRightEdgeFloatingControls();
}
}
void CVectorMapContainer::SetDistanceL(TUint aDistance)
{
iTopBorderVisAdapter->getControl()->SetDistanceL(aDistance,
iView->GetDistanceMode());
}
void CVectorMapContainer::SetETGL(TInt aETG)
{
iTopBorderVisAdapter->getControl()->SetETGL(aETG);
}
void CVectorMapContainer::SetSpeedL(TInt aSpeed)
{
iTopBorderVisAdapter->getControl()->SetSpeedL(aSpeed,
iView->GetDistanceMode());
}
void CVectorMapContainer::SetNextStreetL(const TDesC& aNextStreet)
{
iNextStreetVisAdapter->getControl()->SetTextL(aNextStreet);
}
void CVectorMapContainer::Connect()
{
if( !iIsConnected ){
iMapControl->Connect();
iIsConnected = ETrue;
}
return;
}
void CVectorMapContainer::UpdateRepaint()
{
if (iMapDrawingInterface) {
iMapDrawingInterface->requestRepaint();
}
}
void CVectorMapContainer::SetCenter( TInt32 aLat, TInt32 aLon )
{
iCenter = TPoint(aLon, aLat);
iMapMovingInterface->setCenter(Nav2Coordinate(aLat, aLon));
}
void CVectorMapContainer::SetRotation( TInt aHeading )
{
iMapMovingInterface->setAngle((double)aHeading);
}
void CVectorMapContainer::ResetRotation()
{
SetRotation(0);
}
void CVectorMapContainer::RequestMarkedPositionMap( TPoint aPos )
{
SetZoom(EScale2);
SetCenter(aPos.iY, aPos.iX);
}
void CVectorMapContainer::RequestPositionMap( TPoint aPos )
{
SetZoom(EScale2);
SetCenter(aPos.iY, aPos.iX);
}
void CVectorMapContainer::RequestPositionAndZoomMap( TPoint aPos, TInt aScale )
{
SetZoom(aScale);
SetCenter(aPos.iY, aPos.iX);
}
void CVectorMapContainer::SetRoute( TInt64 aRouteId )
{
iMapControl->getMapLib()->setRouteID( RouteID( aRouteId ) );
}
void CVectorMapContainer::ClearRoute( )
{
iMapControl->getMapLib()->clearRouteID( );
HideTopBorder();
NextStreetCtrlMakeVisible(EFalse);
iPedestrianModeVisAdapter->setVisible(EFalse);
}
void CVectorMapContainer::RequestRouteMap( TPoint aTl, TPoint aBr )
{
iMapMovingInterface->setWorldBox(Nav2Coordinate( aTl.iY, aTl.iX ),
Nav2Coordinate( aBr.iY, aBr.iX ));
}
void CVectorMapContainer::SetZoom( TInt aScale )
{
iScale = aScale;
iMapMovingInterface->setScale(aScale);
CheckFavoriteRedraw();
}
void CVectorMapContainer::ZoomToOverview()
{
#ifdef USE_GLOBE
SetZoom(EScaleGlobe);
#else
SetZoom(EScale12);
#endif
}
void
CVectorMapContainer::CheckFavoriteRedraw()
{
TInt aScale = GetScale();
if ( aScale > ROTATE_NORTH_SCALE ) {
/* Might just as well change rotation. */
ResetRotation();
}
CSettingsData* aData = iView->GetSettingsData();
/* Check if we want to show favorites. */
if(aData->m_favoriteShowInMap == isab::GuiProtEnums::ShowFavoriteInMapNever ||
(aScale > EScale6 &&
aData->m_favoriteShowInMap != isab::GuiProtEnums::ShowFavoriteInMapAlways)) {
/* Never show or scale is high and show always is not set. */
/* Don't show favorites. */
if (iFeatureHolder->GetCurrentFavIconSize() >= 1) {
iFeatureHolder->SetCurrentFavIconSize(0);
iView->FavoriteChanged();
}
}
else if( aScale > EScale4 &&
aData->m_favoriteShowInMap != isab::GuiProtEnums::ShowFavoriteInMapNever) {
/* Scale is medium and never show is not set. */
/* Show as small stars. */
if (iFeatureHolder->GetCurrentFavIconSize() >= 2 ||
iFeatureHolder->GetCurrentFavIconSize() <= 0) {
iFeatureHolder->SetCurrentFavIconSize(1);
iView->FavoriteChanged();
}
}
else if( aScale >= EScaleMin &&
aData->m_favoriteShowInMap != isab::GuiProtEnums::ShowFavoriteInMapNever) {
/* Scale is small and never show is not set. */
/* Show as large stars. */
if (iFeatureHolder->GetCurrentFavIconSize() <= 1) {
iFeatureHolder->SetCurrentFavIconSize(2);
iView->FavoriteChanged();
}
}
}
void CVectorMapContainer::ZoomIn()
{
TInt scale = (TInt)(iMapMovingInterface->getScale() + 0.5);
/*if( scale >= EScale12*2 ){
scale /= 2;
}
else*/ if( scale > EScale12 ){
scale = EScale12;
}
else if( scale > EScale11 ){
scale = EScale11;
}
else if( scale > EScale10 ){
scale = EScale10;
}
else if( scale > EScale9 ){
scale = EScale9;
}
else if( scale > EScale8 ){
scale = EScale8;
}
else if( scale > EScale7 ){
scale = EScale7;
}
else if( scale > EScale6 ){
scale = EScale6;
}
else if( scale > EScale5 ){
scale = EScale5;
}
else if( scale > EScale4 ){
scale = EScale4;
}
else if( scale > EScale3 ){
scale = EScale3;
}
else if( scale > EScale2 ){
scale = EScale2;
}
else if( scale > EScale1 ){
scale = EScale1;
}
else /*if( scale > EScaleMin )*/{
scale = EScaleMin;
}
SetZoom(scale);
}
void CVectorMapContainer::ZoomOut()
{
TInt scale = (TInt)(iMapMovingInterface->getScale() + 0.5);
if( scale <= EScaleMin ){
scale = EScaleMin;
}
else if( scale < EScale1 ){
scale = EScale1;
}
else if( scale < EScale2 ){
scale = EScale2;
}
else if( scale < EScale3 ){
scale = EScale3;
}
else if( scale < EScale4 ){
scale = EScale4;
}
else if( scale < EScale5 ){
scale = EScale5;
}
else if( scale < EScale6 ){
scale = EScale6;
}
else if( scale < EScale7 ){
scale = EScale7;
}
else if( scale < EScale8 ){
scale = EScale8;
}
else if( scale < EScale9 ){
scale = EScale9;
}
else if( scale < EScale10 ){
scale = EScale10;
}
else if( scale < EScale11 ){
scale = EScale11;
}
else /*if( scale < EScale12 )*/{
scale = EScale12;
}
/*else if( scale < EScale12*2 ){
scale = EScale12*2;
}
else{
scale *= 2;
}*/
SetZoom(scale);
}
void CVectorMapContainer::ZoomOut3d()
{
TInt scale = (TInt)(iMapMovingInterface->getScale() + 0.5);
if ( scale < EScale1 ) {
scale = EScale1;
} else if ( scale < EScale3 ) {
scale = EScale3;
} else {
scale = EScale5;
}
SetZoom( scale );
iMapDrawingInterface->requestRepaint();
}
void CVectorMapContainer::ZoomIn3d()
{
TInt scale = (TInt)(iMapMovingInterface->getScale() + 0.5);
if ( scale > EScale5 ) {
scale = EScale5;
} else if ( scale > EScale3 ) {
scale = EScale3;
} else {
scale = EScale1;
}
SetZoom( scale );
iMapDrawingInterface->requestRepaint();
}
MC2Point
CVectorMapContainer::getTrackingPoint() const
{
TInt dpiCorrectionFactor = WFLayoutUtils::CalculateDpiCorrectionFactor();
if ( iView->GetTrackingType() == ERotating ) {
// Use same point for 2D and 3D. If 3D point should be modified then
// remove the if false.
if ( false && iView->Get3dMode() ) {
return MC2Point ( iMapControl->Size().iWidth >> 1 ,
iMapControl->Size().iHeight - ( 25 * dpiCorrectionFactor ) );
} else if (iView->HasRoute()) {
// If we have a route we want the track point to be in the lower
// part of the screen.
return MC2Point( iMapControl->Size().iWidth >>1,
iMapControl->Size().iHeight -
TInt( iMapControl->Size().iHeight * 0.22 ) );
} else {
// Otherwise we want to center to position in the map.
return MC2Point( ( iMapControl->Size().iWidth >>1 ),
( iMapControl->Size().iHeight >>1 ) );
}
} else {
// Use same point for 2D and 3D. If 3D point should be modified then
// remove the if false.
if ( false && iView->Get3dMode() ) {
return MC2Point( iMapControl->Size().iWidth >> 1,
iMapControl->Size().iHeight - ( 35 * dpiCorrectionFactor ) );
} else {
return MC2Point( ( iMapControl->Size().iWidth >>1 ),
( iMapControl->Size().iHeight >>1 ) );
}
}
}
MC2Point
CVectorMapContainer::getNonTrackingPoint( bool screenSizeChanged ) const
{
if (!screenSizeChanged) {
// Full screen and screen size didn't change.
// Places cursor at the gps.
return getTrackingPoint();
} else {
// Normal screen or switching to fullscreen.
// Place cursor in the center.
return MC2Point( iMapControl->Size().iWidth >> 1,
iMapControl->Size().iHeight >> 1 );
}
}
void
CVectorMapContainer::ShowUserPos( TBool aShow )
{
if( !aShow ){
/* Remove feature from vector. */
CMapFeature* mf =
iFeatureHolder->RemoveFeature(iFeatureHolder->iPositionPoly);
iFeatureHolder->iPositionPolyShown = EFalse;
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iDarkShadePoly);
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iLightshadePoly);
delete mf;
// Hide the pedestrian position indicator as well.
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iPedPositionPoly);
iFeatureHolder->iPedPositionPolyShown = EFalse;
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iPedPositionFillPoly);
delete mf;
} else if (!iFeatureHolder->iPedPositionPolyShown &&
iView->MapAsPedestrianNavigation()) {
// If we're doning pedestrian navigation and the position indicator
// for pedestrian mode is not shown, we hide the normal position
// indicator and show the pedestrian one.
if (iFeatureHolder->iPositionPolyShown) {
CMapFeature* mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iPositionPoly);
iFeatureHolder->iPositionPolyShown = EFalse;
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iDarkShadePoly);
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iLightshadePoly);
delete mf;
}
CMapFeature* mf = new (ELeave) CMapFeature(map_feature_gps, 0);
iFeatureHolder->AddFeature(iFeatureHolder->iPedPositionPoly, mf);
mf = new (ELeave) CMapFeature(map_feature_gps, 1);
iFeatureHolder->AddFeature(iFeatureHolder->iPedPositionFillPoly, mf);
iFeatureHolder->iPedPositionPolyShown = ETrue;
} else if (!iFeatureHolder->iPositionPolyShown &&
!iView->MapAsPedestrianNavigation()) {
// We're doing car navigation so hide the pedestrian indicator and
// show the car indicator.
if (iFeatureHolder->iPedPositionPolyShown) {
CMapFeature* mf =
iFeatureHolder->RemoveFeature(iFeatureHolder->iPedPositionPoly);
iFeatureHolder->iPedPositionPolyShown = EFalse;
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iPedPositionFillPoly);
delete mf;
}
CMapFeature* mf = new (ELeave) CMapFeature(map_feature_gps, 0);
iFeatureHolder->AddFeature(iFeatureHolder->iPositionPoly, mf);
mf = new (ELeave) CMapFeature(map_feature_gps, 1);
iFeatureHolder->AddFeature(iFeatureHolder->iDarkShadePoly, mf);
mf = new (ELeave) CMapFeature(map_feature_gps, 2);
iFeatureHolder->AddFeature(iFeatureHolder->iLightshadePoly, mf);
iFeatureHolder->iPositionPolyShown = ETrue;
}
}
void
CVectorMapContainer::ShowNorthArrow( TBool aShow )
{
if( !aShow ) {
CMapFeature* mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iNorthPoly);
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iSouthPoly);
delete mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iArrowPoly);
delete mf;
iFeatureHolder->iCompassPolyShown = EFalse;
} else if (!iFeatureHolder->iCompassPolyShown ) {
CMapFeature* mf;
mf = new (ELeave) CMapFeature(map_feature_compass, 0);
iFeatureHolder->AddFeature( iFeatureHolder->iArrowPoly, mf );
mf = new (ELeave) CMapFeature(map_feature_compass, 1);
iFeatureHolder->AddFeature( iFeatureHolder->iNorthPoly, mf );
mf = new (ELeave) CMapFeature(map_feature_compass, 2);
iFeatureHolder->AddFeature( iFeatureHolder->iSouthPoly, mf );
TInt x = 0;
TInt y = 0;
CalcCompassPosition(x, y);
iFeatureHolder->iNorthPoly->setCenter( MC2Point(x,y) );
iFeatureHolder->iSouthPoly->setCenter( MC2Point(x,y) );
iFeatureHolder->iArrowPoly->setCenter( MC2Point(x,y) );
iFeatureHolder->iCompassPolyShown = ETrue;
}
}
void CVectorMapContainer::ResetNorthArrowPos()
{
if (iFeatureHolder->iCompassPolyShown) {
TInt x = 0;
TInt y = 0;
CalcCompassPosition(x, y);
iFeatureHolder->iNorthPoly->setCenter(MC2Point(x,y));
iFeatureHolder->iSouthPoly->setCenter(MC2Point(x,y));
iFeatureHolder->iArrowPoly->setCenter(MC2Point(x,y));
}
}
void CVectorMapContainer::CalcCompassPosition(TInt &aX, TInt &aY)
{
TInt dpiCorrectionFactor = WFLayoutUtils::CalculateDpiCorrectionFactor();
aX = (COMPASS_POLY_HEIGHT / 2) * dpiCorrectionFactor;
aY = aX + WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
aX += WFLayoutUtils::CalculateXValue(X_PADDING);
// Since the top border bar is not a part of the MapLib rect, it is
// positioned above the maps drawing rect, there is no need to take
// this into concideration when positioning the compass poly
if (iNextStreetVisAdapter->isVisible()) {
aY += iNextStreetVisAdapter->getControl()->Rect().Height();
}
if (iTopBorderVisAdapter->isVisible()) {
aY += iTopBorderVisAdapter->getControl()->Rect().Height();
}
}
void CVectorMapContainer::PositionRightEdgeFloatingControls()
{
//calculate the rect for the first control
TSize imgSize = WFLayoutUtils::CalculateSizeUsingMin(INFO_IMAGES_SIZE);
TPoint firstCtrlPos = Rect().iBr;
firstCtrlPos.iX -= (imgSize.iWidth + WFLayoutUtils::CalculateXValue(X_PADDING));
firstCtrlPos.iY = WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING);
if (iNextStreetVisAdapter->isVisible()) {
firstCtrlPos.iY += iNextStreetVisAdapter->getControl()->Rect().Height();
}
if (iTopBorderVisAdapter->isVisible()) {
firstCtrlPos.iY += iTopBorderVisAdapter->getControl()->Rect().Height();
}
TRect currentControlRect(firstCtrlPos, imgSize);
// position the gps image
if(iGpsIndicatorVisAdapter->isVisible()) {
iGpsIndicatorVisAdapter->getControl()->SetImageRect(currentControlRect);
currentControlRect.Move(0,
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING) +
currentControlRect.Height());
}
//position the detour
if(iDetourPictureVisAdapter->isVisible()) {
iDetourPictureVisAdapter->getControl()->SetImageRect(currentControlRect);
currentControlRect.Move(0,
WFLayoutUtils::CalculateYValueUsingFullScreen(Y_PADDING) +
currentControlRect.Height());
}
// Position the speedcam image
if(iSpeedCamPictureVisAdapter->isVisible()) {
iSpeedCamPictureVisAdapter->getControl()->SetImageRect(currentControlRect);
}
}
void
CVectorMapContainer::ShowScale( TBool aShow )
{
if( !aShow ) {
CMapFeature* mf;
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iScaleFeature);
delete mf;
iFeatureHolder->iScaleFeatureShown = EFalse;
} else if (!iFeatureHolder->iScaleFeatureShown ) {
CMapFeature* mf;
mf = new (ELeave) CMapFeature(map_feature_scale, 0);
iFeatureHolder->AddFeature( iFeatureHolder->iScaleFeature, mf );
TInt x, y;
if (WFLayoutUtils::IsTouchScreen()) {
// If the zoom in and out buttons are valid then the scale should be
// positioned above these.
x = Rect().Width() - iXPadding;
y = iMapControl->Rect().Height() -
m_mapInfoControl->getDefaultHeight() - iYPadding -
iZoomInPictureVisAdapter->getControl()->GetRect().Height() -
iYPadding;
} else {
x = Rect().Width() - iXPadding;
y = iMapControl->Rect().Height() -
m_mapInfoControl->getDefaultHeight() - iYPadding;
}
iFeatureHolder->iScaleFeature->setPoint( MC2Point(x,y) );
iFeatureHolder->iScaleFeatureShown = ETrue;
} else {
TInt x, y;
if (WFLayoutUtils::IsTouchScreen()) {
// If the zoom in and out buttons are valid then the scale should be
// positioned above these.
x = Rect().Width() - iXPadding;
y = iMapControl->Rect().Height() -
m_mapInfoControl->getDefaultHeight() - iYPadding -
iZoomInPictureVisAdapter->getControl()->GetRect().Height() -
iYPadding;
} else {
x = Rect().Width() - iXPadding;
y = iMapControl->Rect().Height() -
m_mapInfoControl->getDefaultHeight() - iYPadding;
}
iFeatureHolder->iScaleFeature->setPoint( MC2Point(x,y) );
iFeatureHolder->iScaleFeatureShown = ETrue;
}
}
void
CVectorMapContainer::ShowEnd( TBool aShow, TInt32 aLat, TInt32 aLon )
{
if( !aShow ){
CMapFeature* mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iEndBitmap);
delete mf;
iFeatureHolder->iEndBitmapShown = EFalse;
} else {
CMapFeature* mf = iFeatureHolder->GetFeature(iFeatureHolder->iEndBitmap);
if (mf != NULL) {
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iEndBitmap);
delete mf;
}
mf = new (ELeave) CMapFeature(map_feature_pin, 0);
iFeatureHolder->AddFeature( iFeatureHolder->iEndBitmap, mf );
iFeatureHolder->iEndBitmap->setCenter( Nav2Coordinate(aLat, aLon) );
iFeatureHolder->iEndBitmapShown = ETrue;
}
}
void
CVectorMapContainer::ShowStart( TBool aShow, TInt32 aLat, TInt32 aLon )
{
if( !aShow ){
CMapFeature* mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iStartBitmap);
delete mf;
iFeatureHolder->iStartBitmapShown = EFalse;
} else {
CMapFeature* mf = iFeatureHolder->GetFeature(iFeatureHolder->iStartBitmap);
if (mf != NULL) {
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iStartBitmap);
delete mf;
}
mf = new (ELeave) CMapFeature(map_feature_pin, 0);
iFeatureHolder->AddFeature( iFeatureHolder->iStartBitmap, mf );
iFeatureHolder->iStartBitmap->setCenter( Nav2Coordinate(aLat, aLon) );
iFeatureHolder->iStartBitmapShown = ETrue;
}
}
void CVectorMapContainer::ShowPoint( TBool aShow, TInt32 aLat, TInt32 aLon )
{
if( !aShow ){
CMapFeature* mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iPointBitmap);
delete mf;
iFeatureHolder->iPointBitmapShown = EFalse;
} else {
CMapFeature* mf = iFeatureHolder->GetFeature(iFeatureHolder->iPointBitmap);
if (mf != NULL) {
mf = iFeatureHolder->RemoveFeature(iFeatureHolder->iPointBitmap);
delete mf;
}
mf = new (ELeave) CMapFeature(map_feature_pin, 0);
iFeatureHolder->AddFeature( iFeatureHolder->iPointBitmap, mf );
iFeatureHolder->iPointBitmap->setCenter( Nav2Coordinate(aLat, aLon) );
iFeatureHolder->iPointBitmapShown = ETrue;
}
}
void CVectorMapContainer::GetCoordinate( TPoint& aRealCoord )
{
MC2Coordinate mc2Coord = m_mapMover->getCoordinate();
Nav2Coordinate nav2Coord( mc2Coord );
aRealCoord.iY = nav2Coord.nav2lat;
aRealCoord.iX = nav2Coord.nav2lon;
}
void CVectorMapContainer::GetLongPressOrNormalCoordinate( TPoint& aRealCoord )
{
if(iUsingLongPressPosition) {
MC2Coordinate mc2Coord;
iMapMovingInterface->inverseTransform( mc2Coord, iLongPressPosition);
Nav2Coordinate nav2Coord( mc2Coord );
aRealCoord.iY = nav2Coord.nav2lat;
aRealCoord.iX = nav2Coord.nav2lon;
}
else {
MC2Coordinate mc2Coord = m_mapMover->getCoordinate();
Nav2Coordinate nav2Coord( mc2Coord );
aRealCoord.iY = nav2Coord.nav2lat;
aRealCoord.iX = nav2Coord.nav2lon;
}
}
void CVectorMapContainer::GetCoordinate( MC2Coordinate& aMC2Coord )
{
aMC2Coord = m_mapMover->getCoordinate();
}
void CVectorMapContainer::GetLongPressOrNormalCoordinate( MC2Coordinate& aMC2Coord )
{
if(iUsingLongPressPosition) {
iMapMovingInterface->inverseTransform( aMC2Coord, iLongPressPosition);
}
else {
aMC2Coord = m_mapMover->getCoordinate();
}
}
void CVectorMapContainer::setInfoText(const char *txt,
const char *left,
const char *right,
TBool persistant,
uint32 hideAfterMS )
{
if ( txt == NULL && !iInfoTextShown ) {
return;
}
// Cancel the hide timer.
if ( m_hideInfoTimerID != MAX_UINT32 ) {
iMapControl->getToolkit()->cancelTimer( this, m_hideInfoTimerID );
}
if (txt == NULL) {
iInfoTextShown = EFalse;
m_detailedInfoTextShown = false;
iInfoTextPersistant = EFalse;
iView->ReleaseInfoText();
// iMapControl->setInfoText(txt);
m_mapInfoControl->setInfoText(txt);
//iCopyrightLabel->MakeVisible(ETrue);
iView->ToggleSoftKeys(ETrue);
if (iZoomInPictureVisAdapter && iZoomOutPictureVisAdapter) {
// If we have zoom buttons...
if (WFLayoutUtils::IsTouchScreen() &&
!iView->Get3dMode() &&
!iZoomInPictureVisAdapter->isVisible()) {
// Un-hide the zoom buttons if they should be shown again.
iZoomInPictureVisAdapter->setVisible(ETrue);
iZoomOutPictureVisAdapter->setVisible(ETrue);
}
}
} else {
if (iMapControl) {
if ( left != NULL || right != NULL ) {
m_detailedInfoTextShown = true;
} else {
m_detailedInfoTextShown = false;
}
iInfoTextShown = true;
iInfoTextPersistant = persistant;
// iMapControl->setInfoText(txt, left, right);
m_mapInfoControl->setInfoText(txt, left, right);
//iCopyrightLabel->MakeVisible(EFalse);
iView->ToggleSoftKeys( !m_detailedInfoTextShown );
// Enable the hide timer if requested.
if ( hideAfterMS != MAX_UINT32 ) {
m_hideInfoTimerID = iMapControl->getToolkit()->requestTimer(
this,
hideAfterMS,
TileMapToolkit::PRIO_LOW );
}
if (iZoomInPictureVisAdapter && iZoomOutPictureVisAdapter) {
// If we have zoom buttons...
if ((Rect().iBr.iY - m_mapInfoControl->getInfoBox().Height()) <
iZoomInPictureVisAdapter->getControl()->GetRect().iBr.iY) {
// The info text covers the zoom buttons so hide them temporarily.
iZoomInPictureVisAdapter->setVisible(EFalse);
iZoomOutPictureVisAdapter->setVisible(EFalse);
} else if (WFLayoutUtils::IsTouchScreen() &&
!iView->Get3dMode() &&
!iZoomInPictureVisAdapter->isVisible()) {
// Un-hide the zoom buttons if they should be shown again and
// the info text does not cover them.
iZoomInPictureVisAdapter->setVisible(ETrue);
iZoomOutPictureVisAdapter->setVisible(ETrue);
}
}
}
}
updateCursorVisibility();
}
TBool
CVectorMapContainer::IsInfoTextOn()
{
return iInfoTextShown;
}
void CVectorMapContainer::ShowFeatureInfo()
{
const char* feature = m_mapMover->getInfo();
setInfoText( feature );
}
HBufC* CVectorMapContainer::GetServerStringL()
{
const ClickInfo& clickedFeature =
iMapMovingInterface->getInfoForFeatureAt(getActivePoint(), false);
const char* charServerString = clickedFeature.getServerString();
HBufC* serverString = NULL;
if (charServerString != NULL) {
char* urlencodedString = new char[3 * strlen(charServerString) + 1];
StringUtility::URLEncode(urlencodedString, charServerString);
serverString = WFTextUtil::AllocL(urlencodedString);
delete[] urlencodedString;
}
return serverString;
}
void CVectorMapContainer::ShowDetailedFeatureInfo(TBool showWithList)
{
const ClickInfo& aClickedFeature =
iMapMovingInterface->getInfoForFeatureAt( getActivePoint(),
false ); // highlightable
UserDefinedFeature* udf = aClickedFeature.getClickedUserFeature();
if (udf) {
/* User clicked a user defined feature. */
CMapFeature* mf = iFeatureHolder->GetFeature(udf);
if (mf) {
/* Got it. */
if (mf->Type() == map_feature_favorite) {
/* Got a favorite. */
uint32 id = (uint32)mf->Id();
iView->RequestFavorite(id);
}
}
} else {
/* No user defined feature, check if we have anything else */
const char *serverString = aClickedFeature.getServerString();
const char *name = aClickedFeature.getName();
if (serverString && (name && strlen(name) != 0)) {
/* Got a map feature. */
setInfoText(name);
/* Send request for additional info. */
iView->GetDetails( serverString, showWithList );
} else {
setInfoText( NULL );
}
}
}
void CVectorMapContainer::GetFeatureName()
{
const char* feature =
iMapControl->getFeatureName( getActivePoint() );
if( feature == NULL ){
HBufC* unknownString = iCoeEnv->AllocReadResourceL(
R_WAYFINDER_UNKNOWN_TEXT);
feature = WFTextUtil::TDesCToUtf8L(unknownString->Des());
}
iView->SetMapFeatureName( (const unsigned char*)feature );
}
TInt CVectorMapContainer::GetScale()
{
return (TInt)(iMapMovingInterface->getScale() + 0.5);
}
void CVectorMapContainer::setTrackingMode( TBool /*aOnOff*/,
TrackingType aType,
bool interpolating )
{
if (iMapControl) {
bool northUp = ( aType != ERotating );
m_mapMover->statusChanged( getTrackingPoint(),
getNonTrackingPoint(),
iView->IsTracking(),
northUp,
interpolating );
updateCursorVisibility();
}
}
void CVectorMapContainer::SetCellIdIconEnabled(bool enabled)
{
if(enabled) {
iFeatureHolder->iCellIdBitmap->setVisible(true);
} else {
iFeatureHolder->iCellIdBitmap->setVisible(false);
}
UpdateRepaint();
}
void CVectorMapContainer::UpdateCellIdIconDimensions()
{
if ( iFeatureHolder->iCellIdBitmap->isVisible() ) {
// use the last known radius
UpdateCellIdIconDimensions(iRadiusMeters);
UpdateRepaint();
}
}
#define MIN_PIXEL_RADIUS 25
void CVectorMapContainer::UpdateCellIdIconDimensions(int aRadiusMeters)
{
iRadiusMeters = aRadiusMeters;
int pixelDiameter =
static_cast<int>((aRadiusMeters *
WFLayoutUtils::CalculateDpiCorrectionFactor() * 2) /
iMapMovingInterface->getScale());
// set a minimum size for the cell id so it is still visible when you zoom out
if ( pixelDiameter < MIN_PIXEL_RADIUS ) {
pixelDiameter = MIN_PIXEL_RADIUS;
}
// The map/phone gets really slow when rescaling an image that is huge,
// so we limit the resize of the cellId bitmap to 1.5 times the largest
// size of the screen.
TInt maxSize = WFLayoutUtils::CalculateUnitsUsingMax(float(1.5));
if (pixelDiameter < maxSize) {
iFeatureHolder->iCellIdBitmap->setDimensions(pixelDiameter,
pixelDiameter);
}
}
void CVectorMapContainer::UpdateCellIdPosition(const MC2Coordinate& coord)
{
iFeatureHolder->iCellIdBitmap->setCenter(coord);
}
void
CVectorMapContainer::ShowVectorMapWaitSymbol( bool start )
{
// Only start showing the wait symbol in map.
if (start) {
// Lower left corner.
TInt x = 8;
TInt y = Rect().Height() - 33;
iFeatureHolder->iWaitSymbol->setCenter( MC2Point(x,y) );
iFeatureHolder->iWaitSymbol->setVisible( true );
UpdateRepaint();
} else {
// Simply set it to not be visible. No need to remove etc.
iFeatureHolder->iWaitSymbol->setVisible( false );
UpdateRepaint();
}
}
/* key handler */
void CVectorMapContainer::TimerHandler()
{
#ifdef USE_AUTO_TRACKING_TIMER
/* Timer used as timeout for tracking. */
if (iView->UseTrackingOnAuto()) {
iView->SetTracking(ETrue);
}
if ( m_autoTrackingOnTimer->IsActive() ) {
m_autoTrackingOnTimer->Cancel();
}
#endif
}
bool
CVectorMapContainer::setGpsPos( const MC2Coordinate& coord,
int direction,
int scale,
bool interpolated )
{
// if (iView->MapAsPedestrianNavigation()) {
// setPedestrianGpsPos(coord);
// }
return m_mapMover->setGpsPos( coord, direction, scale, interpolated );
}
#if 0
void CVectorMapContainer::setPedestrianGpsPos(const MC2Coordinate& coord)
{
MC2Point screenPos(0,0);
iMapMovingInterface->transform(screenPos, coord);
iPedestrianPositionVisAdapter->getControl()->SetCenter(screenPos);
}
#endif
// returns Input info about the app
// required if the derived class is implementing OfferKeyEventL()
TCoeInputCapabilities CVectorMapContainer::InputCapabilities() const
{
return(TCoeInputCapabilities(TCoeInputCapabilities::EAllText));
}
int CVectorMapContainer::getMemCacheSize() const
{
#ifdef NAV2_CLIENT_SERIES60_V1
int maxSize = 64*1024;
#else
int maxSize = 128*1024;
#endif
int memFree = 0;
#ifndef NAV2_CLIENT_SERIES60_V3
HAL::Get(HALData::EMemoryRAMFree, memFree );
#else
// We cannot get any usable measure of how much memory is available.
// Let's assume we can afford the full memory cache.
memFree = maxSize * 2;
#endif
// TBuf<64> str;
// str.Format(_L("Memory free : %i"), memFree );
// CEikonEnv::Static()->InfoMsg( str );
// SHOWMSGWIN( str );
return MIN( maxSize, memFree / 2);
}
void
CVectorMapContainer::timerExpired( uint32 id )
{
if ( m_hideInfoTimerID == id ) {
// Hide the blue note containing info.
setInfoText( NULL );
// Reset the timer id.
m_hideInfoTimerID = MAX_UINT32;
}
}
void CVectorMapContainer::AddSfdCacheFiles()
{
MapLib* mapLib = iMapControl->getMapLib();
if ( mapLib == NULL ) {
return;
}
_LIT(KWfdName, "*.wfd");
class RFs fs;
fs.Connect();
TFindFile finder(fs);
CDir* dir;
TInt res = finder.FindWildByDir(KWfdName, iView->GetMapCachePath(), dir);
// Add all sfd-files found.
while (res == KErrNone) {
for (TInt i = 0; i < dir->Count(); i++) {
TParse parser;
parser.Set((*dir)[i].iName, &finder.File(), NULL);
char* fullPath = WFTextUtil::TDesCToUtf8LC(parser.FullName());
mapLib->addSingleFileCache(fullPath, NULL);
CleanupStack::PopAndDestroy(fullPath);
}
delete dir;
dir = NULL;
// Continue the search on the next drive.
res = finder.FindWild(dir);
}
fs.Close();
}
void
CVectorMapContainer::HandleResourceChange(TInt aType)
{
CCoeControl::HandleResourceChange(aType);
if (aType == KEikDynamicLayoutVariantSwitch) {
BindMovementKeys(WFLayoutUtils::LandscapeMode());
TInt dpiCorrFact = WFLayoutUtils::CalculateDpiCorrectionFactor();
TRect vectorMapRect;
// Get location of cba buttons.
AknLayoutUtils::TAknCbaLocation cbaLocation =
AknLayoutUtils::CbaLocation();
if (WFLayoutUtils::LandscapeMode() && !WFLayoutUtils::IsTouchScreen() &&
(cbaLocation != AknLayoutUtils::EAknCbaLocationBottom)) {
// If we're in landscape mode, not touch screen and we dont have
// the CBAs in the bottom of the screen (like e71) we have to
// let the top and bottom pane be visible.
vectorMapRect = WFLayoutUtils::GetMainPaneRect();
} else {
// Otherwise the only system pane we show is the CBA buttons.
vectorMapRect = WFLayoutUtils::GetFullScreenMinusCBARect();
}
SetRect(vectorMapRect);
MapLib* mapLib = iMapControl->getMapLib();
if(mapLib) {
mapLib->setDPICorrectionFactor(dpiCorrFact);
}
iFeatureHolder->RescalePolygons();
m_cursorSprite->updateSize();
m_highlightCursorSprite->updateSize();
iView->GetDpiCorrFact() = dpiCorrFact;
}
SetNightModeL( iView->IsNightMode() );
}
void
CVectorMapContainer::BindMovementKeys(TBool aLandscapeMode)
{
int nbrBindings = 0;
const CVectorMapContainer::key_array_pair_t* keyBindings = NULL;
if (aLandscapeMode) {
nbrBindings = sizeof(c_landscapeKeyBindings) / sizeof(c_landscapeKeyBindings[0]);
keyBindings = c_landscapeKeyBindings;
} else {
nbrBindings = sizeof(c_portraitKeyBindings) / sizeof(c_portraitKeyBindings[0]);
keyBindings = c_portraitKeyBindings;
}
for (int i = nbrBindings - 1; i >= 0; --i) {
m_keyMap[keyBindings[i].first] = keyBindings[i].second;
}
}
void
CVectorMapContainer::SetNightModeL(TBool aNightMode)
{
if (iTopBorderVisAdapter->getControl()) {
iTopBorderVisAdapter->getControl()->SetNightModeL(aNightMode);
}
if (iNextStreetVisAdapter->getControl()) {
iNextStreetVisAdapter->getControl()->SetNightModeL(aNightMode);
}
if (m_mapInfoControl) {
m_mapInfoControl->SetNightMode(aNightMode);
}
if (iMapControl) {
iMapControl->SetNightModeL(aNightMode);
}
}
void
CVectorMapContainer::Set3dMode(TBool aOn)
{
if (aOn) {
if (iMapControl) {
// iMapControl->getMapLib()->
// setHorizonHeight(WFLayoutUtils::CalculateYValueUsingFullScreen(BLUE_BAR_HEIGHT));
}
}
if (iZoomInPictureVisAdapter && iZoomOutPictureVisAdapter) {
// Zoom buttons should not be visible in 3d mode.
iZoomInPictureVisAdapter->setVisible(!aOn);
iZoomOutPictureVisAdapter->setVisible(!aOn);
}
SizeChanged();
}
void CVectorMapContainer::SetMapControlsNull()
{
ReleaseMapControlDependencies();
iMapControl = NULL;
iFeatureHolder = NULL;
m_mapInfoControl = NULL;
m_keyHandler = NULL;
}
void CVectorMapContainer::ResetLongPressPositionFlag()
{
iUsingLongPressPosition = EFalse;
}
void CVectorMapContainer::handleTileMapEvent(const class TileMapEvent &event)
{
switch (event.getType()) {
case TileMapEvent::USER_DEFINED_FEATURES_REDRAWN:
if(m_keyHandler && iUpdateCursorAndInfoAtNextRedraw) {
const char* featureText = m_keyHandler->checkHighlight();
setInfoText(featureText, NULL, NULL, EFalse, 3000);
iUpdateCursorAndInfoAtNextRedraw = EFalse;
}
break;
default:
break;
}
}
void CVectorMapContainer::ReleaseMapControlDependencies()
{
if(m_keyHandler) {
m_keyHandler->cancelInfoCallback();
}
if(iMapControl) {
iMapControl->Handler().removeEventListener(this);
}
}
void CVectorMapContainer::StopKeyHandler()
{
m_keyHandler->stop();
}
| [
"[email protected]"
]
| [
[
[
1,
3061
]
]
]
|
d1d453ccb3d9241af6b6b74949a653ea8e052dd8 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEMax8Exporter/SEMax8Exporter/SEMax8UnimaterialMesh.cpp | c8c37806406a8521ce6964b8dc46bb5efa36227b | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 11,582 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEMax8UnimaterialMesh.h"
using namespace Swing;
#include <algorithm>
#include <vector>
using namespace std;
//----------------------------------------------------------------------------
Max8UnimaterialMesh::Max8UnimaterialMesh()
{
m_iVCount = 0;
m_aVertex = NULL;
m_aNormal = NULL;
m_iCCount = 0;
m_aColor = NULL;
m_iTCount = 0;
m_aTexture = NULL;
m_iFCount = 0;
m_aiFace = NULL;
m_aiCFace = NULL;
m_aiTFace = NULL;
}
//----------------------------------------------------------------------------
int& Max8UnimaterialMesh::VCount()
{
return m_iVCount;
}
//----------------------------------------------------------------------------
Swing::SEVector3f*& Max8UnimaterialMesh::Vertex()
{
return m_aVertex;
}
//----------------------------------------------------------------------------
Swing::SEVector3f*& Max8UnimaterialMesh::Normal()
{
return m_aNormal;
}
//----------------------------------------------------------------------------
int& Max8UnimaterialMesh::CCount()
{
return m_iCCount;
}
//----------------------------------------------------------------------------
Swing::SEColorRGB*& Max8UnimaterialMesh::Color()
{
return m_aColor;
}
//----------------------------------------------------------------------------
int& Max8UnimaterialMesh::TCount()
{
return m_iTCount;
}
//----------------------------------------------------------------------------
Swing::SEVector2f*& Max8UnimaterialMesh::Texture()
{
return m_aTexture;
}
//----------------------------------------------------------------------------
int& Max8UnimaterialMesh::FCount()
{
return m_iFCount;
}
//----------------------------------------------------------------------------
int*& Max8UnimaterialMesh::Face()
{
return m_aiFace;
}
//----------------------------------------------------------------------------
int*& Max8UnimaterialMesh::CFace()
{
return m_aiCFace;
}
//----------------------------------------------------------------------------
int*& Max8UnimaterialMesh::TFace()
{
return m_aiTFace;
}
//----------------------------------------------------------------------------
Swing::SEMaterialStatePtr& Max8UnimaterialMesh::MState()
{
return m_spSEMaterialState;
}
//----------------------------------------------------------------------------
Swing::SETexturePtr& Max8UnimaterialMesh::TState()
{
return m_spTState;
}
//----------------------------------------------------------------------------
void Max8UnimaterialMesh::DuplicateGeometry()
{
// 建立一个当前网格的顶点属性数组,
// 该数组表明了当前网格的每个顶点被平面索引的次数,
// 每个顶点每次被平面索引时,可能使用不同的顶点颜色和纹理坐标.
vector<VertexAttr>* aVArray = new vector<VertexAttr>[m_iVCount];
int i;
for( i = 0; i < 3*m_iFCount; i++ )
{
VertexAttr tempAttr;
tempAttr.V = m_aiFace[i];
if( m_iCCount > 0 )
{
tempAttr.C = m_aiCFace[i];
}
if( m_iTCount > 0 )
{
tempAttr.T = m_aiTFace[i];
}
aVArray[m_aiFace[i]].push_back(tempAttr);
}
// 如果某个顶点被多次索引,并且在这些索引中指定了不同的顶点颜色或纹理坐标,
// 则根据我们的数据要求,该顶点应该被复制,复制出的新顶点使用同样的顶点索引,
// 但使用了不同的颜色或纹理坐标索引.
// 因此为了包含这些新复制出的顶点,计算总共需要多少顶点.
int iNewVCount = 0;
for( i = 0; i < m_iVCount; i++ )
{
// 确保唯一性,移除重复的索引.
sort(aVArray[i].begin(), aVArray[i].end());
vector<VertexAttr>::iterator pEnd = unique(aVArray[i].begin(),
aVArray[i].end());
aVArray[i].erase(pEnd, aVArray[i].end());
iNewVCount += aVArray[i].size();
}
// 分配Swing Engine几何体所需数据.
Swing::SEVector3f* aNewVertex = new SEVector3f[iNewVCount];
Swing::SEVector3f* aNewNormal = new SEVector3f[iNewVCount];
Swing::SEColorRGB* aNewColor = NULL;
if( m_iCCount > 0 )
{
aNewColor = new Swing::SEColorRGB[iNewVCount];
}
SEVector2f* aNewTexture = NULL;
if( m_iTCount > 0 )
{
aNewTexture = new SEVector2f[iNewVCount];
}
int j, k;
for( i = 0, k = 0; i < m_iVCount; i++ )
{
vector<VertexAttr>& rVArray = aVArray[i];
int iSize = rVArray.size();
for( j = 0; j < iSize; j++, k++ )
{
aNewVertex[k] = m_aVertex[i];
aNewNormal[k] = m_aNormal[i];
VertexAttr tempAttr = rVArray[j];
if( aNewColor )
{
aNewColor[k] = m_aColor[tempAttr.C];
}
if( aNewTexture )
{
aNewTexture[k] = m_aTexture[tempAttr.T];
}
// 复制当前slot中的每个顶点属性,供稍后使用.
tempAttr.V = k;
rVArray.push_back(tempAttr);
}
}
// 修改平面顶点索引,使其索引到新创建的重复顶点.
for( i = 0; i < m_iFCount; i++ )
{
int iThreeI = 3 * i;
int* aiVIndex = m_aiFace + iThreeI;
int* aiCIndex = ( m_iCCount > 0 ? m_aiCFace + iThreeI : NULL );
int* aiTIndex = ( m_iTCount > 0 ? m_aiTFace + iThreeI : NULL );
for( j = 0; j < 3; j++ )
{
VertexAttr tempAttr;
tempAttr.V = aiVIndex[j];
if( aiCIndex )
{
tempAttr.C = aiCIndex[j];
}
if( aiTIndex )
{
tempAttr.T = aiTIndex[j];
}
// VArray中有N个原始顶点属性和N个复制出的顶点属性.
vector<VertexAttr>& rVArray = aVArray[aiVIndex[j]];
int iHalfSize = rVArray.size() / 2;
for( k = 0; k < iHalfSize; k++ )
{
if( rVArray[k] == tempAttr )
{
// 找到匹配的顶点属性,更新顶点索引.
aiVIndex[j] = rVArray[iHalfSize + k].V;
break;
}
}
}
}
delete[] m_aVertex;
delete[] m_aNormal;
delete[] m_aColor;
delete[] m_aTexture;
delete[] m_aiTFace;
m_iVCount = iNewVCount;
m_aVertex = aNewVertex;
m_aNormal = aNewNormal;
m_aColor = aNewColor;
m_aTexture = aNewTexture;
delete[] aVArray;
}
//----------------------------------------------------------------------------
SETriMesh* Max8UnimaterialMesh::ToTriMesh()
{
// 创建所需Swing Engine VB.
Swing::SEAttributes tempSEAttr;
tempSEAttr.SetPositionChannels(3);
if( m_aNormal )
{
tempSEAttr.SetNormalChannels(3);
}
if( m_aColor )
{
tempSEAttr.SetColorChannels(0, 3);
}
if( m_aTexture )
{
tempSEAttr.SetTCoordChannels(0, 2);
}
Swing::SEVertexBuffer* pSEVBuffer = new Swing::SEVertexBuffer(tempSEAttr,
m_iVCount);
for( int i = 0; i < m_iVCount; i++ )
{
(*(Swing::SEVector3f*)pSEVBuffer->PositionTuple(i)) = m_aVertex[i];
if( m_aNormal )
{
*(Swing::SEVector3f*)pSEVBuffer->NormalTuple(i) = m_aNormal[i];
}
if( m_aColor )
{
*(Swing::SEColorRGB*)pSEVBuffer->ColorTuple(0, i) = m_aColor[i];
}
if( m_aTexture )
{
*(Swing::SEVector2f*)pSEVBuffer->TCoordTuple(0, i) = m_aTexture[i];
}
}
// 创建所需Swing Engine IB.
Swing::SEIndexBuffer* pSEIBuffer = new Swing::SEIndexBuffer(3 * m_iFCount);
int* pSEIBufferData = pSEIBuffer->GetData();
memcpy(pSEIBufferData, m_aiFace, 3*m_iFCount*sizeof(int));
Swing::SETriMesh* pSEMesh = new Swing::SETriMesh(pSEVBuffer, pSEIBuffer);
Swing::SEEffect* pSEEffect = NULL;
// 根据Swing Engine网格所带材质和纹理,为其添加effect.
// 目前导出器支持的材质和纹理effect是:
// SEMaterialEffect,SEMaterialTextureEffect,SEDefaultShaderEffect.
if( m_spSEMaterialState )
{
pSEMesh->AttachGlobalState(m_spSEMaterialState);
if( m_spTState )
{
// 待实现.
// 当拆分网格后如何处理多重纹理?
std::string tempFName = m_spTState->GetImage()->GetName();
// 减去".seif"长度
size_t uiLength = strlen(tempFName.c_str()) - 5;
char tempBuffer[64];
Swing::SESystem::SE_Strncpy(tempBuffer, 64, tempFName.c_str(),
uiLength);
tempBuffer[uiLength] = 0;
pSEEffect = new Swing::SEMaterialTextureEffect(tempBuffer);
}
else
{
// 待实现:
// 暂时无法使用SEMaterialEffect
//pSEEffect = new Swing::SEMaterialEffect();
assert( !m_aTexture );
if( m_aTexture )
{
delete[] m_aTexture;
}
}
}
// 理论上不可能出现这种情况
if( !m_spSEMaterialState && m_spTState )
{
assert( false );
}
if( !m_spSEMaterialState && !m_spTState )
{
pSEEffect = new Swing::SEDefaultShaderEffect;
}
if( pSEEffect )
{
pSEMesh->AttachEffect(pSEEffect);
}
return pSEMesh;
}
//----------------------------------------------------------------------------
Max8UnimaterialMesh::VertexAttr::VertexAttr()
{
V = -1;
C = -1;
T = -1;
}
//----------------------------------------------------------------------------
bool Max8UnimaterialMesh::VertexAttr::operator==(const VertexAttr& rAttr)
const
{
return V == rAttr.V && C == rAttr.C && T == rAttr.T;
}
//----------------------------------------------------------------------------
bool Max8UnimaterialMesh::VertexAttr::operator<(const VertexAttr& rAttr) const
{
if( V < rAttr.V )
{
return true;
}
if( V > rAttr.V )
{
return false;
}
if( C < rAttr.C )
{
return true;
}
if( C > rAttr.C )
{
return false;
}
return T < rAttr.T;
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
388
]
]
]
|
b1732379ecfd719345f0de5e015332f0c53d3394 | 73acb5def25cb5693f6f5cdede8f5ba668f1d6ec | /LanTran/PhoneDlg.h | 51fc35db63518083b7c54ed20e59f28e09503c88 | [
"Apache-2.0"
]
| permissive | daoyuan14/lantran | ee4bec0cd4386507e001ebeaf548ae67fdb50bb5 | 066972873257d4c26739b8884e5fb95dc3127621 | refs/heads/master | 2021-01-23T13:35:38.296793 | 2010-10-10T13:01:20 | 2010-10-10T13:01:20 | 34,151,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,695 | h | #if !defined(AFX_PHONEDLG_H__064AC888_996B_4936_A677_DFF2B9A6917B__INCLUDED_)
#define AFX_PHONEDLG_H__064AC888_996B_4936_A677_DFF2B9A6917B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// PhoneDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CPhoneDlg dialog
#include "PhoneServerSocket.h"
#include "PhoneClientSocket.h"
#include "Sound.h"
#include <afxmt.h>
class CPhoneDlg : public CDialog
{
// Construction
public:
//==================================================
HMIXER m_hMixer;
MIXERCAPS m_mxcaps;
DWORD m_curvalue;
DWORD m_controlid;
//===================================================
CPhoneDlg(CWnd* pParent = NULL); // standard constructor
~CPhoneDlg();
// Dialog Data
//{{AFX_DATA(CPhoneDlg)
enum { IDD = IDD_DIALOG_PHONE };
CString m_sInputString;
CString m_sShowString;
UINT m_uPort; // NOTE: the ClassWizard will add data members here
//========================================================================
CSliderCtrl m_control;
//===============================================================================
//}}AFX_DATA
public:
void ProcessPendingAccept();
void CloseSessionSocket();
void ClearContent();
void OnClearconnection();
public:
bool m_bInit;
bool m_bClient;
CPhoneClientSocket m_clientsocket;
CPhoneServerSocket m_pListenSocket;
CPtrList m_connectionList;
CString m_sMsgList;
CSound m_sound;
CMutex m_mutex;
BOOL m_bIsFileClosed;
BOOL m_willchating;
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPhoneDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CPhoneDlg)
virtual BOOL OnInitDialog();
afx_msg void OnInputText();
afx_msg void OnSetserver();
afx_msg void OnNewsend();
afx_msg void WriteBufferFull(LPARAM lp,WPARAM wp); // NOTE: the ClassWizard will add member functions here
afx_msg void OnConnectserver();
afx_msg void OnSound();
//=======================================================================================
afx_msg LONG OnMixerCtrlChange(UINT wParam, LONG lParam);
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
//============================================================
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PHONEDLG_H__064AC888_996B_4936_A677_DFF2B9A6917B__INCLUDED_)
| [
"clzqwdy@687b6e4e-9fc3-60ed-f37d-c8c0d9c0bbbd"
]
| [
[
[
1,
88
]
]
]
|
b29ac266a09f882e3eef924184d057d559a4469d | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /MediaPlayers/HttpLinkEngine.h | 789522e30d40b9788cbc28851b077a2bbaa9a172 | []
| no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,064 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * 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, 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 GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#ifndef _HttpLinkEngine_h_
#define _HttpLinkEngine_h_
#include "MediaPlayerEngine.h"
class BassVisualization;
class HttpLinkEngine:public MediaPlayerEngine
{
public:
HttpLinkEngine();
virtual ~HttpLinkEngine();
virtual void SetConfig(MediaEngineConfigOption meco, INT value) {}
virtual INT GetConfig(MediaEngineConfigOption meco) {return -1;}
virtual BOOL Supports(MediaEngineConfigOption meco) {return FALSE;}
virtual void SetEventTarget(EventTarget* evTarg) {}
virtual EventTarget* GetEventTarget() {return NULL;}
//This will be The MediaPlayer Engine
virtual BOOL Open(LPCTSTR str);
virtual void Close();
//Playback Commands
virtual BOOL Start();
virtual BOOL Pause() {return FALSE;}
virtual BOOL Stop() {return FALSE;}
virtual PlayState GetPlayState() {return m_ps;}
//Total Media Length in seconds
virtual INT GetMediaInfo(MediaEngineOptionalIntInfoEnum meoii) {return 0;}
virtual LPCTSTR GetLocation() {return m_URL.c_str();}
virtual DOUBLE GetMediaLength() {return 0.0;}
//Media Position is seconds
virtual DOUBLE GetMediaPos() {return 0.0;}
virtual void SetMediaPos(DOUBLE secs) {}
//Settings
//Should be between 0-100
virtual void SetVolume(INT volume);
virtual INT GetVolume() {return m_volume;}
virtual void SetMute(BOOL bMute) {m_mute = bMute;}
virtual BOOL GetMute() {return m_mute;}
virtual BOOL CanPlay(LPCTSTR str);
virtual MediaEngineState GetEngineState() {return MES_Ready;}
virtual MediaEngineErrorEnum GetLastError() {return MEE_NoError;}
virtual BOOL IsVideo() {return TRUE;}
virtual BOOL GetSoundData(MediaEngineSoundData mesd, void* buffer, UINT bufferLen)
{return FALSE;}
virtual const TCHAR* GetEngineDescription() {return _T("HttpLink");}
virtual void SetVideoContainerHWND(HWND hwnd) {}
virtual HWND GetVideoContainerHWND() {return 0;}
virtual void SetVideoPosition(int x, int y, int cx, int cy) {};
private:
std::tstring m_URL;
PlayState m_ps;
INT m_volume;
BOOL m_mute;
};
#endif
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
90
]
]
]
|
744e5779d043db81e3e0604f63f44a689b50b0e3 | b738fc6ffa2205ea210d10c395ae47b25ba26078 | /TUDT/TStunClient/NPeer.cpp | be26acf5d07b6633f27765cd9b9ee7eeeef79a4c | []
| no_license | RallyWRT/ppsocket | d8609233df9bba8d316a85a3d96919b8618ea4b6 | b4b0b16e2ceffe8a697905b1ef1aeb227595b110 | refs/heads/master | 2021-01-19T16:23:26.812183 | 2009-09-23T06:57:58 | 2009-09-23T06:57:58 | 35,471,076 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,054 | cpp | #include ".\npeer.h"
#include "../src/debug.h"
#include "NPeerMng.h"
#include <iostream>
using namespace std;
NPeer::NPeer(NPeerMng *pMng,unsigned int iPeerId)
{
ASSERT(NULL!=pMng);
m_pMng = pMng;
m_iPeerId = iPeerId;
m_currSocket = UDT::INVALID_SOCK;
//tianzuo,2009-6-19.这些功能移动到mng类的工厂函数中
//向Mng注册自己
//if(!m_pMng->AddPeer(iPeerId,this))
//{
// throw std::bad_exception("NPeer existed.");
//}
}
NPeer::~NPeer(void)
{
//tianzuo,2009-6-19.这些功能移动到MNG类的析构函数中
//让服务器删除所有与节点相关记录(而不仅仅是RemovePeer)
//m_pMng->ClosePeer(m_iPeerId);
}
//====多种连接方式====
//通过STUN服务器查询地址连接
bool NPeer::PeerConnect(int iWaitTime)
{
if (IsReady())
{
return true;
}
return m_pMng->PeerConnect(m_iPeerId,iWaitTime);
}
//知道地址,直接连接
bool NPeer::PeerConnect(const sockaddr* nameKnown, int namelen,bool bTrySTUN)
{
if (IsReady())
{
return true;
}
return m_pMng->PeerConnect(m_iPeerId,nameKnown,namelen,bTrySTUN);
}
//知道地址和辅助用户id,直接连接
bool NPeer::PeerConnect(const sockaddr* nameKnown, int namelen,int iHelperId,bool bTrySTUN)
{
if (IsReady())
{
return true;
}
return m_pMng->PeerConnect(m_iPeerId,nameKnown,namelen,iHelperId,bTrySTUN);
}
unsigned int NPeer::GetPeerId()
{
return m_iPeerId;
}
int NPeer::GetSpeed(int &iUpSpeed,int &iDownSpeed)
{
return 0;
}
int NPeer::SendPeerMsg(const char* pData,int iLen)
{
if (IsReady())
{
TBasePack *pBasePack = TPackData::Factory(pData,iLen);
int bRes = SendPack(pBasePack,TPackData::GetTotalLen(iLen));
delete[] pBasePack;
//return bRes;
if (bRes>0)
{
return iLen;
}
return -1;
}
else
{
return -1;
}
}
int NPeer::SendPack(const TBasePack *pPack,int iLen)
{
return UDT::sendmsg(m_currSocket,(char *)pPack,iLen,-1,true);
}
bool NPeer::IsReady()
{
return UDT::INVALID_SOCK!=m_currSocket;
}
NPeerMng *NPeer::GetPeerMng()
{
return m_pMng;
}
void NPeer::OnPeerConnected(bool bSuccess)
{
if (bSuccess)
{
std::cout<<m_iPeerId<<" 上线。"<<endl;
}
else
{
std::cout<<m_iPeerId<<" 连接失败"<<endl;
}
}
void NPeer::OnPeerDisConnected()
{
std::cout<<m_iPeerId<<" 断开连接。"<<endl;
//默认删除连接
m_pMng->ClosePeer(m_iPeerId);
}
void NPeer::OnPeerData(const char* pData, int ilen)
{
std::cout<<m_iPeerId<<" 说:"<<pData<<endl;
}
void NPeer::SetCurrentSocket(UDTSOCKET u)
{
if (m_currSocket==u)
{
return;
}
UDTSOCKET uOld = m_currSocket;
m_currSocket = u;
//socket从不可用变为可用,说明连接成功
if (uOld==UDT::INVALID_SOCK && u!=UDT::INVALID_SOCK)
{
OnPeerConnected(true);
}
//socket从可用变为不可用,说明连接断开
else if (uOld!=UDT::INVALID_SOCK && u==UDT::INVALID_SOCK)
{
OnPeerDisConnected();
}
}
UDTSOCKET NPeer::GetCurrentSocket()
{
return m_currSocket;
} | [
"tantianzuo@159e4f46-9839-11de-8efd-97b2a7529d09"
]
| [
[
[
1,
148
]
]
]
|
9bfd37074cf4f263704cb271d38c8c092733d4c1 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_kernel/include/iptv_kernel/MediaCaptureNotify.h | 01eac282c1355a1bc808aa755b12271ae66b6b42 | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | h | #ifndef MEDIA_CAPTURE_NOTIFY_H
#define MEDIA_CAPTURE_NOTIFY_H
#include "CAudioFrame.h"
enum MediaCaptureNotifyCode {
MCNC_CAPTURE_VIDEO_DATA, // Parameter class: MediaCaptureVideoDataParam
MCNC_CAPTURE_AUDIO_FRAME, // Parameter class: MediaCaptureAudioDataParam
};
/** @brief Base structure to send MediaCapture notifications.
*
*/
struct MediaCaptureParam
{
MediaCaptureNotifyCode m_code;
};
/** @brief MediaCapture notification structure.
*
*/
struct MediaCaptureVideoDataParam : public MediaCaptureParam
{
unsigned char *m_data;
unsigned long m_dataLength;
unsigned long m_width;
unsigned long m_height;
};
/** @brief MediaCapture notification structure.
*
*/
struct MediaCaptureAudioFrameParam : public MediaCaptureParam
{
CAudioFrame *m_audioFrame;
};
/** @brief Receives notifications from MediaCapture class.
*
* Any class that needs to receive MediaCapture notifications should
* be derived of this class.
*
*/
class MediaCaptureNotify
{
public:
virtual void OnMediaCaptureNotify(MediaCaptureParam ¶m) = 0;
};
#endif
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
51
]
]
]
|
fccc86fd214d61d8cb0b1269d2e31002728ab40e | 475150d6e2022a5391be49a7f2411fda6da46dde | /editmode.h | 759674da13354dad1c4c849ed6eb9c3e4beb7e68 | []
| no_license | theclakuh/Nonogramz | c1beffb1cd5783d22b1b462a52bade4c9d1acfc2 | a867ee476dbafe0b73eb98ace7a3c4d60365b9fe | refs/heads/master | 2021-01-23T00:07:20.997678 | 2011-12-20T23:18:43 | 2011-12-20T23:18:43 | 2,754,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | h | #ifndef EDITMODE_H
#define EDITMODE_H
#include "mode.h"
#include "solvestrategy.h"
#include "level.h"
#include "matrix.h"
class EditMode : public Mode
{
public:
EditMode(SolveStrategy *solver, int height, int width, Level level);
EditMode(SolveStrategy *solver, Matrix *matrix);
bool testCorrectness();
void setMatrix(Matrix *matrix);
private:
SolveStrategy *solver;
Level level;
SolveStrategy* getSolver();
void setSolver(SolveStrategy *solver);
};
#endif // EDITMODE_H
| [
"[email protected]"
]
| [
[
[
1,
26
]
]
]
|
905140cfd53a8608e1eafa0d53c257ff3b985b15 | 4891542ea31c89c0ab2377428e92cc72bd1d078f | /Arcanoid/Arcanoid/AI.cpp | 55a21007cbdc482e2c31fdded881737188300561 | []
| no_license | koutsop/arcanoid | aa32c46c407955a06c6d4efe34748e50c472eea8 | 5bfef14317e35751fa386d841f0f5fa2b8757fb4 | refs/heads/master | 2021-01-18T14:11:00.321215 | 2008-07-17T21:50:36 | 2008-07-17T21:50:36 | 33,115,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | cpp | /*
*author: koutsop
*/
#include <algorithm>
#include "AI.h"
#include "KeyLogger.h"
#include "MyTime.h"
#include "Terrain.h"
#define TIME_BRICK_STOP 7
#define TIME_BRICK_MOVE 1
#define NAIN_TIME 10
void AI::AIBricks(SpriteHolder* sh){
timestamp_t theTime = MyTime::GetGameTime();
static timestamp_t msec = 0;
static bool insert1 = false; //mono mia fora se TIME_BRICK_STOP sec na kanei thn for_each
static bool insert2 = false; //mono mia fora se TIME_BRICK_MOVE sec na kanei thn for_each
if( !msec ) { msec = theTime;}
else{
timestamp_t time = MyTime::GetGameDiffTimeInSec(theTime, msec);
if( time <= TIME_BRICK_STOP+TIME_BRICK_MOVE ){
if( time < TIME_BRICK_STOP && !insert1){
std::for_each(sh->GetFirst(), sh->GetEnd(), StopBricksFunctor());
insert1 = true;
insert2 = false;
}
else if( time >= TIME_BRICK_STOP && !insert2 ) {
std::for_each(sh->GetFirst(), sh->GetEnd(), SetSpeedFunctor());
insert1 = false;
insert2 = true;
}
}//end if
else { msec = 0; }
}
return;
}//end of AIBRICKS;
void AI::AINain(NainSpin *nain, int dx, int dy){
timestamp_t theTime = MyTime::GetGameTime();
static timestamp_t msec = 0;
if( !msec ) { msec = theTime;}
else{
timestamp_t time = MyTime::GetGameDiffTimeInSec(theTime, msec);
if( time >= NAIN_TIME && !nain->IsVisible() ){
nain->SetPosition(dx, dy);
nain->SetVisibility(true);
msec = 0;
}
}
return;
}
| [
"koutsop@5c4dd20e-9542-0410-abe3-ad2d610f3ba4"
]
| [
[
[
1,
63
]
]
]
|
04f7f90cfc8efb36e5d05a78bdb6d5d4d9a84256 | 4be39d7d266a00f543cf89bcf5af111344783205 | /PortableFileSystemWatcher/PortableFileSystemWatcher/LinuxImpl.hpp | 7296bb78be0e615e92b2b6d1b4782a85bced6400 | []
| no_license | nkzxw/lastigen-haustiere | 6316bb56b9c065a52d7c7edb26131633423b162a | bdf6219725176ae811c1063dd2b79c2d51b4bb6a | refs/heads/master | 2021-01-10T05:42:05.591510 | 2011-02-03T14:59:11 | 2011-02-03T14:59:11 | 47,530,529 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,204 | hpp | #ifndef LinuxImpl_h__
#define LinuxImpl_h__
#include <string>
#include <cstdio> //<stdio.h>
#include <cstdlib> //<stdlib.h>
#include <cerrno> //<errno.h>
//#include <pthread.h> // Threads
#include <sys/types.h>
#include <sys/inotify.h>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
namespace detail
{
typedef boost::shared_ptr<boost::thread> HeapThread;
class LinuxImpl
{
public:
~LinuxImpl()
{
closing_ = true;
printf("removing watch...\n");
int retRMWatch = inotify_rm_watch( fileDescriptor_, watchDescriptor_ );
printf("retRMWatch: %d\n", retRMWatch);
printf("closing file descriptor...\n");
int retClose = close( fileDescriptor_ );
printf("retClose: %d\n", retClose);
thread_->join();
}
void startMonitoring(const std::string& path)
{
fileDescriptor_ = inotify_init();
if ( fileDescriptor_ < 0 )
{
perror( "inotify_init" );
}
//watchDescriptor_ = inotify_add_watch( fileDescriptor_, "/home/fernando/temp1", IN_MODIFY | IN_CREATE | IN_DELETE );
watchDescriptor_ = inotify_add_watch( fileDescriptor_, path.c_str(), IN_MODIFY | IN_CREATE | IN_DELETE );
thread_.reset( new boost::thread( boost::bind(&LinuxImpl::HandleDirectoryChange, this) ) );
}
// Event Handlers
FileSystemEventHandler Changed;
FileSystemEventHandler Created;
FileSystemEventHandler Deleted;
RenamedEventHandler Renamed;
private:
void HandleDirectoryChange() //TODO: rename
{
int i = 0;
char buffer[BUF_LEN];
//TODO: while
//TODO: boost asio buffer
printf("reading in file descriptor\n");
int length = read( fileDescriptor_, buffer, BUF_LEN );
printf("end reading on file descriptor\n");
if (! closing_)
{
printf("length: %d\n", length);
if ( length < 0 )
{
perror( "read" );
}
//int j;
//for (j = 0; j<length; j++)
//{
// printf("buffer[j]: %d\n", buffer[j]);
//}
printf("i: %d\n", i);
while ( i < length )
{
printf("inside the 'while'\n");
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; //TODO:
printf("event: %d\n", (void*)event);
printf("event->len: %d\n", event->len);
if ( event->len )
{
if ( event->mask & IN_CREATE )
{
if (this->Created)
{
//std::string fileName( event->name );
FileSystemEventArgs temp;
temp.Name = event->name; //fileName;
//threadObject->This->Created(temp);
this->Created(temp);
}
//if ( event->mask & IN_ISDIR )
//{
// printf( "The directory '%s' was created.\n", event->name );
//}
//else
//{
// printf( "The file '%s' was created.\n", event->name );
//}
}
else if ( event->mask & IN_DELETE )
{
if ( event->mask & IN_ISDIR )
{
printf( "The directory '%s' was deleted.\n", event->name );
}
else
{
printf( "The file '%s' was deleted.\n", event->name );
}
}
else if ( event->mask & IN_MODIFY )
{
if ( event->mask & IN_ISDIR )
{
printf( "The directory '%s' was modified.\n", event->name );
}
else
{
printf( "The file '%s' was modified.\n", event->name );
}
}
}
i += EVENT_SIZE + event->len;
printf("i: %d\n", i);
}
}
////( void ) inotify_rm_watch( fileDescriptor_, wd );
////( void ) close( fileDescriptor_ );
//int retRMWatch = inotify_rm_watch( fileDescriptor_, watchDescriptor_ );
//printf("retRMWatch: %d\n", retRMWatch);
//int retClose = close( fileDescriptor_ );
//printf("retClose: %d\n", retClose);
//pthread_join( thread1, NULL);
////printf("Thread 1 returns: %d\n", iret1);
//exit(0);
}
HeapThread thread_;
int fileDescriptor_; // file descriptor
int watchDescriptor_;
bool closing_;
};
typedef LinuxImpl PlatformImpl;
}
#endif // LinuxImpl_h__
| [
"fpelliccioni@c29dda52-a065-11de-a33f-1de61d9b9616"
]
| [
[
[
1,
187
]
]
]
|
8cf6646c19aad86aa6b57032b39a1eb202b5ad40 | bdec684af41a89175c2dffe95dda9ab565913118 | /CNP-digger/DlgMedics.cpp | 6a3392c42c67e90d7406475af9d9500a32f1603c | []
| no_license | laurdimana/cnp-digger | 3608afd24b5e8d2cffefd5c9766696a3ea5ea506 | f15c89b0734a803ddaa7956abe501a2324070399 | refs/heads/master | 2020-05-04T14:37:10.774333 | 2011-08-21T14:40:18 | 2011-08-21T14:40:18 | 33,174,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | #include "stdafx.h"
#include "DlgMedics.h"
#include "CNP-digger.h"
#include "DlgCreateMedic.h"
BEGIN_MESSAGE_MAP( CDlgMedics, CDialogEx )
ON_BN_CLICKED( IDOK, OnBtnSelect )
ON_BN_CLICKED( MEDICS_BTN_ADD, OnBtnAdd )
ON_BN_CLICKED( MEDICS_BTN_DEL, OnBtnDel )
END_MESSAGE_MAP()
////////////////////////////////////////////////// Constructor / Destructor /////////////////////////////////////////////////
CDlgMedics::CDlgMedics() : CDialogEx( CDlgMedics::IDD )
{
}
CDlgMedics::~CDlgMedics()
{
}
///////////////////////////////////////////////////// Overrides ////////////////////////////////////////////////////////////
void CDlgMedics::DoDataExchange( CDataExchange* pDX )
{
CDialogEx::DoDataExchange( pDX );
DDX_Control( pDX, MEDICS_CMB_MEDIC, m_cmbMedic );
DDX_Control( pDX, IDOK, m_btnSelect );
DDX_Control( pDX, MEDICS_BTN_ADD, m_btnAdd );
DDX_Control( pDX, MEDICS_BTN_DEL, m_btnDel );
DDX_Control( pDX, IDCANCEL, m_btnCancel );
}
BOOL CDlgMedics::OnInitDialog()
{
CDialogEx::OnInitDialog();
CMapStringToMedic::CPair *pCurVal = theApp.m_pProgramData->GetMedicsMap()->PGetFirstAssoc();
m_cmbMedic.ResetContent();
while ( pCurVal != NULL )
{
CString strMedic;
strMedic.Format( L"%s %s %s",
pCurVal->value.strLastName,
pCurVal->value.strFirstName,
pCurVal->value.strID );
m_cmbMedic.AddString( strMedic );
pCurVal = theApp.m_pProgramData->GetMedicsMap()->PGetNextAssoc( pCurVal );
}
return TRUE;
}
///////////////////////////////////////////////////////// Events ///////////////////////////////////////////////////////////////
void CDlgMedics::OnBtnSelect()
{
if ( m_cmbMedic.GetWindowTextLength() > 0 )
{
CString strMedic;
m_cmbMedic.GetWindowText( strMedic );
strMedic = strMedic.Right( strMedic.GetLength() - strMedic.ReverseFind( L' ' ) - 1 );
theApp.m_pProgramData->SetCurrentMedicID( strMedic );
CDialogEx::OnOK();
}
else
{
AfxMessageBox( L"Please select a medic.", MB_ICONERROR );
}
}
void CDlgMedics::OnBtnAdd()
{
CDlgCreateMedic dlgCreateMedic;
if ( dlgCreateMedic.DoModal() == IDOK )
{
TRACE( L"@ CDlgMedics::OnBtnAdd -> Create medic %s, %s, %s\n",
dlgCreateMedic.GetID(), dlgCreateMedic.GetLastName(), dlgCreateMedic.GetFirstName() );
theApp.m_pProgramData->AddMedic( dlgCreateMedic.GetID(), dlgCreateMedic.GetLastName(), dlgCreateMedic.GetFirstName() );
MEDIC *m = new MEDIC;
m->strID = dlgCreateMedic.GetID();
m->strLastName = dlgCreateMedic.GetLastName();
m->strFirstName = dlgCreateMedic.GetFirstName();
theApp.m_pWorkerThread->PostThreadMessage( WM_ADD_MEDIC_TO_XML, (WPARAM)m, 0 );
OnInitDialog();
}
}
void CDlgMedics::OnBtnDel()
{
if ( m_cmbMedic.GetWindowTextLength() > 0 )
{
CString strMedic;
m_cmbMedic.GetWindowText( strMedic );
strMedic = strMedic.Right( strMedic.GetLength() - strMedic.ReverseFind( L' ' ) - 1 );
MEDIC medic = theApp.m_pProgramData->GetMedic( strMedic );
CString strMsg;
strMsg.Format( L"Delete medic %s %s %s ?",
medic.strLastName, medic.strFirstName, medic.strID );
if ( AfxMessageBox( strMsg, MB_YESNO | MB_ICONQUESTION ) == IDYES )
{
TRACE( L"@ CDlgMedics::OnBtnDel -> Delete medic %s %s %s\n",
medic.strLastName, medic.strFirstName, medic.strID );
theApp.m_pProgramData->DeleteMedic( medic.strID );
MEDIC *m = new MEDIC;
m->strID = medic.strID;
m->strFirstName = medic.strFirstName;
m->strLastName = medic.strLastName;
theApp.m_pWorkerThread->PostThreadMessage( WM_DELETE_MEDIC_FROM_XML, (WPARAM)m, 0 );
OnInitDialog();
}
}
else
{
AfxMessageBox( L"Please select a medic.", MB_ICONERROR );
}
}
| [
"[email protected]@e5df85e2-01b0-9024-d18a-d63b7c2566ab"
]
| [
[
[
1,
137
]
]
]
|
905b56e1d6c7f2fdd4e0d0e8525395b24eacff27 | c1eae8224c4d3d380cc83ff6b218ba2a9df8d687 | /Source Codes/MeshUI/Numerical/Heap.h | aab1f2140496087dd6467b569d240ce6c2d01e8b | []
| no_license | pizibing/noise-removal | 15bad5c0fe1b3b5fb3f8b775040fc3dfeb48e49b | c087356bfa07305ce7ac6cce8745b1e676d6dc42 | refs/heads/master | 2016-09-06T17:40:15.754799 | 2010-03-05T06:47:59 | 2010-03-05T06:47:59 | 34,849,474 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,256 | h | // Heap.h: interface for the CHeap class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_HEAP_H__D95FA3CF_0DC1_4A82_9DE2_B872CF7EEAFA__INCLUDED_)
#define AFX_HEAP_H__D95FA3CF_0DC1_4A82_9DE2_B872CF7EEAFA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define MAX_NODE 65535
typedef struct node Node;
struct node{
int type;
int type2;
double pos[3];
void * p;
double v;
Node * next;
Node * prev;
};
class CHeap // Min Heap ×îС¶Ñ
{
public:
int heapFind(int type);
int heapFindPair(int type, int type2);
bool heapEmpty();
void heapCheck();
Node* heapSelectMin();
void heapConstruct(Node* a[], int N);
void heapPrint();
void heapDownheap(void* v);
void heapUpheap(void* v);
Node* heapNode(void* v);
int heapIndex(void* v);
void heapsort(Node* a[], int N);
Node* replace(Node* v);
Node* Remove();
void downheap(int k);
void insert(Node* v);
void upheap(int k);
void construct(Node* b[], int M);
int NodeCompare(Node* a, Node* b);
int N;
int capacity;
Node** a;
CHeap();
virtual ~CHeap();
};
#endif // !defined(AFX_HEAP_H__D95FA3CF_0DC1_4A82_9DE2_B872CF7EEAFA__INCLUDED_)
| [
"weihongyu1987@f7207f0a-2814-11df-8e46-3928208ddfa0"
]
| [
[
[
1,
57
]
]
]
|
a7aade840a66cf1a802d178ce2937a88a42f9859 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /GameClient/NetworkService.cpp | 74849d1f7edf3a46ac4dd71bb1ff4fd85dda07d8 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,673 | cpp | #include "StdAfx.h"
#include "NetworkService.h"
#include "Application.h"
#include <process.h>
BEGIN_DISPATCHER_TABLE( CNetworkService, message_type )
DECLARE_DISPATCH( SYSTEM_MESSAGE_TYPE, OnSystemMessage )
END_DISPATCHER_TABLE( CNetworkService, message_type )
BEGIN_DISPATCHER_TABLE( CNetworkService, system_code )
DECLARE_DISPATCH( EVENT_CONNECT, OnNetworkConnect )
DECLARE_DISPATCH( EVENT_CLOSE, OnNetworkClose )
END_DISPATCHER_TABLE( CNetworkService, system_code )
BEGIN_DISPATCHER_TABLE( CNetworkService, server_code )
//DECLARE_DISPATCH( C2S_REGIST_REQUEST, OnRegistRequest )
//DECLARE_DISPATCH( C2S_LOGON_REQUEST, OnLogonRequest )
END_DISPATCHER_TABLE( CNetworkService, server_code )
CNetworkService::CNetworkService(void)
{
}
CNetworkService::~CNetworkService(void)
{
}
void CNetworkService::Start()
{
m_thread_h = _beginthreadex( NULL, 0, Svc, (void*)this, 0, NULL );
}
void CNetworkService::Stop()
{
m_bWork = false;
WaitForSingleObject( (HANDLE)m_thread_h, -1 );
}
__declspec( thread ) _uint32 network_h = -1;
__declspec( thread ) userdata_ptr puserdata = 0;
unsigned int __stdcall CNetworkService::Svc( _lpvoid pParam )
{
CNetworkService *pService = (CNetworkService*)pParam;
pService->m_bWork = true;
INetPacket *pPacket = NULL;
while( pService->m_bWork )
{
pPacket = Application::Instance().GetMessageQueue()->PopMessage();
if( pPacket )
{
network_h = pPacket->handle();
puserdata = (userdata_ptr)pPacket->userdata();
if( puserdata == 0 )
{
long_ptr param[1] = { (long_ptr)&network_h };
ExecuteState( Operator_GetUserdata, (long_ptr)param );
puserdata = (userdata_ptr)param[0];
}
// 处理数据
pService->Process( pPacket->data(), pPacket->size() );
pPacket->release();
}
}
return 0;
}
void CNetworkService::Process( const char* data, size_t size )
{
unsigned char type = *data;
func pFunc = DISPATCHER_GET( message_type, type );
if( pFunc )
return (this->*pFunc)( data+1, size-1 );
}
void CNetworkService::OnSystemMessage( const char* data, size_t size )
{
unsigned char type = *data;
func pFunc = DISPATCHER_GET( system_code, type );
if( pFunc )
return (this->*pFunc)( data+1, size-1 );
}
void CNetworkService::OnServerMessage( const char* data, size_t size )
{
unsigned char type = *data;
func pFunc = DISPATCHER_GET( server_code, type );
if( pFunc )
return (this->*pFunc)( data+1, size-1 );
}
//////////////////////////////////////////////////////////////////////////
// 系统消息
//////////////////////////////////////////////////////////////////////////
//--------------------------------------------------------//
// created: 8:12:2009 17:56
// filename: NetworkService
// author: Albert.xu
//
// purpose: 用户建立连接
//--------------------------------------------------------//
void CNetworkService::OnNetworkConnect( const char* data, size_t size )
{
userdata_ptr pud = new userdata();
pud->id = 0;
pud->order = 0;
long_ptr param[2] = { (long_ptr)&network_h, (long_ptr)pud };
ExecuteState( Operator_SetUserdata, (long_ptr)param );
}
//--------------------------------------------------------//
// created: 8:12:2009 17:56
// filename: NetworkService
// author: Albert.xu
//
// purpose: 用户断开连接
//--------------------------------------------------------//
void CNetworkService::OnNetworkClose( const char* data, size_t size )
{
long_ptr param[1] = { (long_ptr)&network_h };
ExecuteState( Operator_GetUserdata, (long_ptr)param );
userdata_ptr ud = (userdata_ptr)param[0];
delete ud;
}
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
131
]
]
]
|
72263f6df003467676938e7ec4f9b14b6b7fc284 | 14298a990afb4c8619eea10988f9c0854ec49d29 | /PowerBill四川电信专用版本/ibill_source/public.cpp | 9e7f8e46ccbfcd9cfe27667a87785cd2991d47db | []
| 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 | 17,152 | cpp |
#include "public.h"
//写日志
void __fastcall SaveLog(const char * chMessage)
{
if(LogFile != NULL)
{
fprintf(LogFile,"%s:%s\n",FormatDateTime("yyyy-mm-dd hh:nn:ss",Now()),chMessage);
}
if(SlentMode)
{
printf("%s:%s\n",FormatDateTime("yyyy-mm-dd hh:nn:ss",Now()),chMessage);
}
}
//出错时写日志并显示错误信息
void __fastcall ShowErrorMessage(HWND hWnd,const char * chMessage,bool DoExitProcess,int ExitCode)
{
SaveLog(chMessage);
if(!SlentMode)
MessageBox(hWnd,chMessage,"错误",MB_OK | MB_ICONSTOP);
if(InCmdMode && DoExitProcess)
{
fclose(LogFile);
ExitProcess(ExitCode);
}
}
//Param1是结束符
AnsiString __fastcall RightBCDToStr(const unsigned char chSource[],int len,int Param1,int Param2)
{
char str[50] = {0};
char c;
int nPos = 0;
for(int i = 0;i < len;i++)
{
c = chSource[i] >> 4 & 0x0f;
if(c >= 0x0a && c <= 0x0e)
str[nPos] = c + 65;
else
str[nPos] = c + 48;
if(c == Param1)
break;
++nPos;
c = chSource[i] & 0x0f;
if(c == Param1)
break;
if(c >= 0x0a && c <= 0x0e)
str[nPos] = c + 65;
else
str[nPos] = c + 48;
++nPos;
}
str[nPos] = 0x00;
return AnsiString(str);
}
void __fastcall RightBCDToStr(char chDest[],const unsigned char chSource[],int len,int Param1,int Param2)
{
char c;
int pos = 0;
for(int i = 0;i < len;i++)
{
c = chSource[i] >> 4 & 0x0f;
if(c >= 0x0a && c <= 0x0e)
chDest[pos] = c + 65;
else
chDest[pos] = c + 48;
if(c == Param1)
break;
++pos;
c = chSource[i] & 0x0f;
if(c == Param1)
break;
if(c >= 0x0a && c <= 0x0e)
chDest[pos] = c + 65;
else
chDest[pos] = c + 48;
++pos;
}
chDest[pos] = 0x00;
}
//将字符串转换为BCD右对齐格式
//返回转换后的数组长度
//chSource : 要转换的字符串.字符串中只允许0-9和BCDE字符,不在此范围内的字符将被忽略
//Param1 : 是BCD的终止符
//len : 传入的chDest的长度
int __fastcall StrToRightBCD(char chDest[],const char * chSource,int len,int Param1,int Param2)
{
memset(&chDest[0],(char)Param1,len);
unsigned char ch1,ch2; //ch1是源,ch2是目标
int pos = 0;
int SourceLen = strlen(chSource);
int n = 0;
while(true)
{
ch1 = * (chSource + n);
if(ch1 >= '0' && ch1 <= '9') //数字
{
ch2 = ch1 - 48;
}
else if(ch1 >= 'A' && ch1 <= 'E') //字符
{
ch2 = ch1 - 55;
}
ch2 = (ch2 << 4);
++n;
if(n >= SourceLen)
{
* (chDest + pos) = ch2 + 0x0f;
break;
}
ch1 = * (chSource + n);
if(ch1 >= '0' && ch1 <= '9') //数字
{
ch2 = ch2 + (ch1 - 48);
}
else if(ch1 >= 'A' && ch1 <= 'E') //字符
{
ch2 = ch2 + (ch1 - 55);
}
* (chDest + pos) = ch2;
++n;
if(n >= SourceLen)
break;
++pos;
}
return pos;
}
//将一个字符串转换为BCD左对齐格式
//返回转换后的数组长度
//chSource : 要转换的字符串.字符串中只允许0-9和BCDE字符,不在此范围内的字符将被忽略
//Param1 : 是BCD的终止符
//len : 传入的chDest的长度
int __fastcall StrToLeftBCD(char chDest[],const char * chSource,int len,int Param1,int Param2)
{
memset(&chDest[0],(char)Param1,len);
unsigned char ch1,ch2; //ch1是源,ch2是目标
int pos = 0;
int SourceLen = strlen(chSource);
int n = 0;
while(true)
{
ch1 = * (chSource + n);
if(ch1 >= '1' && ch1 <= '9') //数字
{
ch2 = ch1 - 48;
}
else if(ch1 >= 'B' && ch1 <= 'E') //字符
{
ch2 = ch1 - 55;
}
else if(ch1 == '0')
{
ch2 = 0x0a;
}
++n;
if(n >= SourceLen)
{
* (chDest + pos) = 0xf0 + ch2;
break;
}
ch1 = * (chSource + n);
if(ch1 >= '1' && ch1 <= '9') //数字
{
ch2 = ch2 + ((ch1 - 48) << 4);
}
else if(ch1 >= 'B' && ch1 <= 'E') //字符
{
ch2 = ch2 + ((ch1 - 55) << 4);
}
else if(ch1 == '0')
{
ch2 = ch2 + 0xa0;
}
if(ch2 < 0x0f)
ch2 = 0xf0 + ch2;
* (chDest + pos) = ch2;
++n;
if(n >= SourceLen)
break;
++pos;
}
return pos;
}
//BCD左对齐转换为字符串
//Param1是终止符
AnsiString __fastcall LeftBCDToStr(const unsigned char chSource[],int len,int Param1,int Param2)
{
char str[20] = {0};
char c;
int pos = 0;
for(int i = 0;i < len;i++)
{
//处理低位
if(chSource[i] == 0xff)
break;
c = (chSource[i] & 0x0f);
if(c == Param1)
break;
if(c > 0x0a)
c += 55;
else
c = (c % 10) + 48;
str[pos] = c;
++pos;
//处理高位
c = (chSource[i] >> 4) & 0x0f;
if(c == Param1)
break;
if(c > 0x0a)
c += 55;
else
c = (c % 10) + 48;
str[pos] = c;
++pos;
}
str[pos] = 0x00;
return AnsiString(str);
}
//转换char 为 short int
AnsiString __fastcall ConvertToWord(const unsigned char chSource[],int len,int Param1,int Param2)
{
unsigned short int * Value = (unsigned short int *)chSource;
try
{
return StrToInt(* Value);
}
catch(...)
{
return 32767;
}
}
//转换char 为 unsigned int
AnsiString __fastcall ConvertToUINT(const unsigned char chSource[],int len,int Param1,int Param2)
{
unsigned long int * Value = (unsigned long int *)chSource;
try
{
return (* Value);
}
catch(...)
{
return 2147483648;
}
}
//转换char 为 int
AnsiString __fastcall ConvertToInt(const unsigned char chSource[],int len,int Param1,int Param2)
{
long int * Value = (long int *)chSource;
try
{
return (* Value);
}
catch(...)
{
return 2147483648;
}
}
//转换char 为 byte
AnsiString __fastcall ConvertToBYTE(const unsigned char chSource[],int len,int Param1,int Param2)
{
//unsigned long int * Value = (unsigned long int *)chSource;
try
{
return StrToInt(* chSource);
}
catch(...)
{
return 255;
}
}
//将话单中的秒数转换为日期时间
//Param1是基准时间
AnsiString __fastcall ConvertBasedDateTime(const unsigned char chSource[],int len,int Param1,int Param2)
{
int * Seconds = (int *)chSource;
return FormatDateTime("yyyy-mm-dd hh:nn:ss",IncSecond(* ((TDateTime *)Param1),* (Seconds)));
}
//转换RBCD_YYYYMMDDHHMMSS为日期时间
AnsiString __fastcall ConvertRBCDYYYYMMDDHHMMSS(const unsigned char chSource[],int len,int Param1,int Param2)
{
char Year[5] = {0};
char Month[3] = {0};
char Day[3] = {0};
char Hour[3] = {0};
char Minute[3] = {0};
char Second[3] = {0};
RightBCDToStr(Year,chSource,2,Param1,0);
RightBCDToStr(Month,(unsigned char *)(chSource + 2),1,Param1,0);
RightBCDToStr(Day,(unsigned char *)(chSource + 3),1,Param1,0);
RightBCDToStr(Hour,(unsigned char *)(chSource + 4),1,Param1,0);
RightBCDToStr(Minute,(unsigned char *)(chSource + 5),1,Param1,0);
RightBCDToStr(Second,(unsigned char *)(chSource + 6),1,Param1,0);
char chResult[18] = {0};
strcat(&chResult[0],&Year[0]);
strcat(&chResult[0],"-");
strcat(&chResult[0],&Month[0]);
strcat(&chResult[0],"-");
strcat(&chResult[0],&Day[0]);
strcat(&chResult[0]," ");
strcat(&chResult[0],&Hour[0]);
strcat(&chResult[0],":");
strcat(&chResult[0],&Minute[0]);
strcat(&chResult[0],":");
strcat(&chResult[0],&Second[0]);
return AnsiString(chResult);
}
//转换RBCD_YYMMDDHHMMSS为日期时间
AnsiString __fastcall ConvertRBCDYYMMDDHHMMSS(const unsigned char chSource[],int len,int Param1,int Param2)
{
char Year[5] = {'2','0',0,0,0};
char Month[3] = {0};
char Day[3] = {0};
char Hour[3] = {0};
char Minute[3] = {0};
char Second[3] = {0};
RightBCDToStr(&Year[2],chSource,1,Param1,0);
RightBCDToStr(Month,(unsigned char *)(chSource + 1),1,Param1,0);
RightBCDToStr(Day,(unsigned char *)(chSource + 2),1,Param1,0);
RightBCDToStr(Hour,(unsigned char *)(chSource + 3),1,Param1,0);
RightBCDToStr(Minute,(unsigned char *)(chSource + 4),1,Param1,0);
RightBCDToStr(Second,(unsigned char *)(chSource + 5),1,Param1,0);
char chResult[18] = {0};
strcat(&chResult[0],&Year[0]);
strcat(&chResult[0],"-");
strcat(&chResult[0],&Month[0]);
strcat(&chResult[0],"-");
strcat(&chResult[0],&Day[0]);
strcat(&chResult[0]," ");
strcat(&chResult[0],&Hour[0]);
strcat(&chResult[0],":");
strcat(&chResult[0],&Minute[0]);
strcat(&chResult[0],":");
strcat(&chResult[0],&Second[0]);
return AnsiString(chResult);
}
AnsiString __fastcall ConvertStr(const unsigned char chSource[],int len,int Param1,int Param2)
{
char * Buffer = new char[++len];
memset(Buffer,0,len);
memcpy(Buffer,chSource,--len);
AnsiString Result = Buffer;
delete[] Buffer;
return Result;
}
//转换STR_YYYYMMDDHHMMSS为日期时间格式
AnsiString __fastcall ConvertSTRYYYYMMDDHHMMSS(const unsigned char chSource[],int len,int Param1,int Param2)
{
/*
char Year[5] = {0};
char Month[3] = {0};
char Day[3] = {0};
char Hour[3] = {0};
char Minute[3] = {0};
char Second[3] = {0};
strncpy(&Year[0],chSource,4);
strncpy(&Month[0],(unsigned char *)(chSource + 4),2);
strncpy(&Day[0],(unsigned char *)(chSource + 6),2);
strncpy(&Hour[0],(unsigned char *)(chSource + 8),2);
strncpy(&Minute[0],(unsigned char *)(chSource + 10),2);
strncpy(&Second[0],(unsigned char *)(chSource + 12),2);
char chResult[18] = {0};
strcat(&chResult[0],&Year[0]);
strcat(&chResult[0],"-");
strcat(&chResult[0],&Month[0]);
strcat(&chResult[0],"-");
strcat(&chResult[0],&Day[0]);
strcat(&chResult[0]," ");
strcat(&chResult[0],&Hour[0]);
strcat(&chResult[0],":");
strcat(&chResult[0],&Minute[0]);
strcat(&chResult[0],":");
strcat(&chResult[0],&Second[0]);
return AnsiString(chResult);
*/
char chResult[20] = {0,0,0,0,'-',0,0,'-',0,0,' ',0,0,':',0,0,':',0,0,0};
strncpy(&chResult[0],chSource,4);
strncpy(&chResult[5],(unsigned char *)(chSource + 4),2);
strncpy(&chResult[8],(unsigned char *)(chSource + 6),2);
strncpy(&chResult[11],(unsigned char *)(chSource + 8),2);
strncpy(&chResult[14],(unsigned char *)(chSource + 10),2);
strncpy(&chResult[17],(unsigned char *)(chSource + 12),2);
return AnsiString(chResult);
}
//转换二进制日期和时间
AnsiString __fastcall ConvertBINYYMMDDHHMMSS(const unsigned char * chSource,int len,int Param1,int Param2)
{
short int Year = 2000 + * (chSource);
short int Month = * (chSource + 1);
short int Day = * (chSource + 2);
short int Hour = * (chSource + 3);
short int Minute = * (chSource + 4);
short int Second = * (chSource + 5);
short int MilliSecond = 0;
try
{
return FormatDateTime("yyyy-mm-dd hh:nn:ss",EncodeDateTime(Year,Month,Day,Hour,Minute,Second,MilliSecond));
}
catch(...)
{
return "1900-01-01 00:00:00";
}
}
//判断给定的字符串中是否含有非数字字符
bool __fastcall IsNumber(const char * chStr)
{
char ch;
int len = strlen(chStr);
if(len == 0)
return false;
for(int n = 0;n < len;n++)
{
ch = *(chStr + n);
if(n == 0 && (ch == '-' || ch == '+'))
continue;
if(ch < '0' || ch > '9')
return false;
}
return true;
}
int __fastcall StrToIntEx(const char * chStr)
{
char ch1[11] = {0};
ch1[0] = '0';
char ch2 = 0;
for(int n = 0;n < (int)strlen(chStr);n++)
{
memcpy(&ch2,(chStr + n),1);
if(ch2 < '0' || ch2 > '9')
break;
ch1[n] = ch2;
}
return StrToInt(ch1);
}
//返回字符串chScan在chStr中最后一将出现的基于0的位置
//如果chStr中没有找到chScan,返回-1.
int StrRScan(const char * chStr,const char * chScan,int len)
{
if(len == -1)
len = strlen(chScan);
for(int n = strlen(chStr) - len/* - 1*/;n > -1;n--)
{
if(chStr[n] == *(chScan) && memcmp((void *)(chStr + n),chScan,len) == 0)
return n;
}
return -1;
}
//搜索一个字符在字符串中第一次出现的位置
//如果成功返回该字符在字符串中出现的基于0的位置
//否则返回-1.
int StrLScan(const char * chStr,const char * chScan,int len)
{
//int len = strlen(chScan);
if(len == -1)
len = strlen(chScan);
for(int n = 0;n < (int)strlen(chStr);n++)
{
if(chStr[n] == *(chScan) && memcmp(chStr + n,chScan,len) == 0)
return n;
}
return -1;
}
AnsiString EncryFTPPassword(AnsiString Password)
{
TWCDESComp * WCDESComp = new TWCDESComp(NULL);
AnsiString Result = WCDESComp->EncryStrHex(Password,FTP_PASSWORD_KEY);
delete WCDESComp;
return Result;
}
AnsiString DecryFTPPassword(AnsiString Password)
{
TWCDESComp * WCDESComp = new TWCDESComp(NULL);
AnsiString Result = WCDESComp->DecryStrHex(Password,FTP_PASSWORD_KEY);
delete WCDESComp;
return Result;
}
void Split(AnsiString str,AnsiString Separator,TStringList * List)
{
AnsiString str1 = str;
int pos1 = str.Pos(Separator);
while(pos1 > 0)
{
List->Add(str1.SubString(0,pos1 - 1));
str1 = str1.SubString(pos1 + 1,str1.Length() - pos1);
pos1 = str1.Pos(Separator);
}
if(str1 != "")
List->Add(str1);
}
AnsiString __fastcall XMLDecode(AnsiString str)
{
str = AnsiReplaceText(str,"[ASCII=124]","|");
str = AnsiReplaceText(str,"[ASCII=32]"," ");
str = AnsiReplaceText(str,"[ASCII=13]","[回车符]");
str = AnsiReplaceText(str,"[ASCII=10]","[换行符]");
str = AnsiReplaceText(str,"[ASCII=9]","[制表符]");
return str;
}
AnsiString __fastcall XMLDecodeForField(AnsiString str)
{
str = AnsiReplaceText(str,"[ASCII=124]","|");
str = AnsiReplaceText(str,"[ASCII=32]"," ");
str = AnsiReplaceText(str,"[ASCII=13]","\n");
str = AnsiReplaceText(str,"[ASCII=10]","\r");
str = AnsiReplaceText(str,"[ASCII=9]","\t");
return str;
}
AnsiString __fastcall XMLEncode(AnsiString str)
{
str = AnsiReplaceText(str,"|","[ASCII=124]");
str = AnsiReplaceText(str," ","[ASCII=32]");
str = AnsiReplaceText(str,"\t","[ASCII=9]");
str = AnsiReplaceText(str,"[回车符]","[ASCII=13]");
str = AnsiReplaceText(str,"[换行符]","[ASCII=10]");
str = AnsiReplaceText(str,"[制表符]","[ASCII=9]");
return str;
}
AnsiString __fastcall GetErrorString(int nCode)
{
LPVOID lpMsgBuf;
lpMsgBuf=LocalLock(LocalAlloc(LMEM_MOVEABLE|LMEM_ZEROINIT,1000));
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|
FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
nCode,
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL);
AnsiString ErrorString = AnsiString((char *)lpMsgBuf).Trim();
if(ErrorString=="")
{
ErrorString = "未知错误:" + IntToStr(nCode);
}
LocalFree(lpMsgBuf);
return ErrorString;
}
AnsiString DecrySysInfo(AnsiString String)
{
TWCDESComp * WCDESComp = new TWCDESComp(NULL);
AnsiString Result = WCDESComp->DecryStrHex(String,SYS_INFO_KEY);
delete WCDESComp;
return Result;
}
//加密系统信息
AnsiString EncrySysInfo(AnsiString String)
{
TWCDESComp * WCDESComp = new TWCDESComp(NULL);
AnsiString Result = WCDESComp->EncryStrHex(String,SYS_INFO_KEY);
delete WCDESComp;
return Result;
}
AnsiString EncryRegisteCode(AnsiString String)
{
TWCDESComp * WCDESComp = new TWCDESComp(NULL);
AnsiString Result = WCDESComp->EncryStrHex(String,"ACCSEED\r\n\t_@($*!&MM<ASJJKDSA\t0x28KHFTAL98213897(*&$#($&@!)234hdslfsarewq90");
delete WCDESComp;
return Result;
}
AnsiString GetATempFileName(AnsiString TempDirectory,AnsiString FileName)
{
if(!DirectoryExists(TempDirectory)&&!CreateDir(TempDirectory))
{
return "";
}
else if(TempDirectory.Pos("\\") < 1)
{
TempDirectory = TempDirectory + "\\";
}
char chTempFileName[MAX_PATH];
GetTempFileName(TempDirectory.c_str(),FileName.c_str(),0,&chTempFileName[0]);
//MessageBox(NULL,FileName.c_str(),"",MB_OK);
AnsiString Result = chTempFileName;
DeleteFile(Result);
//memset(&chTempFileName[0],0,MAX_PATH);
//GetTempFileName(TempDirectory.c_str(),FileName.c_str(),0,&chTempFileName[0]);
//Result = chTempFileName;
return Result;
}
unsigned int GetLocalFileSize(AnsiString FileName)
{
HANDLE hFile = CreateFile(FileName.c_str(),GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
return -1;
}
unsigned int FileSize = GetFileSize(hFile,NULL);
CloseHandle(hFile);
return FileSize;
}
AnsiString GetFullFTPFileName(AnsiString FileName)
{
if(FileName.SubString(1,6) != "ftp://")
return FileName;
AnsiString Str = FileName.SubString(7,FileName.Length() - 6);
int pos = Str.Pos("@");
Str = Str.SubString(pos + 1,Str.Length() - pos);
return "ftp://" + AnsiReplaceStr(AnsiReplaceStr(Str,"||",""),"|PASV|","");
}
| [
"cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99"
]
| [
[
[
1,
610
]
]
]
|
ea1b4b0059530b5aea64e1a7450b1503d4f70f7a | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/game/g_syscalls.cpp | 1c63ce5a206d6815f876c42606446c2c64116010 | []
| no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,896 | cpp | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
#include"game_pch.h"
// this file is only included when building a dll
// g__G_syscalls.asm is included instead when building a qvm
#ifdef Q3_VM
#error "Do not use in VM build"
#endif
static SysCallArg (QDECL *_G_syscall)(int id, const SysCallArgs &args) = (SysCallArg (QDECL *)(int, const SysCallArgs &args))-1;
EXTERN_C DLLEXPORT void dllEntry( SysCallArg (QDECL *syscallptr)(int id, const SysCallArgs &args) )
{
_G_syscall = syscallptr;
}
void _G_trap_Printf( const char *fmt ) {
SysCallArgs args(1);
args[0]=fmt;
_G_syscall( G_PRINT, args );
}
void _G_trap_Error( const char *fmt ) {
SysCallArgs args(1);
args[0]=fmt;
_G_syscall( G_ERROR, args );
}
int _G_trap_Milliseconds( void ) {
return (int)_G_syscall( G_MILLISECONDS,SysCallArgs(0) );
}
int _G_trap_Argc( void ) {
return (int)_G_syscall( G_ARGC,SysCallArgs(0) );
}
void _G_trap_Argv( int n, char *buffer, int bufferLength ) {
SysCallArgs args(3);
args[0]=n;
args[1]=buffer;
args[2]=bufferLength;
_G_syscall( G_ARGV, args);
}
int _G_trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
SysCallArgs args(3);
args[0]=qpath;
args[1]=f;
args[2]=(int)mode;
return (int)_G_syscall( G_FS_FOPEN_FILE, args);
}
void _G_trap_FS_Read( void *buffer, int len, fileHandle_t f ) {
SysCallArgs args(3);
args[0]=buffer;
args[1]=len;
args[2]=(int)f;
_G_syscall( G_FS_READ, args);
}
void _G_trap_FS_Write( const void *buffer, int len, fileHandle_t f ) {
SysCallArgs args(3);
args[0]=buffer;
args[1]=len;
args[2]=(int)f;
_G_syscall( G_FS_WRITE, args);
}
void _G_trap_FS_FCloseFile( fileHandle_t f ) {
SysCallArgs args(1);
args[0]=(int)f;
_G_syscall( G_FS_FCLOSE_FILE, args);
}
int _G_trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
SysCallArgs args(4);
args[0]=path;
args[1]=extension;
args[2]=listbuf;
args[3]=bufsize;
return (int)_G_syscall( G_FS_GETFILELIST, args);
}
int _G_trap_FS_Seek( fileHandle_t f, long offset, int origin ) {
SysCallArgs args(3);
args[0]=(int)f;
args[1]=offset;
args[2]=origin;
return (int)_G_syscall( G_FS_SEEK, args );
}
void _G_trap_SendConsoleCommand( int exec_when, const char *text ) {
SysCallArgs args(2);
args[0]=exec_when;
args[1]=text;
_G_syscall( G_SEND_CONSOLE_COMMAND, args );
}
void _G_trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, int flags ) {
SysCallArgs args(4);
args[0]=cvar;
args[1]=var_name;
args[2]=value;
args[3]=flags;
_G_syscall( G_CVAR_REGISTER, args );
}
void _G_trap_Cvar_Update( vmCvar_t *cvar ) {
SysCallArgs args(1);
args[0]=cvar;
_G_syscall( G_CVAR_UPDATE, args );
}
void _G_trap_Cvar_Set( const char *var_name, const char *value ) {
SysCallArgs args(2);
args[0]=var_name;
args[1]=value;
_G_syscall( G_CVAR_SET, args );
}
int _G_trap_Cvar_VariableIntegerValue( const char *var_name ) {
SysCallArgs args(1);
args[0]=var_name;
return (int)_G_syscall( G_CVAR_VARIABLE_INTEGER_VALUE, args );
}
void _G_trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
SysCallArgs args(3);
args[0]=var_name;
args[1]=buffer;
args[2]=bufsize;
_G_syscall( G_CVAR_VARIABLE_STRING_BUFFER, args);
}
void _G_trap_LocateGameData( gentity_t *gEnts, int numGEntities, int sizeofGEntity_t,
playerState_t *clients, int sizeofGClient ) {
SysCallArgs args(5);
args[0]=gEnts;
args[1]=numGEntities;
args[2]=sizeofGEntity_t;
args[3]=clients;
args[4]=sizeofGClient;
_G_syscall( G_LOCATE_GAME_DATA, args);
}
void _G_trap_DropClient( int clientNum, const char *reason ) {
SysCallArgs args(2);
args[0]=clientNum;
args[1]=reason;
_G_syscall( G_DROP_CLIENT, args);
}
void _G_trap_SendServerCommand( int clientNum, const char *text ) {
SysCallArgs args(2);
args[0]=clientNum;
args[1]=text;
_G_syscall( G_SEND_SERVER_COMMAND, args);
}
void _G_trap_SetConfigstring( int num, const char *string ) {
SysCallArgs args(2);
args[0]=num;
args[1]=string;
_G_syscall( G_SET_CONFIGSTRING, args);
}
void _G_trap_GetConfigstring( int num, char *buffer, int bufferSize ) {
SysCallArgs args(3);
args[0]=num;
args[1]=buffer;
args[2]=bufferSize;
_G_syscall( G_GET_CONFIGSTRING, args );
}
void _G_trap_GetUserinfo( int num, char *buffer, int bufferSize ) {
SysCallArgs args(3);
args[0]=num;
args[1]=buffer;
args[2]=bufferSize;
_G_syscall( G_GET_USERINFO, args);
}
void _G_trap_SetUserinfo( int num, const char *buffer ) {
SysCallArgs args(2);
args[0]=num;
args[1]=buffer;
_G_syscall( G_SET_USERINFO, args );
}
void _G_trap_GetServerinfo( char *buffer, int bufferSize ) {
SysCallArgs args(2);
args[0]=buffer;
args[1]=bufferSize;
_G_syscall( G_GET_SERVERINFO, args);
}
void _G_trap_SetBrushModel( gentity_t *ent, const char *name ) {
SysCallArgs args(2);
args[0]=ent;
args[1]=name;
_G_syscall( G_SET_BRUSH_MODEL, args);
}
void _G_trap_Trace( trace_t *results, const bvec3_t start, const bvec3_t mins, const bvec3_t maxs,
const bvec3_t end, int passEntityNum, int contentmask ) {
SysCallArgs args(7);
args[0]=results;
args[1]=start;
args[2]=mins;
args[3]=maxs;
args[4]=end;
args[5]=passEntityNum;
args[6]=contentmask;
_G_syscall( G_TRACE, args );
}
void _G_trap_TraceCapsule( trace_t *results, const bvec3_t start, const bvec3_t mins, const bvec3_t maxs,
const bvec3_t end, int passEntityNum, int contentmask ) {
SysCallArgs args(7);
args[0]=results;
args[1]=start;
args[2]=mins;
args[3]=maxs;
args[4]=end;
args[5]=passEntityNum;
args[6]=contentmask;
_G_syscall( G_TRACECAPSULE, args );
}
int _G_trap_PointContents( const bvec3_t point, int passEntityNum ) {
SysCallArgs args(2);
args[0]=point;
args[1]=passEntityNum;
return (int)_G_syscall( G_POINT_CONTENTS, args );
}
qboolean _G_trap_InPVS( const bvec3_t p1, const bvec3_t p2 ) {
SysCallArgs args(2);
args[0]=p1;
args[1]=p2;
return (int)(qboolean)_G_syscall( G_IN_PVS, args );
}
qboolean _G_trap_InPVSIgnorePortals( const bvec3_t p1, const bvec3_t p2 ) {
SysCallArgs args(2);
args[0]=p1;
args[1]=p2;
return (int)(qboolean)_G_syscall( G_IN_PVS_IGNORE_PORTALS, args);
}
void _G_trap_AdjustAreaPortalState( gentity_t *ent, qboolean open ) {
SysCallArgs args(2);
args[0]=ent;
args[1]=open;
_G_syscall( G_ADJUST_AREA_PORTAL_STATE, args);
}
qboolean _G_trap_AreasConnected( int area1, int area2 ) {
SysCallArgs args(2);
args[0]=area1;
args[1]=area2;
return (int)(qboolean)_G_syscall( G_AREAS_CONNECTED, args );
}
void _G_trap_LinkEntity( gentity_t *ent ) {
SysCallArgs args(1);
args[0]=ent;
_G_syscall( G_LINKENTITY, args );
}
void _G_trap_UnlinkEntity( gentity_t *ent ) {
SysCallArgs args(1);
args[0]=ent;
_G_syscall( G_UNLINKENTITY, args );
}
int _G_trap_EntitiesInBox( const bvec3_t mins, const bvec3_t maxs, int *list, int maxcount ) {
SysCallArgs args(4);
args[0]=mins;
args[1]=maxs;
args[2]=list;
args[3]=maxcount;
return (int)_G_syscall( G_ENTITIES_IN_BOX, args );
}
qboolean _G_trap_EntityContact( const bvec3_t mins, const bvec3_t maxs, const gentity_t *ent ) {
SysCallArgs args(3);
args[0]=mins;
args[1]=maxs;
args[2]=ent;
return (int)(qboolean)_G_syscall( G_ENTITY_CONTACT, args );
}
qboolean _G_trap_EntityContactCapsule( const bvec3_t mins, const bvec3_t maxs, const gentity_t *ent ) {
SysCallArgs args(3);
args[0]=mins;
args[1]=maxs;
args[2]=ent;
return (int)(qboolean)_G_syscall( G_ENTITY_CONTACTCAPSULE, args);
}
int _G_trap_BotAllocateClient( void ) {
return (int)_G_syscall( G_BOT_ALLOCATE_CLIENT,SysCallArgs(0) );
}
void _G_trap_BotFreeClient( int clientNum ) {
SysCallArgs args(1);
args[0]=clientNum;
_G_syscall( G_BOT_FREE_CLIENT, args );
}
void _G_trap_GetUsercmd( int clientNum, usercmd_t *cmd ) {
SysCallArgs args(2);
args[0]=clientNum;
args[1]=cmd;
_G_syscall( G_GET_USERCMD, args );
}
qboolean _G_trap_GetEntityToken( char *buffer, int bufferSize ) {
SysCallArgs args(2);
args[0]=buffer;
args[1]=bufferSize;
return (int)(qboolean)_G_syscall( G_GET_ENTITY_TOKEN, args);
}
int _G_trap_DebugPolygonCreate(int color, int numPoints, bvec3_t *points) {
SysCallArgs args(3);
args[0]=color;
args[1]=numPoints;
args[2]=points;
return (int)_G_syscall( G_DEBUG_POLYGON_CREATE, args );
}
void _G_trap_DebugPolygonDelete(int id) {
SysCallArgs args(1);
args[0]=id;
_G_syscall( G_DEBUG_POLYGON_DELETE, args);
}
int _G_trap_RealTime( qtime_t *qtime ) {
SysCallArgs args(1);
args[0]=qtime;
return (int)_G_syscall( G_REAL_TIME, args);
}
// BotLib traps start here
int _G_trap_BotLibSetup( void ) {
return (int)_G_syscall( BOTLIB_SETUP,SysCallArgs(0) );
}
int _G_trap_BotLibShutdown( void ) {
return (int)_G_syscall( BOTLIB_SHUTDOWN,SysCallArgs(0) );
}
int _G_trap_BotLibVarSet(const char *var_name, const char *value) {
SysCallArgs args(2);
args[0]=var_name;
args[1]=value;
return (int)_G_syscall( BOTLIB_LIBVAR_SET, args);
}
int _G_trap_BotLibVarGet(const char *var_name, char *value, int size) {
SysCallArgs args(3);
args[0]=var_name;
args[1]=value;
args[2]=size;
return (int)_G_syscall( BOTLIB_LIBVAR_GET, args);
}
int _G_trap_BotLibDefine(const char *string) {
SysCallArgs args(1);
args[0]=string;
return (int)_G_syscall( BOTLIB_PC_ADD_GLOBAL_DEFINE, args );
}
int _G_trap_BotLibStartFrame(gfixed time) {
SysCallArgs args(1);
args[0]=time;
return (int)_G_syscall( BOTLIB_START_FRAME, args );
}
int _G_trap_BotLibLoadMap(const char *mapname) {
SysCallArgs args(1);
args[0]=mapname;
return (int)_G_syscall( BOTLIB_LOAD_MAP, args );
}
int _G_trap_BotLibUpdateEntity(int ent, void /* struct bot_updateentity_s */ *bue) {
SysCallArgs args(2);
args[0]=ent;
args[1]=bue;
return (int)_G_syscall( BOTLIB_UPDATENTITY, args );
}
int _G_trap_BotLibTest(int parm0, char *parm1, bvec3_t parm2, bvec3_t parm3) {
SysCallArgs args(4);
args[0]=parm0;
args[1]=parm1;
args[2]=parm2;
args[3]=parm3;
return (int)_G_syscall( BOTLIB_TEST, args );
}
int _G_trap_BotGetSnapshotEntity( int clientNum, int sequence ) {
SysCallArgs args(2);
args[0]=clientNum;
args[1]=sequence;
return (int)_G_syscall( BOTLIB_GET_SNAPSHOT_ENTITY, args);
}
int _G_trap_BotGetServerCommand(int clientNum, char *message, int size) {
SysCallArgs args(3);
args[0]=clientNum;
args[1]=message;
args[2]=size;
return (int)_G_syscall( BOTLIB_GET_CONSOLE_MESSAGE, args);
}
void _G_trap_BotUserCommand(int clientNum, usercmd_t *ucmd) {
SysCallArgs args(2);
args[0]=clientNum;
args[1]=ucmd;
_G_syscall( BOTLIB_USER_COMMAND, args);
}
void _G_trap_AAS_EntityInfo(int entnum, void /* struct aas_entityinfo_s */ *info) {
SysCallArgs args(2);
args[0]=entnum;
args[1]=info;
_G_syscall( BOTLIB_AAS_ENTITY_INFO, args);
}
int _G_trap_AAS_Initialized(void) {
return (int)_G_syscall( BOTLIB_AAS_INITIALIZED,SysCallArgs(0) );
}
void _G_trap_AAS_PresenceTypeBoundingBox(int presencetype, bvec3_t mins, bvec3_t maxs) {
SysCallArgs args(3);
args[0]=presencetype;
args[1]=mins;
args[2]=maxs;
_G_syscall( BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX, args);
}
gfixed _G_trap_AAS_Time(void) {
return (gfixed)_G_syscall( BOTLIB_AAS_TIME,SysCallArgs(0) );
}
int _G_trap_AAS_PointAreaNum(bvec3_t point) {
SysCallArgs args(1);
args[0]=point;
return (int)_G_syscall( BOTLIB_AAS_POINT_AREA_NUM, args );
}
int _G_trap_AAS_PointReachabilityAreaIndex(bvec3_t point) {
SysCallArgs args(1);
args[0]=point;
return (int)_G_syscall( BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX, args );
}
int _G_trap_AAS_TraceAreas(bvec3_t start, bvec3_t end, int *areas, bvec3_t *points, int maxareas) {
SysCallArgs args(5);
args[0]=start;
args[1]=end;
args[2]=areas;
args[3]=points;
args[4]=maxareas;
return (int)_G_syscall( BOTLIB_AAS_TRACE_AREAS, args);
}
int _G_trap_AAS_BBoxAreas(bvec3_t absmins, bvec3_t absmaxs, int *areas, int maxareas) {
SysCallArgs args(4);
args[0]=absmins;
args[1]=absmaxs;
args[2]=areas;
args[3]=maxareas;
return (int)_G_syscall( BOTLIB_AAS_BBOX_AREAS, args);
}
int _G_trap_AAS_AreaInfo( int areanum, void /* struct aas_areainfo_s */ *info ) {
SysCallArgs args(2);
args[0]=areanum;
args[1]=info;
return (int)_G_syscall( BOTLIB_AAS_AREA_INFO, args );
}
int _G_trap_AAS_PointContents(bvec3_t point) {
SysCallArgs args(1);
args[0]=point;
return (int)_G_syscall( BOTLIB_AAS_POINT_CONTENTS, args );
}
int _G_trap_AAS_NextBSPEntity(int ent) {
SysCallArgs args(1);
args[0]=ent;
return (int)_G_syscall( BOTLIB_AAS_NEXT_BSP_ENTITY, args );
}
int _G_trap_AAS_ValueForBSPEpairKey(int ent, const char *key, char *value, int size) {
SysCallArgs args(4);
args[0]=ent;
args[1]=key;
args[2]=value;
args[3]=size;
return (int)_G_syscall( BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY, args);
}
int _G_trap_AAS_VectorForBSPEpairKey(int ent, const char *key, bvec3_t v) {
SysCallArgs args(3);
args[0]=ent;
args[1]=key;
args[2]=v;
return (int)_G_syscall( BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY, args );
}
int _G_trap_AAS_FloatForBSPEpairKey(int ent, const char *key, gfixed *value) {
SysCallArgs args(3);
args[0]=ent;
args[1]=key;
args[2]=value;
return (int)_G_syscall( BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY, args);
}
int _G_trap_AAS_IntForBSPEpairKey(int ent, const char *key, int *value) {
SysCallArgs args(3);
args[0]=ent;
args[1]=key;
args[2]=value;
return (int)_G_syscall( BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY, args);
}
int _G_trap_AAS_AreaReachability(int areanum) {
SysCallArgs args(1);
args[0]=areanum;
return (int)_G_syscall( BOTLIB_AAS_AREA_REACHABILITY, args );
}
int _G_trap_AAS_AreaTravelTimeToGoalArea(int areanum, bvec3_t origin, int goalareanum, int travelflags) {
SysCallArgs args(4);
args[0]=areanum;
args[1]=origin;
args[2]=goalareanum;
args[3]=travelflags;
return (int)_G_syscall( BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA, args );
}
int _G_trap_AAS_EnableRoutingArea( int areanum, int enable ) {
SysCallArgs args(2);
args[0]=areanum;
args[1]=enable;
return (int)_G_syscall( BOTLIB_AAS_ENABLE_ROUTING_AREA, args );
}
int _G_trap_AAS_PredictRoute(void /*struct aas_predictroute_s*/ *route, int areanum, bvec3_t origin,
int goalareanum, int travelflags, int maxareas, int maxtime,
int stopevent, int stopcontents, int stoptfl, int stopareanum) {
SysCallArgs args(11);
args[0]=route;
args[1]=areanum;
args[2]=origin;
args[3]=goalareanum;
args[4]=travelflags;
args[5]=maxareas;
args[6]=maxtime;
args[7]=stopevent;
args[8]=stopcontents;
args[9]=stoptfl;
args[10]=stopareanum;
return (int)_G_syscall( BOTLIB_AAS_PREDICT_ROUTE, args );
}
int _G_trap_AAS_AlternativeRouteGoals(bvec3_t start, int startareanum, bvec3_t goal, int goalareanum, int travelflags,
void /*struct aas_altroutegoal_s*/ *altroutegoals, int maxaltroutegoals,
int type) {
SysCallArgs args(8);
args[0]=start;
args[1]=startareanum;
args[2]=goal;
args[3]=goalareanum;
args[4]=travelflags;
args[5]=altroutegoals;
args[6]=maxaltroutegoals;
args[7]=type;
return (int)_G_syscall( BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL, args );
}
int _G_trap_AAS_Swimming(bvec3_t origin) {
SysCallArgs args(1);
args[0]=origin;
return (int)_G_syscall( BOTLIB_AAS_SWIMMING, args);
}
int _G_trap_AAS_PredictClientMovement(void /* struct aas_clientmove_s */ *move, int entnum, bvec3_t origin, int presencetype,
int onground, bvec3_t velocity, bvec3_t cmdmove, int cmdframes, int maxframes,
gfixed frametime, int stopevent, int stopareanum, int visualize) {
SysCallArgs args(13);
args[0]=move;
args[1]=entnum;
args[2]=origin;
args[3]=presencetype;
args[4]=onground;
args[5]=velocity;
args[6]=cmdmove;
args[7]=cmdframes;
args[8]=maxframes;
args[9]=frametime;
args[10]=stopevent;
args[11]=stopareanum;
args[12]=visualize;
return (int)_G_syscall( BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT, args);
}
void _G_trap_EA_Say(int client, const char *str) {
SysCallArgs args(2);
args[0]=client;
args[1]=str;
_G_syscall( BOTLIB_EA_SAY, args);
}
void _G_trap_EA_SayTeam(int client, const char *str) {
SysCallArgs args(2);
args[0]=client;
args[1]=str;
_G_syscall( BOTLIB_EA_SAY_TEAM, args);
}
void _G_trap_EA_Command(int client, const char *command) {
SysCallArgs args(2);
args[0]=client;
args[1]=command;
_G_syscall( BOTLIB_EA_COMMAND, args);
}
void _G_trap_EA_Action(int client, int action) {
SysCallArgs args(2);
args[0]=client;
args[1]=action;
_G_syscall( BOTLIB_EA_ACTION, args );
}
void _G_trap_EA_Gesture(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_GESTURE, args );
}
void _G_trap_EA_Talk(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_TALK, args );
}
void _G_trap_EA_Attack(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_ATTACK, args );
}
void _G_trap_EA_Use(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_USE, args );
}
void _G_trap_EA_Respawn(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_RESPAWN, args );
}
void _G_trap_EA_Crouch(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_CROUCH, args );
}
void _G_trap_EA_MoveUp(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_MOVE_UP, args );
}
void _G_trap_EA_MoveDown(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_MOVE_DOWN, args );
}
void _G_trap_EA_MoveForward(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_MOVE_FORWARD, args );
}
void _G_trap_EA_MoveBack(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_MOVE_BACK, args );
}
void _G_trap_EA_MoveLeft(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_MOVE_LEFT, args );
}
void _G_trap_EA_MoveRight(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_MOVE_RIGHT, args );
}
void _G_trap_EA_SelectWeapon(int client, int weapon) {
SysCallArgs args(2);
args[0]=client;
args[1]=weapon;
_G_syscall( BOTLIB_EA_SELECT_WEAPON, args );
}
void _G_trap_EA_Jump(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_JUMP, args );
}
void _G_trap_EA_DelayedJump(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_DELAYED_JUMP, args );
}
void _G_trap_EA_Move(int client, avec3_t dir, bfixed speed) {
SysCallArgs args(3);
args[0]=client;
args[1]=dir;
args[2]=speed;
_G_syscall( BOTLIB_EA_MOVE, args );
}
void _G_trap_EA_View(int client, avec3_t viewangles) {
SysCallArgs args(2);
args[0]=client;
args[1]=viewangles;
_G_syscall( BOTLIB_EA_VIEW, args );
}
void _G_trap_EA_EndRegular(int client, gfixed thinktime) {
SysCallArgs args(2);
args[0]=client;
args[1]=thinktime;
_G_syscall( BOTLIB_EA_END_REGULAR, args );
}
void _G_trap_EA_GetInput(int client, gfixed thinktime, void /* struct bot_input_s */ *input) {
SysCallArgs args(3);
args[0]=client;
args[1]=thinktime;
args[2]=input;
_G_syscall( BOTLIB_EA_GET_INPUT, args);
}
void _G_trap_EA_ResetInput(int client) {
SysCallArgs args(1);
args[0]=client;
_G_syscall( BOTLIB_EA_RESET_INPUT, args );
}
int _G_trap_BotLoadCharacter(const char *charfile, gfixed skill) {
SysCallArgs args(2);
args[0]=charfile;
args[1]=skill;
return (int)_G_syscall( BOTLIB_AI_LOAD_CHARACTER, args);
}
void _G_trap_BotFreeCharacter(int character) {
SysCallArgs args(1);
args[0]=character;
_G_syscall( BOTLIB_AI_FREE_CHARACTER, args );
}
gfixed _G_trap_Characteristic_Float(int character, int index) {
SysCallArgs args(2);
args[0]=character;
args[1]=index;
return (gfixed)_G_syscall( BOTLIB_AI_CHARACTERISTIC_FLOAT, args );
}
gfixed _G_trap_Characteristic_BFloat(int character, int index, gfixed min, gfixed max) {
SysCallArgs args(4);
args[0]=character;
args[1]=index;
args[2]=min;
args[3]=max;
return (gfixed)_G_syscall( BOTLIB_AI_CHARACTERISTIC_BFLOAT, args );
}
int _G_trap_Characteristic_Integer(int character, int index) {
SysCallArgs args(2);
args[0]=character;
args[1]=index;
return (int)_G_syscall( BOTLIB_AI_CHARACTERISTIC_INTEGER, args );
}
int _G_trap_Characteristic_BInteger(int character, int index, int min, int max) {
SysCallArgs args(4);
args[0]=character;
args[1]=index;
args[2]=min;
args[3]=max;
return (int)_G_syscall( BOTLIB_AI_CHARACTERISTIC_BINTEGER, args );
}
void _G_trap_Characteristic_String(int character, int index, char *buf, int size) {
SysCallArgs args(4);
args[0]=character;
args[1]=index;
args[2]=buf;
args[3]=size;
_G_syscall( BOTLIB_AI_CHARACTERISTIC_STRING, args);
}
int _G_trap_BotAllocChatState(void) {
return (int)_G_syscall( BOTLIB_AI_ALLOC_CHAT_STATE,SysCallArgs(0) );
}
void _G_trap_BotFreeChatState(int handle) {
SysCallArgs args(1);
args[0]=handle;
_G_syscall( BOTLIB_AI_FREE_CHAT_STATE, args);
}
void _G_trap_BotQueueConsoleMessage(int chatstate, int type, const char *message) {
SysCallArgs args(3);
args[0]=chatstate;
args[1]=type;
args[2]=message;
_G_syscall( BOTLIB_AI_QUEUE_CONSOLE_MESSAGE, args);
}
void _G_trap_BotRemoveConsoleMessage(int chatstate, int handle) {
SysCallArgs args(2);
args[0]=chatstate;
args[1]=handle;
_G_syscall( BOTLIB_AI_REMOVE_CONSOLE_MESSAGE, args);
}
int _G_trap_BotNextConsoleMessage(int chatstate, void /* struct bot_consolemessage_s */ *cm) {
SysCallArgs args(2);
args[0]=chatstate;
args[1]=cm;
return (int)_G_syscall( BOTLIB_AI_NEXT_CONSOLE_MESSAGE, args);
}
int _G_trap_BotNumConsoleMessages(int chatstate) {
SysCallArgs args(1);
args[0]=chatstate;
return (int)_G_syscall( BOTLIB_AI_NUM_CONSOLE_MESSAGE, args);
}
void _G_trap_BotInitialChat(int chatstate, const char *type, int mcontext, const char *var0, const char *var1, const char *var2,
const char *var3, const char *var4, const char *var5, const char *var6, const char *var7 ) {
SysCallArgs args(11);
args[0]=chatstate;
args[1]=type;
args[2]=mcontext;
args[3]=var0;
args[4]=var1;
args[5]=var2;
args[6]=var3;
args[7]=var4;
args[8]=var5;
args[9]=var6;
args[10]=var7;
_G_syscall( BOTLIB_AI_INITIAL_CHAT, args );
}
int _G_trap_BotNumInitialChats(int chatstate, const char *type) {
SysCallArgs args(2);
args[0]=chatstate;
args[1]=type;
return (int)_G_syscall( BOTLIB_AI_NUM_INITIAL_CHATS, args);
}
int _G_trap_BotReplyChat(int chatstate, const char *message, int mcontext, int vcontext, const char *var0, const char *var1,
const char *var2, const char *var3, const char *var4, const char *var5, const char *var6, const char *var7 ) {
SysCallArgs args(12);
args[0]=chatstate;
args[1]=message;
args[2]=mcontext;
args[3]=vcontext;
args[4]=var0;
args[5]=var1;
args[6]=var2;
args[7]=var3;
args[8]=var4;
args[9]=var5;
args[10]=var6;
args[11]=var7;
return (int)_G_syscall( BOTLIB_AI_REPLY_CHAT, args );
}
int _G_trap_BotChatLength(int chatstate) {
SysCallArgs args(1);
args[0]=chatstate;
return (int)_G_syscall( BOTLIB_AI_CHAT_LENGTH, args);
}
void _G_trap_BotEnterChat(int chatstate, int client, int sendto) {
SysCallArgs args(3);
args[0]=chatstate;
args[1]=client;
args[2]=sendto;
_G_syscall( BOTLIB_AI_ENTER_CHAT, args );
}
void _G_trap_BotGetChatMessage(int chatstate, char *buf, int size) {
SysCallArgs args(3);
args[0]=chatstate;
args[1]=buf;
args[2]=size;
_G_syscall( BOTLIB_AI_GET_CHAT_MESSAGE, args);
}
int _G_trap_StringContains(const char *str1, const char *str2, int casesensitive) {
SysCallArgs args(3);
args[0]=str1;
args[1]=str2;
args[2]=casesensitive;
return (int)_G_syscall( BOTLIB_AI_STRING_CONTAINS, args);
}
int _G_trap_BotFindMatch(const char *str, void /* struct bot_match_s */ *match, unsigned long int context) {
SysCallArgs args(3);
args[0]=str;
args[1]=match;
args[2]=(int)context;
return (int)_G_syscall( BOTLIB_AI_FIND_MATCH, args);
}
void _G_trap_BotMatchVariable(void /* struct bot_match_s */ *match, int variable, char *buf, int size) {
SysCallArgs args(4);
args[0]=match;
args[1]=variable;
args[2]=buf;
args[3]=size;
_G_syscall( BOTLIB_AI_MATCH_VARIABLE, args);
}
void _G_trap_UnifyWhiteSpaces(char *string) {
SysCallArgs args(1);
args[0]=string;
_G_syscall( BOTLIB_AI_UNIFY_WHITE_SPACES, args);
}
void _G_trap_BotReplaceSynonyms(char *string, unsigned long int context) {
SysCallArgs args(2);
args[0]=string;
args[1]=(int)context;
_G_syscall( BOTLIB_AI_REPLACE_SYNONYMS, args);
}
int _G_trap_BotLoadChatFile(int chatstate, const char *chatfile, const char *chatname) {
SysCallArgs args(3);
args[0]=chatstate;
args[1]=chatfile;
args[2]=chatname;
return (int)_G_syscall( BOTLIB_AI_LOAD_CHAT_FILE, args);
}
void _G_trap_BotSetChatGender(int chatstate, int gender) {
SysCallArgs args(2);
args[0]=chatstate;
args[1]=gender;
_G_syscall( BOTLIB_AI_SET_CHAT_GENDER, args);
}
void _G_trap_BotSetChatName(int chatstate, const char *name, int client) {
SysCallArgs args(3);
args[0]=chatstate;
args[1]=name;
args[2]=client;
_G_syscall( BOTLIB_AI_SET_CHAT_NAME, args);
}
void _G_trap_BotResetGoalState(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_RESET_GOAL_STATE, args);
}
void _G_trap_BotResetAvoidGoals(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_RESET_AVOID_GOALS, args);
}
void _G_trap_BotRemoveFromAvoidGoals(int goalstate, int number) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=number;
_G_syscall( BOTLIB_AI_REMOVE_FROM_AVOID_GOALS, args);
}
void _G_trap_BotPushGoal(int goalstate, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=goal;
_G_syscall( BOTLIB_AI_PUSH_GOAL, args );
}
void _G_trap_BotPopGoal(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_POP_GOAL, args );
}
void _G_trap_BotEmptyGoalStack(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_EMPTY_GOAL_STACK, args);
}
void _G_trap_BotDumpAvoidGoals(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_DUMP_AVOID_GOALS, args);
}
void _G_trap_BotDumpGoalStack(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_DUMP_GOAL_STACK, args);
}
void _G_trap_BotGoalName(int number, char *name, int size) {
SysCallArgs args(3);
args[0]=number;
args[1]=name;
args[2]=size;
_G_syscall( BOTLIB_AI_GOAL_NAME, args );
}
int _G_trap_BotGetTopGoal(int goalstate, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=goal;
return (int)_G_syscall( BOTLIB_AI_GET_TOP_GOAL, args );
}
int _G_trap_BotGetSecondGoal(int goalstate, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=goal;
return (int)_G_syscall( BOTLIB_AI_GET_SECOND_GOAL, args );
}
int _G_trap_BotChooseLTGItem(int goalstate, bvec3_t origin, int *inventory, int travelflags) {
SysCallArgs args(4);
args[0]=goalstate;
args[1]=origin;
args[2]=inventory;
args[3]=travelflags;
return (int)_G_syscall( BOTLIB_AI_CHOOSE_LTG_ITEM, args);
}
int _G_trap_BotChooseNBGItem(int goalstate, bvec3_t origin, int *inventory, int travelflags,
void /* struct bot_goal_s */ *ltg, gfixed maxtime) {
SysCallArgs args(6);
args[0]=goalstate;
args[1]=origin;
args[2]=inventory;
args[3]=travelflags;
args[4]=ltg;
args[5]=maxtime;
return (int)_G_syscall( BOTLIB_AI_CHOOSE_NBG_ITEM, args );
}
int _G_trap_BotTouchingGoal(bvec3_t origin, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(2);
args[0]=origin;
args[1]=goal;
return (int)_G_syscall( BOTLIB_AI_TOUCHING_GOAL, args);
}
int _G_trap_BotItemGoalInVisButNotVisible(int viewer, bvec3_t eye, avec3_t viewangles, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(4);
args[0]=viewer;
args[1]=eye;
args[2]=viewangles;
args[3]=goal;
return (int)_G_syscall( BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE, args );
}
int _G_trap_BotGetLevelItemGoal(int index, const char *classname, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(3);
args[0]=index;
args[1]=classname;
args[2]=goal;
return (int)_G_syscall( BOTLIB_AI_GET_LEVEL_ITEM_GOAL, args);
}
int _G_trap_BotGetNextCampSpotGoal(int num, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(2);
args[0]=num;
args[1]=goal;
return (int)_G_syscall( BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL, args);
}
int _G_trap_BotGetMapLocationGoal(char *name, void /* struct bot_goal_s */ *goal) {
SysCallArgs args(2);
args[0]=name;
args[1]=goal;
return (int)_G_syscall( BOTLIB_AI_GET_MAP_LOCATION_GOAL, args);
}
gfixed _G_trap_BotAvoidGoalTime(int goalstate, int number) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=number;
return (gfixed)_G_syscall( BOTLIB_AI_AVOID_GOAL_TIME, args);
}
void _G_trap_BotSetAvoidGoalTime(int goalstate, int number, gfixed avoidtime) {
SysCallArgs args(3);
args[0]=goalstate;
args[1]=number;
args[2]=avoidtime;
_G_syscall( BOTLIB_AI_SET_AVOID_GOAL_TIME, args);
}
void _G_trap_BotInitLevelItems(void) {
_G_syscall( BOTLIB_AI_INIT_LEVEL_ITEMS,SysCallArgs(0) );
}
void _G_trap_BotUpdateEntityItems(void) {
_G_syscall( BOTLIB_AI_UPDATE_ENTITY_ITEMS,SysCallArgs(0) );
}
int _G_trap_BotLoadItemWeights(int goalstate, const char *filename) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=filename;
return (int)_G_syscall( BOTLIB_AI_LOAD_ITEM_WEIGHTS,args);
}
void _G_trap_BotFreeItemWeights(int goalstate) {
SysCallArgs args(1);
args[0]=goalstate;
_G_syscall( BOTLIB_AI_FREE_ITEM_WEIGHTS, args);
}
void _G_trap_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) {
SysCallArgs args(3);
args[0]=parent1;
args[1]=parent2;
args[2]=child;
_G_syscall( BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC, args);
}
void _G_trap_BotSaveGoalFuzzyLogic(int goalstate, const char *filename) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=filename;
_G_syscall( BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC, args);
}
void _G_trap_BotMutateGoalFuzzyLogic(int goalstate, gfixed range) {
SysCallArgs args(2);
args[0]=goalstate;
args[1]=range;
_G_syscall( BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC, args);
}
int _G_trap_BotAllocGoalState(int state) {
SysCallArgs args(1);
args[0]=state;
return (int)_G_syscall( BOTLIB_AI_ALLOC_GOAL_STATE, args);
}
void _G_trap_BotFreeGoalState(int handle) {
SysCallArgs args(1);
args[0]=handle;
_G_syscall( BOTLIB_AI_FREE_GOAL_STATE, args);
}
void _G_trap_BotResetMoveState(int movestate) {
SysCallArgs args(1);
args[0]=movestate;
_G_syscall( BOTLIB_AI_RESET_MOVE_STATE, args);
}
void _G_trap_BotAddAvoidSpot(int movestate, bvec3_t origin, bfixed radius, int type) {
SysCallArgs args(4);
args[0]=movestate;
args[1]=origin;
args[2]=radius;
args[3]=type;
_G_syscall( BOTLIB_AI_ADD_AVOID_SPOT, args);
}
void _G_trap_BotMoveToGoal(void /* struct bot_moveresult_s */ *result, int movestate, void /* struct bot_goal_s */ *goal,
int travelflags) {
SysCallArgs args(4);
args[0]=result;
args[1]=movestate;
args[2]=goal;
args[3]=travelflags;
_G_syscall( BOTLIB_AI_MOVE_TO_GOAL, args);
}
int _G_trap_BotMoveInDirection(int movestate, avec3_t dir, bfixed speed, int type) {
SysCallArgs args(4);
args[0]=movestate;
args[1]=dir;
args[2]=speed;
args[3]=type;
return (int)_G_syscall( BOTLIB_AI_MOVE_IN_DIRECTION, args);
}
void _G_trap_BotResetAvoidReach(int movestate) {
SysCallArgs args(1);
args[0]=movestate;
_G_syscall( BOTLIB_AI_RESET_AVOID_REACH, args);
}
void _G_trap_BotResetLastAvoidReach(int movestate) {
SysCallArgs args(1);
args[0]=movestate;
_G_syscall( BOTLIB_AI_RESET_LAST_AVOID_REACH, args);
}
int _G_trap_BotReachabilityArea(bvec3_t origin, int testground) {
SysCallArgs args(2);
args[0]=origin;
args[1]=testground;
return (int)_G_syscall( BOTLIB_AI_REACHABILITY_AREA, args );
}
int _G_trap_BotMovementViewTarget(int movestate, void /* struct bot_goal_s */ *goal, int travelflags, bfixed lookahead,
bvec3_t target) {
SysCallArgs args(5);
args[0]=movestate;
args[1]=goal;
args[2]=travelflags;
args[3]=lookahead;
args[4]=target;
return (int)_G_syscall( BOTLIB_AI_MOVEMENT_VIEW_TARGET, args);
}
int _G_trap_BotPredictVisiblePosition(bvec3_t origin, int areanum, void /* struct bot_goal_s */ *goal, int travelflags,
bvec3_t target) {
SysCallArgs args(5);
args[0]=origin;
args[1]=areanum;
args[2]=goal;
args[3]=travelflags;
args[4]=target;
return (int)_G_syscall( BOTLIB_AI_PREDICT_VISIBLE_POSITION, args);
}
int _G_trap_BotAllocMoveState(void) {
return (int)_G_syscall( BOTLIB_AI_ALLOC_MOVE_STATE,SysCallArgs(0) );
}
void _G_trap_BotFreeMoveState(int handle) {
SysCallArgs args(1);
args[0]=handle;
_G_syscall( BOTLIB_AI_FREE_MOVE_STATE, args );
}
void _G_trap_BotInitMoveState(int handle, void /* struct bot_initmove_s */ *initmove) {
SysCallArgs args(2);
args[0]=handle;
args[1]=initmove;
_G_syscall( BOTLIB_AI_INIT_MOVE_STATE, args);
}
int _G_trap_BotChooseBestFightWeapon(int weaponstate, int *inventory) {
SysCallArgs args(2);
args[0]=weaponstate;
args[1]=inventory;
return (int)_G_syscall( BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON, args);
}
void _G_trap_BotGetWeaponInfo(int weaponstate, int weapon, void /* struct weaponinfo_s */ *weaponinfo) {
SysCallArgs args(3);
args[0]=weaponstate;
args[1]=weapon;
args[2]=weaponinfo;
_G_syscall( BOTLIB_AI_GET_WEAPON_INFO, args);
}
int _G_trap_BotLoadWeaponWeights(int weaponstate, const char *filename) {
SysCallArgs args(2);
args[0]=weaponstate;
args[1]=filename;
return (int)_G_syscall( BOTLIB_AI_LOAD_WEAPON_WEIGHTS, args);
}
int _G_trap_BotAllocWeaponState(void) {
return (int)_G_syscall( BOTLIB_AI_ALLOC_WEAPON_STATE,SysCallArgs(0) );
}
void _G_trap_BotFreeWeaponState(int weaponstate) {
SysCallArgs args(1);
args[0]=weaponstate;
_G_syscall( BOTLIB_AI_FREE_WEAPON_STATE, args );
}
void _G_trap_BotResetWeaponState(int weaponstate) {
SysCallArgs args(1);
args[0]=weaponstate;
_G_syscall( BOTLIB_AI_RESET_WEAPON_STATE, args );
}
int _G_trap_GeneticParentsAndChildSelection(int numranks, gfixed *ranks, int *parent1, int *parent2, int *child) {
SysCallArgs args(5);
args[0]=numranks;
args[1]=ranks;
args[2]=parent1;
args[3]=parent2;
args[4]=child;
return (int)_G_syscall( BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION, args );
}
int _G_trap_PC_LoadSource( const char *filename ) {
SysCallArgs args(1);
args[0]=filename;
return (int)_G_syscall( BOTLIB_PC_LOAD_SOURCE, args);
}
int _G_trap_PC_FreeSource( int handle ) {
SysCallArgs args(1);
args[0]=handle;
return (int)_G_syscall( BOTLIB_PC_FREE_SOURCE, args);
}
int _G_trap_PC_ReadToken( int handle, pc_token_t *pc_token ) {
SysCallArgs args(2);
args[0]=handle;
args[1]=pc_token;
return (int)_G_syscall( BOTLIB_PC_READ_TOKEN, args);
}
int _G_trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) {
SysCallArgs args(3);
args[0]=handle;
args[1]=filename;
args[2]=line;
return (int)_G_syscall( BOTLIB_PC_SOURCE_FILE_AND_LINE, args);
}
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac",
"crioux@684fc592-8442-0410-8ea1-df6b371289ac"
]
| [
[
[
1,
30
],
[
32,
32
],
[
34,
377
],
[
379,
384
],
[
386,
392
],
[
394,
522
],
[
524,
531
],
[
533,
539
],
[
541,
547
],
[
549,
636
],
[
638,
643
],
[
645,
650
],
[
652,
791
],
[
793,
855
],
[
857,
883
],
[
886,
900
],
[
902,
907
],
[
910,
947
],
[
949,
955
],
[
957,
985
],
[
987,
1000
],
[
1002,
1117
],
[
1119,
1163
],
[
1165,
1184
],
[
1186,
1318
],
[
1320,
1377
]
],
[
[
31,
31
],
[
33,
33
],
[
378,
378
],
[
385,
385
],
[
393,
393
],
[
523,
523
],
[
532,
532
],
[
540,
540
],
[
548,
548
],
[
637,
637
],
[
644,
644
],
[
651,
651
],
[
792,
792
],
[
856,
856
],
[
884,
885
],
[
901,
901
],
[
908,
909
],
[
948,
948
],
[
956,
956
],
[
986,
986
],
[
1001,
1001
],
[
1118,
1118
],
[
1164,
1164
],
[
1185,
1185
],
[
1319,
1319
]
]
]
|
e026b59c47932f2dcf1078246e991f5614896f55 | daa30b544c9d5b10e007a7ff9b5647cfc8551b23 | /Traversal.h | eaf9e845b74b7389d6a145c364889ae81ffb8789 | []
| no_license | yutopio/RedBlackTree | 99c12e973c92815dab1eae308cd389af49bcbf11 | 72b5d0c9af0414b5b891ec9ef47df83ba57f46d7 | refs/heads/master | 2020-04-30T22:02:05.437521 | 2011-10-07T07:34:48 | 2011-10-07T07:34:48 | 2,531,072 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | h |
#ifndef TRAVERSAL_H
#define TRAVERSAL_H
#include <queue>
enum TraversalMode {
PreOrder,
InOrder,
PostOrder
};
template <class Node>
Node *DFS(Node *node, bool (*action)(Node *), TraversalMode mode) {
Node *ret;
if (mode == PreOrder && action(node)) return node;
if (node->Left) {
ret = DFS(node->Left, action, mode);
if (ret) return ret;
}
if (mode == InOrder && action(node)) return node;
if (node->Right) {
ret = DFS(node->Right, action, mode);
if (ret) return ret;
}
if (mode == PostOrder && action(node)) return node;
return NULL;
}
template <class Node>
Node *BFS(Node *node, bool (*action)(Node *)) {
if (!node) return NULL;
std::queue<Node *> q;
q.push(node);
while (q.size()) {
Node *current = q.front();
q.pop();
if (action(current)) return current;
if (current->Left) q.push(current->Left);
if (current->Right) q.push(current->Right);
}
return NULL;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
06febbbf6c15caaef676c005ea046984f06b90e4 | e19b72560f44dd99124b49f8437d04e7408c26ac | /VPTree/Test CertisLib/feature.cpp | 90dbf9ba9ff421a615d791358b43029715db7a1a | []
| no_license | jbfiot/rangers | d5a588da14e188e0f605758e93c6aaf4616cf4f3 | 15b88a73e39708e68c6224f9809cd2966f9dbe26 | refs/heads/master | 2021-01-17T05:25:35.494251 | 2009-03-20T10:09:26 | 2009-03-20T10:09:26 | 38,111,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | cpp | #include "Feature.h"
#include <math.h>
/**
*
* Codes d'erreurs :
* - 3 : erreur de type de feature
**/
//Feature::Feature(std::vector<double> pos, std::vector<double> coef, int typ){
// position = pos;
// coeffs = (Vector) Vector(coef);
// type = typ;
//}
Feature::Feature(std::vector<double> pos, Vector coef, int typ){
position = pos;
coeffs = coef;
type = typ;
}
/**
* Calcule les proba d'appartenance aux k-classes du k-means.
**/
void Feature::get_kmeans_proba( std::vector<Vector> &k_centers, Vector &sigmas, Vector &proba/* Conteneur resultat */) {
// Formule : proba appartenance classe-k = distance au centre k divisee par la somme des distances aux centres.
double sum=0;
proba.resize(k_centers.size());
for (int i=0; i<k_centers.size(); i++){
double dist = this->coeffs.get_distance_with_chi2(k_centers[i]);
proba[i] = exp(- dist / sigmas[i]);
sum+=proba[i];
}
for (unsigned int i=0; i<k_centers.size(); i++){
proba[i] = proba[i]/sum;
}
}
| [
"[email protected]",
"hellwoxx@a27398a2-dc2a-11dd-8561-ef618b9164eb"
]
| [
[
[
1,
33
],
[
35,
36
],
[
38,
44
]
],
[
[
34,
34
],
[
37,
37
]
]
]
|
446aa37b2845249da78da501fc8438054dc7a395 | 13ab3c3dbedde1ef5374dde02d7162bbfd728f44 | /glib/wch.h | bcae5c46c86d3826da28355ea7d5f7fe815df632 | []
| no_license | pikma/Snap | f4dbb4f99a4ca7a98243c9d10bdb5e0b94ef574e | 911f40a2eb0ef5330ecde983137557526955e28a | refs/heads/master | 2020-05-20T04:41:03.292112 | 2011-12-11T22:44:18 | 2011-12-11T22:44:18 | 2,729,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,638 | h | #ifndef GLIB_WCH_H
#define GLIB_WCH_H
#include "ds.h"
/////////////////////////////////////////////////
// Wide-Char
class TWCh{
private:
uchar MsVal;
uchar LsVal;
public:
static const TWCh Mn;
static const TWCh Mx;
static const int Vals;
TWCh(): MsVal(0), LsVal(0){}
TWCh(const uchar& _LsVal): MsVal(0), LsVal(_LsVal){}
TWCh(const uchar& _MsVal, const uchar& _LsVal):
MsVal(_MsVal), LsVal(_LsVal){}
TWCh(const int& _MsVal, const int& _LsVal):
MsVal(uchar(_MsVal)), LsVal(uchar(_LsVal)){}
operator char() const {return LsVal;}
TWCh(TSIn& SIn){SIn.Load(MsVal); SIn.Load(LsVal);}
void Save(TSOut& SOut) const {SOut.Save(MsVal); SOut.Save(MsVal);}
TWCh& operator=(const TWCh& WCh){
MsVal=WCh.MsVal; LsVal=WCh.LsVal; return *this;}
bool operator==(const TWCh& WCh) const {
return (MsVal==WCh.MsVal)&&(LsVal==WCh.LsVal);}
bool operator<(const TWCh& WCh) const {
return (MsVal<WCh.MsVal)||((MsVal==WCh.MsVal)&&(LsVal<WCh.LsVal));}
int GetMemUsed() const {return sizeof(MsVal)+sizeof(LsVal);}
int GetPrimHashCd() const {return LsVal;}
int GetSecHashCd() const {return MsVal;}
char GetCh() const {
if (MsVal==TCh::NullCh){return LsVal;} else {return '#';}}
static TWCh LoadTxt(const PSIn& SIn){
uchar LsVal=SIn->GetCh(); uchar MsVal=SIn->GetCh();
return TWCh(MsVal, LsVal);}
void SaveTxt(const PSOut& SOut) const {
SOut->PutCh(MsVal); SOut->PutCh(LsVal);}
static const TWCh StartWCh;
static const TWCh TabWCh;
static const TWCh LfWCh;
static const TWCh CrWCh;
static const TWCh SpaceWCh;
};
typedef TVec<TWCh> TWChV;
/////////////////////////////////////////////////
// Wide-Char-Array
class TWChA{
private:
TWChV WChV;
void AddCStr(const char* CStr);
void PutCStr(const char* CStr);
public:
TWChA(const int& MxWChs=0): WChV(MxWChs, 0){}
TWChA(const TWChA& WChA): WChV(WChA.WChV){}
TWChA(const TWChV& _WChV): WChV(_WChV){}
TWChA(const char* CStr): WChV(){PutCStr(CStr);}
TWChA(const TChA& ChA): WChV(){PutCStr(ChA.CStr());}
TWChA(const TStr& Str): WChV(){PutCStr(Str.CStr());}
~TWChA(){}
TWChA(TSIn& SIn): WChV(SIn){}
void Save(TSOut& SOut){WChV.Save(SOut);}
TWChA& operator=(const TWChA& WChA){
if (this!=&WChA){WChV=WChA.WChV;} return *this;}
TWChA& operator=(const char* CStr){PutCStr(CStr); return *this;}
TWChA& operator=(const TChA& ChA){PutCStr(ChA.CStr()); return *this;}
TWChA& operator=(const TStr& Str){PutCStr(Str.CStr()); return *this;}
bool operator==(const TWChA& WChA) const {return WChV==WChA.WChV;}
bool operator==(const char* CStr) const {return strcmp(GetStr().CStr(), CStr)!=0;}
TWChA& operator+=(const char& Ch){WChV.Add(TWCh(Ch)); return *this;}
TWChA& operator+=(const TWCh& WCh){WChV.Add(WCh); return *this;}
TWChA& operator+=(const char* CStr){AddCStr(CStr); return *this;}
TWChA& operator+=(const TChA& ChA){AddCStr(ChA.CStr()); return *this;}
TWChA& operator+=(const TStr& Str){AddCStr(Str.CStr()); return *this;}
TWChA& operator+=(const TWChA& WChA){WChV.AddV(WChA.WChV); return *this;}
TWCh operator[](const int& ChN) const {return WChV[ChN];}
int GetMemUsed(){return WChV.GetMemUsed();}
void Clr(){WChV.Clr();}
int Len() const {return WChV.Len();}
bool Empty() const {return WChV.Empty();}
TStr GetStr() const;
void GetSubWChA(const int& BChN, const int& EChN, TWChA& WChA) const {
WChV.GetSubValV(BChN, EChN, WChA.WChV);}
void InsStr(const int& BChN, const TStr& Str);
void DelSubStr(const int& BChN, const int& EChN);
bool DelStr(const TStr& Str);
void SplitOnCh(TStr& LStr, const char& SplitCh, TStr& RStr) const;
int SearchCh(const TWCh& WCh, const int& BChN=0) const {
return WChV.SearchForw(WCh, BChN);}
int SearchStr(const TWChA& WChA, const int& BChN=0) const {
return WChV.SearchVForw(WChA.WChV, BChN);}
bool IsChIn(const char& Ch) const {return SearchCh(Ch)!=-1;}
bool IsStrIn(const TWChA& WChA) const {return SearchStr(WChA)!=-1;}
bool IsPrefix(const TWChA& WChA) const {
TWChV SubWChV; WChV.GetSubValV(0, WChA.Len()-1, SubWChV);
return SubWChV==WChA.WChV;}
bool IsSufix(const TWChA& WChA) const {
TWChV SubWChV; WChV.GetSubValV(Len()-WChA.Len(), Len()-1, SubWChV);
return SubWChV==WChA.WChV;}
int ChangeStr(const TStr& SrcStr, const TStr& DstStr, const int& BChN=0);
int ChangeStrAll(const TStr& SrcStr, const TStr& DstStr);
static void LoadTxt(const PSIn& SIn, TWChA& WChA);
void SaveTxt(const PSOut& SOut) const;
static TWChA EmptyWChA;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
124
]
]
]
|
3fd15d7f03d50281883a4e56d3631f3d9cfb963e | f95341dd85222aa39eaa225262234353f38f6f97 | /ObjectDock/DockletSDK/Docklet/Docklet.cpp | 0f2c221772acb7d2a1173b021a7509dba6994cca | []
| no_license | Templier/threeoaks | 367b1a0a45596b8fe3607be747b0d0e475fa1df2 | 5091c0f54bd0a1b160ddca65a5e88286981c8794 | refs/heads/master | 2020-06-03T11:08:23.458450 | 2011-10-31T04:33:20 | 2011-10-31T04:33:20 | 32,111,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,504 | cpp | ///////////////////////////////////////////////////////////////////////////////////////////////
//
// DockletSDK : Docklet Class
//
// (c) 2004 - Julien Templier
//
///////////////////////////////////////////////////////////////////////////////////////////////
// * $LastChangedRevision$
// * $LastChangedDate$
// * $LastChangedBy$
///////////////////////////////////////////////////////////////////////////////////////////////
#include "Docklet.h"
Docklet::Docklet(HWND hwndDocklet,HINSTANCE hInstance)
{
data = new DOCKLET_STATIC_DATA;
PopulateStaticData(hwndDocklet, hInstance);
}
Docklet::~Docklet()
{
delete(data);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Populate the static data structure used by the Docklet class
void Docklet::PopulateStaticData(HWND hwndDocklet,HINSTANCE hInstance)
{
data->hInstance = hInstance;
data->hwndDocklet = hwndDocklet;
char root[MAX_PATH+1];
strcpy_s(root, "");
_GetRootFolder(root);
data->rootFolder = string(root);
char relative[MAX_PATH+1];
strcpy_s(relative,"");
_GetRelativeFolder(relative);
data->relativeFolder = string(relative);
}
///////////////////////////////////////////////////////////////////////////////////////////////
void Docklet::_GetRootFolder(char *szRootFolder)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, char *szRootFolder);
DUMMY_TYPEDEF HostDockletGetRootFolder = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletGetRootFolder");
if(!HostDockletGetRootFolder)
return;
HostDockletGetRootFolder(data->hwndDocklet, szRootFolder);
}
///////////////////////////////////////////////////////////////////////////////////////////////
void Docklet::_GetRelativeFolder(char *szFolder)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, char *szFolder);
DUMMY_TYPEDEF HostDockletGetRelativeFolder = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletGetRelativeFolder");
if(!HostDockletGetRelativeFolder)
return;
HostDockletGetRelativeFolder(data->hwndDocklet, szFolder);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Get the handle to the window that owns this docklet.
HWND Docklet::GetHWND()
{
return data->hwndDocklet;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Get the handle to the instance of this docklet DLL.
HINSTANCE Docklet::GetInstance()
{
return data->hInstance;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Query for whether or not the specified Docklet is currently visible
bool Docklet::IsVisible()
{
typedef BOOL(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet);
DUMMY_TYPEDEF HostDockletIsVisible = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletIsVisible");
if(!HostDockletIsVisible)
return false;
return HostDockletIsVisible(data->hwndDocklet) != 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Retrieves the bounding rectangle of this Docklet in screen coordinates.
bool Docklet::GetRect(RECT* rect)
{
typedef BOOL(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, RECT *rcDocklet);
DUMMY_TYPEDEF HostDockletGetRect = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletGetRect");
if(!HostDockletGetRect)
return false;
return HostDockletGetRect(data->hwndDocklet, rect) != 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Changes the current label of this Docklet.
void Docklet::SetLabel(string label)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, char *szLabel);
DUMMY_TYPEDEF HostDockletSetLabel = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletSetLabel");
if(!HostDockletSetLabel)
return;
HostDockletSetLabel(data->hwndDocklet, (char*)label.c_str());
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Retrieves the current label of this Docklet.
string Docklet::GetLabel()
{
typedef int(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, char *szLabel);
DUMMY_TYPEDEF HostDockletGetLabel = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletGetLabel");
if(!HostDockletGetLabel)
return 0;
char label[MAX_PATH+1];
strcpy_s(label, "");
HostDockletGetLabel(data->hwndDocklet, label);
return string(label);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Loads a GDI+ image based on the given relative path.
Bitmap* Docklet::LoadGDIPlusImage(string imagePath)
{
typedef Bitmap *(__stdcall *DUMMY_TYPEDEF)(char *szImage);
DUMMY_TYPEDEF HostDockletLoadGDIPlusImage = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletLoadGDIPlusImage");
if(!HostDockletLoadGDIPlusImage)
return NULL;
return HostDockletLoadGDIPlusImage((char*)imagePath.c_str());
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Sets this docklet's image to a given GDI+ Image
void Docklet::SetImage(Image *image, bool automaticallyDeleteImage)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, Image *lpImageNew, BOOL bAutomaticallyDeleteImage);
DUMMY_TYPEDEF HostDockletSetImage = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletSetImage");
if(!HostDockletSetImage)
return;
HostDockletSetImage(data->hwndDocklet, image, automaticallyDeleteImage);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Sets this docklet's image to that of the given file.
void Docklet::SetImageFile(string image)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, char *szImage);
DUMMY_TYPEDEF HostDockletSetImageFile = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletSetImageFile");
if(!HostDockletSetImageFile)
return;
HostDockletSetImageFile(data->hwndDocklet, (char*)image.c_str());
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Sets this docklet's image overlay to a given GDI+ Image
void Docklet::SetImageOverlay(Image *imageOverlay, bool automaticallyDeleteImage)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, Image *imageOverlay, BOOL bAutomaticallyDeleteImage);
DUMMY_TYPEDEF HostDockletSetImageOverlay = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletSetImageOverlay");
if(!HostDockletSetImageOverlay)
return;
HostDockletSetImageOverlay(data->hwndDocklet, imageOverlay, automaticallyDeleteImage);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Shows the standard ObjectDock "Choose Image" dialog template, and allows you to select
/// an image file for any purpose you wish, including choosing images for different states
/// a docklet might have.
bool Docklet::BrowseForImage(HWND hwndParent, char* image, string alternativeRelativeRoot)
{
typedef BOOL(__stdcall *DUMMY_TYPEDEF)(HWND hwndParent, char *szImage, char *szAlternateRelativeRoot);
DUMMY_TYPEDEF HostDockletBrowseForImage = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletBrowseForImage");
if(!HostDockletBrowseForImage)
return false;
return HostDockletBrowseForImage(hwndParent, image, (char*)alternativeRelativeRoot.c_str()) != 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Lock the mouse effect (e.g. zooming, etc) of this docklet's owning dock
void Docklet::LockMouseEffect(bool lock)
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, BOOL bLock);
DUMMY_TYPEDEF HostDockletLockMouseEffect = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletLockMouseEffect");
if(!HostDockletLockMouseEffect)
return;
HostDockletLockMouseEffect(data->hwndDocklet, lock);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Causes this Docklet to animate in the dock to try to get the user's attention
void Docklet::DoAttentionAnimation()
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet);
DUMMY_TYPEDEF HostDockletDoAttentionAnimation = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletDoAttentionAnimation");
if(!HostDockletDoAttentionAnimation)
return;
HostDockletDoAttentionAnimation(data->hwndDocklet);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Causes this Docklet to animate in the dock to try to get the user's attention
void Docklet::DoClickAnimation()
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet);
DUMMY_TYPEDEF HostDockletDoClickAnimation = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletDoClickAnimation");
if(!HostDockletDoClickAnimation)
return;
HostDockletDoClickAnimation(data->hwndDocklet);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Remove the current docklet from the dock
BOOL Docklet::RemoveSelf(WPARAM wParam)
{
typedef BOOL(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, WPARAM wParam);
DUMMY_TYPEDEF HostDockletRemoveSelf = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletRemoveSelf");
if(!HostDockletRemoveSelf)
return FALSE;
return HostDockletRemoveSelf(data->hwndDocklet, wParam);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Retrieves the relative path of the folder that contains this Docklet's DLL
string Docklet::GetRootFolder()
{
return data->rootFolder;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Retrieves the absolute location of the ObjectDock root folder,
/// from which all things are relative
string Docklet::GetRelativeFolder()
{
return data->relativeFolder;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Opens up the default configuration dialog for this Docklet.
void Docklet::DefaultConfigDialog()
{
typedef void(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet);
DUMMY_TYPEDEF HostDockletDefaultConfigDialog = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletDefaultConfigDialog");
if(!HostDockletDefaultConfigDialog)
return;
HostDockletDefaultConfigDialog(data->hwndDocklet);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Retrieves which edge of the screen the dock with this Docklet is located on.
Docklet::EDGE Docklet::QueryDockEdge()
{
typedef int(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet);
DUMMY_TYPEDEF HostDockletQueryDockEdge = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletQueryDockEdge");
if(!HostDockletQueryDockEdge)
return (Docklet::EDGE)0; //-1;
return (Docklet::EDGE)HostDockletQueryDockEdge(data->hwndDocklet);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Retrieves the alignment of the dock with this Docklet
Docklet::ALIGN Docklet::QueryDockAlign()
{
typedef int(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet);
DUMMY_TYPEDEF HostDockletQueryDockAlign = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletQueryDockAlign");
if(!HostDockletQueryDockAlign)
return (ALIGN)0; //-1;
return (Docklet::ALIGN)HostDockletQueryDockAlign(data->hwndDocklet);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Changes which edge of the screen the dock with this Docklet is located on.
bool Docklet::SetDockEdge(Docklet::EDGE newEdge)
{
typedef BOOL(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, int iNewEdge);
DUMMY_TYPEDEF HostDockletSetDockEdge = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletSetDockEdge");
if(!HostDockletSetDockEdge)
return false;
return HostDockletSetDockEdge(data->hwndDocklet, (int)newEdge) != 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Changes the alignment of the dock with this Docklet.
bool Docklet::SetDockAlign(Docklet::ALIGN newAlign)
{
typedef BOOL(__stdcall *DUMMY_TYPEDEF)(HWND hwndDocklet, int iNewAlign);
DUMMY_TYPEDEF HostDockletSetDockAlign = (DUMMY_TYPEDEF) GetProcAddress(GetModuleHandle(NULL), "DockletSetDockAlign");
if(!HostDockletSetDockAlign)
return false;
return HostDockletSetDockAlign(data->hwndDocklet, (int)newAlign) != 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// HELPER FUNCTIONS ///
///////////////////////////////////////////////////////////////////////////////////////////////
int WritePrivateProfileInt(LPCTSTR lpAppName, LPCTSTR lpKeyName, int iValue, LPCTSTR lpFileName)
{
//////////////////////////////////////////////////////////////////////////
///Helper function included to quickly & easily save integers to an Ini
char szNumber[100];
strcpy_s(szNumber, "");
_itoa_s(iValue, szNumber, 10);
return WritePrivateProfileString(lpAppName, lpKeyName, szNumber, lpFileName);
}
/// EOF | [
"julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d"
]
| [
[
[
1,
335
]
]
]
|
0947bb5eaa9ebdaa9f3be91de31412a20549034f | 6eef3e34d3fe47a10336a53df1a96a591b15cd01 | /ASearch/Rank/Rank.hpp | fb1e284f3586da0869367b86bc3467b03406fe3f | []
| no_license | praveenmunagapati/alkaline | 25013c233a80b07869e0fdbcf9b8dfa7888cc32e | 7cf43b115d3e40ba48854f80aca8d83b67f345ce | refs/heads/master | 2021-05-27T16:44:12.356701 | 2009-10-29T11:23:09 | 2009-10-29T11:23:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,079 | hpp | #include <platform/include.hpp>
#include <Vector/SVector.hpp>
#include <Vector/Vector.hpp>
#include <Search/SearchTypes.hpp>
#include <SwapVector/SwapVector.hpp>
#ifndef ALKALINE_C_RANK_HPP
#define ALKALINE_C_RANK_HPP
class CRank
{
public:
CRank();
void GetSortedVector(CSearchData *SearchData);
void GetSortedSwapVector(CSearchData *SearchData);
void AddVector(CSVector *VectorToAdd, const short int Weight, const bool Mandatory, const bool ShouldBeMissing);
void AddVector(CSwapVector *VectorToAdd, const short int Weight, const bool Mandatory, const bool ShouldBeMissing);
void Clear();
short int GetMaxPossibleQuality();
void ShowVectors();
void QuickSort(const int l, const int r);
private:
bool m_bMandatoryWordMissing;
CVector<CSVector*> m_VectorsToSort;
CVector<CSwapVector*> m_SwapVectorsToSort;
CVector<short int> m_Weight;
CVector<short int> *m_TempResult;
CVector<int> *m_Result;
int m_ProbableFinalSize;
unsigned short int m_MinValue;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
38802fb99259026e120be8747ed1244278dc24e5 | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/HwWrite.cpp | 8ce0a32e15b3c81a1f64fa529067bfecfebd7b2d | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,537 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "Common.h"
#include "Hardware.h"
#include "ps2/HwInternal.h"
#include "ps2/eeHwTraceLog.inl"
using namespace R5900;
// Shift the middle 8 bits (bits 4-12) into the lower 8 bits.
// This helps the compiler optimize the switch statement into a lookup table. :)
#define HELPSWITCH(m) (((m)>>4) & 0xff)
#define mcase(src) case HELPSWITCH(src)
template< uint page > void __fastcall _hwWrite8(u32 mem, u8 value);
template< uint page > void __fastcall _hwWrite16(u32 mem, u8 value);
template< uint page > void __fastcall _hwWrite128(u32 mem, u8 value);
template<uint page>
void __fastcall _hwWrite32( u32 mem, u32 value )
{
pxAssume( (mem & 0x03) == 0 );
// Notes:
// All unknown registers on the EE are "reserved" as discarded writes and indeterminate
// reads. Bus error is only generated for registers outside the first 16k of mapped
// register space (which is handled by the VTLB mapping, so no need for checks here).
switch (page)
{
case 0x00: if (!rcntWrite32<0x00>(mem, value)) return; break;
case 0x01: if (!rcntWrite32<0x01>(mem, value)) return; break;
case 0x02:
if (!ipuWrite32(mem, value)) return;
break;
case 0x04:
case 0x05:
case 0x06:
case 0x07:
{
// [Ps2Confirm] Direct FIFO read/write behavior. We need to create a test that writes
// data to one of the FIFOs and determine the result. I'm not quite sure offhand a good
// way to do that --air
// Current assumption is that 32-bit and 64-bit writes likely do 128-bit zero-filled
// writes (upper 96 bits are 0, lower 32 bits are effective).
u128 zerofill = u128::From32(0);
zerofill._u32[(mem >> 2) & 0x03] = value;
DevCon.WriteLn( Color_Cyan, "Writing 32-bit FIFO data (zero-extended to 128 bits)" );
_hwWrite128<page>(mem & ~0x0f, &zerofill);
}
return;
case 0x03:
if (mem >= EEMemoryMap::VIF0_Start)
{
if(mem >= EEMemoryMap::VIF1_Start)
{
if (!vifWrite32<1>(mem, value)) return;
}
else
{
if (!vifWrite32<0>(mem, value)) return;
}
}
else iswitch(mem)
{
icase(GIF_CTRL)
{
psHu32(mem) = value & 0x8;
if (value & 0x1)
gsGIFReset();
if (value & 8)
gifRegs.stat.PSE = true;
else
gifRegs.stat.PSE = false;
return;
}
icase(GIF_MODE)
{
// need to set GIF_MODE (hamster ball)
gifRegs.mode.write(value);
// set/clear bits 0 and 2 as per the GIF_MODE value.
const u32 bitmask = GIF_MODE_M3R | GIF_MODE_IMT;
psHu32(GIF_STAT) &= ~bitmask;
psHu32(GIF_STAT) |= (u32)value & bitmask;
return;
}
}
break;
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x0e:
if (!dmacWrite32<page>(mem, value)) return;
break;
case 0x0f:
{
switch( HELPSWITCH(mem) )
{
mcase(INTC_STAT):
psHu32(INTC_STAT) &= ~value;
//cpuTestINTCInts();
return;
mcase(INTC_MASK):
psHu32(INTC_MASK) ^= (u16)value;
cpuTestINTCInts();
return;
mcase(SIO_TXFIFO):
{
u8* woot = (u8*)&value;
// [Ps2Confirm] What happens when we write 32 bit values to SIO_TXFIFO?
// If it works like the IOP, then all 32 bits are written to the FIFO in
// order. PCSX2 up to this point simply ignored non-8bit writes to this port.
_hwWrite8<0x0f>(SIO_TXFIFO, woot[0]);
_hwWrite8<0x0f>(SIO_TXFIFO, woot[1]);
_hwWrite8<0x0f>(SIO_TXFIFO, woot[2]);
_hwWrite8<0x0f>(SIO_TXFIFO, woot[3]);
}
return;
mcase(SBUS_F200):
// Performs a standard psHu32 assignment (which is the default action anyway).
//psHu32(mem) = value;
break;
mcase(SBUS_F220):
psHu32(mem) |= value;
return;
mcase(SBUS_F230):
psHu32(mem) &= ~value;
return;
mcase(SBUS_F240):
if(!(value & 0x100))
psHu32(mem) &= ~0x100;
else
psHu32(mem) |= 0x100;
return;
mcase(SBUS_F260):
psHu32(mem) = 0;
return;
mcase(MCH_RICM)://MCH_RICM: x:4|SA:12|x:5|SDEV:1|SOP:4|SBC:1|SDEV:5
if ((((value >> 16) & 0xFFF) == 0x21) && (((value >> 6) & 0xF) == 1) && (((psHu32(0xf440) >> 7) & 1) == 0))//INIT & SRP=0
rdram_sdevid = 0; // if SIO repeater is cleared, reset sdevid
psHu32(mem) = value & ~0x80000000; //kill the busy bit
return;
mcase(MCH_DRD):
// Performs a standard psHu32 assignment (which is the default action anyway).
//psHu32(mem) = value;
break;
mcase(DMAC_ENABLEW):
if (!dmacWrite32<0x0f>(DMAC_ENABLEW, value)) return;
//mcase(SIO_ISR):
//mcase(0x1000f410):
// Mystery Regs! No one knows!?
// (unhandled so fall through to default)
}
}
break;
}
psHu32(mem) = value;
}
template<uint page>
void __fastcall hwWrite32( u32 mem, u32 value )
{
eeHwTraceLog( mem, value, false );
_hwWrite32<page>( mem, value );
}
// --------------------------------------------------------------------------------------
// hwWrite8 / hwWrite16 / hwWrite64 / hwWrite128
// --------------------------------------------------------------------------------------
template< uint page >
void __fastcall _hwWrite8(u32 mem, u8 value)
{
iswitch (mem)
icase(SIO_TXFIFO)
{
static bool iggy_newline = false;
static char sio_buffer[1024];
static int sio_count;
if (value == '\r')
{
iggy_newline = true;
sio_buffer[sio_count++] = '\n';
}
else if (!iggy_newline || (value != '\n'))
{
iggy_newline = false;
sio_buffer[sio_count++] = value;
}
if ((sio_count == ArraySize(sio_buffer)-1) || (sio_buffer[sio_count-1] == '\n'))
{
sio_buffer[sio_count] = 0;
eeConLog( ShiftJIS_ConvertString(sio_buffer) );
sio_count = 0;
}
return;
}
u32 merged = _hwRead32<page,false>(mem & ~0x03);
((u8*)&merged)[mem & 0x3] = value;
_hwWrite32<page>(mem & ~0x03, merged);
}
template< uint page >
void __fastcall hwWrite8(u32 mem, u8 value)
{
eeHwTraceLog( mem, value, false );
_hwWrite8<page>(mem, value);
}
template< uint page >
void __fastcall _hwWrite16(u32 mem, u16 value)
{
pxAssume( (mem & 0x01) == 0 );
u32 merged = _hwRead32<page,false>(mem & ~0x03);
((u16*)&merged)[(mem>>1) & 0x1] = value;
hwWrite32<page>(mem & ~0x03, merged);
}
template< uint page >
void __fastcall hwWrite16(u32 mem, u16 value)
{
eeHwTraceLog( mem, value, false );
_hwWrite16<page>(mem, value);
}
template<uint page>
void __fastcall _hwWrite64( u32 mem, const mem64_t* srcval )
{
pxAssume( (mem & 0x07) == 0 );
// * Only the IPU has true 64 bit registers.
// * FIFOs have 128 bit registers that are probably zero-fill.
// * All other registers likely disregard the upper 32-bits and simply act as normal
// 32-bit writes.
switch (page)
{
case 0x02:
if (!ipuWrite64(mem, *srcval)) return;
break;
case 0x04:
case 0x05:
case 0x06:
case 0x07:
{
DevCon.WriteLn( Color_Cyan, "Writing 64-bit FIFO data (zero-extended to 128 bits)" );
u128 zerofill = u128::From32(0);
zerofill._u64[(mem >> 3) & 0x01] = *srcval;
hwWrite128<page>(mem & ~0x0f, &zerofill);
}
return;
default:
// disregard everything except the lower 32 bits.
// ... and skip the 64 bit writeback since the 32-bit one will suffice.
hwWrite32<page>( mem, ((u32*)srcval)[0] );
return;
}
psHu64(mem) = *srcval;
}
template<uint page>
void __fastcall hwWrite64( u32 mem, const mem64_t* srcval )
{
eeHwTraceLog( mem, *srcval, false );
_hwWrite64<page>(mem, srcval);
}
template< uint page >
void __fastcall _hwWrite128(u32 mem, const mem128_t* srcval)
{
pxAssume( (mem & 0x0f) == 0 );
// FIFOs are the only "legal" 128 bit registers. Handle them first.
// all other registers fall back on the 64-bit handler (and from there
// most of them fall back to the 32-bit handler).
switch (page)
{
case 0x04:
WriteFIFO_VIF0(srcval);
return;
case 0x05:
WriteFIFO_VIF1(srcval);
return;
case 0x06:
WriteFIFO_GIF(srcval);
return;
case 0x07:
if (mem & 0x10)
{
WriteFIFO_IPUin(srcval);
}
else
{
// [Ps2Confirm] Most likely writes to IPUout will be silently discarded. A test
// to confirm such would be easy -- just dump some data to FIFO_IPUout and see
// if the program causes BUSERR or something on the PS2.
//WriteFIFO_IPUout(srcval);
}
return;
}
// All upper bits of all non-FIFO 128-bit HW writes are almost certainly disregarded. --air
hwWrite64<page>(mem, (mem64_t*)srcval);
//CopyQWC(&psHu128(mem), srcval);
}
template< uint page >
void __fastcall hwWrite128(u32 mem, const mem128_t* srcval)
{
eeHwTraceLog( mem, *srcval, false );
_hwWrite128<page>(mem, srcval);
}
#define InstantizeHwWrite(pageidx) \
template void __fastcall hwWrite8<pageidx>(u32 mem, mem8_t value); \
template void __fastcall hwWrite16<pageidx>(u32 mem, mem16_t value); \
template void __fastcall hwWrite32<pageidx>(u32 mem, mem32_t value); \
template void __fastcall hwWrite64<pageidx>(u32 mem, const mem64_t* srcval); \
template void __fastcall hwWrite128<pageidx>(u32 mem, const mem128_t* srcval);
InstantizeHwWrite(0x00); InstantizeHwWrite(0x08);
InstantizeHwWrite(0x01); InstantizeHwWrite(0x09);
InstantizeHwWrite(0x02); InstantizeHwWrite(0x0a);
InstantizeHwWrite(0x03); InstantizeHwWrite(0x0b);
InstantizeHwWrite(0x04); InstantizeHwWrite(0x0c);
InstantizeHwWrite(0x05); InstantizeHwWrite(0x0d);
InstantizeHwWrite(0x06); InstantizeHwWrite(0x0e);
InstantizeHwWrite(0x07); InstantizeHwWrite(0x0f);
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
392
]
]
]
|
e0d174929790d319f4b85270f07b85cea79eb1a4 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /Shared/data/Table_stream.h | b8d1aa2e0185da5593d0d83a9e06e2dc3be5c68e | []
| no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | h | #ifndef TABLE_STREAM_H
#define TABLE_STREAM_H
#include <data\table_base.h>
// ------------------------------------------------------------------
// Short description:
// this class is will read a simple space separated text file
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
class DATA_EXPORT Table_stream : public Table_base
{
public:
Table_stream (void);
Table_stream (const char* File_name);
// name of file.
string File_name;
protected:
ifstream In_stream;
virtual void Open_table (void);
virtual void Close_table (void);
virtual void Read_field_names (void);
virtual void Read_next_record (void);
virtual void Position_at_first (void);
virtual void Position_at_last (void);
virtual void Position_at_prior (void);
};
#endif | [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
]
| [
[
[
1,
38
]
]
]
|
e92c93ed57d0a3858fb005290211bfe274fcf0a8 | 119ba245bea18df8d27b84ee06e152b35c707da1 | /unreal/branches/VisualDebugger/qrgui/mainwindow/shapeEdit/pointPort.cpp | a0867b1eded69eaf7e29776c33be15b33f527a29 | []
| no_license | nfrey/qreal | 05cd4f9b9d3193531eb68ff238d8a447babcb3d2 | 71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164 | refs/heads/master | 2020-04-06T06:43:41.910531 | 2011-05-30T19:30:09 | 2011-05-30T19:30:09 | 1,634,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,714 | cpp | #include "pointPort.h"
const int step = 3;
PointPort::PointPort(qreal x, qreal y, Item *parent) : Item(parent)
{
mNeedScalingRect = true;
mRadius = 4;
mRect = QRectF(x - mRadius / 2, y - mRadius / 2, mRadius, mRadius);
mX1 = x - mRadius * 0.8;
mY1 = y - mRadius * 0.8;
mX2 = x + mRadius * 0.8;
mY2 = y + mRadius * 0.8;
mPen = QPen(Qt::blue);
mBrush = QBrush(Qt::SolidPattern);
mBrush.setColor(Qt::blue);
mDomElementType = portType;
}
PointPort::PointPort(PointPort const &other)
:Item()
{
mNeedScalingRect = other.mNeedScalingRect ;
mPen = other.mPen;
mBrush = other.mBrush;
mDomElementType = portType;
mX1 = other.mX1;
mX2 = other.mX2;
mY1 = other.mY1;
mY2 = other.mY2;
mRect = other.mRect;
mRadius = other.mRadius;
mListScalePoint = other.mListScalePoint;
setPos(other.x(), other.y());
}
Item* PointPort::clone()
{
PointPort* item = new PointPort(*this);
return item;
}
QRectF PointPort::boundingRect() const
{
return mRect.adjusted(-scalingDrift, -scalingDrift, scalingDrift, scalingDrift);
}
void PointPort::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setPen(mPen);
painter->setBrush(mBrush);
painter->drawEllipse(mRect);
}
void PointPort::drawExtractionForItem(QPainter* painter)
{
QPen pen(Qt::red);
pen.setWidth(mRadius / 2.3);
painter->setPen(pen);
Item::drawExtractionForItem(painter);
drawFieldForResizeItem(painter);
painter->setPen(QPen(Qt::red));
painter->setBrush(QBrush(Qt::SolidPattern));
drawScalingRects(painter);
}
void PointPort::drawFieldForResizeItem(QPainter* painter)
{
Q_UNUSED(painter);
}
void PointPort::drawScalingRects(QPainter* painter)
{
QBrush brush(Qt::SolidPattern);
QRectF itemBoundingRect = boundingRect().adjusted(scalingDrift, scalingDrift, -scalingDrift, -scalingDrift);
qreal x1= itemBoundingRect.left();
qreal y1 = itemBoundingRect.top();
int scalingPoint = scalingRect;
brush.setColor(mListScalePoint.at(4).second);
painter->setBrush(brush);
painter->drawRect(x1 - scalingPoint - step, y1 - step, scalingPoint, scalingPoint);
brush.setColor(mListScalePoint.at(0).second);
painter->setBrush(brush);
painter->drawRect(x1 - step, y1 - scalingPoint - step, scalingPoint, scalingPoint);
}
void PointPort::changeDragState(qreal x, qreal y)
{
Q_UNUSED(x);
Q_UNUSED(y);
}
void PointPort::changeScalingPointState(qreal x, qreal y)
{
QRectF itemBoundingRect = boundingRect().adjusted(scalingDrift, scalingDrift, -scalingDrift, -scalingDrift);
qreal x1= itemBoundingRect.left();
qreal x2 = itemBoundingRect.right();
qreal y1 = itemBoundingRect.top();
qreal y2 = itemBoundingRect.bottom();
int correction = step;
calcForChangeScalingState(QPointF(x, y), QPointF(x1, y1), QPointF(x2, y2), correction);
}
void PointPort::resizeItem(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event);
}
QPair<QDomElement, Item::DomElementTypes> PointPort::generateItem(QDomDocument &document, QPoint const &topLeftPicture)
{
QRectF itemBoundingRect = boundingRect().adjusted(scalingDrift, scalingDrift, -scalingDrift, -scalingDrift);
QDomElement pointPort = document.createElement("pointPort");
int const x = static_cast<int>(scenePos().x() + itemBoundingRect.x() + mRadius / 2 - topLeftPicture.x());
int const y = static_cast<int>(scenePos().y() + itemBoundingRect.y() + mRadius / 2 - topLeftPicture.y());
pointPort.setAttribute("y", setSingleScaleForDoc(4, x, y));
pointPort.setAttribute("x", setSingleScaleForDoc(0, x, y));
return QPair<QDomElement, Item::DomElementTypes>(pointPort, mDomElementType);
}
| [
"[email protected]"
]
| [
[
[
1,
123
]
]
]
|
4ffa66a1bd7a2d9ab71323e8a594364014cac53d | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/Utility.h | fc47d75162f26f36633037292ad1f3da0bf79143 | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,361 | h | /*******************************************************************************/
/**
* @file Utility.h.
*
* @brief ユーティリティークラスヘッダファイル.
*
* @date 2008/06/28.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#ifndef _NGL_UTIITY_H_
#define _NGL_UTIITY_H_
#include <string>
namespace Ngl{
/**
* @class Utility
* @brief ユーティリティークラス.
*/
class Utility
{
public:
/*=========================================================================*/
/**
* @brief フルパスのファイル名からファイル名を切り出す( 拡張子なし )
*
* @param[in] fileName 切り出すファイル名.
* @return 切り出したファイル名.
*/
static std::string getFileName( const char* fileName );
/*=========================================================================*/
/**
* @brief 拡張子を切り出す( .を含まない )
*
* @param[in] fileName 切り出すファイル名.
* @return 切り出した拡張子.
*/
static std::string getFileExtension( const char* fileName );
/*=========================================================================*/
/**
* @brief ファイルパスのドライブ名を切り出す
*
* @param[in] fileName 切り出すファイル名.
* @return 切り出したパス.
*/
static std::string getFilePathDrave( const char* fileName );
/*=========================================================================*/
/**
* @brief ファイルパスのディレクトリ名を切り出す
*
* @param[in] fileName 切り出すファイル名.
* @return 切り出したディレクトリ.
*/
static std::string getFilePathDir( const char* fileName );
/*=========================================================================*/
/**
* @brief charからwchar_tへ変換する
*
* @param[in] src 変換元のconst char型文字列.
* @param[in] dest 変換データを格納するwchar_t型文字列.
* @return なし.
*/
static void multiByteToWideChar( const char* src, wchar_t* dest );
};
} // namespace ngl
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
86
]
]
]
|
4d1ef1387deb9f03e24ba1944d24a9f7a3ca1343 | 699401c51bd407f32c4984faec2e4807fede97be | /AnimationThread.h | a6d5b04bc1c30cf8d43ed702e31bf2b6d35f50f5 | []
| no_license | NIA/Fractal | 9c7d817d62b6f20a8309814a001f23bf90623d7c | c8b0eb622284d7ccbf3478422bc0a21ad6ee2a75 | refs/heads/master | 2021-04-26T16:48:07.242246 | 2009-12-17T19:30:40 | 2009-12-17T19:30:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | h | #pragma once
#include "Thread.h"
class CFractalDlg;
class CAnimationThread : public CThread, public ICanvasThread
{
private:
CCalculationThread * current_thread;
CFractalDlg * dialog;
unsigned zoom_count;
bool zoom_in;
public:
CAnimationThread(CFractalDlg * dialog, unsigned zoom_count, bool zoom_in);
unsigned get_zoom_count() { return zoom_count; }
virtual RGBQUAD *get_pixels();
void calculate_frame(bool zoom);
void post_message(UINT msg);
static DWORD WINAPI routine( void * param);
virtual LPTHREAD_START_ROUTINE get_routine(){ return routine; };
virtual void on_stop();
}; | [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
31bb9f054bba41f0cd9dbfa98eded05d2509477c | bd84d60e0313382c31d33f516c1fe6a692e81807 | /Alive_Video_Converter_5_lnk/arduino.cpp | 43a035839fcec1cf107148b70ed2cb5d45b0ce65 | []
| no_license | kevlolol/WordClock | 5c23cd90835407ff151ab828a252336aa0294c1d | 4b6f1ebb24ba8042ae29bd30fbaeba4f2c7c09ee | refs/heads/master | 2020-05-30T18:38:51.403830 | 2011-07-24T08:13:16 | 2011-07-24T08:13:16 | 2,095,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21 | cpp | class Arduino
{
}
| [
"[email protected]"
]
| [
[
[
1,
5
]
]
]
|
a3fba57335c96ec05f30812805f86a7a0fe412e4 | fe7a7f1385a7dd8104e6ccc105f9bb3141c63c68 | /movement.cpp | b3967194ed9a56c49105381f30e4ea2f0e6b7ab9 | []
| no_license | divinity76/ancient-divinity-ots | d29efe620cea3fe8d61ffd66480cf20c8f77af13 | 0c7b5bfd5b9277c97d28de598f781dbb198f473d | refs/heads/master | 2020-05-16T21:01:29.130756 | 2010-10-11T22:58:07 | 2010-10-11T22:58:07 | 29,501,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,852 | cpp | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// 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 "otpch.h"
#include "game.h"
#include "creature.h"
#include "player.h"
#include "tile.h"
#include <sstream>
#include "tools.h"
#include "combat.h"
#include "vocation.h"
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include "movement.h"
extern Game g_game;
extern Vocations g_vocations;
extern MoveEvents* g_moveEvents;
MoveEvents::MoveEvents() :
m_scriptInterface("MoveEvents Interface")
{
m_scriptInterface.initState();
}
MoveEvents::~MoveEvents()
{
clear();
}
void MoveEvents::clear()
{
MoveListMap::iterator it = m_itemIdMap.begin();
while(it != m_itemIdMap.end()){
for(int i = 0; i < MOVE_EVENT_LAST; ++i){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[i];
for(std::list<MoveEvent*>::iterator it = moveEventList.begin(); it != moveEventList.end(); ++it){
delete (*it);
}
}
m_itemIdMap.erase(it);
it = m_itemIdMap.begin();
}
it = m_actionIdMap.begin();
while(it != m_actionIdMap.end()){
for(int i = 0; i < MOVE_EVENT_LAST; ++i){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[i];
for(std::list<MoveEvent*>::iterator it = moveEventList.begin(); it != moveEventList.end(); ++it){
delete (*it);
}
}
m_actionIdMap.erase(it);
it = m_actionIdMap.begin();
}
it = m_uniqueIdMap.begin();
while(it != m_uniqueIdMap.end()){
for(int i = 0; i < MOVE_EVENT_LAST; ++i){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[i];
for(std::list<MoveEvent*>::iterator it = moveEventList.begin(); it != moveEventList.end(); ++it){
delete (*it);
}
}
m_uniqueIdMap.erase(it);
it = m_uniqueIdMap.begin();
}
MovePosListMap::iterator posIter = m_positionMap.begin();
while(posIter != m_positionMap.end()){
for(int i = 0; i < MOVE_EVENT_LAST; ++i){
std::list<MoveEvent*>& moveEventList = posIter->second.moveEvent[i];
for(std::list<MoveEvent*>::iterator it = moveEventList.begin(); it != moveEventList.end(); ++it){
delete (*it);
}
}
m_positionMap.erase(posIter);
posIter = m_positionMap.begin();
}
m_scriptInterface.reInitState();
}
LuaScriptInterface& MoveEvents::getScriptInterface()
{
return m_scriptInterface;
}
std::string MoveEvents::getScriptBaseName()
{
return "movements";
}
Event* MoveEvents::getEvent(const std::string& nodeName)
{
if(asLowerCaseString(nodeName) == "movevent"){
return new MoveEvent(&m_scriptInterface);
}
else{
return NULL;
}
}
bool MoveEvents::registerEvent(Event* event, xmlNodePtr p)
{
MoveEvent* moveEvent = dynamic_cast<MoveEvent*>(event);
if(!moveEvent)
return false;
bool success = true;
int id;
std::string str;
MoveEvent_t eventType = moveEvent->getEventType();
if(eventType == MOVE_EVENT_ADD_ITEM || eventType == MOVE_EVENT_REMOVE_ITEM){
if(readXMLInteger(p,"tileitem",id) && id == 1){
switch(eventType){
case MOVE_EVENT_ADD_ITEM:
moveEvent->setEventType(MOVE_EVENT_ADD_ITEM_ITEMTILE);
break;
case MOVE_EVENT_REMOVE_ITEM:
moveEvent->setEventType(MOVE_EVENT_REMOVE_ITEM_ITEMTILE);
break;
default:
break;
}
}
}
if(readXMLInteger(p,"itemid",id)){
if(moveEvent->getEventType() == MOVE_EVENT_EQUIP){
ItemType& it = Item::items.getItemType(id);
it.wieldInfo = moveEvent->getWieldInfo();
it.minReqLevel = moveEvent->getReqLevel();
it.minReqMagicLevel = moveEvent->getReqMagLv();
it.vocationString = moveEvent->getVocationString();
}
addEvent(moveEvent, id, m_itemIdMap);
}
else if(readXMLInteger(p,"uniqueid",id)){
addEvent(moveEvent, id, m_uniqueIdMap);
}
else if(readXMLInteger(p,"actionid",id)){
addEvent(moveEvent, id, m_actionIdMap);
}
else if(readXMLString(p,"pos",str)){
std::vector<std::string> posList = explodeString(str, ";");
if(posList.size() < 3){
success = false;
}
else{
Position pos;
pos.x = atoi(posList[0].c_str());
pos.y = atoi(posList[1].c_str());
pos.z = atoi(posList[2].c_str());
addEvent(moveEvent, pos, m_positionMap);
}
}
else{
success = false;
}
return success;
}
void MoveEvents::addEvent(MoveEvent* moveEvent, int32_t id, MoveListMap& map)
{
MoveListMap::iterator it = map.find(id);
if(it == map.end()){
MoveEventList moveEventList;
moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent);
map[id] = moveEventList;
}
else{
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[moveEvent->getEventType()];
for(std::list<MoveEvent*>::iterator it = moveEventList.begin(); it != moveEventList.end(); ++it){
if((*it)->getSlot() == moveEvent->getSlot()){
std::cout << "Warning: [MoveEvents::addEvent] Duplicate move event found: " << id << std::endl;
}
}
moveEventList.push_back(moveEvent);
}
}
MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType, slots_t slot)
{
uint32_t slotp = 0;
switch(slot)
{
case SLOT_HEAD: slotp = SLOTP_HEAD; break;
case SLOT_NECKLACE: slotp = SLOTP_NECKLACE; break;
case SLOT_BACKPACK: slotp = SLOTP_BACKPACK; break;
case SLOT_ARMOR: slotp = SLOTP_ARMOR; break;
case SLOT_RIGHT: slotp = SLOTP_RIGHT; break;
case SLOT_LEFT: slotp = SLOTP_LEFT; break;
case SLOT_LEGS: slotp = SLOTP_LEGS; break;
case SLOT_FEET: slotp = SLOTP_FEET; break;
case SLOT_AMMO: slotp = SLOTP_AMMO; break;
case SLOT_RING: slotp = SLOTP_RING; break;
default: slotp = 0; break;
}
MoveListMap::iterator it = m_itemIdMap.find(item->getID());
if(it != m_itemIdMap.end()){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[eventType];
for(std::list<MoveEvent*>::iterator it = moveEventList.begin(); it != moveEventList.end(); ++it){
if(((*it)->getSlot() & slotp) != 0){
return *it;
}
}
}
return NULL;
}
MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType)
{
MoveListMap::iterator it;
if(item->getUniqueId() != 0){
it = m_uniqueIdMap.find(item->getUniqueId());
if(it != m_uniqueIdMap.end()){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[eventType];
if(!moveEventList.empty()){
return *moveEventList.begin();
}
}
}
if(item->getActionId() != 0){
it = m_actionIdMap.find(item->getActionId());
if(it != m_actionIdMap.end()){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[eventType];
if(!moveEventList.empty()){
return *moveEventList.begin();
}
}
}
it = m_itemIdMap.find(item->getID());
if(it != m_itemIdMap.end()){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[eventType];
if(!moveEventList.empty()){
return *moveEventList.begin();
}
}
return NULL;
}
void MoveEvents::addEvent(MoveEvent* moveEvent, Position pos, MovePosListMap& map)
{
MovePosListMap::iterator it = map.find(pos);
if(it == map.end()){
MoveEventList moveEventList;
moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent);
map[pos] = moveEventList;
}
else{
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[moveEvent->getEventType()];
if(!moveEventList.empty()){
std::cout << "Warning: [MoveEvents::addEvent] Duplicate move event found: " << pos << std::endl;
}
moveEventList.push_back(moveEvent);
}
}
MoveEvent* MoveEvents::getEvent(Tile* tile, MoveEvent_t eventType)
{
MovePosListMap::iterator it = m_positionMap.find(tile->getPosition());
if(it != m_positionMap.end()){
std::list<MoveEvent*>& moveEventList = it->second.moveEvent[eventType];
if(!moveEventList.empty()){
return *moveEventList.begin();
}
}
return NULL;
}
uint32_t MoveEvents::onCreatureMove(Creature* creature, Tile* tile, bool isIn)
{
MoveEvent_t eventType;
if(isIn){
eventType = MOVE_EVENT_STEP_IN;
}
else{
eventType = MOVE_EVENT_STEP_OUT;
}
uint32_t ret = 1;
MoveEvent* moveEvent = getEvent(tile, eventType);
if(moveEvent){
ret = ret & moveEvent->fireStepEvent(creature, NULL, tile->getPosition());
}
int32_t j = tile->__getLastIndex();
Item* tileItem = NULL;
for(int32_t i = tile->__getFirstIndex(); i < j; ++i){
Thing* thing = tile->__getThing(i);
if(thing && (tileItem = thing->getItem())){
moveEvent = getEvent(tileItem, eventType);
if(moveEvent){
ret = ret & moveEvent->fireStepEvent(creature, tileItem, tile->getPosition());
}
}
}
return ret;
}
uint32_t MoveEvents::onPlayerEquip(Player* player, Item* item, slots_t slot)
{
MoveEvent* moveEvent = getEvent(item, MOVE_EVENT_EQUIP, slot);
if(moveEvent){
return moveEvent->fireEquip(player, item, slot, false);
}
return 1;
}
uint32_t MoveEvents::onPlayerDeEquip(Player* player, Item* item, slots_t slot, bool isRemoval)
{
MoveEvent* moveEvent = getEvent(item, MOVE_EVENT_DEEQUIP, slot);
if(moveEvent){
return moveEvent->fireEquip(player, item, slot, isRemoval);
}
return 1;
}
uint32_t MoveEvents::onItemMove(Item* item, Tile* tile, bool isAdd)
{
MoveEvent_t eventType1;
MoveEvent_t eventType2;
if(isAdd){
eventType1 = MOVE_EVENT_ADD_ITEM;
eventType2 = MOVE_EVENT_ADD_ITEM_ITEMTILE;
}
else{
eventType1 = MOVE_EVENT_REMOVE_ITEM;
eventType2 = MOVE_EVENT_REMOVE_ITEM_ITEMTILE;
}
uint32_t ret = 1;
MoveEvent* moveEvent = getEvent(tile, eventType1);
if(moveEvent){
ret = ret & moveEvent->fireAddRemItem(item, NULL, tile->getPosition());
}
moveEvent = getEvent(item, eventType1);
if(moveEvent){
ret = ret & moveEvent->fireAddRemItem(item, NULL, tile->getPosition());
}
int32_t j = tile->__getLastIndex();
Item* tileItem = NULL;
for(int32_t i = tile->__getFirstIndex(); i < j; ++i){
Thing* thing = tile->__getThing(i);
if(thing && (tileItem = thing->getItem()) && (tileItem != item)){
moveEvent = getEvent(tileItem, eventType2);
if(moveEvent){
ret = ret & moveEvent->fireAddRemItem(item, tileItem, tile->getPosition());
}
}
}
return ret;
}
MoveEvent::MoveEvent(LuaScriptInterface* _interface) :
Event(_interface)
{
m_eventType = MOVE_EVENT_NONE;
stepFunction = NULL;
moveFunction = NULL;
equipFunction = NULL;
slot = 0xFFFFFFFF;
reqLevel = 0;
reqMagLevel = 0;
premium = false;
}
MoveEvent::~MoveEvent()
{
//
}
std::string MoveEvent::getScriptEventName()
{
switch(m_eventType){
case MOVE_EVENT_STEP_IN:
return "onStepIn";
break;
case MOVE_EVENT_STEP_OUT:
return "onStepOut";
break;
case MOVE_EVENT_EQUIP:
return "onEquip";
break;
case MOVE_EVENT_DEEQUIP:
return "onDeEquip";
break;
case MOVE_EVENT_ADD_ITEM:
return "onAddItem";
break;
case MOVE_EVENT_REMOVE_ITEM:
return "onRemoveItem";
break;
default:
std::cout << "Error: [MoveEvent::getScriptEventName()] No valid event type." << std::endl;
return "";
break;
};
}
bool MoveEvent::configureEvent(xmlNodePtr p)
{
std::string str;
int intValue;
if(readXMLString(p, "event", str)){
if(asLowerCaseString(str) == "stepin"){
m_eventType = MOVE_EVENT_STEP_IN;
}
else if(asLowerCaseString(str) == "stepout"){
m_eventType = MOVE_EVENT_STEP_OUT;
}
else if(asLowerCaseString(str) == "equip"){
m_eventType = MOVE_EVENT_EQUIP;
}
else if(asLowerCaseString(str) == "deequip"){
m_eventType = MOVE_EVENT_DEEQUIP;
}
else if(asLowerCaseString(str) == "additem"){
m_eventType = MOVE_EVENT_ADD_ITEM;
}
else if(asLowerCaseString(str) == "removeitem"){
m_eventType = MOVE_EVENT_REMOVE_ITEM;
}
else{
std::cout << "Error: [MoveEvent::configureMoveEvent] No valid event name " << str << std::endl;
return false;
}
if(m_eventType == MOVE_EVENT_EQUIP || m_eventType == MOVE_EVENT_DEEQUIP){
if(readXMLString(p, "slot", str)){
if(asLowerCaseString(str) == "head"){
slot = SLOTP_HEAD;
}
else if(asLowerCaseString(str) == "necklace"){
slot = SLOTP_NECKLACE;
}
else if(asLowerCaseString(str) == "backpack"){
slot = SLOTP_BACKPACK;
}
else if(asLowerCaseString(str) == "armor"){
slot = SLOTP_ARMOR;
}
else if(asLowerCaseString(str) == "right-hand"){
slot = SLOTP_RIGHT;
}
else if(asLowerCaseString(str) == "left-hand"){
slot = SLOTP_LEFT;
}
else if(asLowerCaseString(str) == "hand"){
slot = SLOTP_RIGHT | SLOTP_LEFT;
}
else if(asLowerCaseString(str) == "legs"){
slot = SLOTP_LEGS;
}
else if(asLowerCaseString(str) == "feet"){
slot = SLOTP_FEET;
}
else if(asLowerCaseString(str) == "ring"){
slot = SLOTP_RING;
}
else if(asLowerCaseString(str) == "ammo"){
slot = SLOTP_AMMO;
}
else{
std::cout << "Warning: [MoveEvent::configureMoveEvent] " << "Unknown slot type " << str << std::endl;
}
}
wieldInfo = 0;
if(readXMLInteger(p, "lvl", intValue) || readXMLInteger(p, "level", intValue)){
reqLevel = intValue;
if(reqLevel > 0){
wieldInfo |= WIELDINFO_LEVEL;
}
}
if(readXMLInteger(p, "maglv", intValue) || readXMLInteger(p, "maglevel", intValue)){
reqMagLevel = intValue;
if(reqMagLevel > 0){
wieldInfo |= WIELDINFO_MAGLV;
}
}
if(readXMLInteger(p, "prem", intValue) || readXMLInteger(p, "premium", intValue)){
premium = (intValue != 0);
if(premium){
wieldInfo |= WIELDINFO_PREMIUM;
}
}
//Gather vocation information
typedef std::list<std::string> STRING_LIST;
STRING_LIST vocStringList;
xmlNodePtr vocationNode = p->children;
while(vocationNode){
if(xmlStrcmp(vocationNode->name,(const xmlChar*)"vocation") == 0){
if(readXMLString(vocationNode, "name", str)){
int32_t vocationId = g_vocations.getVocationId(str);
if(vocationId != -1){
vocEquipMap[vocationId] = true;
intValue = 1;
readXMLInteger(vocationNode, "showInDescription", intValue);
if(intValue != 0){
toLowerCaseString(str);
vocStringList.push_back(str);
}
}
}
}
vocationNode = vocationNode->next;
}
if(!vocStringList.empty()){
for(STRING_LIST::iterator it = vocStringList.begin(); it != vocStringList.end(); ++it){
if(*it != vocStringList.front()){
if(*it != vocStringList.back()){
vocationString += ", ";
}
else{
vocationString += " and ";
}
}
vocationString += *it;
vocationString += "s";
}
wieldInfo |= WIELDINFO_VOCREQ;
}
}
}
else{
std::cout << "Error: [MoveEvent::configureMoveEvent] No event found." << std::endl;
return false;
}
return true;
}
bool MoveEvent::loadFunction(const std::string& functionName)
{
if(asLowerCaseString(functionName) == "onstepinfield"){
stepFunction = StepInField;
}
else if(asLowerCaseString(functionName) == "onstepoutfield"){
stepFunction = StepOutField;
}
else if(asLowerCaseString(functionName) == "onaddfield"){
moveFunction = AddItemField;
}
else if(asLowerCaseString(functionName) == "onremovefield"){
moveFunction = RemoveItemField;
}
else if(asLowerCaseString(functionName) == "onequipitem"){
equipFunction = EquipItem;
}
else if(asLowerCaseString(functionName) == "ondeequipitem"){
equipFunction = DeEquipItem;
}
else{
return false;
}
m_scripted = false;
return true;
}
MoveEvent_t MoveEvent::getEventType() const
{
if(m_eventType == MOVE_EVENT_NONE){
std::cout << "Error: [MoveEvent::getEventType()] MOVE_EVENT_NONE" << std::endl;
return (MoveEvent_t)0;
}
return m_eventType;
}
void MoveEvent::setEventType(MoveEvent_t type)
{
m_eventType = type;
}
uint32_t MoveEvent::StepInField(Creature* creature, Item* item, const Position& pos)
{
MagicField* field = item->getMagicField();
if(field){
bool purposeful = true;
if(creature->getPlayer())
purposeful = false;
field->onStepInField(creature, purposeful);
return 1;
}
return LUA_ERROR_ITEM_NOT_FOUND;
}
uint32_t MoveEvent::StepOutField(Creature* creature, Item* item, const Position& pos)
{
return 1;
}
uint32_t MoveEvent::AddItemField(Item* item, Item* tileItem, const Position& pos)
{
if(MagicField* field = item->getMagicField()){
Tile* tile = item->getTile();
for(CreatureVector::iterator cit = tile->creatures.begin(); cit != tile->creatures.end(); ++cit){
field->onStepInField(*cit);
}
return 1;
}
return LUA_ERROR_ITEM_NOT_FOUND;
}
uint32_t MoveEvent::RemoveItemField(Item* item, Item* tileItem, const Position& pos)
{
return 1;
}
uint32_t MoveEvent::EquipItem(MoveEvent* moveEvent, Player* player, Item* item, slots_t slot, bool isRemoval)
{
if(player->isItemAbilityEnabled(slot)){
return 1;
}
//Enable item only when requirements are complete
//This includes item transforming
if(!player->hasFlag(PlayerFlag_IgnoreWeaponCheck) && moveEvent->getWieldInfo() != 0){
if((int32_t)player->getLevel() < moveEvent->getReqLevel()
|| (int32_t)player->getMagicLevel() < moveEvent->getReqMagLv() ||
!player->isPremium() && moveEvent->isPremium())
{
return 1;
}
const VocEquipMap vocMap = moveEvent->getVocEquipMap();
if(!vocMap.empty()){
if(vocMap.find(player->getVocationId()) == vocMap.end()){
return 1;
}
}
}
const ItemType& it = Item::items[item->getID()];
if(it.transformEquipTo != 0){
Item* newItem = g_game.transformItem(item, it.transformEquipTo);
g_game.startDecay(newItem);
}
else{
player->setItemAbility(slot, true);
}
if(it.abilities.preventLoss){
player->setLossPercent(LOSS_ITEMS, 0);
}
if(it.abilities.invisible){
Condition* condition = Condition::createCondition((ConditionId_t)slot, CONDITION_INVISIBLE, -1, 0);
player->addCondition(condition);
}
if(it.abilities.manaShield){
Condition* condition = Condition::createCondition((ConditionId_t)slot, CONDITION_MANASHIELD, -1, 0);
player->addCondition(condition);
}
if(it.abilities.speed != 0){
g_game.changeSpeed(player, it.abilities.speed);
}
if(it.abilities.conditionSuppressions != 0){
player->setConditionSuppressions(it.abilities.conditionSuppressions, false);
player->sendIcons();
}
if(it.abilities.regeneration){
Condition* condition = Condition::createCondition((ConditionId_t)slot, CONDITION_REGENERATION, -1, 0);
if(it.abilities.healthGain != 0){
condition->setParam(CONDITIONPARAM_HEALTHGAIN, it.abilities.healthGain);
}
if(it.abilities.healthTicks != 0){
condition->setParam(CONDITIONPARAM_HEALTHTICKS, it.abilities.healthTicks);
}
if(it.abilities.manaGain != 0){
condition->setParam(CONDITIONPARAM_MANAGAIN, it.abilities.manaGain);
}
if(it.abilities.manaTicks != 0){
condition->setParam(CONDITIONPARAM_MANATICKS, it.abilities.manaTicks);
}
player->addCondition(condition);
}
//skill modifiers
bool needUpdateSkills = false;
for(int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i){
if(it.abilities.skills[i]){
needUpdateSkills = true;
player->setVarSkill((skills_t)i, it.abilities.skills[i]);
}
}
if(needUpdateSkills){
player->sendSkills();
}
//stat modifiers
bool needUpdateStats = false;
for(int32_t s = STAT_FIRST; s <= STAT_LAST; ++s){
if(it.abilities.stats[s]){
needUpdateStats = true;
player->setVarStats((stats_t)s, it.abilities.stats[s]);
}
if(it.abilities.statsPercent[s]){
needUpdateStats = true;
player->setVarStats((stats_t)s, (int32_t)(player->getDefaultStats((stats_t)s) * ((it.abilities.statsPercent[s] - 100) / 100.f)));
}
}
if(needUpdateStats){
player->sendStats();
}
return 1;
}
uint32_t MoveEvent::DeEquipItem(MoveEvent* moveEvent, Player* player, Item* item, slots_t slot, bool isRemoval)
{
if(!player->isItemAbilityEnabled(slot)){
return 1;
}
player->setItemAbility(slot, false);
const ItemType& it = Item::items[item->getID()];
if(isRemoval && it.transformDeEquipTo != 0){
g_game.transformItem(item, it.transformDeEquipTo);
g_game.startDecay(item);
}
if(it.abilities.preventLoss) {
player->setLossPercent(LOSS_ITEMS, 10);
}
if(it.abilities.invisible){
player->removeCondition(CONDITION_INVISIBLE, (ConditionId_t)slot);
}
if(it.abilities.manaShield){
player->removeCondition(CONDITION_MANASHIELD, (ConditionId_t)slot);
}
if(it.abilities.speed != 0){
g_game.changeSpeed(player, -it.abilities.speed);
}
if(it.abilities.conditionSuppressions != 0){
player->setConditionSuppressions(it.abilities.conditionSuppressions, true);
player->sendIcons();
}
if(it.abilities.regeneration){
player->removeCondition(CONDITION_REGENERATION, (ConditionId_t)slot);
}
//skill modifiers
bool needUpdateSkills = false;
for(int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i){
if(it.abilities.skills[i] != 0){
needUpdateSkills = true;
player->setVarSkill((skills_t)i, -it.abilities.skills[i]);
}
}
if(needUpdateSkills){
player->sendSkills();
}
//stat modifiers
bool needUpdateStats = false;
for(int32_t s = STAT_FIRST; s <= STAT_LAST; ++s){
if(it.abilities.stats[s]){
needUpdateStats = true;
player->setVarStats((stats_t)s, -it.abilities.stats[s]);
}
if(it.abilities.statsPercent[s]){
needUpdateStats = true;
player->setVarStats((stats_t)s, -(int32_t)(player->getDefaultStats((stats_t)s) * ((it.abilities.statsPercent[s] - 100) / 100.f)));
}
}
if(needUpdateStats){
player->sendStats();
}
return 1;
}
uint32_t MoveEvent::fireStepEvent(Creature* creature, Item* item, const Position& pos)
{
if(m_scripted){
return executeStep(creature, item, pos);
}
else{
return stepFunction(creature, item, pos);
}
}
uint32_t MoveEvent::executeStep(Creature* creature, Item* item, const Position& pos)
{
//onStepIn(cid, item, pos)
//onStepOut(cid, item, pos)
if(m_scriptInterface->reserveScriptEnv()){
ScriptEnviroment* env = m_scriptInterface->getScriptEnv();
#ifdef __DEBUG_LUASCRIPTS__
std::stringstream desc;
desc << creature->getName() << " itemid: " << item->getID() << " - " << pos;
env->setEventDesc(desc.str());
#endif
env->setScriptId(m_scriptId, m_scriptInterface);
env->setRealPos(pos);
uint32_t cid = env->addThing(creature);
uint32_t itemid = env->addThing(item);
lua_State* L = m_scriptInterface->getLuaState();
m_scriptInterface->pushFunction(m_scriptId);
lua_pushnumber(L, cid);
LuaScriptInterface::pushThing(L, item, itemid);
LuaScriptInterface::pushPosition(L, pos, 0);
int32_t result = m_scriptInterface->callFunction(3);
m_scriptInterface->releaseScriptEnv();
return (result != LUA_FALSE);
}
else{
std::cout << "[Error] Call stack overflow. MoveEvent::executeStep" << std::endl;
return 0;
}
}
uint32_t MoveEvent::fireEquip(Player* player, Item* item, slots_t slot, bool isRemoval)
{
if(m_scripted){
return executeEquip(player, item, slot);
}
else{
return equipFunction(this, player, item, slot, isRemoval);
}
}
uint32_t MoveEvent::executeEquip(Player* player, Item* item, slots_t slot)
{
//onEquip(cid, item, slot)
//onDeEquip(cid, item, slot)
if(m_scriptInterface->reserveScriptEnv()){
ScriptEnviroment* env = m_scriptInterface->getScriptEnv();
#ifdef __DEBUG_LUASCRIPTS__
std::stringstream desc;
desc << player->getName() << " itemid:" << item->getID() << " slot:" << slot;
env->setEventDesc(desc.str());
#endif
env->setScriptId(m_scriptId, m_scriptInterface);
env->setRealPos(player->getPosition());
uint32_t cid = env->addThing(player);
uint32_t itemid = env->addThing(item);
lua_State* L = m_scriptInterface->getLuaState();
m_scriptInterface->pushFunction(m_scriptId);
lua_pushnumber(L, cid);
LuaScriptInterface::pushThing(L, item, itemid);
lua_pushnumber(L, slot);
int32_t result = m_scriptInterface->callFunction(3);
m_scriptInterface->releaseScriptEnv();
return (result != LUA_FALSE);
}
else{
std::cout << "[Error] Call stack overflow. MoveEvent::executeEquip" << std::endl;
return 0;
}
}
uint32_t MoveEvent::fireAddRemItem(Item* item, Item* tileItem, const Position& pos)
{
if(m_scripted){
return executeAddRemItem(item, tileItem, pos);
}
else{
return moveFunction(item, tileItem, pos);
}
}
uint32_t MoveEvent::executeAddRemItem(Item* item, Item* tileItem, const Position& pos)
{
//onAddItem(moveitem, tileitem, pos)
//onRemoveItem(moveitem, tileitem, pos)
if(m_scriptInterface->reserveScriptEnv()){
ScriptEnviroment* env = m_scriptInterface->getScriptEnv();
#ifdef __DEBUG_LUASCRIPTS__
std::stringstream desc;
if(tileItem){
desc << "tileid: " << tileItem->getID();
}
desc << " itemid: " << item->getID() << " - " << pos;
env->setEventDesc(desc.str());
#endif
env->setScriptId(m_scriptId, m_scriptInterface);
env->setRealPos(pos);
uint32_t itemidMoved = env->addThing(item);
uint32_t itemidTile = env->addThing(tileItem);
lua_State* L = m_scriptInterface->getLuaState();
m_scriptInterface->pushFunction(m_scriptId);
LuaScriptInterface::pushThing(L, item, itemidMoved);
LuaScriptInterface::pushThing(L, tileItem, itemidTile);
LuaScriptInterface::pushPosition(L, pos, 0);
int32_t result = m_scriptInterface->callFunction(3);
m_scriptInterface->releaseScriptEnv();
return (result != LUA_FALSE);
}
else{
std::cout << "[Error] Call stack overflow. MoveEvent::executeAddRemItem" << std::endl;
return 0;
}
}
| [
"[email protected]@6be3b30e-f956-11de-ba51-6b4196a2b81e"
]
| [
[
[
1,
975
]
]
]
|
0793896001107a7abc9fcd299de3370e54ab91f4 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Samples/LightShafts/Main.cpp | 6b13dee53a4049e34febc34e90ceb3e45e912d01 | []
| 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 | 644 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: Main.cpp
Version: 0.50
Info: Main source for the IGK'2008 demo application.
---------------------------------------------------------------------------
*/
#define NOMINMAX
#include <windows.h>
#include "App.h"
using namespace nGENE::Application;
/*
Application is created here.
*/
int main()
{
#ifdef _WIN32
App app;
#else
#endif
app.createApplication();
app.run();
app.shutdown();
return 0;
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
39
]
]
]
|
75218d06869165edbb89755b40cb9d52289cbcd8 | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/messages/player_messages/chat_msg_item.hpp | 7481ac45d473d29d1043f9ad4e781abd98ad8346 | []
| no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 766 | hpp | #ifndef CHAT_MSG_ITEM_HPP
#define CHAT_MSG_ITEM_HPP
#include <string>
#include <vector>
struct chat_msg_item_t {
unsigned int color;
std::string msg;
bool is_clear;
// Сообщение
chat_msg_item_t(unsigned int color, std::string const& msg);
// Очистка чата
chat_msg_item_t();
~chat_msg_item_t();
};
typedef std::vector<chat_msg_item_t> chat_msg_items_t;
struct chat_bubble_t {
unsigned color;
float draw_distance;
int expire_time;
std::string text;
chat_bubble_t();
chat_bubble_t(int expire_time);
};
chat_msg_items_t create_chat_items(std::string const& msg);
chat_bubble_t create_chat_bubble(std::string const& text);
#endif // CHAT_MSG_ITEM_HPP
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
]
| [
[
[
1,
33
]
]
]
|
9c2447b431eea6f3d21f9442059db610d05b6f81 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/idudpserver.hpp | 689bee33c29d5723dd30354ac0c8744329a60a5e | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,904 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IdUDPServer.pas' rev: 6.00
#ifndef IdUDPServerHPP
#define IdUDPServerHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <IdUDPBase.hpp> // Pascal unit
#include <IdThread.hpp> // Pascal unit
#include <IdStackConsts.hpp> // Pascal unit
#include <IdSocketHandle.hpp> // Pascal unit
#include <IdGlobal.hpp> // Pascal unit
#include <IdException.hpp> // Pascal unit
#include <IdComponent.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Idudpserver
{
//-- type declarations -------------------------------------------------------
typedef void __fastcall (__closure *TUDPReadEvent)(System::TObject* Sender, Classes::TStream* AData, Idsockethandle::TIdSocketHandle* ABinding);
class DELPHICLASS TIdUDPListenerThread;
class DELPHICLASS TIdUDPServer;
class PASCALIMPLEMENTATION TIdUDPServer : public Idudpbase::TIdUDPBase
{
typedef Idudpbase::TIdUDPBase inherited;
protected:
Idsockethandle::TIdSocketHandles* FBindings;
Idsockethandle::TIdSocketHandle* FCurrentBinding;
TIdUDPListenerThread* FListenerThread;
TUDPReadEvent FOnUDPRead;
bool FThreadedEvent;
int __fastcall GetDefaultPort(void);
void __fastcall SetBindings(const Idsockethandle::TIdSocketHandles* Value);
void __fastcall SetDefaultPort(const int AValue);
void __fastcall PacketReceived(Classes::TStream* AData, Idsockethandle::TIdSocketHandle* ABinding);
virtual void __fastcall DoUDPRead(Classes::TStream* AData, Idsockethandle::TIdSocketHandle* ABinding);
virtual Idsockethandle::TIdSocketHandle* __fastcall GetBinding(void);
virtual void __fastcall CloseBinding(void);
DYNAMIC void __fastcall BroadcastEnabledChanged(void);
virtual bool __fastcall GetActive(void);
public:
__fastcall virtual TIdUDPServer(Classes::TComponent* axOwner);
__fastcall virtual ~TIdUDPServer(void);
__published:
__property Idsockethandle::TIdSocketHandles* Bindings = {read=FBindings, write=SetBindings};
__property int DefaultPort = {read=GetDefaultPort, write=SetDefaultPort, nodefault};
__property TUDPReadEvent OnUDPRead = {read=FOnUDPRead, write=FOnUDPRead};
__property bool ThreadedEvent = {read=FThreadedEvent, write=FThreadedEvent, default=0};
};
class PASCALIMPLEMENTATION TIdUDPListenerThread : public Idthread::TIdThread
{
typedef Idthread::TIdThread inherited;
protected:
Idsockethandle::TIdSocketHandle* IncomingData;
int FAcceptWait;
Classes::TMemoryStream* FBuffer;
int FBufferSize;
public:
TIdUDPServer* FServer;
__fastcall TIdUDPListenerThread(const int ABufferSize, TIdUDPServer* Owner);
__fastcall virtual ~TIdUDPListenerThread(void);
virtual void __fastcall Run(void);
void __fastcall UDPRead(void);
__property int AcceptWait = {read=FAcceptWait, write=FAcceptWait, nodefault};
};
class DELPHICLASS EIdUDPServerException;
class PASCALIMPLEMENTATION EIdUDPServerException : public Idudpbase::EIdUDPException
{
typedef Idudpbase::EIdUDPException inherited;
public:
#pragma option push -w-inl
/* Exception.Create */ inline __fastcall EIdUDPServerException(const AnsiString Msg) : Idudpbase::EIdUDPException(Msg) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EIdUDPServerException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Idudpbase::EIdUDPException(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EIdUDPServerException(int Ident)/* overload */ : Idudpbase::EIdUDPException(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EIdUDPServerException(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Idudpbase::EIdUDPException(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EIdUDPServerException(const AnsiString Msg, int AHelpContext) : Idudpbase::EIdUDPException(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EIdUDPServerException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Idudpbase::EIdUDPException(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EIdUDPServerException(int Ident, int AHelpContext)/* overload */ : Idudpbase::EIdUDPException(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EIdUDPServerException(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Idudpbase::EIdUDPException(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EIdUDPServerException(void) { }
#pragma option pop
};
class DELPHICLASS EIdNoBindingsSpecified;
class PASCALIMPLEMENTATION EIdNoBindingsSpecified : public EIdUDPServerException
{
typedef EIdUDPServerException inherited;
public:
#pragma option push -w-inl
/* Exception.Create */ inline __fastcall EIdNoBindingsSpecified(const AnsiString Msg) : EIdUDPServerException(Msg) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EIdNoBindingsSpecified(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : EIdUDPServerException(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EIdNoBindingsSpecified(int Ident)/* overload */ : EIdUDPServerException(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EIdNoBindingsSpecified(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : EIdUDPServerException(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EIdNoBindingsSpecified(const AnsiString Msg, int AHelpContext) : EIdUDPServerException(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EIdNoBindingsSpecified(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : EIdUDPServerException(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EIdNoBindingsSpecified(int Ident, int AHelpContext)/* overload */ : EIdUDPServerException(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EIdNoBindingsSpecified(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : EIdUDPServerException(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EIdNoBindingsSpecified(void) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Idudpserver */
using namespace Idudpserver;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // IdUDPServer
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
172
]
]
]
|
104427544ad9b01eb020e7105f96f71051d23253 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/Demo/User_ModifyPsw.cpp | 81df35f200d1ed61eea42876be291c7d03fb5c43 | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,469 | cpp | // User_ModifyPsw.cpp : implementation file
//
#include "stdafx.h"
#include "netsdkdemo.h"
#include "User_ModifyPsw.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CUser_ModifyPsw dialog
CUser_ModifyPsw::CUser_ModifyPsw(CWnd* pParent /*=NULL*/)
: CDialog(CUser_ModifyPsw::IDD, pParent)
{
//{{AFX_DATA_INIT(CUser_ModifyPsw)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CUser_ModifyPsw::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CUser_ModifyPsw)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CUser_ModifyPsw, CDialog)
//{{AFX_MSG_MAP(CUser_ModifyPsw)
ON_BN_CLICKED(IDC_BTN_OK, OnBtnOk)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CUser_ModifyPsw message handlers
BOOL CUser_ModifyPsw::OnInitDialog()
{
CDialog::OnInitDialog();
g_SetWndStaticText(this);
if (!m_dev || !m_user_info)
{
return TRUE;
}
GetDlgItem(IDC_NAME_EDIT)->SetWindowText(m_user_info->userList[m_userIdx].name);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CUser_ModifyPsw::SetEnvrmt(USER_MANAGE_INFO *info, DWORD userIdx, DeviceNode *dev)
{
m_dev = dev;
m_user_info = info;
m_userIdx = userIdx;
}
void CUser_ModifyPsw::OnBtnOk()
{
USER_INFO newInfo = {0};
USER_INFO oldInfo = {0};
char tmp1[USER_PSW_LENGTH] = {0};
char tmp2[USER_PSW_LENGTH] = {0};
GetDlgItem(IDC_NEW_PSW_EDIT1)->GetWindowText(tmp1, USER_PSW_LENGTH);
GetDlgItem(IDC_NEW_PSW_EDIT2)->GetWindowText(tmp2, USER_PSW_LENGTH);
if (strcmp(tmp1, tmp2) != 0)
{
MessageBox(ConvertString("Illegal input"));
return;
}
memcpy(newInfo.passWord, tmp1, USER_PSW_LENGTH);
memcpy(oldInfo.name, m_user_info->userList[m_userIdx].name, USER_PSW_LENGTH);
GetDlgItem(IDC_OLD_PSW_EDIT)->GetWindowText(tmp1, USER_PSW_LENGTH);
memcpy(oldInfo.passWord, tmp1, USER_PSW_LENGTH);
BOOL bRet = CLIENT_OperateUserInfo(m_dev->LoginID, 6, (void *)&newInfo, &oldInfo, 1000);
if (!bRet)
{
MessageBox(ConvertString("Failed to operate user info"));
}
else
{
EndDialog(0);
}
}
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
96
]
]
]
|
27353edb383a07b3fd4566b7238b27b076d43162 | c70941413b8f7bf90173533115c148411c868bad | /plugins/AS3Plugin/src/vtxas3DisplayObject.cpp | 9ee3de82b3b7c589659aa1b29455d08728ff5c08 | []
| no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,116 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "vtxas3DisplayObject.h"
#include "vtxas3Object.h"
#include "vtxas3Stage.h"
#include "vtxas3ScriptInterface.h"
#include "vtxMovieClip.h"
#include "vtxMovie.h"
#include "vtxStage.h"
#include "cspVmCore.h"
namespace vtx { namespace as3 {
//-----------------------------------------------------------------------
void DisplayObject::ctor()
{
EventDispatcher::ctor();
}
//-----------------------------------------------------------------------
double DisplayObject::get_x()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_x()");
return mDisplayObject->getX();
}
//-----------------------------------------------------------------------
void DisplayObject::set_x(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_x()");
if(!mDisplayObject) return;
mDisplayObject->setX((float)val);
}
//-----------------------------------------------------------------------
double DisplayObject::get_y()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_y()");
if(!mDisplayObject) return 0;
return mDisplayObject->getY();
}
//-----------------------------------------------------------------------
void DisplayObject::set_y(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_y()");
if(!mDisplayObject) return;
mDisplayObject->setY((float)val);
}
//-----------------------------------------------------------------------
double DisplayObject::get_rotation()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_rotation()");
if(!mDisplayObject) return 0;
return mDisplayObject->getAngle();
}
//-----------------------------------------------------------------------
void DisplayObject::set_rotation(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_rotation()");
if(!mDisplayObject) return;
mDisplayObject->setAngle((float)val);
}
//-----------------------------------------------------------------------
double DisplayObject::get_scaleX()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_scaleX()");
if(!mDisplayObject) return 0;
return mDisplayObject->getScaleX();
}
//-----------------------------------------------------------------------
void DisplayObject::set_scaleX(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_scaleX()");
if(!mDisplayObject) return;
mDisplayObject->setScaleX((float)val);
}
//-----------------------------------------------------------------------
double DisplayObject::get_scaleY()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_scaleY()");
if(!mDisplayObject) return 0;
return mDisplayObject->getScaleY();
}
//-----------------------------------------------------------------------
void DisplayObject::set_scaleY(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_scaleY()");
if(!mDisplayObject) return;
mDisplayObject->setScaleY((float)val);
}
//-----------------------------------------------------------------------
double DisplayObject::get_width()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_width()");
if(!mDisplayObject) return 0;
return mDisplayObject->getWidth();
}
//-----------------------------------------------------------------------
void DisplayObject::set_width(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_width()");
if(!mDisplayObject) return;
mDisplayObject->setWidth((float)val);
}
//-----------------------------------------------------------------------
double DisplayObject::get__height()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_height()");
if(!mDisplayObject) return 0;
return mDisplayObject->getHeight();
}
//-----------------------------------------------------------------------
void DisplayObject::set__height(double val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject(NULL)::set_height()");
if(!mDisplayObject) return;
mDisplayObject->setHeight((float)val);
}
//-----------------------------------------------------------------------
DisplayObjectContainer* DisplayObject::get__parent()
{
VTX_DEBUG_WARNING(mDisplayObject, "DisplayObject(NULL)::get_parent()");
if(!mDisplayObject)
{
CSP_CORE->console << implToString() << "\n";
return NULL;
}
vtx::DisplayObjectContainer* parent = mDisplayObject->getParentContainer();
if(parent)
{
VTX_DEBUG_WARNING(parent, "DisplayObject::get_parent()");
AS3Object* object = static_cast<ScriptInterface*>(parent->getScriptObject())->getObject();
return static_cast<DisplayObjectContainer*>(object);
}
return NULL;
//return NULL;
// DisplayObjectContainer* container = static_cast<DisplayObjectContainer*>(mDisplayObject->getParentContainer()->getScriptObject());
// std::cout << "DisplayObject::parent() = " << container << std::endl;
// return container;
}
//-----------------------------------------------------------------------
DisplayObject* DisplayObject::get__root()
{
ScriptInterface* iface = static_cast<ScriptInterface*>(getParentMovie()->getMainMovieClip()->getScriptObject());
return static_cast<DisplayObject*>(iface->getObject());
}
//-----------------------------------------------------------------------
Stage* DisplayObject::get_stage()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_stage()");
ScriptInterface* iface = static_cast<ScriptInterface*>(mDisplayObject->getStage()->getScriptObject());
Stage* stage = static_cast<Stage*>(iface->getObject());
return stage;
//std::cout << "DisplayObject::get_stage()=" << mDisplayObject->getParent()->getStage()->getScriptObject() << std::endl;
//return static_cast<Stage*>(mDisplayObject->getParent()->getStage()->getScriptObject());
//return NULL;
}
//-----------------------------------------------------------------------
void DisplayObject::set__visible(bool val)
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::set_visible()");
if(!mDisplayObject) return;
mDisplayObject->setVisible(val);
}
//-----------------------------------------------------------------------
bool DisplayObject::get__visible()
{
VTX_DEBUG_ASSERT(mDisplayObject, "DisplayObject::get_visible()");
if(!mDisplayObject) return false;
return mDisplayObject->getVisible();
}
//-----------------------------------------------------------------------
void DisplayObject::init(Instance* inst, ScriptInterface* iface)
{
EventDispatcher::init(inst, iface);
mDisplayObject = static_cast<vtx::DisplayObject*>(inst);
}
//-----------------------------------------------------------------------
}}
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
]
| [
[
[
1,
207
]
]
]
|
eada1cb9e3a9db2aea470a28b75c922e34a832c2 | 20cf3257c981cb0c8db71ea6872d5833644e8159 | /build/msvc8/test_runner/test_runner.cpp | 3cb36535f189373908b90ce650ecdd272b9898b5 | []
| no_license | gfordyce/stan | f624847d3065700346ad0adc5470e639a8fdfb19 | 2d1eeafaf2336a205b37b785011bdc8a7e2dfe13 | refs/heads/master | 2021-01-10T19:17:15.909935 | 2010-03-10T14:07:49 | 2010-03-10T14:07:49 | 126,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | cpp | // test_runner.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
11
]
]
]
|
d67c9cd6763b427c489cf0d9d9cc5cefd4d88789 | 4c274852c010d1cff62b4c6294fbc158c3948f6c | /ometahcats/itsCatsProblem.hpp | 361fbeb0bbeb4d7eaaee592c7b1224bf99063173 | []
| no_license | BackupTheBerlios/ometah | 8531a9279e3b0c24c025351ff6c180ecaaaadd34 | ae26c936ce580e5f6d88b7fe01dab849e9abdcfb | refs/heads/master | 2021-01-23T07:30:08.211404 | 2007-05-23T09:01:58 | 2007-05-23T09:01:58 | 40,050,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | hpp | #ifndef ITSCATSPROBLEM
#define ITSCATSPROBLEM
#include <ometah/itsProblem.hpp>
#include <ometah/common/itsPoint.hpp>
class itsCatsProblem : public itsProblem
{
public:
itsCatsProblem();
itsPoint objectiveFunction(itsPoint point);
};
class itsCatsProblemFactory : public itsProblemFactory
{
public:
itsProblem * create();
};
#endif
| [
"nojhan"
]
| [
[
[
1,
22
]
]
]
|
5d907979ba32ab6239832dd26d0b1e705bcf4648 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/WFLMSOpWrapper.h | 5655b5f4b25802ef1dbbae8b434aabe7d2e03c3f | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,492 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __LANDMARKS_LM_OP_WRAPPER_H__
#define __LANDMARKS_LM_OP_WRAPPER_H__
// INCLUDES
#include <e32base.h>
// FORWARD DECLARATIONS
class CPosLmOperation;
// CLASS DECLARATION
/**
* Active class that wraps an instance of CPosLmOperation.
* The wrapped CPosLmOperation instance is executed incrementally.
* Execution progress can be reported.
* This class is designed to be utilized by active objects.
*/
class CWFLMSOpWrapper: public CActive
{
public: // Constructors and destructor
/**
* C++ default constructor.
*
*/
CWFLMSOpWrapper();
/**
* Destructor.
*/
~CWFLMSOpWrapper();
public: // New Functions
/**
* Starts execution of the supplied operation.
*
* @param aLmOperation operation to execute. Ownership of the operation
* is transferred to this instance.
* @param aStatus the request status to complete when execution of the
* supplied LmOperation is finished.
* @param aReportProgress ETrue if progress should be reported
* (incremental execution), EFalse otherwise.
*/
void StartOperation(CPosLmOperation* aLmOperation,
TRequestStatus& aStatus,
TBool aReportProgress = EFalse);
/**
* Returns a pointer to the wrapped CPosLmOperation object.
* This object keeps ownership of the operation.
*
* @return a pointer to a CPosLmOperation instance
*/
CPosLmOperation* LmOperationPtr();
/**
* Executes the next step of the incremental operation. Typically
* called when progress of the CPosLmOperaiotion is reported.
*
* @param aStatus the request status to complete when execution of the
* next step is finished.
*/
void ExecuteNextStep(TRequestStatus& aStatus);
/**
* Return the current progress of the CPosLmnOperation.
*
* @return a number between 0-100. 100 means that the operation is
* completed
*/
TInt Progress();
/**
* Deletes iLmOperation if we dont have an outstanding request.
*/
void ResetOperationPtr();
protected: // from CActive
/**
* Implements cancellation of an outstanding request.
*/
void DoCancel();
/**
* Handles an active objectÂ?s request completion event.
*/
void RunL();
private:
/**
* Executes the next step of the incremental operation.
*/
void ExecuteNextStep();
private: // Data
/// the wrapped CPosLmOperation that is executed
CPosLmOperation* iLmOperation;
/// contains a value between 0-1 and indicates the progress
TReal32 iProgress;
/// the req. status of the caller executing the operation
TRequestStatus* iCallerStatus;
/// indicates if progress should be reported or not
TBool iReportProgress;
};
#endif // __LANDMARKS_LM_OP_WRAPPER_H__
// End of File
| [
"[email protected]"
]
| [
[
[
1,
126
]
]
]
|
ee667b19ad04cc8b08f1baf36ab88a240041ef37 | 46e34957617ae9aa499d42e2112a5a7048af0bcc | /mar/mainwindow.cpp | 9215480aad6e3550c2812d23f11ad7d573c20b5c | []
| no_license | abelsoares/portfolio | 718e390ebc725d57fc77067e3fd168398e31dbab | 8155c7f6cb32bf0d0cc90554c436cd6135f9c8ba | refs/heads/master | 2021-01-19T08:03:16.655776 | 2011-08-26T14:03:05 | 2011-08-26T14:03:05 | 2,274,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,909 | cpp | #include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsWidget>
#include <QGraphicsLinearLayout>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include <QPushButton>
#include <QLayout>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLibrary>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <QDebug>
using namespace std;
#define MAINCONTAINERWIDTH 0.5
#define windowIniX 100
#define windowIniY 100
#define windowIniWidth 800
#define windowIniHeight 600
MainWindow::MainWindow(CvCapture *cam, QWidget *parent) :
QWidget(parent)
//,
//ui(new Ui::MainWindow)
{
this->detect = false;
/* DLL LOAD */
// QLibrary mylib("FindImage"); // DLL file name to be loaded, including path
QLibrary findImgDll;
findImgDll.setFileName("D:/mar/demo_01/demo_01/release/FindImage.dll");
bool okLoad = findImgDll.load(); // check load DLL file successful or not
bool ok = findImgDll.isLoaded(); // check is DLL file loaded or not
cout << ok << endl;
cout << okLoad << endl;
/* \DLL LOAD */
if (okLoad)
{
qDebug() << "OK load";
_findImage = (findImage) findImgDll.resolve("findImage");
}else
{
qDebug() << "KO load";
QMessageBox::information(NULL, "found", "found image");
}
/// create componentes
this->navigation = new NavigationWidget();
/// create the bookviewer widget
this->bookViewer = new BookViewerWidget();
/// connect events model
QObject::connect(this->navigation, SIGNAL(buttonClicked()),
this, SLOT(teste()));
QObject::connect(this->navigation, SIGNAL(videoButtonClicked()),
this, SLOT(startImageDetection()));//this, SLOT(loadVideoWidget()));
QObject::connect(this->navigation, SIGNAL(oglButtonClicked()),
this, SLOT(startVideoDetection()));//this, SLOT(loadOglWidget()));
QObject::connect(this->bookViewer, SIGNAL(closeBtClicked()),
this, SLOT(closeVideo()));
//ui->setupUi(this);
/// maximized app window
this->setWindowState(Qt::WindowMaximized);
/// custom app window size and position
//this->setGeometry(windowIniX, windowIniY, windowIniWidth, windowIniHeight);
/// setup the layout
QGridLayout *layout = new QGridLayout(this);
layout->setSpacing(0);
layout->setMargin(0);
/// create the camera widget container
QWidget *cameraWidgetContainer = new QWidget(this);
cameraWidgetContainer->setSizePolicy(QSizePolicy::Minimum,
QSizePolicy::Minimum);
cameraWidgetContainer->setFixedSize(400, 400);
cameraWidgetContainer->setStyleSheet("* { background-color: rgb(234, 231, 239) }");
/// create the camera widget
m_camera = cam;
m_cvwidget = new QOpenCVWidget(cameraWidgetContainer);
m_cvwidget->resize(400, 400);
startTimer(100); // 0.1-second timer
QStringList fileNames;
fileNames << videoPath;
this->videoWidget = new VideoWidget(this->bookViewer->bookView);
this->videoWidget->setGeometry(220,320,610,400);
this->videoWidget->setFiles(fileNames);
this->videoWidget->init();
this->videoWidget->hide();
this->glw = new GLWidget(this->bookViewer->bookView);
this->glw->setGeometry(220,320,610,400);
this->glw->hide();
/// create the navigation container
QWidget *navWidgetContainer = new QWidget(this);
navWidgetContainer->setSizePolicy(QSizePolicy::Minimum,
QSizePolicy::Expanding);
navWidgetContainer->setStyleSheet("* { background-color: rgb(165, 152, 186) }");
/// navigation widget
this->navigation->setParent(navWidgetContainer);
/// add widgets to the grid layout
layout->addWidget(cameraWidgetContainer, 0, 0);
//layout->addWidget(contentWidgetContainer, 0, 1, 0, 1);
layout->addWidget(this->bookViewer->bookView, 0, 1, 0, 1);
layout->addWidget(navWidgetContainer, 1, 0);
setLayout(layout);
this->resizeLayout();
}
void MainWindow::startVideoDetection()
{
this->detect = true;
}
void MainWindow::startImageDetection()
{
this->detect = true;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::loadOglWidget()
{
this->bookViewer->object->hide();
this->bookViewer->objectAnima->show();
this->resizeLayout();
if(this->videoWidget->isPlaying())
{
this->videoWidget->playpause();
}
this->videoWidget->hide();
this->glw->show();
QObject *rect = this->bookViewer->object->findChild<QObject*>("overlay");
if (rect)
rect->setProperty("opacity", "0");
QObject *overlay_bt = this->bookViewer->object->findChild<QObject*>("overlay_bt");
if (overlay_bt)
overlay_bt->setProperty("opacity", "0");
QObject *overlay_text = this->bookViewer->object->findChild<QObject*>("overlay_text");
if (overlay_text)
overlay_text->setProperty("opacity", "0");
QObject *rectAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay");
if (rectAnima)
rectAnima->setProperty("opacity", "0,9");
QObject *overlay_btAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay_bt");
if (overlay_btAnima)
overlay_btAnima->setProperty("opacity", "0,9");
QObject *overlay_textAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay_text");
if (overlay_textAnima)
overlay_textAnima->setProperty("opacity", "0,9");
}
void MainWindow::closeVideo()
{
if(this->videoWidget->isPlaying())
{
this->videoWidget->playpause();
}
this->videoWidget->hide();
this->glw->hide();
QObject *rect = this->bookViewer->object->findChild<QObject*>("overlay");
if (rect)
rect->setProperty("opacity", "0");
QObject *overlay_bt = this->bookViewer->object->findChild<QObject*>("overlay_bt");
if (overlay_bt)
overlay_bt->setProperty("opacity", "0");
QObject *overlay_text = this->bookViewer->object->findChild<QObject*>("overlay_text");
if (overlay_text)
overlay_text->setProperty("opacity", "0");
QObject *rectAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay");
if (rectAnima)
rectAnima->setProperty("opacity", "0");
QObject *overlay_btAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay_bt");
if (overlay_btAnima)
overlay_btAnima->setProperty("opacity", "0");
QObject *overlay_textAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay_text");
if (overlay_textAnima)
overlay_textAnima->setProperty("opacity", "0");
}
void MainWindow::loadVideoWidget()
{
this->bookViewer->objectAnima->hide();
this->bookViewer->object->show();
this->glw->hide();
this->videoWidget->playpause();
this->videoWidget->show();
QObject *rect = this->bookViewer->object->findChild<QObject*>("overlay");
if (rect)
rect->setProperty("opacity", "0,9");
QObject *overlay_bt = this->bookViewer->object->findChild<QObject*>("overlay_bt");
if (overlay_bt)
overlay_bt->setProperty("opacity", "0,9");
QObject *overlay_text = this->bookViewer->object->findChild<QObject*>("overlay_text");
if (overlay_text)
overlay_text->setProperty("opacity", "0,9");
QObject *rectAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay");
if (rectAnima)
rectAnima->setProperty("opacity", "0");
QObject *overlay_btAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay_bt");
if (overlay_btAnima)
overlay_btAnima->setProperty("opacity", "0");
QObject *overlay_textAnima = this->bookViewer->objectAnima->findChild<QObject*>("overlay_text");
if (overlay_textAnima)
overlay_textAnima->setProperty("opacity", "0");
}
void MainWindow::teste()
{
QMessageBox::information(NULL, "MainWindow::teste", "Invoking a MainWindow::teste");
}
void MainWindow::timerEvent(QTimerEvent*)
{
IplImage *image=cvQueryFrame(m_camera);
m_cvwidget->putImage(image);
if(this->detect)
{
if(_findImage(image,"D:/mar/demo_01/demo_01/release/capalivro2.png"))
{
this->loadVideoWidget();
this->detect = false;
}
}
}
void
MainWindow::resizeEvent(QResizeEvent *event)
{
this->resizeLayout();
}
void
MainWindow::resizeLayout()
{
int mainContainerWitdh = MAINCONTAINERWIDTH*this->width();
int cameraContainerWitdh = (1 - MAINCONTAINERWIDTH)*this->width();
}
| [
"[email protected]"
]
| [
[
[
1,
268
]
]
]
|
100d7c1c7a1b14c6ff2a4733145750d04c645ef8 | d609fb08e21c8583e5ad1453df04a70573fdd531 | /trunk/DiskMonitor/DiskMonitorDlg.cpp | 6753bae6cd5376f014704b7279c2673428640341 | []
| no_license | svn2github/openxp | d68b991301eaddb7582b8a5efd30bc40e87f2ac3 | 56db08136bcf6be6c4f199f4ac2a0850cd9c7327 | refs/heads/master | 2021-01-19T10:29:42.455818 | 2011-09-17T10:27:15 | 2011-09-17T10:27:15 | 21,675,919 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 21,516 | cpp | #include "stdafx.h"
#include "DiskMonitor.h"
#include "DiskMonitorDlg.h"
#include "HBrowseFolder.h"
#include "HSelectDlg.h"
#include "TimeTrace.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define IDM_TIMER_CHECKTIME 1121
CDiskMonitorDlg::CDiskMonitorDlg(CWnd* pParent) : CDialog(CDiskMonitorDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_hWatchThread = NULL;
m_hDirectory = INVALID_HANDLE_VALUE;
m_vecCI.clear();
}
CDiskMonitorDlg::~CDiskMonitorDlg()
{
pCheckInfo PI;
for (size_t i = 0; i < m_vecCI.size(); i++)
{
PI = NULL;
PI = m_vecCI[i];
if (NULL != PI)
delete PI;
}
m_vecCI.clear();
if (m_pszListIndex != NULL)
{
delete m_pszListIndex;
m_pszListIndex = NULL;
}
if(m_hWatchThread !=NULL)
{
::TerminateThread(m_hWatchThread, 0 );
m_hWatchThread = NULL;
}
if(m_hDirectory !=INVALID_HANDLE_VALUE)
{
CloseHandle(m_hDirectory);
m_hDirectory = INVALID_HANDLE_VALUE;
}
}
void CDiskMonitorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_INFO, m_listAllInfo);
}
BEGIN_MESSAGE_MAP(CDiskMonitorDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON_CHOICEPATH, &CDiskMonitorDlg::OnBnClickedButtonChoicepath)
ON_BN_CLICKED(IDC_BUTTON_START, &CDiskMonitorDlg::OnBnClickedButtonStart)
ON_BN_CLICKED(IDC_BUTTON_CLEARALL, &CDiskMonitorDlg::OnBnClickedButtonClearall)
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDC_BUTTON_STOP, &CDiskMonitorDlg::OnBnClickedButtonStop)
ON_WM_SYSCOMMAND()
ON_MESSAGE(WM_HOTKEY,OnHotKey)
ON_BN_CLICKED(IDC_BUTTON_OPTION, &CDiskMonitorDlg::OnBnClickedButtonOption)
ON_BN_CLICKED(IDC_CHECK_AUTOSTART, &CDiskMonitorDlg::OnBnClickedCheckAutostart)
ON_BN_CLICKED(IDC_CHECK_MINSIZE, &CDiskMonitorDlg::OnBnClickedCheckMinsize)
ON_BN_CLICKED(IDC_CHECK_AUTORUN, &CDiskMonitorDlg::OnBnClickedCheckAutorun)
ON_BN_CLICKED(IDC_CHECK_ALWAYFROUND, &CDiskMonitorDlg::OnBnClickedCheckAlwayfround)
ON_BN_CLICKED(IDC_BUTTON_EXPORT, &CDiskMonitorDlg::OnBnClickedButtonExport)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_INFO, OnDblclkList1)
ON_WM_TIMER()
END_MESSAGE_MAP()
BOOL CDiskMonitorDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
InitDlgItem();
return TRUE;
}
void CDiskMonitorDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this);
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HCURSOR CDiskMonitorDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
//监视线程
DWORD WINAPI CDiskMonitorDlg::ThreadWatchProc( LPVOID lParam )
{
CDiskMonitorDlg *obj = (CDiskMonitorDlg*)lParam;
obj->m_hDirectory = CreateFile( //打开目录,得到目录的句柄
obj->m_strWatchedDir,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL
);
if(obj->m_hDirectory ==INVALID_HANDLE_VALUE)
return false;
char buf[(sizeof(FILE_NOTIFY_INFORMATION)+MAX_PATH)*2];
FILE_NOTIFY_INFORMATION* pNotify=(FILE_NOTIFY_INFORMATION*)buf;
DWORD dwBytesReturned;
while(true)
{
if(::ReadDirectoryChangesW(obj->m_hDirectory,
pNotify,
sizeof(buf),
true,
FILE_NOTIFY_CHANGE_FILE_NAME|
FILE_NOTIFY_CHANGE_DIR_NAME|
FILE_NOTIFY_CHANGE_ATTRIBUTES|
FILE_NOTIFY_CHANGE_SIZE|
FILE_NOTIFY_CHANGE_LAST_WRITE|
FILE_NOTIFY_CHANGE_LAST_ACCESS|
FILE_NOTIFY_CHANGE_CREATION|
FILE_NOTIFY_CHANGE_SECURITY,
&dwBytesReturned,
NULL,
NULL))
{
char tmp[MAX_PATH], str1[MAX_PATH], str2[MAX_PATH];
memset(tmp, 0, sizeof(tmp));
WideCharToMultiByte(CP_ACP,0,pNotify->FileName,pNotify->FileNameLength/2,tmp,99,NULL,NULL);
strcpy(str1, tmp);
if(pNotify->NextEntryOffset != 0)
{
PFILE_NOTIFY_INFORMATION p = (PFILE_NOTIFY_INFORMATION)((char*)pNotify+pNotify->NextEntryOffset);
memset(tmp, 0, sizeof(tmp));
WideCharToMultiByte(CP_ACP,0,p->FileName,p->FileNameLength/2,tmp,99,NULL,NULL);
strcpy(str2, tmp);
}
switch(pNotify->Action)
{
case FILE_ACTION_ADDED:
if(obj->m_bAddNew)
{
CTime tt = CTime::GetCurrentTime();
CString strTT;
strTT.Format(_T("%d:%d:%d"),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
obj->m_listAllInfo.InsertItem(0,obj->m_pszListIndex);
obj->m_listAllInfo.SetItemText(0,2,_T("添加了新文件"));
obj->m_listAllInfo.SetItemText(0,3,str1);
obj->m_listAllInfo.SetItemText(0,1,strTT);
pCheckInfo PI = NULL;
PI = new tagCheckInfo();
strcpy(PI->szIndex,obj->m_pszListIndex);
strcpy(PI->szTime,strTT);
strcpy(PI->szType,_T("添加了新文件"));
strcpy(PI->szDetail,str1);
obj->m_vecCI.push_back(PI);
}
break;
case FILE_ACTION_REMOVED:
if(obj->m_bDelete)
{
CTime tt=CTime::GetCurrentTime();
CString strTT;
strTT.Format(_T("%d:%d:%d"),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
obj->m_listAllInfo.InsertItem(0,obj->m_pszListIndex);
obj->m_listAllInfo.SetItemText(0,2,_T("删除了文件"));
obj->m_listAllInfo.SetItemText(0,3,str1);
obj->m_listAllInfo.SetItemText(0,1,strTT);
pCheckInfo PI = NULL;
PI = new tagCheckInfo();
strcpy(PI->szIndex,obj->m_pszListIndex);
strcpy(PI->szTime,strTT);
strcpy(PI->szType,_T("删除了文件"));
strcpy(PI->szDetail,str1);
obj->m_vecCI.push_back(PI);
}
break;
case FILE_ACTION_RENAMED_NEW_NAME:
if(obj->m_bRename)
{
CTime tt = CTime::GetCurrentTime();
CString strTT;
strTT.Format(_T("%d:%d:%d"),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
obj->m_listAllInfo.InsertItem(0,obj->m_pszListIndex);
obj->m_listAllInfo.SetItemText(0,2,_T("重命名了文件"));
strcat(str1,_T("->"));
obj->m_listAllInfo.SetItemText(0,3,strcat(str1,str2));
obj->m_listAllInfo.SetItemText(0,1,strTT);
pCheckInfo PI = NULL;
PI = new tagCheckInfo();
strcpy(PI->szIndex,obj->m_pszListIndex);
strcpy(PI->szTime,strTT);
strcpy(PI->szType,_T("重命名了文件"));
strcpy(PI->szDetail,strcat(str1,str2));
obj->m_vecCI.push_back(PI);
}
break;
case FILE_ACTION_RENAMED_OLD_NAME:
if(obj->m_bRename)
{
CTime tt=CTime::GetCurrentTime();
CString strTT;
strTT.Format(_T("%d:%d:%d"),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
obj->m_listAllInfo.InsertItem(0,obj->m_pszListIndex);
obj->m_listAllInfo.SetItemText(0,2,_T("重命名了文件"));
strcat(str1,_T(" 改名为 "));
obj->m_listAllInfo.SetItemText(0,3,strcat(str1,str2));
obj->m_listAllInfo.SetItemText(0,1,strTT);
pCheckInfo PI = NULL;
PI = new tagCheckInfo();
strcpy(PI->szIndex,obj->m_pszListIndex);
strcpy(PI->szTime,strTT);
strcpy(PI->szType,_T("重命名了文件"));
strcpy(PI->szDetail,strcat(str1,str2));
obj->m_vecCI.push_back(PI);
}
break;
case FILE_ACTION_MODIFIED:
if(obj->m_bModify)
{
CTime tt = CTime::GetCurrentTime();
CString strTT;
strTT.Format(_T("%d:%d:%d"),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
obj->m_listAllInfo.InsertItem(0,obj->m_pszListIndex);
obj->m_listAllInfo.SetItemText(0,2,_T("修改了文件"));
obj->m_listAllInfo.SetItemText(0,3,str1);
obj->m_listAllInfo.SetItemText(0,1,strTT);
pCheckInfo PI = NULL;
PI = new tagCheckInfo();
strcpy(PI->szIndex,obj->m_pszListIndex);
strcpy(PI->szTime,strTT);
strcpy(PI->szType,_T("修改了文件"));
strcpy(PI->szDetail,str1);
obj->m_vecCI.push_back(PI);
}
break;
default:
if(obj->m_bOther)
{
CTime tt = CTime::GetCurrentTime();
CString strTT;
strTT.Format(_T("%d:%d:%d"),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
obj->m_listAllInfo.InsertItem(0,obj->m_pszListIndex);
obj->m_listAllInfo.SetItemText(0,2,_T("未知变化"));
obj->m_listAllInfo.SetItemText(0,3,_T(""));
obj->m_listAllInfo.SetItemText(0,1,strTT);
pCheckInfo PI = NULL;
PI = new tagCheckInfo();
strcpy(PI->szIndex,obj->m_pszListIndex);
strcpy(PI->szTime,strTT);
strcpy(PI->szType,_T("未知变化"));
strcpy(PI->szDetail,_T(""));
obj->m_vecCI.push_back(PI);
}
break;
}
obj->m_nListCount++;
itoa(obj->m_nListCount,obj->m_pszListIndex,10);
}
else
break;
}
obj->m_nListCount = 1;
return 0;
}
//初始化对话框元素
void CDiskMonitorDlg::InitDlgItem()
{
//添加状态栏
m_wndStatusBar.Create(WS_CHILD|WS_VISIBLE|CCS_BOTTOM,CRect(0,0,0,0),this,10000);
int strPartDim[3]={220,350,-1};
m_wndStatusBar.SetParts(3,strPartDim);//设置状态栏为4部分
m_wndStatusBar.SetText("ESC:隐藏窗体 ALT+W:隐藏/显示窗体",0,0);
m_wndStatusBar.SetText("读取时间中...",1,0);
m_wndStatusBar.SetText("选项中可设置当前监视项目 (小兴)",2,0);
SetTimer(IDM_TIMER_CHECKTIME,1000,NULL);
m_listAllInfo.ModifyStyle(LVS_TYPEMASK,LVS_REPORT);
m_listAllInfo.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_FLATSB|LVS_EX_TWOCLICKACTIVATE |LVS_EX_GRIDLINES);
m_listAllInfo.InsertColumn(0,_T("数量"),LVCFMT_LEFT,40);
m_listAllInfo.InsertColumn(1,_T("时间"),LVCFMT_LEFT,80);
m_listAllInfo.InsertColumn(2,_T("类型"),LVCFMT_LEFT,100);
m_listAllInfo.InsertColumn(3,_T("变化的内容"),LVCFMT_LEFT,500);
LOGFONT lf;
::ZeroMemory(&lf,sizeof(lf));
lf.lfHeight = 90;
lf.lfWeight = FW_NORMAL;
lf.lfItalic = false;
::lstrcpy(lf.lfFaceName,_T("Verdana"));
m_hFont.CreatePointFontIndirect(&lf);
GetDlgItem(IDC_STATIC_PATH)->SetFont(&m_hFont);
GetDlgItem(IDC_BUTTON_STOP)->EnableWindow(FALSE);
//载入ini配置文件
m_bAddNew = (::GetPrivateProfileInt("Selections","AddNew",0,".\\Settings.ini")==0 ?false:true);
m_bDelete = (::GetPrivateProfileInt("Selections","Delete",0,".\\Settings.ini")==0 ?false:true);
m_bRename = (::GetPrivateProfileInt("Selections","Rename",0,".\\Settings.ini")==0 ?false:true);
m_bModify = (::GetPrivateProfileInt("Selections","Modify",0,".\\Settings.ini")==0 ?false:true);
m_bOther = (::GetPrivateProfileInt("Selections","Other",0,".\\Settings.ini")==0 ?false:true);
char buf[MAX_PATH];
::GetPrivateProfileString("Settings","WatchDir","",buf,MAX_PATH,".\\Settings.ini");
m_strWatchedDir.Format("%s",buf);
CString strBuffer = _T("你选择了监视 ");
m_strWatchedDir.FreeExtra();
strBuffer += m_strWatchedDir;
GetDlgItem(IDC_STATIC_PATH)->SetWindowText(strBuffer);
CButton *p = NULL;
m_bAlwaysOnTop = (::GetPrivateProfileInt("Settings","AlwaysOnTop",0,".\\Settings.ini")==0 ?false:true);
p = (CButton*)GetDlgItem(IDC_CHECK_ALWAYFROUND);
p->SetCheck(m_bAlwaysOnTop);
if (m_bAlwaysOnTop)
SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | WS_EX_TOPMOST);
m_bAutoRun = (::GetPrivateProfileInt("Settings","AutoRun",0,".\\Settings.ini")==0 ?false:true);
p = (CButton*)GetDlgItem(IDC_CHECK_AUTORUN);
p->SetCheck(m_bAutoRun);
if (m_bAutoRun)
{
m_bAutoRun = false;
OnBnClickedCheckAutorun();
}
m_bMinimized = (::GetPrivateProfileInt("Settings","Minimized",0,".\\Settings.ini")==0 ?false:true);
p = (CButton*)GetDlgItem(IDC_CHECK_MINSIZE);
p->SetCheck(m_bMinimized);
if (m_bMinimized)
PostMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0);
m_bAutoStart = (::GetPrivateProfileInt("Settings","AutoStart",0,".\\Settings.ini")==0 ?false:true);
p = (CButton*)GetDlgItem(IDC_CHECK_AUTOSTART);
p->SetCheck(m_bAutoStart);
if (m_bAutoStart && !m_strWatchedDir.IsEmpty())
OnBnClickedButtonStart();
m_nListCount = 1;
m_pszListIndex = new TCHAR[MAX_PATH];
itoa(m_nListCount,m_pszListIndex,10);
::RegisterHotKey(m_hWnd,1121,MOD_ALT,'W');
}
//选择监视目录
void CDiskMonitorDlg::OnBnClickedButtonChoicepath()
{
HBrowseFolder Dlg;
if(Dlg.DoModal(this,NULL) == IDOK)
{
m_strWatchedDir.Format("%s",Dlg.GetDirPath());
CString strBuffer = _T("你选择了监视 ");
GetDlgItem(IDC_STATIC_PATH)->SetWindowText(strBuffer+m_strWatchedDir);
::WritePrivateProfileString("Settings","WatchDir",m_strWatchedDir,".\\Settings.ini");
}
}
//开始监视按钮
void CDiskMonitorDlg::OnBnClickedButtonStart()
{
if (m_strWatchedDir.IsEmpty())
{
AfxMessageBox("请选择监视目录!");
return;
}
this->StartWatch(m_strWatchedDir);
GetDlgItem(IDC_BUTTON_STOP)->EnableWindow(true);
GetDlgItem(IDC_BUTTON_START)->EnableWindow(false);
GetDlgItem(IDC_BUTTON_CHOICEPATH)->EnableWindow(false);
CString strBuffer = _T("正在监视... ");
GetDlgItem(IDC_STATIC_PATH)->SetWindowText(strBuffer+m_strWatchedDir);
}
//开始监视线程
BOOL CDiskMonitorDlg::StartWatch( CString strPath )
{
m_strWatchedDir = strPath;
DWORD ThreadId;
m_hWatchThread = ::CreateThread(NULL,0,ThreadWatchProc,this,0,&ThreadId);
return (NULL!=m_hWatchThread);
}
//停止监视
void CDiskMonitorDlg::OnBnClickedButtonStop()
{
CString strBuffer = _T("停止了监视 ");
GetDlgItem(IDC_STATIC_PATH)->SetWindowText(strBuffer+m_strWatchedDir);
if(m_hWatchThread != NULL)
{
::TerminateThread(m_hWatchThread,0);
m_hWatchThread = NULL;
}
if(m_hDirectory != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hDirectory);
m_hDirectory = INVALID_HANDLE_VALUE;
}
GetDlgItem(IDC_BUTTON_STOP)->EnableWindow(TRUE);
GetDlgItem(IDC_BUTTON_START)->EnableWindow(TRUE);
GetDlgItem(IDC_BUTTON_CHOICEPATH)->EnableWindow(TRUE);
}
//清除列表控件内容
void CDiskMonitorDlg::OnBnClickedButtonClearall()
{
m_listAllInfo.DeleteAllItems();
m_nListCount = 1;
pCheckInfo PI;
for (size_t i = 0; i < m_vecCI.size(); i++)
{
PI = NULL;
PI = m_vecCI[i];
if (NULL != PI)
delete PI;
}
m_vecCI.clear();
}
//控件颜色
HBRUSH CDiskMonitorDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if(pWnd->GetDlgCtrlID() == IDC_STATIC_PATH)
pDC->SetTextColor(RGB(0,0,255));
return hbr;
}
//消息解析
BOOL CDiskMonitorDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN)
{
switch (pMsg->wParam)
{
case VK_ESCAPE:
ShowWindow(SW_HIDE);
return true;
case VK_RETURN:
return true;
default: break;
}
}
return CDialog::PreTranslateMessage(pMsg);
}
//系统消息解析
void CDiskMonitorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if(nID == SC_MINIMIZE)
{
ShowWindow(SW_HIDE);
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
//热键解析
LRESULT CDiskMonitorDlg::OnHotKey( WPARAM wParam,LPARAM lParam )
{
if(wParam == 1121)
{
if(IsWindowVisible())
ShowWindow(SW_HIDE);
else
ShowWindow(SW_SHOWNORMAL);
}
return 1;
}
//选项设置
void CDiskMonitorDlg::OnBnClickedButtonOption()
{
HSelectDlg sel;
if(sel.DoModal() == IDOK)
{
this->m_bAddNew = sel.m_bAddNew;
this->m_bDelete = sel.m_bDel;
this->m_bModify = sel.m_bModify;
this->m_bRename = sel.m_bRename;
this->m_bOther = sel.m_bOther;
::WritePrivateProfileString("Selections","Add",sel.m_bAddNew? "1":"0",".\\Settings.ini");
::WritePrivateProfileString("Selections","Delete",sel.m_bDel? "1":"0",".\\Settings.ini");
::WritePrivateProfileString("Selections","Modify",sel.m_bModify? "1":"0",".\\Settings.ini");
::WritePrivateProfileString("Selections","Rename",sel.m_bRename? "1":"0",".\\Settings.ini");
::WritePrivateProfileString("Selections","Other",sel.m_bOther? "1":"0",".\\Settings.ini");
}
}
//导出到文件
void CDiskMonitorDlg::OnBnClickedButtonExport()
{
pCheckInfo PI;
for (size_t i = 0; i < m_vecCI.size(); i++)
{
PI = NULL;
PI = m_vecCI[i];
if (NULL != PI)
{
TCHAR szInfo[2048] = {0};
sprintf(szInfo,"%s --> %s\r\n",PI->szType,PI->szDetail);
if (strcmp(PI->szType,"添加了新文件") == 0)
{
HTraceHtml(HTML_COLOR_NORMAL,szInfo);
}
else if (strcmp(PI->szType,"删除了文件") == 0)
{
HTraceHtml(HTML_COLOR_ERROR,szInfo);
}
else if (strcmp(PI->szType,"重命名了文件") == 0)
{
HTraceHtml(HTML_COLOR_WARNING,szInfo);
}
else if (strcmp(PI->szType,"修改了文件") == 0)
{
HTraceHtml(HTML_COLOR_WARNING,szInfo);
}
else if (strcmp(PI->szType,"未知变化") == 0)
{
HTraceHtml(HTML_COLOR_WARNING,szInfo);
}
delete PI;
}
}
m_vecCI.clear();
int nErrorCode = ::MessageBox(this->GetSafeHwnd(),_T("导出成功,是否清除全部信息!"),_T("系统提示"),MB_YESNO);
if (nErrorCode == 6)
OnBnClickedButtonClearall();
nErrorCode = ::MessageBox(this->GetSafeHwnd(),_T("清除成功,是否查看导出文件!"),_T("系统提示"),MB_YESNO);
if (nErrorCode == 6)
{
TCHAR exeFullPath[MAX_PATH+1];
GetModuleFileName(NULL,exeFullPath,MAX_PATH);
(_tcsrchr(exeFullPath, _T('\\')))[1] = 0;//删除文件名,只获得路径
::ShellExecute(NULL,"open",exeFullPath,NULL,NULL,SW_SHOW);
}
}
//设置程序启动时,自动开始检测
void CDiskMonitorDlg::OnBnClickedCheckAutostart()
{
m_bAutoStart = !m_bAutoStart;
::WritePrivateProfileString("Settings","AutoStart",m_bAutoStart? "1":"0",".\\Settings.ini");
}
//设置程序启动时,自动隐藏
void CDiskMonitorDlg::OnBnClickedCheckMinsize()
{
m_bMinimized = !m_bMinimized;
::WritePrivateProfileString("Settings","Minimized",m_bMinimized? "1":"0",".\\Settings.ini");
}
//设置程序开机自启动
void CDiskMonitorDlg::OnBnClickedCheckAutorun()
{
m_bAutoRun = !m_bAutoRun;
const TCHAR gcszAutoRunKey[]= _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
const TCHAR gcszWindowClass[] = _T("LJSoft");
HKEY hKey;
LONG lRet, lRet2;
DWORD dwLength, dwDataType;
TCHAR szItemValue[MAX_PATH], szPrevValue[MAX_PATH];
TCHAR szBuffer[MAX_PATH];
GetModuleFileName(NULL, szItemValue, MAX_PATH);
lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,gcszAutoRunKey,0,KEY_READ|KEY_WRITE,&hKey);
if(lRet != ERROR_SUCCESS) return;
dwLength = sizeof(szBuffer);
lRet = RegQueryValueEx(hKey,gcszWindowClass,NULL,&dwDataType,(LPBYTE)szBuffer,&dwLength);
if(m_bAutoRun)//添加
{
::WritePrivateProfileString("Settings","AutoRun",m_bAutoRun? "1":"0",".\\Settings.ini");
if(lRet != ERROR_SUCCESS)// AutoRun项目不存在
{
lRet2 = RegSetValueEx(hKey,gcszWindowClass,0,REG_SZ,(LPBYTE)szItemValue,strlen(szItemValue));
}
else//存在, 比较二者是否相同
{
dwLength = sizeof(szPrevValue);
lRet2 = RegQueryValueEx(hKey, gcszWindowClass,0, &dwDataType,(LPBYTE)szPrevValue, &dwLength);
if(lstrcmp(szItemValue, szPrevValue))// 不相同则替换
{
lRet2 = RegDeleteValue( hKey, gcszWindowClass );
lRet2 = RegSetValueEx( hKey, gcszWindowClass,0, REG_SZ,(LPBYTE)szItemValue, strlen( szItemValue ) );
}
}
}
else // 删除
{
if(lRet == ERROR_SUCCESS)
lRet2 = RegDeleteValue(hKey,gcszWindowClass); // AutoRun项目已存在则删除
::WritePrivateProfileString("Settings","AutoRun",m_bAutoRun? "1":"0",".\\Settings.ini");
}
RegCloseKey(hKey);
}
//设置窗体Z系位置
void CDiskMonitorDlg::OnBnClickedCheckAlwayfround()
{
m_bAlwaysOnTop = !m_bAlwaysOnTop;
if (m_bAlwaysOnTop)
{
SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | WS_EX_TOPMOST);
::WritePrivateProfileString("Settings","AlwaysOnTop",m_bAlwaysOnTop? "1":"0",".\\Settings.ini");
}
else
{
::SetWindowPos(GetSafeHwnd(), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
::WritePrivateProfileString("Settings","AlwaysOnTop",m_bAlwaysOnTop? "1":"0",".\\Settings.ini");
}
}
//销毁窗体
BOOL CDiskMonitorDlg::DestroyWindow()
{
::UnregisterHotKey(m_hWnd,1121);
return CDialog::DestroyWindow();
}
//系统关闭按钮
void CDiskMonitorDlg::OnCancel()
{
if (!::IsWindowEnabled(GetDlgItem(IDC_BUTTON_START)->GetSafeHwnd()))
{
int nErrorCode = ::MessageBox(this->GetSafeHwnd(),_T("侦测正在运行中,是否强制退出?"),_T("系统提示"),MB_YESNO);
if (nErrorCode == 7)
return;
}
CDialog::OnCancel();
}
//双击列表控件
void CDiskMonitorDlg::OnDblclkList1(NMHDR* pNMHDR, LRESULT* pResult)
{
int nIndex = m_listAllInfo.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED);
if(nIndex == -1)
return;
TCHAR buf[MAX_PATH];
m_listAllInfo.GetItemText(nIndex,3,buf,MAX_PATH);
CString str;
str = this->m_strWatchedDir+"\\"+buf;
::ShellExecute(NULL,"open",str,NULL,NULL,SW_SHOW);
*pResult = 0;
}
//定时器
void CDiskMonitorDlg::OnTimer(UINT_PTR nIDEvent)
{
if (nIDEvent == IDM_TIMER_CHECKTIME)
{
CTime time = CTime::GetCurrentTime();
CString date = time.Format("%Y-%m-%d %H:%M:%S");
m_wndStatusBar.SetText(date,1,0);
}
CDialog::OnTimer(nIDEvent);
}
| [
"[email protected]@f92b348d-55a1-4afa-8193-148a6675784b"
]
| [
[
[
1,
719
]
]
]
|
1214a61bb1a436068bc0148eda6001c837560c0c | 8ffc2ad8cf32ffd9ba2974ee9bb4ae36de90a860 | /SIFT_DEMO/src/sift.cpp | e592a166195658599553e509ce7c81d556eb3961 | []
| no_license | mhlee1215/sift-custom | ca40895d3b3ba6e3e2c6b45947e21a4e07a5270e | ec3910e172eae4bafa6e21952e058f6875362569 | refs/heads/master | 2016-09-06T10:54:10.910652 | 2010-06-10T08:52:48 | 2010-06-10T08:52:48 | 33,061,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,989 | cpp | /*
Functions for detecting SIFT image features.
For more information, refer to:
Lowe, D. Distinctive image features from scale-invariant keypoints.
<EM>International Journal of Computer Vision, 60</EM>, 2 (2004),
pp.91--110.
Copyright (C) 2006 Rob Hess <[email protected]>
Note: The SIFT algorithm is patented in the United States and cannot be
used in commercial products without a license from the University of
British Columbia. For more information, refer to the file LICENSE.ubc
that accompanied this distribution.
@version 1.1.1-20070913
*/
#include "sift.h"
#include "imgfeatures.h"
#include "utils.h"
#include <cxcore.h>
#include <cv.h>
/************************* Local Function Prototypes *************************/
IplImage* create_init_img( IplImage*, int, double );
IplImage* convert_to_gray32( IplImage* );
IplImage*** build_gauss_pyr( IplImage*, int, int, double );
IplImage* downsample( IplImage* );
IplImage*** build_dog_pyr( IplImage***, int, int );
CvSeq* scale_space_extrema( IplImage***, int, int, double, int, CvMemStorage*);
int is_extremum( IplImage***, int, int, int, int );
struct feature* interp_extremum( IplImage***, int, int, int, int, int, double);
void interp_step( IplImage***, int, int, int, int, double*, double*, double* );
CvMat* deriv_3D( IplImage***, int, int, int, int );
CvMat* hessian_3D( IplImage***, int, int, int, int );
double interp_contr( IplImage***, int, int, int, int, double, double, double );
struct feature* new_feature( void );
int is_too_edge_like( IplImage*, int, int, int );
void calc_feature_scales( CvSeq*, double, int );
void adjust_for_img_dbl( CvSeq* );
void calc_feature_oris( CvSeq*, IplImage*** );
double* ori_hist( IplImage*, int, int, int, int, double );
int calc_grad_mag_ori( IplImage*, int, int, double*, double* );
void smooth_ori_hist( double*, int );
double dominant_ori( double*, int );
void add_good_ori_features( CvSeq*, double*, int, double, struct feature* );
struct feature* clone_feature( struct feature* );
void compute_descriptors( CvSeq*, IplImage***, int, int );
double*** descr_hist( IplImage*, int, int, double, double, int, int );
void interp_hist_entry( double***, double, double, double, double, int, int);
void hist_to_descr( double***, int, int, struct feature* );
void normalize_descr( struct feature* );
int feature_cmp( void*, void*, void* );
void release_descr_hist( double****, int );
void release_pyr( IplImage****, int, int );
/*********************** Functions prototyped in sift.h **********************/
/**
Finds SIFT features in an image using default parameter values. All
detected features are stored in the array pointed to by \a feat.
@param img the image in which to detect features
@param feat a pointer to an array in which to store detected features
@return Returns the number of features stored in \a feat or -1 on failure
@see _sift_features()
*/
int sift_features( IplImage* img, struct feature** feat )
{
return _sift_features( img, feat, SIFT_INTVLS, SIFT_SIGMA, SIFT_CONTR_THR,
SIFT_CURV_THR, SIFT_IMG_DBL, SIFT_DESCR_WIDTH,
SIFT_DESCR_HIST_BINS );
}
/**
Finds SIFT features in an image using user-specified parameter values. All
detected features are stored in the array pointed to by \a feat.
@param img the image in which to detect features
@param fea a pointer to an array in which to store detected features
@param intvls the number of intervals sampled per octave of scale space
@param sigma the amount of Gaussian smoothing applied to each image level
before building the scale space representation for an octave
@param cont_thr a threshold on the value of the scale space function
\f$\left|D(\hat{x})\right|\f$, where \f$\hat{x}\f$ is a vector specifying
feature location and scale, used to reject unstable features; assumes
pixel values in the range [0, 1]
@param curv_thr threshold on a feature's ratio of principle curvatures
used to reject features that are too edge-like
@param img_dbl should be 1 if image doubling prior to scale space
construction is desired or 0 if not
@param descr_width the width, \f$n\f$, of the \f$n \times n\f$ array of
orientation histograms used to compute a feature's descriptor
@param descr_hist_bins the number of orientations in each of the
histograms in the array used to compute a feature's descriptor
@return Returns the number of keypoints stored in \a feat or -1 on failure
@see sift_keypoints()
*/
int _sift_features( IplImage* img, struct feature** feat, int intvls,
double sigma, double contr_thr, int curv_thr,
int img_dbl, int descr_width, int descr_hist_bins )
{
IplImage* init_img;
IplImage*** gauss_pyr, *** dog_pyr;
CvMemStorage* storage;
CvSeq* features;
int octvs, i, n = 0;
/* check arguments */
if( ! img )
fatal_error( "NULL pointer error, %s, line %d", __FILE__, __LINE__ );
if( ! feat )
fatal_error( "NULL pointer error, %s, line %d", __FILE__, __LINE__ );
/* build scale space pyramid; smallest dimension of top level is ~4 pixels */
init_img = create_init_img( img, img_dbl, sigma );
octvs = log( MIN( init_img->width, init_img->height ) * 1.0 ) / log(2.0) - 2;
gauss_pyr = build_gauss_pyr( init_img, octvs, intvls, sigma );
dog_pyr = build_dog_pyr( gauss_pyr, octvs, intvls );
storage = cvCreateMemStorage( 0 );
features = scale_space_extrema( dog_pyr, octvs, intvls, contr_thr,
curv_thr, storage );
calc_feature_scales( features, sigma, intvls );
if( img_dbl )
adjust_for_img_dbl( features );
calc_feature_oris( features, gauss_pyr );
compute_descriptors( features, gauss_pyr, descr_width, descr_hist_bins );
/* sort features by decreasing scale and move from CvSeq to array */
cvSeqSort( features, (CvCmpFunc)feature_cmp, NULL );
n = features->total;
*feat = (feature *)calloc( n, sizeof(feature) );
*feat = (feature *)cvCvtSeqToArray( features, *feat, CV_WHOLE_SEQ );
for( i = 0; i < n; i++ )
{
free( (*feat)[i].feature_data );
(*feat)[i].feature_data = NULL;
}
cvReleaseMemStorage( &storage );
cvReleaseImage( &init_img );
release_pyr( &gauss_pyr, octvs, intvls + 3 );
release_pyr( &dog_pyr, octvs, intvls + 2 );
return n;
}
/************************ Functions prototyped here **************************/
/*
Converts an image to 8-bit grayscale and Gaussian-smooths it. The image is
optionally doubled in size prior to smoothing.
@param img input image
@param img_dbl if true, image is doubled in size prior to smoothing
@param sigma total std of Gaussian smoothing
*/
IplImage* create_init_img( IplImage* img, int img_dbl, double sigma )
{
IplImage* gray, * dbl;
float sig_diff;
gray = convert_to_gray32( img );
if( img_dbl )
{
sig_diff = sqrt( sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA * 4 );
dbl = cvCreateImage( cvSize( img->width*2, img->height*2 ),
IPL_DEPTH_32F, 1 );
cvResize( gray, dbl, CV_INTER_CUBIC );
cvSmooth( dbl, dbl, CV_GAUSSIAN, 0, 0, sig_diff, sig_diff );
cvReleaseImage( &gray );
return dbl;
}
else
{
sig_diff = sqrt( sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA );
cvSmooth( gray, gray, CV_GAUSSIAN, 0, 0, sig_diff, sig_diff );
return gray;
}
}
/*
Converts an image to 32-bit grayscale
@param img a 3-channel 8-bit color (BGR) or 8-bit gray image
@return Returns a 32-bit grayscale image
*/
IplImage* convert_to_gray32( IplImage* img )
{
IplImage* gray8, * gray32;
gray8 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
gray32 = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 );
if( img->nChannels == 1 )
gray8 = (IplImage *)cvClone( img );
else
cvCvtColor( img, gray8, CV_BGR2GRAY );
cvConvertScale( gray8, gray32, 1.0 / 255.0, 0 );
cvReleaseImage( &gray8 );
return gray32;
}
/*
Builds Gaussian scale space pyramid from an image
@param base base image of the pyramid
@param octvs number of octaves of scale space
@param intvls number of intervals per octave
@param sigma amount of Gaussian smoothing per octave
@return Returns a Gaussian scale space pyramid as an octvs x (intvls + 3) array
*/
IplImage*** build_gauss_pyr( IplImage* base, int octvs,
int intvls, double sigma )
{
IplImage*** gauss_pyr;
double* sig = (double *)calloc( intvls + 3, sizeof(double));
double sig_total, sig_prev, k;
int i, o;
gauss_pyr = ( IplImage *** )calloc( octvs, sizeof( IplImage** ) );
for( i = 0; i < octvs; i++ )
gauss_pyr[i] = ( IplImage ** )calloc( intvls + 3, sizeof( IplImage* ) );
/*
precompute Gaussian sigmas using the following formula:
\sigma_{total}^2 = \sigma_{i}^2 + \sigma_{i-1}^2
*/
sig[0] = sigma;
k = pow( 2.0, 1.0 / intvls );
for( i = 1; i < intvls + 3; i++ )
{
sig_prev = pow( k, i - 1 ) * sigma;
sig_total = sig_prev * k;
sig[i] = sqrt( sig_total * sig_total - sig_prev * sig_prev );
}
for( o = 0; o < octvs; o++ )
for( i = 0; i < intvls + 3; i++ )
{
if( o == 0 && i == 0 )
gauss_pyr[o][i] = cvCloneImage(base);
/* base of new octvave is halved image from end of previous octave */
else if( i == 0 )
gauss_pyr[o][i] = downsample( gauss_pyr[o-1][intvls] );
/* blur the current octave's last image to create the next one */
else
{
gauss_pyr[o][i] = cvCreateImage( cvGetSize(gauss_pyr[o][i-1]),
IPL_DEPTH_32F, 1 );
cvSmooth( gauss_pyr[o][i-1], gauss_pyr[o][i],
CV_GAUSSIAN, 0, 0, sig[i], sig[i] );
}
}
free( sig );
return gauss_pyr;
}
/*
Downsamples an image to a quarter of its size (half in each dimension)
using nearest-neighbor interpolation
@param img an image
@return Returns an image whose dimensions are half those of img
*/
IplImage* downsample( IplImage* img )
{
IplImage* smaller = cvCreateImage( cvSize(img->width / 2, img->height / 2),
img->depth, img->nChannels );
cvResize( img, smaller, CV_INTER_NN );
return smaller;
}
/*
Builds a difference of Gaussians scale space pyramid by subtracting adjacent
intervals of a Gaussian pyramid
@param gauss_pyr Gaussian scale-space pyramid
@param octvs number of octaves of scale space
@param intvls number of intervals per octave
@return Returns a difference of Gaussians scale space pyramid as an
octvs x (intvls + 2) array
*/
IplImage*** build_dog_pyr( IplImage*** gauss_pyr, int octvs, int intvls )
{
IplImage*** dog_pyr;
int i, o;
dog_pyr = ( IplImage *** )calloc( octvs, sizeof( IplImage** ) );
for( i = 0; i < octvs; i++ )
dog_pyr[i] = ( IplImage ** )calloc( intvls + 2, sizeof(IplImage*) );
for( o = 0; o < octvs; o++ )
for( i = 0; i < intvls + 2; i++ )
{
dog_pyr[o][i] = cvCreateImage( cvGetSize(gauss_pyr[o][i]),
IPL_DEPTH_32F, 1 );
cvSub( gauss_pyr[o][i+1], gauss_pyr[o][i], dog_pyr[o][i], NULL );
}
return dog_pyr;
}
/*
Detects features at extrema in DoG scale space. Bad features are discarded
based on contrast and ratio of principal curvatures.
@param dog_pyr DoG scale space pyramid
@param octvs octaves of scale space represented by dog_pyr
@param intvls intervals per octave
@param contr_thr low threshold on feature contrast
@param curv_thr high threshold on feature ratio of principal curvatures
@param storage memory storage in which to store detected features
@return Returns an array of detected features whose scales, orientations,
and descriptors are yet to be determined.
*/
CvSeq* scale_space_extrema( IplImage*** dog_pyr, int octvs, int intvls,
double contr_thr, int curv_thr,
CvMemStorage* storage )
{
CvSeq* features;
double prelim_contr_thr = 0.5 * contr_thr / intvls;
struct feature* feat;
struct detection_data* ddata;
int o, i, r, c;
features = cvCreateSeq( 0, sizeof(CvSeq), sizeof(struct feature), storage );
for( o = 0; o < octvs; o++ )
for( i = 1; i <= intvls; i++ )
for(r = SIFT_IMG_BORDER; r < dog_pyr[o][0]->height-SIFT_IMG_BORDER; r++)
for(c = SIFT_IMG_BORDER; c < dog_pyr[o][0]->width-SIFT_IMG_BORDER; c++)
/* perform preliminary check on contrast */
if( ABS( pixval32f( dog_pyr[o][i], r, c ) ) > prelim_contr_thr )
if( is_extremum( dog_pyr, o, i, r, c ) )
{
feat = interp_extremum(dog_pyr, o, i, r, c, intvls, contr_thr);
if( feat )
{
ddata = feat_detection_data( feat );
if( ! is_too_edge_like( dog_pyr[ddata->octv][ddata->intvl],
ddata->r, ddata->c, curv_thr ) )
{
cvSeqPush( features, feat );
}
else
free( ddata );
free( feat );
}
}
return features;
}
/*
Determines whether a pixel is a scale-space extremum by comparing it to it's
3x3x3 pixel neighborhood.
@param dog_pyr DoG scale space pyramid
@param octv pixel's scale space octave
@param intvl pixel's within-octave interval
@param r pixel's image row
@param c pixel's image col
@return Returns 1 if the specified pixel is an extremum (max or min) among
it's 3x3x3 pixel neighborhood.
*/
int is_extremum( IplImage*** dog_pyr, int octv, int intvl, int r, int c )
{
float val = pixval32f( dog_pyr[octv][intvl], r, c );
int i, j, k;
/* check for maximum */
if( val > 0 )
{
for( i = -1; i <= 1; i++ )
for( j = -1; j <= 1; j++ )
for( k = -1; k <= 1; k++ )
if( val < pixval32f( dog_pyr[octv][intvl+i], r + j, c + k ) )
return 0;
}
/* check for minimum */
else
{
for( i = -1; i <= 1; i++ )
for( j = -1; j <= 1; j++ )
for( k = -1; k <= 1; k++ )
if( val > pixval32f( dog_pyr[octv][intvl+i], r + j, c + k ) )
return 0;
}
return 1;
}
/*
Interpolates a scale-space extremum's location and scale to subpixel
accuracy to form an image feature. Rejects features with low contrast.
Based on Section 4 of Lowe's paper.
@param dog_pyr DoG scale space pyramid
@param octv feature's octave of scale space
@param intvl feature's within-octave interval
@param r feature's image row
@param c feature's image column
@param intvls total intervals per octave
@param contr_thr threshold on feature contrast
@return Returns the feature resulting from interpolation of the given
parameters or NULL if the given location could not be interpolated or
if contrast at the interpolated loation was too low. If a feature is
returned, its scale, orientation, and descriptor are yet to be determined.
*/
struct feature* interp_extremum( IplImage*** dog_pyr, int octv, int intvl,
int r, int c, int intvls, double contr_thr )
{
struct feature* feat;
struct detection_data* ddata;
double xi, xr, xc, contr;
int i = 0;
while( i < SIFT_MAX_INTERP_STEPS )
{
interp_step( dog_pyr, octv, intvl, r, c, &xi, &xr, &xc );
if( ABS( xi ) < 0.5 && ABS( xr ) < 0.5 && ABS( xc ) < 0.5 )
break;
c += cvRound( xc );
r += cvRound( xr );
intvl += cvRound( xi );
if( intvl < 1 ||
intvl > intvls ||
c < SIFT_IMG_BORDER ||
r < SIFT_IMG_BORDER ||
c >= dog_pyr[octv][0]->width - SIFT_IMG_BORDER ||
r >= dog_pyr[octv][0]->height - SIFT_IMG_BORDER )
{
return NULL;
}
i++;
}
/* ensure convergence of interpolation */
if( i >= SIFT_MAX_INTERP_STEPS )
return NULL;
contr = interp_contr( dog_pyr, octv, intvl, r, c, xi, xr, xc );
if( ABS( contr ) < contr_thr / intvls )
return NULL;
feat = new_feature();
ddata = feat_detection_data( feat );
feat->img_pt.x = feat->x = ( c + xc ) * pow( 2.0, octv );
feat->img_pt.y = feat->y = ( r + xr ) * pow( 2.0, octv );
ddata->r = r;
ddata->c = c;
ddata->octv = octv;
ddata->intvl = intvl;
ddata->subintvl = xi;
return feat;
}
/*
Performs one step of extremum interpolation. Based on Eqn. (3) in Lowe's
paper.
@param dog_pyr difference of Gaussians scale space pyramid
@param octv octave of scale space
@param intvl interval being interpolated
@param r row being interpolated
@param c column being interpolated
@param xi output as interpolated subpixel increment to interval
@param xr output as interpolated subpixel increment to row
@param xc output as interpolated subpixel increment to col
*/
void interp_step( IplImage*** dog_pyr, int octv, int intvl, int r, int c,
double* xi, double* xr, double* xc )
{
CvMat* dD, * H, * H_inv, X;
double x[3] = { 0 };
dD = deriv_3D( dog_pyr, octv, intvl, r, c );
H = hessian_3D( dog_pyr, octv, intvl, r, c );
H_inv = cvCreateMat( 3, 3, CV_64FC1 );
cvInvert( H, H_inv, CV_SVD );
cvInitMatHeader( &X, 3, 1, CV_64FC1, x, CV_AUTOSTEP );
cvGEMM( H_inv, dD, -1, NULL, 0, &X, 0 );
cvReleaseMat( &dD );
cvReleaseMat( &H );
cvReleaseMat( &H_inv );
*xi = x[2];
*xr = x[1];
*xc = x[0];
}
/*
Computes the partial derivatives in x, y, and scale of a pixel in the DoG
scale space pyramid.
@param dog_pyr DoG scale space pyramid
@param octv pixel's octave in dog_pyr
@param intvl pixel's interval in octv
@param r pixel's image row
@param c pixel's image col
@return Returns the vector of partial derivatives for pixel I
{ dI/dx, dI/dy, dI/ds }^T as a CvMat*
*/
CvMat* deriv_3D( IplImage*** dog_pyr, int octv, int intvl, int r, int c )
{
CvMat* dI;
double dx, dy, ds;
dx = ( pixval32f( dog_pyr[octv][intvl], r, c+1 ) -
pixval32f( dog_pyr[octv][intvl], r, c-1 ) ) / 2.0;
dy = ( pixval32f( dog_pyr[octv][intvl], r+1, c ) -
pixval32f( dog_pyr[octv][intvl], r-1, c ) ) / 2.0;
ds = ( pixval32f( dog_pyr[octv][intvl+1], r, c ) -
pixval32f( dog_pyr[octv][intvl-1], r, c ) ) / 2.0;
dI = cvCreateMat( 3, 1, CV_64FC1 );
cvmSet( dI, 0, 0, dx );
cvmSet( dI, 1, 0, dy );
cvmSet( dI, 2, 0, ds );
return dI;
}
/*
Computes the 3D Hessian matrix for a pixel in the DoG scale space pyramid.
@param dog_pyr DoG scale space pyramid
@param octv pixel's octave in dog_pyr
@param intvl pixel's interval in octv
@param r pixel's image row
@param c pixel's image col
@return Returns the Hessian matrix (below) for pixel I as a CvMat*
/ Ixx Ixy Ixs \ <BR>
| Ixy Iyy Iys | <BR>
\ Ixs Iys Iss /
*/
CvMat* hessian_3D( IplImage*** dog_pyr, int octv, int intvl, int r, int c )
{
CvMat* H;
double v, dxx, dyy, dss, dxy, dxs, dys;
v = pixval32f( dog_pyr[octv][intvl], r, c );
dxx = ( pixval32f( dog_pyr[octv][intvl], r, c+1 ) +
pixval32f( dog_pyr[octv][intvl], r, c-1 ) - 2 * v );
dyy = ( pixval32f( dog_pyr[octv][intvl], r+1, c ) +
pixval32f( dog_pyr[octv][intvl], r-1, c ) - 2 * v );
dss = ( pixval32f( dog_pyr[octv][intvl+1], r, c ) +
pixval32f( dog_pyr[octv][intvl-1], r, c ) - 2 * v );
dxy = ( pixval32f( dog_pyr[octv][intvl], r+1, c+1 ) -
pixval32f( dog_pyr[octv][intvl], r+1, c-1 ) -
pixval32f( dog_pyr[octv][intvl], r-1, c+1 ) +
pixval32f( dog_pyr[octv][intvl], r-1, c-1 ) ) / 4.0;
dxs = ( pixval32f( dog_pyr[octv][intvl+1], r, c+1 ) -
pixval32f( dog_pyr[octv][intvl+1], r, c-1 ) -
pixval32f( dog_pyr[octv][intvl-1], r, c+1 ) +
pixval32f( dog_pyr[octv][intvl-1], r, c-1 ) ) / 4.0;
dys = ( pixval32f( dog_pyr[octv][intvl+1], r+1, c ) -
pixval32f( dog_pyr[octv][intvl+1], r-1, c ) -
pixval32f( dog_pyr[octv][intvl-1], r+1, c ) +
pixval32f( dog_pyr[octv][intvl-1], r-1, c ) ) / 4.0;
H = cvCreateMat( 3, 3, CV_64FC1 );
cvmSet( H, 0, 0, dxx );
cvmSet( H, 0, 1, dxy );
cvmSet( H, 0, 2, dxs );
cvmSet( H, 1, 0, dxy );
cvmSet( H, 1, 1, dyy );
cvmSet( H, 1, 2, dys );
cvmSet( H, 2, 0, dxs );
cvmSet( H, 2, 1, dys );
cvmSet( H, 2, 2, dss );
return H;
}
/*
Calculates interpolated pixel contrast. Based on Eqn. (3) in Lowe's paper.
@param dog_pyr difference of Gaussians scale space pyramid
@param octv octave of scale space
@param intvl within-octave interval
@param r pixel row
@param c pixel column
@param xi interpolated subpixel increment to interval
@param xr interpolated subpixel increment to row
@param xc interpolated subpixel increment to col
@param Returns interpolated contrast.
*/
double interp_contr( IplImage*** dog_pyr, int octv, int intvl, int r,
int c, double xi, double xr, double xc )
{
CvMat* dD, X, T;
double t[1], x[3] = { xc, xr, xi };
cvInitMatHeader( &X, 3, 1, CV_64FC1, x, CV_AUTOSTEP );
cvInitMatHeader( &T, 1, 1, CV_64FC1, t, CV_AUTOSTEP );
dD = deriv_3D( dog_pyr, octv, intvl, r, c );
cvGEMM( dD, &X, 1, NULL, 0, &T, CV_GEMM_A_T );
cvReleaseMat( &dD );
return pixval32f( dog_pyr[octv][intvl], r, c ) + t[0] * 0.5;
}
/*
Allocates and initializes a new feature
@return Returns a pointer to the new feature
*/
feature* new_feature( void )
{
feature* feat;
detection_data* ddata;
feat = (feature *)malloc( sizeof( feature ) );
memset( feat, 0, sizeof( feature ) );
ddata = (detection_data *)malloc( sizeof( detection_data ) );
memset( ddata, 0, sizeof( detection_data ) );
feat->feature_data = ddata;
feat->type = FEATURE_LOWE;
return feat;
}
/*
Determines whether a feature is too edge like to be stable by computing the
ratio of principal curvatures at that feature. Based on Section 4.1 of
Lowe's paper.
@param dog_img image from the DoG pyramid in which feature was detected
@param r feature row
@param c feature col
@param curv_thr high threshold on ratio of principal curvatures
@return Returns 0 if the feature at (r,c) in dog_img is sufficiently
corner-like or 1 otherwise.
*/
int is_too_edge_like( IplImage* dog_img, int r, int c, int curv_thr )
{
double d, dxx, dyy, dxy, tr, det;
/* principal curvatures are computed using the trace and det of Hessian */
d = pixval32f(dog_img, r, c);
dxx = pixval32f( dog_img, r, c+1 ) + pixval32f( dog_img, r, c-1 ) - 2 * d;
dyy = pixval32f( dog_img, r+1, c ) + pixval32f( dog_img, r-1, c ) - 2 * d;
dxy = ( pixval32f(dog_img, r+1, c+1) - pixval32f(dog_img, r+1, c-1) -
pixval32f(dog_img, r-1, c+1) + pixval32f(dog_img, r-1, c-1) ) / 4.0;
tr = dxx + dyy;
det = dxx * dyy - dxy * dxy;
/* negative determinant -> curvatures have different signs; reject feature */
if( det <= 0 )
return 1;
if( tr * tr / det < ( curv_thr + 1.0 )*( curv_thr + 1.0 ) / curv_thr )
return 0;
return 1;
}
/*
Calculates characteristic scale for each feature in an array.
@param features array of features
@param sigma amount of Gaussian smoothing per octave of scale space
@param intvls intervals per octave of scale space
*/
void calc_feature_scales( CvSeq* features, double sigma, int intvls )
{
struct feature* feat;
struct detection_data* ddata;
double intvl;
int i, n;
n = features->total;
for( i = 0; i < n; i++ )
{
feat = CV_GET_SEQ_ELEM( struct feature, features, i );
ddata = feat_detection_data( feat );
intvl = ddata->intvl + ddata->subintvl;
feat->scl = sigma * pow( 2.0, ddata->octv + intvl / intvls );
ddata->scl_octv = sigma * pow( 2.0, intvl / intvls );
}
}
/*
Halves feature coordinates and scale in case the input image was doubled
prior to scale space construction.
@param features array of features
*/
void adjust_for_img_dbl( CvSeq* features )
{
struct feature* feat;
int i, n;
n = features->total;
for( i = 0; i < n; i++ )
{
feat = CV_GET_SEQ_ELEM( struct feature, features, i );
feat->x /= 2.0;
feat->y /= 2.0;
feat->scl /= 2.0;
feat->img_pt.x /= 2.0;
feat->img_pt.y /= 2.0;
}
}
/*
Computes a canonical orientation for each image feature in an array. Based
on Section 5 of Lowe's paper. This function adds features to the array when
there is more than one dominant orientation at a given feature location.
@param features an array of image features
@param gauss_pyr Gaussian scale space pyramid
*/
void calc_feature_oris( CvSeq* features, IplImage*** gauss_pyr )
{
feature* feat;
detection_data* ddata;
double* hist;
double omax;
int i, j, n = features->total;
for( i = 0; i < n; i++ )
{
feat = (feature *)malloc( sizeof( feature ) );
cvSeqPopFront( features, feat );
ddata = feat_detection_data( feat );
hist = ori_hist( gauss_pyr[ddata->octv][ddata->intvl],
ddata->r, ddata->c, SIFT_ORI_HIST_BINS,
cvRound( SIFT_ORI_RADIUS * ddata->scl_octv ),
SIFT_ORI_SIG_FCTR * ddata->scl_octv );
for( j = 0; j < SIFT_ORI_SMOOTH_PASSES; j++ )
smooth_ori_hist( hist, SIFT_ORI_HIST_BINS );
omax = dominant_ori( hist, SIFT_ORI_HIST_BINS );
add_good_ori_features( features, hist, SIFT_ORI_HIST_BINS,
omax * SIFT_ORI_PEAK_RATIO, feat );
free( ddata );
free( feat );
free( hist );
}
}
/*
Computes a gradient orientation histogram at a specified pixel.
@param img image
@param r pixel row
@param c pixel col
@param n number of histogram bins
@param rad radius of region over which histogram is computed
@param sigma std for Gaussian weighting of histogram entries
@return Returns an n-element array containing an orientation histogram
representing orientations between 0 and 2 PI.
*/
double* ori_hist( IplImage* img, int r, int c, int n, int rad, double sigma)
{
double* hist;
double mag, ori, w, exp_denom, PI2 = CV_PI * 2.0;
int bin, i, j;
hist = (double *)calloc( n, sizeof( double ) );
exp_denom = 2.0 * sigma * sigma;
for( i = -rad; i <= rad; i++ )
for( j = -rad; j <= rad; j++ )
if( calc_grad_mag_ori( img, r + i, c + j, &mag, &ori ) )
{
w = exp( -( i*i + j*j ) / exp_denom );
bin = cvRound( n * ( ori + CV_PI ) / PI2 );
bin = ( bin < n )? bin : 0;
hist[bin] += w * mag;
}
return hist;
}
/*
Calculates the gradient magnitude and orientation at a given pixel.
@param img image
@param r pixel row
@param c pixel col
@param mag output as gradient magnitude at pixel (r,c)
@param ori output as gradient orientation at pixel (r,c)
@return Returns 1 if the specified pixel is a valid one and sets mag and
ori accordingly; otherwise returns 0
*/
int calc_grad_mag_ori( IplImage* img, int r, int c, double* mag, double* ori )
{
double dx, dy;
if( r > 0 && r < img->height - 1 && c > 0 && c < img->width - 1 )
{
dx = pixval32f( img, r, c+1 ) - pixval32f( img, r, c-1 );
dy = pixval32f( img, r-1, c ) - pixval32f( img, r+1, c );
*mag = sqrt( dx*dx + dy*dy );
*ori = atan2( dy, dx );
return 1;
}
else
return 0;
}
/*
Gaussian smooths an orientation histogram.
@param hist an orientation histogram
@param n number of bins
*/
void smooth_ori_hist( double* hist, int n )
{
double prev, tmp, h0 = hist[0];
int i;
prev = hist[n-1];
for( i = 0; i < n; i++ )
{
tmp = hist[i];
hist[i] = 0.25 * prev + 0.5 * hist[i] +
0.25 * ( ( i+1 == n )? h0 : hist[i+1] );
prev = tmp;
}
}
/*
Finds the magnitude of the dominant orientation in a histogram
@param hist an orientation histogram
@param n number of bins
@return Returns the value of the largest bin in hist
*/
double dominant_ori( double* hist, int n )
{
double omax;
int maxbin, i;
omax = hist[0];
maxbin = 0;
for( i = 1; i < n; i++ )
if( hist[i] > omax )
{
omax = hist[i];
maxbin = i;
}
return omax;
}
/*
Interpolates a histogram peak from left, center, and right values
*/
#define interp_hist_peak( l, c, r ) ( 0.5 * ((l)-(r)) / ((l) - 2.0*(c) + (r)) )
/*
Adds features to an array for every orientation in a histogram greater than
a specified threshold.
@param features new features are added to the end of this array
@param hist orientation histogram
@param n number of bins in hist
@param mag_thr new features are added for entries in hist greater than this
@param feat new features are clones of this with different orientations
*/
void add_good_ori_features( CvSeq* features, double* hist, int n,
double mag_thr, struct feature* feat )
{
struct feature* new_feat;
double bin, PI2 = CV_PI * 2.0;
int l, r, i;
for( i = 0; i < n; i++ )
{
l = ( i == 0 )? n - 1 : i-1;
r = ( i + 1 ) % n;
if( hist[i] > hist[l] && hist[i] > hist[r] && hist[i] >= mag_thr )
{
bin = i + interp_hist_peak( hist[l], hist[i], hist[r] );
bin = ( bin < 0 )? n + bin : ( bin >= n )? bin - n : bin;
new_feat = clone_feature( feat );
new_feat->ori = ( ( PI2 * bin ) / n ) - CV_PI;
cvSeqPush( features, new_feat );
free( new_feat );
}
}
}
/*
Makes a deep copy of a feature
@param feat feature to be cloned
@return Returns a deep copy of feat
*/
struct feature* clone_feature( struct feature* feat )
{
struct feature* new_feat;
struct detection_data* ddata;
new_feat = new_feature();
ddata = feat_detection_data( new_feat );
memcpy( new_feat, feat, sizeof( struct feature ) );
memcpy( ddata, feat_detection_data(feat), sizeof( struct detection_data ) );
new_feat->feature_data = ddata;
return new_feat;
}
/*
Computes feature descriptors for features in an array. Based on Section 6
of Lowe's paper.
@param features array of features
@param gauss_pyr Gaussian scale space pyramid
@param d width of 2D array of orientation histograms
@param n number of bins per orientation histogram
*/
void compute_descriptors( CvSeq* features, IplImage*** gauss_pyr, int d, int n)
{
struct feature* feat;
struct detection_data* ddata;
double*** hist;
int i, k = features->total;
for( i = 0; i < k; i++ )
{
feat = CV_GET_SEQ_ELEM( struct feature, features, i );
ddata = feat_detection_data( feat );
hist = descr_hist( gauss_pyr[ddata->octv][ddata->intvl], ddata->r,
ddata->c, feat->ori, ddata->scl_octv, d, n );
hist_to_descr( hist, d, n, feat );
release_descr_hist( &hist, d );
}
}
/*
Computes the 2D array of orientation histograms that form the feature
descriptor. Based on Section 6.1 of Lowe's paper.
@param img image used in descriptor computation
@param r row coord of center of orientation histogram array
@param c column coord of center of orientation histogram array
@param ori canonical orientation of feature whose descr is being computed
@param scl scale relative to img of feature whose descr is being computed
@param d width of 2d array of orientation histograms
@param n bins per orientation histogram
@return Returns a d x d array of n-bin orientation histograms.
*/
double*** descr_hist( IplImage* img, int r, int c, double ori,
double scl, int d, int n )
{
double*** hist;
double cos_t, sin_t, hist_width, exp_denom, r_rot, c_rot, grad_mag,
grad_ori, w, rbin, cbin, obin, bins_per_rad, PI2 = 2.0 * CV_PI;
int radius, i, j;
hist = (double ***)calloc( d, sizeof( double** ) );
for( i = 0; i < d; i++ )
{
hist[i] = (double **)calloc( d, sizeof( double* ) );
for( j = 0; j < d; j++ )
hist[i][j] = (double *)calloc( n, sizeof( double ) );
}
cos_t = cos( ori );
sin_t = sin( ori );
bins_per_rad = n / PI2;
exp_denom = d * d * 0.5;
hist_width = SIFT_DESCR_SCL_FCTR * scl;
radius = hist_width * sqrt(2.0) * ( d + 1.0 ) * 0.5 + 0.5;
for( i = -radius; i <= radius; i++ )
for( j = -radius; j <= radius; j++ )
{
/*
Calculate sample's histogram array coords rotated relative to ori.
Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e.
r_rot = 1.5) have full weight placed in row 1 after interpolation.
*/
c_rot = ( j * cos_t - i * sin_t ) / hist_width;
r_rot = ( j * sin_t + i * cos_t ) / hist_width;
rbin = r_rot + d / 2 - 0.5;
cbin = c_rot + d / 2 - 0.5;
if( rbin > -1.0 && rbin < d && cbin > -1.0 && cbin < d )
if( calc_grad_mag_ori( img, r + i, c + j, &grad_mag, &grad_ori ))
{
grad_ori -= ori;
while( grad_ori < 0.0 )
grad_ori += PI2;
while( grad_ori >= PI2 )
grad_ori -= PI2;
obin = grad_ori * bins_per_rad;
w = exp( -(c_rot * c_rot + r_rot * r_rot) / exp_denom );
interp_hist_entry( hist, rbin, cbin, obin, grad_mag * w, d, n );
}
}
return hist;
}
/*
Interpolates an entry into the array of orientation histograms that form
the feature descriptor.
@param hist 2D array of orientation histograms
@param rbin sub-bin row coordinate of entry
@param cbin sub-bin column coordinate of entry
@param obin sub-bin orientation coordinate of entry
@param mag size of entry
@param d width of 2D array of orientation histograms
@param n number of bins per orientation histogram
*/
void interp_hist_entry( double*** hist, double rbin, double cbin,
double obin, double mag, int d, int n )
{
double d_r, d_c, d_o, v_r, v_c, v_o;
double** row, * h;
int r0, c0, o0, rb, cb, ob, r, c, o;
r0 = cvFloor( rbin );
c0 = cvFloor( cbin );
o0 = cvFloor( obin );
d_r = rbin - r0;
d_c = cbin - c0;
d_o = obin - o0;
/*
The entry is distributed into up to 8 bins. Each entry into a bin
is multiplied by a weight of 1 - d for each dimension, where d is the
distance from the center value of the bin measured in bin units.
*/
for( r = 0; r <= 1; r++ )
{
rb = r0 + r;
if( rb >= 0 && rb < d )
{
v_r = mag * ( ( r == 0 )? 1.0 - d_r : d_r );
row = hist[rb];
for( c = 0; c <= 1; c++ )
{
cb = c0 + c;
if( cb >= 0 && cb < d )
{
v_c = v_r * ( ( c == 0 )? 1.0 - d_c : d_c );
h = row[cb];
for( o = 0; o <= 1; o++ )
{
ob = ( o0 + o ) % n;
v_o = v_c * ( ( o == 0 )? 1.0 - d_o : d_o );
h[ob] += v_o;
}
}
}
}
}
}
/*
Converts the 2D array of orientation histograms into a feature's descriptor
vector.
@param hist 2D array of orientation histograms
@param d width of hist
@param n bins per histogram
@param feat feature into which to store descriptor
*/
void hist_to_descr( double*** hist, int d, int n, struct feature* feat )
{
int int_val, i, r, c, o, k = 0;
for( r = 0; r < d; r++ )
for( c = 0; c < d; c++ )
for( o = 0; o < n; o++ )
feat->descr[k++] = hist[r][c][o];
feat->d = k;
normalize_descr( feat );
for( i = 0; i < k; i++ )
if( feat->descr[i] > SIFT_DESCR_MAG_THR )
feat->descr[i] = SIFT_DESCR_MAG_THR;
normalize_descr( feat );
/* convert floating-point descriptor to integer valued descriptor */
for( i = 0; i < k; i++ )
{
int_val = SIFT_INT_DESCR_FCTR * feat->descr[i];
feat->descr[i] = MIN( 255, int_val );
}
}
/*
Normalizes a feature's descriptor vector to unitl length
@param feat feature
*/
void normalize_descr( struct feature* feat )
{
double cur, len_inv, len_sq = 0.0;
int i, d = feat->d;
for( i = 0; i < d; i++ )
{
cur = feat->descr[i];
len_sq += cur*cur;
}
len_inv = 1.0 / sqrt( len_sq );
for( i = 0; i < d; i++ )
feat->descr[i] *= len_inv;
}
/*
Compares features for a decreasing-scale ordering. Intended for use with
CvSeqSort
@param feat1 first feature
@param feat2 second feature
@param param unused
@return Returns 1 if feat1's scale is greater than feat2's, -1 if vice versa,
and 0 if their scales are equal
*/
int feature_cmp( void* feat1, void* feat2, void* param )
{
struct feature* f1 = (struct feature*) feat1;
struct feature* f2 = (struct feature*) feat2;
if( f1->scl < f2->scl )
return 1;
if( f1->scl > f2->scl )
return -1;
return 0;
}
/*
De-allocates memory held by a descriptor histogram
@param hist pointer to a 2D array of orientation histograms
@param d width of hist
*/
void release_descr_hist( double**** hist, int d )
{
int i, j;
for( i = 0; i < d; i++)
{
for( j = 0; j < d; j++ )
free( (*hist)[i][j] );
free( (*hist)[i] );
}
free( *hist );
*hist = NULL;
}
/*
De-allocates memory held by a scale space pyramid
@param pyr scale space pyramid
@param octvs number of octaves of scale space
@param n number of images per octave
*/
void release_pyr( IplImage**** pyr, int octvs, int n )
{
int i, j;
for( i = 0; i < octvs; i++ )
{
for( j = 0; j < n; j++ )
cvReleaseImage( &(*pyr)[i][j] );
free( (*pyr)[i] );
}
free( *pyr );
*pyr = NULL;
}
| [
"mhlee1215@6231343e-7b99-2e4e-8751-d345bb62f328"
]
| [
[
[
1,
1273
]
]
]
|
27a2d979bc3550779c997bb1c84a915c9c518d3e | 81128e8bcf44c1db5790433785e83bbd70b8d9c2 | /Testbed/Tests/MyContactListenerForSensor.cpp | 4ff93e20e8ddec83085933da8165055f653ce8e3 | [
"Zlib"
]
| permissive | vanminhle246/Box2D_v2.2.1 | 8a16ef72688c6b03466c7887e501e92f264ed923 | 6f06dda1e2c9c7277ce26eb7aa6340863d1f3bbb | refs/heads/master | 2016-09-05T18:41:00.133321 | 2011-11-28T07:47:32 | 2011-11-28T07:47:32 | 2,817,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,527 | cpp | #include "MyContactListenerForSensor.h"
MyContactListenerForSensor::MyContactListenerForSensor(void)
{
}
MyContactListenerForSensor::~MyContactListenerForSensor(void)
{
}
void MyContactListenerForSensor::BeginContact(b2Contact* contact)
{
BallForSensor* radarEntity;
BallForSensor* aircraftEntity;
if (getRadarAndAircraft(contact, radarEntity, aircraftEntity ))
radarEntity->radarAcquiredEnemy(aircraftEntity);
}
void MyContactListenerForSensor::EndContact(b2Contact* contact)
{
BallForSensor* radarEntity;
BallForSensor* aircraftEntity;
if (getRadarAndAircraft(contact, radarEntity, aircraftEntity ))
radarEntity->radarLostEnemy(aircraftEntity);
}
bool MyContactListenerForSensor::getRadarAndAircraft(b2Contact* contact, BallForSensor*& radarEntity, BallForSensor*& aircraftEntity)
{
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
//make sure only one of the fixtures was a sensor
bool sensorA = fixtureA->IsSensor();
bool sensorB = fixtureB->IsSensor();
if (! (sensorA ^ sensorB))
return false;
BallForSensor* entityA = static_cast<BallForSensor *> (fixtureA->GetBody()->GetUserData());
BallForSensor* entityB = static_cast<BallForSensor *> (fixtureB->GetBody()->GetUserData());
if (sensorA) //fixtureB must be an enemy aircraft
{
radarEntity = entityA;
aircraftEntity = entityB;
}
else //fixtureA must be an enemy aircraft
{
radarEntity = entityB;
aircraftEntity = entityA;
}
return true;
} | [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
8a3d9061eff8b448e0330f5f2613237017f339a1 | 9566086d262936000a914c5dc31cb4e8aa8c461c | /EnigmaAudio/IAudioDevice.hpp | 6ecec7967e497557fa0a88bd2b7bb91f5bdd8ef6 | []
| no_license | pazuzu156/Enigma | 9a0aaf0cd426607bb981eb46f5baa7f05b66c21f | b8a4dfbd0df206e48072259dbbfcc85845caad76 | refs/heads/master | 2020-06-06T07:33:46.385396 | 2011-12-19T03:14:15 | 2011-12-19T03:14:15 | 3,023,618 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,706 | hpp | #ifndef IAUDIODEVICE_HPP_INCLUDED
#define IAUDIODEVICE_HPP_INCLUDED
/*
Copyright © 2009 Christopher Joseph Dean Schaefer (disks86)
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.
*/
#include "std_map.hpp"
#include "iostream.hpp"
#include "string.hpp"
#include "boost_foreach.hpp"
#include "Entities\Entity.hpp"
#include "IAudioDecoder.hpp"
#include "IAudioEncoder.hpp"
#include "ClientTransmissionManager.hpp"
#include "ClientConfigurationManager.hpp"
namespace Enigma
{
class DllExport IAudioDevice
{
private:
protected:
IAudioDecoder* mAudioDecoder;
IAudioEncoder* mAudioEncoder;
public:
virtual ~IAudioDevice(){};
virtual void Preinit()=0;
virtual void Init(int argc, Enigma::c8** argv)=0;
virtual void Load()=0;
virtual void Unload()=0;
virtual void Poll()=0;
virtual void Capture()=0;
virtual void SetEncoderAndDecoder(IAudioDecoder* audioDecoder, IAudioEncoder* audioEncoder)
{
mAudioDecoder=audioDecoder;
mAudioEncoder=audioEncoder;
}
//playback
virtual void StreamAtLocation(const Enigma::Entity& entity,Enigma::u8* buffer,int priority,size_t encodedSize)=0;
virtual void StreamVoiceAtLocation(const Enigma::Entity& entity,Enigma::u8* encodedBuffer,size_t encodedSize)=0;
virtual void PlayAtLocation(const Enigma::Entity& entity,const std::string& filename,int priority)=0;
virtual void PlayAtLocation(const Enigma::Entity& entity,Enigma::c8* filename,int priority)=0;
virtual void PlayAtLocation(const Enigma::Entity& entity,const Enigma::c8* filename,int priority)=0;
virtual void UpdateListenerValues(const Enigma::Entity& entity)=0;
//recording
virtual void StartRecording()=0;
virtual void StopRecording()=0;
};
};
#endif // IAUDIODEVICE_HPP_INCLUDED
| [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
0347b2a7d154d76e35232790456129b190659f27 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/UiCtrl/AudioCtrlDa.cpp | b3bcffa8ab151f9c0d398002c2448f135dbb2836 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,279 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AudioCtrlDa.h"
#include "RouteEnums.h"
#include "AudioClipsEnum.h"
/* ******************
This is the syntax implemented by the class AudioCtrlLanguageDa:
SoundListNormal := |
FirstCrossing
FirstCrossing AdditionalCrossing
FirstCrossing := ActionAndWhen
AdditionalCrossing := <UndDann> ActionAndWhen
SoundListPriority := |
<DuKorAtFelHall> |
<DuHarAvvikitFranRutten> |
<DuArFrammeVidDinDest>
ActionAndWhen := Action When |
Action
Action := <SvangVanster> |
<SvangHoger> |
<HallVanster> |
<HallHoger> |
<KorRaktFram> |
<VidDestinationen> |
<SvangVanster> <IRondellen> |
<SvangHoger> <IRondellen> |
<KorRaktFram> <IRondellen> |
<KorUr> |
RoundaboutExit
RoundaboutExit := <KorUr> |
<Ta> NumberedExit <Utfarten> <IRondellen>
When := <Haer> |
<Om[Distance]> (Distance = 25, 50, 100, 200, 500 meter, 1, 2 km)
********************* */
namespace isab{
using namespace RouteEnums;
using namespace AudioClipsEnum;
AudioCtrlLanguageDa::AudioCtrlLanguageDa() : AudioCtrlLanguageStd()
{
}
class AudioCtrlLanguage* AudioCtrlLanguageDa::New() {
return new AudioCtrlLanguageDa();
}
int AudioCtrlLanguageDa::newCameraSoundList(
DistanceInfo &deadlines,
SoundClipsList &soundClips)
{
deadlines.sayAtDistance = -1;
deadlines.abortTooShortDistance = -1;
deadlines.abortTooFarDistance = -1;
m_soundState.soundClips = &soundClips;
m_soundState.truncPoint = 0;
m_soundState.noMoreSounds = false;
appendClip(DaSoundCamera);
appendClip(SoundEnd);
resetState();
m_soundState.soundClips = NULL;
return 0;
}
void AudioCtrlLanguageDa::Distance()
{
switch (m_nextXing.spokenDist) {
case 2000:
appendClip(DaSoundOmTuKilometer);
break;
case 1000:
appendClip(DaSoundOmEnKilometer);
break;
case 500:
appendClip(DaSoundOmFemhundredeMeter);
break;
case 200:
appendClip(DaSoundOmTuHundredeMeter);
break;
case 100:
appendClip(DaSoundOmEttHundredeMeter);
break;
case 50:
appendClip(DaSoundOmHalvtredsMeter);
break;
case 25:
appendClip(DaSoundOmFemOgTuveMeter);
break;
case 0:
// Should never happen
appendClip(DaSoundNu);
break;
default:
// Internal error, kill the whole sound.
truncateThisCrossing();
}
}
void AudioCtrlLanguageDa::When()
{
if (m_nextXing.spokenDist == 0) {
if (m_nextXing.crossingNum == 1) {
appendClip(DaSoundNu);
} else {
appendClip(DaSoundMeddetsamme);
}
} else {
Distance();
}
if (m_nextXing.setTimingMarker) {
appendClip(SoundTimingMarker);
}
}
void AudioCtrlLanguageDa::NumberedExit()
{
if ( (m_nextXing.xing->exitCount < 1) ||
(m_nextXing.xing->exitCount > 8) ) {
// Impossible, can not code that many exits - do nothing
return;
}
appendClip(DaSoundDenForste + m_nextXing.xing->exitCount - 1);
}
void AudioCtrlLanguageDa::RoundaboutExit()
{
if (m_nextXing.spokenDist == 0) {
appendClip(DaSoundDrejTillHojre); /* FIXME - hack */
} else {
appendClip(DaSoundTa);
NumberedExit();
appendClip(DaSoundVej);
appendClip(DaSoundIRundkorseln);
}
}
void AudioCtrlLanguageDa::ActionAndWhen()
{
Action();
if (m_soundState.noMoreSounds) {
return;
}
if ( (RouteAction(m_nextXing.xing->action) == Finally) &&
(m_nextXing.spokenDist == 0) ) {
return; // NB! No distance info added to this sound if spokenDist==0
}
When();
}
void AudioCtrlLanguageDa::Action()
{
switch (RouteAction(m_nextXing.xing->action)) {
case InvalidAction:
case Delta:
case RouteActionMax:
case End:
case Start:
/* Should never occur */
truncateThisCrossing();
return;
case EnterRdbt:
case Ahead:
case On: /* Enter highway from ramp */
case ParkCar:
case FollowRoad:
case EnterFerry:
case ChangeFerry:
/* No sound on purpose. */
truncateThisCrossing();
return;
case Left:
appendClip(DaSoundDrejTillVenstre);
break;
case Right:
appendClip(DaSoundDrejTillHojre);
break;
case Finally:
appendClip(DaSoundMaletErRaettfram);
// NB! No distance info added to this sound if spokenDist==0
break;
case ExitRdbt:
RoundaboutExit();
break;
case AheadRdbt:
if (m_nextXing.spokenDist == 0) {
appendClip(DaSoundDrejTillHojre); /* FIXME - hack */
} else {
appendClip(DaSoundKorLigeUd);
appendClip(DaSoundIRundkorseln);
}
break;
case LeftRdbt:
if (m_nextXing.spokenDist == 0) {
appendClip(DaSoundDrejTillHojre); /* FIXME - hack */
} else {
appendClip(DaSoundDrejTillVenstre);
appendClip(DaSoundIRundkorseln);
}
break;
case RightRdbt:
if (m_nextXing.spokenDist == 0) {
appendClip(DaSoundDrejTillHojre); /* FIXME - hack */
} else {
appendClip(DaSoundDrejTillHojre);
appendClip(DaSoundIRundkorseln);
}
break;
case ExitAt:
case OffRampLeft:
case OffRampRight:
appendClip(DaSoundTa);
appendClip(DaSoundFrakorsel);
break;
case KeepLeft:
appendClip(DaSoundHallTillVenstre);
break;
case KeepRight:
appendClip(DaSoundHallTillHojre);
break;
case UTurn:
case StartWithUTurn:
appendClip(DaSoundLavEnUVandning);
break;
case UTurnRdbt:
if (m_nextXing.spokenDist == 0) {
appendClip(DaSoundDrejTillHojre); /* FIXME - hack */
} else {
appendClip(DaSoundLavEnUVandning);
appendClip(DaSoundIRundkorseln);
}
break;
default:
// Make no sound for unknown turns.
truncateThisCrossing();
return;
}
}
void AudioCtrlLanguageDa::FirstCrossing()
{
ActionAndWhen();
}
void AudioCtrlLanguageDa::AdditionalCrossing()
{
appendClip(DaSoundDarefter);
ActionAndWhen();
}
void AudioCtrlLanguageDa::genericDeviatedFromRoute()
{
appendClip(DaSoundDuErAvviketFraRutten);
}
void AudioCtrlLanguageDa::genericReachedDest()
{
appendClip(DaSoundDuErFrammeVidMalet);
}
} /* namespace isab */
| [
"[email protected]"
]
| [
[
[
1,
290
]
]
]
|
0bf3a9907b17f42e7d9f26f4ae9b5c2b73156825 | 1deb3507c241b7e2417ba041c9c71cb5cf7eef06 | /heroin_data/create_rare_affix_data.cpp | 92cf04522d791199376079d12bf783a6cc9f3763 | []
| no_license | ChefKeeper/heroinglands | 2a076db02bc48d578eb1d8d0eb2771079e8a9e9d | 4585a4adf8c6f3b42e57928fe956cddb5a91ef1a | refs/heads/master | 2016-08-13T02:20:18.085064 | 2009-02-13T20:30:21 | 2009-02-13T20:30:21 | 47,699,838 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,488 | cpp | #include <iostream>
#include <cstdlib>
#include <nil/file.hpp>
#include <nil/array.hpp>
#include <nil/string.hpp>
#include "excel_data.hpp"
#include "creation.hpp"
#include "utility.hpp"
void create_rare_affix_file(std::string const & rareaffix_txt, string_table_manager & string_manager, std::string const & output_directory, std::string const & output_file, std::string const & affix_description)
{
std::stringstream rare_affix_stream;
excel_data rareaffix_data(rareaffix_txt);
std::string const rareaffix_column_strings[] = {"name"};
string_vector rareaffix_columns = array_to_vector(rareaffix_column_strings, nil::countof(rareaffix_column_strings));
string_vectors rareaffix_output;
rareaffix_data.read_lines(rareaffix_columns, rareaffix_output);
for(std::size_t i = 0; i < rareaffix_output.size(); i++)
{
string_vector line = rareaffix_output[i];
std::string name = string_manager.transform(line[0]);
rare_affix_stream << name << "\n";
}
write_file(affix_description, output_directory, output_file, rare_affix_stream);
}
void create_rare_affix_data(std::string const & rareprefix_txt, std::string const & raresuffix_txt, string_table_manager & string_manager, std::string const & output_directory)
{
create_rare_affix_file(rareprefix_txt, string_manager, output_directory, "rare_prefixes.txt", "rare prefixes");
create_rare_affix_file(raresuffix_txt, string_manager, output_directory, "rare_suffixes.txt", "rare suffixes");
}
| [
"binrapt@92c0f8f3-e753-0410-a10c-b3df2c4a8671"
]
| [
[
[
1,
34
]
]
]
|
6e68f1aaa0f097dd3a006499f5aa25023b1daf3c | 67298ca8528b753930a3dc043972dceab5e45d6a | /Asteroids/src/ActiveObject.hpp | ddbb43b056b817f2550cd417431fe732cfda97ae | []
| no_license | WhyKay92/cs260assignment3 | 3cf28dd92b9956b2cd4f850652651cb11f25c753 | 77ad90cd2dc0b44f3ba0a396dc8399021de4faa5 | refs/heads/master | 2021-05-30T14:59:21.297733 | 2010-12-13T09:18:17 | 2010-12-13T09:18:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | hpp | /*!
* @File ActiveObject.hpp
* @Author Steven Liss and Westley Hennigh
* @Date 25 Feb 2010, 20 Oct 2010
* @Brief Threads as objects, neat.
*/
#pragma once
#include "Thread.hpp"
/*
ActiveObject is basically a cookie cutter thread.
Derive from ActiveObject and you can specify init, run and
flush for your own thread.
*/
class ActiveObject
{
public:
ActiveObject ();
virtual ~ActiveObject ();
void Wake (); // I like the idea of telling the thread to go rather than having it do
// so automatically after construction.
void Kill (); //^? must call before exiting... perhaps I should do an isDying check in
// the destructor and clean up (just in case)
protected:
virtual void InitThread () = 0;
virtual void Run () = 0;
virtual void FlushThread () = 0;
// thread function will call virtual functions from derived class
static DWORD WINAPI ThreadFunc (void *pArg);
bool isDying;
Thread mythread;
};
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
27088a2e9a9cda912cd4e3a479dcd76cb5dab83f | 99d3989754840d95b316a36759097646916a15ea | /trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/cv_geometry/ransac.h | 9dce47b19e85fb6fef7fffd57531d0e99b6d24d8 | []
| no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | h | #pragma once
#include <cmath>
namespace ferry {
namespace math {
class RANSAC
{
public:
RANSAC(int modelSampleSize) {
this->s = modelSampleSize;
this->p = 0.99;
}
~RANSAC(void) {}
public:
int calcN(int inliersNumber, int samplesNumber) {
double e = 1 - (double)inliersNumber / samplesNumber;
//cout<<"e: "<<e<<endl;
if (e > 0.9) e = 0.9;
//cout<<"pow: "<<pow((1 - e), s)<<endl;
//cout<<log(1 - pow((1 - e), s))<<endl;
return (int)(log(1 - p) / log(1 - pow((1 - e), s)));
}
private:
//samples size for fitting a model
int s;
double p;
};
}
} | [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
]
| [
[
[
1,
36
]
]
]
|
944a59a57f755ab1d1d484f26165f7f10f379edd | f2cf9ead30a7298b3c1ec672ac118429fbac0a40 | /Poc1/Source/Poc1.Fast/Source/FastNoise.cpp | 07c0726107212712774295d79bb7ea13bc5bedd6 | []
| no_license | johann-gambolputty/robotbastards | 3af0b6cf5d948e8bb0450d596ecb5362bfe5a28d | 1874568ada150e04ba83fff2ea067f5a4b63f893 | refs/heads/master | 2021-01-10T09:52:51.773773 | 2009-08-08T00:19:33 | 2009-08-08T00:19:33 | 44,774,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | #include "stdafx.h"
#include "FastNoise.h"
#include "Mem.h"
namespace Poc1
{
namespace Fast
{
FastNoise::FastNoise( )
{
m_pImpl = new ( Aligned( 16 ) ) SseNoise;
}
FastNoise::FastNoise( unsigned int seed )
{
m_pImpl = new ( Aligned( 16 ) ) SseNoise( seed );
}
FastNoise::!FastNoise( )
{
AlignedDelete( m_pImpl );
}
FastNoise::~FastNoise( )
{
AlignedDelete( m_pImpl );
}
};
}; | [
"fishy.coder@1e31eab0-7329-0410-87fb-016d5637cad0"
]
| [
[
[
1,
29
]
]
]
|
5f9556eb286dc901949098e783e012111107bad2 | c4002649c67b174eb5243ba909081a9bffded5f1 | /Demo1/Viewport.h | 815bbc989773a5515309e76f7403381f2c6fc8d9 | []
| no_license | miyabiarts/Qt3D | d65c524a4d86e2dcc8e4b1d6af92fd10e53417f7 | c65d779fe342269002c639c8a868ebe1298f1f23 | refs/heads/master | 2020-05-30T16:14:02.422123 | 2011-07-08T09:06:00 | 2011-07-08T09:06:00 | 2,015,735 | 2 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 525 | h | #pragma once
#include <Qt3D/QGLView.h>
#include <QTimer>
class Viewport : public QGLView
{
Q_OBJECT
public:
Viewport() :
QGLView(0)
{
}
void initializeGL(QGLPainter * painter)
{
// 定期的に画面を更新
QTimer *timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( updateGL() ) );
timer->setInterval( 16 );
timer->setSingleShot( false );
timer->start();
}
void paintGL(QGLPainter *painter)
{
}
private:
}; | [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
5530d0da8c4590adfef6bd35ac5fd4b794c1ee92 | e68cf672cdb98181db47dab9fb8c45e69b91e256 | /src/VertexPosition4fNormal3fColor4f.cpp | 4fc528d36b004ea94f8410b43d1e4c1f22a973d1 | []
| no_license | jiawen/QD3D11 | 09fc794f580db59bfc2faffbe3373a442180e0a5 | c1411967bd2da8d012eddf640eeb5f7b86e66374 | refs/heads/master | 2021-01-21T13:52:48.111246 | 2011-12-19T19:07:17 | 2011-12-19T19:07:17 | 2,549,080 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cpp | #include "VertexPosition4fNormal3fColor4f.h"
VertexPosition4fNormal3fColor4f::VertexPosition4fNormal3fColor4f()
{
}
VertexPosition4fNormal3fColor4f::VertexPosition4fNormal3fColor4f( Vector4f position, Vector3f normal, Vector4f color ) :
m_position( position ),
m_normal( normal ),
m_color( color )
{
}
// static
int VertexPosition4fNormal3fColor4f::numElements()
{
return 3;
}
// static
int VertexPosition4fNormal3fColor4f::sizeInBytes()
{
return 11 * sizeof( float );
}
// static
D3D11_INPUT_ELEMENT_DESC VertexPosition4fNormal3fColor4f::s_layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 4 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 7 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
| [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
92e10ee54a63aa757b3650066190baaf77cb1f30 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEApplications/SE_OpenGL_Application/SEOpenGLApplication/SEApplication.h | c33f8936ccaca9961676b073c8e8881dd9820d68 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,916 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_Application_H
#define Swing_Application_H
#include "SwingFoundation.h"
namespace Swing
{
//----------------------------------------------------------------------------
// 说明:
// 作者:jazzboysc
// 时间:20080809
//----------------------------------------------------------------------------
class SEApplication
{
public:
// 虚基类
virtual ~SEApplication(void);
// 唯一应用程序对象
static SEApplication* TheApplication;
// 唯一命令行参数对象
static SECommand* TheCommand;
// 派生类必须设置这个函数指针.
// int参数是命令行参数个数.char**参数是参数字符串数组.
typedef int (*EntryPoint)(int, char**);
static EntryPoint Run;
// 平台相关实现所使用的额外数据存储.
void SetExtraData(int iIndex, int iSize, const void* pvData);
void GetExtraData(int iIndex, int iSize, void* pvData) const;
bool LaunchFileDialog(void) const;
// 待实现:
// 这个功能目前只支持Microsoft Windows.
// 其它平台尚不支持.
void LaunchTreeControl(SESpatial* pScene, int iXPos, int iYPos,
int iXSize, int iYSize);
void ShutdownTreeControl(void);
// 用于测试disk-streaming和string-tree系统.
// 传入对象被存储到磁盘并在稍后装载.在debug版本下,
// 发生存储和装载数据不匹配时,将产生断言.
// 在装载之后,LaunchTreeControl函数被调用,用于测试string-tree系统.
// 这个功能目前只支持Microsoft Windows.
void TestStreaming(SESpatial* pScene, int iXPos, int iYPos, int iXSize,
int iYSize, const char* acFilename);
protected:
SEApplication(void);
// 额外数据
enum { APP_EXTRA_DATA_COUNT = 128 };
char m_acExtraData[APP_EXTRA_DATA_COUNT];
// 支持文件对话框
bool m_bLaunchFileDialog;
};
#include "SEApplicationMCR.h"
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
87
]
]
]
|
c4e181cd8adc6023023127fd1de2b5985fa866de | d397b0d420dffcf45713596f5e3db269b0652dee | /src/Axe/Socket.hpp | 33660ecc8e505b86c1c1ecfe99e6100b7d8ccb61 | []
| no_license | irov/Axe | 62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f | d3de329512a4251470cbc11264ed3868d9261d22 | refs/heads/master | 2021-01-22T20:35:54.710866 | 2010-09-15T14:36:43 | 2010-09-15T14:36:43 | 85,337,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,409 | hpp | # pragma once
# include <AxeUtil/Shared.hpp>
# include <AxeUtil/Archive.hpp>
namespace Axe
{
typedef boost::function1<void, boost::system::error_code> FSocketConnectResponse;
typedef boost::function1<void, boost::system::error_code> FSocketAcceptResponse;
typedef boost::function2<void, boost::system::error_code, std::size_t> FSocketReadResponse;
typedef boost::function2<void, boost::system::error_code, std::size_t> FSocketWriteResponse;
class Socket
: virtual public AxeUtil::Shared
{
public:
Socket( boost::asio::io_service & _service );
public:
boost::asio::ip::tcp::socket & getAsioSocket() const;
public:
void connect( const boost::asio::ip::tcp::endpoint & _endpoint, const FSocketConnectResponse & _response );
void accept( boost::asio::ip::tcp::acceptor & _aceeptor, const FSocketAcceptResponse & _response );
void close();
public:
bool is_open() const;
public:
void read( void * _buffer, std::size_t _size, const FSocketReadResponse & _response );
void write( void * _buffer, std::size_t _size, const FSocketWriteResponse & _response );
void read_arhive( const AxeUtil::Archive & _ar, const FSocketReadResponse & _response );
void write_arhive( const AxeUtil::Archive & _ar, const FSocketWriteResponse & _response );
protected:
boost::asio::ip::tcp::socket m_socket;
};
typedef AxeHandle<Socket> SocketPtr;
} | [
"yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0"
]
| [
[
[
1,
42
]
]
]
|
082c2cdb2b1ef90d44788ce1d338fdd33f3656ba | 347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1 | /addons/vaSound/libs/stk/src/BlitSaw.cpp | 67a48a640c00a004940720575a1386861f3d31a8 | []
| no_license | sanyaade/VirtualAwesome | 29688648aa3f191cdd756c826b5c84f6f841b93f | 05f3db98500366be1e79da16f5e353e366aed01f | refs/heads/master | 2020-12-01T03:03:51.561884 | 2010-11-08T00:17:44 | 2010-11-08T00:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,743 | cpp | /***************************************************/
/*! \class BlitSaw
\brief STK band-limited sawtooth wave class.
This class generates a band-limited sawtooth waveform using a
closed-form algorithm reported by Stilson and Smith in "Alias-Free
Digital Synthesis of Classic Analog Waveforms", 1996. The user
can specify both the fundamental frequency of the sawtooth and the
number of harmonics contained in the resulting signal.
If nHarmonics is 0, then the signal will contain all harmonics up
to half the sample rate. Note, however, that this setting may
produce aliasing in the signal when the frequency is changing (no
automatic modification of the number of harmonics is performed by
the setFrequency() function).
Based on initial code of Robin Davies, 2005.
Modified algorithm code by Gary Scavone, 2005.
*/
/***************************************************/
#include <stk/BlitSaw.h>
namespace stk {
BlitSaw:: BlitSaw( StkFloat frequency )
{
nHarmonics_ = 0;
this->reset();
this->setFrequency( frequency );
}
BlitSaw :: ~BlitSaw()
{
}
void BlitSaw :: reset()
{
phase_ = 0.0f;
state_ = 0.0;
lastFrame_[0] = 0.0;
}
void BlitSaw :: setFrequency( StkFloat frequency )
{
#if defined(_STK_DEBUG_)
errorString_ << "BlitSaw::setFrequency: frequency = " << frequency << '.';
handleError( StkError::DEBUG_WARNING );
#endif
p_ = Stk::sampleRate() / frequency;
C2_ = 1 / p_;
rate_ = PI * C2_;
this->updateHarmonics();
}
void BlitSaw :: setHarmonics( unsigned int nHarmonics )
{
nHarmonics_ = nHarmonics;
this->updateHarmonics();
// I found that the initial DC offset could be minimized with an
// initial state setting as given below. This initialization should
// only happen before starting the oscillator for the first time
// (but after setting the frequency and number of harmonics). I
// struggled a bit to decide where best to put this and finally
// settled on here. In general, the user shouldn't be messing with
// the number of harmonics once the oscillator is running because
// this is automatically taken care of in the setFrequency()
// function. (GPS - 1 October 2005)
state_ = -0.5 * a_;
}
void BlitSaw :: updateHarmonics( void )
{
if ( nHarmonics_ <= 0 ) {
unsigned int maxHarmonics = (unsigned int) floor( 0.5 * p_ );
m_ = 2 * maxHarmonics + 1;
}
else
m_ = 2 * nHarmonics_ + 1;
a_ = m_ / p_;
#if defined(_STK_DEBUG_)
errorString_ << "BlitSaw::updateHarmonics: nHarmonics_ = " << nHarmonics_ << ", m_ = " << m_ << '.';
handleError( StkError::DEBUG_WARNING );
#endif
}
} // stk namespace
| [
"[email protected]"
]
| [
[
[
1,
91
]
]
]
|
58d4ab55d8d8843eece0f04734cf9111cd152483 | 0ee189afe953dc99825f55232cd52b94d2884a85 | /nexus/StackStream.cpp | 5ed5a94aebb28911773078e9697cbac7d42fe045 | []
| no_license | spolitov/lib | fed99fa046b84b575acc61919d4ef301daeed857 | 7dee91505a37a739c8568fdc597eebf1b3796cf9 | refs/heads/master | 2016-09-11T02:04:49.852151 | 2011-08-11T18:00:44 | 2011-08-11T18:00:44 | 2,192,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,309 | cpp | #include "pch.h"
#include "StackStream.h"
namespace nexus {
StackStream::StackStream(char * begin, size_t size)
: begin_(begin), pos_(begin), end_(begin + size) {}
void StackStream::put(const char * str)
{
ptrdiff_t n = std::find(str, str + (end_ - pos_) + 1, 0) - str;
checkOverflow(n);
memcpy(pos_, str, n);
pos_ += n;
}
void StackStream::put(const std::string & str)
{
ptrdiff_t n = str.length();
checkOverflow(n);
memcpy(pos_, str.c_str(), n);
pos_ += n;
}
void StackStream::writeCString(const std::string & str)
{
ptrdiff_t n = str.length() + 1;
checkOverflow(n);
memcpy(pos_, str.c_str(), n);
pos_ += n;
}
void StackStream::put(char ch)
{
checkOverflow(1);
*pos_ = ch;
++pos_;
}
void StackStream::write(const char * data, size_t n)
{
checkOverflow(n);
memcpy(pos_, data, n);
pos_ += n;
}
Buffer StackStream::buffer() const
{
return Buffer(begin_, pos_);
}
void StackStream::checkOverflow(size_t required)
{
if(static_cast<size_t>(end_ - pos_) < required)
BOOST_THROW_EXCEPTION(StackStreamException() << mstd::error_message("stack buffer overflow") << ErrorPosition(pos_ - begin_) << ErrorSize(end_ - begin_) << ErrorRequired(required));
}
}
| [
"[email protected]"
]
| [
[
[
1,
59
]
]
]
|
16a981f083a6d4f93aecf7052903e8da0ccd3d84 | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /libproject/Setting/SearchRule.h | 782d62cf3a6626e15d91ec4015638f72f65b8ff0 | []
| 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 | 2,147 | h | #ifndef _SETTING_SEARCHRULE_H__
#define _SETTING_SEARCHRULE_H__
#include <string>
#include <set>
#include <map>
#include <Enumerate.h>
#include <setting\settingitem.h>
#include <setting\configitem.h>
#include <xmldefined.h>
// 用来记录Search Rule的实现
class SearchRule : public SettingItem , public ConfigItem {
public:
SearchRule(void);
~SearchRule(void);
public:
int enableCheck(const std::string &search_host, const bool checked);
void addBlackSearchWord(const char *word) {
SettingItem::setModified(true);
word_set_.insert(word);
}
void removeBlackSeachWord(const char * word) {
WORD_SET::iterator iter = word_set_.find(word);
if (word_set_.end() != iter) {
SettingItem::setModified(true);
word_set_.erase(iter);
}
}
void addSearchHost(const std::string &search_host) {
SettingItem::setModified(true);
search_host_.insert(std::make_pair(search_host, true));
}
bool check(const std::string &host_name, const std::string &search_word) const;
bool shouldCheck(const std::string &search_host) const;
bool setting_shouldCheck(const std::string &search_host) const;
// enumerate
void enumBlackWord(Enumerator1<std::string> * enumerator);
void enumSearchEngine(Enumerator2<std::string, bool> *enumerator);
std::string getFirstSearchWord() const;
std::string getNextSearchWord(const std::string &word) const;
protected:
typedef std::set<std::string> WORD_SET;
WORD_SET word_set_;
typedef std::map<std::string, bool> SEARCH_HOST;
SEARCH_HOST search_host_;
bool checkWord(const std::string &word) const;
// XML文件
public:
virtual int parseConfig(TiXmlElement * item_root);
virtual TiXmlElement * saveConfig(TiXmlElement * item_root);
private:
// 搜索规则
int getSearchRule(TiXmlElement * ele);
int setSearchEngineCheck(const TCHAR *word);
int getSearchBlackWord(TiXmlElement * ele);
int getSearchEngineSetting(TiXmlElement * ele);
int setSearchEngineCheck(const TCHAR *search_engine, const TCHAR *enable);
TiXmlElement * saveSearchRule(TiXmlElement *rules_root);
};
#endif // _SETTING_SEARCHRULE_H__
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
6a5a795d0669cf8587ab6785eccf8290105c7e2d | 73acb5def25cb5693f6f5cdede8f5ba668f1d6ec | /LanTran/LanTranDlg.cpp | 86dd0a8f12371a47a45ec42dca9c13ce7b880945 | [
"Apache-2.0"
]
| permissive | daoyuan14/lantran | ee4bec0cd4386507e001ebeaf548ae67fdb50bb5 | 066972873257d4c26739b8884e5fb95dc3127621 | refs/heads/master | 2021-01-23T13:35:38.296793 | 2010-10-10T13:01:20 | 2010-10-10T13:01:20 | 34,151,996 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 21,441 | cpp | // LanTranDlg.cpp : implementation file
//
#include "stdafx.h"
#include "LanTran.h"
#include "LanTranDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLanTranDlg dialog
vector<ClientInfo> g_AcceptClient; //全局变量,用来管理客户端信息
bool GetSelectedIpAddr(CString &s, LPVOID lparam) //获取选中的IP地址。 不用lparam行不行? 引用的强大作用体现了
{
//CLanTranDlg *pLanTranDlg = (CLanTranDlg *)lparam; 那个参数是给别的类用的
//CLanTranDlg *pLanTranDlg = new CLanTranDlg;
CLanTranDlg *pLanTranDlg;
pLanTranDlg = (CLanTranDlg *)(AfxGetApp()->m_pMainWnd);
bool bChoosed = false;
int nListIndex = -1;
int nListCount = pLanTranDlg->m_ClientInfoList.GetItemCount();
for(int i=0; i<nListCount; i++)
{
if( pLanTranDlg->m_ClientInfoList.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED )
{
bChoosed = true; //有已经选择的项。
nListIndex = i; //已经选择的项序号。
break; //所以只能一次选中一个
}
}
if(!bChoosed) //用户还没有选择。
{
AfxMessageBox("你还没有选择发送的目的用户呢,请选择后再重新发送。");
return false;
}
s = pLanTranDlg->m_ClientInfoList.GetItemText(nListIndex, 2);
return true;
}
BOOL isAnti;
/////////////////////////////////////////////////////////////////////////////
CLanTranDlg::CLanTranDlg(CWnd* pParent /*=NULL*/)
: CDialog(CLanTranDlg::IDD, pParent)
{
m_nOpenState = 0;
//{{AFX_DATA_INIT(CLanTranDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CLanTranDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CLanTranDlg)
DDX_Control(pDX, IDC_TAB1, m_Tab);
DDX_Control(pDX, IDC_LIST2, m_ClientInfoList);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CLanTranDlg, CDialog)
//{{AFX_MSG_MAP(CLanTranDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, OnSelchangeTab1)
ON_BN_CLICKED(IDC_BUTTON_HIDE, OnButtonHide)
ON_MESSAGE(WM_SHOWTASK, OnShowTask) //我自定义的消息。但是两个定义方法略有不同
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_BUTTON_NEW, OnButtonNew)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLanTranDlg message handlers
BOOL CLanTranDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
/*----------------------Tab Control的实现-----------------------------------------*/
m_ImageList.Create(16, 16, ILC_COLOR | ILC_MASK, 5, 0);
m_ImageList.Add(AfxGetApp() -> LoadIcon(IDI_ICON1)); //从外部加入时记得保存reload
m_ImageList.Add(AfxGetApp() -> LoadIcon(IDI_ICON2));
m_ImageList.Add(AfxGetApp() -> LoadIcon(IDI_ICON3));
m_ImageList.Add(AfxGetApp() -> LoadIcon(IDI_ICON4));
m_ImageList.Add(AfxGetApp() -> LoadIcon(IDI_ICON5));
m_Tab.SetImageList(&m_ImageList);
m_Tab.InsertItem(0, "快速传输", 0); //如何变大些?
m_Tab.InsertItem(1, "加密传输", 1);
m_Tab.InsertItem(2, "关联杀毒", 2);
m_Tab.InsertItem(3, "在线聊天", 3);
m_Tab.InsertItem(4, "语音聊天", 4);
m_pFileTranDlg = new CFileTranDlg;
m_pFileTranDlg -> Create(IDD_DIALOG_FILETRAN, GetDlgItem(IDC_STATIC_DLG));
m_pSafeTranDlg = new CSafeTranDlg;
m_pSafeTranDlg -> Create(IDD_DIALOG_SAFETRAN, GetDlgItem(IDC_STATIC_DLG));
m_pAntiVirusDlg = new CAntiVirusDlg;
m_pAntiVirusDlg -> Create(IDD_DIALOG_ANTIVIRUS, GetDlgItem(IDC_STATIC_DLG));
m_pChatDlg = new CChatDlg;
m_pChatDlg -> Create(IDD_DIALOG_CHAT, GetDlgItem(IDC_STATIC_DLG));
m_pPhoneDlg = new CPhoneDlg;
m_pPhoneDlg->Create(IDD_DIALOG_PHONE, GetDlgItem(IDC_STATIC_DLG));
DoTab(0);
/*----------------------Tab Control的实现-----------------------------------------*/
/*----------------------List Control的实现----------------------------------------*/
m_ClientInfoList.SetExtendedStyle(
m_ClientInfoList.GetExtendedStyle() //有用吗?
|LVS_EX_FLATSB //扁平风格滚动条
|LVS_EX_FULLROWSELECT //允许整行选中
|LVS_EX_HEADERDRAGDROP //允许标题拖拽
|LVS_EX_ONECLICKACTIVATE //高亮显示
|LVS_EX_GRIDLINES //画出网格线
);
m_ClientInfoList.InsertColumn(0, "用户名", LVCFMT_LEFT, 120, 0);
m_ClientInfoList.InsertColumn(1, "计算机名", LVCFMT_LEFT, 130, 1);
m_ClientInfoList.InsertColumn(2, "IP地址", LVCFMT_LEFT, 150, 2);
/*----------------------List Control的实现----------------------------------------*/
StartLanShow();
AddAllClientInfo(); // add the current Client Info in g_AcceptClient
isAnti = TRUE; //默认关联
return TRUE; // return TRUE unless you set the focus to a control
}
void CLanTranDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CLanTranDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
//===================================================================================================================
if(!m_pSafeTranDlg->path.IsEmpty())
{
CRect rc;
m_pSafeTranDlg->m_picture.GetClientRect(&rc);
CDC *pDC=m_pSafeTranDlg->m_picture.GetDC();
HBITMAP hbmp=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),m_pSafeTranDlg->path,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_DEFAULTCOLOR|LR_DEFAULTSIZE);
BITMAP bm;
GetObject(hbmp,sizeof(bm),&bm);
CDC memdc;
memdc.CreateCompatibleDC(pDC);
memdc.SelectObject(hbmp);
pDC->StretchBlt(0,0,rc.Width(),rc.Height(),&memdc,0,0,bm.bmWidth,bm.bmHeight,SRCCOPY);
}
//===============================================================================================================================
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CLanTranDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CLanTranDlg::SetDlgState(CWnd *pWnd, BOOL bShow)
{
pWnd -> EnableWindow(bShow);
if (bShow)
{
pWnd -> ShowWindow(SW_SHOW);
pWnd -> CenterWindow();
}
else
{
pWnd -> ShowWindow(SW_HIDE);
}
}
void CLanTranDlg::DoTab(int nSel)
{
if (nSel > 4) //确定nSel值不能超过范围
{
nSel = 4;
}
if (nSel < 0)
{
nSel = 0;
}
BOOL bTab[5];
bTab[0] = bTab[1] = bTab[2] = bTab[3] = bTab[4] = FALSE;
bTab[nSel] = TRUE;
SetDlgState(m_pFileTranDlg, bTab[0]);
SetDlgState(m_pSafeTranDlg, bTab[1]);
SetDlgState(m_pAntiVirusDlg, bTab[2]);
SetDlgState(m_pChatDlg, bTab[3]);
SetDlgState(m_pPhoneDlg, bTab[4]);
}
void CLanTranDlg::OnSelchangeTab1(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
int nSelect = m_Tab.GetCurSel();
if (nSelect >= 0)
{
DoTab(nSelect);
}
*pResult = 0;
}
void CLanTranDlg::OnButtonHide()
{
// TODO: Add your control notification handler code here
ToTray();
}
void CLanTranDlg::ToTray()
{
NOTIFYICONDATA nid;
nid.cbSize = (DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd = this->m_hWnd;
nid.uID = IDR_MAINFRAME;
nid.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP ;
nid.uCallbackMessage = WM_SHOWTASK; //自定义的消息名称
nid.hIcon = LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME));
strcpy(nid.szTip, "LanTran"); //信息提示条
Shell_NotifyIcon(NIM_ADD, &nid); //在托盘区添加图标
m_nOpenState = 1; //设置状态成到系统托盘
ShowWindow(SW_HIDE); //隐藏主窗口
}
LRESULT CLanTranDlg::OnShowTask(WPARAM wParam, LPARAM lParam)
{
if(wParam != IDR_MAINFRAME)
{
return 1;
}
switch(lParam)
{
case WM_RBUTTONUP: //右键起来时弹出快捷菜单,这里只有一个“关闭”
{
LPPOINT lpoint = new tagPOINT;
::GetCursorPos(lpoint); //得到鼠标位置
CMenu menu;
menu.CreatePopupMenu(); //声明一个弹出式菜单,增加菜单项“关闭”,点击则发送消息WM_DESTROY给主窗口(已隐藏),将程序结束。
menu.AppendMenu(MF_STRING,WM_DESTROY,"关闭"); //确定弹出式菜单的位置
menu.TrackPopupMenu(TPM_LEFTALIGN,lpoint->x,lpoint->y,this); //资源回收
HMENU hmenu=menu.Detach();
menu.DestroyMenu();
delete lpoint;
}
break;
case WM_LBUTTONDBLCLK://双击左键的处理
{
this->ShowWindow(SW_SHOW);//简单的显示主窗口完事儿
DeleteTray();
}
break;
default:
break;
}
return 0;
}
void CLanTranDlg::DeleteTray()
{
NOTIFYICONDATA nid;
nid.cbSize = (DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd = this -> m_hWnd;
nid.uID = IDR_MAINFRAME;
nid.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP ;
nid.uCallbackMessage = WM_SHOWTASK; //自定义的消息名称
nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME));
strcpy(nid.szTip, "LanTran"); //信息提示条为“计划任务提醒”
Shell_NotifyIcon(NIM_DELETE, &nid); //在托盘区删除图标
}
void CLanTranDlg::OnDestroy()
{
CDialog::OnDestroy();
// TODO: Add your message handler code here
SendLanShowData(EXIT);
// delete this;一定要吗?
/*----------删除传文件的套接字【必须在m_pFileTranDlg被毁灭前】-------------*/
m_pFileTranDlg->DeleteFileSock();
/*----------删除传文件的套接字-------------*/
if (m_pFileTranDlg)
{
delete m_pFileTranDlg;
}
if (m_pSafeTranDlg)
{
delete m_pSafeTranDlg;
}
if (m_pAntiVirusDlg)
{
delete m_pAntiVirusDlg;
}
// 注释掉下面这段就不会Debug Assertion Failed了
// 估计是因为m_pChatDlg中含的套接字没删除掉
if (m_pChatDlg)
{
delete m_pChatDlg;
}
if (m_pPhoneDlg)
{
delete m_pPhoneDlg;
}
if(m_nOpenState == 1)
{
DeleteTray();
}
}
// StartLanShow()本身不是线程函数,只是个过程调用
// 但是它里面有CreateThread()来开启一个线程
void CLanTranDlg::StartLanShow()
{
BOOL bIni = InitLanShowSocket(); // init and bind a Listen Socket
if ( bIni == FALSE )
return;
InitMyClientInfo(); // add own ip info to Global Variable: g_AcceptClient
SendLanShowData(ENTRY); // 广播发送刚上线的信息, 告诉别人我来了
HANDLE hThread = CreateThread(NULL, 0, LanShowThread, this, CREATE_SUSPENDED, &m_id);
ResumeThread(hThread); // run thread
CloseHandle(hThread);
}
// use WinSock to create, bind socket
BOOL CLanTranDlg::InitLanShowSocket()
{
m_LanShowSocket = socket(AF_INET, SOCK_DGRAM, 0);
if ( m_LanShowSocket == INVALID_SOCKET )
{
AfxMessageBox("Creating listenSocket is failed!");
return FALSE;
}
GetLocalIP(m_dwLocalIP);
m_listenAddr.sin_addr.S_un.S_addr = INADDR_ANY;
m_listenAddr.sin_port = htons(NET_LANSHOW_PORT);
m_listenAddr.sin_family = AF_INET;
int iBind = bind(m_LanShowSocket, (struct sockaddr FAR *) &m_listenAddr, sizeof(SOCKADDR_IN));
if ( iBind == SOCKET_ERROR )
{
AfxMessageBox("binging is failed!");
return FALSE ;
}
return TRUE;
}
void CLanTranDlg::GetLocalIP(DWORD &dwLocalIP)
{
struct in_addr in;
struct hostent *thisHost;
if ( gethostname(m_hostName, sizeof(m_hostName)) == SOCKET_ERROR )
{
AfxMessageBox("can not get local name!");
return;
}
thisHost = gethostbyname(m_hostName);
if ( thisHost == NULL )
{
return ;
}
int i = 0;
while( thisHost->h_addr_list[i] ) //是给结构体赋值吗?不是很懂
{
in.S_un.S_addr = *(unsigned long *) thisHost->h_addr_list[i];
i++;
}
dwLocalIP = in.S_un.S_addr; //因为是引用,所以m_dwLocalIP也改变了
sprintf(m_localIPAddr,"%d.%d.%d.%d" //m_localIPAddr是"%d.%d.%d.%d"的这种形式
,dwLocalIP&0x000000ff
,dwLocalIP>>8&0x0000000ff
,dwLocalIP>>16&0x000000ff
,dwLocalIP>>24&0x000000ff
);
}
void CLanTranDlg::InitMyClientInfo() // 把本机的IP等信息增加到g_AcceptClient中
{
ClientInfo LocalInfo; // 用于保存本机信息的数据结构
strcpy(LocalInfo.m_ClientIPAddr, m_localIPAddr);
strcpy(LocalInfo.m_ComputerName, m_hostName);
DWORD dwNameLen = sizeof ( m_TLocalUserName );
GetUserName(m_TLocalUserName, &dwNameLen);
strcpy(LocalInfo.m_UserName, m_TLocalUserName);
g_AcceptClient.push_back(LocalInfo); // 把自己的信息放在g_AcceptClient中
}
// 把自己的ip info给别人, 并接收局域网内其他在线用户的信息
DWORD WINAPI CLanTranDlg::LanShowThread(LPVOID lParam)
{
CLanTranDlg *pLanTranDlg = (CLanTranDlg *)lParam; // 因为这是静态函数吗?
FD_SET fdR;
struct timeval timeouts;
while( true )
{
timeouts.tv_sec = 1; //Time value, in seconds.
timeouts.tv_usec = 0; //Time value, in microseconds.
FD_ZERO(&fdR);
FD_SET(pLanTranDlg -> m_LanShowSocket, &fdR); // 这里pAcceptClient -> m_listenSocket相当于文件描述符的作用,为整型
switch( select ( pLanTranDlg->m_LanShowSocket + 1, &fdR, NULL, NULL, &timeouts) )
{
case -1:
break;
case 0:
{ // 加括号是为了iEr编译通过
int iEr = WSAGetLastError();
break;
}
default:
if ( FD_ISSET(pLanTranDlg -> m_LanShowSocket, &fdR) )
{
pLanTranDlg -> RecvLanShowData();
pLanTranDlg -> AddAllClientInfo();
}
}
}
return 0L;
}
void CLanTranDlg::SendLanShowData(int nState)
{
char BroadCastIP[20]; //通过提取自己的IP,得出整个局域网应有的IP
sprintf(BroadCastIP,"%d.%d.%d.255" //Write formatted data to a string.
,m_dwLocalIP & 0x000000ff
,m_dwLocalIP >> 8 & 0x0000000ff
,m_dwLocalIP >> 16& 0x000000ff
);
SOCKADDR_IN AddrSendToClient;
AddrSendToClient.sin_addr.S_un.S_addr = inet_addr(BroadCastIP);
AddrSendToClient.sin_family = AF_INET;
AddrSendToClient.sin_port = htons(NET_LANSHOW_PORT);
LanShowData *SendingInfo = new LanShowData; //存储本机的所有信息
memset(SendingInfo, 0, sizeof(LanShowData)); //把SendingInfo都赋值为0
SendingInfo->nState = nState;
strcpy(SendingInfo->m_name, m_TLocalUserName); //用户名
strcpy(SendingInfo->m_iPAddr, m_localIPAddr);
struct hostent *thisHost = gethostbyname(m_hostName); //电脑名
if (thisHost != NULL)
{
strcpy(SendingInfo->m_computerName, thisHost->h_name);
}
int iSend = sendto(m_LanShowSocket,(char FAR *)SendingInfo,sizeof(LanShowData),0,(struct sockaddr FAR *)&AddrSendToClient,sizeof(SOCKADDR_IN)); //给局域网内的所有用户发送自己的SendingInfo
int iError = WSAGetLastError();
delete SendingInfo; //不然会溢出的。
if ( iSend == SOCKET_ERROR )
{
AfxMessageBox("sending initial info is failed!");
return ;
}
}
void CLanTranDlg::RecvLanShowData()
{
SOCKADDR_IN from;
int addrLen = sizeof(SOCKADDR_IN);
char RecvDataInfo[NET_LANSHOW_BUFFER];
int iRecv = recvfrom(m_LanShowSocket, RecvDataInfo, sizeof(RecvDataInfo), 0, (struct sockaddr FAR *)&from, &addrLen);
if ( iRecv == SOCKET_ERROR )
{
AfxMessageBox("Recving ClientInfo is failed!");
return;
}
if ( from.sin_addr.S_un.S_addr != m_dwLocalIP ) // 是群发,所以自己也会收到
{
LanShowData *OneClientInfo = ( LanShowData *)RecvDataInfo; // 很关键; 发送的就是ClientInfo *类型的。
vector<ClientInfo>::iterator ts;
/*
* handle LanShowData: "EXIT"
*/
if (OneClientInfo->nState == EXIT) // EXIT相对另两个的处理比较不同,这样可以让另两个公用一些
{
for( ts = g_AcceptClient.begin(); ts != g_AcceptClient.end(); ts ++ )
{
if ( (strcmp(ts->m_ClientIPAddr, OneClientInfo->m_iPAddr) == 0) ) //Compare strings.=0时相等
{
g_AcceptClient.erase(ts);
break;
}
}
delete OneClientInfo; //是删哪个值?OneClientInfo还是RecvDataInfo
return; //这样后面的消息也就不用判断了
}
/*
* handle LanShowData: "ENTRY" and judge no other message
*/
switch (OneClientInfo->nState) //用switch写更有效率些的
{
case ENTRY:
SendLanShowData(ONLINE);
break;
case ONLINE: // 仅仅只要把下面的信息添加进来就ok了
break;
default:
AfxMessageBox("收到了其他种类的消息");
return; // 不再处理下面的了
}
/*
* so the LanShowData must be "ENTRY" or "ANENTRY"
*
* it's time to add info to g_AcceptClient
*
* 先看看g_AcceptClient中是否已经有了, 如果有的话就直接丢弃了
*/
for( ts = g_AcceptClient.begin(); ts != g_AcceptClient.end(); ts ++ )
{
if ( (strcmp(ts->m_ClientIPAddr, OneClientInfo->m_iPAddr) == 0) ) //Compare strings.=0时相等
{
delete OneClientInfo;
return;
}
}
/*
* 说明g_AcceptClient中还没有, 需要拷贝进来
*/
ClientInfo OneManClientInfo;
strcpy(OneManClientInfo.m_UserName, OneClientInfo->m_name);
strcpy(OneManClientInfo.m_ComputerName, OneClientInfo->m_computerName);
strcpy(OneManClientInfo.m_ClientIPAddr, OneClientInfo->m_iPAddr);
g_AcceptClient.push_back(OneManClientInfo);
delete OneClientInfo;
}
}
void CLanTranDlg::AddAllClientInfo()
{
vector<ClientInfo>::iterator ts; //terator是在vector名字空间中定义的类似于指针的一种结构
m_ClientInfoList.DeleteAllItems(); //刷新的时候先清空列表
int i = 0;
for(ts = g_AcceptClient.begin(); ts != g_AcceptClient.end(); ts ++)
{
m_ClientInfoList.InsertItem(i, ts->m_UserName);
m_ClientInfoList.SetItemText(i, 1, ts->m_ComputerName);
m_ClientInfoList.SetItemText(i, 2, ts->m_ClientIPAddr);
i++; //i控制列表中的顺序
}
}
void CLanTranDlg::OnButtonNew()
{
// TODO: Add your control notification handler code here
SendLanShowData(ONLINE);
Sleep(200); //为了防止狂点吗?
AddAllClientInfo();
}
BOOL CLanTranDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if (pMsg->message==WM_KEYDOWN && (int)pMsg->wParam==VK_ESCAPE) //防止按Esc键关闭对话框
{
return TRUE;
}
return CDialog::PreTranslateMessage(pMsg);
}
| [
"clzqwdy@687b6e4e-9fc3-60ed-f37d-c8c0d9c0bbbd"
]
| [
[
[
1,
707
]
]
]
|
ee8b5d2d26bb8cfdbdfd2a11b39b78c5d94f6bb2 | a7109719291d3fb1e3dabfed9405d2b340ad8a89 | /Gandhi-Prototype/lib/cInputLayer.cpp | cca6aad6e4c751c3f4ee046695ba344a469f5570 | []
| no_license | edufg88/gandhi-prototype | 0ea3c6a7bbe72b6d382fa76f23c40b4a0280c666 | 947f2c6d8a63421664eb5018d5d01b8da71f46a2 | refs/heads/master | 2021-01-01T17:32:40.791045 | 2011-12-19T20:10:34 | 2011-12-19T20:10:34 | 32,288,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,645 | cpp |
#include "cInputLayer.h"
#include "cMouse.h"
#include "cKeyboard.h"
#include "cLog.h"
cInputLayer* cInputLayer::instance = NULL;
cInputLayer* cInputLayer::GetInstance()
{
if (instance == NULL)
instance = new cInputLayer();
return instance;
}
/************************************************************************
Construction and destruction functions
************************************************************************/
cInputLayer::cInputLayer()
{
m_pDI = NULL;
m_pKeyboard = NULL;
m_pMouse = NULL;
}
cInputLayer::~cInputLayer()
{
Finalize();
}
/************************************************************************
cInput::Initialize()
Initializes the input system.
isExclusive set to true for exclusive mouse access
USE_KEYBOARD and USE_MOUSE are flags
************************************************************************/
bool cInputLayer::Init(HINSTANCE hInst, HWND hWnd, bool isExclusive, DWORD flags)
{
cLog *Log = cLog::Instance();
HRESULT hr;
// create DirectInput (DI) object
hr = DirectInput8Create(hInst,
DIRECTINPUT_VERSION, // defined in dinput.h
IID_IDirectInput8, // identifirer for desired DirectInput interface
(void **)&m_pDI, // pointer to variable that will point to requested
// interface, our main DirectObject for input
NULL); // for aggregration. unused so set to NULL
if(FAILED(hr))
{
Log->Error(hr,"Creating DI object");
return false;
}
if( flags & USE_KEYBOARD)
{
m_pKeyboard = new cKeyboard(m_pDI, hWnd);
if(m_pKeyboard == NULL)
{
Log->Msg("Error creating keyboard object!");
return false;
}
}
if( flags & USE_MOUSE)
{
m_pMouse = new cMouse(m_pDI, hWnd, isExclusive);
if(m_pMouse == NULL)
{
Log->Msg("Error creating mouse object!");
return false;
}
}
return true;
}
/************************************************************************
cInput::Finalize()
Releases objects, frees memory
************************************************************************/
bool cInputLayer::Finalize()
{
UnacquireAll();
if(m_pKeyboard)
{
delete m_pKeyboard;
m_pKeyboard = NULL;
}
if (m_pMouse)
{
delete m_pMouse;
m_pMouse = NULL;
}
if(m_pDI)
{
m_pDI->Release();
m_pDI = NULL;
}
return true;
}
/************************************************************************
cInput::Read()
Queries current state of devices
*************************************************************************/
bool cInputLayer::Read()
{
bool res=true;
cLog *Log = cLog::Instance();
if(m_pKeyboard)
{
res = m_pKeyboard->Read();
if(!res)
{
Log->Msg("Error reading from keyboard device!");
return false;
}
}
if(m_pMouse)
{
res = m_pMouse->Read();
if(!res)
{
Log->Msg("Error reading from mouse device!");
return false;
}
}
return res;
}
/************************************************************************
cInput::AcquireAll()
Makes sure all input devices are acquired
*************************************************************************/
void cInputLayer::AcquireAll()
{
if (m_pKeyboard)
m_pKeyboard->Acquire();
if (m_pMouse)
m_pMouse->Acquire();
}
/*************************************************************************
cInput::UnacquireAll()
Unacquires all devices
**************************************************************************/
void cInputLayer::UnacquireAll()
{
if (m_pKeyboard)
m_pKeyboard->Unacquire();
if (m_pMouse)
m_pMouse->Unacquire();
}
/*************************************************************************
Device queries
**************************************************************************/
cKeyboard* cInputLayer::GetKeyboard()
{
return m_pKeyboard;
}
cMouse* cInputLayer::GetMouse()
{
return m_pMouse;
}
bool cInputLayer::KeyDown(char key)
{
return m_pKeyboard->KeyDown(key);
}
bool cInputLayer::KeyUp(char key)
{
return m_pKeyboard->KeyUp(key);
}
bool cInputLayer::ButtonDown(int button)
{
return m_pMouse->ButtonDown(button);
}
bool cInputLayer::ButtonUp(int button)
{
return m_pMouse->ButtonUp(button);
}
void cInputLayer::GetMouseMovement(int *dx, int *dy)
{
m_pMouse->GetMovement(dx, dy);
}
int cInputLayer::GetMouseWheelMovement()
{
return m_pMouse->GetWheelMovement();
}
void cInputLayer::SetMousePosition(int xo, int yo)
{
m_pMouse->SetPosition(xo,yo);
}
void cInputLayer::GetMousePosition(int *xpos, int *ypos)
{
m_pMouse->GetPosition(xpos,ypos);
}
| [
"[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8",
"[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8"
]
| [
[
[
1,
146
],
[
148,
148
],
[
150,
159
],
[
161,
161
],
[
163,
207
]
],
[
[
147,
147
],
[
149,
149
],
[
160,
160
],
[
162,
162
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.