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
36dee0bc0ad145b365c693f467aab0e3cc98964a
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/Include/md_share2.h
8ac42c2b2f3faf716b7b62d3ead3d5024ad86db6
[]
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
29,620
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #if !defined(MD_SHARE2_H__35A13D43_76B6_4580_9346_73722745E1B7__INCLUDED_) #define MD_SHARE2_H__35A13D43_76B6_4580_9346_73722745E1B7__INCLUDED_ #include "md_share0.h" // ====================================================================== // Unit Model Field MF_xxx : unit model field flags information/options/etc for adding tags to the system... const MD_Flags MF_RESULT = DDEF_RESULT; //result field in access window const MD_Flags MF_PARAMETER = DDEF_PARAM; //input field in access window const MD_Flags MF_PARAM_STOPPED = (DDEF_PARAMSTOPPED|DDEF_PARAM); //input field in access window when solver is stopped const MD_Flags MF_SET_ON_CHANGE = DDEF_SETONCHANGE; //apply change on the input field immediatly const MD_Flags MF_NO_FILING = (DDEF_NOFILE|DDEF_NOSNAPSHOT|DDEF_NOSCENARIO); //field does not need to be saved/recovered to database const MD_Flags MF_NO_VIEW = DDEF_NOVIEW; //field not visible to user in access window const MD_Flags MF_INIT_HIDDEN = DDEF_HIDDEN; //field initialiy hidden const MD_Flags MF_NAN_OK = DDEF_NAN_OK; //for floating point fields, NAN (shown as * in access window) is allowed const MD_Flags MF_BUTTON = DDEF_BUTTON; //for bool fields, Present a button //const MD_Flags MF_ISRESULT = DDEF_RESULT; // this is a calculated field which goes invalid on any change const MD_Flags MF_HIDEIFZERO = DDEF_HIDEIFZERO; // hide this field if it is zero const MD_Flags MF_SMALLVALUE = DDEF_SMALLVALUE; const MD_Flags MF_Result = MF_RESULT; //result field in access window const MD_Flags MF_Parameter = MF_PARAMETER; //input field in access window const MD_Flags MF_ParamStopped = MF_PARAM_STOPPED; //input field in access window when solver is stopped const MD_Flags MF_SetOnChange = MF_SET_ON_CHANGE; //apply change on the input field immediatly const MD_Flags MF_NoFiling = MF_NO_FILING; //field does not need to be saved/recovered to database const MD_Flags MF_NoView = MF_NO_VIEW; //field not visible to user in access window const MD_Flags MF_InitHidden = MF_INIT_HIDDEN; //by default field initialiy hidden const MD_Flags MF_NanOK = MF_NAN_OK; //for floating point fields, NAN (shown as * in access window) is allowed const MD_Flags MF_Button = MF_BUTTON; //for bool fields, Present a button //const MD_Flags MF_ISRESULT = MF_ISRESULT; // this is a calculated field which goes invalid on any change const MD_Flags MF_HideIfZero = MF_HIDEIFZERO; // hide this field if it is zero const MD_Flags MF_SmallValue = MF_SMALLVALUE; // SMall values are expected use 'e' fmt // ====================================================================== // Data Definitions for Text equivalents of Integral Values const DWORD MDD_Hidden = 0x00000001; const DWORD MDD_Default = 0x00000002; const DWORD MDD_NoSelect = 0x00000004; struct MDDValueLst { long m_lVal; LPTSTR m_pStr; DWORD m_dwFlags; }; // ====================================================================== // Generalised Property infrastructure // Property Model Field MP_xxx : properies model field flags information/options/etc for adding tags to the system... const DWORD MP_Null = 0x00000000; const DWORD MP_Result = 0x00000000; //result field const DWORD MP_Parameter = 0x00000001; //input field const DWORD MP_ParamStopped = 0x00000002; //input field when solver is stopped const DWORD MP_NoFiling = 0x00000004; //field does not need to be saved/recovered to database const DWORD MP_NoView = 0x00000008; //field not visible to user in access window const DWORD MP_InitHidden = 0x00000010; //by default field initialiy hidden const DWORD MP_NanOK = 0x00000020; //for floating point fields, NAN (shown as * in access window) is allowed const DWORD MP_CheckBox = 0x00000040; //for bool fields, Present a checkbox const DWORD MP_NoAccess = 0x00008000; //not a field const DWORD MP_UserProp = 0x00010000; //belongs to user properties group const DWORD MP_ConfigProp = 0x00020000; //belongs to configuration group const DWORD MP_GlobalProp = 0x00040000; //belongs to global configuration group const DWORD MP_SoftMin = 0x10000000; const DWORD MP_SoftMax = 0x20000000; const DWORD MP_HardMin = 0x40000000; const DWORD MP_HardMax = 0x80000000; // ====================================================================== // Field data types MDT_xxx const unsigned char MDT_NULL = tt_NULL ; const unsigned char MDT_Bool = tt_Bool ; const unsigned char MDT_Bit = tt_Bit ; const unsigned char MDT_Byte = tt_Byte ; const unsigned char MDT_Word = tt_Word ; const unsigned char MDT_DWord = tt_DWord ; const unsigned char MDT_Char = tt_Char ; const unsigned char MDT_Int = tt_Int ; const unsigned char MDT_Short = tt_Short ; const unsigned char MDT_Long = tt_Long ; const unsigned char MDT_Flt16 = tt_Flt16 ; const unsigned char MDT_Float = tt_Float ; const unsigned char MDT_Double = tt_Double ; const unsigned char MDT_Generic = tt_Generic ; const unsigned char MDT_pChar = tt_pChar ; const unsigned char MDT_ppChar = tt_ppChar ; const unsigned char MDT_Strng = tt_Strng ; const unsigned char MDT_RqdPage = tt_RqdPage ; const unsigned char MDT_OptPage = tt_OptPage ; const unsigned char MDT_Column = tt_Column ; const unsigned char MDT_Grid = tt_Grid ; const unsigned char MDT_Grid_E = tt_Grid_E ; const unsigned char MDT_ColHdr = tt_ColHdr ; const unsigned char MDT_RowHdr = tt_RowHdr ; const unsigned char MDT_RowStart = tt_RowStart ; const unsigned char MDT_Text = tt_Text ; const unsigned char MDT_Struct = tt_Struct ; const unsigned char MDT_Element = tt_Element ; const unsigned char MDT_Object = tt_Object ; const unsigned char MDT_Array = tt_Array ; const unsigned char MDT_Struct_E = tt_Struct_E ; const unsigned char MDT_Element_E = tt_Element_E ; const unsigned char MDT_Object_E = tt_Object_E ; const unsigned char MDT_Array_E = tt_Array_E ; const unsigned char MDT_Blob = tt_Blob ; inline bool IsNumDataType(unsigned char iType) { return (iType>=MDT_Bool && iType <= MDT_Generic); }; inline bool IsIntDataType(unsigned char iType) { return (iType>=MDT_Bool && iType <= MDT_Long); }; inline bool IsFloatDataType(unsigned char iType) { return (iType>=MDT_Flt16 && iType <= MDT_Double); }; inline bool IsStrngDataType(unsigned char iType) { return (iType>=MDT_pChar && iType <= MDT_Strng); }; // ====================================================================== // // // // ====================================================================== #undef DllImportExport #if defined(__DATATYPE_CPP) #define DllImportExport __declspec(dllexport) #elif !defined(SCDLIB) #define DllImportExport __declspec(dllimport) #else #define DllImportExport #endif // MTagIO constants for options used in class MTagIO see md_method.h //enum { MTagIO_Int, MTagIO_Double, MTagIO_String }; const long MTagIO_Get = 0x00000001; const long MTagIO_Set = 0x00000002; const long MTagIO_Parm = 0x00000004; const long MTagIO_HoldChecks = 0x00000008; enum MTagIOType { MTagType_Null, MTagType_Long, MTagType_Double, MTagType_String, }; enum MTagIOResult { MTagIO_OK = -1, MTagIO_NotSpecified = -2, MTagIO_NotFound = -3, MTagIO_BadDataType = -4, MTagIO_NotAllowed = -5, MTagIO_ReadOnly = -6, MTagIO_BadCnv = -7, MTagIO_WriteFail = -8, MTagIO_NoSpace = -9, MTagIO_InternalError = -10, MTagIO_GlblConnectBusy = -11, MTagIO_FileIOBusy = -12 }; class PkDataUnion; class MCnv; class DllImportExport MTagIOValue { public: MTagIOValue(); MTagIOValue(long L); MTagIOValue(double D); MTagIOValue(LPCSTR S); MTagIOValue(const MTagIOValue & V); ~MTagIOValue(); MTagIOValue & operator=(const MTagIOValue & V); MTagIOValue & operator=(const PkDataUnion & V); bool operator==(const MTagIOValue & V); bool operator!=(const MTagIOValue & V); MTagIOType getTIOType() const; void putTIOType(MTagIOType T); long getLong() const; void putLong(long L); double getDoubleSI() const; void putDoubleSI(double D); double getDoubleCnv(const MCnv * pCnv) const; void putDoubleCnv(const MCnv * pCnv, double D); LPCSTR getString() const; void putString(LPCSTR S); void Reset(); CString AsString() const; __declspec(property(get=getTIOType,put=putTIOType)) MTagIOType TIOType; __declspec(property(get=getLong,put=putLong)) long Long; __declspec(property(get=getDoubleSI,put=putDoubleSI)) double DoubleSI; __declspec(property(get=getDoubleCnv,put=putDoubleCnv)) double DoubleCnv[]; __declspec(property(get=getString,put=putString)) LPCSTR String; protected: MTagIOType m_TIOType; long m_Long; double m_Double; CString m_String; //PkDataUnion * m_pData; //PkDataUnion * m_pData; }; // ====================================================================== const long AH_Active = 0x01; const long AH_Hold = 0x02; // ====================================================================== // // // // ====================================================================== #undef DllImportExport #if defined(__PROPERTYBASE_CPP) #define DllImportExport __declspec(dllexport) #elif !defined(SCDLIB) #define DllImportExport __declspec(dllimport) #else #define DllImportExport #endif const long MPI_EndOfProps = -1; const long MPI_MoreProps = -2; class DllImportExport MPropertyInfo { public: class MStringValueP { public: LPCSTR m_sID; long m_iValue; DWORD m_dwFlags; }; class MStringValueS { public: CString m_sID; long m_iValue; DWORD m_dwFlags; }; public: MPropertyInfo(); MPropertyInfo(ePropertyTypes iType, LPCTSTR sTag, LPCTSTR sSym, short iCnv, LPCTSTR sCnv, double dMin, double dMax, ULONG dwFlags, LPCTSTR sDesc ); void Set(ePropertyTypes iType, LPCTSTR sTag, LPCTSTR sSym, short iCnv, LPCTSTR sCnv, double dMin, double dMax, ULONG dwFlags, LPCTSTR sDesc ); void Set(ePropertyTypes iType, LPCTSTR sTag, LPCTSTR sSym, MStringValueP * StrValues, ULONG dwFlags, LPCTSTR sDesc ); void SetStructName(LPCTSTR Nm, ULONG dwFlags = MP_ConfigProp, LPCTSTR TableSuffix=NULL); void SetText(LPCTSTR Txt, ULONG dwFlags = 0); void SetPage(LPCTSTR Txt, ePropertyPageTypes Pg, ULONG dwFlags = 0); bool Settable() { return (m_dwFlags & (MP_Parameter|MP_ParamStopped))!=0; }; bool UserGrp() { return (m_dwFlags & MP_UserProp)!=0; }; bool ConfigGrp() { return (m_dwFlags & MP_ConfigProp)!=0; }; bool GlobalGrp() { return (m_dwFlags & MP_GlobalProp)!=0; }; bool HasSoftMin() { return (m_dwFlags & MP_SoftMin )!=0; }; bool HasSoftMax() { return (m_dwFlags & MP_SoftMax )!=0; }; bool HasHardMin() { return (m_dwFlags & MP_HardMin )!=0; }; bool HasHardMax() { return (m_dwFlags & MP_HardMax )!=0; }; double HardMin() { return m_dMin; }; double HardMax() { return m_dMax; }; public: // Variables particular to the Property ePropertyTypes m_iType; CString m_sTag; CString m_sSym; short m_iCnv; CString m_sCnv; double m_dMin; double m_dMax; ULONG m_dwFlags; CString m_sDesc; CArray <MStringValueS, MStringValueS&> m_StrValues; // Variables for Extra's Prior to the Text CString m_sStruct; CString m_sTableSuffix; CString m_sText; byte m_ePgOpt; bool m_bIsObject; }; // ---------------------------------------------------------------------- class DllImportExport MPropertyValue { public: MPropertyValue(void) { m_eType=ePT_Null; }; MPropertyValue(bool V) { *this=V; }; MPropertyValue(int V) { *this=V; }; MPropertyValue(long V) { *this=V; }; MPropertyValue(ULONG V) { *this=V; }; MPropertyValue(double V) { *this=V; }; MPropertyValue(LPCTSTR V) { *this=V; }; MPropertyValue(LPTSTR V) { *this=V; }; ~MPropertyValue(void) {}; ePropertyTypes Type() { return m_eType; }; operator bool(); operator int(); operator long(); //operator ULONG(); operator double(); operator LPCTSTR(); operator LPTSTR(); MPropertyValue & operator=(bool V); MPropertyValue & operator=(int V); MPropertyValue & operator=(long V); MPropertyValue & operator=(ULONG V); MPropertyValue & operator=(double V); MPropertyValue & operator=(LPCTSTR V); MPropertyValue & operator=(LPTSTR V); protected: ePropertyTypes m_eType; long m_Long; ULONG m_ULong; double m_Double; CString m_String; }; // ====================================================================== // // // // ====================================================================== #undef DllImportExport #if defined(__MD_DEFN_CPP) #define DllImportExport __declspec(dllexport) #elif !defined(DEVLIB) #define DllImportExport __declspec(dllimport) #else #define DllImportExport #endif /* Class MCnv: Engineering conversion.*/ class /*DllImportExport*/ MCnv { public: MCnv(short Index=0, LPCTSTR Txt="") { m_Index=Index; m_Txt=Txt; }; MCnv & operator()(LPCTSTR Txt) { m_Txt=Txt; return *this; }; operator short() const { return m_Index; }; operator long() const { return m_Index; }; CCnvIndex getIndex() const { return m_Index; }; LPCTSTR getText() const { return m_Txt; }; __declspec(property(get=getIndex)) CCnvIndex Index; __declspec(property(get=getText)) LPCTSTR Text; public://protected: short m_Index; CString m_Txt; }; // Model Conversions MC_xxx : engineering conversion unit types... extern DllImportExport MCnv MC_ ; //dimensionless extern DllImportExport MCnv MC_None ; //dimensionless extern DllImportExport MCnv MC_Ang ; //Angle : rad extern DllImportExport MCnv MC_DP ; //Pressure Differcence : kPa extern DllImportExport MCnv MC_PpS ; //Pressure Slew Rate : kPa/s extern DllImportExport MCnv MC_PpM ; //Pressure Slew Rate : kPa/kg extern DllImportExport MCnv MC_PpVol ; //Pressure Slew Rate : kPa/m^3 extern DllImportExport MCnv MC_E ; //Energy : kJ extern DllImportExport MCnv MC_Frac ; //Fraction : extern DllImportExport MCnv MC_FracRate ; //Fraction Rate : %/s extern DllImportExport MCnv MC_Assay ; //Assay : extern DllImportExport MCnv MC_HCap ; //Heat Capacity : kJ/dC extern DllImportExport MCnv MC_HCapF ; // : kJ/dC/s extern DllImportExport MCnv MC_L ; //Length : m extern DllImportExport MCnv MC_Ldt ; //Velocity : m/s extern DllImportExport MCnv MC_M ; //Mass : kg extern DllImportExport MCnv MC_Qm ; //Mass Flow : kg/s extern DllImportExport MCnv MC_QmSlew ; //Mass Flow Slewrate : kg/s/s extern DllImportExport MCnv MC_Qv ; //Volumetric Flow : m^3/s extern DllImportExport MCnv MC_QvSlew ; //Volumetric Flow Slewrate: m^3/s/s extern DllImportExport MCnv MC_Qe ; //Enerygy Flow : kJ/s extern DllImportExport MCnv MC_NQv ; //Normal Volumetric Flow : Nm^3/s extern DllImportExport MCnv MC_NVol ; //Normal Volume : Nm^3 extern DllImportExport MCnv MC_P ; //Pressure : kPa extern DllImportExport MCnv MC_Pwr ; //Power : kJ/s extern DllImportExport MCnv MC_pS ; //Per unit time : /s extern DllImportExport MCnv MC_Rho ; //Density : kg/m^3 extern DllImportExport MCnv MC_T ; //Temperature : K extern DllImportExport MCnv MC_Time ; //Time : s extern DllImportExport MCnv MC_Vol ; //Volume : m^3 extern DllImportExport MCnv MC_WI ; //Work Index : kWs/kg extern DllImportExport MCnv MC_HMs ; //Enthalpy : kJ/kg extern DllImportExport MCnv MC_HMl ; //Molar Entalpy : kJ/kmol extern DllImportExport MCnv MC_HV ; //Volume Enthalpy : kJ/m^3 extern DllImportExport MCnv MC_HNV ; //Norm Volume Enthalpy : kJ/Nm^3 extern DllImportExport MCnv MC_SMs ; //Entrophy : kJ/kh.K extern DllImportExport MCnv MC_SMl ; //Molar Entropy : kJ/kmol.K extern DllImportExport MCnv MC_CpMs ; //Cp : kJ/kg.C extern DllImportExport MCnv MC_CpMl ; //Molar Cp : kJ/kmol.C extern DllImportExport MCnv MC_Conc ; //Concetration : kg/m^3 extern DllImportExport MCnv MC_Area ; //Area : m^2 extern DllImportExport MCnv MC_HTC ; //Heat Transfer Coeff : kW/m^2.K extern DllImportExport MCnv MC_HCond ; //Heat Conductivity : kW/m.K extern DllImportExport MCnv MC_UA ; //Heat Transfer : kW/K extern DllImportExport MCnv MC_dT ; //Change in Temperature : K extern DllImportExport MCnv MC_dTdt ; //Rate of change in temp : C/s extern DllImportExport MCnv MC_I ; //Current : A extern DllImportExport MCnv MC_V ; //Potential Diff : V extern DllImportExport MCnv MC_PwrM ; //Specific Power(Pwr/Mass): W/kg extern DllImportExport MCnv MC_Visc ; //Viscosity : Ns/m^2 extern DllImportExport MCnv MC_MpL ; //Mass Loading : kg/m extern DllImportExport MCnv MC_KgMl ; //Moles : kmol extern DllImportExport MCnv MC_QKgMl ; //Molar Flow : kmol/s extern DllImportExport MCnv MC_Cond ; //Conductivity : S/m extern DllImportExport MCnv MC_SpCnt ; //SpecificCOunt : #/kg extern DllImportExport MCnv MC_Cnt ; //Count : # extern DllImportExport MCnv MC_CntRate ; //CountRate : #/s extern DllImportExport MCnv MC_SurfTens ; //Surface Tension : N/m extern DllImportExport MCnv MC_EntRate ; //EntrainRate : %.s/kg extern DllImportExport MCnv MC_DPperVol ; //PressDropPerVolFlow : kPa/m^3/s extern DllImportExport MCnv MC_SurfAreaM; //Surface Area(Mass) : m^2/g extern DllImportExport MCnv MC_SurfAreaL; //Surface Area(Volume) : m^2/L extern DllImportExport MCnv MC_FracSol ; //Fraction(Solids) : extern DllImportExport MCnv MC_FracLiq ; //Fraction(Liquids) : extern DllImportExport MCnv MC_FracVap ; //Fraction(Vapour) : extern DllImportExport MCnv MC_ThermTau ; //Thermal TimeConst : dC/s.C extern DllImportExport MCnv MC_CosPhi ; //Power Factor : Cos(<) extern DllImportExport MCnv MC_Ohms ; //Electrical Resistance : Ohms extern DllImportExport MCnv MC_Bytes ; //Memory Size : bytes extern DllImportExport MCnv MC_ConcRate ; //Concentration Change Rate: kg/m^3/s extern DllImportExport MCnv MC_KinVisc ; //Kinematic Viscosity (Stoke) : m^2/s extern DllImportExport MCnv MC_ElectVA ; //Electrical VA (V*A) : kVA extern DllImportExport MCnv MC_Humidity ; //Specific Humidity : kg(l)/kg(v) extern DllImportExport MCnv MC_Accel ; //Acceleration : m/s^2 extern DllImportExport MCnv MC_ThermDiff; //Thermal Diffusivity : m^2/s extern DllImportExport MCnv MC_Money ; //Money : Base extern DllImportExport MCnv MC_MoneyFlow; //Money Flow : Base/s //"special" time string conversions: extern DllImportExport MCnv MC_TimeStr ; //Time String : s extern DllImportExport MCnv MC_dTimeStr ; //Time String Difference : s class MCnvFamily; // forward class MCnvs; // forward class DllImportExport MCnvItem { public: MCnvItem(); MCnvItem(MCnvFamily iFamily, int iItem); bool Valid() { return m_iFamily>=0 && m_iItem>=0; } //return Name for specified conversion LPCTSTR Name(); //return scale for specified conversion double Scale(); //return offset for specified conversion double Offset(); protected: CCnvIndex m_iFamily; int m_iItem; }; class DllImportExport MCnvFamily { public: MCnvFamily(CCnvIndex iFamily=-1); bool Valid() { return m_iFamily>=0; } // return the Primary name LPCTSTR Name(); // return the number of secondary cnv's int Count(); // return the iSecCnv'th secondary cnv MCnvItem operator[](int iItem); //return index of specified conversion secondary name MCnvItem Find(LPCTSTR Name); operator CCnvIndex() { return m_iFamily; } protected: CCnvIndex m_iFamily; }; /* Class MCnvs: Helper class for accessing collection of engineering conversions.*/ class DllImportExport MCnvs { public: MCnvs(); //try create a valid conversion for the suplied string bool Create(LPCTSTR NameCnv, MCnv & Cnv); //return Name for specified conversion LPCTSTR Name(const MCnv & Cnv); //return scale for specified conversion double Scale(const MCnv & Cnv); //return offset for specified conversion double Offset(const MCnv & Cnv); //return number of Cnvs int Count(); //return the iPriCnv'th conversion MCnvFamily operator[](MCnvFamily iFamily); //return index of specified conversion family name MCnvFamily Find(LPCTSTR FamilyName); MCnvItem Find(LPCTSTR FamilyName, LPCTSTR ItemName); }; //The global instance of the engineering conversion collection helper class: extern DllImportExport MCnvs gs_Cnvs; //--------------------------------------------------------------------------- // Forward declarations... class TaggedObject; class CToleranceBlock; class SpPropOveride; class SpMArray; class DllImportExport MToleranceBlock { public: MToleranceBlock(DWORD Use, LPCTSTR Name, double Abs, double Rel, long MaxIters=100, DWORD Flags=(TBF_UseMax|TBF_UseAbs|TBF_UseRel), CCnvIndex AbsIndex=MC_Frac, LPCTSTR AbsTxt="%"); virtual ~MToleranceBlock(); void SetMaxIters(double MaxIters); void SetAbs(double Abs); void SetRel(double Rel); void SetAbsMult(double Abs); void SetRelMult(double Rel); void SetFlags(DWORD Flags); LPCTSTR GetName(); long GetMaxIters(); double GetAbs(); double GetRel(); double GetAbsMult(); double GetRelMult(); double GetNormalError(); double GetRelativeError(); DWORD GetFlags(); bool UseMax(); bool UseAbs(); bool UseRel(); bool Hide(); bool UseMaxParent(); bool UseAbsParent(); bool UseRelParent(); bool HasParent(); bool ConvergedDV(double D, double V); bool ConvergedVV(double V1, double V2); operator CToleranceBlock&() { return *m_TolBlk; } protected: CToleranceBlock * m_TolBlk; }; //--------------------------------------------------------------------------- #undef DllImportExport #if defined(__MATHLIBTO_CPP) #define DllImportExport __declspec(dllexport) #elif !defined(SCDLIB) #define DllImportExport __declspec(dllimport) #else #define DllImportExport #endif const int RF_OK = 0; const int RF_LoLimit = 1; const int RF_HiLimit = 2; const int RF_BadEstimate = 3; const int RF_BadStartValues = 4; const int RF_NotStarted = 5; const int RF_NotConverged = 6; const int RF_EstimateOK = 7; const int RF_EstimateLoLimit = 8; const int RF_EstimateHiLimit = 9; const int RF_Independant =10; // Root Finder Class class DllImportExport MRootFinderBase { public: MRootFinderBase(char *DescStr, CToleranceBlock & Tol); virtual int Start(double X1, double X2, double Fn1=dNAN, double Fn2=dNAN, bool RetIndependant=false); virtual double Function(double x) = 0; virtual int Solve_Brent(); virtual int SolveFromEst(double Est, double Sign, double dChgFrac=0.01, double dChgInit=dNAN); virtual bool Converged(double X1, double X2, double Fn1, double Fn2); virtual LPCTSTR ObjTag() { return ""; }; virtual void Limits(double X1, double X2) { xmin=X1; xmax=X2; bLimits=1; }; void SetTarget(double FunctionTarget) { dTarget=FunctionTarget; }; void SetEstimate(double Est, double EstSlp) { dEst=Est; dEstSlp=EstSlp; bEstSet=1; }; double EstimatedSlope() { return dEstSlp; }; double Result() { return dResult; }; double Target() { return dTarget; }; double FuncValue() { return m_FnVal; }; double FuncError() { return m_FnErr; }; int Error() { return iError; }; int Iterations() { return iter; }; bool Converging() { return iter>=0; }; bool TestingLimits() { return iter==-1; }; bool TestingEstimate() { return iter==-2; }; void SetLimits(double Min, double Max) { dMin=Min; dMax=Max; }; void SetErrorHandling(bool LogErrors, bool * MRootFinderBusy); static LPCTSTR ResultString(int ErrorRet); protected: LPCTSTR pDescStr; bool bLogErrors; bool * pMRootFinderBusy; int iError; double dTarget; double dResult; double m_FnVal; double m_FnErr; private: double x1, x2, xmin, xmax; double m_Err1, m_Err2, m_Val1, m_Val2; bool bStarted, bLimits, bConverged; bool bEstSet; double dEst, dEstSlp; int iter; double dMin, dMax; CToleranceBlock & m_Tol; }; class DllImportExport MRootFinder: public MRootFinderBase { public: MRootFinder(char *DescStr, CToleranceBlock & Tol) : MRootFinderBase(DescStr, Tol) { }; int FindRoot(double FnTarget, double XLoBnd, double XHiBnd, double XEst=dNAN, double XEstSlope=1.0, bool RetIndependant=false); int FindRootEst(double FnTarget, double XLoBnd, double XHiBnd, double XEst, double XEstSlope=1.0, double ChgMax=0.0, double ChgInit=0.0); }; // ----------------------------------------------------------- #undef DllImportExport // ====================================================================== // // // // ====================================================================== #endif // !defined(MD_SHARE2_H__35A13D43_76B6_4580_9346_73722745E1B7__INCLUDED_)
[ [ [ 1, 7 ], [ 9, 12 ], [ 38, 40 ], [ 44, 70 ], [ 115, 118 ], [ 209, 348 ], [ 350, 354 ], [ 357, 358 ], [ 373, 385 ], [ 387, 423 ], [ 425, 448 ], [ 536, 547 ], [ 551, 565 ], [ 567, 569 ], [ 571, 578 ], [ 580, 583 ], [ 588, 610 ], [ 612, 616 ], [ 618, 619 ], [ 621, 624 ], [ 626, 627 ], [ 629, 641 ], [ 665, 673 ], [ 676, 688 ] ], [ [ 8, 8 ], [ 71, 93 ], [ 99, 114 ], [ 119, 119 ], [ 130, 130 ], [ 208, 208 ], [ 355, 355 ], [ 424, 424 ], [ 449, 450 ], [ 454, 456 ], [ 507, 507 ], [ 517, 517 ], [ 519, 519 ], [ 530, 530 ], [ 533, 533 ] ], [ [ 13, 37 ], [ 41, 43 ], [ 94, 98 ], [ 120, 129 ], [ 131, 207 ], [ 349, 349 ], [ 356, 356 ], [ 359, 372 ], [ 386, 386 ], [ 451, 453 ], [ 457, 506 ], [ 508, 516 ], [ 518, 518 ], [ 520, 529 ], [ 531, 532 ], [ 534, 535 ], [ 548, 550 ], [ 566, 566 ], [ 570, 570 ], [ 579, 579 ], [ 584, 587 ], [ 611, 611 ], [ 617, 617 ], [ 620, 620 ], [ 625, 625 ], [ 628, 628 ], [ 642, 664 ], [ 674, 675 ] ] ]
3cbce965292953743db0a46909261b70a48f8d26
7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b
/maelstrom/wizards/AssetDB/assetdbinfo.h
c82ae7124a0a93540fa9d364e76950b3bbe16e8d
[]
no_license
wangscript/maelstrom-editor
c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31
5bfab31bf444f44b9f8209f4deaed8715c305426
refs/heads/master
2021-01-10T01:37:00.619456
2011-11-21T23:17:08
2011-11-21T23:17:08
50,160,495
0
0
null
null
null
null
UTF-8
C++
false
false
175
h
#ifndef ASSETDBINFO_H #define ASSETDBINFO_H #include <QWizardPage> class AssetDbInfo : public QWizardPage { public: AssetDbInfo(); }; #endif // ASSETDBINFO_H
[ [ [ 1, 11 ] ] ]
3c401cf227585941ca7e126df0cc00780c79a278
3bfe835203f793ee00bdf261c26992b1efea69ed
/fall07/cs300/a2 [phong lighting]/scenelib.h
eba02bfacc169641dbbb151f444a248beb14416b
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
WINDOWS-1252
C++
false
false
8,587
h
/////////////////////////////////////////////////////////////////////// // $Id: scenelib.h 1016 2007-06-12 17:07:55Z gherron $ // // Operations for building a scene full of objects, their geometry, // colors, textures and such. // // Gary Herron // // Copyright © 2007 DigiPen Institute of Technology //////////////////////////////////////////////////////////////////////// using namespace std; #include <assert.h> int invert(Matrix4x4* mat, Matrix4x4* inv); //////////////////////////////////////////////////////////////////////// // A texture map has height, width, and channel sizes and a large // float array. class Texture { public: int width; // Width of texel array int height; // Height of texel array int channels; // Number of colors/values per texel float* texels; // Array of width*height*channels floats void* processed; // Unused -- for student use // Use this method to access a single float value in the Texture. // Parameters (i,j) index a texel, parameter k indexes a single // channel of that texel. float* texel(int i, int j, int k); // Acces hints: // texture.texel(i,j,0) -- pointer to red channel value // texture.texel(i,j,1) -- pointer to green channel value // texture.texel(i,j,2) -- pointer to blue channel value // // texture.texel(i,j,0) -- pointer to RGB triple // // texture.texel(i,j,0) -- pointer to bump map single height value // Constructor and setters used by the framework to build a texture Texture(int w, int h, int c); void set(int i, int j, Color& c); void set(int i, int j, float v); }; //////////////////////////////////////////////////////////////////////// // Various specializations of Texture for specific uses. class ReflTexture: public Texture { public: ReflTexture(); }; class TileTexture: public Texture { public: TileTexture(int w, int h); }; class TileBump: public Texture { public: double s(int k) { return pow(double(k), 0.25); } TileBump(int w, int h); }; class WoodTexture: public Texture { public: WoodTexture(int w, int h); }; //////////////////////////////////////////////////////////////////////// // Class Vertex reperesents one vertex on a polygon. class Vertex { public: Vector4D V; // Vertex's position Vector3D N; // Vertex's normal float u,v; // Vertex's texture coordinates int prevIndex; // Index of edge's other end vertex }; //////////////////////////////////////////////////////////////////////// // An APolygon is a list (of type std::vector<>) of vertex's (Named // APolygon because MS compilers choke on things named Polygon). typedef std::vector<Vertex> APolygon; //////////////////////////////////////////////////////////////////////// // An Object contains a list of polygons and color and texture info class Object { public: std::vector<APolygon> polygons; // List of polygons defining this object. Color Kd; // Object's diffuse color Color Ks; // Object's specular color int n; // Object's Phong shininess exponent Texture* texture; // Texture map -- may be NULL Texture* bump; // Bump height map -- may be NULL Texture* refl; // Reflection map -- may be NULL bool closed; // Object is back-face cullable. }; //////////////////////////////////////////////////////////////////////// // A light contains a Vector3D position and a Color. class Light { public: Point3D position; Color color; }; //////////////////////////////////////////////////////////////////////// // A LightList is a list (of type std::vector<>) of Light's typedef std::vector<Light> LightList; //////////////////////////////////////////////////////////////////////// // Class Transformation implements a Matrix4x4 along with the usual // methods to build a transformation from primitives, plus the ability // to push and pop the matrix onto a stack. class Transformation { public: Transformation(); // Constructor -- yields an identity // Standard graphics pipeline matrix stack operations void Push(); void Pop(); // Standard graphics pipeline operations to build the transformation. void Identity(); void RotateX(float theta); void RotateY(float theta); void RotateZ(float theta); void Scale(float sx, float sy, float sz); void Translate(float tx, float ty, float tz); void Perspective(float sx, float sy, float front, float back); // Called to compute the inverse transformation when the foreard // transformation is finsihed being built. void ComputeInverse() { invert(&curr, &inv); } // Methods to (forward) transform a point. Vector4D Transform(Vector4D& V); Vector4D Transform(const Vector4D& V); // Methods to back-transform a point. Vector4D InverseTransform(Vector4D& V); Vector4D InverseTransform(const Vector4D& V); // Get matrix as a float* for passing to OpenGL void ArrayForOpenGL(float* array16); private: Matrix4x4 curr; // The current transformation Matrix4x4 inv; // Its inverse std::vector<Matrix4x4> matrixStack; // A stack for Push/Pop methods. }; //////////////////////////////////////////////////////////////////////// // Class Scene represents a whole scene as a list of polygons, and // contains several state variables and methods used to build up a // scene. class Scene { public: bool EnableLighting; // Compute (or not) Phong lighting bool EnableFlatShading; // Do (or not) normal interpolation bool UseOpenGLRendering; // Toggled via the 'g' key. bool UseFastRendering; // Toggled when doing an interactive transform bool UseAntiAliasing; // Toggled via the 'a' key. Color ambient; // The scene's ambient color LightList lights; // The scene's list of lights std::vector<Object> objects; // The scene's list of Objects Transformation viewing; // The interactive viewing transformation Transformation projection; // The interactive perspective transformation // The following parameters and methods are used by the scene // building code. By the time the framework is running these // parameters have no useful values, and the methods will no // longer be called. Just ignore them! Transformation modeling; Vector3D currentNormal; Color currentKd; Color currentKs; int currentExpn; int currentStartIndex; Texture* currentTexture; Texture* currentBump; Texture* currentRefl; float currentU, currentV; Scene(); void Clear(); void SetAmbient(const Color); void AddLight(const Point3D, const Color); void NewObject(bool closed=false); void NewPolygon(); void Hole(); void Vertex(Point3D); void SetNormal(Vector3D); void SetColor(Color Kd, Color Ks, int n); void SetTexture(Texture* texture, Texture* bump=NULL, Texture* refl=NULL); void SetTexCoord(float u, float v); }; void CreateRectangularPrism(Scene& scene, double l, double w, double h); void CreateCone(Scene& scene, double r, double l, double count); void CreateCylinder(Scene& scene, double r, double l, double count); void CreateSphereOctant(Scene& scene, double r, double count); void CreateSphere(Scene& scene, double r, double count, float theta=2*PI, float phi=PI); void CreateLetterA(Scene& scene); void Reflector(Scene& scene, int n, int m); void CreateRect(Scene& scene, double l, double w); //////////////////////////////////////////////////////////////////////// // The framework will call CreateScene once during startup to create // the scene as a list of polygons. It will then call PreprocessScene // once to allow the user to execute any scene preprocessing code. // // Note: Each class project will come with a project specific version // of CreateScene to create a scene appropriate to the project. // // Note: Each class project will also come with a scene specific // procedure to draw the scene using OpenGL called // DrawSceneWithOpenGL. Student code can toggle between their own // rendering code and DrawSceneWithOpenGL for comparisson purposes. // void CreateScene(Scene& scene); void PreprocessScene(Scene& scene); void DrawSceneWithOpenGL(Scene& scene, int width, int height); //////////////////////////////////////////////////////////////////////// // The framework will call DrawScene whenever the scene needs to be // redrawn, because either the window has been exposed, or a // mouse/keyboard interaction requires it. // // Note: Most student code will be implemented in DrawScene. // void DrawScene(Scene& scene, int width, int height);
[ [ [ 1, 247 ] ] ]
bf28043d3ff975ea5e4c74d43479a0b7819f9c99
9e2c39ce4b2a226a6db1f5a5d361dea4b2f02345
/tools/LePlatz/DataModel/DataStructs/BgPlatform.cpp
ec131580c1d2674df9ffc84050d8c7bb178b28ad
[]
no_license
gonzalodelgado/uzebox-paul
38623933e0fb34d7b8638b95b29c4c1d0b922064
c0fa12be79a3ff6bbe70799f2e8620435ce80a01
refs/heads/master
2016-09-05T22:24:29.336414
2010-07-19T07:37:17
2010-07-19T07:37:17
33,088,815
0
0
null
null
null
null
UTF-8
C++
false
false
3,446
cpp
/* * LePlatz - A level editor for the Platz toolset (Uzebox - supports VIDEO_MODE 3) * Copyright (C) 2009 Paul McPhee * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "WorldItem.h" #include "BgPlatform.h" QString BgPlatform::platformFlagsToString(const int &flags) { if (flags&Smooth) return "MP_SMOOTH"; else return "MP_STEPPED"; } BgPlatform::BgPlatform() : WorldItem(0), clrTile(0), platformFlags(Smooth), vel(0) { platformData = ""; WorldItem::worldStats.platformCount++; } BgPlatform::BgPlatform(const QList<QVariant> &data, WorldItem* parent) : WorldItem(parent), clrTile(0), platformFlags(Smooth), vel(0) { if (data.length() > 0) platformData = data[0].toString(); else platformData = ""; WorldItem::worldStats.platformCount++; } WorldItem* BgPlatform::createItem(const QList<QVariant> &data, WorldItem *parent) { BgPlatform *bgp = new BgPlatform(data, (parent) ? parent : this->parent()); if (bgp) { bgp->setClearTile(clrTile); bgp->setFlags(platformFlags); bgp->setVelocity(vel); bgp->setRelativeBoundingRect(relativeBoundingRect()); if (graphicalRepresentation()) bgp->setGraphicalRepresentation(new PlatzGraphicsItem(bgp, graphicalRepresentation()->mode())); } return bgp; } QVariant BgPlatform::data(int column) const { if (column == 0) return QVariant(platformData + " " + QString::number(row())); else return QVariant(""); } QVariant BgPlatform::dataDecoration(int) const { return QVariant(WorldItem::worldItemIcon(WorldItem::PlatformIcon)); } QVariant BgPlatform::tooltipData(int column) const { return data(column); } QString BgPlatform::detailData() const { QString details; if (platformFlags == Smooth) details = "Platform Movement: Smooth"; else details = "Platform Movement: Stepped"; details += "\tVelocity: " + QString::number(vel); details += "\nClear Tile: " + clrTile; return details; } WorldItem::WorldItemType BgPlatform::type() const { return WorldItem::Platform; } bool BgPlatform::validChild(const WorldItem::WorldItemType&) const { return false; } void BgPlatform::setData(const QVariant &data) { platformData = data.toString(); } qreal BgPlatform::offsetX() const { WorldItem *p = this->parent(); if (p) return p->offsetX() + p->relativeBoundingRect().left(); else return 0.0; } WorldItem* BgPlatform::validateState() { if (clearTile().isEmpty()) return this; return WorldItem::validateState(); } BgPlatform::~BgPlatform() { WorldItem::worldStats.platformCount--; }
[ "[email protected]@08aac7ea-4340-11de-bfec-d9b18e096ff9" ]
[ [ [ 1, 130 ] ] ]
d55aef92344be8bc28581b96b037566ce6594fa2
85c91b680d74357b379204ecf7643ae1423f8d1e
/branches/pre_mico_2_3-12/examples/general/philosopher/dinner_CutleryImpl/dinner_CutleryImpl.cpp
0283a5ad109ba0e75ed37b0921f6951f59e2fbf3
[]
no_license
BackupTheBerlios/qedo-svn
6fdec4ca613d24b99a20b138fb1488f1ae9a80a2
3679ffe8ac7c781483b012dbef70176e28fea174
refs/heads/master
2020-11-26T09:42:37.603285
2010-07-02T10:00:26
2010-07-02T10:00:26
40,806,890
0
0
null
null
null
null
UTF-8
C++
false
false
8,042
cpp
// // generated by Qedo // #include "dinner_CutleryImpl.h" // BEGIN USER INSERT SECTION file #include <iostream> #include "component_valuetypes.h" using namespace std; // END USER INSERT SECTION file namespace dinner { // BEGIN USER INSERT SECTION CutlerySessionImpl // END USER INSERT SECTION CutlerySessionImpl CutlerySessionImpl::CutlerySessionImpl() { // BEGIN USER INSERT SECTION CutlerySessionImpl::CutlerySessionImpl // END USER INSERT SECTION CutlerySessionImpl::CutlerySessionImpl } CutlerySessionImpl::~CutlerySessionImpl() { // BEGIN USER INSERT SECTION CutlerySessionImpl::~CutlerySessionImpl cout << "CutlerySessionImpl: Destructor called" << endl; // END USER INSERT SECTION CutlerySessionImpl::~CutlerySessionImpl } void CutlerySessionImpl::set_context(::dinner::CCM_Cutlery_ContextImpl_ptr context) throw (CORBA::SystemException, Components::CCMException) { context_ = ::dinner::CCM_Cutlery_ContextImpl::_duplicate(context); } void CutlerySessionImpl::configuration_complete() throw (CORBA::SystemException, Components::InvalidConfiguration) { // BEGIN USER INSERT SECTION CutlerySessionImpl::configuration_complete // END USER INSERT SECTION CutlerySessionImpl::configuration_complete } void CutlerySessionImpl::remove() throw (CORBA::SystemException) { // BEGIN USER INSERT SECTION CutlerySessionImpl::remove // END USER INSERT SECTION CutlerySessionImpl::remove } void CutlerySessionImpl::name(const char* param) throw(CORBA::SystemException) { // BEGIN USER INSERT SECTION CutlerySessionImpl::_name id_ = param; // END USER INSERT SECTION CutlerySessionImpl::_name } char* CutlerySessionImpl::name() throw(CORBA::SystemException) { // BEGIN USER INSERT SECTION CutlerySessionImpl::name return CORBA::string_dup (id_.c_str()); // END USER INSERT SECTION CutlerySessionImpl::name } // BEGIN USER INSERT SECTION Seg // END USER INSERT SECTION Seg Seg::Seg() { // BEGIN USER INSERT SECTION Seg::Seg in_use_ = false; // END USER INSERT SECTION Seg::Seg } Seg::~Seg() { // BEGIN USER INSERT SECTION Seg::~Seg cout << "Seg: Destructor called" << endl; // END USER INSERT SECTION Seg::~Seg } void Seg::set_context(::dinner::CCM_Cutlery_ContextImpl_ptr context) throw (CORBA::SystemException, Components::CCMException) { context_ = ::dinner::CCM_Cutlery_ContextImpl::_duplicate(context); } void Seg::configuration_complete() throw (CORBA::SystemException, Components::InvalidConfiguration) { // BEGIN USER INSERT SECTION Seg::configuration_complete // END USER INSERT SECTION Seg::configuration_complete } Components::Cookie* Seg::obtain_fork() throw(CORBA::SystemException, ::dinner::ForkNotAvailable) { // BEGIN USER INSERT SECTION Seg::obtain_fork cout << ".....obtain_fork called" << endl; if (in_use_) { cout << ".....fork already used" << endl; throw dinner::ForkNotAvailable(); } cout << ".....fork now used" << endl; in_use_ = true; // Normally we should store a cookie somewhere to check later, whether the caller // is allowed to relase the fork return new Cookie_impl(); // END USER INSERT SECTION Seg::obtain_fork } void Seg::release_fork(Components::Cookie* ck) throw(CORBA::SystemException, ::dinner::NotTheEater) { // BEGIN USER INSERT SECTION Seg::release_fork // We should first check the cookie ;-) in_use_ = false; // END USER INSERT SECTION Seg::release_fork } // BEGIN USER INSERT SECTION CutleryImpl // END USER INSERT SECTION CutleryImpl CutleryImpl::CutleryImpl() :component_(new CutlerySessionImpl()) , Seg_(new Seg()) { // BEGIN USER INSERT SECTION CutleryImpl::CutleryImpl // END USER INSERT SECTION CutleryImpl::CutleryImpl } CutleryImpl::~CutleryImpl() { // BEGIN USER INSERT SECTION CutleryImpl::~CutleryImpl cout << "CutleryImpl: Destructor called" << endl; // END USER INSERT SECTION CutleryImpl::~CutleryImpl component_->_remove_ref(); Seg_->_remove_ref(); } ::CORBA::Object* CutleryImpl::obtain_executor(const char* name) throw (CORBA::SystemException) { if (! strcmp ( name, "component" ) ) { return Components::EnterpriseComponent::_duplicate (component_); } else if (! strcmp (name, "the_fork")) { return Components::EnterpriseComponent::_duplicate (Seg_); } else if (! strcmp (name, "the_name")) { return Components::EnterpriseComponent::_duplicate (component_); } return Components::EnterpriseComponent::_nil(); } void CutleryImpl::release_executor(::CORBA::Object_ptr executor) throw (CORBA::SystemException) { CORBA::release (executor); } void CutleryImpl::configuration_complete() throw (CORBA::SystemException, Components::InvalidConfiguration) { component_->configuration_complete(); Seg_->configuration_complete(); // BEGIN USER INSERT SECTION CutleryImpl::configuration_complete // END USER INSERT SECTION CutleryImpl::configuration_complete } void CutleryImpl::set_session_context(::Components::SessionContext_ptr context) throw (CORBA::SystemException, Components::CCMException) { #ifdef TAO_ORB ::dinner::CCM_Cutlery_Context_ptr tmp_context; tmp_context = dynamic_cast<::dinner::CCM_Cutlery_ContextImpl*>(context); if (tmp_context) context_ = ::dinner::CCM_Cutlery_ContextImpl::_duplicate(tmp_context); else context_ = ::dinner::CCM_Cutlery_ContextImpl::_nil(); #else context_ = ::dinner::CCM_Cutlery_ContextImpl::_narrow(context); #endif component_->set_context(context_); Seg_->set_context(context_); } void CutleryImpl::ccm_activate() throw (CORBA::SystemException, Components::CCMException) { // BEGIN USER INSERT SECTION CutleryImpl::ccm_activate cout << "CutleryImpl: ccm_activate() called" << endl; // END USER INSERT SECTION CutleryImpl::ccm_activate } void CutleryImpl::ccm_passivate() throw (CORBA::SystemException, Components::CCMException) { // BEGIN USER INSERT SECTION CutleryImpl::ccm_passivate cout << "CutleryImpl: ccm_passivate() called" << endl; // END USER INSERT SECTION CutleryImpl::ccm_passivate } void CutleryImpl::ccm_remove() throw (CORBA::SystemException, Components::CCMException) { // BEGIN USER INSERT SECTION CutleryImpl::ccm_remove cout << "CutleryImpl: ccm_remove() called" << endl; // END USER INSERT SECTION CutleryImpl::ccm_remove } // BEGIN USER INSERT SECTION CutleryHomeImpl // END USER INSERT SECTION CutleryHomeImpl CutleryHomeImpl::CutleryHomeImpl() { // BEGIN USER INSERT SECTION CutleryHomeImpl::CutleryHomeImpl // END USER INSERT SECTION CutleryHomeImpl::CutleryHomeImpl } CutleryHomeImpl::~CutleryHomeImpl() { // BEGIN USER INSERT SECTION CutleryHomeImpl::~CutleryHomeImpl cout << "CutleryHomeImpl: Destructor called" << endl; int dummy = 0; CORBA::ORB_var orb = CORBA::ORB_init (dummy, 0); orb->unregister_value_factory ("IDL:omg.org/Components/Cookie:1.0"); // END USER INSERT SECTION CutleryHomeImpl::~CutleryHomeImpl } void CutleryHomeImpl::set_context(Components::HomeContext_ptr ctx) throw (CORBA::SystemException, Components::CCMException) { context_ = Components::HomeContext::_duplicate(ctx); } ::Components::EnterpriseComponent_ptr CutleryHomeImpl::create () throw (CORBA::SystemException, Components::CreateFailure) { // BEGIN USER INSERT SECTION CutleryHomeImpl::create cout << "CutleryHomeImpl: create() called" << endl; // END USER INSERT SECTION CutleryHomeImpl::create return new CutleryImpl(); } }; // // entry point // ::Components::HomeExecutorBase_ptr create_CutleryHomeE(void) { // BEGIN USER INSERT SECTION create_CutleryHome // END USER INSERT SECTION create_CutleryHome return new ::dinner::CutleryHomeImpl(); }
[ "tom@798282e8-cfd4-0310-a90d-ae7fb11434eb" ]
[ [ [ 1, 333 ] ] ]
cdaf7bc7c0ec97b2324e2a1abbda0e4cdd17407d
2139c9f6c7d201e394631dfd54a3e658269e9e68
/Resources/OpenGL/RenderBuffer.cpp
247bcc10104ae4699f3a0dd512df756a2ec85a28
[]
no_license
OpenEngineDK/branches-PostProcessing
294b87604d8d8e73b12ab7a6fd704a83ca33f3c9
2497ce3879973c410469618d2cf01b051bd4edbb
refs/heads/master
2020-12-24T21:10:50.209919
2009-04-27T10:12:37
2009-04-27T10:12:37
58,073,279
0
0
null
null
null
null
UTF-8
C++
false
false
8,499
cpp
#include "RenderBuffer.h" /* @author Bjarke N. Laustsen */ namespace OpenEngine { namespace Resources { /** Create a new 2D renderbuffer * @param width the renderbuffer width * @param height the renderbuffer height * @param format the renderbuffer format */ RenderBuffer::RenderBuffer(int width, int height, PixelFormat format) { this->rbID = 0; // must be done before calling createOrModifyRB! CreateOrModifyRB(width, height, format); } /** delete this renderbuffer */ RenderBuffer::~RenderBuffer() { glDeleteRenderbuffersEXT(1, &rbID); } /** bind this renderbuffer */ void RenderBuffer::Bind() { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, rbID); } /** unbind any renderbuffer (not only this one) * @note no need to call this method between bind calls */ void RenderBuffer::Unbind() { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); } /** get OpenGL handle of this renderbuffer */ int RenderBuffer::GetID() { return (int)rbID; } /** get the width of this renderbuffer * @returns the width */ unsigned int RenderBuffer::GetWidth() { GuardedBind(); // avoid side effects GLsizei width; glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_WIDTH_EXT, &width); GuardedUnbind(); return (int)width; } /** get the height of this renderbuffer * @returns the height */ unsigned int RenderBuffer::GetHeight() { GuardedBind(); // avoid side effects GLsizei height; glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_HEIGHT_EXT, &height); GuardedUnbind(); return (int)height; } /** get the depth of this renderbuffer (always 0) * @returns the depth */ int RenderBuffer::GetZDepth() { return 0; } /** get the bit-depth of this renderbuffer (not z-depth!!!) * @returns the bit-depth */ unsigned int RenderBuffer::GetDepth() { throw NotImplemented(); } /** get the internal format of this renderbuffer * @returns the internal format */ PixelFormat RenderBuffer::GetFormat() { GuardedBind(); // avoid side effects GLint internalFormat; glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_INTERNAL_FORMAT_EXT, &internalFormat); GuardedUnbind(); return GetOEInternalFormat(internalFormat); } /** Resize this renderbuffer (destructive resize - content will not be preserved) * @param width the new width * @param height the new height * * @note: content of renderbuffer will be trashed * @todo: keep the contents somehow. This will probably trash performance (when it's not needed), so make it optional. */ void RenderBuffer::Resize(int width, int height) { CreateOrModifyRB(width, height, GetFormat()); } /** Resize this renderbuffer and change internal format (destructive resize - content will not be preserved) * @param width the new width * @param height the new height * @param format the new internal format * * @note: content of renderbuffer will be trashed * @todo: keep the contents somehow. This will probably trash performance (when it's not needed), so make it optional. */ void RenderBuffer::Resize(int width, int height, PixelFormat format) { CreateOrModifyRB(width, height, format); } /** returns an array of unsigned chars of size width*height*numcomponents * you should delete the array with "delete" when you're done with it. * (returns arrays instead of vectors, because this is how it is in ITextureResource) */ unsigned char* RenderBuffer::GetData() { throw NotImplemented(); } /** returns an array of floats of size width*height*numcomponents * you should delete the array with "delete" when you're done with it. * (returns arrays instead of vectors, because this is how it is in ITextureResource) */ float* RenderBuffer::GetFloatData() { throw NotImplemented(); } /** expected array of the same size as the texture multiplied by num components: GetWidth()*GetHeight()*numcomp */ void RenderBuffer::SetData(unsigned char* data) { throw NotImplemented(); } /** expected array of the same size as the texture multiplied by num components: GetWidth()*GetHeight()*numcomp */ void RenderBuffer::SetFloatData(float* data) { throw NotImplemented(); } void RenderBuffer::CreateOrModifyRB(int width, int height, PixelFormat format) { if (rbID == 0) glGenRenderbuffersEXT(1, &rbID); GuardedBind(); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GetGLInternalFormat(format), GetGLWidth(width), GetGLHeight(height)); CheckGLErrors("createOrModifyRB"); GuardedUnbind(); } /* these returns opengl stuff depending on the instance vars */ GLint RenderBuffer::GetGLInternalFormat(PixelFormat format) { switch (format) { case RB_DEPTH: return GL_DEPTH_COMPONENT; case RB_STENCIL: return GL_STENCIL_INDEX; case RB_RGB: return GL_RGB; case RB_RGBA: return GL_RGBA; default: throw PPEResourceException("illegal format"); } } GLsizei RenderBuffer::GetGLWidth(int width) { return (GLsizei)width; } GLsizei RenderBuffer::GetGLHeight(int height) { return (GLsizei)height; } PixelFormat RenderBuffer::GetOEInternalFormat(GLint glInternalFormat) { switch (glInternalFormat) { case GL_DEPTH_COMPONENT: return RB_DEPTH; case GL_STENCIL_INDEX: return RB_STENCIL; case GL_RGB: return RB_RGB; case GL_RGBA: return RB_RGBA; default: throw PPEResourceException("illegal format2"); } } /** * Checks for OpenGL errors. * Extremely useful debugging function: When developing, * make sure to call this after almost every GL call. */ void RenderBuffer::CheckGLErrors (const char *label) { GLenum errCode; const GLubyte *errStr; if ((errCode = glGetError()) != GL_NO_ERROR) { errStr = gluErrorString(errCode); logger.error << "OpenGL ERROR: "; if (errStr != NULL) logger.error << errStr << "<errCode=" << errCode << ">"; else logger.error << "<NULL - errCode=" << errCode << ">"; logger.error << "(Label: " << label << ")\n." << logger.end; } //framebuffer specific stuff... nice 2 have GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch (status) { case GL_FRAMEBUFFER_COMPLETE_EXT: break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT : logger.error << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT (label:" << label << ")" << logger.end; break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT : logger.error << "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT (label:" << label << ")" << logger.end; break; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT : logger.error << "GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT (label:" << label << ")" << logger.end; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: logger.error << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT (label:" << label << ")" << logger.end; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: logger.error << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT (label:" << label << ")" << logger.end; break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT : logger.error << "GL_FRAMEBUFFER_UNSUPPORTED_EXT (label:" << label << ")" << logger.end; break; /* you gotta choose different formats */ case GL_INVALID_FRAMEBUFFER_OPERATION_EXT : logger.error << "GL_INVALID_FRAMEBUFFER_OPERATION_EXT (label:" << label << ")" << logger.end; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: logger.error << "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT (label:" << label << ")" << logger.end; break; default: logger.error << "UNKNOWN ERROR:" << status << logger.end; break; } } /** Get image type. This is IMG_RENDERBUFFER. * @returns IMG_RENDERBUFFER */ ImageType RenderBuffer::GetImageType() { // texture2D, renderbuffer, ... return IMG_RENDERBUFFER; } void RenderBuffer::GuardedBind() { if (savedRbID != 0) throw PPEResourceException("internal error"); // to prevent recursive-ish routines messing up the guardedBind glGetIntegerv(GL_RENDERBUFFER_BINDING_EXT, &savedRbID); if (rbID != (GLuint)savedRbID) // no need to bind if this RB is already bound glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, rbID); } void RenderBuffer::GuardedUnbind() { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, (GLuint)savedRbID); savedRbID = 0; } } // NS Resources } // NS OpenEngine
[ [ [ 1, 47 ], [ 49, 58 ], [ 60, 77 ], [ 80, 122 ], [ 124, 130 ], [ 132, 136 ], [ 138, 142 ], [ 144, 160 ], [ 162, 178 ], [ 180, 224 ], [ 226, 237 ] ], [ [ 48, 48 ], [ 59, 59 ], [ 78, 79 ], [ 123, 123 ], [ 131, 131 ], [ 137, 137 ], [ 143, 143 ], [ 161, 161 ], [ 179, 179 ], [ 225, 225 ] ] ]
1c1870461cd14f70fe3324ad5e1dcc08b5aa0bcc
0caca2bf0ec6c1b680d0bd50dd0855ffb78113fb
/src/engine/e_language.cpp
e9a44851472ff3d9b4777362fdfe751a97588454
[ "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
sanyaade-gamedev/zteeworlds
e029afd193476c25cb24090a31570c175f1668ba
73ad5e6d34d5639c67c93298f21dcd523b06bf73
refs/heads/master
2021-01-18T17:48:47.321015
2010-05-10T15:43:49
2010-05-10T15:43:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,383
cpp
#include "e_language.h" #include <stdlib.h> #include <stdio.h> #include <base/system.h> #include <string.h> #include "e_linereader.h" #include "e_engine.h" #include <vector> void format_replace(char * text) { int i = 0; int j = 0; int len = str_length(text); while (i < len) { if (text[i] == '\\' && text[i + 1] == '\\') { text[j] = '\\'; i += 2; j++; continue; } if (text[i] == '\\' && text[i + 1] == 'n') { text[j] = '\n'; i += 2; j++; continue; } if (text[i] == '\\' && text[i + 1] == 'r') { text[j] = '\r'; i += 2; j++; continue; } text[j] = text[i]; i++; j++; } mem_zero(text + j, len - j); } typedef struct LANGUAGE_ITEM { int gid; const char * str; const char * translated; bool delete_str; bool delete_translated; } LANGUAGE_ITEM; std::vector<LANGUAGE_ITEM *> language; void lang_init() { language.clear(); } void lang_free() { if (language.size() == 0) return; for (int i = 0; i < language.size(); i++) { if (language[i]) { if (language[i]->delete_str && language[i]->str) { free((void *)language[i]->str); language[i]->str = 0; } if (language[i]->delete_translated && language[i]->translated) { free((void *)language[i]->translated); language[i]->translated = 0; } } delete language[i]; language[i] = 0; } language.clear(); } int lang_load(const char * filename) { lang_free(); if (str_length(filename) == 0) return 1; IOHANDLE file; char fn_buf[512]; str_format(fn_buf, sizeof(fn_buf), "languages/%s", filename); file = engine_openfile(fn_buf, IOFLAG_READ); while(file) { int gid = -1; const char * str = 0; char *line = ""; LINEREADER lr; char buf[4096]; linereader_init(&lr, file); if (!(line = linereader_get(&lr))) // skiping language name { io_close(file); break; } while (line = linereader_get(&lr)) { format_replace(line); if (str_length(line) == 0 || line[0] == '\r' || line[0] == '\n') continue; if (!str) { sscanf(line, "%d", &gid); if (gid != -1) { int start = 0, len = str_length(line); while (line[len - 1] <= ' ' && len > 0) len--; while (line[start] >= '0' && line[start] <= '9') start++; if (line[start] != 0) { start++; if (line[start] != 0) { len -= start; mem_copy(buf, line + start, len); buf[len] = 0; } else buf[0] = 0; } else buf[0] = 0; str = buf; } } else { LANGUAGE_ITEM * langitem = new LANGUAGE_ITEM; langitem->gid = gid; langitem->str = strdup(str); langitem->translated = strdup(line); langitem->delete_str = true; langitem->delete_translated = true; language.push_back(langitem); gid = -1; str = 0; } } io_close(file); file = 0; dbg_msg("lang", "Language %s loaded", filename); return 0; } dbg_msg("lang", "Cannot load language %s", filename); return 1; } const char * _T(int gid, const char * str) { if (!str) return str; char buf[4096]; int start = 0, end = str_length(str); while (str[start] && (str[start] == ' ' || str[start] == '\n') && start < end) start++; mem_copy(buf, str + start, end - start + 1); end = str_length(buf) - 1; while (buf[end] && (buf[end] == ' ' || buf[end] == '\n') && end > 0) { buf[end] = 0; end--; }; if (language.size() > 0) { for (int q = 0; q < 2; q++) { for (int i = 0; i < language.size(); i++) { if (!language[i] || !language[i]->str) continue; if ((language[i]->gid == gid || q == 1) && strcmp(language[i]->str, buf) == 0) { if (language[i]->translated) return language[i]->translated; else return language[i]->str; } } } } LANGUAGE_ITEM * langitem = new LANGUAGE_ITEM; langitem->gid = gid; langitem->str = strdup(buf); langitem->translated = 0; langitem->delete_str = true; langitem->delete_translated = false; language.push_back(langitem); #ifdef CONF_DEBUG dbg_msg("lang", "%d %s", gid, str); #endif return str; } int get_gid(const char * str) { int q = 0; for (int i = 0; i < strlen(str); i++) { q = (q + str[i] * i)%65536; } return q; }
[ "Lite@17bf8faa-f2ac-4608-91d1-a55e81355a97" ]
[ [ [ 1, 216 ] ] ]
b666848a69643330d71fc4119f96b6bd8a6c8068
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/ChildFrm.h
db1b31e47d882073b56c06dc6078c9d1f8033e99
[]
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
14,034
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. */ // ChildFrm.h : interface of the CChildFrame class // ///////////////////////////////////////////////////////////////////////////// void sys_Printf(int Contents, const char *format, ...); extern CMainFrame *g_pMainWnd; #pragma once // Forward Defines. class IRCServer; class IRCChannel; class IRCQuery; class CChildFrame : public CChildCommon, public CListener, public CDropFilesHandler<CChildFrame> { private: int m_LastDirtyStatus; // used when updating GUI elements, like serverlist IRCUser *m_SelectedUserListUser; //used for userlist context menus. WindowPrefs *m_pWindowPrefs; // null until GetWindowPrefs is called int m_LastSize; // SIZE_*, see WM_SIZE Notification short m_InfoUpdateTicks; CSimpleArray<CTimerCommand*> m_TimerCommands; public: // from top to bottom CHeaderView m_HeaderView; CMsgView m_MsgView; CUserListView m_UserListView; CInfoView m_InfoView; CTextInputView m_TextInputView; // from top to bottom CHydraHorSplitterWindow m_HorizSplitter1; // used by HeaderView and m_VertSplitter1 CHydraHorSplitterWindow m_HorizSplitter2; // used by m_VertSplitter1 and InputView CHydraSplitterWindow m_VertSplitter1; // used by MessageView and m_HorizSplitter3 CHydraHorSplitterWindow m_HorizSplitter3; // used by Info and UserList views CHydraPaneContainer m_UserListPane; CHydraPaneContainer m_InfoPane; //CChildSplitter *m_pSplitter; IRCServer *m_pServer; IRCChannel *m_pChannel; IRCQuery *m_pQuery; char *m_StatusStr; BOOL m_FirstFocus; // there are unused color items in here which are not relevant to child windows COLORREF m_ColorPrefs[PREF_COLOR_MAX]; // ID's used when calling plugins (todo: use a union?) int m_ChannelID; int m_ServerID; int m_QueryID; int m_ScrollTickCount; void CChildFrame::OnEvent(int EventID, void *pData); CChildFrame(CEventManager *pEventManager, IRCServer *pServer); CChildFrame(CEventManager *pEventManager, IRCServer *pServer, IRCChannel *pChannel); CChildFrame(CEventManager *pEventManager, IRCServer *pServer, IRCQuery *pQuery); ~CChildFrame(); void GetWindowPrefs( void ); void Initialise( void ); void ActivateTextInputPane( void ); void ToggleUserList( void ); void ShowUserList( void ); void HideUserList( void ); BOOL IsUserListVisible( void ); void ToggleHeader( void ); void ShowHeader( void ); void HideHeader( void ); BOOL IsHeaderVisible( void ); void ToggleInfo( void ); void ShowInfo( void ); void HideInfo( void ); BOOL IsInfoVisible( void ); BOOL CanHaveInfo( void ) { return (m_WindowType == CWTYPE_SERVER || m_WindowType == CWTYPE_CHANNEL || m_WindowType == CWTYPE_QUERY || m_WindowType == CWTYPE_DCCCHAT) ? TRUE : FALSE; } BOOL CanHaveHeader( void ) { return (m_WindowType == CWTYPE_SERVER || m_WindowType == CWTYPE_CHANNEL || m_WindowType == CWTYPE_QUERY || m_WindowType == CWTYPE_DCCCHAT) ? TRUE : FALSE; } BOOL CanHaveUserList( void ) { return (m_WindowType == CWTYPE_SERVER || m_WindowType == CWTYPE_CHANNEL || m_WindowType == CWTYPE_QUERY || m_WindowType == CWTYPE_DCCCHAT) ? TRUE : FALSE; } BEGIN_MSG_MAP(CChildFrame) //sys_Printf(BIC_GUI,"message: 0x%08x - code: 0x08%x\n",uMsg, uMsg == WM_NOTIFY ? ((LPNMHDR)lParam)->code : 0); //if (uMsg == WM_NOTIFY) sys_Printf(BIC_GUI,"notify message: %x - code: %x\n",uMsg, ((LPNMHDR)lParam)->code); // custom messages MESSAGE_HANDLER(WM_TEXTINPUT, OnTextInput) // sent by the textinputview MESSAGE_HANDLER(WM_HEADERCHANGED, OnHeaderChanged) // sent by the headerview MESSAGE_HANDLER(WM_UPDATEINFOPANE, OnUpdateInfoPane) // sent by anything MESSAGE_HANDLER(WM_NETEVENT, OnNetEvent) // sent by m_pSocket MESSAGE_HANDLER(WM_DNSEVENT, OnDNSEvent) // sent by m_pSocket MESSAGE_HANDLER(WM_BUFFERWAITING, OnBufferWaiting) // sent by AddToBuffer() MESSAGE_HANDLER(WM_PROCESSQUEUEWAITING,OnProcessQueue) #ifdef USE_TABBEDMDI MESSAGE_HANDLER(WM_UPDATETAB, OnUpdateTab) // sent by anything #endif // pane messages COMMAND_ID_HANDLER(ID_PANE_CLOSE, OnPaneClose) // sent by pane windows // Windows Platform SDK Messages NOTIFY_CODE_HANDLER(EN_MSGFILTER, OnEnMsgFilter) // for text selections NOTIFY_CODE_HANDLER(EN_LINK, ::OnEnLink) // for doubleclickable url's MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_CLOSE, OnClose) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_SYSCOMMAND, OnSysCommand) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) MESSAGE_HANDLER(WM_MDIACTIVATE, OnMDIActivate) MESSAGE_HANDLER(WM_FORWARDMSG, OnForwardMsg) // handle mouse activate correctly (Daniel Bowen, see WTL Mailing list - digest 718) MESSAGE_HANDLER(WM_MOUSEACTIVATE, OnMouseActivate) MESSAGE_HANDLER(WM_COPY, OnEditCopy) // context menu COMMAND_ID_HANDLER(IDC_CHILDFRAME_CLEARBUFFER, m_MsgView.OnBnClickedClearBuffer) COMMAND_ID_HANDLER(IDC_CHILDFRAME_COPYBUFFER, m_MsgView.OnBnClickedCopyBuffer) COMMAND_ID_HANDLER(ID_CHANNEL_MONITOR, g_pMainWnd->OnToggleChannelMonitor) COMMAND_ID_HANDLER(ID_SERVER_MONITOR, g_pMainWnd->OnToggleServerMonitor) COMMAND_ID_HANDLER(ID_CHANNEL_PROPERTIES, g_pMainWnd->OnChannelProperties) COMMAND_ID_HANDLER(ID_CHANNEL_SHOWSERVER, g_pMainWnd->OnChannelShowServer) COMMAND_ID_HANDLER(ID_CHANNEL_CHANNELLIST, g_pMainWnd->OnChannelChannelList) COMMAND_ID_HANDLER(ID_OPTIONS_TOGGLEINFO, g_pMainWnd->OnToggleInfo) COMMAND_ID_HANDLER(ID_OPTIONS_TOGGLEHEADER, g_pMainWnd->OnToggleHeader) COMMAND_ID_HANDLER(ID_OPTIONS_TOGGLEUSERLIST, g_pMainWnd->OnToggleUserList) COMMAND_ID_HANDLER(ID_OPTIONS_LOGGING, g_pMainWnd->OnToggleOptionLogging) COMMAND_ID_HANDLER(ID_OPTIONS_TIMESTAMPS, g_pMainWnd->OnToggleOptionTimeStamps) COMMAND_ID_HANDLER(IDC_CHILDFRAME_VIEWLOGFILE, OnViewLogFile) COMMAND_ID_HANDLER(IDC_CHILDFRAME_CYCLE, OnCycleChannel) COMMAND_ID_HANDLER(IDC_CHILDFRAME_DCCSEND, OnDCCSend) COMMAND_ID_HANDLER(IDC_CHILDFRAME_DCCCHAT, OnDCCChat) COMMAND_ID_HANDLER(IDC_CHILDFRAME_WHOIS, OnWhoIs) COMMAND_RANGE_HANDLER(IDC_CHILDFRAME_VERBOSELEVEL_LEVEL0,IDC_CHILDFRAME_VERBOSELEVEL_LEVEL3,OnSetVerboseLevel) COMMAND_RANGE_HANDLER(ID_USERLISTFIRST,ID_USERLISTLAST,OnUserListContext) //CHAIN_CLIENT_COMMANDS() CHAIN_MSG_MAP(baseClass) //+ <gliptic> Drag and drop files CHAIN_MSG_MAP(CDropFilesHandler<CChildFrame>) // </gliptic> //-CHAIN_MSG_MAP(CMDIChildWindowImpl<CChildFrame>) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) // Custom Messages for HydraIRC LRESULT OnTextInput(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnHeaderChanged(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnPaneClose(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnUpdateInfoPane(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); #ifdef USE_TABBEDMDI LRESULT OnUpdateTab(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); #endif LRESULT OnUserListContext(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnSetVerboseLevel(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnViewLogFile(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnCycleChannel(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnDCCSend(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnDCCChat(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnWhoIs(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnNetEvent(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnDNSEvent(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnBufferWaiting(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnProcessQueue(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); // Windows Platform SDK messages LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnForwardMsg(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/); LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnMDIActivate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); LRESULT OnEnMsgFilter(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/); LRESULT OnMouseActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); //LRESULT OnEnSelChange(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); LRESULT OnEditCopy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); //+ <gliptic> Drag and drop files BOOL IsReadyForDrop(void); BOOL HandleDroppedFile(LPCTSTR szBuff); void EndDropFiles(void); // </gliptic> void DoContextMenu( void ); void DoUserListContextMenu(TreeItemInfo *pTII, CUserListView *pUserListView); void DoUserListDoubleClick(TreeItemInfo *pTII); void SetVerboseLevel(int VerboseLevel); void UpdateSettings( BOOL IgnoreWindowPrefs ); void UpdateStatus( void ); void UpdateInfo( void ); #ifdef USE_TABBEDMDI void UpdateTab( void ); #endif void ProcessBuffer( void ); virtual void OnFinalMessage(HWND /*hWnd*/); /* BEGIN_CEL_PATCH */ void CheckPluginProcessing(char *Buffer, DWORD Mode); /* END_CEL_PATCH */ void ProcessTextInput(char *Buffer, BOOL Parse); IRCServer *GetServer( void ); void AddTimerCommand(int Delay, char *CommandProfileName); CTimerCommand *GetTimerCommand(char *CommandProfileName); private: void InitialiseWindows( void ); BOOL ProcessCommand(char *Command, char *Args); // Sends output to the default message buffer associated with this instance. void Put(const int Contents, char *buffer); void Printf(const int Contents, const char *format, ...); public: // IRC Commands (that the user can use as commands, e,g /msg) // some have matching functions in IRCServer that do the actual // socket sending, these are just input/arg parsers. void CMD_CTCPRequest (char *Args); void CMD_Action (const char *Msg ); void CMD_Notice (char *Args ); void CMD_PrivMsg (char *Args ); void CMD_PrivMsg (const char *To, const char *Msg); void CMD_Part (char *Args ); void CMD_Cycle ( void ); void CMD_Help (const char *Args ); void CMD_Quit (char *Args ); void CMD_Exit (char *Args ); void CMD_Join (char *Args, int Flags = CCF_NONE ); void CMD_Query (char *Args ); void CMD_Server (char *Args, BOOL NewWindow = FALSE ); void CMD_Raw (char *Args ); void CMD_Exec (char *Args ); void CMD_Timer (char *Args ); void CMD_StopTimer (char *Args ); void CMD_Nick (char *Args ); void CMD_GetNick (char *Args ); void CMD_Monitor (const char *Args ); void CMD_Logging (const char *Args ); void CMD_AudioMute (const char *Args ); void CMD_Timestamps (char *Args ); void CMD_Set (char *Args ); void CMD_DCC (char *Args ); void CMD_DCCSend (char *Args ); void CMD_DCCChat (char *Args ); void CMD_UnloadPlugin (char *Args ); void CMD_RefreshPlugins (const char *Args ); void CMD_ListPlugins (const char *Args ); void CMD_Ignore (const char *Args ); void CMD_Clear (const char *Args ); void CMD_SaveTheme (char *Args ); void CMD_Window (const char *Args ); /* BEGIN_CEL_PATCH */ void CMD_CLEAR (void ); /* END_CEL_PATCH */ protected: void ResizeHeader( void ); };
[ "hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0" ]
[ [ [ 1, 332 ] ] ]
9a44d96b2bdaacc919dea39bf0f9612313c31c37
710981ad55d08ec46a9ffa06df2f07aa54ae5dcd
/player/src/interface/Control/Save_Load_Menu_scene.cpp
0036600a76799b7f2bc1bf8bc7a649a6210e871c
[]
no_license
weimingtom/easyrpg
b2ee6acf5a97a4744554b26feede7367b7c16233
8877364261e4d4f52cd36cbb43929ed1351f06e1
refs/heads/master
2021-01-10T02:14:36.939339
2009-02-15T03:45:32
2009-02-15T03:45:32
44,462,893
1
0
null
null
null
null
ISO-8859-1
C++
false
false
2,172
cpp
/*Save_Load_Menu_scene.cpp, Save_Load_Menu_Scene routines. Copyright (C) 2007 EasyRPG Project <http://easyrpg.sourceforge.net/>. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Save_Load_Menu_scene.h" /* Save_Load_Menu_Scene::~ Save_Load_Menu_Scene() { } Save_Load_Menu_Scene:: Save_Load_Menu_Scene() { } */ void Save_Load_Menu_Scene::init(Audio * theaudio, bool * run,unsigned char * TheScene,Player_Team * TheTeam) { myteam=TheTeam; myaudio=theaudio; std::string system_string; system_string.append("System/"); system_string.append(myteam->data2.System_dat.System_graphic); system_string.append(".png"); descripcion.init(320,30,0,0,(char *)system_string.c_str()); descripcion.add_text("¿Dónde deseas guardar la partida? ",10,5); Save_pos_1.init(320,70,0,30,(char *)system_string.c_str()); Save_pos_2.init(320,70,0,100,(char *)system_string.c_str()); Save_pos_3.init(320,70,0,170,(char *)system_string.c_str()); running= run; NScene=TheScene; retardo=0; } void Save_Load_Menu_Scene::update(SDL_Surface* Screen) { retardo++; if(retardo==6) { Save_pos_1.draw(Screen); Save_pos_2.draw(Screen); Save_pos_3.draw(Screen); descripcion.draw(Screen); retardo=0; } } void Save_Load_Menu_Scene::updatekey() { if (Key_press_and_realsed(LMK_X )) { (*myaudio).load("../Sound/Cansel2.wav");* NScene=4; } } void Save_Load_Menu_Scene::dispose() { Save_pos_1.dispose(); Save_pos_2.dispose(); Save_pos_3.dispose(); descripcion.dispose(); }
[ "fdelapena@2452c464-c253-f492-884b-b99f1bb2d923", "lobomon@2452c464-c253-f492-884b-b99f1bb2d923" ]
[ [ [ 1, 32 ], [ 34, 74 ] ], [ [ 33, 33 ] ] ]
4325c47f7862ec622957768cc3c52a19cf12d89c
fca81f35295cceafd1525f0c40910bce7d4880af
/Source/ConstructionManager.cpp
61dd0df1cf3f0939c1fcda741aac0361ecc726f6
[]
no_license
armontoubman/massexpand
b324da674cd5013ba1076865d33fc16bfac4f01f
4daec6bd7d5799de1019e341917c1179158daaa4
refs/heads/master
2021-01-10T13:55:47.067590
2011-11-20T16:20:48
2011-11-20T16:20:48
50,496,084
0
0
null
null
null
null
UTF-8
C++
false
false
7,040
cpp
#include "ConstructionManager.h" #include <BWAPI.h> #include "HighCommand.h" #include "Util.h" #include "Product.h" #include "BuildingPlacer.h" ConstructionManager::ConstructionManager(HighCommand* h) { this->hc = h; this->gas = 0; this->minerals = 0; this->supplyTotal = 0; this->supplyUsed = 0; } void ConstructionManager::update() { this->gas = Broodwar->self()->gas(); this->minerals = Broodwar->self()->minerals(); this->supplyTotal = Broodwar->self()->supplyTotal(); this->supplyUsed = Broodwar->self()->supplyUsed(); this->gas = this->gas - this->hc->ctm->getTotalGas(); this->minerals = this->minerals - this->hc->ctm->getTotalMinerals(); Product top; int products = this->hc->pm->getBuildList()->size(); for(int i=0; i<products; i++) { top = this->hc->pm->getBuildList()->top(); if(process(top)) { buy(top); this->hc->pm->getBuildList()->removeTop(); } else { break; } } } bool ConstructionManager::requirementsSatisfied(Product p) { if(p.type == BuildProduct) { return requirementsSatisfied(p.buildtype); } if(p.type == TechProduct) { return requirementsSatisfied(p.techtype); } if(p.type == UpgradeProduct) { return requirementsSatisfied(p.upgradetype); } if(p.type == ExpandProduct) { return requirementsSatisfied(BWAPI::UnitTypes::Zerg_Hatchery); } return false; } bool ConstructionManager::requirementsSatisfied(BWAPI::UnitType unittype) { std::map<BWAPI::UnitType, int> reqs = unittype.requiredUnits(); UnitGroup allUnits = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()); bool reqsMet = true; for each(std::pair<BWAPI::UnitType, int> req in reqs) { if(allUnits(GetType, req.first)(isCompleted).size() == 0) { reqsMet = false; } } if(unittype == BWAPI::UnitTypes::Zerg_Lurker || unittype == BWAPI::UnitTypes::Zerg_Lurker_Egg) { if(!BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Lurker_Aspect)) { reqsMet = false; } } return reqsMet; } bool ConstructionManager::requirementsSatisfied(BWAPI::TechType techtype) { UnitGroup allUnits = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()); bool reqsMet = true; reqsMet = allUnits(GetType, techtype.whatResearches())(isCompleted).size() > 0; return reqsMet; } bool ConstructionManager::requirementsSatisfied(BWAPI::UpgradeType upgradetype) { UnitGroup allUnits = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()); bool reqsMet = true; reqsMet = allUnits(GetType, upgradetype.whatUpgrades())(isCompleted).size() > 0; return reqsMet; } bool ConstructionManager::process(Product p) { if(p.type == BuildProduct) { return processBuild(p); } if(p.type == TechProduct) { return processTech(p); } if(p.type == UpgradeProduct) { return processUpgrade(p); } if(p.type == ExpandProduct) { return processExpand(p); } return false; } bool ConstructionManager::processBuild(Product p) { if(p.buildtype.isBuilding()) { return processBuilding(p); } else { return processUnit(p); } } bool ConstructionManager::processTech(Product p) { if(!this->canAfford(p) || !this->requirementsSatisfied(p)) { return false; } BWAPI::UnitType typeofresearcher = p.techtype.whatResearches(); UnitGroup researchers = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(GetType, typeofresearcher)(isCompleted); if(researchers.size() == 0) { return false; } bool beingdone = false; for each(BWAPI::Unit* unit in researchers) { if(unit->isResearching() && unit->getTech() == p.techtype) { beingdone = true; } } if(!beingdone) { for each(BWAPI::Unit* unit in researchers) { if(!unit->isResearching()) { unit->research(p.techtype); return true; } } } return false; } bool ConstructionManager::processUpgrade(Product p) { if(!this->canAfford(p) || !this->requirementsSatisfied(p)) { return false; } BWAPI::UnitType typeofresearcher = p.upgradetype.whatUpgrades(); UnitGroup researchers = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(GetType, typeofresearcher)(isCompleted); if(researchers.size() == 0) { return false; } bool beingdone = false; for each(BWAPI::Unit* unit in researchers) { if(unit->isUpgrading() && unit->getUpgrade() == p.upgradetype) { beingdone = true; } } if(!beingdone) { for each(BWAPI::Unit* unit in researchers) { if(!unit->isUpgrading()) { unit->upgrade(p.upgradetype); return true; } } } return false; } bool ConstructionManager::processExpand(Product p) { if(!this->canAfford(p) || !this->requirementsSatisfied(p)) { return false; } this->hc->ctm->newExpandContract(); return true; } bool ConstructionManager::processBuilding(Product p) { if(!this->canAfford(p) || !this->requirementsSatisfied(p)) { return false; } if(p.buildtype == BWAPI::UnitTypes::Zerg_Lair || p.buildtype == BWAPI::UnitTypes::Zerg_Hive) { if(p.buildtype == BWAPI::UnitTypes::Zerg_Lair) { UnitGroup hatcheries = allEigenUnits()(Hatchery)(isCompleted); if(hatcheries.size() > 0) { BWAPI::Unit* hatchery = *hatcheries.begin(); hatchery->morph(BWAPI::UnitTypes::Zerg_Lair); return true; } else { return false; } } else { UnitGroup lairs = allEigenUnits()(Lair)(isCompleted); if(lairs.size() > 0) { BWAPI::Unit* lair = *lairs.begin(); lair->morph(BWAPI::UnitTypes::Zerg_Hive); return true; } return false; } } else { this->hc->ctm->newContract(p.buildtype); return true; } } bool ConstructionManager::processUnit(Product p) { if(!this->canAfford(p) || !this->requirementsSatisfied(p)) { return false; } if(p.buildtype == BWAPI::UnitTypes::Zerg_Lurker) { UnitGroup hydras = allEigenUnits()(Hydralisk); if(hydras.size() > 0) { if(hydras(isIdle).size() > 0) { BWAPI::Unit* hydra = *hydras(isIdle).begin(); hydra->morph(BWAPI::UnitTypes::Zerg_Lurker); return true; } else { BWAPI::Unit* hydra = *hydras.begin(); hydra->morph(BWAPI::UnitTypes::Zerg_Lurker); return true; } } else { return false; } } else { UnitGroup larva = allEigenUnits()(Larva); if(larva.size() > 0) { BWAPI::Unit* larv = *larva.begin(); larv->morph(p.buildtype); return true; } else { return false; } } } bool ConstructionManager::canAfford(Product p) { if(p.type == ExpandProduct) { return BWAPI::UnitTypes::Zerg_Hatchery.gasPrice() <= this->gas && BWAPI::UnitTypes::Zerg_Hatchery.mineralPrice() <= this->minerals; } return p.gasPrice() <= this->gas && p.mineralPrice() <= this->minerals; } void ConstructionManager::buy(Product p) { this->gas = this->gas - p.gasPrice(); this->minerals = this->minerals - p.mineralPrice(); }
[ [ [ 1, 315 ] ] ]
3993ddab5ddbc3655b3fb097102328009a521187
61352a7371397524fe7dcfab838de40d502c3c9a
/CorbaClasses/Sources/IClientServer/IClientServer_impl.cpp
bfb3a0a9248d4c062b3481ec9171f78f1cd6e42c
[]
no_license
ustronieteam/emmanuelle
fec6b6ccfa1a9a6029d8c3bb5ee2b9134fccd004
68d639091a781795d2e8ce95c3806ce6ae9f36f6
refs/heads/master
2021-01-21T13:04:29.965061
2009-01-28T04:07:01
2009-01-28T04:07:01
32,144,524
2
0
null
null
null
null
UTF-8
C++
false
false
3,678
cpp
#include <OB/CORBA.h> #include <IClientServer_impl.h> #include <boost/bind.hpp> #include <boost/thread/thread.hpp> #include "CorbaConnector.h" #include "Model.h" // // IDL:IClientServer:1.0 // IClientServer_impl::IClientServer_impl(PortableServer::POA_ptr poa) : poa_(PortableServer::POA::_duplicate(poa)) { //logger logger = log4cxx::LoggerPtr(log4cxx::Logger::getLogger("IClinetServer_impl")); logger->setLevel(LOGLEVEL); } IClientServer_impl::~IClientServer_impl() { } PortableServer::POA_ptr IClientServer_impl::_default_POA() { return PortableServer::POA::_duplicate(poa_); } // // IDL:IClientServer/ReceiveMessage:1.0 // void IClientServer_impl::ReceiveMessage(const ::DomainData::User& sender, const ::DomainData::Message& msg) throw(::CORBA::SystemException) { LOG4CXX_DEBUG(logger, "WYWOLANIE RECEIVEMESSAGE"); RemoteObserverData observData; observData.SetObserverType(MESSAGE); observData.SetSenderMessage(msg); observData.SetUser(sender); this->Notify(observData); } // // IDL:IClientServer/ChangeServer:1.0 // void IClientServer_impl::ChangeServer(const ::DomainData::Address& serverAddress) throw(::CORBA::SystemException) { // TODO: Implementation } // funkcja puszczana w odzienlnym watku do nasluchu czy utworzono pipe i mozna odebrac plik void runGetFileThread(IClientClient_var client, DomainData::User sender, IClientServer_impl * cl) { //logger log4cxx::LoggerPtr logger = log4cxx::LoggerPtr(log4cxx::Logger::getLogger("IClinetServer_impl")); logger->setLevel(LOGLEVEL); try { while(true) { LOG4CXX_DEBUG(logger, "... proba wywolania GetFile."); DomainData::File * f = client->GetFile(sender); if(strcmp(f->name.in(), "")) { LOG4CXX_DEBUG(logger, "Znalezino plik na pipe holderze"); RemoteObserverData observData; observData.SetObserverType(FFILE); observData.SetUser(sender); LOG4CXX_DEBUG(logger, "Zawartosc body: " << f->body.get_buffer()); std::ofstream fileStream(f->name.in(), std::ios_base::binary); if(fileStream.is_open()) { observData.SetFileName(f->name.in()); char * content = const_cast<char *>(f->body.get_buffer()); fileStream.write(content, f->size); fileStream.close(); } cl->Notify(observData); break; } else LOG4CXX_DEBUG(logger, "... nie ma pliku na pipeholderze."); #ifndef WIN32 sleep(5); #else Sleep(5000); #endif } } catch(CORBA::SystemException & e) { } } // // IDL:IClientServer/CreatePipeRequest:1.0 // ::CORBA::Boolean IClientServer_impl::CreatePipeRequest(const ::DomainData::User& sender, const ::DomainData::User& pipeHolder) throw(::CORBA::SystemException) { LOG4CXX_DEBUG(logger, "WYWOLANIE CREATEPIPEREQUEST "); try { IServerClient_var server = Model::GetInstance()->GetServerInstance(); CORBA::ORB_var orb; IClientClient_var client; if(!CorbaConnector::connectToClientClient(server->GetUserAddressByName(pipeHolder)->localization.in(), orb, client)) { LOG4CXX_ERROR(logger, "Nie mozna polaczyc sie z klientem"); return false; } DomainData::User sender2 = sender; sender2.number = 0; client->CreatePipe(sender2); boost::thread watekGetFile(boost::bind(&runGetFileThread, client, sender2, this)); } catch(CORBA::SystemException & e) { LOG4CXX_ERROR(logger, "nie mozna utworzyc pipe'a" << e._to_string()); return false; } LOG4CXX_DEBUG(logger, "Powodzenie CREATEPIPEREQUEST"); return true; }
[ "coutoPL@c118a9a8-d993-11dd-9042-6d746b85d38b" ]
[ [ [ 1, 147 ] ] ]
53ffd98d88a4e8df01b941a1862288a9654984c2
73bba167d83aec20fc0664b5df15d2b8c6f20003
/factorial/src/factorial/main.cpp
3745d45af4d168792cbdd3609409d37069c7c717
[]
no_license
rnarozniak/fastfactorial
a473603fa4a91a96fcef5ef4b80787c19901819a
dd23732068a17e283c697afe2553579201bf28ae
refs/heads/master
2020-04-01T18:38:55.854345
2010-01-13T18:05:56
2010-01-13T18:05:56
35,261,166
0
0
null
null
null
null
UTF-8
C++
false
false
2,413
cpp
////////////////////////////////////////////////////////////////////////// #ifndef _PRIMESWING_H_ #include "primeswing.h" #endif #ifndef _PARALLELPRIMESWING_H_ #include "parallelprimeswing.h" #endif #ifndef _SCOPETIMEPRINTER_H_ #include "scopetimeprinter.h" #endif #include <iostream> ////////////////////////////////////////////////////////////////////////// void FastCheck(); void TestNumber( int _number ); ////////////////////////////////////////////////////////////////////////// int main() { // Perform a fast check FastCheck(); // It takes approx 25 seconds to calculate 10000000 factorial on // Athlon Dual Core Processor 4050e 2.10 GHz, 2 GB RAM TestNumber(10000000); // Exit return 0; } ////////////////////////////////////////////////////////////////////////// void FastCheck() { for (int i = 1000; i < 10000; i += 500) TestNumber(i); } ////////////////////////////////////////////////////////////////////////// void TestNumber( int _number ) { // Number for calculating factorial mpz_class primeSwingResult; mpz_class parallelPrimeSwingResultresult; std::cout << "Testing number: " << _number << std::endl; // Calculate factorial using prime swing algorithm std::cout << "Prime Swing: "; { PrimeSwing calculator; ScopeTimePrinter printer; primeSwingResult = calculator.Factorial(_number); } std::cout << std::endl; // Calculate factorial using parallel prime swing algorithm std::cout << "Parallel Prime Swing: "; { ParallelPrimeSwing calculator; ScopeTimePrinter printer; parallelPrimeSwingResultresult = calculator.Factorial(_number); } std::cout << std::endl; // Calculate factorial using built in binary split algorithm mpz_class check; std::cout << "Binary split: "; { ScopeTimePrinter printer; mpz_fac_ui(check.get_mpz_t(), _number); } // Check them for equality if (check == primeSwingResult && check == parallelPrimeSwingResultresult) std::cout << " OK"; else std::cout << " FAIL"; std::cout << std::endl << "====================" << std::endl << std::endl; } //////////////////////////////////////////////////////////////////////////
[ "beemasterz@065cf898-fc4d-11de-be56-c15834921611" ]
[ [ [ 1, 99 ] ] ]
1e39e472034b3bd98c1af86bf40f6c0cd0a69da2
f177993b13e97f9fecfc0e751602153824dfef7e
/ImProSln/MyLib/MSSD3DClass.cpp
01bb288e86a420d05b975c00d56a10afdb3c9305
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
32,906
cpp
#include "MSSD3DClass.h" #include <math.h> #include <algorithm> extern HMODULE GetModule(); MS3DObj::MS3DObj() { D3DXCreateMatrixStack(0, &m_pMatrixStack); m_pMatrixStack->LoadIdentity(); } MS3DObj::~MS3DObj() { if (m_pMatrixStack != NULL) { m_pMatrixStack->Release(); m_pMatrixStack = NULL; } } D3DXMATRIX MS3DObj::GetTransform() { return *m_pMatrixStack->GetTop(); } HRESULT MS3DObj::SetTransform(const D3DXMATRIX* mat) { return m_pMatrixStack->LoadMatrix(mat); } BOOL MS3DObj::Translate(D3DXVECTOR3& t) { m_pMatrixStack->Translate(t.x, t.y, t.z); return TRUE; } BOOL MS3DObj::RotateAxis(CONST D3DXVECTOR3 * pV, FLOAT angle) { m_pMatrixStack->RotateAxis(pV, angle); return TRUE; } BOOL MS3DObj::Scale(D3DXVECTOR3& s) { m_pMatrixStack->Scale(s.x, s.y, s.z); return TRUE; } BOOL MS3DObj::ResetTransform() { m_pMatrixStack->LoadIdentity(); return TRUE; } BOOL MS3DObj::PushMatrix() { m_pMatrixStack->Push(); return TRUE; } BOOL MS3DObj::PopMatrix() { m_pMatrixStack->Pop(); return TRUE; } BOOL MS3DObj::SetPosition(D3DXVECTOR3 pos) { D3DXMATRIX mat = GetTransform(); mat.m[3][0] = pos.x; mat.m[3][1] = pos.y; mat.m[3][2] = pos.z; m_pMatrixStack->LoadMatrix(&mat); return TRUE; } D3DXVECTOR3 MS3DObj::GetPosition() { D3DXMATRIX mat = GetTransform(); D3DXVECTOR3 ret(0,0,0); ret.x = mat.m[3][0]; ret.y = mat.m[3][1]; ret.z = mat.m[3][2]; return ret; } //////////MSMeshBase////////////// MSMeshBase::MSMeshBase() { m_pDevice = NULL; m_pMesh = NULL; m_color = D3DCOLOR_ARGB(255,255,255,255); } MSMeshBase::MSMeshBase(IDirect3DDevice9* pDevice) : MSDXBase(pDevice) { m_pMesh = NULL; m_color = D3DCOLOR_ARGB(255,255,255,255); } MSMeshBase::~MSMeshBase() { if (m_pMesh != NULL) { m_pMesh->Release(); m_pMesh = NULL; } } IDirect3DVertexBuffer9* MSMeshBase::GetVertexBuffer() { if (m_pMesh == NULL) return NULL; IDirect3DVertexBuffer9* ret = NULL; if (FAILED(m_pMesh->GetVertexBuffer(&ret))) return NULL; return ret; } IDirect3DIndexBuffer9* MSMeshBase::GetIndexBuffer() { if (m_pMesh == NULL) return NULL; IDirect3DIndexBuffer9* ret = NULL; if (FAILED(m_pMesh->GetIndexBuffer(&ret))) return NULL; return ret; } UINT MSMeshBase::GetVertexNumber() { if (m_pMesh == NULL) { return 0; } return m_pMesh->GetNumVertices(); } UINT MSMeshBase::GetPrimitiveNumber() { if (m_pMesh == NULL) { return 0; } return m_pMesh->GetNumFaces(); } BOOL MSMeshBase::Render(IDirect3DBaseTexture9* pTexture) { if (m_pDevice == NULL) return FALSE; HRESULT hr; hr = m_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, m_color ); hr = m_pDevice->SetTexture(0, pTexture); hr = m_pMesh->DrawSubset(0); hr = m_pDevice->SetTexture(0, NULL); hr = m_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, 0xffffffff); return TRUE; } BOOL MSMeshBase::Render() { if (m_pDevice == NULL || m_pMesh == NULL) return FALSE; HRESULT hr; hr = m_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, m_color ); hr = m_pMesh->DrawSubset(0); hr = m_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, 0xffffffff); return TRUE; } BOOL MSMeshBase::GetVertex(UINT idx, MSMeshBase::CUSTOMVERTEX& vertex) { IDirect3DVertexBuffer9* pVertexBuffer = GetVertexBuffer(); if (pVertexBuffer == NULL) return FALSE; if (idx >= m_pMesh->GetNumVertices()) return FALSE; CUSTOMVERTEX* pData = NULL; pVertexBuffer->Lock(0, 0, (void**)&pData, D3DLOCK_READONLY); vertex = pData[idx]; pVertexBuffer->Unlock(); return TRUE; } BOOL MSMeshBase::SetVertex(UINT idx, MSMeshBase::CUSTOMVERTEX& vertex) { IDirect3DVertexBuffer9* pVertexBuffer = GetVertexBuffer(); if (pVertexBuffer == NULL) return FALSE; if (idx >= m_pMesh->GetNumVertices()) return FALSE; CUSTOMVERTEX* pData = NULL; pVertexBuffer->Lock(0, 0, (void**)&pData, 0); pData[idx] = vertex; pVertexBuffer->Unlock(); return TRUE; } LPD3DXMESH MSMeshBase::GetMesh() { return m_pMesh; } MS3DPlane::MS3DPlane(IDirect3DDevice9* pDevice) : MSMeshBase(pDevice) { InitGeometry(); } MS3DPlane::~MS3DPlane() { } BOOL MS3DPlane::InitGeometry() { HRESULT hr; if (m_pMesh != NULL) { m_pMesh->Release(); m_pMesh = NULL; } hr = D3DXCreateMeshFVF(4,4, D3DXMESH_32BIT | D3DXMESH_VB_MANAGED | D3DXMESH_IB_MANAGED, D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1, m_pDevice, &m_pMesh); if (FAILED(hr)) { OutputDebugStringW(L"@@@@ InitGeometry D3DXCreateMeshFVF Failed in MS3DPlane!!\n"); return FALSE; } IDirect3DVertexBuffer9* pVertexBuffer = NULL; m_pMesh->GetVertexBuffer(&pVertexBuffer); CUSTOMVERTEX* pVertices = NULL; if( FAILED( pVertexBuffer->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) return FALSE; pVertices[0].position = D3DXVECTOR3(-1, 1, 0); pVertices[1].position = D3DXVECTOR3(-1, -1, 0); pVertices[2].position = D3DXVECTOR3(1, -1, 0); pVertices[3].position = D3DXVECTOR3(1, 1, 0); pVertices[0].normal = D3DXVECTOR3(0, 0, -1); pVertices[1].normal = D3DXVECTOR3(0, 0, -1); pVertices[2].normal = D3DXVECTOR3(0, 0, -1); pVertices[3].normal = D3DXVECTOR3(0, 0, -1); pVertices[0].tu = 0; pVertices[0].tv = 0; pVertices[1].tu = 0; pVertices[1].tv = 1; pVertices[2].tu = 1; pVertices[2].tv = 1; pVertices[3].tu = 1; pVertices[3].tv = 0; pVertexBuffer->Unlock(); IDirect3DIndexBuffer9* pIndexBuffer = NULL; m_pMesh->GetIndexBuffer(&pIndexBuffer); UINT* pIndex = NULL; if (FAILED(pIndexBuffer->Lock(0, 0, (void**)&pIndex, 0))) return FALSE; pIndex[0] = 0; pIndex[1] = 1; pIndex[2] = 3; pIndex[3] = 3; pIndex[4] = 1; pIndex[5] = 2; pIndexBuffer->Unlock(); return TRUE; } BOOL MS3DPlane::Render() { HRESULT hr; D3DXMATRIX preMatWorld; m_pDevice->GetTransform(D3DTS_WORLD, &preMatWorld); hr = m_pDevice->SetTransform(D3DTS_WORLD, &this->GetTransform() ); MSMeshBase::Render(); m_pDevice->SetTransform(D3DTS_WORLD, &preMatWorld); return TRUE; } BOOL MS3DPlane::Render(IDirect3DBaseTexture9* pTexture) { HRESULT hr; D3DXMATRIX preMatWorld; hr = m_pDevice->GetTransform(D3DTS_WORLD, &preMatWorld); hr = m_pDevice->SetTransform(D3DTS_WORLD, &this->GetTransform()); MSMeshBase::Render(pTexture); hr = m_pDevice->SetTransform(D3DTS_WORLD, &preMatWorld); return TRUE; } MSCamera::MSCamera() : MSDXBase() { init(); } MSCamera::MSCamera(IDirect3DDevice9* pDevice) : MSDXBase(pDevice) { init(); } MSCamera::~MSCamera() { } BOOL MSCamera::init() { m_vEyePt = D3DXVECTOR3(0,0,-5); m_vLookatPt = D3DXVECTOR3(0,0,0); m_vUpVec = D3DXVECTOR3(0,1,0); m_l = -1;// [in] Minimum x-value of view volume. m_r = 1;// [in] Maximum x-value of view volume. m_b = -1;// [in] Minimum y-value of view volume. m_t = 1;// [in] Maximum y-value of view volume. m_fovy = D3DX_PI/2; m_aspect = 4.0/3.0; m_zn = 1;// [in] Minimum z-value of the view volume. m_zf = 1000;// [in] Maximum z-value of the view volume. m_projType = Ortho; m_coordType = LEFTHAND; return TRUE; } BOOL MSCamera::SetEyePos(D3DXVECTOR3& vEyePt) { m_vEyePt = vEyePt; return TRUE; } BOOL MSCamera::SetLookAt(D3DXVECTOR3& vLookPt) { m_vLookatPt = vLookPt; return TRUE; } BOOL MSCamera::SetUpVec(D3DXVECTOR3& vUpVec) { m_vUpVec = vUpVec; return TRUE; } D3DXVECTOR3 MSCamera::GetEyePos() { return m_vEyePt; } D3DXVECTOR3 MSCamera::GetLookAt() { return m_vLookatPt; } D3DXVECTOR3 MSCamera::GetUpVec() { return m_vUpVec; } BOOL MSCamera::CameraOn() { D3DXMATRIX matView; matView = GetViewMatrix(); m_pDevice->GetTransform(D3DTS_VIEW, &m_BackupMatView); m_pDevice->SetTransform(D3DTS_VIEW, &matView); D3DXMATRIXA16 matProj; matProj = GetProjMatrix(); m_pDevice->GetTransform(D3DTS_PROJECTION, &m_BackupMatProj); m_pDevice->SetTransform( D3DTS_PROJECTION, &matProj ); return TRUE; } BOOL MSCamera::CameraOff() { m_pDevice->SetTransform(D3DTS_VIEW, &m_BackupMatView); m_pDevice->SetTransform(D3DTS_PROJECTION, &m_BackupMatProj); return TRUE; } D3DXMATRIX MSCamera::GetViewMatrix() { D3DXMATRIX matView; if (m_coordType == LEFTHAND) D3DXMatrixLookAtLH( &matView, &m_vEyePt, &m_vLookatPt, &m_vUpVec ); else D3DXMatrixLookAtRH( &matView, &m_vEyePt, &m_vLookatPt, &m_vUpVec ); return matView; } D3DXMATRIX MSCamera::GetProjMatrix() { D3DXMATRIX matProj; if (m_projType == Ortho) { if (m_coordType == LEFTHAND) D3DXMatrixOrthoOffCenterLH( &matProj, m_l, m_r, m_b, m_t, m_zn, m_zf ); else D3DXMatrixOrthoOffCenterRH( &matProj, m_l, m_r, m_b, m_t, m_zn, m_zf ); } else { if (m_coordType == LEFTHAND) D3DXMatrixPerspectiveFovLH( &matProj, m_fovy, m_aspect, m_zn, m_zf ); else D3DXMatrixPerspectiveFovRH( &matProj, m_fovy, m_aspect, m_zn, m_zf ); } return matProj; } BOOL MSCamera::SetProjType(ProjType t) { m_projType = t; return TRUE; } BOOL MSCamera::SetCoordType(CoordType t) { m_coordType = t; return TRUE; } BOOL MSCamera::SetOrthoPara(float l, float t, float r, float b) { m_l = l; m_t = t; m_r = r; m_b = b; return TRUE; } BOOL MSCamera::Screen2World(HWND hwnd, int x, int y, D3DXVECTOR3& vPos, D3DXVECTOR3& vDir) { D3DXMATRIX matView, matInvView; matView = GetViewMatrix(); D3DXMATRIX matProj, matInvProj; matProj = GetProjMatrix(); D3DXMatrixInverse(&matInvView,NULL, &matView); D3DXMatrixInverse(&matInvProj,NULL, &matProj); D3DVIEWPORT9 viewport; m_pDevice->GetViewport(&viewport); D3DXVECTOR4 screenPt(x, y, 0, 1); D3DXVECTOR4 projPt(0,0,0,1); RECT wrect; GetClientRect(hwnd, &wrect); projPt.x = (screenPt.x/(wrect.right - wrect.left) - 0.5) * (m_r - m_l); projPt.y = -(screenPt.y/(wrect.bottom - wrect.top) - 0.5) * (m_t - m_b); D3DXVECTOR4 viewPt(0,0,0,0); D3DXVECTOR4 worldPt(0,0,0,0); D3DXVec4Transform(&viewPt, &projPt, &matInvProj ); D3DXVec4Transform(&worldPt, &viewPt, &matInvView); vPos = D3DXVECTOR3(worldPt.x, worldPt.y, worldPt.z); D3DXVec3Normalize(&vDir , &(m_vLookatPt - m_vEyePt)); //swprintf_s(str, MAX_PATH, L"@@@@ Screen2World: x = %d, y = %d, \n@@@@ vPos = %.2f, %.2f, %.2f, vDir = %.2f, %.2f, %.2f \n", // x, y, vPos.x, vPos.y, vPos.z, vDir.x, vDir.y, vDir.z); //OutputDebugStringW(str); return TRUE; } vector<MS3DDisplay*> MS3DDisplay::m_pAllInstances; int MS3DDisplay::D3DDEVICELOST = 0; MS3DDisplay::MS3DDisplay(IDirect3D9* pD3D, UINT rtWidth, UINT rtHeight) : MSEventManager(NULL), MSDXBase(NULL) { ZeroMemory(&m_d3dpp, sizeof(m_d3dpp)); m_pAllInstances.push_back(this); m_hDisplayWnd = NULL; m_hRenderThread = 0; m_pEffect = NULL; m_texW = 0; m_texH = 0; m_bDeviceFromOthers = false; RegisterWndClass(GetModule()); CreateD3DWindow(rtWidth, rtHeight); InitDevice(pD3D, rtWidth, rtHeight); CreateTexture(rtWidth, rtHeight); if (D3DDEVICELOST == 0) D3DDEVICELOST = RegisterWindowMessage(D3DDEVICELOST_MSG); } MS3DDisplay::MS3DDisplay(IDirect3DDevice9* pDevice, UINT rtWidth, UINT rtHeight) : MSEventManager(NULL), MSDXBase(pDevice) { ZeroMemory(&m_d3dpp, sizeof(m_d3dpp)); m_texW = 0; m_texH = 0; m_pAllInstances.push_back(this); m_hDisplayWnd = NULL; m_hRenderThread = 0; m_pEffect = NULL; m_texW = 0; m_texH = 0; m_bDeviceFromOthers = true; CreateTexture(rtWidth, rtHeight); InitDevice(pDevice, rtWidth, rtHeight); if (D3DDEVICELOST == 0) D3DDEVICELOST = RegisterWindowMessage(D3DDEVICELOST_MSG); } HRESULT MS3DDisplay::ShowDisplayWnd(BOOL bShow) { if (m_hDisplayWnd == 0) { return S_FALSE; } ShowWindow(m_hDisplayWnd, bShow); return S_OK; } ATOM MS3DDisplay::RegisterWndClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_NOCLOSE; wcex.lpfnWndProc = D3DDisplayWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"D3DDisplayWnd"; wcex.hIconSm = NULL; ATOM ret = RegisterClassEx(&wcex); return ret; } HRESULT MS3DDisplay::SetDeviceLostCallback(DeviceLostCallBack pBeforeReset, DeviceLostCallBack pAfterReset, void* pUsetContext) { if (pBeforeReset == NULL || pAfterReset == NULL) return S_FALSE; m_pBeforeReset.push_back(pBeforeReset); m_pAfterReset.push_back(pAfterReset); m_pUserContext.push_back(pUsetContext); return S_OK; } HRESULT MS3DDisplay::OnActivateApp() { HRESULT hr = S_OK; HRESULT err = S_OK; if (m_pDevice != NULL) { HRESULT state = m_pDevice->TestCooperativeLevel(); if (state == D3DERR_DEVICENOTRESET) { for (int i =0; i < m_pAllInstances.size(); i++) { if (m_pAllInstances[i] == NULL) continue; hr = m_pAllInstances[i]->OnDeviceLost(m_pDevice, NULL); if (FAILED(hr)) err = hr; } } } return err; } LRESULT MS3DDisplay::D3DDisplayWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { HRESULT hr = S_OK; if (message == D3DDEVICELOST) { HRESULT err = S_OK; for (int i =0 ;i < m_pAllInstances.size(); i++) { if (m_pAllInstances[i]->GetD3DWnd() == hWnd) { hr = m_pAllInstances[i]->OnActivateApp(); if (FAILED(hr)) err = S_FALSE; } } return err; } switch (message) { default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } HRESULT MS3DDisplay::CreateD3DWindow(UINT winW, UINT winH) { if (winW != 0 && winH != 0) { if (m_hDisplayWnd == 0) { m_hDisplayWnd = CreateWindowExW(WS_EX_APPWINDOW, L"D3DDisplayWnd", L"D3DDisplayWnd", WS_MINIMIZEBOX| WS_MAXIMIZEBOX |WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, winW, winH, NULL, NULL, GetModule(), NULL); ShowWindow(m_hDisplayWnd, FALSE); } } else { if (m_hDisplayWnd == 0) { m_hDisplayWnd = CreateWindowExW(WS_EX_APPWINDOW, L"D3DWnd", L"D3DWnd", WS_MINIMIZEBOX| WS_MAXIMIZEBOX | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, GetModule(), NULL); ShowWindow(m_hDisplayWnd , FALSE); } } return S_OK; } MS3DDisplay::~MS3DDisplay() { if (m_hRenderThread != 0) { SuspendThread(m_hRenderThread); CloseHandle(m_hRenderThread); m_hRenderThread = 0; } if (m_pDisplayPlane != NULL) { delete m_pDisplayPlane; m_pDisplayPlane == NULL; } if (m_pCamera != NULL) { delete m_pCamera; m_pCamera = NULL; } if (m_hDisplayWnd != 0) { if (!m_bDeviceFromOthers) { ::DestroyWindow(m_hDisplayWnd); m_hDisplayWnd = 0; } else { ::ShowWindow(m_hDisplayWnd, FALSE); m_hDisplayWnd = 0; } } vector<MS3DDisplay*>::iterator thisIter = ::find(m_pAllInstances.begin(), m_pAllInstances.end(), this); if (thisIter != m_pAllInstances.end()) { m_pAllInstances.erase(thisIter); } for (int i =0; i< m_pBackupBackBuffer.size(); i++) { if (m_pBackupBackBuffer[i] != NULL) { m_pBackupBackBuffer[i]->Release(); m_pBackupBackBuffer[i] = NULL; } } m_pBackupBackBuffer.clear(); } BOOL MS3DDisplay::Run() { if (m_hRenderThread != 0) { OutputDebugStringW(L"@@@@ hRenderThread != 0 in MS3DDisplay::Run \n"); return FALSE; } HANDLE hThread = 0; DWORD threadID = 0; hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MS3DDisplay::_Run, (void*)this, CREATE_SUSPENDED, &threadID); if (hThread == NULL) { OutputDebugStringW(L"@@@@@ CreateThread Failed in MS3DDisplay::Run()!! \n"); return FALSE; } m_hRenderThread = hThread; ResumeThread(m_hRenderThread); OutputDebugStringW(L"@@@@@ MS3DDisplay::Render Thread Created!! \n"); return TRUE; } BOOL MS3DDisplay::_Run(void* _THIS) { MSG msg; ZeroMemory( &msg, sizeof(msg) ); while( msg.message!=WM_QUIT ) { if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { //EnterCriticalSection(&(((MS3DDisplay*)_THIS)->m_CS)); ((MS3DDisplay*)_THIS)->Render(); //LeaveCriticalSection(&(((MS3DDisplay*)_THIS)->m_CS)); } } ((MS3DDisplay*)_THIS)->m_hRenderThread = 0; return TRUE; } BOOL MS3DDisplay::Stop() { if (m_hRenderThread) { CloseHandle(m_hRenderThread); } m_hRenderThread = 0; return TRUE; } BOOL MS3DDisplay::InitDevice(IDirect3D9* pD3D, UINT rtWidth, UINT rtHeight) { if (pD3D == NULL) { return FALSE; } // Set up the structure used to create the D3DDevice. Since we are now // using more complex geometry, we will create a device with a zbuffer. ZeroMemory( &m_d3dpp, sizeof(m_d3dpp) ); m_d3dpp.Windowed = TRUE; m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; m_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; int screenW, screenH; if (rtWidth == 0 || rtHeight == 0) { HDC dc = GetDC(m_hDisplayWnd); screenW = GetDeviceCaps(dc, HORZRES); screenH = GetDeviceCaps(dc, VERTRES); } else { screenW = rtWidth; screenH = rtHeight; } m_d3dpp.BackBufferWidth = screenW; m_d3dpp.BackBufferHeight = screenH; m_d3dpp.hDeviceWindow = m_hDisplayWnd; m_d3dpp.EnableAutoDepthStencil = TRUE; m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; m_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Create the D3DDevice if( FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hDisplayWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX | D3DCREATE_MULTITHREADED, &m_d3dpp, &m_pDevice ))) { OutputDebugStringW(L"@@@@ CreateDevice Failed!! in MS3DDisplay::InitDevice() \n"); return FALSE; } D3DCAPS9 caps; m_pDevice->GetDeviceCaps(&caps); if (caps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) { int powerof2Width = 1; int powerof2Height = 1; while (powerof2Width < screenW) { powerof2Width *= 2; } while (powerof2Height < screenH) { powerof2Height *= 2; } m_d3dpp.BackBufferWidth = powerof2Width; m_d3dpp.BackBufferHeight = powerof2Height; m_pDevice->Release(); m_pDevice = NULL; if( FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hDisplayWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &m_d3dpp, &m_pDevice ))) { OutputDebugStringW(L"@@@@ CreateDevice Failed!! in MS3DDisplay::InitDevice() \n"); return FALSE; } } HRESULT hr = S_OK; // Turn on the zbuffer hr = m_pDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); // Turn on ambient lighting hr = m_pDevice->SetRenderState( D3DRS_AMBIENT, 0xffffffff ); hr = m_pDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW); hr = m_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, 0xfffffffff ); hr = m_pDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); hr = m_pDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_CONSTANT); hr = m_pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TEXTURE); hr = m_pDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); m_pDisplayPlane = new MS3DPlane(m_pDevice); m_pCamera = new MSCamera(m_pDevice); return TRUE; } BOOL MS3DDisplay::InitDevice(IDirect3DDevice9* pDevice, UINT rtWidth, UINT rtHeight) { if (pDevice == NULL) { return FALSE; } m_pDisplayPlane = new MS3DPlane(m_pDevice); m_pCamera = new MSCamera(m_pDevice); IDirect3DSwapChain9* pSwapChain = NULL; pDevice->GetSwapChain(0, &pSwapChain); if (pSwapChain == NULL) return FALSE; pSwapChain->GetPresentParameters(&m_d3dpp); m_hDisplayWnd = m_d3dpp.hDeviceWindow; pSwapChain->Release(); pSwapChain = NULL; return TRUE; } BOOL MS3DDisplay::CreateTexture(UINT rtWidth = 0, UINT rtHeight = 0) { if (m_pDevice == NULL) { return FALSE; } if (m_pTexture != NULL) { m_pTexture->Release(); m_pTexture = NULL; } HRESULT hr; HWND desktop = GetDesktopWindow(); HDC dc = GetDC(desktop); int screenW = GetDeviceCaps(dc, HORZRES); int screenH = GetDeviceCaps(dc, VERTRES); if (rtWidth == 0 || rtHeight == 0) { m_texW = screenW; m_texH = screenH; hr = D3DXCreateTexture(m_pDevice, screenW, screenH, 0, D3DUSAGE_DYNAMIC, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &m_pTexture); } else { m_texW = rtWidth; m_texH = rtHeight; hr = D3DXCreateTexture(m_pDevice, rtWidth, rtHeight, 0, D3DUSAGE_DYNAMIC, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &m_pTexture); } if (FAILED(hr)) { OutputDebugStringW(L"@@@@@ D3DXCreateTexture Failed in MS3DDisplay::CreateTexture()!! \n"); return FALSE; } return TRUE; } BOOL MS3DDisplay::SetRenderTarget(LPDIRECT3DTEXTURE9 pRenderTarget) { if (pRenderTarget == NULL) return E_FAIL; HRESULT hr = S_OK; LPDIRECT3DSURFACE9 pRTSurface = NULL; LPDIRECT3DSURFACE9 pBackupBuffer = NULL; D3DSURFACE_DESC desc; hr = pRenderTarget->GetSurfaceLevel(0, &pRTSurface); pRTSurface->GetDesc(&desc); if (!(desc.Usage & D3DUSAGE_RENDERTARGET) ) { pRTSurface->Release(); pRTSurface = NULL; return E_FAIL; } hr = m_pDevice->GetRenderTarget(0, &pBackupBuffer); hr = m_pDevice->SetRenderTarget(0, pRTSurface); m_pBackupBackBuffer.push_back(pBackupBuffer); pBackupBuffer->AddRef(); if (pRTSurface != NULL) { pRTSurface->Release(); pRTSurface = NULL; } if (pBackupBuffer != NULL) { pBackupBuffer->Release(); pBackupBuffer = NULL; } return TRUE; } BOOL MS3DDisplay::ResetRenderTarget() { if (m_pBackupBackBuffer.size() <= 0) return E_FAIL; HRESULT hr = S_OK; LPDIRECT3DSURFACE9 pBackupBuffer = m_pBackupBackBuffer[m_pBackupBackBuffer.size()-1]; m_pBackupBackBuffer.pop_back(); m_pDevice->SetRenderTarget(0, pBackupBuffer); pBackupBuffer->Release(); pBackupBuffer = NULL; return TRUE; } BOOL MS3DDisplay::Render() { CAutoLock lck(&m_csResetDevice); m_pDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(50,50,50), 1.0f, 0 ); m_pCamera->CameraOn(); HRESULT hr; if( SUCCEEDED( m_pDevice->BeginScene() ) ) { if (m_pDisplayPlane != NULL) { D3DXMATRIX backupMat; hr = m_pDisplayPlane->Render(m_pTexture); } m_pDevice->EndScene(); } m_pDevice->Present(NULL,NULL,NULL,NULL); m_pCamera->CameraOff(); return TRUE; } BOOL MS3DDisplay::Render(IDirect3DBaseTexture9* pTexture) { CAutoLock lck(&m_csResetDevice); m_pDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(50,50,50), 1.0f, 0 ); m_pCamera->CameraOn(); if( SUCCEEDED( m_pDevice->BeginScene() ) ) { if (m_pDisplayPlane != NULL) { m_pDisplayPlane->Render(pTexture); } m_pDevice->EndScene(); } m_pDevice->Present(NULL,NULL,NULL,NULL); m_pCamera->CameraOff(); return TRUE; } BOOL MS3DDisplay::Render(IDirect3DBaseTexture9* pTexture, ID3DXEffect* pEffect) { return S_FALSE; } BOOL MS3DDisplay::IntersectWithPlane(D3DXVECTOR3 vPos, D3DXVECTOR3 vDir, BOOL& bHit, float& tU, float& tV) { bHit = FALSE; DWORD faceIdx = 0; float pU, pV = 0; float dist = 0; DWORD countOfHits = 0; LPD3DXBUFFER pBuffer = NULL; HRESULT hr; hr = D3DXIntersect(m_pDisplayPlane->GetMesh(), &vPos, &vDir, &bHit, &faceIdx, &pU, &pV, &dist, &pBuffer, &countOfHits); if (FAILED(hr)) { return FALSE; } if (bHit) { IDirect3DIndexBuffer9* pIndices = m_pDisplayPlane->GetIndexBuffer(); UINT* pIndex = NULL; MSMeshBase::CUSTOMVERTEX pVtx[3]; pIndices->Lock(0, NULL, (void**)&pIndex, D3DLOCK_READONLY); m_pDisplayPlane->GetVertex(pIndex[faceIdx*3], pVtx[0]); m_pDisplayPlane->GetVertex(pIndex[faceIdx*3+1], pVtx[1]); m_pDisplayPlane->GetVertex(pIndex[faceIdx*3+2], pVtx[2]); pIndices->Unlock(); tU = pVtx[0].tu + pU*(pVtx[1].tu - pVtx[0].tu) + pV*(pVtx[2].tu - pVtx[0].tu); tV = pVtx[0].tv + pU*(pVtx[1].tv - pVtx[0].tv) + pV*(pVtx[2].tv - pVtx[0].tv); } return TRUE; } ID3DXEffect* MS3DDisplay::GetEffect() { if (m_pEffect == NULL) { DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE ; D3DCAPS9 cap; m_pDevice->GetDeviceCaps(&cap); if (cap.PixelShaderVersion < D3DPS_VERSION(2,0)) { dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; } if (cap.VertexShaderVersion < D3DVS_VERSION(2,0)) { dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; } WCHAR str[MAX_PATH] = {0}; GetCurrentDirectory(MAX_PATH,str); swprintf_s(str, MAX_PATH, L"%s\\..\\fx\\ImHookRender.fx", str); HRESULT hr = D3DXCreateEffectFromFileW( m_pDevice, str, NULL, NULL, dwShaderFlags, NULL, &m_pEffect, NULL ); if (FAILED(hr)) { OutputDebugStringW(L"@@@@ D3DXCreateEffectFromFileW Failed in MS3DDisplay::GetEffect()\n"); return NULL; } } return m_pEffect; } BOOL MS3DDisplay::HitTest(D3DXVECTOR3& vPos, D3DXVECTOR3& vDir) { return TRUE; } bool MS3DDisplay::IsDeviceFromOther() { return m_bDeviceFromOthers; } HRESULT MS3DDisplay::OnDeviceLost(IDirect3DDevice9 * pd3dDevice, void* pUserContext) { HRESULT hr = S_OK; CAutoLock lck(&m_csResetDevice); if (m_pDevice == NULL) { return S_FALSE; } OnBeforeResetDevice(pd3dDevice, pUserContext); for (int i =0; i< m_pBeforeReset.size(); i++) { m_pBeforeReset[i](pd3dDevice, m_pUserContext[i]); } hr = m_pDevice->Reset(&m_d3dpp); if (FAILED(hr)) { return S_FALSE; } OnAfterResetDevice(pd3dDevice, pUserContext); for (int i =0; i< m_pAfterReset.size(); i++) { m_pAfterReset[i](pd3dDevice, m_pUserContext[i]); } return S_OK; } HRESULT MS3DDisplay::OnBeforeResetDevice(IDirect3DDevice9 * pd3dDevice, void* pUserContext) { HRESULT hr = S_OK; if (m_pEffect != NULL) { hr = m_pEffect->OnLostDevice(); } if (m_pDisplayPlane != NULL) { delete m_pDisplayPlane; m_pDisplayPlane = NULL; } if (m_pTexture != NULL) { m_pTexture->Release(); m_pTexture = NULL; } return S_OK; } HRESULT MS3DDisplay::OnAfterResetDevice(IDirect3DDevice9 * pd3dDevice, void* pUserContext) { HRESULT hr = S_OK; // Turn on the zbuffer if (pd3dDevice == NULL) { return S_FALSE; } hr = pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); // Turn on ambient lighting hr = pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0xffffffff ); hr = pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW); hr = pd3dDevice->SetTextureStageState(0, D3DTSS_CONSTANT, 0xfffffffff ); hr = pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); hr = pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_CONSTANT); hr = pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TEXTURE); hr = pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); if (m_pEffect != NULL) { hr = m_pEffect->OnResetDevice(); } if (m_pDisplayPlane != NULL) { delete m_pDisplayPlane; m_pDisplayPlane = NULL; } m_pDisplayPlane = new MS3DPlane(pd3dDevice); CreateTexture(m_texW, m_texH); return S_OK; } BOOL IEventManager::SetParent(IEventManager* parent) { if (m_pParent != NULL) { m_pParent->RemoveChild(this); } m_pParent = parent; if (m_pParent) m_pParent->AddChild(this); return TRUE; } BOOL IEventManager::AddChild(IEventManager* child) { for (vector<IEventManager*>::iterator it =m_Children.begin(); it != m_Children.end(); ++it) { if ((*it) == child) { return TRUE; } } m_Children.push_back(child); return TRUE; } BOOL IEventManager::RemoveChild(IEventManager* child) { for (vector<IEventManager*>::iterator it =m_Children.begin(); it != m_Children.end(); ++it) { if ((*it) == child) { m_Children.erase(it); } return TRUE; } return FALSE; } MSEventManager::MSEventManager(IEventManager* parent) { SetParent(parent); } MSEventManager::~MSEventManager() { } BOOL MSEventManager::HitTest(D3DXVECTOR3& vPos, D3DXVECTOR3& vDir) { /*need to be overwrite */ return FALSE; } BOOL MSEventManager::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { BOOL ret = FALSE; for (vector<IEventManager*>::iterator it =m_Children.begin(); it != m_Children.end(); ++it) { ret = (*it)->WndProc(hWnd, message, wParam, lParam); } return TRUE; } BOOL MSEventManager::PassMouseMessage(UINT message, WPARAM wParam, LPARAM lParam, D3DXVECTOR3& vPos, D3DXVECTOR3& vDir) { BOOL ret = FALSE; if (m_bStargDrag) { switch (message) { case WM_LBUTTONUP: m_bStargDrag = FALSE; break; case WM_MOUSEMOVE: this->Invoke(L"WM_MOUSEDRAGMOVE\0", wParam, lParam, (void*)this); break; } } if (!HitTest(vPos, vDir)) { if (m_bMouseOver) { m_bMouseOver = FALSE; Invoke(L"WM_MOUSELEAVE", NULL, NULL, (void*)this); } return FALSE; } for (vector<IEventManager*>::iterator it =m_Children.begin(); it != m_Children.end(); ++it) { ret = (*it)->PassMouseMessage(message, wParam, lParam, vPos, vDir); if (ret) { if (m_bMouseOver) { m_bMouseOver = FALSE; Invoke(L"WM_MOUSELEAVE", NULL, NULL, (void*)this); } return TRUE; } } if (!m_bMouseOver) { m_bMouseOver = TRUE; Invoke(L"WM_MOUSEENTER", NULL, NULL, (void*)this); } switch (message) { case WM_LBUTTONDOWN: this->Invoke(L"WM_LBUTTONDOWN\0", wParam, lParam, (void*)this); break; case WM_LBUTTONUP: this->Invoke(L"WM_LBUTTONUP\0", wParam, lParam, (void*)this); break; case WM_MOUSEMOVE: this->Invoke(L"WM_MOUSEMOVE\0", wParam, lParam, (void*)this); break; } return TRUE; } BOOL MSEventManager::Bind( WCHAR* msg, TaskFuncPtr pFunc , void* _THIS) { map<WCHAR*, vector<EventTask>, cmp_wstr>::iterator it = m_EventTable.find(msg); if (it == m_EventTable.end()) { vector<EventTask> eventtask; m_EventTable[msg] = eventtask; } EventTask newTask(pFunc, _THIS); for (vector<EventTask>::iterator it2 = m_EventTable[msg].begin(); it2 != m_EventTable[msg].end(); ++it2) { if ((*it2) == newTask) { return FALSE; } } m_EventTable[msg].push_back(newTask); return TRUE; } BOOL MSEventManager::UnBind(WCHAR* msg, TaskFuncPtr pFunc, void* _THIS) { map<WCHAR*, vector<EventTask>, cmp_wstr>::iterator it = m_EventTable.find(msg); if (it == m_EventTable.end()) { return FALSE; } EventTask newTask(pFunc, _THIS); for (vector<EventTask>::iterator it2 = m_EventTable[msg].begin(); it2 != m_EventTable[msg].end(); ++it2) { if ((*it2) == newTask) { m_EventTable[msg].erase(it2); return FALSE; } } return TRUE; } BOOL MSEventManager::Invoke(WCHAR* msg, WPARAM wParam, LPARAM lParam, void* pData) { map<WCHAR*, vector<EventTask>, cmp_wstr>::iterator it = m_EventTable.find(msg); if (it == m_EventTable.end()) { return FALSE; } for (vector<EventTask>::iterator it2 = m_EventTable[msg].begin(); it2 != m_EventTable[msg].end(); ++it2) { BOOL (__stdcall* pTask)(void*, WPARAM, LPARAM, void*) = (*it2).funcPtr; pTask((*it2)._THIS, wParam, lParam, pData); } return TRUE; } BOOL MS3DButton::HitTest(D3DXVECTOR3& vPos, D3DXVECTOR3& vDir) { BOOL hit = FALSE; DWORD FaceIndex = 0; FLOAT U = 0; FLOAT V = 0; FLOAT Dist = 0; LPD3DXBUFFER pAllHits = NULL; DWORD CountOfHits = 0; HRESULT hr; D3DXMATRIX matWorld = GetTransform(); D3DXMATRIX matInvWorld; D3DXMatrixInverse(&matInvWorld, NULL, &matWorld); D3DXVECTOR3 tranPos(0,0,0); D3DXVECTOR3 tranDir(0,0,0); D3DXVec3TransformCoord(&tranPos, &vPos, &matInvWorld); D3DXVec3TransformNormal(&tranDir, &vDir, &matInvWorld); hr = D3DXIntersect(m_pMesh, &(D3DXVECTOR3(tranPos.x, tranPos.y, tranPos.z)), &(D3DXVECTOR3(tranDir.x, tranDir.y, tranDir.z)), &hit, &FaceIndex, &U, &V, &Dist, &pAllHits, &CountOfHits); return hit; } BOOL MS3DButton::OnMouseLDown(void* _THIS, WPARAM wParam, LPARAM lParam, void* pData) { ((MS3DButton*)_THIS)->m_color = D3DCOLOR_ARGB(255,128,0,0); ((MS3DButton*)_THIS)->m_bStargDrag = TRUE; return TRUE; } BOOL MS3DButton::OnMouseLUp(void* _THIS, WPARAM wParam, LPARAM lParam, void* pData) { ((MS3DButton*)_THIS)->m_color = D3DCOLOR_ARGB(255,255,0,0); return TRUE; } BOOL MS3DButton::OnMouseMove(void* _THIS, WPARAM wParam, LPARAM lParam, void* pData) { return TRUE; } BOOL MS3DButton::OnMouseEnter(void* _THIS, WPARAM wParam, LPARAM lParam, void* pData) { ((MS3DButton*)_THIS)->m_color = D3DCOLOR_ARGB(255,255,0,0); return TRUE; } BOOL MS3DButton::OnMouseLeave(void* _THIS, WPARAM wParam, LPARAM lParam, void* pData) { ((MS3DButton*)_THIS)->m_color = D3DCOLOR_ARGB(255,255,255,255); return TRUE; } BOOL MS3DButton::OnMouseDragMove(void* _THIS, WPARAM wParam, LPARAM lParam, void* pData) { return TRUE; }
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 1320 ] ] ]
6029dc3626699c9e347ed095281e984c10ce1b50
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/validators/DTD/DTDGrammar.hpp
2447b3cf199dc3e1a76bbeb22ec980609582682f
[]
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
14,600
hpp
/* * Copyright 1999-2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DTDGrammar.hpp 191054 2005-06-17 02:56:35Z jberry $ */ #if !defined(DTDGRAMMAR_HPP) #define DTDGRAMMAR_HPP #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/NameIdPool.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> #include <xercesc/validators/DTD/DTDElementDecl.hpp> #include <xercesc/validators/DTD/DTDEntityDecl.hpp> #include <xercesc/framework/XMLDTDDescription.hpp> XERCES_CPP_NAMESPACE_BEGIN // // This class stores the DTD information // NOTE: DTDs are not namespace aware, so we just use regular NameIdPool // data structures to store element and attribute decls. They are all set // to be in the global namespace and the full QName is used as the base name // of the decl. This means that all the URI parameters below are expected // to be null pointers (and anything else will cause an exception.) // class VALIDATORS_EXPORT DTDGrammar : public Grammar { public: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- DTDGrammar(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); virtual ~DTDGrammar(); // ----------------------------------------------------------------------- // Implementation of Virtual Interface // ----------------------------------------------------------------------- virtual Grammar::GrammarType getGrammarType() const; virtual const XMLCh* getTargetNamespace() const; // this method should only be used while the grammar is being // constructed, not while it is being used // in a validation episode! virtual XMLElementDecl* findOrAddElemDecl ( const unsigned int uriId , const XMLCh* const baseName , const XMLCh* const prefixName , const XMLCh* const qName , unsigned int scope , bool& wasAdded ) ; virtual unsigned int getElemId ( const unsigned int uriId , const XMLCh* const baseName , const XMLCh* const qName , unsigned int scope ) const ; virtual const XMLElementDecl* getElemDecl ( const unsigned int uriId , const XMLCh* const baseName , const XMLCh* const qName , unsigned int scope ) const ; virtual XMLElementDecl* getElemDecl ( const unsigned int uriId , const XMLCh* const baseName , const XMLCh* const qName , unsigned int scope ); virtual const XMLElementDecl* getElemDecl ( const unsigned int elemId ) const; virtual XMLElementDecl* getElemDecl ( const unsigned int elemId ); virtual const XMLNotationDecl* getNotationDecl ( const XMLCh* const notName ) const; virtual XMLNotationDecl* getNotationDecl ( const XMLCh* const notName ); virtual bool getValidated() const; virtual XMLElementDecl* putElemDecl ( const unsigned int uriId , const XMLCh* const baseName , const XMLCh* const prefixName , const XMLCh* const qName , unsigned int scope , const bool notDeclared = false ); virtual unsigned int putElemDecl ( XMLElementDecl* const elemDecl , const bool notDeclared = false ) ; virtual unsigned int putNotationDecl ( XMLNotationDecl* const notationDecl ) const; virtual void setValidated(const bool newState); virtual void reset(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- // deprecated. returns the ID of the root element; not // useable in multithreaded environments! unsigned int getRootElemId() const; const DTDEntityDecl* getEntityDecl(const XMLCh* const entName) const; DTDEntityDecl* getEntityDecl(const XMLCh* const entName); NameIdPool<DTDEntityDecl>* getEntityDeclPool(); const NameIdPool<DTDEntityDecl>* getEntityDeclPool() const; NameIdPoolEnumerator<DTDElementDecl> getElemEnumerator() const; NameIdPoolEnumerator<DTDEntityDecl> getEntityEnumerator() const; NameIdPoolEnumerator<XMLNotationDecl> getNotationEnumerator() const; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- // deprecated. Not usable in multithreaded environments void setRootElemId(unsigned int rootElemId); virtual void setGrammarDescription( XMLGrammarDescription*); virtual XMLGrammarDescription* getGrammarDescription() const; // ----------------------------------------------------------------------- // Content management methods // ----------------------------------------------------------------------- unsigned int putEntityDecl(DTDEntityDecl* const entityDecl) const; // ----------------------------------------------------------------------- // Notification that lazy data has been deleted // ----------------------------------------------------------------------- static void reinitDfltEntities(); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(DTDGrammar) private: // ----------------------------------------------------------------------- // Private helper methods // ----------------------------------------------------------------------- void resetEntityDeclPool(); // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DTDGrammar(const DTDGrammar &); DTDGrammar& operator = (const DTDGrammar&); // ----------------------------------------------------------------------- // Private data members // // fElemDeclPool // This is the element decl pool. It contains all of the elements // declared in the DTD (and their associated attributes.) // // fElemNonDeclPool // This is the element decl pool that is is populated as new elements // are seen in the XML document (not declared in the DTD), and they // are given default characteristics. // // fEntityDeclPool // This is a pool of EntityDecl objects, which contains all of the // general entities that are declared in the DTD subsets, plus the // default entities (such as &gt; &lt; ...) defined by the XML Standard. // // fNotationDeclPool // This is a pool of NotationDecl objects, which contains all of the // notations declared in the DTD subsets. // // fRootElemId // The id of the root element that we found in the DOCTYPE statement. // Its initialized to ContentModel::fgInvalidElemId, so that its // invalid unless we have a DOCTYPE. // // fValidated // Indicates if the content of the Grammar has been pre-validated // or not. When using a cached grammar, no need for pre content // validation. // // fGramDesc: adopted // // ----------------------------------------------------------------------- static NameIdPool<DTDEntityDecl>* fDefaultEntities; MemoryManager* fMemoryManager; NameIdPool<DTDElementDecl>* fElemDeclPool; NameIdPool<DTDElementDecl>* fElemNonDeclPool; NameIdPool<DTDEntityDecl>* fEntityDeclPool; NameIdPool<XMLNotationDecl>* fNotationDeclPool; XMLDTDDescription* fGramDesc; unsigned int fRootElemId; bool fValidated; friend class XMLInitializer; }; // --------------------------------------------------------------------------- // DTDGrammar: Getter methods // --------------------------------------------------------------------------- inline unsigned int DTDGrammar::getRootElemId() const { return fRootElemId; } // --------------------------------------------------------------------------- // DTDGrammar: Getter methods // --------------------------------------------------------------------------- inline NameIdPoolEnumerator<DTDElementDecl> DTDGrammar::getElemEnumerator() const { return NameIdPoolEnumerator<DTDElementDecl>(fElemDeclPool, fMemoryManager); } inline NameIdPoolEnumerator<DTDEntityDecl> DTDGrammar::getEntityEnumerator() const { return NameIdPoolEnumerator<DTDEntityDecl>(fEntityDeclPool, fMemoryManager); } inline NameIdPoolEnumerator<XMLNotationDecl> DTDGrammar::getNotationEnumerator() const { return NameIdPoolEnumerator<XMLNotationDecl>(fNotationDeclPool, fMemoryManager); } inline const DTDEntityDecl* DTDGrammar::getEntityDecl(const XMLCh* const entName) const { DTDEntityDecl* decl = fDefaultEntities->getByKey(entName); if (!decl) return fEntityDeclPool->getByKey(entName); return decl; } inline DTDEntityDecl* DTDGrammar::getEntityDecl(const XMLCh* const entName) { DTDEntityDecl* decl = fDefaultEntities->getByKey(entName); if (!decl) return fEntityDeclPool->getByKey(entName); return decl; } inline NameIdPool<DTDEntityDecl>* DTDGrammar::getEntityDeclPool() { return fEntityDeclPool; } inline const NameIdPool<DTDEntityDecl>* DTDGrammar::getEntityDeclPool() const { return fEntityDeclPool; } // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- inline void DTDGrammar::setRootElemId(unsigned int rootElemId) { fRootElemId = rootElemId; } inline unsigned int DTDGrammar::putEntityDecl(DTDEntityDecl* const entityDecl) const { return fEntityDeclPool->put(entityDecl); } // --------------------------------------------------------------------------- // DTDGrammar: Virtual methods // --------------------------------------------------------------------------- inline Grammar::GrammarType DTDGrammar::getGrammarType() const { return Grammar::DTDGrammarType; } inline const XMLCh* DTDGrammar::getTargetNamespace() const { return XMLUni::fgZeroLenString; } // Element Decl inline unsigned int DTDGrammar::getElemId (const unsigned int , const XMLCh* const , const XMLCh* const qName , unsigned int) const { // // In this case, we don't return zero to mean 'not found', so we have to // map it to the official not found value if we don't find it. // const DTDElementDecl* decl = fElemDeclPool->getByKey(qName); if (!decl) return XMLElementDecl::fgInvalidElemId; return decl->getId(); } inline const XMLElementDecl* DTDGrammar::getElemDecl( const unsigned int , const XMLCh* const , const XMLCh* const qName , unsigned int) const { const XMLElementDecl* elemDecl = fElemDeclPool->getByKey(qName); if (!elemDecl && fElemNonDeclPool) elemDecl = fElemNonDeclPool->getByKey(qName); return elemDecl; } inline XMLElementDecl* DTDGrammar::getElemDecl (const unsigned int , const XMLCh* const , const XMLCh* const qName , unsigned int) { XMLElementDecl* elemDecl = fElemDeclPool->getByKey(qName); if (!elemDecl && fElemNonDeclPool) elemDecl = fElemNonDeclPool->getByKey(qName); return elemDecl; } inline const XMLElementDecl* DTDGrammar::getElemDecl(const unsigned int elemId) const { // Look up this element decl by id return fElemDeclPool->getById(elemId); } inline XMLElementDecl* DTDGrammar::getElemDecl(const unsigned int elemId) { // Look up this element decl by id return fElemDeclPool->getById(elemId); } inline unsigned int DTDGrammar::putElemDecl(XMLElementDecl* const elemDecl, const bool notDeclared) { if (notDeclared) { if(!fElemNonDeclPool) fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager); return fElemNonDeclPool->put((DTDElementDecl*) elemDecl); } return fElemDeclPool->put((DTDElementDecl*) elemDecl); } // Notation Decl inline const XMLNotationDecl* DTDGrammar::getNotationDecl(const XMLCh* const notName) const { return fNotationDeclPool->getByKey(notName); } inline XMLNotationDecl* DTDGrammar::getNotationDecl(const XMLCh* const notName) { return fNotationDeclPool->getByKey(notName); } inline unsigned int DTDGrammar::putNotationDecl(XMLNotationDecl* const notationDecl) const { return fNotationDeclPool->put(notationDecl); } inline bool DTDGrammar::getValidated() const { return fValidated; } inline void DTDGrammar::setValidated(const bool newState) { fValidated = newState; } XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 428 ] ] ]
e564a32737c334da65dcd49935a46f39b42a2a62
f7b5d803225fa1fdbcc22b69d8cc083691c68f01
/cvaddon_stereo/cvaddon_stereo_calib.h
1b626be43613f31c24a6331d7acea1f00cf8223b
[]
no_license
a40712344/cvaddon
1b3e4b8295eaea3b819598bb7982aa1ba786cb57
e7ebbef09b864b98cce14f0151cef643d2e6bf9d
refs/heads/master
2020-05-20T07:18:49.379088
2008-12-09T03:40:11
2008-12-09T03:40:11
35,675,249
0
0
null
null
null
null
UTF-8
C++
false
false
3,023
h
#pragma once // Data structures and functions dealing with // stereo camera calibration // REQUIRES: MATLAB io libraries #include <cv.h> // OpenCV #include <mat.h> // MATLAB #include <iostream> using std::cerr; using std::endl; // Make sure to include MATLAB .mat io libraries //#pragma comment(lib, "libmat.lib") //#pragma comment(lib, "libmx.lib") // Parameters of single cameras in stereo pair struct CvAddonCameraIntrinsics { double fc[2]; // Focal length double cc[2]; // Focal Center double kc[5]; // Distortion parameters }; // Relationship between stereo camera pair struct CvAddonStereoParameters { double R[9]; // 3x3 double T[3]; double om[3]; CvSize imgSize; // In pixels CvAddonCameraIntrinsics left; CvAddonCameraIntrinsics right; }; // Reads MATLAB .MAT file from stereo calibration and // fills calibration data structure int fillStereoDataFromFile(const char *filename, CvAddonStereoParameters &param , const bool& loadIndividualCameras = false); int fillCameraDataFromFile(const char *filename, CvAddonCameraIntrinsics &param); void printCameraData(const CvAddonCameraIntrinsics& param); void printStereoData(const CvAddonStereoParameters &param); // Utility function to copy MATLAB data to a variable, including error checks inline bool copyMatlabData(MATFile *mfile, const char* varName, double *dst, const int& size) { mxArray *tmp = matGetVariable(mfile, varName); if(tmp == NULL) return false; double *data = mxGetPr(tmp); if(data == NULL) return false; memcpy(dst, data, sizeof(double)*size); mxDestroyArray(tmp); return true; } // Normalizes 2D locations of pixels given camera instrinsics // Based on normalize.m and comp_distortion_oulu.m from // the MATLAB calibration toolbox inline void normalizePixel(const CvPoint2D32f &pt, const CvAddonCameraIntrinsics &params, CvPoint2D32f &result) { static const int UNDISTORT_ITERATIONS = 20; result.x = (pt.x - params.cc[0]) / params.fc[0]; result.y = (pt.y - params.cc[1]) / params.fc[1]; // Lens Distortion float k1 = params.kc[0]; float k2 = params.kc[1]; float k3 = params.kc[4]; float p1 = params.kc[2]; float p2 = params.kc[3]; // Iterative undistort CvPoint2D32f tmp = result; // Initial guess CvPoint2D32f delta; int i; float r_2, k_radial; for(i = 0; i < UNDISTORT_ITERATIONS; ++i) { // r_2 = sum(x.^2); r_2 = tmp.x*tmp.x + tmp.y*tmp.y; // k_radial = 1 + k1 * r_2 + k2 * r_2.^2 + k3 * r_2.^3; k_radial = 1 + k1*r_2 + k2*r_2*r_2 + k3*r_2*r_2*r_2; //delta_x = [2*p1*x(1,:).*x(2,:) + p2*(r_2 + 2*x(1,:).^2); // p1 * (r_2 + 2*x(2,:).^2)+2*p2*x(1,:).*x(2,:)]; delta.x = 2*p1*tmp.x*tmp.y + p2*(r_2 + 2*tmp.x*tmp.x); delta.y = p1*(r_2 + 2*tmp.y*tmp.y) + 2*p2*tmp.x*tmp.y; //x = (xd - delta_x)./(ones(2,1)*k_radial); tmp.x = (result.x - delta.x) / k_radial; tmp.y = (result.y - delta.y) / k_radial; } result = tmp; }
[ "waiho@66626562-0408-11df-adb7-1be7f7e3f636" ]
[ [ [ 1, 106 ] ] ]
e562e0d0490e0624ceda2025e7bc8d310847e47a
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/ScdLib/TKNPARS.CPP
0133c0c52a0b30b827c329cb1bf50762c3f7fb86
[]
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
25,529
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #define __TKNPARS_CPP #include "sc_defs.h" #include "tknpars.h" #include "licbase.h" #include <fstream> //========================================================================== CTokenFileInfo::CTokenFileInfo(CTokenParser* Parser, byte Places, char* FileName, BOOL UseIncludes) { bFnPlaces=Places; pParser = Parser; bUseIncludes = UseIncludes; SetParameters(); FileNames[iFileIndex] = FileName; sIncludeChars = ">>"; } //---------------------------------------------------------------------------- CTokenFileInfo::~CTokenFileInfo() { Close(); } //---------------------------------------------------------------------------- /*#F:Used internally to reset flags etc.*/ void CTokenFileInfo::SetParameters() { Back[0] = 0; bAtEOF = 0; bPartLine = 0; for (int i=0; i<TP_MaxIncludeFiles; i++) { File[i] = NULL; FileLineNo[i] = 0L; } iFileIndex = 0; iIncFileCnt = 0; } void CTokenFileInfo::DecryptToBuffer(Strng encFnFull) { fclose(File[iFileIndex]); std::fstream fin; fin.open(encFnFull(), std::ios::in|std::ios::binary); if (fin.is_open()) { fin.seekg(0, std::ios_base::end); int length = fin.tellg(); fin.seekg(0, std::ios_base::beg); m_Buffer[iFileIndex] = new char[length+1]; fin.read(m_Buffer[iFileIndex], length); fin.close(); int count = fin.gcount(); m_Buffer[iFileIndex][count] = (char)length; int seed = length; for (int i=count-1; i>=0; i--) // decrypt the buffer. { seed *= 1103515245; seed += 12345; // add some deterministic noise to the system. m_Buffer[iFileIndex][i] = m_Buffer[iFileIndex][i] ^ m_Buffer[iFileIndex][i+1] ^ i ^ seed; } m_Buffer[iFileIndex][count] = 0; } fin.close(); m_SS[iFileIndex] = new std::stringstream(m_Buffer[iFileIndex]); File[iFileIndex] = fopen(encFnFull(), "rt"); } bool CTokenFileInfo::OpenFile(Strng FnFull) { gs_EncryptNDemos.CheckForDemo(NULL); Strng encFnFull; encFnFull = FnFull; encFnFull.Append(".x"); File[iFileIndex] = fopen(encFnFull(), "rt"); if (File[iFileIndex] == NULL) { // Encrypted file nonexistent. m_Buffer[iFileIndex] = NULL; File[iFileIndex] = fopen(FnFull(), "rt"); if (File[iFileIndex] == NULL) return False; } else { // Encrypted file found. gs_EncryptNDemos.encryptedPGM = true; DecryptToBuffer(encFnFull); } return true; } //---------------------------------------------------------------------------- /*#F:Opens the primary file for parsing.#R:True if successfully opened.*/ BOOL CTokenFileInfo::Open() { ASSERT(File[0]==NULL); //file is allready open SetParameters(); CString &Fn = FileNames[iFileIndex]; CString FnO = Fn; /*if (FnO.GetLength()>3 && FnO[0]=='.' && FnO[1]=='.' && FnO[2]=='\\') { FnO = PrjPrevDirectory(); FnO += Fn.Right(Fn.GetLength()-3); }*/ AllFileNames[iIncFileCnt] = FnO; Strng FnFull = FnO; bool result = OpenFile(FnFull); //File[iFileIndex] = fopen((const char*)FnO, "rt"); FnModifyTime((char*)(const char*)FnO, FileTimes[iFileIndex]); AllFileTimes[iIncFileCnt]=FileTimes[iFileIndex]; iIncFileCnt++; return result; //if (File[iFileIndex] == NULL) // return FALSE; //return TRUE; } //---------------------------------------------------------------------------- /*#F:Closes all remaining open files (if any)*/ void CTokenFileInfo::Close() { for (int i=iFileIndex; i>=0; i--) { if (File[i] != NULL) { fclose(File[i]); delete m_Buffer[i]; File[i] = NULL; } } } //---------------------------------------------------------------------------- void CTokenFileInfo::SetFileName(char* FileName) { SetParameters(); FileNames[iFileIndex] = FileName; } //---------------------------------------------------------------------------- BOOL CTokenFileInfo::CheckForInclude() { if (bUseIncludes && (pParser->sTokenLine[0]==sIncludeChars[0])) { CString FileName = pParser->sTokenLine; if (pParser->sTokenLine.Find((const char*)sIncludeChars)==0) { FileName = FileName.Mid(sIncludeChars.GetLength(), 1024); FileName = FileName.Right(FileName.GetLength() - FileName.SpanIncluding(" \t").GetLength()); while (FileName.GetLength()>0 && (FileName[FileName.GetLength()-1]==' ' || FileName[FileName.GetLength()-1]=='\t')) FileName = FileName.Left(FileName.GetLength()-1); BOOL Failed = TRUE; DWORD ErrNo = 1;//file not specified if (FileName.GetLength()>0) { if (FileName[0]=='\'' || FileName[0]=='"') FileName = FileName.Right(FileName.GetLength() - 1); int len = FileName.GetLength(); if (len>0) { if (FileName[len-1]=='\'' || FileName[len-1] == '"') FileName = FileName.Left(len-1); len = FileName.GetLength(); if (len>0) { iFileIndex++; if (iFileIndex<TP_MaxIncludeFiles) { Strng Fn, FnFull; Fn.FnDrivePath((char*)(const char*)FileName); if (Fn()==NULL) {// No Path Use Previous Fn.FnDrivePath((char*)(const char*)FileNames[iFileIndex-1]); Fn+=(char*)(const char*)FileName; // FileName=Fn(); } else Fn=(char*)(const char*)FileName; // CNM if ((Fn[0]=='~') || (Fn[0]=='.')) // relative filename ? { // yes - prepend current folder (defined by previously openned file - NOT O/S Strng T; T.FnDrivePath((LPTSTR)(LPCTSTR)AllFileNames[iIncFileCnt-1]); T+=Fn; Fn=T; } FnFull.FnSearchExpand(Fn(), bFnPlaces); Fn.FnContract(); FileName=Fn(); FileNames[iFileIndex] = Fn(); pParser->wLineNo--; FileLineNo[iFileIndex] = 0; Failed = !OpenFile(FnFull); //File[iFileIndex] = fopen(FnFull(), "rt"); FnModifyTime(FnFull(), FileTimes[iFileIndex]); if (iIncFileCnt<TP_MaxTtlIncludeFiles) { AllFileNames[iIncFileCnt]=Fn(); AllFileTimes[iIncFileCnt]=FileTimes[iFileIndex]; iIncFileCnt++; } if (Failed) ErrNo = 2;//cannot open file } else ErrNo = 3;//too many nested includes } } } if (Failed && pParser->pFailFn) { (*(pParser->pFailFn))((char*)(const char*)FileName, ErrNo, pParser->pFailExtraPtr); } return TRUE; } } return FALSE; } char* CTokenFileInfo::ssgets(char* buf, int maxCount) { if (!(m_SS[iFileIndex]->eof())) { m_SS[iFileIndex]->getline(buf, maxCount); } char* match = strchr(buf, 13); if (match != NULL) match[0] = 0; // handle strange line-end characters. return buf; } //---------------------------------------------------------------------------- void CTokenFileInfo::NextLine() { if (File[iFileIndex]!=NULL) { // Add any characters from last time round to buffer int k = strlen(Back); if (k>0) { strrev(Back); strncpy(pParser->Line, Back, k); } char* p = NULL; if (m_Buffer[iFileIndex] == NULL) // No buffer -- reading straight from file. p = fgets((char*)&(pParser->Line[k]), sizeof(pParser->Line) - 1 - k, File[iFileIndex]); else // we've got a buffer, use that instead. { p = ssgets((char*)&(pParser->Line[k]), sizeof(pParser->Line) - 1 - k); } //char* p = fgets((char*)&(pParser->Line[k]), sizeof(pParser->Line) - 1 - k, File[iFileIndex]); if (p==NULL) { if (iFileIndex>0) { pParser->wLineNo--; fclose(File[iFileIndex]); delete m_Buffer[iFileIndex]; File[iFileIndex] = NULL; iFileIndex--; NextLine(); } else bAtEOF = 1; } else { int j = strlen(pParser->Line); if (j==TP_MaxLineLen-2) {//strip chars from the end of the buffer until the next seperator if (bPartLine) pParser->wLineNo--; bPartLine = 1; char *pos = &(pParser->Line[j-1]); char *buf = &Back[0]; *buf = 0; while (strchr(pParser->SeperatorSet, (int)(*pos))==NULL) { *buf = *pos; buf++; *buf = 0; *pos = 0; pos--; VERIFY(pos != pParser->Line); //("Line (without seperator) longer than backup buffer"); } } else { if (bPartLine) pParser->wLineNo--; bPartLine = 0; Back[0] = 0; } //if ((pParser->Line[strlen(p)+k-1] == 10) || (pParser->Line[strlen(p)+k-1] == 13)) if (pParser->Line[strlen(p)+k-1]==10) pParser->Line[strlen(p)+k-1] = 0; } } else { if (iFileIndex>0) { File[iFileIndex] = NULL; iFileIndex--; } else bAtEOF = 1; pParser->bNewLine = 1; pParser->sTokenLine = ""; return; } pParser->bNewLine = 1; pParser->wLineNo++; FileLineNo[iFileIndex]++; pParser->sTokenLine = (char*)&(pParser->Line[0]); } //========================================================================== CTokenBufferInfo::CTokenBufferInfo(CTokenParser* Parser, char* pTxt) { bUseLineEnd = 0; pParser = Parser; pBigBuff = NULL; bMyBigBuff = 0; SetParameters(); SetBuffer(pTxt); } //---------------------------------------------------------------------------- CTokenBufferInfo::CTokenBufferInfo(CTokenParser* Parser) { bUseLineEnd = 0; pParser = Parser; pBigBuff = NULL; bMyBigBuff = 0; SetParameters(); } //---------------------------------------------------------------------------- CTokenBufferInfo::~CTokenBufferInfo() { Close(); } //---------------------------------------------------------------------------- /*#F:Used internally to reset flags etc.*/ void CTokenBufferInfo::SetParameters() { bAtEOBuff = 0; bPartLine = 0; iBuffPos = 0; } //---------------------------------------------------------------------------- /*#F:Opens the primary file for parsing.#R:True if successfully opened.*/ BOOL CTokenBufferInfo::Open() { SetParameters(); if (pBigBuff) return TRUE; return FALSE; } //---------------------------------------------------------------------------- /*#F:Closes all remaining open files (if any)*/ void CTokenBufferInfo::Close() { if (pBigBuff && bMyBigBuff) { delete pBigBuff; pBigBuff = NULL; bMyBigBuff = 0; } } //---------------------------------------------------------------------------- void CTokenBufferInfo::SetBuffer(char* pTxt) { if (pBigBuff && bMyBigBuff) delete pBigBuff; int len = 0; if (pTxt) len = strlen(pTxt); pBigBuff = new char[len+1]; bMyBigBuff = 1; if (len>0) strcpy(pBigBuff, pTxt); pBigBuff[len] = 0; iBuffPos = 0; } //---------------------------------------------------------------------------- void CTokenBufferInfo::SetFarBuffer(char* pTxt) { if (pBigBuff && bMyBigBuff) delete pBigBuff; pBigBuff = pTxt; bMyBigBuff = 0; iBuffPos = 0; } //---------------------------------------------------------------------------- void CTokenBufferInfo::NextLine() { pParser->Line[0] = 0; if (pBigBuff[iBuffPos]==0) { bAtEOBuff = 1; pParser->bNewLine = 1; pParser->sTokenLine = ""; return; } int CopyLen = (bUseLineEnd ? 0 : strlen(&pBigBuff[iBuffPos])); int SepLen = (bUseLineEnd ? sLineEnd.GetLength() : 0); if (bUseLineEnd) { BOOL Found = FALSE; int Pos = 0; while (!Found) { char* p = strchr(&pBigBuff[iBuffPos+Pos], sLineEnd[0]); if (p) { int Pos1 = (p - &pBigBuff[iBuffPos+Pos]); Found = (strncmp((const char*)sLineEnd, p, sLineEnd.GetLength())==0); if (Found) CopyLen = Pos+Pos1; else Pos += (Pos1 + 1); } else { Found = TRUE; SepLen = 0; CopyLen = strlen(&pBigBuff[iBuffPos]); } } } if (CopyLen>=TP_MaxLineLen) { if (bPartLine) pParser->wLineNo--; bPartLine = 1; CopyLen = TP_MaxLineLen-1; while (strchr(pParser->SeperatorSet, (int)(pBigBuff[iBuffPos+CopyLen]))==NULL && CopyLen>0) CopyLen--; //VERIFY(CopyLen>0);//("Line (without seperator) longer than line buffer length"); if (CopyLen==0) CopyLen = TP_MaxLineLen-1; strncpy(pParser->Line, &pBigBuff[iBuffPos], CopyLen); pParser->Line[CopyLen] = 0; iBuffPos += CopyLen; } else { if (bPartLine) pParser->wLineNo--; bPartLine = 0; strncpy(pParser->Line, &pBigBuff[iBuffPos], CopyLen); pParser->Line[CopyLen] = 0; iBuffPos += (CopyLen+SepLen); } pParser->wLineNo++; pParser->bNewLine = 1; pParser->sTokenLine = pParser->Line; } //========================================================================== CTokenParser::CTokenParser(BOOL IgnoreComments/* = TRUE*/, //default = True BOOL UseStringChar/* = TRUE*/) //default = True { bFnPlaces=0; bIgnoreComments = IgnoreComments; bUseStringChar = UseStringChar; CommonConstruct(); } //---------------------------------------------------------------------------- /*#f:Constructer for token file parser. The file name is the only required parameter. Defaults are set: whitespace (space and tab), seperators (,), string char (") and file include characters (>>).*/ CTokenParser::CTokenParser(byte Places, char* FileName, //path and file name BOOL IgnoreComments, //default = True BOOL UseStringChar, //default = True BOOL UseIncludes) //default = True { bFnPlaces=Places; bIgnoreComments = IgnoreComments; bUseStringChar = UseStringChar; CommonConstruct(); pFileInfo = new CTokenFileInfo(this, Places, FileName, UseIncludes); } //---------------------------------------------------------------------------- CTokenParser::CTokenParser(BOOL IgnoreComments, BOOL UseStringChar, char* pTxt) { bFnPlaces=0; bIgnoreComments = IgnoreComments; bUseStringChar = UseStringChar; CommonConstruct(); pBuffInfo = new CTokenBufferInfo(this, pTxt); } //---------------------------------------------------------------------------- /*#F:Destructor, closes any unclosed files.*/ CTokenParser::~CTokenParser() { if (pFileInfo) delete pFileInfo; if (pBuffInfo) delete pBuffInfo; } //---------------------------------------------------------------------------- void CTokenParser::CommonConstruct() { memset(Line, 0, sizeof(Line)); sCurTok = ""; sTokenLine = ""; wLineNo = 0; bLastToken = 0; bFirstToken = 0; bReturnSameToken = 0; bNewLine = 1; bDoneStart = 0; bDoneEnd = 0; bAtEnd = 0; //SetParameters(); WhiteSpaceSet[0] = 32; //space WhiteSpaceSet[1] = 9; //tab WhiteSpaceSet[2] = 0; iWhiteSpaceSetLen = strlen(WhiteSpaceSet); strncpy(SeperatorSet, ",", sizeof(SeperatorSet)); iSeperatorSetLen = strlen(SeperatorSet); cStringChar = '"'; pFileInfo = NULL; pBuffInfo = NULL; pFailFn = NULL; pFailExtraPtr = NULL; } //---------------------------------------------------------------------------- /*#F:Used to specify characters to be ignored as 'whitespace'.*/ void CTokenParser::SetWhiteSpace(char* pNewWhiteSpace) { strncpy(WhiteSpaceSet, pNewWhiteSpace, sizeof(WhiteSpaceSet)); WhiteSpaceSet[sizeof(WhiteSpaceSet)-1] = 0; iWhiteSpaceSetLen = strlen(WhiteSpaceSet); } //---------------------------------------------------------------------------- /*#F:This sets the characters to treated as individual tokens and therefore, token seperators. Every new line is automatically a seperator. If comments are being used, (;) must be included as a seperator for comments part way through a line to be ignored. #E:f.SetSeperators("[]{}<>; /"-+/*=")*/ void CTokenParser::SetSeperators(char* pNewSeperators) { strncpy(SeperatorSet, pNewSeperators, sizeof(SeperatorSet)); SeperatorSet[sizeof(SeperatorSet)-1] = 0; iSeperatorSetLen = strlen(SeperatorSet); } //---------------------------------------------------------------------------- /*#F:#R:True if successfully opened.*/ BOOL CTokenParser::Start() { ASSERT(bDoneStart==0); Line[0] = 0; sCurTok = ""; sTokenLine = ""; wLineNo = 0; bLastToken = 0; bFirstToken = 0; bReturnSameToken = 0; bAtEnd = 0; bNewLine = 1; BOOL b = FALSE; if (pFileInfo) b = pFileInfo->Open(); else if (pBuffInfo) b = pBuffInfo->Open(); bDoneStart = b; bDoneEnd = 0; return b; } //---------------------------------------------------------------------------- /*#F:Closes all remaining open files (if any)*/ void CTokenParser::End() { ASSERT(bDoneStart); ASSERT(bDoneEnd==0); if (pFileInfo) pFileInfo->Close(); bDoneEnd = 1; bDoneStart = 0; } //---------------------------------------------------------------------------- void CTokenParser::SetFileName(char* FileName) { ASSERT(bDoneStart==0); if (!pFileInfo) pFileInfo = new CTokenFileInfo(this, bFnPlaces, FileName, FALSE); pFileInfo->SetFileName(FileName); } //---------------------------------------------------------------------------- void CTokenParser::SetBuffer(char* pTxt) { ASSERT(bDoneStart==0); if (!pBuffInfo) pBuffInfo = new CTokenBufferInfo(this, pTxt); pBuffInfo->SetBuffer(pTxt); } //---------------------------------------------------------------------------- void CTokenParser::SetFarBuffer(char* pTxt) { ASSERT(bDoneStart==0); if (!pBuffInfo) pBuffInfo = new CTokenBufferInfo(this); pBuffInfo->SetFarBuffer(pTxt); } //---------------------------------------------------------------------------- /*#F:#R:The token type of the specified string.*/ TokenTypes CTokenParser::GetTokenType(const char* p) { if (p==NULL) { return TokNull; } else { char c = p[0]; if ((c>96) && (c<123)) return TokAlpha; else if ((c>64) && (c<91)) return TokAlpha; else if ((c>47) && (c<58)) return TokNumeric; else if (c == 59) return TokComment; else if ((c > 32) && (c < 127)) return TokSymbol; else if ((c == 32) || (c == 9) || (c == 10))// || (c == 13)) return TokWhiteSpace; else return TokOther; } } //---------------------------------------------------------------------------- /*#F:Parses the current line for a token. Skips whitespace and loads succesive lines if neccessary. If ReturnSameToken BOOL was set, the line is not parsed, the current token is returned and the BOOL unset. The new token type is determined. #R:A pointer to the current token.*/ const char* CTokenParser::NextToken() { if (bReturnSameToken) { bReturnSameToken = 0; return (const char*)sCurTok; } sCurTok = ""; eTokType = TokNull; if (m_TokenQ.Length()>0) { Strng *p=m_TokenQ.First(); sCurTok=(*p)(); m_TokenQ.Remove(p); eTokType = GetTokenType((const char*)sCurTok); } else { BOOL BlankEnclosedStr = FALSE; while ((sCurTok.GetLength()==0) && (!bAtEnd) && !BlankEnclosedStr) { SkipWhiteSpace(); while ((sTokenLine.GetLength()==0) && (!bAtEnd)) { NextLine(); SkipWhiteSpace(); } if (bAtEnd) sCurTok = ""; else { bFirstToken = bNewLine; char c = sTokenLine[0]; if (pFileInfo && pFileInfo->bUseIncludes && c==pFileInfo->sIncludeChars[0]) if (pFileInfo->CheckForInclude()) {//include file found sCurTok = ""; sTokenLine = ""; return NextToken(); } if (bIgnoreComments && c==';') {//comment found sCurTok = ""; sTokenLine = ""; } else if (bUseStringChar && c==cStringChar) {//start of enclosed string found eTokType = TokString; sTokenLine = sTokenLine.Right(sTokenLine.GetLength()-1); int APos = (int)sTokenLine.Find(cStringChar); if (APos<0) { sCurTok = sTokenLine; sTokenLine = ""; } else if (APos==0) { sCurTok = ""; sTokenLine = sTokenLine.Right(sTokenLine.GetLength() - 1); BlankEnclosedStr = TRUE; } else { sCurTok = sTokenLine.Left(APos); sTokenLine = sTokenLine.Right(sTokenLine.GetLength() - APos - 1); } } else { WORD i = 0; while (i<iSeperatorSetLen && SeperatorSet[i]!=c) i++; if (i<iSeperatorSetLen) {//token seperator character found sTokenLine = sTokenLine.Right(sTokenLine.GetLength()-1); sCurTok = c; } else {//default action SkipToSeperator(sCurTok); sTokenLine = sTokenLine.Right(sTokenLine.GetLength() - sCurTok.GetLength()); } } } } if (eTokType!=TokString) eTokType = GetTokenType((const char*)sCurTok); bNewLine = 0; } bLastToken = (sTokenLine.GetLength()==0); return (const char*)sCurTok; } //---------------------------------------------------------------------------- const char* CTokenParser::NextCSVToken(CString &s) { s = NextToken(); //get value if (s==",") s = ""; else { if (!AtLastToken() && !AtEnd()) NextToken(); //get ',' separater } return (const char*)s; } //---------------------------------------------------------------------------- void CTokenParser::AddToken2Queue(LPCTSTR Tok) { m_TokenQ.Append(Tok); }; //---------------------------------------------------------------------------- /*#F:#R:The complete current token line regardless of any token seperators contained within it.*/ const char* CTokenParser::GetNextLine() { if (bNewLine) NextLine(); bNewLine = 1; if (pFileInfo && pFileInfo->bUseIncludes && sTokenLine.GetLength()>pFileInfo->sIncludeChars.GetLength() && sTokenLine[0]==pFileInfo->sIncludeChars[0]) if (pFileInfo->CheckForInclude()) {//include file found sCurTok = ""; sTokenLine = ""; return GetNextLine(); } sCurTok = sTokenLine; sTokenLine = ""; return (const char*)sCurTok; } //---------------------------------------------------------------------------- /*#F:#R:The first token found in the line supplied.*/ void CTokenParser::GetFirstToken(CString &s, //string to parse CString &Token) //returned token string { CString Temp = sTokenLine; sTokenLine = s; SkipWhiteSpace(); CString Temp2 = sTokenLine.Right(sTokenLine.GetLength()-1); Token = sTokenLine.Left(1); if (strchr(SeperatorSet, (int)(Token[0]))==NULL) Token += Temp2.SpanExcluding(SeperatorSet); s = sTokenLine; sTokenLine = Temp; } //---------------------------------------------------------------------------- /*#F:Removes all the "whitespace" characters from the left of the current line.*/ void CTokenParser::SkipWhiteSpace() { const int len = (sTokenLine.SpanIncluding(WhiteSpaceSet)).GetLength(); if (len>0) sTokenLine = sTokenLine.Right(sTokenLine.GetLength() - len); } //---------------------------------------------------------------------------- /*#F:#R:All the characters upto the first token seperator.*/ void CTokenParser::SkipToSeperator(CString & TempStr) { TempStr = sTokenLine.SpanExcluding(SeperatorSet); } //---------------------------------------------------------------------------- /*#F:Reads the next line from the file.*/ void CTokenParser::NextLine() { if (pFileInfo) { pFileInfo->NextLine(); bAtEnd = pFileInfo->AtEOF(); } else if (pBuffInfo) { pBuffInfo->NextLine(); bAtEnd = pBuffInfo->AtEOBuff(); } } //==========================================================================
[ [ [ 1, 219 ], [ 221, 894 ] ], [ [ 220, 220 ] ] ]
4f48142a790ebb7725f41142c48f8ddc9dbb4f4f
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-network/src/jingxian/string/string_token_iterator.h
17237276a30df2d9dbdd3a017ad1dbfe6071da94
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,047
h
#ifndef _string_token_iterator_ #define _string_token_iterator_ #include "jingxian/config.h" #if !defined (JINGXIAN_LACKS_PRAGMA_ONCE) # pragma once #endif /* JINGXIAN_LACKS_PRAGMA_ONCE */ // Include files # include "jingxian/string/os_string.h" _jingxian_begin template< typename C > struct string_token_iterator ITERATOR_BASE(input_iterator, tstring , ptrdiff_t) { public: typedef C char_type; typedef size_t size_type; string_token_iterator() : _ptr(0), start(0), end(0) {} template< typename S > string_token_iterator(const S & s, const char_type * separator_ = _T(" ")) : separator(separator_), _ptr(c_str_ptr(s)), end(0) { find_next(); } string_token_iterator(const string_token_iterator & rhs) : separator(rhs.separator), _ptr(rhs._ptr), start(rhs.start), end(rhs.end) { } string_token_iterator & operator++() { find_next(); return *this; } string_token_iterator operator++(int) { string_token_iterator temp(*this); ++(*this); return temp; } tstring operator*() const { return tstring(*_ptr, start, end - start); } bool operator==(const string_token_iterator & rhs) const { return (rhs._ptr == _ptr && rhs.start == start && rhs.end == end); } bool operator!=(const string_token_iterator & rhs) const { return !(rhs == *this); } private: void find_next(void) { start = _ptr->find_first_not_of(separator, end); if (start == tstring::npos) { start = end = 0; _ptr = 0; return; } end = _ptr->find_first_of(separator, start); } const char_type * separator; const char_type * const _ptr; size_type start; size_type end; }; _jingxian_end #endif // _string_token_iterator_
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 94 ] ] ]
12146161c5a1acc354e91b902e026f79470b1a0d
9756190964e5121271a44aba29a5649b6f95f506
/SimpleParam/Param/src/ModelMesh/MeshModelRender.cpp
bb79785bc2687dd6750f571bb1c33cb735c2a823
[]
no_license
feengg/Parameterization
40f71bedd1adc7d2ccbbc45cc0c3bf0e1d0b1103
f8d2f26ff83d6f53ac8a6abb4c38d9b59db1d507
refs/heads/master
2020-03-23T05:18:25.675256
2011-01-21T15:19:08
2011-01-21T15:19:08
null
0
0
null
null
null
null
GB18030
C++
false
false
31,122
cpp
/* ================== Library Information ================== */ // [Name] // MeshLib Library // // [Developer] // Xu Dong // State Key Lab of CAD&CG, Zhejiang University // // [Date] // 2005-08-05 // // [Goal] // A general, flexible, versatile and easy-to-use mesh library for research purpose. // Supporting arbitrary polygonal meshes as input, but with a // primary focus on triangle meshes. /* ================== File Information ================== */ // [Name] // MeshModelRender.cpp // // [Developer] // Xu Dong // State Key Lab of CAD&CG, Zhejiang University // // [Date] // 2005-08-05 // // [Goal] // Defining various rendering modes // Including polygon (flag/smooth), wireframe, point, texture mapping, etc #include "MeshModelRender.h" #include "../Common/Utility.h" #include <cassert> // Constructor MeshModelRender::MeshModelRender() { kernel = NULL; auxdata = NULL; } // Destructor MeshModelRender::~MeshModelRender() { } // Initialize void MeshModelRender::ClearData() { m_Mode = RENDER_MODEL_SOLID_FLAT; m_State = RENDER_MODEL_AXIS | RENDER_MODEL_BOUNDING_BOX | RENDER_MODEL_LIGHTING; m_State |= RENDER_MODEL_POINT | RENDER_MODEL_LINE | RENDER_MODEL_POLYGON; m_BbColor = WHITE; m_DftVtxColor = RED; m_DftEdgeColor = GREEN; m_DftFaceColor = BLUE; m_DftPointColor = LIGHT_RED; m_DftLineColor = LIGHT_GREEN; m_DftPolygonColor = LIGHT_BLUE; m_DftElementColor = LIGHT_GREY; m_DftHltVtxColor = YELLOW; m_DftHltEdgeColor = CYAN; m_DftFaceColor = MAGENTA; m_DftVtxSize = 3.0f; m_DftEdgeWidth = 1.5f; m_DftPointSize = 6.0f; m_DftLineWidth = 3.0f; m_DftBdyVtxSize = 3.0f; m_DftBdyEdgeWidth = 2.0f; m_DftHltVtxSize = 6.0f; m_DftHltEdgeWidth = 4.0f; m_ModelMaterial.m_Ambient[0] = 0.2f; m_ModelMaterial.m_Ambient[1] = 0.2f; m_ModelMaterial.m_Ambient[2] = 0.2f; m_ModelMaterial.m_Ambient[3] = 1.0f; m_ModelMaterial.m_Diffuse[0] = 0.8f; m_ModelMaterial.m_Diffuse[1] = 0.8f; m_ModelMaterial.m_Diffuse[2] = 0.8f; m_ModelMaterial.m_Diffuse[3] = 1.0f; m_ModelMaterial.m_Specular[0] = 0.0f; m_ModelMaterial.m_Specular[1] = 0.0f; m_ModelMaterial.m_Specular[2] = 0.0f; m_ModelMaterial.m_Specular[3] = 1.0f; m_ModelMaterial.m_Emissive[0] = 0.0f; m_ModelMaterial.m_Emissive[1] = 0.0f; m_ModelMaterial.m_Emissive[2] = 0.0f; m_ModelMaterial.m_Emissive[3] = 1.0f; m_ModelMaterial.m_Shininess = 0.0f; m_ModelMaterial.m_Transparency = 0.0f; m_ElementMaterial = m_ModelMaterial; } // Initializer void MeshModelRender::AttachKernel(MeshModelKernel* pKernel) { assert(pKernel != NULL); kernel = pKernel; ClearData(); } void MeshModelRender::AttachAuxData(MeshModelAuxData* pAuxData) { assert(pAuxData != NULL); auxdata = pAuxData; } // Rendering entrance function void MeshModelRender::DrawModel() { // set the default material here. m_DefaultMaterial.SetMaterial(); Utility util; // Whether show axis if(util.IsSetFlag(m_State, RENDER_MODEL_AXIS)) DrawAxis(); // Whether show bounding box if(util.IsSetFlag(m_State, RENDER_MODEL_BOUNDING_BOX)) DrawBoundingBox(); // Whether lighting if(util.IsSetFlag(m_State, RENDER_MODEL_LIGHTING)) glEnable(GL_LIGHTING); else glDisable(GL_LIGHTING); glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); // Whether per-element color if(util.IsSetFlag(m_State, RENDER_MODEL_COLOR)) { glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); } else glDisable(GL_COLOR_MATERIAL); switch(m_Mode) { case RENDER_MODEL_VERTICES: DrawModelDepth(); DrawModelVertices(); break; case RENDER_MODEL_WIREFRAME: DrawModelDepth(); DrawModelWireframe(); break; case RENDER_MODEL_SOLID_FLAT: DrawModelSolidFlat(); break; case RENDER_MODEL_SOLID_SMOOTH: DrawModelSolidSmooth(); break; case RENDER_MODEL_SOLID_WITH_SHARPNESS: DrawModelSolidWithSharpness(); break; case RENDER_MODEL_SOLID_AND_WIREFRAME: DrawModelSolidAndWireframe(); break; case RENDER_MODEL_HIGHLIGHT_ONLY: DrawModelHighlightOnly(); break; case RENDER_MODEL_TEXTURE_MAPPING: DrawModelTextureMapping(); break; case RENDER_MODEL_VERTEX_COLOR: DrawModelVertexColor(); break; case RENDER_MODEL_FACE_COLOR: DrawModelFaceColor(); break; case RENDER_MODEL_TRANSPARENT: DrawModelTransparent(); break; case RENDER_MODEL_PARAM_TEXTURE: DrawModelFaceTexture(); break; } glDisable(GL_LIGHTING); if(util.IsSetFlag(m_State, RENDER_MODEL_POINT)) DrawPoint(); if(util.IsSetFlag(m_State, RENDER_MODEL_LINE)) DrawLine(); if(util.IsSetFlag(m_State, RENDER_MODEL_POLYGON)) DrawPolygon(); // draw kmax and kmin here. if(util.IsSetFlag(m_State, RENDER_MODEL_KMAX_CURVATURE) || util.IsSetFlag(m_State, RENDER_MODEL_KMIN_CURVATURE)) { DrawMeshCurvature(m_State); } glEnable(GL_LIGHTING); } // Various rendering functions void MeshModelRender::DrawModelVertices() { glDisable(GL_LIGHTING); glDepthFunc(GL_LEQUAL); Color c = RED; glColor3d(c[0], c[1], c[2]); glPointSize(m_DftVtxSize); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); FlagArray& vFlag = kernel->GetVertexInfo().GetFlag(); size_t nVertex = vCoord.size(); glBegin(GL_POINTS); for(size_t i = 0; i < nVertex; ++ i) { if(util.IsSetFlag(vFlag[i], FLAG_INVALID)) continue; Coord& v = vCoord[i]; glVertex3d(v[0], v[1], v[2]); } glEnd(); glDepthFunc(GL_LESS); glEnable(GL_LIGHTING); } void MeshModelRender::DrawModelWireframe() { glDisable(GL_LIGHTING); glDepthFunc(GL_LEQUAL); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glLineWidth(m_DftEdgeWidth); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); NormalArray& fNormal = kernel->GetFaceInfo().GetNormal(); size_t nFace = fIndex.size(); size_t i, j, n; Color c = BLUE*0.70; glColor3d(c[0], c[1], c[2]); glBegin(GL_LINES); for(i = 0; i < nFace; ++ i) { IndexArray& f = fIndex[i]; n = f.size(); for(j = 0; j < n; ++ j) { Coord& v1 = vCoord[f[j]]; Coord& v2 = vCoord[f[(j+1)%n]]; glVertex3d(v1[0], v1[1], v1[2]); glVertex3d(v2[0], v2[1], v2[2]); } } glEnd(); glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glDisable(GL_BLEND); glDisable(GL_LINE_SMOOTH); glEnable(GL_LIGHTING); glDepthFunc(GL_LESS); glEnable(GL_LIGHTING); } void MeshModelRender::DrawModelSolidFlat() { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(2.0, 2.0); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); NormalArray& fNormal = kernel->GetFaceInfo().GetNormal(); size_t nFace = fIndex.size(); size_t i, j, n; if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; Normal& n = fNormal[i]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } else // General polygonal mesh { for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); glBegin(GL_POLYGON); for(j = 0; j < n; ++ j) { VertexID vID = face[j]; Coord& v = vCoord[vID]; Normal& n = fNormal[i]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } glEnd(); } } glDisable(GL_POLYGON_OFFSET_FILL); } void MeshModelRender::DrawModelTransparent() { glDisable(GL_LIGHTING); glColor4f(0.3f,0.3f,0.3f,0.5f); glBlendFunc(GL_SRC_ALPHA, GL_ONE); // 基于源象素alpha通道值的半透明混合函数 ( 新增 ) glEnable(GL_BLEND); // 打开混合 glDisable(GL_DEPTH_TEST); // 关闭深度测试 DrawModelSolidSmooth(); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); glEnable(GL_LIGHTING); } void MeshModelRender::DrawModelFaceTexture() { glEnable(GL_POLYGON_SMOOTH); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(2.0, 2.0); glDepthFunc(GL_LEQUAL); //glShadeModel(GL_SMOOTH); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); TexCoordArray& vTexCoord = kernel->GetVertexInfo().GetTexCoord(); PolyTexCoordArray& fTexCoord = kernel->GetFaceInfo().GetTexCoord(); NormalArray& fNormal = kernel->GetFaceInfo().GetNormal(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); PolyIndexArray& ftIndex = kernel->GetFaceInfo().GetTexIndex(); if(fTexCoord.size() ==0) return; size_t nFace = fIndex.size(); size_t i, j, n; // set texture env here. glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //glBindTexture(GL_TEXTURE_1D, texName); if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; IndexArray& tex_index = ftIndex[i]; TexCoordArray& f_tex = fTexCoord[i]; Normal& fn = fNormal[i]; n = face.size(); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; const TexCoord& tex = vTexCoord[tex_index[j]]; glNormal3d(fn[0], fn[1], fn[2]); glTexCoord2d(tex[0], tex[1]); //glTexCoord2d(f_tex[j][0], f_tex[j][1]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } glDisable(GL_TEXTURE_2D); glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); } void MeshModelRender::DrawModelSolidSmooth() { glEnable(GL_POLYGON_SMOOTH); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(2.0, 2.0); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); NormalArray& vNormal = kernel->GetVertexInfo().GetNormal(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); size_t nFace = fIndex.size(); size_t i, j, n; if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } else // General polygonal mesh { for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); glBegin(GL_POLYGON); for(j = 0; j < n; ++ j) { VertexID vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } glEnd(); } } glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); } void MeshModelRender::DrawModelSolidWithSharpness() { } void MeshModelRender::DrawModelSolidAndWireframe() { // Draw solid smooth model glEnable(GL_POLYGON_SMOOTH); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(2.0, 2.0); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); NormalArray& vNormal = kernel->GetVertexInfo().GetNormal(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); size_t nFace = fIndex.size(); size_t i, j, n; if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } else // General polygonal mesh { for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); glBegin(GL_POLYGON); for(j = 0; j < n; ++ j) { VertexID vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } glEnd(); } } glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); // Draw wireframe glDisable(GL_LIGHTING); glDepthFunc(GL_LEQUAL); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glLineWidth(m_DftEdgeWidth); Color c = BLUE*0.70; glColor3d(c[0], c[1], c[2]); glBegin(GL_LINES); for(i = 0; i < nFace; ++ i) { IndexArray& f = fIndex[i]; n = f.size(); for(j = 0; j < n; ++ j) { Coord& v1 = vCoord[f[j]]; Coord& v2 = vCoord[f[(j+1)%n]]; glVertex3d(v1[0], v1[1], v1[2]); glVertex3d(v2[0], v2[1], v2[2]); } } glEnd(); glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glDisable(GL_BLEND); glDisable(GL_LINE_SMOOTH); glEnable(GL_LIGHTING); glDepthFunc(GL_LESS); glEnable(GL_LIGHTING); } void MeshModelRender::DrawModelHighlightOnly() { } void MeshModelRender::DrawModelTextureMapping() { CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); TexCoordArray& tCoord = kernel->GetVertexInfo().GetTexCoord(); NormalArray& vNormal = kernel->GetVertexInfo().GetNormal(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); if (tCoord.empty()) { return; } glEnable(GL_POLYGON_SMOOTH); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(2.0, 2.0); glDepthFunc(GL_LEQUAL); //glShadeModel(GL_SMOOTH); size_t nFace = fIndex.size(); size_t i, j, n; // set texture env here. glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //glBindTexture(GL_TEXTURE_1D, texName); if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; Coord2D& t = tCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glTexCoord2d(t[0], t[1]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } else // General polygonal mesh { for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); glBegin(GL_POLYGON); for(j = 0; j < n; ++ j) { VertexID vID = face[j]; Coord& v = vCoord[vID]; Coord2D& t = tCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glTexCoord2d(t[0], t[1]); glVertex3d(v[0], v[1], v[2]); } glEnd(); } } glDisable(GL_TEXTURE_2D); glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); } void MeshModelRender::DrawModelVertexColor() { CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); NormalArray& vNormal = kernel->GetVertexInfo().GetNormal(); ColorArray& vColor = kernel->GetVertexInfo().GetColor(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); if(vColor.size() != vCoord.size()) return; // Get previous material diffuse components float ambient[4], diffuse[4], specular[4], emission[4], shininess; glGetMaterialfv(GL_FRONT, GL_AMBIENT, ambient); glGetMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse); glGetMaterialfv(GL_FRONT, GL_SPECULAR, specular); glGetMaterialfv(GL_FRONT, GL_EMISSION, emission); glGetMaterialfv(GL_FRONT, GL_SHININESS, &shininess); glDisable(GL_LIGHTING); glShadeModel(GL_SMOOTH); //glEnable(GL_POLYGON_SMOOTH); //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //glEnable(GL_POLYGON_OFFSET_FILL); //glPolygonOffset(2.0, 2.0); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); size_t nFace = fIndex.size(); size_t i, j, n; if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; Color& c = vColor[vID]; glColor3d (c[0], c[1], c[2]); glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } else // General polygonal mesh { for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); glBegin(GL_POLYGON); for(j = 0; j < n; ++ j) { VertexID vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; Color& c = vColor[vID]; glColor3d (c[0], c[1], c[2]); glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } glEnd(); } } glDisable(GL_COLOR_MATERIAL); glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); glEnable(GL_LIGHTING); // Reset previous material diffuse components glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emission); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess); } void MeshModelRender::DrawModelFaceColor() { CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); NormalArray& vNormal = kernel->GetVertexInfo().GetNormal(); ColorArray& fColor = kernel->GetFaceInfo().GetColor(); PolyIndexArray& fIndex = kernel->GetFaceInfo().GetIndex(); if(fColor.size() != fIndex.size()) return; // Get previous material diffuse components float ambient[4], diffuse[4], specular[4], emission[4], shininess; glGetMaterialfv(GL_FRONT, GL_AMBIENT, ambient); glGetMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse); glGetMaterialfv(GL_FRONT, GL_SPECULAR, specular); glGetMaterialfv(GL_FRONT, GL_EMISSION, emission); glGetMaterialfv(GL_FRONT, GL_SHININESS, &shininess); glDisable(GL_LIGHTING); glShadeModel(GL_SMOOTH); // glEnable(GL_POLYGON_SMOOTH); // glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glEnable(GL_POLYGON_OFFSET_FILL); // glPolygonOffset(2.0, 2.0); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT, GL_DIFFUSE); size_t nFace = fIndex.size(); size_t i, j, n; if(!kernel->GetModelInfo().IsGeneralMesh()) { if(kernel->GetModelInfo().IsTriMesh()) // Triangle mesh glBegin(GL_TRIANGLES); else if(kernel->GetModelInfo().IsQuadMesh()) // Quadangle mesh glBegin(GL_QUADS); else return; for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); Color& c = fColor[i]; glColor3d(c[0], c[1], c[2]); for(j = 0; j < n; ++ j) { VertexID& vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } } glEnd(); } else // General polygonal mesh { for(i = 0; i < nFace; ++ i) { IndexArray& face = fIndex[i]; n = face.size(); Color& c = fColor[i]; glColor3d(c[0], c[1], c[2]); glBegin(GL_POLYGON); for(j = 0; j < n; ++ j) { VertexID vID = face[j]; Coord& v = vCoord[vID]; Normal& n = vNormal[vID]; glNormal3d(n[0], n[1], n[2]); glVertex3d(v[0], v[1], v[2]); } glEnd(); } } glDisable(GL_COLOR_MATERIAL); glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); glEnable(GL_LIGHTING); // Reset previous material diffuse components glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emission); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess); } // Various utility rendering functions void MeshModelRender::DrawAxis() { } void MeshModelRender::DrawBoundingBox() { Coord BoxMin, BoxMax, BoxDim, Center; kernel->GetModelInfo().GetBoundingBox(BoxMin, BoxMax, BoxDim); // Draw bouding box glDisable(GL_LIGHTING); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glLineWidth(m_DftEdgeWidth); Color c = GREEN*0.8; glColor3d(c[0], c[1], c[2]); glBegin(GL_LINES); // glVertex3d(BoxMin[0], BoxMin[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMin[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMin[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMin[1], BoxMin[2]); glVertex3d(BoxMax[0], BoxMin[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMin[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMin[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMin[1], BoxMax[2]); // glVertex3d(BoxMin[0], BoxMax[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMax[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMax[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMax[1], BoxMin[2]); glVertex3d(BoxMax[0], BoxMax[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMax[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMax[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMax[1], BoxMax[2]); // glVertex3d(BoxMin[0], BoxMin[1], BoxMax[2]); glVertex3d(BoxMin[0], BoxMax[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMin[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMax[1], BoxMax[2]); glVertex3d(BoxMax[0], BoxMin[1], BoxMin[2]); glVertex3d(BoxMax[0], BoxMax[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMin[1], BoxMin[2]); glVertex3d(BoxMin[0], BoxMax[1], BoxMin[2]); glEnd(); glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glDisable(GL_LINE_SMOOTH); glEnable(GL_LIGHTING); } // Various auxiliary data rendering functions void MeshModelRender::DrawPoint() { glEnable(GL_POINT_SMOOTH); glDepthFunc(GL_LEQUAL); glPointSize(m_DftPointSize); PointInfo& pInfo = auxdata->GetPointInfo(); CoordArray& pCoord = pInfo.GetCoord(); ColorArray& pColor = pInfo.GetColor(); size_t n = pCoord.size(); glBegin(GL_POINTS); for(size_t i = 0; i < n; ++ i) { Coord& p = pCoord[i]; Color& c = pColor[i]; glColor3d(c[0], c[1], c[2]); glVertex3d(p[0], p[1], p[2]); } glEnd(); glDepthFunc(GL_LESS); glDisable(GL_POINT_SMOOTH); } void MeshModelRender::DrawLine() { glEnable(GL_LINE_SMOOTH); glDepthFunc(GL_LEQUAL); glLineWidth(m_DftLineWidth); LineInfo& lInfo = auxdata->GetLineInfo(); CoordArray& lfCoord = lInfo.GetfCoord(); CoordArray& lsCoord = lInfo.GetsCoord(); ColorArray& lColor = lInfo.GetColor(); size_t n = lfCoord.size(); glBegin(GL_LINES); for(size_t i = 0; i < n ; ++ i) { Coord& fp = lfCoord[i]; Coord& sp = lsCoord[i]; Color& c = lColor[i]; glColor3d(c[0], c[1], c[2]); glVertex3d(fp[0], fp[1], fp[2]); glVertex3d(sp[0], sp[1], sp[2]); } glEnd(); glDepthFunc(GL_LESS); glDisable(GL_LINE_SMOOTH); } void MeshModelRender::DrawPolygon() { glEnable(GL_POLYGON_SMOOTH); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0, 1.0); PolygonInfo& pInfo = auxdata->GetPolygonInfo(); PolyCoordArray& pCoords = pInfo.GetCoords(); ColorArray& pColor = pInfo.GetColor(); size_t n = pCoords.size(); for(size_t i = 0; i < n; ++ i) { Color& c = pColor[i]; glColor3d(c[0], c[1], c[2]); CoordArray& pv = pCoords[i]; size_t m = pv.size(); glBegin(GL_POLYGON); for(size_t j = 0; j < m; ++ j) { Coord& v = pv[j]; glVertex3d(v[0], v[1], v[2]); } glEnd(); } glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_SMOOTH); } // Rendering object depth for clipping void MeshModelRender::DrawModelDepth() { glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); DrawModelSolidFlat(); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } void MeshModelRender::DrawMeshCurvature(int mode) { double scale = 0.75 * kernel->GetModelInfo().GetAvgEdgeLength(); CoordArray& vCoord = kernel->GetVertexInfo().GetCoord(); CoordArray& vNormal = kernel->GetVertexInfo().GetNormal(); CurvatureArray& vCurvature = kernel->GetVertexInfo().GetCurvatures(); glDisable(GL_LIGHTING); glEnable(GL_POLYGON_OFFSET_LINE); glPolygonOffset(3.0f, -1.0f); glEnable(GL_LINE_SMOOTH); size_t nVertex = vCoord.size(); size_t j; for (j = 0; j < nVertex; j++) { Coord& start = vCoord[j]; Coord& normal = vNormal[j]; CCurvature& curv = vCurvature[j]; // draw the kmax curvature here if (util.IsSetFlag(mode, RENDER_MODEL_KMAX_CURVATURE)) { glColor3d(1.0f,0.0f,1.0f); DrawVector(scale, start, curv.m_direction_kmax, normal); } // draw the kmin curvature here. if (util.IsSetFlag(mode, RENDER_MODEL_KMIN_CURVATURE)) { glColor3d(0.0f,0.0f,1.0f); DrawVector(scale, start, curv.m_direction_kmin, normal); } } glDisable(GL_LINE_SMOOTH); glDisable(GL_POLYGON_OFFSET_LINE); glEnable(GL_LIGHTING); } void MeshModelRender::DrawVector(double scale, Coord& start, Coord& vec, Coord& normal) { double x1 = (double) ( scale * vec[0]); double y1 = (double) ( scale * vec[1]); double z1 = (double) ( scale * vec[2]); double x2 = x1 * 0.8; double y2 = y1 * 0.8; double z2 = z1 * 0.8; Coord isoV = cross(normal, vec).unit(); Coord p0 = Coord(x2, y2, z2) + isoV * scale * 0.15; Coord p1 = Coord(x2, y2, z2) - isoV * scale * 0.15; glPushMatrix(); glTranslated(start[0], start[1], start[2]); glLineWidth(1.0f); glBegin(GL_LINES); glVertex3d(0,0,0); glVertex3d(x1,y1,z1); glEnd(); glBegin(GL_LINES); glVertex3d(p0[0], p0[1], p0[2]); glVertex3d(x1,y1,z1); glEnd(); glBegin(GL_LINES); glVertex3d(p1[0], p1[1], p1[2]); glVertex3d(x1,y1,z1); glEnd(); glPopMatrix(); } int MeshModelRender::CreateTexture(const std::string& texture_file_name) { #ifdef WIN32 GLuint texName; AUX_RGBImageRec* texture_image = auxDIBImageLoadA((LPCSTR)texture_file_name.c_str()); glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 3, texture_image->sizeX, texture_image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_image->data); if (texture_image) { if (texture_image->data) free(texture_image->data); free(texture_image); } #endif return 0; }
[ [ [ 1, 1136 ] ] ]
64bae3c576ac1bd2658e33e7ea4749318d98f063
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib-test/af2-test/pikachu.cpp
a31512485065cfc10f11f8d769a5c2ad0384cad8
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,305
cpp
#include <windows.h> //#include "mwlagh.h" //#include "AugustWindow2.h" #include "mglaugust2.h" //#include "AugustGraphicsManager.h" //class __declspec(dllimport) CMwlAghWindow; /* class CMyWindow : public agh::IWindow { public: virtual bool OnClose(){ MessageBox(NULL,"sdfa","sfda",0); return true; } virtual bool OnDropFiles(std::vector<std::string> &files){ for(int i=0; i<files.size(); i++) MessageBox(NULL,files[i].c_str(),"Drop",0); return true; } }; */ _MWL_HINSTANCE g_hInstance; //class CMyColorFade : public agh::TColorFadeEffect<agh::math::CIntSineWave> class CMyColorFade : public agh::TColorFadeEffect<agh::math::CIntSquareWave> { public: virtual bool OnFadeStop(){return false;} }; //class CMyWindow : public CMwlAghWindow class CMyWindow : public CAugustScreen2 { private: typedef CAugustScreen2 _BASE; // CAugustGraphicsManager m_grp; //agh::CFadeEffect m_fade1; //agh::TColorFadeEffect<agh::math::CIntSineWave> m_fade1; CMyColorFade m_fade1; agh::math::CIntSineWave m_waveY; agh::math::CIntCosWave m_waveX; CAugustText2 m_text; CAugustText2 m_text2; public: // コンストラクタ・デストラクタ CMyWindow(){} virtual ~CMyWindow(){} /*virtual bool OnInit(){ return false; }*/ virtual bool OnGraphicInitEnded() { //m_sinX.SetRange(-2147483648, 2147483647); m_waveX.SetRange(0, 300); m_waveY.SetRange(0, 300); ///////////////////////////////////////////////////// RegistSubControl(&m_fade1); RegistSubControl(&m_text); RegistSubControl(&m_text2); m_text.SetText("ピカチ○ウピカ○ュウピ○チュウピカチュ○"); m_text.SetColor(0x99006600); m_text.SetPoint(40); m_text.SetFontName("MS Mincho"); m_text.SetOption(AGH_FONT_OPTION_BOLD); m_text.SetPos(10,40); m_text2.SetText("光過敏性\n てんかん"); m_text2.SetColor(0x99000077); m_text2.SetPoint(150); m_text2.SetFontName("MS Mincho"); m_text2.SetOption(AGH_FONT_OPTION_BOLD); m_text2.SetPos(50,80); //m_fade1.Setup(this, 0, 0xffffffff, 100); //m_fade1.Setup(this, AGHCOLOR_BLACK, AGHCOLOR_WHITE, 4); //m_fade1.Setup(this, AGHCOLOR_BLUE, AGHCOLOR_YELLOW, 30); //m_fade1.Setup(this, 0xffbbffff, 0xffff6600, 600); m_fade1.Setup(this, 0xffbbffff, 0xffff6600, 4); //m_fade1.FadeIn(this, 100); return true; } virtual void OnCreatedWindow(){ //MessageBox(NULL,"sdfa","sfda",0); _BASE::OnCreatedWindow(); RECT rcPos; rcPos.left = 10; rcPos.right = 100; rcPos.top = 50; rcPos.bottom = 100; HWND hParent = (HWND)GetHwnd(); HWND hWnd = ::CreateWindowEx(0, "BUTTON", "test", 0, rcPos.left, rcPos.top, rcPos.right - rcPos.left, rcPos.bottom - rcPos.top, (HWND)GetHwnd(), NULL, g_hInstance, NULL); // ウインドウの表示をどうするか ShowWindow( hWnd, SW_SHOWDEFAULT ); UpdateWindow( hWnd ); SetColor(12131); } //virtual bool OnClose(){ MessageBox(NULL,"sdfa","sfda",0); return true; } virtual bool OnDropFiles(std::vector<std::string> &files){ for(int i=0; i<files.size(); i++) MessageBox((HWND)GetHwnd(),files[i].c_str(),"Drop",0); return true; } // ウインドウ生成前に呼ばれる virtual void OnCreateWindow(agh::CREATE_WINDOW_INFO *pWindowInfo){ pWindowInfo->nWinWidthSize = 800; pWindowInfo->nWinHeightSize = 600; pWindowInfo->strWindowTitle = "aa"; //pWindowInfo->strWindowTitle = "さんぷるぷろぐらむfさdふぁsdふぁあsdふぁdddddddddddddddddddddddddddddddddddddふぁ"; } virtual bool OnFrameDoUser(){ static int i=-20; //Sleep(1000); //m_grp.Clear(); /* SetColor(AGHCOLOR_RGB(i,i,i)); */ m_text2.SetPos( m_waveX.Get(i/20.0f), m_waveY.Get(i/20.0f) ); i++; return true; } }; int _MWL_APIENTRY WinMain( _MWL_HINSTANCE hInstance, _MWL_HINSTANCE hPrevInstance, char* lpCmdLine, int nCmdShow ) //int main() { g_hInstance = hInstance; //::FreeConsole(); CMyWindow myWindow; //CAugustScreen2 myWindow; myWindow.EnableDropFiles(); myWindow.Start(); return 0; }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 162 ] ] ]
a3329c0e80f9bd005af208462a4f8d5b76f6543b
6f796044ae363f9ca58c66423c607e3b59d077c7
/source/GuiDialogs/GuiDlgGameFileSelect.h
2729c428afbde5a1c2de4f7a8ba1052a09a9d94e
[]
no_license
Wiimpathy/bluemsx-wii
3a68d82ac82268a3a1bf1b5ca02115ed5e61290b
fde291e57fe93c0768b375a82fc0b62e645bd967
refs/heads/master
2020-05-02T22:46:06.728000
2011-10-06T20:57:54
2011-10-06T20:57:54
178,261,485
2
0
null
2019-03-28T18:32:30
2019-03-28T18:32:30
null
UTF-8
C++
false
false
830
h
#ifndef _GUI_DLG_GAME_FILE_SELECT_H #define _GUI_DLG_GAME_FILE_SELECT_H #include "../GuiBase/GuiDialog.h" #include "../Gui/DirectoryHelper.h" typedef struct _fileitem FILEITEM; class GuiElmSelectionList; class GuiElmFrame; class GuiDlgGameFileSelect : public GuiDialog { public: GuiDlgGameFileSelect(GuiContainer *parent, const char *name, const char *dir); virtual ~GuiDlgGameFileSelect(); int Create(void); char* DoModal(void); private: DirectoryHelper directory; char *org_dir; char *root_dir; GuiElmFrame *frame; GuiElmSelectionList *list; int num_files; float posx; float posy; float sizex; float sizey; FILEITEM **items; void CreateFileList(void); void FreeFileList(void); }; #endif
[ "timbrug@c2eab908-c631-11dd-927d-974589228060", "[email protected]" ]
[ [ [ 1, 5 ], [ 7, 15 ], [ 17, 21 ], [ 23, 27 ], [ 32, 39 ] ], [ [ 6, 6 ], [ 16, 16 ], [ 22, 22 ], [ 28, 31 ] ] ]
dceacb0ff41b5f5c8dee070125b307ed683a15a3
d235b8143a573107d81ea4f0d1ed78e853b6dd06
/RobotFindDoor/mainwindow.cpp
cfa11251bab852748c4c17cd8756cce4ddcbcc28
[]
no_license
joshuaeckroth/Robot-Find-Door
e9ff4cdf0f7f34c2abad2d98ee5597ac91127f36
beddc08c73287055f78230b42ebfca39b81b000d
refs/heads/master
2021-01-02T23:07:36.643436
2010-05-30T17:19:18
2010-05-30T17:19:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,395
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "logdialog.h" #include "manager.h" #include <ctime> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), logDialog(new LogDialog(this)) { ui->setupUi(this); connect(ui->logDialogButton, SIGNAL(clicked()), logDialog, SLOT(show())); m = Manager::instance(); connect(m, SIGNAL(action(QString)), logDialog, SLOT(appendAction(QString))); connect(m, SIGNAL(newSeed(int)), this, SLOT(newSeed(int))); connect(m, SIGNAL(solutionComplete()), this, SLOT(solutionComplete())); connect(ui->setSeedButton, SIGNAL(clicked()), this, SLOT(setSeed())); connect(ui->prevMapButton, SIGNAL(clicked()), m, SLOT(prevMap())); connect(ui->nextMapButton, SIGNAL(clicked()), m, SLOT(nextMap())); connect(ui->goButton, SIGNAL(clicked()), m, SLOT(go())); connect(ui->goButton, SIGNAL(clicked()), this, SLOT(go())); connect(ui->resetButton, SIGNAL(clicked()), this, SLOT(reset())); qsrand(std::time(NULL)); m->setViewport(ui->viewport); m->setSeed(qrand()); m->initialize(); ui->resetButton->setDisabled(true); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void MainWindow::setSeed() { m->setSeed(ui->seedInput->text().toInt()); } void MainWindow::newSeed(int seed) { ui->seedInput->setText(QString("%1").arg(seed)); if(m->hasPrevSeed()) ui->prevMapButton->setDisabled(false); else ui->prevMapButton->setDisabled(true); ui->mapLabel->setText(QString("Map %1/%2+") .arg(m->getCurSeed()+1) .arg(m->getNumSeeds())); ui->resetButton->setDisabled(true); ui->goButton->setDisabled(false); } void MainWindow::go() { ui->resetButton->setDisabled(false); ui->goButton->setDisabled(true); } void MainWindow::reset() { m->initialize(); ui->resetButton->setDisabled(true); ui->goButton->setDisabled(false); } void MainWindow::solutionComplete() { ui->resetButton->setDisabled(false); ui->goButton->setDisabled(true); }
[ [ [ 1, 89 ] ] ]
66a2aa64c5d814b5ba743f689a9364f24056fbba
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
/ xcommon/Public/HWXString.cpp
3180330964462c4627dc8b6f25760deff3378c7a
[]
no_license
wermanhme1990/xcommon
49d7185a28316d46992ad9311ae9cdfe220cb586
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
refs/heads/master
2016-09-06T12:43:43.593776
2008-12-05T04:24:11
2008-12-05T04:24:11
39,864,906
2
0
null
null
null
null
GB18030
C++
false
false
38,062
cpp
/******************************************************************** Copyright (c) 2002-2003 汉王科技有限公司. 版权所有. 文件名称: HWXString.h 文件内容: 自定义String处理类 版本历史: 1.0 作者: xuejuntao [email protected] 2008/03/06 *********************************************************************/ #include "StdAfx.h" #include "HWXString.h" #include <stdio.h> #include <wchar.h> #include <tchar.h> #include <ctype.h> #include <Windows.h> #include <AtlBase.h> #include <AtlConv.h> #define HWXString_Len_Inc (256) const WCHAR g_whEndMark = L'\0'; const CHAR g_chEndMark = '\0'; ////////////////////////////////////////////////////////////////////////// // CXStringW ////////////////////////////////////////////////////////////////////////// CXStringW::CXStringW() { Init(); Clear(); } CXStringW::CXStringW(LPCWSTR pwhSource) { Init(); Reset(pwhSource); } CXStringW::CXStringW(const WCHAR& whSource) { Init(); WCHAR awhBuffer[2]; awhBuffer[0] = whSource; awhBuffer[1] = g_whEndMark; Reset(awhBuffer); } CXStringW::CXStringW(LPCWSTR pwhSource, LONG nLen) { Init(); Reset(pwhSource, nLen); } CXStringW::CXStringW(const CXStringW &xstrSource) { Init(); Reset(xstrSource.C_Str()); } ////////////////////////////////////////////////////////////////////////// void CXStringW::Init() { m_nLength = 0; m_nIncStep = HWXString_Len_Inc; m_tPackage.SetIncStep(m_nIncStep * sizeof(WCHAR)); Reserve(m_nIncStep); } ////////////////////////////////////////////////////////////////////////// CXStringW::~CXStringW() { #if defined(_DEBUG) || defined(DEBUG) { Clear(); } #endif } void CXStringW::AssertValid() const { #if defined(_DEBUG) || defined(DEBUG) { assert(m_nLength >= 0); assert(C_Str()); assert(wcslen(C_Str()) == m_nLength); } #endif } ////////////////////////////////////////////////////////////////////////// LPCWSTR CXStringW::C_Str() const { return (LPCWSTR)m_tPackage.GetData(); } LONG CXStringW::StrLen() const { #if defined(_DEBUG) || defined(DEBUG) { LPCWSTR pwhString = C_Str(); LONG nLen = (LONG)wcslen(pwhString); //assert(nLen == m_nLength); } #endif return m_nLength; } ////////////////////////////////////////////////////////////////////////// void CXStringW::Clear() { LPWSTR pwhString = (LPWSTR)C_Str(); assert(NULL != pwhString); #if defined(_DEBUG) || defined(DEBUG) { Mem_ZeroMemory(pwhString, (StrLen() + 1) * sizeof(WCHAR)); } #endif m_nLength = 0; pwhString[m_nLength] = g_whEndMark; } ////////////////////////////////////////////////////////////////////////// void CXStringW::Reserve(LONG nLen) { assert(nLen > 0); VERIFY(NULL != m_tPackage.GetBuffer(nLen * sizeof(WCHAR))); } BOOL CXStringW::IsEmpty() const { return 0 == m_nLength; } void CXStringW::Reverse() { #if _MSC_VER > 1000 _wcsrev((LPWSTR)C_Str()); #else wcsrev((LPWSTR)C_Str()); #endif } //定位 LONG CXStringW::FirstBelong(LPCWSTR pwhChrSet) { assert(NULL != pwhChrSet); assert(wcslen(pwhChrSet) > 0); if (wcslen(pwhChrSet) > 0) { return (LONG)wcscspn((LPWSTR)C_Str(), pwhChrSet); } else { return 0; } } LONG CXStringW::FirstNoBelong(LPCWSTR pwhChrSet) { assert(NULL != pwhChrSet); assert(wcslen(pwhChrSet) > 0); if (wcslen(pwhChrSet) > 0) { return (LONG)wcsspn((LPWSTR)C_Str(), pwhChrSet); } else { return 0; } } BOOL CXStringW::IsBelong(LPCWSTR pwhChrSet) { return m_nLength == FirstNoBelong(pwhChrSet); } BOOL CXStringW::IsNoBelong(LPCWSTR pwhChrSet) { return m_nLength == FirstBelong(pwhChrSet); } WCHAR CXStringW::GetAt(LONG nIndex) { LPWSTR pwhString = (LPWSTR)C_Str(); return nIndex < m_nLength ? pwhString[nIndex] : WCHAR(-1); } WCHAR CXStringW::operator[](LONG nIndex) { return GetAt(nIndex); } BOOL CXStringW::SetAt(LONG nIndex, WCHAR whB) { LPWSTR pwhString = (LPWSTR)C_Str(); assert(NULL != pwhString); if (nIndex < m_nLength) { pwhString[nIndex] = whB; return TRUE; } else { return FALSE; } } BOOL CXStringW::Strcat(LPCWSTR pwhA) { if (pwhA) { LONG nLen = (LONG)wcslen(pwhA); Reserve(m_nLength + nLen + 1); LPWSTR pwhOrgString = (LPWSTR)C_Str(); #if _MSC_VER > 1000 wcscat_s(pwhOrgString, m_nLength + nLen + 1, pwhA); #else wcscat(pwhOrgString, pwhA); #endif m_nLength += nLen; #if defined(_DEBUG) || defined(DEBUG) { LONG nNewLen = (LONG)wcslen(pwhOrgString); assert(nNewLen == m_nLength); } #endif } return TRUE; } BOOL CXStringW::Strcat(LPCWSTR pwhA, LONG nDstLen) { assert(nDstLen > 0); assert(NULL != pwhA); LONG nDstRealLen = (LONG)wcslen(pwhA); assert(nDstLen <= nDstRealLen); Reserve(m_nLength + nDstLen + 1); LPWSTR pwhOrgString = (LPWSTR)C_Str(); Mem_CopyMemory(pwhOrgString + m_nLength, pwhA, nDstLen * sizeof(WCHAR)); pwhOrgString[m_nLength + nDstLen] = g_whEndMark; m_nLength += nDstLen; assert(m_nLength == wcslen(pwhOrgString)); return TRUE; } BOOL CXStringW::Strcat(const CXStringW& strA) { return Strcat(strA.C_Str()); } void CXStringW::Reset(LPCWSTR pwhB) { Clear(); Strcat(pwhB); } void CXStringW::Reset(LPCWSTR pwhA, LONG nLen) { Clear(); Strcat(pwhA, nLen); } void CXStringW::Reset(const CXStringW &strB) { Reset(strB.C_Str()); } CXStringW& CXStringW::operator =(LPCWSTR pwhB) { Reset(pwhB); return *this; } CXStringW& CXStringW::operator =(const CXStringW &xstrSource) { Reset(xstrSource); return *this; } void CXStringW::MakeLower() { LPWSTR ptchString = (LPWSTR)C_Str(); #if _MSC_VER >= 1400 _wcslwr_s(ptchString, m_nLength); #else wcslwr(ptchString); #endif } void CXStringW::MakeUpper() { LPWSTR ptchString = (LPWSTR)C_Str(); #if _MSC_VER >= 1400 _wcsupr_s(ptchString, m_nLength); #else wcsupr(ptchString); #endif } BOOL CXStringW::Compare(LPCWSTR pwhCompareString) const { assert(NULL != pwhCompareString); return pwhCompareString ? (0 == wcscmp(C_Str(), pwhCompareString)) : FALSE; } BOOL CXStringW::Compare(const CXStringW &xstrCompareString) const { return Compare(xstrCompareString.C_Str()); } BOOL CXStringW::CompareNoCase(LPCWSTR pwhCompareString) const { assert(NULL != pwhCompareString); #if _MSC_VER >= 1400 return pwhCompareString ? (0 == _wcsicmp(C_Str(), pwhCompareString)) : FALSE; #else return pwhCompareString ? (0 == wcsicmp(C_Str(), pwhCompareString)) : FALSE; #endif } BOOL CXStringW::CompareNoCase(const CXStringW &xstrA) const { return CompareNoCase(xstrA.C_Str()); } BOOL CXStringW::operator==(const CXStringW &xstrA) const { return Compare(xstrA); } BOOL CXStringW::operator!=(const CXStringW &xstrA) const { return !Compare(xstrA); } BOOL CXStringW::operator==(LPCWSTR pwhData) const { return Compare(pwhData); } BOOL CXStringW::operator!=(LPCWSTR pwhData) const { return !(Compare(pwhData)); } BOOL CXStringW::operator==(const WCHAR whA) const { WCHAR awhTmp[2]; awhTmp[0] = whA; awhTmp[1] = g_whEndMark; return Compare(awhTmp); } BOOL CXStringW::operator!=(const WCHAR whA) const { return !(*this == whA); } LONG CXStringW::Find(LONG nStartIndex, LPCWSTR pwhStringToFind) { LONG nLen = StrLen(); assert(NULL != pwhStringToFind); assert(nStartIndex >= 0 && nStartIndex < nLen); LPWSTR pwhString; if (nStartIndex < 0) { nStartIndex = 0; } else if(nStartIndex > nLen) { nStartIndex = nLen; } pwhString = (LPWSTR)C_Str(); LPWSTR ptchResult = wcsstr(pwhString + nStartIndex, pwhStringToFind); return NULL != ptchResult ? (LONG)(ptchResult - pwhString) : -1; } LONG CXStringW::Find(LPCWSTR pwhStringToFind) { return Find(0, pwhStringToFind); } LONG CXStringW::Find(LONG nStartIndex, WCHAR whChrToFind) { WCHAR awhBuffer[2]; awhBuffer[0] = whChrToFind; awhBuffer[1] = g_whEndMark; return Find(nStartIndex, awhBuffer); } LONG CXStringW::Find(const WCHAR whChrToFind) { return Find(0, whChrToFind); } LONG CXStringW::FindNoCase(LONG nStartIndex, LPCWSTR pwhStringToFind) { CXStringW xstrTempLower = *this; xstrTempLower.MakeLower(); CXStringW xstrStringToFindLower = pwhStringToFind; xstrStringToFindLower.MakeLower(); return xstrTempLower.Find(nStartIndex, xstrStringToFindLower.C_Str()); } LONG CXStringW::FindNoCase(LPCWSTR pwhStringToFind) { return FindNoCase(0, pwhStringToFind); } LONG CXStringW::FindNoCase(LONG nStartIndex, const WCHAR whChrToFind) { WCHAR awhTemp[2]; awhTemp[0] = whChrToFind; awhTemp[1] = g_whEndMark; return FindNoCase(nStartIndex, awhTemp); } LONG CXStringW::FindNoCase(const WCHAR whChrToFind) { return FindNoCase(0, whChrToFind); } LONG CXStringW::ReverseFind(LONG nStartIndex, const WCHAR whChr) { LPWSTR pwhResult = NULL, pwhString = (LPWSTR)C_Str(); assert(nStartIndex >= 0 && nStartIndex < m_nLength); pwhResult = wcsrchr(pwhString + nStartIndex, whChr); return NULL != pwhResult ? (LONG)(pwhResult - pwhString) : -1; } LONG CXStringW::ReverseFind(const WCHAR whChr) { return ReverseFind(0, whChr); } CXStringW CXStringW::Left(LONG nCount) { LPWSTR pwhString = (LPWSTR)C_Str(); assert(NULL != pwhString); assert(nCount > 0 && nCount <= m_nLength); CXStringW xstrTmp(pwhString, nCount); return xstrTmp; } CXStringW CXStringW::ExcludeLeft(LONG nCount) { return Right(m_nLength - nCount); } CXStringW CXStringW::Mid(LONG nIndex, LONG nCount) { assert(nCount >= 0); LPWSTR pwhString = (LPWSTR)C_Str(); assert(nIndex >= 0 && nIndex <= m_nLength - nCount && nCount > 0); CXStringW xstrData(pwhString + nIndex, nCount); return xstrData; } CXStringW CXStringW::Right(LONG nCount) { return Mid(m_nLength - nCount, nCount); } void CXStringW::InternalLeft(LONG nCount) { InternalMid(0, nCount); } void CXStringW::InternalExcludeLeft(LONG nCount) { InternalRight(m_nLength - nCount); } void CXStringW::InternalMid(LONG nIndex, LONG nCount) { LPWSTR pwhString = (LPWSTR)C_Str(); assert(nIndex >= 0 && nIndex + nCount <= m_nLength && nCount >= 0); if (0 != nIndex && nCount > 0) { Mem_CopyMemory(pwhString, pwhString + nIndex, nCount * sizeof(WCHAR)); } pwhString[nCount] = g_whEndMark; #if defined(_DEBUG) || defined(DEBUG) { if (nIndex + nCount < m_nLength) { Mem_ZeroMemory(pwhString + nCount, (m_nLength - nCount) * sizeof(WCHAR)); } } #endif m_nLength = nCount; } void CXStringW::InternalRight(LONG nCount) { InternalMid(m_nLength - nCount, nCount); } CXStringW::operator LPCWSTR() const { return (LPCWSTR)C_Str(); } CXStringW &CXStringW::operator+=(const CXStringW &xstrAdditionalString) { Strcat(xstrAdditionalString); return *this; } CXStringW &CXStringW::operator+=(LPCWSTR pwhAdditionalString) { Strcat(pwhAdditionalString); return *this; } CXStringW &CXStringW::operator+=(const WCHAR& whAdditionalChar) { WCHAR awhAdditionalString[2]; awhAdditionalString[0] = whAdditionalChar; awhAdditionalString[1] = g_whEndMark; Strcat(awhAdditionalString); return *this; } CXStringW CXStringW::operator+(const CXStringW &ptchAdditionalString) { CXStringW xstrTmp = *this; xstrTmp.Strcat(ptchAdditionalString); return xstrTmp; } CXStringW CXStringW::operator+(LPCWSTR pwhAdditionalString) { CXStringW xstrTmp = *this; xstrTmp.Strcat(pwhAdditionalString); return xstrTmp; } CXStringW CXStringW::operator+(const WCHAR &whAdditionalChar) { CXStringW xstrTmp = *this; xstrTmp += whAdditionalChar; return xstrTmp; } CXStringW operator+(LPCWSTR pwhA, const CXStringW &xstrB) { CXStringW xstrTmp = pwhA; xstrTmp += xstrB; return xstrTmp; } CXStringW operator+(const WCHAR &whAdditionalChar, const CXStringW& xstrB) { CXStringW xstrTmp(whAdditionalChar); xstrTmp += xstrB; return xstrTmp; } ////////////////////////////////////////////////////////////////////////// BOOL operator!=(LPCWSTR pwhA, const CXStringW &xstrB) { return !(xstrB == pwhA); } BOOL operator==(LPCWSTR pwhA, const CXStringW &xstrB) { return xstrB == pwhA; } BOOL operator!=(const WCHAR whA, const CXStringW &xstrB) { return !(xstrB == whA); } BOOL operator==(const WCHAR whA, const CXStringW &xstrB) { return xstrB == whA; } ////////////////////////////////////////////////////////////////////////// void CXStringW::TrimLeft(const WCHAR whA) { WCHAR awhTag[2]; awhTag[0] = whA; awhTag[1] = g_whEndMark; TrimLeft(awhTag); } void CXStringW::TrimLeft(LPCWSTR pwhTag) { //assert(NULL != pwhTag); if (IsEmpty()) { return; } LPWSTR pwhString = (LPWSTR)C_Str(); assert(m_nLength > 0); LONG nAmount = 0; if (!pwhTag) { pwhTag = g_awhDelimit; } nAmount = (LONG)wcsspn(pwhString, pwhTag); assert(nAmount <= m_nLength); InternalExcludeLeft(nAmount); } void CXStringW::TrimRight(const WCHAR whA) { WCHAR awhTag[2]; awhTag[0] = whA; awhTag[1] = g_whEndMark; TrimRight(awhTag); } void CXStringW::TrimRight(LPCWSTR pwhTag) { if (IsEmpty()) { return; } LONG nAmount = 0; BOOL blContinue = TRUE; if (NULL == pwhTag) { pwhTag = g_awhDelimit; } for (LONG i = 0; i < m_nLength && blContinue; i++) { if (NULL != wcschr(pwhTag, GetAt(m_nLength - i - 1))) nAmount ++; else blContinue = FALSE; } if (!blContinue || nAmount > 0) InternalLeft(m_nLength - nAmount); } void CXStringW::Trim(const WCHAR whA) { WCHAR awhTag[2]; awhTag[0] = whA; awhTag[1] = g_whEndMark; Trim(awhTag); } void CXStringW::Trim(LPCWSTR pwhTag) { TrimLeft(pwhTag); TrimRight(pwhTag); } LONG CXStringW::GetNumber() { if (IsEmpty()) return 0L; LONG nValue = 0; LPCWSTR pwhIndex = wcspbrk(C_Str(), L"0123456789.-+"); if (pwhIndex) { #if _MSC_VER >= 1000 swscanf_s(pwhIndex, L"%ld", &nValue); #else swscanf(pwhIndex, L"%ld", &nValue); #endif } return nValue; } float CXStringW::GetFloat() { if (IsEmpty()) return 0.0f; float flValue = 0.0; LPCWSTR pwhIndex = wcspbrk(C_Str(), L"0123456789.-+"); if (pwhIndex) { #if _MSC_VER >= 1000 swscanf_s(pwhIndex, L"%f", &flValue); #else swscanf(pwhIndex, L"%f", &flValue); #endif } return flValue; } LONG CXStringW::GetHex() { if (IsEmpty()) return 0; LONG nValue = 0; LPCWSTR pwhIndex = wcspbrk(C_Str(), L"0123456789ABCDEFabcdef-+"); if (pwhIndex) { #if _MSC_VER >= 1000 wscanf_s(pwhIndex, L"%x", &nValue); #else wscanf(pwhIndex, L"%x", &nValue); #endif } return nValue; } void CXStringW::ReplaceChar(const WCHAR A, const WCHAR B) { LPWSTR strString = (LPWSTR)C_Str(); assert(strString); if (!strString) { return; } assert(wcslen(strString) == m_nLength); while (*strString) { if (A == *strString) { *strString = B; } strString ++; } } void CXStringW::ReplaceCharWithString(const WCHAR whA, LPCWSTR pwhStringB) { if (IsEmpty()) return; CXStringW xstrData; LONG nSearchIndex = 0; LONG nFindIndex; LPWSTR pwhString = (LPWSTR)C_Str(); while (nSearchIndex < m_nLength && (nFindIndex = Find(nSearchIndex, whA)) > -1) { //assert (nFindIndex > nSearchIndex); //xstrData += Mid(nSearchIndex, nFindIndex - nSearchIndex); if (nFindIndex != nSearchIndex) { xstrData.Strcat(pwhString + nSearchIndex, nFindIndex - nSearchIndex); } xstrData += pwhStringB; nSearchIndex = ++ nFindIndex; } //处理尾巴 if (nSearchIndex < m_nLength) xstrData += pwhString + nSearchIndex; *this = xstrData; } void CXStringW::ReplaceCharWithString(const WCHAR whA, const CXStringW &xstrB) { ReplaceCharWithString(whA, xstrB.C_Str()); } void CXStringW::Format(LPCWSTR pwhFormat, ...) { LPWSTR pwhBuffer = NULL; LONG nLen = 0; va_list argList; va_start(argList, pwhFormat); nLen = _vscwprintf(pwhFormat, argList); Reserve(nLen + 1); Clear(); pwhBuffer = (LPWSTR)C_Str(); #if _MSC_VER >= 1000 vswprintf_s(pwhBuffer, nLen + 1, pwhFormat, argList); #else _vswprintf(pwhBuffer, pwhFormat, argList); #endif va_end(argList); m_nLength = (LONG)wcslen(pwhBuffer); } void CXStringW::FormatEx(LPCWSTR pwhFormat, ...) { LPWSTR pwhBuffer = NULL; va_list argList; LONG nLen = 0, nLenOrg = m_nLength; va_start(argList, pwhFormat); nLen = _vscwprintf(pwhFormat, argList); Reserve(nLen + nLenOrg + 1); pwhBuffer = (LPWSTR)C_Str(); #if _MSC_VER >= 1000 vswprintf_s(pwhBuffer + nLenOrg, nLen, pwhFormat, argList); #else _vswprintf(pwhBuffer + nLenOrg, pwhFormat, argList); #endif va_end(argList); m_nLength = (LONG)wcslen(pwhBuffer); } BOOL CXStringW::Token(LPCWSTR pwhDelimit, std::vector<CXStringW> &vString) const { assert(pwhDelimit); BOOL blRet = TRUE; if (wcslen(pwhDelimit) < 1) { blRet = FALSE; return blRet; } CXStringW strTmp = *this; CXStringW strSubStr; LPCWSTR pwhToken = NULL; LPWSTR ptStr = (LPWSTR)strTmp.C_Str(); #if _MSC_VER >= 1000 LPWSTR pwhContent = NULL; pwhToken = wcstok_s( ptStr, pwhDelimit, &pwhContent); while( NULL != pwhToken ) { strSubStr = pwhToken; vString.push_back(strSubStr); pwhToken = wcstok_s( NULL, pwhDelimit, &pwhContent); } #else pwhToken = wcstok( ptStr, pwhDelimit); while( NULL != pwhToken ) { strSubStr = pwhToken; vString.push_back(strSubStr); pwhToken = wcstok( NULL, pwhDelimit ); } #endif return blRet; } BOOL CXStringW::Token(const WCHAR whDelimit, std::vector<CXStringW> &vString) const { WCHAR awhDelimit[2]; awhDelimit[0] = whDelimit; awhDelimit[1] = g_whEndMark; return Token(awhDelimit, vString); } CXStringW CXStringW::From( LPCSTR pchA) { USES_CONVERSION; assert(pchA); LPWSTR pwhB = A2W(pchA); return CXStringW(pwhB); } CXStringW CXStringW::From( LPCWSTR pwhA) { return CXStringW(pwhA); } CXStringW CXStringW::From( LONG nData) { WCHAR awhBuffer[50]; #if _MSC_VER >= 1000 swprintf_s(awhBuffer, 50, L"%d", nData); #else swprintf(awhBuffer, L"%d", nData); #endif return awhBuffer; } CXStringW CXStringW::From( DWORD dwData) { WCHAR awhBuffer[50]; #if _MSC_VER >= 1000 swprintf_s(awhBuffer, 50, L"%x", dwData); #else swprintf(awhBuffer, L"%x", dwData); #endif return awhBuffer; } CXStringW CXStringW::From( double dbData) { WCHAR awhBuffer[50]; #if _MSC_VER >= 1000 swprintf_s(awhBuffer, 50, L"%f", dbData); #else swprintf(awhBuffer, L"%f", dbData); #endif return awhBuffer; } LPWSTR CXStringW::GetBuffer( const DWORD& dwSize) { Reserve(sizeof(WCHAR) * (dwSize + 1)); return LPWSTR(m_tPackage.GetData()); } void CXStringW::ReleaseBuffer() { m_nLength = (LONG)wcslen(C_Str()); } void CXStringW::Remove( const WCHAR chA) { if (m_nLength <= 0) { return; } LPWSTR strBuff = (LPWSTR)C_Str(); LPCWSTR strIndex = strBuff; assert((LONG)wcslen(strBuff) == m_nLength); while(*strIndex != g_chEndMark) { if (*strIndex != chA) { *strBuff ++ = *strIndex; } strIndex ++; } *strBuff = g_whEndMark; m_nLength = (LONG)wcslen(C_Str()); } std::ostream &operator<<(std::ostream & oStream, const CXStringW &xStr) { oStream<<xStr.C_Str(); return oStream; } ////////////////////////////////////////////////////////////////////////// // CXStringA ////////////////////////////////////////////////////////////////////////// CXStringA::CXStringA() { Init(); Clear(); } CXStringA::CXStringA(LPCSTR pwhSource) { Init(); Reset(pwhSource); } CXStringA::CXStringA(const CHAR& chSource) { Init(); CHAR achBuffer[2]; achBuffer[0] = chSource; achBuffer[1] = g_chEndMark; Reset(achBuffer); } CXStringA::CXStringA(LPCSTR pwhSource, LONG nLen) { Init(); Reset(pwhSource, nLen); } CXStringA::CXStringA(const CXStringA &xstrSource) { Init(); Reset(xstrSource.C_Str()); } ////////////////////////////////////////////////////////////////////////// void CXStringA::Init() { m_nLength = 0; m_nIncStep = HWXString_Len_Inc; m_tPackage.SetIncStep(m_nIncStep * sizeof(CHAR)); Reserve(m_nIncStep); } ////////////////////////////////////////////////////////////////////////// CXStringA::~CXStringA() { #if defined(_DEBUG) || defined(DEBUG) { Clear(); } #endif } void CXStringA::AssertValid() const { #if defined(_DEBUG) || defined(DEBUG) { assert(m_nLength >= 0); assert(C_Str()); assert(strlen(C_Str()) == m_nLength); } #endif } ////////////////////////////////////////////////////////////////////////// LPCSTR CXStringA::C_Str() const { return (LPCSTR)m_tPackage.GetData(); } LONG CXStringA::StrLen() const { #ifdef _DEBUG { LPCSTR pwhString = C_Str(); LONG nLen = (LONG)strlen(pwhString); assert(nLen == m_nLength); } #endif return m_nLength; } ////////////////////////////////////////////////////////////////////////// void CXStringA::Clear() { LPSTR pchString = (LPSTR)C_Str(); assert(NULL != pchString); #if defined(_DEBUG) || defined(DEBUG) { Mem_ZeroMemory(pchString, (StrLen() + 1) * sizeof(CHAR)); } #endif m_nLength = 0; pchString[m_nLength] = g_chEndMark; } ////////////////////////////////////////////////////////////////////////// void CXStringA::Reserve(LONG nLen) { assert(nLen > 0); VERIFY(NULL != m_tPackage.GetBuffer(nLen * sizeof(CHAR))); } BOOL CXStringA::IsEmpty() const { return 0 == m_nLength; } void CXStringA::Reverse() { #if _MSC_VER >= 1400 _strrev((LPSTR)C_Str()); #else strrev((LPSTR)C_Str()); #endif } //定位 LONG CXStringA::FirstBelong(LPCSTR pchChrSet) { assert(NULL != pchChrSet); assert(strlen(pchChrSet) > 0); if (strlen(pchChrSet) > 0) { return (LONG)strcspn((LPSTR)C_Str(), pchChrSet); } else { return 0; } } LONG CXStringA::FirstNoBelong(LPCSTR pchChrSet) { assert(NULL != pchChrSet); assert(strlen(pchChrSet) > 0); if (strlen(pchChrSet) > 0) { return (LONG)strspn((LPSTR)C_Str(), pchChrSet); } else { return 0; } } BOOL CXStringA::IsBelong(LPCSTR pchChrSet) { return m_nLength == FirstNoBelong(pchChrSet); } BOOL CXStringA::IsNoBelong(LPCSTR pchChrSet) { return m_nLength == FirstBelong(pchChrSet); } CHAR CXStringA::GetAt(LONG nIndex) { LPSTR pwhString = (LPSTR)C_Str(); return nIndex < m_nLength ? pwhString[nIndex] : CHAR(-1); } CHAR CXStringA::operator[](LONG nIndex) { return GetAt(nIndex); } BOOL CXStringA::SetAt(LONG nIndex, CHAR chB) { LPSTR pchString = (LPSTR)C_Str(); assert(NULL != pchString); if (nIndex < m_nLength) { pchString[nIndex] = chB; return TRUE; } else { return FALSE; } } BOOL CXStringA::Strcat(LPCSTR pchA) { if (pchA) { LONG nLen = (LONG)strlen(pchA); Reserve(m_nLength + nLen + 1); LPSTR pwhOrgString = (LPSTR)C_Str(); #if _MSC_VER >= 1000 strcat_s(pwhOrgString, m_nLength + nLen + 1, pchA); #else strcat(pwhOrgString, pchA); #endif m_nLength += nLen; #if defined(_DEBUG) || defined(DEBUG) { LONG nNewLen = (LONG)strlen(pwhOrgString); assert(nNewLen == m_nLength); } #endif } return TRUE; } BOOL CXStringA::Strcat(LPCSTR pwhA, LONG nDstLen) { assert(nDstLen > 0); assert(NULL != pwhA); LONG nDstRealLen = (LONG)strlen(pwhA); assert(nDstLen <= nDstRealLen); Reserve(m_nLength + nDstLen + 1); LPSTR pwhOrgString = (LPSTR)C_Str(); Mem_CopyMemory(pwhOrgString + m_nLength, pwhA, nDstLen * sizeof(CHAR)); pwhOrgString[m_nLength + nDstLen] = g_chEndMark; m_nLength += nDstLen; assert(m_nLength == strlen(pwhOrgString)); return TRUE; } BOOL CXStringA::Strcat(const CXStringA& strA) { return Strcat(strA.C_Str()); } void CXStringA::Reset(LPCSTR pchB) { Clear(); Strcat(pchB); } void CXStringA::Reset(LPCSTR pchA, LONG nLen) { Clear(); Strcat(pchA, nLen); } void CXStringA::Reset(const CXStringA &strB) { Reset(strB.C_Str()); } CXStringA& CXStringA::operator =(LPCSTR pchB) { Reset(pchB); return *this; } CXStringA& CXStringA::operator =(const CXStringA &xstrSource) { Reset(xstrSource); return *this; } void CXStringA::MakeLower() { LPSTR ptchString = (LPSTR)C_Str(); #if _MSC_VER > 1000 _strlwr_s(ptchString, m_nLength); #else strlwr(ptchString, m_nLength); #endif } void CXStringA::MakeUpper() { LPSTR ptchString = (LPSTR)C_Str(); #if _MSC_VER > 1000 _strupr_s(ptchString, m_nLength); #else strupr(ptchString); #endif } BOOL CXStringA::Compare(LPCSTR pchCompareString) const { assert(NULL != pchCompareString); return pchCompareString ? (0 == strcmp(C_Str(), pchCompareString)) : FALSE; } BOOL CXStringA::Compare(const CXStringA &xstrCompareString) const { return Compare(xstrCompareString.C_Str()); } BOOL CXStringA::CompareNoCase(LPCSTR pchCompareString) const { assert(NULL != pchCompareString); #if _MSC_VER >= 1400 return pchCompareString ? (0 == _stricmp(C_Str(), pchCompareString)) : FALSE; #else return pchCompareString ? (0 == stricmp(C_Str(), pchCompareString)) : FALSE; #endif } BOOL CXStringA::CompareNoCase(const CXStringA &xstrA) const { return CompareNoCase(xstrA.C_Str()); } BOOL CXStringA::operator==(const CXStringA &xstrA) const { return Compare(xstrA); } BOOL CXStringA::operator!=(const CXStringA &xstrA) const { return !Compare(xstrA); } BOOL CXStringA::operator==(LPCSTR pchData) const { return Compare(pchData); } BOOL CXStringA::operator!=(LPCSTR pwhData) const { return !(Compare(pwhData)); } BOOL CXStringA::operator==(const CHAR chA) const { CHAR achTmp[2]; achTmp[0] = chA; achTmp[1] = g_chEndMark; return Compare(achTmp); } BOOL CXStringA::operator!=(const CHAR chA) const { return !(*this == chA); } LONG CXStringA::Find(LONG nStartIndex, LPCSTR pchStringToFind) { LONG nLen = StrLen(); assert(NULL != pchStringToFind); assert(nStartIndex >= 0 && nStartIndex < nLen); LPSTR pchString; if (nStartIndex < 0) { nStartIndex = 0; } else if(nStartIndex > nLen) { nStartIndex = nLen; } pchString = (LPSTR)C_Str(); LPSTR ptchResult = strstr(pchString + nStartIndex, pchStringToFind); return NULL != ptchResult ? (LONG)(ptchResult - pchString) : -1; } LONG CXStringA::Find(LPCSTR pchStringToFind) { return Find(0, pchStringToFind); } LONG CXStringA::Find(LONG nStartIndex, CHAR chChrToFind) { CHAR achBuffer[2]; achBuffer[0] = chChrToFind; achBuffer[1] = g_chEndMark; return Find(nStartIndex, achBuffer); } LONG CXStringA::Find(const CHAR chChrToFind) { return Find(0, chChrToFind); } LONG CXStringA::FindNoCase(LONG nStartIndex, LPCSTR pwhStringToFind) { CXStringA xstrTempLower = *this; xstrTempLower.MakeLower(); CXStringA xstrStringToFindLower = pwhStringToFind; xstrStringToFindLower.MakeLower(); return xstrTempLower.Find(nStartIndex, xstrStringToFindLower.C_Str()); } LONG CXStringA::FindNoCase(LPCSTR pchStringToFind) { return FindNoCase(0, pchStringToFind); } LONG CXStringA::FindNoCase(LONG nStartIndex, const CHAR chChrToFind) { CHAR achTemp[2]; achTemp[0] = chChrToFind; achTemp[1] = g_chEndMark; return FindNoCase(nStartIndex, achTemp); } LONG CXStringA::FindNoCase(const CHAR whChrToFind) { return FindNoCase(0, whChrToFind); } LONG CXStringA::ReverseFind(LONG nStartIndex, const CHAR chChr) { LPSTR pwhResult = NULL, pwhString = (LPSTR)C_Str(); assert(nStartIndex >= 0 && nStartIndex < m_nLength); pwhResult = strrchr(pwhString + nStartIndex, chChr); return NULL != pwhResult ? (LONG)(pwhResult - pwhString) : -1; } LONG CXStringA::ReverseFind(const CHAR chChr) { return ReverseFind(0, chChr); } CXStringA CXStringA::Left(LONG nCount) { LPSTR pchString = (LPSTR)C_Str(); assert(NULL != pchString); assert(nCount > 0 && nCount <= m_nLength); CXStringA xstrTmp(pchString, nCount); return xstrTmp; } CXStringA CXStringA::ExcludeLeft(LONG nCount) { return Right(m_nLength - nCount); } CXStringA CXStringA::Mid(LONG nIndex, LONG nCount) { assert(nCount >= 0); LPSTR pchString = (LPSTR)C_Str(); assert(nIndex >= 0 && nIndex <= m_nLength - nCount && nCount > 0); CXStringA xstrData(pchString + nIndex, nCount); return xstrData; } CXStringA CXStringA::Right(LONG nCount) { return Mid(m_nLength - nCount, nCount); } void CXStringA::InternalLeft(LONG nCount) { InternalMid(0, nCount); } void CXStringA::InternalExcludeLeft(LONG nCount) { InternalRight(m_nLength - nCount); } void CXStringA::InternalMid(LONG nIndex, LONG nCount) { LPSTR pwhString = (LPSTR)C_Str(); assert(nIndex >= 0 && nIndex + nCount <= m_nLength && nCount >= 0); if (0 != nIndex && nCount > 0) { Mem_CopyMemory(pwhString, pwhString + nIndex, nCount * sizeof(CHAR)); } pwhString[nCount] = g_whEndMark; #if defined(_DEBUG) || defined(DEBUG) { if (nIndex + nCount < m_nLength) { Mem_ZeroMemory(pwhString + nCount, (m_nLength - nCount) * sizeof(CHAR)); } } #endif m_nLength = nCount; } void CXStringA::InternalRight(LONG nCount) { InternalMid(m_nLength - nCount, nCount); } CXStringA::operator LPCSTR() const { return (LPCSTR)C_Str(); } CXStringA &CXStringA::operator+=(const CXStringA &xstrAdditionalString) { Strcat(xstrAdditionalString); return *this; } CXStringA &CXStringA::operator+=(LPCSTR pchAdditionalString) { Strcat(pchAdditionalString); return *this; } CXStringA &CXStringA::operator+=(const CHAR& chAdditionalChar) { CHAR awhAdditionalString[2]; awhAdditionalString[0] = chAdditionalChar; awhAdditionalString[1] = g_chEndMark; Strcat(awhAdditionalString); return *this; } CXStringA CXStringA::operator+(const CXStringA &pchAdditionalString) { CXStringA xstrTmp = *this; xstrTmp.Strcat(pchAdditionalString); return xstrTmp; } CXStringA CXStringA::operator+(LPCSTR pchAdditionalString) { CXStringA xstrTmp = *this; xstrTmp.Strcat(pchAdditionalString); return xstrTmp; } CXStringA CXStringA::operator+(const CHAR chAdditionalChar) { CXStringA xstrTmp = *this; xstrTmp += chAdditionalChar; return xstrTmp; } CXStringA operator+(LPCSTR pwhA, const CXStringA &xstrB) { CXStringA xstrTmp = pwhA; xstrTmp += xstrB; return xstrTmp; } CXStringA operator+(const CHAR &chAdditionalChar, const CXStringA& xstrB) { CXStringA xstrTmp(chAdditionalChar); xstrTmp += xstrB; return xstrTmp; } ////////////////////////////////////////////////////////////////////////// BOOL operator!=(LPCSTR pwhA, const CXStringA &xstrB) { return !(xstrB == pwhA); } BOOL operator==(LPCSTR pwhA, const CXStringA &xstrB) { return xstrB == pwhA; } BOOL operator!=(const CHAR whA, const CXStringA &xstrB) { return !(xstrB == whA); } BOOL operator==(const CHAR whA, const CXStringA &xstrB) { return xstrB == whA; } ////////////////////////////////////////////////////////////////////////// void CXStringA::TrimLeft(const CHAR chA) { CHAR achTag[2]; achTag[0] = chA; achTag[1] = g_chEndMark; TrimLeft(achTag); } void CXStringA::TrimLeft(LPCSTR pchTag) { //assert(NULL != pchTag); if (IsEmpty()) { return; } LPSTR pwhString = (LPSTR)C_Str(); assert(m_nLength > 0); LONG nAmount = 0; if (!pchTag) { pchTag = g_achDelimit; } nAmount = (LONG)strspn(pwhString, pchTag); assert(nAmount <= m_nLength); InternalExcludeLeft(nAmount); } void CXStringA::TrimRight(const CHAR chA) { CHAR achTag[2]; achTag[0] = chA; achTag[1] = g_chEndMark; TrimRight(achTag); } void CXStringA::TrimRight(LPCSTR pchTag) { if (IsEmpty()) { return; } LONG nAmount = 0; BOOL blContinue = TRUE; if (NULL == pchTag) { pchTag = g_achDelimit; } for (LONG i = 0; i < m_nLength && blContinue; i++) { if (NULL != strchr(pchTag, GetAt(m_nLength - i - 1))) nAmount ++; else blContinue = FALSE; } if (!blContinue || nAmount > 0) InternalLeft(m_nLength - nAmount); } void CXStringA::Trim(const CHAR chA) { CHAR achTag[2]; achTag[0] = chA; achTag[1] = g_chEndMark; Trim(achTag); } void CXStringA::Trim(LPCSTR pchTag) { TrimLeft(pchTag); TrimRight(pchTag); } LONG CXStringA::GetNumber() { if (IsEmpty()) return 0L; LONG nValue = 0; LPCSTR pchIndex = strpbrk(C_Str(), "0123456789.-+"); if (pchIndex) { #if _MSC_VER >= 1000 sscanf_s(pchIndex, "%ld", &nValue); #else sscanf(pchIndex, "%ld", &nValue); #endif } return nValue; } float CXStringA::GetFloat() { if (IsEmpty()) return 0.0f; float flValue = 0.0; LPCSTR pwhIndex = strpbrk(C_Str(), "0123456789.-+"); if (pwhIndex) { #if _MSC_VER >= 1000 sscanf_s(pwhIndex, "%f", &flValue); #else sscanf(pwhIndex, "%f", &flValue); #endif } return flValue; } LONG CXStringA::GetHex() { if (IsEmpty()) return 0; LONG nValue = 0; LPCSTR pwhIndex = strpbrk(C_Str(), "0123456789ABCDEFabcdef-+"); if (pwhIndex) { #if _MSC_VER >= 1000 sscanf_s(pwhIndex, "%x", &nValue); #else sscanf(pwhIndex, "%x", &nValue); #endif } return nValue; } void CXStringA::ReplaceChar(const CHAR A, const CHAR B) { LPSTR strString = (LPSTR)C_Str(); assert(strString); if (!strString) { return; } assert(strlen(strString) == m_nLength); while (*strString) { if (A == *strString) { *strString = B; } strString ++; } } void CXStringA::ReplaceCharWithString(const CHAR chA, LPCSTR pwhStringB) { if (IsEmpty()) return; CXStringA xstrData; LONG nSearchIndex = 0; LONG nFindIndex; LPSTR pwhString = (LPSTR)C_Str(); while (nSearchIndex < m_nLength && (nFindIndex = Find(nSearchIndex, chA)) > -1) { //assert (nFindIndex > nSearchIndex); //xstrData += Mid(nSearchIndex, nFindIndex - nSearchIndex); if (nFindIndex != nSearchIndex) { xstrData.Strcat(pwhString + nSearchIndex, nFindIndex - nSearchIndex); } xstrData += pwhStringB; nSearchIndex = ++ nFindIndex; } //处理尾巴 if (nSearchIndex < m_nLength) xstrData += pwhString + nSearchIndex; *this = xstrData; } void CXStringA::ReplaceCharWithString(const CHAR chA, const CXStringA &xstrB) { ReplaceCharWithString(chA, xstrB.C_Str()); } void CXStringA::Format(LPCSTR pchFormat, ...) { LPSTR pwhBuffer = NULL; LONG nLen = 0; va_list argList; va_start(argList, pchFormat); nLen = _vscprintf(pchFormat, argList); Reserve(nLen + 1); Clear(); pwhBuffer = (LPSTR)C_Str(); #if _MSC_VER >= 1000 vsprintf_s(pwhBuffer, nLen + 1, pchFormat, argList); #else vsprintf(pwhBuffer, pchFormat, argList); #endif va_end(argList); m_nLength = (LONG)strlen(pwhBuffer); } void CXStringA::FormatEx(LPCSTR pchFormat, ...) { LPSTR pchBuffer = NULL; va_list argList; LONG nLen = 0, nLenOrg = m_nLength; va_start(argList, pchFormat); nLen = _vscprintf(pchFormat, argList); Reserve(nLen + nLenOrg + 1); pchBuffer = (LPSTR)C_Str(); #if _MSC_VER >= 1000 vsprintf_s(pchBuffer + nLenOrg, nLen + 1, pchFormat, argList); #else vsprintf(pchBuffer + nLenOrg, pchFormat, argList); #endif va_end(argList); m_nLength = (LONG)strlen(pchBuffer); } BOOL CXStringA::Token(LPCSTR pchDelimit, std::vector<CXStringA> &vString) const { assert(pchDelimit); BOOL blRet = TRUE; if (strlen(pchDelimit) < 1) { blRet = FALSE; return blRet; } CXStringA strTmp = *this; CXStringA strSubStr; LPCSTR pchToken = NULL; LPSTR ptStr = (LPSTR)strTmp.C_Str(); #if _MSC_VER >= 1000 LPSTR pchContent; pchToken = strtok_s( ptStr, pchDelimit, &pchContent); while( NULL != pchToken ) { strSubStr = pchToken; vString.push_back(strSubStr); pchToken = strtok_s( NULL, pchDelimit, &pchContent); } #else pchToken = strtok( ptStr, pchDelimit); while( NULL != pchToken ) { strSubStr = pchToken; vString.push_back(strSubStr); pchToken = strtok( NULL, pchDelimit ); } #endif return blRet; } BOOL CXStringA::Token(const CHAR chDelimit, std::vector<CXStringA> &vString) const { CHAR achDelimit[2]; achDelimit[0] = chDelimit; achDelimit[1] = g_chEndMark; return Token(achDelimit, vString); } CXStringA CXStringA::From( LPCWSTR pwhA) { USES_CONVERSION; LPSTR pchB = W2A(pwhA); return CXStringA(pchB); } CXStringA CXStringA::From( LPCSTR pchA) { return CXStringA(pchA); } CXStringA CXStringA::From( LONG nData) { CHAR achBuffer[50]; #if _MSC_VER >= 1000 sprintf_s(achBuffer, 50, "%d", nData); #else sprintf(achBuffer, "%d", nData); #endif return achBuffer; } CXStringA CXStringA::From( DWORD dwData) { CHAR achBuffer[50]; #if _MSC_VER >= 1000 sprintf_s(achBuffer, 50, "%x", dwData); #else sprintf(achBuffer, "%x", dwData); #endif return achBuffer; } CXStringA CXStringA::From( double dbData) { CHAR achBuffer[50]; #if _MSC_VER >= 1000 sprintf_s(achBuffer, 50, "%f", dbData); #else sprintf(achBuffer, "%f", dbData); #endif return achBuffer; } LPSTR CXStringA::GetBuffer( const DWORD& dwSize) { Reserve(dwSize + 1); return LPSTR(m_tPackage.GetData()); } void CXStringA::ReleaseBuffer() { m_nLength = (LONG)strlen(C_Str()); } void CXStringA::Remove( const CHAR chA) { if (m_nLength <= 0) { return; } LPSTR strBuff = (LPSTR)C_Str(); LPCSTR strIndex = strBuff; assert((LONG)strlen(strBuff) == m_nLength); while(*strIndex != g_chEndMark) { if (*strIndex != chA) { *strBuff ++ = *strIndex; } strIndex ++; } *strBuff = g_chEndMark; m_nLength = (LONG)strlen(C_Str()); } std::ostream &operator<<(std::ostream & oStream, const CXStringA &xStr) { oStream<<xStr.C_Str(); return oStream; }
[ "jtxuee@8e66cb3a-4d54-0410-a772-b92400a1a2d6", "[email protected]" ]
[ [ [ 1, 25 ], [ 28, 30 ], [ 33, 35 ], [ 41, 42 ], [ 46, 48 ], [ 51, 53 ], [ 60, 63 ], [ 65, 65 ], [ 69, 69 ], [ 71, 85 ], [ 87, 90 ], [ 96, 96 ], [ 98, 101 ], [ 104, 108 ], [ 111, 114 ], [ 117, 119 ], [ 121, 123 ], [ 129, 132 ], [ 143, 145 ], [ 156, 158 ], [ 160, 162 ], [ 164, 166 ], [ 169, 172 ], [ 174, 177 ], [ 189, 191 ], [ 211, 213 ], [ 225, 227 ], [ 229, 231 ], [ 234, 236 ], [ 239, 241 ], [ 243, 246 ], [ 249, 252 ], [ 255, 258 ], [ 265, 268 ], [ 275, 278 ], [ 281, 284 ], [ 286, 289 ], [ 296, 299 ], [ 301, 304 ], [ 306, 308 ], [ 310, 312 ], [ 314, 316 ], [ 318, 320 ], [ 325, 327 ], [ 329, 331 ], [ 348, 350 ], [ 352, 354 ], [ 359, 361 ], [ 363, 365 ], [ 371, 373 ], [ 375, 377 ], [ 382, 384 ], [ 386, 388 ], [ 391, 391 ], [ 394, 396 ], [ 398, 400 ], [ 405, 405 ], [ 407, 410 ], [ 412, 415 ], [ 417, 417 ], [ 421, 421 ], [ 423, 426 ], [ 428, 431 ], [ 433, 436 ], [ 438, 441 ], [ 449, 449 ], [ 456, 456 ], [ 458, 461 ], [ 463, 466 ], [ 468, 470 ], [ 473, 476 ], [ 479, 482 ], [ 486, 486 ], [ 489, 492 ], [ 496, 499 ], [ 503, 506 ], [ 510, 513 ], [ 517, 519 ], [ 523, 526 ], [ 528, 531 ], [ 533, 535 ], [ 537, 539 ], [ 541, 544 ], [ 549, 551 ], [ 567, 569 ], [ 574, 576 ], [ 597, 599 ], [ 604, 606 ], [ 609, 611 ], [ 614, 614 ], [ 626, 629 ], [ 632, 632 ], [ 644, 647 ], [ 650, 650 ], [ 654, 654 ], [ 660, 660 ], [ 662, 664 ], [ 666, 683 ], [ 686, 686 ], [ 700, 700 ], [ 706, 706 ], [ 708, 711 ], [ 713, 716 ], [ 732, 735 ], [ 750, 753 ], [ 784, 786 ], [ 791, 793 ], [ 798, 800 ], [ 802, 804 ], [ 812, 814 ], [ 822, 824 ], [ 832, 834 ], [ 837, 839 ], [ 841, 850 ], [ 852, 860 ], [ 862, 864 ], [ 867, 874 ], [ 877, 879 ], [ 882, 884 ], [ 890, 892 ], [ 895, 897 ], [ 900, 903 ], [ 908, 930 ], [ 932, 935 ], [ 941, 941 ], [ 943, 946 ], [ 949, 953 ], [ 956, 959 ], [ 962, 964 ], [ 966, 968 ], [ 974, 977 ], [ 988, 990 ], [ 1001, 1003 ], [ 1005, 1007 ], [ 1009, 1011 ], [ 1014, 1017 ], [ 1019, 1022 ], [ 1034, 1036 ], [ 1048, 1048 ], [ 1056, 1058 ], [ 1070, 1072 ], [ 1074, 1076 ], [ 1079, 1081 ], [ 1084, 1086 ], [ 1088, 1091 ], [ 1094, 1097 ], [ 1100, 1103 ], [ 1110, 1113 ], [ 1120, 1123 ], [ 1126, 1129 ], [ 1131, 1134 ], [ 1141, 1144 ], [ 1146, 1149 ], [ 1151, 1153 ], [ 1155, 1157 ], [ 1159, 1161 ], [ 1163, 1165 ], [ 1170, 1172 ], [ 1174, 1176 ], [ 1193, 1195 ], [ 1197, 1199 ], [ 1204, 1206 ], [ 1208, 1210 ], [ 1216, 1218 ], [ 1220, 1222 ], [ 1227, 1229 ], [ 1231, 1233 ], [ 1236, 1236 ], [ 1239, 1241 ], [ 1243, 1245 ], [ 1250, 1250 ], [ 1252, 1255 ], [ 1257, 1260 ], [ 1262, 1262 ], [ 1266, 1266 ], [ 1268, 1271 ], [ 1273, 1276 ], [ 1278, 1281 ], [ 1283, 1286 ], [ 1294, 1294 ], [ 1301, 1301 ], [ 1303, 1306 ], [ 1308, 1311 ], [ 1313, 1315 ], [ 1318, 1321 ], [ 1324, 1327 ], [ 1331, 1331 ], [ 1334, 1337 ], [ 1341, 1344 ], [ 1348, 1351 ], [ 1355, 1358 ], [ 1362, 1364 ], [ 1368, 1371 ], [ 1373, 1375 ], [ 1377, 1379 ], [ 1381, 1383 ], [ 1385, 1388 ], [ 1393, 1395 ], [ 1411, 1413 ], [ 1418, 1420 ], [ 1441, 1443 ], [ 1448, 1450 ], [ 1453, 1455 ], [ 1458, 1458 ], [ 1470, 1473 ], [ 1476, 1476 ], [ 1488, 1491 ], [ 1494, 1494 ], [ 1506, 1527 ], [ 1530, 1530 ], [ 1544, 1544 ], [ 1550, 1550 ], [ 1552, 1555 ], [ 1557, 1560 ], [ 1576, 1579 ], [ 1594, 1597 ], [ 1629, 1631 ], [ 1636, 1638 ], [ 1642, 1644 ], [ 1646, 1648 ], [ 1656, 1658 ], [ 1666, 1668 ], [ 1676, 1678 ], [ 1681, 1683 ], [ 1685, 1694 ], [ 1696, 1704 ], [ 1706, 1708 ], [ 1711, 1711 ] ], [ [ 26, 27 ], [ 31, 32 ], [ 36, 40 ], [ 43, 45 ], [ 49, 50 ], [ 54, 59 ], [ 64, 64 ], [ 66, 68 ], [ 70, 70 ], [ 86, 86 ], [ 91, 95 ], [ 97, 97 ], [ 102, 103 ], [ 109, 110 ], [ 115, 116 ], [ 120, 120 ], [ 124, 128 ], [ 133, 142 ], [ 146, 155 ], [ 159, 159 ], [ 163, 163 ], [ 167, 168 ], [ 173, 173 ], [ 178, 188 ], [ 192, 210 ], [ 214, 224 ], [ 228, 228 ], [ 232, 233 ], [ 237, 238 ], [ 242, 242 ], [ 247, 248 ], [ 253, 254 ], [ 259, 264 ], [ 269, 274 ], [ 279, 280 ], [ 285, 285 ], [ 290, 295 ], [ 300, 300 ], [ 305, 305 ], [ 309, 309 ], [ 313, 313 ], [ 317, 317 ], [ 321, 324 ], [ 328, 328 ], [ 332, 347 ], [ 351, 351 ], [ 355, 358 ], [ 362, 362 ], [ 366, 370 ], [ 374, 374 ], [ 378, 381 ], [ 385, 385 ], [ 389, 390 ], [ 392, 393 ], [ 397, 397 ], [ 401, 404 ], [ 406, 406 ], [ 411, 411 ], [ 416, 416 ], [ 418, 420 ], [ 422, 422 ], [ 427, 427 ], [ 432, 432 ], [ 437, 437 ], [ 442, 448 ], [ 450, 455 ], [ 457, 457 ], [ 462, 462 ], [ 467, 467 ], [ 471, 472 ], [ 477, 478 ], [ 483, 485 ], [ 487, 488 ], [ 493, 495 ], [ 500, 502 ], [ 507, 509 ], [ 514, 516 ], [ 520, 522 ], [ 527, 527 ], [ 532, 532 ], [ 536, 536 ], [ 540, 540 ], [ 545, 548 ], [ 552, 566 ], [ 570, 573 ], [ 577, 596 ], [ 600, 603 ], [ 607, 608 ], [ 612, 613 ], [ 615, 625 ], [ 630, 631 ], [ 633, 643 ], [ 648, 649 ], [ 651, 653 ], [ 655, 659 ], [ 661, 661 ], [ 665, 665 ], [ 684, 685 ], [ 687, 699 ], [ 701, 705 ], [ 707, 707 ], [ 712, 712 ], [ 717, 731 ], [ 736, 749 ], [ 754, 783 ], [ 787, 790 ], [ 794, 797 ], [ 801, 801 ], [ 805, 811 ], [ 815, 821 ], [ 825, 831 ], [ 835, 836 ], [ 840, 840 ], [ 851, 851 ], [ 861, 861 ], [ 865, 866 ], [ 875, 876 ], [ 880, 881 ], [ 885, 889 ], [ 893, 894 ], [ 898, 899 ], [ 904, 907 ], [ 931, 931 ], [ 936, 940 ], [ 942, 942 ], [ 947, 948 ], [ 954, 955 ], [ 960, 961 ], [ 965, 965 ], [ 969, 973 ], [ 978, 987 ], [ 991, 1000 ], [ 1004, 1004 ], [ 1008, 1008 ], [ 1012, 1013 ], [ 1018, 1018 ], [ 1023, 1033 ], [ 1037, 1047 ], [ 1049, 1055 ], [ 1059, 1069 ], [ 1073, 1073 ], [ 1077, 1078 ], [ 1082, 1083 ], [ 1087, 1087 ], [ 1092, 1093 ], [ 1098, 1099 ], [ 1104, 1109 ], [ 1114, 1119 ], [ 1124, 1125 ], [ 1130, 1130 ], [ 1135, 1140 ], [ 1145, 1145 ], [ 1150, 1150 ], [ 1154, 1154 ], [ 1158, 1158 ], [ 1162, 1162 ], [ 1166, 1169 ], [ 1173, 1173 ], [ 1177, 1192 ], [ 1196, 1196 ], [ 1200, 1203 ], [ 1207, 1207 ], [ 1211, 1215 ], [ 1219, 1219 ], [ 1223, 1226 ], [ 1230, 1230 ], [ 1234, 1235 ], [ 1237, 1238 ], [ 1242, 1242 ], [ 1246, 1249 ], [ 1251, 1251 ], [ 1256, 1256 ], [ 1261, 1261 ], [ 1263, 1265 ], [ 1267, 1267 ], [ 1272, 1272 ], [ 1277, 1277 ], [ 1282, 1282 ], [ 1287, 1293 ], [ 1295, 1300 ], [ 1302, 1302 ], [ 1307, 1307 ], [ 1312, 1312 ], [ 1316, 1317 ], [ 1322, 1323 ], [ 1328, 1330 ], [ 1332, 1333 ], [ 1338, 1340 ], [ 1345, 1347 ], [ 1352, 1354 ], [ 1359, 1361 ], [ 1365, 1367 ], [ 1372, 1372 ], [ 1376, 1376 ], [ 1380, 1380 ], [ 1384, 1384 ], [ 1389, 1392 ], [ 1396, 1410 ], [ 1414, 1417 ], [ 1421, 1440 ], [ 1444, 1447 ], [ 1451, 1452 ], [ 1456, 1457 ], [ 1459, 1469 ], [ 1474, 1475 ], [ 1477, 1487 ], [ 1492, 1493 ], [ 1495, 1505 ], [ 1528, 1529 ], [ 1531, 1543 ], [ 1545, 1549 ], [ 1551, 1551 ], [ 1556, 1556 ], [ 1561, 1575 ], [ 1580, 1593 ], [ 1598, 1628 ], [ 1632, 1635 ], [ 1639, 1641 ], [ 1645, 1645 ], [ 1649, 1655 ], [ 1659, 1665 ], [ 1669, 1675 ], [ 1679, 1680 ], [ 1684, 1684 ], [ 1695, 1695 ], [ 1705, 1705 ], [ 1709, 1710 ] ] ]
202d5b6dddc2086b889f5cb441f797aff54572d6
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/compatanalysercmd/libraryanalyser/inc/xmlstringtostlstring.hpp
53d2ecba5042cc1df5be9be00352f13460c947e5
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
hpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include <xercesc/sax/HandlerBase.hpp> #include <xercesc/sax/AttributeList.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <string> #if !defined XMLSTRTOSTLSTR #define XMLSTRTOSTLSTR class XMLStringToSTLString { public: XMLStringToSTLString(const XMLCh* const toTranscode) { str = XMLString::transcode(toTranscode); } ~XMLStringToSTLString() {} const std::string& data() const { return str; } private: std::string str; }; inline std::ostream& operator<<(std::ostream& target, const XMLStringToSTLString& toDump) { target << toDump.data(); return target; } #endif // XMLSTRTOSTLSTR
[ "none@none" ]
[ [ [ 1, 48 ] ] ]
d6e2842cb39e906f8fb1e098e9389c1f1d559982
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/source/KeyHandler.cpp
e18bbdf4f6646cce874595a9e2070326ee46e495
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
2,768
cpp
/*============================================================================= KeyHandler.cpp Author: Greg King This was going to bind the keys not only to a message but to a certain game object This line of thought was dropped as gameobject ID's may not be consisten between maps or even the reloading of a level =============================================================================*/ #include "Keyhandler.h" //============================================================================= // Constructor // KeyHandler::KeyHandler(OIS::Keyboard* keyBoard) { keyBoard_ = keyBoard; } //============================================================================= // Update // bool KeyHandler::Update(double timeSinceLastFrame) { return true; } //============================================================================= // KeyPressed // /// Called by physics state on keypresses bool KeyHandler::KeyPressed(const OIS::KeyEvent &keyEventRef) { KeyMap::const_iterator currentKey_ = keyListDown_.find(keyEventRef.key); if(currentKey_ == keyListDown_.end()) { return false; } else { Dispatch->DispatchMessage(SEND_IMMEDIATELY, 0, SEND_TO_ALL, currentKey_->second, NULL); return true; } return false; } //============================================================================= // KeyReleased // /// Called by physics state on keyReleases bool KeyHandler::KeyReleased(const OIS::KeyEvent &keyEventRef) { KeyMap::const_iterator currentKey_ = keyListUp_.find(keyEventRef.key); if(currentKey_ == keyListUp_.end()) { return false; } else { Dispatch->DispatchMessage(SEND_IMMEDIATELY, 0, SEND_TO_ALL, currentKey_->second, NULL); return true; } return false; } //============================================================================= // HandleMessage // bool KeyHandler::HandleMessage(const KGBMessage message) { return false; } //============================================================================= // AddKey // /// Adds the entered key as being bound to the entered message /// @warning only binds to keypressed bool KeyHandler::AddKey(const OIS::KeyCode key, KGBMessageType messageType) { keyListDown_[key] = messageType; return true; } //============================================================================= // Addkey // /// Adds a message to key pressed and key released of entered key /// @param messageType1 is pressed, messageType2 is released bool KeyHandler::AddKey(const OIS::KeyCode key, KGBMessageType messageType1, KGBMessageType messageType2) { keyListDown_[key] = messageType1; keyListUp_[key] = messageType2; return true; }
[ "mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce", "Kaziks@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
[ [ [ 1, 6 ], [ 10, 12 ], [ 16, 20 ], [ 24, 28 ], [ 33, 48 ], [ 53, 68 ], [ 72, 76 ], [ 82, 87 ], [ 94, 94 ], [ 97, 98 ] ], [ [ 7, 9 ], [ 13, 15 ], [ 21, 23 ], [ 29, 32 ], [ 49, 52 ], [ 69, 71 ], [ 77, 81 ], [ 88, 93 ], [ 95, 96 ] ] ]
3a631115d4d2892df77daddbd4d0d7e05a6ca0a7
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthreadmisc.cpp
3b4ac9e786a3ea168f4b3c89ab593024028d0ee7
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
8,831
cpp
/* * Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Thread Miscellaneous functions are implemented in this file. * * */ #include <pthread.h> #include <stdio.h> #include <errno.h> #include <e32base.h> #include "threadglobals.h" #define THREAD_NAME_WIDTH 8 #define THREAD_COUNT_ZERO 0 #define MAX_THREAD_CREATE_FAILURE_COUNT 20 #define MAX_THREAD_NAME_LEN 255 #ifdef __EPOC32__ class XPthreadTLSCleanup { public: ~XPthreadTLSCleanup() { Dll::FreeTls(); } }; // Create a global here. It's desctructor invoked on libpthread unload will reset libpthread's TLS XPthreadTLSCleanup gPthreadTLSCleanup; #endif // Internal Function // return : NULL - means no memory void* _pthread_getTls() { _pthread_node_t *selfNodePtr; _global_data_t *glbPtr; THR_PRINTF("[pthread] Begin _pthread_getTls\n"); // Get the TLS contents. TAny *tlsAddr = Dll::Tls(); // If TLS is already initialised then just return the node address if (NULL != tlsAddr) { THR_PRINTF("[pthread] End _pthread_getTls\n"); return ((void*) tlsAddr); } // Create node for main thread and also global data structure. selfNodePtr = new _pthread_node_t; THR_NULL_ASSERT(selfNodePtr,NULL, "[pthread] FATAL: Memory alloc failed for threadnode"); glbPtr = new _global_data_t; THR_NULL_ASSERT(glbPtr, NULL, "[pthread] FATAL:Memory alloc failed for global data"); //Initialize the node selfNodePtr->next = NULL; if (selfNodePtr->lockNode.CreateLocal() != KErrNone) { delete selfNodePtr; delete glbPtr; THR_PRINTF("[pthread] FATAL :Mutex create failed"); return ((void*)NULL); } selfNodePtr->glbDataPtr = glbPtr; selfNodePtr->detachState = PTHREAD_CREATE_JOINABLE; selfNodePtr->threadState = _THREAD_RUNNING; selfNodePtr->returnValue = NULL; selfNodePtr->hasAnyThreadJoined = EFalse; selfNodePtr->threadId = (TUint)selfNodePtr->rtHandle.Id(); selfNodePtr->priority = DEFAULT_THREAD_PRIORITY; selfNodePtr->mainFlag = _MAIN_THREAD; selfNodePtr->tlsHead = NULL; selfNodePtr->cleanStackPtr = NULL; //added to solve memory leak problem //Initialize global data structure glbPtr->start = selfNodePtr; glbPtr->threadCount = 1; //First thread if (glbPtr->lockThreadTable.CreateLocal() != KErrNone) { selfNodePtr->lockNode.Close(); delete selfNodePtr; delete glbPtr; THR_PRINTF("[pthread] FATAL :Mutex create failed"); return ((void*)NULL); } if (glbPtr->globalLockForMutex.CreateLocal() != KErrNone) { selfNodePtr->lockNode.Close(); delete selfNodePtr; glbPtr->lockThreadTable.Close(); delete glbPtr; THR_PRINTF("[pthread] FATAL :Mutex create failed"); return ((void*)NULL); } // Initialize all keys in pthread_key_list to NOT USED for (int loopvar = 0; loopvar < PTHREAD_KEYS_MAX; loopvar++) { // Set it to unused glbPtr->pthread_key_list[loopvar].destr = NULL; } for (int loopvar = 0; loopvar < STAT_FLAG_SIZE; loopvar++) { // Set it to unused glbPtr->statusflag[loopvar] = _KEY_UNUSED; } //Sem table initializations glbPtr->semStart = NULL; if (glbPtr->lockSemTable.CreateLocal() != KErrNone) { glbPtr->globalLockForMutex.Close(); selfNodePtr->lockNode.Close(); delete selfNodePtr; glbPtr->lockThreadTable.Close(); delete glbPtr; THR_PRINTF("[pthread] FATAL :Mutex create failed"); return ((void*)NULL); } //Set node address to TLS Dll::SetTls((TAny*)selfNodePtr); THR_PRINTF("[pthread] End _pthread_getTls\n"); // libc needs to know whether application is multithreaded or not... __isthreaded = 1; return ((void*) selfNodePtr); } // This function has to be called holding global lock and node lock. // Before returning all lock will be opened void _pthread_deleteNode(_pthread_node_t *selfNodePtr, _global_data_t *glbPtr, void ** retValPtr) { _pthread_node_t *tempPtr; _pthread_node_t *prevPtr = NULL; THR_PRINTF("[pthread] Begin _pthread_deleteNode\n"); // Traverse through the list, till node which has to be deleted is found for (tempPtr = glbPtr->start; ((tempPtr != selfNodePtr) && (tempPtr != NULL)); tempPtr = tempPtr->next) { prevPtr = tempPtr; // Store the previous node ptr } if (NULL == tempPtr) //Not found; this should never happen { THR_PRINTF("[pthread] FATAL: Unable to delete the node"); selfNodePtr->lockNode.Signal(); glbPtr->lockThreadTable.Signal(); //release global lock return; } if (tempPtr == glbPtr->start) // Deleting first node { glbPtr->start = tempPtr->next; //Update the link list } else { prevPtr->lockNode.Wait(); //Acquire the previous node lock prevPtr->next = tempPtr->next; //Update the link list prevPtr->lockNode.Signal(); //Release the previous node lock } if (NULL != retValPtr) // Get the return value { *retValPtr = selfNodePtr->returnValue; } selfNodePtr->lockNode.Signal(); // Unlock & Free the node selfNodePtr->lockNode.Close(); selfNodePtr->rtHandle.Close(); delete selfNodePtr; //--(glbPtr->threadCount); // Update the thread count //if (THREAD_COUNT_ZERO == glbPtr->threadCount) //{ // RProcess rp; // rp.Kill(0); // Terminate the process //} glbPtr->lockThreadTable.Signal(); // release thread table lock THR_PRINTF("[pthread] End of _pthread_deleteNode\n"); } void* _getKeyValueSetNull(int keyNumber,_pkey_node_t *tlsPtr) { void* retVal; for ( ; tlsPtr != NULL; tlsPtr = tlsPtr->next) { if (tlsPtr->keyNumber == keyNumber) { retVal = tlsPtr->tls; tlsPtr->tls = NULL; return (retVal); } } //This should never happen; hence dest function will not be called return NULL; } // Before calling this function, global lock and node lock must be open void _pthread_destroyKeys(_global_data_t *glbPtr, _pthread_node_t *selfNodePtr) { int loopvar; int allempty; int keyNumber; destructor_routine dest; void *arg; glbPtr->lockThreadTable.Wait(); // Acquire the thread table lock selfNodePtr->lockNode.Wait(); // Lock the TCB for (loopvar = 0, allempty = 1; allempty && (loopvar < PTHREAD_DESTRUCTOR_ITERATIONS);loopvar++) { allempty = 0; // Assuming all keys are not used. for (keyNumber = 0; keyNumber < PTHREAD_KEYS_MAX; keyNumber++) { int temp; temp = keyNumber / 32; int bitPos; bitPos = keyNumber % 32; if (((glbPtr->statusflag[temp]) & (0x1<<bitPos)) && //Key used (glbPtr->pthread_key_list[keyNumber].destr != NULL)) { if ((arg = _getKeyValueSetNull(keyNumber,selfNodePtr->tlsHead)) != NULL) { dest = glbPtr->pthread_key_list[keyNumber].destr; selfNodePtr->lockNode.Signal(); // Unlock TCB node glbPtr->lockThreadTable.Signal(); // release thread table lock dest(arg); //Call destructor glbPtr->lockThreadTable.Wait();// Acquire the thread table lock selfNodePtr->lockNode.Wait(); // Lock the TCB allempty = 1; // Atleast one key was used } } } } selfNodePtr->lockNode.Signal(); // Unlock TCB node glbPtr->lockThreadTable.Signal(); // release thread table lock } // End of File
[ "none@none" ]
[ [ [ 1, 275 ] ] ]
5a10317c483b061590fcbfaaee9c620de372e523
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/InputDevice.h
72dcc647bb0e99348f023fcec886e22f990b3ede
[]
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
1,100
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: InputDevice.h Version: 0.04 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_INPUTDEVICE_H_ #define __INC_INPUTDEVICE_H_ #include "Prerequisities.h" namespace nGENE { /** Input device base class. @par To create specific device class you have to derive this class. This way apart from creating regular devices like mouse, keyboard or joystick you can make use of any other input device. */ class nGENEDLL InputDevice { public: InputDevice(); virtual ~InputDevice(); /// Creates the device. virtual void createDevice()=0; /// Retrieves input from the device. virtual void retrieveData()=0; }; /// Factory to be used for InputDevice class objects creation. class nGENEDLL InputDeviceFactory { public: virtual InputDevice* createInputDevice()=0; }; } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 51 ] ] ]
f85f8129ded63215512081de261ccedd0d5c1cad
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/Intelligence.h
ce62c9c0ca6e1bb18191746dffbf5083142ec49c
[]
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
2,467
h
// ----------------------------------------------------------------------- // // // MODULE : Intelligence.h // // PURPOSE : An Intelligence object // // CREATED : 9/14/99 // // (c) 1999-2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __INTELLIGENCE_H__ #define __INTELLIGENCE_H__ #include "ltengineobjects.h" #include "Prop.h" #include "IntelMgr.h" LINKTO_MODULE( Intelligence ); class Intelligence : public Prop { public : Intelligence(); ~Intelligence(); protected : virtual uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT lData); virtual bool OnTrigger(HOBJECT hSender, const CParsedMsg &cMsg); void ReadProp(ObjectCreateStruct *pData); void PostPropRead(ObjectCreateStruct* pData); private : void HandleGadgetMsg(HOBJECT hSender); void DoActivate(HOBJECT hSender); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL m_bShowPopup; LTBOOL m_bPhotoOnly; HSTRING m_hstrPickedUpCmd; // Command to send when intelligence is picked up / photographed uint8 m_nIntelId; uint32 m_nTextId; uint8 m_nPopupId; LTBOOL m_bIsIntel; LTBOOL m_bAddToList; LTBOOL m_bStartHidden; LTFLOAT m_fRespawnDelay; // How quickly we respawn HSTRING m_hstrRespawnSnd; // Sound to play when item respawns HSTRING m_hstrPickupSnd; // Sound to play when item is pickedup LTBOOL m_bSkipUpdate; void InitialUpdate(); LTBOOL Update(); }; #ifndef __PSX2 class CIntelPlugin : public CPropPlugin { public: virtual LTRESULT PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength); virtual LTRESULT PreHook_Dims( const char* szRezPath, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims); virtual LTRESULT PreHook_PropChanged( const char *szObjName, const char *szPropName, const int nPropType, const GenericProp &gpPropValue, ILTPreInterface *pInterface, const char *szModifiers ); protected : CIntelMgrPlugin m_IntelMgrPlugin; CCommandMgrPlugin m_CommandMgrPlugin; }; #endif #endif // __INTELLIGENCE_H__
[ [ [ 1, 103 ] ] ]
7ffd8b201041ef3adbb7c9f701cd965bee797ec5
d08c381305e3e675c3f8253ce88fafd5111b103c
/8_8_2008/curve_-project/doc/arm_curve_going/arm_curve_5/display.cpp
69f81cdc862500367c5267329f58443bd081d23e
[]
no_license
happypeter/tinylion
07ea77febf6dff84089eddd6e1e47cd2ae032eb2
2f802f291ff43c568f9ef5eb846719efca03cc80
refs/heads/master
2020-06-03T09:14:19.682005
2010-10-19T09:12:56
2010-10-19T09:12:56
914,128
1
0
null
null
null
null
UTF-8
C++
false
false
2,848
cpp
#include "display.h" #include "screen.h" #include <qlayout.h> #include <qtimer.h> #include <qframe.h> #include <qlineedit.h> #include <qstring.h> #include <qstringlist.h> #include <qpushbutton.h> #include <qfile.h> //#include <cstdlib> #include <iostream> using namespace std; DisplayWidget::DisplayWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { timer = 0; QVBoxLayout *vbox = new QVBoxLayout( this, 10 ); QHBoxLayout *hbox = new QHBoxLayout( vbox ); screen1 = new Screen( this ); screen1->setYTitle( QObject::tr( "Vlure 1" ) ); screen2 = new Screen( this ); screen2->setYTitle( QObject::tr( "Vlure 2" ) ); screen3 = new Screen( this ); screen3->setYTitle( QObject::tr( "Vlure 3" ) ); vbox->addWidget( screen1 ); vbox->addWidget( screen2 ); vbox->addWidget( screen3 ); lineEdit = new QLineEdit(this); lineEdit->setReadOnly( TRUE ); hbox->addWidget( lineEdit ); startButton = new QPushButton( this ); startButton->setText( tr( "&Start" ) ); stopButton = new QPushButton( this ); stopButton->setText( tr( "Sto&p" ) ); hbox->addWidget( startButton ); hbox->addWidget( stopButton ); connect( startButton, SIGNAL( clicked () ), SLOT( start() ) ); connect( stopButton, SIGNAL( clicked () ), SLOT( stop() ) ); time = 0; yval = 0.0; readFile(); } void DisplayWidget::run() { if ( !timer ) { timer = new QTimer( this ); connect( timer, SIGNAL( timeout() ), SLOT( tick() ) ); } timer->start( 1000 ); } void DisplayWidget::tick() { yval = readCurveDate(); screen1->animate( yval ); screen2->animate( yval ); screen3->animate( yval ); lineEdit->setText( QString::number( yval ) ); } void DisplayWidget::start() { run(); } void DisplayWidget::stop() { timer->stop(); } QSize DisplayWidget::sizeHint() const { return QSize( 16 * Margin, 12 * Margin ); } void DisplayWidget::readFile() { QFile file("in.txt"); file.open(IO_ReadOnly); QTextStream in(&file); str = in.read(); strlist = QStringList::split(" ", str); it = strlist.begin(); } double DisplayWidget::readCurveDate( ) { QString tempStr; double tempDate; tempStr =(QString) *it; tempDate = tempStr.toDouble(); if (it != strlist.end()) { ++it; } else { it = strlist.begin(); } return tempDate; }
[ [ [ 1, 114 ] ] ]
2029f82641a2c94081035c602882fea16f1602f0
4285d6cb9c75d3bad47e5c7c5677b81929fcfd84
/src/hsfexp/material.cpp
799fb27e69c24896a41e173548bf36c97e53fbae
[]
no_license
h3r2tic/boxen
a30cf11027f18eae7c20be13ba5f8f13e264f3bb
a8ef2c3c59e5e77869de538dcc5791cf07f64419
refs/heads/master
2020-07-17T00:36:18.131966
2010-10-27T08:50:42
2010-10-27T08:50:42
205,902,909
0
0
null
null
null
null
UTF-8
C++
false
false
7,521
cpp
#include "hsfexp.h" #include "3dsmaxport.h" #include "bmmlib.h" #include "Path.h" #include "IPathConfigMgr.h" #include "shaders.h" int HSFExp::getMaterialId(Mtl* m) { std::map<Mtl*, int>::const_iterator it = mMtlToId.find(m); if (it != mMtlToId.end()) { return it->second; } else { return -1; } } void HSFExp::findMaterial(Mtl* m) { if (!m) return; // No material assigned int id = getMaterialId(m); if (-1 == id) { mMtlToId[m] = mNextMaterialId++; mMaterials.push_back(m); if (m->IsMultiMtl()) { int numSub = m->NumSubMtls(); for (int i = 0; i < numSub; ++i) { findMaterial(m->GetSubMtl(i)); } } } } void HSFExp::findMaterial(INode* node) { // Get the material from the node Mtl* m = node->GetMtl(); findMaterial(m); } void HSFExp::exportMaterials(int level) { Indent(level); fprintf(mStream, _T("materials %d\n"), mMaterials.size()); mLastExporterdMaterial = -1; for ( std::vector<Mtl*>::iterator it = mMaterials.begin(); it != mMaterials.end(); ++it ) { exportMaterial(*it, level); } fprintf(mStream, _T("\n")); } void HSFExp::exportMaterial(Mtl* mat, int level) { if (!mat) { Indent(level); fprintf(mStream, _T("null\n")); return; } int matId = getMaterialId(mat); assert (matId != -1); // Already exported if (matId <= mLastExporterdMaterial) { Indent(level); fprintf(mStream, _T("%d\n"), matId); return; } assert (mLastExporterdMaterial < matId); mLastExporterdMaterial = matId; Indent(level++); fprintf(mStream, _T("%d {\n"), matId); { Indent(level); char* matName = escapeName(mat->GetName()); fprintf(mStream, _T("name '%s'\n"), matName); fflush(mStream); delete[] matName; } if (mat->IsMultiMtl()) { Indent(level); fprintf(mStream, _T("type 'multi'\n")); int numSub = mat->NumSubMtls(); Indent(level); fprintf(mStream, _T("sub %d\n"), numSub); for (int i = 0; i < numSub; ++i) { Mtl* sub = mat->GetSubMtl(i); exportMaterial(sub, level); } } else { BOOL isStd1 = (mat->ClassID() == Class_ID(DMTL_CLASS_ID, 0)); BOOL isStd2 = (mat->ClassID() == Class_ID(DMTL2_CLASS_ID, 0)); // See if it's a Standard material if (isStd1 || isStd2) { Indent(level); fprintf(mStream, _T("type 'standard'\n")); StdMat* stdMat = (StdMat*)mat; char* shadingName; if (isStd2) { Shader* shader = ((StdMat2*)mat)->GetShader(); if (shader) { shadingName = shader->GetName(); } else { shadingName = "Unknown"; } } else { int shading = stdMat->GetShading(); switch (shading) { case SHADE_CONST: // faceted Phong case SHADE_PHONG: { shadingName = "Phong"; } break; case SHADE_METAL: { shadingName = "Metal"; } break; case SHADE_BLINN: { shadingName = "Blinn"; } break; default: { shadingName = "Unknown"; } } } Indent(level); fprintf(mStream, _T("shader '%s'\n"), shadingName); Indent(level); fprintf( mStream, _T("diffuseTint %s\n"), color(stdMat->GetDiffuse(mStart)) ); Indent(level); fprintf( mStream, _T("specularTint %s\n"), color(stdMat->GetSpecular(mStart)) ); Indent(level); fprintf( mStream, _T("shininess %s\n"), floatVal(stdMat->GetShininess(mStart)) ); Indent(level); fprintf( mStream, _T("shininessStrength %s\n"), floatVal(stdMat->GetShinStr(mStart)) ); Indent(level); fprintf( mStream, _T("ior %s\n"), floatVal(stdMat->GetIOR(mStart)) ); Indent(level); fprintf( mStream, _T("opacity %s\n"), floatVal(stdMat->GetOpacity(mStart)) ); BOOL twoSided = stdMat->GetTwoSided(); //buf.printf(_T("Two sided=%d, U Tile = %.1f, V Tile = %.1f"), //two, utile, vtile); int numSubMaps = mat->NumSubTexmaps(); Indent(level); fprintf(mStream, _T("maps %d\n"), numSubMaps); for (int i = 0; i < numSubMaps; ++i) { exportMaterialMap(stdMat, i, level); } } else { Indent(level); fprintf(mStream, _T("type 'Unknown'\n")); } } Indent(--level); fprintf(mStream, _T("}\n")); } void HSFExp::exportMaterialMap(StdMat* mat, unsigned tmapId, int level) { assert (mat); Texmap* tmap = mat->GetSubTexmap(tmapId); if (!tmap || !mat->SubTexmapOn(tmapId)) { Indent(level); fprintf(mStream, _T("null\n")); return; } Indent(level++); fprintf(mStream, _T("{\n")); Class_ID clsId = tmap->ClassID(); Indent(level); char* mapName = escapeName(tmap->GetName()); fprintf(mStream, _T("name '%s'\n"), mapName); fflush(mStream); delete[] mapName; // TODO: time float amount = mat->GetTexmapAmt(tmapId, 0); Indent(level); fprintf(mStream, _T("amount %f\n"), amount); CStr texDir = mExportName + _T("-tex"); TSTR newFilePath = mExportDir + _T("\\") + texDir + _T("\\"); TSTR hsfFilePath = texDir + _T("/"); IPathConfigMgr::GetPathConfigMgr() ->CreateDirectoryHierarchy(mExportDir + _T("\\") + texDir); if (Class_ID(BMTEX_CLASS_ID, 0) == clsId) { Indent(level); fprintf(mStream, _T("type 'bitmap'\n")); BitmapTex *bmt = (BitmapTex*)tmap; TSTR oldFilePath = bmt->GetMapName(); TSTR escapedFilePath; escapedFilePath.append(oldFilePath); { char* fname = escapedFilePath; for (char* ch = fname; ch && *ch; ++ch) { if ('\\' == *ch || '/' == *ch || ':' == *ch) { *ch = '-'; } } } newFilePath += escapedFilePath; hsfFilePath += escapedFilePath; CopyFile(oldFilePath, newFilePath, FALSE); char* fname = escapeName(hsfFilePath); Indent(level); fprintf(mStream, _T("file '%s'\n"), fname); delete[] fname; } else { Indent(level); if (Class_ID(MIRROR_CLASS_ID, 0) == clsId) { fprintf(mStream, _T("type 'flatMirror'\n")); } else if (Class_ID(ACUBIC_CLASS_ID, 0) == clsId) { fprintf(mStream, _T("type 'reflection'\n")); } else if (Class_ID(MIRROR_CLASS_ID, 0) == clsId) { fprintf(mStream, _T("type 'flatMirror'\n")); } else { fprintf(mStream, _T("type 'bitmap'\n")); } Bitmap* bm; BitmapInfo bi; bi.SetType(BMM_TRUE_32); bi.SetWidth(512); bi.SetHeight(512); bi.SetFlags(MAP_HAS_ALPHA); bi.SetCustomFlag(0); bm = TheManager->Create(&bi); assert (bm); tmap->RenderBitmap(mStart, bm, 1.0f, TRUE); newFilePath += tmap->GetName() + _T(".png"); hsfFilePath += tmap->GetName() + _T(".png"); bi.SetPath(MaxSDK::Util::Path(newFilePath)); bm->OpenOutput(&bi); bm->Write(&bi); bm->Close(&bi); char* fname = escapeName(hsfFilePath); Indent(level); fprintf(mStream, _T("file '%s'\n"), fname); delete[] fname; bm->DeleteThis(); } UVGen *uvGen = tmap->GetTheUVGen(); if (uvGen && uvGen->IsStdUVGen()) { StdUVGen* uv = (StdUVGen*)uvGen; assert (uv); float utile = uv->GetUScl(mStart); float vtile = uv->GetVScl(mStart); float uoff = uv->GetUOffs(mStart); float voff = uv->GetVOffs(mStart); if (utile != 1.0f || vtile != 1.0f) { Indent(level); fprintf(mStream, _T("uvTile %f %f\n"), utile, vtile); } if (uoff != 0.0f || voff != 0.0f) { Indent(level); fprintf(mStream, _T("uvOffset %f %f\n"), uoff, voff); } } Indent(--level); fprintf(mStream, _T("}\n")); fflush(mStream); }
[ [ [ 1, 333 ] ] ]
7ae9d68a00006a8e11e7cc3ba5390f97db38c797
7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b
/content_exporters/texture/default_texture_exporters/include/texturebmpexporter.h
ed0cc9574b8edb03f32baaf1543b39acde304ba7
[]
no_license
wangscript/maelstrom-editor
c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31
5bfab31bf444f44b9f8209f4deaed8715c305426
refs/heads/master
2021-01-10T01:37:00.619456
2011-11-21T23:17:08
2011-11-21T23:17:08
50,160,495
0
0
null
null
null
null
UTF-8
C++
false
false
2,401
h
#ifndef TEXTUREBMPEXPORTER_H #define TEXTUREBMPEXPORTER_H #if defined(__linux) #include <stdint.h> typedef unsigned char U8; typedef unsigned short U16; typedef unsigned int U32; typedef signed int I32; #define PACKED(definition) \ definition __attribute__((packed)); #endif #if defined(WIN32) typedef unsigned __int8 U8; typedef unsigned __int16 U16; typedef unsigned __int32 U32; typedef __int32 I32; #define PACKED(definition) \ __pragma(pack(push, 1)) \ definition; \ __pragma(pack(pop)) #endif #include <fstream> #include <../../../../vacp/plugin_header/vacp_plugin_common.h> PACKED( struct BITMAP_FILEHEADER { U16 bfType; U32 bfSize; U16 bfReserved1; U16 bfReserved2; U32 bfOffBits; }) PACKED( struct BITMAP_INFOHEADER{ U32 biSize; I32 biWidth; I32 biHeight; U16 biPlanes; U16 biBitCount; U32 biCompression; U32 biSizeImage; I32 biXPelsPerMeter; I32 biYPelsPerMeter; U32 biClrUsed; U32 biClrImportant; }) PACKED( struct BITMAP_V3HEADER { U32 bV4Size; I32 bV4Width; I32 bV4Height; U16 bV4Planes; U16 bV4BitCount; U32 bV4V4Compression; U32 bV4SizeImage; I32 bV4XPelsPerMeter; I32 bV4YPelsPerMeter; U32 bV4ClrUsed; U32 bV4ClrImportant; U32 bV4RedMask; U32 bV4GreenMask; U32 bV4BlueMask; U32 bV4AlphaMask; }) enum BITMAP_COMPRESSION { CMP_RGB, CMP_RLE8, CMP_RLE4, CMP_BITFIELDS, CMP_JPEG, CMP_PNG }; class BmpExporter : public ContentExporter { private: char *last_error; int parse_dib_bitmapinfoheader(std::ifstream &input, BITMAP_INFOHEADER &header); void flip_scanlines(char *data, U32 size, U32 stride); void transform_1BPP(char *data, U32 stride, U32 stride_padding, U32 scanlines, char **transformed_data, U32 *transformed_length); void transform_24BPP(char *data, U32 stride, U32 stride_padding, U32 scanlines, char **transformed_data, U32 *transformed_length); public: BmpExporter(void); virtual IContent *process(char *path); virtual void destroy(IContent *data); }; #endif
[ [ [ 1, 99 ] ] ]
639fb5c1eaf68d64596f3e17c147613d4695d9d6
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/gerbview/options.cpp
08b2c6985ee7cb0663603e3f33efe4b98cf52c89
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,269
cpp
/********************************************/ /* GERBVIEW - Gestion des Options et Reglages */ /********************************************/ /* Fichier options.cpp */ /* Affichage et modifications des parametres de travail de PcbNew Parametres = dimensions des via, pistes, isolements, options... */ #include "fctsys.h" #include "common.h" #include "gerbview.h" #include "pcbplot.h" #include "id.h" #include "protos.h" #include <wx/spinctrl.h> /* Fonctions locales */ /* variables locales */ /*****************************************************************/ void WinEDA_GerberFrame::OnSelectOptionToolbar(wxCommandEvent& event) /*****************************************************************/ { int id = event.GetId(); wxClientDC dc(DrawPanel); DrawPanel->PrepareGraphicContext(&dc); switch ( id ) { case ID_TB_OPTIONS_SHOW_GRID: m_Draw_Grid = g_ShowGrid = m_OptionsToolBar->GetToolState(id); DrawPanel->ReDraw(&dc, TRUE); break; case ID_TB_OPTIONS_SELECT_UNIT_MM: UnitMetric = MILLIMETRE; Affiche_Status_Box(); /* Reaffichage des coord curseur */ break; case ID_TB_OPTIONS_SELECT_UNIT_INCH: UnitMetric = INCHES; Affiche_Status_Box(); /* Reaffichage des coord curseur */ break; case ID_TB_OPTIONS_SHOW_POLAR_COORD: Affiche_Message(wxEmptyString); DisplayOpt.DisplayPolarCood = m_OptionsToolBar->GetToolState(id); Affiche_Status_Box(); /* Reaffichage des coord curseur */ break; case ID_TB_OPTIONS_SELECT_CURSOR: GetScreen()->Trace_Curseur(DrawPanel, &dc); g_CursorShape = m_OptionsToolBar->GetToolState(id); GetScreen()->Trace_Curseur(DrawPanel, &dc); break; case ID_TB_OPTIONS_SHOW_PADS_SKETCH: if ( m_OptionsToolBar->GetToolState(id) ) { m_DisplayPadFill = FALSE; DisplayOpt.DisplayPadFill = FALSE; } else { m_DisplayPadFill = TRUE; DisplayOpt.DisplayPadFill = TRUE; } DrawPanel->ReDraw(&dc, TRUE); break; case ID_TB_OPTIONS_SHOW_TRACKS_SKETCH: if( m_OptionsToolBar->GetToolState(id) ) { m_DisplayPcbTrackFill = FALSE; DisplayOpt.DisplayPcbTrackFill = FALSE; } else { m_DisplayPcbTrackFill = TRUE; DisplayOpt.DisplayPcbTrackFill = TRUE; } DrawPanel->ReDraw(&dc, TRUE); break; case ID_TB_OPTIONS_SHOW_DCODES: DisplayOpt.DisplayPadNum = m_OptionsToolBar->GetToolState(id); DrawPanel->ReDraw(&dc, TRUE); break; default: DisplayError(this, wxT("WinEDA_PcbFrame::OnSelectOptionToolbar error")); break; } SetToolbars(); } enum id_optpcb { ID_ACCEPT_OPT = 1000, ID_CANCEL_OPT }; /*************************************************/ /* classe derivee pour la frame de Configuration */ /*************************************************/ class WinEDA_GerberGeneralOptionsFrame: public wxDialog { private: WinEDA_BasePcbFrame * m_Parent; wxRadioBox * m_PolarDisplay; wxRadioBox * m_BoxUnits; wxRadioBox * m_CursorShape; wxRadioBox * m_GerberDefaultScale; // Constructor and destructor public: WinEDA_GerberGeneralOptionsFrame(WinEDA_BasePcbFrame *parent,const wxPoint& pos); ~WinEDA_GerberGeneralOptionsFrame(void) {}; private: void AcceptPcbOptions(wxCommandEvent& event); void OnQuit(wxCommandEvent & event); DECLARE_EVENT_TABLE() }; /* Construction de la table des evenements pour WinEDA_GerberGeneralOptionsFrame */ BEGIN_EVENT_TABLE(WinEDA_GerberGeneralOptionsFrame, wxDialog) EVT_BUTTON(ID_ACCEPT_OPT, WinEDA_GerberGeneralOptionsFrame::AcceptPcbOptions) EVT_BUTTON(ID_CANCEL_OPT, WinEDA_GerberGeneralOptionsFrame::OnQuit) END_EVENT_TABLE() /*************************************************/ /* Constructeur de WinEDA_GerberGeneralOptionsFrame */ /************************************************/ WinEDA_GerberGeneralOptionsFrame::WinEDA_GerberGeneralOptionsFrame(WinEDA_BasePcbFrame *parent, const wxPoint& framepos): wxDialog(parent, -1, _("Gerbview Options"), framepos, wxSize(300, 240), wxDEFAULT_DIALOG_STYLE|wxFRAME_FLOAT_ON_PARENT ) { wxPoint pos; int w, h; m_Parent = parent; SetFont(*g_DialogFont); pos.x = 70; pos.y = 180; wxButton * Button = new wxButton(this, ID_ACCEPT_OPT, _("Accept"), pos); pos.x += Button->GetSize().x + 5; Button->SetForegroundColour(*wxRED); Button = new wxButton(this, ID_CANCEL_OPT, _("Cancel"), pos); Button->SetForegroundColour(*wxBLUE); /* Display Selection affichage des coordonnées polaires */ pos.x = 10; pos.y = 10; wxString list_coord[2] = { _("No Display"), _("Display") }; m_PolarDisplay = new wxRadioBox(this, -1, _("Display Polar Coord"), pos, wxDefaultSize, 2, list_coord, 1); m_PolarDisplay->SetSelection(DisplayOpt.DisplayPolarCood ? 1 : 0); /* Selection choix des unités d'affichage */ m_PolarDisplay->GetSize(&w, &h); pos.y += h + 15; wxString list_units[2] = { _("Inches"), _("millimeters") }; m_BoxUnits = new wxRadioBox(this, -1, _("Units"), pos, wxDefaultSize, 2, list_units, 1); m_BoxUnits->SetSelection( UnitMetric ? 1 : 0); /* Selection forme du curseur */ pos.x += 155; pos.y = 10; wxString list_cursors[2] = { _("Small"), _("Big") }; m_CursorShape = new wxRadioBox(this, -1, _("Cursor"), pos, wxDefaultSize, 2, list_cursors, 1); m_CursorShape->SetSelection( g_CursorShape ? 1 : 0); /* Selection Default Scale (i.e. format 2.3 ou 3.4) */ m_CursorShape->GetSize(&w, &h); pos.y += h + 15; wxString list_scales[2] = { _("format: 2.3"), _("format 3.4") }; m_GerberDefaultScale = new wxRadioBox(this, -1, _("Default format"), pos, wxDefaultSize, 2, list_scales, 1); m_GerberDefaultScale->SetSelection( (g_Default_GERBER_Format == 23) ? 0 : 1); } /************************************************************************/ void WinEDA_GerberGeneralOptionsFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) /************************************************************************/ { // true is to force the frame to close Close(true); } /*****************************************************************************/ void WinEDA_GerberGeneralOptionsFrame::AcceptPcbOptions(wxCommandEvent& event) /*****************************************************************************/ { DisplayOpt.DisplayPolarCood = (m_PolarDisplay->GetSelection() == 0) ? FALSE : TRUE; UnitMetric = (m_BoxUnits->GetSelection() == 0) ? 0 : 1; g_CursorShape = m_CursorShape->GetSelection(); g_Default_GERBER_Format = (m_GerberDefaultScale->GetSelection() == 0) ? 23 : 34; EndModal(1); } /******************************************************************/ /* classe derivee pour la frame de Configuration WinEDA_LookFrame */ /******************************************************************/ class WinEDA_LookFrame: public wxDialog { private: protected: public: WinEDA_BasePcbFrame * m_Parent; wxRadioBox * m_OptDisplayLines; wxRadioBox * m_OptDisplayFlashes; wxCheckBox * m_OptDisplayDCodes; wxRadioBox * m_OptDisplayDrawings; // Constructor and destructor WinEDA_LookFrame(WinEDA_BasePcbFrame *parent,const wxPoint& pos); ~WinEDA_LookFrame(void) {}; void AcceptPcbOptions(wxCommandEvent& event); void OnQuit(wxCommandEvent & event); DECLARE_EVENT_TABLE() }; /* Construction de la table des evenements pour WinEDA_LookFrame */ BEGIN_EVENT_TABLE(WinEDA_LookFrame, wxDialog) EVT_BUTTON(ID_ACCEPT_OPT, WinEDA_LookFrame::AcceptPcbOptions) EVT_BUTTON(ID_CANCEL_OPT, WinEDA_LookFrame::OnQuit) END_EVENT_TABLE() /*******************************************************************************/ WinEDA_LookFrame::WinEDA_LookFrame(WinEDA_BasePcbFrame *parent, const wxPoint& framepos): wxDialog(parent, -1, _("Gerbview Draw Options"), framepos, wxSize(350, 200), wxDEFAULT_DIALOG_STYLE|wxFRAME_FLOAT_ON_PARENT ) /*******************************************************************************/ { wxPoint pos; int ii, jj; m_Parent = parent; SetFont(*g_DialogFont); pos.x = 160; pos.y = 140; wxButton * Button = new wxButton(this, ID_ACCEPT_OPT, _("Accept"), pos); Button->SetForegroundColour(*wxRED); pos.x += Button->GetSize().x + 5; Button = new wxButton(this, ID_CANCEL_OPT, _("Cancel"), pos); Button->SetForegroundColour(*wxBLUE); pos.x = 5; pos.y = 5; // Show Option Draw Tracks wxString list_opt2[2] = { _("Sketch"), _("Filled") }; m_OptDisplayLines = new wxRadioBox(this, -1, _("Lines:"), pos, wxDefaultSize, 2, list_opt2, 1); if ( DisplayOpt.DisplayPcbTrackFill ) m_OptDisplayLines->SetSelection(1); m_OptDisplayLines->GetSize(&ii, &jj); pos.y += jj + 15; m_OptDisplayDCodes = new wxCheckBox(this, -1, _("Show D-Codes"), pos); if ( DisplayOpt.DisplayPadNum ) m_OptDisplayDCodes->SetValue(TRUE); pos.x += 100; pos.y = 5; m_OptDisplayFlashes = new wxRadioBox(this, -1, _("Spots:"), pos, wxDefaultSize, 2, list_opt2, 1); if ( DisplayOpt.DisplayPadFill ) m_OptDisplayFlashes->SetSelection(1); pos.x += 100; pos.y = 5; wxString list_opt3[3] = { _("Sketch"), _("Filled"), _("Line") }; m_OptDisplayDrawings = new wxRadioBox(this, -1, _("Display other items:"), pos, wxDefaultSize, 3, list_opt3, 1); m_OptDisplayDrawings->SetSelection(DisplayOpt.DisplayDrawItems); } /**************************************************************/ void WinEDA_LookFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) /**************************************************************/ { // true is to force the frame to close Close(true); } /*************************************************************/ void WinEDA_LookFrame::AcceptPcbOptions(wxCommandEvent& event) /*************************************************************/ /* Met a jour les options */ { if ( m_OptDisplayLines->GetSelection() == 1) DisplayOpt.DisplayPcbTrackFill = TRUE; else DisplayOpt.DisplayPcbTrackFill = FALSE; if (m_OptDisplayFlashes->GetSelection() == 1 ) DisplayOpt.DisplayPadFill = TRUE; else DisplayOpt.DisplayPadFill = FALSE; DisplayOpt.DisplayPadNum = m_OptDisplayDCodes->GetValue(); DisplayOpt.DisplayDrawItems = m_OptDisplayDrawings->GetSelection(); m_Parent->m_DisplayPadFill = DisplayOpt.DisplayPadFill; m_Parent->m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill; m_Parent->GetScreen()->SetRefreshReq(); EndModal(1); } /*****************************************************************/ /* void WinEDA_GerberFrame::InstallConfigFrame(const wxPoint & pos) */ /*****************************************************************/ void WinEDA_GerberFrame::InstallPcbOptionsFrame(const wxPoint & pos, int id) { switch ( id ) { case ID_PCB_LOOK_SETUP: { WinEDA_LookFrame * OptionsFrame = new WinEDA_LookFrame(this, pos); OptionsFrame->ShowModal(); OptionsFrame->Destroy(); } break; case ID_OPTIONS_SETUP: { WinEDA_GerberGeneralOptionsFrame * OptionsFrame = new WinEDA_GerberGeneralOptionsFrame(this, pos); OptionsFrame->ShowModal(); OptionsFrame->Destroy(); } break; } }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 385 ] ] ]
0a454d884a58fe58e2abc230eb9525e7f8846154
cf674554f7af10e2e194b5a2e17bfe687259fa4e
/SongToast/YahooUtil.cpp
cc39e87357612538e89ab2a43dacfedcf55e0d0e
[]
no_license
instcode/songtoast
bc614bee6d4bb1f9026e5b2b460ae64a76d9a916
4315b9675ea187b5b6b9f11d2b60f5dacf9a502f
refs/heads/master
2021-01-10T20:31:44.710421
2007-12-19T04:27:53
2007-12-19T04:27:53
32,088,174
0
0
null
null
null
null
UTF-8
C++
false
false
1,573
cpp
/* SongToast Winamp Plugin Copyright (C) 2005 Khoa Nguyen <instcode (at) gmail.com> */ #include "stdafx.h" #include "YahooUtil.h" void SetCustomStatusMessage(LPTSTR szProfile, LPCTSTR szMessage) { HKEY hRootKey; TCHAR lpszKeyPath[256]; wsprintf(lpszKeyPath, L"Software\\yahoo\\pager\\profiles\\%s\\Custom Msgs\\", szProfile); RegOpenKeyEx(HKEY_CURRENT_USER, lpszKeyPath, 0, KEY_READ | KEY_SET_VALUE, &hRootKey); if (hRootKey != NULL) { // YM 8.1.0.xxx(-) RegSetValueEx(hRootKey, L"1", 0, REG_SZ, (LPBYTE) szMessage, (DWORD)(_tcslen(szMessage) * sizeof(TCHAR)) + 1); // YM 9.0.0.xxx(+) RegSetValueEx(hRootKey, L"1_W", 0, REG_SZ, (LPBYTE) szMessage, (DWORD)(_tcslen(szMessage) * sizeof(TCHAR)) + 1); // Update the combo box.. HWND hWnd = ::FindWindow(L"YahooBuddyMain", NULL); if (hWnd != NULL) { /*************************************** Known WM_COMMAND, WPARAM (MS.Spy++, http://yayak.wordpress.com/2007/05/27/yahoo-messenger-idle-status-by-delphi/) 376 : Available[N] --- 377 : Be Right Back[B] 378 : Busy[B] 379 : Not at Home[B] - Hidden 380 : Not at My Desk[B] 381 : Not in the Office[B] - Hidden 382 : On the Phone[B] 383 : On Vacation[B] - Hidden 384 : Out To Lunch[B] - Hidden 385 : Stepped Out[B] --- 388 : custom_mesg_1 389 : custom_mesg_2 390 : custom_mesg_3 391 : custom_mesg_4 392 : custom_mesg_5 ****************************************/ ::SendMessage(hWnd, WM_COMMAND, 388, 0); } RegCloseKey(hRootKey); } }
[ "instcode@3660ff36-4840-0410-ab72-675ca585a781" ]
[ [ [ 1, 46 ] ] ]
6584fa6c13703dd1e0d6a2c4a3df92438eaa36c5
499e2aa4f031c91b5aa0e4200fec70b1ef4e0ea5
/glm/glm/core/type_mat2x4.hpp
29c71be11b015586a9ad4e4c9d59bfc79f2e322d
[ "MIT" ]
permissive
stine/GL4Demo
c41783bfc6d5a7c7723c63c82a8b9fbef9b4962a
7e42836d7d878e7d523ac6ce0306c63f19f43823
refs/heads/master
2021-01-25T05:28:06.018739
2011-05-06T05:41:17
2011-05-06T05:41:17
1,694,939
0
0
null
null
null
null
UTF-8
C++
false
false
6,349
hpp
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2010 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-08-05 // Updated : 2010-02-11 // Licence : This source is under MIT License // File : glm/core/type_mat2x4.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_core_type_mat2x4 #define glm_core_type_mat2x4 #include "type_mat.hpp" namespace glm { namespace test { void main_mat2x4(); }//namespace test namespace detail { template <typename T> struct tvec1; template <typename T> struct tvec2; template <typename T> struct tvec3; template <typename T> struct tvec4; template <typename T> struct tmat2x2; template <typename T> struct tmat2x3; template <typename T> struct tmat2x4; template <typename T> struct tmat3x2; template <typename T> struct tmat3x3; template <typename T> struct tmat3x4; template <typename T> struct tmat4x2; template <typename T> struct tmat4x3; template <typename T> struct tmat4x4; //!< \brief Template for 2 * 4 matrix of floating-point numbers. template <typename T> struct tmat2x4 { enum ctor{null}; typedef T value_type; typedef std::size_t size_type; typedef tvec4<T> col_type; typedef tvec2<T> row_type; static size_type col_size(); static size_type row_size(); typedef tmat2x4<T> type; typedef tmat4x2<T> transpose_type; private: // Data col_type value[2]; public: // Constructors tmat2x4(); tmat2x4(tmat2x4 const & m); explicit tmat2x4( ctor); explicit tmat2x4( value_type const & s); explicit tmat2x4( value_type const & x0, value_type const & y0, value_type const & z0, value_type const & w0, value_type const & x1, value_type const & y1, value_type const & z1, value_type const & w1); explicit tmat2x4( col_type const & v0, col_type const & v1); // Conversion template <typename U> explicit tmat2x4(tmat2x4<U> const & m); explicit tmat2x4(tmat2x2<T> const & x); explicit tmat2x4(tmat3x3<T> const & x); explicit tmat2x4(tmat4x4<T> const & x); explicit tmat2x4(tmat2x3<T> const & x); explicit tmat2x4(tmat3x2<T> const & x); explicit tmat2x4(tmat3x4<T> const & x); explicit tmat2x4(tmat4x2<T> const & x); explicit tmat2x4(tmat4x3<T> const & x); // Accesses col_type & operator[](size_type i); col_type const & operator[](size_type i) const; // Unary updatable operators tmat2x4<T>& operator= (tmat2x4<T> const & m); template <typename U> tmat2x4<T>& operator= (tmat2x4<U> const & m); template <typename U> tmat2x4<T>& operator+= (U const & s); template <typename U> tmat2x4<T>& operator+= (tmat2x4<U> const & m); template <typename U> tmat2x4<T>& operator-= (U const & s); template <typename U> tmat2x4<T>& operator-= (tmat2x4<U> const & m); template <typename U> tmat2x4<T>& operator*= (U const & s); template <typename U> tmat2x4<T>& operator*= (tmat2x4<U> const & m); template <typename U> tmat2x4<T>& operator/= (U const & s); tmat2x4<T>& operator++ (); tmat2x4<T>& operator-- (); }; // Binary operators template <typename T> tmat2x4<T> operator+ ( tmat2x4<T> const & m, typename tmat2x4<T>::value_type const & s); template <typename T> tmat2x4<T> operator+ ( tmat2x4<T> const & m1, tmat2x4<T> const & m2); template <typename T> tmat2x4<T> operator- ( tmat2x4<T> const & m, typename tmat2x4<T>::value_type const & s); template <typename T> tmat2x4<T> operator- ( tmat2x4<T> const & m1, tmat2x4<T> const & m2); template <typename T> tmat2x4<T> operator* ( tmat2x4<T> const & m, typename tmat2x4<T>::value_type const & s); template <typename T> tmat2x4<T> operator* ( typename tmat2x4<T>::value_type const & s, tmat2x4<T> const & m); template <typename T> typename tmat2x4<T>::row_type operator* ( tmat2x4<T> const & m, typename tmat2x4<T>::col_type const & v); template <typename T> typename tmat2x4<T>::col_type operator* ( typename tmat2x4<T>::row_type const & v, tmat2x4<T> const & m); template <typename T> tmat2x4<T> operator* ( tmat2x4<T> const & m1, tmat2x4<T> const & m2); template <typename T> tmat2x4<T> operator/ ( tmat2x4<T> const & m, typename tmat2x4<T>::value_type const & s); template <typename T> tmat2x4<T> operator/ ( typename tmat2x4<T>::value_type const & s, tmat2x4<T> const & m); // Unary constant operators template <typename T> tmat2x4<T> const operator- ( tmat2x4<T> const & m); template <typename T> tmat2x4<T> const operator-- ( tmat2x4<T> const & m, int); template <typename T> tmat2x4<T> const operator++ ( tmat2x4<T> const & m, int); } //namespace detail namespace core{ namespace type{ namespace precision { //! 2 columns of 4 components matrix of low precision floating-point numbers. //! There is no garanty on the actual precision. //! (From GLSL 1.30.8 specification, section 4.1.6 Matrices and section 4.5 Precision and Precision Qualifiers) typedef detail::tmat2x4<lowp_float> lowp_mat2x4; //! 2 columns of 4 components matrix of medium precision floating-point numbers. //! There is no garanty on the actual precision. //! (From GLSL 1.30.8 specification, section 4.1.6 Matrices and section 4.5 Precision and Precision Qualifiers) typedef detail::tmat2x4<mediump_float> mediump_mat2x4; //! 2 columns of 4 components matrix of high precision floating-point numbers. //! There is no garanty on the actual precision. //! (From GLSL 1.30.8 specification, section 4.1.6 Matrices and section 4.5 Precision and Precision Qualifiers) typedef detail::tmat2x4<highp_float> highp_mat2x4; } //namespace precision }//namespace type }//namespace core } //namespace glm #include "type_mat2x4.inl" #endif //glm_core_type_mat2x4
[ [ [ 1, 212 ] ] ]
6d3c8259e96990a67e621c140ff07207ad9ede27
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/include/OEBase/IOEXmlMgr.h
54ba7f3a79514d0216372efc73e0a4ff943d8ddb
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
724
h
/*! * \file IOEXmlMgr.h * \date 24-7-2009 15:27:38 * * * \author zjhlogo ([email protected]) */ #ifndef __IOEXMLMGR_H__ #define __IOEXMLMGR_H__ #include "../OECore/IOEMgr.h" #include "IOEXmlDocument.h" #include "IOEXmlNode.h" #include "IOEXmlAttribute.h" class IOEXmlMgr : public IOEMgr { public: RTTI_DEF(IOEXmlMgr, IOEMgr); IOEXmlMgr() {}; virtual ~IOEXmlMgr() {}; virtual IOEXmlDocument* CreateDocument() = 0; virtual IOEXmlDocument* CreateDocument(const tstring& strFile) = 0; virtual IOEXmlNode* CreateNode(const tstring& strName) = 0; virtual IOEXmlAttribute* CreateAttribute(const tstring& strName) = 0; }; extern IOEXmlMgr* g_pOEXmlMgr; #endif // __IOEXMLMGR_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 33 ] ] ]
831586dd8bf74fb54b767e6dd631e8278d81b945
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
/mytesgnikrow --username hotga2801/Project/FaceDetect_V1.3/Learn.cpp
53d503e4abbacfa9f43284d24b97d35da14b89c7
[]
no_license
taicent/mytesgnikrow
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
9264faa662454484ade7137ee8a0794e00bf762f
refs/heads/master
2020-04-06T04:25:30.075548
2011-02-17T13:37:16
2011-02-17T13:37:16
34,991,750
0
0
null
null
null
null
UTF-8
C++
false
false
7,576
cpp
#include "stdafx.h" #include <vector> #include <algorithm> #include <functional> #include <fstream> #include <math.h> #include <mmsystem.h> using namespace std; #include "resource.h" #include "IntImage.h" #include "SimpleClassifier.h" #include "AdaBoostClassifier.h" #include "CascadeClassifier.h" #include "Global.h" #include "FFS.h" #include "learn.h" #include "OptionDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void InitTrain() { int i; OptionDialog dlg; dlg.m_size = starting_node; dlg.m_fs = train_method; dlg.m_lc = linear_classifier; dlg.m_ratio = asym_ratio; if(dlg.DoModal()!=IDOK) { AfxMessageBox("Training cancelled."); return; } else { train_method = dlg.m_fs; linear_classifier = dlg.m_lc; asym_ratio = REAL(dlg.m_ratio); } i = starting_node; if(i!=1 && i<=max_nodes) { ofstream f; if(!BoostingInputFiles(true)) { AfxMessageBox("All bootstrapping file used! Training finished! (finally...)"); return; } f.open(FileUsage_log_filename); for(int j=0;j<max_files;j++) f<<fileused[j]<<" "; f.close(); } AfxGetApp()->BeginWaitCursor(); WriteRangeFile(); while(i<=max_nodes) { bool result; result = cascade->OneRound(i); if(result==false) { AfxGetApp()->EndWaitCursor(); AfxMessageBox("All bootstrapping file used! Training finished! (finally...)"); return; } i++; } AfxGetApp()->EndWaitCursor(); } const bool BoostingInputFiles(const bool discard) { int i,pointer,index; IntImage im; ofstream of; im.SetSize(CSize(sx+1,sy+1)); cascade->LoadDefaultCascade(); pointer=facecount; for(i=facecount;i<totalcount;i++) { if(discard) break; if(cascade->ApplyImagePatch(trainset[i])!=0) { if(pointer!=i) SwapIntImage(trainset[i],trainset[pointer]); pointer++; if(pointer==totalcount) break; } } if(pointer==totalcount) return true; index = 0; while(pointer<totalcount) { if(index==bootstrap_size) { if(bootstrap_level==max_bootstrap_level-1) return false; else { bootstrap_level++; for(i=0;i<max_files;i++) fileused[i] = 0; index=0; pointer=facecount; } } if(fileused[index]==1) { index++; continue; } cascade->ApplyOriginalSizeForInputBoosting(bootstrap_filenames[index],pointer); fileused[index]=1; index++; } for(i=0;i<totalcount;i++) { int k,t; memcpy(im.buf,trainset[i].buf,(sx+1)*(sy+1)*sizeof(im.buf[0])); for(k=0;k<=sy;k++) trainset[i].data[0][k] = 0; for(k=0;k<=sx;k++) trainset[i].data[k][0] = 0; for(k=1;k<=sx;k++) for(t=1;t<=sy;t++) trainset[i].data[k][t] = im.data[k][t]-im.data[k-1][t]-im.data[k][t-1]+im.data[k-1][t-1]; } of.open(trainset_filename,ios_base::out | ios_base::binary); of<<totalcount<<endl; unsigned char* writebuf; writebuf = new unsigned char[sx*sy]; ASSERT(writebuf!=NULL); for(i=0;i<totalcount;i++) { of<<trainset[i].label<<endl; of<<sx<<" "<<sy<<endl; for(int k=0;k<sx;k++) for(int t=0;t<sy;t++) writebuf[k*sy+t] = (unsigned char)((int)trainset[i].data[k+1][t+1]); of.write((char*)writebuf,sx*sy); of<<endl; } delete[] writebuf; writebuf=NULL; of.close(); for(i=0;i<totalcount;i++) trainset[i].CalculateVarianceAndIntegralImageInPlace(); for(i=facecount;i<totalcount;i++) { if(cascade->ApplyImagePatch(trainset[i])==0) ; //AfxMessageBox("Something is wrong?"); } return true; } void BackupIntermediateFile(const CString filename, const int round) { CString savename; CString name,ext; int pos; bool backup = false; if(backup==false) return; pos = filename.ReverseFind('\\'); if(pos>0) savename = filename.Right(filename.GetLength()-pos-1); else savename = filename; pos = savename.ReverseFind('.'); name = savename.Left(pos); ext = savename.Right(savename.GetLength()-pos); savename.Format("%d",round); savename = Backup_directory_name + name + savename + ext; CopyFile(filename,savename,FALSE); } const bool CascadeClassifier::OneRound(const int round) { ofstream f; bool result; int i; AdaBoostClassifier ada; CWnd* pwnd; CString str; pwnd = AfxGetMainWnd(); BackupIntermediateFile(trainset_filename,round); str.Format("Training node: %d",round); pwnd->SetWindowText(str); ada.TrainLDS(nof[round-1],true,goal_method); if(train_method==TRAIN_ADA) BackupIntermediateFile(ada_log_filename,round); else BackupIntermediateFile(FFS_log_filename,round); BackupIntermediateFile(cascade_filename,round); str.Format("Training node %d finished. Bootstrapping non-face data for next node.",round); pwnd->SetWindowText(str); result = BoostingInputFiles(false); f.open(FileUsage_log_filename); for(i=0;i<max_files;i++) f<<fileused[i]<<" "; f.close(); BackupIntermediateFile(FileUsage_log_filename,round); return result; } void WriteSimpleClassifiers(void) { int x1,x2,x3,x4,y1,y2,y3,y4; SimpleClassifier sc; int index; ofstream f; int pickup=9; f.open("classifiers.txt"); index = 0; for(x1=0;x1<sx;x1+=1) for(x3=x1+2;x3<=sx;x3+=2) for(y1=0;y1<sy;y1+=1) for(y3=y1+1;y3<=sy;y3+=1) { x2 = (x1+x3)/2; y2 = y4 = x4 = -1; sc.type = 0; sc.error = 0.0; sc.x1 = x1; sc.x2 = x2; sc.x3 = x3; sc.x4 = x4; sc.y1 = y1; sc.y2 = y2; sc.y3 = y3; sc.y4 = y4; sc.parity = 0; sc.thresh = 0.0; if(index%10==pickup) sc.WriteToFile(f); index++; } for(x1=0;x1<sx;x1+=1) for(x3=x1+1;x3<=sx;x3+=1) for(y1=0;y1<sy;y1+=1) for(y3=y1+2;y3<=sy;y3+=2) { y2 = (y1+y3)/2; x2 = x4 = y4 = -1; sc.type = 1; sc.error = 0.0; sc.x1 = x1; sc.x2 = x2; sc.x3 = x3; sc.x4 = x4; sc.y1 = y1; sc.y2 = y2; sc.y3 = y3; sc.y4 = y4; sc.parity = 0; sc.thresh = 0.0; if(index%10==pickup) sc.WriteToFile(f); index++; } for(x1=0;x1<sx;x1++) for(x4=x1+3;x4<=sx;x4+=3) for(y1=0;y1<sy;y1+=1) for(y3=y1+1;y3<=sy;y3+=1) { x2 = x1 + (x4-x1)/3; x3 = x2 + (x4-x1)/3; y2 = y4 = -1; sc.type = 2; sc.error = 0.0; sc.x1 = x1; sc.x2 = x2; sc.x3 = x3; sc.x4 = x4; sc.y1 = y1; sc.y2 = y2; sc.y3 = y3; sc.y4 = y4; sc.parity = 0; sc.thresh = 0.0; if(index%10==pickup) sc.WriteToFile(f); index++; } for(x1=0;x1<sx;x1++) for(x3=x1+1;x3<=sx;x3+=1) for(y1=0;y1<sy;y1++) for(y4=y1+3;y4<=sy;y4+=3) { y2 = y1 + (y4-y1)/3; y3 = y2 + (y4-y1)/3; x2 = x4 = -1; sc.type = 3; sc.error = 0.0; sc.x1 = x1; sc.x2 = x2; sc.x3 = x3; sc.x4 = x4; sc.y1 = y1; sc.y2 = y2; sc.y3 = y3; sc.y4 = y4; sc.parity = 0; sc.thresh = 0.0; if(index%10==pickup) sc.WriteToFile(f); index++; } for(x1=0;x1<sx;x1+=1) for(x3=x1+2;x3<=sx;x3+=2) for(y1=0;y1<sy;y1+=1) for(y3=y1+2;y3<=sy;y3+=2) { x2 = (x1+x3)/2; y2 = (y1+y3)/2; x4 = y4 = -1; sc.type = 4; sc.error = 0.0; sc.x1 = x1; sc.x2 = x2; sc.x3 = x3; sc.x4 = x4; sc.y1 = y1; sc.y2 = y2; sc.y3 = y3; sc.y4 = y4; sc.parity = 0; sc.thresh = 0.0; if(index%10==pickup) sc.WriteToFile(f); index++; } f.close(); } void SubSampleClassifiers() { ofstream f; int i; f.open("classifiers.txt"); for(i=0;i<totalfeatures/10;i++) { classifiers[i*10].WriteToFile(f); } f.close(); }
[ "hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076" ]
[ [ [ 1, 334 ] ] ]
d8c80e05f7384d4e05ca63bfb5f0d0af3fb40f67
09ea547305ed8be9f8aa0dc6a9d74752d660d05d
/Tests/DemoGUI/ui_mainwindow.h
0a8e503bc3291f724d5f0e8c988404623dc3eda1
[]
no_license
SymbianSource/oss.FCL.sf.mw.socialmobilefw
3c49e1d1ae2db8703e7c6b79a4c951216c9c5019
7020b195cf8d1aad30732868c2ed177e5459b8a8
refs/heads/master
2021-01-13T13:17:24.426946
2010-10-12T09:53:52
2010-10-12T09:53:52
72,676,540
0
0
null
null
null
null
UTF-8
C++
false
false
2,531
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created: Tue Jul 27 13:53:17 2010 ** by: Qt User Interface Compiler version 4.6.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHeaderView> #include <QtGui/QMainWindow> #include <QtGui/QMenuBar> #include <QtGui/QStatusBar> #include <QtGui/QTextEdit> #include <QtGui/QToolBar> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QTextEdit *textEdit; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QString::fromUtf8("MainWindow")); MainWindow->resize(600, 400); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); textEdit = new QTextEdit(centralWidget); textEdit->setObjectName(QString::fromUtf8("textEdit")); textEdit->setGeometry(QRect(40, 50, 104, 64)); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QString::fromUtf8("menuBar")); menuBar->setGeometry(QRect(0, 0, 600, 21)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QString::fromUtf8("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QString::fromUtf8("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "none@none" ]
[ [ [ 1, 76 ] ] ]
0c00e97af7c0c2457154e393d7d2f93cfac83447
deb8ef49795452ff607023c6bce8c3e8ed4c8360
/Projects/UAlbertaBot/Source/base/WorkerData.cpp
088e1547f88416bb40a3e0554d143e6b6b890e85
[]
no_license
timburr1/ou-skynet
f36ed7996c21f788a69e3ae643b629da7d917144
299a95fae4419429be1d04286ea754459a9be2d6
refs/heads/master
2020-04-19T22:58:46.259980
2011-12-06T20:10:34
2011-12-06T20:10:34
34,360,542
0
0
null
null
null
null
UTF-8
C++
false
false
8,761
cpp
#include "Common.h" #include "WorkerData.h" WorkerData::WorkerData() {} void WorkerData::workerDestroyed(BWAPI::Unit * unit) { clearPreviousJob(unit); workers.erase(unit); } void WorkerData::addWorker(BWAPI::Unit * unit) { workers.insert(unit); workerJobMap[unit] = Default; } void WorkerData::addWorker(BWAPI::Unit * unit, WorkerJob job, BWAPI::Unit * jobUnit) { assert(workers.find(unit) == workers.end()); workers.insert(unit); setWorkerJob(unit, job, jobUnit); } void WorkerData::addWorker(BWAPI::Unit * unit, enum WorkerJob job, BWAPI::UnitType jobUnitType) { assert(workers.find(unit) == workers.end()); workers.insert(unit); setWorkerJob(unit, job, jobUnitType); } void WorkerData::addDepot(BWAPI::Unit * unit) { assert(depots.find(unit) == depots.end()); depots.insert(unit); depotWorkerCount[unit] = 0; } void WorkerData::removeDepot(BWAPI::Unit * unit) { depots.erase(unit); depotWorkerCount.erase(unit); // re-balance workers in here BOOST_FOREACH (BWAPI::Unit * worker, workers) { // if a worker was working at this depot if (workerDepotMap[worker] == unit) { setWorkerJob(worker, Idle, NULL); } } } void WorkerData::setWorkerJob(BWAPI::Unit * unit, enum WorkerJob job, BWAPI::Unit * jobUnit) { clearPreviousJob(unit); workerJobMap[unit] = job; if (job == Minerals) { // increase the number of workers assigned to this nexus depotWorkerCount[jobUnit] += 1; // set the mineral the worker is working on workerDepotMap[unit] = jobUnit; // right click the mineral to start mining unit->rightClick(getMineralToMine(unit)); } else if (job == Gas) { // increase the count of workers assigned to this refinery refineryWorkerCount[jobUnit] += 1; // set the refinery the worker is working on workerRefineryMap[unit] = jobUnit; // right click the refinery to start harvesting unit->rightClick(jobUnit); } else if (job == Repair) { // only SCVs can repair assert(unit->getType() == BWAPI::UnitTypes::Terran_SCV); // set the building the worker is to repair workerRepairMap[unit] = jobUnit; // start repairing it unit->repair(jobUnit); } else if (job == Scout) { } } void WorkerData::setWorkerJob(BWAPI::Unit * unit, enum WorkerJob job, BWAPI::UnitType jobUnitType) { clearPreviousJob(unit); workerJobMap[unit] = job; if (job == Build) { workerBuildingTypeMap[unit] = jobUnitType; } } void WorkerData::setWorkerJob(BWAPI::Unit * unit, enum WorkerJob job, WorkerMoveData wmd) { clearPreviousJob(unit); workerJobMap[unit] = job; if (job == Move) { workerMoveMap[unit] = wmd; } if (workerJobMap[unit] != Move) { BWAPI::Broodwar->printf("Something went horribly wrong"); } } void WorkerData::clearPreviousJob(BWAPI::Unit * unit) { WorkerJob previousJob = getWorkerJob(unit); if (previousJob == Minerals) { depotWorkerCount[workerDepotMap[unit]] -= 1; workerDepotMap.erase(unit); } else if (previousJob == Gas) { refineryWorkerCount[workerRefineryMap[unit]] -= 1; workerRefineryMap.erase(unit); } else if (previousJob == Build) { workerBuildingTypeMap.erase(unit); } else if (previousJob == Repair) { workerRepairMap.erase(unit); } else if (previousJob == Move) { workerMoveMap.erase(unit); } workerJobMap.erase(unit); } int WorkerData::getNumWorkers() { return workers.size(); } int WorkerData::getNumMineralWorkers() { size_t num = 0; BOOST_FOREACH (BWAPI::Unit * unit, workers) { if (workerJobMap[unit] == WorkerData::Minerals) { num++; } } return num; } int WorkerData::getNumGasWorkers() { size_t num = 0; BOOST_FOREACH (BWAPI::Unit * unit, workers) { if (workerJobMap[unit] == WorkerData::Gas) { num++; } } return num; } int WorkerData::getNumIdleWorkers() { size_t num = 0; BOOST_FOREACH (BWAPI::Unit * unit, workers) { if (workerJobMap[unit] == WorkerData::Idle) { num++; } } return num; } enum WorkerData::WorkerJob WorkerData::getWorkerJob(BWAPI::Unit * unit) { std::map<BWAPI::Unit *, enum WorkerJob>::iterator it = workerJobMap.find(unit); if (it != workerJobMap.end()) { return it->second; } return Default; } bool WorkerData::depotIsFull(BWAPI::Unit * depot) { int assignedWorkers = getNumAssignedWorkers(depot); int mineralsNearDepot = getMineralsNearDepot(depot); if (assignedWorkers >= mineralsNearDepot * 3) { return true; } else { return false; } } int WorkerData::getMineralsNearDepot(BWAPI::Unit * depot) { int mineralsNearDepot = 0; BOOST_FOREACH (BWAPI::Unit * unit, BWAPI::Broodwar->getAllUnits()) { if ((unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field) && unit->getDistance(depot) < 200) { mineralsNearDepot++; } } return mineralsNearDepot; } BWAPI::Unit * WorkerData::getWorkerResource(BWAPI::Unit * unit) { // create the iterator std::map<BWAPI::Unit *, BWAPI::Unit *>::iterator it; // if the worker is mining, set the iterator to the mineral map if (getWorkerJob(unit) == Minerals) { it = workerMineralMap.find(unit); if (it != workerMineralMap.end()) { return it->second; } } else if (getWorkerJob(unit) == Gas) { it = workerRefineryMap.find(unit); if (it != workerRefineryMap.end()) { return it->second; } } return NULL; } BWAPI::Unit * WorkerData::getMineralToMine(BWAPI::Unit * worker) { // get the depot associated with this unit BWAPI::Unit * depot = getWorkerDepot(worker); BWAPI::Unit * mineral = NULL; double closestDist = 10000; if (depot) { BOOST_FOREACH (BWAPI::Unit * unit, BWAPI::Broodwar->getAllUnits()) { if (unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field && unit->getResources() > 0) { double dist = unit->getDistance(depot); if (!mineral || dist < closestDist) { mineral = unit; closestDist = dist; } } } } return mineral; } BWAPI::Unit * WorkerData::getWorkerRepairUnit(BWAPI::Unit * unit) { std::map<BWAPI::Unit *, BWAPI::Unit *>::iterator it = workerRepairMap.find(unit); if (it != workerRepairMap.end()) { return it->second; } return NULL; } BWAPI::Unit * WorkerData::getWorkerDepot(BWAPI::Unit * unit) { std::map<BWAPI::Unit *, BWAPI::Unit *>::iterator it = workerDepotMap.find(unit); if (it != workerDepotMap.end()) { return it->second; } return NULL; } BWAPI::UnitType WorkerData::getWorkerBuildingType(BWAPI::Unit * unit) { std::map<BWAPI::Unit *, BWAPI::UnitType>::iterator it = workerBuildingTypeMap.find(unit); if (it != workerBuildingTypeMap.end()) { return it->second; } return NULL; } WorkerMoveData WorkerData::getWorkerMoveData(BWAPI::Unit * unit) { std::map<BWAPI::Unit *, WorkerMoveData>::iterator it = workerMoveMap.find(unit); assert(it != workerMoveMap.end()); return (it->second); } int WorkerData::getNumAssignedWorkers(BWAPI::Unit * unit) { std::map<BWAPI::Unit *, int>::iterator it; // if the worker is mining, set the iterator to the mineral map if (unit->getType().isResourceDepot()) { it = depotWorkerCount.find(unit); // if there is an entry, return it if (it != depotWorkerCount.end()) { return it->second; } } else if (unit->getType().isRefinery()) { it = refineryWorkerCount.find(unit); // if there is an entry, return it if (it != refineryWorkerCount.end()) { return it->second; } // otherwise, we are only calling this on completed refineries, so set it else { refineryWorkerCount[unit] = 0; } } // when all else fails, return 0 return 0; } char WorkerData::getJobCode(BWAPI::Unit * unit) { WorkerData::WorkerJob j = getWorkerJob(unit); if (j == WorkerData::Build) return 'B'; if (j == WorkerData::Combat) return 'C'; if (j == WorkerData::Default) return 'D'; if (j == WorkerData::Gas) return 'G'; if (j == WorkerData::Idle) return 'I'; if (j == WorkerData::Minerals) return 'M'; if (j == WorkerData::Repair) return 'R'; if (j == WorkerData::Move) return 'O'; if (j == WorkerData::Scout) return 'S'; return 'X'; } void WorkerData::drawDepotDebugInfo() { BOOST_FOREACH(BWAPI::Unit * depot, depots) { int x = depot->getPosition().x() - 64; int y = depot->getPosition().y() - 32; if (DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawBoxMap(x-2, y-1, x+75, y+14, BWAPI::Colors::Black, true); if (DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextMap(x, y, "\x04 Workers: %d", getNumAssignedWorkers(depot)); } }
[ "[email protected]@ce23f72d-95c0-fd94-fabd-fc6dce850bd1" ]
[ [ [ 1, 405 ] ] ]
a8951c0568fe796d2774476a7cf4f31bafac446b
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HHVClientDemo/HHVClientDemo/HWndManager.cpp
7b3527cbff7035fed2b7fe46ad1e75dee79aa6f8
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
GB18030
C++
false
false
5,823
cpp
#include "stdafx.h" #include "HWndManager.h" #include "./CommClass.h" //--------------------------------------------------------------------------- CHWndManager::CHWndManager() { m_hParentWnd = NULL; m_SpliteHandle = -1; m_videoWindowNum = MAX_CLIENT_WINDOW; } //---------------------------------------------------------------------------- CHWndManager::~CHWndManager() { if(HWnd_Clear) HWnd_Clear(m_SpliteHandle); FreeHWndDll(); } //----------------------------------------------------------------------------- int CHWndManager::InitSplit(HWND hParentWnd) { if ( LoadHWndDll() < 0 ) return -1; m_hParentWnd = hParentWnd; m_SpliteHandle = HWnd_Init(m_hParentWnd); if(m_SpliteHandle < 0) return -1; //窗口都初始化为空闲状态 for (int i = 0; i < MAX_CLIENT_WINDOW; i++) { HWND hWnd = HWnd_GetHWnd(m_SpliteHandle, i); m_mWndFree[i].index = i; m_mWndFree[i].hWnd = hWnd; m_mWndFree[i].bFree = true; } return 0; } int CHWndManager::GetFocus() { return HWnd_GetFocus(m_SpliteHandle); } //----------------------------------------------------------------------------- void CHWndManager::SetFocus( int index ) { HWnd_SetFocus(m_SpliteHandle, index); } HWND CHWndManager::GetHWnd( int index ) { if (index < 0) return NULL; return HWnd_GetHWnd(m_SpliteHandle, index); } HWND CHWndManager::GetFocusHWnd( ) { return GetHWnd( GetFocus() ); } void CHWndManager::SelectChannel(POINT pt) { HWnd_OnUpdateFocus(m_SpliteHandle, pt); } //------------------------------------------------------------------------------ void CHWndManager::SetSplitMode ( int currIndex, int num, int clickNum ) { HWnd_SetSplitMode(m_SpliteHandle, currIndex, num); //HWnd_SetSplitMode_WithOrder(m_SpliteHandle, currIndex, num, clickNum); switch(num) { case SPLIT_1: m_videoWindowNum = 1; break; case SPLIT_4: m_videoWindowNum = 4; break; case SPLIT_6: m_videoWindowNum = 6; break; case SPLIT_9: m_videoWindowNum = 9; break; case SPLIT_16: m_videoWindowNum = 16; break; case SPLIT_25: m_videoWindowNum = 25; break; case SPLIT_36: m_videoWindowNum = 36; break; case SPLIT_3: m_videoWindowNum = 3; break; case SPLIT_6_2: m_videoWindowNum = 7; // 实际分割数是6,为了与SPLIT_6相区别,将6改为7 break; case SPLIT_49: m_videoWindowNum = 49; break; case SPLIT_64: m_videoWindowNum = 64; break; default: m_videoWindowNum = 16; break; } } void CHWndManager::SetOsdTextEx(int index, int line, char* text, COLORREF osdcolor) { HWnd_SetOsdTextEx( m_SpliteHandle, index, line, text, osdcolor); } fHWnd_Init HWnd_Init = NULL; fHWnd_Clear HWnd_Clear = NULL; fHWnd_GetHWnd HWnd_GetHWnd = NULL; fHWnd_GetFocus HWnd_GetFocus = NULL; fHWnd_SetFocus HWnd_SetFocus = NULL; fHWnd_SetSplitMode HWnd_SetSplitMode = NULL; fHWnd_OnUpdateFocus HWnd_OnUpdateFocus = NULL; fHWnd_SetPaintBG HWnd_SetPaintBG = NULL; fHWnd_GetIndex HWnd_GetIndex = NULL; fHWnd_SetSplitMode_WithOrder HWnd_SetSplitMode_WithOrder =NULL; fHWnd_GetVisible HWnd_GetVisible = NULL; fHWnd_SetOsdTextEx HWnd_SetOsdTextEx = NULL; HMODULE ghWndDLL = NULL; int LoadHWndDll() { CHAR path[_MAX_PATH] = {0X00}; CCommClass::ExtractFilePath( path ); strcat( path, "\\HWndDll.dll"); ghWndDLL = LoadLibrary(path); if (NULL == ghWndDLL) { char chError[128] = {0x00}; sprintf( chError, "!!!加载 %s 的动态库失败!!!", "HWndDll.dll"); AfxMessageBox( chError ); return -1; } HWnd_Init = (fHWnd_Init) GetProcAddress(ghWndDLL, "HWnd_Init"); HWnd_Clear = (fHWnd_Clear) GetProcAddress(ghWndDLL, "HWnd_Clear"); HWnd_GetHWnd = (fHWnd_GetHWnd) GetProcAddress(ghWndDLL, "HWnd_GetHWnd"); HWnd_GetFocus = (fHWnd_GetFocus) GetProcAddress(ghWndDLL, "HWnd_GetFocus"); HWnd_SetFocus = (fHWnd_SetFocus) GetProcAddress(ghWndDLL, "HWnd_SetFocus"); HWnd_SetSplitMode = (fHWnd_SetSplitMode) GetProcAddress(ghWndDLL, "HWnd_SetSplitMode"); HWnd_OnUpdateFocus = (fHWnd_OnUpdateFocus) GetProcAddress(ghWndDLL, "HWnd_OnUpdateFocus"); HWnd_SetPaintBG = (fHWnd_SetPaintBG) GetProcAddress(ghWndDLL, "HWnd_SetPaintBG"); HWnd_GetIndex = (fHWnd_GetIndex) GetProcAddress(ghWndDLL, "HWnd_GetIndex"); HWnd_SetSplitMode_WithOrder = (fHWnd_SetSplitMode_WithOrder)GetProcAddress(ghWndDLL, "HWnd_SetSplitMode_WithOrder"); HWnd_GetVisible = (fHWnd_GetVisible)GetProcAddress(ghWndDLL, "HWnd_GetVisible"); //2008-08-25 HWnd_SetOsdTextEx = (fHWnd_SetOsdTextEx)GetProcAddress(ghWndDLL, "HWnd_SetOsdTextEx"); if ( HWnd_Init == NULL || HWnd_GetHWnd == NULL || HWnd_GetFocus == NULL || HWnd_SetSplitMode == NULL || HWnd_OnUpdateFocus == NULL || HWnd_SetPaintBG == NULL || HWnd_GetIndex == NULL || HWnd_SetSplitMode_WithOrder == NULL || HWnd_GetVisible == NULL || HWnd_SetOsdTextEx == NULL) return -2; return 0; } int FreeHWndDll() { if ( ghWndDLL != NULL ) { FreeLibrary(ghWndDLL); ghWndDLL = NULL; } return 0; }
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 200 ] ] ]
f502cf88c2dbafeafe86f0b730580a679a3d3a40
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-shared/Threading/ThreadPool.h
504a0b8963ffc35c433a20e6b91acf0ecea1f0b0
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
4,613
h
/* * Thread Pool Class * Copyright (C) Burlex <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "../Common.h" #include "Mutex.h" #include "ThreadStarter.h" #ifndef __THREADPOOL_H #define __THREADPOOL_H #ifdef WIN32 class SERVER_DECL ThreadController { public: HANDLE hThread; uint32 thread_id; void Setup(HANDLE h) { hThread = h; // whoops! GetThreadId is for windows 2003 and up only! :< - Burlex //thread_id = (uint32)GetThreadId(h); } void Suspend() { // We can't be suspended by someone else. That is a big-no-no and will lead to crashes. ASSERT(GetCurrentThreadId() == thread_id); SuspendThread(hThread); } void Resume() { // This SHOULD be called by someone else. ASSERT(GetCurrentThreadId() != thread_id); if(!ResumeThread(hThread)) { DWORD le = GetLastError(); printf("lasterror: %u\n", le); } } void Join() { WaitForSingleObject(hThread, INFINITE); } uint32 GetId() { return thread_id; } }; #else #ifndef HAVE_DARWIN #include <semaphore.h> int GenerateThreadId(); class ThreadController { sem_t sem; pthread_t handle; int thread_id; public: void Setup(pthread_t h) { handle = h; sem_init(&sem, PTHREAD_PROCESS_PRIVATE, 0); thread_id = GenerateThreadId(); } ~ThreadController() { sem_destroy(&sem); } void Suspend() { ASSERT(pthread_equal(pthread_self(), handle)); sem_wait(&sem); } void Resume() { ASSERT(!pthread_equal(pthread_self(), handle)); sem_post(&sem); } void Join() { // waits until the thread finishes then returns pthread_join(handle, NULL); } ARCEMU_INLINE uint32 GetId() { return (uint32)thread_id; } }; #else int GenerateThreadId(); class ThreadController { pthread_cond_t cond; pthread_mutex_t mutex; int thread_id; pthread_t handle; public: void Setup(pthread_t h) { handle = h; pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); thread_id = GenerateThreadId(); } ~ThreadController() { pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } void Suspend() { pthread_cond_wait(&cond, &mutex); } void Resume() { pthread_cond_signal(&cond); } void Join() { pthread_join(handle,NULL); } ARCEMU_INLINE uint32 GetId() { return (uint32)thread_id; } }; #endif #endif struct SERVER_DECL Thread { ThreadBase * ExecutionTarget; ThreadController ControlInterface; Mutex SetupMutex; bool DeleteAfterExit; }; typedef std::set<Thread*> ThreadSet; class SERVER_DECL CThreadPool { int GetNumCpus(); uint32 _threadsRequestedSinceLastCheck; uint32 _threadsFreedSinceLastCheck; uint32 _threadsExitedSinceLastCheck; uint32 _threadsToExit; int32 _threadsEaten; Mutex _mutex; ThreadSet m_activeThreads; ThreadSet m_freeThreads; public: CThreadPool(); // call every 2 minutes or so. void IntegrityCheck(); // call at startup void Startup(); // shutdown all threads void Shutdown(); // return true - suspend ourselves, and wait for a future task. // return false - exit, we're shutting down or no longer needed. bool ThreadExit(Thread * t); // creates a thread, returns a handle to it. Thread * StartThread(ThreadBase * ExecutionTarget); // grabs/spawns a thread, and tells it to execute a task. void ExecuteTask(ThreadBase * ExecutionTarget); // prints some neat debug stats void ShowStats(); // kills x free threads void KillFreeThreads(uint32 count); // resets the gobble counter ARCEMU_INLINE void Gobble() { _threadsEaten=(int32)m_freeThreads.size(); } // gets active thread count ARCEMU_INLINE uint32 GetActiveThreadCount() { return (uint32)m_activeThreads.size(); } // gets free thread count ARCEMU_INLINE uint32 GetFreeThreadCount() { return (uint32)m_freeThreads.size(); } }; extern SERVER_DECL CThreadPool ThreadPool; #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 107 ], [ 109, 143 ], [ 145, 203 ], [ 205, 206 ], [ 208, 209 ], [ 211, 215 ] ], [ [ 108, 108 ], [ 144, 144 ], [ 204, 204 ], [ 207, 207 ], [ 210, 210 ] ] ]
ebb4aa0a6a58394f7ef72081f96db4aa406b38a7
af1e383a9045ce4afbefafdcafbe6fb881d13343
/Dev/Codigo/Data/Block.cpp
e13f8b82b810a33d385b0a691bcaf9dc784fb704
[]
no_license
nicohen/tpdatos2008
17941e24a87728f456ac89e623fbf7efc4a26c38
7437c437325179f35e6cc04de3de2511023f24ff
refs/heads/master
2021-03-24T14:07:53.365348
2008-12-07T22:09:05
2008-12-07T22:09:05
34,405,585
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
#include "Block.h" #include "../Utils.h" #include "ContentOverflowBlockException.h" Block::Block(T_BLOCKSIZE size){ this->_size=size; this->_freeSpace=size; this->_content=(char*)malloc(this->_size); char clean='\0'; for (int i=0;i<this->_size;i++){ this->setFragment(&clean,i,1); } } Block::~Block(){ free(this->_content); } Block::Block(char* content,T_BLOCKSIZE size){ char clean='\0'; this->_size=size; this->_freeSpace=0; this->_content=(char*)malloc(this->_size); for (int i=0;i<this->_size;i++){ this->setFragment(&clean,i,1); } this->setContent(content); } void Block::setFragment(char* content,T_BLOCKSIZE offset,T_BLOCKSIZE size){ memcpy(this->_content+offset,content,size); } char* Block::getContent(){ if(this->getSize()<this->getUsedSpace()){ throw new ContentOverflowBlockException(); } return this->_content; } T_BLOCKSIZE Block::getSize(){ return this->_size; } T_BLOCKSIZE Block::getUsedSpace(){ return this->_size; } int Block::getAvaliableSpace(){ return this->getSize(); } void Block::setContent(char* content){ char clean='\0'; for (int i=0;i<this->_size;i++){ this->setFragment(&clean,i,1); } this->setFragment(content,0,this->_size); }
[ "nahuelquevedo@ce6c4afa-f348-0410-9719-5941d86a54b7", "nicohen@ce6c4afa-f348-0410-9719-5941d86a54b7" ]
[ [ [ 1, 45 ], [ 47, 62 ] ], [ [ 46, 46 ] ] ]
a43adad7d4bcf9d0ccc671798341851b4afb6506
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPWorkspace.h
75b9ec8317adae54fa96250fd2bd45a467f10393
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
8,450
h
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* #if !defined(AFX_BCGPWORKSPACE_H__C82F6ED0_8263_11D3_A9EF_005056800000__INCLUDED_) #define AFX_BCGPWORKSPACE_H__C82F6ED0_8263_11D3_A9EF_005056800000__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BCGCBPro.h" #include "BCGPUserTool.h" class CBCGPMouseManager; class CBCGPContextMenuManager; class CBCGPKeyboardManager; class CBCGPUserToolsManager; class CBCGPFrameImpl; class CBCGPMDIFrameWnd; class CBCGPFrameWnd; class CBCGPOleIPFrameWnd; class CBCGPShellManager; class CBCGPWorkspace; class CBCGPTooltipManager; #if defined _AFXDLL && !defined _BCGCBPRO_STATIC_ // Skins manager can not be used in the static version class CBCGPSkinManager; #endif // Some accessor functions BCGCBPRODLLEXPORT CBCGPWorkspace* GetWorkspace(); #define WORKSPACE (*GetWorkspace()) #define BCG_DEFAULT_SKINS_DIR (LPCTSTR)-1 //--------------------------------------------------------------------------------- // * // * This class is useful to store all the customizations at once // * // * // * you may use this as a mixin class for your CWinApp object ! // * // * i.g. "class CMyApp : public CWinApp, public CBCGPWorkspace {...};" // * // * but you may also use it standalone. Just call once UseWorkspaceManager // * //--------------------------------------------------------------------------------- class BCGCBPRODLLEXPORT CBCGPWorkspace { public: CBCGPWorkspace (BOOL bResourceSmartUpdate = FALSE); virtual ~CBCGPWorkspace(); static BOOL UseWorkspaceManager(LPCTSTR lpszSectionName = NULL, BOOL bResourceSmartUpdate = FALSE); LPCTSTR SetRegistryBase(LPCTSTR lpszSectionName = NULL); LPCTSTR GetRegistryBase() { return m_strRegSection; } // Saved data version: int GetDataVersionMajor () const { return m_iSavedVersionMajor; } int GetDataVersionMinor () const { return m_iSavedVersionMinor; } int GetDataVersion () const; BOOL InitMouseManager (); BOOL InitContextMenuManager (); BOOL InitKeyboardManager (); BOOL InitShellManager (); BOOL InitTooltipManager (); #if defined _AFXDLL && !defined _BCGCBPRO_STATIC_ // Skins manager can not be used in the static version BOOL InitSkinManager (LPCTSTR lpszSkinsDirectory = BCG_DEFAULT_SKINS_DIR); // BCG_DEFAULT_SKINS_DIR is "<program files>\Common Files\BCGSoft\Skins #endif virtual void OnAfterDownloadSkins (const CString& /*strSkinsDirectory*/) {} BOOL EnableUserTools (const UINT uiCmdToolsDummy, const UINT uiCmdFirst, const UINT uiCmdLast, CRuntimeClass* pToolRTC = RUNTIME_CLASS (CBCGPUserTool), UINT uArgMenuID = 0, UINT uInitDirMenuID = 0); BOOL EnableTearOffMenus (LPCTSTR lpszRegEntry, const UINT uiCmdFirst, const UINT uiCmdLast); BOOL IsResourceSmartUpdate () const { return m_bResourceSmartUpdate; } void EnableLoadWindowPlacement (BOOL bEnable = TRUE) { m_bLoadWindowPlacement = bEnable; } CBCGPMouseManager* GetMouseManager(); CBCGPContextMenuManager* GetContextMenuManager(); CBCGPKeyboardManager* GetKeyboardManager(); CBCGPUserToolsManager* GetUserToolsManager(); CBCGPShellManager* GetShellManager (); CBCGPTooltipManager* GetTooltipManager (); #if defined _AFXDLL && !defined _BCGCBPRO_STATIC_ // Skins manager can not be used in the static version CBCGPSkinManager* GetSkinManager(); #endif // Call on of those in CMyApp::InitInstance just after ProcessShellCommand() // and before pMainFrame->ShowWindow(). See BCGDevStudioExample BOOL LoadState (CBCGPMDIFrameWnd* pFrame, LPCTSTR lpszSectionName = NULL); BOOL LoadState (CBCGPFrameWnd* pFrame, LPCTSTR lpszSectionName = NULL); BOOL LoadState (CBCGPOleIPFrameWnd* pFrame, LPCTSTR lpszSectionName = NULL); virtual BOOL LoadState (LPCTSTR lpszSectionName = NULL, CBCGPFrameImpl* pFrameImpl = NULL); virtual BOOL CleanState (LPCTSTR lpszSectionName = NULL); virtual BOOL SaveState (LPCTSTR lpszSectionName = NULL, CBCGPFrameImpl* pFrameImpl = NULL); BOOL SaveState (CBCGPMDIFrameWnd* pFrame, LPCTSTR lpszSectionName = NULL); BOOL SaveState (CBCGPFrameWnd* pFrame, LPCTSTR lpszSectionName = NULL); BOOL SaveState (CBCGPOleIPFrameWnd* pFrame, LPCTSTR lpszSectionName = NULL); BOOL IsStateExists(LPCTSTR lpszSectionName /*=NULL*/); virtual BOOL OnViewDoubleClick (CWnd* pWnd, int iViewId); virtual BOOL ShowPopupMenu (UINT uiMenuResId, const CPoint& point, CWnd* pWnd); CString GetRegSectionPath (LPCTSTR szSectionAdd = _T("")); // These functions load and store values from the "Custom" subkey // To use subkeys of the "Custom" subkey use GetSectionInt() etc. // instead int GetInt(LPCTSTR lpszEntry, int nDefault = 0); CString GetString(LPCTSTR lpszEntry, LPCTSTR lpzDefault = _T("")); BOOL GetBinary(LPCTSTR lpszEntry, LPBYTE* ppData, UINT* pBytes); BOOL GetObject(LPCTSTR lpszEntry, CObject& obj); BOOL WriteInt(LPCTSTR lpszEntry, int nValue ); BOOL WriteString(LPCTSTR lpszEntry, LPCTSTR lpszValue ); BOOL WriteBinary(LPCTSTR lpszEntry, LPBYTE pData, UINT nBytes); BOOL WriteObject(LPCTSTR lpszEntry, CObject& obj); // These functions load and store values from a given subkey // of the "Custom" subkey. For simpler access you may use // GetInt() etc. int GetSectionInt( LPCTSTR lpszSubSection, LPCTSTR lpszEntry, int nDefault = 0); CString GetSectionString( LPCTSTR lpszSubSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault = _T("")); BOOL GetSectionBinary(LPCTSTR lpszSubSection, LPCTSTR lpszEntry, LPBYTE* ppData, UINT* pBytes); BOOL GetSectionObject(LPCTSTR lpszSubSection, LPCTSTR lpszEntry, CObject& obj); BOOL WriteSectionInt( LPCTSTR lpszSubSection, LPCTSTR lpszEntry, int nValue ); BOOL WriteSectionString( LPCTSTR lpszSubSection, LPCTSTR lpszEntry, LPCTSTR lpszValue ); BOOL WriteSectionBinary(LPCTSTR lpszSubSection, LPCTSTR lpszEntry, LPBYTE pData, UINT nBytes); BOOL WriteSectionObject(LPCTSTR lpszSubSection, LPCTSTR lpszEntry, CObject& obj); // WinHelp override: virtual void OnAppContextHelp (CWnd* pWndControl, const DWORD dwHelpIDArray []); // Idle processing override: virtual BOOL OnBCGPIdle (CWnd* /*pWnd*/) { return FALSE; } #if defined _AFXDLL && !defined _BCGCBPRO_STATIC_ // Skins manager can not be used in the static version virtual void OnSelectSkin (); #endif public: BOOL m_bLoadUserToolbars; protected: friend class CBCGPFrameImpl; // Overidables for customization virtual void OnClosingMainFrame (CBCGPFrameImpl* pFrameImpl); // called before anything is loaded virtual void PreLoadState() {} // called after everything is loaded virtual void LoadCustomState() {} // called before anything is saved virtual void PreSaveState() {} // called after everything is saved virtual void SaveCustomState() {} virtual BOOL LoadWindowPlacement ( CRect& rectNormalPosition, int& nFflags, int& nShowCmd); virtual BOOL StoreWindowPlacement ( const CRect& rectNormalPosition, int nFflags, int nShowCmd); virtual BOOL ReloadWindowPlacement (CFrameWnd* pFrame); protected: CString m_strRegSection; BOOL m_bKeyboardManagerAutocreated; BOOL m_bContextMenuManagerAutocreated; BOOL m_bMouseManagerAutocreated; BOOL m_bUserToolsManagerAutoCreated; BOOL m_bTearOffManagerAutoCreated; BOOL m_bSkinManagerAutocreated; BOOL m_bShellManagerAutocreated; BOOL m_bTooltipManagerAutocreated; int m_iSavedVersionMajor; int m_iSavedVersionMinor; BOOL m_bForceDockStateLoad; // Load dock bars state even it's not valid BOOL m_bLoadSaveFrameBarsOnly; BOOL m_bSaveState; // Automatically save state when the main frame is closed. const BOOL m_bResourceSmartUpdate; // Automatic toolbars/menu resource update BOOL m_bForceImageReset; // Force image reset every time when the frame is loaded BOOL m_bLoadWindowPlacement; }; #endif // !defined(AFX_BCGPWORKSPACE_H__C82F6ED0_8263_11D3_A9EF_005056800000__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 226 ] ] ]
30b4c6213d41849d63f40d8e6aedc0dbf519dd8a
df5277b77ad258cc5d3da348b5986294b055a2be
/GameEngineV0.35/Source/MainMenu.h
561272f5b905ee97915639ab27665460b79a147f
[]
no_license
beentaken/cs260-last2
147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22
61b2f84d565cc94a0283cc14c40fb52189ec1ba5
refs/heads/master
2021-03-20T16:27:10.552333
2010-04-26T00:47:13
2010-04-26T00:47:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
h
#pragma once #include "IGameState.h" #include "Engine.h" #include "IController.h" namespace Framework { class MainMenu : public IGameState { public: enum LevelIndex { LI_SinglePlayer = 0 ,LI_HostGame ,LI_JoinGame ,LI_Quit ,LI_NumberOfIndexes }; // LevelIndex public: MainMenu( GameStateManager *gsm ); virtual ~MainMenu( void ); ///Adds a controller to the internal list of the GameState. virtual void AddController( Controller *controller ); ///Removes a controller from the internal list of the GameState. virtual void RemoveController( Controller *controller ); virtual void SendMessage( Message *message ); ///Make asteroids, player, and a score object. virtual void Initialize( void ); ///Update the game, updates all systems. virtual void Update( float dt ); ///Cleanup assets and cleanup and ties to other states. virtual void OnCleanup( void ); ///Reset all the positions, objects, scores, ect... virtual void Restart( void ); private: typedef ObjectLinkList<Controller> ControllerList; ControllerList Controllers; LevelIndex index_; GOCId indexes_[LI_NumberOfIndexes]; }; // MainMenu } // namespace Framework
[ "rziugy@af704e40-745a-32bd-e5ce-d8b418a3b9ef" ]
[ [ [ 1, 55 ] ] ]
4bd0ed99ec5c31639baa0ff3f5225758f4f652b1
e68cf672cdb98181db47dab9fb8c45e69b91e256
/src/DepthStencilTarget.cpp
2eaf97ff325a1d754cc80c7c9aab223f7e2705ac
[]
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
2,011
cpp
#include "DepthStencilTarget.h" // static DepthStencilTarget* DepthStencilTarget::createDepthFloat24StencilUnsignedByte8( ID3D11Device* pDevice, int width, int height ) { DXGI_SAMPLE_DESC sd; sd.Count = 1; sd.Quality = 0; D3D11_TEXTURE2D_DESC td; td.Width = width; td.Height = height; td.ArraySize = 1; td.MipLevels = 1; td.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; td.SampleDesc = sd; td.Usage = D3D11_USAGE_DEFAULT; td.BindFlags = D3D11_BIND_DEPTH_STENCIL; td.CPUAccessFlags = 0; td.MiscFlags = 0; ID3D11Texture2D* pTexture; pDevice->CreateTexture2D( &td, NULL, &pTexture ); return new DepthStencilTarget( pDevice, width, height, pTexture ); } // static DepthStencilTarget* DepthStencilTarget::createDepthFloat32( ID3D11Device* pDevice, int width, int height ) { DXGI_SAMPLE_DESC sd; sd.Count = 1; sd.Quality = 0; D3D11_TEXTURE2D_DESC td; td.Width = width; td.Height = height; td.MipLevels = 1; td.ArraySize = 1; td.Format = DXGI_FORMAT_D32_FLOAT; td.SampleDesc = sd; td.Usage = D3D11_USAGE_DEFAULT; td.BindFlags = D3D11_BIND_DEPTH_STENCIL; td.CPUAccessFlags = 0; td.MiscFlags = 0; ID3D11Texture2D* pTexture; pDevice->CreateTexture2D( &td, NULL, &pTexture ); return new DepthStencilTarget( pDevice, width, height, pTexture ); } // virtual DepthStencilTarget::~DepthStencilTarget() { m_pTexture->Release(); m_pDepthStencilView->Release(); } int DepthStencilTarget::width() { return m_width; } int DepthStencilTarget::height() { return m_height; } ID3D11Texture2D* DepthStencilTarget::texture() { return m_pTexture; } ID3D11DepthStencilView* DepthStencilTarget::depthStencilView() { return m_pDepthStencilView; } DepthStencilTarget::DepthStencilTarget( ID3D11Device* pDevice, int width, int height, ID3D11Texture2D* pTexture ) : m_width( width ), m_height( height ), m_pTexture( pTexture ) { pDevice->CreateDepthStencilView( pTexture, NULL, &m_pDepthStencilView ); }
[ [ [ 1, 86 ] ] ]
2b4bdbe76f79df024d19e994e7dc942dc6a0ba19
2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83
/BasicOgreFramework/PhysxSDK/Samples/SampleCommonCode/src/CookASE.cpp
5465724bcba4db5e4f41b6c587c49fc2e50f5a0e
[]
no_license
mgq812/simengines-g2-code
5908d397ef2186e1988b1d14fa8b73f4674f96ea
699cb29145742c1768857945dc59ef283810d511
refs/heads/master
2016-09-01T22:57:54.845817
2010-01-11T19:26:51
2010-01-11T19:26:51
32,267,377
0
0
null
null
null
null
UTF-8
C++
false
false
3,890
cpp
#include "CookASE.h" #include <NxPhysics.h> #include <stdio.h> #include "Stream.h" #include "cooking.h" #include "MediaPath.h" NxVec3 _offset; char* trimFront(char* c) { while(*c == ' ' || *c == '\t') c++; return c; } void readVertices(FILE* f, NxArray<NxVec3>& vertices, NxVec3 scale) { char line[512]; while(true) { fgets(line, 512, f); char* l = trimFront(line); if (*l == '}') { return; } else if (strstr(l, "*MESH_VERTEX")) { float a,b,c; int i; sscanf(l, "*MESH_VERTEX %d %f %f %f", &i, &a, &b, &c); NxVec3 newV(a,c,-b); newV.x *= scale.x; newV.y *= scale.y; newV.z *= scale.z; vertices[i] = newV; vertices[i] += _offset; } } } void readFaces(FILE* f, NxArray<NxU32>& faces) { char line[512]; while(true) { fgets(line, 512, f); char* l = trimFront(line); if (*l == '}') { return; } else if (strstr(l, "*MESH_FACE")) { int a,b,c; int i; sscanf(l, "*MESH_FACE %d: A: %d B: %d C: %d ", &i, &a, &b, &c); faces[3*i+0] = a; faces[3*i+1] = b; faces[3*i+2] = c; } } } void readMesh(FILE* f, NxArray<NxVec3>& vertices, NxArray<NxU32>& faces, NxVec3 scale) { char line[512]; int nbVertices; int nbFaces; while(true) { fgets(line, 512, f); char* l = trimFront(line); if (*l == '}') { return; } else if (strstr(l, "*MESH_NUMVERTEX")) { sscanf(l, "*MESH_NUMVERTEX %d", &nbVertices); vertices.resize(nbVertices); } else if (strstr(l, "*MESH_NUMFACES")) { sscanf(l, "*MESH_NUMFACES %d", &nbFaces); faces.resize(nbFaces*3); } else if (strstr(l, "*MESH_VERTEX_LIST {")) { readVertices(f, vertices, scale); } else if (strstr(l, "*MESH_FACE_LIST {")) { readFaces(f, faces); } } } NxActor* CookASE(const std::string& filename, NxScene* scene, NxVec3 offset, NxVec3 scale) { _offset = offset; char buff[1024]; //FILE *f = 0; FILE* f = fopen(FindMediaFile(filename.c_str(),buff), "rb"); if (f == NULL) { printf("File not found: %s\n", filename.c_str()); return NULL; } NxArray<NxVec3> vertices; NxArray<NxU32> faces; char line[512]; int linenbr = 0; while (!feof(f)) { fgets(line, 512, f); char* l = trimFront(line); if (!strncmp(l, "*MESH {", 7)) { readMesh(f, vertices, faces, scale); } else { //printf("Line %4d: %s\n", linenbr++, l); } } fclose(f); // Build physical model NxTriangleMeshDesc terrainDesc; terrainDesc.numVertices = vertices.size(); terrainDesc.numTriangles = faces.size()/3; terrainDesc.pointStrideBytes = sizeof(NxVec3); terrainDesc.triangleStrideBytes = 3*sizeof(NxU32); terrainDesc.points = &vertices[0].x; terrainDesc.triangles = &faces[0]; terrainDesc.flags = NX_MF_HARDWARE_MESH; //terrainDesc.heightFieldVerticalAxis = NX_Y; //terrainDesc.heightFieldVerticalExtent = -1000.0f; MemoryWriteBuffer buf; bool status = CookTriangleMesh(terrainDesc, buf); NxTriangleMesh* terrainMesh = scene->getPhysicsSDK().createTriangleMesh(MemoryReadBuffer(buf.data)); // // Please note about the created Triangle Mesh, user needs to release it when no one uses it to save memory. It can be detected // by API "meshData->getReferenceCount() == 0". And, the release API is "gPhysicsSDK->releaseTriangleMesh(*meshData);" // NxTriangleMeshShapeDesc terrainMeshDesc; terrainMeshDesc.meshData = terrainMesh; NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&terrainMeshDesc); NxActor* a = scene->createActor(ActorDesc); assert(a != NULL); assert(a->getNbShapes() == 1); NxShape* s = a->getShapes()[0]; assert(s != NULL); NxTriangleMeshShape* ts = s->isTriangleMesh(); assert(ts != NULL); NxTriangleMeshDesc* tmd= new NxTriangleMeshDesc(); ts->getTriangleMesh().saveToDesc(*tmd); ts->userData = tmd; return a; }
[ "erucarno@789472dc-e1c3-11de-81d3-db62269da9c1" ]
[ [ [ 1, 151 ] ] ]
2ec0c41a4a6cd22f842fa01dee95961850374562
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/plugins/GSdx/GSVertexList.h
463f49fc88dfc4cf10041c1deef8e28a10c8ec26
[]
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
1,838
h
/* * Copyright (C) 2007-2009 Gabest * http://www.gabest.org * * 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 * */ #pragma once template <class Vertex> class GSVertexList { void* m_base; Vertex* m_v[3]; int m_count; public: GSVertexList() : m_count(0) { m_base = _aligned_malloc(sizeof(Vertex) * countof(m_v), 16); for(int i = 0; i < countof(m_v); i++) { m_v[i] = &((Vertex*)m_base)[i]; } } virtual ~GSVertexList() { _aligned_free(m_base); } void RemoveAll() { m_count = 0; } __forceinline Vertex& AddTail() { ASSERT(m_count < 3); return *m_v[m_count++]; } __forceinline void RemoveAt(int pos, int keep) { if(keep == 1) { Vertex* tmp = m_v[pos + 0]; m_v[pos + 0] = m_v[pos + 1]; m_v[pos + 1] = tmp; } else if(keep == 2) { Vertex* tmp = m_v[pos + 0]; m_v[pos + 0] = m_v[pos + 1]; m_v[pos + 1] = m_v[pos + 2]; m_v[pos + 2] = tmp; } m_count = pos + keep; } __forceinline void GetAt(int i, Vertex& v) { v = *m_v[i]; } int GetCount() { return m_count; } };
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 87 ] ] ]
46f5cbefcf52a797a1c300f74f31042dab956af2
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziis/src/mod/encoding/src/compimpl.cc
35fe82b94d845400f45c7ad9a24fef4dcd76f6e3
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
3,041
cc
// // compimpl.cc for in // // Made by texane // Login <[email protected]> // // Started on Thu Mar 23 09:58:21 2006 texane // Last update Fri Apr 07 14:28:10 2006 texane // #include "include/mod_encoding.hh" using namespace std; #ifndef _WIN32 static int cicmp(char a, char b) { // normalize if (a >= 'A' && a <= 'Z') a += 'a' - 'A'; if (b >= 'A' && b <= 'Z') b += 'a' - 'A'; return b - a; } int stricmp(const char* s1, const char* s2) { while (cicmp(*s1, *s2) == 0) { if (*s1 == 0) return 0; ++s1; ++s2; } return *s2 - *s1; } #endif // !_WIN32 // implement ICompressor interface void* mod_encoding::GetNewContext(const char* encoding) { context_t* p_context; p_context = new context_t; p_context->encoding = encoding; p_context->u.context = 0; if (!stricmp(encoding, "deflate")) ZlibGetNewContext(p_context->u.zlib_context); else if (!stricmp(encoding, "gzip")) GzipGetNewContext(p_context->u.gzip_context); else if (!stricmp(encoding, "compress")) GzipGetNewContext(p_context->u.gzip_context); return p_context; } void mod_encoding::DestroyContext(void* p_context) { if (((context_t*)p_context)->encoding == "deflate") ZlibDestroyContext(((context_t*)p_context)->u.zlib_context); else if (((context_t*)p_context)->encoding == "gzip") GzipDestroyContext(((context_t*)p_context)->u.gzip_context); else if (((context_t*)p_context)->encoding == "compress") GzipDestroyContext(((context_t*)p_context)->u.gzip_context); delete (context_t*)p_context; } bool mod_encoding::Compress(void* p_context, IBuffer& buf_in, IBuffer& buf_out) { bool is_success; is_success = true; if (((context_t*)p_context)->encoding == "deflate") is_success = ZlibCompress(((context_t*)p_context)->u.zlib_context, buf_in, buf_out); else if (((context_t*)p_context)->encoding == "gzip") is_success = GzipCompress(((context_t*)p_context)->u.gzip_context, buf_in, buf_out); else if (((context_t*)p_context)->encoding == "compress") is_success = GzipCompress(((context_t*)p_context)->u.gzip_context, buf_in, buf_out); return is_success; } bool mod_encoding::Decompress(void* p_context, IBuffer& buf_in, IBuffer& buf_out) { bool is_success; is_success = true; if (((context_t*)p_context)->encoding == "deflate") is_success = ZlibDecompress(((context_t*)p_context)->u.zlib_context, buf_in, buf_out); else if (((context_t*)p_context)->encoding == "gzip") is_success = GzipDecompress(((context_t*)p_context)->u.gzip_context, buf_in, buf_out); else if (((context_t*)p_context)->encoding == "deflate") is_success = GzipDecompress(((context_t*)p_context)->u.gzip_context, buf_in, buf_out); return is_success; } static const char* _encodings[] = { "deflate", // "gzip", // "compress", 0 }; const char** mod_encoding::GetSupportedEncoding() { return _encodings; }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 117 ] ] ]
799c1030508aec7d093cf62514eff9e29c43a8ce
30e4267e1a7fe172118bf26252aa2eb92b97a460
/code/pkg_Core/Interface/ChangeObserver/Ix_ChangeObserver.h
f7ddc2f848f14745d79e32d562381f15e443fa46
[ "Apache-2.0" ]
permissive
thinkhy/x3c_extension
f299103002715365160c274314f02171ca9d9d97
8a31deb466df5d487561db0fbacb753a0873a19c
refs/heads/master
2020-04-22T22:02:44.934037
2011-01-07T06:20:28
2011-01-07T06:20:28
1,234,211
2
0
null
null
null
null
GB18030
C++
false
false
1,298
h
// Copyright 2008-2011 Zhang Yun Gui, [email protected] // https://sourceforge.net/projects/x3c/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /*! \file Ix_ChangeObserver.h * \brief 定义改变通知观察者的接口 Ix_ChangeObserver * \author Zhang Yun Gui, C++ Plugin Framework * \date 2010.10.22 */ #ifndef X3_OBSERVER_ICHANGEOBSERVER_H_ #define X3_OBSERVER_ICHANGEOBSERVER_H_ class ChangeNotifyData; //! 改变通知观察者的接口 /*! \interface Ix_ChangeObserver \ingroup _GROUP_CHANGE_OBSERVER_ */ interface Ix_ChangeObserver { //! 改变的通知 /*! \param data 通知参数,一般为一个局部变量的地址 */ virtual void Update(ChangeNotifyData* data) = 0; }; #endif // X3_OBSERVER_ICHANGEOBSERVER_H_
[ "rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 40 ] ] ]
9df6b015f7eb4d1fbb03594d85390c95e8845106
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/sipcodec/src/t_csipheaderbase.cpp
9fb9214655e9a7c54a1753844190cb261d30641b
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
10,461
cpp
/* * Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // This contains CT_DataSIPHeaderBase #include "t_csipheaderbase.h" #include <utf.h> #include <s32file.h> #include "T_SIPUtil.h" /*@{*/ _LIT(KCmdCloneL, "CloneL"); _LIT(KCmdName, "Name"); _LIT(KCmdToTextL, "ToTextL"); _LIT(KCmdToTextLC, "ToTextLC"); _LIT(KCmdToTextValueL, "ToTextValueL"); _LIT(KCmdToTextValueLC, "ToTextValueLC"); _LIT(KCmdExternalizeL, "ExternalizeL"); _LIT(KCmdExternalizeSupported, "ExternalizeSupported"); _LIT(KCmdPushLC, "PushLC"); // Fields _LIT(KFldSIPHeaderBase, "sipheaderbase"); _LIT(KFldExpected, "expected"); _LIT(KFldFileName, "filename"); _LIT(KFldSIPHeaders, "sipheaders"); _LIT(KFldAddName, "addname"); // Error _LIT(KLogError, "Error=%d"); _LIT(KMissingParameter, "missing parameter '%S'"); //Info CT_DataSIPHeaderBase::CT_DataSIPHeaderBase() : CDataWrapperBase() { } TBool CT_DataSIPHeaderBase::DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt /*aAsyncErrorIndex*/) { TBool ret = ETrue; if (aCommand == KCmdCloneL) { DoCmdCloneL(aSection); } else if (aCommand == KCmdName) { DoCmdName(aSection); } else if (aCommand == KCmdToTextL) { DoCmdToTextL(aSection); } else if (aCommand == KCmdToTextLC) { DoCmdToTextLC(aSection); } else if (aCommand == KCmdToTextValueL) { DoCmdToTextValueL(aSection); } else if (aCommand == KCmdToTextValueLC) { DoCmdToTextValueLC(aSection); } else if (aCommand == KCmdExternalizeL) { DoCmdExternalizeL(aSection); } else if (aCommand == KCmdExternalizeSupported) { DoCmdExternalizeSupported(aSection); } else if (aCommand == KCmdPushLC) { DoCmdPushLC(aSection); } else { ret = EFalse; } return ret; } void CT_DataSIPHeaderBase::DoCmdCloneL(const TTEFSectionName& aSection) { CSIPHeaderBase* sipHeaderBase = NULL; TPtrC datSipHeaderBase; if (!GetStringFromConfig(aSection, KFldSIPHeaderBase, datSipHeaderBase)) { ERR_PRINTF2(KMissingParameter, &KFldSIPHeaderBase()); SetBlockResult(EFail); } else { INFO_PRINTF1(_L("execute CSIPHeaderBase::CloneL()")); TRAPD(err,sipHeaderBase=GetSIPHeaderBase()->CloneL()); if (err != KErrNone) { ERR_PRINTF2(KLogError, err); SetError(err); } else { SetDataObjectL(datSipHeaderBase, sipHeaderBase); } } } void CT_DataSIPHeaderBase::DoCmdName(const TTEFSectionName& aSection) { RStringF stringF; INFO_PRINTF1(_L("execute CSIPHeaderBase::Name")); stringF = GetSIPHeaderBase()->Name(); const TDesC8 &name = stringF.DesC(); TBuf<KMaxTestExecuteCommandLength> actual; CnvUtfConverter::ConvertToUnicodeFromUtf8(actual, name); INFO_PRINTF2(_L("Header Name is , name: %S"), &actual); TPtrC expected; if (GetStringFromConfig(aSection, KFldExpected, expected) ) { if (expected.Compare(actual) != 0) { ERR_PRINTF3(_L("actual value is not as expected, expected: %S, actual: %S"), &expected, &actual); SetBlockResult(EFail); } } } void CT_DataSIPHeaderBase::DoCmdToTextL(const TTEFSectionName& aSection) { HBufC8* val ; TPtrC expected; INFO_PRINTF1(_L("execute CSIPHeaderBase::ToTextL()")); TRAPD(err,val=GetSIPHeaderBase()->ToTextL()); TBuf<KMaxTestExecuteCommandLength> actual; CnvUtfConverter::ConvertToUnicodeFromUtf8(actual, val->Des()); INFO_PRINTF2(_L("Header Name&Value is , name: %S"), &actual); if (err != KErrNone) { ERR_PRINTF2(KLogError, err); SetError(err); } else if(GetStringFromConfig(aSection, KFldExpected, expected)) { if (expected.Compare(actual) != 0) { ERR_PRINTF3(_L("actual value is not as expected, expected: %S, actual: %S"), &expected, &actual); SetBlockResult(EFail); } delete val; val = NULL; } } void CT_DataSIPHeaderBase::DoCmdToTextLC(const TTEFSectionName& aSection) { HBufC8* val ; TPtrC expected; INFO_PRINTF1(_L("execute CSIPHeaderBase::ToTextLC()")); TRAPD(err,val=GetSIPHeaderBase()->ToTextLC(); CleanupStack::Pop()); TBuf<KMaxTestExecuteCommandLength> actual; CnvUtfConverter::ConvertToUnicodeFromUtf8(actual, val->Des()); INFO_PRINTF2(_L("Header Name&Value is , name: %S"), &actual); if (err != KErrNone) { ERR_PRINTF2(KLogError, err); SetError(err); } else if (GetStringFromConfig(aSection, KFldExpected, expected)) { if (expected.Compare(actual) != 0) { ERR_PRINTF3(_L("actual value is not as expected, expected: %S, actual: %S"), &expected, &actual); SetBlockResult(EFail); } delete val; val = NULL; } } void CT_DataSIPHeaderBase::DoCmdToTextValueL(const TTEFSectionName& aSection) { HBufC8* val ; TPtrC expected; INFO_PRINTF1(_L("execute CSIPHeaderBase::ToTextValueL()")); TRAPD(err,val=GetSIPHeaderBase()->ToTextValueL()); TBuf<KMaxTestExecuteCommandLength> actual; CnvUtfConverter::ConvertToUnicodeFromUtf8(actual, val->Des()); INFO_PRINTF2(_L("Header Name's Value is , name value: %S"), &actual); if (err != KErrNone) { ERR_PRINTF2(KLogError, err); SetError(err); } else if (GetStringFromConfig(aSection, KFldExpected, expected)) { if (expected.Compare(actual) != 0) { ERR_PRINTF3(_L("actual value is not as expected, expected: %S, actual: %S"), &expected, &actual); SetBlockResult(EFail); } delete val; val = NULL; } } void CT_DataSIPHeaderBase::DoCmdToTextValueLC(const TTEFSectionName& aSection) { HBufC8* val ; TPtrC expected; INFO_PRINTF1(_L("execute CSIPHeaderBase::ToTextValueLC()")); TRAPD(err,val=GetSIPHeaderBase()->ToTextValueLC(); CleanupStack::Pop()); TBuf<KMaxTestExecuteCommandLength> actual; CnvUtfConverter::ConvertToUnicodeFromUtf8(actual, val->Des()); INFO_PRINTF2(_L("Header Name's Value is , name value: %S"), &actual); if (err != KErrNone) { ERR_PRINTF2(KLogError, err); SetError(err); } else if (GetStringFromConfig(aSection, KFldExpected, expected)) { if (expected.Compare(actual) != 0) { ERR_PRINTF3(_L("actual value is not as expected, expected: %S, actual: %S"), &expected, &actual); SetBlockResult(EFail); } delete val; val = NULL; } } void CT_DataSIPHeaderBase::DoCmdExternalizeL(const TTEFSectionName& aSection) { TPtrC datFileName; if ( !GetStringFromConfig(aSection, KFldFileName, datFileName) ) { ERR_PRINTF2(KMissingParameter, &KFldFileName); SetBlockResult(EFail); } else { CDirectFileStore* writestore = CDirectFileStore::ReplaceL(FileServer(), datFileName, EFileStream | EFileWrite); CleanupStack::PushL(writestore); writestore->SetTypeL(TUidType(KDirectFileStoreLayoutUid)); RStoreWriteStream writestrm; CleanupClosePushL(writestrm); TStreamId headerid = writestrm.CreateL(*writestore); writestore->SetRootL(headerid); // Execute command and log parameters INFO_PRINTF1(_L("execute CSIPHeaderBase::InternalizeValueL(RReadStream &)")); TBool addname = ETrue; (void)GetBoolFromConfig(aSection, KFldAddName, addname); TRAPD(err, GetSIPHeaderBase()->ExternalizeL(writestrm, addname)); if ( err!=KErrNone ) { ERR_PRINTF2(KLogError, err); SetError(err); } // Cleanup CleanupStack::PopAndDestroy(2, writestore); } } void CT_DataSIPHeaderBase::DoCmdExternalizeSupported(const TTEFSectionName& aSection) { TBool expected; INFO_PRINTF1(_L("execute CSIPHeaderBase::ExternalizeSupported()")); TBool actual = GetSIPHeaderBase()->ExternalizeSupported(); if (GetBoolFromConfig(aSection, KFldExpected, expected)) { if (!expected != !actual) { ERR_PRINTF3(_L("actual value is not as expected, expected: %d, actual: %d"), expected, actual); SetBlockResult(EFail); } } } void CT_DataSIPHeaderBase::DoCmdPushLC(const TTEFSectionName& aSection) { RPointerArray<CSIPHeaderBase> *array = new(ELeave)RPointerArray<CSIPHeaderBase>; if(!CT_SIPUtil::GetSIPHeadersL(*this,aSection,KFldSIPHeaders,*array)) { ERR_PRINTF2(KMissingParameter, &KFldSIPHeaders); SetBlockResult(EFail); } else { INFO_PRINTF1(_L("execute CSIPHeaderBase::PushLC(RPointerArray<CSIPHeaderBase> *aArray)")); TRAPD(err, CSIPHeaderBase::PushLC(array); CleanupStack::Pop()); if (err != KErrNone) { ERR_PRINTF2(KLogError, err); SetError(err); } } }
[ "none@none" ]
[ [ [ 1, 324 ] ] ]
90d14c970e7f2d7f4c27ee020dc41de5bc782018
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestvolume/inc/bctestvolumepopupwindow.h
26eca269bd6546d853f064307321b41a45867b13
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,640
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares popup window for application * */ #ifndef C_BCTESTVOLUMEPOPUPWINDOW_H #define C_BCTESTVOLUMEPOPUPWINDOW_H // INCLUDES #include <aknview.h> // CLASS DECLARATION /** * Popup window class */ class CBCTestVolumePopUpWindow : public CCoeControl { public: // Constructors and destructor /** * C++ default constructor. */ CBCTestVolumePopUpWindow(); /** * Symbian 2nd phase constructor. */ void ConstructL(const TRect& aRect); /** * Destructor. */ virtual ~CBCTestVolumePopUpWindow(); public: // Functions from base classes /** * From CCoeControl, SetColoe * @param aColor, aColor is the color set to. */ void SetColor(TRgb aColor); private: // Functions from base classes /** * From CCoeControl,Draw. * @param Specified area for drawing */ void Draw(const TRect& aRect) const; private: // Data RWindowGroup iMyWindowGroup; TRgb iColor; }; #endif // C_BCTESTVOLUMEPOPUPWINDOW_H // End of File
[ "none@none" ]
[ [ [ 1, 69 ] ] ]
507552fb6242ccd10f367b92b74ca13ee8d3d021
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/AranMath/ArnMath.inl
384f367a57abf4a0b4cc4af353df78aaf5fd1e77
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
2,262
inl
static inline void ArnMatrixRotationX( ArnMatrix* out, float rad ) { out = out; rad = rad; ARN_THROW_NOT_IMPLEMENTED_ERROR } static inline void ArnMatrixRotationY( ArnMatrix* out, float rad ) { out = out; rad = rad; ARN_THROW_NOT_IMPLEMENTED_ERROR } static inline void ArnMatrixRotationZ( ArnMatrix* out, float rad ) { out = out; rad = rad; ARN_THROW_NOT_IMPLEMENTED_ERROR } static inline BOOL almostEqualFloat3(ArnVec3* pV1, ArnVec3* pV2) { return ( fabsf( pV1->x - pV2->x ) < FLT_COMPARE_EPSILON ) && ( fabsf( pV1->y - pV2->y ) < FLT_COMPARE_EPSILON ) && ( fabsf( pV1->z - pV2->z ) < FLT_COMPARE_EPSILON ); } static inline BOOL almostEqualFloat3(float* floatArray1, float* floatArray2) { return ( fabsf( floatArray1[0] - floatArray2[0] ) < FLT_COMPARE_EPSILON ) && ( fabsf( floatArray1[1] - floatArray2[1] ) < FLT_COMPARE_EPSILON ) && ( fabsf( floatArray1[2] - floatArray2[2] ) < FLT_COMPARE_EPSILON ); } static inline BOOL almostEqualFloat4(float* floatArray1, float* floatArray2) { return ( fabsf( floatArray1[0] - floatArray2[0] ) < FLT_COMPARE_EPSILON ) && ( fabsf( floatArray1[1] - floatArray2[1] ) < FLT_COMPARE_EPSILON ) && ( fabsf( floatArray1[2] - floatArray2[2] ) < FLT_COMPARE_EPSILON ) && ( fabsf( floatArray1[3] - floatArray2[3] ) < FLT_COMPARE_EPSILON ); } static inline float ArnToRadian(float deg) { return float(ARN_PI/180.0f*deg); } static inline double ArnToRadian(double deg) { return double(ARN_PI/180.0*deg); } static inline double ArnToDegree(double rad) { return double(rad * (180.0 / ARN_PI)); } static inline float ArnToDegree(float rad) { return float(rad * (180.0 / ARN_PI)); } static inline float ArnVec3GetLength(const ArnVec3& v) { return sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); } static inline float ArnVec3Dot(const ArnVec3& v1, const ArnVec3& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } static inline float ArnVec3Dot(const ArnVec3* v1, const ArnVec3* v2) { return ArnVec3Dot(*v1, *v2); } static inline ArnVec3 ArnVec3GetCrossProduct(const ArnVec3& va, const ArnVec3& vb) { return CreateArnVec3(va.y * vb.z - va.z * vb.y, va.z * vb.x - va.x * vb.z, va.x * vb.y - va.y * vb.x); }
[ [ [ 1, 94 ] ] ]
305bc01e86f89344a4d42382dbce67e6c08b64e0
6eef3e34d3fe47a10336a53df1a96a591b15cd01
/ASearch/Allocator/Allocator.hpp
fbded1a483b4926c4088e183206c5dfe20dcd217
[]
no_license
praveenmunagapati/alkaline
25013c233a80b07869e0fdbcf9b8dfa7888cc32e
7cf43b115d3e40ba48854f80aca8d83b67f345ce
refs/heads/master
2021-05-27T16:44:12.356701
2009-10-29T11:23:09
2009-10-29T11:23:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,348
hpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved ______________________________________________ written by Daniel Doubrovkine - [email protected] Revision history: 28.08.2000: First release */ #ifndef ALLOCATOR_HPP #define ALLOCATOR_HPP #include <platform/include.hpp> #include <Vector/Vector.hpp> #include <Mutex/Mutex.hpp> template <class T> class CAllocator { public: CAllocator(const unsigned int Dim); ~CAllocator(); T* GetNew(); void Free(T* Pointer); void PrintBits(int Number); void FreeAll(); private: int m_IntSize; int m_EltsNumberPerSeg; CMutex m_Mutex; unsigned int m_Dim; int m_AllEltsUsed; int m_BitFieldSize; CVector<T*> m_DataSegments; CVector<int> m_DataSegFirstFreeElt; CVector<int*> m_BitFields; CVector<int> m_SegmentIsLinear; CVector<int> m_NextFreeElt; bool AddDataSegment(); void RemoveElt(int Segment, unsigned int Elt); inline int FindNextFreeElt(const int Number, const int BasePos); }; template <class T> inline int CAllocator<T>::FindNextFreeElt(const int Segment, const int BasePos) { register int i; for(i=BasePos;i<m_BitFieldSize;i++) if ( (m_BitFields[Segment][i]&m_AllEltsUsed) != m_AllEltsUsed) return i; return -1; } #endif
[ [ [ 1, 61 ] ] ]
29048c733519f260ab76bac83753a0c34bc42dcc
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/SQLCEHelper/Source/Index.cpp
d78679d6f21404cf4d4586dda4d41a09b6e3a48d
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
2,073
cpp
#include "stdafx.h" using namespace OLEDBCLI; //------------------------------------------------------------------------- // // CIndex - manipulates the table index schema // //------------------------------------------------------------------------- // CIndex::CIndex // // Default constructor // CIndex::CIndex() : m_bUnique (false), m_bPrimary (false), m_bConstraint (false) { } CIndex::CIndex(LPCTSTR pszIndexName, bool bUnique, bool bPrimary) : m_strName (pszIndexName), m_bUnique (bUnique), m_bPrimary (bPrimary), m_bConstraint (false) { } // CIndex::CIndex // // Initialize a CIndex from an OLE DB constraint description. // This constructor is used for UNIQUE constraints. // CIndex::CIndex(DBCONSTRAINTDESC* pConstraintDesc) : m_bUnique (true), m_bPrimary (false), m_bConstraint (false) { ULONG i; ATLASSERT(pConstraintDesc != NULL); m_strName = pConstraintDesc->pConstraintID->uName.pwszName; m_bConstraint = pConstraintDesc->ConstraintType == DBCONSTRAINTTYPE_UNIQUE; m_bPrimary = pConstraintDesc->ConstraintType == DBCONSTRAINTTYPE_PRIMARYKEY; for(i = 0; i < pConstraintDesc->cColumns; ++i) AddColumn(pConstraintDesc->rgColumnList[i].uName.pwszName, DB_COLLATION_ASC, i + 1); } CIndex::~CIndex() { size_t i, n = m_columns.GetCount(); for(i = 0; i < n; ++i) delete m_columns[i]; } // CIndex::AddColumn // // Adds a new index column to the list // void CIndex::AddColumn(LPCTSTR pszColumnName, short nCollation, ULONG nOrdinal) { CIndexColumn* pIndexColumn = new CIndexColumn(pszColumnName, nCollation, nOrdinal); if(pIndexColumn != NULL) m_columns.Add(pIndexColumn); } // CIndex::FindColumn // // Finds an index column given its name. // Returns the zero-based index of the column or -1 if not found. // int CIndex::FindColumn(LPCTSTR pszColumnName) { int i, n = int(m_columns.GetCount()); for(i = 0; i < n; ++i) { if(wcsicmp(pszColumnName, m_columns[i]->GetName()) == 0) return i; } return -1; }
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 95 ] ] ]
bae5743b1ada950bdb183a20fa8f6f0b4bdf5b7f
928b250a42ffbe1d1c1009b4af7fd3f6a1f46266
/forlijia/ForlijiaEx/ForlijiaEx/ForlijiaExDlg.cpp
53ce24c2995eb099af2df8e218410ee2522b45dd
[]
no_license
jimcoly/comyitian
81044cc6e5d06613e1f2bda8b658457e8337ab8f
6f70e202907be1071d3310bfe1441567ebffed1e
refs/heads/master
2020-05-31T17:54:26.448254
2011-09-01T07:28:07
2011-09-01T07:28:07
33,866,360
0
0
null
null
null
null
GB18030
C++
false
false
12,542
cpp
// ForlijiaExDlg.cpp : implementation file // #include "stdafx.h" #include <sstream> #include <fstream> #include "ForlijiaEx.h" #include "ForlijiaExDlg.h" #include "DlgProxy.h" #include "afxdialogex.h" #include "ConfigurationDlg.h" #include "..\AddressW\utitily.h" #include <algorithm> #include "..\ExcelW\ExcelWrapper.h" #include "exlDistribution.h" #include "..\AddressW\FilterAddress.h" #include "TipDlg.h" #include "Peisong.h" using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CForlijiaExDlg dialog IMPLEMENT_DYNAMIC(CForlijiaExDlg, CDialogEx); CForlijiaExDlg::CForlijiaExDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CForlijiaExDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_pAutoProxy = NULL; } CForlijiaExDlg::~CForlijiaExDlg() { // If there is an automation proxy for this dialog, set // its back pointer to this dialog to NULL, so it knows // the dialog has been deleted. if (m_pAutoProxy != NULL) m_pAutoProxy->m_pDialog = NULL; ExcelWrapper::ReleaseExcel(); } void CForlijiaExDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CForlijiaExDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_CLOSE() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_config, &CForlijiaExDlg::OnBnClickedButtonconfig) ON_BN_CLICKED(IDC_BUTTON_LOAD, &CForlijiaExDlg::OnBnClickedButtonLoad) ON_BN_CLICKED(IDC_BUTTON_save, &CForlijiaExDlg::OnBnClickedButtonsave) ON_BN_CLICKED(IDC_BUTTON_slect, &CForlijiaExDlg::OnBnClickedButtonslect) ON_BN_CLICKED(IDC_BUTTON_Process, &CForlijiaExDlg::OnBnClickedButtonProcess) ON_BN_CLICKED(IDC_BUTTON_test, &CForlijiaExDlg::OnBnClickedButtontest) END_MESSAGE_MAP() // CForlijiaExDlg message handlers BOOL CForlijiaExDlg::OnInitDialog() { CDialogEx::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) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); 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 return TRUE; // return TRUE unless you set the focus to a control } void CForlijiaExDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::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 CForlijiaExDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CForlijiaExDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } // Automation servers should not exit when a user closes the UI // if a controller still holds on to one of its objects. These // message handlers make sure that if the proxy is still in use, // then the UI is hidden but the dialog remains around if it // is dismissed. void CForlijiaExDlg::OnClose() { if (CanExit()) CDialogEx::OnClose(); } void CForlijiaExDlg::OnOK() { if (CanExit()) CDialogEx::OnOK(); } void CForlijiaExDlg::OnCancel() { if (CanExit()) CDialogEx::OnCancel(); } BOOL CForlijiaExDlg::CanExit() { // If the proxy object is still around, then the automation // controller is still holding on to this application. Leave // the dialog around, but hide its UI. if (m_pAutoProxy != NULL) { ShowWindow(SW_HIDE); return FALSE; } return TRUE; } void CForlijiaExDlg::OnBnClickedButtonconfig() { // TODO: Add your control notification handler code here ConfigurationDlg dlg; dlg.DoModal(); } std::string WChar2Ansi( LPCWSTR pwszSrc ) { int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL); if (nLen<= 0) return std::string(""); char* pszDst = new char[nLen]; if (NULL == pszDst) return std::string(""); WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL); pszDst[nLen -1] = 0; std::string strTemp(pszDst); delete [] pszDst; return strTemp; } std::wstring Ansi2Wchar( std::string str ) { int nLen = (int)str.size(); if (nLen==0) { return std::wstring(); } int nwLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), nLen, NULL, 0); WCHAR *temp = new WCHAR[nwLen + 1]; MultiByteToWideChar(CP_ACP, 0, str.c_str(), nLen, temp, nwLen); temp[nwLen] = 0; std::wstring wStrTemp(temp); delete [] temp; return wStrTemp; } void CForlijiaExDlg::OnBnClickedButtonLoad() { //// TODO: Add your control notification handler code here //m_dataCenter.Load(); } void CForlijiaExDlg::OnBnClickedButtonsave() { //// TODO: Add your control notification handler code here //for (auto iter=m_addaddressList.begin();iter!=m_addaddressList.end();iter++) //{ // m_dataCenter.Insert(iter->first,iter->second); //} //m_dataCenter.Save(); } void CForlijiaExDlg::OnBnClickedButtonslect()//读取更新用的 { //FilterAddress fa; //// TODO: Add your control notification handler code here //WCHAR Filter[]=L"excel(*.xls)|*.xls||"; //CFileDialog dlgOpen(TRUE,0,0,OFN_HIDEREADONLY|OFN_FILEMUSTEXIST,(LPCTSTR)Filter,NULL); //if(dlgOpen.DoModal()==IDOK) //{ // CString filePathname=dlgOpen.GetPathName(); // ExlDistribution ed; // if (!ed.Open(filePathname.GetString())) // { // MessageBox(L"打开失败"); // } // addressDataList getdataList=ed.get_sep_list(); // for (addressDataList::iterator iter=getdataList.begin();iter!=getdataList.end();iter++) // { // std::wstring addressstr=iter->first.m_address; // fa.just_filter_sheng_and_Num(addressstr); // StreetData sd(addressstr); // if (!m_dataCenter.IsOther(iter->second.m_UninstallPorts) // && !m_dataCenter.IsTiaojian(addressstr) // && m_dataCenter.check(sd) ) // { // m_addaddressList.insert(std::make_pair(sd,iter->second)); // } // } // ed.Close(); // SetDlgItemInt(IDC_STATIC_addcount,m_addaddressList.size()); // SetDlgItemInt(IDC_STATIC_totalcount,getdataList.size()); //} //else //{ // return ; //} } void CForlijiaExDlg::Process() { #ifdef _MYTest Peisong ps; ps.Process(); #else CTipDlg *tipDlg=new CTipDlg(this); WCHAR Filter[]=L"excel(*.xls)|*.xls||"; CFileDialog dlgOpen(TRUE,0,0,OFN_HIDEREADONLY|OFN_FILEMUSTEXIST,(LPCTSTR)Filter,NULL); if(dlgOpen.DoModal()==IDOK) { tipDlg->Create(IDD_DIALOG_TIP,this); tipDlg->ShowWindow(SW_SHOW); tipDlg->SetTipText(L"处理中..."); CString filePathname=dlgOpen.GetPathName(); CString GetPath=dlgOpen.GetFolderPath(); Peisong ps; ps.Open(filePathname.GetString()); ps.Process(); ps.Save_And_Close(GetPath+L"\\"); tipDlg->CloseWindow(); delete tipDlg; } #endif //CTipDlg *tipDlg=new CTipDlg(this); //WCHAR Filter[]=L"excel(*.xls)|*.xls||"; //CFileDialog dlgOpen(TRUE,0,0,OFN_HIDEREADONLY|OFN_FILEMUSTEXIST,(LPCTSTR)Filter,NULL); //if(dlgOpen.DoModal()==IDOK) //{ // CString filePathname=dlgOpen.GetPathName(); // ExlDistribution ed; // if (!ed.Open(filePathname.GetString())) // { // MessageBox(L"打开失败"); // return; // } // tipDlg->Create(IDD_DIALOG_TIP,this); // tipDlg->ShowWindow(SW_SHOW); // tipDlg->SetTipText(L"正在初始化..."); // m_dataCenter.Load(); // tipDlg->SetTipText(L"正在读取excel数据..."); // ExlDistribution::addressDataListexl getdataList=ed.get_data_list(); // if (!ed.check_Port_is_empty(getdataList)) // { // MessageBox(L"已经有数据"); // return; // } // else // { // tipDlg->SetTipText(L"正在处理..."); // std::list<PortData> pset=_Process(getdataList); // ed.set_data_port(pset); // } // tipDlg->CloseWindow(); // delete tipDlg; // ExcelWrapper::ReleaseExcel(); //} //else //{ // return ; //} } //std::list<PortData> CForlijiaExDlg::_Process( ExlDistribution::addressDataListexl &getdataList ) //{ // //std::list<PortData> portdataList; // //for (auto iter=getdataList.begin();iter!=getdataList.end();iter++) // //{ // // PortData pdata; // // //外敷处理 // // if(m_dataCenter.Tiaojian(iter->sd.m_address,pdata)) // // { // // //continue; // // } // // else // // { // // pdata=m_dataCenter.process(iter->sd.m_address); // // } // // portdataList.push_back(pdata); // //} // //return portdataList; //} void CForlijiaExDlg::OnBnClickedButtonProcess() { // TODO: Add your control notification handler code here Process(); } void CForlijiaExDlg::OnBnClickedButtontest() { // TODO: Add your control notification handler code here //std::wstring str1=L"成都市城区通锦路"; //std::wstring str2=L"四川省成都市武侯区四川大学望江校区财务处"; //std::wstring str3=L"四川省成都市金牛区蜀汉路520号天河馨城4栋1单元1302室"; //std::wstring str4=L"四川省成都市金牛区荷花池市场东1区C排29号"; //std::wstring str5=L"四川省成都市成华区荷花池市场童装市场2期B做 临街30号"; //std::wstring str6=L"四川省成都市锦江区静居寺帕丽湾1栋1单元305"; //std::wstring str7=L"四川省成都市锦江区东大街澳龙名城 10栋1单元3305"; //std::wstring str8=L"四川省成都市青羊区通惠门路锦都花园2栋1单元603"; //std::wstring str9=L"四川省成都市青羊区家园南街成都花园上层3栋3单元903"; //std::wstring str10=L"四川省成都市青羊区通惠门路锦都花园2栋1单元603"; //std::wstring str11=L"四川省成都市金牛区站西桥西街16号3单元31"; //ExlDistribution::addressDataListexl getdataList; //ExlDistribution::exldata ed1={StreetData(str1),PortData()}; //getdataList.push_back(ed1); //ExlDistribution::exldata ed2={StreetData(str2),PortData()}; //getdataList.push_back(ed2); //ExlDistribution::exldata ed3={StreetData(str3),PortData()}; //getdataList.push_back(ed3); //ExlDistribution::exldata ed4={StreetData(str4),PortData()}; //getdataList.push_back(ed4); //ExlDistribution::exldata ed5={StreetData(str5),PortData()}; //getdataList.push_back(ed5); //ExlDistribution::exldata ed6={StreetData(str6),PortData()}; //getdataList.push_back(ed6); //ExlDistribution::exldata ed7={StreetData(str7),PortData()}; //getdataList.push_back(ed7); //ExlDistribution::exldata ed8={StreetData(str8),PortData()}; //getdataList.push_back(ed8); //ExlDistribution::exldata ed9={StreetData(str9),PortData()}; //getdataList.push_back(ed9); //ExlDistribution::exldata ed10={StreetData(str10),PortData()}; //getdataList.push_back(ed10); //ExlDistribution::exldata ed11={StreetData(str11),PortData()}; //getdataList.push_back(ed11); //_Process(getdataList); }
[ "sdy63420@3919fc08-f352-11de-9907-777483041811" ]
[ [ [ 1, 453 ] ] ]
e0d40c26dea2841bbd9d6df8357b558a06106cb4
436c40ae4fd156e1c53a2a9915fdf9ea67c0eca0
/src/tinylog.cpp
0cddf7128c2ca93430e32984c9f6b35a56e10500
[]
no_license
mweiguo/tinylogger
06490d51aa317842ae007f8fc9a265f409b5d6c0
c86675cf926b1e3a2ab1f826b951ca20197d5845
refs/heads/master
2021-01-13T02:06:12.999545
2010-12-29T12:54:08
2010-12-29T12:54:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,170
cpp
#include "tinyLog.h" #include <stdexcept> #include <cstdarg> #include <cstring> #include <cstdlib> // ======================================================================== tinyLog::tinyLog () { _level = info; _showTitle = false; destination ( "stdout" ); format ( "%25(asctime)'%(filename)' : %(lineno) : %(funame)\t:\t" ); _logMsgHandler = 0; } // ======================================================================== tinyLog::~tinyLog () { std::map<std::string,std::ofstream*>::iterator end=_outf.end(), pp; for ( pp=_outf.begin(); pp!=end; ++pp ) { pp->second->close(); delete pp->second; } } // ======================================================================== int tinyLog::MatchKeyword ( const char* p, FmtElement::KEYWORDTYPE& keyword ) { // none, levelno, levelname, pathname, filename, lineno, asctime if ( memcmp ( p, "levelno)", 8 ) == 0 ) { keyword = FmtElement::levelno; return 7; } else if ( memcmp ( p, "levelname)", 10 ) == 0 ) { keyword = FmtElement::levelname; return 9; } else if ( memcmp ( p, "pathname)", 9 ) == 0 ) { keyword = FmtElement::pathname; return 8; } else if ( memcmp ( p, "filename)", 9 ) == 0 ) { keyword = FmtElement::filename; return 8; } else if ( memcmp ( p, "lineno)", 7 ) == 0 ) { keyword = FmtElement::lineno; return 6; } else if ( memcmp ( p, "asctime)", 8 ) == 0 ) { keyword = FmtElement::asctime; return 7; } else if ( memcmp ( p, "funame)", 7 ) == 0 ) { keyword = FmtElement::funame; return 6; } return 0; } // ======================================================================== void tinyLog::format ( const char* str ) { // clear first, means reformat _FmtManager.clear(); // unsaved buffer std::vector<char> usBuffer; // state number int state = 0, align = 0, space = -1; std::stringstream ss; FmtElement::KEYWORDTYPE keyword = FmtElement::none; for ( const char* p=str; ; p++ ) { switch ( state ) { case 0: if ( *p == '%' ) state = 1; else state = 5; usBuffer.push_back ( *p ); break; case 1: if ( *p == '+' ){ state = 2; align = 0; } else if ( *p == '-' ){ state = 46; align = 1; } else if ( isdigit(*p)){ state = 3; ss << *p; } else if ( *p == '(' ) state = 4; else state = 5; usBuffer.push_back ( *p ); break; case 2: if ( isdigit(*p) ){ state = 3; ss << *p; } else if ( *p == '(' ) state = 4; else state = 5; usBuffer.push_back ( *p ); break; case 46: if ( isdigit(*p) ){ state = 3; ss << *p; } else if ( *p == '(' ) state = 4; else state = 5; usBuffer.push_back ( *p ); break; case 3: if ( *p == '(' ){ state = 4; space = atoi ( ss.str().c_str() ); ss.str(""); } else if ( isdigit(*p) ) { state = 3; ss << *p; }else state = 5; usBuffer.push_back ( *p ); break; case 4: { int offset = MatchKeyword ( p, keyword ); if ( offset != 0 ){ std::copy ( p, p+offset, std::back_inserter(usBuffer)); p += offset; state = 44; }else { state = 5; usBuffer.push_back ( *p ); } } break; case 44: // finish keyword { // save command first _FmtManager.push_back ( FmtElement() ); FmtElement& ele = _FmtManager.back(); ele.Keyword = keyword; ele.align = align; ele.space = space; // clear keyword, align and space keyword = FmtElement::none; align = 0; space = -1; ss.str(""); usBuffer.clear(); // read next if ( *p == '%' ) state = 1; else state = 5; usBuffer.push_back ( *p ); break; } case 5: { // save command first for ( std::vector<char>::iterator pp = usBuffer.begin(); pp!=usBuffer.end(); ++pp ) { _FmtManager.push_back ( FmtElement() ); FmtElement& ele = _FmtManager.back(); ele.Keyword = FmtElement::none; ele.ch = *pp; } // clear keyword, align and space keyword = FmtElement::none; align = 0; space = -1; ss.str(""); usBuffer.clear(); // read next if ( *p == '%' ) state = 1; else state = 5; usBuffer.push_back ( *p ); break; } case 45: return; } if ( *p == 0 ) state = 45; } } // ======================================================================== void tinyLog::log ( const char* fname, const char* filename, int lineno, tinyLog::LEVEL l, const char* format, ... ) { if ( !_out ) throw std::invalid_argument("invalid destination"); if ( _level==none || l > _level ) return; if ( _showTitle ) { const char* szMsgTitle[] = {"[ERROR]","[WARNING]","[INFO]","[DEBUG]"}; (*_out[l]) << std::left << std::setw(12) << szMsgTitle[l]; for ( std::vector<FmtElement>::iterator pp=_FmtManager.begin(); pp!=_FmtManager.end(); ++pp ) { switch ( pp->Keyword ) { case FmtElement::none: (*_out[l]) << pp->ch; break; case FmtElement::levelno: break; case FmtElement::levelname: break; case FmtElement::pathname: break; case FmtElement::filename: if ( pp->space != 32767 ) (*_out[l]) << std::setw(pp->space); if ( pp->align == 0 ) (*_out[l]) << std::left; else (*_out[l]) << std::right; (*_out[l]) << filename; break; case FmtElement::lineno: if ( pp->space != 32767 ) (*_out[l]) << std::setw(pp->space); if ( pp->align == 0 ) (*_out[l]) << std::left; else (*_out[l]) << std::right; (*_out[l]) << lineno; break; case FmtElement::funame: if ( pp->space != 32767 ) (*_out[l]) << std::setw(pp->space); if ( pp->align == 0 ) (*_out[l]) << std::left; else (*_out[l]) << std::right; (*_out[l]) << fname; break; case FmtElement::asctime: { if ( pp->space != 32767 ) (*_out[l]) << std::setw(pp->space); if ( pp->align == 0 ) (*_out[l]) << std::left; else (*_out[l]) << std::right; time_t tm; time ( &tm ); std::string stm = ctime ( &tm ); std::string::size_type pos; if ( std::string::npos != (pos=stm.find_last_of ( '\n' )) ) stm.replace ( pos, pos+1, "" ); (*_out[l]) << stm; } break; } } } char buffer[512] = {0}; va_list vl; va_start ( vl, format ); vsprintf ( buffer, format, vl ); va_end ( vl ); // (*_out[l]) << buffer << std::endl; (*_out[l]) << buffer; if ( _logMsgHandler ) { switch (l) { case info: _logMsgHandler ("info", buffer ); break; case warning: _logMsgHandler ("warning", buffer ); break; case error: _logMsgHandler ("error", buffer ); break; case debug: _logMsgHandler ("debug", buffer ); break; default: break; } } } // ======================================================================== void tinyLog::destination ( LEVEL l, const char* dest ) { if ( l == none ) return; if ( strcmp ( dest, "stdout" )==0 ){ _out[l] = &std::cout; }else if ( strcmp ( dest, "stderr" )==0 ){ _out[l] = &std::cerr; } else { std::ofstream o; if ( _outf.find ( dest ) == _outf.end() ) { _outf[dest] = new std::ofstream(dest); } _out[l] = _outf[dest]; } } // ========================================================================
[ [ [ 1, 276 ] ] ]
09be4f898882a8c90b6a77e30f01827acc2716f6
15730792376cc6ffa986d6bcb88ba9fd7acf9369
/raytracer3.0.06.no_rec.samp/openCLcode.cpp
81e3afce852bbf835232f16143147e793cebe1b4
[]
no_license
markrosoft/se-195-project-ray-tracer
0b8c14422e52aa5ede17a158c6ef7521934ce029
0712d443be8c0da986ab1315a257740fbb3a653d
refs/heads/master
2021-01-10T07:14:00.513175
2011-11-18T06:42:15
2011-11-18T06:42:15
43,331,160
0
0
null
null
null
null
UTF-8
C++
false
false
16,020
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <math.h> #include "raytracer.h" #include "scene.h" #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif extern int useGPU; static int forceWorkSize = 0; std::string outputLine1 = "1:"; std::string outputLine2 = "2:"; std::string outputLine3 = "3:"; std::string outputLine4 = "4:"; std::string outputLine5 = "5:"; std::string outputLine6 = "6:"; std::string outputLine7 = "7:"; std::string outputLine8 = "8:"; std::string outputLine9 = "9:"; /* OpenCL variables */ static cl_context context; static cl_mem colorBuffer; static cl_mem m_DestBuffer; static cl_mem primitiveBuffer; static cl_mem tracedRayBuffer; static cl_mem cameraBuffer; static cl_command_queue commandQueue; static cl_program program; static cl_kernel kernel; static unsigned int workGroupSize = 1; static char *kernelFileName = "openCLcode.cl"; extern int m_Width, m_Height; extern Pixel* m_Dest; //extern vector3 * camera; static vector3 * colors; static void FreeBuffers() { cl_int status = clReleaseMemObject(m_DestBuffer); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to release OpenCL pixel buffer: %d\n", status); exit(-1); } status = clReleaseMemObject(primitiveBuffer); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to release OpenCL pixel buffer: %d\n", status); exit(-1); } } void AllocateBuffers() { const int pixelCount = m_Width * m_Height; cl_int status; cl_uint sizeBytes = sizeof(unsigned int) * pixelCount; m_DestBuffer = clCreateBuffer( context, CL_MEM_READ_WRITE, sizeBytes, NULL, &status); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to create OpenCL output buffer: %d\n", status); exit(-1); } status = clEnqueueWriteBuffer( commandQueue, m_DestBuffer, CL_TRUE, 0, sizeBytes, m_Dest, 0, NULL, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to write the OpenCL seeds buffer: %d\n", status); exit(-1); } int primCount = m_Scene->m_Primitives; sizeBytes = sizeof(Primitive) * primCount; primitiveBuffer = clCreateBuffer( context, CL_MEM_READ_WRITE, sizeBytes, NULL, &status); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to create OpenCL scene buffer: %d\n", status); exit(-1); } status = clEnqueueWriteBuffer( commandQueue, primitiveBuffer, CL_TRUE, 0, sizeBytes, m_Scene->m_Primitive, 0, NULL, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to write the OpenCL scene buffer: %d\n", status); exit(-1); } } static char *ReadSources(const char *fileName) { FILE *file = fopen(fileName, "rb"); if (!file) { fprintf(stderr, "Failed to open file '%s'\n", fileName); exit(-1); } if (fseek(file, 0, SEEK_END)) { fprintf(stderr, "Failed to seek file '%s'\n", fileName); exit(-1); } long size = ftell(file); if (size == 0) { fprintf(stderr, "Failed to check position on file '%s'\n", fileName); exit(-1); } rewind(file); char *src = (char *)malloc(sizeof(char) * size + 1); if (!src) { fprintf(stderr, "Failed to allocate memory for file '%s'\n", fileName); exit(-1); } fprintf(stderr, "Reading file '%s' (size %ld bytes)\n", fileName, size); size_t res = fread(src, 1, sizeof(char) * size, file); if (res != sizeof(char) * size) { fprintf(stderr, "Failed to read file '%s' (read %ld)\n", fileName, res); exit(-1); } src[size] = '\0'; /* NULL terminated */ fclose(file); return src; } char* openCLcode() { cl_device_type dType; char buffer[1024]; if (useGPU) dType = CL_DEVICE_TYPE_GPU; else dType = CL_DEVICE_TYPE_CPU; // Select the platform cl_uint numPlatforms; cl_platform_id platform = NULL; cl_int status = clGetPlatformIDs(0, NULL, &numPlatforms); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL platforms\n"); exit(-1); } if (numPlatforms > 0) { cl_platform_id *platforms = (cl_platform_id *)malloc(sizeof(cl_platform_id) * numPlatforms); status = clGetPlatformIDs(numPlatforms, platforms, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL platform IDs\n"); exit(-1); } unsigned int i; for (i = 0; i < numPlatforms; ++i) { char pbuf[100]; status = clGetPlatformInfo(platforms[i], CL_PLATFORM_VENDOR, sizeof(pbuf), pbuf, NULL); status = clGetPlatformIDs(numPlatforms, platforms, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL platform IDs\n"); exit(-1); } fprintf(stderr, "OpenCL Platform %d: %s\n", i, pbuf); sprintf_s(buffer, "OpenCL Platform %d: %s ", i, pbuf); outputLine1 += buffer; } platform = platforms[0]; free(platforms); } // Select the device cl_device_id devices[32]; cl_uint deviceCount; status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 32, devices, &deviceCount); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device IDs\n"); exit(-1); } int deviceFound = 0; cl_device_id selectedDevice; unsigned int i; for (i = 0; i < deviceCount; ++i) { cl_device_type type = 0; status = clGetDeviceInfo(devices[i], CL_DEVICE_TYPE, sizeof(cl_device_type), &type, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } char *stype; switch (type) { case CL_DEVICE_TYPE_ALL: stype = "TYPE_ALL"; break; case CL_DEVICE_TYPE_DEFAULT: stype = "TYPE_DEFAULT"; break; case CL_DEVICE_TYPE_CPU: stype = "TYPE_CPU"; if (!useGPU && !deviceFound) { selectedDevice = devices[i]; deviceFound = 1; } break; case CL_DEVICE_TYPE_GPU: stype = "TYPE_GPU"; if (useGPU && !deviceFound) { selectedDevice = devices[i]; deviceFound = 1; } break; default: stype = "TYPE_UNKNOWN"; break; } fprintf(stderr, "OpenCL Device %d: Type = %s\n", i, stype); sprintf_s(buffer, "OpenCL Device %d: Type = %s ", i, stype); outputLine2 += buffer; char buf[256]; status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(char[256]), &buf, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } fprintf(stderr, "OpenCL Device %d: Name = %s\n", i, buf); sprintf_s(buffer, "OpenCL Device %d: Name = %s ", i, buf); outputLine3 += buffer; cl_uint units = 0; status = clGetDeviceInfo(devices[i], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &units, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } fprintf(stderr, "OpenCL Device %d: Compute units = %u\n", i, units); sprintf_s(buffer, "OpenCL Device %d: Compute units = %u ", i, units); outputLine4 += buffer; size_t gsize = 0; status = clGetDeviceInfo(devices[i], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &gsize, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } fprintf(stderr, "OpenCL Device %d: Max. work group size = %d\n", i, (unsigned int)gsize); sprintf_s(buffer, "OpenCL Device %d: Max. work group size = %d ", i, (unsigned int)gsize); outputLine5 += buffer; } if (!deviceFound) { fprintf(stderr, "Unable to select an appropriate device\n"); exit(-1); } // Create the context cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties) platform, 0 }; cl_context_properties *cprops = (NULL == platform) ? NULL : cps; context = clCreateContext( cprops, 1, &selectedDevice, NULL, NULL, &status); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to open OpenCL context\n"); exit(-1); } /* Get the device list data */ size_t deviceListSize; status = clGetContextInfo( context, CL_CONTEXT_DEVICES, 32, devices, &deviceListSize); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL context info: %d\n", status); exit(-1); } /* Print devices list */ for (i = 0; i < deviceListSize / sizeof(cl_device_id); ++i) { cl_device_type type = 0; status = clGetDeviceInfo(devices[i], CL_DEVICE_TYPE, sizeof(cl_device_type), &type, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } char *stype; switch (type) { case CL_DEVICE_TYPE_ALL: stype = "TYPE_ALL"; break; case CL_DEVICE_TYPE_DEFAULT: stype = "TYPE_DEFAULT"; break; case CL_DEVICE_TYPE_CPU: stype = "TYPE_CPU"; break; case CL_DEVICE_TYPE_GPU: stype = "TYPE_GPU"; break; default: stype = "TYPE_UNKNOWN"; break; } fprintf(stderr, "[SELECTED] OpenCL Device %d: Type = %s\n", i, stype); sprintf_s(buffer, "[SELECTED] OpenCL Device %d: Type = %s ", i, stype); outputLine6 += buffer; char buf[256]; status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(char[256]), &buf, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } fprintf(stderr, "[SELECTED] OpenCL Device %d: Name = %s\n", i, buf); sprintf_s(buffer, "[SELECTED] OpenCL Device %d: Name = %s ", i, buf); outputLine7 += buffer; cl_uint units = 0; status = clGetDeviceInfo(devices[i], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &units, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } fprintf(stderr, "[SELECTED] OpenCL Device %d: Compute units = %u\n", i, units); sprintf_s(buffer, "[SELECTED] OpenCL Device %d: Compute units = %u ", i, units); outputLine8 += buffer; size_t gsize = 0; status = clGetDeviceInfo(devices[i], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &gsize, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL device info: %d\n", status); exit(-1); } fprintf(stderr, "[SELECTED] OpenCL Device %d: Max. work group size = %d\n", i, (unsigned int)gsize); sprintf_s(buffer, "[SELECTED] OpenCL Device %d: Max. work group size = %d ", i, (unsigned int)gsize); outputLine9 += buffer; } cl_command_queue_properties prop = 0; commandQueue = clCreateCommandQueue( context, devices[0], prop, &status); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to create OpenCL command queue: %d\n", status); exit(-1); } /*------------------------------------------------------------------------*/ // here was the the create // sphereBuffer, // cameraBuffer /*------------------------------------------------------------------------*/ /* Create the kernel program */ const char *sources = ReadSources(kernelFileName); program = clCreateProgramWithSource( context, 1, &sources, NULL, &status); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to open OpenCL kernel sources: %d\n", status); exit(-1); } #ifdef __APPLE__ status = clBuildProgram(program, 1, devices, "-I. -D__APPLE__", NULL, NULL); #else status = clBuildProgram(program, 1, devices, "-I. ", NULL, NULL); #endif if (status != CL_SUCCESS) { fprintf(stderr, "Failed to build OpenCL kernel: %d\n", status); size_t retValSize; status = clGetProgramBuildInfo( program, devices[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &retValSize); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL kernel info size: %d\n", status); exit(-1); } char *buildLog = (char *)malloc(retValSize + 1); status = clGetProgramBuildInfo( program, devices[0], CL_PROGRAM_BUILD_LOG, retValSize, buildLog, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL kernel info: %d\n", status); exit(-1); } buildLog[retValSize] = '\0'; fprintf(stderr, "OpenCL Programm Build Log: %s\n", buildLog); exit(-1); } kernel = clCreateKernel(program, "raytrace_kernel", &status); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to create OpenCL kernel: %d\n", status); exit(-1); } // LordCRC's patch for better workGroupSize size_t gsize = 0; status = clGetKernelWorkGroupInfo(kernel, devices[0], CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &gsize, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to get OpenCL kernel work group size info: %d\n", status); exit(-1); } workGroupSize = (unsigned int) gsize; fprintf(stderr, "OpenCL Device 0: kernel work group size = %d\n", workGroupSize); if (forceWorkSize > 0) { fprintf(stderr, "OpenCL Device 0: forced kernel work group size = %d\n", forceWorkSize); workGroupSize = forceWorkSize; } char* realOutput = _strdup(outputLine1.c_str()); return realOutput; } void ExecuteKernel() { /* Enqueue a kernel run call */ size_t globalThreads[1]; globalThreads[0] = m_Width * m_Height; if (globalThreads[0] % workGroupSize != 0) globalThreads[0] = (globalThreads[0] / workGroupSize + 1) * workGroupSize; size_t localThreads[1]; localThreads[0] = workGroupSize; cl_int status = clEnqueueNDRangeKernel( commandQueue, kernel, 1, NULL, globalThreads, localThreads, 0, NULL, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to enqueue OpenCL work: %d\n", status); exit(-1); } } void SetKernelArguments(){ /* Set kernel arguments */ cl_int status = clSetKernelArg( kernel, 0, sizeof(int), (void *)&m_Height); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to set OpenCL arg. #0: %d\n", status); exit(-1); } status = clSetKernelArg( kernel, 1, sizeof(int), (void *)&m_Width); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to set OpenCL arg. #1: %d\n", status); exit(-1); } status = clSetKernelArg( kernel, 2, sizeof(cl_mem), (void *)&m_DestBuffer); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to set OpenCL arg. #2: %d\n", status); exit(-1); } status = clSetKernelArg( kernel, 3, sizeof(cl_mem), (void *)&primitiveBuffer); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to set OpenCL arg. #3: %d\n", status); exit(-1); } int primitiveCount = m_Scene->m_Primitives; status = clSetKernelArg( kernel, 4, sizeof(int), (void *)&primitiveCount); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to set OpenCL arg. #4: %d\n", status); exit(-1); } /*status = clSetKernelArg( kernel, 5, sizeof(cl_mem), (void *)&colorBuffer); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to set OpenCL arg. #5: %d\n", status); exit(-1); }*/ } void ReadKernelBuffer(){ /* Enqueue readBuffer */ cl_int status = clEnqueueReadBuffer( commandQueue, m_DestBuffer, CL_TRUE, 0, m_Width * m_Height * sizeof(unsigned int), m_Dest, 0, NULL, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Failed to read the OpenCL pixel buffer: %d\n", status); exit(-1); } }
[ [ [ 1, 643 ] ] ]
eb6993063b918d97a06216927069259a8248be30
a6c9a8f361863ad66a54d15e0da04f356f4f76e9
/test/filer/mfttest/wv/MFTReader/stdafx.cpp
1e0489381d447b70828fc168888b2a69346a163a
[]
no_license
mohammadul/addondev
2e47505112cf4c506e4523572d2dbcfabfd23496
ee18da2abaafebca565792c29d698cc87bb233ca
refs/heads/master
2016-09-06T08:54:57.642723
2011-10-04T16:42:38
2011-10-04T16:42:38
42,942,733
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
384
cpp
// stdafx.cpp : 標準インクルード MFTReader.pch のみを // 含むソース ファイルは、プリコンパイル済みヘッダーになります。 // stdafx.obj にはプリコンパイル済み型情報が含まれます。 #include "stdafx.h" // TODO: このファイルではなく、STDAFX.H で必要な // 追加ヘッダーを参照してください。
[ "s@localhost" ]
[ [ [ 1, 8 ] ] ]
23b9fcbbc7c5636fbcca989130bd157c8931d8c5
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/face/msnface/ImageTabWnd.cpp
c352a6649073013d1c125b39f3db566bacb0caff
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
GB18030
C++
false
false
11,201
cpp
// ImageTabWnd.cpp : implementation file // #include "stdafx.h" #include "Messenger.h" #include "ImageTabWnd.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CImageTabWnd CImageTabWnd::CImageTabWnd() { m_pBitmapTab = NULL; m_pRectTab = NULL; m_nTabCount = 0; m_nCurrentIndex = 0; for(int i=0; i<MAX_DIALOG; i++) m_pTabDialog[i] = NULL; } CImageTabWnd::~CImageTabWnd() { if (m_pRectTab) delete []m_pRectTab; if (m_pBitmapTab) delete []m_pBitmapTab; } BEGIN_MESSAGE_MAP(CImageTabWnd, CWnd) //{{AFX_MSG_MAP(CImageTabWnd) ON_WM_PAINT() ON_WM_SETCURSOR() ON_WM_LBUTTONDOWN() ON_WM_SIZE() ON_WM_TIMER() ON_WM_ERASEBKGND() ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CImageTabWnd message handlers void CImageTabWnd::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: Add your message handler code here CRect rcClient; GetClientRect(&rcClient); CDC m_MemDC; m_MemDC.CreateCompatibleDC(&dc); CBitmap btScreen; btScreen.CreateCompatibleBitmap(&dc, rcClient.Width(), rcClient.Height()); m_MemDC.SelectObject(&btScreen); btScreen.DeleteObject(); //画背景 DrawRangeImage(&m_BitmapBk, &m_MemDC, rcClient); DrawRangeImage(&m_BitmapLeft, &m_MemDC, CRect(0, 0, m_szBitmapLeft.cx, rcClient.Height())); DrawRangeImage(&m_BitmapRight, &m_MemDC, CRect(rcClient.Width()-m_szBitmapRight.cx, 2, rcClient.Width(), rcClient.Height()-m_szBitmapBottom.cy)); DrawRangeImage(&m_BitmapTop, &m_MemDC, CRect(0, 0, rcClient.Width()-2, m_szBitmapTop.cy)); //画Tab DrawPosImage(&m_pBitmapTab[m_nCurrentIndex], &m_MemDC, CPoint(0, 0)); //画Bottom DrawRangeImage(&m_BitmapLeft, &m_MemDC, CRect(0, rcClient.Height()-m_szBitmapBottom.cy, 2*m_szBitmapLeft.cx, rcClient.Height())); DrawRangeImage(&m_BitmapBottom, &m_MemDC, CRect(m_szBitmapLeft.cx-1, rcClient.Height()-m_szBitmapBottom.cy, rcClient.Width()-1, rcClient.Height())); //画广告图片 //CPoint ptAd; //if ((rcClient.Width()-m_szBitmapAd.cx)/2 >0) // ptAd = CPoint((rcClient.Width()-m_szBitmapAd.cx)/2, rcClient.Height()-(m_szBitmapBottom.cy+m_szBitmapAd.cy)/2+1); //else // ptAd = CPoint(0, rcClient.Height()-(m_szBitmapBottom.cy+m_szBitmapAd.cy)/2+1); //DrawPosImage(&m_BitmapAd, &m_MemDC, ptAd); //画到显示器上 dc.BitBlt(rcClient.left, rcClient.top, rcClient.Width(), rcClient.Height(), &m_MemDC, 0, 0, SRCCOPY); m_MemDC.DeleteDC(); // Do not call CWnd::OnPaint() for painting messages } void CImageTabWnd::SetTabCount(int nCount) { m_nTabCount = nCount; if (m_pBitmapTab) delete []m_pRectTab; m_pBitmapTab = new CBitmap[m_nTabCount]; if (m_pRectTab) delete []m_pRectTab; m_pRectTab = new CRect[m_nTabCount]; } void CImageTabWnd::SetTabImage(int nIndex, CString strName) { ASSERT(nIndex < m_nTabCount); HBITMAP hBitmap = NULL; hBitmap = (HBITMAP)::LoadImage(NULL, strName, IMAGE_BITMAP, 0, 0, LR_DEFAULTSIZE|LR_LOADFROMFILE); ASSERT(hBitmap); if (m_pBitmapTab[nIndex].m_hObject) m_pBitmapTab[nIndex].Detach(); m_pBitmapTab[nIndex].Attach(hBitmap); } void CImageTabWnd::SetTabImage(int nIndex, UINT nID) { ASSERT(nIndex < m_nTabCount); if (m_pBitmapTab[nIndex].m_hObject) m_pBitmapTab[nIndex].Detach(); m_pBitmapTab[nIndex].LoadBitmap(nID); } void CImageTabWnd::SetTabRect(int nIndex, CRect rc) { ASSERT(nIndex < m_nTabCount); m_pRectTab[nIndex] = rc; } void CImageTabWnd::SetImage(CBitmap &bitmap, CString strName) { HBITMAP hBitmap = NULL; hBitmap = (HBITMAP)::LoadImage(NULL, strName, IMAGE_BITMAP, 0, 0, LR_DEFAULTSIZE|LR_LOADFROMFILE); ASSERT(hBitmap); if (bitmap.m_hObject) bitmap.Detach(); bitmap.Attach(hBitmap); } void CImageTabWnd::SetImage(CBitmap &bitmap, UINT nID) { if (bitmap.m_hObject) bitmap.Detach(); bitmap.LoadBitmap(nID); } void CImageTabWnd::SetTopImage(CString strName) { SetImage(m_BitmapTop, strName); SetImageSize(&m_BitmapTop, m_szBitmapTop); } void CImageTabWnd::SetTopImage(UINT nID) { SetImage(m_BitmapTop, nID); SetImageSize(&m_BitmapTop, m_szBitmapTop); } void CImageTabWnd::SetBottomImage(CString strName) { SetImage(m_BitmapBottom, strName); SetImageSize(&m_BitmapBottom, m_szBitmapBottom); } void CImageTabWnd::SetBottomImage(UINT nID) { SetImage(m_BitmapBottom, nID); SetImageSize(&m_BitmapBottom, m_szBitmapBottom); } void CImageTabWnd::SetLeftImage(CString strName) { SetImage(m_BitmapLeft, strName); SetImageSize(&m_BitmapLeft, m_szBitmapLeft); } void CImageTabWnd::SetLeftImage(UINT nID) { SetImage(m_BitmapLeft, nID); SetImageSize(&m_BitmapLeft, m_szBitmapLeft); } void CImageTabWnd::SetRightImage(CString strName) { SetImage(m_BitmapRight, strName); SetImageSize(&m_BitmapRight, m_szBitmapRight); } void CImageTabWnd::SetRightImage(UINT nID) { SetImage(m_BitmapRight, nID); SetImageSize(&m_BitmapRight, m_szBitmapRight); } void CImageTabWnd::SetBkImage(CString strName) { SetImage(m_BitmapBk, strName); SetImageSize(&m_BitmapBk, m_szBitmapBk); } void CImageTabWnd::SetBkImage(UINT nID) { SetImage(m_BitmapBk, nID); SetImageSize(&m_BitmapBk, m_szBitmapBk); } void CImageTabWnd::SetAdImage(CString strName) { SetImage(m_BitmapAd, strName); SetImageSize(&m_BitmapAd, m_szBitmapAd); } void CImageTabWnd::SetAdImage(UINT nID) { SetImage(m_BitmapAd, nID); SetImageSize(&m_BitmapAd, m_szBitmapAd); } void CImageTabWnd::DrawRangeImage(CBitmap *pBitmap, CDC *pDC, CRect rc) { CDC MemDC; BITMAP bm; pBitmap->GetBitmap(&bm); int li_Width = bm.bmWidth; int li_Height = bm.bmHeight; MemDC.CreateCompatibleDC(pDC); CBitmap* pOldBitmap = MemDC.SelectObject(pBitmap); int x=rc.left; int y=rc.top; while (y < (rc.Height()+rc.top)) { while(x < (rc.Width()+rc.left)) { pDC->BitBlt(x, y, li_Width, li_Height, &MemDC, 0, 0, SRCCOPY); x += li_Width; } x = rc.left; y += li_Height; } MemDC.SelectObject(pOldBitmap); MemDC.DeleteDC(); } void CImageTabWnd::DrawPosImage(CBitmap *pBitmap, CDC *pDC, CPoint pt) { CDC MemDC; MemDC.CreateCompatibleDC(pDC); CBitmap *pOldBitmap = (CBitmap*)MemDC.SelectObject(pBitmap); BITMAP bm; pBitmap->GetBitmap(&bm); int li_Width = bm.bmWidth; int li_Height = bm.bmHeight; pDC->BitBlt(pt.x, pt.y, li_Width, li_Height, &MemDC, 0, 0, SRCCOPY); MemDC.SelectObject(pOldBitmap); MemDC.DeleteDC(); } BOOL CImageTabWnd::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // TODO: Add your message handler code here and/or call default CPoint pt; GetCursorPos(&pt); ScreenToClient(&pt); for(int i=0; i<m_nTabCount; i++) { if (m_pRectTab[i].PtInRect(pt) && m_nCurrentIndex != i) { SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(32649))); return TRUE; } } return CWnd::OnSetCursor(pWnd, nHitTest, message); } void CImageTabWnd::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default for(int i=0; i<m_nTabCount; i++) { if (m_pRectTab[i].PtInRect(point) && m_nCurrentIndex != i) { m_nCurrentIndex = i; ShowDialog(); Invalidate(); break; } } CWnd::OnLButtonDown(nFlags, point); } void CImageTabWnd::SetImageSize(CBitmap *pBitmap, CSize &sz) { BITMAP bm; pBitmap->GetBitmap(&bm); sz = CSize(bm.bmWidth, bm.bmHeight); } void CImageTabWnd::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); // TODO: Add your message handler code here CRect rcClient; GetClientRect(&rcClient); for(int i=0; i<m_nTabCount; i++) { if (m_pTabDialog[i]) { m_rcDialog = CRect(m_szBitmapLeft.cx+DIALOG_MARGIN, m_szBitmapTop.cy+DIALOG_MARGIN, rcClient.Width()-m_szBitmapRight.cx-DIALOG_MARGIN, rcClient.Height() - m_szBitmapBottom.cy - DIALOG_MARGIN); if (m_pTabDialog[i]->GetSafeHwnd()) { m_pTabDialog[i]->MoveWindow(m_rcDialog, FALSE); UpdateTabWnd(); } } } ShowDialog(); } void CImageTabWnd::SetTabWnd(int nIndex, CDialog *pDlg) { ASSERT(nIndex < m_nTabCount); m_pTabDialog[nIndex] = pDlg; } void CImageTabWnd::ShowDialog() { CRect rcClient; GetClientRect(&rcClient); for(int i=0; i<m_nTabCount; i++) { if (m_pTabDialog[i] && i!= m_nCurrentIndex) { m_pTabDialog[i]->ShowWindow(SW_HIDE); } } if (m_pTabDialog[m_nCurrentIndex]) { m_pTabDialog[m_nCurrentIndex]->ShowWindow(SW_SHOW); m_pTabDialog[m_nCurrentIndex]->SetFocus(); } } void CImageTabWnd::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default if (m_BitmapAd.m_hObject) { CRect rcClient; GetClientRect(&rcClient); CRect rcAd; if ((rcClient.Width()-m_szBitmapAd.cx)/2 >0) rcAd = CRect((rcClient.Width()-m_szBitmapAd.cx)/2-2, rcClient.Height()-(m_szBitmapBottom.cy+m_szBitmapAd.cy)/2, (rcClient.Width()+m_szBitmapAd.cx)/2+4, rcClient.Height()+(m_szBitmapBottom.cy-m_szBitmapAd.cy)/2+2); else rcAd = CRect(0, rcClient.Height()-(m_szBitmapBottom.cy+m_szBitmapAd.cy)/2+1, m_szBitmapAd.cx, rcClient.Height()+(m_szBitmapBottom.cy-m_szBitmapAd.cy)/2); InvalidateRect(rcAd, FALSE); } CWnd::OnTimer(nIDEvent); } void CImageTabWnd::PreSubclassWindow() { // TODO: Add your specialized code here and/or call the base class SetTimer(1, 1000, NULL); CWnd::PreSubclassWindow(); } BOOL CImageTabWnd::OnEraseBkgnd(CDC* pDC) { // TODO: Add your message handler code here and/or call default return TRUE; return CWnd::OnEraseBkgnd(pDC); } void CImageTabWnd::UpdateTabWnd() { CRect rcClient; GetClientRect(&rcClient); //TOP InvalidateRect(CRect(0, 0, rcClient.Width(), TITLE_HEIGHT)); //BOTTOM InvalidateRect(CRect(0, rcClient.Height()-m_szBitmapBottom.cy-DIALOG_MARGIN, rcClient.Width(), rcClient.Height())); //LEFT InvalidateRect(CRect(0, 0, m_szBitmapLeft.cx+DIALOG_MARGIN, rcClient.Height())); //RIGHT InvalidateRect(CRect(rcClient.Width()-m_szBitmapRight.cx-DIALOG_MARGIN, 0, rcClient.Width(), rcClient.Height())); } void CImageTabWnd::SetToolTip(int nIndex, CString strTips) { ASSERT(nIndex < m_nTabCount); ASSERT(m_pRectTab[nIndex].IsRectEmpty() == FALSE); m_ToolTip.AddTool(this, strTips, m_pRectTab[nIndex], 12345678); m_ToolTip.SetTipBkColor(RGB(231,236,247)); m_ToolTip.Activate(TRUE); } BOOL CImageTabWnd::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class if (m_ToolTip.GetSafeHwnd()) m_ToolTip.RelayEvent( pMsg ); return CWnd::PreTranslateMessage(pMsg); } int CImageTabWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here if (!m_ToolTip.Create(this)) return -1; //ModifyStyleEx(0, WS_EX_CLIENTEDGE); return 0; }
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 450 ] ] ]
f3e2811be7be46d47f16cc4cc68e33c28a17dee8
c436a5d7cdbebc04e5d202c6bb3c83448a5db529
/QtOgre/include/LogModelSortFilterProxy.h
b8b44e4b968f36f9d54e5b8d4587ea76e711b6cc
[ "Zlib" ]
permissive
pvdk/QtOgreFramework
89132be5c0ea4f11a43abf4632577ebb21a0b10a
e32bafae2b0c1a8af9700efea61ff351866bb1d5
refs/heads/master
2021-01-23T08:15:38.575879
2010-11-15T21:39:06
2010-11-15T21:39:06
1,680,419
0
1
null
null
null
null
UTF-8
C++
false
false
624
h
#ifndef QTOGRE_LOGMODELSORTFILTERPROXY_H_ #define QTOGRE_LOGMODELSORTFILTERPROXY_H_ #include <QSortFilterProxyModel> namespace QtOgre { class LogModelSortFilterProxy : public QSortFilterProxyModel { Q_OBJECT public: LogModelSortFilterProxy(QObject *parent = 0); void setShowLineAndFile(bool show); void setVisisbleLevels(int levelBitmask); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; bool filterAcceptsColumn(int sourceColumn, const QModelIndex &sourceParent) const; private: bool mShowLineAndFile; int mVisibleLevels; }; } #endif
[ "esuvs@2eb06014-c84b-0410-ad17-af83cdd4cbf1" ]
[ [ [ 1, 25 ] ] ]
9cc1bd22bfc4d3b0a92a45b7176f6c36ff020c8e
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEAudio/SESceneGraph/SESoundBuffer.h
490902e8ab4656131bb730e25a33fdb0f8c42500
[]
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,091
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_SoundBuffer_H #define Swing_SoundBuffer_H #include "SEAudioLIB.h" #include "SEObject.h" #include "SEAudioBindable.h" #include "SEWave.h" namespace Swing { //---------------------------------------------------------------------------- // Description:wave数据可以作为音频资源绑定给音频设备. // Author:Sun Che // Date:20090618 //---------------------------------------------------------------------------- class SE_AUDIO_API SESoundBuffer : public SEObject, public SEAudioBindable { SE_DECLARE_RTTI; SE_DECLARE_NAME_ID; SE_DECLARE_STREAM; public: SESoundBuffer(int iWCount, SEWave** apWaves); SESoundBuffer(const SESoundBuffer* pSBuffer); virtual ~SESoundBuffer(void); // 成员访问. inline int GetWaveCount(void) const; inline SEWave* GetWave(int i); inline const SEWave* GetWave(int i) const; protected: // streaming support SESoundBuffer(void); void* m_pID; // wave数据. std::vector<SEWavePtr> m_Waves; }; typedef SESmartPointer<SESoundBuffer> SESoundBufferPtr; #include "SESoundBuffer.inl" } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 69 ] ] ]
eb56c70c4f7c50060efcbcde3dd78195fd327637
8e4d21a99d0ce5413eab7a083544aff9f944b26f
/include/NthContourProcess.h
3f36d63ccbe48997657c5e8e67af4688abb9958a
[]
no_license
wangjunbao/nontouchsdk
957612b238b8b221b4284efb377db220bd41186a
81ab8519ea1af45dbb7ff66c6784961f14f9930c
refs/heads/master
2021-01-23T13:57:20.020732
2010-10-31T12:03:49
2010-10-31T12:03:49
34,656,556
0
0
null
null
null
null
UTF-8
C++
false
false
393
h
/* * NthContourProcess.h * CopyRight @South China Institute of Software Engineering,.GZU * Author: * 2010/10/20 */ #ifndef NTHCONTROLLER_H #define NTHCONTROLLER_H #ifdef DLL_FILE class _declspec(dllexport) NthContourProcess #else class _declspec(dllimport) NthContourProcess #endif { public: NthContourProcess(void); ~NthContourProcess(void); }; #endif
[ "tinya0913@6b3f5b0f-ac10-96f7-b72e-cc4b20d3e213" ]
[ [ [ 1, 24 ] ] ]
c805729de34e57dcd517ac77a9d5219deebe8b15
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleAffectors/ParticleUniverseLinearForceAffectorFactory.h
58cf2cf36a4e36a22f16b65c17fd0b1ea866384c
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
1,733
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_LINEAR_FORCE_AFFECTOR_FACTORY_H__ #define __PU_LINEAR_FORCE_AFFECTOR_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseForceAffectorTokens.h" #include "ParticleUniverseLinearForceAffector.h" #include "ParticleUniverseAffectorFactory.h" namespace ParticleUniverse { /** Factory class responsible for creating the LinearForceAffector. */ class _ParticleUniverseExport LinearForceAffectorFactory : public ParticleAffectorFactory { public: LinearForceAffectorFactory(void) {}; virtual ~LinearForceAffectorFactory(void) {}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType() const { return "LinearForce"; } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { return _createAffector<LinearForceAffector>(); } /** See ParticleAffectorFactory */ virtual void setupTokenDefinitions(ITokenRegister* tokenRegister){} protected: ForceAffectorTokens mForceAffectorTokens; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 55 ] ] ]
4f408dfa9ef3f2f9bd0b92da01723089b084bfb6
afa89ae5cc719f0343d2a9df8172200ad6524f57
/CCV-COT/addons/ofxNCore/src/Modules/ofxNCoreVision.cpp
7292b49f42bb31948ea6cc81bac543c918fa6cff
[]
no_license
guozanhua/ccv-object-tracking
8409d76e3cb804e7b5d733686f9b31d62dd7755e
cc26ec43c601241120e55b66e38c7777b21db6bd
refs/heads/master
2020-12-26T03:11:14.590984
2010-10-20T08:22:40
2010-10-20T08:22:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,444
cpp
/* * ofxNCoreVision.cpp * NUI Group Community Core Vision * * Created by NUI Group Dev Team A on 2/1/09. * Copyright 2009 NUI Group. All rights reserved. * */ #include "ofxNCoreVision.h" #include "../Controls/gui.h" /****************************************************************************** * The setup function is run once to perform initializations in the application *****************************************************************************/ void ofxNCoreVision::_setup(ofEventArgs &e) { //set the title ofSetWindowTitle(" Community Core Vision v 1.4"); //create filter if(filter == NULL) filter = new ProcessFilters(); if ( filter_fiducial == NULL ){filter_fiducial = new ProcessFilters();} //Load Settings from config.xml file loadXMLSettings(); if(debugMode) { printf("DEBUG MODE : Printing to File\n"); /***************************************************************************************************** * LOGGING ******************************************************************************************************/ /* alright first we need to get time and date so our logs can be ordered */ time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (fileName,80,"../logs/log_%B_%d_%y_%H_%M_%S.txt",timeinfo); FILE *stream ; sprintf(fileName, ofToDataPath(fileName).c_str()); if((stream = freopen(fileName, "w", stdout)) == NULL){} /******************************************************************************************************/ } cameraInited = false; //Setup Window Properties ofSetWindowShape(winWidth,winHeight); ofSetVerticalSync(false); //Set vertical sync to false for better performance? //printf("Application Loaded...\n?"); //load camera/video initDevice(); printf("Camera(s)/Video Initialised...\n"); //set framerate ofSetFrameRate(camRate * 1.3); //This will be based on camera fps in the future /***************************************************************************************************** * Allocate images (needed for drawing/processing images) ******************************************************************************************************/ processedImg.allocate(camWidth, camHeight); //main Image that'll be processed. processedImg.setUseTexture(false); //We don't need to draw this so don't create a texture sourceImg.allocate(camWidth, camHeight); //Source Image sourceImg.setUseTexture(false); //We don't need to draw this so don't create a texture //Fiducial Images processedImg_fiducial.allocate(camWidth, camHeight); //main Image that'll be processed. processedImg_fiducial.setUseTexture(false); //We don't need to draw this so don't create a texture undistortedImg.allocate(camWidth, camHeight); /******************************************************************************************************/ //Fonts - Is there a way to dynamically change font size? verdana.loadFont("verdana.ttf", 8, true, true); //Font used for small images //Static Images background.loadImage("images/background.jpg"); //Main (Temp?) Background //GUI Controls controls = ofxGui::Instance(this); setupControls(); //printf("Controls Loaded...\n"); //Setup Calibration calib.setup(camWidth, camHeight, &tracker); //Allocate Filters filter->allocate( camWidth, camHeight ); filter_fiducial->allocate( camWidth, camHeight ); //Fiducial Initialisation // factor for Fiducial Drawing. The ImageSize is hardcoded 320x240 Pixel!(Look at ProcessFilters.h at the draw() Method fiducialDrawFactor_Width = 320 / static_cast<float>(filter->camWidth);//camWidth; fiducialDrawFactor_Height = 240 / static_cast<float>(filter->camHeight);//camHeight; /***************************************************************************************************** * Startup Modes ******************************************************************************************************/ //If Standalone Mode (not an addon) if (bStandaloneMode) { printf("Starting in standalone mode...\n\n"); showConfiguration = true; } if (bMiniMode) { showConfiguration = true; bShowInterface = false; printf("Starting in Mini Mode...\n\n"); ofSetWindowShape(190, 200); //minimized size filter->bMiniMode = bMiniMode; } else{ bShowInterface = true; printf("Starting in full mode...\n\n"); } //If Object tracking activated if(contourFinder.bTrackObjects) { templates.loadTemplateXml(); } contourFinder.setTemplateUtils(&templates); tracker.passInFiducialInfo(&fidfinder); #ifdef TARGET_WIN32 //get rid of the console window FreeConsole(); #endif printf("Community Core Vision is setup!\n\n"); } /**************************************************************** * Load/Save config.xml file Settings ****************************************************************/ void ofxNCoreVision::loadXMLSettings() { // TODO: a seperate XML to map keyboard commands to action message = "Loading config.xml..."; // Can this load via http? if ( XML.loadFile("config.xml")) message = "Settings Loaded!\n\n"; else message = "No Settings Found...\n\n"; //FAIL //-------------------------------------------------------------- // START BINDING XML TO VARS //-------------------------------------------------------------- winWidth = XML.getValue("CONFIG:WINDOW:WIDTH", 950); winHeight = XML.getValue("CONFIG:WINDOW:HEIGHT", 600); bcamera = XML.getValue("CONFIG:CAMERA_0:USECAMERA", 1); deviceID = XML.getValue("CONFIG:CAMERA_0:DEVICE", 0); camWidth = XML.getValue("CONFIG:CAMERA_0:WIDTH", 320); camHeight = XML.getValue("CONFIG:CAMERA_0:HEIGHT", 240); camRate = XML.getValue("CONFIG:CAMERA_0:FRAMERATE", 0); videoFileName = XML.getValue("CONFIG:VIDEO:FILENAME", "test_videos/RearDI.m4v"); maxBlobs = XML.getValue("CONFIG:BLOBS:MAXNUMBER", 20); bShowLabels = XML.getValue("CONFIG:BOOLEAN:LABELS",0); bDrawOutlines = XML.getValue("CONFIG:BOOLEAN:OUTLINES",0); bUndistort = XML.getValue("CONFIG:BOOLEAN:UNDISTORT", 0); filter->bLearnBakground = XML.getValue("CONFIG:BOOLEAN:LEARNBG",0); filter->bVerticalMirror = XML.getValue("CONFIG:BOOLEAN:VMIRROR",0); filter->bHorizontalMirror = XML.getValue("CONFIG:BOOLEAN:HMIRROR",0); //Filters filter->bTrackDark = XML.getValue("CONFIG:BOOLEAN:TRACKDARK", 0); filter->bHighpass = XML.getValue("CONFIG:BOOLEAN:HIGHPASS",1); filter->bAmplify = XML.getValue("CONFIG:BOOLEAN:AMPLIFY", 1); filter->bSmooth = XML.getValue("CONFIG:BOOLEAN:SMOOTH", 1); filter->bDynamicBG = XML.getValue("CONFIG:BOOLEAN:DYNAMICBG", 1); //MODES bGPUMode = XML.getValue("CONFIG:BOOLEAN:GPU", 0); bMiniMode = XML.getValue("CONFIG:BOOLEAN:MINIMODE",0); //CONTROLS tracker.MOVEMENT_FILTERING = XML.getValue("CONFIG:INT:MINMOVEMENT",0); MIN_BLOB_SIZE = XML.getValue("CONFIG:INT:MINBLOBSIZE",2); MAX_BLOB_SIZE = XML.getValue("CONFIG:INT:MAXBLOBSIZE",100); backgroundLearnRate = XML.getValue("CONFIG:INT:BGLEARNRATE", 0.01f); //Filter Settings filter->threshold = XML.getValue("CONFIG:INT:THRESHOLD",0); filter->highpassBlur = XML.getValue("CONFIG:INT:HIGHPASSBLUR",0); filter->highpassNoise = XML.getValue("CONFIG:INT:HIGHPASSNOISE",0); filter->highpassAmp = XML.getValue("CONFIG:INT:HIGHPASSAMP",0); filter->smooth = XML.getValue("CONFIG:INT:SMOOTH",0); minTempArea = XML.getValue("CONFIG:INT:MINTEMPAREA",0); maxTempArea = XML.getValue("CONFIG:INT:MAXTEMPAREA",0); //Tracking Options contourFinder.bTrackFingers = XML.getValue("CONFIG:BOOLEAN:TRACKFINGERS",0); contourFinder.bTrackObjects = XML.getValue("CONFIG:BOOLEAN:TRACKOBJECTS",0); contourFinder.bTrackFiducials = XML.getValue("CONFIG:BOOLEAN:TRACKFIDUCIALS",0); //NETWORK SETTINGS bTUIOMode = XML.getValue("CONFIG:BOOLEAN:TUIO",0); myTUIO.bOSCMode = XML.getValue("CONFIG:BOOLEAN:OSCMODE",1); myTUIO.bTCPMode = XML.getValue("CONFIG:BOOLEAN:TCPMODE",1); myTUIO.bBinaryMode = XML.getValue("CONFIG:BOOLEAN:BINMODE",1); myTUIO.bHeightWidth = XML.getValue("CONFIG:BOOLEAN:HEIGHTWIDTH",0); tmpLocalHost = XML.getValue("CONFIG:NETWORK:LOCALHOST", "localhost"); tmpPort = XML.getValue("CONFIG:NETWORK:TUIOPORT_OUT", 3333); tmpFlashPort = XML.getValue("CONFIG:NETWORK:TUIOFLASHPORT_OUT", 3000); myTUIO.setup(tmpLocalHost.c_str(), tmpPort, tmpFlashPort); //have to convert tmpLocalHost to a const char* //-------------------------------------------------------------- // END XML SETUP //Filter for Fiducial setup filter_fiducial->bLearnBackground = false; filter_fiducial->bVerticalMirror = filter->bVerticalMirror; filter_fiducial->bHorizontalMirror = filter->bHorizontalMirror; filter_fiducial->bTrackDark = filter->bTrackDark; //^^ did not want to hardcode this , but these will not be any use of this. filter_fiducial->bHighpass = XML.getValue("CONFIG:FIDUCIAL:HIGHPASS", 0); filter_fiducial->bAmplify = XML.getValue("CONFIG:FIDUCIAL:AMPLIFY", 0); filter_fiducial->bSmooth = XML.getValue("CONFIG:FIDUCIAL:SMOOTH", 0); filter_fiducial->threshold = XML.getValue("CONFIG:FIDUCIAL:THRESHOLD", 0); filter_fiducial->highpassBlur = XML.getValue("CONFIG:FIDUCIAL:HIGHPASSBLUR", 0); filter_fiducial->highpassNoise = XML.getValue("CONFIG:FIDUCIAL:HIGHPASSNOISE", 0); filter_fiducial->highpassAmp = XML.getValue("CONFIG:FIDUCIAL:HIGHPASSAMP", 0); filter_fiducial->smooth = XML.getValue("CONFIG:FIDUCIAL:SMOOTHVALUE", 0); } void ofxNCoreVision::saveSettings() { XML.setValue("CONFIG:CAMERA_0:USECAMERA", bcamera); XML.setValue("CONFIG:CAMERA_0:DEVICE", deviceID); XML.setValue("CONFIG:CAMERA_0:WIDTH", camWidth); XML.setValue("CONFIG:CAMERA_0:HEIGHT", camHeight); XML.setValue("CONFIG:CAMERA_0:FRAMERATE", camRate); XML.setValue("CONFIG:BOOLEAN:PRESSURE",bShowPressure); XML.setValue("CONFIG:BOOLEAN:LABELS",bShowLabels); XML.setValue("CONFIG:BOOLEAN:OUTLINES",bDrawOutlines); XML.setValue("CONFIG:BOOLEAN:UNDISTORT",bUndistort); XML.setValue("CONFIG:BOOLEAN:LEARNBG", filter->bLearnBakground); XML.setValue("CONFIG:BOOLEAN:VMIRROR", filter->bVerticalMirror); XML.setValue("CONFIG:BOOLEAN:HMIRROR", filter->bHorizontalMirror); XML.setValue("CONFIG:BOOLEAN:TRACKDARK", filter->bTrackDark); XML.setValue("CONFIG:BOOLEAN:HIGHPASS", filter->bHighpass); XML.setValue("CONFIG:BOOLEAN:AMPLIFY", filter->bAmplify); XML.setValue("CONFIG:BOOLEAN:SMOOTH", filter->bSmooth); XML.setValue("CONFIG:BOOLEAN:DYNAMICBG", filter->bDynamicBG); XML.setValue("CONFIG:BOOLEAN:GPU", bGPUMode); XML.setValue("CONFIG:INT:MINMOVEMENT", tracker.MOVEMENT_FILTERING); XML.setValue("CONFIG:INT:MINBLOBSIZE", MIN_BLOB_SIZE); XML.setValue("CONFIG:INT:MAXBLOBSIZE", MAX_BLOB_SIZE); XML.setValue("CONFIG:INT:BGLEARNRATE", backgroundLearnRate); XML.setValue("CONFIG:INT:THRESHOLD", filter->threshold); XML.setValue("CONFIG:INT:HIGHPASSBLUR", filter->highpassBlur); XML.setValue("CONFIG:INT:HIGHPASSNOISE", filter->highpassNoise); XML.setValue("CONFIG:INT:HIGHPASSAMP", filter->highpassAmp); XML.setValue("CONFIG:INT:SMOOTH", filter->smooth); XML.setValue("CONFIG:INT:MINTEMPAREA", minTempArea); XML.setValue("CONFIG:INT:MAXTEMPAREA", maxTempArea); XML.setValue("CONFIG:BOOLEAN:MINIMODE", bMiniMode); XML.setValue("CONFIG:BOOLEAN:TUIO",bTUIOMode); XML.setValue("CONFIG:BOOLEAN:TRACKFINGERS",contourFinder.bTrackFingers); XML.setValue("CONFIG:BOOLEAN:TRACKOBJECTS",contourFinder.bTrackObjects); XML.setValue("CONFIG:BOOLEAN:TRACKFIDUCIALS",contourFinder.bTrackFiducials); XML.setValue("CONFIG:BOOLEAN:HEIGHTWIDTH", myTUIO.bHeightWidth); XML.setValue("CONFIG:BOOLEAN:OSCMODE", myTUIO.bOSCMode); XML.setValue("CONFIG:BOOLEAN:TCPMODE", myTUIO.bTCPMode); XML.setValue("CONFIG:BOOLEAN:BINMODE", myTUIO.bBinaryMode); XML.setValue("CONFIG:FIDUCIAL:HIGHPASS", filter_fiducial->bHighpass); XML.setValue("CONFIG:FIDUCIAL:AMPLIFY", filter_fiducial->bAmplify); XML.setValue("CONFIG:FIDUCIAL:SMOOTH", filter_fiducial->bSmooth); XML.setValue("CONFIG:FIDUCIAL:THRESHOLD", filter_fiducial->threshold); XML.setValue("CONFIG:FIDUCIAL:HIGHPASSBLUR", filter_fiducial->highpassBlur); XML.setValue("CONFIG:FIDUCIAL:HIGHPASSNOISE", filter_fiducial->highpassNoise); XML.setValue("CONFIG:FIDUCIAL:HIGHPASSAMP", filter_fiducial->highpassAmp); XML.setValue("CONFIG:FIDUCIAL:SMOOTHVALUE", filter_fiducial->smooth); XML.saveFile("config.xml"); } /************************************************ * Init Device ************************************************/ //Init Device (camera/video) void ofxNCoreVision::initDevice() { //save/update log file if(debugMode) if((stream = freopen(fileName, "a", stdout)) == NULL){} //Pick the Source - camera or video if (bcamera) { cameraInited=true; //check if a firefly, ps3 camera, or other is plugged in #ifdef TARGET_WIN32 /****PS3 - PS3 camera only****/ if(ofxPS3::getDeviceCount() > 0 && PS3 == NULL) { PS3 = new ofxPS3(); PS3->listDevices(); PS3->initPS3(camWidth, camHeight, camRate); camWidth = PS3->getCamWidth(); camHeight = PS3->getCamHeight(); printf("PS3 Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, PS3->getCamWidth(), PS3->getCamHeight()); return; } /****ffmv - firefly camera only****/ else if(ofxffmv::getDeviceCount() > 0 && ffmv == NULL) { ffmv = new ofxffmv(); ffmv->listDevices(); ffmv->initFFMV(camWidth,camHeight); printf("FFMV Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, ffmv->getCamWidth(), ffmv->getCamHeight()); camWidth = ffmv->getCamWidth(); camHeight = ffmv->getCamHeight(); return; } else if( vidGrabber == NULL ) { vidGrabber = new ofVideoGrabber(); vidGrabber->listDevices(); vidGrabber->setVerbose(true); vidGrabber->initGrabber(camWidth,camHeight); printf("Video Grabber Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, vidGrabber->width, vidGrabber->height); camWidth = vidGrabber->width; camHeight = vidGrabber->height; return; } else if( dsvl == NULL) { dsvl = new ofxDSVL(); dsvl->initDSVL(); printf("DSVL Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, dsvl->getCamWidth(), dsvl->getCamHeight()); camWidth = dsvl->getCamWidth(); camHeight = dsvl->getCamHeight(); return; } #else if( vidGrabber == NULL ) { vidGrabber = new ofVideoGrabber(); vidGrabber->listDevices(); vidGrabber->setVerbose(true); vidGrabber->initGrabber(camWidth,camHeight); printf("Linux Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, vidGrabber->width, vidGrabber->height); camWidth = vidGrabber->width; camHeight = vidGrabber->height; return; } #endif } else { if( vidPlayer == NULL ) { vidPlayer = new ofVideoPlayer(); vidPlayer->loadMovie( videoFileName ); vidPlayer->play(); vidPlayer->setLoopState(OF_LOOP_NORMAL); printf("Video Mode\n\n"); camHeight = vidPlayer->height; camWidth = vidPlayer->width; return; } } } /****************************************************************************** * The update function runs continuously. Use it to update states and variables *****************************************************************************/ void ofxNCoreVision::_update(ofEventArgs &e) { if(debugMode) if((stream = freopen(fileName, "a", stdout)) == NULL){} bNewFrame = false; if(bcamera) //if camera { #ifdef TARGET_WIN32 if(PS3!=NULL)//ps3 camera { bNewFrame = PS3->isFrameNew(); } else if(ffmv!=NULL) { ffmv->grabFrame(); bNewFrame = true; } else if(vidGrabber !=NULL) { vidGrabber->grabFrame(); bNewFrame = vidGrabber->isFrameNew(); } else if(dsvl !=NULL) { bNewFrame = dsvl->isFrameNew(); } #else vidGrabber->grabFrame(); bNewFrame = vidGrabber->isFrameNew(); #endif } else //if video { vidPlayer->idleMovie(); bNewFrame = vidPlayer->isFrameNew(); } //if no new frame, return if(!bNewFrame) { return; } else//else process camera frame { ofBackground(0, 0, 0); // Calculate FPS of Camera frames++; float time = ofGetElapsedTimeMillis(); if (time > (lastFPSlog + 1000)) { fps = frames; frames = 0; lastFPSlog = time; }//End calculation float beforeTime = ofGetElapsedTimeMillis(); if (bGPUMode) { grabFrameToGPU(filter->gpuSourceTex); filter->applyGPUFilters(); contourFinder.findContours(filter->gpuReadBackImageGS, (MIN_BLOB_SIZE * 2) + 1, ((camWidth * camHeight) * .4) * (MAX_BLOB_SIZE * .001), maxBlobs, false); if(contourFinder.bTrackFiducials) { grabFrameToGPU(filter_fiducial->gpuSourceTex); filter_fiducial->applyGPUFilters(); fidfinder.findFiducials( filter_fiducial->gpuReadBackImageGS ); } } else { grabFrameToCPU(); filter->applyCPUFilters( processedImg ); contourFinder.findContours(processedImg, (MIN_BLOB_SIZE * 2) + 1, ((camWidth * camHeight) * .4) * (MAX_BLOB_SIZE * .001), maxBlobs, false); if(contourFinder.bTrackFiducials) { filter_fiducial->applyCPUFilters( processedImg_fiducial ); fidfinder.findFiducials( processedImg_fiducial ); } } //If Object tracking or Finger tracking is enabled if(contourFinder.bTrackFingers || contourFinder.bTrackObjects) { tracker.track(&contourFinder); } //Map Fiducials from camera to screen position if(contourFinder.bTrackFiducials) { tracker.doFiducialCalculation(); } //get DSP time differenceTime = ofGetElapsedTimeMillis() - beforeTime; //Dynamic Background subtraction LearRate if (filter->bDynamicBG) { filter->fLearnRate = backgroundLearnRate * .0001; //If there are no blobs, add the background faster. if (contourFinder.nBlobs > 0) //If there ARE blobs, add the background slower. { filter->fLearnRate = backgroundLearnRate * .0001; } }//End Background Learning rate //Sending TUIO messages if (myTUIO.bOSCMode || myTUIO.bTCPMode || myTUIO.bBinaryMode) { //printf("sending data osc : %d TCP : %d binary : %d\n", myTUIO.bOSCMode, myTUIO.bTCPMode, myTUIO.bBinaryMode); myTUIO.setMode(contourFinder.bTrackFingers , contourFinder.bTrackObjects, contourFinder.bTrackFiducials); myTUIO.sendTUIO(&getBlobs(),&getObjects(),&fidfinder.fiducialsList); } } } /************************************************ * Input Device Stuff ************************************************/ //get pixels from camera void ofxNCoreVision::getPixels() { #ifdef TARGET_WIN32 if(PS3!=NULL) { //already grayscale processedImg.setFromPixels(PS3->getPixels(), camWidth, camHeight); if(contourFinder.bTrackFiducials){processedImg_fiducial = processedImg;} } else if(ffmv != NULL) { processedImg.setFromPixels(ffmv->fcImage[ffmv->getDeviceID()].pData, camWidth, camHeight); if(contourFinder.bTrackFiducials){processedImg_fiducial.setFromPixels(ffmv->fcImage[0].pData, camWidth, camHeight);} } else if(vidGrabber != NULL ) { sourceImg.setFromPixels(vidGrabber->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; if(contourFinder.bTrackFiducials){processedImg_fiducial = sourceImg;} } else if(dsvl!=NULL) { if(dsvl->getNumByes() != 1){ //if not grayscale sourceImg.setFromPixels(dsvl->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; if(contourFinder.bTrackFiducials){processedImg_fiducial = sourceImg;} } else { //if grayscale processedImg.setFromPixels(dsvl->getPixels(), camWidth, camHeight); if(contourFinder.bTrackFiducials){processedImg_fiducial.setFromPixels(dsvl->getPixels(), camWidth, camHeight);} } } #endif } //Grab frame from CPU void ofxNCoreVision::grabFrameToCPU() { //Set sourceImg as new camera/video frame if (bcamera) { #ifdef TARGET_WIN32 getPixels(); #else sourceImg.setFromPixels(vidGrabber->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; if(contourFinder.bTrackFiducials){processedImg_fiducial = sourceImg;} #endif } else { sourceImg.setFromPixels(vidPlayer->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; if(contourFinder.bTrackFiducials){processedImg_fiducial = sourceImg;} } } //Grab frame from GPU void ofxNCoreVision::grabFrameToGPU(GLuint target) { //grab the frame to a raw openGL texture if (bcamera) { glEnable(GL_TEXTURE_2D); //glPixelStorei(1); glBindTexture(GL_TEXTURE_2D, target); #ifdef TARGET_WIN32 if(PS3!=NULL) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, PS3->getPixels()); } else if(vidGrabber!=NULL) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, vidGrabber->getPixels()); } else if(dsvl!=NULL) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, dsvl->getPixels()); } #else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, vidGrabber->getPixels()); #endif glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D,0); } else { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, target); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, vidPlayer->getPixels()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D,0); } } /****************************************************************************** * The draw function paints the textures onto the screen. It runs after update. *****************************************************************************/ void ofxNCoreVision::_draw(ofEventArgs &e) { if (showConfiguration) { //if calibration if (bCalibration) { //Don't draw main interface calib.passInContourFinder(contourFinder.nBlobs, contourFinder.blobs); calib.doCalibration(); } //if mini mode else if (bMiniMode) { drawMiniMode(); } //if full mode else if (bShowInterface) { drawFullMode(); if(bDrawOutlines || bShowLabels) drawFingerOutlines(); if(contourFinder.bTrackFiducials) { drawFiducials(); } if(contourFinder.bTrackObjects && isSelecting) { ofNoFill(); ofSetColor(255, 0, 0); ofRect(rect.x,rect.y,rect.width,rect.height); ofSetColor(0, 255, 0); ofRect(minRect.x,minRect.y,minRect.width, minRect.height); ofSetColor(0, 0, 255); ofRect(maxRect.x, maxRect.y, maxRect.width, maxRect.height); } } //draw gui controls if (!bCalibration && !bMiniMode) {controls->draw();} } } void ofxNCoreVision::drawFullMode() { ofSetColor(0xFFFFFF); //Draw Background Image background.draw(0,0); //Draw Image Filters To Screen if (bGPUMode) filter->drawGPU(); else { if(!bFidMode) { filter->draw(); } else { filter_fiducial->draw(); } } // ofSetColor(0x444444); // ofFill(); // ofRect(570,392,128,190); ofSetColor(0xFFFFFF); if (bcamera) { string str1 = "Mode: Camera\n"; string str2 = "Resolution: "; str2+= ofToString(camWidth, 0) + "x" + ofToString(camHeight, 0) + "\n"; string str3 = "FPS: "; str3+= ofToString(fps, 0)+"\n"; string str4 = "Processing: "; str4+= ofToString(differenceTime, 0)+" ms \n"; string str5 = "Filter: "; if(!bFidMode) { str5+= "Finger/Object\n"; } else { str5+= "Fiducial\n"; } string str6 = "Blobs: "; str6+= ofToString(contourFinder.nBlobs,0)+", "+ofToString(contourFinder.nObjects,0)+", "+ofToString(fidfinder.fiducialsList.size(),0)+"\n"; ofSetColor(0x969696); verdana.drawString( str3+ str1 + str6 + str4 + str2 + str5 , 570, 430); } else { string str1 = "Mode: Video\n"; string str2 = "Resolution: "; str2+= ofToString(vidPlayer->width, 0) + "x" + ofToString(vidPlayer->height, 0) + "\n"; string str3 = "FPS: "; str3+= ofToString(fps, 0)+"\n"; string str4 = "Processing: "; str4+= ofToString(differenceTime, 0)+" ms \n"; string str5 = "Filter: "; if(!bFidMode) { str5+= "Finger/Object\n"; } else { str5+= "Fiducial\n"; } string str6 = "Blobs: "; str6+= ofToString(contourFinder.nBlobs,0)+", "+ofToString(fidfinder.fiducialsList.size(),0)+", "+ofToString(contourFinder.nObjects,0)+"\n"; ofSetColor(0x969696); verdana.drawString(str3+ str1 + str6 + str4 + str2 + str5 , 573, 427); } //TUIO data drawing char buf[256]=""; if(myTUIO.bOSCMode && myTUIO.bTCPMode) { sprintf(buf, "Dual Mode"); } else if(myTUIO.bOSCMode) { sprintf(buf, "Host: %s\nProtocol: UDP [OSC]\nPort: %i", myTUIO.localHost, myTUIO.TUIOPort); } else if(myTUIO.bTCPMode) { if(myTUIO.bIsConnected) sprintf(buf, "Host: %s\nProtocol: TCP [XML]\nPort: %i", myTUIO.localHost, myTUIO.TUIOFlashPort); else sprintf(buf, "Binding Error\nHost: %s\nProtocol: TCP [XML]\nPort: %i", myTUIO.localHost, myTUIO.TUIOFlashPort); } else if(myTUIO.bBinaryMode) { if(myTUIO.bIsConnected) sprintf(buf, "Host: %s\nProtocol: Binary\nPort: %i", myTUIO.localHost, myTUIO.TUIOFlashPort); else sprintf(buf, "Binding Error\nHost: %s\nProtocol: Binary\nPort: %i", myTUIO.localHost, myTUIO.TUIOFlashPort); } ofSetColor(0x969696); verdana.drawString(buf, 573, 515); } void ofxNCoreVision::drawMiniMode() { //black background ofSetColor(0,0,0); ofRect(0,0,ofGetWidth(), ofGetHeight()); //draw outlines if (bDrawOutlines) { for (int i=0; i<contourFinder.nBlobs; i++) { contourFinder.blobs[i].drawContours(0,0, camWidth, camHeight+175, ofGetWidth(), ofGetHeight()); } for (int i=0;i<contourFinder.nObjects; i++) { contourFinder.objects[i].drawBox(0,0, camWidth, camHeight+175, ofGetWidth(), ofGetHeight()); } } //draw grey rectagles for text information ofSetColor(128,128,128); ofFill(); ofRect(0,ofGetHeight() - 83, ofGetWidth(), 20); ofRect(0,ofGetHeight() - 62, ofGetWidth(), 20); ofRect(0,ofGetHeight() - 41, ofGetWidth(), 20); ofRect(0,ofGetHeight() - 20, ofGetWidth(), 20); //draw text ofSetColor(250,250,250); verdana.drawString("Calc. Time [ms]: " + ofToString(differenceTime,0),10, ofGetHeight() - 70 ); if (bcamera) { verdana.drawString("Camera [fps]: " + ofToString(fps,0),10, ofGetHeight() - 50 ); } else { verdana.drawString("Video [fps]: " + ofToString(fps,0),10, ofGetHeight() - 50 ); } verdana.drawString("Blob Count: " + ofToString(contourFinder.nBlobs,0),10, ofGetHeight() - 29 ); verdana.drawString("Communication: " ,10, ofGetHeight() - 9 ); //draw green tuio circle if((myTUIO.bIsConnected || myTUIO.bOSCMode) && bTUIOMode) ofSetColor(0x00FF00); //green = connected else ofSetColor(0xFF0000); //red = not connected ofFill(); ofCircle(ofGetWidth() - 17 , ofGetHeight() - 10, 5); ofNoFill(); } void ofxNCoreVision::drawFingerOutlines() { //Find the blobs for drawing if(contourFinder.bTrackFingers) { for (int i=0; i<contourFinder.nBlobs; i++) { if (bDrawOutlines) { //Draw contours (outlines) on the source image contourFinder.blobs[i].drawContours(30, 15, camWidth, camHeight, MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT); } if (bShowLabels) //Show ID label; { float xpos = contourFinder.blobs[i].centroid.x * (MAIN_WINDOW_WIDTH/camWidth); float ypos = contourFinder.blobs[i].centroid.y * (MAIN_WINDOW_HEIGHT/camHeight); ofSetColor(0xCCFFCC); char idStr[1024]; sprintf(idStr, "id: %i", contourFinder.blobs[i].id); verdana.drawString(idStr, xpos + 365, ypos + contourFinder.blobs[i].boundingRect.height/2 + 45); } } } //Object Drawing if(contourFinder.bTrackObjects) { for (int i=0; i<contourFinder.nObjects; i++) { if (bDrawOutlines) { //Draw contours (outlines) on the source image contourFinder.objects[i].drawBox(40, 30, camWidth, camHeight, MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT); } if (bShowLabels) //Show ID label; { float xpos = contourFinder.objects[i].centroid.x * (MAIN_WINDOW_WIDTH/camWidth); float ypos = contourFinder.objects[i].centroid.y * (MAIN_WINDOW_HEIGHT/camHeight); ofSetColor(0xCCFFCC); char idStr[1024]; sprintf(idStr, "id: %i", contourFinder.objects[i].id); verdana.drawString(idStr, xpos + 365, ypos + contourFinder.objects[i].boundingRect.height/2 + 45); } } } ofSetColor(0xFFFFFF); } void ofxNCoreVision::drawFiducials() { for (list<ofxFiducial>::iterator fiducial = fidfinder.fiducialsList.begin(); fiducial != fidfinder.fiducialsList.end(); fiducial++) { fiducial->drawScaled(30,15,fiducialDrawFactor_Width,fiducialDrawFactor_Height); fiducial->drawCornersScaled( 30, 15 ,fiducialDrawFactor_Width,fiducialDrawFactor_Height); ofSetColor(0,0,255); ofSetColor(255,255,255); } } /***************************************************************************** * KEY EVENTS *****************************************************************************/ void ofxNCoreVision::_keyPressed(ofKeyEventArgs &e) { if (showConfiguration) { switch (e.key) { case 'b': if(!bFidMode) { filter->bLearnBakground = true; } else { filter_fiducial->bLearnBackground = true; } break; case 'o': bDrawOutlines ? bDrawOutlines = false : bDrawOutlines = true; controls->update(appPtr->trackedPanel_outlines, kofxGui_Set_Bool, &appPtr->bDrawOutlines, sizeof(bool)); break; case 'h': filter->bHorizontalMirror ? filter->bHorizontalMirror = false : filter->bHorizontalMirror = true; filter_fiducial->bHorizontalMirror ? filter_fiducial->bHorizontalMirror = false : filter_fiducial->bHorizontalMirror = true; controls->update(appPtr->propertiesPanel_flipH, kofxGui_Set_Bool, &appPtr->filter->bHorizontalMirror, sizeof(bool)); break; case 'j': filter->bVerticalMirror ? filter->bVerticalMirror = false : filter->bVerticalMirror = true; filter_fiducial->bVerticalMirror ? filter_fiducial->bVerticalMirror = false : filter_fiducial->bVerticalMirror = true; controls->update(appPtr->propertiesPanel_flipV, kofxGui_Set_Bool, &appPtr->filter->bVerticalMirror, sizeof(bool)); break; case 't': myTUIO.bOSCMode = !myTUIO.bOSCMode; myTUIO.bTCPMode = false; myTUIO.bBinaryMode = false; bTUIOMode = myTUIO.bOSCMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); controls->update(appPtr->optionPanel_bin_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bBinaryMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'f': myTUIO.bOSCMode = false; myTUIO.bTCPMode = !myTUIO.bTCPMode; myTUIO.bBinaryMode = false; bTUIOMode = myTUIO.bTCPMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); controls->update(appPtr->optionPanel_bin_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bBinaryMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'n': myTUIO.bOSCMode = false; myTUIO.bTCPMode = false; myTUIO.bBinaryMode = !myTUIO.bBinaryMode; bTUIOMode = myTUIO.bBinaryMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); controls->update(appPtr->optionPanel_bin_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bBinaryMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'g': // bGPUMode ? bGPUMode = false : bGPUMode = true; // filter->bLearnBakground = true; break; case 'v': if (bcamera && vidGrabber != NULL) if(PS3) PS3->showSettings(); else if(vidGrabber) vidGrabber->videoSettings(); break; case 'l': bShowLabels ? bShowLabels = false : bShowLabels = true; controls->update(appPtr->trackedPanel_ids, kofxGui_Set_Bool, &appPtr->bShowLabels, sizeof(bool)); break; case 'p': bShowPressure ? bShowPressure = false : bShowPressure = true; break; case ' ': if (bMiniMode && !bCalibration) // NEED TO ADD HERE ONLY GO MINI MODE IF NOT CALIBRATING { bMiniMode = false; bShowInterface = true; filter->bMiniMode = bMiniMode; filter_fiducial->bMiniMode = bMiniMode; ofSetWindowShape(950,600); //default size } else if(!bCalibration) { bMiniMode = true; bShowInterface = false; filter->bMiniMode = bMiniMode; filter_fiducial->bMiniMode = bMiniMode; ofSetWindowShape(190,200); //minimized size } break; case 'x': //Exit Calibrating if (bCalibration) { bShowInterface = true; bCalibration = false; calib.calibrating = false; tracker.isCalibrating = false; if (bFullscreen == true) ofToggleFullscreen(); bFullscreen = false; } break; case OF_KEY_RETURN: //Close Template Selection and save it if( contourFinder.bTrackObjects && isSelecting ) { isSelecting = false; templates.addTemplate(rect,minRect,maxRect,camWidth/320,camHeight/240); rect = ofRectangle(); minRect = rect; maxRect = rect; minTempArea = 0; maxTempArea = 0; controls->update(appPtr->TemplatePanel_minArea, kofxGui_Set_Float, &appPtr->minTempArea, sizeof(float)); controls->update(appPtr->TemplatePanel_maxArea, kofxGui_Set_Float, &appPtr->maxTempArea, sizeof(float)); } break; case 'i': bFidMode = !bFidMode; if(bFidMode) {//Update the GUI with Fiducial Filter values //Smooth controls->update(appPtr->smoothPanel_use, kofxGui_Set_Bool, &appPtr->filter_fiducial->bSmooth, sizeof(bool)); controls->update(appPtr->smoothPanel_smooth, kofxGui_Set_Float, &appPtr->filter_fiducial->smooth, sizeof(float)); //Highpass controls->update(appPtr->highpassPanel_use, kofxGui_Set_Bool, &appPtr->filter_fiducial->bHighpass, sizeof(bool)); controls->update(appPtr->highpassPanel_blur, kofxGui_Set_Float, &appPtr->filter_fiducial->highpassBlur, sizeof(float)); controls->update(appPtr->highpassPanel_noise, kofxGui_Set_Float, &appPtr->filter_fiducial->highpassNoise, sizeof(float)); //Amplify controls->update(appPtr->amplifyPanel_use, kofxGui_Set_Bool, &appPtr->filter_fiducial->bAmplify, sizeof(bool)); controls->update(appPtr->amplifyPanel_amp, kofxGui_Set_Float, &appPtr->filter_fiducial->highpassAmp, sizeof(float)); //Threshold controls->update(appPtr->trackedPanel_threshold, kofxGui_Set_Float, &appPtr->filter_fiducial->threshold, sizeof(float)); } else {//Update the GUI with normal Filter values //Smooth controls->update(appPtr->smoothPanel_use, kofxGui_Set_Bool, &appPtr->filter->bSmooth, sizeof(bool)); controls->update(appPtr->smoothPanel_smooth, kofxGui_Set_Float, &appPtr->filter->smooth, sizeof(float)); //Highpass controls->update(appPtr->highpassPanel_use, kofxGui_Set_Bool, &appPtr->filter->bHighpass, sizeof(bool)); controls->update(appPtr->highpassPanel_blur, kofxGui_Set_Float, &appPtr->filter->highpassBlur, sizeof(float)); controls->update(appPtr->highpassPanel_noise, kofxGui_Set_Float, &appPtr->filter->highpassNoise, sizeof(float)); //Amplify controls->update(appPtr->amplifyPanel_use, kofxGui_Set_Bool, &appPtr->filter->bAmplify, sizeof(bool)); controls->update(appPtr->amplifyPanel_amp, kofxGui_Set_Float, &appPtr->filter->highpassAmp, sizeof(float)); //Threshold controls->update(appPtr->trackedPanel_threshold, kofxGui_Set_Float, &appPtr->filter->threshold, sizeof(float)); } //TODO:Update the GUI break; default: //Check key character <<<<===== Remove this //printf("%c",e.key); break; } } } void ofxNCoreVision::_keyReleased(ofKeyEventArgs &e) { if (showConfiguration) { if ( e.key == 'c' && !bCalibration) { bShowInterface = false; // Enter/Exit Calibration bCalibration = true; calib.calibrating = true; tracker.isCalibrating = true; if (bFullscreen == false) ofToggleFullscreen(); bFullscreen = true; } } if ( e.key == '~' || e.key == '`' && !bMiniMode && !bCalibration) showConfiguration = !showConfiguration; } /***************************************************************************** * MOUSE EVENTS *****************************************************************************/ void ofxNCoreVision::_mouseDragged(ofMouseEventArgs &e) { if (showConfiguration) controls->mouseDragged(e.x, e.y, e.button); //guilistener if(contourFinder.bTrackObjects) { if( e.x > 385 && e.x < 705 && e.y > 30 && e.y < 270 ) { if( e.x < rect.x || e.y < rect.y ) { rect.width = rect.x - e.x; rect.height = rect.y - e.y; rect.x = e.x; rect.y = e.y; } else { rect.width = e.x - rect.x; rect.height = e.y - rect.y; } } } } void ofxNCoreVision::_mousePressed(ofMouseEventArgs &e) { if (showConfiguration) { controls->mousePressed( e.x, e.y, e.button ); //guilistener if ( contourFinder.bTrackObjects ) { if ( e.x > 385 && e.x < 705 && e.y > 30 && e.y < 270 ) { isSelecting = true; rect.x = e.x; rect.y = e.y; rect.width = 0; rect.height = 0; } } //Launch the website in browser if ( e.x > 722 && e.y > 586 ) ofLaunchBrowser("http://ccv.nuigroup.com"); } } void ofxNCoreVision::_mouseReleased(ofMouseEventArgs &e) { if (showConfiguration) controls->mouseReleased(e.x, e.y, 0); //guilistener if( e.x > 385 && e.x < 705 && e.y > 30 && e.y < 270 ) { if ( contourFinder.bTrackObjects && isSelecting ) { minRect = rect; maxRect = rect; } } } /***************************************************************************** * Getters *****************************************************************************/ std::map<int, Blob> ofxNCoreVision::getBlobs() { return tracker.getTrackedBlobs(); } std::map<int,Blob> ofxNCoreVision::getObjects() { return tracker.getTrackedObjects(); } /***************************************************************************** * ON EXIT *****************************************************************************/ void ofxNCoreVision::_exit(ofEventArgs &e) { saveSettings(); //Save templates if(contourFinder.bTrackObjects) templates.saveTemplateXml(); // AlexP // C++ guarantees that operator delete checks its argument for null-ness #ifdef TARGET_WIN32 delete PS3; PS3 = NULL; delete ffmv; ffmv = NULL; delete dsvl; dsvl = NULL; #endif delete filter; filter = NULL; delete vidGrabber; vidGrabber = NULL; delete vidPlayer; vidPlayer = NULL; // -------------------------------- SAVE STATE ON EXIT printf("Vision module has exited!\n"); }
[ "amit.getinfo@85fc5e24-5cb5-a459-a2e3-60d0933772b6" ]
[ [ [ 1, 1169 ] ] ]
972cbccbee547becf5f1b3ba7adb9e4429013720
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/LogoScene.h
879f37f6c04a9876cc66eb8ca04a4cb15e0917fb
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UTF-8
C++
false
false
1,013
h
#pragma once #ifndef _LOGOSCENE_H_ #define _LOGOSCENE_H_ #include "Scene.h" class CCharactor; class CameraWork; //class CEfSurface; class LogoScene : public IScene { private: VOID Initialize(); VOID Release(); public: LogoScene() { this->Initialize(); } virtual ~LogoScene() { this->Release(); } typedef struct _DATA { BOOL bActivate; DWORD dFrameSpeed; DWORD dBeginTime; }DATA, *LPDATA; virtual HRESULT Create( LPDIRECT3DDEVICE9 _pd3dDevice, LPD3DXSPRITE _pSprite, HWND _hWnd ); virtual VOID Update(); virtual VOID Render(); virtual INT GetSceneNext(); virtual INT GetSceneState(); private: LPDIRECT3DDEVICE9 m_pD3dDevice; LPD3DXSPRITE m_pSprite; HWND m_hWnd; INT m_scnNext; INT m_scnState; CCharactor* m_pLogo; CameraWork* m_pCameraWork; CLight* m_pLight; CMatrices* m_pMatrices; DATA m_datLogo; DATA m_datScene; //CEfSurface * m_pEff; public: }; #endif
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 8 ], [ 10, 41 ], [ 43, 57 ], [ 59, 62 ] ], [ [ 9, 9 ], [ 42, 42 ], [ 58, 58 ] ] ]
152e12530ae2781d3fbfdc4704ff33ed3e5d383d
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/SRC/Queue/queue.cc
7e3afe03bd118c0c01f7ac759d705b34108bffe6
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
GB18030
C++
false
false
9,888
cc
// Virtual Base class for all queue types. // Provides some common functionality #include "queue.h" #include "droptail.h" #include "simulator.h" #include "link.h" #include "interface.h" #ifdef HAVE_QT #include "gui_ctrl.h" #include "GUI_Defs.h" #endif using namespace std; // 静态成员变量 Queue* Queue::defaultQueue = nil; Count_t Queue::defaultLength = DEFAULT_DROPTAIL_LIMIT; Count_t Queue::defaultLimitPkts = 0; Count_t Queue::defaultAnimWidth = 10; Count_t Queue::globalQueueDrop = 0; void Queue::DummyEnque(Packet*) // 由派生类按需进行覆盖 { } Count_t Queue::DequeAllDstMac(MACAddr) // 由派生类按需进行覆盖 { return 0; } Count_t Queue::DequeAllDstIP(IPAddr_t) // 由派生类按需进行覆盖 { return 0; } Packet* Queue::DequeOneDstMac(MACAddr) // 由派生类按需进行覆盖 { return nil; } Packet* Queue::DequeOneDstIP(IPAddr_t) // 由派生类按需进行覆盖 { return nil; } DCount_t Queue::Average() // 计算平均队列长度 { Time_t now = Simulator::Now(); if (now == startTime) return 0.0; // 避免除数为0 return totalByteSeconds / (now - startTime); } void Queue::ResetAverage() // 使用新的时间间隔来计算平均队列 { startTime = Simulator::Now(); lastUpdate = startTime; totalByteSeconds = 0; } void Queue::UpdateAverage() // 队列发生变化更新平均队列值 { Time_t now = Simulator::Now(); totalByteSeconds += (now - lastUpdate) * Length(); lastUpdate = now; // 如果启用了队列长度的日志,则还需更新日志 UpdateTimeSizeLog(); } bool Queue::Detailed() // 判断detailed模式是否被使用,有则返回True,否则返回False { return detailed; } void Queue::Detailed(bool d) // 设定是否使用detailed模式 { detailed = d; } Time_t Queue::QueuingDelay() // 计算排队延时 { #ifndef WIN32 if (!interface) return 0; // 没有相关的接口则不做处理 Rate_t linkBw = interface->GetLink()->Bandwidth(); return ((Length() * 8.0) / linkBw); // 清空(让数据包通过)队列所需时间 #else if (!interface_) return 0; // 没有绑定接口则不做处理 Rate_t linkBw = interface_->GetLink()->Bandwidth(); return ((Length() * 8.0) / linkBw); // 清空(让数据包通过)队列所需时间 #endif } DCount_t Queue::TotalWorkload() // 计算总的工作负载 { return totalByteSeconds; } void Queue::SetInterface(Interface* i) // 设定相关的接口 { #ifndef WIN32 interface = i; #else interface_ = i; #endif } Count_t Queue::DropCount() //返回丢弃的数据包的总数 { return dropCount; } Count_t Queue::EnqueueCount() //返回入队的数据包总数 { return totEnq; } void Queue::CountEnq(Packet* p) //对一次入队操作进行计数,当链路不忙时由接口调用 { totEnq++; } void Queue::ResetStats() //重置所用从属于此队列的数据为0 { dropCount = 0; totEnq = 0; } void Queue::AddForcedLoss(Time_t t, Count_t c, Time_t e) /* 描述:添加一次强制丢包行为有关的信息 参数:Arg1 丢包的时刻 Arg2 这段时间内连续丢包的数目 Arg3 丢包结束的时刻 */ { if (!forcedLosses) forcedLosses = new LossList_t(); LossList_t::iterator i; for (i = forcedLosses->begin(); i != forcedLosses->end(); ++i) { if (t < i->time) break; // Insert before here } forcedLosses->insert(i, ForcedLoss(t, c, e)); } bool Queue::CheckForcedLoss(bool remove) //判断一次强制丢包是否应该被执行 { if (!forcedLosses) return false; // 没有丢包列表 if (forcedLosses->empty()) return false; // 丢包列表为空 LossList_t::iterator i; Time_t now = Simulator::Now(); bool r = false; for (i = forcedLosses->begin(); i != forcedLosses->end(); ) { if (now < i->time) return r; // Done checking if (now < i->expiration) r = true; if (0) cout << "Forced loss at " << now << " count " << i->count << endl; if (remove) i->count--; if (i->count == 0 || now >= i->expiration) { // Done with this one, remove it LossList_t::iterator j = i; ++i; if (remove) forcedLosses->erase(j); } if (r) return r; // No need to keep checking } return r; // code later } bool Queue::CheckSpoofedSource(Packet*) //一些队列管理机制会执行包过滤,判断是否丢弃来自某个源IP欺骗,一般队列不过滤 { return false; } void Queue::EnableTimeSizeLog(bool b) //是否开启日志记录队列长度随时间的变化 { if (b) { // b为True,开启 if (!timeSizeLog) timeSizeLog = new TimeSeq_t(); } else { // 否则关闭日志,并删除所有存在的记录 delete timeSizeLog; timeSizeLog = nil; } } void Queue::LogSizePackets(bool b) //日志中队列长度的单位是为数据包个数(True)或是字节(False) { timeSizePackets = b; } void Queue::PrintTimeSizeLog(ostream& os, Count_t div, char sep) /* 描述:将记录队列长度随时间变化的日志导入文件中 参数:Arg1 输出流 Arg2 非零时,每个序号要除以该数 Arg3 时间和序列号间的分隔符 */ { if (!timeSizeLog) return; //无数据可用 for (TimeSeq_t::size_type i = 0; i < timeSizeLog->size(); ++i) { TimeSeq& ts = (*timeSizeLog)[i]; Count_t v = ts.seq; if (div) v /= div; os << ts.time << sep << v << endl; } } void Queue::DisplayQueue(gui_ctrl* qtw, Node* s, Node* d) //动画展示缓冲队列的使用率 { #ifdef HAVE_QT if (!animate) return; MyPoint sp = qtw->NodeLocation(s); // Get location of source MyPoint dp = qtw->NodeLocation(d); // Get location of destination // Compute slope of line connecting src/dst double dx = dp.x() - sp.x(); double dy = dp.y() - sp.y(); // Compute the angle of a line from src to dst double theta = atan2(dy, dx); double sinTheta = sin(theta); double cosTheta = cos(theta); double sinThetaM2 = sin(theta + M_PI_2); double cosThetaM2 = cos(theta + M_PI_2); // Allocate the qLines vector if not already if (!qLines) qLines = new ItemVec_t(); #ifdef OLD_WAY Count_t k = 0; while(true) { // Display this one Packet* p = GetPacket(k); if (!p) break; // No more double lx = sp.x() + k * cosThetaM2; // Left x double ly = sp.y() + k * sinThetaM2; // Left y double rx = sp.x() + Queue::defaultAnimWidth * cosTheta + k * cosThetaM2; double ry = sp.y() + Queue::defaultAnimWidth * sinTheta + k * sinThetaM2; MyCanvasLine* line = nil; if (k < qLines->size()) { line = (*qLines)[k]; } else { line = new MyCanvasLine(qtw->Canvas()); qLines->push_back(line); } if (p->IsColored()) { line->setPen(MyColor(p->R(), p->G(), p->B())); } else { line->setPen(Qt::blue); } line->setPoints((int)lx, (int)ly, (int)rx, (int)ry); line->show(); ++k; } #else ColorVec_t colors; GetPacketColors(colors); ColorVec_t::size_type i = 0; ItemVec_t::size_type k = 0; for (; i < colors.size(); ++i) { MyCanvasLine* line = nil; if (k < qLines->size()) { line = (*qLines)[k]; } else { line = new MyCanvasLine(qtw->Canvas()); qLines->push_back(line); double lx = sp.x() + k * cosThetaM2; // Left x double ly = sp.y() + k * sinThetaM2; // Left y double rx = sp.x() + Queue::defaultAnimWidth * cosTheta + k * cosThetaM2; double ry = sp.y() + Queue::defaultAnimWidth * sinTheta + k * sinThetaM2; line->setPoints((int)lx, (int)ly, (int)rx, (int)ry); } line->show(); line->setPen(MyColor(colors[i])); ++k; } #endif while(k < qLines->size()) { // Hide any excess (*qLines)[k]->hide(); ++k; } #endif } //保护方法成员 void Queue::UpdateTimeSizeLog() //由派生类用来更新记录队列长度随时间变化的日志 { // Note that we use the TimeSeq log from TCP for this, which is // a slight hack. The TimeSeq object uses a type Seq_t for // the value being logged, but we need a Count_t value. Luckily // these are both just unsigned long's so we are ok. if (!timeSizeLog) return; Count_t l = Length(); if (timeSizePackets) l = LengthPkts(); if (!timeSizeLog->empty()) { // See if current timestamp is same as prior, // if so, overwrite last entry TimeSeq& last = timeSizeLog->back(); if (last.time == Simulator::Now()) { // Same, just overwrite last.seq = l; return; } } timeSizeLog->push_back(TimeSeq(Simulator::Now(), l)); } // 静态方法 void Queue::Default(const Queue& d) //set一个默认的队列 { if (defaultQueue) delete defaultQueue; // 删除存在的默认队列 defaultQueue = d.Copy(); } Queue& Queue::Default() //返回对默认队列对象的引用 { if (!defaultQueue) defaultQueue = new DropTail(); return *defaultQueue; } void Queue::DefaultLength(Count_t l) //设定默认队列缓冲区的大小(单位:字节) { defaultLength = l; Default().SetLimit(l); } void Queue::DefaultLimitPkts(Count_t l) //设定默认队列缓冲区的大小(单位:数据包个数) { defaultLimitPkts = l; Default().SetLimitPkts(l); }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 386 ] ] ]
43ddf77c9abdb5dc1679f66b09bae717bb803cbc
b8fbe9079ce8996e739b476d226e73d4ec8e255c
/src/engine/rb_nature/jtreeleaf.cpp
971043dc3f84059d1bfb30e2b78b32015eedff46
[]
no_license
dtbinh/rush
4294f84de1b6e6cc286aaa1dd48cf12b12a467d0
ad75072777438c564ccaa29af43e2a9fd2c51266
refs/heads/master
2021-01-15T17:14:48.417847
2011-06-16T17:41:20
2011-06-16T17:41:20
41,476,633
1
0
null
2015-08-27T09:03:44
2015-08-27T09:03:44
null
UTF-8
C++
false
false
531
cpp
/***********************************************************************************/ // File: JTreeLeaf.cpp // Date: 10.08.2005 // Author: Ruslan Shestopalyuk /***********************************************************************************/ #include "stdafx.h" #include "JTreeLeaf.h" /***********************************************************************************/ /* JTreeLeaf implementation /***********************************************************************************/ decl_class(JTreeLeaf);
[ [ [ 1, 12 ] ] ]
751b892f1f3173790179ee31eaf0c2f7e836be0d
fde5aa467c3a25c49765c2b441c0f3bd58a02d93
/GitRPG/user.h
eaf2b52b3fe7ae8e5030c5df92368b4fcecc6bb6
[]
no_license
Stals/Git-Rpg
85d50816214b5260fefb199ec7f7c5c14558984c
76461c19ae87513d3c2b17386d3adda822574f12
refs/heads/master
2021-01-20T09:09:21.289695
2011-07-14T10:29:00
2011-07-14T10:29:00
1,576,842
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,283
h
#ifndef USER_H #define USER_H #include <string> #include "eventqueue.h" struct Stats{ int lvl; int exp; int maxExp; int lastExp;//опыт предведущего уровня (на первой уровне = 0) Stats():lastExp(0){} }; class User { public: User(); //загружает данные из файла Stats.grpg ~User();//Вызывается при заверщении программы, сохраняет статистики обратно в Stats.grpg std::string name; Stats joint; Stats plus; Stats minus; std::pair<int,int>newExp;//плюс и минус полученные из файла Stals first - Additions, second - delitions //(обновляется методами mainwindow,даже при старте приложения получает значения там) //Но после того как пройдёт func статы в newExp и в plus,minus будут одинаковы void checkForLvls();//проверяет и увеличивает уровень std::string getStats();//возвращает строку для печати или вывода void loadStats(); void saveStats(); }; #endif // USER_H
[ [ [ 1, 23 ], [ 29, 29 ], [ 31, 36 ] ], [ [ 24, 28 ], [ 30, 30 ] ] ]
769518342812af62fdf7371f5c0e86d45d418309
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/UnitTests/UnitTest_RTTLayer/MyGUI_RTTLayer.cpp
1642ae1de7d62ee4b91be8d71319e3811abae1fa
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
2,613
cpp
/*! @file @author Albert Semenov @date 12/2009 */ #include "MyGUI_LayerItem.h" #include "MyGUI_RTTLayer.h" #include "MyGUI_Enumerator.h" #include "MyGUI_FactoryManager.h" #include "MyGUI_RenderManager.h" #include "MyGUI_Gui.h" #include "MyGUI_LayerNode.h" namespace MyGUI { RTTLayer::RTTLayer() : mTexture(nullptr) { } RTTLayer::~RTTLayer() { if (mTexture) { MyGUI::RenderManager::getInstance().destroyTexture(mTexture); mTexture = nullptr; } } void RTTLayer::deserialization(xml::ElementPtr _node, Version _version) { Base::deserialization(_node, _version); MyGUI::xml::ElementEnumerator propert = _node->getElementEnumerator(); while (propert.next("Property")) { const std::string& key = propert->findAttribute("key"); const std::string& value = propert->findAttribute("value"); if (key == "TextureSize") setTextureSize(utility::parseValue<IntSize>(value)); if (key == "TextureName") setTextureName(value); } } void RTTLayer::renderToTarget(IRenderTarget* _target, bool _update) { bool out_date = false; for (VectorILayerNode::iterator iter = mChildItems.begin(); iter != mChildItems.end(); ++iter) { if ((*iter)->castType<LayerNode>()->isOutOfDate()) { out_date = true; break; } } if (out_date || _update) { MyGUI::IRenderTarget* target = mTexture->getRenderTarget(); if (target != nullptr) { target->begin(); for (VectorILayerNode::iterator iter = mChildItems.begin(); iter != mChildItems.end(); ++iter) { (*iter)->renderToTarget(target, _update); } target->end(); } } } void RTTLayer::setTextureSize(const IntSize& _size) { if (mTextureSize == _size) return; mTextureSize = _size; if (mTexture) { MyGUI::RenderManager::getInstance().destroyTexture(mTexture); mTexture = nullptr; } MYGUI_ASSERT(mTextureSize.width * mTextureSize.height, "RTTLayer texture size must have non-zero width and height"); std::string name = mTextureName.empty() ? MyGUI::utility::toString((size_t)this, getClassTypeName()) : mTextureName; mTexture = MyGUI::RenderManager::getInstance().createTexture(name); mTexture->createManual(mTextureSize.width, mTextureSize.height, MyGUI::TextureUsage::RenderTarget, MyGUI::PixelFormat::R8G8B8A8); } void RTTLayer::setTextureName(const std::string& _name) { mTextureName = _name; if (mTexture != nullptr) { IntSize size = mTextureSize; mTextureSize.clear(); setTextureSize(size); } } } // namespace MyGUI
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 104 ] ] ]
5396cbb7c9af8ca7c49dcd589f8f7ee81d003457
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/NxOgre/build/source/NxOgreHeightFieldGeometry.cpp
970841a4a3eea1286909a19de03ce25d9914bfb8
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,723
cpp
/** File: NxOgreHeightFieldGeometry.cpp Created on: 15-Mar-09 Author: Robin Southern "betajaen" © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NxOgre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #include "NxOgreStable.h" #include "NxOgreHeightFieldGeometry.h" #include "NxOgreHeightField.h" #include "NxOgreHeightFieldGeometryBlueprint.h" #include "NxOgrePhysXUserEntityReport.h" #include "NxOgreFunctions.h" #include "NxPhysics.h" namespace NxOgre { HeightFieldGeometry::HeightFieldGeometry(HeightField* heightfield, const Vec3& size, HeightFieldGeometryBlueprint* blueprint) : Shape(blueprint), mHeightField(0), mHeightFieldShape(0) { blueprint->mHeightField = heightfield; blueprint->mSize.x = size.x / Real(blueprint->mHeightField->getHeightField()->getNbRows()); blueprint->mSize.y = size.y / 32768.0f; blueprint->mSize.z = size.z / Real(blueprint->mHeightField->getHeightField()->getNbColumns()); blueprint->mTerrainCentering = Enums::TerrainCentering_LocalPose; blueprint->mSmoothSphereCollisions; blueprint->mHoleMaterial = 65535; blueprint->mHighBits = 0; } HeightFieldGeometry::HeightFieldGeometry(HeightField* heightfield, HeightFieldGeometryBlueprint* blueprint) : Shape(blueprint), mHeightField(0), mHeightFieldShape(0) { blueprint->mHeightField = heightfield; blueprint->mTerrainCentering = Enums::TerrainCentering_LocalPose; blueprint->mSmoothSphereCollisions; blueprint->mHoleMaterial = 65535; blueprint->mHighBits = 0; } HeightFieldGeometry::~HeightFieldGeometry(void) { } NxShapeDesc* HeightFieldGeometry::create(void) { NxHeightFieldShapeDesc* heightfield = new NxHeightFieldShapeDesc(); createAbstract(heightfield); HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); heightfield->heightField = blueprint->mHeightField->getHeightField(); heightfield->rowScale = blueprint->mSize.x; heightfield->heightScale = blueprint->mSize.y; heightfield->columnScale = blueprint->mSize.z; heightfield->holeMaterial = blueprint->mHoleMaterial; heightfield->materialIndexHighBits = blueprint->mHighBits; heightfield->meshFlags = blueprint->mMeshFlags; if (blueprint->mSmoothSphereCollisions) heightfield->meshFlags |= NX_MESH_SMOOTH_SPHERE_COLLISIONS; if (blueprint->mTerrainCentering == Enums::TerrainCentering_CenterXZ) { heightfield->localPose.t.x = -(blueprint->mSize.x * 0.5f); heightfield->localPose.t.z = -(blueprint->mSize.z * 0.5f); } else if (blueprint->mTerrainCentering == Enums::TerrainCentering_CenterAbove) { heightfield->localPose.t.x = -(blueprint->mSize.x * 0.5f); heightfield->localPose.t.y = blueprint->mSize.y; heightfield->localPose.t.z = -(blueprint->mSize.z * 0.5f); } return heightfield; } void HeightFieldGeometry::assign(NxShape* heightfield) { assignAbstract(heightfield); mHeightFieldShape = heightfield->isHeightField(); } Enums::ShapeFunctionType HeightFieldGeometry::getShapeFunctionType() const { return Enums::ShapeFunctionType_HeightField; } HeightField* HeightFieldGeometry::getHeightField() const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mHeightField; } else { return mHeightField; } } Enums::TerrainCentering HeightFieldGeometry::getTerrainCentering() const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mTerrainCentering; } else { return Enums::TerrainCentering_LocalPose; } } bool HeightFieldGeometry::getSmoothSphereCollisions() const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mSmoothSphereCollisions; } else { return false; } } MaterialIdentifier HeightFieldGeometry::getHoleMaterial() const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mHoleMaterial; } return 0; } MaterialIdentifier HeightFieldGeometry::getHighBits() const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mHighBits; } return 0; } void HeightFieldGeometry::setHeightField(HeightField* hf) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mHeightField = hf; } } void HeightFieldGeometry::setTerrainCentering(Enums::TerrainCentering tc) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mTerrainCentering = tc; } } void HeightFieldGeometry::setSmoothSphereCollisions(bool ssc) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mSmoothSphereCollisions = ssc; } } void HeightFieldGeometry::setHoleMaterial(MaterialIdentifier identifier) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mHoleMaterial = identifier; } } void HeightFieldGeometry::setHighBits(MaterialIdentifier identifier) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mHighBits = identifier; } } void HeightFieldGeometry::setSize(const Vec3& size) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mSize.x = size.x / Real(blueprint->mHeightField->getHeightField()->getNbRows()); blueprint->mSize.y = size.y / Real(blueprint->mHeightField->getHeightField()->getNbColumns()); blueprint->mSize.z = size.z / 32768.0f; } else { mHeightFieldShape->setRowScale(size.x / Real(mHeightFieldShape->getHeightField().getNbRows())); mHeightFieldShape->setHeightScale(size.y / Real(mHeightFieldShape->getHeightField().getNbColumns())); mHeightFieldShape->setColumnScale(size.z / 32768.0f); } } void HeightFieldGeometry::setScale(const Vec3& scale) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mSize.x = scale.x; blueprint->mSize.y = scale.y; blueprint->mSize.z = scale.z; } else { mHeightFieldShape->setRowScale(scale.x); mHeightFieldShape->setHeightScale(scale.y); mHeightFieldShape->setColumnScale(scale.z); } } Real HeightFieldGeometry::getHeightScale(void) const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mSize.y; } else return mHeightFieldShape->getHeightScale(); } Real HeightFieldGeometry::getRowScale(void) const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mSize.x; } else return mHeightFieldShape->getRowScale(); } Real HeightFieldGeometry::getColumnScale(void) const { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); return blueprint->mSize.z; } else return mHeightFieldShape->getColumnScale(); } void HeightFieldGeometry::setHeightScale(Real scale) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mSize.y = scale; } else mHeightFieldShape->setHeightScale(scale); } void HeightFieldGeometry::setRowScale(Real scale) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mSize.x = scale; } else mHeightFieldShape->setRowScale(scale); } void HeightFieldGeometry::setColumnScale(Real scale) { if (mBlueprint) { HeightFieldGeometryBlueprint* blueprint = static_cast<HeightFieldGeometryBlueprint*>(mBlueprint); blueprint->mSize.z = scale; } else mHeightFieldShape->setColumnScale(scale); } bool HeightFieldGeometry::overlapAAABTriangles(const Bounds3& bounds, unsigned int queryFlags, EntityReport<Index>* callback ) const { if (mHeightFieldShape == 0) return false; PhysXUserEntityReport<Index> report(callback); NxBounds3 nBounds; Functions::XYZ<Vec3, NxVec3>(bounds.max, nBounds.max); Functions::XYZ<Vec3, NxVec3>(bounds.min, nBounds.min); return mHeightFieldShape->overlapAABBTriangles(nBounds, queryFlags, &report); } void HeightFieldGeometry::getTriangle(Triangle& out, unsigned int* flags, Index index, bool worldTrans, bool worldRot ) { NxTriangle triangle; mHeightFieldShape->getTriangle(triangle, 0, flags, index, worldTrans, worldRot); Functions::XYZ<NxVec3, Vec3>(triangle.verts[0], out.mVertices[0]); Functions::XYZ<NxVec3, Vec3>(triangle.verts[1], out.mVertices[1]); Functions::XYZ<NxVec3, Vec3>(triangle.verts[2], out.mVertices[2]); } void HeightFieldGeometry::getTriangle(Triangle& out, Triangle& outEdge, unsigned int* flags, Index index, bool worldTrans, bool worldRot ) { NxTriangle triangle; NxTriangle edge; mHeightFieldShape->getTriangle(triangle, &edge, flags, index, worldTrans, worldRot); Functions::XYZ<NxVec3, Vec3>(triangle.verts[0], out.mVertices[0]); Functions::XYZ<NxVec3, Vec3>(triangle.verts[1], out.mVertices[1]); Functions::XYZ<NxVec3, Vec3>(triangle.verts[2], out.mVertices[2]); Functions::XYZ<NxVec3, Vec3>(edge.verts[0], outEdge.mVertices[0]); Functions::XYZ<NxVec3, Vec3>(edge.verts[1], outEdge.mVertices[1]); Functions::XYZ<NxVec3, Vec3>(edge.verts[2], outEdge.mVertices[2]); } bool HeightFieldGeometry::isPointOnHeightField(const Vec2& vec) { return mHeightFieldShape->isShapePointOnHeightField(vec.x, vec.y); } bool HeightFieldGeometry::isPointOnHeightField(Real x, Real z) { return mHeightFieldShape->isShapePointOnHeightField(x, z); } MaterialIdentifier HeightFieldGeometry::getMaterialAt(const Vec2& vec) { if (mHeightFieldShape == 0) return 0xFFFF; return mHeightFieldShape->getMaterialAtShapePoint(vec.x, vec.y); } MaterialIdentifier HeightFieldGeometry::getMaterialAt(Real x, Real z) { if (mHeightFieldShape == 0) return 0xFFFF; return mHeightFieldShape->getMaterialAtShapePoint(x, z); } Vec3 HeightFieldGeometry::getNormalAt(Real x, Real z) { if (mHeightFieldShape == 0) return Vec3::ZERO; return Functions::XYZ<NxVec3, Vec3>(mHeightFieldShape->getNormalAtShapePoint(x, z)); } Vec3 HeightFieldGeometry::getNormalAt(const Vec2& vec) { if (mHeightFieldShape == 0) return Vec3::ZERO; return Functions::XYZ<NxVec3, Vec3>(mHeightFieldShape->getNormalAtShapePoint(vec.x, vec.y)); } Vec3 HeightFieldGeometry::getSmoothNormalAt(Real x, Real z) { if (mHeightFieldShape == 0) return Vec3::ZERO; return Functions::XYZ<NxVec3, Vec3>(mHeightFieldShape->getSmoothNormalAtShapePoint(x, z)); } Vec3 HeightFieldGeometry::getSmoothNormalAt(const Vec2& vec) { if (mHeightFieldShape == 0) return Vec3::ZERO; return Functions::XYZ<NxVec3, Vec3>(mHeightFieldShape->getSmoothNormalAtShapePoint(vec.x, vec.y)); } } // namespace NxOgre
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 423 ] ] ]
48578c2d5d827886f7199b84977c48a611f90165
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/PlayerObject.cpp
03a2143d217de231fc745c25426ecb7e215fa135
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
GB18030
C++
false
false
4,043
cpp
#include "cltpch.h" #include "PlayerObject.h" #include "ClRegisterClass.h" #include "RemoteEvents.h" #include "KylinRoot.h" #include "uiMiniMapMenu.h" #include "rOgreRoot.h" #include "ActionDispatcher.h" #include "Action.h" #include "ClScriptFunction.h" #include "OgreOggSound.h" #ifdef _DEBUG #include "ClLobby.h" #endif namespace Kylin { BtImplementRTTI(PlayerObject, Character, id_player); Implement_Event_Handler(PlayerObject, Character) { {&ev_post_killed, &EV_Killed}, {&ev_post_reborn, &EV_Reborn}, {&ev_restore_hp, &EV_RestoreHP}, {&ev_learn_skill, &EV_LearnSkill}, {&ev_do_teleport, &Ev_Teleport}, {NULL, NULL} }; PlayerObject::PlayerObject() : m_fRebornTime(10.0f) { } KBOOL PlayerObject::Init( const PropertySet& kProp ) { if ( !Character::Init(kProp) ) return false; return true; } int ttstdaf = 0; KVOID PlayerObject::Tick( KFLOAT fElapsed ) { Character::Tick(fElapsed); // #ifdef _DEBUG // if (ttstdaf++ == 10) // { // KylinRoot::GetSingletonPtr()->SwitchStatus(KNEW ClLobby()); // ttstdaf = 0; // } // #endif } KVOID PlayerObject::PostSpawn() { Character::PostSpawn(); // 更新UI MiniMapMenu* pMenu = GET_GUI_PTR(MiniMapMenu); pMenu->SetMyself(this->GetID()); // //------------------------------- // // test code #ifdef _DEBUG // OgreRoot::GetSingletonPtr()->SetNextPolygonMode(); // OgreRoot::GetSingletonPtr()->SetNextPolygonMode(); #endif } KVOID PlayerObject::PostDestroy() { Character::PostDestroy(); } KBOOL PlayerObject::IsMyself() { return true; } KVOID PlayerObject::Reborn() { // EventPtr spEV( KNEW Event( &ev_post_reborn, Event::ev_timing, m_fRebornTime, 0, NULL )); KylinRoot::GetSingletonPtr()->PostMessage(this->GetID(),spEV); } KVOID PlayerObject::EV_Killed( EventPtr spEV ) { KUINT uKiller = boost::get<unsigned int>(spEV->args[0]); Dead(); } KVOID PlayerObject::EV_Reborn( EventPtr spEV ) { this->SetVisible(true); //----------------------------------------------------------------- // 设置出生点 KANY var; if (m_kProperty.GetValue("$BirthPosition",var)) { KPoint3 kPos = boost::any_cast<KPoint3>(var); this->SetTranslate(kPos); } if (m_kProperty.GetValue("$BirthRotation",var)) { KQuaternion kQua = boost::any_cast<KQuaternion>(var); this->SetRotation(kQua); } //----------------------------------------------------------------- // 重置生命 KINT nHp; m_kProperty.GetIntValue("$InitHP",nHp); m_kProperty.SetValue("$HP",nHp); m_eLifeStatus = LS_ALIVE; KylinRoot::GetSingletonPtr()->NotifyScriptEntity(this,"on_reborn"); } KVOID PlayerObject::Dead() { this->SetVisible(false); // 重生事件 Reborn(); } KVOID PlayerObject::EV_RestoreHP( EventPtr spEV ) { KINT nReHp = boost::get<int>(spEV->args[0]); AssertEx(nReHp > 0,"恢复的生命值不允许是负数!"); KINT nHp,nInitHp; m_kProperty.GetIntValue("$InitHP",nInitHp); m_kProperty.GetIntValue("$HP",nHp); nHp += nReHp; if (nHp + nReHp > nInitHp) nHp = nInitHp; m_kProperty.SetValue("$HP",nHp); } KVOID PlayerObject::EV_LearnSkill(EventPtr spEV) { KINT nSkill = boost::get<int>(spEV->args[0]); Script::to_learn_skill(this->GetID(),nSkill,true); } KVOID PlayerObject::Ev_Teleport( EventPtr spEV ) { KPoint3 pt(0,50000,0); pt.x = boost::get<float>(spEV->args[0]); pt.z = boost::get<float>(spEV->args[1]); KPoint3 ptRet(pt); if ( KylinRoot::GetSingletonPtr()->GetTerrainHeight(ptRet) )//HitTest(pt,KPoint3::NEGATIVE_UNIT_Y,ptRet) ) { pt.y = ptRet.y; this->SetTranslate(pt); } } KVOID PlayerObject::SetTranslate( KPoint3 kPos ) { Character::SetTranslate(kPos); SAFE_CALL(OgreOggSound::OgreOggSoundManager::getSingletonPtr()->getListener(),setPosition(kPos)); } }
[ [ [ 1, 189 ] ] ]
cac3f6d98d0f898f62f485173f55cf0c28c95821
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/Tool/ServerMonitor/PingThread.h
c17a9514fbd6031469aa91e5031eafd414738883
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
IBM852
C++
false
false
2,569
h
#pragma once const DWORD WM_MSG_STATUS = WM_USER + 100; const WORD wNoticeCode_Error = 0; const WORD wNoticeCode_UpdateNetAddr = 1; const WORD wNoticeCode_RequestTimedOut = 2; const WORD wNoticeCode_UpdateNetDelay = 3; struct tagNoticeHeader { WORD wNoticeCode; DWORD dwContext; }; struct tagNoticeError { tagNoticeHeader Header; DWORD dwSocketError; TCHAR szError[64]; }; struct tagNoticeUpdateNetAddr { tagNoticeHeader Header; TCHAR szNetAddr[64]; }; struct tagNoticeUpdateNetDelay { tagNoticeHeader Header; DWORD dwElapsed; }; ////////////////////////////////////////////////////////////////////////// #pragma pack(1) #define ICMP_ECHOREPLY 0 #define ICMP_ECHOREQ 8 typedef struct tagIPHDR { u_char VIHL; u_char TOS; short TotLen; short ID; short FlagOff; u_char TTL; u_char Protocol; u_short Checksum; struct in_addr iaSrc; struct in_addr iaDst; }IPHDR, *PIPHDR; typedef struct tagICMPHDR { u_char Type; u_char Code; u_short Checksum; u_short ID; u_short Seq; char Data; }ICMPHDR, *PICMPHDR; #define REQ_DATASIZE 32 typedef struct tagECHOREQUEST { ICMPHDR icmpHdr; DWORD dwTime; char cData[REQ_DATASIZE]; }ECHOREQUEST, *PECHOREQUEST; typedef struct tagECHOREPLY { IPHDR ipHdr; ECHOREQUEST echoRequest; char cFiller[256]; }ECHOREPLY, *PECHOREPLY; #pragma pack() ////////////////////////////////////////////////////////////////////////// struct tagPingTask { TCHAR szHost[128]; DWORD dwContext; }; typedef CArray<tagPingTask, tagPingTask> tagPingTask_Array; class CPingThread: public CServiceThread { public: CPingThread(void); ~CPingThread(void); void InitPing(HWND hWnd,BOOL *bContinue); void AddTask(LPCSTR lpstrHost, DWORD dwContext); private: //Run║»╩ř virtual bool RepetitionRun(); protected: void UpdateContext(DWORD dwContext); void Ping(UINT nRetries,LPCSTR pstrHost); int WaitForEchoReply(SOCKET s); int SendEchoRequest(SOCKET, LPSOCKADDR_IN); DWORD RecvEchoReply(SOCKET, LPSOCKADDR_IN, u_char *, DWORD*); u_short in_cksum(u_short *addr, int len); void UpdateNetDelay(DWORD dwElapsed, DWORD dwContext); void RequestTimedOut(); void UpdateNetAddr(LPCSTR pstrAddr); void WSAError(LPCSTR pstrFrom); protected: HWND m_hWnd; DWORD m_dwContext; BOOL* m_bContinue; ECHOREQUEST echoReq; u_short nId; u_short nSeq; tagPingTask_Array m_tagPingTask_Array; int m_nCurTaskIndex; CThreadLock m_TaskLock; };
[ [ [ 1, 119 ] ] ]
18524b827c25682921f4839b29b0367892b1a403
c6311b5096eeed35f7b8cdb5c228de915075eb71
/tp3/Tp_3_Mundial2010v1/MainDialog.cpp
d0e8d5c9cee385341fde88dca9a07753b108dda5
[]
no_license
kevinalle/metnum2010
5dccdba68bb4d3065c6a696f02836e7119eba657
142a5464429e564c13aabd339a7b01800ea9023e
refs/heads/master
2020-05-28T05:01:34.835358
2010-07-23T19:19:27
2010-07-23T19:19:27
32,120,707
0
0
null
null
null
null
UTF-8
C++
false
false
14,614
cpp
/** \file \author Pablo Haramburu Copyright: Copyright (C)2010 Pablo Haramburu. License: This file is part of mundial2010. mundial2010 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mundial2010 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mundial2010. If not, see <http://www.gnu.org/licenses/>. */ // Generated by DialogBlocks (unregistered), 31/05/2010 13:18:00 // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include "MainDialog.h" #include <wx/filedlg.h> #include <wx/wupdlock.h> ////@begin XPM images ////@end XPM images /*! * MainDialog type definition */ IMPLEMENT_DYNAMIC_CLASS( MainDialog, wxDialog ) /*! * MainDialog event table definition */ BEGIN_EVENT_TABLE( MainDialog, wxDialog ) ////@begin MainDialog event table entries EVT_BUTTON( ID_ADD_GOALKEEPER_BUTTON, MainDialog::OnAddGoalkeeperButtonClick ) EVT_BUTTON( ID_ADD_TESTFILE_BUTTON, MainDialog::OnAddTestfileButtonClick ) EVT_BUTTON( ID_RUN_TESTS_BUTTON, MainDialog::OnRunTestsButtonClick ) EVT_UPDATE_UI( ID_RUN_TESTS_BUTTON, MainDialog::OnRunTestsButtonUpdate ) ////@end MainDialog event table entries END_EVENT_TABLE() /*! * MainDialog constructors */ MainDialog::MainDialog() { Init(); } MainDialog::MainDialog( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create(parent, id, caption, pos, size, style); } /*! * MainDialog creator */ bool MainDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin MainDialog creation SetExtraStyle(wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end MainDialog creation return true; } /*! * MainDialog destructor */ MainDialog::~MainDialog() { ////@begin MainDialog destruction ////@end MainDialog destruction } /*! * Member initialisation */ void MainDialog::Init() { ////@begin MainDialog member initialisation m_goalkeepers = NULL; m_testfiles = NULL; ////@end MainDialog member initialisation } /*! * Control creation for MainDialog */ void MainDialog::CreateControls() { ////@begin MainDialog content construction // Generated by DialogBlocks, 01/06/2010 04:00:41 (unregistered) MainDialog* itemDialog1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemDialog1->SetSizer(itemBoxSizer2); wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer3, 0, wxGROW, 5); wxStaticText* itemStaticText4 = new wxStaticText( itemDialog1, wxID_STATIC, _("Arquero(s):"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer3->Add(itemStaticText4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemBoxSizer3->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton6 = new wxButton( itemDialog1, ID_ADD_GOALKEEPER_BUTTON, _("Agregar"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer3->Add(itemButton6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString m_goalkeepersStrings; m_goalkeepers = new wxListBox( itemDialog1, ID_GOALKEEPERS_LISTBOX, wxDefaultPosition, wxDefaultSize, m_goalkeepersStrings, wxLB_EXTENDED ); itemBoxSizer2->Add(m_goalkeepers, 1, wxGROW|wxALL, 5); wxBoxSizer* itemBoxSizer8 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer8, 0, wxGROW, 5); wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("Archivos de entrada:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer8->Add(itemStaticText9, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemBoxSizer8->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton11 = new wxButton( itemDialog1, ID_ADD_TESTFILE_BUTTON, _("Agregar"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer8->Add(itemButton11, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString m_testfilesStrings; m_testfiles = new wxListBox( itemDialog1, ID_TESTSFILES_LISTBOX, wxDefaultPosition, wxDefaultSize, m_testfilesStrings, wxLB_EXTENDED ); itemBoxSizer2->Add(m_testfiles, 0, wxGROW|wxALL, 5); m_showAnimation = new wxCheckBox( itemDialog1, wxID_ANY, _("Mostrar animacion") ); itemBoxSizer2->Add(m_showAnimation, 0, wxALIGN_LEFT|wxALL, 5); wxBoxSizer* itemBoxSizer13 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer13, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxButton* itemButton14 = new wxButton( itemDialog1, ID_RUN_TESTS_BUTTON, _("&Probar!"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer13->Add(itemButton14, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton15 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer13->Add(itemButton15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); // Connect events and objects m_goalkeepers->Connect(ID_GOALKEEPERS_LISTBOX, wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::OnGoalkeepersListboxKeyDown), NULL, this); m_testfiles->Connect(ID_TESTSFILES_LISTBOX, wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::OnTestsfilesListboxKeyDown), NULL, this); ////@end MainDialog content construction m_showAnimation->SetValue(true); //inicializamos el contenido de las listas { wxArrayString paths; m_model.getGoalkeepers(paths); m_goalkeepers->Append(paths); } { wxArrayString paths; m_model.getTestfiles(paths); m_testfiles->Append(paths); } } /*! * Should we show tooltips? */ bool MainDialog::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap MainDialog::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin MainDialog bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end MainDialog bitmap retrieval } /*! * Get icon resources */ wxIcon MainDialog::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin MainDialog icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end MainDialog icon retrieval } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ADD_GOALKEEPER_BUTTON */ void MainDialog::OnAddGoalkeeperButtonClick( wxCommandEvent& event ) { wxFileDialog dlg(this, _("Seleccione archivos de arqueros"), wxT(""), wxT(""), _("Ejecutables (*.exe)|*.exe|Todos los archivos (*.*)|*.*"), wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_CHANGE_DIR); if (dlg.ShowModal() == wxID_OK) { wxArrayString paths; dlg.GetPaths(paths); m_model.addGoalkeepers(paths); m_model.getGoalkeepers(paths); wxWindowUpdateLocker lock(this); m_goalkeepers->Clear(); m_goalkeepers->Append(paths); } } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ADD_TESTFILE_BUTTON */ void MainDialog::OnAddTestfileButtonClick( wxCommandEvent& event ) { wxFileDialog dlg(this, _("Seleccione archivos de prueba"), wxT(""), wxT(""), _("Todos los archivos (*.*)|*.*"), wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_CHANGE_DIR); if (dlg.ShowModal() == wxID_OK) { wxArrayString paths; dlg.GetPaths(paths); m_model.addTestfiles(paths); m_model.getTestfiles(paths); wxWindowUpdateLocker lock(this); m_testfiles->Clear(); m_testfiles->Append(paths); } } class TooSimpleGUI : public ITestGUI { public: TooSimpleGUI(wxWindow * parent) : m_parent(parent) {} public: /// \name ITestGUI virtual void testingStarts() {} virtual void testingEnded() {} virtual void setGoalkeeperName(const wxString & name) { m_goalkeeper = name; } virtual void setTestName(const wxString & name) { m_testfile = name; } virtual void goalkeeperStarts() {} virtual void goalkeeperEnded() {} virtual void reportTestFailure(const wxString & message) { wxString s; s += _("Arquero: ") + m_goalkeeper + wxT("\n"); s += _("Test: ") + m_testfile + wxT("\n"); s += message; wxMessageBox(s, _("Fallo el test"), wxOK, m_parent); } virtual void reportSimulation(bool isGoal, const std::vector<SimulationStep> & simulation) { wxString s; s += _("Arquero: ") + m_goalkeeper + wxT("\n"); s += _("Test: ") + m_testfile + wxT("\n"); s += isGoal ? _("Goool !!") : _("El arqueeero !!"); wxMessageBox(s, _("Resultado"), wxOK, m_parent); } private: wxWindow * m_parent; wxString m_goalkeeper; wxString m_testfile; }; #include "TestResultsDialog.h" class SimpleGUI : public ITestGUI { public: SimpleGUI(wxWindow * parent) : m_dlg(parent), m_catched(0), m_total(0) {} public: /// \name ITestGUI virtual void testingStarts() { m_dlg.m_cancelBtn->Disable(); m_dlg.Show(); } virtual void testingEnded() { m_dlg.Hide(); m_dlg.m_cancelBtn->Enable(); m_dlg.ShowModal(); } virtual void setGoalkeeperName(const wxString & name) { m_goalkeeper = name; m_catched = 0; m_total = 0; long item = m_dlg.m_summary->InsertItem(m_dlg.m_summary->GetItemCount(), m_goalkeeper); m_dlg.m_summary->SetItem(item, 1, wxString() << m_catched); m_dlg.m_summary->SetItem(item, 2, wxString() << m_total); } virtual void setTestName(const wxString & name) { m_testfile = name; } virtual void goalkeeperStarts() {} virtual void goalkeeperEnded() {} virtual void reportTestFailure(const wxString & message) { wxString s; s += _("Arquero: ") + m_goalkeeper + wxT("\n"); s += _("Test: ") + m_testfile + wxT("\n"); s += message; wxMessageBox(s, _("Fallo el test"), wxOK, &m_dlg); } virtual void reportSimulation(bool isGoal, const std::vector<SimulationStep> & simulation) { long item = m_dlg.m_results->InsertItem(m_dlg.m_results->GetItemCount(), m_goalkeeper); m_dlg.m_results->SetItem(item, 1, m_testfile); m_dlg.m_results->SetItem(item, 2, isGoal ? _("Goool !!") : _("El arqueeero !!")); if (!isGoal) ++m_catched; ++m_total; item = m_dlg.m_summary->GetItemCount()-1; //zero-based m_dlg.m_summary->SetItem(item, 1, wxString() << m_catched); m_dlg.m_summary->SetItem(item, 2, wxString() << m_total); } private: TestResultsDialog m_dlg; wxString m_goalkeeper; wxString m_testfile; size_t m_catched; size_t m_total; }; #include "ShotAnimationDialog.h" class AnimationGUI : public ITestGUI { public: AnimationGUI(wxWindow * parent) : m_dlg(parent), m_catched(0), m_total(0), m_cancelled(false) {} public: /// \name ITestGUI virtual void testingStarts() { m_dlg.Show(); } virtual void testingEnded() { m_dlg.Hide(); if (!m_cancelled) m_dlg.ShowModal(); } virtual void setGoalkeeperName(const wxString & name) { m_goalkeeper = name; m_catched = 0; m_total = 0; m_dlg.m_goalkeeper->SetValue(m_goalkeeper); } virtual void setTestName(const wxString & name) { m_testfile = name; m_dlg.m_testfile->SetValue(m_testfile); } virtual void goalkeeperStarts() {} virtual void goalkeeperEnded() {} virtual void reportTestFailure(const wxString & message) { wxString s; s += _("Arquero: ") + m_goalkeeper + wxT("\n"); s += _("Test: ") + m_testfile + wxT("\n"); s += message; wxMessageBox(s, _("Fallo el test"), wxOK, &m_dlg); } virtual void reportSimulation(bool isGoal, const std::vector<SimulationStep> & simulation) { if (!isGoal) ++m_catched; ++m_total; m_dlg.m_goalkeeper->SetValue(m_goalkeeper); m_dlg.m_testfile->SetValue(m_testfile); m_dlg.setSimulation(simulation); if (!m_cancelled) { m_dlg.Hide(); m_cancelled = wxID_CANCEL == m_dlg.ShowModal(); m_dlg.Show(); } } private: ShotAnimationDialog m_dlg; wxString m_goalkeeper; wxString m_testfile; size_t m_catched; size_t m_total; bool m_cancelled; }; /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RUN_TESTS_BUTTON */ void MainDialog::OnRunTestsButtonClick( wxCommandEvent& event ) { //TooSimpleGUI gui(this); if (m_showAnimation->IsChecked()) { AnimationGUI gui(this); m_model.runTests(gui); } else { SimpleGUI gui(this); m_model.runTests(gui); } } /*! * wxEVT_UPDATE_UI event handler for ID_RUN_TESTS_BUTTON */ void MainDialog::OnRunTestsButtonUpdate( wxUpdateUIEvent& event ) { event.Enable(m_model.canRunTests()); } void collectSelection(wxListBox * lst, wxArrayString & items) { wxArrayInt selection; int nSelect = lst->GetSelections(selection); if (nSelect <= 0 || nSelect != selection.size()) return; items.clear(); items.reserve(nSelect); for (size_t i = 0; i < nSelect; ++i) { wxString s = lst->GetString(selection[i]); assert(!s.empty()); if (!s.empty()) items.push_back(s); } } /*! * wxEVT_KEY_DOWN event handler for ID_GOALKEEPERS_LISTBOX */ void MainDialog::OnGoalkeepersListboxKeyDown( wxKeyEvent& event ) { if (event.GetKeyCode() == WXK_DELETE) //untranslated non-unicode... { wxArrayString paths; collectSelection(m_goalkeepers, paths); if (!paths.empty()) { m_model.deleteGoalkeepers(paths); m_model.getGoalkeepers(paths); wxWindowUpdateLocker lock(this); m_goalkeepers->Clear(); m_goalkeepers->Append(paths); return; } } event.Skip(); } /*! * wxEVT_KEY_DOWN event handler for ID_TESTSFILES_LISTBOX */ void MainDialog::OnTestsfilesListboxKeyDown( wxKeyEvent& event ) { if (event.GetKeyCode() == WXK_DELETE) //untranslated non-unicode... { wxArrayString paths; collectSelection(m_testfiles, paths); if (!paths.empty()) { m_model.deleteTestfiles(paths); m_model.getTestfiles(paths); wxWindowUpdateLocker lock(this); m_testfiles->Clear(); m_testfiles->Append(paths); return; } } event.Skip(); }
[ "kevinalle@8062f241-9d54-ddaa-24e5-4d4b1e181026" ]
[ [ [ 1, 523 ] ] ]
ba27ce53808e39d17d23106ea9dbbcb3708187d6
65009c85bdacd1e7bb64ea9264b284c4fbc44207
/bbAnalog/MessageBox.h
8c8335891f2e514db0794c506f15045b8cceb02d
[]
no_license
Tobbe/bbPlugLdr
e184205e2d7def9f1f77462b5e7ef18b10eb3b52
3ecf92fdf4954f33def44c2d042b7628fb38d769
refs/heads/master
2016-09-10T17:07:59.242760
2011-08-02T12:06:23
2011-08-02T12:06:23
2,124,897
1
1
null
null
null
null
UTF-8
C++
false
false
2,091
h
// MessageBox.h: Wrapper class for MessageBoxIndirect and MSGBOXPARAMS // // (C) 2000, Peter Kenyon <[email protected]> // // Features: 1) Easy way to create message boxes with custom icons // 2) Allows you to use string resources in a message box // 3) MFC-like : Simply construct a CMessageBox object and call // DoModal(). // // 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. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MESSAGEBOX_H__A2893FB7_C936_11D3_B0FA_0040054C5E60__INCLUDED_) #define AFX_MESSAGEBOX_H__A2893FB7_C936_11D3_B0FA_0040054C5E60__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <windows.h> #include <tchar.h> class CMessageBox : public MSGBOXPARAMS { public: CMessageBox(); CMessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType = MB_OK, HINSTANCE hInst = GetModuleHandle(NULL)); CMessageBox(HWND hWnd, UINT uText, UINT uCaption, UINT uType = MB_OK, HINSTANCE hInst = GetModuleHandle(NULL)); void SetIcon(LPCTSTR lpIcon, HINSTANCE hInstance = GetModuleHandle(NULL)); void SetIcon(UINT uIcon, HINSTANCE hInstance = GetModuleHandle(NULL)); void SetLangID(DWORD dwLang) { dwLanguageId = dwLang; } ; void SetHelpContext(DWORD dwHC) { dwContextHelpId = dwHC; } ; void SetStyle(DWORD dwMBStyle) { dwStyle = dwMBStyle; } ; void SetHelpCallback(MSGBOXCALLBACK mbCallback) { lpfnMsgBoxCallback = mbCallback; } ; void SetText(LPCTSTR pszText) { lpszText = pszText; } void SetText(UINT uText) { lpszText = MAKEINTRESOURCE(uText); } void SetCaption(LPCTSTR pszCaption) { lpszCaption = pszCaption; } void SetCaption(UINT uCaption) { lpszCaption = MAKEINTRESOURCE(uCaption); } int DoModal() { return ::MessageBoxIndirect(this); } ; }; #endif // !defined(AFX_MESSAGEBOX_H__A2893FB7_C936_11D3_B0FA_0040054C5E60__INCLUDED_)
[ [ [ 1, 50 ] ] ]
fd4ba314216d61a16d29825239d5faf65588e4a2
11af1673bab82ca2329ef8b596d1f3d2f8b82481
/source/cgame/cg_drawtools.cpp
6ce59ca0305218bda4f28162dc8cb5c491e4fa0e
[]
no_license
legacyrp/legacyojp
8b33ecf24fd973bee5e7adbd369748cfdd891202
d918151e917ea06e8698f423bbe2cf6ab9d7f180
refs/heads/master
2021-01-10T20:09:55.748893
2011-04-18T21:07:13
2011-04-18T21:07:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,763
cpp
// Copyright (C) 1999-2000 Id Software, Inc. // // cg_drawtools.c -- helper functions called by cg_draw, cg_scoreboard, cg_info, etc #include "cg_local.h" #include "../game/q_shared.h" /* ================ UI_DrawRect Coordinates are 640*480 virtual values ================= */ void CG_DrawRect( float x, float y, float width, float height, float size, const float *color ) { trap_R_SetColor( color ); CG_DrawTopBottom(x, y, width, height, size); CG_DrawSides(x, y, width, height, size); trap_R_SetColor( NULL ); } /* ================= CG_GetColorForHealth ================= */ void CG_GetColorForHealth( int health, int armor, vec4_t hcolor ) { int count; int max; // calculate the total points of damage that can // be sustained at the current health / armor level if ( health <= 0 ) { VectorClear( hcolor ); // black hcolor[3] = 1; return; } count = armor; max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION ); if ( max < count ) { count = max; } health += count; // set the color based on health hcolor[0] = 1.0; hcolor[3] = 1.0; if ( health >= 100 ) { hcolor[2] = 1.0; } else if ( health < 66 ) { hcolor[2] = 0; } else { hcolor[2] = ( health - 66 ) / 33.0; } if ( health > 60 ) { hcolor[1] = 1.0; } else if ( health < 30 ) { hcolor[1] = 0; } else { hcolor[1] = ( health - 30 ) / 30.0; } } /* ================ CG_DrawSides Coords are virtual 640x480 ================ */ void CG_DrawSides(float x, float y, float w, float h, float size) { size *= cgs.screenXScale; trap_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); trap_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); } void CG_DrawTopBottom(float x, float y, float w, float h, float size) { size *= cgs.screenYScale; trap_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); trap_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); } /* ------------------------- CGC_FillRect2 real coords ------------------------- */ void CG_FillRect2( float x, float y, float width, float height, const float *color ) { trap_R_SetColor( color ); trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); trap_R_SetColor( NULL ); } /* ================ CG_FillRect Coordinates are 640*480 virtual values ================= */ void CG_FillRect( float x, float y, float width, float height, const float *color ) { trap_R_SetColor( color ); trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); trap_R_SetColor( NULL ); } /* ================ CG_DrawPic Coordinates are 640*480 virtual values A width of 0 will draw with the original image width ================= */ void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { trap_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); } /* ================ CG_DrawRotatePic Coordinates are 640*480 virtual values A width of 0 will draw with the original image width rotates around the upper right corner of the passed in point ================= */ void CG_DrawRotatePic( float x, float y, float width, float height,float angle, qhandle_t hShader ) { trap_R_DrawRotatePic( x, y, width, height, 0, 0, 1, 1, angle, hShader ); } /* ================ CG_DrawRotatePic2 Coordinates are 640*480 virtual values A width of 0 will draw with the original image width Actually rotates around the center point of the passed in coordinates ================= */ void CG_DrawRotatePic2( float x, float y, float width, float height,float angle, qhandle_t hShader ) { trap_R_DrawRotatePic2( x, y, width, height, 0, 0, 1, 1, angle, hShader ); } /* =============== CG_DrawChar Coordinates and size in 640*480 virtual screen size =============== */ void CG_DrawChar( int x, int y, int width, int height, int ch ) { int row, col; float frow, fcol; float size; float ax, ay, aw, ah; float size2; ch &= 255; if ( ch == ' ' ) { return; } ax = x; ay = y; aw = width; ah = height; row = ch>>4; col = ch&15; frow = row*0.0625; fcol = col*0.0625; size = 0.03125; size2 = 0.0625; trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cgs.media.charsetShader ); } /* ================== CG_DrawStringExt Draws a multi-colored string with a drop shadow, optionally forcing to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ //[SVN] //rearraigned repository to make it easier to initially compile. #include "../../jke/ui/jamp/menudef.h" //[/SVN] void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, qboolean forceColor, qboolean shadow, int charWidth, int charHeight, int maxChars ) { if (trap_Language_IsAsian()) { // hack-a-doodle-do (post-release quick fix code)... // vec4_t color; memcpy(color,setColor, sizeof(color)); // de-const it CG_Text_Paint(x, y, 1.0f, // float scale, color, // vec4_t color, string, // const char *text, 0.0f, // float adjust, 0, // int limit, shadow ? ITEM_TEXTSTYLE_SHADOWED : 0, // int style, FONT_MEDIUM // iMenuFont ) ; } else { vec4_t color; const char *s; int xx; // draw the drop shadow if (shadow) { color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; trap_R_SetColor( color ); s = string; xx = x; while ( *s ) { if ( Q_IsColorString( s ) ) { s += 2; continue; } CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s ); xx += charWidth; s++; } } // draw the colored text s = string; xx = x; trap_R_SetColor( setColor ); while ( *s ) { if ( Q_IsColorString( s ) ) { if ( !forceColor ) { memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); color[3] = setColor[3]; trap_R_SetColor( color ); } s += 2; continue; } CG_DrawChar( xx, y, charWidth, charHeight, *s ); xx += charWidth; s++; } trap_R_SetColor( NULL ); } } void CG_DrawBigString( int x, int y, const char *s, float alpha ) { float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; CG_DrawStringExt( x, y, s, color, qfalse, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 ); } void CG_DrawBigStringColor( int x, int y, const char *s, vec4_t color ) { CG_DrawStringExt( x, y, s, color, qtrue, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 ); } void CG_DrawSmallString( int x, int y, const char *s, float alpha ) { float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; CG_DrawStringExt( x, y, s, color, qfalse, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); } void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) { CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); } /* ================= CG_DrawStrlen Returns character count, skiping color escape codes ================= */ int CG_DrawStrlen( const char *str ) { const char *s = str; int count = 0; while ( *s ) { if ( Q_IsColorString( s ) ) { s += 2; } else { count++; s++; } } return count; } /* ============= CG_TileClearBox This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) { float s1, t1, s2, t2; s1 = x/64.0; t1 = y/64.0; s2 = (x+w)/64.0; t2 = (y+h)/64.0; trap_R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); } /* ============== CG_TileClear Clear around a sized down screen ============== */ void CG_TileClear( void ) { int top, bottom, left, right; int w, h; w = cgs.glconfig.vidWidth; h = cgs.glconfig.vidHeight; if ( cg.refdef.x == 0 && cg.refdef.y == 0 && cg.refdef.width == w && cg.refdef.height == h ) { return; // full screen rendering } top = cg.refdef.y; bottom = top + cg.refdef.height-1; left = cg.refdef.x; right = left + cg.refdef.width-1; // clear above view screen CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader ); // clear below view screen CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader ); // clear left of view screen CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader ); // clear right of view screen CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader ); } /* ================ CG_FadeColor ================ */ float *CG_FadeColor( int startMsec, int totalMsec ) { static vec4_t color; int t; if ( startMsec == 0 ) { return NULL; } t = cg.time - startMsec; if ( t >= totalMsec ) { return NULL; } // fade out if ( totalMsec - t < FADE_TIME ) { color[3] = ( totalMsec - t ) * 1.0/FADE_TIME; } else { color[3] = 1.0; } color[0] = color[1] = color[2] = 1; return color; } /* ================= CG_ColorForHealth ================= */ void CG_ColorForGivenHealth( vec4_t hcolor, int health ) { // set the color based on health hcolor[0] = 1.0; if ( health >= 100 ) { hcolor[2] = 1.0; } else if ( health < 66 ) { hcolor[2] = 0; } else { hcolor[2] = ( health - 66 ) / 33.0; } if ( health > 60 ) { hcolor[1] = 1.0; } else if ( health < 30 ) { hcolor[1] = 0; } else { hcolor[1] = ( health - 30 ) / 30.0; } } /* ================= CG_ColorForHealth ================= */ void CG_ColorForHealth( vec4_t hcolor ) { int health; int count; int max; // calculate the total points of damage that can // be sustained at the current health / armor level health = cg.snap->ps.stats[STAT_HEALTH]; if ( health <= 0 ) { VectorClear( hcolor ); // black hcolor[3] = 1; return; } count = cg.snap->ps.stats[STAT_ARMOR]; max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION ); if ( max < count ) { count = max; } health += count; hcolor[3] = 1.0; CG_ColorForGivenHealth( hcolor, health ); } /* ============== CG_DrawNumField Take x,y positions as if 640 x 480 and scales them to the proper resolution ============== */ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charHeight,int style,qboolean zeroFill) { char num[16], *ptr; int l; int frame; int xWidth; int i = 0; if (width < 1) { return; } // draw number string if (width > 5) { width = 5; } switch ( width ) { case 1: value = value > 9 ? 9 : value; value = value < 0 ? 0 : value; break; case 2: value = value > 99 ? 99 : value; value = value < -9 ? -9 : value; break; case 3: value = value > 999 ? 999 : value; value = value < -99 ? -99 : value; break; case 4: value = value > 9999 ? 9999 : value; value = value < -999 ? -999 : value; break; } Com_sprintf (num, sizeof(num), "%i", value); l = strlen(num); if (l > width) l = width; // FIXME: Might need to do something different for the chunky font?? switch(style) { case NUM_FONT_SMALL: xWidth = charWidth; break; case NUM_FONT_CHUNKY: xWidth = (charWidth/1.2f) + 2; break; default: case NUM_FONT_BIG: xWidth = (charWidth/2) + 7;//(charWidth/6); break; } if ( zeroFill ) { for (i = 0; i < (width - l); i++ ) { switch(style) { case NUM_FONT_SMALL: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[0] ); break; case NUM_FONT_CHUNKY: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0] ); break; default: case NUM_FONT_BIG: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[0] ); break; } x += 2 + (xWidth); } } else { x += 2 + (xWidth)*(width - l); } ptr = num; while (*ptr && l) { if (*ptr == '-') frame = STAT_MINUS; else frame = *ptr -'0'; switch(style) { case NUM_FONT_SMALL: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[frame] ); x++; // For a one line gap break; case NUM_FONT_CHUNKY: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame] ); break; default: case NUM_FONT_BIG: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[frame] ); break; } x += (xWidth); ptr++; l--; } } #include "../ui/ui_shared.h" // for some text style junk void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) { // having all these different style defines (1 for UI, one for CG, and now one for the re->font stuff) // is dumb, but for now... // int iStyle = 0; int iMenuFont = (style & UI_SMALLFONT) ? FONT_SMALL : FONT_MEDIUM; switch (style & (UI_LEFT|UI_CENTER|UI_RIGHT)) { default: case UI_LEFT: { // nada... } break; case UI_CENTER: { x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; } break; case UI_RIGHT: { x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; } break; } if (style & UI_DROPSHADOW) { iStyle = ITEM_TEXTSTYLE_SHADOWED; } else if ( style & (UI_BLINK|UI_PULSE) ) { iStyle = ITEM_TEXTSTYLE_BLINK; } CG_Text_Paint(x, y, 1.0, color, str, 0, 0, iStyle, iMenuFont); } void UI_DrawScaledProportionalString( int x, int y, const char* str, int style, vec4_t color, float scale) { // having all these different style defines (1 for UI, one for CG, and now one for the re->font stuff) // is dumb, but for now... // int iStyle = 0; switch (style & (UI_LEFT|UI_CENTER|UI_RIGHT)) { default: case UI_LEFT: { // nada... } break; case UI_CENTER: { x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; } break; case UI_RIGHT: { x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; } break; } if (style & UI_DROPSHADOW) { iStyle = ITEM_TEXTSTYLE_SHADOWED; } else if ( style & (UI_BLINK|UI_PULSE) ) { iStyle = ITEM_TEXTSTYLE_BLINK; } CG_Text_Paint(x, y, scale, color, str, 0, 0, iStyle, FONT_MEDIUM); } //[UiEnhanceSys] void UI_OJPDrawColouredString( int x, int y, const char* str, vec4_t color) { float scale; //set the defaults scale = 0.5; CG_Text_Paint(x, y, scale, color, str, 0, 0, ITEM_TEXTSTYLE_SHADOWED, FONT_SMALL); } //[/UiEnhanceSys]
[ "[email protected]@5776d9f2-9662-11de-ad41-3fcdc5e0e42d" ]
[ [ [ 1, 695 ] ] ]
6d6ccfbd0df29bfb1b0f9d1a040750b13ce56e51
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Renderer/D3D10LineTexture.cpp
e76bc690a825e809d9c9c56526f5e900031d3209
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
3,295
cpp
#include "D3D10LineTexture.h" #include "D3D10RenderWindow.h" namespace Flagship { D3D10LineTexture::D3D10LineTexture() { m_pD3D10LineTexture = NULL; m_pD3D10ShaderResource = NULL; m_iClassType = Base::Texture_Line; } D3D10LineTexture::~D3D10LineTexture() { SAFE_RELEASE( m_pD3D10LineTexture ); SAFE_RELEASE( m_pD3D10ShaderResource ); } ID3D10Texture1D * D3D10LineTexture::GetImpliment() { return m_pD3D10LineTexture; } ID3D10ShaderResourceView * D3D10LineTexture::GetShaderResourceView() { return m_pD3D10ShaderResource; } bool D3D10LineTexture::CreateFromMemory() { // 获取D3D10设备指针 ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice(); // 创建D3D10贴图对象 D3DX10_IMAGE_LOAD_INFO LoadInfo; LoadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE; ID3D10Resource * pResource; HRESULT hr = D3DX10CreateTextureFromMemory( pD3D10Device, m_kFileBuffer.GetPointer() , m_kFileBuffer.GetSize(), &LoadInfo, NULL, &pResource, NULL ); pResource->QueryInterface( __uuidof( ID3D10Texture1D ), (LPVOID*)&m_pD3D10LineTexture ); pD3D10Device->CreateShaderResourceView( m_pD3D10LineTexture, NULL, &m_pD3D10ShaderResource ); SAFE_RELEASE( pResource ); if ( FAILED( hr ) ) { char szLog[10240]; char szFile[256]; wcstombs( szFile, m_szPathName.c_str(), 256 ); sprintf( szLog, "D3D10LineTexture::CreateFromMemory() Fail! File:%s", szFile ); LogManager::GetSingleton()->WriteLog( szLog ); return false; } return true; } bool D3D10LineTexture::CreateDynamic( UINT uiWidth, UINT uiHeight, DWORD dwFormat ) { // 获取D3D10设备指针 ID3D10Device * pD3D10Device = ( ( D3D10RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice(); // 创建D3D10贴图对象 D3D10_TEXTURE1D_DESC Desc; Desc.Width = uiWidth; Desc.MipLevels = 1; Desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; Desc.Usage = D3D10_USAGE_DYNAMIC; Desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; Desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; Desc.MiscFlags = 0; Desc.ArraySize = 1; HRESULT hr = pD3D10Device->CreateTexture1D( &Desc, NULL, &m_pD3D10LineTexture ); pD3D10Device->CreateShaderResourceView( m_pD3D10LineTexture, NULL, &m_pD3D10ShaderResource ); if ( FAILED( hr ) ) { char szLog[10240]; sprintf( szLog, "D3D10LineTexture::CreateRenderTexture() Fail! Format:%d", (int)dwFormat ); LogManager::GetSingleton()->WriteLog( szLog ); return false; } return true; } bool D3D10LineTexture::ClearTexture() { return true; } bool D3D10LineTexture::Lock( int& rPitch, void ** ppData ) { HRESULT hr = m_pD3D10LineTexture->Map( 0, D3D10_MAP_WRITE_DISCARD, 0, ppData ); if ( FAILED( hr ) ) { char szLog[10240]; sprintf( szLog, "D3D10LineTexture::Lock() Fail!" ); LogManager::GetSingleton()->WriteLog( szLog ); return false; } return true; } void D3D10LineTexture::UnLock() { m_pD3D10LineTexture->Unmap( 0 ); } void D3D10LineTexture::UnCache() { Texture::UnCache(); SAFE_RELEASE( m_pD3D10LineTexture ); SAFE_RELEASE( m_pD3D10ShaderResource ); } }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 122 ] ] ]
dbebe4f529dfc25b52f2af7bfbb8f6c7a28f211b
09f09cd06656848ed80f132c7073568c4ce87bd5
/CBIR/Retrieval/RetrievallView.h
5243da34d2a65e78cb6407739f821f7812051f5f
[]
no_license
cyb3727/annrecognition
90ecf3af572f8b629b276a06af51785f656ca2be
6e4f200e1119196eba5e7fe56efa93e3ed978bc1
refs/heads/master
2021-01-17T11:31:39.865232
2011-07-10T13:50:44
2011-07-10T13:50:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,910
h
#if !defined(AFX_RETRIEVALLVIEW_H__0D9D7609_89D7_4D03_83A9_ABB468635411__INCLUDED_) #define AFX_RETRIEVALLVIEW_H__0D9D7609_89D7_4D03_83A9_ABB468635411__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // RetrievallView.h : header file // #include "retrievalDoc.h" ///////////////////////////////////////////////////////////////////////////// // CRetrievallView view class CRetrievallView : public CScrollView { protected: CRetrievallView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CRetrievallView) // Attributes public: CRetrievalDoc* GetDocument(); float mintwo(float a,float b){return a<b?a:b;} float Caculate(int,int,int,int); float distance(int,int,int,int); float distance_weight(int,int,int,int); void RGBToMTM(int r,int g,int b,double *h,double *v,double *c); void RGBToHSV(int r,int g,int b,double *h,double *s,double *v); int mymin(int,int,int); int mymax(int,int,int); double mtm_fun(double); void hsv_general(int); void hsv_succession(int); void hsv_centerM(int); void mtm_general(int); void mtm_succession(int); void mtm_centerM(int); float result_te[40]; int cixu[40]; float tezheng[3][12]; void sortimage(int); int m_exam; bool if_lbd; bool ifSelect; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CRetrievallView) protected: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual void OnInitialUpdate(); // first time after construct //}}AFX_VIRTUAL // Implementation protected: virtual ~CRetrievallView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions //{{AFX_MSG(CRetrievallView) afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnHSV_GEN_OU(); afx_msg void OnHSV_GEN_QUAN(); afx_msg void OnHSV_GEN_JIAO(); afx_msg void OnHSV_SUC_OU(); afx_msg void OnHSV_CEN_OU(); afx_msg void OnMTM_GEN_OU(); afx_msg void OnMTM_GEN_QUAN(); afx_msg void OnMTM_GEN_JIAO(); afx_msg void OnMTM_SUC_OU(); afx_msg void OnMTM_CEN_OU(); afx_msg void OnHSV1_2(); afx_msg void OnHSV2_2(); afx_msg void OnHSV3_2(); afx_msg void OnHSV4_2(); afx_msg void OnHSV4_3(); afx_msg void OnHSV5_2(); afx_msg void OnRotate(); afx_msg void OnBig(); afx_msg void OnSmall(); afx_msg void OnMove(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RETRIEVALLVIEW_H__0D9D7609_89D7_4D03_83A9_ABB468635411__INCLUDED_)
[ "damoguyan8844@2e4fddd8-cc6a-11de-b393-33af5e5426e5" ]
[ [ [ 1, 106 ] ] ]
473d0cd289587855f759d40315465b2d41096f18
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/include/dockingwindows/DockImpl.cpp
f0d96a1c22d7e9ff484a78534719de37cee86098
[]
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
2,097
cpp
// Copyright (c) 2002 // Sergey Klimov ([email protected]) // WTL Docking windows // // This code is provided "as is", with absolutely no warranty expressed // or implied. Any use is at your own risk. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name is included. If // the source code in this file is used in any commercial application // then a simple email woulod be nice. #include "DockMisc.h" #include "DockingBox.h" namespace dockwins{ CDWSettings::CSettings CDWSettings::settings; CDockingBoxMessage CDockingBox::m_message; #ifdef DF_AUTO_HIDE_FEATURES COutlookLikeCaption ::CPinButton::CIcons COutlookLikeCaption ::CPinButton::m_icons; CVC6LikeCaption::CPinButton::CIcons CVC6LikeCaption::CPinButton::m_icons; #endif void DrawEllipsisText(CDC& dc,LPCTSTR sText,int n,LPRECT prc,bool bHorizontal) { assert(n>0); long width=bHorizontal ? prc->right - prc->left : prc->bottom - prc->top; CSize size; LPTSTR sTmp=0; bool bRes=(GetTextExtentPoint32(dc, sText, n,&size)!=FALSE); assert(bRes); if(width<size.cx) { LPCTSTR sEllipsis=_T("..."); const int ellipsisLen=sizeof(sEllipsis)-1; sTmp=new TCHAR[ellipsisLen+n]; _tcscpy(sTmp,_T("...")); _tcsncpy(sTmp+ellipsisLen,sText,n); bRes=(GetTextExtentExPoint(dc,sTmp,ellipsisLen+n,width,&n,NULL,&size)!=FALSE); if(bRes) { if(n<ellipsisLen+1) n=ellipsisLen+1; _tcsncpy(sTmp,sText,n-ellipsisLen); _tcsncpy(sTmp+(n-ellipsisLen),sEllipsis,ellipsisLen); sText=sTmp; } } // UINT prevAlign=dc.SetTextAlign(TA_LEFT | TA_TOP | TA_NOUPDATECP); CPoint pt(prc->left,prc->top); if(bHorizontal) pt.y = (prc->bottom - prc->top-size.cy)/2+prc->top; else pt.x = prc->right-(prc->right - prc->left-size.cy)/2; dc.ExtTextOut(pt.x,pt.y,ETO_CLIPPED,prc,sText,n,NULL); // dc.SetTextAlign(prevAlign); delete [] sTmp; } }//namespace dockwins
[ "hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0" ]
[ [ [ 1, 68 ] ] ]
178908113a6ac0b11208671a6bde0bd65d9c7307
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/DLG_Chooser.h
8940becc851984e0fa4585dff42e20dac3e4b108
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
1,557
h
#if !defined(AFX_DLG_CHOOSER_H__CBF77C8B_3E60_49F9_9CDA_B286DC12C7FE__INCLUDED_) #define AFX_DLG_CHOOSER_H__CBF77C8B_3E60_49F9_9CDA_B286DC12C7FE__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "stdafx.h" #include "_common.h" ///////////////////////////////////////////////////////////////////////////// // CDLG_Chooser dialog class CDLG_Chooser : public CDialog { // Construction public: SimpleTracker Track; int m_iIconID; int m_iStartElen; CString m_sTitle; CStringArray* m_pOptionList; CDLG_Chooser(const char* szTitle,const char* szHelpString, CStringArray* pOptionList, int iStartElen, int iIconID, CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDLG_Chooser) enum { IDD = IDD_SIMPLECHOOSER }; CComboBox m_ChooseList; CString m_HelpString; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDLG_Chooser) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDLG_Chooser) virtual void OnOK(); virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLG_CHOOSER_H__CBF77C8B_3E60_49F9_9CDA_B286DC12C7FE__INCLUDED_)
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 53 ] ] ]
9d8eb125254fd3323e22494a3d4737b9f52afa86
bf89d461ac1ca2c793997a80094d32d0e2a9a163
/ARDUINO/state_machine.cpp
fff7c2f95e6b7574b21f210f34ce979e1a7581ae
[]
no_license
bricef/led-cube
c544305bbc399d34ad2fcab2f74be7ae1de14bbf
7f4d291ac38375358ae136361bcbb773dc988702
refs/heads/master
2016-09-06T14:18:04.814856
2009-05-21T02:22:51
2009-05-21T02:22:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,897
cpp
#define MAX_LAYER_WAIT 25 #define ERROR_DURATION 250 void loop(void){ switch(status){ case INIT_STATE: SMClean(); if(waitForOpcode(INIT_IS_READY)){ SSend(INIT_OK); status=WAIT_BEGIN_CUBE; }else{ status=ERROR_STATE; }; break; case WAIT_BEGIN_CUBE: if(waitForOpcode(BEGIN_CUBE)){ status=WAIT_BEGIN_LAYER; }else{ status=ERROR_STATE; }; break; case WAIT_BEGIN_LAYER: if(waitForOpcode(BEGIN_LAYER)){ status=RECEIVING_LAYER; }else{ status=ERROR_STATE; }; break; case RECEIVING_LAYER: if(getLayer(currentLayer)){ status=WAIT_LAYER_END; }else{ SSend(LAYER_ACK_FAIL); status=WAIT_BEGIN_LAYER; } break; case WAIT_LAYER_END: if(waitForOpcode(END_LAYER)){ SSend(LAYER_ACK_SUCCESS); nextLayer(); if(currentLayer==8){ status=WAIT_END_CUBE; }else{ status=WAIT_BEGIN_LAYER; }; }else{ status=ERROR_STATE; }; break; case ERROR_STATE: sendErrorSignal(); status=INIT_STATE; break; case WAIT_END_CUBE: if(waitForOpcode(END_CUBE)){ SSend(CUBE_SUCCESS); status=INIT_STATE; }else{ status=ERROR_STATE; }; break; } } void sendErrorSignal(){ unsigned long time = millis(); while(millis()-time<ERROR_DURATION){ Serial.print(ERROR, BYTE); } } void SMClean(void){ currentLayer=0; } void nextLayer(void){ currentLayer++; } void SSend(byte opcode){ Serial.print(opcode, BYTE); } boolean getLayer(int layer){ unsigned long time = millis(); for(int i=0; i<numbytes; i++){ if (Serial.available()){ val = Serial.read(); doubleBuffer[layer][i]=val; if(val==END_LAYER){ return false; } } if(millis()-time>MAX_LAYER_WAIT){ return false; } } return true; }
[ "brice.fernandes@d0259a58-13ce-11de-b208-e5a9466b8568" ]
[ [ [ 1, 107 ] ] ]
4630a6041a65679ab998de4f4dc43eb2496cd2ac
c436a5d7cdbebc04e5d202c6bb3c83448a5db529
/QtOgre/include/LogEntry.h
57c253458bc2d1c1952a17d940846cd0131b1c64
[ "Zlib" ]
permissive
pvdk/QtOgreFramework
89132be5c0ea4f11a43abf4632577ebb21a0b10a
e32bafae2b0c1a8af9700efea61ff351866bb1d5
refs/heads/master
2021-01-23T08:15:38.575879
2010-11-15T21:39:06
2010-11-15T21:39:06
1,680,419
0
1
null
null
null
null
UTF-8
C++
false
false
434
h
#ifndef QTOGRE_LOGENTRY_H_ #define QTOGRE_LOGENTRY_H_ #include "LogLevel.h" #include <QString> #include <QTime> #include <QVariant> namespace QtOgre { class LogEntry { public: LogEntry(const QString &msg, LogLevel level); LogLevel getLevel(void); const QString& getMessage(void); const QTime& getTimestamp(void); private: QString mMsg; QTime mTimestamp; LogLevel mLevel; }; } #endif
[ "esuvs@2eb06014-c84b-0410-ad17-af83cdd4cbf1" ]
[ [ [ 1, 27 ] ] ]
bfc2b219d854dcd7b47a64804208a81d816ee949
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/ModelExporter/copy - ModelExporter.cpp
df65bfdd71a9799e2ba92a6f721e77425f6d7ca4
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UHC
C++
false
false
15,429
cpp
// ModelExporter.cpp // 2007 Geoyeob Kim // #include "Main.h" #include "ModelExporter.h" #include "ErrorProcedure.h" #include "NullRestoreObj.h" #ifndef DEBUG_MSG #define DEBUG_MSG(x) (;) #endif extern HINSTANCE hInstance; ModelExporter::ModelExporter(void) :isFirstTimeInit(FALSE), isExportSuccessful(FALSE) { } ModelExporter::~ModelExporter(void) { } int ModelExporter::ExtCount() { return 1; } const TCHAR* ModelExporter::Ext(int n) { return _T("ARN"); } const TCHAR* ModelExporter::LongDesc() { return _T("Aran Model Exporter (2007)"); } const TCHAR* ModelExporter::ShortDesc() { return _T("Aran Model Exporter"); } const TCHAR* ModelExporter::AuthorName() { return _T("Geoyeob Kim"); } const TCHAR* ModelExporter::CopyrightMessage() { return _T(""); } const TCHAR* ModelExporter::OtherMessage1() { return _T(""); } const TCHAR* ModelExporter::OtherMessage2() { return _T(""); } unsigned int ModelExporter::Version() { return 0 * 100 + 0 * 10 + 1; } void ModelExporter::ShowAbout(HWND hWnd) { //::DialogBox(hInstance, MAKEINTRESOURCE(IDD_ABOUT), hWnd, AboutProc); } BOOL ModelExporter::SupportsOptions(int ext, DWORD options) { return TRUE; } int ModelExporter::DoExport(const TCHAR* name, ExpInterface* ei, Interface* i, BOOL suppressPrompts, DWORD options) { DebugPrint(_T("===================================================\n")); DebugPrint(_T("DoExport() Function Start!\n")); DebugPrint(_T("===================================================\n")); srand(time(NULL)); if (this->isFirstTimeInit == FALSE) { ::InitCustomControls(hInstance); INITCOMMONCONTROLSEX iccx; iccx.dwSize = sizeof(INITCOMMONCONTROLSEX); iccx.dwICC = ICC_WIN95_CLASSES | ICC_PROGRESS_CLASS | ICC_USEREX_CLASSES | ICC_LISTVIEW_CLASSES; bool initControls = (::InitCommonControlsEx(&iccx) != 0); assert(initControls != false); this->isFirstTimeInit = TRUE; } time_t currentTime = 0; time(&currentTime); tm tempTM; localtime_s(&tempTM, &currentTime); strftime(this->exportTime, sizeof(this->exportTime) / sizeof(this->exportTime[0]), "%Y-%m-%d %H:%M:%S", &tempTM); this->coreInterface = GetCOREInterface(); this->exportName = name; ErrorProcedure ep; SetErrorCallBack(&ep); float iGameVersion = GetIGameVersion(); DebugPrint(_T("3ds Max compatible version %.2f\n"), GetSupported3DSVersion()); this->game = GetIGameInterface(); IGameConversionManager* cm = GetConversionManager(); cm->SetCoordSystem(IGameConversionManager::IGAME_D3D); // 애니메이션 기능은 빠져있으므로 현재 프레임으로 익스포팅한다고 가정 this->coreFrame = this->coreInterface->GetTime(); // 선택된 개체만 할 것인가 전부 할 것인가를 결정해야하는데, // 일단 전부 익스포트하는 것으로 한다. this->game->InitialiseIGame(false); try { theHold.Begin(); // Do your job here! this->StartExporting(); theHold.Put(new NullRestoreObj()); theHold.Accept(_T("Export Settings")); } catch(char const* error) { theHold.Cancel(); ::MessageBox(0, error, _T("Error while exporting"), MB_OK); this->isExportSuccessful = false; } this->game->ReleaseIGame(); this->coreInterface->ProgressEnd(); //::MessageBox(0, _T("Export Process"), _T("DoExport()"), MB_OK); return 1; } int ModelExporter::StartExporting() { IGameScene* ig = this->game; int nodeCount = ig->GetTopLevelNodeCount(); int i; this->rootMaterialCount = this->game->GetRootMaterialCount(); this->fout.open(this->exportName.c_str(), std::ios_base::binary); for (i = 0; i < ig->GetRootMaterialCount(); i++) { DebugPrint(_T("RootMaterial INDEX: %d, Name: %s\n"), i, ig->GetRootMaterial(i)->GetMaterialName()); this->PrintChildMaterialInfo(ig->GetRootMaterial(i), 1); } for (i = 0; i < nodeCount; i++) { IGameNode* node = ig->GetTopLevelNode(i); this->ExportNode(node); } this->fout.close(); return 0; } void ModelExporter::PrintChildMaterialInfo(IGameMaterial *igm, int depth) { int i, j; if (igm->GetSubMaterialCount() == 0) return; for (i = 0; i < igm->GetSubMaterialCount(); i++) { for (j = 0; j < depth; j++) DebugPrint(_T(" ")); DebugPrint(_T("ChildMaterial INDEX: %d, Name: %s, ID: %d\n"), i, igm->GetSubMaterial(i)->GetMaterialName(), igm->GetMaterialID(i)); this->PrintChildMaterialInfo(igm->GetSubMaterial(i), depth + 1); } return; } int ModelExporter::ExportNode(IGameNode* node) { std::string nodeName = node->GetName(); DebugPrint(_T("Exporting Node: %s\n"), nodeName.c_str()); GMatrix maxToDx, otm, ptm; maxToDx.SetRow(0, Point4(1, 0, 0, 0)); maxToDx.SetRow(1, Point4(0, 0, -1, 0)); maxToDx.SetRow(2, Point4(0, 1, 0, 0)); maxToDx.SetRow(3, Point4(0, 0, 0, 1)); otm = node->GetWorldTM(this->coreFrame) * maxToDx; ptm.SetIdentity(); if (node->GetNodeParent() != NULL) { ptm = node->GetNodeParent()->GetWorldTM(this->coreFrame) * maxToDx; otm = otm * ptm.Inverse(); } //otm.SetRow(3, Point4(otm.Translation() * 1.0f / 1.0f, 1)); IGameObject* obj = node->GetIGameObject(); int nodeMaterialIndex = -1; if (obj) { if (obj->GetIGameType() == IGameObject::IGAME_SPLINE) { } else if (obj->IsEntitySupported()) { IGameObject::ObjectTypes objectType = obj->GetIGameType(); switch (objectType) { case IGameObject::IGAME_MESH: //////////////////////////////////////////////////////////////////// // // Start of Node Definition Data (NDD) for ARN format // //////////////////////////////////////////////////////////////////// nodeMaterialIndex = node->GetMaterialIndex(); // // - Node name // - Vertex Data Definition (VDD) // - Free-Material Table (FMT) // - Material & Texture Definition (MTD) // // are processed by following function; // this->ExportMesh(node, obj); // // - Animation Data Definition (ADD) // // is processed by following function; // this->ExportAnimation(node, obj); break; case IGameObject::IGAME_CAMERA: //this->ExportCamera(node, obj); //this->ExportAnimation(node, obj); break; case IGameObject::IGAME_LIGHT: break; default: break; } } } int childCount = node->GetChildCount(); int i; for (i = 0; i < childCount; i++) { DebugPrint(_T("Child node detected.\n")); this->ExportNode(node->GetNodeChild(i)); } return 0; } int ModelExporter::ExportCamera(IGameNode* node, IGameObject* obj) { IGameCamera* igc = static_cast<IGameCamera*>(obj); return 0; } int ModelExporter::ExportAnimation(IGameNode* node, IGameObject* obj) { const DWORD tick = 4800; const int fps = 30; const int startFrame = 0; const int endFrame = 40; int i = 0; /*GMatrix maxToDx; maxToDx.SetRow(0, Point4(1, 0, 0, 0)); maxToDx.SetRow(1, Point4(0, 0, -1, 0)); maxToDx.SetRow(2, Point4(0, 1, 0, 0)); maxToDx.SetRow(3, Point4(0, 0, 0, 1));*/ // // Write down Animation Data Definition (ADD) for ARN format // // Rotation-Scaling-Translation Data this->fout.write("ANIM", 4); // Frame range this->fout.write((char*)&startFrame, sizeof(int)); this->fout.write((char*)&endFrame, sizeof(int)); for (i = startFrame; i <= endFrame; i++) { // get current frame's world transformation matrix GMatrix tm = node->GetWorldTM(tick * i / fps); // decompose it to RST matrix Matrix3 m3 = tm.ExtractMatrix3(); Point3 translation; Quat rotation; Point3 scale; DecomposeMatrix(m3, translation, rotation, scale); DebugPrint(_T("Ticks: %d / R: %.4f, %.4f, %.4f, %.4f / S: %.4f, %.4f, %.4f / T: %.4f %.4f %.4f\n"), tick*i/fps, rotation.x, rotation.y, rotation.z, rotation.w, scale.x, scale.y, scale.z, translation.x, translation.y, translation.z); // // CAUTION: AXIS SWAPPING occurs instead of matrix calculation // this->fout.write((char*)&rotation.x, sizeof(float)); this->fout.write((char*)&rotation.z, sizeof(float)); this->fout.write((char*)&rotation.y, sizeof(float)); this->fout.write((char*)&rotation.w, sizeof(float)); this->fout.write((char*)&scale.x, sizeof(float)); this->fout.write((char*)&scale.z, sizeof(float)); this->fout.write((char*)&scale.y, sizeof(float)); this->fout.write((char*)&translation.x, sizeof(float)); this->fout.write((char*)&translation.z, sizeof(float)); this->fout.write((char*)&translation.y, sizeof(float)); } return 0; } int ModelExporter::ExportMesh(IGameNode *node, IGameObject *obj) { IGameMesh* igm = static_cast<IGameMesh*>(obj); IGameSkin* igs = obj->IsObjectSkinned() ? obj->GetIGameSkin() : 0; // unused for now static char buf[4096]; igm->SetCreateOptimizedNormalList(); if (!igm->InitializeData()) { _snprintf_s(buf, 4095, 4095, "Could not read mesh data from '%s'\n", node->GetName()); buf[4095] = '\0'; DebugPrint(_T(buf)); } DWORD faceCount = igm->GetNumberOfFaces(); DWORD vertCount = faceCount * 3; // write mesh(node) name(Null terminated variable length string) this->fout.write(node->GetName(), (int)(strlen(node->GetName()) + 1)); // write total vertices count(int) this->fout.write((char*)&vertCount, sizeof(vertCount)); DebugPrint(_T("Total Vertices: %d\n"), vertCount); int vertsDataStartingOffset = this->fout.tellp(); // 버텍스 정보가 시작되는 오프셋 저장 int i, j, k; Custom_FVF fvf; GMatrix maxToDx; maxToDx.SetRow(0, Point4(1, 0, 0, 0)); maxToDx.SetRow(1, Point4(0, 0, -1, 0)); maxToDx.SetRow(2, Point4(0, 1, 0, 0)); maxToDx.SetRow(3, Point4(0, 0, 0, 1)); std::vector<Custom_Material> materialList; for (i = 0; i < (int)faceCount; i++) { FaceEx* face = igm->GetFace(i); IGameMaterial* igmat = igm->GetMaterialFromFace(face); TCHAR* matName = NULL; TCHAR* matClassName = NULL; DebugPrint(_T("Face #%d - MatID: %d"), i, face->matID); int matID = -1; if (igmat != NULL) { DebugPrint(_T(" (has material info: %s"), igmat->GetMaterialName()); //matID = igmat->GetMaterialID(0); matName = igmat->GetMaterialName(); matClassName = igmat->GetMaterialClass(); Custom_Material cm; cm.texFileName = _T(""); if (igmat->GetNumberOfTextureMaps() != 0) { IGameTextureMap* igtm = igmat->GetIGameTextureMap(0); TCHAR* textureFileName = igtm->GetBitmapFileName(); DebugPrint(_T(", %s)\n"), textureFileName); cm.texFileName = textureFileName; igtm = NULL; } else { DebugPrint(_T(")\n")); } // insert to material list bool isFirstMaterial = true; for (k = 0; k < materialList.size(); k++) { if (materialList[k].matName.compare(matName) == 0) { isFirstMaterial = false; break; } } if (isFirstMaterial == true) { Point3 p3; cm.matName = matName; igmat->GetDiffuseData()->GetPropertyValue(p3); cm.d3dMat.Diffuse.r = p3.x; cm.d3dMat.Diffuse.g = p3.y; cm.d3dMat.Diffuse.b = p3.z; cm.d3dMat.Diffuse.a = 1.0f; igmat->GetAmbientData()->GetPropertyValue(p3); cm.d3dMat.Ambient.r = p3.x; cm.d3dMat.Ambient.g = p3.y; cm.d3dMat.Ambient.b = p3.z; cm.d3dMat.Ambient.a = 1.0f; igmat->GetSpecularData()->GetPropertyValue(p3); cm.d3dMat.Specular.r = p3.x; cm.d3dMat.Specular.g = p3.y; cm.d3dMat.Specular.b = p3.z; cm.d3dMat.Specular.a = 1.0f; igmat->GetEmissiveData()->GetPropertyValue(p3); cm.d3dMat.Emissive.r = p3.x; cm.d3dMat.Emissive.g = p3.y; cm.d3dMat.Emissive.b = p3.z; cm.d3dMat.Emissive.a = 1.0f; PropType pt = igmat->GetOpacityData()->GetType(); materialList.push_back(cm); } /*IGameProperty* igprop = igmat->GetDiffuseData(); float dummyFloat; int dummyInt; Point3 dummyPoint3; Point4 dummyPoint4; TCHAR* dummyTchar; switch (igprop->GetType()) { case IGAME_FLOAT_PROP: igprop->GetPropertyValue(dummyFloat); break; case IGAME_INT_PROP: igprop->GetPropertyValue(dummyInt); break; case IGAME_POINT3_PROP: igprop->GetPropertyValue(dummyPoint3); break; case IGAME_POINT4_PROP: igprop->GetPropertyValue(dummyPoint4); break; case IGAME_STRING_PROP: igprop->GetPropertyValue(dummyTchar); break; case IGAME_UNKNOWN_PROP: break; }*/ } else { DebugPrint(_T("\n")); } // three vertices per face for (j = 0; j < 3; j++) { fvf.vertex = igm->GetVertex(face->vert[j], false) * maxToDx; fvf.normal = ModelExporter::TransformVector(maxToDx, igm->GetNormal(face->norm[j], false)); Point2 texCoord = igm->GetTexVertex(face->texCoord[j]); //fvf.vertex = igm->GetVertex(face->vert[j], false); //fvf.normal = igm->GetNormal(face->norm[j], false); //fvf.vertex.z = -fvf.vertex.z; //fvf.normal.z = -fvf.normal.z; //Point3 color = igm->GetColorVertex(face->vert[j]); //fvf.color = ModelExporter::Point3ToIntColor(color); fvf.color = 0xffffffff; fvf.u = texCoord.x; fvf.v = texCoord.y; //fvf.u = 0.0f; //fvf.v = 0.0f; //DebugPrint("v %5.2f, %5.2f, %5.2f n %5.2f %5.2f %5.2f\n", fvf.vertex.x, fvf.vertex.y, fvf.vertex.z, fvf.normal.x, fvf.normal.y, fvf.normal.z); this->fout.write((const char*)&fvf, sizeof(Custom_FVF)); } // write material reference this->fout.seekp(vertsDataStartingOffset + vertCount * sizeof(Custom_FVF) + i * sizeof(int), std::ios_base::beg); bool isRightMaterialName = false; for (k = 0; k < materialList.size(); k++) { if (igmat == NULL) break; if (materialList[k].matName.compare(igmat->GetMaterialName()) == 0) { isRightMaterialName = true; this->fout.write((char*)&k, sizeof(int)); break; } } if (isRightMaterialName != true) { int ffffffff = -1; this->fout.write((char*)&ffffffff, sizeof(int)); DebugPrint(_T("Material Not Found!")); } this->fout.seekp(vertsDataStartingOffset + 3 * (i+1) * sizeof(Custom_FVF), std::ios_base::beg); //this->fout.close(); } this->fout.seekp(vertsDataStartingOffset + vertCount * sizeof(Custom_FVF) + faceCount * sizeof(int), std::ios_base::beg); int materialCount = (int)materialList.size(); this->fout.write((char*)&materialCount, sizeof(int)); for (i = 0; i < materialCount; i++) { this->fout.write(materialList[i].matName.c_str(), (int)(materialList[i].matName.length() + 1)); this->fout.write((char*)&materialList[i].d3dMat, sizeof(D3DMATERIAL9)); this->fout.write(materialList[i].texFileName.c_str(), (int)(materialList[i].texFileName.length() + 1)); } return 0; } Point3 ModelExporter::TransformVector(GMatrix const& gm, Point3 const& p) { float out[3]; float const* v = &p.x; GRow const* m = gm.GetAddr(); int i, j; for (i = 0; i < 3; i++) { float o = 0; for (j = 0; j < 3; j++) { o += m[j][i] * v[j]; } out[i] = o; } return (Point3&)out; } int ModelExporter::Point3ToIntColor(Point3& p3) { return (int)(255 * p3.x) + ((int)(255 * p3.y) << 8) + ((int)(255 * p3.z) << 16); }
[ [ [ 1, 588 ] ] ]
82340d04179f640318fc9716099943b301e7cfd1
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment3/slistiterator.hpp
96259a06115f659c7a941bbf0cda6e13a25c16c9
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
1,165
hpp
////////////////////////////////////////////////////////////////////// /// @file slist.hpp /// @author James Anderson CS 153 Section A /// @brief Template implemintation file for singly /// linked list iterator class for assignment 3 ////////////////////////////////////////////////////////////////////// template <class generic> SListIterator<generic>::SListIterator () : m_current (NULL) { } template <class generic> SListIterator<generic>::SListIterator (SNode<generic> * x) : m_current (x) { } template <class generic> generic SListIterator<generic>::operator* () const { return m_current->data; } template <class generic> SListIterator<generic> SListIterator<generic>::operator++ () { m_current = m_current->forward; return *this; } template <class generic> SListIterator<generic> SListIterator<generic>::operator++ (int) { return ++(*this); } template <class generic> bool SListIterator<generic>::operator== (const SListIterator & rhs) const { return m_current == rhs.m_current; } template <class generic> bool SListIterator<generic>::operator!= (const SListIterator & rhs) const { return m_current != rhs.m_current; }
[ [ [ 1, 47 ] ] ]
85eeeaf7e1887f52140ef8d218682d72879221fc
45229380094a0c2b603616e7505cbdc4d89dfaee
/wavelets/haar_src/src/stdafx.h
a8f4872b667c3ff4a5b05540f8554049bb81fdc2
[]
no_license
xcud/msrds
a71000cc096723272e5ada7229426dee5100406c
04764859c88f5c36a757dbffc105309a27cd9c4d
refs/heads/master
2021-01-10T01:19:35.834296
2011-11-04T09:26:01
2011-11-04T09:26:01
45,697,313
1
2
null
null
null
null
UTF-8
C++
false
false
2,472
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef _SECURE_ATL #define _SECURE_ATL 1 #endif #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include "targetver.h" #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #ifndef _AFX_NO_OLE_SUPPORT #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT // TODO: reference additional headers your program requires here #pragma warning(disable : 4996) #include <stdlib.h> #include <time.h> #include <dshow.h> #pragma include_alias( "dxtrans.h", "qedit.h" ) #define __IDxtCompositor_INTERFACE_DEFINED__ #define __IDxtAlphaSetter_INTERFACE_DEFINED__ #define __IDxtJpeg_INTERFACE_DEFINED__ #define __IDxtKey_INTERFACE_DEFINED__ #include <qedit.h> #include <math.h> #include <mm3dnow.h> #include <emmintrin.h> #include <stdio.h> #include <float.h> #include <gdiplus.h> #include <vector> #include <string> #ifdef _UNICODE #if defined _M_IX86 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_IA64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_X64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") #else #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #endif #endif
[ "perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671" ]
[ [ [ 1, 78 ] ] ]
a0e34667f30ffd40ef23f88cf5e8e1f89a0d9942
f1e1d4a52a7c840334ed8cc00b45e66aeb81f721
/src/stl.cpp
5c329cc595e2dc3f0a166f711e1ef4767af6b723
[]
no_license
attrezzo/repsnapper
54f17c4de848378007500c5b173fc8de9e26af0f
8e431670f5b4c69222be3060d7d2106901ceab4e
refs/heads/master
2020-12-29T03:18:38.732606
2011-08-30T14:37:13
2011-08-30T14:37:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
81,761
cpp
/* This file is a part of the RepSnapper project. Copyright (C) 2010 Kulitorum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <limits> #include "stdafx.h" #include "string.h" #include "stl.h" #include "gcode.h" #include "math.h" #include "settings.h" #include "rfo.h" #ifdef WIN32 # include <GL/glut.h> // Header GLUT Library # pragma warning( disable : 4018 4267) #endif #include <iostream> #include <fstream> #include <algorithm> // for PointHash #ifdef __GNUC__ # define _BACKWARD_BACKWARD_WARNING_H 1 // kill annoying warning # include <ext/hash_map> namespace std { using namespace __gnu_cxx; } #else # include <hash_map> using namespace stdext; #endif #define ABS(a) (((a) < 0) ? -(a) : (a)) /* A number that speaks for itself, every kissable digit. */ #define PI 3.141592653589793238462643383279502884197169399375105820974944592308 #define CUTTING_PLANE_DEBUG 0 using namespace std; #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /* call me before glutting */ void checkGlutInit() { static bool inited = false; if (inited) return; inited = true; int argc; char *argv[] = { (char *) "repsnapper" }; glutInit (&argc, argv); } void renderBitmapString(Vector3f pos, void* font, string text) { char asd[100]; char *a = &asd[0]; checkGlutInit(); sprintf(asd,"%s",text.c_str()); glRasterPos3f(pos.x, pos.y, pos.z); for (uint c=0;c<text.size();c++) glutBitmapCharacter(font, (int)*a++); } // STL constructor STL::STL() { Min.x = Min.y = Min.z = 0.0f; Max.x = Max.y = Max.z = 200.0f; CalcCenter(); } /* Loads an binary STL file by filename * Returns 0 on success and -1 on failure */ int STL::loadBinaryFile(string filename) { if(getFileType(filename) != BINARY_STL) { return -1; } triangles.clear(); Min.x = Min.y = Min.z = numeric_limits<float>::infinity(); Max.x = Max.y = Max.z = -numeric_limits<float>::infinity(); ifstream file; file.open(filename.c_str()); if(file.fail()) { cerr << "Error: Unable to open stl file - " << filename << endl; return -1; } /* Binary STL files have a meaningless 80 byte header * followed by the number of triangles */ file.seekg(80, ios_base::beg); unsigned int num_triangles; file.read(reinterpret_cast < char * > (&num_triangles), sizeof(unsigned int)); // N_Triangles triangles.reserve(num_triangles); for(uint i = 0; i < num_triangles; i++) { float a,b,c; file.read(reinterpret_cast < char * > (&a), sizeof(float)); file.read(reinterpret_cast < char * > (&b), sizeof(float)); file.read(reinterpret_cast < char * > (&c), sizeof(float)); Vector3f N(a,b,c); file.read(reinterpret_cast < char * > (&a), sizeof(float)); file.read(reinterpret_cast < char * > (&b), sizeof(float)); file.read(reinterpret_cast < char * > (&c), sizeof(float)); Vector3f Ax(a,b,c); file.read(reinterpret_cast < char * > (&a), sizeof(float)); file.read(reinterpret_cast < char * > (&b), sizeof(float)); file.read(reinterpret_cast < char * > (&c), sizeof(float)); Vector3f Bx(a,b,c); file.read(reinterpret_cast < char * > (&a), sizeof(float)); file.read(reinterpret_cast < char * > (&b), sizeof(float)); file.read(reinterpret_cast < char * > (&c), sizeof(float)); Vector3f Cx(a,b,c); /* Recalculate normal vector - can't trust an STL file! */ Vector3f AA=Cx-Ax; Vector3f BB=Cx-Bx; N.x = AA.y * BB.z - BB.y * AA.z; N.y = AA.z * BB.x - BB.z * AA.x; N.z = AA.x * BB.y - BB.x * AA.y; N.normalize(); /* attribute byte count - sometimes contains face color information but is useless for our purposes */ unsigned short byte_count; file.read(reinterpret_cast < char * > (&byte_count), sizeof(unsigned short)); Triangle T(N,Ax,Bx,Cx); triangles.push_back(T); T.AccumulateMinMax (Min, Max); } file.close(); return 0; } /* Loads an ASCII STL file by filename * Returns 0 on success and -1 on failure */ int STL::loadASCIIFile(string filename) { // Check filetype if(getFileType(filename) != ASCII_STL) { cerr << "None ASCII STL file passed to loadASCIIFile" << endl; return -1; } triangles.clear(); Min.x = Min.y = Min.z = numeric_limits<float>::infinity(); Max.x = Max.y = Max.z = -numeric_limits<float>::infinity(); ifstream file; file.open(filename.c_str()); if(file.fail()) { cerr << "Error: Unable to open stl file - " << filename << endl; return -1; } /* ASCII files start with "solid [Name_of_file]" * so get rid of them to access the data */ string solid; file >> solid; char c_str_name[256]; file.getline(c_str_name, 256); while(!file.eof()) { // Loop around all triangles string facet; file >> facet; // Parse possible end of file - "endsolid" if(facet == "endsolid") { break; } if(facet != "facet") { cerr << "Error: Facet keyword not found in STL file!" << endl; return -1; } // Parse Face Normal - "normal %f %f %f" string normal; Vector3f normal_vec; file >> normal >> normal_vec.x >> normal_vec.y >> normal_vec.z; if(normal != "normal") { cerr << "Error: normal keyword not found in STL file!" << endl; return -1; } // Parse "outer loop" line string outer, loop; file >> outer >> loop; if(outer != "outer" || loop != "loop") { cerr << "Error: Outer/Loop keywords not found!" << endl; return -1; } // Grab the 3 vertices - each one of the form "vertex %f %f %f" Vector3f vertices[3]; for(int i=0; i<3; i++) { string vertex; file >> vertex >> vertices[i].x >> vertices[i].y >> vertices[i].z; if(vertex != "vertex") { cerr << "Error: Vertex keyword not found" << endl; return -1; } } // Parse end of vertices loop - "endloop endfacet" string endloop, endfacet; file >> endloop >> endfacet; if(endloop != "endloop" || endfacet != "endfacet") { cerr << "Error: Vertex keyword not found" << endl; return -1; } // Create triangle object and push onto the vector Triangle triangle(normal_vec, vertices[0], vertices[1], vertices[2]); triangle.AccumulateMinMax(Min, Max); triangles.push_back(triangle); } file.close(); return 0; } // STL::loadASCIIFile(string filename) /* Returns the STL filetype of the given file */ filetype_t STL::getFileType(string filename) { // Extract file extension (i.e. "stl") string extension = filename.substr(filename.find_last_of(".")+1); if(extension != "stl" && extension != "STL") { return NONE_STL; } ifstream file; file.open(filename.c_str()); if(file.fail()) { cerr << "Error: Unable to open stl file - " << filename << endl; return NONE_STL; } // ASCII files start with "solid [Name_of_file]" string first_word; file >> first_word; file.close(); if(first_word == "solid") { // ASCII return ASCII_STL; } else { return BINARY_STL; } } /* Loads an stl file by filename * Returns -1 on error, and 0 on success * Error messages placed on stderr */ int STL::loadFile(string filename) { if(getFileType(filename) == ASCII_STL) { loadASCIIFile(filename); } else { // Binary loadBinaryFile(filename); } OptimizeRotation(); CalcCenter(); scale_factor = 1.0; return 0; } void STL::CalcCenter() { Center = (Max + Min )/2; } void STL::displayInfillOld(const Settings &settings, CuttingPlane &plane, uint LayerNr, vector<int>& altInfillLayers) { if (settings.Display.DisplayinFill) { // inFill vector<Vector2f> infill; CuttingPlane infillCuttingPlane = plane; if (settings.Slicing.ShellOnly == false) { switch (settings.Slicing.ShrinkQuality) { case SHRINK_FAST: infillCuttingPlane.ClearShrink(); infillCuttingPlane.ShrinkFast(settings.Hardware.ExtrudedMaterialWidth*0.5f, settings.Slicing.Optimization, settings.Display.DisplayCuttingPlane, false, settings.Slicing.ShellCount); break; case SHRINK_LOGICK: break; } // check if this if a layer we should use the alternate infill distance on float infillDistance = settings.Slicing.InfillDistance; if (std::find(altInfillLayers.begin(), altInfillLayers.end(), LayerNr) != altInfillLayers.end()) { infillDistance = settings.Slicing.AltInfillDistance; } infillCuttingPlane.CalcInFill(infill, LayerNr, infillDistance, settings.Slicing.InfillRotation, settings.Slicing.InfillRotationPrLayer, settings.Display.DisplayDebuginFill); } glColor4f(1,1,0,1); glPointSize(5); glBegin(GL_LINES); for(size_t i=0;i<infill.size();i+=2) { if(infill.size() > i+1) { glVertex3f(infill[i ].x, infill[i ].y, plane.getZ()); glVertex3f(infill[i+1].x, infill[i+1].y, plane.getZ()); } } glEnd(); } } // FIXME: why !? do we grub around with the rfo here ? void STL::draw(RFO &rfo, const Settings &settings) { // polygons glEnable(GL_LIGHTING); glEnable(GL_POINT_SMOOTH); float no_mat[] = {0.0f, 0.0f, 0.0f, 1.0f}; // float mat_ambient[] = {0.7f, 0.7f, 0.7f, 1.0f}; // float mat_ambient_color[] = {0.8f, 0.8f, 0.2f, 1.0f}; float mat_diffuse[] = {0.1f, 0.5f, 0.8f, 1.0f}; float mat_specular[] = {1.0f, 1.0f, 1.0f, 1.0f}; // float no_shininess = 0.0f; // float low_shininess = 5.0f; float high_shininess = 100.0f; // float mat_emission[] = {0.3f, 0.2f, 0.2f, 0.0f}; int i; for (i = 0; i < 4; i++) mat_diffuse[i] = settings.Display.PolygonRGBA.rgba[i]; mat_specular[0] = mat_specular[1] = mat_specular[2] = settings.Display.Highlight; /* draw sphere in first row, first column * diffuse reflection only; no ambient or specular */ glMaterialfv(GL_FRONT, GL_AMBIENT, no_mat); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialf(GL_FRONT, GL_SHININESS, high_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, no_mat); glEnable (GL_POLYGON_OFFSET_FILL); if(settings.Display.DisplayPolygons) { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); // glDepthMask(GL_TRUE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //define blending factors glBegin(GL_TRIANGLES); for(size_t i=0;i<triangles.size();i++) { /* switch(triangles[i].axis) { case NEGX: glColor4f(1,0,0,opacity); break; case POSX: glColor4f(0.5f,0,0,opacity); break; case NEGY: glColor4f(0,1,0,opacity); break; case POSY: glColor4f(0,0.5f,0,opacity); break; case NEGZ: glColor4f(0,0,1,opacity); break; case POSZ: glColor4f(0,0,0.3f,opacity); break; default: glColor4f(0.2f,0.2f,0.2f,opacity); break; }*/ glNormal3fv((GLfloat*)&triangles[i].Normal); glVertex3fv((GLfloat*)&triangles[i].A); glVertex3fv((GLfloat*)&triangles[i].B); glVertex3fv((GLfloat*)&triangles[i].C); } glEnd(); } glDisable (GL_POLYGON_OFFSET_FILL); // WireFrame if(settings.Display.DisplayWireframe) { if(!settings.Display.DisplayWireframeShaded) glDisable(GL_LIGHTING); for (i = 0; i < 4; i++) mat_diffuse[i] = settings.Display.WireframeRGBA.rgba[i]; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glColor4fv(settings.Display.WireframeRGBA.rgba); for(size_t i=0;i<triangles.size();i++) { glBegin(GL_LINE_LOOP); glLineWidth(1); glNormal3fv((GLfloat*)&triangles[i].Normal); glVertex3fv((GLfloat*)&triangles[i].A); glVertex3fv((GLfloat*)&triangles[i].B); glVertex3fv((GLfloat*)&triangles[i].C); glEnd(); } } glDisable(GL_LIGHTING); // normals if(settings.Display.DisplayNormals) { glColor4fv(settings.Display.NormalsRGBA.rgba); glBegin(GL_LINES); for(size_t i=0;i<triangles.size();i++) { Vector3f center = (triangles[i].A+triangles[i].B+triangles[i].C)/3.0f; glVertex3fv((GLfloat*)&center); Vector3f N = center + (triangles[i].Normal*settings.Display.NormalsLength); glVertex3fv((GLfloat*)&N); } glEnd(); } // Endpoints if(settings.Display.DisplayEndpoints) { glColor4fv(settings.Display.EndpointsRGBA.rgba); glPointSize(settings.Display.EndPointSize); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); for(size_t i=0;i<triangles.size();i++) { glVertex3f(triangles[i].A.x, triangles[i].A.y, triangles[i].A.z); glVertex3f(triangles[i].B.x, triangles[i].B.y, triangles[i].B.z); glVertex3f(triangles[i].C.x, triangles[i].C.y, triangles[i].C.z); } glEnd(); } glDisable(GL_DEPTH_TEST); // Make Layers if(settings.Display.DisplayCuttingPlane) { uint LayerNr = 0; uint LayerCount = (uint)ceil((Max.z+settings.Hardware.LayerThickness*0.5f)/settings.Hardware.LayerThickness); vector<int> altInfillLayers; settings.Slicing.GetAltInfillLayers (altInfillLayers, LayerCount); float zSize = (Max.z-Min.z); float z=settings.Display.CuttingPlaneValue*zSize+Min.z; float zStep = zSize; if(settings.Display.DisplayAllLayers) { z=Min.z; zStep = settings.Hardware.LayerThickness; } while(z<Max.z) { for(size_t o=0;o<rfo.Objects.size();o++) { for(size_t f=0;f<rfo.Objects[o].files.size();f++) { Matrix4f T = rfo.GetSTLTransformationMatrix(o,f); Vector3f t = T.getTranslation(); t+= Vector3f(settings.Hardware.PrintMargin.x+settings.Raft.Size*settings.RaftEnable, settings.Hardware.PrintMargin.y+settings.Raft.Size*settings.RaftEnable, 0); T.setTranslation(t); CuttingPlane plane; T=Matrix4f::IDENTITY; CalcCuttingPlane(z, plane, T); // output is alot of un-connected line segments with individual vertices float hackedZ = z; while (plane.LinkSegments(hackedZ, settings.Slicing.Optimization) == false) // If segment linking fails, re-calc a new layer close to this one, and use that. { // This happens when there's triangles missing in the input STL break; hackedZ+= 0.1f; CalcCuttingPlane(hackedZ, plane, T); // output is alot of un-connected line segments with individual vertices } switch( settings.Slicing.ShrinkQuality ) { case SHRINK_FAST: plane.ShrinkFast(settings.Hardware.ExtrudedMaterialWidth*0.5f, settings.Slicing.Optimization, settings.Display.DisplayCuttingPlane, false, settings.Slicing.ShellCount); displayInfillOld(settings, plane, LayerNr, altInfillLayers); break; case SHRINK_LOGICK: plane.ShrinkLogick(settings.Hardware.ExtrudedMaterialWidth, settings.Slicing.Optimization, settings.Display.DisplayCuttingPlane, settings.Slicing.ShellCount); plane.Draw(settings.Display.DrawVertexNumbers, settings.Display.DrawLineNumbers, settings.Display.DrawCPOutlineNumbers, settings.Display.DrawCPLineNumbers, settings.Display.DrawCPVertexNumbers); displayInfillOld(settings, plane, LayerNr, altInfillLayers); break; } LayerNr++; } } z+=zStep; } }// If display cuttingplane if(settings.Display.DisplayBBox) { // Draw bbox glColor3f(1,0,0); glLineWidth(1); glBegin(GL_LINE_LOOP); glVertex3f(Min.x, Min.y, Min.z); glVertex3f(Min.x, Max.y, Min.z); glVertex3f(Max.x, Max.y, Min.z); glVertex3f(Max.x, Min.y, Min.z); glEnd(); glBegin(GL_LINE_LOOP); glVertex3f(Min.x, Min.y, Max.z); glVertex3f(Min.x, Max.y, Max.z); glVertex3f(Max.x, Max.y, Max.z); glVertex3f(Max.x, Min.y, Max.z); glEnd(); glBegin(GL_LINES); glVertex3f(Min.x, Min.y, Min.z); glVertex3f(Min.x, Min.y, Max.z); glVertex3f(Min.x, Max.y, Min.z); glVertex3f(Min.x, Max.y, Max.z); glVertex3f(Max.x, Max.y, Min.z); glVertex3f(Max.x, Max.y, Max.z); glVertex3f(Max.x, Min.y, Min.z); glVertex3f(Max.x, Min.y, Max.z); glEnd(); } } int findClosestUnused(std::vector<Vector3f> lines, Vector3f point, std::vector<bool> &used) { int closest = -1; float closestDist = numeric_limits<float>::max(); size_t count = lines.size(); for(uint i=0;i<count;i++) { if(used[i] == false) { float dist = (lines[i]-point).length(); if(dist < closestDist) { closestDist = dist; closest = i; } } } return closest; } uint findOtherEnd(uint p) { uint a = p%2; if(a == 0) return p+1; return p-1; } CuttingPlane::CuttingPlane() { } CuttingPlane::~CuttingPlane() { } struct GCodeStateImpl { GCode &code; Vector3f LastPosition; Command lastCommand; float lastLayerZ; GCodeStateImpl(GCode &_code) : code(_code), LastPosition(0,0,0), lastLayerZ(0) {} }; GCodeState::GCodeState(GCode &code) { pImpl = new GCodeStateImpl(code); } GCodeState::~GCodeState() { delete pImpl; } void GCodeState::SetZ(float z) { pImpl->LastPosition.z = z; } const Vector3f &GCodeState::LastPosition() { return pImpl->LastPosition; } void GCodeState::SetLastPosition(const Vector3f &v) { pImpl->LastPosition = v; } void GCodeState::AppendCommand(Command &command) { pImpl->lastCommand = command; pImpl->code.commands.push_back(command); } float GCodeState::GetLastLayerZ(float curZ) { if (pImpl->lastLayerZ <= 0) pImpl->lastLayerZ = curZ; return pImpl->lastLayerZ; } void GCodeState::SetLastLayerZ(float z) { pImpl->lastLayerZ = z; } void GCodeState::ResetLastWhere(Vector3f to) { pImpl->lastCommand.where = to; } float GCodeState::DistanceFromLastTo(Vector3f here) { return (pImpl->lastCommand.where - here).length(); } float GCodeState::LastCommandF() { return pImpl->lastCommand.f; } void GCodeState::MakeAcceleratedGCodeLine (Vector3f start, Vector3f end, float extrusionFactor, float &E, float z, const Settings::SlicingSettings &slicing, const Settings::HardwareSettings &hardware) { if ((end-start).length() < 0.05) // ignore micro moves return; Command command; if (slicing.EnableAcceleration) { if(end != start) //If we are going to somewhere else { float len; ResetLastWhere (start); Vector3f direction = end-start; len = direction.length(); // total distance direction.normalize(); // Set start feedrage command.Code = SETSPEED; command.where = start; if (slicing.UseIncrementalEcode) command.e = E; // move or extrude? else command.e = 0.0f; // move or extrude? command.f = hardware.MinPrintSpeedXY; AppendCommand(command); if(len < hardware.DistanceToReachFullSpeed*2) { // TODO: First point of acceleration is the middle of the line segment command.Code = COORDINATEDMOTION; command.where = (start+end)*0.5f; float extrudedMaterial = DistanceFromLastTo(command.where)*extrusionFactor; if(slicing.UseIncrementalEcode) E += extrudedMaterial; else E = extrudedMaterial; command.e = E; // move or extrude? float lengthFactor = (len/2.0f)/hardware.DistanceToReachFullSpeed; command.f = (hardware.MaxPrintSpeedXY-hardware.MinPrintSpeedXY)*lengthFactor+hardware.MinPrintSpeedXY; AppendCommand(command); // And then decelerate command.Code = COORDINATEDMOTION; command.where = end; if(slicing.UseIncrementalEcode) E += extrudedMaterial; else E = extrudedMaterial; command.e = E; // move or extrude? command.f = hardware.MinPrintSpeedXY; AppendCommand(command); }// if we will never reach full speed else { // Move to max speed command.Code = COORDINATEDMOTION; command.where = start+(direction*hardware.DistanceToReachFullSpeed); float extrudedMaterial = DistanceFromLastTo(command.where)*extrusionFactor; if(slicing.UseIncrementalEcode) E += extrudedMaterial; else E = extrudedMaterial; command.e = E; // move or extrude? command.f = hardware.MaxPrintSpeedXY; AppendCommand(command); // Sustian speed till deacceleration starts command.Code = COORDINATEDMOTION; command.where = end-(direction*hardware.DistanceToReachFullSpeed); extrudedMaterial = DistanceFromLastTo(command.where)*extrusionFactor; if(slicing.UseIncrementalEcode) E += extrudedMaterial; else E = extrudedMaterial; command.e = E; // move or extrude? command.f = hardware.MaxPrintSpeedXY; AppendCommand(command); // deacceleration untill end command.Code = COORDINATEDMOTION; command.where = end; extrudedMaterial = DistanceFromLastTo(command.where)*extrusionFactor; if(slicing.UseIncrementalEcode) E += extrudedMaterial; else E = extrudedMaterial; command.e = E; // move or extrude? command.f = hardware.MinPrintSpeedXY; AppendCommand(command); } // if we will reach full speed }// if we are going somewhere } // Firmware acceleration else // No accleration { // Make a accelerated line from lastCommand.where to lines[thisPoint] if(end != start) //If we are going to somewhere else { ResetLastWhere (start); if (slicing.Use3DGcode) { { command.Code = EXTRUDEROFF; AppendCommand(command); float speed = hardware.MinPrintSpeedXY; command.Code = COORDINATEDMOTION3D; command.where = start; command.e = E; // move or extrude? command.f = speed; AppendCommand(command); } // we need to move before extruding command.Code = EXTRUDERON; AppendCommand(command); float speed = hardware.MinPrintSpeedXY; command.Code = COORDINATEDMOTION3D; command.where = end; command.e = E; // move or extrude? command.f = speed; AppendCommand(command); // Done, switch extruder off command.Code = EXTRUDEROFF; AppendCommand(command); } else // 5d gcode, no acceleration { Vector3f direction = end-start; direction.normalize(); // set start speed to max if(LastCommandF() != hardware.MaxPrintSpeedXY) { command.Code = SETSPEED; command.where = Vector3f(start.x, start.y, z); command.f=hardware.MaxPrintSpeedXY; command.e = E; AppendCommand(command); } // store endPoint command.Code = COORDINATEDMOTION; command.where = end; float extrudedMaterial = DistanceFromLastTo(command.where)*extrusionFactor; if(slicing.UseIncrementalEcode) E += extrudedMaterial; else E = extrudedMaterial; command.e = E; // move or extrude? command.f = hardware.MaxPrintSpeedXY; AppendCommand(command); } // 5D gcode }// If we are going to somewhere else*/ }// If using firmware acceleration } // Convert Cuttingplane to GCode void CuttingPlane::MakeGcode(GCodeState &state, const std::vector<Vector2f> &infill, float &E, float z, const Settings::SlicingSettings &slicing, const Settings::HardwareSettings &hardware) { // Make an array with all lines, then link'em Command command; float lastLayerZ = state.GetLastLayerZ(z); // Set speed for next move command.Code = SETSPEED; command.where = Vector3f(0,0,lastLayerZ); command.e = E; // move command.f = hardware.MinPrintSpeedZ; // Use Min Z speed state.AppendCommand(command); command.comment = ""; // Move Z axis command.Code = ZMOVE; command.where = Vector3f(0,0,z); command.e = E; // move command.f = hardware.MinPrintSpeedZ; // Use Min Z speed state.AppendCommand(command); command.comment = ""; std::vector<Vector3f> lines; for(size_t i=0;i<infill.size();i++) lines.push_back(Vector3f(infill[i].x, infill[i].y, z)); if( optimizers.size() != 0 ) { // new method for( uint i = 1; i < optimizers.size()-1; i++) { optimizers[i]->RetrieveLines(lines); } } else { // old method // Copy polygons if(offsetPolygons.size() != 0) { for(size_t p=0;p<offsetPolygons.size();p++) { for(size_t i=0;i<offsetPolygons[p].points.size();i++) { Vector2f P3 = offsetVertices[offsetPolygons[p].points[i]]; Vector2f P4 = offsetVertices[offsetPolygons[p].points[(i+1)%offsetPolygons[p].points.size()]]; lines.push_back(Vector3f(P3.x, P3.y, z)); lines.push_back(Vector3f(P4.x, P4.y, z)); } } } } // Find closest point to last point std::vector<bool> used; used.resize(lines.size()); for(size_t i=0;i<used.size();i++) used[i] = false; int thisPoint = findClosestUnused(lines, state.LastPosition(), used); if(thisPoint == -1) // No lines = no gcode return; used[thisPoint] = true; while(thisPoint != -1) { // float len; // Make a MOVE accelerated line from LastPosition to lines[thisPoint] if(state.LastPosition() != lines[thisPoint]) //If we are going to somewhere else { state.MakeAcceleratedGCodeLine (state.LastPosition(), lines[thisPoint], 0.0f, E, z, slicing, hardware); } // If we are going to somewhere else state.SetLastPosition (lines[thisPoint]); used[thisPoint] = true; // Find other end of line thisPoint = findOtherEnd(thisPoint); used[thisPoint] = true; // store thisPoint // Make a PLOT accelerated line from LastPosition to lines[thisPoint] // if(EnableAcceleration) state.MakeAcceleratedGCodeLine (state.LastPosition(), lines[thisPoint], hardware.ExtrusionFactor, E, z, slicing, hardware); /* else { command.Code = COORDINATEDMOTION; command.where = lines[thisPoint]; len = (LastPosition - command.where).length(); if(UseIncrementalEcode) E += len*extrusionFactor; else E = len*extrusionFactor; command.e = E; // move or extrude? command.f = MinPrintSpeedXY; state.AppendCommand(command); }*/ state.SetLastPosition(lines[thisPoint]); thisPoint = findClosestUnused(lines, state.LastPosition(), used); if(thisPoint != -1) used[thisPoint] = true; } state.SetLastLayerZ(z); } // intersect lines with plane void STL::CalcCuttingPlane(float where, CuttingPlane &plane, const Matrix4f &T) { #if CUTTING_PLANE_DEBUG cout << "intersect with z " << where << "\n"; #endif plane.Clear(); plane.SetZ(where); Vector3f min = T*Min; Vector3f max = T*Max; plane.Min.x = min.x; plane.Min.y = min.y; plane.Max.x = max.x; plane.Max.y = max.y; Vector2f lineStart; Vector2f lineEnd; bool foundOne = false; for (size_t i = 0; i < triangles.size(); i++) { foundOne=false; CuttingPlane::Segment line(-1,-1); Vector3f P1 = T*triangles[i].A; Vector3f P2 = T*triangles[i].B; // Are the points on opposite sides of the plane ? if ((where <= P1.z) != (where <= P2.z)) { float t = (where-P1.z)/(float)(P2.z-P1.z); Vector3f p = P1+((Vector3f)(P2-P1)*t); lineStart = Vector2f(p.x,p.y); line.start = plane.RegisterPoint(lineStart); foundOne = true; } P1 = T*triangles[i].B; P2 = T*triangles[i].C; if ((where <= P1.z) != (where <= P2.z)) { float t = (where-P1.z)/(float)(P2.z-P1.z); Vector3f p = P1+((Vector3f)(P2-P1)*t); if(foundOne) { lineEnd = Vector2f(p.x,p.y); line.end = plane.RegisterPoint(lineEnd); } else { lineStart = Vector2f(p.x,p.y); line.start = plane.RegisterPoint(lineStart); } } P1 = T*triangles[i].C; P2 = T*triangles[i].A; if ((where <= P1.z) != (where <= P2.z)) { float t = (where-P1.z)/(float)(P2.z-P1.z); Vector3f p = P1+((Vector3f)(P2-P1)*t); lineEnd = Vector2f(p.x,p.y); line.end = plane.RegisterPoint(lineEnd); if( line.end == line.start ) continue; } // Check segment normal against triangle normal. Flip segment, as needed. if (line.start != -1 && line.end != -1 && line.end != line.start) // if we found a intersecting triangle { Vector3f Norm = triangles[i].Normal; Vector2f triangleNormal = Vector2f(Norm.x, Norm.y); Vector2f segmentNormal = (lineEnd - lineStart).normal(); triangleNormal.normalise(); segmentNormal.normalise(); if( (triangleNormal-segmentNormal).lengthSquared() > 0.2f) // if normals does not align, flip the segment line.Swap(); plane.AddLine(line); } } } vector<InFillHit> HitsBuffer; void CuttingPlane::CalcInFill(vector<Vector2f> &infill, uint LayerNr, float InfillDistance, float InfillRotation, float InfillRotationPrLayer, bool DisplayDebuginFill) { int c=0; float step = InfillDistance; bool examine = false; float Length = sqrtf(2)*( ((Max.x)>(Max.y)? (Max.x):(Max.y)) - ((Min.x)<(Min.y)? (Min.x):(Min.y)) )/2.0f; // bbox of lines to intersect the poly with float rot = InfillRotation/180.0f*M_PI; rot += (float)LayerNr*InfillRotationPrLayer/180.0f*M_PI; Vector2f InfillDirX(cosf(rot), sinf(rot)); Vector2f InfillDirY(-InfillDirX.y, InfillDirX.x); Vector2f Center = (Max+Min)/2.0f; for(float x = -Length ; x < Length ; x+=step) { bool examineThis = false; HitsBuffer.clear(); Vector2f P1 = (InfillDirX * Length)+(InfillDirY*x)+ Center; Vector2f P2 = (InfillDirX * -Length)+(InfillDirY*x) + Center; if(DisplayDebuginFill) { glBegin(GL_LINES); glColor3f(0,0.2f,0); glVertex3f(P1.x, P1.y, Z); glVertex3f(P2.x, P2.y, Z); glEnd(); } float Examine = 0.5f; if(DisplayDebuginFill) if(!examine && ((Examine-0.5f)*2 * Length <= x)) { examineThis = examine = true; glColor3f(1,1,1); // Draw the line glVertex3f(P1.x, P1.y, Z); glVertex3f(P2.x, P2.y, Z); } if(offsetPolygons.size() != 0) { for(size_t p=0;p<offsetPolygons.size();p++) { for(size_t i=0;i<offsetPolygons[p].points.size();i++) { Vector2f P3 = offsetVertices[offsetPolygons[p].points[i]]; Vector2f P4 = offsetVertices[offsetPolygons[p].points[(i+1)%offsetPolygons[p].points.size()]]; Vector3f point; InFillHit hit; if(IntersectXY(P1,P2,P3,P4,hit)) { HitsBuffer.push_back(hit); } } } } /* else if(vertices.size() != 0) { // Fallback, collide with lines rather then polygons for(size_t i=0;i<lines.size();i++) { Vector2f P3 = vertices[lines[i].start]; Vector2f P4 = vertices[lines[i].end]; Vector3f point; InFillHit hit; if(IntersectXY(P1,P2,P3,P4,hit)) { if(examineThis) int a=0; HitsBuffer.push_back(hit); } } }*/ // Sort hits // Sort the vector using predicate and std::sort std::sort(HitsBuffer.begin(), HitsBuffer.end(), InFillHitCompareFunc); if(examineThis) { glPointSize(4); glBegin(GL_POINTS); for(size_t i=0;i<HitsBuffer.size();i++) glVertex3f(HitsBuffer[0].p.x, HitsBuffer[0].p.y, Z); glEnd(); glPointSize(1); } // Verify hits intregrety // Check if hit extists in table restart_check: for(size_t i=0;i<HitsBuffer.size();i++) { bool found = false; for(size_t j=i+1;j<HitsBuffer.size();j++) if( ABS(HitsBuffer[i].d - HitsBuffer[j].d) < 0.0001) { found = true; // Delete both points, and continue HitsBuffer.erase(HitsBuffer.begin()+j); if(i != 0 && i != HitsBuffer.size()-1) //If we are "Going IN" to solid material, and there's more points, keep one of the points HitsBuffer.erase(HitsBuffer.begin()+i); goto restart_check; } if(found) continue; } // Sort hits by distance and transfer to InFill Buffer if(HitsBuffer.size() != 0 && HitsBuffer.size() % 2) continue; // There's a uneven number of hits, skip this infill line (U'll live) c=0; // Color counter while(HitsBuffer.size()) { infill.push_back(HitsBuffer[0].p); if(examineThis) { switch(c) { case 0: glColor3f(1,0,0); break; case 1: glColor3f(0,1,0); break; case 2: glColor3f(0,0,1); break; case 3: glColor3f(1,1,0); break; case 4: glColor3f(0,1,1); break; case 5: glColor3f(1,0,1); break; case 6: glColor3f(1,1,1); break; case 7: glColor3f(1,0,0); break; case 8: glColor3f(0,1,0); break; case 9: glColor3f(0,0,1); break; case 10: glColor3f(1,1,0); break; case 11: glColor3f(0,1,1); break; case 12: glColor3f(1,0,1); break; case 13: glColor3f(1,1,1); break; } c++; glPointSize(10); glBegin(GL_POINTS); glVertex3f(HitsBuffer[0].p.x, HitsBuffer[0].p.y, Z); glEnd(); glPointSize(1); } HitsBuffer.erase(HitsBuffer.begin()); } } } // calculates intersection and checks for parallel lines. // also checks that the intersection point is actually on // the line segment p1-p2 bool IntersectXY(const Vector2f &p1, const Vector2f &p2, const Vector2f &p3, const Vector2f &p4, InFillHit &hit) { // BBOX test if(MIN(p1.x,p2.x) > MAX(p3.x,p4.x)) return false; if(MAX(p1.x,p2.x) < MIN(p3.x,p4.x)) return false; if(MIN(p1.y,p2.y) > MAX(p3.y,p4.y)) return false; if(MAX(p1.y,p2.y) < MIN(p3.y,p4.y)) return false; if(ABS(p1.x-p3.x) < 0.01 && ABS(p1.y - p3.y) < 0.01) { hit.p = p1; hit.d = sqrtf( (p1.x-hit.p.x) * (p1.x-hit.p.x) + (p1.y-hit.p.y) * (p1.y-hit.p.y)); hit.t = 0.0f; return true; } if(ABS(p2.x-p3.x) < 0.01 && ABS(p2.y - p3.y) < 0.01) { hit.p = p2; hit.d = sqrtf( (p1.x-hit.p.x) * (p1.x-hit.p.x) + (p1.y-hit.p.y) * (p1.y-hit.p.y)); hit.t = 1.0f; return true; } if(ABS(p1.x-p4.x) < 0.01 && ABS(p1.y - p4.y) < 0.01) { hit.p = p1; hit.d = sqrtf( (p1.x-hit.p.x) * (p1.x-hit.p.x) + (p1.y-hit.p.y) * (p1.y-hit.p.y)); hit.t = 0.0f; return true; } if(ABS(p2.x-p4.x) < 0.01 && ABS(p2.y - p4.y) < 0.01) { hit.p = p2; hit.d = sqrtf( (p1.x-hit.p.x) * (p1.x-hit.p.x) + (p1.y-hit.p.y) * (p1.y-hit.p.y)); hit.t = 1.0f; return true; } InFillHit hit2; float t0,t1; if(intersect2D_Segments(p1,p2,p3,p4,hit.p, hit2.p, t0,t1) == 1) { hit.d = sqrtf( (p1.x-hit.p.x) * (p1.x-hit.p.x) + (p1.y-hit.p.y) * (p1.y-hit.p.y)); hit.t = t0; return true; } return false; /* float xD1,yD1,xD2,yD2,xD3,yD3; float dot,deg,len1,len2; float segmentLen1,segmentLen2; float ua,ub,div; // calculate differences xD1=p2.x-p1.x; xD2=p4.x-p3.x; yD1=p2.y-p1.y; yD2=p4.y-p3.y; xD3=p1.x-p3.x; yD3=p1.y-p3.y; // calculate the lengths of the two lines len1=sqrt(xD1*xD1+yD1*yD1); len2=sqrt(xD2*xD2+yD2*yD2); // calculate angle between the two lines. dot=(xD1*xD2+yD1*yD2); // dot product deg=dot/(len1*len2); // if ABS(angle)==1 then the lines are parallell, // so no intersection is possible if(ABS(deg)==1) return false; // find intersection Pt between two lines hit.p=Vector2f (0,0); div=yD2*xD1-xD2*yD1; ua=(xD2*yD3-yD2*xD3)/div; ub=(xD1*yD3-yD1*xD3)/div; hit.p.x=p1.x+ua*xD1; hit.p.y=p1.y+ua*yD1; // calculate the combined length of the two segments // between Pt-p1 and Pt-p2 xD1=hit.p.x-p1.x; xD2=hit.p.x-p2.x; yD1=hit.p.y-p1.y; yD2=hit.p.y-p2.y; segmentLen1=sqrt(xD1*xD1+yD1*yD1)+sqrt(xD2*xD2+yD2*yD2); // calculate the combined length of the two segments // between Pt-p3 and Pt-p4 xD1=hit.p.x-p3.x; xD2=hit.p.x-p4.x; yD1=hit.p.y-p3.y; yD2=hit.p.y-p4.y; segmentLen2=sqrt(xD1*xD1+yD1*yD1)+sqrt(xD2*xD2+yD2*yD2); // if the lengths of both sets of segments are the same as // the lenghts of the two lines the point is actually // on the line segment. // if the point isn't on the line, return null if(ABS(len1-segmentLen1)>0.00 || ABS(len2-segmentLen2)>0.00) return false; hit.d = segmentLen1-segmentLen2; return true;*/ } /* int PntOnLine(Vector2f p1, Vector2f p2, Vector2f t) { * * given a line through P:(px,py) Q:(qx,qy) and T:(tx,ty) * return 0 if T is not on the line through <--P--Q--> * 1 if T is on the open ray ending at P: <--P * 2 if T is on the closed interior along: P--Q * 3 if T is on the open ray beginning at Q: Q--> * * Example: consider the line P = (3,2), Q = (17,7). A plot * of the test points T(x,y) (with 0 mapped onto '.') yields: * * 8| . . . . . . . . . . . . . . . . . 3 3 * Y 7| . . . . . . . . . . . . . . 2 2 Q 3 3 Q = 3 * 6| . . . . . . . . . . . 2 2 2 2 2 . . . * a 5| . . . . . . . . 2 2 2 2 2 2 . . . . . * x 4| . . . . . 2 2 2 2 2 2 . . . . . . . . * i 3| . . . 2 2 2 2 2 . . . . . . . . . . . * s 2| 1 1 P 2 2 . . . . . . . . . . . . . . P = 1 * 1| 1 1 . . . . . . . . . . . . . . . . . * +-------------------------------------- * 1 2 3 4 5 X-axis 10 15 19 * * Point-Line distance is normalized with the Infinity Norm * avoiding square-root code and tightening the test vs the * Manhattan Norm. All math is done on the field of integers. * The latter replaces the initial ">= MAX(...)" test with * "> (ABS(qx-px) + ABS(qy-py))" loosening both inequality * and norm, yielding a broader target line for selection. * The tightest test is employed here for best discrimination * in merging collinear (to grid coordinates) vertex chains * into a larger, spanning vectors within the Lemming editor. if ( ABS((p2.y-p1.y)*(t.x-p1.x)-(t.y-p1.y)*(p2.x-p1.x)) >= (MAX(ABS(p2.x-p1.x), ABS(p2.y-p1.y)))) return(0); if (((p2.x<=p1.x)&&(p1.x<=t.x)) || ((p2.y<=p1.y)&&(p1.y<=t.y))) return(1); if (((t.x<=p1.x)&&(p1.x<=p2.x)) || ((t.y<=p1.y)&&(p1.y<=p2.y))) return(1); if (((p1.x<=p2.x)&&(p2.x<=t.x)) || ((p1.y<=p2.y)&&(p2.y<=t.y))) return(3); if (((t.x<=p2.x)&&(p2.x<=p1.x)) || ((t.y<=p2.y)&&(p2.y<=p1.y))) return(3); return(2); } */ float dist ( float x1, float y1, float x2, float y2) { return sqrt( ((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)) ) ; } int PntOnLine(Vector2f p1, Vector2f p2, Vector2f t, float &where) { float A = t.x - p1.x; float B = t.y - p1.y; float C = p2.x - p1.x; float D = p2.y - p1.y; where = ABS(A * D - C * B) / sqrt(C * C + D * D); if(where > 0.01) return 0; float dot = A * C + B * D; float len_sq = C * C + D * D; where = dot / len_sq; /* float xx,yy; xx = p1.x + where * C; yy = p1.y + where * D; glPointSize(8); glBegin(GL_POINTS); glColor3f(1,0,1); glVertex2f(xx, yy); glEnd(); */ if(where <= 0.0f) // before p1 { // where = param; return 1; /* xx = p1.x; yy = p1.y; where = dist(t.x, t.y, xx, yy);//your distance function return 1;*/ } else if(where >= 1.0f) // after p2 { // where = param; return 3; /* xx = p2.x; yy = p2.y; where = dist(t.x, t.y, xx, yy);//your distance function return 3;*/ } else // between p1 and p2 { // where = param; return 2; // fast exit, don't need where for this case /* xx = p1.x + param * C; yy = p1.y + param * D; where = dist(t.x, t.y, xx, yy);//your distance function return 2;*/ } } class OverlapLine{ public: OverlapLine(Vector2f start, Vector2f end){s=start;e=end;}; bool overlaps(Vector2f p1, Vector2f p2) { int res[2]; float t1,t2; if(p1 == s || p2==s) return 1; if(p1 == e || p2==e) return 3; res[0] = PntOnLine(s,e,p1, t1); // Is p1 on my line? if(res[0] == 0) return false; res[1] = PntOnLine(s,e,p2, t2); // Is p2 on my line? if(res[1] == 0) return false; glPointSize(2); glBegin(GL_POINTS); glColor3f(1,0,0); glVertex2f(s.x, s.y); glColor3f(0,1,0); glVertex2f(e.x, e.y); glEnd(); if(res[0] != res[1]) // expanding both ends { Vector2f i1 = s+(e-s)*t1; Vector2f i2 = s+(e-s)*t2; if(t1 < 0 && t1 < t2) // Move p1 s = p1; else if(t2 < 0) // Move p1 s = p2; if(t1 > 1 && t1 > t2) e = p1; else if(t2 > 1) // e = p2; /* glPointSize(5); glBegin(GL_POINTS); glColor3f(1,0,0); glVertex2f(s.x, s.y); glColor3f(0,1,0); glVertex2f(e.x, e.y); glEnd(); */ return true; } glPointSize(1); glBegin(GL_POINTS); glColor3f(0.5,0.5,0.5); glVertex2f(s.x, s.y); glColor3f(0.5,0.5,0.5); glVertex2f(e.x, e.y); glEnd(); return false; } Vector2f s,e; }; /* * Unfortunately, finding connections via co-incident points detected by * the PointHash is not perfect. For reasons unknown (probably rounding * errors), this is often not enough. We fall-back to finding a nearest * match from any detached points and joining them, with new synthetic * segments. */ bool CuttingPlane::CleanupConnectSegments(float z) { vector<int> vertex_types; vector<int> vertex_counts; vertex_types.resize (vertices.size()); vertex_counts.resize (vertices.size()); // which vertices are referred to, and how much: for (uint i = 0; i < lines.size(); i++) { vertex_types[lines[i].start]++; vertex_types[lines[i].end]--; vertex_counts[lines[i].start]++; vertex_counts[lines[i].end]++; } // the count should be zero for all connected lines, // positive for those ending no-where, and negative for // those starting no-where. std::vector<int> detached_points; for (uint i = 0; i < vertex_types.size(); i++) { if (vertex_types[i]) { #if CUTTING_PLANE_DEBUG cout << "detached point " << i << "\t" << vertex_types[i] << " refs at " << vertices[i].x << "\t" << vertices[i].y << "\n"; #endif detached_points.push_back (i); } } // Lets hope we have an even number of detached points if (detached_points.size() % 2) { cout << "oh dear - an odd number of detached points => an un-pairable impossibility\n"; return false; } // pair them nicely to their matching type for (uint i = 0; i < detached_points.size(); i++) { float nearest_dist_sq = (std::numeric_limits<float>::max)(); int nearest = 0; int n = detached_points[i]; if (n < 0) continue; const Vector2f &p = vertices[n]; for (uint j = i + 1; j < detached_points.size(); j++) { int pt = detached_points[j]; if (pt < 0) continue; // already connected // don't connect a start to a start if (vertex_types[n] == vertex_types[pt]) continue; const Vector2f &q = vertices[pt]; float dist_sq = pow (p.x - q.x, 2) + pow (p.y - q.y, 2); if (dist_sq < nearest_dist_sq) { nearest_dist_sq = dist_sq; nearest = j; } } assert (nearest != 0); // allow points 1mm apart to be joined, not more if (nearest_dist_sq > 1.0) { cout << "oh dear - the nearest connecting point is " << sqrt (nearest_dist_sq) << "mm away - aborting\n"; return false; } #if CUTTING_PLANE_DEBUG cout << "add join of length " << sqrt (nearest_dist_sq) << "\n" ; #endif CuttingPlane::Segment seg(detached_points[nearest], detached_points[i]); if (vertex_types[n] < 0) // start but no end at this point seg.Swap(); AddLine (seg); detached_points[nearest] = -1; } return true; } /* * sometimes we find adjacent polygons with shared boundary * points and lines; these cause grief and slowness in * LinkSegments, so try to identify and join those polygons * now. */ bool CuttingPlane::CleanupSharedSegments(float z) { vector<int> vertex_counts; vertex_counts.resize (vertices.size()); for (uint i = 0; i < lines.size(); i++) { vertex_counts[lines[i].start]++; vertex_counts[lines[i].end]++; } // ideally all points have an entrance and // an exit, if we have co-incident lines, then // we have more than one; do we ? std::vector<int> duplicate_points; for (uint i = 0; i < vertex_counts.size(); i++) { #if CUTTING_PLANE_DEBUG cout << "vtx " << i << " count: " << vertex_counts[i] << "\n"; #endif if (vertex_counts[i] > 2) duplicate_points.push_back (i); } if (duplicate_points.size() == 0) return true; // all sane for (uint i = 0; i < duplicate_points.size(); i++) { std::vector<int> dup_lines; // find all line segments with this point in use for (uint j = 0; j < lines.size(); j++) { if (lines[j].start == duplicate_points[i] || lines[j].end == duplicate_points[i]) dup_lines.push_back (j); } // identify and eliminate identical line segments // NB. hopefully by here dup_lines.size is small. std::vector<int> lines_to_delete; for (uint j = 0; j < dup_lines.size(); j++) { const Segment &jr = lines[dup_lines[j]]; for (uint k = j + 1; k < dup_lines.size(); k++) { const Segment &kr = lines[dup_lines[k]]; if ((jr.start == kr.start && jr.end == kr.end) || (jr.end == kr.start && jr.start == kr.end)) { lines_to_delete.push_back (dup_lines[j]); lines_to_delete.push_back (dup_lines[k]); } } } // we need to remove from the end first to avoid disturbing // the order of removed items std::sort(lines_to_delete.begin(), lines_to_delete.end()); for (int r = lines_to_delete.size() - 1; r >= 0; r--) { #if CUTTING_PLANE_DEBUG cout << "delete co-incident line: " << lines_to_delete[r] << "\n"; #endif lines.erase(lines.begin() + lines_to_delete[r]); } } return true; } /* * Attempt to link all the Segments in 'lines' together. */ bool CuttingPlane::LinkSegments(float z, float Optimization) { if (vertices.size() == 0) return true; if (!CleanupSharedSegments (z)) return false; if (!CleanupConnectSegments (z)) return false; vector<vector<int> > planepoints; planepoints.resize(vertices.size()); for (uint i = 0; i < lines.size(); i++) planepoints[lines[i].start].push_back(i); // Build polygons vector<bool> used; used.resize(lines.size()); for (uint i=0;i>used.size();i++) used[i] = false; for (uint current = 0; current < lines.size(); current++) { if (used[current]) continue; // already used used[current] = true; int startPoint = lines[current].start; int endPoint = lines[current].end; Poly poly; poly.points.push_back (endPoint); int count = lines.size()+100; while (endPoint != startPoint && count != 0) // While not closed { const vector<int> &pathsfromhere = planepoints[endPoint]; // Find the next line. if (pathsfromhere.size() == 0) // no where to go ... { // lets get to the bottom of this data set: cout.precision (8); cout.width (12); cout << "\r\npolygon was cut at z " << z << " LinkSegments at vertex " << endPoint; cout << "\n " << vertices.size() << " vertices:\nvtx\tpos x\tpos y\trefs\n"; for (int i = 0; i < (int)vertices.size(); i++) { int refs = 0, pol = 0; for (int j = 0; j < (int)lines.size(); j++) { if (lines[j].start == i) { refs++; pol++; } if (lines[j].end == i) { refs++; pol--; } } cout << i << "\t" << vertices[i].x << "\t" << vertices[i].y << "\t" << refs << " pol " << pol; if (refs % 2) // oh dear, a dangling vertex cout << " odd, dangling vertex\n"; cout << "\n"; } cout << "\n " << lines.size() << " lines:\nline\tstart vtx\tend vtx\n"; for (int i = 0; i < (int)lines.size(); i++) { if (i == endPoint) cout << "problem line:\n"; cout << i << "\t" << lines[i].start << "\t" << lines[i].end << "\n"; } cout << "\n " << vertices.size() << " vertices:\nvtx\tpos x\tpos y\tlinked to\n"; for (int i = 0; i < (int)planepoints.size(); i++) { if (i == endPoint) cout << "problem vertex:\n"; cout << i << "\t" << vertices[i].x << "\t" << vertices[i].y << "\t"; int j; switch (planepoints[i].size()) { case 0: cout << "nothing - error !\n"; break; case 1: cout << "neighbour: " << planepoints[i][0]; break; default: cout << "Unusual - multiple: \n"; for (j = 0; j < (int)planepoints[i].size(); j++) cout << planepoints[i][j] << " "; cout << " ( " << j << " other vertices )"; break; } cout << "\n"; } // model failure - we will get called recursivelly // for a different z and different cutting plane. return false; } if (pathsfromhere.size() != 1) cout << "Risky co-incident node during shrinking\n"; // TODO: we need to do better here, some idas: // a) calculate the shortest path back to our start node, and // choose that and/or // b) identify all 2+ nodes and if they share start/end // directions eliminate them to join the polygons. uint i; for (i = 0; i < pathsfromhere.size() && used[pathsfromhere[i]]; i++); if (i >= pathsfromhere.size()) { cout << "no-where unused to go"; return false; } used[pathsfromhere[i]] = true; const Segment &nextsegment = lines[pathsfromhere[i]]; assert( nextsegment.start == endPoint ); endPoint = nextsegment.end; poly.points.push_back (endPoint); count--; } // Check if loop is complete if (count != 0) polygons.push_back (poly); // This is good else { // We will be called for a slightly different z cout << "\r\nentered loop at LinkSegments " << z; return false; } } // Cleanup polygons CleanupPolygons(Optimization); return true; } uint CuttingPlane::selfIntersectAndDivideRecursive(float z, uint startPolygon, uint startVertex, vector<outline> &outlines, const Vector2f endVertex, uint &level) { level++; outline result; for(size_t p=startPolygon; p<offsetPolygons.size();p++) { size_t count = offsetPolygons[p].points.size(); for(size_t v=startVertex; v<count;v++) { for(size_t p2=0; p2<offsetPolygons.size();p2++) { size_t count2 = offsetPolygons[p2].points.size(); for(size_t v2=0; v2<count2;v2++) { if((p==p2) && (v == v2)) // Dont check a point against itself continue; Vector2f P1 = offsetVertices[offsetPolygons[p].points[v]]; Vector2f P2 = offsetVertices[offsetPolygons[p].points[(v+1)%count]]; Vector2f P3 = offsetVertices[offsetPolygons[p2].points[v2]]; Vector2f P4 = offsetVertices[offsetPolygons[p2].points[(v2+1)%count2]]; InFillHit hit; result.push_back(P1); if(P1 != P3 && P2 != P3 && P1 != P4 && P2 != P4) if(IntersectXY(P1,P2,P3,P4,hit)) { if( (hit.p-endVertex).length() < 0.01) { // outlines.push_back(result); // return (v+1)%count; } result.push_back(hit.p); // v=selfIntersectAndDivideRecursive(z, p2, (v2+1)%count2, outlines, hit.p, level); // outlines.push_back(result); // return; } } } } } outlines.push_back(result); level--; return startVertex; } void CuttingPlane::recurseSelfIntersectAndDivide(float z, vector<locator> &EndPointStack, vector<outline> &outlines, vector<locator> &visited) { // pop an entry from the stack. // Trace it till it hits itself // store a outline // When finds splits, store locator on stack and recurse while(EndPointStack.size()) { locator start(EndPointStack.back().p, EndPointStack.back().v, EndPointStack.back().t); visited.push_back(start); // add to visited list EndPointStack.pop_back(); // remove from to-do stack // search for the start point outline result; for(int p = start.p; p < (int)offsetPolygons.size(); p++) { for(int v = start.v; v < (int)offsetPolygons[p].points.size(); v++) { Vector2f P1 = offsetVertices[offsetPolygons[p].points[v]]; Vector2f P2 = offsetVertices[offsetPolygons[p].points[(v+1)%offsetPolygons[p].points.size()]]; result.push_back(P1); // store this point for(int p2=0; p2 < (int)offsetPolygons.size(); p2++) { int count2 = offsetPolygons[p2].points.size(); for(int v2 = 0; v2 < count2; v2++) { if((p==p2) && (v == v2)) // Dont check a point against itself continue; Vector2f P3 = offsetVertices[offsetPolygons[p2].points[v2]]; Vector2f P4 = offsetVertices[offsetPolygons[p2].points[(v2+1)%offsetPolygons[p2].points.size()]]; InFillHit hit; if(P1 != P3 && P2 != P3 && P1 != P4 && P2 != P4) { if(IntersectXY(P1,P2,P3,P4,hit)) { bool alreadyVisited=false; size_t i; for(i=0;i<visited.size();i++) { if(visited[i].p == p && visited[i].v == v) { alreadyVisited = true; break; } } if(alreadyVisited == false) { EndPointStack.push_back(locator(p,v+1,hit.t)); // continue from here later on p=p2;v=v2; // continue along the intersection line Vector2f P1 = offsetVertices[offsetPolygons[p].points[v]]; Vector2f P2 = offsetVertices[offsetPolygons[p].points[(v+1)%offsetPolygons[p].points.size()]]; } result.push_back(hit.p); // Did we hit the starting point? if (start.p == p && start.v == v) // we have a loop { outlines.push_back(result); result.clear(); recurseSelfIntersectAndDivide(z, EndPointStack, outlines, visited); return; } glPointSize(10); glColor3f(1,1,1); glBegin(GL_POINTS); glVertex3f(hit.p.x, hit.p.y, z); glEnd(); } } } } } } } } float angleBetween(Vector2f V1, Vector2f V2) { float dotproduct, lengtha, lengthb, result; dotproduct = (V1.x * V2.x) + (V1.y * V2.y); lengtha = sqrt(V1.x * V1.x + V1.y * V1.y); lengthb = sqrt(V2.x * V2.x + V2.y * V2.y); result = acos( dotproduct / (lengtha * lengthb) ); if(result > 0) result += M_PI; else result -= M_PI; return result; } bool not_equal(const float& val1, const float& val2) { float diff = val1 - val2; return ((-Epsilon > diff) || (diff > Epsilon)); } bool is_equal(const float& val1, const float& val2) { float diff = val1 - val2; return ((-Epsilon <= diff) && (diff <= Epsilon)); } bool intersect(const float& x1, const float& y1, const float& x2, const float& y2, const float& x3, const float& y3, const float& x4, const float& y4, float& ix, float& iy) { float ax = x2 - x1; float bx = x3 - x4; float lowerx; float upperx; float uppery; float lowery; if (ax < float(0.0)) { lowerx = x2; upperx = x1; } else { upperx = x2; lowerx = x1; } if (bx > float(0.0)) { if ((upperx < x4) || (x3 < lowerx)) return false; } else if ((upperx < x3) || (x4 < lowerx)) return false; float ay = y2 - y1; float by = y3 - y4; if (ay < float(0.0)) { lowery = y2; uppery = y1; } else { uppery = y2; lowery = y1; } if (by > float(0.0)) { if ((uppery < y4) || (y3 < lowery)) return false; } else if ((uppery < y3) || (y4 < lowery)) return false; float cx = x1 - x3; float cy = y1 - y3; float d = (by * cx) - (bx * cy); float f = (ay * bx) - (ax * by); if (f > float(0.0)) { if ((d < float(0.0)) || (d > f)) return false; } else if ((d > float(0.0)) || (d < f)) return false; float e = (ax * cy) - (ay * cx); if (f > float(0.0)) { if ((e < float(0.0)) || (e > f)) return false; } else if ((e > float(0.0)) || (e < f)) return false; float ratio = (ax * -by) - (ay * -bx); if (not_equal(ratio,float(0.0))) { ratio = ((cy * -bx) - (cx * -by)) / ratio; ix = x1 + (ratio * ax); iy = y1 + (ratio * ay); } else { if (is_equal((ax * -cy),(-cx * ay))) { ix = x3; iy = y3; } else { ix = x4; iy = y4; } } return true; } CuttingPlaneOptimizer::CuttingPlaneOptimizer(CuttingPlane* cuttingPlane, float z) { Z = z; vector<Poly>* planePolygons = &cuttingPlane->GetPolygons(); vector<Vector2f>* planeVertices = &cuttingPlane->GetVertices(); std::list<Polygon2f*> unsortedPolys; // first add solids. This builds the tree, placing the holes afterwards is easier/faster for(uint p = 0; p < planePolygons->size(); p++) { Poly* poly = &((*planePolygons)[p]); poly->calcHole(*planeVertices); if( !poly->hole ) { Polygon2f* newPoly = new Polygon2f(); newPoly->hole = poly->hole; newPoly->index = p; size_t count = poly->points.size(); for(size_t i=0; i<count;i++) { newPoly->vertices.push_back(((*planeVertices)[poly->points[i]])); } PushPoly(newPoly); } } // then add holes for(uint p = 0; p < planePolygons->size(); p++) { Poly* poly = &((*planePolygons)[p]); if( poly->hole ) { Polygon2f* newPoly = new Polygon2f(); newPoly->hole = poly->hole; size_t count = poly->points.size(); for (size_t i = 0; i < count; i++) { newPoly->vertices.push_back(((*planeVertices)[poly->points[i]])); } PushPoly(newPoly); } } } void CuttingPlaneOptimizer::Dispose() { for(list<Polygon2f*>::iterator pIt =positivePolygons.begin(); pIt!=positivePolygons.end(); pIt++) { delete (*pIt); *pIt = NULL; } } void CuttingPlaneOptimizer::MakeOffsetPolygons(vector<Poly>& polys, vector<Vector2f>& vectors) { for(list<Polygon2f*>::iterator pIt=this->positivePolygons.begin(); pIt!=this->positivePolygons.end(); pIt++) { DoMakeOffsetPolygons(*pIt, polys, vectors); } } void CuttingPlaneOptimizer::DoMakeOffsetPolygons(Polygon2f* pPoly, vector<Poly>& polys, vector<Vector2f>& vectors) { Poly p; for( vector<Vector2f>::iterator pIt = pPoly->vertices.begin(); pIt!=pPoly->vertices.end(); pIt++) { p.points.push_back(vectors.size()); vectors.push_back(*pIt); } p.hole = pPoly->hole; polys.push_back(p); for( list<Polygon2f*>::iterator pIt = pPoly->containedSolids.begin(); pIt!=pPoly->containedSolids.end(); pIt++) { DoMakeOffsetPolygons(*pIt, polys, vectors); } for( list<Polygon2f*>::iterator pIt = pPoly->containedHoles.begin(); pIt!=pPoly->containedHoles.end(); pIt++) { DoMakeOffsetPolygons(*pIt, polys, vectors); } } void CuttingPlaneOptimizer::RetrieveLines(vector<Vector3f>& lines) { for(list<Polygon2f*>::iterator pIt=this->positivePolygons.begin(); pIt!=this->positivePolygons.end(); pIt++) { DoRetrieveLines(*pIt, lines); } } void CuttingPlaneOptimizer::DoRetrieveLines(Polygon2f* pPoly, vector<Vector3f>& lines) { if( pPoly->vertices.size() == 0) return; lines.reserve(lines.size()+pPoly->vertices.size()*2); { vector<Vector2f>::iterator pIt = pPoly->vertices.begin(); lines.push_back(Vector3f(pIt->x, pIt->y, Z)); pIt++; for( ; pIt!=pPoly->vertices.end(); pIt++) { lines.push_back(Vector3f(pIt->x, pIt->y, Z)); lines.push_back(Vector3f(pIt->x, pIt->y, Z)); } lines.push_back(Vector3f(pPoly->vertices.front().x, pPoly->vertices.front().y, Z)); } for( list<Polygon2f*>::iterator pIt = pPoly->containedSolids.begin(); pIt!=pPoly->containedSolids.end(); pIt++) { DoRetrieveLines(*pIt, lines); } for( list<Polygon2f*>::iterator pIt = pPoly->containedHoles.begin(); pIt!=pPoly->containedHoles.end(); pIt++) { DoRetrieveLines(*pIt, lines); } } void CuttingPlaneOptimizer::PushPoly(Polygon2f* poly) { poly->PlaceInList(positivePolygons); } void CuttingPlaneOptimizer::Draw() { float color = 1; Polygon2f::DisplayPolygons(positivePolygons, Z, 0,color,0,1); for(list<Polygon2f*>::iterator pIt =positivePolygons.begin(); pIt!=positivePolygons.end(); pIt++) { Polygon2f::DrawRecursive(*pIt, Z, color); } } void CuttingPlaneOptimizer::Shrink(float distance, list<Polygon2f*> &resPolygons) { for(list<Polygon2f*>::iterator pIt =positivePolygons.begin(); pIt!=positivePolygons.end(); pIt++) { list<Polygon2f*> parentPolygons; (*pIt)->Shrink(distance, parentPolygons, resPolygons); } } void CuttingPlane::ShrinkLogick(float extrudedWidth, float optimization, bool DisplayCuttingPlane, int ShellCount) { CuttingPlaneOptimizer* cpo = new CuttingPlaneOptimizer(this, Z); optimizers.push_back(cpo); CuttingPlaneOptimizer* clippingPlane = new CuttingPlaneOptimizer(Z); cpo->Shrink(extrudedWidth*0.5, clippingPlane->positivePolygons); optimizers.push_back(clippingPlane); for(int outline = 2; outline <= ShellCount+1; outline++) { CuttingPlaneOptimizer* newOutline = new CuttingPlaneOptimizer(Z); optimizers.back()->Shrink(extrudedWidth, newOutline->positivePolygons); optimizers.push_back(newOutline); } optimizers.back()->MakeOffsetPolygons(offsetPolygons, offsetVertices); } void CuttingPlane::ShrinkFast(float distance, float optimization, bool DisplayCuttingPlane, bool useFillets, int ShellCount) { distance*=ShellCount; glColor4f(1,1,1,1); for(size_t p=0; p<polygons.size();p++) { Poly offsetPoly; if(DisplayCuttingPlane) glBegin(GL_LINE_LOOP); size_t count = polygons[p].points.size(); for(size_t i=0; i<count;i++) { Vector2f Na = Vector2f(vertices[polygons[p].points[(i-1+count)%count]].x, vertices[polygons[p].points[(i-1+count)%count]].y); Vector2f Nb = Vector2f(vertices[polygons[p].points[i]].x, vertices[polygons[p].points[i]].y); Vector2f Nc = Vector2f(vertices[polygons[p].points[(i+1)%count]].x, vertices[polygons[p].points[(i+1)%count]].y); Vector2f V1 = (Nb-Na).getNormalized(); Vector2f V2 = (Nc-Nb).getNormalized(); Vector2f biplane = (V2 - V1).getNormalized(); float a = angleBetween(V1,V2); bool convex = V1.cross(V2) < 0; Vector2f p; if(convex) p = Nb+biplane*distance/(cos((M_PI-a)*0.5f)); else p = Nb-biplane*distance/(sin(a*0.5f)); /* if(DisplayCuttingPlane) glEnd(); if(convex) glColor3f(1,0,0); else glColor3f(0,1,0); ostringstream oss; oss << a; renderBitmapString(Vector3f (Nb.x, Nb.y, Z) , GLUT_BITMAP_8_BY_13 , oss.str()); if(DisplayCuttingPlane) glBegin(GL_LINE_LOOP); glColor3f(1,1,0); */ /* Vector2f N1 = Vector2f(-V1.y, V1.x); Vector2f N2 = Vector2f(-V2.y, V2.x); N1.normalise(); N2.normalise(); Vector2f Normal = N1+N2; Normal.normalise(); int vertexNr = polygons[p].points[i]; Vector2f p = vertices[vertexNr] - (Normal * distance);*/ offsetPoly.points.push_back(offsetVertices.size()); offsetVertices.push_back(p); if(DisplayCuttingPlane) glVertex3f(p.x, p.y, Z); } if(DisplayCuttingPlane) glEnd(); offsetPolygons.push_back(offsetPoly); } // CleanupOffsetPolygons(0.1f); // selfIntersectAndDivide(); //make this work for z-tensioner_1off.stl rotated 45d on X axis } /* bool Point2f::FindNextPoint(Point2f* origin, Point2f* destination, bool expansion) { assert(ConnectedPoints.size() >= 2 ); if( ConnectedPoints.size() == 2 ) { if( ConnectedPoints.front() == origin ) { destination = ConnectedPoints.back(); ConnectedPoints.clear(); return true; } else { if( ConnectedPoints.back() == origin ) { destination = ConnectedPoints.front(); ConnectedPoints.clear(); return true; } destination = NULL; return false; } } float originAngle = AngleTo(origin); float minAngle = PI*4; float maxAngle = -PI*4; for(list<Point2f*>::iterator it = ConnectedPoints.begin(); it != ConnectedPoints.end(); ) { if( *it != origin ) { float angle = AngleTo(*it)-originAngle; if( expansion ) { if( angle > 0 ) angle -= PI*2; if( angle < minAngle ) { minAngle = angle; destination = *it; } } else { if( angle < 0 ) angle += PI*2; if( angle > maxAngle ) { maxAngle = angle; destination = *it; } } it++; } else { it = ConnectedPoints.erase(it); } } ConnectedPoints.remove(destination); return true; } float Point2f::AngleTo(Point2f* point) { return atan2f(Point.y-point->Point.y, Point.x-point->Point.x); } */ /*********************************************************************************************/ /*** ***/ /*** Bisector/Fillet/Boolean version ***/ /*** ***/ /*********************************************************************************************/ /*void CuttingPlane::Shrink(float distance, float z, bool DisplayCuttingPlane, bool useFillets) { }*/ /* * We bucket space up into a grid of size 1/mult and generate hash values * from this. We use a margin of 2 * float_epsilon to detect values near * the bottom or right hand edge of the bucket, and check the adjacent * grid entries for similar values within float_epsilon of us. */ struct PointHash::Impl { typedef std::vector< std::pair< uint, Vector2f > > IdxPointList; hash_map<uint, IdxPointList> points; typedef hash_map<uint, IdxPointList>::iterator iter; typedef hash_map<uint, IdxPointList>::const_iterator const_iter; static uint GetHashes (uint *hashes, float x, float y) { uint xh = x * mult; uint yh = y * mult; int xt, yt; uint c = 0; hashes[c++] = xh + yh * 1000000; if ((xt = (uint)((x + 2*PointHash::float_epsilon) * PointHash::mult) - xh)) hashes[c++] = xh + xt + yh * 1000000; if ((yt = (uint)((y + 2*PointHash::float_epsilon) * PointHash::mult) - yh)) hashes[c++] = xh + (yt + yh) * 1000000; if (xt && yt) hashes[c++] = xh + xt + (yt + yh) * 1000000; #if CUTTING_PLANE_DEBUG > 1 cout << "hashes for " << x << ", " << y << " count: " << c << ": "; for (int i = 0; i < c; i++) cout << hashes[i] << ", "; cout << "\n"; #endif return c; } }; const float PointHash::mult = 100; const float PointHash::float_epsilon = 0.001; PointHash::PointHash() { impl = new Impl(); } PointHash::~PointHash() { clear(); delete impl; } PointHash::PointHash(const PointHash &copy) { impl = new Impl(); Impl::const_iter it; for (it = copy.impl->points.begin(); it != copy.impl->points.end(); it++) impl->points[it->first] = it->second; } void PointHash::clear() { impl->points.clear(); } int PointHash::IndexOfPoint(const Vector2f &p) { uint hashes[4]; uint c = Impl::GetHashes (hashes, p.x, p.y); for (uint i = 0; i < c; i++) { Impl::const_iter iter = impl->points.find (hashes[i]); if (iter == impl->points.end()) continue; const Impl::IdxPointList &pts = iter->second; for (uint j = 0; j < pts.size(); j++) { const Vector2f &v = pts[j].second; if( ABS(v.x - p.x) < float_epsilon && ABS(v.y - p.y) < float_epsilon) return pts[j].first; #if CUTTING_PLANE_DEBUG > 1 else if( ABS(v.x-p.x) < 0.01 && ABS(v.y-p.y) < 0.01) cout << "hash " << hashes[i] << " missed idx " << pts[j].first << " by " << (v.x - p.x) << ", " << (v.y - p.y) << " hash: " << v.x << ", " << v.y << " vs. p " << p.x << ", " << p.y << "\n"; #endif } } return -1; } void PointHash::InsertPoint (uint idx, const Vector2f &p) { uint hashes[4]; int c = Impl::GetHashes (hashes, p.x, p.y); for (int i = 0; i < c; i++) { Impl::IdxPointList &pts = impl->points[hashes[i]]; pts.push_back (pair<uint, Vector2f>( idx, p )); #if CUTTING_PLANE_DEBUG > 1 cout << "insert " << hashes[i] << " idx " << idx << " vs. p " << p.x << ", " << p.y << "\n"; #endif } } void CuttingPlane::AddLine(const Segment &line) { lines.push_back(line); } int CuttingPlane::RegisterPoint(const Vector2f &p) { int res; if( (res = points.IndexOfPoint(p)) >= 0) { #if CUTTING_PLANE_DEBUG > 1 cout << "found vertex idx " << res << " at " << p.x << ", " << p.y << "\n"; #endif return res; } res = vertices.size(); vertices.push_back(p); #if CUTTING_PLANE_DEBUG > 1 cout << "insert vertex idx " << res << " at " << p.x << ", " << p.y << "\n"; #endif points.InsertPoint(res, p); return res; } bool CuttingPlane::VertexIsOutsideOriginalPolygon( Vector2f point, float z) { // Shoot a ray along +X and count the number of intersections. // If n_intersections is euqal, return true, else return false Vector2f EndP(point.x+10000, point.y); int intersectcount = 0; for(size_t p=0; p<polygons.size();p++) { size_t count = polygons[p].points.size(); for(size_t i=0; i<count;i++) { Vector2f P1 = Vector2f( vertices[polygons[p].points[(i-1+count)%count]] ); Vector2f P2 = Vector2f( vertices[polygons[p].points[i]]); if(P1.y == P2.y) // Skip hortisontal lines, we can't intersect with them, because the test line in horitsontal continue; InFillHit hit; if(IntersectXY(point,EndP,P1,P2,hit)) intersectcount++; } } return intersectcount%2; } #define RESOLUTION 4 #define FREE(p) {if (p) {free(p); (p)= NULL;}} void CuttingPlane::Draw(bool DrawVertexNumbers, bool DrawLineNumbers, bool DrawOutlineNumbers, bool DrawCPLineNumbers, bool DrawCPVertexNumbers) { // Draw the raw poly's in red glColor3f(1,0,0); for(size_t p=0; p<polygons.size();p++) { glLineWidth(1); glBegin(GL_LINE_LOOP); for(size_t v=0; v<polygons[p].points.size();v++) glVertex3f(vertices[polygons[p].points[v]].x, vertices[polygons[p].points[v]].y, Z); glEnd(); if(DrawOutlineNumbers) { ostringstream oss; oss << p; renderBitmapString(Vector3f(polygons[p].center.x, polygons[p].center.y, Z) , GLUT_BITMAP_8_BY_13 , oss.str()); } } for(size_t o=1;o<optimizers.size()-1;o++) { optimizers[o]->Draw(); } glPointSize(1); glBegin(GL_POINTS); glColor4f(1,0,0,1); for(size_t v=0;v<vertices.size();v++) { glVertex3f(vertices[v].x, vertices[v].y, Z); } glEnd(); glColor4f(1,1,0,1); glPointSize(3); glBegin(GL_POINTS); for(size_t p=0;p<polygons.size();p++) { for(size_t v=0;v<polygons[p].points.size();v++) { glVertex3f(vertices[polygons[p].points[v]].x, vertices[polygons[p].points[v]].y, Z); } } glEnd(); if(DrawVertexNumbers) { for(size_t v=0;v<vertices.size();v++) { ostringstream oss; oss << v; renderBitmapString(Vector3f (vertices[v].x, vertices[v].y, Z) , GLUT_BITMAP_8_BY_13 , oss.str()); } } if(DrawLineNumbers) { for(size_t l=0;l<lines.size();l++) { ostringstream oss; oss << l; Vector2f Center = (vertices[lines[l].start]+vertices[lines[l].end]) *0.5f; glColor4f(1,0.5,0,1); renderBitmapString(Vector3f (Center.x, Center.y, Z) , GLUT_BITMAP_8_BY_13 , oss.str()); } } if(DrawCPVertexNumbers) { for(size_t p=0; p<polygons.size();p++) { for(size_t v=0; v<polygons[p].points.size();v++) { ostringstream oss; oss << v; renderBitmapString(Vector3f(vertices[polygons[p].points[v]].x, vertices[polygons[p].points[v]].y, Z) , GLUT_BITMAP_8_BY_13 , oss.str()); } } } if(DrawCPLineNumbers) { Vector3f loc; loc.z = Z; for(size_t p=0; p<polygons.size();p++) { for(size_t v=0; v<polygons[p].points.size();v++) { loc.x = (vertices[polygons[p].points[v]].x + vertices[polygons[p].points[(v+1)%polygons[p].points.size()]].x) /2; loc.y = (vertices[polygons[p].points[v]].y + vertices[polygons[p].points[(v+1)%polygons[p].points.size()]].y) /2; ostringstream oss; oss << v; renderBitmapString(loc, GLUT_BITMAP_8_BY_13 , oss.str()); } } } // Pathfinder a(offsetPolygons, offsetVertices); } void STL::OptimizeRotation() { // Find the axis that has the largest surface // Rotate to point this face towards -Z // if dist center <|> 0.1 && Normal points towards, add area Vector3f AXIS_VECTORS[3]; AXIS_VECTORS[0] = Vector3f(1,0,0); AXIS_VECTORS[1] = Vector3f(0,1,0); AXIS_VECTORS[2] = Vector3f(0,0,1); float area[6]; for(uint i=0;i<6;i++) area[i] = 0.0f; for(size_t i=0;i<triangles.size();i++) { triangles[i].axis = NOT_ALIGNED; for(size_t triangleAxis=0;triangleAxis<3;triangleAxis++) { if (triangles[i].Normal.cross(AXIS_VECTORS[triangleAxis]).length() < 0.1) { int positive=0; if(triangles[i].Normal[triangleAxis] > 0)// positive positive=1; AXIS axisNr = (AXIS)(triangleAxis*2+positive); triangles[i].axis = axisNr; if( ! (ABS(Min[triangleAxis]-triangles[i].A[triangleAxis]) < 1.1 || ABS(Max[triangleAxis]-triangles[i].A[triangleAxis]) < 1.1) ) // not close to boundingbox edges? { triangles[i].axis = NOT_ALIGNED; // Not close to bounding box break; } area[axisNr] += triangles[i].area(); break; } } } AXIS down = NOT_ALIGNED; float LargestArea = 0; for(uint i=0;i<6;i++) { if(area[i] > LargestArea) { LargestArea = area[i]; down = (AXIS)i; } } switch(down) { case NEGX: RotateObject(Vector3f(0,-1,0), M_PI/2.0f); break; case POSX: RotateObject(Vector3f(0,1,0), M_PI/2.0f); break; case NEGY: RotateObject(Vector3f(1,0,0), M_PI/2.0f); break; case POSY: RotateObject(Vector3f(-1,0,0), M_PI/2.0f); break; case POSZ: RotateObject(Vector3f(1,0,0), M_PI); break; default: // unhandled break; } CenterAroundXY(); } void STL::Scale(float in_scale_factor) { for(size_t i = 0; i < triangles.size(); i++) { for(int j = 0; j < 3; j++) { /* Translate to origin */ triangles[i][j] = triangles[i][j] - Center; triangles[i][j].scale(in_scale_factor/scale_factor); triangles[i][j] = triangles[i][j] + Center; } } Min = Min - Center; Min.scale(in_scale_factor/scale_factor); Min = Min + Center; Max = Max - Center; Max.scale(in_scale_factor/scale_factor); Max = Max + Center; CenterAroundXY(); /* Save current scale_factor */ scale_factor = in_scale_factor; } // Rotate and adjust for the user - not a pure rotation by any means void STL::RotateObject(Vector3f axis, float angle) { Vector3f min,max; Vector3f oldmin,oldmax; min.x = min.y = min.z = oldmin.x = oldmin.y = oldmin.z = 99999999.0f; max.x = max.y = max.z = oldmax.x = oldmax.y = oldmax.z -99999999.0f; for (size_t i=0; i<triangles.size(); i++) { triangles[i].AccumulateMinMax (oldmin, oldmax); triangles[i].Normal = triangles[i].Normal.rotate(angle, axis.x, axis.y, axis.z); triangles[i].A = triangles[i].A.rotate(angle, axis.x, axis.y, axis.z); triangles[i].B = triangles[i].B.rotate(angle, axis.x, axis.y, axis.z); triangles[i].C = triangles[i].C.rotate(angle, axis.x, axis.y, axis.z); triangles[i].AccumulateMinMax (min, max); } Vector3f move(0, 0, 0); // if we rotated under the bed, translate us up again if (min.z < 0) { move.z = - min.z; // cout << "vector moveup: " << move << "\n"; } // ensure our x/y bbox is at the same offset from the bottom/left move.x = oldmin.x - min.x; move.y = oldmin.y - min.y; for (uint i = 0; i < triangles.size(); i++) triangles[i].Translate(move); max.x += move.x; min.x += move.x; max.y += move.y; min.y += move.y; max.z += move.z; min.z += move.z; Min = min; Max = max; // cout << "min " << Min << " max " << Max << "\n"; } Vector3f &Triangle::operator[] (const int index) { switch(index) { case 0: return A; case 1: return B; case 2: return C; } return A; } float Triangle::area() { return ( ((C-A).cross(B-A)).length() ); } Vector3f Triangle::GetMax() { Vector3f max(-99999999.0f, -99999999.0f, -99999999.0f); for (uint i = 0; i < 3; i++) { max[i] = MAX(max[i], A[i]); max[i] = MAX(max[i], B[i]); max[i] = MAX(max[i], C[i]); } return max; } Vector3f Triangle::GetMin() { Vector3f min(99999999.0f, 99999999.0f, 99999999.0f); for (uint i = 0; i < 3; i++) { min[i] = MIN(min[i], A[i]); min[i] = MIN(min[i], B[i]); min[i] = MIN(min[i], C[i]); } return min; } void Triangle::AccumulateMinMax(Vector3f &min, Vector3f &max) { Vector3f tmin = GetMin(); Vector3f tmax = GetMax(); for (uint i = 0; i < 3; i++) { min[i] = MIN(tmin[i], min[i]); max[i] = MAX(tmax[i], max[i]); } } void Triangle::Translate(const Vector3f &vector) { A += vector; B += vector; C += vector; } void CuttingPlane::CleanupPolygons (float Optimization) { float allowedError = Optimization; for (size_t p = 0; p < polygons.size(); p++) { for (size_t v = 0; v < polygons[p].points.size() + 1; ) { Vector2f p1 = vertices[polygons[p].points[(v-1+polygons[p].points.size())%polygons[p].points.size()]]; Vector2f p2 = vertices[polygons[p].points[v%polygons[p].points.size()]]; Vector2f p3 = vertices[polygons[p].points[(v+1)%polygons[p].points.size()]]; Vector2f v1 = (p2-p1); Vector2f v2 = (p3-p2); v1.normalize(); v2.normalize(); if ((v1-v2).lengthSquared() < allowedError) { polygons[p].points.erase(polygons[p].points.begin()+(v%polygons[p].points.size())); #if CUTTING_PLANE_DEBUG cout << "optimising out polygon " << p << "\n"; #endif } else v++; } } } void CuttingPlane::CleanupOffsetPolygons(float Optimization) { float allowedError = Optimization; for(size_t p=0;p<offsetPolygons.size();p++) { for(size_t v=0;v<offsetPolygons[p].points.size();) { Vector2f p1 =offsetVertices[offsetPolygons[p].points[(v-1+offsetPolygons[p].points.size())%offsetPolygons[p].points.size()]]; Vector2f p2 =offsetVertices[offsetPolygons[p].points[v]]; Vector2f p3 =offsetVertices[offsetPolygons[p].points[(v+1)%offsetPolygons[p].points.size()]]; Vector2f v1 = (p2-p1); Vector2f v2 = (p3-p2); v1.normalize(); v2.normalize(); if((v1-v2).lengthSquared() < allowedError) { offsetPolygons[p].points.erase(offsetPolygons[p].points.begin()+v); } else v++; } } } void STL::CenterAroundXY() { Vector3f displacement = -Min; for(size_t i=0; i<triangles.size() ; i++) { triangles[i].A = triangles[i].A + displacement; triangles[i].B = triangles[i].B + displacement; triangles[i].C = triangles[i].C + displacement; } Max += displacement; Min += displacement; // cout << "Center Around XY min" << Min << " max " << Max << "\n"; CalcCenter(); } void Poly::calcHole(vector<Vector2f> &offsetVertices) { if(points.size() == 0) return; // hole is undefined Vector2f p(-6000, -6000); int v=0; center = Vector2f(0,0); for(size_t vert=0;vert<points.size();vert++) { center += offsetVertices[points[vert]]; if(offsetVertices[points[vert]].x > p.x) { p = offsetVertices[points[vert]]; v=vert; } else if(offsetVertices[points[vert]].x == p.x && offsetVertices[points[vert]].y > p.y) { p.y = offsetVertices[points[vert]].y; v=vert; } } center /= points.size(); // we have the x-most vertex (with the highest y if there was a contest), v Vector2f V1 = offsetVertices[points[(v-1+points.size())%points.size()]]; Vector2f V2 = offsetVertices[points[v]]; Vector2f V3 = offsetVertices[points[(v+1)%points.size()]]; Vector2f Va=V2-V1; Vector2f Vb=V3-V1; hole = Va.cross(Vb) > 0; }
[ [ [ 1, 18 ] ], [ [ 19, 20 ], [ 28, 28 ], [ 60, 60 ], [ 99, 99 ], [ 321, 321 ], [ 327, 327 ], [ 352, 352 ], [ 356, 356 ], [ 376, 376 ], [ 422, 428 ], [ 518, 518 ], [ 520, 520 ], [ 522, 522 ], [ 542, 542 ], [ 547, 547 ], [ 589, 589 ], [ 591, 591 ], [ 593, 593 ], [ 595, 595 ], [ 608, 608 ], [ 628, 628 ], [ 630, 701 ], [ 706, 706 ], [ 711, 711 ], [ 720, 720 ], [ 724, 726 ], [ 728, 728 ], [ 733, 735 ], [ 739, 741 ], [ 746, 747 ], [ 751, 752 ], [ 758, 761 ], [ 765, 766 ], [ 770, 773 ], [ 777, 778 ], [ 783, 785 ], [ 789, 790 ], [ 799, 800 ], [ 804, 805 ], [ 810, 810 ], [ 814, 814 ], [ 816, 816 ], [ 821, 821 ], [ 824, 824 ], [ 832, 833 ], [ 836, 836 ], [ 838, 839 ], [ 844, 846 ], [ 850, 851 ], [ 857, 862 ], [ 868, 868 ], [ 874, 875 ], [ 881, 882 ], [ 924, 924 ], [ 930, 930 ], [ 933, 940 ], [ 949, 951 ], [ 958, 958 ], [ 963, 963 ], [ 965, 966 ], [ 970, 970 ], [ 981, 981 ], [ 1059, 1060 ], [ 1702, 1703 ], [ 1720, 1720 ], [ 1723, 1723 ], [ 1734, 1734 ], [ 1742, 1742 ], [ 1757, 1757 ], [ 1778, 1778 ], [ 1872, 1872 ], [ 1874, 1874 ], [ 1880, 1880 ], [ 1882, 1883 ], [ 2493, 2493 ], [ 2685, 2685 ], [ 2725, 2726 ], [ 2760, 2760 ], [ 2764, 2764 ], [ 2766, 2767 ], [ 2769, 2769 ], [ 2771, 2778 ], [ 2780, 2797 ], [ 2800, 2800 ], [ 2818, 2856 ], [ 2875, 2875 ], [ 2877, 2880 ], [ 2927, 2928 ] ], [ [ 21, 26 ], [ 29, 31 ], [ 33, 59 ], [ 61, 86 ], [ 88, 98 ], [ 100, 101 ], [ 170, 170 ], [ 301, 302 ], [ 307, 307 ], [ 319, 320 ], [ 322, 325 ], [ 328, 328 ], [ 330, 334 ], [ 336, 336 ], [ 338, 340 ], [ 345, 350 ], [ 354, 355 ], [ 360, 375 ], [ 378, 385 ], [ 387, 391 ], [ 393, 393 ], [ 396, 396 ], [ 398, 409 ], [ 411, 421 ], [ 429, 440 ], [ 442, 442 ], [ 444, 446 ], [ 449, 450 ], [ 452, 466 ], [ 468, 468 ], [ 470, 474 ], [ 476, 481 ], [ 483, 483 ], [ 486, 498 ], [ 500, 501 ], [ 503, 504 ], [ 506, 507 ], [ 509, 510 ], [ 512, 513 ], [ 515, 517 ], [ 519, 519 ], [ 521, 521 ], [ 523, 523 ], [ 525, 530 ], [ 532, 537 ], [ 539, 540 ], [ 543, 544 ], [ 548, 557 ], [ 559, 588 ], [ 590, 590 ], [ 594, 594 ], [ 596, 607 ], [ 609, 627 ], [ 629, 629 ], [ 702, 705 ], [ 707, 710 ], [ 712, 719 ], [ 721, 723 ], [ 727, 727 ], [ 729, 732 ], [ 736, 738 ], [ 742, 745 ], [ 748, 750 ], [ 753, 757 ], [ 762, 764 ], [ 767, 769 ], [ 774, 776 ], [ 779, 782 ], [ 786, 788 ], [ 791, 798 ], [ 801, 803 ], [ 806, 809 ], [ 811, 813 ], [ 815, 815 ], [ 817, 820 ], [ 822, 823 ], [ 825, 831 ], [ 834, 835 ], [ 837, 837 ], [ 840, 843 ], [ 847, 849 ], [ 852, 856 ], [ 863, 867 ], [ 869, 873 ], [ 876, 880 ], [ 883, 923 ], [ 925, 929 ], [ 931, 932 ], [ 941, 948 ], [ 952, 957 ], [ 959, 962 ], [ 964, 964 ], [ 967, 969 ], [ 971, 980 ], [ 982, 1058 ], [ 1061, 1701 ], [ 1704, 1719 ], [ 1721, 1722 ], [ 1724, 1733 ], [ 1735, 1741 ], [ 1743, 1756 ], [ 1758, 1777 ], [ 1779, 1871 ], [ 1873, 1873 ], [ 1875, 1879 ], [ 1881, 1881 ], [ 1884, 2492 ], [ 2494, 2684 ], [ 2686, 2724 ], [ 2727, 2730 ], [ 2761, 2763 ], [ 2765, 2765 ], [ 2768, 2768 ], [ 2770, 2770 ], [ 2779, 2779 ], [ 2798, 2799 ], [ 2801, 2802 ], [ 2813, 2817 ], [ 2857, 2874 ], [ 2876, 2876 ], [ 2881, 2926 ], [ 2929, 2964 ] ], [ [ 27, 27 ], [ 326, 326 ], [ 329, 329 ], [ 335, 335 ], [ 337, 337 ], [ 341, 344 ], [ 351, 351 ], [ 353, 353 ], [ 357, 359 ], [ 397, 397 ], [ 410, 410 ], [ 441, 441 ], [ 443, 443 ], [ 467, 467 ], [ 475, 475 ], [ 482, 482 ], [ 485, 485 ], [ 499, 499 ], [ 502, 502 ], [ 505, 505 ], [ 508, 508 ], [ 511, 511 ], [ 514, 514 ], [ 524, 524 ], [ 531, 531 ], [ 538, 538 ], [ 541, 541 ], [ 545, 546 ], [ 558, 558 ], [ 592, 592 ] ], [ [ 32, 32 ] ], [ [ 87, 87 ], [ 377, 377 ], [ 386, 386 ], [ 392, 392 ], [ 394, 395 ], [ 447, 448 ], [ 451, 451 ], [ 469, 469 ], [ 484, 484 ] ], [ [ 102, 169 ], [ 171, 300 ], [ 303, 306 ], [ 308, 318 ], [ 2731, 2759 ], [ 2803, 2812 ] ] ]
6d2333cb4456a3dd83dbf304bf8e6b66d45ef3e2
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/range/test/reversible_range.cpp
e902c5e5be1aae4a5f2bb039b92b3b1168649cc9
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
3,897
cpp
// Boost.Range library // // Copyright Thorsten Ottosen 2003-2004. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org/libs/range/ // #include <boost/detail/workaround.hpp> #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) # pragma warn -8091 // supress warning in Boost.Test # pragma warn -8057 // unused argument argc/argv in Boost.Test #endif #include <boost/range/rbegin.hpp> #include <boost/range/rend.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> #include <boost/test/test_tools.hpp> #include <vector> #include <algorithm> using namespace boost; using namespace std; void check_iterator() { typedef vector<char> vec_t; typedef vec_t::iterator iterator; typedef pair<iterator,iterator> pair_t; typedef range_reverse_iterator<pair_t>::type rev_iterator; typedef pair<rev_iterator,rev_iterator> rev_pair_t; vec_t vec; pair_t p = make_pair( vec.begin(), vec.end() ); rev_pair_t rp = make_pair( rbegin( p ), rend( p ) ); char* str = "mutable"; const char* cstr = "not mutable"; char a[] = "mutable"; const char ca[] = "not mutable"; wchar_t* wstr = L"mutable"; const wchar_t* cwstr= L"not mutable"; wchar_t wa[] = L"mutable"; const wchar_t cwa[]= L"not mutable"; BOOST_CHECK( rbegin( vec ) == range_reverse_iterator<vec_t>::type( vec.end() ) ); BOOST_CHECK( rend( vec ) == range_reverse_iterator<vec_t>::type( vec.begin() ) ); BOOST_CHECK( std::distance( rbegin( vec ), rend( vec ) ) == std::distance( begin( vec ), end( vec ) ) ); BOOST_CHECK( rbegin( p ) == begin( rp ) ); BOOST_CHECK( rend( p ) == end( rp ) ); BOOST_CHECK( std::distance( rbegin( p ), rend( p ) ) == std::distance( begin( rp ), end( rp ) ) ); BOOST_CHECK( std::distance( begin( p ), end( p ) ) == std::distance( rbegin( rp ), rend( rp ) ) ); BOOST_CHECK_EQUAL( &*begin( str ), &*( rend( str ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( str ) - 1 ), &*rbegin( str ) ); BOOST_CHECK_EQUAL( &*begin( cstr ), &*( rend( cstr ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( cstr ) - 1 ), &*rbegin( cstr ) ); BOOST_CHECK_EQUAL( &*begin( a ), &*( rend( a ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( a ) - 1 ), &*rbegin( a ) ); BOOST_CHECK_EQUAL( &*begin( ca ), &*( rend( ca ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( ca ) - 1 ), &*rbegin( ca ) ); BOOST_CHECK_EQUAL( &*begin( wstr ), &*( rend( wstr ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( wstr ) - 1 ), &*rbegin( wstr ) ); BOOST_CHECK_EQUAL( &*begin( cwstr ), &*( rend( cwstr ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( cwstr ) - 1 ), &*rbegin( cwstr ) ); BOOST_CHECK_EQUAL( &*begin( wa ), &*( rend( wa ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( wa ) - 1 ), &*rbegin( wa ) ); BOOST_CHECK_EQUAL( &*begin( cwa ), &*( rend( cwa ) - 1 ) ); BOOST_CHECK_EQUAL( &*( end( cwa ) - 1 ), &*rbegin( cwa ) ); } #include <boost/test/unit_test.hpp> using boost::unit_test::test_suite; test_suite* init_unit_test_suite( int argc, char* argv[] ) { test_suite* test = BOOST_TEST_SUITE( "Range Test Suite" ); test->add( BOOST_TEST_CASE( &check_iterator ) ); return test; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 102 ] ] ]
c221f105e574e6a30e540593f8584de10936406a
b22c254d7670522ec2caa61c998f8741b1da9388
/FinalClient/PhysXObjectHandlers.cpp
6adc9e57fc3e91f589ed5b3e5505685dc6f08fab
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
17,712
cpp
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #include "PhysXObjectHandlers.h" #include "NxPhysics.h" #include "NxCapsuleController.h" #include "PhysXEngine.h" #include "NxVec3.h" #include "ObjectsDescription.h" /*********************************************************** Constructor ***********************************************************/ PhysXObjectHandlerBase::PhysXObjectHandlerBase(boost::shared_ptr<PhysXEngine> Pengine, boost::shared_ptr<ActorUserData> UserData) : _Pengine(Pengine), _UserData(UserData) {} /*********************************************************** Constructor ***********************************************************/ PhysXActorHandler::PhysXActorHandler(boost::shared_ptr<PhysXEngine> Pengine, boost::shared_ptr<ActorUserData> UserData, NxActor* Actor, boost::shared_ptr<SimpleRotationHandler> rotH) : PhysXObjectHandlerBase(Pengine, UserData), _Actor(Actor), _rotH(rotH) {} /*********************************************************** get object position in the world ***********************************************************/ void PhysXActorHandler::GetPosition(float &X, float &Y, float &Z) { if(!_Actor) return; NxVec3 vec = _Actor->getGlobalPosition(); X = vec.x; Y = vec.y; Z = vec.z; } /*********************************************************** get object rotation on all axis ***********************************************************/ void PhysXActorHandler::GetRotation(LbaQuaternion& Q) { _rotH->GetRotation(Q); } /*********************************************************** set object position in the world ***********************************************************/ void PhysXActorHandler::SetPosition(float X, float Y, float Z) { if(!_Actor) return; _Actor->setGlobalPosition(NxVec3(X, Y, Z)); _resetted = true; } /*********************************************************** set object rotation on all axis ***********************************************************/ void PhysXActorHandler::SetRotation(const LbaQuaternion& Q) { _rotH->SetRotation(Q); _resetted = true; } /*********************************************************** move object in the world ***********************************************************/ void PhysXActorHandler::Move(float deltaX, float deltaY, float deltaZ) { float currPosX, currPosY, currPosZ; GetPosition(currPosX, currPosY, currPosZ); MoveTo(currPosX+deltaX, currPosY+deltaY, currPosZ+deltaZ); } /*********************************************************** move object to a position in the world ***********************************************************/ void PhysXActorHandler::MoveTo(float X, float Y, float Z) { if(!_Actor) return; _Actor->moveGlobalPosition(NxVec3(X, Y, Z)); } /*********************************************************** rotate object in the world ***********************************************************/ void PhysXActorHandler::RotateTo(const LbaQuaternion& Q) { _rotH->RotateTo(Q); } /*********************************************************** rotate object in the world ***********************************************************/ void PhysXActorHandler::Destroy() { _Pengine->DestroyActor(_Actor); } /*********************************************************** Constructor ***********************************************************/ PhysXDynamicActorHandler::PhysXDynamicActorHandler(boost::shared_ptr<PhysXEngine> Pengine, boost::shared_ptr<ActorUserData> UserData, NxActor* Actor, const LbaQuaternion& rotation) : PhysXObjectHandlerBase(Pengine, UserData), _Actor(Actor) { SetRotation(rotation); } /*********************************************************** get object position in the world ***********************************************************/ void PhysXDynamicActorHandler::GetPosition(float &X, float &Y, float &Z) { if(!_Actor) return; NxVec3 vec = _Actor->getGlobalPosition(); X = vec.x; Y = vec.y; Z = vec.z; } /*********************************************************** get object rotation on all axis ***********************************************************/ void PhysXDynamicActorHandler::GetRotation(LbaQuaternion& Q) { if(!_Actor) return; NxQuat quat = _Actor->getGlobalOrientationQuat(); Q.X = quat.x; Q.Y = quat.y; Q.Z = quat.z; Q.W = quat.w; } /*********************************************************** set object position in the world ***********************************************************/ void PhysXDynamicActorHandler::SetPosition(float X, float Y, float Z) { if(!_Actor) return; _Actor->setGlobalPosition(NxVec3(X, Y, Z)); _resetted = true; } /*********************************************************** set object rotation on all axis ***********************************************************/ void PhysXDynamicActorHandler::SetRotation(const LbaQuaternion& Q) { if(!_Actor) return; _Actor->setGlobalOrientationQuat(NxQuat(NxVec3(Q.X, Q.Y, Q.Z), Q.W)); _resetted = true; } /*********************************************************** move object in the world ***********************************************************/ void PhysXDynamicActorHandler::Move(float deltaX, float deltaY, float deltaZ) { float currPosX, currPosY, currPosZ; GetPosition(currPosX, currPosY, currPosZ); MoveTo(currPosX+deltaX, currPosY+deltaY, currPosZ+deltaZ); } /*********************************************************** move object to a position in the world ***********************************************************/ void PhysXDynamicActorHandler::MoveTo(float X, float Y, float Z) { if(!_Actor) return; _Actor->moveGlobalPosition(NxVec3(X, Y, Z)); } /*********************************************************** rotate object in the world ***********************************************************/ void PhysXDynamicActorHandler::RotateTo(const LbaQuaternion& Q) { if(!_Actor) return; _Actor->moveGlobalOrientationQuat(NxQuat(NxVec3(Q.X, Q.Y, Q.Z), Q.W)); } /*********************************************************** rotate object in the world ***********************************************************/ void PhysXDynamicActorHandler::Destroy() { _Pengine->DestroyActor(_Actor); } /*********************************************************** Constructor ***********************************************************/ PhysXControllerHandler::PhysXControllerHandler(boost::shared_ptr<PhysXEngine> Pengine, boost::shared_ptr<ActorUserData> UserData, NxController* Controller, boost::shared_ptr<SimpleRotationHandler> rotH) : PhysXObjectHandlerBase(Pengine, UserData), _Controller(Controller), _rotH(rotH) {} /*********************************************************** get object position in the world ***********************************************************/ void PhysXControllerHandler::GetPosition(float &X, float &Y, float &Z) { if(!_Controller) return; NxExtendedVec3 vec = _Controller->getPosition(); X = (float)vec.x; Y = (float)vec.y; Z = (float)vec.z; } /*********************************************************** get object rotation on all axis ***********************************************************/ void PhysXControllerHandler::GetRotation(LbaQuaternion& Q) { _rotH->GetRotation(Q); } /*********************************************************** set object position in the world ***********************************************************/ void PhysXControllerHandler::SetPosition(float X, float Y, float Z) { if(!_Controller) return; NxExtendedVec3 pos; pos.x = X; pos.y = Y; pos.z = Z; _Controller->setPosition(pos); _resetted = true; } /*********************************************************** set object rotation on all axis ***********************************************************/ void PhysXControllerHandler::SetRotation(const LbaQuaternion& Q) { _rotH->SetRotation(Q); _resetted = true; } /*********************************************************** move object in the world ***********************************************************/ void PhysXControllerHandler::Move(float deltaX, float deltaY, float deltaZ) { if(!_Controller) return; unsigned int CollisionFlag = _Pengine->MoveCharacter(_Controller, NxVec3(deltaX, deltaY, deltaZ), true); _UserData->CollisionUpFlag = (CollisionFlag == NXCC_COLLISION_UP); _UserData->CollisionDownFlag = (CollisionFlag == NXCC_COLLISION_DOWN); _UserData->CollisionSideFlag = (CollisionFlag == NXCC_COLLISION_SIDES); } /*********************************************************** move object to a position in the world ***********************************************************/ void PhysXControllerHandler::MoveTo(float X, float Y, float Z) { SetPosition(X, Y, Z); } /*********************************************************** rotate object in the world ***********************************************************/ void PhysXControllerHandler::RotateTo(const LbaQuaternion& Q) { _rotH->RotateTo(Q); } /*********************************************************** rotate object in the world ***********************************************************/ void PhysXControllerHandler::Destroy() { _Pengine->DestroyCharacter(_Controller); } /*********************************************************** Constructor ***********************************************************/ PhysicalDescriptionBox::PhysicalDescriptionBox(float posX, float posY, float posZ, int Otype, float Odensity, const LbaQuaternion &rot, float sX, float sY, float sZ) :PhysicalDescriptionWithShape(posX, posY, posZ, Otype, Odensity, rot), sizeX(sX), sizeY(sY), sizeZ(sZ) { } /*********************************************************** destructor ***********************************************************/ PhysicalDescriptionBox::~PhysicalDescriptionBox() { } /*********************************************************** build description into a reald physic object ***********************************************************/ boost::shared_ptr<PhysicalObjectHandlerBase> PhysicalDescriptionBox::BuildSelf( boost::shared_ptr<PhysXEngine> _PEngine) const { boost::shared_ptr<ActorUserData> udata = boost::shared_ptr<ActorUserData>(new ActorUserData()); if(type != 4) { NxActor* act = _PEngine->CreateBox(NxVec3(positionX, positionY, positionZ), sizeX, sizeY, sizeZ, density, type, udata.get()); if(type != 3) { return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXActorHandler(_PEngine, udata, act, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); } else { return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXDynamicActorHandler(_PEngine, udata, act, rotation)); } } else { NxController* controller = _PEngine->CreateCharacterBox(NxVec3(positionX, positionY, positionZ), NxVec3(sizeX, sizeY, sizeZ), udata.get()); return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXControllerHandler(_PEngine, udata, controller, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); } } /*********************************************************** Constructor ***********************************************************/ PhysicalDescriptionCapsule::PhysicalDescriptionCapsule(float posX, float posY, float posZ, int Otype, float Odensity, const LbaQuaternion &rot, float rad, float ht) :PhysicalDescriptionWithShape(posX, posY, posZ, Otype, Odensity, rot), radius(rad), height(ht) { } /*********************************************************** destructor ***********************************************************/ PhysicalDescriptionCapsule::~PhysicalDescriptionCapsule() { } /*********************************************************** build description into a reald physic object ***********************************************************/ boost::shared_ptr<PhysicalObjectHandlerBase> PhysicalDescriptionCapsule::BuildSelf( boost::shared_ptr<PhysXEngine> _PEngine) const { boost::shared_ptr<ActorUserData> udata = boost::shared_ptr<ActorUserData>(new ActorUserData()); if(type != 4) { NxActor* act = _PEngine->CreateCapsule(NxVec3(positionX, positionY, positionZ), radius, height, density, type, udata.get()); if(type != 3) { return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXActorHandler(_PEngine, udata, act, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); } else { return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXDynamicActorHandler(_PEngine, udata, act, rotation)); } } else { NxController* controller = _PEngine->CreateCharacter(NxVec3(positionX, positionY, positionZ), radius, height, udata.get()); return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXControllerHandler(_PEngine, udata, controller, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); } } /*********************************************************** Constructor ***********************************************************/ PhysicalDescriptionSphere::PhysicalDescriptionSphere(float posX, float posY, float posZ, int Otype, float Odensity, const LbaQuaternion &rot, float rad) :PhysicalDescriptionWithShape(posX, posY, posZ, Otype, Odensity, rot), radius(rad) { } /*********************************************************** destructor ***********************************************************/ PhysicalDescriptionSphere::~PhysicalDescriptionSphere() { } /*********************************************************** build description into a reald physic object ***********************************************************/ boost::shared_ptr<PhysicalObjectHandlerBase> PhysicalDescriptionSphere::BuildSelf( boost::shared_ptr<PhysXEngine> _PEngine) const { boost::shared_ptr<ActorUserData> udata = boost::shared_ptr<ActorUserData>(new ActorUserData()); if(type != 4) { NxActor* act = _PEngine->CreateSphere(NxVec3(positionX, positionY, positionZ), radius, density, type, udata.get()); if(type != 3) { return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXActorHandler(_PEngine, udata, act, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); } else { return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXDynamicActorHandler(_PEngine, udata, act, rotation)); } } else { NxController* controller = _PEngine->CreateCharacter(NxVec3(positionX, positionY, positionZ), radius, 0, udata.get()); return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXControllerHandler(_PEngine, udata, controller, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); } } /*********************************************************** Constructor ***********************************************************/ PhysicalDescriptionTriangleMesh::PhysicalDescriptionTriangleMesh(float posX, float posY, float posZ, const std::string &FileName) :PhysicalDescriptionWithShape(posX, posY, posZ, 1, 0, LbaQuaternion()), MeshInfoDataFileName(FileName) { } /*********************************************************** destructor ***********************************************************/ PhysicalDescriptionTriangleMesh::~PhysicalDescriptionTriangleMesh() { } /*********************************************************** build description into a reald physic object ***********************************************************/ boost::shared_ptr<PhysicalObjectHandlerBase> PhysicalDescriptionTriangleMesh::BuildSelf( boost::shared_ptr<PhysXEngine> _PEngine) const { boost::shared_ptr<ActorUserData> udata = boost::shared_ptr<ActorUserData>(new ActorUserData()); NxActor* actor = _PEngine->LoadTriangleMeshFile(NxVec3(positionX, positionY, positionZ), MeshInfoDataFileName, udata); return boost::shared_ptr<PhysicalObjectHandlerBase>(new PhysXActorHandler(_PEngine, udata, actor, boost::shared_ptr<SimpleRotationHandler>(new SimpleRotationHandler(rotation)))); }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 538 ] ] ]
42a3a0060357edfe5b8c78a987da8c8c5584ae76
1724fb22a0b715c4597c5056ce571f0fbdb1cc46
/tools/sty2tex/tilewrite.cpp
bffa969e29571b44d2e73447d9d60f7c2638b28e
[]
no_license
basecq/OpenGTA2
71127e333b7b6c6a60388ad8b4fb5c4408aa5bdd
2266c354a638397b84ca4766c69e3a50f4e367de
refs/heads/master
2020-04-06T05:25:34.926813
2010-01-27T02:35:09
2010-01-27T02:35:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,638
cpp
#include "sty2tex.h" void write_tile_bmp(int tileid) { unsigned int vpallete = pallete_index[tileid]; //Write image... for (int y=63;y>=0;y--) { for (int x=0;x<64;x++) { unsigned int tilecolor = tile_data[(y+(tileid / 4)*64)*256+(x+(tileid % 4)*64)]; unsigned int palid = (vpallete/64)*256*64+(vpallete % 64)+tilecolor*64; unsigned int finalcolor = (pallete[palid]) & 0xFFFFFF; fwrite(&finalcolor,3,1,bmp); } } //Write 8-bit alpha... for (int y=63;y>=0;y--) { for (int x=0;x<64;x++) { unsigned int tilecolor = tile_data[(y+(tileid / 4)*64)*256+(x+(tileid % 4)*64)]; unsigned int finalcolor = 0xFF - (tilecolor > 0) * 0xFF; fwrite(&finalcolor,1,1,bmp); } } } void copy_tile(int tileid) { unsigned int vpallete = pallete_index[/*palletebase.tile + */tileid]; //Write image... for (int y=0;y<64;y++) { for (int x=0;x<64;x++) { unsigned int tilecolor = tile_data[(y+(tileid / 4)*64)*256+(x+(tileid % 4)*64)]; unsigned int palid = (vpallete/64)*256*64+(vpallete % 64)+tilecolor*64; unsigned int finalcolor = (pallete[palid]) & 0xFFFFFF; unsigned int alphacolor = (/*0xFF - */(tilecolor > 0) * 0xFF) << 24; //unsigned int finalcolor = alphacolor >> 24; sprite_buffer[x+y*64] = finalcolor+alphacolor; } } } void save_tile(char* filename, int tileid) { bmp = fopen(filename,"wb+"); unsigned char bmpHeader[54] = { 0x42, 0x4D, 0x36, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; fwrite(&bmpHeader,1,54,bmp); write_tile_bmp(tileid); fclose(bmp); } //============================================================================= static void write_sprite_bmp(int spriteid) { unsigned int vpallete = pallete_index[palletebase.tile + spriteid]; int sprh = sprite_entries[spriteid].h; int sprw = sprite_entries[spriteid].w; int basex = (sprite_entries[spriteid].ptr % 256); int basey = (sprite_entries[spriteid].ptr / 256); int base = (sprite_entries[spriteid].ptr - basex - basey*256); //Write sprite for (int y=sprh-1;y>=0;y--) { for (int x=0;x<sprw;x++) { unsigned int spritecolor = spritedata[base+((basex+x)+(basey+y)*256)]; unsigned int palid = (vpallete/64)*256*64+(vpallete % 64)+spritecolor*64; unsigned int finalcolor = (pallete[palid]) & 0xFFFFFF; fwrite(&finalcolor,3,1,bmp); } int t = sprw*3; while (t % 4 != 0) { int temp = 0; fwrite(&temp,1,1,bmp); t++; } } //Write 8-bit alpha... for (int y=sprh-1;y>=0;y--) { for (int x=0;x<sprw;x++) { unsigned int spritecolor = spritedata[sprite_entries[spriteid].ptr+x+y*256]; unsigned int finalcolor = 0xFF - (spritecolor > 0) * 0xFF; fwrite(&finalcolor,1,1,bmp); } } } void copy_sprite(int spriteid) { unsigned int vpallete = pallete_index[palletebase.tile + sprite_entries[spriteid].pad]; int sprh = sprite_entries[spriteid].h; int sprw = sprite_entries[spriteid].w; int basex = (sprite_entries[spriteid].ptr % 256); int basey = (sprite_entries[spriteid].ptr / 256); int base = (sprite_entries[spriteid].ptr - basex - basey*256); //Write sprite for (int y=0;y<sprh;y++) { for (int x=0;x<sprw;x++) { unsigned int spritecolor = spritedata[base+((basex+x)+(basey+y)*256)]; unsigned int palid = (vpallete/64)*256*64+(vpallete % 64)+spritecolor*64; unsigned int finalcolor = (pallete[palid]) & 0xFFFFFF; unsigned int alphacolor = (/*0xFF - */(spritecolor > 0) * 0xFF) << 24; //fwrite(&finalcolor,3,1,bmp); sprite_buffer[x+y*sprw] = finalcolor+alphacolor; } } } void save_sprite(char* filename, int spriteid) { bmp = fopen(filename,"wb+"); unsigned char bmpHeader[54] = { 0x42, 0x4D, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; fwrite(&bmpHeader,1,54,bmp); write_sprite_bmp(spriteid); int size = ftell(bmp); fseek(bmp,3,0); fwrite(&size,4,1,bmp); fseek(bmp,18,0); fwrite(&sprite_entries[spriteid].w,1,1,bmp); fseek(bmp,22,0); fwrite(&sprite_entries[spriteid].h,1,1,bmp); fclose(bmp); }
[ [ [ 1, 145 ] ] ]
30e5a5ce7f0e5418f334b8f9fa9f57c60521474f
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/synccam/camSyncClient.h
5392b3faa94671a2678d514311c1f1b4c6fd8f1c
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#pragma once #include "..\network\udp_connection.h" #include "..\utility\fastdelegate.h" #define CAMSYNC_BROADCAST_IP "232.132.1.8" #define CAMSYNC_BROADCAST_PORT 30008 #ifdef __cplusplus_cli #pragma managed(push,off) #endif #pragma pack (1) struct SyncCamPacket { unsigned short seconds; unsigned long ticks; unsigned long seqNum; unsigned char id; }; #pragma pack () class CamSyncReceiver; typedef FastDelegate3<SyncCamPacket, CamSyncReceiver*, void*> CamSync_Msg_handler; using namespace std; class CamSyncReceiver { private: udp_connection *conn; void UDPCallback(udp_message& msg, udp_connection* conn, void* arg); CamSync_Msg_handler cbk; void* cbk_arg; public: CamSyncReceiver(void); ~CamSyncReceiver(void); void SetCallback(CamSync_Msg_handler handler, void* arg); int sequenceNumber; int packetCount; int dropCount; };
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 45 ] ] ]
1f3fe3517820b40f58f6bd4750f23a9a310b4e92
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Game/BioGame/include/EnemyManager.h
dab7ec495f015af0a9031c84c0867cd613ad3dad
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
510
h
#pragma once #include <XML/XMLTreeNode.h> #include "EnemyResource.h" #include "EnemyInstance.h" #include <string> #include <vector> using namespace std; typedef vector<CEnemyResource> VectorEnemyResource; typedef vector<CEnemyInstance> VectorEnemyInstance; class CEnemyManager { public: CEnemyManager(void); virtual ~CEnemyManager(void); void Init(const string& _szPath); void Release(); private: VectorEnemyResource m_vResources; VectorEnemyInstance m_vEnemies; };
[ [ [ 1, 29 ] ] ]
318b000fa5a614fbc7d091007f0e735e82fdb50d
3f6437b0deb731e795642e71ea219b911e6af3cc
/fogDialog.cpp
69be4ce90f9faa682fe94ef30da8bdb6d16bf4e1
[]
no_license
tzafrir/graphics1
b910f554108235f595b7d3db1407c284afc5a66f
0bde27d56ad4b36c5b5b355d919e18e0367a4e0d
refs/heads/master
2016-09-10T21:37:58.249424
2011-01-03T19:35:18
2011-01-03T19:35:18
1,098,744
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
cpp
// fogDialog.cpp : implementation file // #include "stdafx.h" #include "OpenGL.h" #include "fogDialog.h" // fogDialog dialog IMPLEMENT_DYNAMIC(fogDialog, CDialog) fogDialog::fogDialog( double valDens, double valColR , double valColG , double valColB , double valColA , double valStart , double valEnd , int valMode , int valQuality , CWnd* pParent/*=NULL*/) : CDialog(fogDialog::IDD, pParent), density(valDens),red(valColR),green(valColG),blue(valColB), alpha(valColA*100), start(valStart), end(valEnd),mode(valMode), quality(valQuality) { } fogDialog::~fogDialog() { } void fogDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_START, start); DDX_Text(pDX, IDC_EDIT_END, end); DDX_Slider(pDX, IDC_SLIDER_DENS , density); DDX_Slider(pDX, IDC_SLIDER_ALPHA , alpha); DDX_CBIndex(pDX, IDC_COMBO_QUALITY, quality); DDX_CBIndex(pDX, IDC_COMBO_MODE, mode); } BEGIN_MESSAGE_MAP(fogDialog, CDialog) ON_BN_CLICKED(IDOK, &fogDialog::OnBnClickedOk) END_MESSAGE_MAP() void fogDialog::OnBnClickedOk() { OnOK(); }
[ [ [ 1, 48 ] ] ]
072f3ae6506149d52e2b5c3e1ea54b8b638d3f81
dc9d65f711d3507da390eefb57c7519c97e81c64
/plugins/filetransfer/ftprogressdialog.h
3f5bf8ac1847350d1b03ea5642e5a5974092a2fb
[]
no_license
xjohncz/saje
40cd6d3a11b07c7e4b0f205762aacbe7528e4906
7c8a6c1cfab57feacc2dd657c70380b38330e3ef
refs/heads/master
2021-01-20T08:46:49.601271
2011-04-20T03:18:10
2011-04-20T03:18:10
35,888,997
0
0
null
null
null
null
UTF-8
C++
false
false
924
h
#ifndef FTPROGRESSDIALOG_H #define FTPROGRESSDIALOG_H #include <QtGui/QDialog> #include <contact_info_i.h> #include "ftid.h" namespace Ui { class FTProgressDialog; } class FTProgressDialog : public QDialog { Q_OBJECT Q_DISABLE_COPY(FTProgressDialog) public: typedef enum {ST_ACCEPTED, ST_CANCELLED, ST_INPROGRESS, ST_COMPLETED} State; explicit FTProgressDialog(const FTId &ftid, const QString &filename, int bytes, QWidget *parent = 0); virtual ~FTProgressDialog(); void setState(State s); State getState() {return state;} void setProgress(int prog); bool getIncoming() {return ftid.incoming;} signals: void cancelled(const FTId &ftid); protected: virtual void changeEvent(QEvent *e); private: Ui::FTProgressDialog *m_ui; FTId ftid; int sizeBytes; State state; private slots: void on_btnDone_clicked(); }; #endif // FTPROGRESSDIALOG_H
[ "sje397@200c22c1-0253-0410-a7cc-2773c7d12e9d" ]
[ [ [ 1, 43 ] ] ]
e25117e201e0e80ded214c14f4edbc914ec1cebe
00fdb9c8335382401ee0a8c06ad6ebdcaa136b40
/ARM9/source/component.cpp
20c92b1e54e2e11a375c3799f2179519ff5470ee
[]
no_license
Mbmax/ismart-kernel
d82633ba0864f9f697c3faa4ebc093a51b8463b2
f80d8d7156897d019eb4e16ef9cec8a431d15ed3
refs/heads/master
2016-09-06T13:28:25.260481
2011-03-29T10:31:04
2011-03-29T10:31:04
35,029,299
1
2
null
null
null
null
UTF-8
C++
false
false
9,504
cpp
#pragma Ospace #include <NDS.h> #include "_const.h" #include "_console.h" #include "maindef.h" #include "memtool.h" #include "shell.h" #include "lang.h" #include "component.h" #include "skin.h" #include "strtool.h" // --------------------- static CglFont *pDefaultFont; void Component_SetFont(CglFont *pFont) { pDefaultFont=pFont; } // --------------------- void ComponentLabel_Init(TComponentLabel *pComponentLabel,CglCanvas *pCanvas) { TComponentLabel *pcl=pComponentLabel; pcl->CallBack_Click=NULL; pcl->pCanvas=pCanvas; pcl->Rect=CreateRect(0,0,0,0); pcl->Visible=true; pcl->Center=false; pcl->isTitle=false; pcl->TextColor=0; pcl->pMsgUTF8=""; static UnicodeChar ucs[1]={0}; pcl->pMsgUnicode=ucs; } void ComponentLabel_Draw(TComponentLabel *pComponentLabel) { TComponentLabel *pcl=pComponentLabel; if(pcl->Visible==false) return; pcl->pCanvas->SetCglFont(pDefaultFont); if(pcl->TextColor!=0){ pcl->pCanvas->SetFontTextColor(pcl->TextColor); }else{ if(pcl->isTitle==false){ pcl->pCanvas->SetFontTextColor(ColorTable.Component.Label_Text); }else{ pcl->pCanvas->SetFontTextColor(ColorTable.Component.TitleLabel_Text); } } const char *pmsgUTF8=pcl->pMsgUTF8; u32 TextWidth=pcl->pCanvas->GetTextWidthUTF8(pmsgUTF8); u32 TextHeight=glCanvasTextHeight; if(pcl->Rect.w==0) pcl->Rect.w=TextWidth; if(pcl->Rect.h==0) pcl->Rect.h=TextHeight; TRect r=pcl->Rect; // pcl->pCanvas->SetColor(pcl->BGColor); // pcl->pCanvas->FillBox(r.x,r.y,r.w,r.h); if(pmsgUTF8[0]!=0){ if(pcl->Center==false){ pcl->pCanvas->TextOutUTF8(r.x,r.y,pmsgUTF8); }else{ pcl->pCanvas->TextOutUTF8(r.x+((r.w-TextWidth)/2),r.y,pmsgUTF8); } } if(pcl->pMsgUnicode[0]!=0) pcl->pCanvas->TextOutW(r.x,r.y,pcl->pMsgUnicode); } s32 ComponentLabel_GetWidth(TComponentLabel *pComponentLabel) { TComponentLabel *pcl=pComponentLabel; if(pcl->Visible==false) return(0); pcl->pCanvas->SetCglFont(pDefaultFont); pcl->pCanvas->SetFontTextColor(ColorTable.Component.Label_Text); const char *pmsgUTF8=pcl->pMsgUTF8; u32 TextWidth=pcl->pCanvas->GetTextWidthUTF8(pmsgUTF8); if(pcl->Rect.w==0) pcl->Rect.w=TextWidth; TRect r=pcl->Rect; s32 w=0; if(pmsgUTF8[0]!=0){ if(pcl->Center==false){ w=pcl->pCanvas->GetTextWidthUTF8(pmsgUTF8); }else{ w=r.w; } } if(pcl->pMsgUnicode[0]!=0) w=pcl->pCanvas->GetTextWidthW(pcl->pMsgUnicode); return(w+2); } s32 ComponentLabel_GetIndexFromPos(TComponentLabel *pComponentLabel,s32 mx,s32 my) { TComponentLabel *pcl=pComponentLabel; TRect r=pcl->Rect; if(pcl->Visible==false) return(-1); mx-=r.x; my-=r.y; if((0<=mx)&&(mx<r.w)){ if((0<=my)&&(my<r.h)){ return(0); } } return(-1); } bool ComponentLabel_MouseUp(TComponentLabel *pComponentLabel,s32 mx,s32 my) { TComponentLabel *pcl=pComponentLabel; if(pcl->Visible==false) return(false); if(ComponentLabel_GetIndexFromPos(pcl,mx,my)==-1) return(false); if(pcl->CallBack_Click!=NULL) pcl->CallBack_Click(pcl); return(true); } // ------------------ void ComponentCheck_Init(TComponentCheck *pComponentCheck,CglCanvas *pCanvas) { TComponentCheck *pcc=pComponentCheck; pcc->CallBack_Click=NULL; pcc->UserData=0; pcc->pCanvas=pCanvas; pcc->pOnIcon=NULL; pcc->pOffIcon=NULL; pcc->Checked=false; pcc->Rect=CreateRect(0,0,0,0); pcc->Visible=true; pcc->pMsgUTF8=""; pcc->TextColor=ColorTable.Component.Check_Text; } void ComponentCheck_Draw(TComponentCheck *pComponentCheck) { TComponentCheck *pcc=pComponentCheck; if(pcc->Visible==false) return; if(pcc->pOnIcon!=NULL){ if(pcc->Rect.w==0) pcc->Rect.w=pcc->pOnIcon->GetWidth(); if(pcc->Rect.h==0) pcc->Rect.h=pcc->pOnIcon->GetHeight(); } TRect r=pcc->Rect; CglTGF *pSrcTGF=NULL; if(pcc->Checked==true){ pSrcTGF=pcc->pOnIcon; }else{ pSrcTGF=pcc->pOffIcon; } if(pSrcTGF!=NULL){ s32 x=r.x; s32 y=r.y; s32 w=pSrcTGF->GetWidth(); s32 h=pSrcTGF->GetHeight(); x+=(r.w-w+0)/2; y+=(r.h-h+1)/2; pSrcTGF->BitBlt(pcc->pCanvas,x,y); } pcc->pCanvas->SetCglFont(pDefaultFont); pcc->pCanvas->SetFontTextColor(pcc->TextColor); const char *pmsgUTF8=pcc->pMsgUTF8; u32 TextX=r.x+r.w+2; u32 TextY=r.y; // u32 TextWidth=pcc->pCanvas->GetTextWidthUTF8(pmsgUTF8); u32 TextHeight=glCanvasTextHeight; TextY+=(r.h-TextHeight+1)/2; // pcc->pCanvas->SetColor(RGB15(0,0,0)|BIT15); // pcc->pCanvas->FillBox(TextX,TextY,64,TextHeight); pcc->pCanvas->TextOutUTF8(TextX,TextY,pmsgUTF8); } s32 ComponentCheck_GetWidth(TComponentCheck *pComponentCheck) { TComponentCheck *pcc=pComponentCheck; if(pcc->Visible==false) return(0); if(pcc->pOnIcon!=NULL){ if(pcc->Rect.w==0) pcc->Rect.w=pcc->pOnIcon->GetWidth(); } TRect r=pcc->Rect; pcc->pCanvas->SetCglFont(pDefaultFont); const char *pmsgUTF8=pcc->pMsgUTF8; return(r.w+2+pcc->pCanvas->GetTextWidthUTF8(pmsgUTF8)+2); } static bool ComponentCheck_GetIndexFromPos(TComponentCheck *pComponentCheck,s32 mx,s32 my) { TComponentCheck *pcc=pComponentCheck; TRect r=pcc->Rect; if(pcc->Visible==false) return(false); pcc->pCanvas->SetCglFont(pDefaultFont); const char *pmsgUTF8=pcc->pMsgUTF8; s32 TextWidth; if(str_isEmpty(pcc->pMsgUTF8)==true){ TextWidth=ScreenWidth; }else{ TextWidth=r.w+2+pcc->pCanvas->GetTextWidthUTF8(pmsgUTF8); } mx-=r.x; my-=r.y; if((0<=mx)&&(mx<TextWidth)){ if((0<=my)&&(my<r.h)){ return(true); } } return(false); } bool ComponentCheck_MouseUp(TComponentCheck *pComponentCheck,s32 mx,s32 my) { TComponentCheck *pcc=pComponentCheck; if(pcc->Visible==false) return(false); if(ComponentCheck_GetIndexFromPos(pcc,mx,my)==false) return(false); if(pcc->CallBack_Click!=NULL) pcc->CallBack_Click(pcc); return(true); } // ------------------ void ComponentButton_Init(TComponentButton *pComponentButton,CglCanvas *pCanvas) { TComponentButton *pcb=pComponentButton; pcb->CallBack_Click=NULL; pcb->pCanvas=pCanvas; pcb->pIcon=NULL; pcb->DrawFrame=true; pcb->Pressing=false; pcb->Rect=CreateRect(0,0,0,0); pcb->pMsgUTF8=""; pcb->Visible=true; pcb->NormalTextColor=ColorTable.Component.Button_NormalText; pcb->PressTextColor=ColorTable.Component.Button_PressText; } void ComponentButton_Draw(TComponentButton *pComponentButton) { TComponentButton *pcb=pComponentButton; if(pcb->Visible==false) return; if(pcb->DrawFrame==true){ if(pcb->Pressing==false){ TRect r=pcb->Rect; pcb->pCanvas->SetColor(ColorTable.Component.Button_NormalHighlight); pcb->pCanvas->DrawBox(r.x-1,r.y-1,r.w+2,r.h+2); pcb->pCanvas->SetColor(ColorTable.Component.Button_NormalShadow); pcb->pCanvas->DrawBox(r.x,r.y,r.w+1,r.h+1); pcb->pCanvas->SetColor(ColorTable.Component.Button_NormalBG); pcb->pCanvas->FillBox(r.x,r.y,r.w,r.h); }else{ TRect r=pcb->Rect; pcb->pCanvas->SetColor(ColorTable.Component.Button_PressHighlight); pcb->pCanvas->DrawBox(r.x-1,r.y-1,r.w+2,r.h+2); pcb->pCanvas->SetColor(ColorTable.Component.Button_PressShadow); pcb->pCanvas->DrawBox(r.x,r.y,r.w+1,r.h+1); pcb->pCanvas->SetColor(ColorTable.Component.Button_PressBG); pcb->pCanvas->FillBox(r.x,r.y,r.w,r.h); } } pcb->pCanvas->SetCglFont(pDefaultFont); if(pcb->Pressing==false){ pcb->pCanvas->SetFontTextColor(pcb->NormalTextColor); }else{ pcb->pCanvas->SetFontTextColor(pcb->PressTextColor); } const char *pmsgUTF8=pcb->pMsgUTF8; TRect r=pcb->Rect; s32 IconWidth; s32 IconHeight; if(pcb->pIcon==NULL){ IconWidth=-8; IconHeight=0; }else{ IconWidth=pcb->pIcon->GetWidth(); IconHeight=pcb->pIcon->GetHeight(); } s32 TextWidth=pcb->pCanvas->GetTextWidthUTF8(pmsgUTF8); s32 TextHeight=glCanvasTextHeight; s32 BodyWidth=IconWidth; if(TextWidth!=0) BodyWidth+=8+TextWidth; s32 BodyHeight=IconHeight; if(IconHeight<TextHeight) BodyHeight=TextHeight; s32 BodyX=r.x+((r.w-BodyWidth)/2); s32 BodyY=r.y+((r.h-BodyHeight)/2); if(pcb->pIcon!=NULL){ s32 x=BodyX; s32 y=BodyY+((BodyHeight-IconHeight)/2); pcb->pIcon->BitBlt(pcb->pCanvas,x,y); } pcb->pCanvas->TextOutUTF8(BodyX+8+IconWidth,BodyY+((BodyHeight-TextHeight)/2),pmsgUTF8); } s32 ComponentButton_GetIndexFromPos(TComponentButton *pComponentButton,s32 mx,s32 my) { TComponentButton *pcb=pComponentButton; TRect r=pcb->Rect; if(pcb->Visible==false) return(-1); mx-=r.x; my-=r.y; if((0<=mx)&&(mx<r.w)){ if((0<=my)&&(my<r.h)){ return(0); } } return(-1); } bool ComponentButton_MouseUp(TComponentButton *pComponentButton,s32 mx,s32 my) { TComponentButton *pcb=pComponentButton; if(pcb->Visible==false) return(false); if(ComponentButton_GetIndexFromPos(pcb,mx,my)==-1) return(false); if(pcb->CallBack_Click!=NULL) pcb->CallBack_Click(pcb); return(true); }
[ "feng.flash@4bd7f34a-4c62-84e7-1fb2-5fbc975ebfb2" ]
[ [ [ 1, 391 ] ] ]
d600d77a07a7b1498873b134318270763da538a3
dd7d419eb5bb1158f198a1009b0a4268b05d5a29
/ProyectoGame/Input/InputEntry.h
7de2dc4d72710235b8920cbc4d22f768104f232e
[]
no_license
carlixyz/galacticinvaders
6cb09540a725357e118a1f4dcd45a2461536561f
1e08405b62846b7909144331fe72452737bc6d7d
refs/heads/master
2018-01-08T16:49:50.443309
2010-06-10T17:51:06
2010-06-10T17:51:06
36,534,643
0
0
null
null
null
null
ISO-8859-1
C++
false
false
569
h
#pragma once class cInputEntry { public: unsigned muiDevice; unsigned muiChannel; }; struct tActionMapping { int miAction; int miDevice; int miChannel; }; // tActionMapping tiene una larga historia de recorridos primero empezó en InputConfiguration.h // pero inputManager no lo reconocía como tipo en los parametros de su Init() // solamente lo aceptaba declarado al principio de su Header como se comenta en los apuntes pero considero // que ya estaba bastante grande el fichero así que decidí incluirlo en este que está pequeñito
[ [ [ 1, 19 ] ] ]
c3318430d6d4e8086caed309d4508f84217d5124
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/MultimediaProtocols/RTPExample/inc/RTPFileStreamer.h
62f1cf6d46e6a243314f991fa8ec852cef94e0b3
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
3,357
h
// RTPFileStreamer.h // // Copyright (c) Symbian Software Ltd 2005. All rights reserved. // #ifndef __RTPFILESTREAMER_H__ #define __RTPFILESTREAMER_H__ #include "CommDbConnPref.h" #include <in_sock.h> #include <f32file.h> #include <rtp.h> class MFileStreamerObserver /** A simple observer pattern interface to display the status information. */ { public: virtual void NotifyPacketSent() {} virtual void NotifyPacketReceived() {} virtual void NotifyComplete() {} virtual void NotifyError() {} }; class CRtpFileSender : public CActive /** An Active Object which sends a block of a file after every n microseconds as an RTP payload. */ { public: //Callbacks for the sender static void PacketSent(CRtpFileSender* aPtr, const TRtpEvent& aEvent); void DoPacketSent(const TRtpEvent& aEvent); static void SendError(CRtpFileSender* aPtr, const TRtpEvent& aEvent); void DoSendError(const TRtpEvent& aEvent); static CRtpFileSender* NewL(RRtpSession& aSession,RFs& aFs,const TDesC& aSrcFilename, TInt aPacketSize, TInt aDelayMicroSeconds); void StartL(); void SetObserver(MFileStreamerObserver& aObserver) { iObserver = &aObserver; } ~CRtpFileSender(); private: CRtpFileSender(RRtpSession& aSession,RFs& aFs,TInt aPacketSize, TInt aDelayMicroSeconds); void ConstructL(const TDesC& aSrcFilename); void RunL(); void DoCancel(); private: RTimer iSendIntervalTimer; TInt iDelayMicroSecs; TInt iPacketSize; RRtpSession& iSession; RRtpSendSource iSendSrc; RRtpSendPacket iSendPacket; TPtr8 iPayloadDesC; MFileStreamerObserver* iObserver; RFile iFile; RFs& iFs; }; class CRtpFileStreamer : public CBase /** CRtpFileStreamer demonstrates the initialisation of RTP and the method to register for callbacks in the RTP event model. It handles the receiving of RTP packets on the RRtpSession it owns. */ { public: static CRtpFileStreamer* NewL( RSocketServ& aRSocketServ, const TDesC& aSrcFilename, const TDesC& aDestFilename, TInt aBlockLen, const TInetAddr& aDestAddr, TUint aLocalPort,TInt aConnId); ~CRtpFileStreamer(); //Callbacks for the receiver static void NewSource(CRtpFileStreamer* aPtr, const TRtpEvent& aEvent); static void PacketArrived(CRtpFileStreamer* aPtr, const TRtpEvent& aEvent); inline RRtpReceiveSource& ReceiveSrc() { return iRtpRecvSrc; } void SendNextPacketL(); void HandleReceivedPacketL(); void SetObserver(MFileStreamerObserver& aObserver) { iObserver = &aObserver; if (iSender) iSender->SetObserver(aObserver); } void StartL(); private: CRtpFileStreamer( RSocketServ& aSocketServ, const TInetAddr& aDestAddr, TUint aLocalPort); void ConstructL(const TDesC& aSrcFilename, const TDesC& aDestFilename, TInt aPacketSize, TInt aDelayMicroSecs, TInt aConnId); public: RRtpReceivePacket iRecvPacket; private: RSocketServ& iSocketServ; RSocket iSocket; RSocket iRtcpSocket; RConnection iConnection; TInetAddr iDestAddr; TUint iLocalPort; RRtpSession iRtpSession; RRtpReceiveSource iRtpRecvSrc; MFileStreamerObserver* iObserver; CRtpFileSender* iSender; RFs iRFs; RFile iDestFile; }; #endif //__RTPFILESTREAMER_H__
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 125 ] ] ]
3dd534962720468cdffa76799372227409a388b0
14f73382b96f592b53bf77ee8adc4948508a3edf
/src/re330/Light.cpp
c79dd4308dfc79501accd1a61852b06382e3e4c5
[]
no_license
alawrenc/graphics-projects
2fb86312b13db1fb1d17f6e0c987fcc1af1568bb
d0e4fa974cb49c60ab2e6c11e1185adbea1a32cd
refs/heads/master
2021-01-18T07:58:40.639644
2010-05-12T00:37:19
2010-05-12T00:37:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
#include "Light.h" using namespace RE330; Light::Light() : mDirection(0,0,1), mPosition(0,0,1), mType(DIRECTIONAL), mDiffuse(1,1,1), mAmbient(0,0,0), mSpecular(1,1,1), mSpotDirection(0,0,1), mSpotExponent(0.f), mSpotCutoff(180.f) { } void Light::setType(Light::Type type) { mType = type; } Light::Type Light::getType() const { return mType; } void Light::setDirection(const Vector3 &direction) { mDirection = direction; } const Vector3 &Light::getDirection() const { return mDirection; } void Light::setPosition(const Vector3 &position) { mPosition = position; } const Vector3 &Light::getPosition() const { return mPosition; } void Light::setDiffuseColor(const Vector3 &diffuse) { mDiffuse = diffuse; } const Vector3 &Light::getDiffuseColor() const { return mDiffuse; } void Light::setAmbientColor(const Vector3 &ambient) { mAmbient = ambient; } const Vector3 &Light::getAmbientColor() const { return mAmbient; } void Light::setSpecularColor(const Vector3 &specular) { mSpecular = specular; } const Vector3 &Light::getSpecularColor() const { return mSpecular; } void Light::setSpotDirection(const Vector3 &spotDirection) { mSpotDirection = spotDirection; } const Vector3 &Light::getSpotDirection() const { return mSpotDirection; } void Light::setSpotExponent(float spotExponent) { mSpotExponent = spotExponent; } float Light::getSpotExponent() const { return mSpotExponent; } void Light::setSpotCutoff(float spotCutoff) { mSpotCutoff = spotCutoff; } float Light::getSpotCutoff() const { return mSpotCutoff; }
[ [ [ 1, 99 ] ] ]
cb6d5bc89e1e19445ca911a4cf870e10672f5eb0
61a1444517cf2b76d273ff90243f8a8d7e627e6a
/util/stabi/interface/keyAccessible.h
ef8ad04dc98d71bbd4b91b099c4ea8d1504b3632
[]
no_license
DayBreakZhang/stabi
eeea80792a3d2501732d19d5a7c8593e497f43a4
0d50868bf384a25840a31af87bebb3989d3b350c
refs/heads/master
2020-05-20T07:29:06.875021
2010-06-22T09:40:45
2010-06-22T09:40:45
33,292,141
0
0
null
null
null
null
UTF-8
C++
false
false
2,024
h
// Copyright (c) 2010 Yu-Li Lin // // 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 __UTIL_STABI_INTERFACE_KEY_ACCESSIBLE_H #define __UTIL_STABI_INTERFACE_KEY_ACCESSIBLE_H namespace util { namespace stabi { namespace interface { template< typename _KeyType, typename _DataType > class KeyAccessible { public: typedef _KeyType KeyType; typedef _DataType DataType; public: // modifier virtual bool Put(const KeyType &key, const DataType &data) throw () = 0; virtual bool EraseKey(const KeyType &key) throw () = 0; virtual bool Remove(const KeyType &key, DataType &outData) throw () = 0; // operation virtual DataType *Get(const KeyType &key) throw () = 0; virtual const DataType *Get(const KeyType &key) const throw () = 0; virtual bool ContainsKey(const KeyType &key) const throw () = 0; }; } // namespace interface } // namespace stabi } // namespace util #endif // __UTIL_STABI_INTERFACE_KEY_ACCESSIBLE_H
[ "yuli.lin@c77a587f-fc48-8b61-66aa-f312bb63b7e1" ]
[ [ [ 1, 56 ] ] ]
da8443347240891eff4de015676074395c7c5301
ae65aa26731db0e8bf7a6e5271a76c87354ba254
/anDecoder.cpp
a6907ff896cc2098e8e756710aa3542244bf9a12
[]
no_license
mweiguo/lightsimulator
ff8272227b77790506f7ddd41956ed3c01a93f3e
31e0347b94f01a83733c4908cdc145cc95c50799
refs/heads/master
2016-09-06T20:00:41.621848
2009-02-13T10:01:03
2009-02-13T10:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,239
cpp
#include "stdafx.h" #include "andecoder.h" #include "MethodDispatcher.h" #include "dispatch.h" extern MethodDispatcher dispatcher; extern tinyLogger log1; //---------------------------------------------------------------------------------------------------------------- clsANDecorder::clsANDecorder (): bStopParse(false), bCancelParse(false) { } //---------------------------------------------------------------------------------------------------------------- pcap_if_t* palldev; int clsANDecorder::select_device ( Tcl_Interp* interp ) { // select device //pcap_if_t* palldev; char errbuf[PCAP_ERRBUF_SIZE] = {0}; if ( 0 != pcap_findalldevs_ex ( PCAP_SRC_IF_STRING, NULL, &palldev, errbuf ) ){ LOG_ERROR ( log1, "can not get device list\n" ); Tcl_SetResult ( interp, "can not get device list", TCL_VOLATILE ); pcap_freealldevs(palldev); palldev = 0; return -1; } // find specific device std::vector<Tcl_Obj*> lists; lists.push_back ( 0 ); // reserved int i=1; for ( pcap_if_t* p=palldev; p; p=p->next, i++ ){ std::string ipAddr; if ( p->addresses && AF_INET == p->addresses->addr->sa_family ) { sockaddr_in* pp = (sockaddr_in*)p->addresses->addr; in_addr* paddr = (in_addr*)&(pp->sin_addr); std::stringstream ss; ss << (unsigned)paddr->s_net << '.' << (unsigned)paddr->s_host << '.' << (unsigned)paddr->s_lh << '.' << (unsigned)paddr->s_impno << ':' << (unsigned)pp->sin_port; ipAddr = ss.str(); } Tcl_Obj* argv[3] = { Tcl_NewIntObj ( i ), Tcl_NewStringObj ( p->name, strlen(p->name)), Tcl_NewStringObj ( ipAddr.data(), ipAddr.length()) }; lists.push_back ( Tcl_NewListObj ( 3, argv )); } // check whether selection script exist Tcl_Eval ( interp, "info procs device_selection" ); const char* szResult = Tcl_GetStringResult ( interp ); if ( strcmp( szResult, "device_selection") != 0 ) { LOG_ERROR ( log1, "should define 'proc device_selection args' first\n" ); Tcl_SetResult ( interp, "should define 'proc device_selection args' first", TCL_VOLATILE ); pcap_freealldevs(palldev); palldev = 0; return -1; } // select device lists[0] = Tcl_NewStringObj ( "device_selection", strlen("device_selection")); Tcl_EvalObjv ( interp, lists.size(), &lists.front(), TCL_EVAL_DIRECT ); szResult = Tcl_GetStringResult ( interp ); if ( strcmp ( szResult , "-1" ) == 0 ) { LOG_ERROR ( log1, "should select validate device id\n" ); Tcl_SetResult ( interp, "should select validate device id", TCL_VOLATILE ); palldev = 0; return -1; } LOG_INFO ( log1, "select device: \n", szResult ); //pcap_freealldevs(palldev); return atoi( szResult ); } //---------------------------------------------------------------------------------------------------------------- int clsANDecorder::start_recieving (Tcl_Interp* interp, const char* szCmd, int device ) { char errbuf[PCAP_ERRBUF_SIZE] = {0}; // collect add device info //pcap_if_t* palldev; //if ( 0 != pcap_findalldevs_ex ( PCAP_SRC_IF_STRING, NULL, &palldev, errbuf ) ){ // std::cout << "can not get device list" << std::endl; // Tcl_SetResult ( interp, "can not get device list", TCL_VOLATILE ); // pcap_freealldevs(palldev); // return -1; //} // find specific device int i = device; pcap_if_t* pd = palldev; for ( int j=1; j<i; j++, pd=pd->next ); // skip if ( !pd ) { LOG_ERROR ( log1, "can not get selected device\n" ); Tcl_SetResult ( interp, "can not get selected device ", TCL_VOLATILE ); pcap_freealldevs(palldev); palldev = 0; return -1; } // open adapter pcap_t* phandle = pcap_open ( pd->name, 65536, PCAP_OPENFLAG_PROMISCUOUS, 300, NULL, errbuf ); if ( 0 == phandle ){ LOG_ERROR ( log1, "open adapter error\n" ); Tcl_SetResult ( interp, errbuf, TCL_VOLATILE ); pcap_freealldevs(palldev); palldev = 0; return -1; } // set filter option bpf_u_int32 netmask; if ( pd->addresses ) netmask = ((sockaddr_in*)(pd->addresses->netmask->sa_data))->sin_addr.s_addr; else netmask = 0xffffff; bpf_program fp; if ( -1 == pcap_compile ( phandle, &fp, "udp", 1, netmask ) ){ LOG_ERROR ( log1, "error in pcap_compile\n" ); Tcl_SetResult ( interp, "error in pcap_compile", TCL_VOLATILE ); pcap_freealldevs(palldev); palldev = 0; return -1; } if ( -1 == pcap_setfilter ( phandle, &fp ) ){ LOG_ERROR ( log1, "error in pcap_setfilter\n" ); Tcl_SetResult ( interp, "error in pcap_setfilter", TCL_VOLATILE ); pcap_freealldevs(palldev); palldev = 0; return -1; } enter_capture_loop ( phandle, interp, szCmd ); pcap_freealldevs(palldev); palldev = 0; return 0; } //---------------------------------------------------------------------------------------------------------------- int clsANDecorder::enter_capture_loop (pcap_t* phandle, Tcl_Interp* interp, const char* szCmd) { // capture packets //static unsigned int time = GetTickCount (); int i =0; while ( ++i ){ if ( bStopParse ) continue; if ( bCancelParse ) { bCancelParse = false; break; } pcap_pkthdr* pheader; const unsigned char* pdata; if ( 1 != pcap_next_ex ( phandle, &pheader, &pdata ) ){ LOG_WARNING ( log1, "recieve packet time out: %d ms\n", 300 ); Tcl_SetResult ( interp, "recieve packet time out", TCL_VOLATILE ); continue; } // interpret Art-Net only IPHEADER *pIpHeader = (IPHEADER*)(pdata+14); UDPHEADER *pUdpHeader = (UDPHEADER*)((char*)pIpHeader+sizeof(IPHEADER)); ARTNETHEADER *pArtNetHeader = (ARTNETHEADER*)((char*)pUdpHeader+sizeof(UDPHEADER)); // check if packet is artnet first if ( strcmp ( (char*)pArtNetHeader->id, "Art-Net" )!= 0 ) continue; //if ( GetTickCount () - time < 50 ) // continue; if ( pArtNetHeader->op_code != 0x5000 ) continue; pArtNetHeader->length = ntohs ( pArtNetHeader->length ); if ( pArtNetHeader->universe < 0 || pArtNetHeader->universe > 3 ) { LOG_WARNING ( log1, "universe number should in range [0-4]\n" ); continue; } dispatch_dmx ( interp, pArtNetHeader->universe, pArtNetHeader->pdata, pArtNetHeader->length ); //time = GetTickCount (); } return 0; } //---------------------------------------------------------------------------------------------------------------- //int clsANDecorder::decode_artnet ( ARTNETHEADER *pArtNetHeader, Tcl_Interp* interp, const char* szCmd ) //{ // pArtNetHeader->op_code = ntohs ( pArtNetHeader->op_code ); // pArtNetHeader->protver = ntohs ( pArtNetHeader->protver ); // pArtNetHeader->length = ntohs ( pArtNetHeader->length ); // static unsigned int oVal = GetTickCount(), nVal; // static int ii=0; // // //std::for_each ( pArtNetHeader->pdata, pArtNetHeader->pdata+512, HexOut<unsigned int>() ); // //std::cout << std::endl; // dispatch_dmx ( interp, pArtNetHeader->pdata, pArtNetHeader->length ); // // return 0; //} //---------------------------------------------------------------------------------------------------------------- int clsANDecorder::pause_recieving ( ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[] ) { if ( objc != 1 ){ Tcl_WrongNumArgs ( interp, objc, objv, "pause_recv_artnet" ); return TCL_ERROR; } bStopParse = true; return TCL_OK; } //---------------------------------------------------------------------------------------------------------------- int clsANDecorder::resume_recieving ( ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[] ) { if ( objc != 1 ){ Tcl_WrongNumArgs ( interp, objc, objv, "resume_recv_artnet" ); return TCL_ERROR; } bStopParse = false; return TCL_OK; } //---------------------------------------------------------------------------------------------------------------- int clsANDecorder::close_artnet ( ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[] ) { if ( objc != 1 ){ Tcl_WrongNumArgs ( interp, objc, objv, "stop_recv_artnet" ); return TCL_ERROR; } // close worker thread bCancelParse = true; return TCL_OK; } //----------------------------------------------------------------------------------------------------------------
[ [ [ 1, 234 ] ] ]
e2d95e671170e870ef0af53fffbc294e59a42cfd
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlBspTree.h
fb92dbefa6ae41c587d293be1af22ca290c8e736
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
2,197
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLBSPTREE_H #define WMLBSPTREE_H // Creation of a BSP tree from a list of triangles. The internal nodes of // the tree are BspNode objects and store the coplanar triangles (if any) // of the splitting planes. #include "WmlBspNode.h" #include "WmlColorRGB.h" #include "WmlVector2.h" #include "WmlVector3.h" #include <list> namespace Wml { class WML_ITEM BspTree : public BspNode { WmlDeclareRTTI; WmlDeclareStream; public: class WML_ITEM Triangle { public: Triangle (); Vector3f m_akVertex[3]; Vector3f* m_apkNormal[3]; ColorRGB* m_apkColor[3]; Vector2f* m_apkTexture[3]; }; typedef std::list<Triangle*> TriangleList; // Construction. The input list is consumed by the construction, so the // application should keep a copy of the list if it needs to be used // elsewhere. BspTree (TriangleList& rkList); protected: BspTree (); void CreateTree (TriangleList& rkList); void SplitTriangle (Triangle* pkTri, TriangleList& rkPositive, TriangleList& rkNegative, TriangleList& rkCoincident); void ClipTriangle (int i0, int i1, int i2, Triangle* pkTri, float afDistance[3], TriangleList& rkPositive, TriangleList& rkNegative); void AddTriangle (TriangleList& rkList, const Vector3f& rkV0, const Vector3f& rkV1, const Vector3f& rkV2, bool bHasNormals, const Vector3f* pkN0, const Vector3f* pkN1, const Vector3f* pkN2, bool bHasColors, const ColorRGB* pkC0, const ColorRGB* pkC1, const ColorRGB* pkC2, bool bHasTextures, const Vector2f* pkT0, const Vector2f* pkT1, const Vector2f* pkT2); }; WmlSmartPointer(BspTree); WmlRegisterStream(BspTree); } #endif
[ [ [ 1, 76 ] ] ]
271f5dd963854811f45f785a825c955e37942d79
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/source/aosl/referential.cpp
742fcd5f70197977d935912e46e996f598fa618f
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
4,166
cpp
// 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. // // Begin prologue. // #define AOSLCPP_SOURCE // // End prologue. #include <xsd/cxx/pre.hxx> #include "aosl/referential.hpp" #include <xsd/cxx/xml/dom/wildcard-source.hxx> #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> #include <xsd/cxx/tree/comparison-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; static const ::xsd::cxx::tree::comparison_plate< 0, char > comparison_plate_init; } namespace aosl { // Referential // Referential:: Referential (const ::xercesc::DOMElement& e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (e, f, c) { _xsd_Referential_convert (); } Referential:: Referential (const ::xercesc::DOMAttr& a, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (a, f, c) { _xsd_Referential_convert (); } Referential:: Referential (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (s, e, f, c) { _xsd_Referential_convert (); } Referential* Referential:: _clone (::xml_schema::Flags f, ::xml_schema::Container* c) const { return new class Referential (*this, f, c); } Referential::Value Referential:: _xsd_Referential_convert () const { ::xsd::cxx::tree::enum_comparator< char > c (_xsd_Referential_literals_); const Value* i (::std::lower_bound ( _xsd_Referential_indexes_, _xsd_Referential_indexes_ + 2, *this, c)); if (i == _xsd_Referential_indexes_ + 2 || _xsd_Referential_literals_[*i] != *this) { throw ::xsd::cxx::tree::unexpected_enumerator < char > (*this); } return *i; } const char* const Referential:: _xsd_Referential_literals_[2] = { "relative", "absolute" }; const Referential::Value Referential:: _xsd_Referential_indexes_[2] = { ::aosl::Referential::absolute, ::aosl::Referential::relative }; } #include <ostream> #include <xsd/cxx/tree/std-ostream-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::std_ostream_plate< 0, char > std_ostream_plate_init; } namespace aosl { ::std::ostream& operator<< (::std::ostream& o, Referential::Value i) { return o << Referential::_xsd_Referential_literals_[i]; } ::std::ostream& operator<< (::std::ostream& o, const Referential& i) { return o << static_cast< const ::xml_schema::String& > (i); } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace aosl { } #include <ostream> #include <xsd/cxx/tree/error-handler.hxx> #include <xsd/cxx/xml/dom/serialization-source.hxx> #include <xsd/cxx/tree/type-serializer-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_serializer_plate< 0, char > type_serializer_plate_init; } namespace aosl { void operator<< (::xercesc::DOMElement& e, const Referential& i) { e << static_cast< const ::xml_schema::String& > (i); } void operator<< (::xercesc::DOMAttr& a, const Referential& i) { a << static_cast< const ::xml_schema::String& > (i); } void operator<< (::xml_schema::ListStream& l, const Referential& i) { l << static_cast< const ::xml_schema::String& > (i); } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "klaim@localhost" ]
[ [ [ 1, 189 ] ] ]
df7df81a8269952cbc5aef79616b365d897a1594
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/XMLTestCode/xmlTest/XmlStream.cpp
f82e23bd04961b73855004106e3e6c9651cfbdc9
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
GB18030
C++
false
false
15,767
cpp
#include "stdafx.h" #include "XmlStream.h" //class class CFindChar { public: CFindChar( char* strInput ) :Pos( -1 ) { strValue = strInput ; memset( pBuf, 0x0, sizeof(pBuf) ); memcpy( pSave, strInput, min(CHAR_MAX_LENGTH, strlen( strInput) + 1 ) ); Pointer = pSave; } char* GetNextChar( ) { memset( pBuf, 0x0, sizeof(pBuf) ); Pos = strValue.find( '//', Pos + 1 ); if ( -1 == Pos ) { return NULL; } pSave[Pos] = '\0'; memcpy( pBuf, Pointer, min(CHAR_MAX_LENGTH, strlen( Pointer) + 1 ) ); Pointer = pSave + Pos + 1; return pBuf; } protected: private: string strValue; char pBuf [CHAR_MAX_LENGTH]; char pSave[CHAR_MAX_LENGTH]; char *Pointer; long Pos; }; //Function int MB2WC( wchar_t* _pwc, const char* _pch ) { int buf_ln = MultiByteToWideChar(CP_ACP, 0, _pch, -1, _pwc, 0); MultiByteToWideChar(CP_ACP, 0, _pch, -1, _pwc, buf_ln); return buf_ln; } int WC2MB( char* _pch, wchar_t* _pwc ) { int buf_ln = WideCharToMultiByte(CP_ACP, 0, _pwc, -1, _pch, 0, 0, 0); WideCharToMultiByte(CP_ACP, 0, _pwc, -1, _pch, buf_ln, 0, 0); return buf_ln; } //class CXmlNode CXmlNode::CXmlNode() : m_CurElement( NULL ), m_pCXmlStream( NULL ) { } CXmlNode::CXmlNode( wchar_t *pwcNodeName ) : m_CurElement( NULL ), m_pCXmlStream( NULL ) { char wcTemp[ CHAR_MAX_LENGTH ] = ""; WC2MB( wcTemp, pwcNodeName ); m_CurElement = new TiXmlElement( wcTemp ); if ( NULL == m_CurElement ) { _ASSERT(0); } } CXmlNode::~CXmlNode() { if ( NULL == m_pCXmlStream && NULL != m_CurElement ) { delete m_CurElement; m_CurElement = NULL; } } //public: EN_MOVE CXmlNode::MoveNext() { if ( NULL == m_CurElement ) { _ASSERT(0); return MOVE_END; } m_CurElement = /*(TiXmlElement*)*/(m_CurElement->NextSibling())->ToElement(); if ( NULL == m_CurElement ) { return MOVE_END; } return MOVE_OK; } HRESULT CXmlNode::GetNodeContent( wchar_t* pwcsNodePath, wchar_t** ppwcsNodeValue, NodeAttribute_t** ppAttributes, long* lAttributesCount ) { HRESULT hr = S_OK; BOOL bIsFind = TRUE; *lAttributesCount = 0; //从当前位置取得信息 if ( NULL == pwcsNodePath ) { hr = SubGetNodeContent( m_CurElement, ppwcsNodeValue, ppAttributes, lAttributesCount ); if (FAILED(hr)) { _ASSERT(0); hr = E_FAIL; } return hr; } //从pwcsNodePath指定的位置取得信息 if ( NULL == m_CurElement ) { _ASSERT(0); return E_FAIL; } do { long lSize = wcslen( pwcsNodePath) + 1; char *pTemp = new char [ lSize ]; if ( NULL == *pTemp ) { _ASSERT(0); hr = E_FAIL; break; } memset( pTemp, 0x0, lSize * sizeof( char ) ); WC2MB( pTemp, pwcsNodePath ); CFindChar clCFindChar( pTemp ); TiXmlElement* pPreNode = NULL; TiXmlElement* pCurNode = NULL; //fisrt time char *pBuf = clCFindChar.GetNextChar(); if ( NULL == pBuf ) { _ASSERT(0); hr = E_FAIL; break; } pPreNode = m_CurElement->FirstChildElement( pBuf ); if ( NULL == pPreNode ) { _ASSERT(0); hr = E_FAIL; break; } //loop while ( TRUE ) { pBuf = clCFindChar.GetNextChar(); if ( NULL == pBuf ) { break; } if ( NULL == pPreNode ) { bIsFind = FALSE; break; } pCurNode = pPreNode->FirstChildElement( pBuf ); pPreNode = pCurNode; pCurNode = NULL; } delete [] pTemp; if ( !bIsFind ) { _ASSERT(0); hr = E_FAIL; break; } else { hr = SubGetNodeContent( pPreNode, ppwcsNodeValue, ppAttributes, lAttributesCount ); if (FAILED(hr)) { _ASSERT(0); hr = E_FAIL; break; } } } while ( FALSE ); return hr; } HRESULT CXmlNode::SetNodeContent( wchar_t* pwcsNodePath, wchar_t* pwcsNodeValue, NodeAttribute_t* ppAttributes, long lAttributesCount ) { if ( NULL == m_CurElement ) { _ASSERT(0); return E_FAIL; } HRESULT hr = S_OK; if ( NULL == pwcsNodePath ) { hr = SubSetNodeContent( m_CurElement, pwcsNodeValue, ppAttributes, lAttributesCount ); } else { char chPath[ CHAR_MAX_LENGTH ] = ""; WC2MB( chPath, pwcsNodePath ); if ( NULL == m_pCXmlStream ) { _ASSERT(0); return E_FAIL; } TiXmlElement* pTiXmlElement; hr = m_pCXmlStream->FindNode( chPath, &pTiXmlElement ); if ( FAILED(hr) ) { _ASSERT(0); return E_FAIL; } hr = SubSetNodeContent( pTiXmlElement, pwcsNodeValue, ppAttributes, lAttributesCount ); } #ifdef _DEBUG if ( NULL != m_pCXmlStream ) { m_pCXmlStream->GetDocument()->SaveFile( "./FileName.xml" ); } #endif return hr; } HRESULT CXmlNode::SubSetNodeContent( TiXmlElement* pNode, wchar_t* pwcsNodeValue, NodeAttribute_t* ppAttributes, long lAttributesCount ) { // if ( NULL != pwcsNodeValue ) // { char chValue[ CHAR_MAX_LENGTH ] = ""; WC2MB( chValue, pwcsNodeValue ); TiXmlText text( chValue ); for ( int i = 0; i < lAttributesCount; ++i ) { char name [ CHAR_MAX_LENGTH ] = ""; char value[ CHAR_MAX_LENGTH ] = ""; WC2MB( name , ppAttributes[i].wcsName ); WC2MB( value, ppAttributes[i].wcsValue ); pNode->SetAttribute( name, value ); } pNode->InsertEndChild( text ); // } // else // { // _ASSERT(0); // return E_FAIL; // } return S_OK; } HRESULT CXmlNode::AppendNode( CXmlNode* pCXmlNode ) { if ( NULL == m_CurElement ) { _ASSERT(0); return E_FAIL; } m_CurElement->InsertEndChild( *( pCXmlNode->GetElement() ) ); #ifdef _DEBUG if ( NULL != m_pCXmlStream ) { m_pCXmlStream->GetDocument()->SaveFile( "./FileName.xml" ); } #endif return S_OK; } //private: HRESULT CXmlNode::SubGetNodeContent( TiXmlElement* pNode, wchar_t** ppwcsNodeValue, NodeAttribute_t** ppAttributes, long* lAttributesCount ) { const char *pText = pNode->GetText(); if ( NULL == pText ) { *ppwcsNodeValue = NULL; } else { MB2WC( *ppwcsNodeValue, pText ); } TiXmlAttribute* pAttr = pNode->FirstAttribute(); while ( NULL != pAttr ) { pAttr = pAttr->Next(); ++(*lAttributesCount); } if ( 0 < (*lAttributesCount) ) { *ppAttributes = new NodeAttribute_t[ *lAttributesCount ]; pAttr = pNode->FirstAttribute(); for (int i = 0; i < *lAttributesCount; ++i ) { MB2WC( (*ppAttributes)[i].wcsName , pAttr->Name() ); MB2WC( (*ppAttributes)[i].wcsValue, pAttr->Value() ); pAttr = pAttr->Next(); } } return S_OK; } HRESULT CXmlNode::SetNodePtr( TiXmlElement* pNode, CXmlStream* pCXmlStream ) { if ( NULL == pNode || NULL == pCXmlStream ) { _ASSERT(0); return E_FAIL; } m_pCXmlStream = pCXmlStream; m_CurElement = pNode; return S_OK; } TiXmlElement* CXmlNode::GetElement() { if ( NULL == m_CurElement ) { _ASSERT(0); } return m_CurElement; } //class CXmlStream CXmlStream::CXmlStream() :m_pTiXmlDocument( NULL ), m_EnType( EnCreateXml ), bIsFirst( TRUE ) { } CXmlStream::~CXmlStream() { if ( NULL != m_pTiXmlDocument ) { delete m_pTiXmlDocument; m_pTiXmlDocument = NULL; } } //public: HRESULT CXmlStream::GetXmlStream( wchar_t* pwcStream, long lSize ) { m_strBuf << *m_pTiXmlDocument; MB2WC( pwcStream, m_strBuf.c_str() ); return S_OK; } HRESULT CXmlStream::Initialize( long lSize ) { HRESULT hr = S_OK; do { if ( lSize <= 0 ) { _ASSERT( 0 ); hr = E_FAIL; break; } if ( NULL != m_pTiXmlDocument ) { delete m_pTiXmlDocument; m_pTiXmlDocument = NULL; } m_pTiXmlDocument = new TiXmlDocument(); if ( NULL == m_pTiXmlDocument ) { _ASSERT(0); hr = E_FAIL; break; } } while (FALSE); m_EnType = EnCreateXml; return hr; } HRESULT CXmlStream::Load( wchar_t* pwcsXmlBuf, long lSize ) { if ( NULL == pwcsXmlBuf ) // need ReAlloc { _ASSERT(0); return E_FAIL; } HRESULT hr = S_OK; do { if ( NULL == m_pTiXmlDocument ) { _ASSERT(0); hr = E_FAIL; break; } char *pTemp = new char[ lSize ]; if ( NULL == pTemp ) { _ASSERT(0); hr = E_FAIL; break; } WC2MB( pTemp, pwcsXmlBuf); m_strBuf = pTemp; delete [] pTemp; m_pTiXmlDocument->Parse( m_strBuf.c_str() ); if ( m_pTiXmlDocument->Error() ) { _ASSERT(0); hr = E_FAIL; break; } } while (FALSE); m_EnType = EnLoadXml; return hr; } HRESULT CXmlStream::SelectNode( wchar_t* pwcsNodePath, CXmlNode** pclXmlNode ) { if ( NULL == pwcsNodePath ) { _ASSERT(0); return E_FAIL; } HRESULT hr = S_OK; do { long lSize = wcslen( pwcsNodePath) + 1; char *pTemp = new char [ lSize ]; if ( NULL == *pTemp ) { _ASSERT(0); hr = E_FAIL, *pclXmlNode = NULL; break; } memset( pTemp, 0x0, lSize * sizeof( char ) ); WC2MB( pTemp, pwcsNodePath ); hr = SubSelectNode( pTemp, pclXmlNode ); delete [] pTemp; if ( FAILED( hr ) ) { *pclXmlNode = NULL; break; } } while ( FALSE ); return hr; } //private: HRESULT CXmlStream::SubSelectNode( char *pcsNodePath, CXmlNode** pclXmlNode ) { HRESULT hr = S_OK; do { if ( EnLoadXml == m_EnType ) { hr = ParseXml( pcsNodePath, pclXmlNode ); } else { hr = MakeXml( pcsNodePath, pclXmlNode ); } } while ( FALSE ); return hr; } HRESULT CXmlStream::MakeXmlFirst( char *pcsNodePath, CXmlNode** pclXmlNode ) { HRESULT hr = S_OK; do { CFindChar clCFindChar( pcsNodePath ); //first time char *pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } TiXmlElement *pNode = new TiXmlElement( pTemp ); m_pTiXmlDocument->LinkEndChild( pNode ); TiXmlElement *pTempNode = NULL; do { pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } pTempNode = new TiXmlElement( pTemp ); pNode->LinkEndChild( pTempNode ); pNode = pTempNode; #ifdef _DEBUG if ( NULL != m_pTiXmlDocument ) { m_pTiXmlDocument->SaveFile( "./FileName.xml" ); } #endif } while ( TRUE ); if ( NULL != pNode ) { * pclXmlNode = new CXmlNode; if ( NULL == *pclXmlNode ) { _ASSERT(0); return E_FAIL; } (*pclXmlNode)->SetNodePtr( pNode, this ); } } while ( FALSE ); return hr; } #if 0 HRESULT CXmlStream::MakeXmlFirst( char *pcsNodePath, CXmlNode** pclXmlNode ) { HRESULT hr = S_OK; vector< TiXmlElement * > vecElement; do { CFindChar clCFindChar( pcsNodePath ); TiXmlElement *pCurElement = NULL; TiXmlElement *pPreElement = NULL; do { char *pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } TiXmlElement * pElement = new TiXmlElement( pTemp ); if ( NULL == pElement ) { _ASSERT(0); hr = E_FAIL; break; } vecElement.push_back( pElement ); } while ( TRUE ); hr = SubMakeXml( vecElement ); } while ( FALSE ); if ( SUCCEEDED(hr) ) { #ifdef _DEBUG if ( NULL != m_pCXmlStream ) { m_pCXmlStream->GetDocument()->SaveFile( "./FileName.xml" ); } #endif } return hr; } HRESULT CXmlStream::SubMakeXml( vector<TiXmlElement*> & vecElement) { vector< TiXmlElement * >::reverse_iterator ri, riend, save; riend = vecElement.rend(); ri = save = vecElement.rbegin(); ++ri; for ( ri; ri != riend; ++ri, ++save ) { (*ri)->InsertEndChild( *(*save) ); } m_pTiXmlDocument->LinkEndChild( *(vecElement.begin()) ); vector< TiXmlElement * >::iterator iter = vecElement.begin(); ++iter; for ( ; iter != vecElement.end(); ++iter ) { delete (*iter); (*iter) = NULL; } return S_OK; } #endif HRESULT CXmlStream::MakeXml( char *pcsNodePath, CXmlNode** pclXmlNode ) { HRESULT hr = S_OK; if ( bIsFirst ) { bIsFirst = FALSE; TiXmlDeclaration *pDeclaration = new TiXmlDeclaration( "1.0", "UTF-8", "" ); if ( NULL == pDeclaration || NULL == m_pTiXmlDocument ) { _ASSERT(0); return E_FAIL; } m_pTiXmlDocument->LinkEndChild(pDeclaration); hr = MakeXmlFirst( pcsNodePath, pclXmlNode ); return hr; } do { CFindChar clCFindChar( pcsNodePath ); //first time char *pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } TiXmlElement *pNode = m_pTiXmlDocument->FirstChildElement( pTemp ); if ( NULL == pNode ) { pNode = new TiXmlElement( pTemp ); m_pTiXmlDocument->LinkEndChild( pNode ); #ifdef _DEBUG if ( NULL != m_pTiXmlDocument ) { m_pTiXmlDocument->SaveFile( "./FileName.xml" ); } #endif } TiXmlElement *pTempNode = NULL; do { pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } pTempNode = pNode->FirstChildElement( pTemp ); if ( NULL == pTempNode ) { pTempNode = new TiXmlElement( pTemp ); pNode->LinkEndChild( pTempNode ); pNode = pTempNode; #ifdef _DEBUG if ( NULL != m_pTiXmlDocument ) { m_pTiXmlDocument->SaveFile( "./FileName.xml" ); } #endif } else { pNode = pTempNode; } } while ( TRUE ); if ( NULL != pNode ) { * pclXmlNode = new CXmlNode; if ( NULL == *pclXmlNode ) { _ASSERT(0); return E_FAIL; } (*pclXmlNode)->SetNodePtr( pNode, this ); } } while ( FALSE ); return hr; } HRESULT CXmlStream::ParseXml( char *pcsNodePath, CXmlNode** pclXmlNode ) { HRESULT hr = S_OK; string strTemp = pcsNodePath; TiXmlElement* pPreNode = NULL; TiXmlElement* pCurNode = NULL; BOOL bIsFind = TRUE; do { CFindChar clCFindChar( pcsNodePath ); //first time char *pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } pPreNode = m_pTiXmlDocument->FirstChildElement( pTemp ); if ( NULL == pPreNode ) { _ASSERT(0); hr = E_FAIL; break; } //loop while ( TRUE ) { pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } if ( NULL == pPreNode ) { bIsFind = FALSE; break; } pCurNode = pPreNode->FirstChildElement( pTemp ); pPreNode = pCurNode; pCurNode = NULL; } } while ( FALSE ); if ( FAILED(hr) || !bIsFind ) { *pclXmlNode = NULL; } else { //create node do { *pclXmlNode = new CXmlNode; if ( NULL == *pclXmlNode ) { _ASSERT(0); hr = E_FAIL; break; } (*pclXmlNode)->SetNodePtr( pPreNode, this ); } while ( FALSE ); } return hr; } HRESULT CXmlStream::FindNode( char *pcsNodePath, TiXmlElement** pclXmlElement ) { HRESULT hr = S_OK; *pclXmlElement = NULL; do { CFindChar clCFindChar( pcsNodePath ); //first time char *pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } TiXmlElement *pNode = m_pTiXmlDocument->FirstChildElement( pTemp ); if ( NULL == pNode ) { _ASSERT(0); hr = E_FAIL; break; } TiXmlElement *pTempNode = NULL; do { pTemp = clCFindChar.GetNextChar(); if ( NULL == pTemp ) { break; } pTempNode = pNode->FirstChildElement( pTemp ); if ( NULL == pTempNode ) { _ASSERT(0); hr = E_FAIL; break; } pNode = pTempNode; } while ( TRUE ); if ( NULL != pTempNode ) { *pclXmlElement = pTempNode; } } while ( FALSE ); return hr; } TiXmlDocument* CXmlStream::GetDocument() { return m_pTiXmlDocument; }
[ [ [ 1, 880 ] ] ]
c31a7f933dfc00a26750f8e04d851f6dc9511145
da9b11cab53e4771eaa6c0d2c885e4331580b2f3
/src/semaphore.h
9fa7257a4490917b234980d56f0b974c14768fd3
[]
no_license
ud1/dhtpp
305913dea8f3c65d52bdb872aa6f26f5aca7a9a6
016aa4e0b628f92614e9a38e90461cea8bc4df78
refs/heads/master
2021-01-13T16:44:30.537380
2010-05-31T22:22:55
2010-05-31T22:22:55
77,243,109
0
0
null
null
null
null
UTF-8
C++
false
false
603
h
#ifndef DHT_SEMAPHORE_H #define DHT_SEMAPHORE_H #include "timer.h" namespace dhtpp { class CVirtualSemaphore { public: CVirtualSemaphore(int count_) { count = count_; } bool Wait() { // this semaphore cannot wait really //assert(count > 0); --count; return true; } bool Wait(int milliseconds) { // move virtual time forward GetTimerInstance()->AddTimeInterval(milliseconds); return Wait(); } void Post() { ++count; } protected: int count; }; typedef CVirtualSemaphore CSemaphore; } #endif // DHT_SEMAPHORE_H
[ [ [ 1, 37 ] ] ]