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
4f074c3b973778c29afcee49e677d13ee8c83965
cb9967f3c1349124878d5769d1ecd16500f60a08
/ProcessStub/HookAttachment.cpp
60db4c4fa7847869677b29eeaf41c853879db854
[]
no_license
josiahdecker/TaskbarExtender
b71ab2439e6844060e6b41763b23ace6c00ccad2
3977192ba85d48bd8caf543bfc3a0f6d0df9efc9
refs/heads/master
2020-05-30T17:11:14.543553
2011-03-20T14:08:46
2011-03-20T14:08:46
1,503,110
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
cpp
#include "StdAfx.h" #include "Windows.h" #include "HookAttachment.h" namespace TaskbarExtender { using namespace System; using namespace System::Runtime::InteropServices; HookAttachment::HookAttachment(String^ hook_dll_location, int ordinal, int systemCallToHook){ data = gcnew HookData(); data->DllLocation = hook_dll_location; data->FunctionOrdinal = ordinal; IntPtr location_ptr = Marshal::StringToHGlobalUni(hook_dll_location); LPCWSTR location = (LPCWSTR)location_ptr.ToPointer(); data->hinstDll = LoadLibraryW(location); Marshal::FreeHGlobal(location_ptr); data->hkProc = (HOOKPROC)GetProcAddress(data->hinstDll, (LPCSTR)data->FunctionOrdinal); //"_windowSignalResponse@12" or "windowSignalResponse" data->hhook = SetWindowsHookEx( systemCallToHook, data->hkProc, data->hinstDll, 0); if (!data->hhook) { int err = GetLastError(); Console::WriteLine("Error setting hook- num: {0}", err); } } HookAttachment::~HookAttachment(){ if (data->hhook){ UnhookWindowsHookEx(data->hhook); } } }
[ [ [ 1, 41 ] ] ]
08f4ba27aa036d1004230d9bed7f5346b7912b0a
a0155e192c9dc2029b231829e3db9ba90861f956
/MailFilter/Platform/nlm/MFNLM.cpp
63297cbe8e8a26c6de02cfcdf16a0262ffae716f
[]
no_license
zeha/mailfilter
d2de4aaa79bed2073cec76c93768a42068cfab17
898dd4d4cba226edec566f4b15c6bb97e79f8001
refs/heads/master
2021-01-22T02:03:31.470739
2010-08-12T23:51:35
2010-08-12T23:51:35
81,022,257
0
0
null
null
null
null
ISO-8859-1
C++
false
false
39,364
cpp
/* + + MFNLM.cpp + + NetWare Platform Specific Functions + for CLib AND LibC + + + Copyright 2001-2004 Christian Hofstädtler. + + */ #ifndef __cplusplus #error No Cpp support! #endif #ifdef N_PLAT_NLM // Using _MAIN_ to get variables defined here. #define _MAILFILTER_MAIN_ #define _MFD_MODULE "MFNLM.CPP" // Include MailFilter.h #include "..\..\Main\MailFilter.h" #include "MFConfig-defines.h" // And undef it ... ;) #undef _MAILFILTER_MAIN_ #include "MFVersion.h" #include "MFZip.h" #include "MFUnZip.h" #include "MFRelayHost.h++" #include "MFConfig.h++" #include "MFAVA-NLM.h" #include <sys/utsname.h> #ifdef __NOVELL_LIBC__ #include <nks/netware.h> #include <nks/dirio.h> #include <client.h> #endif extern int MailFilter_Main_RunAppConfig(bool bStandalone); extern int MailFilter_Main_RunAppRestore(bool bStandalone); extern int MailFilter_Main_RunAppNRM(bool bStandalone); extern char MFL_LicenseKey[MAX_PATH]; extern void MailFilter_NRM_sigterm(); // NUT: Local Prototypes static int MF_NutVerifyExit(void); // debug key static void MF_NutHandlerKeyF2 (void *handle); // real keys static void MF_NutHandlerKeyF6 (void *handle); static void MF_NutHandlerKeyF7 (void *handle); static void MF_NutHandlerKeyF8 (void *handle); static void MF_NutHandlerKeyF9 (void *handle); static void MF_NutHandlerKeyF10 (void *handle); // NUT: Status Portal Handle static PCB *statusPortalPCB = NULL; static bool MFT_NUT_GetKey = true; // Time ... static tm tmp_TimeTM; static time_t tmp_Time; static int MF_NutMutexQueryUser = 0; extern void MFWorker_SetupPaths(); #ifdef __NOVELL_LIBC__ extern "C" { int __init_malloc(); int __deinit_malloc(); } #else inline int __init_malloc() { return 0; }; inline int __deinit_malloc() { return 0; }; #endif // // // #ifndef __NOVELL_LIBC__ extern "C" { extern int NWIsNLMLoadedProtected(void); extern int nlmisloadedprotected (void); } inline bool mf_nlmisloadedprotected() { return (bool)nlmisloadedprotected(); } #else inline bool mf_nlmisloadedprotected() { return (bool)nlmisloadedprotected(); } #endif // // Event Handler For NLM ShutDown // void MF_ExitProc(void) { // Shut down NUT if (MF_NutInfo != NULL) { NWSRestoreNut ( MF_NutInfo ); MF_NutInfo = NULL; statusPortalPCB = NULL; } // Destroy Screen ... if (MFD_ScreenID) #ifdef __NOVELL_LIBC__ CloseScreen ( MFD_ScreenID ); #else DestroyScreen ( MFD_ScreenID ); #endif if (MF_GlobalConfiguration != NULL) delete(MF_GlobalConfiguration); __deinit_malloc(); } // " F6-Restart F7-Exit F9-Show Configuration F10 Configure ", void MF_NutHandlerKeyF6 (void *handle) // RESTART { int rc = 0; handle = handle; // Keep compiler quiet. MFT_NLM_Exiting = 254; MF_StatusText("Preparing to restart MailFilter..."); // We need this to wake the UI thread up ... NWSUngetKey ( K_ESCAPE , 0 , MF_NutInfo ); return; } void MF_NutHandlerKeyF7 (void *handle) // EXIT { if (MF_NutVerifyExit()) { MF_StatusText("Shutting Down On Keyboard Request ..."); MF_DisplayCriticalError("MAILFILTER: Shutting Down On Keyboard Request ...\n"); // Disable Func. Keys so user can't exit a 2nd time NWSDisableAllInterruptKeys((NUTInfo*)handle); #ifdef __NOVELL_LIBC__ raise(SIGTERM); #else system("MFSTOP"); #endif } } void MF_NutHandlerKeyF8 (void *handle) // RESTORE ME { #pragma unused(handle) MFT_NLM_Exiting = 252; // We need this to wake the UI thread up ... NWSUngetKey ( K_ESCAPE , 0 , MF_NutInfo ); return; } void MF_NutHandlerKeyF10 (void *handle) // CONFIGURE ME { #pragma unused(handle) MFT_NLM_Exiting = 253; // We need this to wake the UI thread up ... NWSUngetKey ( K_ESCAPE , 0 , MF_NutInfo ); return; } void MF_NutHandlerKeyF9 (void *handle) // SHOW CONFIG { #pragma unused(handle) MF_UI_ShowConfiguration(); } namespace MailFilter_Configuration { int MF_ConfigReadInt(std::string ConfigFile, const int Entry); } void MF_NutHandlerKeyF2 (void *handle) // debug stuff { handle = handle; // Keep compiler quiet. char buf[81]; #ifdef _MF_MEMTRACE sprintf(buf,"AllocCount: %d",MFD_AllocCounts); MF_StatusUI_UpdateLog(buf); #endif sprintf(buf,"StackAvail: %d, DebugLevel: %d",stackavail(),MFT_Debug); MF_StatusUI_UpdateLog(buf); MFUtil_CheckCurrentVersion(); ThreadSwitch(); /* do useless stuff for certification */ { MFZip z("SYS:SYSTEM\\MAILFLT.ZIP",9,0); ThreadSwitch(); z.AddFile("MAILFLT.NLM","SYS:SYSTEM\\MAILFLT.NLM"); ThreadSwitch(); } { MFUnZip z("SYS:SYSTEM\\MAILFLT.ZIP"); ThreadSwitch(); iXList* list = z.ReadZipContents(); ThreadSwitch(); delete(list); ThreadSwitch(); z.ExtractFile("MAILFLT.NLM","SYS:SYSTEM\\MAILFLT.OUT"); ThreadSwitch(); } ThreadSwitch(); char* szEmail = (char*)_mfd_malloc(5000,"szEmail"); sprintf(szEmail,"Dear PostMaster!\r\n\r\n" "You got this mail because someone requested it by pressing F2 on the\r\n" "MailFilter Main Screen.\r\n" "\r\n" "Yours,\r\nMailFilter Version %s on %s.\r\n\r\n", MAILFILTERVERNUM, MF_GlobalConfiguration->ServerName.c_str() ); ThreadSwitch(); MF_EMailPostmasterGeneric( "Debug Mail Requested",szEmail, "SYS:SYSTEM\\MAILFLT.NLM","MAILFLT.NLM"); _mfd_free(szEmail,"szEmail"); ThreadSwitch(); extern void MF_StatusSendDailyReport(const char* szLogFile); MF_StatusSendDailyReport("SYS:\\ETC\\CONSOLE.LOG"); ThreadSwitch(); extern void __mfd_symbols_worker(); __mfd_symbols_worker(); ThreadSwitch(); MFL_VerInfo(); ThreadSwitch(); MFRelayHost* rh = new MFRelayHost("127.0.0.2"); ThreadSwitch(); rh->LookupRBL_DNS("bl.spamcop.net", "127.0.0.1"); ThreadSwitch(); rh->LookupDNS(); delete(rh); ThreadSwitch(); MFD_Out(MFD_SOURCE_MAIL,"%s\n",strprintf("foo").c_str()); ThreadSwitch(); MailFilter_Configuration::MF_ConfigReadInt("SYS:\\ETC\\MAILFLT\\CONFIG.OLD",10); ThreadSwitch(); MF_OutOfMemoryHandler(); ThreadSwitch(); char szVirusName[MAX_PATH]; bool bFoundVirus = false; int iVirusType; szVirusName[0] = 0; iVirusType = 0; ThreadSwitch(); MailFilter_AV_ScanFile("SYS:\\SYSTEM\\MAILFLT.ZIP", szVirusName, MAX_PATH, iVirusType); ThreadSwitch(); // MF_LoginUser(); } void MFL_VerInfo() { MF_StatusText(MF_Msg(MSG_EVAL_LINE1)); MF_StatusText(MF_Msg(MSG_EVAL_LINE2)); MF_StatusText(MF_Msg(MSG_EVAL_LINE3)); MF_StatusText(MF_Msg(MSG_EVAL_LINE4)); MF_StatusNothing(); } bool _mf_nutinit2(rtag_t tagID) { long ccode; ccode=NWSInitializeNut( /* utility */ MSG_PROGRAM_NAME, /* version */ (unsigned long)-1, /* headerType */ NO_HEADER, //SMALL_HEADER, /* compatibilityType */ NUT_REVISION_LEVEL, #ifdef __NOVELL_LIBC__ /* messageTable */ (char **)programMesgTable, #else /* messageTable */ (unsigned char **)programMesgTable, #endif /* helpScreens */ NULL, /* screenID */ MF_ScreenID, /* resourceTag */ tagID, /* handle */ &MF_NutInfo ); if(ccode != 0) return false; return true; } // // NUT: Initialize NUT and Tags // bool MF_NutInit(void) { rtag_t tagID; char szTemp[80+2]; #ifdef __NOVELL_LIBC__ tagID=AllocateResourceTag( /* NLMHandle */ MF_NLMHandle, /* descriptionString */ MF_Msg(MSG_PROGRAM_TAG_NAME), /* resourceType */ AllocSignature ); #else tagID=AllocateResourceTag( /* NLMHandle */ MF_NLMHandle, /* descriptionString */ (const unsigned char*)MF_Msg(MSG_PROGRAM_TAG_NAME), /* resourceType */ AllocSignature ); #endif if(tagID == NULL) { MF_DisplayCriticalError("MAILFILTER: Error allocating Resource Tag for NUT!\n"); return false; } if (!_mf_nutinit2(tagID)) { #ifdef __NOVELL_LIBC__ // load threads.nlm for nwsnut MF_DisplayCriticalError("MAILFILTER: Loading THREADS.NLM for NWSNUT.\n"); LoadModule(0, "THREADS.NLM", 0); if (!_mf_nutinit2(tagID)) #endif { MF_DisplayCriticalError("MAILFILTER: Error initializing NWSNUT!\n"); return false; } } memset(szTemp,' ',81); sprintf(szTemp," MailFilter Server"); #ifdef MAILFILTER_VERSION_BETA char* szBeta = "** BETA **"; memcpy(szTemp+35,szBeta,strlen(szBeta)); #endif #ifdef _TRACE char* szTrace = "** DEBUG **"; memcpy(szTemp+35,szTrace,strlen(szTrace)); #endif memcpy(szTemp+62,"Version",7); memcpy(szTemp+70,MAILFILTERVERNUM,strlen(MAILFILTERVERNUM)); NWSShowLineAttribute ( 0 , 0 , (_MF_NUTCHAR)szTemp , VINTENSE , 80 , (struct ScreenStruct*)MF_NutInfo->screenID ); return true; } bool MF_NutDeinit(void) { if (MF_NutInfo != NULL) NWSRestoreNut(MF_NutInfo); MF_NutInfo = NULL; return true; } static bool MailFilterApp_Server_InitNut() { if (!MF_NutInit()) return false; LONG statusPortal; statusPortal = NWSCreatePortal( 4, 0, 20, 80, 20, 80, SAVE, NULL, //(unsigned char *)"Application Messages", VNORMAL, SINGLE, VNORMAL, CURSOR_OFF, VIRTUAL, MF_NutInfo); NWSGetPCB(&statusPortalPCB, statusPortal, MF_NutInfo); NWSSelectPortal(statusPortal, MF_NutInfo); NWSClearPortal(statusPortalPCB); NWSDeselectPortal(MF_NutInfo); NWSEnableFunctionKey ( K_F6 , MF_NutInfo ); NWSEnableFunctionKey ( K_F7 , MF_NutInfo ); NWSEnableFunctionKey ( K_F8 , MF_NutInfo ); NWSEnableFunctionKey ( K_F9 , MF_NutInfo ); NWSEnableFunctionKey ( K_F10 , MF_NutInfo ); NWSEnableInterruptKey ( K_F6 , *MF_NutHandlerKeyF6, MF_NutInfo ); NWSEnableInterruptKey ( K_F7 , *MF_NutHandlerKeyF7, MF_NutInfo ); NWSEnableInterruptKey ( K_F8 , *MF_NutHandlerKeyF8, MF_NutInfo ); NWSEnableInterruptKey ( K_F9 , *MF_NutHandlerKeyF9, MF_NutInfo ); NWSEnableInterruptKey ( K_F10 , *MF_NutHandlerKeyF10, MF_NutInfo ); // debug key NWSEnableFunctionKey ( K_F2 , MF_NutInfo ); NWSEnableInterruptKey ( K_F2 , *MF_NutHandlerKeyF2, MF_NutInfo ); return true; } // // NUT: Prompt User To Unload NLM // static int MF_NutVerifyExit(void) { signed int cCode = 0; BYTE kKey; LONG kType; if (MF_NutInfo == NULL) return 0; MFT_NUT_GetKey = false; MF_NutMutexQueryUser = 1; char szTemp[82]; for (int i=0;i<81;i++) szTemp[i]=' '; szTemp[80]=0; strncpy(szTemp,MF_Msg(MENU_MAIN_EXIT),75); NWSShowLineAttribute ( 24, 0, (_MF_NUTCHAR) szTemp, VREVERSE /*VINTENSE*/, 80, (struct ScreenStruct*)MF_NutInfo->screenID); while (cCode == 0) { NWSGetKey ( &kType, &kKey, MF_NutInfo); if (kType == K_ESCAPE) cCode = -2; if (kKey == K_SELECT) cCode = -1; if (kType == K_ESCAPE) cCode = -2; if (kKey == K_SELECT) cCode = -1; if (kKey == 121) // y cCode = -1; if (kKey == 110) // n cCode = -2; if (kKey == 89) // Y cCode = -1; if (kKey == 78) // N cCode = -2; } MF_NutMutexQueryUser = 0; MFT_NUT_GetKey = true; MF_StatusUI_Update(NULL); if (cCode == -2) return 0; //NO if (cCode == -1) return 1; //YES return 0; } inline void MF_StatusUI_UpdateLog(int newText) { MF_StatusUI_UpdateLog(MF_Msg(newText)); } void MF_StatusUI_UpdateLog(const char* newText) { char szTemp[82]; // Update Status (History) Window for (int i=0;i<81;i++) szTemp[i]=' '; szTemp[80]=0; time(&tmp_Time); tmp_TimeTM = *localtime (&tmp_Time); sprintf(szTemp,"%02d:%02d:%02d ",tmp_TimeTM.tm_hour,tmp_TimeTM.tm_min,tmp_TimeTM.tm_sec); strncat(szTemp , newText , 69 ); szTemp[80]=0; ThreadSwitch(); NWSScrollPortalZone ( 0L, //LONG Line 0L, //LONG Columns 22L, //Height 78, //Width VNORMAL, //LONG attribute, 1L, //LONG count, V_UP, //LONG direction, statusPortalPCB); ThreadSwitch(); NWSShowPortalLine(17, 0, (_MF_NUTCHAR) szTemp, strlen(szTemp), statusPortalPCB); ThreadSwitch(); NWSUpdatePortal(statusPortalPCB); } // 0 1 2 3 static char cStatus[] = { '|','/','-','\\' }; extern unsigned int MFT_SleepTimer; // // NUT: Update Status Line // void MF_StatusUI_Update(const char* newText) { #pragma unused(newText) char szTemp[90]; int i; if (!MF_NutMutexQueryUser) { // Update Function-Key-Text Line ... for (i=0;i<81;i++) { szTemp[i]=' '; } szTemp[80]=0; if (MFT_NLM_Exiting == 0) { strncpy(szTemp,MF_Msg(STATUS_STATISTICS),79); NWSShowLineAttribute ( 24, 0, (_MF_NUTCHAR) szTemp, VREVERSE /*VINTENSE*/, 80, (struct ScreenStruct*)MF_NutInfo->screenID); } } // Update Statistics in top of NUT screen if (!MFT_NLM_Exiting) { static unsigned long lastClck; static int iStatusChar; std::string szDynamic; unsigned int chk; bool bHaveFeatures = false; #ifdef __NOVELL_LIBC__ if ( MF_GlobalConfiguration->RequireAVA && (MailFilter_AV_Check() != 0) && MFT_bTriedAVInit) { // // for (i=0;i<81;i++) // szTemp[i]=' '; // szTemp[80]=0; // NWSShowLineAttribute( 1, 0, (_MF_NUTCHAR) szTemp, VBLINK, strlen(szTemp), (struct ScreenStruct*)MF_NutInfo->screenID); // NWSShowLineAttribute( 2, 0, (_MF_NUTCHAR) szTemp, VBLINK, strlen(szTemp), (struct ScreenStruct*)MF_NutInfo->screenID); // NWSShowLineAttribute( 3, 0, (_MF_NUTCHAR) szTemp, VBLINK, strlen(szTemp), (struct ScreenStruct*)MF_NutInfo->screenID); strcpy(szTemp,"NO AntiVirus NLM DETECTED - NO E-MAIL TRANSPORT"); FillScreenArea(getscreenhandle(),1,0,3,80,' ',COLOR_ATTR_YELLOW); DisplayScreenTextWithAttribute(getscreenhandle(),2,((80-strlen(szTemp))/2)-1,strlen(szTemp),COLOR_ATTR_YELLOW,szTemp); } else { #endif unsigned long clck = clock() / CLOCKS_PER_SEC; if (lastClck != clck) { lastClck = clck; ++iStatusChar; if (iStatusChar > 3) iStatusChar = 0; } clck = clck / 60; unsigned long days = clck / 24 / 60; unsigned long hours = (clck - (days * 24 * 60)) / 60; unsigned long minutes = clck - (days * 24 * 60) - (hours * 60); sprintf(szTemp,MF_Msg(MSG_INFOPORTAL_LINE1), days,hours,minutes); chk = MF_GlobalConfiguration->DomainHostname.length(); if (chk>55) chk=55; memcpy(szTemp+2,MF_GlobalConfiguration->DomainHostname.c_str(),chk); NWSShowLineAttribute( 1, 0, (_MF_NUTCHAR) szTemp, VNORMAL, strlen(szTemp), (struct ScreenStruct*)MF_NutInfo->screenID); sprintf(szTemp,MF_Msg(MSG_INFOPORTAL_LINE2),MFS_MF_MailsInputTotal,MFS_MF_MailsInputFailed); if ( MF_GlobalConfiguration->RequireAVA && !MFT_bTriedAVInit && MFL_GetFlag(MAILFILTER_MC_M_VIRUSSCAN) ) { szDynamic = "Waiting for AntiVirus NLM"; } else { szDynamic = "Running "; szDynamic += cStatus[iStatusChar]; } memcpy(szTemp+2,szDynamic.c_str(),szDynamic.length()); NWSShowLineAttribute( 2, 0, (_MF_NUTCHAR) szTemp, VNORMAL, strlen(szTemp), (struct ScreenStruct*)MF_NutInfo->screenID); sprintf(szTemp,MF_Msg(MSG_INFOPORTAL_LINE3),MFS_MF_MailsOutputTotal,MFS_MF_MailsOutputFailed); szDynamic = "Modules: "; #ifdef MF_WITH_ZIP bHaveFeatures = true; szDynamic += "ZIP "; #endif if (MFC_MAILSCAN_Enabled) { szDynamic += "Decode "; bHaveFeatures = true; } if (MFBW_CheckCurrentScheduleState() == false) { szDynamic += "Schedule "; bHaveFeatures = true; } if (MailFilter_AV_Check() == 0) { szDynamic += "AV "; bHaveFeatures = true; } if (MF_GlobalConfiguration->NRMInitialized == true) { szDynamic += "NRM "; bHaveFeatures = true; } if (!bHaveFeatures) szDynamic += "None"; memcpy(szTemp+2,szDynamic.c_str(),szDynamic.length()); NWSShowLineAttribute( 3, 0, (_MF_NUTCHAR) szTemp, VNORMAL, strlen(szTemp), (struct ScreenStruct*)MF_NutInfo->screenID); #ifdef __NOVELL_LIBC__ } #endif } return; } #ifndef _MF_CLEANBUILD void MFD_UseMainScreen() { if (MFD_ScreenID) #ifdef __NOVELL_LIBC__ CloseScreen ( MFD_ScreenID ); #else DestroyScreen ( MFD_ScreenID ); #endif MFD_ScreenID = NULL; } #ifndef COLOR_ATTR_NONE extern "C" { int vsnprintf( char * restrict, size_t n, const char * restrict, va_list ); } // borrowed from LibC's screen.h /* attributes for OutputToScreenWithAttributes(); cf. HTML color names */ #define COLOR_ATTR_NONE 0 /* (black, no color at all) */ #define COLOR_ATTR_NAVY 1 /* (dim blue) */ #define COLOR_ATTR_BLUE (0x01|8) #define COLOR_ATTR_GREEN 2 #define COLOR_ATTR_LIME (0x02|8) /* (bright green) */ #define COLOR_ATTR_TEAL 3 /* (dim cyan) */ #define COLOR_ATTR_CYAN (0x03|8) #define COLOR_ATTR_MAROON 4 /* (dim red) */ #define COLOR_ATTR_RED (0x04|8) #define COLOR_ATTR_PURPLE 5 #define COLOR_ATTR_MAGENTA (0x05|8) /* (bright purple) */ #define COLOR_ATTR_OLIVE 6 /* (brown, dim yellow) */ #define COLOR_ATTR_YELLOW (0x06|8) #define COLOR_ATTR_SILVER 7 /* normal white, dim/unhighlighted */ #define COLOR_ATTR_GREY 8 /* (dimmed white) */ #define COLOR_ATTR_WHITE 15 /* bright, highlighted white */ #endif void MFD_Out_func(int source, const char* fmt, ...) { va_list argList; unsigned char attr = 0; if (!chkFlag(MFT_Debug,source)) return; switch (source) { case MFD_SOURCE_GENERIC: { attr = COLOR_ATTR_SILVER; break; } case MFD_SOURCE_WORKER: { attr = COLOR_ATTR_CYAN; break; } case MFD_SOURCE_CONFIG: { attr = COLOR_ATTR_GREEN; break; } case MFD_SOURCE_VSCAN: { attr = COLOR_ATTR_LIME; break; } case MFD_SOURCE_ZIP: { attr = COLOR_ATTR_TEAL; break; } case MFD_SOURCE_ERROR: { attr = COLOR_ATTR_RED; break; } case MFD_SOURCE_RULE: { attr = COLOR_ATTR_YELLOW; break; } case MFD_SOURCE_MAIL: { attr = COLOR_ATTR_PURPLE; break; } case MFD_SOURCE_SMTP: { attr = COLOR_ATTR_WHITE; break; } default: { attr = COLOR_ATTR_GREY; break; } } va_start(argList, fmt); #ifndef __NOVELL_LIBC__ int oldScreen = 0; if (MFD_ScreenID) oldScreen=SetCurrentScreen((int)MFD_ScreenID); vprintf(fmt, argList); if (oldScreen) SetCurrentScreen(oldScreen); #else char buffer[5000]; vsnprintf(buffer,4999,fmt,argList); buffer[4999] = 0; #ifdef _TRACE MF_DisplayCriticalError("%s",buffer); #else // MF_UseMainScreen() support if (MFD_ScreenID) OutputToScreenWithAttribute(MFD_ScreenID,attr,"%s",buffer); else OutputToScreenWithAttribute(MF_ScreenID,attr,"%s",buffer); #endif #endif va_end (argList); } #endif //!_MF_CLEANBUILD // // Event Handler For Server ShutDown // // * Tell NLM to unload. Nothing special ... // void eventShutDownReport(LONG par1,LONG par2) { MF_StatusText(MF_Msg(MSG_CLOSEFILES)); MFT_NLM_Exiting = 255; MF_StatusFree(); par1 = par1; par2 = par2; // Get rid of compiler warnings ;) } // // Event Handler For Server ShutDown // // * Tell NLM to unload. Nothing special ... // LONG eventShutDownWarn(void (*OutPutFunc)(const void *fmt,...),LONG par1,LONG par2) { #pragma unused (OutPutFunc) // Warning: DO NOT do anything to the parameters passed, DO NOT call OutPutFunc ... // OutPutFunc("MAILFILTER: Will Terminate Worker Thread on Server Shut Down.\n"); par1=par1; par2=par2; return 0; // Simply Allow Shutdown ... } void NLM_SignalHandler(int sig) { #ifndef __NOVELL_LIBC__ int handlerThreadGroupID; #endif switch(sig) { case SIGTERM: { MFT_NLM_Exiting = 255; #ifndef __NOVELL_LIBC__ if (MF_Thread_Work > 0) ResumeThread(MF_Thread_Work); if (MF_Thread_SMTP > 0) ResumeThread(MF_Thread_SMTP); handlerThreadGroupID = GetThreadGroupID(); SetThreadGroupID(mainThread_ThreadGroupID); #endif // NLM SDK functions may be called here // We need this to wake the UI thread up ... #ifndef __NOVELL_LIBC__ if (MF_NutInfo != NULL) { NWSUngetKey ( K_ESCAPE , 0 , MF_NutInfo ); } SetThreadGroupID(handlerThreadGroupID); #else ungetcharacter(27); if ( (MF_GlobalConfiguration->ApplicationMode == MailFilter_Configuration::NRM) || (MF_GlobalConfiguration->NRMInitialized == true) ) { MailFilter_NRM_sigterm(); } #endif while (MFT_NLM_ThreadCount > 0) { // wait for MailFilter threads to terminate NXThreadYield(); } } break; case SIGINT: { // ignore CTRL-C signal(SIGINT, NLM_SignalHandler); break; } } return; } #ifdef _MF_MEMTRACE static void _mfd_tellallocccountonexit() { MF_DisplayCriticalError("MAILFILTER: AllocCount: %d\n",MFD_AllocCounts); } #endif //_MF_MEMTRACE static void MF_Cleanup_Startup(void *dummy) { #pragma unused(dummy) // Rename this Thread #if defined( N_PLAT_NLM ) && (defined(__NOVELL_LIBC__)) NXContextSetName(NXContextGet(),"MailFilterCleaner"); #endif MFT_NLM_ThreadCount++; unsigned long counter = 0; MF_CheckProblemDirAgeSize(); while (MFT_NLM_Exiting == 0) { ++counter; if (counter > (2*3600)) // wait two hours between checks. { counter = 0; MF_CheckProblemDirAgeSize(); } delay(1000); NXThreadYield(); } MFT_NLM_ThreadCount--; MF_DisplayCriticalError("MAILFILTER: CleanerThread: Terminated.\n"); } static void LoadNRMThreadStartup(void *dummy) { #pragma unused(dummy) MF_GlobalConfiguration->NRMInitialized = true; MailFilter_Main_RunAppNRM(false); } // // // NLM Application Startup Function: // SERVER // // * Start Thread(s) ... // * Run NUT in foreground thread. // static int MailFilter_Main_RunAppServer(const char* szProgramName) { int rc = 0; // Init NWSNut printf(MF_Msg(MSG_BOOT_USERINTERFACE)); if (!MailFilterApp_Server_InitNut()) { MF_DisplayCriticalError("MAILFILTER: Error communicating with NWSNUT. Terminating!\n"); goto MF_MAIN_TERMINATE; } ThreadSwitch(); if (!MailFilterApp_Server_LoginToServer()) { MF_DisplayCriticalError("MAILFILTER: Error logging into the Server. Terminating!\n"); goto MF_MAIN_TERMINATE; } if (!MailFilterApp_Server_SelectUserConnection()) { MF_DisplayCriticalError("MAILFILTER: Error selecting server connection. Terminating!\n"); goto MF_MAIN_TERMINATE; } ThreadSwitch(); MF_MAIN_RUNLOOP: { // needed for mf restart MFT_NLM_Exiting = 0; MFT_bStartupComplete = false; MFD_Out(MFD_SOURCE_GENERIC,"Initializing Logging...\n"); // Init Status if (!MF_StatusInit()) { MF_DisplayCriticalError("MAILFILTER: Error initializing Logging. Terminating!\n"); goto MF_MAIN_TERMINATE; } // get OS info { char szStatusMsg[82]; #ifndef __NOVELL_LIBC__ struct utsname un; MF_StatusLog("MailFilter CLIB Version "MAILFILTERVERNUM); uname(&un); sprintf(szStatusMsg,"Operating System: Novell NetWare %s.%s",un.release,un.version); MF_StatusText(szStatusMsg); MF_StatusText("MFLT50: Limited Functionality MailFilter."); MF_StatusText("Please upgrade to a modern NetWare OS to get full functionality!"); #else MF_StatusLog("MailFilter LIBC Version "MAILFILTERVERNUM); struct utsname u; uname(&u); sprintf(szStatusMsg,"Operating System: Novell NetWare %d.%d SP %d", u.netware_major, u.netware_minor, u.servicepack); MF_StatusText(szStatusMsg); #endif } ThreadSwitch(); MF_StatusUI_Update(MF_Msg(MSG_BOOT_LOADING)); MFWorker_SetupPaths(); strncpy(MFL_LicenseKey,MF_GlobalConfiguration->LicenseKey.c_str(),MF_GlobalConfiguration->LicenseKey.size() > MAX_PATH ? MAX_PATH : MF_GlobalConfiguration->LicenseKey.size() ); // Start Thread: ** WORK ** #ifdef __NOVELL_LIBC__ NXContext_t ctxWorker; if (NXThreadCreateSx( MF_Work_Startup , NULL, NX_THR_JOINABLE|NX_THR_BIND_CONTEXT , &ctxWorker , &MF_Thread_Work )) #else MF_Thread_Work = BeginThread(MF_Work_Startup,NULL,2*65536,NULL); // Set 64k Stack for new thread if( MF_Thread_Work == EFAILURE ) #endif { MF_DisplayCriticalError(MF_Msg(CONMSG_MAIN_ERRTHREADSTART)); MF_Thread_Work = 0; goto MF_MAIN_TERMINATE; } // Start Thread: ** Cleanup ** #ifdef __NOVELL_LIBC__ NXContext_t ctxCleanup; if (NXThreadCreateSx( MF_Cleanup_Startup , NULL, NX_THR_JOINABLE|NX_THR_BIND_CONTEXT , &ctxCleanup , &MF_Thread_Cleanup )) #else MF_Thread_Cleanup = BeginThread(MF_Cleanup_Startup,NULL,2*65536,NULL); // Set 64k Stack for new thread if( MF_Thread_Cleanup == EFAILURE ) #endif { MF_DisplayCriticalError(MF_Msg(CONMSG_MAIN_ERRTHREADSTART)); MF_Thread_Cleanup = 0; goto MF_MAIN_TERMINATE; } if (MF_GlobalConfiguration->EnableNRMThread == true) { #ifdef __NOVELL_LIBC__ if (!mf_nlmisloadedprotected()) { MFD_Out(MFD_SOURCE_CONFIG,"NRM thread will be started.\n"); // Start Thread: ** NRM ** #ifdef __NOVELL_LIBC__ NXContext_t ctxNrm; if (NXThreadCreateSx( LoadNRMThreadStartup , NULL, NX_THR_JOINABLE|NX_THR_BIND_CONTEXT, &ctxNrm, &MF_Thread_NRM )) #else MF_Thread_NRM = BeginThread(LoadNRMThreadStartup,NULL,2*65536,NULL); // Set 64k Stack for new thread if( MF_Thread_NRM == EFAILURE ) #endif { //MF_DisplayCriticalError(MF_Msg(CONMSG_MAIN_ERRTHREADSTART)); MF_StatusText("ERROR: NRM Startup Error. NRM NOT loaded."); MF_Thread_NRM = 0; // goto MF_MAIN_TERMINATE; } } else { MF_StatusText("Loading NRM out-of-process."); std::string loadCmd = "LOAD "; loadCmd += szProgramName; loadCmd += " -t nrm "; loadCmd += MF_GlobalConfiguration->config_directory; system(loadCmd.c_str()); } #else MF_StatusText("NOTE: NRM is not available for MFLT50."); #endif } /* #ifndef _MF_CLEANBUILD MFD_Out("Starting SMTP Thread...\n"); // SMTP is enabled only in debug mode as this is not yet released. if (MFT_Debug) { // Start Thread: ** SMTP ** MF_Thread_SMTP = BeginThread(MF_SMTP_Startup,NULL,65536,NULL); // Set 64k Stack for new thread if( MF_Thread_SMTP == EFAILURE ) { MF_DisplayCriticalError(MF_Msg(CONMSG_MAIN_ERRTHREADSTART)); MF_Thread_SMTP = 0; goto MF_MAIN_TERMINATE; } } #endif */ // Allow a Thread Switch to occour - start the worker! ThreadSwitch(); /* check Filter Rules for RE errors */ { unsigned int curItem = 0; for (curItem = 0; curItem < MF_GlobalConfiguration->filterList.size(); curItem++) { if (MF_GlobalConfiguration->filterList[(unsigned int)curItem].expression == "") break; switch(MF_GlobalConfiguration->filterList[curItem].matchfield) { /* these fields dont have regular exprs */ case MailFilter_Configuration::size: case MailFilter_Configuration::archiveContentCount: case MailFilter_Configuration::blacklist: case MailFilter_Configuration::ipUnresolvable: case MailFilter_Configuration::virus: break; default: { int rc = -99; pcre *re; const char *error; int erroffset; re = pcre_compile( MF_GlobalConfiguration->filterList[(unsigned int)curItem].expression.c_str(), /* the pattern */ PCRE_UTF8, /* default options + UTF8 */ &error, /* for error message */ &erroffset, /* for error offset */ NULL); /* use default character tables */ if (re == NULL) { // TODO: Add a message to the log/screen MFD_Out(MFD_SOURCE_REGEX,"Rule #%d is broken, please fix!\n->%s\n->Error: %s (offset: %d)\n", curItem, MF_GlobalConfiguration->filterList[(unsigned int)curItem].expression.c_str(), error, erroffset); } else pcre_free(re); ThreadSwitch(); } } } } // Lie that we've already exited ... --MFT_NLM_ThreadCount; MF_StatusUI_Update(MF_Msg(MSG_BOOT_COMPLETE)); MFD_Out(MFD_SOURCE_GENERIC,"Startup Complete.\n"); // LONG tmp_Key_Type; BYTE tmp_Key_Value; // Don't exit thread until all other threads are terminated ... while ( (MFT_NLM_ThreadCount > 0) || (!MFT_bStartupComplete) ) { if (MFT_NLM_Exiting > 0) break; ThreadSwitch(); if (MFT_NUT_GetKey) { NWSGetKey ( &tmp_Key_Type, &tmp_Key_Value, MF_NutInfo ); } } // 254 = restart // 253 = config // 252 = restore if ((MFT_NLM_Exiting == 254) || (MFT_NLM_Exiting == 253) || (MFT_NLM_Exiting == 252)) { bool bDoConfig = false; if (MFT_NLM_Exiting == 253) bDoConfig = true; bool bDoRestore = false; if (MFT_NLM_Exiting == 252) bDoRestore = true; MF_StatusText(" Please wait ... (may take a few minutes)"); NXThreadYield(); #ifndef __NOVELL_LIBC__ if (MF_Thread_Work > 0) ResumeThread(MF_Thread_Work); if (MF_Thread_SMTP > 0) ResumeThread(MF_Thread_SMTP); #else if (MF_Thread_Work > 0) NXThreadContinue (MF_Thread_Work); if (MF_Thread_SMTP > 0) NXThreadContinue (MF_Thread_SMTP); if ( MF_GlobalConfiguration->NRMInitialized == true ) { MFD_Out(MFD_SOURCE_CONFIG,"shutting down NRM thread\n"); MailFilter_NRM_sigterm(); } else { if (mf_nlmisloadedprotected()) { MF_DisplayCriticalError("MAILFILTER: Unloading NRM/OS agent [%s].\n",szProgramName); char szCmdLine[MAX_PATH]; sprintf(szCmdLine,"UNLOAD ADDRESS SPACE = OS %s",szProgramName); system(szCmdLine); //TODO ActivateScreen } } #endif MFT_NLM_Exiting = 255; // wait for other threads to exit // we lied above, anyway. while (MFT_NLM_ThreadCount > 0) NXThreadYield(); MFT_NLM_Exiting = 0; MF_StatusFree(); MF_NutDeinit(); ThreadSwitch(); // ok... here we go: // * reinit config // Read Configuration from File if (!MF_GlobalConfiguration->ReadFromFile("")) { MF_DisplayCriticalError("MAILFILTER: Restart failed\n"); MF_DisplayCriticalError("\tConfiguration Module reported an unrecoverable error.\n"); goto MF_MAIN_TERMINATE; } if (bDoConfig == true) { // reconfigure mf MailFilter_Main_RunAppConfig(false); // * reinit config // Read Configuration from File if (!MF_GlobalConfiguration->ReadFromFile("")) { MF_DisplayCriticalError("MAILFILTER: Restart failed\n"); MF_DisplayCriticalError("\tConfiguration Module reported an unrecoverable error.\n"); goto MF_MAIN_TERMINATE; } } if (bDoRestore == true) { // open restore list MailFilter_Main_RunAppRestore(false); } if (!MailFilterApp_Server_InitNut()) { MF_DisplayCriticalError("MAILFILTER: Restart failed\n"); MF_DisplayCriticalError("\tUI Module reported an unrecoverable error.\n"); goto MF_MAIN_TERMINATE; } // increase thread count so we can decrease it above again. ++MFT_NLM_ThreadCount; goto MF_MAIN_RUNLOOP; } } rc = 666; MF_MAIN_TERMINATE: MailFilterApp_Server_LogoutFromServer(); return rc; } // // Main NLM Function // // * Startup // * Read Configuration // * Run the selected MF app // int main( int argc, char *argv[ ]) { ++MFT_NLM_ThreadCount; MF_NutInfo = NULL; MF_ScreenID = NULL; __init_malloc(); printf("MailFilter is starting...\n"); /* useless certification stuff */ /* try { throw std::bad_alloc(); } catch (...) {} try { throw std::bad_exception(); } catch (...) {} try { throw std::exception(); } catch (...) {} try { throw std::logic_error("a"); } catch (...) {} try { throw std::length_error("a"); } catch (...) {} try { throw std::out_of_range("a"); } catch (...) {} */ // try { MF_GlobalConfiguration = NULL; MF_GlobalConfiguration = new MailFilter_Configuration::Configuration(); #ifdef _MF_MEMTRACE atexit(_mfd_tellallocccountonexit); #endif //_MF_MEMTRACE MF_ProductName = "MailFilter professional "MAILFILTERVERNUM" ["MAILFILTERPLATFORM"]"; printf("%s\n",MF_ProductName); #ifndef __NOVELL_LIBC__ // Save Thread Group mainThread_ThreadGroupID = GetThreadGroupID(); // Rename UI Thread RenameThread( GetThreadID() , MF_Msg(MSG_THREADNAME_MAIN) ); MF_DisplayCriticalError("MAILFILTER: Info: This is the Legacy version of MailFilter!\n\tUse only on NetWare 5.0, NetWare 5.1 prior SP6 or NetWare 6.0 prior SP3.\n"); #else NXContextSetName(NXContextGet(),"MailFilterUI"); { struct utsname u; uname(&u); if ( (u.netware_major == 6) && (u.netware_minor == 0) && (u.servicepack < 2) ) { MF_DisplayCriticalError("MAILFILTER: Detected NetWare 6.0 prior to SP3.\n\tPlease upgrade to a newer version or use the legacy MFLT50.NLM\n"); return 0; } if ( (u.netware_major == 5) && (u.netware_minor == 1) && (u.servicepack < 6) ) { MF_DisplayCriticalError("MAILFILTER: Detected NetWare 5.1 prior to SP6.\n\tPlease upgrade to a newer version or use the legacy MFLT50.NLM\n"); return 0; } if ( (u.netware_major == 5) && (u.netware_minor == 0) ) { MF_DisplayCriticalError("MAILFILTER: Detected NetWare 5.0.\n\tPlease upgrade to a newer version or use the legacy MFLT50.NLM\n"); return 0; } } #endif ThreadSwitch(); int rc = 0; // put this here extern int MF_ParseCommandLine( int argc, char **argv ); // Parse Command Line and build some vars... if (!MF_ParseCommandLine(argc,argv)) goto MF_MAIN_TERMINATE; if (MFT_Debug) { // set up stderr redirection fclose(stderr); stderr = fopen("sys:\\mferr.log","w"); // done. } ThreadSwitch(); // Get NLM and Screen Handles #ifdef __NOVELL_LIBC__ MFD_ScreenTag = NULL; MF_NLMHandle = getnlmhandle(); MF_ScreenID = getscreenhandle(); setscreenmode(SCR_AUTOCLOSE_ON_EXIT|0x00000002); #else MF_NLMHandle = GetNLMHandle(); MF_ScreenID = GetCurrentScreen(); SetCtrlCharCheckMode(false); SetAutoScreenDestructionMode(true); #endif // debug screen if (MFT_Debug) { extern bool MF_NLM_OpenDebugScreen(); if (!MF_NLM_OpenDebugScreen()) { MF_DisplayCriticalError("MAILFILTER: Unable to create debug screen!\n"); goto MF_MAIN_TERMINATE; } } // Register Exit Proc ... #ifndef __NOVELL_LIBC__ atexit(MF_ExitProc); #endif signal( SIGTERM , NLM_SignalHandler ); signal( SIGINT , NLM_SignalHandler ); ThreadSwitch(); unlink("SYS:\\SYSTEM\\MFINST.NLM"); unlink("SYS:\\SYSTEM\\MFREST.NLM"); unlink("SYS:\\SYSTEM\\MFNRM.NLM"); unlink("SYS:\\SYSTEM\\MFUPGR.NLM"); printf("startup...\n"); switch (MF_GlobalConfiguration->ApplicationMode) { case MailFilter_Configuration::SERVER: #ifdef __NOVELL_LIBC__ NXContextSetName(NXContextGet(),"MailFilterServer"); #endif // Read Configuration from File printf(MF_Msg(MSG_BOOT_CONFIGURATION)); MF_GlobalConfiguration->config_mode_strict = true; if (!MF_GlobalConfiguration->ReadFromFile("")) { MF_DisplayCriticalError("MAILFILTER: Could not read configuration. Terminating!\n"); goto MF_MAIN_TERMINATE; } printf("Starting Server Application...\n"); rc = MailFilter_Main_RunAppServer(argv[0]); break; case MailFilter_Configuration::CONFIG: #ifdef __NOVELL_LIBC__ NXContextSetName(NXContextGet(),"MailFilterConfig"); #endif // Read Configuration from File printf(MF_Msg(MSG_BOOT_CONFIGURATION)); MF_GlobalConfiguration->config_mode_strict = false; if (!MF_GlobalConfiguration->ReadFromFile("")) { MF_DisplayCriticalError("MAILFILTER: Could not read configuration. Terminating!\n"); goto MF_MAIN_TERMINATE; } --MFT_NLM_ThreadCount; rc = MailFilter_Main_RunAppConfig(true); break; case MailFilter_Configuration::RESTORE: #ifdef __NOVELL_LIBC__ NXContextSetName(NXContextGet(),"MailFilterRestore"); #endif // Read Configuration from File printf(MF_Msg(MSG_BOOT_CONFIGURATION)); MF_GlobalConfiguration->config_mode_strict = true; if (!MF_GlobalConfiguration->ReadFromFile("")) { MF_DisplayCriticalError("MAILFILTER: Could not read configuration. Terminating!\n"); goto MF_MAIN_TERMINATE; } --MFT_NLM_ThreadCount; rc = MailFilter_Main_RunAppRestore(true); rc = 0; break; case MailFilter_Configuration::NRM: #ifdef __NOVELL_LIBC__ NXContextSetName(NXContextGet(),"MailFilterNRM"); // Read Configuration from File printf(MF_Msg(MSG_BOOT_CONFIGURATION)); MF_GlobalConfiguration->config_mode_strict = true; if (!MF_GlobalConfiguration->ReadFromFile("")) { MF_DisplayCriticalError("MAILFILTER: Could not read configuration. Terminating!\n"); goto MF_MAIN_TERMINATE; } --MFT_NLM_ThreadCount; rc = MailFilter_Main_RunAppNRM(true); #else rc = -1; MF_DisplayCriticalError("MAILFILTER: NRM is not available for MFLT50. Please Upgrade!\n"); #endif break; case MailFilter_Configuration::INSTALL: MFD_UseMainScreen(); printf(" MailFilter_Configuration::INSTALL kick off!\n"); MF_GlobalConfiguration->CreateFromInstallFile(MF_GlobalConfiguration->config_directory + "\\INSTALL.CFG"); printf(" Saving new configuration to file...\n"); MF_GlobalConfiguration->WriteToFile(""); printf(" MailFilter_Configuration::INSTALL complete!\n"); #ifdef __NOVELL_LIBC__ if (MFT_Debug) pressenter(); #endif break; case MailFilter_Configuration::UPGRADE: MFD_UseMainScreen(); printf(" MailFilter_Configuration::UPGRADE kick off!\n"); MF_GlobalConfiguration->config_mode_strict = false; MF_GlobalConfiguration->ReadFromFile(""); printf(" Saving new configuration to file...\n"); MF_GlobalConfiguration->WriteToFile(""); printf(" MailFilter_Configuration::UPGRADE complete!\n"); #ifdef __NOVELL_LIBC__ if (MFT_Debug) pressenter(); #endif break; default: MF_DisplayCriticalError("MAILFILTER: Could not run your selected application.\n\tMaybe it is not compiled-in.\n"); rc = -1; break; } extern char* MFT_Local_ServerName; if (MFT_Local_ServerName != NULL) { _mfd_free(MFT_Local_ServerName,"Config:LocalServer"); } MF_MAIN_TERMINATE: return rc; /* } catch (std::exception e) { MF_DisplayCriticalError("MAILFILTER: Uncaught Exception: %s\n",e.what()); } */ } #endif // N_PLAT_NLM /* * --- eof --- */
[ [ [ 1, 1608 ] ] ]
be9f5c6049034e3b8539f0a56fe26c1b8296ce27
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/robots/qrgui/interpreters/robots/details/blocks/enginesStopBlock.cpp
4570be3cdd48474d691da0b81c366e2a3983bf56
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
#include "enginesStopBlock.h" using namespace qReal; using namespace interpreters::robots::details::blocks; EnginesStopBlock::EnginesStopBlock(robotParts::Motor &motor1, robotParts::Motor &motor2, robotParts::Motor &motor3) : EngineCommandBlock(motor1, motor2, motor3) { } void EnginesStopBlock::run() { QVector<bool> ports = parsePorts(); if (ports[0]) mMotor1.off(); if (ports[1]) mMotor2.off(); if (ports[2]) mMotor3.off(); emit done(mNextBlock); }
[ [ [ 1, 21 ] ] ]
552a32873cddb3142ca62d98e338c84165888e8b
b369aabb8792359175aedfa50e949848ece03180
/src/glWin/DialogWindow.h
df285b887a42229374d46a1c8c995eafd18a7db2
[]
no_license
LibreGamesArchive/magiccarpet
6d49246817ab913f693f172fcfc53bf4cc153842
39210d57096d5c412de0f33289fbd4d08c20899b
refs/heads/master
2021-05-08T02:00:46.182694
2009-01-06T20:25:36
2009-01-06T20:25:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,904
h
/////////////////////////////////////////////////////////////////////////////// // DialogWindow.h // ============== // A class of Dialog Box for MS Windows // It creates a dialog box with CreateDialogParam() API call. // // AUTHOR: Song Ho Ahn // CREATED: 2005-03-16 // UPDATED: 2006-06-20 /////////////////////////////////////////////////////////////////////////////// #ifndef WIN_DIALOG_WINDOW_H #define WIN_DIALOG_WINDOW_H #include <windows.h> #include "Controller.h" namespace Win { class DialogWindow { public: // ctor/dtor with minimal args // The second param, id should be the template ID of a dialog in resource.rc(IDD_*). DialogWindow(HINSTANCE hInst, WORD id, HWND hParent, Controller* ctrl); ~DialogWindow(); HWND create(); // create a dialog void show(int cmdShow=SW_SHOWDEFAULT); // make the window visible or invisible HWND getHandle() { return handle; }; // return dialog window handle // setters void setPosition(int _x, int _y) { x = _x; y = _y; }; void setWidth(int w) { width = w; }; void setHeight(int h) { height = h; }; private: HWND handle; // handle to this window HWND parentHandle; // handle to parent window WORD id; int x; // window position X int y; // window position Y int width; // window width int height; // window height HINSTANCE instance; // handle to instance Win::Controller *controller; // pointer to controller }; } #endif
[ [ [ 1, 52 ] ] ]
51ffbf31e5e663ac9e47d63c376d381e0a7e2e00
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/HUD/HUDPowerStruggle.h
4c25ce1815a0c2996e9c1f9aec0b01d27b92772d
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
5,819
h
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2007. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: PowerStruggle mode HUD (BuyMenu) code (refactored from old HUD code) ------------------------------------------------------------------------- History: - 21:02:20067 20:00 : Created by Jan Müller *************************************************************************/ #ifndef HUD_POWER_STRUGGLE_H #define HUD_POWER_STRUGGLE_H # pragma once #include "HUDObject.h" #include "HUD.h" class CGameFlashAnimation; class CHUDPowerStruggle : public CHUDObject { friend class CHUD; public: CHUDPowerStruggle(CHUD *pHUD, CGameFlashAnimation *pBuyMenu, CGameFlashAnimation *pHexIcon); ~CHUDPowerStruggle(); void Update(float fDeltaTime); void Reset(); //buyable item types enum EBuyMenuPage { E_WEAPONS = 1 << 0, E_VEHICLES = 1 << 1, E_EQUIPMENT = 1 << 2, E_AMMO = 1 << 3, E_PROTOTYPES = 1 << 4, E_LOADOUT = 1 << 5 }; enum EHexIconState { E_HEX_ICON_NONE, E_HEX_ICON_EXPOSURE, E_HEX_ICON_CAPTURING, E_HEX_ICON_BUY, E_HEX_ICON_BUILDING, E_HEX_ICON_LAST }; struct SItem { string strName; string strDesc; string strClass; string strCategory; int iPrice; float level; int iInventoryID; bool isWeapon; bool isUnique; bool bAmmoType; bool bVehicleType; int iCount; int iMaxCount; bool loadout; bool special; }; struct SEquipmentPack { string strName; int iPrice; std::vector<SItem> itemArray; }; virtual bool IsFactoryType(EntityId entity, EBuyMenuPage type); virtual bool CanBuild(IEntity *pEntity, const char *vehicle); bool IsPlayerSpecial(); void UpdateLastPurchase(); void UpdateBuyZone(bool trespassing, EntityId zone); void UpdateServiceZone(bool trespassing, EntityId zone); void UpdateBuyList(const char *page = NULL); void Scroll(int direction); // Swing-O-Meter interface // sets current client team void SetSOMTeam(int teamId); // hide/unhide SOM void HideSOM(bool hide); void DetermineCurrentBuyZone(bool sendToFlash = false); void GetTeamStatus(int teamId, float &power, float &turretstatus, int &controlledAliens, EntityId &prototypeFactoryId); void ShowCaptureProgress(bool show); void SetCaptureProgress(float progress); void SetCaptureContested(bool contested); void ShowConstructionProgress(bool show, bool queued, float time); ILINE EHexIconState GetCurrentIconState() {return m_currentHexIconState; }; ILINE void SetLastPurchase(const char* itemName) { SItem itemdef; if(GetItemFromName(itemName, itemdef)) { itemdef.iInventoryID = 0; m_thisPurchase.itemArray.push_back(itemdef); m_thisPurchase.iPrice += itemdef.iPrice; } } private: int GetPlayerPP(); int GetPlayerTeamScore(); void Buy(const char* item, bool reload = true); void DeletePackage(int index); void BuyPackage(int index); void BuyPackage(SEquipmentPack equipmentPackage); void InitEquipmentPacks(); void SaveEquipmentPacks(); SEquipmentPack LoadEquipmentPack(int index); void SavePackage(const char *name, int index = -1); void RequestNewLoadoutName(string &name, const char *bluePrint); bool CheckDoubleLoadoutName(const char *name); void CreateItemFromTableEntry(IScriptTable *pItemScriptTable, SItem &item); bool GetItemFromName(const char *name, SItem &item); bool WeaponUseAmmo(CWeapon *pWeapon, IEntityClass* pAmmoType); bool CanUseAmmo(IEntityClass* pAmmoType); void GetItemList(EBuyMenuPage itemType, std::vector<SItem> &itemList, bool buyMenu = true ); void PopulateBuyList(); void UpdatePackageItemList(const char *page); EBuyMenuPage ConvertToBuyList(const char *page); void ActivateBuyMenuTabs(); void UpdatePackageList(); void UpdateCurrentPackage(); void OnSelectPackage(int index); void UpdateModifyPackage(int index); //****************************************** MEMBER VARIABLES *********************************** //current active buy zones std::vector<EntityId> m_currentBuyZones; //current active buy zones std::vector<EntityId> m_currentServiceZones; //standing in buy zone ? Or service zone ? bool m_bInBuyZone; bool m_bInServiceZone; //-2=inactive, -1=catch page, 1-0=catch item on page int m_iCatchBuyMenuPage; //available equipment packs std::vector<SEquipmentPack> m_EquipmentPacks; //items bought between the last buy menu open and buy menu close SEquipmentPack m_lastPurchase; //items bought in a sequence after buy menu open SEquipmentPack m_thisPurchase; //current buy menu page EBuyMenuPage m_eCurBuyMenuPage; //buy menu flash movie - managed by HUD CGameFlashAnimation *g_pBuyMenu; CGameFlashAnimation *g_pHexIcon; //swing-o-meter - managed here CGameFlashAnimation m_animSwingOMeter; //the main hud CHUD *g_pHUD; //currently available buy menu pages std::vector<bool> m_factoryTypes; std::vector<bool> m_serviceZoneTypes; //swing-o-meter setup bool m_nkLeft; //new powerstruggle rules std::vector<EntityId> m_powerpoints; std::vector<EntityId> m_hqs; bool m_gotpowerpoints; EntityId m_protofactory; bool m_capturing; float m_captureProgress; bool m_constructing; bool m_constructionQueued; float m_constructionTime; float m_constructionTimer; int m_lastConstructionTime; int m_lastBuildingTime; EHexIconState m_currentHexIconState; int m_lastTeamCol, m_lastPowerPoints; int m_lastAlienArg1, m_lastAlienArg2; int m_lastPowerArg1, m_lastPowerArg2; wstring m_lastHQArg1, m_lastHQArg2; int m_teamId; }; #endif
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 14 ], [ 21, 31 ], [ 33, 34 ], [ 37, 44 ], [ 57, 63 ], [ 65, 70 ], [ 72, 73 ], [ 76, 87 ], [ 91, 91 ], [ 93, 93 ], [ 95, 101 ], [ 104, 107 ], [ 109, 111 ], [ 124, 131 ], [ 133, 137 ], [ 140, 144 ], [ 146, 148 ], [ 150, 158 ], [ 163, 163 ], [ 165, 168 ], [ 173, 176 ], [ 178, 183 ], [ 186, 190 ], [ 193, 202 ], [ 210, 212 ] ], [ [ 15, 20 ], [ 32, 32 ], [ 35, 36 ], [ 45, 56 ], [ 64, 64 ], [ 71, 71 ], [ 74, 75 ], [ 88, 90 ], [ 92, 92 ], [ 94, 94 ], [ 102, 103 ], [ 108, 108 ], [ 112, 123 ], [ 132, 132 ], [ 138, 139 ], [ 145, 145 ], [ 149, 149 ], [ 159, 162 ], [ 164, 164 ], [ 169, 172 ], [ 177, 177 ], [ 184, 185 ], [ 191, 192 ], [ 203, 209 ], [ 213, 214 ] ] ]
050fc19c5f018a70fd43866cd4faa7c83cd59b92
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/kernelhwsrv/base/performance/f32/t_perf/src/F32PerformanceServer.cpp
f5667ad818dcc182d6575bba899021696e71673e
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
3,685
cpp
/* * Copyright (c) 2007 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 "F32PerformanceServer.h" #include "EntryStep.h" #include "ReadFileStep.h" #include "SeekFileStep.h" #include "WriteFileStep.h" #include "UtilsCleanupStep.h" #include "UtilsSetupStep.h" // Function : CT_F32PerformanceServer // Description :CT_F32PerformanceServer class constructor // @return :CT_F32PerformanceServer CT_F32PerformanceServer::CT_F32PerformanceServer() :CTestServer () { } // Function : NewL // @return :An instance of test server // Description: Same code for Secure and non-secure variants // Called inside the MainL() function to create and start the // CTestServer derived server. CT_F32PerformanceServer* CT_F32PerformanceServer::NewL() { CT_F32PerformanceServer* performServer=new(ELeave) CT_F32PerformanceServer(); CleanupStack::PushL(performServer); performServer->ConstructL(KT_PerformServ); CleanupStack::Pop(performServer); return performServer; } // Function : ~CT_F32PerformanceServer // Description :CT_F32PerformanceServer class destructor CT_F32PerformanceServer::~CT_F32PerformanceServer() { } // Function : MainL // Description: Secure variant // Much simpler, uses the new Rendezvous() // call to sync with the client LOCAL_C void MainL() { // Leave the hooks in for platform security #if (defined __DATA_CAGING__) RProcess().DataCaging(RProcess::EDataCagingOn); RProcess().SecureApi(RProcess::ESecureApiOn); #endif CActiveScheduler* performScheduler=NULL; performScheduler=new(ELeave) CActiveScheduler; //Install me as current ActiveScheduler CActiveScheduler::Install(performScheduler); CT_F32PerformanceServer* server = NULL; // Create CT_ F32PerformanceServer(the CTestServer derived server) TRAPD(err,server = CT_F32PerformanceServer::NewL()); if(!err) { // Sync with the client and enter this active scheduler RProcess::Rendezvous(KErrNone); performScheduler->Start(); } delete server; delete performScheduler; } //End MainL // Function : E32Main // @return Standard Epoc error code on exit GLDEF_C TInt E32Main() { CTrapCleanup* cleanup = CTrapCleanup::New(); if(cleanup == NULL) { return KErrNoMemory; } #if (defined TRAP_IGNORE) TRAP_IGNORE(MainL()); #else TRAPD(err,MainL()); #endif delete cleanup; return KErrNone; } // @return - A CTestStep derived instance // Description : Implementation of CTestServer pure virtual // (i.e Creates the test steps) // @param : aStepName The name of the test step to be created CTestStep* CT_F32PerformanceServer::CreateTestStep(const TDesC& aStepName) { CTestStep* testStep = NULL; if (aStepName == KT_EntryStep) { testStep = new CT_EntryStep(); } else if (aStepName ==KT_ReadFileStep) { testStep = new CT_ReadFileStep (); } else if (aStepName==KT_SeekFileStep) { testStep= new CT_SeekFileStep (); } else if (aStepName==KT_WriteFileStep) { testStep= new CT_WriteFileStep (); } else if(aStepName==KT_CleanupStep) { testStep=new CT_CleanupStep(); } else if (aStepName==KT_SetupStep) { testStep=new CT_SetupStep(); } return testStep; }
[ "none@none" ]
[ [ [ 1, 150 ] ] ]
f4b4d31b1d0e521391de48aa0b3f2d6bc2c62584
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/PluginTemplates/Master_Adaptor.h
b8ad9f4ae0b83f91f720df719f179e1ee0732acd
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
1,594
h
#ifndef MASTER_ADAPTOR_INCLUDED #define MASTER_ADAPTOR_INCLUDED #include "HandlerItem.h" //#include "lwmaster.h" struct LWMasterAccess; template <class T, int Type> class Master_Adaptor : public HandlerItem<T> { public: Master_Adaptor(const char *name); virtual ~Master_Adaptor(); static double Event_Callback(LWInstance inst,const LWMasterAccess *ma); static unsigned int Flags_Callback (LWInstance inst); static int Master_Callback( long version, GlobalFunc *global, void *INlocal, void *serverData ); }; template <class T, int Type> Master_Adaptor<T,Type>::Master_Adaptor(const char *name) : HandlerItem<T>(LWMASTER_HCLASS, name, Master_Callback) {} template <class T, int Type> Master_Adaptor<T,Type>::~Master_Adaptor() {} template <class T, int Type> double Master_Adaptor<T,Type>::Event_Callback(LWInstance inst,const LWMasterAccess *ma) { return ((T*)inst)->Event( ma ); } template <class T, int Type> unsigned int Master_Adaptor<T,Type>::Flags_Callback (LWInstance inst) { return ((T*)inst)->Flags(); } template <class T, int Type> int Master_Adaptor<T,Type>::Master_Callback( long version, GlobalFunc *global, void *INlocal, void *serverData ) { if(version != LWMASTER_VERSION) return(AFUNC_BADVERSION); LWMasterHandler *local=(LWMasterHandler *)INlocal; local->event=Event_Callback; local->flags=Flags_Callback; local->type=Type; HandlerItem_Callback(global, local->inst, local->item); return AFUNC_OK; } #endif // MASTER_ADAPTOR_INCLUDED
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 63 ] ] ]
cf0e36e0fab8a9f0437d672ecfd1c3915e44a129
7cf0bc0c3120c2040c3ed534421082cd93f0242f
/GPUIdxLcss/GPUIdxLcss/indexing/inverted_based.h
80f7de7503acfa9e07bc0c590e0bfda19882acf8
[]
no_license
zephyrer/ab-mfc
3d7be0283fa3fff3dcb7120fc1544e60a3811d88
f228b27a6fdbcb55f481155e9e9d77302335336a
refs/heads/master
2021-01-13T02:15:55.470629
2010-12-10T12:16:23
2010-12-10T12:16:23
40,066,957
0
0
null
null
null
null
GB18030
C++
false
false
2,113
h
#ifndef _INVERTED_BASED_H_ #define _INVERTED_BASED_H_ enum IndexingConstants { SeriesLength = 20, // 序列长度 AlphabetLength = 10 // 字母集大小 }; enum { FindOneSolution, // 找到一个解,可以接着找下一个解 MayHaveSolution, // 肯能有解,需要接着找 NoSolution, // 无解了,不用再找了 }; struct Solution { int Type; // 返回类型 int Value; // 值,如果Typ = FindOneSolution,表示 Solution():Type(NoSolution),Value(0){} }; const char * SolutionTypeName[]; namespace ListIndexing { // 读取所有的数据文件,建立索引,返回总记录数 int ConstructIndexFromFile(const char * strDir); // 随机创建recordCount条数据,初始化随机种子为randNumber void ConstructIndexByRandom(unsigned int seed,int recordCount); // 用LB_DLCS在索引上进行检索 void SearchByLB_DLCS(int sampleID,int delta,float maxDistance); // 用DLCS顺序检索 void SearchByDLCS(int sampleID,int delta,float maxDistance); }; namespace VectorIndexing { // 读取所有的数据文件,建立索引,返回总记录数 int ConstructIndexFromFile(const char * strDir); // 随机创建recordCount条数据,初始化随机种子为randNumber void ConstructIndexByRandom(unsigned int seed,int recordCount); // 用LB_DLCS在索引上进行检索 void SearchByLB_DLCS(int sampleID,int delta,float maxDistance); // 用DLCS顺序检索 void SearchByDLCS(int sampleID,int delta,float maxDistance); }; namespace ThresholdIndexing { // 读取所有的数据文件,建立索引,返回总记录数 int ConstructIndexFromFile(const char * strDir); // 随机创建recordCount条数据,初始化随机种子为randNumber void ConstructIndexByRandom(unsigned int seed,int recordCount); // 用LB_DLCS在索引上进行检索 void SearchByLB_DLCS(int sampleID,int delta,float maxDistance); // 用DLCS顺序检索 void SearchByDLCS(int sampleID,int delta,float maxDistance); }; #endif
[ "superkiki1989@ce34bfc1-e555-5f21-4a2b-332ae8037cd2" ]
[ [ [ 1, 75 ] ] ]
9070ec1d3dbd8cd3860c01f7fa6100aecb6a21f3
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Utilities/include/GameEntity.h
d9e127e00bb77e9bc0f1d563450a86247e298bc5
[]
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
2,719
h
#pragma once #ifndef __GAME_ENTITY_H__ #define __GAME_ENTITY_H__ // NO INCLOURE AQUEST ARXIU !!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!! // incloure "EntityDefines.h" #include "base.h" #include <set> #ifndef __ENTITY_DEFINES_H__ #error S'ha d'incloure "EntityDefines.h" i no "GameEntity.h" #endif class CBaseComponent; class CEntityManager; class CRenderManager; class CGameEntity: public CBaseControl { public: int GetGUID() const {return m_iGUID;}; template<class T> T* GetComponent(CBaseComponent::Type _type) const; template<class T> T* GetComponent() const; void DeleteComponent(CBaseComponent::Type _type); void PreUpdate(float _fDeltaTime) ; void Update(float _fDeltaTime) ; void UpdatePrePhysX(float _fDeltaTime) ; void UpdatePostPhysX(float _fDeltaTime); void UpdatePostAnim(float _fDeltaTime) ; void PostUpdate(float _fDeltaTime) ; void DebugRender(CRenderManager*) ; string GetName() const; void SetActive(bool _bActive); bool IsActive() {return m_bActive;}; protected: virtual void Release(); private: CGameEntity(int _iId):m_iGUID(_iId),m_pszName(0),m_bActive(true) {SetOk(true);}; ~CGameEntity() {Done();}; void AddComponent(CBaseComponent* _pComponent); void AddCachedComponents(); void DeleteComponents(); void ReceiveEvent(const SEvent& _Event); map<CBaseComponent::Type, CBaseComponent*> m_vNewComponents; set<CBaseComponent::Type> m_vDeleteComponents; map<CBaseComponent::Type, CBaseComponent*> m_mComponents; vector<CBaseComponent*> m_vComponents; int m_iGUID; const string* m_pszName; bool m_bActive; friend class CBaseComponent; friend class CEntityManager; }; template<class T> T* CGameEntity::GetComponent(CBaseComponent::Type _type) const { map<CBaseComponent::Type, CBaseComponent*>::const_iterator l_it = m_mComponents.find(_type); if(l_it == m_mComponents.cend()) { l_it = m_vNewComponents.find(_type); if(l_it == m_vNewComponents.cend()) { return 0; } } return dynamic_cast<T*>(l_it->second); } template<class T> T* CGameEntity::GetComponent() const { map<CBaseComponent::Type, CBaseComponent*>::const_iterator l_it = m_mComponents.find(T::GetStaticType()); if(l_it == m_mComponents.cend()) { l_it = m_vNewComponents.find(T::GetStaticType()); if(l_it == m_vNewComponents.cend()) { return 0; } } return dynamic_cast<T*>(l_it->second); } #endif
[ "atridas87@576ee6d0-068d-96d9-bff2-16229cd70485", "Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485", "sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 32 ], [ 34, 46 ], [ 50, 54 ], [ 56, 63 ], [ 66, 70 ], [ 72, 84 ], [ 87, 101 ], [ 104, 112 ] ], [ [ 33, 33 ], [ 64, 65 ], [ 85, 86 ], [ 102, 103 ] ], [ [ 47, 49 ], [ 55, 55 ], [ 71, 71 ] ] ]
21b555babef5bf709455d43134fb1ff82d6c9932
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/Frustum.h
de82a891845ca4b8cbe3fe1f9edc8a675ecb143b
[]
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
5,207
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: Frustum.h Version: 0.08 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_FRUSTUM_H_ #define __INC_FRUSTUM_H_ #include "ISerializable.h" #include "Matrix4x4.h" #include "Plane.h" #include "Prerequisities.h" #include "TypeInfo.h" namespace nGENE { /// Type defining if a shape is contained withing a frustum enum CULLING_RESULT { CR_UNKNOWN, ///< It is not yet known if shape is visible CR_VISIBLE, ///< A shape is fully contained CR_INTERSECT, ///< A shape intersects frustum CR_INVISIBLE ///< A shape is outside frustum }; /** Frustum is the area visible from the camera's eye. @remarks Although most frequently frustums are used with cameras you can as well use them for other purposes, eg. light cones. @remarks Although as tradinionally frustum class lets you cull the invisible geometry, the method itself is not traditional at all. It uses 'radar' approach described in GPU Gems 5 by Frank Puig Placeres in his article titled: "Improved Frustum Culling". It is much more effective than regular way of doing this as no planes calculus is involved. */ class nGENEDLL Frustum: public BaseClass { EXPOSE_TYPE private: float m_fNearPlane; ///< Near plane distance float m_fFarPlane; ///< Far plane distance float m_fAspect; ///< Aspect float m_FOV; ///< Field of view float m_fRFactor; float m_fUFactor; float m_fRSphereFactor; float m_fUSphereFactor; // Pointers to the appropriate vectors - in case of View Frustum // these are Camera's vectors. Vector3 m_vecEyePos; Vector3 m_vecForward; Vector3 m_vecRight; Vector3 m_vecUp; /// Frustum projection matrix. Matrix4x4 m_matProjection; /// Has frustum changed recently bool m_bChanged; public: Frustum(); virtual ~Frustum(); void init(); void cleanup(); /** Updates the frustum. @remarks When the frustum is updated all planes are re-calculated regarding to the new camera position. */ void update(); /// Frustum reset. void reset(); /// Checks if frustum has changed since last time. bool hasChanged() const; /// Checks if a point is inside frustum. bool testPoint(const Vector3& _vec); /// Checks if a sphere is inside frustum. virtual bool testSphere(const Vector3& _centre, float _radius); /** Checks if an AABB is inside frustum. */ virtual CULLING_RESULT testAABB(AABB& _box); /// Sets near plane distance. virtual void setNear(float _near); virtual float getNear() const {return m_fNearPlane;} /// Sets far plane distance. virtual void setFar(float _far); virtual float getFar() const {return m_fFarPlane;} /// Sets field of view angle. virtual void setFOV(float _fov); virtual float getFOV() const {return m_FOV;} /// Sets acpect ratio. virtual void setAspect(float _aspect); virtual float getAspect() const {return m_fAspect;} /// Sets all parameters at once. virtual void setPerspective(const float _fov, const float _aspect, const float _near, const float _far); /// Sets frustum vectors. virtual void setVectors(Vector3& _pos, Vector3& _forward, Vector3& _right, Vector3& _up); Vector3& getEyePos(); Vector3& getForward(); Vector3& getRight(); Vector3& getUp(); /// Returns frustum projection matrix. Matrix4x4& getProjectionMatrix(); /** Returns 8 points describing the frustum in world space. @param _points [out] array of points being returned. */ void getFrustumPoints(Vector4* _points); /** Returns 8 points describing the frustum in eye space. @param _points [out] array of points being returned. */ void getFrustumPointsLocal(Vector4* _points); /// Returns 6 planes describing the frustum in world space. void getFrustumPlanes(Plane* _planes); /// Returns 6 planes describing the frustum in local space. void getFrustumPlanesLocal(Plane* _planes); }; inline Matrix4x4& Frustum::getProjectionMatrix() { return m_matProjection; } //---------------------------------------------------------------------- inline Vector3& Frustum::getEyePos() { return m_vecEyePos; } //---------------------------------------------------------------------- inline Vector3& Frustum::getForward() { return m_vecForward; } //---------------------------------------------------------------------- inline Vector3& Frustum::getRight() { return m_vecRight; } //---------------------------------------------------------------------- inline Vector3& Frustum::getUp() { return m_vecUp; } //---------------------------------------------------------------------- inline bool Frustum::hasChanged() const { return m_bChanged; } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 192 ] ] ]
1c75cea487685195291bffdad5e010d0b03cae29
1131c49e8329f4ab07a2c5d54945077b2a0ff491
/coinchange.cpp
878a57aa1f7af6b9c00195b9bd6ec5d1a48ffc91
[]
no_license
davinash/blogdataavi
e7dcbe2d7734589196938e9df048499b54389dcf
0548d59bbc2b20f97777f42b7cb138d020b0980b
refs/heads/master
2021-03-12T20:44:19.854943
2011-06-28T13:21:44
2011-06-28T13:21:44
32,113,806
0
0
null
null
null
null
UTF-8
C++
false
false
855
cpp
#include <vector> #include <iostream> #include <string> int compute_change(std::vector<int> &d, int size) { int k = (int)d.size(); std::vector<std::vector<int> > table(k , std::vector<int>(size + 1)); for ( int row = 0; row < k ; row++) table[row][0] = 0; for ( int col = 0; col <= size ; col++) table[0][col] = col; for ( int row = 1 ; row < k; row++) { for ( int col = 1 ; col <= size; col++) { if ( col < d[row] ) table[row][col] = table[row - 1][col]; else table[row][col] = std::min(table[row - 1][col], 1 + table[row][col - d[row]]); } } return table[k - 1][size - 1]; } int main ( int argc, char **argv) { int points[] = { 1, 2, 3, 17, 23, 42, 98}; std::vector<int> d (points, points + sizeof(points) / sizeof(int)); int solution = compute_change(d,2349 ); return 0; }
[ [ [ 1, 31 ] ] ]
916581ea6c78e808886cddaec9a3dc4ed7720b6c
5927f0908f05d3f58fe0adf4d5d20c27a4756fbe
/examples/chrome/browser_shutdown.cpp
8bc522275de1fba4b8d67043ee4b8d1678f882cd
[]
no_license
seasky013/x-framework
b5585505a184a7d00d229da8ab0f556ca0b4b883
575e29de5840ede157e0348987fa188b7205f54d
refs/heads/master
2016-09-16T09:41:26.994686
2011-09-16T06:16:22
2011-09-16T06:16:22
41,719,436
0
1
null
null
null
null
UTF-8
C++
false
false
7,649
cpp
#include "browser_shutdown.h" #include "base/threading/thread_restrictions.h" #include "base/time.h" namespace browser_shutdown { // Whether the browser is trying to quit (e.g., Quit chosen from menu). bool g_trying_to_quit = false; base::Time shutdown_started_; ShutdownType shutdown_type_ = NOT_VALID; ShutdownType GetShutdownType() { return shutdown_type_; } void OnShutdownStarting(ShutdownType type) { if(shutdown_type_ != NOT_VALID) { return; } shutdown_type_ = type; // For now, we're only counting the number of renderer processes // since we can't safely count the number of plugin processes from this // thread, and we'd really like to avoid anything which might add further // delays to shutdown time. shutdown_started_ = base::Time::Now(); // Call FastShutdown on all of the RenderProcessHosts. This will be // a no-op in some cases, so we still need to go through the normal // shutdown path for the ones that didn't exit here. //shutdown_num_processes_ = 0; //shutdown_num_processes_slow_ = 0; //for(RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); // !i.IsAtEnd(); i.Advance()) //{ // ++shutdown_num_processes_; // if(!i.GetCurrentValue()->FastShutdownIfPossible()) // { // ++shutdown_num_processes_slow_; // } //} } void Shutdown() { // During shutdown we will end up some blocking operations. But the // work needs to get done and we're going to wait for them no matter // what thread they're on, so don't worry about it slowing down // shutdown. base::ThreadRestrictions::SetIOAllowed(true); // Shutdown the IPC channel to the service processes. //ServiceProcessControl::GetInstance()->Disconnect(); // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough // time to get here. If you have something that *must* happen on end session, // consider putting it in BrowserProcessImpl::EndSession. //PrefService* prefs = g_browser_process->local_state(); //ProfileManager* profile_manager = g_browser_process->profile_manager(); //PrefService* user_prefs = profile_manager->GetDefaultProfile()->GetPrefs(); //chrome_browser_net::SavePredictorStateForNextStartupAndTrim(user_prefs); //MetricsService* metrics = g_browser_process->metrics_service(); //if(metrics) //{ // metrics->RecordCompletedSessionEnd(); //} //if(shutdown_type_>NOT_VALID && shutdown_num_processes_>0) //{ // // Record the shutdown info so that we can put it into a histogram at next // // startup. // prefs->SetInteger(prefs::kShutdownType, shutdown_type_); // prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_); // prefs->SetInteger(prefs::kShutdownNumProcessesSlow, // shutdown_num_processes_slow_); //} //// Check local state for the restart flag so we can restart the session below. //bool restart_last_session = false; //if(prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) //{ // restart_last_session = // prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown); // prefs->ClearPref(prefs::kRestartLastSessionOnShutdown); //} //prefs->SavePersistentPrefs(); //// Cleanup any statics created by RLZ. Must be done before NotificationService //// is destroyed. //RLZTracker::CleanupRlz(); //// The jank'o'meter requires that the browser process has been destroyed //// before calling UninstallJankometer(). //delete g_browser_process; //g_browser_process = NULL; //// Uninstall Jank-O-Meter here after the IO thread is no longer running. //UninstallJankometer(); //if(delete_resources_on_shutdown) //{ // ResourceBundle::CleanupSharedInstance(); //} //if(!browser_util::IsBrowserAlreadyRunning() && // shutdown_type_!=browser_shutdown::END_SESSION) //{ // upgrade_util::SwapNewChromeExeIfPresent(); //} //if(restart_last_session) //{ // // Make sure to relaunch the browser with the original command line plus // // the Restore Last Session flag. Note that Chrome can be launched (ie. // // through ShellExecute on Windows) with a switch argument terminator at // // the end (double dash, as described in b/1366444) plus a URL, // // which prevents us from appending to the command line directly (issue // // 46182). We therefore use GetSwitches to copy the command line (it stops // // at the switch argument terminator). // CommandLine old_cl(*CommandLine::ForCurrentProcess()); // scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram())); // std::map<std::string, CommandLine::StringType> switches = // old_cl.GetSwitches(); // // Remove the switches that shouldn't persist across restart. // about_flags::RemoveFlagsSwitches(&switches); // switches::RemoveSwitchesForAutostart(&switches); // // Append the old switches to the new command line. // for(std::map<std::string, CommandLine::StringType>::const_iterator i= // switches.begin(); i!=switches.end(); ++i) // { // CommandLine::StringType switch_value = i->second; // if(!switch_value.empty()) // { // new_cl->AppendSwitchNative(i->first, i->second); // } // else // { // new_cl->AppendSwitch(i->first); // } // } // // Ensure restore last session is set. // if(!new_cl->HasSwitch(switches::kRestoreLastSession)) // { // new_cl->AppendSwitch(switches::kRestoreLastSession); // } // upgrade_util::RelaunchChromeBrowser(*new_cl.get()); //} //if(shutdown_type_>NOT_VALID && shutdown_num_processes_>0) //{ // // Measure total shutdown time as late in the process as possible // // and then write it to a file to be read at startup. // // We can't use prefs since all services are shutdown at this point. // TimeDelta shutdown_delta = Time::Now() - shutdown_started_; // std::string shutdown_ms = // base::Int64ToString(shutdown_delta.InMilliseconds()); // int len = static_cast<int>(shutdown_ms.length()) + 1; // FilePath shutdown_ms_file = GetShutdownMsPath(); // file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len); //} //ChromeURLDataManager::DeleteDataSources(); } void SetTryingToQuit(bool quitting) { g_trying_to_quit = quitting; } bool IsTryingToQuit() { return g_trying_to_quit; } bool ShuttingDownWithoutClosingBrowsers() { return false; } } //namespace browser_shutdown
[ [ [ 1, 191 ] ] ]
ffa4fef76672c5df5a9b694487f3c7cc0cd565fe
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelController/include/Dan2.h
1aaeeecef657f4aa176e42ecde14fe321d504d7c
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
899
h
#ifndef __Orz_Dan2__ #define __Orz_Dan2__ #include "WheelGobalConfig.h" #include "DanListener.h" #include <CEGUI/cegui.h> #include <Ogre/ogre.h> #include <orz/Framework_Base/System/IInputManager.h> namespace Orz { class Dan2: public KeyListener { public: Dan2(DanListener * listener); bool textAccepted(const CEGUI::EventArgs&) ; bool onKeyPressed(const KeyEvent & evt); virtual bool onKeyReleased(const KeyEvent & evt); void result(bool ret); void show(void); void redo(int old, int now); //void getData(void); void setDan2Data(int i, int data); void hide(void); void setup(void); void update(TimeType time); ~Dan2(void); void bao_zhang_ma(const std::string & n); private: CEGUI::Window * _win; boost::array<CEGUI::Editbox*, 9> _editboxs; int _n; TimeType _time; DanListener * _callback; }; } #endif
[ [ [ 1, 44 ] ] ]
9bbe836b6c051dbb524cb9abeeefca9bc2373d39
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/chromium/src/WebFileSystemCallbacksImpl.cpp
48c698e6484330948426c3e874e5714bc0eee228
[ "BSD-2-Clause" ]
permissive
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,252
cpp
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebFileSystemCallbacksImpl.h" #if ENABLE(FILE_SYSTEM) #include "AsyncFileSystemCallbacks.h" #include "AsyncFileSystemChromium.h" #include "ExceptionCode.h" #include "WebFileSystemEntry.h" #include "WebFileInfo.h" #include "WebString.h" #include <wtf/Vector.h> using namespace WebCore; namespace WebKit { WebFileSystemCallbacksImpl::WebFileSystemCallbacksImpl(PassOwnPtr<AsyncFileSystemCallbacks> callbacks) : m_callbacks(callbacks) { } WebFileSystemCallbacksImpl::~WebFileSystemCallbacksImpl() { } void WebFileSystemCallbacksImpl::didSucceed() { ASSERT(m_callbacks); m_callbacks->didSucceed(); delete this; } void WebFileSystemCallbacksImpl::didReadMetadata(const WebFileInfo& info) { ASSERT(m_callbacks); m_callbacks->didReadMetadata(info.modificationTime); delete this; } void WebFileSystemCallbacksImpl::didReadDirectory(const WebVector<WebFileSystemEntry>& entries, bool hasMore) { ASSERT(m_callbacks); for (size_t i = 0; i < entries.size(); ++i) m_callbacks->didReadDirectoryEntry(entries[i].name, entries[i].isDirectory); m_callbacks->didReadDirectoryEntries(hasMore); if (!hasMore) delete this; } void WebFileSystemCallbacksImpl::didOpenFileSystem(const WebString& name, const WebString& path) { m_callbacks->didOpenFileSystem(name, new AsyncFileSystemChromium(path)); delete this; } void WebFileSystemCallbacksImpl::didFail(WebFileError error) { ASSERT(m_callbacks); m_callbacks->didFail(error); delete this; } } // namespace WebKit #endif // ENABLE(FILE_SYSTEM)
[ [ [ 1, 95 ] ] ]
67eafef3f9bf26355d4f1919e5ec16c55a335389
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/core/MenuVoting.cpp
d1f5d672ae75c6947bf657b8c24a003cfa30835b
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,136
cpp
/** * vim: set ts=4 : * ============================================================================= * SourceMod * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #include <string.h> #include <stdlib.h> #include "MenuVoting.h" #include "PlayerManager.h" #include "sourcemm_api.h" float g_next_vote = 0.0f; #if defined ORANGEBOX_BUILD void OnVoteDelayChange(IConVar *cvar, const char *value, float flOldValue); #else void OnVoteDelayChange(ConVar *cvar, const char *value); #endif ConVar sm_vote_delay("sm_vote_delay", "30", 0, "Sets the recommended time in between public votes", false, 0.0, false, 0.0, OnVoteDelayChange); #if defined ORANGEBOX_BUILD void OnVoteDelayChange(IConVar *cvar, const char *value, float flOldValue) #else void OnVoteDelayChange(ConVar *cvar, const char *value) #endif { /* See if the new vote delay isn't something we need to account for */ if (sm_vote_delay.GetFloat() < 1.0f) { g_next_vote = 0.0f; return; } /* If there was never a last vote, ignore this change */ if (g_next_vote < 0.1f) { return; } /* Subtract the original value, then add the new one. */ g_next_vote -= (float)atof(value); g_next_vote += sm_vote_delay.GetFloat(); } unsigned int VoteMenuHandler::GetRemainingVoteDelay() { if (g_next_vote <= gpGlobals->curtime) { return 0; } return (unsigned int)(g_next_vote - gpGlobals->curtime); } void VoteMenuHandler::OnSourceModAllInitialized() { g_Players.AddClientListener(this); } void VoteMenuHandler::OnSourceModShutdown() { g_Players.RemoveClientListener(this); } void VoteMenuHandler::OnSourceModLevelChange(const char *mapName) { g_next_vote = 0.0f; } unsigned int VoteMenuHandler::GetMenuAPIVersion2() { return m_pHandler->GetMenuAPIVersion2(); } void VoteMenuHandler::OnClientDisconnected(int client) { if (!IsVoteInProgress()) { return; } /* Wipe out their vote if they had one */ int item; if ((item = m_ClientVotes[client]) >= 0) { assert((unsigned)item < m_Items); assert(m_Votes[item] > 0); m_Votes[item]--; m_ClientVotes[client] = -1; } } bool VoteMenuHandler::IsVoteInProgress() { return (m_pCurMenu != NULL); } bool VoteMenuHandler::StartVote(IBaseMenu *menu, unsigned int num_clients, int clients[], unsigned int max_time, unsigned int flags/* =0 */) { if (!InitializeVoting(menu, menu->GetHandler(), max_time, flags)) { return false; } float fVoteDelay = sm_vote_delay.GetFloat(); if (fVoteDelay < 1.0) { g_next_vote = 0.0; } else { /* This little trick breaks for infinite votes! * However, we just ignore that since those 1) shouldn't exist and * 2) people must be checking IsVoteInProgress() beforehand anyway. */ g_next_vote = gpGlobals->curtime + fVoteDelay + (float)max_time; } for (unsigned int i=0; i<num_clients; i++) { menu->Display(clients[i], max_time, this); } StartVoting(); return true; } bool VoteMenuHandler::InitializeVoting(IBaseMenu *menu, IMenuHandler *handler, unsigned int time, unsigned int flags) { if (IsVoteInProgress()) { return false; } InternalReset(); /* Mark all clients as not voting */ for (int i=1; i<=gpGlobals->maxClients; i++) { m_ClientVotes[i] = -2; } m_Items = menu->GetItemCount(); if (m_Votes.size() < (size_t)m_Items) { /* Only clear the items we need to... */ size_t size = m_Votes.size(); for (size_t i=0; i<size; i++) { m_Votes[i] = 0; } m_Votes.resize(m_Items, 0); } else { for (unsigned int i=0; i<m_Items; i++) { m_Votes[i] = 0; } } m_pCurMenu = menu; m_VoteTime = time; m_VoteFlags = flags; m_pHandler = handler; m_pHandler->OnMenuStart(m_pCurMenu); return true; } void VoteMenuHandler::StartVoting() { if (!m_pCurMenu) { return; } m_bStarted = true; m_pHandler->OnMenuVoteStart(m_pCurMenu); /* By now we know how many clients were set. * If there are none, we should end IMMEDIATELY. */ if (m_Clients == 0) { EndVoting(); } } void VoteMenuHandler::DecrementPlayerCount() { assert(m_Clients > 0); m_Clients--; if (m_bStarted && m_Clients == 0) { EndVoting(); } } int SortVoteItems(const void *item1, const void *item2) { return ((menu_vote_result_t::menu_item_vote_t *)item2)->count - ((menu_vote_result_t::menu_item_vote_t *)item1)->count; } void VoteMenuHandler::EndVoting() { /* Set when the next delay ends. We ignore cancellation because a menu * was, at one point, displayed, which is all that counts. However, we * do re-calculate the time just in case the menu had no time limit. */ float fVoteDelay = sm_vote_delay.GetFloat(); if (fVoteDelay < 1.0) { g_next_vote = 0.0; } else { g_next_vote = gpGlobals->curtime + fVoteDelay; } if (m_bCancelled) { /* If we were cancelled, don't bother tabulating anything. * Reset just in case someone tries to redraw, which means * we need to save our states. */ IBaseMenu *menu = m_pCurMenu; IMenuHandler *handler = m_pHandler; InternalReset(); handler->OnMenuVoteCancel(menu, VoteCancel_Generic); handler->OnMenuEnd(menu, MenuEnd_VotingCancelled); return; } menu_vote_result_t vote; menu_vote_result_t::menu_client_vote_t client_vote[256]; menu_vote_result_t::menu_item_vote_t item_vote[256]; memset(&vote, 0, sizeof(vote)); /* Build the item list */ for (unsigned int i=0; i<m_Items; i++) { if (m_Votes[i] > 0) { item_vote[vote.num_items].count = m_Votes[i]; item_vote[vote.num_items].item = i; vote.num_votes += m_Votes[i]; vote.num_items++; } } vote.item_list = item_vote; if (!vote.num_votes) { IBaseMenu *menu = m_pCurMenu; IMenuHandler *handler = m_pHandler; InternalReset(); handler->OnMenuVoteCancel(menu, VoteCancel_NoVotes); handler->OnMenuEnd(menu, MenuEnd_VotingCancelled); return; } /* Build the client list */ for (int i=1; i<=gpGlobals->maxClients; i++) { if (m_ClientVotes[i] >= -1) { client_vote[vote.num_clients].client = i; client_vote[vote.num_clients].item = m_ClientVotes[i]; vote.num_clients++; } } vote.client_list = client_vote; /* Sort the item list descending like we promised */ qsort(item_vote, vote.num_items, sizeof(menu_vote_result_t::menu_item_vote_t), SortVoteItems); /* Save states, then clear what we've saved. * This makes us re-entrant, which is always the safe way to go. */ IBaseMenu *menu = m_pCurMenu; IMenuHandler *handler = m_pHandler; InternalReset(); /* Send vote info */ handler->OnMenuVoteResults(menu, &vote); handler->OnMenuEnd(menu, MenuEnd_VotingDone); } void VoteMenuHandler::OnMenuStart(IBaseMenu *menu) { m_Clients++; } void VoteMenuHandler::OnMenuEnd(IBaseMenu *menu, MenuEndReason reason) { DecrementPlayerCount(); } void VoteMenuHandler::OnMenuCancel(IBaseMenu *menu, int client, MenuCancelReason reason) { m_pHandler->OnMenuCancel(menu, client, reason); } void VoteMenuHandler::OnMenuDisplay(IBaseMenu *menu, int client, IMenuPanel *display) { m_ClientVotes[client] = -1; m_pHandler->OnMenuDisplay(menu, client, display); } unsigned int VoteMenuHandler::OnMenuDisplayItem(IBaseMenu *menu, int client, IMenuPanel *panel, unsigned int item, const ItemDrawInfo &dr) { return m_pHandler->OnMenuDisplayItem(menu, client, panel, item, dr); } void VoteMenuHandler::OnMenuDrawItem(IBaseMenu *menu, int client, unsigned int item, unsigned int &style) { m_pHandler->OnMenuDrawItem(menu, client, item, style); } void VoteMenuHandler::OnMenuSelect(IBaseMenu *menu, int client, unsigned int item) { /* Check by our item count, NOT the vote array size */ if (item < m_Items) { m_ClientVotes[client] = item; m_Votes[item]++; m_NumVotes++; } m_pHandler->OnMenuSelect(menu, client, item); } void VoteMenuHandler::OnMenuSelect2(IBaseMenu *menu, int client, unsigned int item, unsigned int item_on_page) { if (m_pHandler->GetMenuAPIVersion2() >= 13) { m_pHandler->OnMenuSelect2(menu, client, item, item_on_page); } } void VoteMenuHandler::InternalReset() { m_Clients = 0; m_Items = 0; m_bStarted = false; m_pCurMenu = NULL; m_NumVotes = 0; m_bCancelled = false; m_pHandler = NULL; } void VoteMenuHandler::CancelVoting() { if (m_bCancelled || !m_pCurMenu) { return; } m_bCancelled = true; m_pCurMenu->Cancel(); } IBaseMenu *VoteMenuHandler::GetCurrentMenu() { return m_pCurMenu; } bool VoteMenuHandler::IsCancelling() { return m_bCancelled; }
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 39 ], [ 43, 43 ], [ 45, 54 ], [ 58, 58 ], [ 60, 413 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ] ], [ [ 40, 42 ], [ 44, 44 ], [ 55, 57 ], [ 59, 59 ] ] ]
43843403a8ee05233cbae09250e69188afc2fd5d
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/SkillObject.cpp
35db3be2fe6b28948d549a7cac5f9df0148e82ea
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UHC
C++
false
false
19,494
cpp
#include "EmptyProjectPCH.h" #include "SkillObject.h" #include "WorldStateManager.h" #include "BattleState.h" #include "Character.h" #include "DynamicMotion.h" #include "Sound.h" #include "ShaderWrapper.h" #include "Unit.h" #include "ScriptManager.h" #include "Action.h" #include "DynamicMotion.h" #include "ArnMath.h" extern BombShader* g_bombShader; extern LPD3DXMESH g_bst[BST_COUNT]; SkillObject::SkillObject( BasicShapeType bst, float size, D3DCOLOR color, DynamicMotion* dm ) : Unit( UT_SKILLOBJECT ) , m_bst( bst ) , m_user( 0 ) , m_target( 0 ) , m_velocity( 0 ) , m_dm( dm ) , m_size( size ) , m_color( color ) { } SkillObject::SkillObject( const SkillObject& so ) : Unit( UT_SKILLOBJECT ) , m_bst( so.m_bst ) , m_user( so.m_user ) , m_target( so.m_target ) , m_velocity( so.m_velocity ) , m_dm( so.m_dm->clone() ) , m_size( so.m_size ) , m_color( so.m_color ) { ActionList::const_iterator cit = so.m_onHitActionList.begin(); for ( ; cit != so.m_onHitActionList.end(); ++cit ) { Action* act = (*cit)->clone(); addOnHitAction( act ); } m_dm->setMotionTarget( this ); } SkillObject::~SkillObject(void) { //m_effectObject->release(); //delete m_effectObject; EP_SAFE_release( m_dm ); EpSafeReleaseAll( m_onHitActionList ); } bool SkillObject::frameMove( double dTime, float fElapsedTime ) { // This bool indicates that whether the present frameMove() is the last(final) call // or another frameMove() will be called after this call. // If SkillObject hits(collides) to target unit, than this will be last call, // otherwise there will be one or more frameMove() until collision occurs. bool frameMoveInProgress = true; // 'm_dm' governs the movement of this SkillObject. m_dm->frameMove( fElapsedTime ); ArnVec3 objToTarget = getPos() - m_target->getPos(); float dist = ArnVec3Length( &objToTarget ); if ( dist < 0.1f ) { assert( m_target ); m_target->addMoveImpulse( ArnConsts::ARNVEC3_Z / 2.5f ); // Attacked unit shows startled shake ActionList::iterator it = m_onHitActionList.begin(); UINT updateInProgressCount = 0; for ( ; it != m_onHitActionList.end(); ++it ) { bool updateInProgress = (*it)->update( dTime, fElapsedTime ); if ( updateInProgress ) ++updateInProgress; } if ( updateInProgressCount > 0 ) frameMoveInProgress = true; // SkillObject is collided with target unit, however hit actions are not completed yet. else frameMoveInProgress = false; // No more frameMove() is needed. } Unit::frameMove( dTime, fElapsedTime ); return frameMoveInProgress; } HRESULT SkillObject::frameRender ( IDirect3DDevice9* pd3dDevice, double dTime, float fElapsedTime ) { HRESULT f = 0; D3DPERF_BeginEvent( 0, L"SkillObject Render" ); HRESULT hr = S_OK; ArnMatrix mWorld; ArnMatrixIdentity( &mWorld ); UINT iPass, cPasses; if ( SUCCEEDED(g_bombShader->setMainTechnique()) ) { ArnMatrix arnvm, arnpm; memcpy(arnvm.m, GetG().m_camera.GetViewMatrix()->m, sizeof(float)*16); memcpy(arnpm.m, GetG().m_camera.GetProjMatrix()->m, sizeof(float)*16); V( g_bombShader->setWorldViewProj( dTime, fElapsedTime, &getLocalXform(), &arnvm, &arnpm) ); V( g_bombShader->begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_bombShader->beginPass( iPass ) ); // TODO Mesh pointing should be done here? not OnResetDevice? if ( getMesh() == 0 ) { setMesh( g_bst[ m_bst ] ); } f = getMesh()->DrawSubset( 0 ); V( g_bombShader->endPass() ); } V( g_bombShader->end() ); } else { // TODO Mesh pointing should be done here? not OnResetDevice? if ( getMesh() == 0 ) { setMesh( g_bst[ m_bst ] ); } pd3dDevice->SetTransform(D3DTS_WORLD, (const D3DXMATRIX*)getLocalXform().m); f = getMesh()->DrawSubset( 0 ); } D3DPERF_EndEvent(); return f; } BattleState* SkillObject::getBattleState() const { return reinterpret_cast<BattleState*>( GetWorldStateManager().getCurState() ); } SkillObject* SkillObject::createSkillObject( const char* bst, float size, D3DCOLOR color, DynamicMotion* dm ) { BasicShapeType bstEnum; if ( strcmp( bst, "SPHERE" ) == 0 ) bstEnum = BST_SPHERE; else if ( strcmp( bst, "CUBE" ) == 0 ) bstEnum = BST_CUBE; else if ( strcmp( bst, "PLANE" ) == 0 ) bstEnum = BST_PLANE; else bstEnum = BST_UNKNOWN; SkillObject* so = new SkillObject( bstEnum, size, color, dm ); return so; } SkillObject* SkillObject::clone() const { return new SkillObject( *this ); } void SkillObject::setUserAndTarget( Character* user, Character* target ) { m_user = user; m_target = target; m_dm->setFireAndTargetUnit( user, target ); ActionList::iterator it = m_onHitActionList.begin(); for ( ; it != m_onHitActionList.end(); ++it ) { CharacterAction* ca = dynamic_cast<CharacterAction*>( *it ); if ( ca ) { ca->setCharacter( m_target ); } } } ////////////////////////////////////////////////////////////////////////// SkillObject* EpCreateSkillObject( const char* bst, double size, int color /* ARGB */, void* dmPtr ) { DynamicMotion* dm = reinterpret_cast<DynamicMotion*>( dmPtr ); return SkillObject::createSkillObject( bst, (float)size, (D3DCOLOR)color, dm ); } SCRIPT_CALLABLE_PV_PC_D_I_PV( EpCreateSkillObject ) int EpSkillObjectAddOnHitAction( void* soPtr, void* actPtr ) { SkillObject* so = reinterpret_cast<SkillObject*>( soPtr ); Action* act = reinterpret_cast<Action*>( actPtr ); so->addOnHitAction( act ); return 0; } SCRIPT_CALLABLE_I_PV_PV( EpSkillObjectAddOnHitAction ) START_SCRIPT_FACTORY( SkillObject ) CREATE_OBJ_COMMAND( EpCreateSkillObject ) CREATE_OBJ_COMMAND( EpSkillObjectAddOnHitAction ) END_SCRIPT_FACTORY( SkillObject ) ////////////////////////////////////////////////////////////////////////// //SkillObject* SkillObject::createSOnormalAttack(Character* user, Character* target, Unit* effectObject) //{ // SOnormalAttack* so = new SOnormalAttack (user, target, effectObject); // return so; //} // //SkillObject* SkillObject::createSOheal(Character* user, Unit* effectObject) //{ // SOheal* so = new SOheal (user, effectObject); // return so; //} // //SkillObject* SkillObject::createSOmeditation(Character* user, Unit* effectObject) //{ // SOmeditation* so = new SOmeditation (user, effectObject); // return so; //} // //SkillObject* SkillObject::createSOcsBurn(Character* target, Unit* effectObject) //{ // SOcsBurn* so = new SOcsBurn (target, effectObject); // return so; //} // //SkillObject* SkillObject::createSOmtBullet(Character* user, Character* target, Unit* effectObject, int leftNumber, int maxNumber) //{ // SOmtBullet* so = new SOmtBullet (user, target, effectObject, leftNumber, maxNumber); // return so; //} // //SkillObject* SkillObject::createSOgoto (Character* user, Character* target, Unit* effectObject) //{ // SOgoto* so = new SOgoto (user, target, effectObject); // return so; //} ///////////////////////////////////////////////////////////////////////////////////////////////////////// //SOnormalAttack::~SOnormalAttack(void) //{ //} // //bool SOnormalAttack::frameMove (float fElapsedTime) //{ // // if ( !m_effectObject->frameMove ( fElapsedTime ) ) // { // //스크립트 함수를 호출한다. // //onObjectHitTarget(---); // // // // Hit to the target! // int damage = m_user->getStat().coding- m_target->getStat().def + 5; // // m_target->damage(damage); // // ArnVec3 posDiff = m_target->getPos() - m_user->getPos(); // D3DXVec3Normalize( &posDiff, &posDiff ); // m_target->addMoveImpulse( posDiff / 3 ); // Attacked unit shows startled shake // // char stringBuffer[20]; // _itoa_s (damage, stringBuffer, 10); // std::string resultLog = stringBuffer; // // if ( m_target->getType() == UT_HERO ) // { // // resultLog += "포인트 데미지를 받았다!"; // getBattleState()->pushBattleLog(resultLog.c_str()); // if (m_target->isDead()) // { // getBattleState()->pushBattleLog("HP가 모두 소진되었습니다. 게임 오버입니다."); // getBattleState()->pushBattleLog("순순히 F5키를 누르고 종료하시죠."); // m_target->setDead(); // getBattleState()->setNextTurnType(TT_NATURAL); // getBattleState()->passTurn(); // } // else // { // getBattleState()->setNextTurnType(TT_PLAYER); // getBattleState()->passTurn(); // } // } // else // { // resultLog += "포인트 데미지를 입혔다!"; // getBattleState()->pushBattleLog(resultLog.c_str()); // if (m_target->isDead()) // { // getBattleState()->pushBattleLog("대상을 섬멸하였습니다! (Enter key로 월드로 복귀)"); // m_target->setDead(); // getBattleState()->setNextTurnType(TT_NATURAL); // GetAudioState().pSoundBank->Play( GetAudioState().iAttack, 0, 0, NULL ); // } // else // { // getBattleState()->setNextTurnType(TT_COMPUTER); // getBattleState()->passTurn(); // GetAudioState().pSoundBank->Play( GetAudioState().iAttack, 0, 0, NULL ); // } // } // // return false; // } // return true; //} // //SOnormalAttack::SOnormalAttack (Character* user, Character* target, Unit* effectObject) //{ // m_user = user; // m_target = target; // m_effectObject = effectObject; //} // /////////////////////////////////////////////////////////////////////////////////////////////////////////// // //SOheal::~SOheal(void) //{ //} // //bool SOheal::frameMove (float fElapsedTime) //{ // if ( !m_effectObject->frameMove( fElapsedTime )) // { // int healPoint = m_user->getStat().sense * 50; // m_user->heal (healPoint); // // char stringBuffer[20]; // _itoa_s (healPoint, stringBuffer, 10); // std::string resultLog = stringBuffer; // resultLog += "포인트 HP가 회복됩니다."; // getBattleState()->pushBattleLog(resultLog.c_str()); // // if ( m_user->getType() == UT_HERO ) // { // getBattleState()->setNextTurnType(TT_COMPUTER); // getBattleState()->passTurn(); // GetAudioState().pSoundBank->Play( GetAudioState().iSE, 0, 0, NULL ); // } // else // { // getBattleState()->setNextTurnType(TT_PLAYER); // getBattleState()->passTurn(); // } // return false; // // } // return true; //} // //SOheal::SOheal (Character* user, Unit* effectObject) //{ // m_user = user; // m_effectObject = effectObject; //} // /////////////////////////////////////////////////////////////////////////////////////////////////////////// // //SOmeditation::~SOmeditation(void) //{ //} // //bool SOmeditation::frameMove (float fElapsedTime) //{ // if ( !m_effectObject->frameMove( fElapsedTime )) // { // for (int i=0; i<3; i++) // { // m_user->recoverCs(); // } // // getBattleState()->pushBattleLog("청명한 기운을 느끼며 CS가 30% 회복됩니다."); // // if ( m_user->getType() == UT_HERO ) // { // getBattleState()->setNextTurnType(TT_COMPUTER); // getBattleState()->passTurn(); // GetAudioState().pSoundBank->Play( GetAudioState().iSE, 0, 0, NULL ); // } // else // { // getBattleState()->setNextTurnType(TT_PLAYER); // getBattleState()->passTurn(); // } // return false; // } // return true; //} // //SOmeditation::SOmeditation (Character* user, Unit* effectObject) //{ // m_user = user; // m_effectObject = effectObject; //} // /////////////////////////////////////////////////////////////////////////////////////////////////////////// // // //SOcsBurn::~SOcsBurn(void) //{ //} // //bool SOcsBurn::frameMove (float fElapsedTime) //{ // if ( !m_effectObject->frameMove( fElapsedTime )) // { // // Hit to the target! // m_target->setCurCs(0); // // getBattleState()->pushBattleLog("스피릿이 모두 소진되었습니다."); // // int m_burnDamage = m_target->getCurHp() / 2; // // m_target->damage(m_burnDamage); // // getBattleState()->pushBattleLog("스피릿 소진에 의한 현기증으로 인해"); // getBattleState()->pushBattleLog("현재 HP가 반으로 줄어듭니다."); // // // // if ( m_target->getType() == UT_HERO ) // { // getBattleState()->setNextTurnType(TT_COMPUTER); // getBattleState()->passTurn(); // GetAudioState().pSoundBank->Play( GetAudioState().iSE, 0, 0, NULL ); // } // else // { // getBattleState()->setNextTurnType(TT_PLAYER); // getBattleState()->passTurn(); // } // return false; // // // } // return true; //} // //SOcsBurn::SOcsBurn (Character* target, Unit* effectObject) //{ // m_target = target; // m_effectObject = effectObject; //} // // /////////////////////////////////////////////////////////////////////////////////////////////////////////// // // //SOmtBullet::~SOmtBullet(void) //{ //} // //bool SOmtBullet::frameMove (float fElapsedTime) //{ // float interval = 1; // m_elapsedTime += fElapsedTime; // if (m_elapsedTime < interval * (m_maxNumber - m_leftNumber - 1)) // { // return true; // } // else if (m_target->isDead()) // return false; // // if ( !m_effectObject->frameMove ( fElapsedTime ) ) // { // int damage; // // Hit to the target! // if (m_leftNumber != 0) // damage = ( m_user->getStat().coding - m_target->getStat().def + 5) / 3; // else // //방어 무시 // damage = m_user->getStat().coding / 2; // // m_target->damage(damage); // // ArnVec3 posDiff = m_target->getPos() - m_user->getPos(); // D3DXVec3Normalize( &posDiff, &posDiff ); // if (m_leftNumber != 0) // m_target->addMoveImpulse( posDiff / 3 ); // Attacked unit shows startled shake // else // m_target->addMoveImpulse( posDiff * 3 ); // // char stringBuffer[20]; // _itoa_s (damage, stringBuffer, 10); // std::string resultLog = stringBuffer; // // if ( m_target->getType() == UT_HERO ) // { // // resultLog += "포인트 쓰레드 데미지!"; // getBattleState()->pushBattleLog(resultLog.c_str()); // if (m_target->isDead()) // { // getBattleState()->pushBattleLog("HP가 모두 소진되었습니다. 게임 오버입니다."); // getBattleState()->pushBattleLog("순순히 F5키를 누르고 종료하시죠."); // m_target->setDead(); // // getBattleState()->setNextTurnType(TT_NATURAL); // getBattleState()->passTurn(); // // } // else // { // if (m_leftNumber == 0) // { // getBattleState()->setNextTurnType(TT_PLAYER); // getBattleState()->passTurn(); // } // } // } // else // { // resultLog += "포인트 쓰레드 데미지!"; // getBattleState()->pushBattleLog(resultLog.c_str()); // if (m_target->isDead()) // { // getBattleState()->pushBattleLog("대상을 섬멸하였습니다! (Enter key로 월드로 복귀)"); // m_target->setDead(); // getBattleState()->setNextTurnType(TT_NATURAL); // GetAudioState().pSoundBank->Play( GetAudioState().iAttack, 0, 0, NULL ); // } // else // { // if (m_leftNumber == 0) // { // getBattleState()->setNextTurnType(TT_COMPUTER); // getBattleState()->passTurn(); // GetAudioState().pSoundBank->Play( GetAudioState().iAttack, 0, 0, NULL ); // } // } // } // // return false; // } // return true; //} // //SOmtBullet::SOmtBullet (Character* user, Character* target, Unit* effectObject, int leftNumber, int maxNumber) //{ // m_user = user; // m_target = target; // m_effectObject = effectObject; // m_leftNumber = leftNumber; // m_maxNumber = maxNumber; // m_elapsedTime = 0; //} // /////////////////////////////////////////////////////////////////////////////////////////////////////////// // // //SOgoto::~SOgoto(void) //{ // m_illusion->release(); // delete m_illusion; //} // //bool SOgoto::frameMove (float fElapsedTime) //{ // // 상대방에게 다가가는 중일 경우 // if (m_phase == 0) // { // if (m_illusion->frameMove(fElapsedTime)) // return true; // m_phase = 1; // m_illusion->setDynamicMotion(NULL); // return true; // } // // 공격 이펙트가 진행되는 경우 // else if (m_phase == 1) // { // if (m_effectObject->frameMove (fElapsedTime)) // return true; // // // Hit to the target! // // 자신의 공격력 + 자신의 방어력 - 상대방 공격력 // int damage = m_user->getStat().coding + m_user->getStat().def - m_target->getStat().def; // // m_target->damage(damage); // // ArnVec3 posDiff = m_target->getPos() - m_user->getPos(); // D3DXVec3Normalize( &posDiff, &posDiff ); // m_target->addMoveImpulse( posDiff / 3 ); // Attacked unit shows startled shake // // char stringBuffer[20]; // _itoa_s (damage, stringBuffer, 10); // std::string resultLog = stringBuffer; // // if ( m_target->getType() == UT_HERO ) // { // resultLog += "포인트 데미지를 받았다!"; // getBattleState()->pushBattleLog(resultLog.c_str()); // if (m_target->isDead()) // { // getBattleState()->pushBattleLog("HP가 모두 소진되었습니다. 게임 오버입니다."); // getBattleState()->pushBattleLog("순순히 F5키를 누르고 종료하시죠."); // m_target->setDead(); // getBattleState()->setNextTurnType(TT_NATURAL); // getBattleState()->passTurn(); // return false; // } // } // else // { // resultLog += "포인트 데미지를 입혔다!"; // getBattleState()->pushBattleLog(resultLog.c_str()); // if (m_target->isDead()) // { // getBattleState()->pushBattleLog("대상을 섬멸하였습니다! (Enter key로 월드로 복귀)"); // m_target->setDead(); // getBattleState()->setNextTurnType(TT_NATURAL); // GetAudioState().pSoundBank->Play( GetAudioState().iAttack, 0, 0, NULL ); // return false; // } // } // // m_phase = 2; // ArnVec3 fireDir = m_originPoint - m_user->getPos(); // float dist = ArnVec3Length( &fireDir ); // D3DXVec3Normalize( &fireDir, &fireDir ); // // m_effectObject->setVisible(false); // m_illusion->setDynamicMotion (DynamicMotion::createDMfireUniformly (m_user, m_user->getPos(), fireDir, dist, 10)); // // return true; // } // //복귀하는 과정 // else if (m_phase == 2) // { // if (m_illusion->frameMove(fElapsedTime)) // return true; // // m_illusion->setDynamicMotion (NULL); // // if ( m_target->getType() == UT_HERO ) // { // getBattleState()->setNextTurnType(TT_PLAYER); // getBattleState()->passTurn(); // } // else // { // getBattleState()->setNextTurnType(TT_COMPUTER); // getBattleState()->passTurn(); // GetAudioState().pSoundBank->Play( GetAudioState().iAttack, 0, 0, NULL ); // } // // return false; // } // // return true; //} // // //SOgoto::SOgoto (Character* user, Character* target, Unit* effectObject) //{ // m_user = user; // m_target = target; // m_effectObject = effectObject; // m_phase = 0; // m_originPoint = m_user->getPos(); // // LPD3DXMESH mesh; // D3DXCreateSphere( GetG().m_dev, 0.3f, 16, 16, &mesh, 0); // // m_illusion = Character::createCharacter(mesh, 0, 0, 0); // //m_illusion = Unit::createUnit(mesh, 0, 0, 0); // // ArnVec3 fireDir = m_target->getPos() - m_user->getPos(); // float dist = ArnVec3Length( &fireDir ); // D3DXVec3Normalize( &fireDir, &fireDir ); // // // m_illusion->setDynamicMotion (DynamicMotion::createDMfireUniformly (m_user, m_user->getPos(), fireDir, dist, 10)); //}
[ [ [ 1, 7 ], [ 49, 50 ], [ 57, 58 ], [ 60, 60 ], [ 94, 95 ], [ 97, 97 ], [ 143, 145 ], [ 147, 150 ], [ 247, 247 ], [ 249, 250 ] ], [ [ 8, 48 ], [ 51, 56 ], [ 59, 59 ], [ 61, 93 ], [ 96, 96 ], [ 98, 142 ], [ 146, 146 ], [ 151, 246 ], [ 248, 248 ], [ 251, 685 ] ] ]
d30c0eead7288ab5207c07e776b2fe78085ca8b1
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/StandardShapes.cpp
858b360b79bfbd6ad7f53ef720ff9f62444d97c5
[ "BSD-3-Clause" ]
permissive
spring/assimp
fb53b91228843f7677fe8ec18b61d7b5886a6fd3
db29c9a20d0dfa9f98c8fd473824bba5a895ae9e
refs/heads/master
2021-01-17T23:19:56.511185
2011-11-08T12:15:18
2011-11-08T12:15:18
2,017,841
1
1
null
null
null
null
UTF-8
C++
false
false
16,493
cpp
/* Open Asset Import Library (ASSIMP) ---------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ /** @file StandardShapes.cpp * @brief Implementation of the StandardShapes class * * The primitive geometry data comes from * http://geometrictools.com/Documentation/PlatonicSolids.pdf. */ #include "AssimpPCH.h" #include "StandardShapes.h" namespace Assimp { # define ADD_TRIANGLE(n0,n1,n2) \ positions.push_back(n0); \ positions.push_back(n1); \ positions.push_back(n2); # define ADD_PENTAGON(n0,n1,n2,n3,n4) \ if (polygons) \ { \ positions.push_back(n0); \ positions.push_back(n1); \ positions.push_back(n2); \ positions.push_back(n3); \ positions.push_back(n4); \ } \ else \ { \ ADD_TRIANGLE(n0, n1, n2) \ ADD_TRIANGLE(n0, n2, n3) \ ADD_TRIANGLE(n0, n3, n4) \ } # define ADD_QUAD(n0,n1,n2,n3) \ if (polygons) \ { \ positions.push_back(n0); \ positions.push_back(n1); \ positions.push_back(n2); \ positions.push_back(n3); \ } \ else \ { \ ADD_TRIANGLE(n0, n1, n2) \ ADD_TRIANGLE(n0, n2, n3) \ } // ------------------------------------------------------------------------------------------------ // Fast subdivision for a mesh whose verts have a magnitude of 1 void Subdivide(std::vector<aiVector3D>& positions) { // assume this to be constant - (fixme: must be 1.0? I think so) const float fl1 = positions[0].Length(); unsigned int origSize = (unsigned int)positions.size(); for (unsigned int i = 0 ; i < origSize ; i+=3) { aiVector3D& tv0 = positions[i]; aiVector3D& tv1 = positions[i+1]; aiVector3D& tv2 = positions[i+2]; aiVector3D a = tv0, b = tv1, c = tv2; aiVector3D v1 = aiVector3D(a.x+b.x, a.y+b.y, a.z+b.z).Normalize()*fl1; aiVector3D v2 = aiVector3D(a.x+c.x, a.y+c.y, a.z+c.z).Normalize()*fl1; aiVector3D v3 = aiVector3D(b.x+c.x, b.y+c.y, b.z+c.z).Normalize()*fl1; tv0 = v1; tv1 = v3; tv2 = v2; // overwrite the original ADD_TRIANGLE(v1, v2, a); ADD_TRIANGLE(v2, v3, c); ADD_TRIANGLE(v3, v1, b); } } // ------------------------------------------------------------------------------------------------ // Construct a mesh from given vertex positions aiMesh* StandardShapes::MakeMesh(const std::vector<aiVector3D>& positions, unsigned int numIndices) { if (positions.size() & numIndices || positions.empty() || !numIndices) return NULL; // Determine which kinds of primitives the mesh consists of aiMesh* out = new aiMesh(); switch (numIndices) { case 1: out->mPrimitiveTypes = aiPrimitiveType_POINT; break; case 2: out->mPrimitiveTypes = aiPrimitiveType_LINE; break; case 3: out->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; break; default: out->mPrimitiveTypes = aiPrimitiveType_POLYGON; break; }; out->mNumFaces = (unsigned int)positions.size() / numIndices; out->mFaces = new aiFace[out->mNumFaces]; for (unsigned int i = 0, a = 0; i < out->mNumFaces;++i) { aiFace& f = out->mFaces[i]; f.mNumIndices = numIndices; f.mIndices = new unsigned int[numIndices]; for (unsigned int i = 0; i < numIndices;++i,++a) f.mIndices[i] = a; } out->mNumVertices = (unsigned int)positions.size(); out->mVertices = new aiVector3D[out->mNumVertices]; ::memcpy(out->mVertices,&positions[0],out->mNumVertices*sizeof(aiVector3D)); return out; } // ------------------------------------------------------------------------------------------------ // Construct a mesh with a specific shape (callback) aiMesh* StandardShapes::MakeMesh ( unsigned int (*GenerateFunc)( std::vector<aiVector3D>&)) { std::vector<aiVector3D> temp; unsigned num = (*GenerateFunc)(temp); return MakeMesh(temp,num); } // ------------------------------------------------------------------------------------------------ // Construct a mesh with a specific shape (callback) aiMesh* StandardShapes::MakeMesh ( unsigned int (*GenerateFunc)( std::vector<aiVector3D>&, bool)) { std::vector<aiVector3D> temp; unsigned num = (*GenerateFunc)(temp,true); return MakeMesh(temp,num); } // ------------------------------------------------------------------------------------------------ // Construct a mesh with a specific shape (callback) aiMesh* StandardShapes::MakeMesh (unsigned int num, void (*GenerateFunc)( unsigned int,std::vector<aiVector3D>&)) { std::vector<aiVector3D> temp; (*GenerateFunc)(num,temp); return MakeMesh(temp,3); } // ------------------------------------------------------------------------------------------------ // Build an incosahedron with points.magnitude == 1 unsigned int StandardShapes::MakeIcosahedron(std::vector<aiVector3D>& positions) { positions.reserve(positions.size()+60); const float t = (1.f + 2.236067977f)/2.f; const float s = sqrt(1.f + t*t); const aiVector3D v0 = aiVector3D(t,1.f, 0.f)/s; const aiVector3D v1 = aiVector3D(-t,1.f, 0.f)/s; const aiVector3D v2 = aiVector3D(t,-1.f, 0.f)/s; const aiVector3D v3 = aiVector3D(-t,-1.f, 0.f)/s; const aiVector3D v4 = aiVector3D(1.f, 0.f, t)/s; const aiVector3D v5 = aiVector3D(1.f, 0.f,-t)/s; const aiVector3D v6 = aiVector3D(-1.f, 0.f,t)/s; const aiVector3D v7 = aiVector3D(-1.f, 0.f,-t)/s; const aiVector3D v8 = aiVector3D(0.f, t, 1.f)/s; const aiVector3D v9 = aiVector3D(0.f,-t, 1.f)/s; const aiVector3D v10 = aiVector3D(0.f, t,-1.f)/s; const aiVector3D v11 = aiVector3D(0.f,-t,-1.f)/s; ADD_TRIANGLE(v0,v8,v4); ADD_TRIANGLE(v0,v5,v10); ADD_TRIANGLE(v2,v4,v9); ADD_TRIANGLE(v2,v11,v5); ADD_TRIANGLE(v1,v6,v8); ADD_TRIANGLE(v1,v10,v7); ADD_TRIANGLE(v3,v9,v6); ADD_TRIANGLE(v3,v7,v11); ADD_TRIANGLE(v0,v10,v8); ADD_TRIANGLE(v1,v8,v10); ADD_TRIANGLE(v2,v9,v11); ADD_TRIANGLE(v3,v11,v9); ADD_TRIANGLE(v4,v2,v0); ADD_TRIANGLE(v5,v0,v2); ADD_TRIANGLE(v6,v1,v3); ADD_TRIANGLE(v7,v3,v1); ADD_TRIANGLE(v8,v6,v4); ADD_TRIANGLE(v9,v4,v6); ADD_TRIANGLE(v10,v5,v7); ADD_TRIANGLE(v11,v7,v5); return 3; } // ------------------------------------------------------------------------------------------------ // Build a dodecahedron with points.magnitude == 1 unsigned int StandardShapes::MakeDodecahedron(std::vector<aiVector3D>& positions, bool polygons /*= false*/) { positions.reserve(positions.size()+108); const float a = 1.f / 1.7320508f; const float b = sqrt((3.f-2.23606797f)/6.f); const float c = sqrt((3.f+2.23606797f)/6.f); const aiVector3D v0 = aiVector3D(a,a,a); const aiVector3D v1 = aiVector3D(a,a,-a); const aiVector3D v2 = aiVector3D(a,-a,a); const aiVector3D v3 = aiVector3D(a,-a,-a); const aiVector3D v4 = aiVector3D(-a,a,a); const aiVector3D v5 = aiVector3D(-a,a,-a); const aiVector3D v6 = aiVector3D(-a,-a,a); const aiVector3D v7 = aiVector3D(-a,-a,-a); const aiVector3D v8 = aiVector3D(b,c,0.f); const aiVector3D v9 = aiVector3D(-b,c,0.f); const aiVector3D v10 = aiVector3D(b,-c,0.f); const aiVector3D v11 = aiVector3D(-b,-c,0.f); const aiVector3D v12 = aiVector3D(c, 0.f, b); const aiVector3D v13 = aiVector3D(c, 0.f, -b); const aiVector3D v14 = aiVector3D(-c, 0.f, b); const aiVector3D v15 = aiVector3D(-c, 0.f, -b); const aiVector3D v16 = aiVector3D(0.f, b, c); const aiVector3D v17 = aiVector3D(0.f, -b, c); const aiVector3D v18 = aiVector3D(0.f, b, -c); const aiVector3D v19 = aiVector3D(0.f, -b, -c); ADD_PENTAGON(v0, v8, v9, v4, v16); ADD_PENTAGON(v0, v12, v13, v1, v8); ADD_PENTAGON(v0, v16, v17, v2, v12); ADD_PENTAGON(v8, v1, v18, v5, v9); ADD_PENTAGON(v12, v2, v10, v3, v13); ADD_PENTAGON(v16, v4, v14, v6, v17); ADD_PENTAGON(v9, v5, v15, v14, v4); ADD_PENTAGON(v6, v11, v10, v2, v17); ADD_PENTAGON(v3, v19, v18, v1, v13); ADD_PENTAGON(v7, v15, v5, v18, v19); ADD_PENTAGON(v7, v11, v6, v14, v15); ADD_PENTAGON(v7, v19, v3, v10, v11); return (polygons ? 5 : 3); } // ------------------------------------------------------------------------------------------------ // Build an octahedron with points.magnitude == 1 unsigned int StandardShapes::MakeOctahedron(std::vector<aiVector3D>& positions) { positions.reserve(positions.size()+24); const aiVector3D v0 = aiVector3D(1.0f, 0.f, 0.f) ; const aiVector3D v1 = aiVector3D(-1.0f, 0.f, 0.f); const aiVector3D v2 = aiVector3D(0.f, 1.0f, 0.f); const aiVector3D v3 = aiVector3D(0.f, -1.0f, 0.f); const aiVector3D v4 = aiVector3D(0.f, 0.f, 1.0f); const aiVector3D v5 = aiVector3D(0.f, 0.f, -1.0f); ADD_TRIANGLE(v4,v0,v2); ADD_TRIANGLE(v4,v2,v1); ADD_TRIANGLE(v4,v1,v3); ADD_TRIANGLE(v4,v3,v0); ADD_TRIANGLE(v5,v2,v0); ADD_TRIANGLE(v5,v1,v2); ADD_TRIANGLE(v5,v3,v1); ADD_TRIANGLE(v5,v0,v3); return 3; } // ------------------------------------------------------------------------------------------------ // Build a tetrahedron with points.magnitude == 1 unsigned int StandardShapes::MakeTetrahedron(std::vector<aiVector3D>& positions) { positions.reserve(positions.size()+9); const float a = 1.41421f/3.f; const float b = 2.4494f/3.f; const aiVector3D v0 = aiVector3D(0.f,0.f,1.f); const aiVector3D v1 = aiVector3D(2*a,0,-1.f/3.f); const aiVector3D v2 = aiVector3D(-a,b,-1.f/3.f); const aiVector3D v3 = aiVector3D(-a,-b,-1.f/3.f); ADD_TRIANGLE(v0,v1,v2); ADD_TRIANGLE(v0,v2,v3); ADD_TRIANGLE(v0,v3,v1); ADD_TRIANGLE(v1,v3,v2); return 3; } // ------------------------------------------------------------------------------------------------ // Build a hexahedron with points.magnitude == 1 unsigned int StandardShapes::MakeHexahedron(std::vector<aiVector3D>& positions, bool polygons /*= false*/) { positions.reserve(positions.size()+36); const float length = 1.f/1.73205080f; const aiVector3D v0 = aiVector3D(-1.f,-1.f,-1.f)*length; const aiVector3D v1 = aiVector3D(1.f,-1.f,-1.f)*length; const aiVector3D v2 = aiVector3D(1.f,1.f,-1.f)*length; const aiVector3D v3 = aiVector3D(-1.f,1.f,-1.f)*length; const aiVector3D v4 = aiVector3D(-1.f,-1.f,1.f)*length; const aiVector3D v5 = aiVector3D(1.f,-1.f,1.f)*length; const aiVector3D v6 = aiVector3D(1.f,1.f,1.f)*length; const aiVector3D v7 = aiVector3D(-1.f,1.f,1.f)*length; ADD_QUAD(v0,v3,v2,v1); ADD_QUAD(v0,v1,v5,v4); ADD_QUAD(v0,v4,v7,v3); ADD_QUAD(v6,v5,v1,v2); ADD_QUAD(v6,v2,v3,v7); ADD_QUAD(v6,v7,v4,v5); return (polygons ? 4 : 3); } // Cleanup ... #undef ADD_TRIANGLE #undef ADD_QUAD #undef ADD_PENTAGON // ------------------------------------------------------------------------------------------------ // Create a subdivision sphere void StandardShapes::MakeSphere(unsigned int tess, std::vector<aiVector3D>& positions) { // Reserve enough storage. Every subdivision // splits each triangle in 4, the icosahedron consists of 60 verts positions.reserve(positions.size()+60 * integer_pow(4, tess)); // Construct an icosahedron to start with MakeIcosahedron(positions); // ... and subdivide it until the requested output // tesselation is reached for (unsigned int i = 0; i<tess;++i) Subdivide(positions); } // ------------------------------------------------------------------------------------------------ // Build a cone void StandardShapes::MakeCone(float height,float radius1, float radius2,unsigned int tess, std::vector<aiVector3D>& positions,bool bOpen /*= false */) { // Sorry, a cone with less than 3 segments makes ABSOLUTELY NO SENSE if (tess < 3 || !height) return; size_t old = positions.size(); // No negative radii radius1 = ::fabs(radius1); radius2 = ::fabs(radius2); float halfHeight = height / 2; // radius1 is always the smaller one if (radius2 > radius1) { std::swap(radius2,radius1); halfHeight = -halfHeight; } else old = SIZE_MAX; // Use a large epsilon to check whether the cone is pointy if (radius1 < (radius2-radius1)*10e-3f)radius1 = 0.f; // We will need 3*2 verts per segment + 3*2 verts per segment // if the cone is closed const unsigned int mem = tess*6 + (!bOpen ? tess*3 * (radius1 ? 2 : 1) : 0); positions.reserve(positions.size () + mem); // Now construct all segments const float angle_delta = (float)AI_MATH_TWO_PI / tess; const float angle_max = (float)AI_MATH_TWO_PI; float s = 1.f; // cos(angle == 0); float t = 0.f; // sin(angle == 0); for (float angle = 0.f; angle < angle_max; ) { const aiVector3D v1 = aiVector3D (s * radius1, -halfHeight, t * radius1 ); const aiVector3D v2 = aiVector3D (s * radius2, halfHeight, t * radius2 ); const float next = angle + angle_delta; float s2 = ::cos(next); float t2 = ::sin(next); const aiVector3D v3 = aiVector3D (s2 * radius2, halfHeight, t2 * radius2 ); const aiVector3D v4 = aiVector3D (s2 * radius1, -halfHeight, t2 * radius1 ); positions.push_back(v1); positions.push_back(v2); positions.push_back(v3); positions.push_back(v4); positions.push_back(v1); positions.push_back(v3); if (!bOpen) { // generate the end 'cap' positions.push_back(aiVector3D(s * radius2, halfHeight, t * radius2 )); positions.push_back(aiVector3D(s2 * radius2, halfHeight, t2 * radius2 )); positions.push_back(aiVector3D(0.f, halfHeight, 0.f)); if (radius1) { // generate the other end 'cap' positions.push_back(aiVector3D(s * radius1, -halfHeight, t * radius1 )); positions.push_back(aiVector3D(s2 * radius1, -halfHeight, t2 * radius1 )); positions.push_back(aiVector3D(0.f, -halfHeight, 0.f)); } } s = s2; t = t2; angle = next; } // Need to flip face order? if ( SIZE_MAX != old ) { for (size_t s = old; s < positions.size();s += 3) { std::swap(positions[s],positions[s+1]); } } } // ------------------------------------------------------------------------------------------------ // Build a circle void StandardShapes::MakeCircle(float radius, unsigned int tess, std::vector<aiVector3D>& positions) { // Sorry, a circle with less than 3 segments makes ABSOLUTELY NO SENSE if (tess < 3 || !radius) return; radius = ::fabs(radius); // We will need 3 vertices per segment positions.reserve(positions.size()+tess*3); const float angle_delta = (float)AI_MATH_TWO_PI / tess; const float angle_max = (float)AI_MATH_TWO_PI; float s = 1.f; // cos(angle == 0); float t = 0.f; // sin(angle == 0); for (float angle = 0.f; angle < angle_max; ) { positions.push_back(aiVector3D(s * radius,0.f,t * radius)); angle += angle_delta; s = ::cos(angle); t = ::sin(angle); positions.push_back(aiVector3D(s * radius,0.f,t * radius)); positions.push_back(aiVector3D(0.f,0.f,0.f)); } } } // ! Assimp
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 502 ] ] ]
4567b9ed7b8ce2acbf8dd50b459e9a187ad71cbf
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume IV/00488.cpp
6fa1e3091e200c2e08421b72d3c6d27d8c31f472
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
728
cpp
///////////////////////////////// // 00488 - Triangle Wave ///////////////////////////////// #include<cstdio> #include<string> #include<vector> const char *a[] = {"1\n","22\n","333\n","4444\n","55555\n", "666666\n","7777777\n","88888888\n","999999999\n"}; char i,j; unsigned int amp,cnum,freq; std::vector <std::string> v(9); int main(void){ for(i = 1; i < 10; i++){ v[i-1] = ""; for(j = 0; j < i; j++) v[i-1] += a[j]; for(j = i-2; j > -1 ; j--) v[i-1] += a[j]; } scanf("%u\n",&cnum); while(cnum--){ scanf("%u\n%u\n",&amp,&freq); const char *ans = v[amp-1].c_str(); while(freq--){ printf("%s",ans); if(freq) putc('\n',stdout); } if(cnum) putc('\n',stdout); } return 0; }
[ [ [ 1, 29 ] ] ]
10bfef3bdc664729ba3a866e4b7da507f08d4e17
353bd39ba7ae46ed521936753176ed17ea8546b5
/tools/libname/test/axxx_test.cpp
fa93d3eb600fe97c161b2fbf887e0da492317d76
[]
no_license
d0n3val/axe-engine
1a13e8eee0da667ac40ac4d92b6a084ab8a910e8
320b08df3a1a5254b776c81775b28fa7004861dc
refs/heads/master
2021-01-01T19:46:39.641648
2007-12-10T18:26:22
2007-12-10T18:26:22
32,251,179
1
0
null
null
null
null
UTF-8
C++
false
false
1,737
cpp
/** * @file * Axe 'libname' test code * @see axe_libname.h */ #include "axxx_test.h" #define AXXX_NO_AUTOLINK #include "axe_libname.h" /// Version of this test code #define AXE_LIBNAME_TEST_VERSION 1 // Use proper library -------- #ifdef _DEBUG #pragma comment( lib, "../../../output_debug/lib/axe_libname.lib" ) #else #pragma comment( lib, "../../../output_release/lib/axe_libname.lib" ) #endif /** * Checks for the current 'error' state of the library */ void error( int num, const char* file, long line ) { printf( "\n\n\n*** ERROR in %s(%u): %s\n", file, line, axxx_get_error_message(num) ); getchar(); } /** * Checks if this code and the lib have the same version */ int check_versions() { printf( "\nGetting lib version ... " ); int lib_version = axxx_get( AXXX_VERSION ); if( lib_version != AXE_LIBNAME_TEST_VERSION ) { printf( "This test program and the library versions differ! Lib:%d Test:%d\n", lib_version, AXE_LIBNAME_TEST_VERSION ); getchar(); return( 0 ); } printf( "Library Version: %d - This testing program: %d\n\n", lib_version, AXE_LIBNAME_TEST_VERSION ); return( 1 ); } /** * Simple code to test all functionality of the library */ int main() { printf( "Axe 'libname' library test STARTED\n" ); // Check versions ------------------------------------ if( check_versions() == 0 ) { return( 0 ); } // Start --------------------------------------------- getchar(); // Finish -------------------------------------------- printf( "\nAxe 'libname' library test FINISHED\n" ); return( 1 ); } /* $Id: axpl_test.cpp,v 1.1 2004/07/27 22:42:49 doneval Exp $ */
[ "d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54" ]
[ [ [ 1, 76 ] ] ]
0b56c7537edfe9fdef4bb9348ff5a6af0dad70cb
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/sound/src/SoundChannel.cpp
2ec8494dbac47d545f6f0861f504cf3b44f9cfeb
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,904
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "SoundChannel.h" #include <OgreMovableObject.h> #include <OgreAxisAlignedBox.h> #include <OgreVector3.h> #include "Sound.h" #include "SoundSubsystem.h" extern "C" { #include <fmod.h> } Ogre::String rl::SoundChannel::msMovableType = "SoundChannel"; Ogre::AxisAlignedBox rl::SoundChannel::msAABox = Ogre::AxisAlignedBox(-0.5, -0.5, -0.5, 0.5, 0.5, 0.5); using namespace Ogre; namespace rl { SoundChannel::SoundChannel(Sound *sound, const Ogre::String &name) : MovableObject(), mChannel(NO_CHANNEL), mSound(sound), mName(name) { } SoundChannel::~SoundChannel() { FSOUND_StopSound(getChannel()); if (mSound) { delete mSound; } } /** * @author JoSch * @date 07-23-2005 */ void SoundChannel::play() throw (RuntimeException) { if (!mSound->isValid()) { mSound->load(); } setChannel(mSound->createChannel()); setGain(255); setPosition(Vector3(0.0, 0.0, 0.0)); setDirection(Vector3(0.0, 0.0, 0.0)); setVelocity(Vector3(0.0, 0.0, 0.0)); FSOUND_3D_SetMinMaxDistance(mChannel, 4.0, 9999999.0); pause(false); } /** * @author JoSch * @date 03-11-2005 * @return Den Namen */ const String& SoundChannel::getName() const { return mName; } /** * @author JoSch * @date 07-04-2005 * @return Der Soundkanal */ const signed int SoundChannel::getChannel() const { return mChannel; } /** * @author JoSch * @date 07-21-2005 * @param channel Der Soundkanal */ void SoundChannel::setChannel(signed int channel) { mChannel = channel; } /** * @author JoSch * @date 03-11-2005 * @return Den Objekttypen */ const String& SoundChannel::getMovableType() const { return msMovableType; } /** * @author JoSch * @date 03-11-2005 */ void SoundChannel::_notifyCurrentCamera(Camera *cam) { // Brauchen wir nicht zu wissen. } /** * @author JoSch * @date 03-11-2005 */ const AxisAlignedBox& SoundChannel::getBoundingBox() const { return msAABox; } /** * @author JoSch * @date 03-11-2005 */ Real SoundChannel::getBoundingRadius (void) const { return 0.0; } /** * @author JoSch * @date 03-11-2005 */ void SoundChannel::_updateRenderQueue(RenderQueue *queue) { // Brauchen wir nicht } /** * @return Die aktuelle Richtung der Soundquelle * @author JoSch * @date 07-23-2004 */ const Vector3 SoundChannel::getDirection() const throw (RuntimeException) { Vector3 result; return result; } /** * @param direction Die neue Richtung der Soundquelle. * @author JoSch * @date 07-23-2004 */ void SoundChannel::setDirection (const Vector3& direction) throw (RuntimeException) { // TODO } /** * @return Ist der Kanal gueltig? * @author JoSch * @date 08-05-2005 */ bool SoundChannel::isValid() const throw (RuntimeException) { return mSound->isValid() && (mChannel > 0); } /** * @return Spielt die Soundquelle noch? * @author JoSch * @date 07-04-2005 */ const bool SoundChannel::isPlaying() const { if (isValid()) { return FSOUND_IsPlaying(getChannel()); } return false; } bool SoundChannel::isLooping() const { return mSound->isLooping(); } void SoundChannel::setLooping( bool looping ) { mSound->setLooping( looping ); } bool SoundChannel::is3d() const { return mSound->is3d(); } void SoundChannel::set3d( bool is3d ) { mSound->set3d(is3d); } /** * @return Die aktuelle Position der Soundquelle * @author JoSch * @date 07-04-2005 */ const Vector3 SoundChannel::getPosition() const throw (RuntimeException) { float pos[3]; if (isValid()) { FSOUND_3D_GetAttributes(getChannel(), pos, 0); } Vector3 result(pos); return result; } class SoundSampleMovable; /** * @param position Die neue Position der Soundquelle. * @author JoSch * @date 07-04-2005 */ void SoundChannel::setPosition(const Vector3& position) throw (RuntimeException) { if (isValid()) { float pos[] = {position[0], position[1], position[2]}; FSOUND_3D_SetAttributes(getChannel(), pos, 0); } } /** * @return Die aktuelle Geschwindigkeit der Soundquelle * @author JoSch * @date 07-04-2005 */ const Vector3 SoundChannel::getVelocity() const throw (RuntimeException) { float vel[3]; if (isValid()) { FSOUND_3D_GetAttributes(getChannel(), 0, vel); } Vector3 result(vel); return result; } /** * @param velocity Die neue Geschwindigkeit der Soundquelle. * @author JoSch * @date 07-04-2005 */ void SoundChannel::setVelocity(const Vector3& velocity) throw (RuntimeException) { if (isValid()) { float vel[] = {velocity[0], velocity[1], velocity[2]}; FSOUND_3D_SetAttributes(getChannel(), 0, vel); } } /** * @return Die aktuelle Lautstaerke der Soundquelle * @author JoSch * @date 07-04-2005 */ const int SoundChannel::getGain() const throw (RuntimeException) { if (isValid()) { return FSOUND_GetVolume(getChannel()); } return 0; } /** * @param gain Die neue Lautstarke der Soundquelle. * @author JoSch * @date 07-04-2005 */ void SoundChannel::setGain(const int gain) throw (RuntimeException) { if (isValid()) { FSOUND_SetVolume(getChannel(), gain); } } /** * @param pausing TRUE l�sst den Sound unterbrechen. * @author JoSch * @date 07-04-2005 */ void SoundChannel::pause(bool pausing) throw (RuntimeException) { if (isValid()) { FSOUND_SetPaused(getChannel(), pausing); } } /** * @author JoSch * @date 07-23-2004 */ void SoundChannel::stop() throw (RuntimeException) { if (isValid()) { FSOUND_StopSound(getChannel()); } } /** * @return TRUE wenn der Sound unterbrochen wurde. * @author JoSch * @date 07-04-2005 */ bool SoundChannel::isPaused() throw (RuntimeException) { if (isValid()) { return FSOUND_GetPaused(getChannel()); } return true; } };
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 344 ] ] ]
acccbd9da07df7367eaaeb64e207b2a389888459
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/LiteEditor/shell_window.h
2a52d485a3440341c65ca6b17379c0f9580744e7
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
#ifndef SHELL_WINDOW_H #define SHELL_WINDOW_H #include "wx/wxscintilla.h" class ShellWindow : public wxScintilla { protected: void ConnectEvents(); public: ShellWindow(wxWindow *parent); virtual ~ShellWindow(); void AppendLine(const wxString &text); void Clear(); void OnKeyDown(wxKeyEvent &event); }; #endif // SHELL_WINDOW_H
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 19 ] ] ]
040806cf33c0484132fcbb24ba9d84e380ca81e0
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/TransCritical/TTechWOR/TTWORPrecip.cpp
ce8b5c6f47e35ae7b7b6685c7ca9045da6826624
[]
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
17,543
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // New Precipitation model Transcritical Technologies Pty Ltd Feb 05 // Time-stamp: <2006-09-28 14:35:50 Rod Stephenson Transcritical Pty Ltd> // Copyright (C) 2005 by Transcritical Technologies Pty Ltd and KWA //=========================================================================== #include "stdafx.h" #include "TTWORPrecip.h" //=========================================================================== // Define the species in the particular precipiation model... static MInitialiseTest InitTest("Precip"); //static MSpeciePtr spAlumina (InitTest, "NaAl[OH]4(l)", false); //static MSpeciePtr spTHA (InitTest, "Al[OH]3(s)", false); static MSpeciePtr spAlumina (InitTest, "Al2O3(l)", false); static MSpeciePtr spTHA (InitTest, "Al2O3.3H2O(s)", false); static MSpeciePtr spWater (InitTest, "H2O(l)", false); static MSpeciePtr spWaterVapor (InitTest, "H2O(g)", false); static MSpeciePtr spCausticSoda (InitTest, "NaOH(l)", false); static MSpeciePtr spOccSoda (InitTest, "Na2O(s)", false); static MSpeciePtr spCarbonate (InitTest, "Na2CO3(l)", false); static MSpeciePtr spOrganics (InitTest, "NaOrg(l)", false); // static MSpeciePtr spBoundOrganics (InitTest, "Na2C5.2O7.2*(s)", false); enum PrecipComponents {iALUMINA, iOCC_SODA, iBOUND_ORGANICS, iWATER, nPRECIPCOMPS}; enum {GRM_AAEq, GRM_sigma}; enum {PB_None, PB_SSA, PB_PSD}; // Particle balance model const long idFeed = 0; const long idUflow = 1; const long idOflow = 2; static MInOutDefStruct s_IODefs[]= { { "Feed", "Feed", idFeed, 1, 10, 0, 1.0f, MIO_In |MIO_Material }, { "Underflow", "UFlow", idUflow, 1, 1, 0, 1.0f, MIO_Out|MIO_Material }, { "Overflow", "OFlow", idOflow, 0, 1, 1, 1.0f, MIO_Out|MIO_Material }, { NULL }, }; double Drw_CPrecipitator[] = { MDrw_Poly, -5,10, -5,-10, 5,-10, 5,10, MDrw_End }; //--------------------------------------------------------------------------- DEFINE_TRANSFER_UNIT(CPrecipitator, "Precipitator", DLL_GroupName) void CPrecipitator_UnitDef::GetOptions() { SetDefaultTag("PC"); SetDrawing("Tank", Drw_CPrecipitator); SetTreeDescription("Worsley:Precipitator"); SetDescription("TODO: Worsley Precip Model"); SetModelSolveMode(MSolveMode_Probal); SetModelGroup(MGroup_Alumina); SetModelLicense(MLicense_HeatExchange|MLicense_Alumina); }; //--------------------------------------------------------------------------- long CPrecipitator::m_lGrowthTerm = GRM_sigma; long CPrecipitator::m_lNuclTerm = GRM_AAEq; long CPrecipitator::m_lSodaTerm = 0; double CPrecipitator::m_dActEGrowth = -12260.; double CPrecipitator::m_dActENucleation = 8344. ; double CPrecipitator::m_dActESoda = 2535.; double CPrecipitator::m_dK_G = 2.18e15 ; double CPrecipitator::m_dK_N = 2.211e-6 ; double CPrecipitator::m_dn_s = 1.0; double CPrecipitator::m_dgamma_2 = 1.00; double CPrecipitator::m_dgamma_g = 2.0; double CPrecipitator::m_dgamma_N = 2.0; double CPrecipitator::m_dgamma_s = 2.00; #include "wordata.cpp" CPrecipitator::CPrecipitator(MUnitDefBase *pUnitDef, TaggedObject * pNd) : MBaseMethod(pUnitDef, pNd), SavedTank(this, "Tank") // Evap(this, "Evap") { //default values... // x=new double[4]; // xo = new double[4]; m_bEvapConnected = 0; bKernelOK = false; bVerbose = false; bOnLine = 1; dTempDropRqd = 0.5; dFixedTempRqd = C2K(70); dThermalLossRqd = 1500.0; iThermalLossMethod = THL_TempDrop; iCoolMethod=0; bTest = 0; dTankVol = 3000; dAggMinLim = .5; iPSD=1; dSolPrecip = 0.0; dGrowthRate = 0.0; dGrowthRateFactor = 0.0; dYield = 0.0; dTin = C2K(25.0); dTout = C2K(25.0); dQvin = 0.0; dQvout = 0.0; dACin = 0.0; dACout = 0.0; dResidenceTime = 0.0; dThermalLoss = 0.0; dReactionHeat = 0.0; m_dCoolOutTotHz = 0.0; dtact = 0.5; m_dAcc = 20.; // Planat Parameters m_lMaxAgglomClass = 18; m_dSurfaceAct = 1.0; m_dSodaConst = 9e-3; m_dKAgglom = 8.5e-13; m_dNuclPlantCorr = 300.0; alreadySolved = false; m_dBypass = 0.05; m_dSharp_Index = 5.0 ; m_dCut_Size = 100.0; m_dSlurry_split = .05; m_dOverpass = 0.0; m_dL0 = 0.0; m_lIterations = 0; m_lItermax = 50; } //--------------------------------------------------------------------------- CPrecipitator::~CPrecipitator() { // delete[] x; // delete[] xo; } //--------------------------------------------------------------------------- void CPrecipitator::Init() { SetIODefinition(s_IODefs); #ifdef TTDEBUG dbg.tcltk_init(); #endif } //--------------------------------------------------------------------------- const long OM_Simple = 0; const long OM_Condensing = 1; //--------------------------------------------------------------------------- // Modified for NaAl[OH]4 as primary species. void CPrecipitator::AdjustMasses() { double InAluminaMass = Feed.MassVector[spAlumina]; // Al2O3(l) double InWaterMass = Feed.MassVector[spWater]; // H2O double InTHAMass = Feed.MassVector[spTHA]; // Al[OH]3(s) double InCausticMass = Feed.MassVector[spCausticSoda]; // NaOH double InOccSodaMass = Feed.MassVector[spOccSoda]; double InOrganicMass = Feed.MassVector[spOrganics]; // double &InBoundOrganicMass = Feed.MassVector[spBoundOrganics]; MVDouble AluminaMass (Tank, spAlumina); // Al2O3(l) MVDouble WaterMass (Tank, spWater); // H2O MVDouble THAMass (Tank, spTHA); // Al[OH]3(s) MVDouble CausticMass (Tank, spCausticSoda); // NaOH MVDouble OccSodaMass (Tank, spOccSoda); MVDouble OrganicMass (Tank, spOrganics); // double &BoundOrganicMass = Tank.MassVector[spBoundOrganics]; const int NumSpecies = gs_MVDefn.Count(); for (int i=0; i<NumSpecies; i++) Tank.M[i] = Feed.M[i]; if (m_dMassDamping>0.0) { // Mass damping terms... may only be needed at veryhigh rates for (int i=0; i<nPRECIPCOMPS; i++) x[i] = xo[i]*m_dMassDamping+x[i]*(1-m_dMassDamping); } /// // adjust masses... x is mass of precipitated Gibbsite AluminaMass = InAluminaMass - Alpha*x[iALUMINA]; THAMass = InTHAMass + x[iALUMINA]; CausticMass = InCausticMass - (2*MW_NaOH)/MW_Na2O*x[iOCC_SODA]; //OrganicMass = InOrganicMass - x[iBOUND_ORGANICS]; // BoundOrganicMass = InBoundOrganicMass + x[iBOUND_ORGANICS]; OccSodaMass = InOccSodaMass + x[iOCC_SODA]; WaterMass = InWaterMass - x[iWATER] - (1-Alpha)*x[iALUMINA]+MW_H2O/MW_Na2O*x[iOCC_SODA]; // if (m_bUpdateT) Tank.MarkStateChanged(); // Manual fixup of heat loads eventually... } void CPrecipitator::AdjustT() { double dHeatIn = Feed.totHz(); dReactionHeat = x[iALUMINA]*GibbsiteHOR(K2C(Tank.T)); double newTotDH = m_dOldTotDH*m_dDamping+(m_dTotThermalLoss-dReactionHeat)*(1-m_dDamping); if (iThermalLossMethod == THL_TempDrop) Tank.T = Feed.T - dTempDropRqd; else if (iThermalLossMethod == THL_FixedTemp) Tank.T = dFixedTempRqd; else Tank.Set_totHz(dHeatIn - newTotDH); m_dOldTotDH = newTotDH; } void CPrecipitator::AdjustSSA() { } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // All the precipitation rate calcs are done in this routine // Takes the tank composition and calculates rates from this // Rates (in kg/s) are put into global x //--------------------------------------------------------------------------- void CPrecipitator::EvalPrecipRates(MStream & Tank) { Numbers(Tank); xo[0] = x[0]; xo[1]=x[1]; xo[2]=x[2]; xo[3]=x[3]; double solidsIn = m_PSDin.getVol()*Feed.Volume(MP_All, C2K(25.))*2420; double solidsOut = m_PSD1.getVol()*Tank.Volume(MP_All, C2K(25.))*2420; x[iALUMINA] = (solidsOut-solidsIn); // Precipitation is as trihydrate double xx = x[iALUMINA]; x[iBOUND_ORGANICS]=0.; x[iOCC_SODA]=x[iALUMINA]*dSoda/100.; //x[iOCC_SODA] = 0; x[iALUMINA] -= x[iOCC_SODA]; x[iWATER]= 0.0; } //--------------------------------------------------------------------------- // All the thermal loss calcs are done in this routine // Also calculate the water loss through evaporation // m_dTotThermalLoss is the total thermal loss, //--------------------------------------------------------------------------- void CPrecipitator::EvalLosses(MStream &Tank) { } void CPrecipitator::AdjustPSD() { m_PSD1 = BrahmaPSD(NewN); m_PSD1.put(Tank); } //------------------------------------------------------------------------ // Check for convergence of the iteration // // //------------------------------------------------------------------------ bool CPrecipitator::ConvergenceTest() { double xmag = (x[0]*x[0]+x[1]*x[1]+x[2]*x[2]); double err = (Sqr(x[0]-xo[0]) + Sqr(x[1]-xo[1]) +Sqr(x[2]-xo[2]))/GTZ(xmag); //double err = 0.0; double nn=0; double nt =0; for (int i=1; i<=nClasses; i++) { if (NewN[i]==0 && n[i]==0) {} else err += Sqr((NewN[i]-n[i])/(NewN[i]+n[i])); // nn+= Sqr(NewN[i]); // nt+= Sqr(NewN[i]-n[i]); } // err += nt/GTZ(nn); for (int i=1; i<=nClasses; i++) n[i] = NewN[i]; if (err < m_dConvergenceLimit) return true; else return false; } void CPrecipitator::DoClassifier(MStream & OFlow, MStream &UFlow) { double pVol_U = 0.0, pVol_O=0.0, mO=0.0, mU=0.0; double eff, ab, nl[nClasses+1][2]; double xS; MIPSD & FeedPSD = Feed.IF<MIPSD>(false); MIPSD & OFPSD = OFlow.IF<MIPSD>(false); MIPSD & UFPSD = UFlow.IF<MIPSD>(false); for (int i=0; i<=nClasses; i++) { if (m_dL0==0) ab=m_dBypass; else ab=m_dBypass*(1-Lav[i]/m_dL0); switch (iClassMethod) { case CM_Molerus: eff = ab + (1-ab) * (1-m_dOverpass) / ( 1 + pow(Lav[i]/m_dCut_Size, -m_dSharp_Index) ); break; case CM_Lynch: eff = ab + (1-ab) * (1-m_dOverpass) * ( exp(m_dSharp_Index*Lav[i]/m_dCut_Size) - 1 ) / ( exp(m_dSharp_Index) + exp(m_dSharp_Index*Lav[i]/m_dCut_Size) - 2 ); break; case CM_Plitt: eff = ab + (1-ab) * (1-m_dOverpass) * ( 1 - exp(-0.693147*pow(Lav[i]/m_dCut_Size, m_dSharp_Index)) ); break; } nl[i][0]=FeedPSD.getFrac(i)*eff; nl[i][1]=FeedPSD.getFrac(i)*(1-eff); mU += nl[i][0]; mO += nl[i][1]; dd[7][i] = eff; } if (mO+mU !=0.0) xS = mU/(mU+mO); else xS = 1.0; m_dxS = xS; m_dEff = eff; UFlow.SetF(Feed, MP_Liq, m_dSlurry_split); UFlow.AddF(Feed, MP_Sol, xS); OFlow.SetF(Feed, MP_Liq, 1.-m_dSlurry_split); OFlow.AddF(Feed, MP_Sol, 1.-xS); for (int i=0; i<=nClasses; i++) { if (xS<1.0) OFPSD.putFrac(i, nl[i][1]/(1-xS)); UFPSD.putFrac(i, nl[i][0]/xS); } OFPSD.Normalise(); UFPSD.Normalise(); } void CPrecipitator::DoResults() { MIBayer & FeedB=Feed.IF<MIBayer>(false); MIBayer & TankB=Tank.IF<MIBayer>(false); m_dNuclN = m_PSDin.getN()-m_PSD.getN(); dACin = FeedB.AtoC(); dACout = TankB.AtoC(); dQvin = Feed.Volume(); dQvout = Tank.Volume(); dQmin = Feed.Mass(); dQmout = Tank.Mass(); double dQvout25 = Tank.Volume(MP_All, C2K(25)); double Cout = TankB.CausticConc(Tank.T); m_dACeq = TankB.AluminaConcSat(Tank.T)/Cout; double ACTank = TankB.AtoC(); m_dSSat = ACTank/m_dACeq; m_dBSSat = (ACTank - m_dACeq)/(m_dACeq*(1-1.039*ACTank)); dYield = Cout*(dACin-dACout); double SolIn = Feed.MassVector[spTHA]; double SolOut = Tank.MassVector[spTHA]; dTHAPrecip = SolOut - SolIn; dAlPrecip = dTHAPrecip*102/156; SolIn = Feed.Mass(MP_Sol); SolOut = Tank.Mass(MP_Sol); dSolPrecip = SolOut - SolIn; dSolConc = Tank.Mass(MP_Sol)/dQvout25; m_dLiquorTin = Tank.T; dTin = Feed.T; dTout = Tank.T; m_dNucleation = m_dNuclN * PI/6*1.4618*Sqr(L[1])*L[1]*1e-18*Tank.Density(MP_Sol); dResidenceTime = dTankVol/GTZ(Tank.Volume(MP_SL)); dFeedNTot = Feed.Volume(MP_All, C2K(25))*m_PSDin.getN(); dProdNTot = Tank.Volume(MP_All, C2K(25))*m_PSD1.getN(); dSSA = m_PSD1.getArea()/dSolConc/1000.; } void CPrecipitator::EvalProducts() { try { x[0] = x[1] = x[2] = x[3] = 0.0; FlwIOs.AddMixtureIn_Id(Feed, idFeed); MStream & UFlow = FlwIOs[FlwIOs.First[idUflow]].Stream; //Reference to the output stream MStream & OFlow = FlwIOs[FlwIOs.First[idOflow]].Stream; //Reference to the output stream MStreamI OutFlow; if (SavedTank.MassFlow() < 1.0e-5 || !bTest) { Tank = Feed; } else { Tank = SavedTank; } OFlow = Feed; UFlow = Feed; OFlow.SetF(Feed, MP_All, 0.0); UFlow.SetF(Feed, MP_All, 1.0); bool streamOK=(Feed.Mass()>1.0e-4); if (streamOK) { // Check for existence of Bayer Property... MIBayer & FeedB=Feed.IF<MIBayer>(false); // Do the checks up front if (bVerbose) Log.SetCondition(IsNothing(FeedB), 1, MMsg_Warning, "Bad Feed Stream - Not BATC Bayer Model"); // Try PSD MIPSD & FeedPSD = Feed.IF<MIPSD>(false); if (!IsNothing(FeedPSD)) { lPBType = PB_PSD; m_PSDin = BrahmaPSD(Feed); } else { // Try SSA... MISSA & FeedSSA = Feed.IF<MISSA>(false); if (!IsNothing(FeedSSA)) lPBType = PB_SSA; else lPBType = PB_None; } if (bVerbose) Log.SetCondition(lPBType==PB_None, 1, MMsg_Warning, "Bad Feed Stream - No PSD or SSA Property"); if (IsNothing(FeedB) || IsNothing(FeedPSD)) streamOK = false; if (!IsNothing(FeedPSD)) { displayPSD(Feed, 2); } } else { if (bVerbose) Log.SetCondition(!streamOK, 1, MMsg_Warning, "Zero Flow"); } if (bOnLine && streamOK) { // Online and have Bayer and SSA properties... if (!bKernelOK) { AgglomKernel(); bKernelOK = true; } DoPrecip(); displayPSD(m_PSDin, 4); displayPSD(m_PSD1, 5); DoResults(); UFlow = Tank; alreadySolved = true; SavedTank = Tank; if (bClassOn) // Online and have Bayer and SSA properties... DoClassifier(OFlow, UFlow); } else { // Just tidy up and put some sensible stuff in the results... } } catch (MMdlException &e) { Log.Message(MMsg_Error, e.Description); } catch (MFPPException &e) { e.ClearFPP(); Log.Message(MMsg_Error, e.Description); } catch (MSysException &e) { Log.Message(MMsg_Error, e.Description); } catch (...) { Log.Message(MMsg_Error, "Some Unknown Exception occured"); } } //-------------------------------------------------------------------------- void CPrecipitator::ClosureInfo(MClosureInfo & CI) {//ensure heat balance if (CI.DoFlows()) { CI.AddPowerIn(0, -dThermalLoss); } } void CPrecipitator::DoPrecip() { bool converged = false; int Iter=1; // Number of iterations in main loop m_dOldTotDH = 0.0; MIBayer & tb=Tank.IF<MIBayer>(false); m_PSD = BrahmaPSD(Feed); m_PSD1 = BrahmaPSD(Tank); m_PSD1.getN(n); while (!converged && Iter < m_lItermax) { // Main iterative loop on final temperature and concentration m_lIterations = Iter; EvalPrecipRates(Tank); /// Determine the precipitation rates EvalLosses(Tank); /// Evaluate the thermal losses AdjustMasses(); /// Adjust the mass flows AdjustT(); /// Adjust temperature for thermal losses, reaction heats etc // AdjustSSA(Tank); /// Adjust SSA AdjustPSD(); /// Adjust PSD converged = ConvergenceTest(); //// Final convergence test Iter++; } if (Iter==m_lItermax) {/// Convergence Failure, automatically increase damping and iterations??? } m_lIterations = Iter; Log.SetCondition(Iter==m_lItermax, 4, MMsg_Warning, "No convergence of precip routine"); } void CPrecipitator::displayPSD(MStream &ms, int scrn) { MIPSD & mpsd = ms.IF<MIPSD>(false); /// Does the mud stream have PSD... int ic = mpsd.getSizeCount(); if (ic>40) ic=40; double x; BrahmaPSD p(ms); for (int i=0; i<ic; i++) { switch (iPSD) { case 0: x = mpsd.getMass(i); break; case 1: x = mpsd.getFrac(i); break; case 2: x = p.getN(i); break; } dd[scrn][i]=x; } } void CPrecipitator::displayPSD(BrahmaPSD &p, int scrn) { for (int i=0; i<=nClasses; i++) { dd[scrn][i]=p.getN(i); } dd[scrn][26] = p.getN(); dd[scrn][27] = p.getArea(); dd[scrn][28] = p.getVol(); dd[scrn][29]=0.0; } double CEquil(MStream & s, double T) { MStream s1 = s; MIBayer & sB=s.IF<MIBayer>(false); double asat = sB.AluminaConcSat(T); return asat; } #include "worcalc.cpp"
[ [ [ 1, 201 ], [ 208, 209 ], [ 216, 684 ] ], [ [ 202, 207 ], [ 210, 215 ] ] ]
90fca97b84be12f0e7cdf6a2c756f7ed76387cef
12d2d19ae9e12973a7d25b97b5bc530b82dd9519
/deliciousServer/DMServiceLocalDBImpl.cpp
a8fa8b6ecdfd37bb4a3e0778a2a2bfdc81404f6a
[]
no_license
gaoxiaojun/delicacymap
fe82b228e89d3fad48262e03bd097a9041c2a252
aceabb664bbd6f7b87b0c9b8ffdad55bc6310c68
refs/heads/master
2021-01-10T11:11:51.412815
2010-05-05T02:36:14
2010-05-05T02:36:14
47,736,729
0
0
null
null
null
null
UTF-8
C++
false
false
21,274
cpp
#include "stdafx.h" #include "DMServiceLocalDBImpl.h" #include "DBResult.h" #include "ProtubufDBRowConversion.h" #include <vector> #include <boost/function.hpp> #include <boost/bind.hpp> using namespace std; using namespace google::protobuf; using namespace ProtocolBuffer; using namespace boost; DMServiceLocalDBImpl::DMServiceLocalDBImpl(google::protobuf::RpcController* controller) { this->controller = controller; } DMServiceLocalDBImpl::~DMServiceLocalDBImpl(void) { } void DMServiceLocalDBImpl::CallMethod( protorpc::FunctionID method_id, google::protobuf::RpcController* controller, const google::protobuf::MessageLite* request, google::protobuf::MessageLite* response, google::protobuf::Closure* done ) { switch (method_id) { case protorpc::GetRestaurants: GetRestaurants(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::RestaurantList*>(response), done); break; case protorpc::GetLastestCommentsOfRestaurant: GetLastestCommentsOfRestaurant(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::CommentList*>(response), done); break; case protorpc::GetLastestCommentsByUser: GetLastestCommentsByUser(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::CommentList*>(response), done); break; case protorpc::GetCommentsOfUserSince: GetCommentsOfUserSince(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::CommentList*>(response), done); break; case protorpc::GetCommentsOfRestaurantSince: GetCommentsOfRestaurantSince(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::CommentList*>(response), done); break; case protorpc::UserLogin: UserLogin(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::User*>(response), done); break; case protorpc::RegisterUser: RegisterUser(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::User*>(response), done); break; case protorpc::GetUserInfo: GetUser(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::User*>(response), done); break; case protorpc::UpdateUserInfo: UpdateUserInfo(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::User*>(response), done); break; case protorpc::GetRelatedUsers: GetRelatedUsers(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::UserList*>(response), done); break; case protorpc::AddCommentForRestaurant: AddCommentForRestaurant(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::Comment*>(response), done); break; case protorpc::SetUserRelation: SetUserRelation(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), done); break; case protorpc::AddRestaurant: AddRestaurant(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::Restaurant*>(response), done); break; case protorpc::Search: Search(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::SearchResult*>(response), done); break; case protorpc::GetSubscribtionInfo: GetSubscribtionInfo(controller, ::google::protobuf::down_cast<const ::ProtocolBuffer::Query*>(request), ::google::protobuf::down_cast< ::ProtocolBuffer::SearchResult*>(response), done); break; default: pantheios::log_CRITICAL("Not handled method id!!!(CallMethod)"); } } void DMServiceLocalDBImpl::GetRestaurants( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::RestaurantList* response, ::google::protobuf::Closure* done ) { //validate query if (request->has_area() && request->has_level()) { try { deliciousDataAdapter::GetInstance()->QueryRestaurantWithinLocation( request->area().southwest().longitude(), request->area().southwest().latitude(), request->area().northeast().longitude(), request->area().northeast().latitude(), request->level(), bind(&DMServiceLocalDBImpl::GetRestaurantsCallback, this, _1, response)); //pantheios::log_DEBUG(response->Utf8DebugString()); } catch (const std::exception &e) { pantheios::log_ERROR(e.what()); controller->SetFailed("Error calling GetRestaurants()."); } } else { pantheios::log_WARNING("calling GetRestaurants() with wrong request message."); controller->SetFailed("calling GetRestaurants() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetLastestCommentsOfRestaurant( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::CommentList* response, ::google::protobuf::Closure* done ) { if (request->has_rid() && request->has_n()) { deliciousDataAdapter::GetInstance()->QueryLatestCommentsOfRestaurant( request->rid(), request->n(), bind(&DMServiceLocalDBImpl::GetCommentsCallback, this, _1, response)); //pantheios::log_DEBUG(response->DebugString()); } else { pantheios::log_WARNING("calling GetLastestCommentsOfRestaurant() with wrong request message."); controller->SetFailed("calling GetLastestCommentsOfRestaurant() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetCommentsOfRestaurantSince( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::CommentList* response, ::google::protobuf::Closure* done ) { if (request->has_rid() && request->has_time()) { deliciousDataAdapter::GetInstance()->QueryCommentsOfRestaurantSince( request->rid(), request->time().timestamp(), bind(&DMServiceLocalDBImpl::GetCommentsCallback, this, _1, response)); //pantheios::log_DEBUG(response->DebugString()); } else { pantheios::log_WARNING("calling GetCommentsOfRestaurantSince() with wrong request message."); controller->SetFailed("calling GetCommentsOfRestaurantSince() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetLastestCommentsByUser( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::CommentList* response, ::google::protobuf::Closure* done ) { if (request->has_uid() && request->has_n()) { deliciousDataAdapter::GetInstance()->QueryLastestCommentsByUser( request->uid(), request->n(), bind(&DMServiceLocalDBImpl::GetCommentsCallback, this, _1, response)); //pantheios::log_DEBUG(response->DebugString()); } else { pantheios::log_WARNING("calling GetLastestCommentsByUser() with wrong request message."); controller->SetFailed("calling GetLastestCommentsByUser() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetCommentsOfUserSince( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::CommentList* response, ::google::protobuf::Closure* done ) { if (request->has_uid() && request->has_time()) { deliciousDataAdapter::GetInstance()->QueryCommentsOfUserSince( request->uid(), request->time().timestamp(), bind(&DMServiceLocalDBImpl::GetCommentsCallback, this, _1, response)); //pantheios::log_DEBUG(response->DebugString()); } else { pantheios::log_WARNING("calling GetCommentsOfUserSince() with wrong request message."); controller->SetFailed("calling GetCommentsOfUserSince() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::AddCommentForRestaurant( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::Comment* response, ::google::protobuf::Closure* done ) { if (request->has_uid() && request->has_rid() && request->has_msg()) { DBResultWrap ret = deliciousDataAdapter::GetInstance()->PostCommentForRestaurant( request->rid(), request->uid(), request->msg(), request->has_image() ? &request->image() : NULL); if (!ret.empty()) { const DBRow& newcomment = ret.getResult()->GetRow(0); ProtubufDBRowConversion::Convert(newcomment, *response); ProtubufDBRowConversion::Convert(newcomment, *response->mutable_userinfo()); } else { pantheios::log_WARNING("AddCommentForRestaurant() did not return any results, SQLite error?."); controller->SetFailed("Add Comment failed."); } } else { pantheios::log_WARNING("calling AddCommentForRestaurant() with wrong request message."); controller->SetFailed("calling AddCommentForRestaurant() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::UserLogin( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::User* response, ::google::protobuf::Closure* done ) { if (request->has_password() && request->has_emailaddress()) { DBResultWrap ret = deliciousDataAdapter::GetInstance()->UserLogin(request->emailaddress(), request->password()); if (!ret.empty()) { const DBRow& usr = ret.getResult()->GetRow(0); ProtubufDBRowConversion::Convert(usr, *response); // preferTypes and friends is not implemented yet. } else { pantheios::log_INFORMATIONAL("Login failed. usr=", request->emailaddress(), ", pwd=", request->password(), "."); controller->SetFailed("Username password mismatch."); } } else { pantheios::log_WARNING("calling UserLogin() with wrong request message."); controller->SetFailed("calling UserLogin() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetUser( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::User* response, ::google::protobuf::Closure* done ) { if (request->has_uid()) { DBResultWrap ret = deliciousDataAdapter::GetInstance()->GetUserInfo(request->uid()); if (!ret.empty()) { const DBRow& usr = ret.getResult()->GetRow(0); ProtubufDBRowConversion::Convert(usr, *response); response->set_password(""); // preferTypes and friends is not implemented yet. } else { pantheios::log_INFORMATIONAL("No user exist whose uid = ", pantheios::integer(request->uid()), "."); controller->SetFailed("User do not exist."); } } else { pantheios::log_WARNING("calling GetUser() with wrong request message."); controller->SetFailed("calling GetUser() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::UpdateUserInfo( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::User* response, ::google::protobuf::Closure* done ) { if (request->has_uid() && request->has_password() && request->has_userinfo()) { deliciousDataAdapter* adapter = deliciousDataAdapter::GetInstance(); DBResultWrap usrrow = adapter->GetUserAfterValidation(request->uid(), request->password()); if (!usrrow.empty()) { const ProtocolBuffer::User &toupdate = request->userinfo(); DBRow& row = usrrow.getResult()->GetRow(0); ProtubufDBRowConversion::Convert(toupdate, row); DBResultWrap updatedUser = adapter->UpdateRows(usrrow, "Users", "UID"); if (!updatedUser.empty()) ProtubufDBRowConversion::Convert(updatedUser.getResult()->GetRow(0), *response); } else { pantheios::log_INFORMATIONAL("UpdateUserInfo() failed because user do not exist or authentication failed."); } } else { pantheios::log_WARNING("calling UpdateUserInfo() with wrong request message."); controller->SetFailed("calling UpdateUserInfo() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetRelatedUsers( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::UserList* response, ::google::protobuf::Closure* done ) { if (request->has_uid() && request->has_relation()) { deliciousDataAdapter::GetInstance()->GetRelatedUsersWith( request->uid(), request->relation(), bind(&DMServiceLocalDBImpl::GetUsersCallback, this, _1, response)); } else { pantheios::log_WARNING("calling GetRelatedUser() with wrong request message."); controller->SetFailed("calling GetRelatedUser() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::SetUserRelation( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::google::protobuf::Closure* done ) { if (request->has_uid() && request->has_uid_target() && request->has_relation()) { if (!deliciousDataAdapter::GetInstance()->SetUserRelation(request->uid(), request->uid_target(), request->relation())) { controller->SetFailed("Set user relation failed"); } } else { pantheios::log_WARNING("calling SetUserRelation() with wrong request message."); controller->SetFailed("calling SetUserRelation() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::AddRestaurant( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::Restaurant* response, ::google::protobuf::Closure* done ) { if (request->has_rinfo()) { DBResultWrap ret = deliciousDataAdapter::GetInstance()->AddRestaurant(request->rinfo().name(), request->rinfo().location().latitude(), request->rinfo().location().longitude(), request->rinfo().type().tid(), request->rinfo().averageexpense().amount()); if (ret.empty()) { pantheios::log_ERROR("Add restaurant error, database failed?"); controller->SetFailed("Server failed to add the restaurant."); } else ProtubufDBRowConversion::Convert(ret.getResult()->GetRow(0), *response); } else { pantheios::log_WARNING("calling AddRestaurant() with wrong request message."); controller->SetFailed("calling AddRestaurant() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::Search( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::SearchResult* response, ::google::protobuf::Closure* done ) { if (request->has_msg()) { deliciousDataAdapter* adapter = deliciousDataAdapter::GetInstance(); DBResultWrap ret = adapter->SearchRestaurant(request->msg()); if (!ret.empty()) { for (size_t i=0;i<ret.getResult()->RowsCount();i++) { ProtocolBuffer::Restaurant* newr = response->mutable_restaurants()->add_restaurants(); ProtubufDBRowConversion::Convert(ret.getResult()->GetRow(i), *newr); } } DBResultWrap retuser = adapter->SearchUser(request->msg()); if (!retuser.empty()) { for (size_t i=0;i<retuser.getResult()->RowsCount();i++) { ProtocolBuffer::User* newu = response->mutable_users()->add_users(); ProtubufDBRowConversion::Convert(retuser.getResult()->GetRow(i), *newu); } } } else { pantheios::log_WARNING("calling SearchRestaurant() with wrong request message."); controller->SetFailed("calling SearchRestaurant() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetSubscribtionInfo( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::SearchResult* response, ::google::protobuf::Closure* done ) { if (request->has_uid()) { deliciousDataAdapter* adapter = deliciousDataAdapter::GetInstance(); DBResultWrap retuser = adapter->GetSubscribedUserBy(request->uid()); DBResultWrap retrestaurant = adapter->GetSubscribedRestaurantBy(request->uid()); if (!retuser.empty()) { ProtocolBuffer::UserList* rs = response->mutable_users(); for (size_t i=0;i<retuser.getResult()->RowsCount();i++) { ProtubufDBRowConversion::Convert(retuser.getResult()->GetRow(i), *rs->add_users()); } } if (!retrestaurant.empty()) { ProtocolBuffer::RestaurantList* us = response->mutable_restaurants(); for (size_t i=0;i<retrestaurant.getResult()->RowsCount();i++) { ProtubufDBRowConversion::Convert(retrestaurant.getResult()->GetRow(i), *us->add_restaurants()); } } } else { pantheios::log_WARNING("calling GetSubscribtionInfo() with wrong request message."); controller->SetFailed("calling GetSubscribtionInfo() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::RegisterUser( ::google::protobuf::RpcController* controller, const ::ProtocolBuffer::Query* request, ::ProtocolBuffer::User* response, ::google::protobuf::Closure* done ) { if (request->has_emailaddress() && request->has_password() && request->has_nickname()) { deliciousDataAdapter* adapter = deliciousDataAdapter::GetInstance(); DBResultWrap usr = adapter->GetUserInfo(request->emailaddress()); if (!usr.empty()) { controller->SetFailed("User already exist."); } else { DBResultWrap newUsr = adapter->AddUser(request->nickname(), request->emailaddress(), request->password()); ProtubufDBRowConversion::Convert(newUsr.getResult()->GetRow(0), *response); } } else { pantheios::log_WARNING("calling RegisterUser() with wrong request message."); controller->SetFailed("calling RegisterUser() with wrong request message."); } done->Run(); } void DMServiceLocalDBImpl::GetRestaurantsCallback( const DBRow& row, RestaurantList* result ) { Restaurant *newr = result->add_restaurants(); ProtubufDBRowConversion::Convert(row, *newr); } void DMServiceLocalDBImpl::GetCommentsCallback( const DBRow& row, ProtocolBuffer::CommentList* result ) { Comment *newc = result->add_comments(); ProtubufDBRowConversion::Convert(row, *newc); ProtubufDBRowConversion::Convert(row, *newc->mutable_userinfo()); } void DMServiceLocalDBImpl::GetUsersCallback( const DBRow& row, ProtocolBuffer::UserList* result ) { User* newuser = result->add_users(); ProtubufDBRowConversion::Convert(row, *newuser); }
[ "colprog@d4fe8cd8-f54c-11dd-8c4e-4bbb75a408b7" ]
[ [ [ 1, 522 ] ] ]
5f73e2eaa92b02d0ffeff1884c3309947116bf9d
49db059c239549a8691fda362adf0654c5749fb1
/2010/prisivko/task2/main.cpp
a6efafdd32312ae355b1d26e83363d09e4154ff2
[]
no_license
bondarevts/amse-qt
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
2b9b76c7a5576bc1079fc037adcf039fed4dc848
refs/heads/master
2020-05-07T21:19:48.773724
2010-12-07T07:53:51
2010-12-07T07:53:51
35,804,478
0
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
#include "MyDialog.h" #include <QtGui/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MyDialog w; w.show(); return a.exec(); }
[ "vprisivko@1a14799f-55e9-4979-7f51-533a2053511e" ]
[ [ [ 1, 11 ] ] ]
830c557417b4fb74f007d55c2ccbd80645361933
92bedc8155e2fb63f82603c5bf4ddec445d49468
/src/platform/Platform.h
7d1a48c2bec7d06a3359bc3d028667cda9b1acba
[]
no_license
jemyzhang/pluto-hades
16372453f05510918b07720efa210c748b887316
78d9cf2ec7022ad35180e4fb685d780525ffc45d
refs/heads/master
2016-09-06T15:11:35.964172
2009-09-26T09:53:12
2009-09-26T09:53:12
32,126,635
0
0
null
null
null
null
UTF-8
C++
false
false
7,514
h
/******************************************************************************* ** ** NAME: Platform.h ** VER: 1.0 ** CREATE DATE: 2009/07/11 ** AUTHOR: Roger.Yi ([email protected]) ** ** Copyright (C) 2009 - PlutoWare All Rights Reserved ** ** ** PURPOSE: Class Platform ** ** -------------------------------------------------------------- ** ** HISTORY: v1.0, 2009/07/11 ** ** *******************************************************************************/ #ifndef PLATFORM_H #define PLATFORM_H #include "platform_global.h" #include <QString> #include <QApplication> #include <QWidget> #include <QFileDialog> #include <QMessageBox> namespace platform { class PLATFORM_EXPORT Platform : public QApplication { Q_OBJECT public: enum ScreenRotateAngle { Angle0 = 0, Angle90 = 1, Angle180 = 2, Angle270 = 4, //Angle0 = 3, //Angle90 = 0, //Angle180 = 2, //Angle270 = 1, }; enum M8ScreenRotateAngle { SCREEN_LANDSCAPE_N_ = 2, SCREEN_LANDSCAPE_P_ = 3, SCREEN_PORTRAIT_N_ = 1, SCREEN_PORTRAIT_P_ = 0, }; enum M8Key { WPARAM_KEY_EVENT_CLICK_VOLUP = 0xB001, WPARAM_KEY_EVENT_CLICK_VOLDOWN, WPARAM_KEY_EVENT_CLICK_LINE, WPARAM_KEY_EVENT_CLICK_PLAY, WPARAM_KEY_EVENT_CLICK_HOME, WPARAM_KEY_EVENT_CLICK_POWER, WPARAM_KEY_EVENT_CLICK_VOLMUTE, WPARAM_KEY_EVENT_DBLCLICK_VOLUP = 0xB101, WPARAM_KEY_EVENT_DBLCLICK_VOLDOWN, WPARAM_KEY_EVENT_DBLCLICK_LINE, WPARAM_KEY_EVENT_DBLCLICK_PLAY, WPARAM_KEY_EVENT_DBLCLICK_HOME, WPARAM_KEY_EVENT_DBLCLICK_POWER, WPARAM_KEY_EVENT_DBLCLICK_VOLMUTE, WPARAM_KEY_EVENT_LONGCLICK_VOLUP = 0xB201, WPARAM_KEY_EVENT_LONGCLICK_VOLDOWN, WPARAM_KEY_EVENT_LONGCLICK_LINE, WPARAM_KEY_EVENT_LONGCLICK_PLAY, WPARAM_KEY_EVENT_LONGCLICK_HOME, WPARAM_KEY_EVENT_LONGCLICK_POWER, WPARAM_KEY_EVENT_LONGCLICK_VOLMUTE, }; struct MemoryStatus { quint32 memoryLoad; double totalPhys;//in mega double availPhys; double usedPhys; }; public: Platform(int& argc, char ** argv); virtual ~Platform(); public://helper functions QString pathRelateToAppDir(const QString& relativePath) const; QString helpFile() const; QString fileInArgument() const; public://style relative void loadStyle(const QString& styleFile); void reloadStyle(); public://screen relative helper functions bool screenCanRotate() const; ScreenRotateAngle convertM8Angle(M8ScreenRotateAngle m8angle) const; ScreenRotateAngle realScreenRotateAngle() const; ScreenRotateAngle originalRotateAngle() const; ScreenRotateAngle lastScreenRotateAngle() const; ScreenRotateAngle currentScreenRotateAngle() const; ScreenRotateAngle nextScreenRotateAngle(ScreenRotateAngle angle) const; int deltaAngle(ScreenRotateAngle angle1, ScreenRotateAngle angle2) const; Qt::Orientation screenOrientation() const; void rotateScreen(ScreenRotateAngle angle); void rotateScreenToOriginal(); void rotateScreenToLast(); void rotateScreenToCurrent(); void advance90degree(); void advance180degree(); void enterFullScreen(QWidget* mainWin); void leaveFullScreen(QWidget* mainWin); void reEnterFullScreen(QWidget* mainWin); public://system info helper functions int batteryPercentage() const; MemoryStatus memoryStatus() const; public://shell helper functions QString getOpenFileName(QWidget *parent = 0, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = 0, QFileDialog::Options options = 0); void holdShellKey(QWidget * mainWin, bool holdHomeKey = false) const; void releaseShellKey(QWidget * mainWin) const; quint32 getShellEventId() const; quint32 getEntryLockPhoneEventId() const {return this->getEntryLockPhoneEventId_();}; quint32 getLeaveLockPhoneEventId() const {return this->getLeaveLockPhoneEventId_();}; QMessageBox::StandardButton msgboxQuestion(QWidget* parent, const QString& title, const QString& content) const; public://acc relative quint32 getAccEventId() const; void setAccOpen(bool open); public://SIP helper void openSip(); void closeSip(); private: virtual bool screenCanRotate_() const {return false;}; virtual ScreenRotateAngle realScreenRotateAngle_() const {return Angle0;}; virtual Qt::Orientation screenOrientation_() const {return Qt::Horizontal;}; virtual void rotateScreen_(ScreenRotateAngle /*angle*/) {}; virtual void enterFullScreen_(QWidget* /*mainWin*/) {}; virtual void leaveFullScreen_(QWidget* /*mainWin*/) {}; virtual int batteryPercentage_() const {return 100;}; virtual MemoryStatus memoryStatus_() const {return MemoryStatus();}; virtual QString getOpenFileName_(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options); virtual quint32 getShellEventId_() const {return 0;}; virtual quint32 getEntryLockPhoneEventId_() const {return 0;}; virtual quint32 getLeaveLockPhoneEventId_() const {return 0;}; virtual quint32 getAccEventId_() const {return 0;}; virtual void setAccOpen_(bool /*open*/) {}; virtual void holdShellKey_(QWidget * /*mainWin*/, bool /*holdHomeKey*/) const {}; virtual void releaseShellKey_(QWidget * /*mainWin*/) const {}; virtual QMessageBox::StandardButton msgboxQuestion_(QWidget* parent, const QString& title, const QString& content) const; virtual void openSip_() {}; virtual void closeSip_() {}; private: mutable ScreenRotateAngle originalAngle_; ScreenRotateAngle lastAngle_; ScreenRotateAngle currAngle_; QString styleFile_; }; #define plutoApp (static_cast<platform::Platform *>(QCoreApplication::instance())) /************************************************************************/ /* /* M8Platform /* /************************************************************************/ class PLATFORM_EXPORT M8Platform : public Platform { Q_OBJECT public: M8Platform(int& argc, char ** argv); virtual ~M8Platform(); virtual bool winEventFilter(MSG *message, long *result); private: virtual bool screenCanRotate_() const; virtual ScreenRotateAngle realScreenRotateAngle_() const; virtual Qt::Orientation screenOrientation_() const; virtual void rotateScreen_(ScreenRotateAngle angle); virtual void enterFullScreen_(QWidget* mainWin); virtual void leaveFullScreen_(QWidget* mainWin); virtual int batteryPercentage_() const; virtual MemoryStatus memoryStatus_() const; virtual QString getOpenFileName_(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options); virtual quint32 getShellEventId_() const; virtual quint32 getEntryLockPhoneEventId_() const; virtual quint32 getLeaveLockPhoneEventId_() const; virtual quint32 getAccEventId_() const; virtual void setAccOpen_(bool open); virtual void holdShellKey_(QWidget * mainWin, bool holdHomeKey) const; virtual void releaseShellKey_(QWidget * mainWin) const; virtual QMessageBox::StandardButton msgboxQuestion_(QWidget* parent, const QString& title, const QString& content) const; virtual void openSip_(); virtual void closeSip_(); }; } #endif // PLATFORM_H
[ "roger2yi@35b8d456-67b3-11de-a2f9-0f955267958a" ]
[ [ [ 1, 282 ] ] ]
45d0d341c6514b7f1b7dc124a88ebd5811cdb72c
d6f4ab7df13591365d31c22d7782d8697d288b44
/backup/UArbol.h
88c1d2e9f51c6422024b87287d10d78fdbdd6084
[]
no_license
ereslibre/pe
cfb5d225cd1f925e6aaa2c87458e22ba106431b3
f91642d4e0c865b0ed31a29dc4ff1cc048938fff
refs/heads/master
2021-01-06T20:46:49.167360
2010-07-26T01:08:19
2010-07-26T01:08:19
2,196,712
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,443
h
//--------------------------------------------------------------------------- #ifndef UArbolH #define UArbolH #include <math.h> #include <stdio.h> #include <vector.h> #define CTE_ERROR 0.2 #define MIN_ERROR 0.1 #define MAX_CAD 256 #define LONG_MAX_NOM 100 #define ARCHIVO_DATOS "datos.txt" //--------------------------------------------------------------------------- /*Estructura de los datos de entrenamiento*/ struct TDatos { char planeta[LONG_MAX_NOM]; float A; /* Distancia media al sol */ float P; /* Periodo orbital */ }; /*Estructura de las funciones*/ struct TFuncion { int aridad; String nombreFun; }; /* Clase que implementa los árboles de expresiones */ class TArbol { /* Atributos privados de la clase */ private: String nombre; TArbol* hd; TArbol* hi; TArbol* padre; int profundidad; int numNodos; int posSimbolo; bool hoja, raiz; bool esHi; /*Indica si el nodo es hijo izquierdo de su padre o no*/ public: /* Constructoras de la clase */ TArbol() {profundidad = 0;}; TArbol(TArbol* arbol, TArbol* pater); TArbol(vector<TFuncion> * cjtoFuns, vector<String> * cjtoTerms, int hmax, int prof, TArbol* pater, bool esHizq, bool esRaiz); /* Métodos para acceder a las variables privadas */ String leerNombre() { return nombre; }; int leerPosSimbolo() { return posSimbolo; }; TArbol* leerHd() { return hd; }; TArbol* leerHi() { return hi; }; TArbol* leerPadre() { return padre; }; bool esHoja() { return hoja; }; bool esRaiz() { return raiz; }; bool esHijoIzquierdo() { return esHi; }; int leerProfundidad() { return profundidad;}; int leerNumNodos() { return numNodos;}; /* Métodos para escribir las variables privadas */ void escribirProfundidad(int p) { profundidad=p;}; void escribirNumNodos(int n) { numNodos=n;}; void escribirHd(TArbol* nodo); void escribirHi(TArbol* nodo); void escribirPadre(TArbol* pater) { padre = pater; }; void escribirRaiz(bool esRaiz) { raiz = esRaiz; }; /* Métodos propios de la clase */ String mostrar(); float evaluar(float a); int altura(); void actualizar(int prof); TArbol* nodoAleatorio(); TArbol* buscarNodo(int n); void mutaNodo( vector<TFuncion> cjtoFuns, vector<String> cjtoTerms); }; #endif
[ [ [ 1, 86 ] ] ]
7ddf1ad21df6bbbaf11ebf7bb97c7a97f951d291
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/Core.cpp
e47a3912bf460b6e528768e85fab851682bc2e0b
[]
no_license
danishcake/FusionForever
8fc3b1a33ac47177666e6ada9d9d19df9fc13784
186d1426fe6b3732a49dfc8b60eb946d62aa0e3b
refs/heads/master
2016-09-05T16:16:02.040635
2010-04-24T11:05:10
2010-04-24T11:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,726
cpp
#include "StdAfx.h" #include "Core.h" #include "XMLCore.h" #include "RotatingAI.h" #include "JointAngles.h" #include "JointTracker.h" #include "SpinningJoint.h" #include "TrackerArm.h" #include "Blaster.h" #include "HeatBeamGun.h" #include "HomingMissileLauncher.h" #include "Swarmer.h" #include "ChainGun.h" #include "PlasmaArtillery.h" #include "SectionTypes.h" #include "XMLSection.h" static const float CORE_ROT_RATE_MAX = 400.0f; static const float CORE_MOVE_RATE_MAX = 300.0f; static const float CORE_MOVE_EXP_BRAKING = 10.0f; static const float CORE_ROT_RATE_DELTA = 500000000.0f; static const float CORE_ACCL_RATE = 1000000.0f; static const float CORE_EXP_BRAKING = 3000.0f; static const float CORE_BASIC_MASS = 1000.0f; static const float CORE_TOP_MASS = 20000.0; Core::Core(BaseAI* _AI) :Section() { AI_ = _AI; energy_ = FlexFloat(100, 100); thrust_ = FlexFloat(100); target_ = NULL; total_damage_ = 0; total_shield_damage_ = 0; total_health_ = health_.GetMaxValue(); loss_of_thrust_factor_ = 0; last_damage_time_; } Core::~Core(void) { delete AI_; if(target_ != NULL) target_->RemoveSubscriber(this); } void Core::Tick(float _timespan, std::vector<Projectile_ptr>& _spawn_prj, std::vector<Decoration_ptr>& _spawn_dec, Matrix4f _transform, std::vector<Core_ptr>& _allies, std::vector<Core_ptr>& _enemies, ICollisionManager* _collision_manager) { //Do all the standard moving and rotating Section::Tick(_timespan, _spawn_prj, _spawn_dec, _transform, _enemies, _collision_manager); //Get the AI instructions (how to move, rotate and fire) AIAction action; float max_speed; float max_spin; if(mass_ <= CORE_BASIC_MASS) { max_speed = CORE_MOVE_RATE_MAX * (thrust_.GetValue() / 100.0f); max_spin = CORE_ROT_RATE_MAX * (thrust_.GetValue() / 100.0f); } else if(mass_ <= CORE_TOP_MASS) { max_speed = CORE_MOVE_RATE_MAX * (1.0f - (((mass_ - CORE_BASIC_MASS )/ (CORE_TOP_MASS-CORE_BASIC_MASS)) * 0.95f))* (thrust_.GetValue() / 100.0f); max_spin = CORE_ROT_RATE_MAX * (1.0f - (((mass_ - CORE_BASIC_MASS )/ (CORE_TOP_MASS-CORE_BASIC_MASS)) * 0.95f))* (thrust_.GetValue() / 100.0f); } else { max_speed = CORE_MOVE_RATE_MAX * 0.05f * thrust_.GetValue() / 100.0f; max_spin = CORE_ROT_RATE_MAX * 0.05f * thrust_.GetValue() / 100.0f; } if(AI_ != NULL) { action = AI_->Tick(_timespan, _allies, _enemies, this); float effective_thrust = thrust_.GetValue() / 100.0f; if(action.thrust_ && PowerRequirement(25)) { effective_thrust *= 3.0f; energy_ -= 10.0f * effective_thrust * _timespan; max_speed *= 1.5f; max_spin *= 1.5f; } float damage_fraction = GetTotalDamage() / GetTotalHealth(); if(damage_fraction > 0.7f) { float slow_factor = 1.0f - 0.95f *((damage_fraction - 0.7f) / 0.3f); slow_factor = slow_factor > 1.0f ? 1.0f : slow_factor < 0.05f ? 0.05f : slow_factor; max_speed = max_speed * slow_factor; max_spin = max_spin * slow_factor; effective_thrust *= slow_factor; } if(action.target_ != NULL && target_ != action.target_) { if(target_ != NULL) target_->RemoveSubscriber(this); target_ = action.target_; target_->AddSubscriber(this); } Vector2f dv= Vector2f(action.dx_, action.dy_); if(dv.lengthSq()!=0) dv.normalize(); velocity_.x += dv.x * _timespan * CORE_ACCL_RATE * effective_thrust / mass_; velocity_.y += dv.y * _timespan * CORE_ACCL_RATE * effective_thrust / mass_; if(dv.lengthSq() <= 0.01f) { velocity_ *= expf(-_timespan * CORE_EXP_BRAKING * effective_thrust / mass_); } if(velocity_.length() > max_speed) { float excess_speed = velocity_.length() - max_speed; float decay_factor = expf(-_timespan * CORE_MOVE_EXP_BRAKING); velocity_.normalize(); velocity_ *= (max_speed + (excess_speed * decay_factor)); } spin_ += action.dtheta_ * _timespan * CORE_ROT_RATE_DELTA / moment_; if(spin_ > 2 * max_spin) spin_ = 2 * max_spin; if(spin_ < -2 * max_spin) spin_ = -2 * max_spin; if(spin_ > max_spin) spin_ = max_spin + (spin_ - max_spin) * expf(-_timespan * CORE_MOVE_EXP_BRAKING); if(spin_ < -max_spin) spin_ = -max_spin + (spin_ + max_spin) * expf(-_timespan * CORE_MOVE_EXP_BRAKING); firing_ = action.firing_; } } void Core::OverrideAI(BaseAI* _new_AI) { delete AI_; AI_ = _new_AI; } Core_ptr Core::CreateCore(std::string _name) { std::string file_name = _name; TiXmlDocument ship_document = TiXmlDocument(file_name.c_str()); if(ship_document.LoadFile()) { TiXmlHandle section_handle = TiXmlHandle(&ship_document); TiXmlElement* core_element = section_handle.FirstChild("Section").Element(); if(core_element) { Core_ptr core = NULL; ParseShip(core_element, ((Section_ptr*)&core)); if(core) return core; } else { Logger::ErrorOut() << "Ship :" << file_name << " has no root section\n"; return NULL; } } else { Logger::ErrorOut() << "Unable to open file '" << file_name << "' :" << ship_document.ErrorDesc() << "(" << boost::lexical_cast<std::string, int>(ship_document.ErrorRow()) << ":" << boost::lexical_cast<std::string, int>(ship_document.ErrorCol()) << ")\n"; } return NULL; } bool Core::ParseShip(TiXmlElement* _section, Section_ptr* _parent) { Section_ptr self = NULL; //If *_parent==NULL then it's a root and we have to set root if(!(*_parent)) { Core_ptr n_core = ParseCore(_section); if(n_core) { *_parent = n_core; self = *_parent; } else return false; //Error! } else { Section_ptr n_section = ParseSection(_section); if(n_section) { (*_parent)->AddChild(n_section); self = n_section; } else return false; //Error! } //Consider children for(TiXmlElement* child_section = _section->FirstChildElement("Section"); child_section != NULL; child_section = child_section->NextSiblingElement()) { if(!ParseShip(child_section, &self)) return false; } return true; } Core_ptr Core::ParseCore(TiXmlElement* _core_element) { Core_ptr core = NULL; std::string core_string; if(_core_element->QueryValueAttribute("SectionType", &core_string) == TIXML_SUCCESS) { //Lookup Core in map of hardcoded Cores core = XMLCore::CreateXMLCore(core_string); if(!core) Logger::ErrorOut() << "Unable to open core:" << core_string << "\n"; if(core) { //Now query any standard section atttributes ParseCommon(_core_element, core); //Now query any core only section atttributes } } return core; } Section_ptr Core::ParseSection(TiXmlElement* _section_element) { Section_ptr section = NULL; std::string section_string; if(_section_element->QueryValueAttribute("SectionType", &section_string) == TIXML_SUCCESS) { //Lookup section in map of hardcoded Cores section = SectionTypes::GetSection(section_string); if(!section) { //Attempt to find XMLSection section = XMLSection::CreateXMLSection(section_string); if(!section) { //Can't find, log error Logger::ErrorOut() << "Unable to find section type" << section_string << "\n"; } } if(section) { //Now query any standard section atttributes ParseCommon(_section_element, section); section->ParseSpecific(_section_element); //Now query any non core attributes Vector3f position = section->GetPosition(); if((_section_element->QueryValueAttribute("x", &position.x) == TIXML_SUCCESS) | (_section_element->QueryValueAttribute("y", &position.y) == TIXML_SUCCESS)) section->SetPosition(position); } } else { Logger::ErrorOut() << "Unable to create section, SectionType attribute is blank\n"; } return section; } void Core::ParseCommon(TiXmlElement* _section_element, Section* _section) { //Now query any standard section atttributes float health = 100; if(_section_element->QueryValueAttribute("Health", &health) == TIXML_SUCCESS) _section->SetMaxHealth(health); float angle = 0; if(_section_element->QueryValueAttribute("Angle", &angle) == TIXML_SUCCESS) _section->SetAngle(angle); float delay = 0; if(_section_element->QueryValueAttribute("Delay", &delay) == TIXML_SUCCESS) _section->SetFiringDelay(delay); } void Core::EndSubscription(Subscriber* _source) { if(target_ == _source) target_ = NULL; } void Core::ReportDamage(float _damage, float /*_shield_damage*/) { total_damage_ += _damage; last_damage_time_ = 0; } void Core::RegisterMetadata() { Section::RegisterMetadata(); SectionMetadata::RegisterSectionTag(section_type_, "Core"); }
[ "Edward Woolhouse@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "[email protected]" ]
[ [ [ 1, 40 ], [ 42, 91 ], [ 101, 147 ], [ 149, 289 ], [ 291, 293 ] ], [ [ 41, 41 ], [ 92, 100 ] ], [ [ 148, 148 ], [ 290, 290 ], [ 294, 300 ] ] ]
f7e3ac5e2a6cbb2839feb4c4bcd60e2b6d721e49
fb598854bdef4d7202407bda501df9ee35bad385
/ArticulatedFigure/ArticulatedFigure.cpp
9768fd6c9d807ccb0c1c37a29ee95efda8cf3727
[]
no_license
nxp3932/gc-articulate-figure
b5f48941bdc720751401ada1c375ec8d61bf1590
558608978bdaa6a545cfc0e2a5a6ae28bc8c1b21
refs/heads/master
2016-09-06T15:33:25.193720
2010-05-06T19:47:24
2010-05-06T19:47:24
41,727,036
0
0
null
null
null
null
UTF-8
C++
false
false
11,008
cpp
#include <stdlib.h> #include <time.h> #include <GL/glut.h> #include <string> #include <stdio.h> #include <vector> #define WIDTH 500 #define HEIGHT 500 #define FIGURE "human.txt" #define ANIMATION "animation.txt" #define MAX_JCOUNT 6 #define MAX_KFCOUNT 512 bool typing = false; bool keyframe_typing = false; int cmd_buffer_len = 0; char cmd_buffer[100]; int frameNum = 0; int baseTime = 0; using namespace std; //Define a keyframe for joints typedef struct keyframe_t { int time; float angle1; float angle2; struct keyframe_t *next; } Keyframe; typedef struct joint_t { char name[100]; float x, y, z, angle1, angle2; // Start int childCount; struct joint_t *children[MAX_JCOUNT]; Keyframe *keyframe; Keyframe *curframe; } Joint; /* This adds a joint to a parent, or initializes it as the root if there are no parents */ Joint *addJoint(Joint *parent, float x, float y, float z, float angle1, float angle2, char name[]) { Joint *newJoint; if(!parent) { parent = (Joint *)malloc(sizeof(Joint)); } else if(parent->childCount < MAX_JCOUNT) { newJoint = (Joint *)malloc(sizeof(Joint)); parent->children[parent->childCount++] = newJoint; parent = newJoint; } parent->x = x; parent->y = y; parent->z = z; parent->angle1 = angle1; parent->angle2 = angle2; Keyframe *newframe = (Keyframe *)malloc(sizeof(Keyframe)); newframe->angle1 = angle1; newframe->angle2 = angle2; newframe->time = 0; newframe->next = NULL; parent->curframe = newframe; parent->keyframe = newframe; parent->childCount = 0; strcpy(parent->name, name); for(int x = 0; x < MAX_JCOUNT; x++) parent->children[x] = NULL; return parent; } Joint *root; Joint *selected; Joint *FindJoint(Joint *node, char name[]) { if(strcmp(node->name, name) == 0) return node; else { Joint *found = NULL; for(int i = 0; i < node->childCount; i++) { found = FindJoint(node->children[i], name); if(found) return found; } } return NULL; } Keyframe *addKeyframe(Joint *joint, int time, float angle1, float angle2) { Keyframe *newframe = (Keyframe *)malloc(sizeof(Keyframe)); newframe->time = time; newframe->angle1 = angle1; newframe->angle2 = angle2; newframe->next = NULL; Keyframe *oldframe = joint->keyframe; while(oldframe->next != NULL) oldframe = oldframe->next; oldframe->next = newframe; if(!joint->curframe) joint->curframe = newframe; return newframe; } void LoadFigure(char *path) { // parent x y z angle1 angle2 name FILE *file; float x=0, y=0, z=0, angle1=0, angle2=0; char name[20], parent[20], buffer[512]; Joint *tmpJoint; if(!(file = fopen(path, "r"))) { printf("Unable to load file\n"); return; } while(!feof(file)) { fgets(buffer, 512, file); sscanf(buffer, "%s %f %f %f %f %f %s\n", parent, &x, &y, &z, &angle1, &angle2, name); if(strcmp(parent, "0") == 0) root = addJoint(NULL, x, y, z, angle1, angle2, name); else { tmpJoint = FindJoint(root, parent); addJoint(tmpJoint, x, y, z, angle1, angle2, name); } } selected = root; fclose(file); } void LoadAnimation(char *path) { FILE *file; char buffer[512], name[20]; float angle1, angle2; int time; if(!(file = fopen(path, "r"))) { printf("Unable to load file\n"); return; } while(!feof(file)) { fgets(buffer, 512, file); name[0] = 0; if(sscanf(buffer, "%s %f %f %d\n", name, &angle1, &angle2, &time) == 4) { Joint *framejoint = FindJoint(root, name); addKeyframe(framejoint, time, angle1, angle2); } } fclose(file); } void SaveTraversal(Joint *node, int time, char* buffer) { printf("%f %f %d\n", node->angle1, node->angle2, time); sprintf(buffer+strlen(buffer), "%s %f %f %d\n", node->name, node->angle1, node->angle2, time); //strcat(buffer, tmpbuffer); for(int i = 0; i < node->childCount; i++) { SaveTraversal(node->children[i], time, buffer); } } void SaveKeyframe(char *path, int time) { FILE *file; char buffer[1024] = ""; if(!(file = fopen(path, "a"))) { printf("Unable to load file\n"); return; } SaveTraversal(root, time, buffer); fprintf(file, buffer); fclose(file); } //Animate the joint in question using interpolation void jointAnimate(Joint *joint, int time) { if(joint->curframe != NULL && joint->curframe->next != NULL && joint->curframe->next->time < time) joint->curframe = joint->curframe->next; if(joint->curframe != NULL && joint->curframe->next != NULL) { int cur_time = time - joint->curframe->time - baseTime; int tdelta = joint->curframe->next->time - joint->curframe->time; float fraction = (float)cur_time/tdelta; joint->angle1 = joint->curframe->angle1 + (cur_time)*(joint->curframe->next->angle1 - joint->curframe->angle1)/tdelta; joint->angle2 = joint->curframe->angle2 + (cur_time)*(joint->curframe->next->angle2 - joint->curframe->angle2)/tdelta; } } // Draws a joint and traverses to its children to draw those void DrawJoint(Joint *node) { int time = glutGet(GLUT_ELAPSED_TIME); jointAnimate(node, time); glPushMatrix(); glRotatef(node->angle1, 0.0, 0.0, 1.0); glRotatef(node->angle2, 1.0, 0.0, 0.0); glBegin(GL_LINES); if(node == selected) glColor3f(0, 1, 0); else glColor3f(1, 0, 0); glVertex3f(0, 0, 0); glVertex3f(node->x, node->y, node->z); glEnd(); glTranslatef(node->x, node->y, node->z); for(int i = 0; i < node->childCount; i++) { DrawJoint(node->children[i]); } glPopMatrix(); return; } // Draws the figure void DrawFigure(float x, float y, float z) { glPushMatrix(); glTranslatef(x, y, z); DrawJoint(root); glPopMatrix(); } // Draws the stage that the figure will be located on void DrawStage(void) { glBegin(GL_POLYGON); glColor3f(0.3, 0.3, 0.3); glVertex3f(0, 0, 0); glVertex3f(0, 0, 1); glVertex3f(1, 0, 1); glVertex3f(1, 0, 0); glEnd(); } // Draws the xyz axis for reference void DrawAxis(void) { glBegin(GL_LINES); glColor3f(1, 0, 0); glVertex3f(0, 0, 0); glVertex3f(0.1, 0, 0); glEnd(); glBegin(GL_LINES); glColor3f(0, 1, 0); glVertex3f(0, 0, 0); glVertex3f(0, 0.1, 0); glEnd(); glBegin(GL_LINES); glColor3f(0, 0, 1); glVertex3f(0, 0, 0); glVertex3f(0, 0, 0.1); glEnd(); } // Displays a command window to select figure joints void DisplayCmd() { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1, 1, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glRasterPos2f( 0.5, 0.8 ); for(int i = 0; i < cmd_buffer_len; i++) { glutBitmapCharacter( GLUT_BITMAP_TIMES_ROMAN_24, cmd_buffer[i]); } glutBitmapCharacter( GLUT_BITMAP_TIMES_ROMAN_24, '_'); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glPopMatrix(); // Restore The Old Projection Matrix glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glPopMatrix(); // Restore The Old Projection Matrix } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1,1,1); glPushMatrix(); DrawStage(); DrawAxis(); DrawFigure(0.8, 0.2, 0.6); if(typing) DisplayCmd(); glPopMatrix(); glutSwapBuffers(); } typedef struct coord_t { float x; float y; float z; } Coord; Coord eye = { 1.5, 0.8, 1.5 }; Coord lookat = { 0.5, 0, 0.5 }; Coord top = { 0, 1, 0 }; void rotateScene(float angle1, float angle2, float angle3) { glTranslatef(0.5, 0, 0.5); glRotatef(angle3, 0, 0, 1); glRotatef(angle2, 1, 0, 0); glRotatef(angle1, 0, 1, 0); //gluLookAt( 0, 0, 0, lookat.x, lookat.y, lookat.z, top.x, top.y, top.z ); glTranslatef(-0.5, 0, -0.5); glutPostRedisplay(); //gluLookAt( eye.x, eye.y, eye.z, lookat.x, lookat.y, lookat.z, top.x, top.y, top.z ); return; } void motion(int x, int y) { selected->angle1 = x; selected->angle2 = y; glutPostRedisplay(); } void idle(void) { glutPostRedisplay(); } void keyboard(unsigned char key, int x, int y) { if(typing == true) { if(key == 27) { // ESC key cmd_buffer[0] = 0; cmd_buffer_len = 0; typing = false; keyframe_typing = false; } else if(key == 8 && cmd_buffer_len > 0) { // Backspace cmd_buffer[cmd_buffer_len--] = 0; } else if(key == 13) { // Enter key if(keyframe_typing) SaveKeyframe(ANIMATION, atoi(cmd_buffer)); else selected = FindJoint(root, cmd_buffer); cmd_buffer[0] = 0; cmd_buffer_len = 0; typing = false; keyframe_typing = false; } else { // Any other key cmd_buffer[cmd_buffer_len++] = key; cmd_buffer[cmd_buffer_len] = 0; } } else if(key == 'j') rotateScene(-0.3, 0, 0); else if(key =='l') rotateScene(0.3, 0, 0); else if(key == 'u') rotateScene(0, -0.3, 0); else if(key == 'o') rotateScene(0, 0.3, 0); else if(key == '7') rotateScene(0, 0, -0.3); else if(key == '9') rotateScene(0, 0, 0.3); else if(key == 'r') LoadFigure(FIGURE); else if(key == 'x') baseTime = glutGet(GLUT_ELAPSED_TIME); else { // Enter command mode if(key == 'c') typing = true; else if(key == 'v') { typing = true; keyframe_typing = true; } else if(selected != NULL) { if(key == 'w') selected->angle1 += .3; else if(key == 's') selected->angle1 -= .3; else if(key == 'd') selected->angle2 += .3; else if(key == 'a') selected->angle2 -= .3; } } glutPostRedisplay(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize (WIDTH, HEIGHT); glutInitWindowPosition (500, 100); glutCreateWindow (argv[0]); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluPerspective(60.0, 1.0, 1.0, 10.0); gluLookAt( eye.x, eye.y, eye.z, lookat.x, lookat.y, lookat.z, top.x, top.y, top.z ); LoadFigure(FIGURE); LoadAnimation(ANIMATION); glClearColor (0.0, 0.0, 0.0, 0.0); glutDisplayFunc(display); // glutMotionFunc(motion); glutKeyboardFunc(keyboard); glutIdleFunc(idle); glutMainLoop(); return 0; }
[ "rclark72@d68364d2-591d-d464-8a7f-fb39578533eb" ]
[ [ [ 1, 455 ] ] ]
a8728184be0d775ba15e55b91b99f6aafcf1c1d8
075043812c30c1914e012b52c60bc3be2cfe49cc
/src/SDLGUIlibTests/MenuWidgetTests.cpp
bf7d266510ccd9a4e4451f9cbfc7bec468fab1b0
[]
no_license
Luke-Vulpa/Shoko-Rocket
8a916d70bf777032e945c711716123f692004829
6f727a2cf2f072db11493b739cc3736aec40d4cb
refs/heads/master
2020-12-28T12:03:14.055572
2010-02-28T11:58:26
2010-02-28T11:58:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,201
cpp
#include "stdafx.h" #include <MenuWidget.h> namespace { int start_count = 0; void start_callback(Widget* /*_widget*/) { start_count++; } int options_count = 0; void options_callback(Widget* /*_widget*/) { options_count++; } int exit_count = 0; void exit_callback(Widget* /*_widget*/) { exit_count++; } } TEST_FIXTURE(SDL_fixture, MenuAutoLinks) { CHECK(SDL_init_ok); if(SDL_init_ok) { MenuWidget* menu = new MenuWidget(); Widget* pStart = menu->AddMenuItem("Start"); Widget* pOptions = menu->AddMenuItem("Options"); Widget* pExit = menu->AddMenuItem("Exit"); pStart->OnClick.connect(start_callback); pOptions->OnClick.connect(options_callback); pExit->OnClick.connect(exit_callback); menu->SetFocusToFirst(); CHECK_EQUAL(menu->GetChildren().at(0), Widget::GetWidgetWithFocus()); Widget::GetWidgetWithFocus()->HandleEvent(Event(EventType::KeyDown)); CHECK_EQUAL(menu->GetChildren().at(1), Widget::GetWidgetWithFocus()); Widget::GetWidgetWithFocus()->HandleEvent(Event(EventType::KeyDown)); CHECK_EQUAL(menu->GetChildren().at(2), Widget::GetWidgetWithFocus()); Widget::GetWidgetWithFocus()->HandleEvent(Event(EventType::KeyDown)); CHECK_EQUAL(menu->GetChildren().at(0), Widget::GetWidgetWithFocus()); CHECK_EQUAL(Vector2i(0, 0), menu->GetChildren().at(0)->GetPosition()); CHECK_EQUAL(Vector2i(8, 40), menu->GetChildren().at(1)->GetPosition()); CHECK_EQUAL(Vector2i(16, 80), menu->GetChildren().at(2)->GetPosition()); CHECK_EQUAL(0, start_count); CHECK_EQUAL(0, options_count); CHECK_EQUAL(0, exit_count); Widget::GetWidgetWithFocus()->HandleEvent(Event(EventType::KeyEnter)); CHECK_EQUAL(menu->GetChildren().at(0), Widget::GetWidgetWithFocus()); CHECK_EQUAL(1, start_count); CHECK_EQUAL(0, options_count); CHECK_EQUAL(0, exit_count); Widget::GetWidgetWithFocus()->HandleEvent(Event(EventType::KeyUp)); CHECK_EQUAL(menu->GetChildren().at(2), Widget::GetWidgetWithFocus()); Widget::GetWidgetWithFocus()->HandleEvent(Event(EventType::KeyEnter)); CHECK_EQUAL(1, start_count); CHECK_EQUAL(0, options_count); CHECK_EQUAL(1, exit_count); } }
[ [ [ 1, 69 ] ] ]
160b606145023e371642245780c27618d63441d3
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/TestDialogBar.h
2449248c20a2ac94832a190c27185043e403d040
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
UTF-8
C++
false
false
1,635
h
#if !defined(AFX_TESTDIALOGBAR_H__53274537_E9E9_11D2_88EF_0000E8A1A5C0__INCLUDED_) #define AFX_TESTDIALOGBAR_H__53274537_E9E9_11D2_88EF_0000E8A1A5C0__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // TestDialogBar.h : header file // #include "resource.h" ///////////////////////////////////////////////////////////////////////////// // CTaiToolBar dialog class CTaiToolBar : public CDialog { // Construction public: CTaiToolBar(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CTaiToolBar) enum { IDD = IDD_DIALOGBAR }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTaiToolBar) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL OnToolTipNotify(UINT id,NMHDR *pTTTStruct,LRESULT *pResult); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CTaiToolBar) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnFileOpen(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: CToolBar m_wndToolBar; CToolTipCtrl m_wndToolTip; }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_TESTDIALOGBAR_H__53274537_E9E9_11D2_88EF_0000E8A1A5C0__INCLUDED_)
[ [ [ 1, 56 ] ] ]
ebcb3c0c2c04c8eb11a322a43f0d2c52fd52c1f5
252e638cde99ab2aa84922a2e230511f8f0c84be
/replib/src/RepTripInfoInputForm.cpp
d00c18db007d2fb62ac7f027abc9a61910910cb4
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,659
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "StdTool.h" #include "TourTool.h" #include "FieldDef.h" #include "RepTripInfoGenerator.h" #include "RepTripInfoInputForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "RXDBCtrl" #pragma link "VADODataSourceOrdering" #pragma link "VCustomDataSourceOrdering" #pragma link "VDBSortGrid" #pragma link "Placemnt" #pragma resource "*.dfm" TTourRepTripInfoInputForm *TourRepTripInfoInputForm; //--------------------------------------------------------------------------- __fastcall TTourRepTripInfoInputForm::TTourRepTripInfoInputForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTourRepTripInfoInputForm::FormCreate(TObject *Sender) { FunctionArgUsedSkip(Sender); CursorWaitOpen(); try { #ifdef TOURDATABASEMODEBDE TripDataSourceOrdering->Active = true; #endif TripQuery->Open(); if (TripQuery->IsEmpty()) { CreateReportButton->Enabled = false; } #ifdef TOURDATABASEMODEADO TripDataSourceOrdering->Active = true; #endif } catch (Exception &exception) { TourShowDialogException(NULL,&exception); } CursorWaitClose(); } //--------------------------------------------------------------------------- void __fastcall TTourRepTripInfoInputForm::FormDestroy(TObject *Sender) { FunctionArgUsedSkip(Sender); if (TripQuery->Active) { TripQuery->Close(); } } //--------------------------------------------------------------------------- void __fastcall TTourRepTripInfoInputForm::CreateReportButtonClick(TObject *Sender) { FunctionArgUsedSkip(Sender); if (!TripQuery->IsEmpty()) { TripInfoReportGenerate(TripQuery->FieldByName(TripIdFieldNameStr)->AsString); ModalResult = mrOk; } } //--------------------------------------------------------------------------- void __fastcall TTourRepTripInfoInputForm::TripGridDblClick(TObject *Sender) { CreateReportButtonClick(Sender); } //--------------------------------------------------------------------------- void __fastcall TTourRepTripInfoInputForm::TripGridKeyDown (TObject *Sender,WORD &Key, TShiftState Shift) { FunctionArgUsedSkip(Shift); if (Key == VK_RETURN) { CreateReportButtonClick(Sender); } } //---------------------------------------------------------------------------
[ [ [ 1, 94 ] ] ]
065971202e1bd6e53b67471f22a0ebc8e544cade
3dc524d7d842eb91d2c5c93e87688e473697197a
/Source/ASPX.cpp
45a0f95573cd61b850c4abf5f3a6ae3beb64d980
[]
no_license
SamOatesUniversity/Year-2---Animation-Simulation---PigCam
8aae5ddf90289f92275349ccafe096b07447c8c2
aa33e4dea6bd42cb2d1cf4159d8b2c4e67e63cae
refs/heads/master
2020-06-03T13:59:52.260548
2011-02-15T17:53:26
2011-02-15T17:53:26
41,170,127
0
0
null
null
null
null
UTF-8
C++
false
false
4,245
cpp
#include "ASPX.h" namespace ASPX { namespace Kinematics { void Euler( twm::Vector &value, const twm::Vector &derivative, float h ) { value += derivative * h; } } namespace Transformation { twm::Matrix Position( float x, float y, float z ) { return twm::Matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ); } twm::Matrix Position( twm::Vector xyz ) { return twm::Matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, xyz.x, xyz.y, xyz.z, 1 ); } twm::Matrix Rotate( float x, float y, float z ) { x = Conversion::DegreesToRad( x ); y = Conversion::DegreesToRad( y ); z = Conversion::DegreesToRad( z ); twm::Matrix xMatrix( 1, 0, 0, 0, 0, cos(x), -sin(x), 0, 0, sin(x), cos(x), 0, 0, 0, 0, 1); twm::Matrix yMatrix( cos(y), 0, sin(y), 0, 0, 1, 0, 0, -sin(y), 0, cos(y), 0, 0, 0, 0, 1); twm::Matrix zMatrix( cos(z), -sin(z), 0, 0, sin(z), cos(z), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return xMatrix * yMatrix * zMatrix; } twm::Matrix Rotate( twm::Vector xyz ) { float x = Conversion::DegreesToRad( xyz.x ); float y = Conversion::DegreesToRad( xyz.y ); float z = Conversion::DegreesToRad( xyz.z ); twm::Matrix xMatrix( 1, 0, 0, 0, 0, cos(x), -sin(x), 0, 0, sin(x), cos(x), 0, 0, 0, 0, 1); twm::Matrix yMatrix( cos(y), 0, sin(y), 0, 0, 1, 0, 0, -sin(y), 0, cos(y), 0, 0, 0, 0, 1); twm::Matrix zMatrix( cos(z), -sin(z), 0, 0, sin(z), cos(z), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return xMatrix * yMatrix * zMatrix; } } namespace Conversion { float DegreesToRad( float deg ) { return deg * 0.017453f; } float RadToDegrees( float rad ) { return rad * 57.29578f; } } namespace Interpolation { float Smoothstep( float min, float max, float x ) { return ( (x) * (x) * ( 3 - 2*(x) ) ); } float Percentage ( float min, float max, float x ) { return ( x - min ) / ( max - min ); } } namespace KeyFrame { CKeyFrame::CKeyFrame(void) { activeFrame_ = 0; animationLength_ = 0.0f; } CKeyFrame::~CKeyFrame(void) { } void CKeyFrame::addFrame( twm::Vector value, float time ) { SKeyFrame frame; frame.value = value; frame.time = time; frame_.push_back( frame ); animationLength_ = time; intialTime_ = frame_[0].time; } bool CKeyFrame::update( twm::Vector &vector, float time ) { //Calculate the percentage with respect to time float s = Interpolation::Percentage( frame_[activeFrame_].time, frame_[activeFrame_+1].time, time ); //Work out the new position float smooth = Interpolation::Smoothstep( frame_[activeFrame_].time, frame_[activeFrame_+1].time, Interpolation::Clamp( 0.0f, 1.0f, s ) ); vector = Interpolation::Lerp( frame_[activeFrame_].value, frame_[activeFrame_+1].value, smooth ); //If current time is the next frames start time, increase the current frame if( time >= frame_[activeFrame_+1].time - 0.05f ) activeFrame_++; //If the active frame is greater than the frame count //Increase each frames time by the complete animation length //and set the active frame back to zero if( activeFrame_ >= frame_.size()-1 ) { for( unsigned int i = 0; i < frame_.size(); i++ ) frame_[i].time += (animationLength_ - intialTime_); activeFrame_ = 0; } return true; } } namespace Path { twm::Matrix Frenet( const twm::Vector& pos, const twm::Vector& dir, const twm::Vector& up ) { const twm::Vector W = twm::Unit( dir ); const twm::Vector U = twm::Cross( up, W ); const twm::Vector V = twm::Cross( U, W ); return twm::Matrix( U.x, U.y, U.z, 0, V.x, V.y, V.z, 0, W.x, W.y, W.z, 0, pos.x, pos.y, pos.z, 1 ); } } }
[ [ [ 1, 169 ] ] ]
4fde729a34fe65d8d3d56dc42140096a61aeebd1
c3efe4021165e718d23ce0f853808e10c7114216
/LuaEdit/stdext.h
3c67b6780371efed07d9ae6dfb39b72e3eb96453
[]
no_license
lkdd/modstudio2
254b47ebd28a51a7d8c8682a86c576dafcc971bf
287b4782580e37c8ac621046100dc550abd05b1d
refs/heads/master
2021-01-10T08:14:56.230097
2009-03-08T19:14:16
2009-03-08T19:14:16
52,721,924
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
/* Copyright (c) 2008 Peter "Corsix" Cawley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once template <class TOut, class TIn> TOut implicit_cast(TIn _Ty) { return _Ty; } template <class T> const T const_apply(T _Ty) { return const_cast<const T>(_Ty); }
[ "corsix@07142bc5-7355-0410-a98c-5fd2ca6e29ee" ]
[ [ [ 1, 37 ] ] ]
d376729c7f08fbe35d74cff3babceab38d3019fd
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/ui/uicomponent.h
aa03608e022d2ad84e6827acd12be32cc7dc3d1b
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
2,265
h
/* * uicomponent.h * * Created on: 21.7.2011 * Author: akin */ #ifndef UIVIEW_H_ #define UIVIEW_H_ #include <glm/glm> #include "uieventhandler.h" #include "uiparent.h" #include <graphics/shader/shaderprogram.h> #define UI_DEBUG_HOVER #undef UI_DEBUG_HOVER namespace ice { enum UISelectState { UIActive, UIDrag, UIResize, UIHover, UINone, }; enum UIListenerEvents { UIClick, UIClickRelease, UIHoverIn, UIHoverOut, UIChange, UIListenerCount, }; class UIComponent : public UIEventHandler { protected: std::string ident; ShaderProgram *shader; UIParent *parent; UISelectState selected; bool visible; bool eventScriptActive[ UIListenerCount ]; std::string eventScript[ UIListenerCount ]; glm::vec2 position; glm::vec2 dimension; glm::vec2 dislocation; static UIListenerEvents translateListenerEvent( const std::string eventName ); void executeListenerEvent( const UIListenerEvents& event ); public: UIComponent(); virtual ~UIComponent(); void setIdent( std::string val ); std::string getIdent(); virtual void setVisible( bool state ); bool isVisible(); glm::vec2& getPosition(); glm::vec2& getDimension(); void setWidth( float width ); void setHeight( float height ); void setSize( float width , float height ); float getWidth() const; float getHeight() const; void setX( float x ); void setY( float y ); float getX() const; float getY() const; void setPosition( float x , float y ); virtual void render( glm::vec2& pos ) = 0; void setScript( std::string listener , std::string script ); void setScriptState( std::string listener , bool state ); std::string getScript( std::string listener ); bool getScriptState( std::string listener ); virtual bool handleClickEvent( glm::vec2& pos , const Mouse& mouse , const unsigned int button , const float state ) = 0; virtual bool handleMoveEvent( glm::vec2& pos , const Mouse& mouse ) = 0; void setParent( UIParent *val ); bool hasParent(); void clearParent(); virtual void setShader( ShaderProgram *val ); ShaderProgram *getShader(); }; } #endif /* UIVIEW_H_ */
[ "akin@lich", "akin@localhost" ]
[ [ [ 1, 13 ], [ 15, 108 ] ], [ [ 14, 14 ] ] ]
2520e348b7890f491dcf8d3792803fd0c058d8ca
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/XmlLiteUtilities.h
c28dbf1efad4edb1aade28ec3ddcc34b5d50a517
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
8,658
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #ifndef _XmlLiteUtilities_h_ #define _XmlLiteUtilities_h_ #include <xmllite.h> //================================================================================ //================================================================================ //============================== FileStream ====================================== //================================================================================ //================================================================================ class FileStream : public IStream { FileStream(HANDLE hFile) { _refcount = 1; _hFile = hFile; } ~FileStream() { if (_hFile != INVALID_HANDLE_VALUE) { ::CloseHandle(_hFile); } } public: HRESULT static OpenFile(LPCWSTR pName, IStream ** ppStream, bool fWrite) { HANDLE hFile = ::CreateFileW(pName, fWrite ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ, NULL, fWrite ? CREATE_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); *ppStream = new FileStream(hFile); if(*ppStream == NULL) CloseHandle(hFile); return S_OK; } virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void ** ppvObject) { if (iid == __uuidof(IUnknown) || iid == __uuidof(IStream) || iid == __uuidof(ISequentialStream)) { *ppvObject = static_cast<IStream*>(this); AddRef(); return S_OK; } else return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return (ULONG)InterlockedIncrement(&_refcount); } virtual ULONG STDMETHODCALLTYPE Release(void) { ULONG res = (ULONG) InterlockedDecrement(&_refcount); if (res == 0) delete this; return res; } // ISequentialStream Interface public: virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) { BOOL rc = ReadFile(_hFile, pv, cb, pcbRead, NULL); return (rc) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } virtual HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) { BOOL rc = WriteFile(_hFile, pv, cb, pcbWritten, NULL); return rc ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } // IStream Interface public: virtual HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE CopyTo(IStream*, ULARGE_INTEGER, ULARGE_INTEGER*, ULARGE_INTEGER*) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Commit(DWORD) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Revert(void) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Clone(IStream **) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove, DWORD dwOrigin, ULARGE_INTEGER* lpNewFilePointer) { DWORD dwMoveMethod; switch(dwOrigin) { case STREAM_SEEK_SET: dwMoveMethod = FILE_BEGIN; break; case STREAM_SEEK_CUR: dwMoveMethod = FILE_CURRENT; break; case STREAM_SEEK_END: dwMoveMethod = FILE_END; break; default: return STG_E_INVALIDFUNCTION; break; } if (SetFilePointerEx(_hFile, liDistanceToMove, (PLARGE_INTEGER) lpNewFilePointer, dwMoveMethod) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; } virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD grfStatFlag) { if (GetFileSizeEx(_hFile, (PLARGE_INTEGER) &pStatstg->cbSize) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; } private: HANDLE _hFile; LONG _refcount; }; //================================================================================ //================================================================================ //============================== ReadOnlyMemStream =============================== //================================================================================ //================================================================================ class ReadOnlyMemStream : public IStream { ReadOnlyMemStream(const BYTE* pMem, ULONG length, BOOL bAutoDelete) { _refcount = 1; _pMem = pMem; _length = length; _bAutoDelete = bAutoDelete; _curPos = 0; } ~ReadOnlyMemStream() { if (_bAutoDelete) delete _pMem; } public: HRESULT static Create(const BYTE* pMem, ULONG length, BOOL bAutoDelete, IStream** ppStream) { *ppStream = new ReadOnlyMemStream(pMem, length, bAutoDelete); return S_OK; } virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void ** ppvObject) { if (iid == __uuidof(IUnknown) || iid == __uuidof(IStream) || iid == __uuidof(ISequentialStream)) { *ppvObject = static_cast<IStream*>(this); AddRef(); return S_OK; } else return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return (ULONG)InterlockedIncrement(&_refcount); } virtual ULONG STDMETHODCALLTYPE Release(void) { ULONG res = (ULONG) InterlockedDecrement(&_refcount); if (res == 0) delete this; return res; } // ISequentialStream Interface public: virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) { ASSERT(pv != NULL && pcbRead != NULL); ASSERT(_pMem != NULL); *pcbRead = ((_curPos + cb) > _length) ? (_length - _curPos) : cb; memcpy(pv, &_pMem[_curPos], *pcbRead); _curPos += *pcbRead; return S_OK; } virtual HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) {return E_NOTIMPL;} // IStream Interface public: virtual HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE CopyTo(IStream*, ULARGE_INTEGER, ULARGE_INTEGER*, ULARGE_INTEGER*) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Commit(DWORD) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Revert(void) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Clone(IStream **) {return E_NOTIMPL;} virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove, DWORD dwOrigin, ULARGE_INTEGER* lpNewFilePointer) { switch(dwOrigin) { case STREAM_SEEK_SET: _curPos = liDistanceToMove.LowPart; break; case STREAM_SEEK_CUR: _curPos += liDistanceToMove.LowPart; break; case STREAM_SEEK_END: return STG_E_INVALIDFUNCTION; break; default: return STG_E_INVALIDFUNCTION; break; } if (_curPos > _length) return STG_E_INVALIDFUNCTION; return S_OK; } virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD grfStatFlag) { pStatstg->cbSize.LowPart = _length; return S_OK; } private: const BYTE* _pMem; LONG _refcount; ULONG _length; ULONG _curPos; BOOL _bAutoDelete; }; class XmlLiteReaderHelper { public: #ifdef _UNITTESTING static BOOL UnitTest(); #endif XmlLiteReaderHelper(IXmlReader& reader):m_reader(reader){} BOOL FindElement(LPCTSTR elementName, INT restrictDepth = -1); LPCTSTR GetElementText(); LPCTSTR GetElementAttribute(LPCTSTR attributeName); INT GetCurrentDepth(); private: IXmlReader& m_reader; }; #endif
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 302 ] ] ]
7eb7471c51d4939c7a6941d99aa8ecf9b8632b56
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/WallBrowser/WallBrowserTwoParamsDlg.cpp
ea01c7fd95dd6ed91d696e56ddf0e39fa9eac200
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
8,592
cpp
/* WallBrowserTwoParamsDlg.cpp Dialogo per le opzioni. Luca Piergentili, 30/09/01 [email protected] WallBrowser - the smart picture browser http://www.crawlpaper.com/ copyright © 1998-2004 Luca Piergentili, all rights reserved crawlpaper is a registered name, all rights reserved This is a free software, released under the terms of the BSD license. Do not attempt to use it in any form which violates the license or you will be persecuted and charged for this. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of "crawlpaper" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "env.h" #include "pragma.h" #include "macro.h" #include "window.h" #include "CImageParams.h" #include "WallBrowserTwoParamsDlg.h" #include "resource.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP(CWallBrowserTwoParamsDlg,CDialog) ON_BN_CLICKED(IDOK,OnOK) ON_WM_VSCROLL() ON_CBN_KILLFOCUS(IDC_COMBO_SUBVALUE,OnKillFocusCombo) ON_CBN_SELCHANGE(IDC_COMBO_SUBVALUE,OnSelChangeCombo) END_MESSAGE_MAP() /* DoDataExchange() */ void CWallBrowserTwoParamsDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX,IDC_EDIT_VALUE,m_nFirstValue); DDV_MinMaxInt(pDX,m_nFirstValue,m_nFirstMin,m_nFirstMax); DDX_Text(pDX,IDC_EDIT_SUBVALUE,m_nSecondValue); DDV_MinMaxInt(pDX,m_nSecondValue,m_nSecondMin,m_nSecondMax); DDX_Control(pDX,IDC_COMBO_SUBVALUE,m_CComboSubValue); } /* CWallBrowserTwoParamsDlg() */ CWallBrowserTwoParamsDlg::CWallBrowserTwoParamsDlg(CString strProperty,CString strOperation,CString strSubOperation,int nFirstDefaultValue, int nFirstMin, int nFirstMax,int nSecondDefaultValue,int nSecondMin, int nSecondMax) : CDialog(IDD_DIALOG_TWOPARAMS) { m_strProperty = strProperty; m_strOperation = strOperation; m_strSubOperation = strSubOperation; m_nFirstValue = m_nFirstDefaultValue = nFirstDefaultValue; m_nFirstMin = nFirstMin; m_nFirstMax = nFirstMax; m_nSecondValue = m_nSecondDefaultValue = nSecondDefaultValue; m_nSecondMin = nSecondMin; m_nSecondMax = nSecondMax; m_bHaveCombo = TRUE; } /* OnInitDialog() */ BOOL CWallBrowserTwoParamsDlg::OnInitDialog(void) { CDialog::OnInitDialog(); HICON hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); SetIcon(hIcon,TRUE); SetIcon(hIcon,FALSE); SetDlgItemText(IDC_STATIC_PROPERTY,m_strProperty); CSpinButtonCtrl* pSpinFirst = (CSpinButtonCtrl*)GetDlgItem(IDC_SPIN_VALUE); pSpinFirst->SetRange(m_nFirstMin,m_nFirstMax); pSpinFirst->SetPos(m_nFirstDefaultValue); pSpinFirst->SetBuddy(GetDlgItem(IDC_EDIT_VALUE)); if(m_strSubOperation=="Halftone") { m_CComboSubValue.AddString("print"); // HT_PRINT m_CComboSubValue.AddString("display"); // HT_VIEW } else if(m_strSubOperation=="Emboss") { m_CComboSubValue.AddString("north"); // EMBOSS_N m_CComboSubValue.AddString("north/east"); // EMBOSS_NE m_CComboSubValue.AddString("east"); // EMBOSS_E m_CComboSubValue.AddString("south/east"); // EMBOSS_SE m_CComboSubValue.AddString("south"); // EMBOSS_S m_CComboSubValue.AddString("south/west"); // EMBOSS_SW m_CComboSubValue.AddString("west"); // EMBOSS_W m_CComboSubValue.AddString("north/west"); // EMBOSS_NW } else if(m_strSubOperation=="Noise") { m_CComboSubValue.AddString("all channels"); // NOISE_CHANNEL_MASTER m_CComboSubValue.AddString("red channel"); // NOISE_CHANNEL_RED m_CComboSubValue.AddString("green channel"); // NOISE_CHANNEL_GREEN m_CComboSubValue.AddString("blue channel"); // NOISE_CHANNEL_BLUE } else m_bHaveCombo = FALSE; CString str; str.Format("%s (%d/%d)",m_strOperation,m_nFirstMin,m_nFirstMax); SetDlgItemText(IDC_STATIC_OPERATION,str); if(m_bHaveCombo) { SetDlgItemText(IDC_STATIC_SUBOPERATION,m_strSubOperation); GetDlgItem(IDC_EDIT_SUBVALUE)->EnableWindow(FALSE); GetDlgItem(IDC_EDIT_SUBVALUE)->ShowWindow(SW_HIDE); GetDlgItem(IDC_SPIN_SUBVALUE)->EnableWindow(FALSE); GetDlgItem(IDC_SPIN_SUBVALUE)->ShowWindow(SW_HIDE); m_CComboSubValue.SetCurSel(0); } else { str.Format("%s (%d/%d)",m_strSubOperation,m_nSecondMin,m_nSecondMax); SetDlgItemText(IDC_STATIC_SUBOPERATION,str); GetDlgItem(IDC_COMBO_SUBVALUE)->EnableWindow(FALSE); GetDlgItem(IDC_COMBO_SUBVALUE)->ShowWindow(SW_HIDE); CSpinButtonCtrl *pSpinSecond = (CSpinButtonCtrl*)GetDlgItem(IDC_SPIN_SUBVALUE); pSpinSecond->SetRange(m_nSecondMin,m_nSecondMax); pSpinFirst->SetPos(m_nSecondDefaultValue); pSpinSecond->SetBuddy(GetDlgItem (IDC_EDIT_SUBVALUE)); } UpdateData(FALSE); return(TRUE); } /* OnOK() */ void CWallBrowserTwoParamsDlg::OnOK(void) { if(UpdateData(TRUE)) { if(m_bHaveCombo) { if(strcmp(m_szComboSubValue,"print")==0) m_nSecondValue = HT_PRINT; else if(strcmp(m_szComboSubValue,"display")==0) m_nSecondValue = HT_VIEW; else if(strcmp(m_szComboSubValue,"north")==0) m_nSecondValue = EMBOSS_N; else if(strcmp(m_szComboSubValue,"north/east")==0) m_nSecondValue = EMBOSS_NE; else if(strcmp(m_szComboSubValue,"east")==0) m_nSecondValue = EMBOSS_E; else if(strcmp(m_szComboSubValue,"south/east")==0) m_nSecondValue = EMBOSS_SE; else if(strcmp(m_szComboSubValue,"south")==0) m_nSecondValue = EMBOSS_S; else if(strcmp(m_szComboSubValue,"south/west")==0) m_nSecondValue = EMBOSS_SW; else if(strcmp(m_szComboSubValue,"west")==0) m_nSecondValue = EMBOSS_W; else if(strcmp(m_szComboSubValue,"north/west")==0) m_nSecondValue = EMBOSS_NW; else if(strcmp(m_szComboSubValue,"all channels")==0) m_nSecondValue = NOISE_CHANNEL_MASTER; else if(strcmp(m_szComboSubValue,"red channel")==0) m_nSecondValue = NOISE_CHANNEL_RED; else if(strcmp(m_szComboSubValue,"green channel")==0) m_nSecondValue = NOISE_CHANNEL_GREEN; else if(strcmp(m_szComboSubValue,"blue channel")==0) m_nSecondValue = NOISE_CHANNEL_BLUE; } EndDialog(IDOK); } } /* OnKillFocusCombo() */ void CWallBrowserTwoParamsDlg::OnKillFocusCombo(void) { m_CComboSubValue.GetWindowText(m_szComboSubValue,sizeof(m_szComboSubValue)); } /* OnSelChangeCombo() */ void CWallBrowserTwoParamsDlg::OnSelChangeCombo(void) { m_CComboSubValue.GetLBText(m_CComboSubValue.GetCurSel(),m_szComboSubValue); } /* OnVScroll() */ void CWallBrowserTwoParamsDlg::OnVScroll(UINT nSBCode,UINT nPos,CScrollBar* pScrollBar) { if(nSBCode!=SB_ENDSCROLL) { CString strValue; strValue.Format("%d",(int)nPos); ((CSpinButtonCtrl*)pScrollBar)->GetBuddy()->SetWindowText(strValue); ((CSpinButtonCtrl*)pScrollBar)->SetPos((int)nPos); } CDialog::OnVScroll(nSBCode,nPos,pScrollBar); }
[ [ [ 1, 252 ] ] ]
36f994f1b3e29697020e0ce67422833e95d76d63
9907be749dc7553f97c9e51c5f35e69f55bd02c0
/WordplaySingle/template_project/framework_code/text_handler.h
e63321481003c2c445197d4d7e9e884024b9cd7d
[]
no_license
jdeering/csci476winthrop
bc8907b9cc0406826de76aca05e6758810377813
2bc485781f819c8fd82393ac86de33404e7ad6d3
refs/heads/master
2021-01-10T19:53:14.853438
2009-04-24T14:26:36
2009-04-24T14:26:36
32,223,762
0
0
null
null
null
null
UTF-8
C++
false
false
2,987
h
/* Jason Deering text_handler.h This class is for use in the Framework. The TextHandler class controls the display and text-to-speech reading of all text objects. DATA ITEMS std::map<std::string, Text> text - container for all text objects, mapped to key values of type std::string int numObjects bool readEnabled PUBLIC FUNCTIONS bool AddText(std::string refName, std::string textstd::string, int x, int y, bool visible) - adds a text object to the container using the textstd::string parameter as the text object's std::string bool AddText(std::string refName, const char* instd::string, int x, int y, bool visible) - adds a text object to the container using the instd::string parameter as the text object's std::string bool AddTextByRef(std::string refName, std::string assetName, int x, int y, bool visible) - adds a text object to the container using a std::string specified in the XML text asset reference file bool ChangeText(std::string refName, std::string textstd::string) - changes the std::string of the text object at key refName bool RemoveText(std::string refName) - removes the text object at key refName from the container bool ShowText(std::string refName, int setVisible, BITMAP *bmp) - displays the referenced text object void SetTextPosition(std::string refName, int x, int y) - changes the x,y position of the text object void SetSize(std::string refName, int sz) - changes the pixel size of the text object void SetColor(std::string refName, int r, int g, int b) - changes the foreground color of the text object void SetBackgroundColor(std::string refName, int r, int g, int b) - changes the background color of the text object void SetVisible(std::string refName, int vis) - changes the visibility of the text object void SetTTS(bool TTS) - sets the text-to-speech flag void ShowAllVisible(BITMAP* dest) - displays all visible text objects on the dest BITMAP */ #ifndef _TEXT_HANDLER_H #define _TEXT_HANDLER_H #include "text.h" class TextHandler { private: std::map<std::string, Text> text; int numObjects; bool readEnabled; public: TextHandler(); ~TextHandler(); bool AddText(std::string refName, std::string textString, int x, int y, bool visible); bool AddText(std::string refName, const char* inString, int x, int y, bool visible); bool AddTextByRef(std::string refName, std::string assetName, int x, int y, bool visible); bool ChangeText(std::string refName, std::string textString); bool RemoveText(std::string refName); bool ShowText(std::string refName, int setVisible, BITMAP *bmp); void SetTextPosition(std::string refName, int x, int y); void SetSize(std::string refName, int sz); void SetColor(std::string refName, int r, int g, int b); void SetBackgroundColor(std::string refName, int r, int g, int b); void SetVisible(std::string refName, int vis); void SetTTS(bool TTS); void ShowAllVisible(BITMAP* dest); }; #endif
[ "lcairco@2656ef14-ecf4-11dd-8fb1-9960f2a117f8" ]
[ [ [ 1, 67 ] ] ]
93069e1f1a910c8e8d3f40b739adb7a63772f4c8
a14b1659f72560b52f84c4d930867c2dad1e20bb
/sg16-win2kXP2003/debug.cpp
245a98ff11642d6ab95b23028a6948ddb0c680ea
[]
no_license
SigrandLLC/drivers
d36a6d0e827112f3b8913b7f7b7b7c20f33756bc
e8c7f672db1a102e0402043f8a7de798a5bae725
refs/heads/master
2021-04-28T08:49:28.042779
2009-03-10T06:31:10
2009-03-10T06:31:10
122,025,316
0
2
null
null
null
null
UTF-8
C++
false
false
1,744
cpp
#include "common.h" #include <stdio.h> #include <stdarg.h> #ifdef _DEBUG UINT DebugLevel=5; /* ----------------------------------------------------------------------------- * ------------------------------------------------------------------------------- */ void _UniCall DebugVPrintf( UINT const Level, AdapterDesc const *const Adapter, PCSTR const Fmt, va_list const Args ) { if( Level >= DebugLevel ) { char Str[128]; vsprintf( Str, Fmt, Args ); LARGE_INTEGER Time; NdisGetCurrentSystemTime( &Time ); UINT const MS=UINT( Time.QuadPart / 10000 ) % 100000; PCSTR const Type=( Level < 9 ) ? " " : "***** "; if( Adapter && Adapter->MemoryWindowAddr ) { DbgPrint( "sg16%c%05u %X:%s%s\n", Type[0], MS, Adapter->MemoryWindowAddr, Type, Str ); } else { DbgPrint( "sg16 %05u:%s%s\n", MS, Type, Str ); } } } /* ----------------------------------------------------------------------------- * ------------------------------------------------------------------------------- */ void _cdecl DebugPrintf( UINT const Level, AdapterDesc const *const Adapter, PCSTR const Fmt, ... ) { if( Level >= DebugLevel ) { va_list Args; va_start( Args, Fmt ); DebugVPrintf( Level, Adapter, Fmt, Args ); } } /* ----------------------------------------------------------------------------- * Verify pointer validity ------------------------------------------------------------------------------- */ bool _UniCall IsValidPtr( PCVOID Block, ULONG Size ) { Assert( KeGetCurrentIrql() <= DISPATCH_LEVEL ); return ( Block && MmIsAddressValid(PVOID(Block)) && MmIsAddressValid(PBYTE(Block) + Size - 1) ); } #endif /* _DEBUG */
[ [ [ 1, 65 ] ] ]
541e86be111f97ad5d3f0d5b96541ed145eaa7a8
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/CryEngine/CryCommon/CREImposter.h
90c1e1fdffc9645ea36867724eaa8c484b0b3d04
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,786
h
/*============================================================================= CREImposter.h : Imoster RE declarations/implementations. Copyright (c) 2001-2005 Crytek Studios. All Rights Reserved. Revision history: =============================================================================*/ #ifndef __CREIMPOSTER_H__ #define __CREIMPOSTER_H__ //================================================================================ struct SDynTexture2; struct SDynTexture; class CREImposter : public CRendElement { friend class CRECloud; CRenderCamera m_LastCamera; bool m_bScreenImposter; bool m_bSplit; float m_fRadiusX; float m_fRadiusY; Vec3 m_vQuadCorners[4]; // in world space, relative to m_vPos, in clockwise order, can be rotated Vec3 m_vNearPoint; Vec3 m_vFarPoint; int m_nLogResolutionX; int m_nLogResolutionY; IDynTexture *m_pTexture; static IDynTexture *m_pScreenTexture; IDynTexture *m_pFrontTexture; IDynTexture *m_pTextureDepth; float m_fErrorToleranceCosAngle; // cosine of m_fErrorToleranceAngle used to check if IsImposterValid SMinMaxBox m_WorldSpaceBV; struct CTerrainNode * m_pTerrainNode; uint m_State; int m_AlphaRef; float m_fCurTransparency; ColorF m_ColorHelper; Vec3 m_vPos; Vec3 m_vLastSunDir; uint8 m_nLastBestEdge; // 0..11 this edge is favored to not jitter between different edges float m_fNear; float m_fFar; bool IsImposterValid(const CRenderCamera& cam, float fRadiusX, float fRadiusY, float fCamRadiusX, float fCamRadiusY, const int iRequiredLogResX, const int iRequiredLogResY, const uint32 dwBestEdge ); void ReleaseResources(); const SMinMaxBox& mfGetWorldSpaceBounds() { return m_WorldSpaceBV; } bool Display(bool bDisplayFrontOfSplit); bool IsSplit() { return m_bSplit; } bool UpdateImposter(); bool PrepareForUpdate(); Vec3 GetPosition(); public: int m_nFrameReset; int m_FrameUpdate; float m_fTimeUpdate; static int m_MemUpdated; static int m_MemPostponed; static int m_PrevMemUpdated; static int m_PrevMemPostponed; CREImposter() : CRendElement(), m_pTexture(NULL), m_pFrontTexture(NULL), m_pTextureDepth(NULL), m_bSplit(false), m_fRadiusX(0), m_fRadiusY(0), m_fErrorToleranceCosAngle(cos(DEG2RAD(0.25f))), m_bScreenImposter(false), m_State(GS_DEPTHWRITE), m_AlphaRef(-1), m_fCurTransparency(1.0f), m_FrameUpdate(0), m_nFrameReset(0), m_fTimeUpdate(0), m_pTerrainNode(0), m_vLastSunDir(0, 0, 0), m_nLogResolutionX(0), m_nLogResolutionY(0), m_nLastBestEdge(0) { mfSetType(eDATA_Imposter); mfUpdateFlags(FCEF_TRANSFORM); m_ColorHelper = Col_White; } virtual ~CREImposter() { ReleaseResources(); } virtual float mfDistanceToCameraSquared(Matrix34& matInst); virtual void mfPrepare(); virtual bool mfDraw(CShader *ef, SShaderPass *sl); virtual CTerrainNode * GetTerrainNode() { return m_pTerrainNode; } virtual void SetTerrainNode(CTerrainNode * pTerrainNode) { m_pTerrainNode = pTerrainNode; } virtual void SetBBox(const Vec3 & min, const Vec3 & max) { m_WorldSpaceBV.SetMin(min); m_WorldSpaceBV.SetMax(max); } }; #include "Cry_Camera.h" class CREPanoramaCluster : public CRendElement { friend class CRECloud; SDynTexture * m_pTexture; SDynTexture * m_pTexture1; // For ATI HDR int m_AlphaRef; Vec3 m_vPrevCamPos; CCamera m_Camera; int m_nTexRes; int m_nDLDFlags; bool m_bTextureIsEmpty; void ReleaseResources(); bool Display(bool bDisplayFrontOfSplit); public: int m_FrameUpdate; float m_fTimeUpdate; float m_fCVarsCheckSumm; Vec3 m_vSunDir; Vec3 m_vSunColor; Vec3 m_vSkyColor; CREPanoramaCluster() : CRendElement(), m_pTexture(NULL), m_pTexture1(NULL), m_AlphaRef(-1), m_FrameUpdate(0), m_fTimeUpdate(0), m_vPrevCamPos(0,0,0), m_nTexRes(256), m_nDLDFlags(0), m_fCVarsCheckSumm(0), m_vSunDir(0,0,0), m_vSunColor(0,0,0), m_vSkyColor(0,0,0) { mfSetType(eDATA_PanoramaCluster); mfUpdateFlags(FCEF_TRANSFORM); } virtual ~CREPanoramaCluster() { ReleaseResources(); } bool UpdateImposter(); virtual void mfPrepare(); virtual bool mfDraw(CShader *ef, SShaderPass *sl); virtual float mfDistanceToCameraSquared(Matrix34& matInst); virtual void SetCamera(const CCamera & cam) { m_Camera = cam; } virtual void SetPrevCamPos(const Vec3 & vPrevCamPos) { m_vPrevCamPos = vPrevCamPos; } virtual Vec3 GetPrevCamPos() { return m_vPrevCamPos; } virtual void SetTexRes(int nTexRes) { m_nTexRes = nTexRes; } virtual void SetDLDFlags(int nDLDFlags) { m_nDLDFlags = nDLDFlags; } }; #endif // __CREIMPOSTER_H__
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 45 ], [ 48, 60 ], [ 62, 81 ], [ 83, 85 ], [ 88, 97 ], [ 99, 157 ], [ 159, 167 ] ], [ [ 46, 47 ], [ 61, 61 ], [ 82, 82 ], [ 86, 87 ], [ 98, 98 ], [ 158, 158 ] ] ]
6186f31aae2aceeb3fdd27b3c8b3f582b2b1d75a
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/luabind/detail/format_signature.hpp
9c165c3238bf7e125bcb6edf32595e83b43e7768
[]
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
3,265
hpp
// Copyright Daniel Wallin 2008. 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) #ifndef LUABIND_FORMAT_SIGNATURE_081014_HPP # define LUABIND_FORMAT_SIGNATURE_081014_HPP # include <luabind/config.hpp> # include <luabind/lua_include.hpp> # include <boost/mpl/begin_end.hpp> # include <boost/mpl/next.hpp> # include <boost/mpl/size.hpp> namespace luabind { class object; class argument; } // namespace luabind namespace luabind { namespace detail { LUABIND_API std::string get_class_name(lua_State* L, LUABIND_TYPE_INFO i); template <class T> struct type_to_string { static void get(lua_State* L) { lua_pushstring(L, get_class_name(L, LUABIND_TYPEID(T)).c_str()); } }; template <class T> struct type_to_string<T*> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, "*"); lua_concat(L, 2); } }; template <class T> struct type_to_string<T&> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, "&"); lua_concat(L, 2); } }; template <class T> struct type_to_string<T const> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, " const"); lua_concat(L, 2); } }; # define LUABIND_TYPE_TO_STRING(x) \ template <> \ struct type_to_string<x> \ { \ static void get(lua_State* L) \ { \ lua_pushstring(L, #x); \ } \ }; # define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(unsigned x) LUABIND_INTEGRAL_TYPE_TO_STRING(char) LUABIND_INTEGRAL_TYPE_TO_STRING(short) LUABIND_INTEGRAL_TYPE_TO_STRING(int) LUABIND_INTEGRAL_TYPE_TO_STRING(long) LUABIND_TYPE_TO_STRING(void) LUABIND_TYPE_TO_STRING(bool) LUABIND_TYPE_TO_STRING(std::string) LUABIND_TYPE_TO_STRING(lua_State) LUABIND_TYPE_TO_STRING(luabind::object) LUABIND_TYPE_TO_STRING(luabind::argument) # undef LUABIND_INTEGRAL_TYPE_TO_STRING # undef LUABIND_TYPE_TO_STRING template <class End> void format_signature_aux(lua_State*, bool, End, End) {} template <class Iter, class End> void format_signature_aux(lua_State* L, bool first, Iter, End end) { if (!first) lua_pushstring(L, ","); type_to_string<typename Iter::type>::get(L); format_signature_aux(L, false, typename mpl::next<Iter>::type(), end); } template <class Signature> void format_signature(lua_State* L, char const* function, Signature) { typedef typename mpl::begin<Signature>::type first; type_to_string<typename first::type>::get(L); lua_pushstring(L, " "); lua_pushstring(L, function); lua_pushstring(L, "("); format_signature_aux( L , true , typename mpl::next<first>::type() , typename mpl::end<Signature>::type() ); lua_pushstring(L, ")"); lua_concat(L, mpl::size<Signature>() * 2 + 2); } }} // namespace luabind::detail #endif // LUABIND_FORMAT_SIGNATURE_081014_HPP
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 136 ] ] ]
716b20238dec7bd32bb81d2ac2908959cff09f07
45229380094a0c2b603616e7505cbdc4d89dfaee
/wavelets/facedetector_src/src/cvLib/ImageFrame.cpp
7a5f492c20fc0093984df2fb6680d5f9a331cb5d
[]
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,331
cpp
#include "stdafx.h" #include "imageframe.h" #include "vec2D.h" #include "vec2Dc.h" //gaus blur filter static float gblur[] = { 0.0625f, 0.125f, 0.0625f, 0.125f, 0.25f, 0.125f, 0.0625f, 0.125f, 0.0625f }; ImageFrame::ImageFrame(unsigned int width, unsigned int height, float zoom) : m_zoom(zoom) { unsigned int w = unsigned int(zoom * (float)width); unsigned int h = unsigned int(zoom * (float)height); m_y = new vec2D(h, w); m_y_blured = new vec2D(h, w); m_gaus_filter = new vec2D(3, 3, -1, -1, gblur); m_face_map = new vec2D(h, w); m_tmp_face_map = new vec2D(h, w); m_search_map = new vec2Dc(h, w); m_motion_map = new vec2Dc(h, w); m_skin_map = new vec2Dc(h, w); grdx = new vec2D(2, w); grdy = new vec2D(2, h); } ImageFrame::~ImageFrame() { delete m_y; delete m_y_blured; delete m_gaus_filter; delete m_face_map; delete m_tmp_face_map; delete m_search_map; delete m_motion_map; delete m_skin_map; delete grdx; delete grdy; } void ImageFrame::load_frame(const vec2D* y, const vec2Dc* motion, const vec2Dc* skin) { if (m_zoom == 1.0f) { m_y->copy(*y); m_search_map->set(1); if (skin != 0) m_skin_map->copy(*skin); else m_skin_map->set(1); if (motion != 0) m_motion_map->copy(*motion); else m_motion_map->set(1); } else { m_y->inter2(*y, *grdx, *grdy); if (skin != 0) m_skin_map->inter2(*skin, *grdx, *grdy); else m_skin_map->set(1); if (motion != 0) m_motion_map->inter2(*motion, *grdx, *grdy); else m_motion_map->set(1); } m_search_map->and(*m_motion_map, *m_skin_map); m_y_blured->conv2D(*m_y, *m_gaus_filter); }
[ "perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671" ]
[ [ [ 1, 76 ] ] ]
2c944d31e139cce8b6445a7a5fa67ea63d791ae3
28aa891f07cc2240c771b5fb6130b1f4025ddc84
/clpbr/clpbr/renderer.h
660b15e8a1c8b9cc8ec5754ae27fd2f5e1640d63
[]
no_license
Hincoin/mid-autumn
e7476d8c9826db1cc775028573fc01ab3effa8fe
5271496fb820f8ab1d613a1c2355504251997fef
refs/heads/master
2021-01-10T19:17:01.479703
2011-12-19T14:32:51
2011-12-19T14:32:51
34,730,620
0
0
null
null
null
null
UTF-8
C++
false
false
173
h
#ifndef _RENDERER_H_ #define _RENDERER_H_ class Scene; class Renderer{ public: virtual ~Renderer(){} //virtual void Render(const Scene *scene) = 0; }; #endif
[ "luozhiyuan@ea6f400c-e855-0410-84ee-31f796524d81" ]
[ [ [ 1, 12 ] ] ]
9ab9483be02dfdb03e8ac7c6bc360eb42931bae9
25233569ca21bf93b0d54ca99027938d65dc09d5
/BlankTexture.h
0050895c2474ecdc015ba6ccec89d435090937ec
[]
no_license
jugg/litestep-module-label
6ede7ff5c80c25e1dc611d02ba5dc13559914ddc
a75ef94a56d68c2a928bde5bab60318e609b9a10
refs/heads/master
2021-01-18T09:20:42.000147
2004-10-07T12:28:00
2004-10-07T12:28:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
335
h
#if !defined(__BLANKTEXTURE_H) #define __BLANKTEXTURE_H #include "Texture.h" class BlankTexture : public Texture { public: void configure(const string &prefix, const string &subKey) { } void apply(HDC hDC, int x, int y, int width, int height) { } boolean isTransparent() const { return true; } }; #endif
[ [ [ 1, 19 ] ] ]
54e02787b459393751e144138047c9561cffbae2
50e6ba037f1c60e5342c707a9d4223ac379a8047
/framework/App.cpp
24229ba31c5cc666f53cbe584066bfb63d98a490
[]
no_license
buryhuang/blueplus
299bbe23efa93f9d3acceeedccd5e8194cb71891
7843ccfa4b8fc773c6de1992acb9c9bb805671ed
refs/heads/master
2021-05-06T15:59:40.471142
2011-05-31T06:50:46
2011-05-31T06:50:46
113,696,936
1
0
null
null
null
null
UTF-8
C++
false
false
127
cpp
/** \addtogroup framework * @{ */ #include "App.h" CApp::CApp(void) { } CApp::~CApp(void) { } /** @}*/
[ [ [ 1, 16 ] ] ]
2acec5e750c04614a60338633061efbf9fea489a
aa604ed879fcf702e369db84fe61d3b25b855211
/StudContainer.cpp
f5706df1efee88d991c17c60105784875f2f8a4a
[]
no_license
dziedmaroz/structures
f89e65ef25b53f9e5ba884e1ad660757083aa7c7
3983712379e72eb0f975ad2ec9a5725ffcf467e8
refs/heads/master
2020-05-30T09:29:20.512138
2011-04-29T04:45:00
2011-04-29T04:45:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,728
cpp
#include "StudContainer.h" #include <iostream> #include <cstring> #include <cstdlib> StudContainer::StudContainer (int n) { size_=n; studPointer_=new Student[size_]; count_=0; } StudContainer::StudContainer(const StudContainer &orig) { size_= orig.size_; count_=orig.count_; delete []studPointer_; studPointer_=new Student [size_]; for (int i=0;i<count_;i++) { studPointer_[i]=orig.studPointer_[i]; } } StudContainer& StudContainer::operator = (StudContainer& orig) { size_= orig.size_; count_=orig.count_; delete []studPointer_; studPointer_=new Student [size_]; for (int i=0;i<count_;i++) { studPointer_[i]=orig.studPointer_[i]; } return *this; } StudContainer::~StudContainer () { delete [] studPointer_; } bool StudContainer::insert (Student &item) { if (count_<size_) { studPointer_[count_]=item; count_++; return true; } return false; } bool StudContainer::remove (char* name) { if (findByName (name)==-1) return false; if (count_!=0) { for (int i=findByName(name);i<count_;i++) { studPointer_[i]=studPointer_[i+1]; } count_--; return true; } return false; } int StudContainer::getSize () { return size_; } int StudContainer::getCount () { return count_+1; } Student* StudContainer::getStud (char* name) { if (findByName (name)==-1) return NULL; Student* tmp = new Student; *tmp = studPointer_[findByName(name)]; return tmp; } void StudContainer::print (ostream &stream) { for (int i=0;i<count_;i++) stream<<studPointer_[i].name<<"\t"<<studPointer_[i].num<<"\t"<<studPointer_[i].grade<<"\n"; } int StudContainer::findByName (char* name) { for (int i=0;i<count_;i++) { bool isMatch=true; for (int j=0;j<strlen(name);j++) if (studPointer_[i].name[j]!=name[j]) { isMatch=false; break; } if (isMatch) return i; } return -1; } int StudContainer::cmpNames (const void* x, const void* y) { int i=0; Student* a=(Student*)x; Student* b=(Student*)y; while (strlen(a->name)==strlen(b->name) && i<strlen(a->name) && a->name[i]==b->name[i++]); return a->name[i]-b->name[i]; }; void StudContainer::sortByName () { for (int i=0;i<this->count_;i++) for (int j=i;j<this->count_-1;j++) { if (cmpNames ((void*)(this->studPointer_+j),(void*)(this->studPointer_+j+1))>0) { Student tmp = studPointer_[j]; studPointer_[j]=studPointer_[j+1]; studPointer_[j+1]=tmp; } } }
[ [ [ 1, 131 ] ] ]
e8be4b9710c962b59d81b72780cc9c7d15e6bb3d
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/tools/wfbuildgrid.cc
e2cd79f34eab222f096b098a090f0a7db840a926
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,425
cc
//------------------------------------------------------------------- // wfbuildgrid.cc // Generate Nomads build grid bitmap from island collision model. // (C) 2000 RadonLabs GmbH //------------------------------------------------------------------- #include "kernel/nkernelserver.h" #include "gfx/nbmpfile.h" #include "mathlib/triangle.h" #include "mathlib/bbox.h" #include "tools/wfobject.h" #include "tools/wftools.h" #ifndef PI #define PI 3.14159265f #endif enum nGridType { VALID, OUTSIDE, TOOSTEEP }; static int NumFaces = 0; static int Width = 0; static int Height = 0; static bbox3 BBox; static triangle *TriArray = NULL; static float *HeightArray = NULL; static nGridType* typeArray = NULL; //------------------------------------------------------------------- // alloc_arrays() // Get maximum x/z size of the island and initialize // global variables Width, Height, HeightArray. // 09-Nov-00 floh created //------------------------------------------------------------------- void alloc_arrays(wfObject& src, float grid_size) { n_assert(NULL == HeightArray); // compute the mesh's bounding box BBox.begin_grow(); vector<wfCoord>::iterator v_src; for (v_src=src.v_array.begin(); v_src!=src.v_array.end(); v_src++) { BBox.grow(v_src->v); } // the midpoint of the heightarray equals the midpoint of the island float x0 = n_abs(BBox.vmax.x); float x1 = n_abs(BBox.vmin.x); float y0 = n_abs(BBox.vmax.z); float y1 = n_abs(BBox.vmin.z); // adjust bounding box size to multiple of grid_size float adjustX0 = (float) ((floor(x0 / grid_size) + 1.0) * grid_size); float adjustX1 = (float) ((floor(x1 / grid_size) + 1.0) * grid_size); float adjustY0 = (float) ((floor(y0 / grid_size) + 1.0) * grid_size); float adjustY1 = (float) ((floor(y1 / grid_size) + 1.0) * grid_size); float xsize = 2.0f * ((adjustX0 > adjustX1) ? adjustX0 : adjustX1); float ysize = 2.0f * ((adjustY0 > adjustY1) ? adjustY0 : adjustY1); // get the required height array size Width = int(xsize / grid_size); Height = int(ysize / grid_size); HeightArray = new float[Width*Height]; typeArray = new nGridType[Width*Height]; // make sure that width and height are even n_assert(((Width>>1)<<1) == Width); n_assert(((Height>>1)<<1) == Height); } //------------------------------------------------------------------- // gen_tri_array() // Generate array of vector3 objects with triangle data from // wavefront file. // 09-Nov-00 floh created //------------------------------------------------------------------- void gen_tri_array(wfObject& src) { n_assert(NULL == TriArray); fprintf(stderr,"-> generating triangles\n"); NumFaces = src.f_array.size(); TriArray = new triangle[NumFaces]; vector<wfFace>::iterator f_src; int fi; for (fi=0,f_src=src.f_array.begin(); f_src!=src.f_array.end(); f_src++,fi++) { vector3 v[3]; int i; for (i=0; i<3; i++) { v[i] = src.v_array.at(f_src->points.at(i).v_index).v; } TriArray[fi].set(v[0],v[1],v[2]); } } //------------------------------------------------------------------- // gen_height_array() // Shoot grid of vertical rays on triangle array, and record // intersection positions in height array. // 09-Nov-00 floh created //------------------------------------------------------------------- void gen_height_array(float grid_size, float max_h_diff) { fprintf(stderr,"-> doing intersection checks...\n"); // compute the borders of the range we have to check float x0 = float(Width>>1) * -grid_size; float z0 = float(Height>>1) * -grid_size; // we do multiple intersections per height array element // and compute the average of all checks per height element // as well as determine whether the terrain at that position // is too steep to build there const int res = 4; float advance = grid_size / float(res); float sub_array[res+1][res+1]; int ix,iz; for (iz=0; iz<Height; iz++) { for (ix=0; ix<Width; ix++) { int ixx,izz; float cur_z = z0 + float(iz) * grid_size; for (izz=0; izz<=res; izz++, cur_z+=advance) { float cur_x = x0 + float(ix) * grid_size; for (ixx=0; ixx<=res; ixx++, cur_x+=advance) { // shoot ray at current x and z position into island vector3 v0(cur_x, 127.0f, cur_z); vector3 v1(cur_x, -128.0f, cur_z); line3 l(v0,v1); float max_t = 0.0f; bool has_intersected = false; int k; for (k=0; k<NumFaces; k++) { float t; if (TriArray[k].intersect(l,t)) { t = 1.0f - t; if (t > max_t) { max_t = t; } has_intersected = true; } } if (has_intersected) { sub_array[ixx][izz] = max_t; } else { sub_array[ixx][izz] = -1.0f; } } } // validate subgrid: // - if there is at least one non-intersection, the whole area // becomes invalid // - if the height difference is greater then max_height, // the whole area becomes invalid // - otherwise, the resulting height is the average of // all subheights bool is_valid = true; bool is_toosteep = false; float min_h = +2.0f; float max_h = -2.0f; int num_outside = 0; for (ixx=0; ixx<=res; ixx++) { for (izz=0; izz<=res; izz++) { float h = sub_array[ixx][izz]; if (h < -0.1f) { // no intersection at this position, increment // "outside" counter num_outside++; } else { // valid intersection position, update minimal // and maximal and average_height if (h < min_h) { min_h = h; } if (h > max_h) { max_h = h; } } } } // too many "outside" hits, invalidate grid position if (num_outside > 2) { is_valid = false; is_toosteep = false; } // see if (max_h-min_h) is greater then allowed height difference if (is_valid && ((max_h-min_h) > max_h_diff)) { is_valid = false; is_toosteep = true; } // if valid, fill HeightArray element with average height if (is_valid) { HeightArray[iz*Width + ix] = min_h; typeArray[iz*Width + ix] = VALID; fprintf(stderr, "o"); } else if (is_toosteep) { HeightArray[iz*Width + ix] = min_h; typeArray[iz*Width + ix] = TOOSTEEP; fprintf(stderr, "x"); } else { HeightArray[iz*Width + ix] = min_h; typeArray[iz*Width + ix] = OUTSIDE; fprintf(stderr, "."); } } fprintf(stderr, "\n"); } } //------------------------------------------------------------------- // gen_bmp_file() // 09-Nov-00 floh created //------------------------------------------------------------------- void gen_bmp_file(const char *fname) { n_assert(fname); fprintf(stderr, "-> writing bmp file...\n"); nBmpFile bmp; bmp.SetWidth(Width); bmp.SetHeight(Height); if (bmp.Open(fname,"wb")) { int buf_size = Width*3+4; uchar *buf = new uchar[buf_size]; int x,y; for (y=0; y<Height; y++) { float *heights = &(HeightArray[Width*y]); nGridType* types = &(typeArray[Width*y]); for (x=0; x<Width; x++) { // compute height as ushort ushort height16 = (ushort) (heights[x] * ((1<<16)-1)); switch (types[x]) { case TOOSTEEP: // too steep: blue == 128 buf[x*3+0] = 128; buf[x*3+1] = (uchar) (height16 >> 8); buf[x*3+2] = (uchar) (height16 & 0xff); break; case VALID: // valid position: blue == 0 buf[x*3+0] = 0; buf[x*3+1] = (uchar) (height16 >> 8); buf[x*3+2] = (uchar) (height16 & 0xff); break; case OUTSIDE: // not on island: blue == 255 buf[x*3+0] = 255; buf[x*3+1] = 0; buf[x*3+2] = 0; break; } } bmp.WriteLine(buf); } delete buf; bmp.Close(); } } //------------------------------------------------------------------- // main() // 09-Nov-00 floh created //------------------------------------------------------------------- int main(int argc, char *argv[]) { nKernelServer *ks = new nKernelServer; bool help; long retval = 0; float grid_size; float max_height_diff; const char *fname; fprintf(stderr,"-> wfbuildgrid\n"); // check args help = wf_getboolarg(argc, argv, "-help"); grid_size = wf_getfloatarg(argc, argv, "-gridsize", 5.0f); max_height_diff = wf_getfloatarg(argc, argv, "-maxdiff", 1.0f); fname = wf_getstrarg(argc,argv, "-fname", "bgrid.bmp"); if (help) { fprintf(stderr, "wfbuildgrid [-help] [-gridsize] [-maxdiff] [-fname]\n" "(C) 2000 Andre Weissflog\n" "Generate height map for spherical terrain renderer from 3d model.\n" "-help -- show help\n" "-gridsize -- size of grid element in meters (def 5.0)\n" "-maxdiff -- max height difference in grid element in meters (def 1.0)\n" "-fname -- filename of output file (24 bpp BMP, def bgrid.bmp\n"); return 0; } wfObject src; FILE *in, *out; if (!wf_openfiles(argc, argv, in, out)) { fprintf(stderr,"file open failed!\n"); retval = 10; goto ende; } // load source object fprintf(stderr,"loading...\n"); if (!src.load(in)) { fprintf(stderr,"Load failed!\n"); retval = 10; goto ende; } // do stuff... alloc_arrays(src, grid_size); gen_tri_array(src); gen_height_array(grid_size, (max_height_diff/256.0f)); gen_bmp_file(fname); wf_closefiles(in, out); ende: if (TriArray) delete[] TriArray; if (HeightArray) delete[] HeightArray; fprintf(stderr,"<- wfbuildgrid\n"); delete ks; return retval; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 366 ] ] ]
9c077294febf3f907853158c43da9a4305c37f8d
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleAffectors/ParticleUniverseInterParticleColliderFactory.h
397bbe82536e5845e62559eba0ce399c117750ad
[]
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,908
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_INTERPARTICLE_COLLIDER_FACTORY_H__ #define __PU_INTERPARTICLE_COLLIDER_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseInterParticleColliderTokens.h" #include "ParticleUniverseInterParticleCollider.h" #include "ParticleUniverseAffectorFactory.h" namespace ParticleUniverse { /** Factory class responsible for creating the InterParticleCollider. */ class _ParticleUniverseExport InterParticleColliderFactory : public ParticleAffectorFactory { public: InterParticleColliderFactory(void){}; virtual ~InterParticleColliderFactory(void){}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType() const { return "InterParticleCollider"; } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { return _createAffector<InterParticleCollider>(); } /** See ParticleAffectorFactory */ virtual void setupTokenDefinitions(ITokenRegister* tokenRegister) { // Delegate to mInterParticleColliderTokens mInterParticleColliderTokens.setupTokenDefinitions(tokenRegister); } protected: InterParticleColliderTokens mInterParticleColliderTokens; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 59 ] ] ]
e6dd46580fe81691817e1fd13c7b0bf4c9d7cb78
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Components/Metrics/AdvancedKappaStatistic/elxAdvancedKappaStatisticMetric.cxx
5a33f4243230631db9b98f4b6298f49cb54d6760
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
676
cxx
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #include "elxAdvancedKappaStatisticMetric.h" elxInstallMacro( AdvancedKappaStatisticMetric );
[ [ [ 1, 18 ] ] ]
0a2eb0f547113c55102286ca600dd610773de0df
78af025c564e5a348fd268e2f398a79a9b76d7d1
/src/iPhoneToday/PropertySheetPageAnimation.cpp
ce997e72db6fee8b3bc2010abe9dcced64869a6a
[]
no_license
tronikos/iphonetoday
c2482f527299f315440a1afa1df72ab8e4f68154
d2ba13d97df16270c61642b2f477af8480c6abdf
refs/heads/master
2021-01-01T18:22:46.483398
2011-05-14T05:20:58
2011-05-14T05:20:58
32,228,280
1
0
null
null
null
null
UTF-8
C++
false
false
3,599
cpp
////////////////////////////////////////////////////////////////////////////// // PropertySheetPageAnimation.cpp : Defines the property sheet page procedures. // #include "stdafx.h" #include "iPhoneToday.h" #include "OptionDialog.h" /*************************************************************************/ /* General options dialog box procedure function */ /*************************************************************************/ LRESULT CALLBACK OptionDialogAnimation(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { InitOptionsDialog(hDlg, TAB_ANIMATION); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"None"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"Expand rectangle from center"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"Zoom out from center"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"Zoom in to center"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"Expand rectangle from clicked area"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"Zoom out from clicked area"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_ADDSTRING, 0, (LPARAM)L"Zoom in to clicked area"); SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_SETCURSEL, configuracion->animationEffect, 0); SetDlgItemHex(hDlg, IDC_EDIT_ANIM_COLOR, configuracion->animationColor); SetDlgItemInt(hDlg, IDC_EDIT_ANIMATION_TIME, configuracion->animationDuration, TRUE); SetDlgItemInt(hDlg, IDC_EDIT_ANIMATION_DELAY, configuracion->animationDelay, TRUE); SendMessage(GetDlgItem(hDlg, IDC_CHECK_ANIMATION_LAUNCHAPP), BM_SETCHECK, configuracion->launchAppAtBeginningOfAnimation ? BST_CHECKED : BST_UNCHECKED, 0); } return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_BUTTON_ANIM_COLOR: int rgbCurrent; COLORREF nextColor; rgbCurrent = GetDlgItemHex(hDlg, IDC_EDIT_ANIM_COLOR, NULL); if (ColorSelector(hDlg, rgbCurrent, &nextColor)) { SetDlgItemHex(hDlg, IDC_EDIT_ANIM_COLOR, nextColor); } break; } break; } return DefOptionWindowProc(hDlg, TAB_ANIMATION, uMsg, wParam, lParam); } /*BOOL IsValidConfigurationAnimation(HWND hDlg) { int animationDuration = GetDlgItemInt(hDlg, IDC_EDIT_ANIMATION_TIME, NULL, TRUE); int animationDelay = GetDlgItemInt(hDlg, IDC_EDIT_ANIMATION_DELAY, NULL, TRUE); if (animationDuration < 0 || animationDuration > 10000) { MessageBox(hDlg, TEXT("Animation time value is not valid!"), TEXT("Error"), MB_OK); return FALSE; } if (animationDelay < 0 || animationDelay > 10000) { MessageBox(hDlg, TEXT("Animation delay value is not valid!"), TEXT("Error"), MB_OK); return FALSE; } return TRUE; }*/ BOOL SaveConfigurationAnimation(HWND hDlg) { // if (!IsValidConfigurationAnimation(hDlg)) return FALSE; configuracion->animationEffect = SendMessage(GetDlgItem(hDlg, IDC_COMBO_ANIMATION), CB_GETCURSEL, 0, 0); configuracion->animationColor = GetDlgItemHex(hDlg, IDC_EDIT_ANIM_COLOR, NULL); configuracion->animationDuration= GetDlgItemInt(hDlg, IDC_EDIT_ANIMATION_TIME, NULL, TRUE); configuracion->animationDelay = GetDlgItemInt(hDlg, IDC_EDIT_ANIMATION_DELAY, NULL, TRUE); configuracion->launchAppAtBeginningOfAnimation = SendMessage(GetDlgItem(hDlg, IDC_CHECK_ANIMATION_LAUNCHAPP), BM_GETCHECK, 0, 0) == BST_CHECKED; return TRUE; }
[ [ [ 1, 81 ] ] ]
6f29a80d5e1fc02bc46538ddbd41041c2e79ea2d
1bedffb06790d8e001e78e970fc290234550ed67
/lazyslash/ResultsDisplay.h
eb339060a91e25b08d00d5b9a37999fff516a0b2
[]
no_license
mRB0/lazyslash
e14e2a7769b466555848548aee0d1d522da8ff9e
52e06cf64cca5726b30d2f74b2c3392114f59dd9
refs/heads/master
2021-01-21T12:46:55.957672
2010-03-24T06:58:52
2010-03-24T06:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,296
h
/* * $Id$ */ #pragma once using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; namespace lazyslash { /// <summary> /// Summary for ResultsDisplay /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class ResultsDisplay : public System::Windows::Forms::Form { public: ResultsDisplay(String^ resultsText) { InitializeComponent(); this->resultsBox->Text = resultsText; this->CancelButton = this->closeButton; } ResultsDisplay(String^ resultsText, String^ windowtitle) { InitializeComponent(); this->resultsBox->Text = resultsText; this->CancelButton = this->closeButton; this->Text = windowtitle; } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~ResultsDisplay() { if (components) { delete components; } } private: System::Windows::Forms::Button^ closeButton; private: System::Windows::Forms::TextBox^ resultsBox; protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(ResultsDisplay::typeid)); this->closeButton = (gcnew System::Windows::Forms::Button()); this->resultsBox = (gcnew System::Windows::Forms::TextBox()); this->SuspendLayout(); // // closeButton // this->closeButton->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right)); this->closeButton->Location = System::Drawing::Point(545, 293); this->closeButton->Name = L"closeButton"; this->closeButton->Size = System::Drawing::Size(75, 23); this->closeButton->TabIndex = 0; this->closeButton->Text = L"Close"; this->closeButton->UseVisualStyleBackColor = true; // // resultsBox // this->resultsBox->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->resultsBox->BackColor = System::Drawing::Color::Black; this->resultsBox->Font = (gcnew System::Drawing::Font(L"Courier New", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->resultsBox->ForeColor = System::Drawing::Color::DarkOrange; this->resultsBox->Location = System::Drawing::Point(12, 12); this->resultsBox->Multiline = true; this->resultsBox->Name = L"resultsBox"; this->resultsBox->ReadOnly = true; this->resultsBox->ScrollBars = System::Windows::Forms::ScrollBars::Vertical; this->resultsBox->Size = System::Drawing::Size(608, 275); this->resultsBox->TabIndex = 1; // // ResultsDisplay // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(632, 328); this->Controls->Add(this->resultsBox); this->Controls->Add(this->closeButton); this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon"))); this->Name = L"ResultsDisplay"; this->Text = L"Results!"; this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion }; }
[ [ [ 1, 122 ] ] ]
c1db9b3258467f9fcd50da3af323b42e4f68bc3f
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/Network/MsgTalk.cpp
22e820b4c40f782329f59ba7ab0126bfe1d56821
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
GB18030
C++
false
false
27,042
cpp
#include "AllMsg.h" #pragma warning(disable:4786) #include "mapgroup.h" #include "user.h" void CMsgTalk::Process(CMapGroup& mapGroup, SOCKET_ID idSocket, OBJID idNpc) { #ifdef _MSGDEBUG ::LogMsg("Process MsgTalk, Sender:%s, Receiver:%s, Words:%s", szSender, szReceiver, szWords); #endif char szSender[_MAX_NAMESIZE]; char szReceiver[_MAX_NAMESIZE]; char szEmotion[_MAX_NAMESIZE]; char szWords[_MAX_WORDSSIZE]; m_StrPacker.GetString(0, szSender, sizeof(szSender)); m_StrPacker.GetString(1, szReceiver, sizeof(szReceiver)); m_StrPacker.GetString(2, szEmotion, sizeof(szEmotion)); m_StrPacker.GetString(3, szWords, sizeof(szWords)); CHECK(strlen(szWords) <= 255); IRole* pRole = mapGroup.GetRoleManager()->QueryRole(idSocket, idNpc); if(!pRole) { if(idSocket == SOCKET_NONE) return; // TransmitMsg switch(m_unTxtAttribute) { case _TXTATR_SYNDICATE: { OBJID idSyn = m_idTransmit; CSyndicate* pSyn = mapGroup.GetSynManager()->QuerySyndicate(idSyn); if (pSyn) { pSyn->BroadcastSynMsg(this, NULL); } } break; } return; } CUser* pUser = NULL; pRole->QueryObj(OBJ_USER, IPP_OF(pUser)); //? pUser may be null if(pUser && strcmp(pUser->GetName(), szSender) != 0) { if (!pUser->IsGM()) { ::GmLogSave("玩家[%s]企图冒用他人名字[%s]发布Talk消息,请予封号。", pUser->GetName(), szSender); return ; } } if(!pRole->IsTalkEnable()) { pRole->SendSysMsg(STR_CAN_NOT_TALK); return; } if(pUser && pUser->IsGM()) { ::GmLogSave("-TALK %s->%s: %s", szSender, szReceiver, szWords); } if(pUser && szWords[0] == '/') { char szCmd[_MAX_WORDSSIZE] = "NO_CMD"; char szParam[_MAX_WORDSSIZE] = ""; DEBUG_TRY // VVVVVVVVVVVVVVVVVVVVVVVVV sscanf(szWords+1, "%s %s", szCmd, szParam); if(stricmp(szCmd, "pro") == 0) { if(pUser->IsPM()) { int nData = atoi(szParam); pUser->SetAttrib(_USERATTRIB_PORFESSION, nData, SYNCHRO_TRUE); } } else if (stricmp(szCmd, "焰火") == 0) { if(pUser->IsGM()) { MsgItem msg; IF_OK (msg.Create(pUser->GetID(), ITEMACT_FIREWORKS, ITEMPOSITION_NONE)) pUser->BroadcastRoomMsg(&msg, true); } } else if (stricmp(szCmd, "焰火2") == 0) { if(pUser->IsGM()) { int nLen = strlen(szParam); if (nLen > 0 && nLen < 9) { CMsgName msg; IF_OK (msg.Create(NAMEACT_FIREWORKS, szParam)) pUser->BroadcastRoomMsg(&msg, true); } } } else if (stricmp(szCmd, "kickoutcheat") == 0) { if(pUser->IsPM()) { int nData = 0; if (2 == sscanf(szWords+1, "%s %d", szCmd, &nData)) { extern long g_sKickoutCheat; long nOld = InterlockedExchange(&g_sKickoutCheat, nData); pUser->SendSysMsg("set kickoutcheat OK! old value is %d", nOld); } } } #ifdef _DEBUG else if (stricmp(szCmd, "recover") == 0) { int nData = 0; if (2 == sscanf(szWords+1, "%s %d", szCmd, &nData)) { pUser->RecoverEquipmentDur(nData); } } else if (stricmp(szCmd, "weaponexp") == 0) { int nData = 0, nWeapon = 0; if (3 == sscanf(szWords+1, "%s %d %d", szCmd, &nWeapon, &nData)) { pUser->AddWeaponSkillExp(nWeapon, nData); } } else if (stricmp(szCmd, "itemquality") == 0) { int nData = atoi(szParam); pUser->UpEquipmentQuality(nData); } else if (stricmp(szCmd, "itemlev") == 0) { int nData = atoi(szParam); pUser->UpEquipmentLevel(nData); } else if (stricmp(szCmd, "divoice") == 0) { pUser->Divorce(); } /* else if (stricmp(szCmd, "resetlev") == 0) { int nForce = 5, nDex = 2, nHealth = 3, nSoul = 0; int nPro = pUser->GetProfessionSort(); if (nPro == 1) pUser->SetAttrib(_USERATTRIB_PORFESSION, 10, SYNCHRO_TRUE); else if (nPro == 2) pUser->SetAttrib(_USERATTRIB_PORFESSION, 20, SYNCHRO_TRUE); else if (nPro >= 10 && nPro < 20) { pUser->SetAttrib(_USERATTRIB_PORFESSION, 100, SYNCHRO_TRUE); nForce = 0; nDex = 2; nHealth = 3; nSoul = 5; } pUser->SetAttrib(_USERATTRIB_FORCE, nForce, SYNCHRO_TRUE); pUser->SetAttrib(_USERATTRIB_SOUL, nSoul, SYNCHRO_TRUE); pUser->SetAttrib(_USERATTRIB_HEALTH, nHealth, SYNCHRO_TRUE); pUser->SetAttrib(_USERATTRIB_DEX, nDex, SYNCHRO_TRUE); pUser->SetAttrib(_USERATTRIB_LEV, 1, SYNCHRO_TRUE); } */ else if (stricmp(szCmd, "rename") == 0) { pUser->SetName(szParam); pUser->SendSysMsg("阁下已经更名为%s。", szParam); } else if(stricmp(szCmd, "pk") == 0) { int nData = 0; if (2 == sscanf(szWords+1, "%s %d", szCmd, &nData)) { int nDeltaPk = nData - pUser->GetPk(); pUser->AddPk(nDeltaPk); } } else if(stricmp(szCmd, "addpoint") == 0) { int nData = 0; if (2 == sscanf(szWords+1, "%s %d", szCmd, &nData)) { pUser->SetAttrib(_USERATTRIB_ADDPOINT, nData, SYNCHRO_TRUE); } } else if(stricmp(szCmd, "testmonster") == 0) { DWORD dwType = 0, dwAmount = 0; if (3 == sscanf(szWords+1, "%s %u %u", szCmd, &dwType, &dwAmount)) { CNpcType* pType = MonsterType()->GetObj(dwType); if (pType) { for (int j=0; j<dwAmount; j++) { ST_CREATENEWNPC info; memset(&info, 0L, sizeof(info)); info.id = MONSTERID_FIRST+j; info.idMap = 1002; CMonster* pMonster = CMonster::CreateNew(); //if (pMonster->Create(m_idProcess, pType, &info)) if (pMonster->Create(mapGroup.GetID(), pType, &info)) { pMonster->BeKill(pUser->QueryRole()); } pMonster->ReleaseByOwner(); } } } } #endif else if(stricmp(szCmd, "sp") == 0) { if(pUser->IsPM()) { int nData = atoi(szParam); pUser->SetAttrib(_USERATTRIB_ENERGY, nData, SYNCHRO_TRUE); } } else if(stricmp(szCmd, "awardmoney") == 0) { if(pUser->IsPM()) { int nMoney = atoi(szParam); if(pUser->GainMoney(nMoney, SYNCHRO_TRUE)) pUser->SendSysMsg("[您的钱增加了。]"); } } else if(stricmp(szCmd, "awarditem") == 0) { if(pUser->IsPM()) { int nItemType = atoi(szParam); if(pUser->AwardItem(nItemType, SYNCHRO_TRUE, CUser::IDENT_OK)) pUser->SendSysMsg("[您的物品增加了。]"); } } else if(stricmp(szCmd, "kickout") == 0) { if(pUser->IsGM()) { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szParam); if (pTarget) { mapGroup.GetUserManager()->KickOutSocket(pTarget->GetSocketID(), "GM /kickout"); } } } else if(stricmp(szCmd, "kickoutall") == 0) { if(pUser->IsGM()) { LOGMSG("kickoutall process!"); pUser->SendSysMsg(STR_KICKOUT_ALL); mapGroup.QueryIntraMsg()->PrintText("Server stop by GM, close server please!"); mapGroup.QueryIntraMsg()->CloseMapGroup(idSocket); } } else if(stricmp(szCmd, "find") == 0) { if(pUser->IsGM()) { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szParam); if (pTarget) { int nPosX = pTarget->GetPosX(); int nPosY = pTarget->GetPosY(); pUser->FlyMap(pTarget->GetMapID(), nPosX, nPosY); } } } else if(stricmp(szCmd, "uplev") == 0) { if (pUser->IsPM()) { int nLev = atoi(szParam); if (nLev > 0) { pUser->IncLev(nLev); // pUser->AddAttrib(_USERATTRIB_ADDPOINT, nLev*_ADDITIONALPOINT_NUM, SYNCHRO_TRUE); pUser->AllotPoint(); CMsgAction msg; if (msg.Create(pUser->GetID(), 0, 0, 0, actionUplev, 0, 0)) pUser->BroadcastRoomMsg(&msg, INCLUDE_SELF); pUser->AddAttrib(_USERATTRIB_LEV, 0, SYNCHRO_TRUE); } } } else if(stricmp(szCmd, "life") == 0) { if (pUser->IsGM()) { int nData = pUser->GetMaxLife(); int nLife = 0; sscanf(szWords+1, "%s %d", szCmd, &nLife); if(nLife) nData = nLife; pUser->SetAttrib(_USERATTRIB_LIFE, nData, SYNCHRO_TRUE); } } else if(stricmp(szCmd, "mana") == 0) { if (pUser->IsGM()) { int nData = pUser->GetMaxMana(); pUser->SetAttrib(_USERATTRIB_MANA, nData, SYNCHRO_TRUE); } } else if(stricmp(szCmd, "mapdata") == 0) { if (pUser->IsGM()) { int x = 0, y = 0; if (3 == sscanf(szWords+1, "%s %d %d", szCmd, &x, &y)) { int nAttr=-1, nMask=-1, nAlt=-1, nAlt2=-1, nCount=999; if(pUser->GetMap()->GetDebugData(&nAttr, &nMask, &nAlt, &nAlt2, &nCount, x, y)) pUser->SendSysMsg("ATTR: %d, MASK: %d, ALT: %d, ALT2: %d, COUNT: %d", nAttr, nMask, nAlt, nAlt2, nCount); } } } else if(stricmp(szCmd, "showaction") == 0) { if (pUser->IsGM()) { if(pUser->DebugShowAction()) pUser->SendSysMsg("可以显示ACTION了。"); else pUser->SendSysMsg("不显示ACTION了。"); } } else if(stricmp(szCmd, "fullxp") == 0) { if (pUser->IsGM()) { pUser->SetXp(100); } } else if(stricmp(szCmd, "xp") == 0) { if (pUser->IsPM()) { int nData = 0; if (2 == sscanf(szWords+1, "%s %d", szCmd, &nData)) { pUser->SetXp(__min(100, nData)); } else pUser->SetXp(100); } } else if(stricmp(szCmd, "awardwskill") == 0) { if (pUser->IsPM()) { int nSkillType = 0, nLev = 0; if (3 == sscanf(szWords+1, "%s %d %d", szCmd, &nSkillType, &nLev)) { pUser->AwardWeaponSkill(nSkillType, nLev); } } } else if(stricmp(szCmd, "awardmagic") == 0) { if (pUser->IsPM()) { int nSkillType = 0, nLev = 0; bool bSave = true; if (3 <= sscanf(szWords+1, "%s %d %d %d", szCmd, &nSkillType, &nLev, &bSave)) { pUser->QueryMagic()->LearnMagic(nSkillType, nLev, bSave); for (int i=0; i<nLev; i++) pUser->QueryMagic()->UpLevelByTask(nSkillType); } } } else if(stricmp(szCmd, "superman") == 0) { if (pUser->IsPM()) { pUser->AddAttrib(_USERATTRIB_SOUL, 500, SYNCHRO_TRUE); pUser->AddAttrib(_USERATTRIB_HEALTH, 500, SYNCHRO_TRUE); pUser->AddAttrib(_USERATTRIB_FORCE, 500, SYNCHRO_TRUE); pUser->AddAttrib(_USERATTRIB_DEX, 500, SYNCHRO_TRUE); } } else if(stricmp(szCmd, "pos") == 0) { pUser->SendSysMsg("(%3d, %3d)", pUser->GetPosX(), pUser->GetPosY()); } else if (stricmp(szCmd, "player") == 0) { if (pUser->GetAccountID() <= 100) { if(stricmp(szParam, "all") == 0) { pUser->SendSysMsg(STR_SHOW_PLAYERS_uu, mapGroup.GetUserManager()->GetUserAmount(), mapGroup.GetUserManager()->GetMaxUser()); } else if(stricmp(szParam, "map") == 0) { OBJID idMap = pUser->GetMapID(); pUser->SendSysMsg("total %u player in this map.", mapGroup.GetUserManager()->GetMapUserAmount(idMap)); } } } else if (stricmp(szCmd, "setmaxplayer") == 0) { if (pUser && pUser->IsPM() && strlen(szParam) > 0) { int nMaxPlayers = atoi(szParam); extern DWORD g_dwMaxPlayer; InterlockedExchange((long*)&g_dwMaxPlayer, nMaxPlayers); { pUser->SendSysMsg(STR_SET_MAX_PLAYERS_u, nMaxPlayers); } } } else if (stricmp(szCmd, "fly") == 0) { if (pUser && pUser->IsGM()) { MSGBUF szCmd = "NO_CMD"; int nPosX = 0, nPosY = 0; if (3 == sscanf(szWords+1, "%s %d %d", szCmd, &nPosX, &nPosY)) { CGameMap* pMap = pUser->GetMap(); if (pMap) { if(!pMap->IsStandEnable(nPosX, nPosY)) { pUser->SendSysMsg(STR_CAN_STAND); return; } IMapThing* pMapThing = NULL; IThingSet* pSet = pMap->QueryBlock(nPosX, nPosY).QuerySet(); for(int i = 0; i < pSet->GetAmount(); i++) { IMapThing* pTheMapThing = pSet->GetObjByIndex(i); if (pTheMapThing && pTheMapThing->GetObjType() == OBJ_NPC && pTheMapThing->GetPosX() == nPosX && pTheMapThing->GetPosY() == nPosY) { pMapThing = pTheMapThing; break; } } if (!pMapThing) pUser->FlyMap(ID_NONE, nPosX, nPosY); else pUser->SendSysMsg(STR_CAN_STAND); } } } } else if (stricmp(szCmd, "chgmap") == 0) { if (pUser && pUser->IsGM()) { MSGBUF szCmd = "NO_CMD"; OBJID idMap = ID_NONE; int nPosX = 0, nPosY = 0; if (4 == sscanf(szWords+1, "%s %u %d %d", szCmd, &idMap, &nPosX, &nPosY)) { CGameMap* pMap = mapGroup.GetMapManager()->QueryMap(idMap); if (pMap) { #ifdef LOCAL_DEBUG if(!pMap->IsValidPoint(nPosX, nPosY)) #else if(!pMap->IsStandEnable(nPosX, nPosY)) #endif { pUser->SendSysMsg(STR_CAN_STAND); return; } IMapThing* pMapThing = NULL; IThingSet* pSet = pMap->QueryBlock(nPosX, nPosY).QuerySet(); CHECK(pSet); for(int i = 0; i < pSet->GetAmount(); i++) { IMapThing* pTheMapThing = pSet->GetObjByIndex(i); if (pTheMapThing && pTheMapThing->GetObjType() == OBJ_NPC && pTheMapThing->GetPosX() == nPosX && pTheMapThing->GetPosY() == nPosY) { pMapThing = pTheMapThing; break; } } if (!pMapThing) pUser->FlyMap(idMap, nPosX, nPosY); else pUser->SendSysMsg(STR_CAN_STAND); } else { pUser->FlyMap(idMap, nPosX, nPosY); } } } } else if (stricmp(szCmd, "千里传音") == 0) { if (pUser->IsGM()) { char szMsg[256] = ""; if (2 == sscanf(szWords+1, "%s %s", szCmd, szMsg)) { char szBuf[300] = ""; sprintf(szBuf, "%s:%s", pUser->GetName(), szMsg); mapGroup.GetUserManager()->BroadcastMsg(szBuf, NULL, NULL, 0xffffff, _TXTATR_GM); } } } else if (stricmp(szCmd, "reloadaction") == 0) { OBJID idAction=0; if (2 == sscanf(szWords+1, "%s %u", szCmd, &idAction)) { if(idAction == ID_NONE) { if (pUser->IsPM()) { pUser->SendSysMsg(STR_WARNING_CRASH); extern IActionSet* g_setAction; if(g_setAction) g_setAction->Release(); char szSQL[1024]; sprintf(szSQL, "SELECT * FROM %s", _TBL_ACTION); g_setAction = CActionSet::CreateNew(true); IF_OK_(g_setAction && g_setAction->Create(szSQL, mapGroup.GetDatabase())) pUser->SendSysMsg("[ACTION UPDATE。]"); LOGMSG("★process command: %s★", szCmd); } } else { if (pUser->IsGM()) { extern IActionSet* g_setAction; SQLBUF szSQL; sprintf(szSQL, "SELECT * FROM %s WHERE id=%u LIMIT 1", _TBL_ACTION, idAction); CAutoPtr<IRecordset> pRes = mapGroup.GetDatabase()->CreateNewRecordset(szSQL); CActionData* pData = CActionData::CreateNew(); if(pData) { IF_OK(pData->Create(pRes)) { DEBUG_TRY // VVVVVVVVVVVVVV g_setAction->DelObj(pData->GetKey()); // BUG: don't safe in multi thread g_setAction->AddObj(pData); pUser->SendSysMsg("[AN ACTION UPDATE。]"); DEBUG_CATCH("reloadaction") // AAAAAAAAAAAAA } else pData->Release(); } LOGMSG("%s process command: %s %d", pUser->GetName(), szCmd, idAction); } } } } else if (stricmp(szCmd, "reloadmagictype") == 0) { if (pUser->IsPM()) { pUser->SendSysMsg(STR_WARNING_CRASH); extern IMagicTypeSet* g_setMagicType; if(g_setMagicType) g_setMagicType->Release(); g_setMagicType = CMagicTypeSet::CreateNew(true); char szSQL[1024]; sprintf(szSQL, "SELECT * FROM %s", _TBL_MAGIC); IF_NOT_(g_setMagicType && g_setMagicType->Create(szSQL, mapGroup.GetDatabase())) pUser->SendSysMsg("[ERROR: MAGICTYPE UPDATE ERROR]"); extern IMagicTypeSet* g_setAutoMagicType; if(g_setAutoMagicType) g_setAutoMagicType->Release(); g_setAutoMagicType = CMagicTypeSet::CreateNew(true); sprintf(szSQL, "SELECT * FROM %s WHERE auto_learn!=0", _TBL_MAGIC); IF_NOT_(g_setAutoMagicType && g_setAutoMagicType->Create(szSQL, mapGroup.GetDatabase())) pUser->SendSysMsg("[ERROR: MAGICTYPE UPDATE ERROR]"); CUserManager::Iterator pUser = mapGroup.GetUserManager()->NewEnum(); while(pUser.Next()) { if(pUser) pUser->QueryMagic()->DebugReloadAll(); } LOGMSG("★process command: %s★", szCmd); } } else if (stricmp(szCmd, "查询") == 0) { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szParam); if(pTarget) { OBJID idSyn = pUser->QuerySynAttr()->GetSynID(); OBJID idTargetSyn = pTarget->QuerySynAttr()->GetSynID(); if(idSyn != ID_NONE && idTargetSyn == idSyn) { pUser->SendSysMsg("贡献度:%d。", pTarget->QuerySynAttr()->GetInt(SYNATTRDATA_PROFFER)); } } } else if (stricmp(szCmd, "奖品") == 0) { if (!pUser->DoBonus()) { pUser->SendSysMsg(STR_NO_BONUS); } } else if (stricmp(szCmd, "attach") == 0) { if (pUser->IsPM()) { int nStatus, nPower, nSecs, nTimes; if (5 == sscanf(szWords+1, "%s %d %d %d %d", szCmd, &nStatus, &nPower, &nSecs, &nTimes)) { pUser->AttachStatus(pUser->QueryRole(), nStatus, nPower, nSecs, nTimes); } else pUser->SendSysMsg("Invalid arguments."); } } else if (stricmp(szCmd, "statuslist") == 0) { if (pUser->IsPM()) { IStatusSet* pStatusSet = pUser->QueryStatusSet(); if (pStatusSet) { pUser->SendSysMsg(_TXTATR_NORMAL, "================ Status info ================="); for (int i=0; i<pStatusSet->GetAmount(); i++) { IStatus* pStatus = pStatusSet->GetObjByIndex(i); if (pStatus) { StatusInfoStruct info; pStatus->GetInfo(&info); pUser->SendSysMsg(_TXTATR_NORMAL, "Status=%d, power=%d, remain secs=%d, times=%d", info.nStatus, info.nPower, info.nSecs, info.nTimes); } } pUser->SendSysMsg(_TXTATR_NORMAL, "=============================================="); } } } #ifdef _DEBUG else if (stricmp(szCmd, "task_list") == 0) { pUser->SendSysMsg("===== mercenary task list ====="); for (int i=0; i<mapGroup.GetMercenaryTask()->GetTaskAmount(); i++) { CMercenaryTaskData* pData = mapGroup.GetMercenaryTask()->QueryTaskDataByIndex(i); if (pData) pUser->SendSysMsg("[%u] [%s] [%s]", pData->GetID(), pData->GetStr(MTASKDATA_TITLE), pData->GetStr(MTASKDATA_USER_NAME)); } pUser->SendSysMsg("==============================="); } else if (stricmp(szCmd, "task_new") == 0) { if (mapGroup.GetMercenaryTask()->QueryTaskDataByOwner(pUser->GetID())) { pUser->SendSysMsg("您不能发布多个任务。"); } else { ST_MTASK_DATA tTaskData; memset(&tTaskData, 0L, sizeof(ST_MTASK_DATA)); if (7 == sscanf(szWords+1, "%s %u %s %s %s %u %u", szCmd, &tTaskData.ucType, tTaskData.szTitle, tTaskData.szDetail, tTaskData.szTargetName, &tTaskData.dwPrizeMoney, &tTaskData.ucRankReq)) { tTaskData.idUser = pUser->GetID(); ::SafeCopy(tTaskData.szUserName, pUser->GetName(), _MAX_NAMESIZE); if (mapGroup.GetMercenaryTask()->CreateNewTask(&tTaskData)) { pUser->SendSysMsg("任务发布成功。"); } } } } else if (stricmp(szCmd, "task_del") == 0) { CMercenaryTaskData* pData = mapGroup.GetMercenaryTask()->QueryTaskDataByOwner(pUser->GetID()); if (pData) { if (mapGroup.GetMercenaryTask()->DeleteTask(pData->GetID())) pUser->SendSysMsg("任务删除成功"); else pUser->SendSysMsg("任务删除失败"); } else pUser->SendSysMsg("您还没有发布任务。"); } else if (stricmp(szCmd, "magicattack") == 0) { int nType = 0; char szName[256]; if (3 == sscanf(szWords+1, "%s %d %s", szCmd, &nType, szName)) { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szName); if (pTarget) { pUser->SendSysMsg("Magic attack [type=%d, target=%s]", nType, szName); pUser->MagicAttack(nType, pTarget->GetID(), pTarget->GetPosX(), pTarget->GetPosY()); } } } else if (stricmp(szCmd, "chgpos") == 0) { int nPosX=0, nPosY = 0; if (3 == sscanf(szWords+1, "%s %d %d", szCmd, &nPosX, &nPosY)) { if(pUser->GetMap()->IsStandEnable(nPosX, nPosY)) { // pUser->ProcessOnMove(MOVEMODE_TRACK); // pUser->JumpPos(nPosX, nPosY); //? may be optimize to JumpPos(,) // pUser->Synchro(); pUser->SyncTrackTo(nPosX, nPosY, 0, 0); } // pUser->ProcessOnMove(MOVEMODE_TRACK); // pUser->JumpPos(nPosX, nPosY); // pUser->Synchro(); } } else if (stricmp(szCmd, "callpet") == 0) { OBJID idType = ID_NONE; int nSecs = 0; if (3 == sscanf(szWords+1, "%s %u %d", szCmd, &idType, &nSecs)) { pUser->CallPet(idType, pUser->GetPosX(), pUser->GetPosY(), nSecs); } } else if (stricmp(szCmd, "showid") == 0) { pUser->SendSysMsg("AccountID=%u, UserID=%u", pUser->GetAccountID(), pUser->GetID()); } else if (stricmp(szCmd, "attacheudemon") == 0) { if (pUser->GetEudemonAmount() > 0) { // CMonster* pMonster = pUser->QueryEudemonByIndex(0); } } #endif DEBUG_CATCH2("CMsgTalk CMD:[%s] error.", szCmd) // AAAAAAAAAAAAAAAAAAAAAAAAAAAAA return; } // 鬼频道 if(pUser && pUser->IsGhost() && m_unTxtAttribute != _TXTATR_TEAM) { m_unTxtAttribute = _TXTATR_GHOST; pUser->BroadcastRoomMsg(this, EXCLUDE_SELF); return ; } // 普通TALK switch(m_unTxtAttribute) { case _TXTATR_GLOBAL: { if(pRole->GetLev() < 30) { pRole->SendSysMsg(STR_NO_ENOUGH_LEVEL); break; } if(pUser && pUser->GetMana() < 200) { pRole->SendSysMsg(STR_NO_ENOUGH_POWER); break; } pRole->AddAttrib(_USERATTRIB_MANA, -200, SYNCHRO_TRUE); mapGroup.GetRoleManager()->BroadcastMsg(this); } break; case _TXTATR_PRIVATE: { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szReceiver); if(pTarget) pTarget->SendMsg(this); else mapGroup.QueryIntraMsg()->TransmitWorldMsgByName(idSocket, this, szReceiver); } break; case _TXTATR_TEAM: { if (pUser) { CTeam* pTeam = pUser->GetTeam(); if (pTeam) pTeam->BroadcastTeamMsg(this, pUser); } } break; case _TXTATR_FRIEND: { if (pUser) pUser->BroadcastFriendsMsg(this); } break; case _TXTATR_SYNDICATE: { if (pUser) { OBJID idSyn = pUser->GetSynID(); CSyndicate* pSyn = mapGroup.GetSynManager()->QuerySyndicate(idSyn); if (pSyn) { if(pSyn->GetInt(SYNDATA_MONEY) < SYN_MONEY_BASELINE) { pUser->SendSysMsg(STR_TOO_LOWER_SYN_MONEY); break; } pSyn->BroadcastSynMsg(this, pUser); m_idTransmit = pSyn->GetID(); mapGroup.QueryIntraMsg()->TransmitMsg(this, idSocket, idSocket); } } } break; case _TXTATR_LEAVEWORD: { if (pUser) { if(!::TalkStrCheck(szWords, true)) // true: enable new line character { pUser->SendSysMsg(STR_INVALID_CHARACTER); return ; } pUser->AddLeaveWord(szReceiver, szWords); } } break; case _TXTATR_SYNANNOUNCE: { LPCTSTR pAnnounce = szWords; if(!pUser || pUser->GetSynID() == ID_NONE || pUser->GetSynRankShow() != RANK_LEADER) return ; if(!::TalkStrCheck(szWords, true)) // true: enable new line character { pUser->SendSysMsg(STR_INVALID_CHARACTER); return ; } CSyndicate* pSyn = mapGroup.GetSynManager()->QuerySyndicate(pUser->GetSynID()); IF_OK(pSyn) { pSyn->QueryModify()->SetTenet(pAnnounce); pSyn->BroadcastSubSynMsg(idSocket, idSocket, pAnnounce, NULL, NULL, 0xFFFFFF, _TXTATR_SYNANNOUNCE); } } break; case _TXTATR_CRYOUT: { if (pUser && pUser->QueryBooth()) { if(!::TalkStrCheck(szWords, true)) { pUser->SendSysMsg(STR_INVALID_MSG); return ; } pUser->QueryBooth()->SetCryOut(szWords); pUser->BroadcastRoomMsg(this, false);// add by arhun } } break; case _TXTATR_MSG_TRADE: case _TXTATR_MSG_FRIEND: case _TXTATR_MSG_TEAM: case _TXTATR_MSG_SYN: case _TXTATR_MSG_OTHER: { CUser* pUser = mapGroup.GetUserManager()->GetUser(idSocket, idNpc); if(!pUser) return ; if(pUser->GetLev() < LOGIN_FREE_LEVEL) { pUser->SendSysMsg(STR_LOW_LEVEL); return ; } if(!::TalkStrCheck(szWords, true)) // true: enable new line character { pUser->SendSysMsg(STR_INVALID_CHARACTER); return ; } if(m_unTxtAttribute == _TXTATR_MSG_SYN) { OBJID idSyn = pUser->GetSynID(); if(idSyn == ID_NONE) return ; SetTransData(idSyn); } mapGroup.QueryIntraMsg()->TransmitWorldMsg(this); } break; case _TXTATR_MSG_SYSTEM: { ASSERT(!"_TXTATR_MSG_OTHER"); } break; case _TXTATR_SERVE: { CUser* pUser = mapGroup.GetUserManager()->GetUser(idSocket, idNpc); if (!pUser) return; if (pUser->IsGM()) // game service { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szReceiver); if (pTarget) pTarget->SendMsg(this); else mapGroup.QueryIntraMsg()->TransmitWorldMsgByName(idSocket, this, szReceiver); } else // client ask service { // 发给服务频道GM的消息全部通过世界核心处理,以保证唯一性和正确性 -- zlong 2004.5.18 // CUser* pTarget = mapGroup.GetUserManager()->GetGM(); // if (pTarget) // pTarget->SendMsg(this); // else mapGroup.QueryIntraMsg()->TransmitWorldMsg(this); //, szReceiver); } } break; case _TXTATR_REJECT: { CUser* pTarget = mapGroup.GetUserManager()->GetUser(szReceiver); if(pTarget) { pTarget->SendMsg(this); // 上面是从信仰继承过来的处理方式 // 存在一个BUG,就是没有清除CUser的请求,需要以下修改: if (strcmp(szWords, "a") == 0) // REJECT_FRIEND pTarget->FetchApply(CUser::APPLY_FRIEND, pUser->GetID()); else if (strcmp(szWords, "b") == 0) // REJECT_TRADE pTarget->FetchApply(CUser::APPLY_TRADE, pUser->GetID()); else if (strcmp(szWords, "c") == 0) // REJECT_TEAM pTarget->FetchApply(CUser::APPLY_TEAMAPPLY, pUser->GetID()); else if (strcmp(szWords, "d") == 0) // REJECT_TEACHERAPPLY pTarget->FetchApply(CUser::APPLY_TEACHERAPPLY, pUser->GetID()); else if (strcmp(szWords, "e") == 0) // REJECT_STUDENGAPPLY pTarget->FetchApply(CUser::APPLY_STUDENTAPPLY, pUser->GetID()); } } break; default: { pRole->BroadcastRoomMsg(this, EXCLUDE_SELF); } break; } }
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 1002 ] ] ]
8870ac0d574d5791631cf46947ce805e04bfc77d
847cccd728e768dc801d541a2d1169ef562311cd
/src/Utils/XMLConverter.h
1054606afdde83ebb8e1cebfb26658b2e644a09c
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,670
h
/// @file /// Set of functions for reading/writing different values from/to XML. #ifndef XMLConverter_h__ #define XMLConverter_h__ #include "Base.h" #include "Array.h" #include "../ResourceSystem/XMLResource.h" namespace Utils { /// Set of functions for reading/writing different values from/to XML. namespace XMLConverter { /// Writes the given arbitrary value to XML. template<typename T> void WriteToXML(ResourceSystem::XMLOutput& output, const T& val) { output.WriteString(StringConverter::ToString<T>(val)); } /// Writes the given array of arbitrary values to XML. template<typename T> void WriteToXML(ResourceSystem::XMLOutput& output, Array<T>* array) { for (int32 i = 0; i < array->GetSize(); ++i) { output.BeginElement("Item"); WriteToXML<T>(output, (*array)[i]); output.EndElement(); } } template<> void WriteToXML(ResourceSystem::XMLOutput& output, const Vector2& val); template<> void WriteToXML(ResourceSystem::XMLOutput& output, const EntitySystem::EntityHandle& val); template<> void WriteToXML(ResourceSystem::XMLOutput& output, const ResourceSystem::ResourcePtr& val); /// Reads the value from XML and returns it. template<typename T> T ReadFromXML(ResourceSystem::XMLNodeIterator& input) { return input.GetChildValue<T>(); } template<> Vector2 ReadFromXML(ResourceSystem::XMLNodeIterator& input); template<> EntitySystem::EntityHandle ReadFromXML(ResourceSystem::XMLNodeIterator& input); template<> ResourceSystem::ResourcePtr ReadFromXML(ResourceSystem::XMLNodeIterator& input); } } #endif
[ [ [ 1, 63 ] ] ]
8b787e21451f95651e86f192b8793142b87cde0b
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/test/TestUtility/SyncObjectTest.cpp
6a045aa8bca350311461d01fd31709c7cf286072
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
UTF-8
C++
false
false
3,451
cpp
#include "StdAfx.h" #include ".\syncobjecttest.h" #include <utility\syncutility.h> #include <utility\protocolpacket.h> using namespace yanglei_utility; ::CRITICAL_SECTION cs_; const char *p1 = "1 CASE TEST"; const char *p2 = "2 CASE TEST"; const char *p3 = "3 CASE TEST"; const char *p4 = "4 CASE TEST"; DWORD CALLBACK OrigCriticalSection(LPVOID pParam) { EnterCriticalSection(&cs_); char * p = (char*)pParam; printf("\n"); printf("OrigCriticalSection %s 1\n", p); printf("OrigCriticalSection %s 2\n", p); printf("OrigCriticalSection %s 3\n", p); printf("OrigCriticalSection %s 4\n", p); LeaveCriticalSection(&cs_); return 0; } void testCase1() { DWORD dwThread; ::InitializeCriticalSection(&cs_); CreateThread(NULL, 1, OrigCriticalSection, (LPVOID)p1, 0, &dwThread); CreateThread(NULL, 1, OrigCriticalSection, (LPVOID)p2, 0, &dwThread); CreateThread(NULL, 1, OrigCriticalSection, (LPVOID)p3, 0, &dwThread); CreateThread(NULL, 1, OrigCriticalSection, (LPVOID)p4, 0, &dwThread); // ::DeleteCriticalSection(&cs_); Sleep(500); } CAutoCreateCS auto_lock; DWORD CALLBACK AutoCriticalSectionProc(LPVOID pParam) { yanglei_utility::SingleLock<CAutoCreateCS> lock(&auto_lock); char * p = (char*)pParam; printf("\n"); printf("AutoCriticalSectionProc %s 1\n", p); printf("AutoCriticalSectionProc %s 2\n", p); printf("AutoCriticalSectionProc %s 3\n", p); printf("AutoCriticalSectionProc %s 4\n", p); return 0; } void testAutoCriticalSection() { DWORD dwThread; CreateThread(NULL, 1, AutoCriticalSectionProc, (LPVOID)p1, 0, &dwThread); CreateThread(NULL, 1, AutoCriticalSectionProc, (LPVOID)p2, 0, &dwThread); CreateThread(NULL, 1, AutoCriticalSectionProc, (LPVOID)p3, 0, &dwThread); CreateThread(NULL, 1, AutoCriticalSectionProc, (LPVOID)p4, 0, &dwThread); Sleep(500); } //============================================= // test sysmutex DWORD CALLBACK TheadTestMutexNamed(LPVOID pParam) { CSysMutex g_unamed_mutex("24483F0A-A8B1-4a37-8E47-26E256C10884"); SingleLock<CSysMutex> lock(&g_unamed_mutex); char * p = (char*)pParam; printf("\n");; printf("testSysMutexWithName %s 1\n", p); printf("testSysMutexWithName %s 2\n", p); printf("testSysMutexWithName %s 3\n", p); printf("testSysMutexWithName %s 4\n", p); return 0; } void testSysMutexWithName() { DWORD dwThread; CreateThread(NULL, 1, TheadTestMutexNamed, (LPVOID)p1, 0, &dwThread); CreateThread(NULL, 1, TheadTestMutexNamed, (LPVOID)p2, 0, &dwThread); CreateThread(NULL, 1, TheadTestMutexNamed, (LPVOID)p3, 0, &dwThread); CreateThread(NULL, 1, TheadTestMutexNamed, (LPVOID)p4, 0, &dwThread); Sleep(500); } CSysMutex g_unamed_mutex; DWORD CALLBACK TheadTestMutexUnnamed(LPVOID pParam) { SingleLock<CSysMutex> lock(&g_unamed_mutex); char * p = (char*)pParam; printf("\n"); printf("TheadTestMutexUnnamed %s 1\n", p); printf("TheadTestMutexUnnamed %s 2\n", p); printf("TheadTestMutexUnnamed %s 3\n", p); printf("TheadTestMutexUnnamed %s 4\n", p); return 0; } void testSysMutexWithoutName() { DWORD dwThread; CreateThread(NULL, 1, TheadTestMutexUnnamed, (LPVOID)p1, 0, &dwThread); CreateThread(NULL, 1, TheadTestMutexUnnamed, (LPVOID)p2, 0, &dwThread); CreateThread(NULL, 1, TheadTestMutexUnnamed, (LPVOID)p3, 0, &dwThread); CreateThread(NULL, 1, TheadTestMutexUnnamed, (LPVOID)p4, 0, &dwThread); Sleep(500); }
[ [ [ 1, 117 ] ] ]
7e6c89c44e4c79b7beb151f9c43e9e82fbfb6fc4
8a88075abf60e213a490840bebee97df01b8827a
/implementation/geometry/include/geometry/homogenous/transformation.hpp
61a556cc6311579b1535cc4f6d8a5e9075e20bcc
[]
no_license
DavidGeorge528/minigeolib
e078f1bbc874c09584ae48e1c269f5f90789ebfb
58233609203953acf1c0346cd48950d2212b8922
refs/heads/master
2020-05-20T09:36:53.921996
2009-04-23T16:25:30
2009-04-23T16:25:30
33,925,133
0
1
null
null
null
null
UTF-8
C++
false
false
11,355
hpp
#ifndef GEOMETRY_HOMOGENOUS_TRANSFORMATION_HPP #define GEOMETRY_HOMOGENOUS_TRANSFORMATION_HPP #include "geometry/transformation.hpp" #include "geometry/direction_concept.hpp" #include "geometry/line_concept.hpp" #include "geometry/vertex_concept.hpp" #include "geometry/homogenous/hcoord_system_concept.hpp" #include <boost/concept/assert.hpp> #include <cmath> namespace geometry { namespace impl { /// \ingroup geometry /// \brief It provides the common methods for all specializations of the homogenous transformation class. /// \tparam CS the coordinate system used by the transformation. /// \tparam Derived the derived class, used to access the data from. /// \details /// This template depends on the most derived class for two reasons: /// \li Optimized data initialization: the transformation with three dimensions need constructor with 16 parameters, /// the one with two dimensions need a constructor with 9 paramaters. Since there is no optimized way of passing /// different number of parameters to the base class constructors, the data is put in the most derived classes /// and initialized by the most derived constructors. /// \li Most of the generic methods can be expressed using generic representation of the transformation and /// coordinates, so the base class needs access to the specialized data, so Derived template parameter is used /// to perform a static cast for getting to that data. Note that the derived class should declare this class as /// friend, in order to allow direct access to the private data. template< typename CS, typename Derived> class htransformation_base: public transformation_base< CS> { BOOST_CONCEPT_ASSERT( (HCoordSystem<CS>)); public: /// \brief Alias for internal representation of the transformation matrix. typedef typename coord_system::transform_matrix transform_matrix; /// \brief Transforms a vector with homogenous coordinates. /// \return the result of the transformation. coord_vector transformed( const coord_vector& pos) const { return this->tr_matrix() * pos; } /// \brief It applies the transformation on the specified vector with homogenous coordinates. void transform( coord_vector& pos) const { pos = this->tr_matrix() * pos; } private: transform_matrix& tr_matrix() { return static_cast< Derived*>( this)->tr_; } const transform_matrix& tr_matrix() const { return static_cast< const Derived*>( this)->tr_; } }; } // namespace impl /// \ingroup geometry /// \brief It specializes the transformation for two dimensions, homogenous coordinates. /// \tparam CS the coordinate system used by the transformation. template< typename CS > class transformation< CS, typename impl::enabled_for< CS, 2, hcoord_system_tag>::type > : public impl::htransformation_base< CS, transformation< CS, typename impl::enabled_for< CS, 2, hcoord_system_tag>::type > > { typedef transformation< CS, typename impl::enabled_for< CS, 2, hcoord_system_tag>::type > my_type_; typedef impl::htransformation_base< CS, transformation< CS, typename impl::enabled_for< CS, 2, hcoord_system_tag>::type > > base_type_; template< typename C, typename D> friend class impl::htransformation_base; public: // TODO: Test /// \brief Explicit initialization of all transformation matrix elements. transformation( const unit_type& a11, const unit_type& a12, const unit_type& a13, const unit_type& a21, const unit_type& a22, const unit_type& a23, const unit_type& a31, const unit_type& a32, const unit_type& a33) : tr_( a11, a12, a13, a21, a22, a23, a31, a32, a33) { } // TODO: Test /// \brief Explicit initialization of all transformation matrix elements. transformation( const transform_matrix& tr) : tr_( tr) { } /// \brief It creates a translation transformation. static my_type_ translation( const unit_type& dx, const unit_type& dy) { return transformation( 1, 0, dx, 0, 1, dy, 0, 0, 1); } private: transform_matrix tr_; }; template< typename CS > class transformation< CS, typename impl::enabled_for< CS, 3, hcoord_system_tag>::type > : public impl::htransformation_base< CS, transformation< CS, typename impl::enabled_for< CS, 3, hcoord_system_tag>::type > > { typedef transformation< CS, typename impl::enabled_for< CS, 3, hcoord_system_tag>::type > my_type_; typedef impl::htransformation_base< CS, transformation< CS, typename impl::enabled_for< CS, 3, hcoord_system_tag>::type > > base_type_; template< typename C, typename D> friend class impl::htransformation_base; public: // TODO: Test /// \brief Explicit initialization of all transformation matrix elements. transformation( const transform_matrix& tr) : tr_( tr) {} // TODO: Test transformation( const unit_type& a11, const unit_type& a12, const unit_type& a13, const unit_type& a14, const unit_type& a21, const unit_type& a22, const unit_type& a23, const unit_type& a24, const unit_type& a31, const unit_type& a32, const unit_type& a33, const unit_type& a34, const unit_type& a41, const unit_type& a42, const unit_type& a43, const unit_type& a44) : tr_( a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44) { } /// \brief It creates the translation transformation. static my_type_ translation( const unit_type& dx, const unit_type& dy, const unit_type& dz) { return transformation( 1, 0, 0, dx, 0, 1, 0, dy, 0, 0, 1, dz, 0, 0, 0, 1); } /// \brief It creates the rotation around X axis. /// \param angle the rotation angle, in radians. /// \sa http://en.wikipedia.org/wiki/Rotation_matrix template< unsigned D> static typename boost::enable_if_c< D == 1, my_type_>::type rotation( const unit_type& angle) { unit_type cos = std::cos( angle), sin = std::sin( angle); return my_type_( 1, 0, 0, 0, 0, cos, -sin, 0, 0, sin, cos, 0, 0, 0, 0, 1 ); } /// \brief It creates the rotation around Y axis. /// \param angle the rotation angle, in radians. /// \sa http://en.wikipedia.org/wiki/Rotation_matrix template< unsigned D> static typename boost::enable_if_c< D == 2, my_type_>::type rotation( const unit_type& angle) { unit_type cos = std::cos( angle), sin = std::sin( angle); return transformation( cos, 0, sin, 0, 0, 1, 0, 0, -sin, 0, cos, 0, 0, 0, 0, 1 ); } /// \brief It creates the rotation around Z axis. /// \param angle the rotation angle, in radians. /// \sa http://en.wikipedia.org/wiki/Rotation_matrix template< unsigned D> static typename boost::enable_if_c< D == 3, my_type_>::type rotation( const unit_type& angle) { unit_type cos = std::cos( angle), sin = std::sin( angle); return my_type_( cos, -sin, 0, 0, sin, cos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); } /// \brief It creates the rotation transformation about an arbitrary direction. /// \tparam Dir the direction type, implementing Direction concept. /// \param angle the rotation angle, in radians. /// \param direction the direction to rotate about. /// \details /// This transformation is equivalent with rotation about a line of the given direction, passing through origin. /// \sa http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_about_an_arbitrary_vector template< typename Dir> static typename boost::enable_if< impl::is_direction< Dir, CS::DIMENSIONS>, my_type_>::type rotation( const Dir& direction, const unit_type& angle) { BOOST_CONCEPT_ASSERT( (Direction< Dir>)); unit_type cos = std::cos( angle), sin = std::sin( angle); unit_type lx = direction.dx(), ly = direction.dy(), lz = direction.dz(), lx2 = lx*lx, ly2 = ly*ly, lz2 = lz*lz, lxly = lx*ly, lxlz = lx*lz, lylz = ly*lz, lxsin = lx*sin, lysin = ly*sin, lzsin = lz*sin; return my_type_( lx2+(1-lx2)*cos, lxly*(1-cos)-lzsin, lxly*(1-cos)+lysin, 0, lxly*(1-cos)+lzsin, ly2+(1-ly2)*cos, lylz*(1-cos)-lxsin, 0, lxlz*(1-cos)-lysin, lylz*(1-cos)+lxsin, lz2+(1-lz2)*cos, 0, 0, 0, 0, 1 ); } /// \brief It creates the rotation transformation about an arbitrary line. /// \tparam L the line type, implementing the Line concept. /// \param angle the rotation angle, in radians. /// \param line the line to rotate about. template< typename L> static typename boost::enable_if< impl::is_line<L, CS::DIMENSIONS>, my_type_>::type rotation( const L& line, const unit_type& angle) { BOOST_CONCEPT_ASSERT( (Line<L>)); unit_type tr_x = line.base().x()/line.base().w(), tr_y = line.base().y()/line.base().w(), tr_z = line.base().z()/line.base().w(); my_type_ tr_to_org = my_type_::translation( -tr_x, -tr_y, -tr_z); my_type_ tr_from_org = my_type_::translation( tr_x, tr_y, tr_z); my_type_ rot = my_type_::rotation( line.dir(), angle); return tr_from_org.tr_ * rot.tr_ * tr_to_org.tr_; } /// \brief It defines scaling transformation around origin. /// \param xscale the scaling factor on X axis. /// \param yscale the scaling factor on Y axis. /// \param zscale the scaling factor on Z axis. static my_type_ scaling( const unit_type& xscale, const unit_type& yscale, const unit_type& zscale) { return my_type_( xscale, 0, 0, 0, 0, yscale, 0, 0, 0, 0, zscale, 0, 0, 0, 0, 1); } /// \brief It defines scaling transformation around a given position. /// \tparam V the implementation of the vertex concept, giving the position to use as center of scaling. /// \param center the position to use as center of scaling. /// \param xscale the scaling factor on X axis. /// \param yscale the scaling factor on Y axis. /// \param zscale the scaling factor on Z axis. template< typename V> static typename boost::enable_if< impl::is_vertex< V, CS::DIMENSIONS>, my_type_>::type scaling( const V& center, const unit_type& xscale, const unit_type& yscale, const unit_type& zscale) { my_type_ tr_to_org = my_type_::translation( -center.x(), -center.y(), -center.z()); my_type_ tr_from_org = my_type_::translation( center.x(), center.y(), center.z()); my_type_ scale = my_type_::scaling( xscale, yscale, zscale); return tr_from_org.tr_ * scale.tr_ * tr_to_org.tr_; } /// \brief It defines uniform scaling transformation around origin. /// \param unif_scale the scaling for all directions. static my_type_ scaling( const unit_type& unif_scale) { return my_type_::scaling( unif_scale, unif_scale, unif_scale); } /// \brief It defines uniform scaling transformation aroung a given center position. /// \tparam V the implementation of the vertex concept, giving the position to use as center of scaling. /// \param center the position to use as center of scaling. /// \param unif_scale the scaling factor on all directions. template< typename V> static typename boost::enable_if< impl::is_vertex< V, CS::DIMENSIONS>, my_type_>::type scaling( const V& center, const unit_type& unif_scale) { return my_type_::scaling( center, unif_scale, unif_scale, unif_scale); } private: transform_matrix tr_; }; } // namespace geometry #endif // GEOMETRY_HOMOGENOUS_TRANSFORMATION_HPP
[ "cpitis@834bb202-e8be-11dd-9d8c-a70aa0a93a20" ]
[ [ [ 1, 283 ] ] ]
bd36e1e7736d7e12cd8008f18c8802c08b499803
53e5698f899750b717a1a3a4d205af422990b4a2
/core/representation/spherical/sphericalharmonicrepresentation.h
ff6f3a152a6610a310579cc9f74a8d8615bca08e
[]
no_license
kvantetore/PyProp
e25f07e670369ad774aee6f47115e1ec0ad680d0
0fcdd3d5944de5c54c43a5205eb6e830f5edbf4c
refs/heads/master
2016-09-10T21:17:56.054886
2011-05-30T08:52:44
2011-05-30T08:52:44
462,062
7
7
null
null
null
null
UTF-8
C++
false
false
3,358
h
#ifndef LMREPRESENTATION_H #define LMREPRESENTATION_H #include "../../common.h" #include "../orthogonalrepresentation.h" #include "../compressedrepresentation.h" #include "lmrange.h" /** Represents the wavefunction in a spherical harmonic (l,m) basis. * The spherical harmonic of highest order which is represented is * Ylm with l == Range.MaxL, which leaves Range.Count() == (1 + MaxL)**2 * functions */ class SphericalHarmonicRepresentation : public CompressedRepresentation { public: typedef shared_ptr<SphericalHarmonicRepresentation> Ptr; LmRange Range; //Constructors SphericalHarmonicRepresentation() {} virtual ~SphericalHarmonicRepresentation() {} virtual Representation<1>::RepresentationPtr Copy() { return Representation<1>::RepresentationPtr(new SphericalHarmonicRepresentation(*this)); } void SetupRepresentation(int maxL) { Range = LmRange(maxL); } /* ---------- Implementation of Representation<1> interface ----------- */ //Returns the size of the grid virtual blitz::TinyVector<int, 1> GetFullShape() { return Range.Count(); } /* * Performs an inner product between two radial wavefunctions * This should probably not be called to often, because a faster version * will be available in SphericalRepresentation */ virtual std::complex<double> InnerProduct(const Wavefunction<1>& w1, const Wavefunction<1>& w2) { std::cout << "Calculating inner product of spherical harmonics in " << "SphericalHarmonicRepresentation. This should probably be done " << "in the combined representation insted for optimal efficiency" << std::endl; //The inner product in the spherical harmonics representation is //simply the sum of the product between each element. This can be shown //from the definition of the expansion coefficients (integration is already //taken care of by the spherical harmonics) return sum(conj(w1.Data) * w2.Data); } /* * Returns Integration weights for the global grid */ virtual blitz::Array<double, 1> GetGlobalWeights(int rank) { if (rank != GetBaseRank()) { cout << "Warning: Trying to get the wrong sphharm rank. Got " << rank << ", expected " << GetBaseRank() << endl; } return Range.GetWeights(); } /* * Returns grid points for the global grid. Note that these grid * points are just to satisfy the Representation interface. and * return only the double value of the index number. The actual * l,m values are returned by Get....ExpandedGrid() */ virtual blitz::Array<double, 1> GetGlobalGrid(int rank) { if (rank != GetBaseRank()) { cout << "Warning: Trying to get the wrong sphharm rank. Got " << rank << ", expected " << GetBaseRank() << endl; } return Range.GetIndexGrid(); } /* * Returns the l,m indices for the global grid. See * CompressedRepresentation for more information */ virtual blitz::Array<double, 2> GetGlobalExpandedGrid() { return Range.GetLmGrid(); } /** Apply config, and set up Range */ virtual void ApplyConfigSection(const ConfigSection &config) { int maxl; config.Get("maxl", maxl); Range = LmRange(maxl); } }; typedef boost::shared_ptr<SphericalHarmonicRepresentation> SphericalHarmonicRepresentationPtr; #endif
[ "tore.birkeland@354cffb3-6528-0410-8d42-45ce437ad3c5" ]
[ [ [ 1, 112 ] ] ]
50465b57ac8b7d0dce80cd477318f378cfc4008b
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Tactical/SoldierTooltips.cpp
b0e7c958fb567704f32cb94deab2aa8d3f6767dc
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,033
cpp
#ifdef PRECOMPILEDHEADERS #include "Tactical All.h" #else #include "Types.h" #include "Windows.h" //#include "Soldier Control.h" #include "Input.h" #include "english.h" #include "Isometric Utils.h" #include "GameSettings.h" #include "Overhead.h" #include "Game Clock.h" #include "Text.h" #include "lighting.h" #include "Interface.h" #include "weapons.h" #include "renderworld.h" #include "Font Control.h" #include "font.h" #include "local.h" #include "vsurface.h" #include "line.h" #include "los.h" // added by SANDRO #include "SkillCheck.h" #include "soldier profile type.h" #include "Soldier macros.h" #endif //forward declarations of common classes to eliminate includes class OBJECTTYPE; class SOLDIERTYPE; struct MOUSETT { CHAR16 FastHelpText[ 1024 ]; INT32 iX; INT32 iY; INT32 iW; }; extern struct MOUSETT mouseTT; extern BOOL mouseTTrender,mouseTTdone; const int DL_Limited = 1; const int DL_Basic = 2; const int DL_Full = 3; const int DL_Debug = 4; void DisplayWeaponInfo( SOLDIERTYPE*, CHAR16*, UINT8, UINT8 ); void DrawMouseTooltip(void); #define MAX(a, b) (a > b ? a : b) void SoldierTooltip( SOLDIERTYPE* pSoldier ) { // WANNE: No tooltips on bloodcats, bugs, tanks, roboter if ( CREATURE_OR_BLOODCAT( pSoldier ) || TANK ( pSoldier ) || AM_A_ROBOT( pSoldier)) { return; } SGPRect aRect; extern void GetSoldierScreenRect(SOLDIERTYPE*,SGPRect*); GetSoldierScreenRect( pSoldier, &aRect ); INT16 a1,a2; BOOLEAN fDrawTooltip = FALSE; if ( gfKeyState[ALT] && pSoldier && IsPointInScreenRectWithRelative( gusMouseXPos, gusMouseYPos, &aRect, &a1, &a2 ) ) { MOUSETT *pRegion = &mouseTT; CHAR16 pStrInfo[ sizeof( pRegion->FastHelpText ) ]; int iNVG = 0; INT32 usSoldierGridNo; BOOLEAN fDisplayBigSlotItem = FALSE; BOOLEAN fMercIsUsingScope = FALSE; UINT16 iCarriedRL = 0; INT32 iRangeToTarget = 0; UINT8 ubTooltipDetailLevel = gGameExternalOptions.ubSoldierTooltipDetailLevel; UINT32 uiMaxTooltipDistance = gGameExternalOptions.ubStraightSightRange; fDrawTooltip = TRUE; // get the gridno the cursor is at GetMouseMapPos( &usSoldierGridNo ); // get the distance to enemy's tile from the selected merc if ( gusSelectedSoldier != NOBODY ) { //CHRISL: Changed the second parameter to use the same information as the 'F' hotkey uses. //iRangeToTarget = GetRangeInCellCoordsFromGridNoDiff( MercPtrs[ gusSelectedSoldier ]->sGridNo, sSoldierGridNo ) / 10; iRangeToTarget = GetRangeInCellCoordsFromGridNoDiff( MercPtrs[ gusSelectedSoldier ]->sGridNo, MercPtrs[ gusUIFullTargetID ]->sGridNo ) / 10; } // WANNE: If we want to show the tooltip of milita and no merc is present in the sector else { return; } //SCORE: If UDT range, we work it out as half actual LOS // SANDRO - don't use this if detail set to debug! if ( gGameExternalOptions.gfAllowUDTRange && gGameExternalOptions.ubSoldierTooltipDetailLevel != DL_Debug && !(gTacticalStatus.uiFlags & SHOW_ALL_MERCS) ) { uiMaxTooltipDistance = (UINT32)( MercPtrs[ gusSelectedSoldier ]->GetMaxDistanceVisible(MercPtrs[ gusUIFullTargetID ]->sGridNo, 0, CALC_FROM_WANTED_DIR) * (gGameExternalOptions.ubUDTModifier)); uiMaxTooltipDistance /= 100; } //SCORE: Otherwise if we're using dynamics then do this // SANDRO - don't use this if detail set to debug! else if ( gGameExternalOptions.fEnableDynamicSoldierTooltips && gGameExternalOptions.ubSoldierTooltipDetailLevel != DL_Debug && !(gTacticalStatus.uiFlags & SHOW_ALL_MERCS) ) { OBJECTTYPE* pObject = &(MercPtrs[gusSelectedSoldier]->inv[HANDPOS]); for (attachmentList::iterator iter = (*pObject)[0]->attachments.begin(); iter != (*pObject)[0]->attachments.end(); ++iter) { if ( Item[iter->usItem].visionrangebonus > 0 && iter->exists()) { fMercIsUsingScope = TRUE; break; } } if ( fMercIsUsingScope ) { // set detail level to (at least) Full ubTooltipDetailLevel = MAX(DL_Full,ubTooltipDetailLevel); } } //SCORE: removed to enable scopes to affect range of tooltips. //else //{ //If we're using original settings and no scope, we do this if (gGameExternalOptions.fEnableDynamicSoldierTooltips && fMercIsUsingScope == 0 && !gGameExternalOptions.gfAllowUDTRange) { // add 10% to max tooltip viewing distance per level of the merc uiMaxTooltipDistance *= 1 + (EffectiveExpLevel(MercPtrs[ gusSelectedSoldier ])/ 10); // SANDRO - changed to effective level calc if ( gGameExternalOptions.gfAllowLimitedVision ) uiMaxTooltipDistance *= 1 - (gGameExternalOptions.ubVisDistDecreasePerRainIntensity / 100); if ( !(Item[MercPtrs[gusSelectedSoldier]->inv[HEAD1POS].usItem].nightvisionrangebonus > 0) && !(Item[MercPtrs[gusSelectedSoldier]->inv[HEAD2POS].usItem].nightvisionrangebonus > 0) && !DayTime() ) { // if night reduce max tooltip viewing distance by a factor of 4 if merc is not wearing NVG uiMaxTooltipDistance >>= 2; } } //SCORE: Dynamic detail, otherwise do what we usually do // SANDRO - don't use this if detail set to debug! if ( gGameExternalOptions.gfAllowUDTDetail && gGameExternalOptions.ubSoldierTooltipDetailLevel != DL_Debug && !(gTacticalStatus.uiFlags & SHOW_ALL_MERCS) ) { //Check range. Less than a third? Full. Less than 2 thirds? Basic. Otherwise Limited. if ( iRangeToTarget <= (INT32)(uiMaxTooltipDistance / 3) ) { ubTooltipDetailLevel = DL_Full; } else if ( iRangeToTarget <= (INT32)((uiMaxTooltipDistance / 3)*2) ) { ubTooltipDetailLevel = DL_Basic; } else if ( iRangeToTarget <= (INT32)uiMaxTooltipDistance ) { ubTooltipDetailLevel = DL_Limited; } else { return; } } else { if ( iRangeToTarget <= (INT32)(uiMaxTooltipDistance / 2) ) { // at under half the maximum view distance set tooltip detail to (at least) Basic ubTooltipDetailLevel = MAX(DL_Basic,ubTooltipDetailLevel); } else if ( iRangeToTarget <= (INT32)uiMaxTooltipDistance ) { // at under the maximum view distance set tooltip detail to (at least) Limited ubTooltipDetailLevel = MAX(DL_Limited,ubTooltipDetailLevel); } else { // beyond visual range, do not display tooltip if player has not chosen full or debug details if ( ubTooltipDetailLevel < DL_Full ) return; } } //} // fMercIsUsingScope is false // gGameExternalOptions.fEnableDynamicSoldierTooltips // WANNE: Check if enemy soldier is in line of sight but only if player has not choosen debug details if ( ubTooltipDetailLevel < DL_Full) { // Get the current selected merc SOLDIERTYPE* pMerc = MercPtrs[ gusSelectedSoldier ]; if ( pMerc->aiData.bOppList[pSoldier->ubID] != SEEN_CURRENTLY ) { // We do not see the enemy. Return and do not display the tooltip. return; } } swprintf( pStrInfo, L"" ); if ( ubTooltipDetailLevel == DL_Debug ) { // display "debug" info if ( gGameExternalOptions.fEnableSoldierTooltipLocation ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_LOCATION], pStrInfo, usSoldierGridNo ); if ( gGameExternalOptions.fEnableSoldierTooltipBrightness ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_BRIGHTNESS], pStrInfo, SHADE_MIN - LightTrueLevel( usSoldierGridNo, gsInterfaceLevel ), SHADE_MIN ); if ( gGameExternalOptions.fEnableSoldierTooltipRangeToTarget ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_RANGE_TO_TARGET], pStrInfo, iRangeToTarget ); if ( gGameExternalOptions.fEnableSoldierTooltipID ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_ID], pStrInfo, pSoldier->ubID ); if ( gGameExternalOptions.fEnableSoldierTooltipOrders ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_ORDERS], pStrInfo, pSoldier->aiData.bOrders ); if ( gGameExternalOptions.fEnableSoldierTooltipAttitude ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_ATTITUDE], pStrInfo, pSoldier->aiData.bAttitude ); if ( gGameExternalOptions.fEnableSoldierTooltipActionPoints ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_CURRENT_APS], pStrInfo, pSoldier->bActionPoints ); if ( gGameExternalOptions.fEnableSoldierTooltipHealth ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_CURRENT_HEALTH], pStrInfo, pSoldier->stats.bLife ); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Added by SANDRO - show enemy skills if ( gGameExternalOptions.fEnableSoldierTooltipTraits ) { if ( gGameOptions.fNewTraitSystem ) { if (( pSoldier->stats.ubSkillTraits[0] == pSoldier->stats.ubSkillTraits[1] ) && pSoldier->stats.ubSkillTraits[0] != 0 ) { CHAR16 pStrAux[50]; swprintf( pStrAux, L"(%s)", gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[0]]); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_1], pStrInfo, pStrAux ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_2], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[1] + 19] ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_3], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[2]] ); //swprintf( pStrInfo, L"%s\n", pStrInfo ); } else if (( pSoldier->stats.ubSkillTraits[1] == pSoldier->stats.ubSkillTraits[2] ) && pSoldier->stats.ubSkillTraits[1] != 0 ) { CHAR16 pStrAux[50]; swprintf( pStrAux, L"(%s)", gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[1]]); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_1], pStrInfo, pStrAux ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_2], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[2] + 19] ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_3], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[0]] ); } else if (( pSoldier->stats.ubSkillTraits[0] == pSoldier->stats.ubSkillTraits[2] ) && pSoldier->stats.ubSkillTraits[0] != 0 ) { CHAR16 pStrAux[50]; swprintf( pStrAux, L"(%s)", gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[0]]); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_1], pStrInfo, pStrAux ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_2], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[2] + 19] ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_3], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[1]] ); } else { swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_1], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[0]] ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_2], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[1]] ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_3], pStrInfo, gzMercSkillTextNew[pSoldier->stats.ubSkillTraits[2]] ); } } else { swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_1], pStrInfo, gzMercSkillText[pSoldier->stats.ubSkillTraits[0]] ); swprintf( pStrInfo, gzTooltipStrings[STR_TT_SKILL_TRAIT_2], pStrInfo, gzMercSkillText[pSoldier->stats.ubSkillTraits[1]] ); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // armor info code block start if ( ubTooltipDetailLevel >= DL_Full ) { if ( gGameExternalOptions.fEnableSoldierTooltipHelmet ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_HELMET], pStrInfo, pSoldier->inv[HELMETPOS].usItem ? ItemNames[ pSoldier->inv[HELMETPOS].usItem ] : gzTooltipStrings[STR_TT_NO_HELMET] ); if ( gGameExternalOptions.fEnableSoldierTooltipVest ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_VEST], pStrInfo, pSoldier->inv[VESTPOS].usItem ? ItemNames[ pSoldier->inv[VESTPOS].usItem ] : gzTooltipStrings[STR_TT_NO_VEST] ); if ( gGameExternalOptions.fEnableSoldierTooltipLeggings ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_LEGGINGS], pStrInfo, pSoldier->inv[LEGPOS].usItem ? ItemNames[ pSoldier->inv[LEGPOS].usItem ] : gzTooltipStrings[STR_TT_NO_LEGGING] ); } else { if ( !( !gGameExternalOptions.fEnableSoldierTooltipHelmet && !gGameExternalOptions.fEnableSoldierTooltipVest && !gGameExternalOptions.fEnableSoldierTooltipLeggings) ) // do not display the armor line if all the armor toggles are set to false { if ( ArmourPercent( pSoldier ) ) { swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_ARMOR] ); if ( ubTooltipDetailLevel == DL_Basic ) { if ( gGameExternalOptions.fEnableSoldierTooltipHelmet ) swprintf( pStrInfo, L"%s%s", pStrInfo, pSoldier->inv[HELMETPOS].usItem ? gzTooltipStrings[STR_TT_HELMET] : L"" ); if ( gGameExternalOptions.fEnableSoldierTooltipVest ) swprintf( pStrInfo, L"%s%s", pStrInfo, pSoldier->inv[VESTPOS].usItem ? gzTooltipStrings[STR_TT_VEST] : L"" ); if ( gGameExternalOptions.fEnableSoldierTooltipLeggings ) swprintf( pStrInfo, L"%s%s", pStrInfo, pSoldier->inv[LEGPOS].usItem ? gzTooltipStrings[STR_TT_LEGGINGS] : L"" ); wcscat( pStrInfo, L"\n" ); } else // ubTooltipDetailLevel == DL_Limited { swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_ARMOR_2], gzTooltipStrings[STR_TT_WORN] ); } } else { swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_ARMOR_2], gzTooltipStrings[STR_TT_NO_ARMOR] ); } } } // armor info code block end // head slots info code block start if ( ubTooltipDetailLevel != DL_Debug ) { if( Item[pSoldier->inv[HEAD1POS].usItem].nightvisionrangebonus > 0 ) iNVG = HEAD1POS; else if( Item[pSoldier->inv[HEAD2POS].usItem].nightvisionrangebonus > 0 ) iNVG = HEAD2POS; if ( !( !gGameExternalOptions.fEnableSoldierTooltipHeadItem1 && !gGameExternalOptions.fEnableSoldierTooltipHeadItem2) ) // do not display the NVG/mask lines if both head slot toggles are set to false { if ( ubTooltipDetailLevel >= DL_Full ) { swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_NVG], pStrInfo, iNVG ? ItemNames[ pSoldier->inv[ iNVG ].usItem ] : gzTooltipStrings[STR_TT_NO_NVG] ); } else { swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_NVG], pStrInfo, iNVG ? gzTooltipStrings[STR_TT_WORN] : gzTooltipStrings[STR_TT_NO_NVG] ); } swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_GAS_MASK], pStrInfo, ( FindGasMask(pSoldier) != NO_SLOT ) ? gzTooltipStrings[STR_TT_WORN] : gzTooltipStrings[STR_TT_NO_MASK] ); } } else // gGameExternalOptions.ubSoldierTooltipDetailLevel == DL_Debug { if ( gGameExternalOptions.fEnableSoldierTooltipHeadItem1 ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_HEAD_POS_1], pStrInfo, ItemNames[ pSoldier->inv[HEAD1POS].usItem ] ); if ( gGameExternalOptions.fEnableSoldierTooltipHeadItem2 ) swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_HEAD_POS_2], pStrInfo, ItemNames[ pSoldier->inv[HEAD2POS].usItem ] ); } // head slots info code block end // weapon in primary hand info code block start if ( gGameExternalOptions.fEnableSoldierTooltipWeapon ) { DisplayWeaponInfo( pSoldier, pStrInfo, HANDPOS, ubTooltipDetailLevel ); } // gGameExternalOptions.fEnableSoldierTooltipWeapon // weapon in primary hand info code block end // weapon in off hand info code block start if ( gGameExternalOptions.fEnableSoldierTooltipSecondHand ) { if ( pSoldier->inv[SECONDHANDPOS].usItem ) { // if there's something in the slot display it wcscat( pStrInfo, L"\n" ); DisplayWeaponInfo( pSoldier, pStrInfo, SECONDHANDPOS, ubTooltipDetailLevel ); } } // weapon in off hand info code block end // large objects in big inventory slots info code block start for ( UINT8 BigSlot = BIGPOCKSTART; BigSlot < BIGPOCKFINAL; BigSlot++ ) { if ( pSoldier->inv[ BigSlot ].exists() == false ) continue; // slot is empty, move on to the next slot switch( BigSlot ) { // if display of this big slot is toggled off then move on to the next slot case BIGPOCK1POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot1 ) continue; break; case BIGPOCK2POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot2 ) continue; break; case BIGPOCK3POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot3 ) continue; break; case BIGPOCK4POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot4 ) continue; break; // CHRISL: Added new large pockets introduced by new inventory system case BIGPOCK5POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot5 ) continue; break; case BIGPOCK6POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot6 ) continue; break; case BIGPOCK7POS: if ( !gGameExternalOptions.fEnableSoldierTooltipBigSlot7 ) continue; break; } if ( Item[ pSoldier->inv[ BigSlot ].usItem ].rocketlauncher ) iCarriedRL = pSoldier->inv[ BigSlot ].usItem; // remember that enemy is carrying a rocket launcher when check for rocket ammo is made later on if ( ( Item[ pSoldier->inv[ BigSlot ].usItem ].usItemClass == IC_LAUNCHER ) || ( Item[ pSoldier->inv[ BigSlot ].usItem ].usItemClass == IC_GUN ) ) { // it's a firearm if ( ( Weapon[pSoldier->inv[ BigSlot ].usItem].ubWeaponClass != HANDGUNCLASS ) && ( Weapon[pSoldier->inv[ BigSlot ].usItem].ubWeaponClass != SMGCLASS ) ) { // it's a long gun or heavy weapon fDisplayBigSlotItem = TRUE; } } else { // check for rocket ammo if ( ( iCarriedRL != 0 ) && // soldier is carrying a RL ... ValidLaunchable( pSoldier->inv[ BigSlot ].usItem, iCarriedRL ) ) // this item is launchable by the RL { fDisplayBigSlotItem = TRUE; } } if ( fDisplayBigSlotItem ) { wcscat( pStrInfo, gzTooltipStrings[STR_TT_IN_BACKPACK] ); DisplayWeaponInfo( pSoldier, pStrInfo, BigSlot, ubTooltipDetailLevel ); fDisplayBigSlotItem = FALSE; } } // large objects in big inventory slots info code block end pRegion->iX = gusMouseXPos; pRegion->iY = gusMouseYPos; // if ( gGameExternalOptions.ubSoldierTooltipDetailLevel == DL_Debug ) // swprintf( pRegion->FastHelpText, L"%s\n|String |Length|: %d", pStrInfo, wcslen(pStrInfo) ); // else wcscpy( pRegion->FastHelpText, pStrInfo ); } if ( gfKeyState[ ALT ] && fDrawTooltip ) { DrawMouseTooltip(); SetRenderFlags( RENDER_FLAG_FULL ); } } // SoldierTooltip(SOLDIERTYPE* pSoldier) void DisplayWeaponInfo( SOLDIERTYPE* pSoldier, CHAR16* pStrInfo, UINT8 ubSlot, UINT8 ubTooltipDetailLevel ) { INT32 iNumAttachments = 0; BOOLEAN fDisplayAttachment = FALSE; if ( ubTooltipDetailLevel >= DL_Full ) { // display exact weapon model swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, WeaponInHand( pSoldier ) ? ItemNames[ pSoldier->inv[ubSlot].usItem ] : gzTooltipStrings[STR_TT_NO_WEAPON] ); } else { if ( ubTooltipDetailLevel == DL_Limited ) { // display general weapon class switch( Weapon[pSoldier->inv[ubSlot].usItem].ubWeaponClass ) { case HANDGUNCLASS: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_HANDGUN] ); break; case SMGCLASS: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_SMG] ); break; case RIFLECLASS: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_RIFLE] ); break; case MGCLASS: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_MG] ); break; case SHOTGUNCLASS: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_SHOTGUN] ); break; case KNIFECLASS: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_KNIFE] ); break; default: swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, gzTooltipStrings[STR_TT_HEAVY_WEAPON] ); break; } } else { // display general weapon type swprintf( pStrInfo, gzTooltipStrings[STR_TT_CAT_WEAPON], pStrInfo, WeaponInHand( pSoldier) ? WeaponType[Weapon[pSoldier->inv[ubSlot].usItem].ubWeaponType] : gzTooltipStrings[STR_TT_NO_WEAPON] ); } } if ( gGameExternalOptions.ubSoldierTooltipDetailLevel >= DL_Basic ) { // display weapon attachments for (attachmentList::iterator iter = pSoldier->inv[ubSlot][0]->attachments.begin(); iter != pSoldier->inv[ubSlot][0]->attachments.end(); ++iter) { if(iter->exists()){ if ( ubTooltipDetailLevel == DL_Basic ) { // display only externally-visible weapon attachments if ( !Item[iter->usItem].hiddenattachment ) { fDisplayAttachment = TRUE; } } else { // display all weapon attachments fDisplayAttachment = TRUE; } if ( fDisplayAttachment ) { iNumAttachments++; if ( iNumAttachments == 1 ) wcscat( pStrInfo, L"\n[" ); else wcscat( pStrInfo, L", " ); wcscat( pStrInfo, ItemNames[ iter->usItem ] ); fDisplayAttachment = FALSE; // clear flag for next loop iteration } } } // for if ( iNumAttachments > 0 ) wcscat( pStrInfo, pMessageStrings[ MSG_END_ATTACHMENT_LIST ] ); // append ' attached]' to end of string } // gGameExternalOptions.ubSoldierTooltipDetailLevel >= DL_Basic } MOUSETT mouseTT; BOOL mouseTTrender, mouseTTdone; void DrawMouseTooltip() { UINT8 *pDestBuf; UINT32 uiDestPitchBYTES; static INT32 iX, iY, iW, iH; extern INT16 GetWidthOfString(const STR16); extern INT16 GetNumberOfLinesInHeight(const STR16); extern void DisplayHelpTokenizedString(const STR16,INT16,INT16); extern BOOLEAN initTooltipBuffer(); extern PTR LockTooltipBuffer(UINT32*); extern void UnlockTooltipBuffer(); extern void DisplayTooltipString( const STR16 pStringA, INT16 sX, INT16 sY ); extern void j_log(PTR,...); iX = mouseTT.iX;iY = mouseTT.iY; iW = (INT32)GetWidthOfString( mouseTT.FastHelpText ) + 10; iH = (INT32)( GetNumberOfLinesInHeight( mouseTT.FastHelpText ) * (GetFontHeight(FONT10ARIAL)+1) + 8 ); if(1)//draw at cursor { iY -= (iH / 2); if (gusMouseXPos > (SCREEN_WIDTH / 2)) iX = gusMouseXPos - iW - 24; else iX = gusMouseXPos + 24; //if (gusMouseYPos > (SCREEN_HEIGHT / 2)) // iY -= 32; if (iY <= 0) iY += 32; } else { //draw in panel //502,485 658,596 160*110 580,540 iX = 580 - (iW / 2); iY = 540 - (iH/2); if (iY + iH > SCREEN_HEIGHT) iY = SCREEN_HEIGHT - iH - 3 ; } pDestBuf = LockVideoSurface( FRAME_BUFFER, &uiDestPitchBYTES ); SetClippingRegionAndImageWidth( uiDestPitchBYTES, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); RectangleDraw( TRUE, iX + 1, iY + 1, iX + iW - 1, iY + iH - 1, Get16BPPColor( FROMRGB( 65, 57, 15 ) ), pDestBuf ); RectangleDraw( TRUE, iX, iY, iX + iW - 2, iY + iH - 2, Get16BPPColor( FROMRGB( 227, 198, 88 ) ), pDestBuf ); UnLockVideoSurface( FRAME_BUFFER ); ShadowVideoSurfaceRect( FRAME_BUFFER, iX + 2, iY + 2, iX + iW - 3, iY + iH - 3 ); ShadowVideoSurfaceRect( FRAME_BUFFER, iX + 2, iY + 2, iX + iW - 3, iY + iH - 3 ); SetFont( FONT10ARIAL ); SetFontShadow( FONT_NEARBLACK ); DisplayHelpTokenizedString( mouseTT.FastHelpText ,( INT16 )( iX + 5 ), ( INT16 )( iY + 5 ) ); InvalidateRegion( iX, iY, (iX + iW) , (iY + iH) ); //InvalidateScreen(); }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 603 ] ] ]
1caae8fc0905aa8f75416f5abed4ddf64345f51d
1102f77e8dbf563a024cec0b885c0d9f9da2ef39
/model/documentmodel.cc
0f4c1472e453b979e78e4cb2dba4ccd9f6baebda
[]
no_license
pgoodman/uwo-cooper
7c38c1bc0b3fc04cabb128cd5a3c984c67efc2f3
ea881e9794cb2c0ae64c0d73117facfd92c3f96b
refs/heads/master
2016-09-11T03:29:39.537161
2010-04-05T21:28:26
2010-04-05T21:28:26
32,091,588
0
0
null
null
null
null
UTF-8
C++
false
false
6,511
cc
#include "documentmodel.h" DocumentModel::DocumentModel(int doctype){ //cursor = new QTextCursor(this); switch(doctype){ case PHONE_LIST_PUBLIC: generatePhoneList(false); break; case PHONE_LIST_ALL: generatePhoneList(true); break; case COMMITTEE_LIST: generateCommitteeList(); break; case TASK_LIST: generateTaskList(0); break; } } //generate document with sorting //valid for phone list only DocumentModel::DocumentModel(int doctype, int sort){ if(doctype == PHONE_LIST_PUBLIC) { generatePhoneList(false, sort); }else if(doctype == PHONE_LIST_ALL) { generatePhoneList(true, sort); }else {} } DocumentModel::DocumentModel(int doctype, CommitteeModel *committee){ if(doctype == TASK_LIST){ generateTaskList(committee); }else { generateCommitteeList(); } } DocumentModel::~DocumentModel(){ } void DocumentModel::generatePhoneList(bool isconfidential, int sort){ QString html; html.append("<p><b>MEMBER PHONE LIST</b></p><br />"); html.append("NOTE: Contacts listed in italic are under 21 years old living with the nearest member above"); html.append("<table border=0 cellpadding=10>"); html.append("<tr><td align=""left""><b>Name</b></td><td align=""left""><b>Unit</b></td><td align=""left""><b>Phone Number</b></td></tr>"); const char *cond; if (sort == SORT_BY_LASTNAME) { cond = "1=1 ORDER BY last_name ASC"; }else if(sort == SORT_BY_UNIT){ cond = "1=1 ORDER BY unit_id ASC"; }else{ cond = "1=1"; } MemberModel::iterator_range itr = MemberModel::findAll(cond); MemberModel::iterator it = itr.first; MemberModel::iterator end = itr.second; int membercount; QString cell1; QString cell2; QString cell3; for(membercount = 0; it != end; it++){ membercount++; MemberModel *m = *it; if(!m->isMarkedDeleted()){ if(isconfidential || m->isTelephoneShared()){ cell1 = ""; cell2 = ""; cell3 = ""; cell1.append("<td>" + m->getLastName() + "," + m->getFirstName() + "</td>"); cell2.append("<td>" + QString::number(m->findUnit()->id) + "-" + m->findUnit()->address + "</td>"); cell3.append("<td>" + m->getTelephoneNum() + "</td>"); html.append("<tr>" + cell1 + cell2 + cell3 + "</tr>"); } DependantModel::iterator_range ditr = m->findDependants(); DependantModel::iterator dit = ditr.first; DependantModel::iterator dend = ditr.second; for(; dit != dend; dit++){ DependantModel *d = *dit; cell1 = ""; cell2 = ""; cell3 = ""; cell1.append("<td><i>" + d->getName() + "</i></td>"); cell2.append("<td><i>" + QString::number(m->findUnit()->id) + "-" + m->findUnit()->address + "</i></td>"); cell3.append("<td><i>" + m->getTelephoneNum() + "</i></td>"); html.append("<tr>" + cell1 + cell2 + cell3 + "</tr>"); } } } html.append("</table><br />"); this->setHtml(html); } void DocumentModel::generateCommitteeList(){ QString html; html.append("<p><b>COMMITTEE LIST</b></p><br />"); CommitteeModel::iterator_range citr = CommitteeModel::findAll(); CommitteeModel::iterator cit = citr.first; CommitteeModel::iterator cend = citr.second; //committee name int committeecount; for(committeecount = 0; cit != cend; cit++){ CommitteeModel *c = *cit; //committee member html.append("<p><b>" + c->toString() + " Committee" + "</b></p>"); html.append("<table border=0 cellpadding=10>"); html.append("<tr><td align=""left"">Member Name</td><td align=""left"">Unit</td><td align=""left"">Role</td></tr>"); //name | unit number | role MemberModel::iterator_range itr = c->findMembers(); MemberModel::iterator it = itr.first; MemberModel::iterator end = itr.second; for(; it != end; it++){ MemberModel *m = *it; if(!m->isMarkedDeleted()){ QString cell1 = ""; QString cell2 = ""; QString cell3 = ""; cell1.append("<td>" + m->getLastName() + "," + m->getFirstName() + "</td>"); cell2.append("<td>" + QString::number(m->findUnit()->id) + "-" + m->findUnit()->address + "</td>"); cell3.append("<td>" + m->getRoleAtCommittee() + "</td>"); html.append("<tr>" + cell1 + cell2 + cell3 + "</tr>"); } } html.append("</table><br />"); } this->setHtml(html); } void DocumentModel::generateTaskList(CommitteeModel *committee){ QString html; if(committee != 0){ html.append("<p><b>PENDING TASK LIST</b></p><br />"); html.append("NOTE: Highlighted tasks are overdue tasks"); html.append("<table border=0 cellpadding=10>"); html.append("<tr><td align=""left"">Check</td><td align=""left"">Task Name</td><td align=""left"">Due Date</td></tr>"); TaskModel::iterator_range itr = committee->findTasks(); TaskModel::iterator it = itr.first; TaskModel::iterator end = itr.second; for(; it != end; it++){ TaskModel *t = *it; QDate today = QDate::currentDate(); if(t->isPending()) { QString cell1 = ""; QString cell2 = ""; QString cell3 = ""; QDate deadline = t->getDeadline().date(); cell1.append("<td><img src=""images/checkbox.gif"" width=""15"" height=""15""></img></td>"); cell2.append("<td>" + t->getName() + "</td>"); cell3.append("<td>" + deadline.toString() + "</td>"); //highlight row if deadline passed if(deadline < today) { html.append("<tr style=""background-color:yellow"">"); }else{ html.append("<tr>"); } html.append(cell1 + cell2 + cell3 + "</tr>"); } } this->setHtml(html); } }
[ "jlu.newera@c307de66-1bdf-11df-a447-cf726199f266", "peter.goodman@c307de66-1bdf-11df-a447-cf726199f266" ]
[ [ [ 1, 164 ], [ 166, 180 ] ], [ [ 165, 165 ] ] ]
2d9f165d6be866c7ec6fd33ac610209fd22c2cb2
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/src/Tdk/Header Files/TdkAbstractImage.h
28f77a7ab04c56d7f82e1689128a7fbf1fe35b50
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,056
h
/****************************************************************************** * FUNCATE - GIS development team * * TerraLib Components - TeCOM * * @(#) tdkAbstractImage.h * ******************************************************************************* * * $Rev$: * * $Author: rui.gregorio $: * * $Date: 2009/07/17 11:09:56 $: * ******************************************************************************/ // Elaborated by Rui Mauricio Gregório #ifndef __TDK_ABSTRACT_IMAGE_H #define __TDK_ABSTRACT_IMAGE_H #include <iostream> using namespace std; //! \class tdkAbstractImage /*! Class to Images manipulation */ class TdkAbstractImage { protected : std::string _fileName; //!< File Name String public : TdkAbstractImage(); virtual ~TdkAbstractImage(); //! \brief setHeight /*! Method to set the height image \param value height value */ virtual void setHeight(const double &value) = 0; //! \brief setWidth /*! Method to set the width image \param value width value */ virtual void setWidth(const double &value) = 0; //! \brief getHeight /*! Abstract method to return the image's height \return returns the height value */ virtual double getHeight() = 0; //! \brief getWidth /*! Abstract method to return the image's width \return returns the width value */ virtual double getWidth() = 0; //! \brief save /*! Method to save the image object to file \param fileName file name \return returns true whether sucess */ virtual bool save(const std::string &fileName) = 0; //! \brief Clear /*! Method to clear image from memory */ virtual void clear() = 0; //! \brief setFileName /*! Method to set the image's file name \param fileName String file name */ virtual void setFileName(const std::string &fileName); //! \brief getFileName /*! Method to returns a string that represents the image file name \param returns the file name string */ virtual std::string getFileName(); }; #endif
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 93 ] ] ]
bfe0d4bcc5d0a85755a890911ab96bdcb70293f1
507d733770b2f22ea6cebc2b519037a5fa3cceed
/gs2d/src/Platform/Platform.cpp
56e9dbae44dd57ac9744a1300128c067f3a7f3eb
[]
no_license
andresan87/Torch
a3e7fa338a675b0e552afa914cb86050d641afeb
cecdbb9b4ea742b6f03e609f9445849a932ed755
refs/heads/master
2021-01-20T08:47:25.624168
2011-07-08T12:40:55
2011-07-08T12:40:55
2,014,722
0
1
null
null
null
null
UTF-8
C++
false
false
1,365
cpp
/*----------------------------------------------------------------------- Ethanon Engine (C) Copyright 2009-2011 Andre Santee http://www.asantee.net/ethanon/ This file is part of Ethanon Engine. Ethanon Engine 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. Ethanon Engine 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 Ethanon Engine. If not, see <http://www.gnu.org/licenses/>. -----------------------------------------------------------------------*/ #include "Platform.h" #include <iostream> namespace Platform { gs2d::str_type::string GetFileName(const gs2d::str_type::string &source) { const unsigned int len = source.length(); gs2d::str_type::string r = source; unsigned int t; for (t = len-1; t > 0; t--) { if (r[t] == GS_L('\\') || r[t] == GS_L('/')) { r = r.substr(t+1); break; } } return r; } } // namespace Platform
[ "Andre@AndreDell.(none)" ]
[ [ [ 1, 45 ] ] ]
47c496f87ee71e360a66386e7d114acaa1162947
d6bc5bc03cb6c7ea15f2cc44a90df63c179b898c
/IphoneVideoCaptureTester/opencv_device/include/opencv2/gpu/gpu.hpp
a184358a41cbe9ada117a864868b2b5d58d89c2e
[]
no_license
jjzhang166/VisionHackerTestBase
ce442ef535768a7ab9cb4be23ad0fcf3fd4ce78b
7a6a1dbf725227dc431945cc7deaf1fe9c72385c
refs/heads/master
2021-01-23T19:26:00.535856
2011-10-17T13:52:43
2011-10-17T13:52:43
102,822,190
0
0
null
null
null
null
UTF-8
C++
false
false
79,991
hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other GpuMaterials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_GPU_HPP__ #define __OPENCV_GPU_HPP__ #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/gpu/devmem2d.hpp" #include "opencv2/features2d/features2d.hpp" namespace cv { namespace gpu { //////////////////////////////// Initialization & Info //////////////////////// //! This is the only function that do not throw exceptions if the library is compiled without Cuda. CV_EXPORTS int getCudaEnabledDeviceCount(); //! Functions below throw cv::Expception if the library is compiled without Cuda. CV_EXPORTS void setDevice(int device); CV_EXPORTS int getDevice(); enum FeatureSet { FEATURE_SET_COMPUTE_10 = 10, FEATURE_SET_COMPUTE_11 = 11, FEATURE_SET_COMPUTE_12 = 12, FEATURE_SET_COMPUTE_13 = 13, FEATURE_SET_COMPUTE_20 = 20, FEATURE_SET_COMPUTE_21 = 21, GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13 }; // Gives information about what GPU archs this OpenCV GPU module was // compiled for class CV_EXPORTS TargetArchs { public: static bool builtWith(FeatureSet feature_set); static bool has(int major, int minor); static bool hasPtx(int major, int minor); static bool hasBin(int major, int minor); static bool hasEqualOrLessPtx(int major, int minor); static bool hasEqualOrGreater(int major, int minor); static bool hasEqualOrGreaterPtx(int major, int minor); static bool hasEqualOrGreaterBin(int major, int minor); private: TargetArchs(); }; // Gives information about the given GPU class CV_EXPORTS DeviceInfo { public: // Creates DeviceInfo object for the current GPU DeviceInfo() : device_id_(getDevice()) { query(); } // Creates DeviceInfo object for the given GPU DeviceInfo(int device_id) : device_id_(device_id) { query(); } string name() const { return name_; } // Return compute capability versions int majorVersion() const { return majorVersion_; } int minorVersion() const { return minorVersion_; } int multiProcessorCount() const { return multi_processor_count_; } size_t freeMemory() const; size_t totalMemory() const; // Checks whether device supports the given feature bool supports(FeatureSet feature_set) const; // Checks whether the GPU module can be run on the given device bool isCompatible() const; private: void query(); void queryMemory(size_t& free_memory, size_t& total_memory) const; int device_id_; string name_; int multi_processor_count_; int majorVersion_; int minorVersion_; }; /////////////////////////// Multi GPU Manager ////////////////////////////// // Provides functionality for working with many GPUs class CV_EXPORTS MultiGpuManager { public: MultiGpuManager(); ~MultiGpuManager(); // Must be called before any other GPU calls void init(); // Makes the given GPU active void gpuOn(int gpu_id); // Finishes the piece of work on the current GPU void gpuOff(); static const int BAD_GPU_ID = -1; private: void operator=(const MultiGpuManager&); MultiGpuManager(const MultiGpuManager&); class Impl; Ptr<Impl> impl_; }; //////////////////////////////// Error handling //////////////////////// CV_EXPORTS void error(const char *error_string, const char *file, const int line, const char *func); CV_EXPORTS void nppError( int err, const char *file, const int line, const char *func); //////////////////////////////// GpuMat //////////////////////////////// class Stream; class CudaMem; //! Smart pointer for GPU memory with reference counting. Its interface is mostly similar with cv::Mat. class CV_EXPORTS GpuMat { public: //! default constructor GpuMat(); //! constructs GpuMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) GpuMat(int rows, int cols, int type); GpuMat(Size size, int type); //! constucts GpuMatrix and fills it with the specified value _s. GpuMat(int rows, int cols, int type, const Scalar& s); GpuMat(Size size, int type, const Scalar& s); //! copy constructor GpuMat(const GpuMat& m); //! constructor for GpuMatrix headers pointing to user-allocated data GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); //! creates a matrix header for a part of the bigger matrix GpuMat(const GpuMat& m, const Range& rowRange, const Range& colRange); GpuMat(const GpuMat& m, const Rect& roi); //! builds GpuMat from Mat. Perfom blocking upload to device. explicit GpuMat (const Mat& m); //! destructor - calls release() ~GpuMat(); //! assignment operators GpuMat& operator = (const GpuMat& m); //! assignment operator. Perfom blocking upload to device. GpuMat& operator = (const Mat& m); //! returns lightweight DevMem2D_ structure for passing to nvcc-compiled code. // Contains just image size, data ptr and step. template <class T> operator DevMem2D_<T>() const; template <class T> operator PtrStep_<T>() const; //! pefroms blocking upload data to GpuMat. void upload(const cv::Mat& m); //! upload async void upload(const CudaMem& m, Stream& stream); //! downloads data from device to host memory. Blocking calls. operator Mat() const; void download(cv::Mat& m) const; //! download async void download(CudaMem& m, Stream& stream) const; //! returns a new GpuMatrix header for the specified row GpuMat row(int y) const; //! returns a new GpuMatrix header for the specified column GpuMat col(int x) const; //! ... for the specified row span GpuMat rowRange(int startrow, int endrow) const; GpuMat rowRange(const Range& r) const; //! ... for the specified column span GpuMat colRange(int startcol, int endcol) const; GpuMat colRange(const Range& r) const; //! returns deep copy of the GpuMatrix, i.e. the data is copied GpuMat clone() const; //! copies the GpuMatrix content to "m". // It calls m.create(this->size(), this->type()). void copyTo( GpuMat& m ) const; //! copies those GpuMatrix elements to "m" that are marked with non-zero mask elements. void copyTo( GpuMat& m, const GpuMat& mask ) const; //! converts GpuMatrix to another datatype with optional scalng. See cvConvertScale. void convertTo( GpuMat& m, int rtype, double alpha=1, double beta=0 ) const; void assignTo( GpuMat& m, int type=-1 ) const; //! sets every GpuMatrix element to s GpuMat& operator = (const Scalar& s); //! sets some of the GpuMatrix elements to s, according to the mask GpuMat& setTo(const Scalar& s, const GpuMat& mask = GpuMat()); //! creates alternative GpuMatrix header for the same data, with different // number of channels and/or different number of rows. see cvReshape. GpuMat reshape(int cn, int rows = 0) const; //! allocates new GpuMatrix data unless the GpuMatrix already has specified size and type. // previous data is unreferenced if needed. void create(int rows, int cols, int type); void create(Size size, int type); //! decreases reference counter; // deallocate the data when reference counter reaches 0. void release(); //! swaps with other smart pointer void swap(GpuMat& mat); //! locates GpuMatrix header within a parent GpuMatrix. See below void locateROI( Size& wholeSize, Point& ofs ) const; //! moves/resizes the current GpuMatrix ROI inside the parent GpuMatrix. GpuMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); //! extracts a rectangular sub-GpuMatrix // (this is a generalized form of row, rowRange etc.) GpuMat operator()( Range rowRange, Range colRange ) const; GpuMat operator()( const Rect& roi ) const; //! returns true iff the GpuMatrix data is continuous // (i.e. when there are no gaps between successive rows). // similar to CV_IS_GpuMat_CONT(cvGpuMat->type) bool isContinuous() const; //! returns element size in bytes, // similar to CV_ELEM_SIZE(cvMat->type) size_t elemSize() const; //! returns the size of element channel in bytes. size_t elemSize1() const; //! returns element type, similar to CV_MAT_TYPE(cvMat->type) int type() const; //! returns element type, similar to CV_MAT_DEPTH(cvMat->type) int depth() const; //! returns element type, similar to CV_MAT_CN(cvMat->type) int channels() const; //! returns step/elemSize1() size_t step1() const; //! returns GpuMatrix size: // width == number of columns, height == number of rows Size size() const; //! returns true if GpuMatrix data is NULL bool empty() const; //! returns pointer to y-th row uchar* ptr(int y = 0); const uchar* ptr(int y = 0) const; //! template version of the above method template<typename _Tp> _Tp* ptr(int y = 0); template<typename _Tp> const _Tp* ptr(int y = 0) const; //! matrix transposition GpuMat t() const; /*! includes several bit-fields: - the magic signature - continuity flag - depth - number of channels */ int flags; //! the number of rows and columns int rows, cols; //! a distance between successive rows in bytes; includes the gap if any size_t step; //! pointer to the data uchar* data; //! pointer to the reference counter; // when GpuMatrix points to user-allocated data, the pointer is NULL int* refcount; //! helper fields used in locateROI and adjustROI uchar* datastart; uchar* dataend; }; //#define TemplatedGpuMat // experimental now, deprecated to use #ifdef TemplatedGpuMat #include "GpuMat_BetaDeprecated.hpp" #endif //! Creates continuous GPU matrix CV_EXPORTS void createContinuous(int rows, int cols, int type, GpuMat& m); //! Ensures that size of the given matrix is not less than (rows, cols) size //! and matrix type is match specified one too CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, GpuMat& m); //////////////////////////////// CudaMem //////////////////////////////// // CudaMem is limited cv::Mat with page locked memory allocation. // Page locked memory is only needed for async and faster coping to GPU. // It is convertable to cv::Mat header without reference counting // so you can use it with other opencv functions. class CV_EXPORTS CudaMem { public: enum { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2, ALLOC_WRITE_COMBINED = 4 }; CudaMem(); CudaMem(const CudaMem& m); CudaMem(int rows, int cols, int type, int _alloc_type = ALLOC_PAGE_LOCKED); CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED); //! creates from cv::Mat with coping data explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED); ~CudaMem(); CudaMem& operator = (const CudaMem& m); //! returns deep copy of the matrix, i.e. the data is copied CudaMem clone() const; //! allocates new matrix data unless the matrix already has specified size and type. void create(int rows, int cols, int type, int alloc_type = ALLOC_PAGE_LOCKED); void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED); //! decrements reference counter and released memory if needed. void release(); //! returns matrix header with disabled reference counting for CudaMem data. Mat createMatHeader() const; operator Mat() const; //! maps host memory into device address space and returns GpuMat header for it. Throws exception if not supported by hardware. GpuMat createGpuMatHeader() const; operator GpuMat() const; //returns if host memory can be mapperd to gpu address space; static bool canMapHostMemory(); // Please see cv::Mat for descriptions bool isContinuous() const; size_t elemSize() const; size_t elemSize1() const; int type() const; int depth() const; int channels() const; size_t step1() const; Size size() const; bool empty() const; // Please see cv::Mat for descriptions int flags; int rows, cols; size_t step; uchar* data; int* refcount; uchar* datastart; uchar* dataend; int alloc_type; }; //////////////////////////////// CudaStream //////////////////////////////// // Encapculates Cuda Stream. Provides interface for async coping. // Passed to each function that supports async kernel execution. // Reference counting is enabled class CV_EXPORTS Stream { public: Stream(); ~Stream(); Stream(const Stream&); Stream& operator=(const Stream&); bool queryIfComplete(); void waitForCompletion(); //! downloads asynchronously. // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its subMat) void enqueueDownload(const GpuMat& src, CudaMem& dst); void enqueueDownload(const GpuMat& src, Mat& dst); //! uploads asynchronously. // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its ROI) void enqueueUpload(const CudaMem& src, GpuMat& dst); void enqueueUpload(const Mat& src, GpuMat& dst); void enqueueCopy(const GpuMat& src, GpuMat& dst); void enqueueMemSet(GpuMat& src, Scalar val); void enqueueMemSet(GpuMat& src, Scalar val, const GpuMat& mask); // converts matrix type, ex from float to uchar depending on type void enqueueConvert(const GpuMat& src, GpuMat& dst, int type, double a = 1, double b = 0); private: void create(); void release(); struct Impl; Impl *impl; friend struct StreamAccessor; }; ////////////////////////////// Arithmetics /////////////////////////////////// //! transposes the matrix //! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc) CV_EXPORTS void transpose(const GpuMat& src1, GpuMat& dst); //! reverses the order of the rows, columns or both in a matrix //! supports CV_8UC1, CV_8UC4 types CV_EXPORTS void flip(const GpuMat& a, GpuMat& b, int flipCode); //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i)) //! destination array will have the depth type as lut and the same channels number as source //! supports CV_8UC1, CV_8UC3 types CV_EXPORTS void LUT(const GpuMat& src, const Mat& lut, GpuMat& dst); //! makes multi-channel array out of several single-channel arrays CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst); //! makes multi-channel array out of several single-channel arrays CV_EXPORTS void merge(const vector<GpuMat>& src, GpuMat& dst); //! makes multi-channel array out of several single-channel arrays (async version) CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst, const Stream& stream); //! makes multi-channel array out of several single-channel arrays (async version) CV_EXPORTS void merge(const vector<GpuMat>& src, GpuMat& dst, const Stream& stream); //! copies each plane of a multi-channel array to a dedicated array CV_EXPORTS void split(const GpuMat& src, GpuMat* dst); //! copies each plane of a multi-channel array to a dedicated array CV_EXPORTS void split(const GpuMat& src, vector<GpuMat>& dst); //! copies each plane of a multi-channel array to a dedicated array (async version) CV_EXPORTS void split(const GpuMat& src, GpuMat* dst, const Stream& stream); //! copies each plane of a multi-channel array to a dedicated array (async version) CV_EXPORTS void split(const GpuMat& src, vector<GpuMat>& dst, const Stream& stream); //! computes magnitude of complex (x(i).re, x(i).im) vector //! supports only CV_32FC2 type CV_EXPORTS void magnitude(const GpuMat& x, GpuMat& magnitude); //! computes squared magnitude of complex (x(i).re, x(i).im) vector //! supports only CV_32FC2 type CV_EXPORTS void magnitudeSqr(const GpuMat& x, GpuMat& magnitude); //! computes magnitude of each (x(i), y(i)) vector //! supports only floating-point source CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude); //! async version CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, const Stream& stream); //! computes squared magnitude of each (x(i), y(i)) vector //! supports only floating-point source CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude); //! async version CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, const Stream& stream); //! computes angle (angle(i)) of each (x(i), y(i)) vector //! supports only floating-point source CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees = false); //! async version CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees, const Stream& stream); //! converts Cartesian coordinates to polar //! supports only floating-point source CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees = false); //! async version CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees, const Stream& stream); //! converts polar coordinates to Cartesian //! supports only floating-point source CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees = false); //! async version CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees, const Stream& stream); //////////////////////////// Per-element operations //////////////////////////////////// //! adds one matrix to another (c = a + b) //! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types CV_EXPORTS void add(const GpuMat& a, const GpuMat& b, GpuMat& c); //! adds scalar to a matrix (c = a + s) //! supports CV_32FC1 and CV_32FC2 type CV_EXPORTS void add(const GpuMat& a, const Scalar& sc, GpuMat& c); //! subtracts one matrix from another (c = a - b) //! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types CV_EXPORTS void subtract(const GpuMat& a, const GpuMat& b, GpuMat& c); //! subtracts scalar from a matrix (c = a - s) //! supports CV_32FC1 and CV_32FC2 type CV_EXPORTS void subtract(const GpuMat& a, const Scalar& sc, GpuMat& c); //! computes element-wise product of the two arrays (c = a * b) //! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types CV_EXPORTS void multiply(const GpuMat& a, const GpuMat& b, GpuMat& c); //! multiplies matrix to a scalar (c = a * s) //! supports CV_32FC1 and CV_32FC2 type CV_EXPORTS void multiply(const GpuMat& a, const Scalar& sc, GpuMat& c); //! computes element-wise quotient of the two arrays (c = a / b) //! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types CV_EXPORTS void divide(const GpuMat& a, const GpuMat& b, GpuMat& c); //! computes element-wise quotient of matrix and scalar (c = a / s) //! supports CV_32FC1 and CV_32FC2 type CV_EXPORTS void divide(const GpuMat& a, const Scalar& sc, GpuMat& c); //! computes exponent of each matrix element (b = e**a) //! supports only CV_32FC1 type CV_EXPORTS void exp(const GpuMat& a, GpuMat& b); //! computes natural logarithm of absolute value of each matrix element: b = log(abs(a)) //! supports only CV_32FC1 type CV_EXPORTS void log(const GpuMat& a, GpuMat& b); //! computes element-wise absolute difference of two arrays (c = abs(a - b)) //! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types CV_EXPORTS void absdiff(const GpuMat& a, const GpuMat& b, GpuMat& c); //! computes element-wise absolute difference of array and scalar (c = abs(a - s)) //! supports only CV_32FC1 type CV_EXPORTS void absdiff(const GpuMat& a, const Scalar& s, GpuMat& c); //! compares elements of two arrays (c = a <cmpop> b) //! supports CV_8UC4, CV_32FC1 types CV_EXPORTS void compare(const GpuMat& a, const GpuMat& b, GpuMat& c, int cmpop); //! performs per-elements bit-wise inversion CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask=GpuMat()); //! async version CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask, const Stream& stream); //! calculates per-element bit-wise disjunction of two arrays CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat()); //! async version CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask, const Stream& stream); //! calculates per-element bit-wise conjunction of two arrays CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat()); //! async version CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask, const Stream& stream); //! calculates per-element bit-wise "exclusive or" operation CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat()); //! async version CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask, const Stream& stream); //! computes per-element minimum of two arrays (dst = min(src1, src2)) CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst); //! Async version CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const Stream& stream); //! computes per-element minimum of array and scalar (dst = min(src1, src2)) CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst); //! Async version CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst, const Stream& stream); //! computes per-element maximum of two arrays (dst = max(src1, src2)) CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst); //! Async version CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const Stream& stream); //! computes per-element maximum of array and scalar (dst = max(src1, src2)) CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst); //! Async version CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst, const Stream& stream); ////////////////////////////// Image processing ////////////////////////////// //! DST[x,y] = SRC[xmap[x,y],ymap[x,y]] with bilinear interpolation. //! supports CV_8UC1, CV_8UC3 source types and CV_32FC1 map type CV_EXPORTS void remap(const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap); //! Does mean shift filtering on GPU. CV_EXPORTS void meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr, TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1)); //! Does mean shift procedure on GPU. CV_EXPORTS void meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr, TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1)); //! Does mean shift segmentation with elimination of small regions. CV_EXPORTS void meanShiftSegmentation(const GpuMat& src, Mat& dst, int sp, int sr, int minsize, TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1)); //! Does coloring of disparity image: [0..ndisp) -> [0..240, 1, 1] in HSV. //! Supported types of input disparity: CV_8U, CV_16S. //! Output disparity has CV_8UC4 type in BGRA format (alpha = 255). CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp); //! async version CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp, const Stream& stream); //! Reprojects disparity image to 3D space. //! Supports CV_8U and CV_16S types of input disparity. //! The output is a 4-channel floating-point (CV_32FC4) matrix. //! Each element of this matrix will contain the 3D coordinates of the point (x,y,z,1), computed from the disparity map. //! Q is the 4x4 perspective transformation matrix that can be obtained with cvStereoRectify. CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q); //! async version CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q, const Stream& stream); //! converts image from one color space to another CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn = 0); //! async version CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn, const Stream& stream); //! applies fixed threshold to the image CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type); //! async version CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type, const Stream& stream); //! resizes the image //! Supports INTER_NEAREST, INTER_LINEAR //! supports CV_8UC1, CV_8UC4 types CV_EXPORTS void resize(const GpuMat& src, GpuMat& dst, Size dsize, double fx=0, double fy=0, int interpolation = INTER_LINEAR); //! warps the image using affine transformation //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC CV_EXPORTS void warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR); //! warps the image using perspective transformation //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC CV_EXPORTS void warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR); //! rotate 8bit single or four channel image //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC //! supports CV_8UC1, CV_8UC4 types CV_EXPORTS void rotate(const GpuMat& src, GpuMat& dst, Size dsize, double angle, double xShift = 0, double yShift = 0, int interpolation = INTER_LINEAR); //! copies 2D array to a larger destination array and pads borders with user-specifiable constant //! supports CV_8UC1, CV_8UC4, CV_32SC1 and CV_32FC1 types CV_EXPORTS void copyMakeBorder(const GpuMat& src, GpuMat& dst, int top, int bottom, int left, int right, const Scalar& value = Scalar()); //! computes the integral image //! sum will have CV_32S type, but will contain unsigned int values //! supports only CV_8UC1 source type CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum); //! buffered version CV_EXPORTS void integralBuffered(const GpuMat& src, GpuMat& sum, GpuMat& buffer); //! computes the integral image and integral for the squared image //! sum will have CV_32S type, sqsum - CV32F type //! supports only CV_8UC1 source type CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, GpuMat& sqsum); //! computes squared integral image //! result matrix will have 64F type, but will contain 64U values //! supports source images of 8UC1 type only CV_EXPORTS void sqrIntegral(const GpuMat& src, GpuMat& sqsum); //! computes vertical sum, supports only CV_32FC1 images CV_EXPORTS void columnSum(const GpuMat& src, GpuMat& sum); //! computes the standard deviation of integral images //! supports only CV_32SC1 source type and CV_32FC1 sqr type //! output will have CV_32FC1 type CV_EXPORTS void rectStdDev(const GpuMat& src, const GpuMat& sqr, GpuMat& dst, const Rect& rect); // applies Canny edge detector and produces the edge map // disabled until fix crash //CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, double threshold1, double threshold2, int apertureSize = 3); //CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, GpuMat& buffer, double threshold1, double threshold2, int apertureSize = 3); //CV_EXPORTS void Canny(const GpuMat& srcDx, const GpuMat& srcDy, GpuMat& edges, double threshold1, double threshold2, int apertureSize = 3); //CV_EXPORTS void Canny(const GpuMat& srcDx, const GpuMat& srcDy, GpuMat& edges, GpuMat& buffer, double threshold1, double threshold2, int apertureSize = 3); //! computes Harris cornerness criteria at each image pixel CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, double k, int borderType=BORDER_REFLECT101); //! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, int borderType=BORDER_REFLECT101); //! performs per-element multiplication of two full (not packed) Fourier spectrums //! supports 32FC2 matrixes only (interleaved format) CV_EXPORTS void mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false); //! performs per-element multiplication of two full (not packed) Fourier spectrums //! supports 32FC2 matrixes only (interleaved format) CV_EXPORTS void mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false); //! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix. //! Param dft_size is the size of DFT transform. //! //! If the source matrix is not continous, then additional copy will be done, //! so to avoid copying ensure the source matrix is continous one. If you want to use //! preallocated output ensure it is continuous too, otherwise it will be reallocated. //! //! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values //! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved. //! //! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format. CV_EXPORTS void dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0); //! computes convolution (or cross-correlation) of two images using discrete Fourier transform //! supports source images of 32FC1 type only //! result matrix will have 32FC1 type CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr=false); struct CV_EXPORTS ConvolveBuf; //! buffered version CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf); struct CV_EXPORTS ConvolveBuf { ConvolveBuf() {} ConvolveBuf(Size image_size, Size templ_size) { create(image_size, templ_size); } void create(Size image_size, Size templ_size); private: static Size estimateBlockSize(Size result_size, Size templ_size); friend void convolve(const GpuMat&, const GpuMat&, GpuMat&, bool, ConvolveBuf&); Size result_size; Size block_size; Size dft_size; int spect_len; GpuMat image_spect, templ_spect, result_spect; GpuMat image_block, templ_block, result_data; }; //! computes the proximity map for the raster template and the image where the template is searched for CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method); ////////////////////////////// Matrix reductions ////////////////////////////// //! computes mean value and standard deviation of all or selected array elements //! supports only CV_8UC1 type CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev); //! computes norm of array //! supports NORM_INF, NORM_L1, NORM_L2 //! supports all matrices except 64F CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2); //! computes norm of array //! supports NORM_INF, NORM_L1, NORM_L2 //! supports all matrices except 64F CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf); //! computes norm of the difference between two arrays //! supports NORM_INF, NORM_L1, NORM_L2 //! supports only CV_8UC1 type CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2); //! computes sum of array elements //! supports only single channel images CV_EXPORTS Scalar sum(const GpuMat& src); //! computes sum of array elements //! supports only single channel images CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf); //! computes sum of array elements absolute values //! supports only single channel images CV_EXPORTS Scalar absSum(const GpuMat& src); //! computes sum of array elements absolute values //! supports only single channel images CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf); //! computes squared sum of array elements //! supports only single channel images CV_EXPORTS Scalar sqrSum(const GpuMat& src); //! computes squared sum of array elements //! supports only single channel images CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf); //! finds global minimum and maximum array elements and returns their values CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat()); //! finds global minimum and maximum array elements and returns their values CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf); //! finds global minimum and maximum array elements and returns their values with locations CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, const GpuMat& mask=GpuMat()); //! finds global minimum and maximum array elements and returns their values with locations CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc, const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf); //! counts non-zero array elements CV_EXPORTS int countNonZero(const GpuMat& src); //! counts non-zero array elements CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf); ///////////////////////////// Calibration 3D ////////////////////////////////// CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec, GpuMat& dst); CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec, GpuMat& dst, const Stream& stream); CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec, const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst); CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec, const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst, const Stream& stream); CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat, const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false, int num_iters=100, float max_dist=8.0, int min_inlier_count=100, vector<int>* inliers=NULL); //////////////////////////////// Filter Engine //////////////////////////////// /*! The Base Class for 1D or Row-wise Filters This is the base class for linear or non-linear filters that process 1D data. In particular, such filters are used for the "horizontal" filtering parts in separable filters. */ class CV_EXPORTS BaseRowFilter_GPU { public: BaseRowFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {} virtual ~BaseRowFilter_GPU() {} virtual void operator()(const GpuMat& src, GpuMat& dst) = 0; int ksize, anchor; }; /*! The Base Class for Column-wise Filters This is the base class for linear or non-linear filters that process columns of 2D arrays. Such filters are used for the "vertical" filtering parts in separable filters. */ class CV_EXPORTS BaseColumnFilter_GPU { public: BaseColumnFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {} virtual ~BaseColumnFilter_GPU() {} virtual void operator()(const GpuMat& src, GpuMat& dst) = 0; int ksize, anchor; }; /*! The Base Class for Non-Separable 2D Filters. This is the base class for linear or non-linear 2D filters. */ class CV_EXPORTS BaseFilter_GPU { public: BaseFilter_GPU(const Size& ksize_, const Point& anchor_) : ksize(ksize_), anchor(anchor_) {} virtual ~BaseFilter_GPU() {} virtual void operator()(const GpuMat& src, GpuMat& dst) = 0; Size ksize; Point anchor; }; /*! The Base Class for Filter Engine. The class can be used to apply an arbitrary filtering operation to an image. It contains all the necessary intermediate buffers. */ class CV_EXPORTS FilterEngine_GPU { public: virtual ~FilterEngine_GPU() {} virtual void apply(const GpuMat& src, GpuMat& dst, Rect roi = Rect(0,0,-1,-1)) = 0; }; //! returns the non-separable filter engine with the specified filter CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU>& filter2D, int srcType, int dstType); //! returns the separable filter engine with the specified filters CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU>& rowFilter, const Ptr<BaseColumnFilter_GPU>& columnFilter, int srcType, int bufType, int dstType); //! returns horizontal 1D box filter //! supports only CV_8UC1 source type and CV_32FC1 sum type CV_EXPORTS Ptr<BaseRowFilter_GPU> getRowSumFilter_GPU(int srcType, int sumType, int ksize, int anchor = -1); //! returns vertical 1D box filter //! supports only CV_8UC1 sum type and CV_32FC1 dst type CV_EXPORTS Ptr<BaseColumnFilter_GPU> getColumnSumFilter_GPU(int sumType, int dstType, int ksize, int anchor = -1); //! returns 2D box filter //! supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1)); //! returns box filter engine CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size& ksize, const Point& anchor = Point(-1,-1)); //! returns 2D morphological filter //! only MORPH_ERODE and MORPH_DILATE are supported //! supports CV_8UC1 and CV_8UC4 types //! kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height CV_EXPORTS Ptr<BaseFilter_GPU> getMorphologyFilter_GPU(int op, int type, const Mat& kernel, const Size& ksize, Point anchor=Point(-1,-1)); //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported. CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1); //! returns 2D filter with the specified kernel //! supports CV_8UC1 and CV_8UC4 types CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, const Size& ksize, Point anchor = Point(-1, -1)); //! returns the non-separable linear filter engine CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, const Point& anchor = Point(-1,-1)); //! returns the primitive row filter with the specified kernel. //! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 source type. //! there are two version of algorithm: NPP and OpenCV. //! NPP calls when srcType == CV_8UC1 or srcType == CV_8UC4 and bufType == srcType, //! otherwise calls OpenCV version. //! NPP supports only BORDER_CONSTANT border type. //! OpenCV version supports only CV_32F as buffer depth and //! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types. CV_EXPORTS Ptr<BaseRowFilter_GPU> getLinearRowFilter_GPU(int srcType, int bufType, const Mat& rowKernel, int anchor = -1, int borderType = BORDER_CONSTANT); //! returns the primitive column filter with the specified kernel. //! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 dst type. //! there are two version of algorithm: NPP and OpenCV. //! NPP calls when dstType == CV_8UC1 or dstType == CV_8UC4 and bufType == dstType, //! otherwise calls OpenCV version. //! NPP supports only BORDER_CONSTANT border type. //! OpenCV version supports only CV_32F as buffer depth and //! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types. CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel, int anchor = -1, int borderType = BORDER_CONSTANT); //! returns the separable linear filter engine CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel, const Mat& columnKernel, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! returns filter engine for the generalized Sobel operator CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! returns the Gaussian filter engine CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! returns maximum filter CV_EXPORTS Ptr<BaseFilter_GPU> getMaxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1)); //! returns minimum filter CV_EXPORTS Ptr<BaseFilter_GPU> getMinFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1)); //! smooths the image using the normalized box filter //! supports CV_8UC1, CV_8UC4 types CV_EXPORTS void boxFilter(const GpuMat& src, GpuMat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1)); //! a synonym for normalized box filter static inline void blur(const GpuMat& src, GpuMat& dst, Size ksize, Point anchor = Point(-1,-1)) { boxFilter(src, dst, -1, ksize, anchor); } //! erodes the image (applies the local minimum operator) CV_EXPORTS void erode( const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1); //! dilates the image (applies the local maximum operator) CV_EXPORTS void dilate( const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1); //! applies an advanced morphological operation to the image CV_EXPORTS void morphologyEx( const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1); //! applies non-separable 2D linear filter to the image CV_EXPORTS void filter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1,-1)); //! applies separable 2D linear filter to the image CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY, Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! applies generalized Sobel operator to the image CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! applies the vertical or horizontal Scharr operator to the image CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! smooths the image using Gaussian filter. CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2 = 0, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); //! applies Laplacian operator to the image //! supports only ksize = 1 and ksize = 3 CV_EXPORTS void Laplacian(const GpuMat& src, GpuMat& dst, int ddepth, int ksize = 1, double scale = 1); //////////////////////////////// Image Labeling //////////////////////////////// //!performs labeling via graph cuts CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels, GpuMat& buf); ////////////////////////////////// Histograms ////////////////////////////////// //! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type. CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel); //! Calculates histogram with evenly distributed bins for signle channel source. //! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types. //! Output hist will have one row and histSize cols and CV_32SC1 type. CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel); //! Calculates histogram with evenly distributed bins for four-channel source. //! All channels of source are processed separately. //! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types. //! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type. CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4]); //! Calculates histogram with bins determined by levels array. //! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise. //! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types. //! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type. CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels); //! Calculates histogram with bins determined by levels array. //! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise. //! All channels of source are processed separately. //! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types. //! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type. CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4]); //////////////////////////////// StereoBM_GPU //////////////////////////////// class CV_EXPORTS StereoBM_GPU { public: enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 }; enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 }; //! the default constructor StereoBM_GPU(); //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8. StereoBM_GPU(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ); //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair //! Output disparity has CV_8U type. void operator() ( const GpuMat& left, const GpuMat& right, GpuMat& disparity); //! async version void operator() ( const GpuMat& left, const GpuMat& right, GpuMat& disparity, const Stream & stream); //! Some heuristics that tries to estmate // if current GPU will be faster then CPU in this algorithm. // It queries current active device. static bool checkIfGpuCallReasonable(); int preset; int ndisp; int winSize; // If avergeTexThreshold == 0 => post procesing is disabled // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold // i.e. input left image is low textured. float avergeTexThreshold; private: GpuMat minSSD, leBuf, riBuf; }; ////////////////////////// StereoBeliefPropagation /////////////////////////// // "Efficient Belief Propagation for Early Vision" // P.Felzenszwalb class CV_EXPORTS StereoBeliefPropagation { public: enum { DEFAULT_NDISP = 64 }; enum { DEFAULT_ITERS = 5 }; enum { DEFAULT_LEVELS = 5 }; static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels); //! the default constructor explicit StereoBeliefPropagation(int ndisp = DEFAULT_NDISP, int iters = DEFAULT_ITERS, int levels = DEFAULT_LEVELS, int msg_type = CV_32F); //! the full constructor taking the number of disparities, number of BP iterations on each level, //! number of levels, truncation of data cost, data weight, //! truncation of discontinuity cost and discontinuity single jump //! DataTerm = data_weight * min(fabs(I2-I1), max_data_term) //! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term) //! please see paper for more details StereoBeliefPropagation(int ndisp, int iters, int levels, float max_data_term, float data_weight, float max_disc_term, float disc_single_jump, int msg_type = CV_32F); //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair, //! if disparity is empty output type will be CV_16S else output type will be disparity.type(). void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity); //! async version void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream); //! version for user specified data term void operator()(const GpuMat& data, GpuMat& disparity); void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream); int ndisp; int iters; int levels; float max_data_term; float data_weight; float max_disc_term; float disc_single_jump; int msg_type; private: GpuMat u, d, l, r, u2, d2, l2, r2; std::vector<GpuMat> datas; GpuMat out; }; /////////////////////////// StereoConstantSpaceBP /////////////////////////// // "A Constant-Space Belief Propagation Algorithm for Stereo Matching" // Qingxiong Yang, Liang Wang�, Narendra Ahuja // http://vision.ai.uiuc.edu/~qyang6/ class CV_EXPORTS StereoConstantSpaceBP { public: enum { DEFAULT_NDISP = 128 }; enum { DEFAULT_ITERS = 8 }; enum { DEFAULT_LEVELS = 4 }; enum { DEFAULT_NR_PLANE = 4 }; static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane); //! the default constructor explicit StereoConstantSpaceBP(int ndisp = DEFAULT_NDISP, int iters = DEFAULT_ITERS, int levels = DEFAULT_LEVELS, int nr_plane = DEFAULT_NR_PLANE, int msg_type = CV_32F); //! the full constructor taking the number of disparities, number of BP iterations on each level, //! number of levels, number of active disparity on the first level, truncation of data cost, data weight, //! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane, float max_data_term, float data_weight, float max_disc_term, float disc_single_jump, int min_disp_th = 0, int msg_type = CV_32F); //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair, //! if disparity is empty output type will be CV_16S else output type will be disparity.type(). void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity); //! async version void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream); int ndisp; int iters; int levels; int nr_plane; float max_data_term; float data_weight; float max_disc_term; float disc_single_jump; int min_disp_th; int msg_type; bool use_local_init_data_cost; private: GpuMat u[2], d[2], l[2], r[2]; GpuMat disp_selected_pyr[2]; GpuMat data_cost; GpuMat data_cost_selected; GpuMat temp; GpuMat out; }; /////////////////////////// DisparityBilateralFilter /////////////////////////// // Disparity map refinement using joint bilateral filtering given a single color image. // Qingxiong Yang, Liang Wang�, Narendra Ahuja // http://vision.ai.uiuc.edu/~qyang6/ class CV_EXPORTS DisparityBilateralFilter { public: enum { DEFAULT_NDISP = 64 }; enum { DEFAULT_RADIUS = 3 }; enum { DEFAULT_ITERS = 1 }; //! the default constructor explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS); //! the full constructor taking the number of disparities, filter radius, //! number of iterations, truncation of data continuity, truncation of disparity continuity //! and filter range sigma DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range); //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image. //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type. void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst); //! async version void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream); private: int ndisp; int radius; int iters; float edge_threshold; float max_disc_threshold; float sigma_range; GpuMat table_color; GpuMat table_space; }; //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// struct CV_EXPORTS HOGDescriptor { enum { DEFAULT_WIN_SIGMA = -1 }; enum { DEFAULT_NLEVELS = 64 }; enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL }; HOGDescriptor(Size win_size=Size(64, 128), Size block_size=Size(16, 16), Size block_stride=Size(8, 8), Size cell_size=Size(8, 8), int nbins=9, double win_sigma=DEFAULT_WIN_SIGMA, double threshold_L2hys=0.2, bool gamma_correction=true, int nlevels=DEFAULT_NLEVELS); size_t getDescriptorSize() const; size_t getBlockHistogramSize() const; void setSVMDetector(const vector<float>& detector); static vector<float> getDefaultPeopleDetector(); static vector<float> getPeopleDetector48x96(); static vector<float> getPeopleDetector64x128(); void detect(const GpuMat& img, vector<Point>& found_locations, double hit_threshold=0, Size win_stride=Size(), Size padding=Size()); void detectMultiScale(const GpuMat& img, vector<Rect>& found_locations, double hit_threshold=0, Size win_stride=Size(), Size padding=Size(), double scale0=1.05, int group_threshold=2); void getDescriptors(const GpuMat& img, Size win_stride, GpuMat& descriptors, int descr_format=DESCR_FORMAT_COL_BY_COL); Size win_size; Size block_size; Size block_stride; Size cell_size; int nbins; double win_sigma; double threshold_L2hys; bool gamma_correction; int nlevels; protected: void computeBlockHistograms(const GpuMat& img); void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& qangle); double getWinSigma() const; bool checkDetectorSize() const; static int numPartsWithin(int size, int part_size, int stride); static Size numPartsWithin(Size size, Size part_size, Size stride); // Coefficients of the separating plane float free_coef; GpuMat detector; // Results of the last classification step GpuMat labels; Mat labels_host; // Results of the last histogram evaluation step GpuMat block_hists; // Gradients conputation results GpuMat grad, qangle; }; ////////////////////////////////// BruteForceMatcher ////////////////////////////////// class CV_EXPORTS BruteForceMatcher_GPU_base { public: enum DistType {L1Dist = 0, L2Dist}; explicit BruteForceMatcher_GPU_base(DistType distType = L2Dist); // Add descriptors to train descriptor collection. void add(const std::vector<GpuMat>& descCollection); // Get train descriptors collection. const std::vector<GpuMat>& getTrainDescriptors() const; // Clear train descriptors collection. void clear(); // Return true if there are not train descriptors in collection. bool empty() const; // Return true if the matcher supports mask in match methods. bool isMaskSupported() const; // Find one best match for each query descriptor. // trainIdx.at<int>(0, queryIdx) will contain best train index for queryIdx // distance.at<float>(0, queryIdx) will contain distance void matchSingle(const GpuMat& queryDescs, const GpuMat& trainDescs, GpuMat& trainIdx, GpuMat& distance, const GpuMat& mask = GpuMat()); // Download trainIdx and distance to CPU vector with DMatch static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector<DMatch>& matches); // Find one best match for each query descriptor. void match(const GpuMat& queryDescs, const GpuMat& trainDescs, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat()); // Make gpu collection of trains and masks in suitable format for matchCollection function void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const vector<GpuMat>& masks = std::vector<GpuMat>()); // Find one best match from train collection for each query descriptor. // trainIdx.at<int>(0, queryIdx) will contain best train index for queryIdx // imgIdx.at<int>(0, queryIdx) will contain best image index for queryIdx // distance.at<float>(0, queryIdx) will contain distance void matchCollection(const GpuMat& queryDescs, const GpuMat& trainCollection, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, const GpuMat& maskCollection); // Download trainIdx, imgIdx and distance to CPU vector with DMatch static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector<DMatch>& matches); // Find one best match from train collection for each query descriptor. void match(const GpuMat& queryDescs, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); // Find k best matches for each query descriptor (in increasing order of distances). // trainIdx.at<int>(queryIdx, i) will contain index of i'th best trains (i < k). // distance.at<float>(queryIdx, i) will contain distance. // allDist is a buffer to store all distance between query descriptors and train descriptors // it have size (nQuery,nTrain) and CV_32F type // allDist.at<float>(queryIdx, trainIdx) will contain FLT_MAX, if trainIdx is one from k best, // otherwise it will contain distance between queryIdx and trainIdx descriptors void knnMatch(const GpuMat& queryDescs, const GpuMat& trainDescs, GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k, const GpuMat& mask = GpuMat()); // Download trainIdx and distance to CPU vector with DMatch // compactResult is used when mask is not empty. If compactResult is false matches // vector will have the same size as queryDescriptors rows. If compactResult is true // matches vector will not contain matches for fully masked out query descriptors. static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); // Find k best matches for each query descriptor (in increasing order of distances). // compactResult is used when mask is not empty. If compactResult is false matches // vector will have the same size as queryDescriptors rows. If compactResult is true // matches vector will not contain matches for fully masked out query descriptors. void knnMatch(const GpuMat& queryDescs, const GpuMat& trainDescs, std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(), bool compactResult = false); // Find k best matches for each query descriptor (in increasing order of distances). // compactResult is used when mask is not empty. If compactResult is false matches // vector will have the same size as queryDescriptors rows. If compactResult is true // matches vector will not contain matches for fully masked out query descriptors. void knnMatch(const GpuMat& queryDescs, std::vector< std::vector<DMatch> >& matches, int knn, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false ); // Find best matches for each query descriptor which have distance less than maxDistance. // nMatches.at<unsigned int>(0, queruIdx) will contain matches count for queryIdx. // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches, // because it didn't have enough memory. // trainIdx.at<int>(queruIdx, i) will contain ith train index (i < min(nMatches.at<unsigned int>(0, queruIdx), trainIdx.cols)) // distance.at<int>(queruIdx, i) will contain ith distance (i < min(nMatches.at<unsigned int>(0, queruIdx), trainIdx.cols)) // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x nTrain, // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches // Matches doesn't sorted. void radiusMatch(const GpuMat& queryDescs, const GpuMat& trainDescs, GpuMat& trainIdx, GpuMat& nMatches, GpuMat& distance, float maxDistance, const GpuMat& mask = GpuMat()); // Download trainIdx, nMatches and distance to CPU vector with DMatch. // matches will be sorted in increasing order of distances. // compactResult is used when mask is not empty. If compactResult is false matches // vector will have the same size as queryDescriptors rows. If compactResult is true // matches vector will not contain matches for fully masked out query descriptors. static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& nMatches, const GpuMat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); // Find best matches for each query descriptor which have distance less than maxDistance // in increasing order of distances). void radiusMatch(const GpuMat& queryDescs, const GpuMat& trainDescs, std::vector< std::vector<DMatch> >& matches, float maxDistance, const GpuMat& mask = GpuMat(), bool compactResult = false); // Find best matches from train collection for each query descriptor which have distance less than // maxDistance (in increasing order of distances). void radiusMatch(const GpuMat& queryDescs, std::vector< std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); private: DistType distType; std::vector<GpuMat> trainDescCollection; }; template <class Distance> class CV_EXPORTS BruteForceMatcher_GPU; template <typename T> class CV_EXPORTS BruteForceMatcher_GPU< L1<T> > : public BruteForceMatcher_GPU_base { public: explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L1Dist) {} explicit BruteForceMatcher_GPU(L1<T> /*d*/) : BruteForceMatcher_GPU_base(L1Dist) {} }; template <typename T> class CV_EXPORTS BruteForceMatcher_GPU< L2<T> > : public BruteForceMatcher_GPU_base { public: explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L2Dist) {} explicit BruteForceMatcher_GPU(L2<T> /*d*/) : BruteForceMatcher_GPU_base(L2Dist) {} }; ////////////////////////////////// CascadeClassifier_GPU ////////////////////////////////////////// // The cascade classifier class for object detection. class CV_EXPORTS CascadeClassifier_GPU { public: CascadeClassifier_GPU(); CascadeClassifier_GPU(const string& filename); ~CascadeClassifier_GPU(); bool empty() const; bool load(const string& filename); void release(); /* returns number of detected objects */ int detectMultiScale( const GpuMat& image, GpuMat& objectsBuf, double scaleFactor=1.2, int minNeighbors=4, Size minSize=Size()); bool findLargestObject; bool visualizeInPlace; Size getClassifierSize() const; private: struct CascadeClassifierImpl; CascadeClassifierImpl* impl; }; ////////////////////////////////// SURF ////////////////////////////////////////// class CV_EXPORTS SURF_GPU : public CvSURFParams { public: //! the default constructor SURF_GPU(); //! the full constructor taking all the necessary parameters explicit SURF_GPU(double _hessianThreshold, int _nOctaves=4, int _nOctaveLayers=2, bool _extended=false, float _keypointsRatio=0.01f, bool _upright = false); //! returns the descriptor size in float's (64 or 128) int descriptorSize() const; //! upload host keypoints to device memory void uploadKeypoints(const vector<KeyPoint>& keypoints, GpuMat& keypointsGPU); //! download keypoints from device to host memory void downloadKeypoints(const GpuMat& keypointsGPU, vector<KeyPoint>& keypoints); //! download descriptors from device to host memory void downloadDescriptors(const GpuMat& descriptorsGPU, vector<float>& descriptors); //! finds the keypoints using fast hessian detector used in SURF //! supports CV_8UC1 images //! keypoints will have 1 row and type CV_32FC(6) //! keypoints.at<float[6]>(1, i) contains i'th keypoint //! format: (x, y, laplacian, size, dir, hessian) void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints); //! finds the keypoints and computes their descriptors. //! Optionally it can compute descriptors for the user-provided keypoints and recompute keypoints direction void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors, bool useProvidedKeypoints = false); void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints); void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors, bool useProvidedKeypoints = false); void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, std::vector<float>& descriptors, bool useProvidedKeypoints = false); //! max keypoints = keypointsRatio * img.size().area() float keypointsRatio; bool upright; GpuMat sum, mask1, maskSum, intBuffer; GpuMat det, trace; GpuMat maxPosBuffer; GpuMat featuresBuffer; GpuMat keypointsBuffer; }; } //! Speckle filtering - filters small connected components on diparity image. //! It sets pixel (x,y) to newVal if it coresponds to small CC with size < maxSpeckleSize. //! Threshold for border between CC is diffThreshold; CV_EXPORTS void filterSpeckles( Mat& img, uchar newVal, int maxSpeckleSize, uchar diffThreshold, Mat& buf); } #include "opencv2/gpu/matrix_operations.hpp" #endif /* __OPENCV_GPU_HPP__ */
[ "[email protected]", "yangmu@localhost.(none)" ]
[ [ [ 1, 50 ], [ 52, 62 ], [ 64, 66 ], [ 122, 122 ], [ 146, 146 ], [ 162, 165 ], [ 167, 336 ], [ 344, 444 ], [ 447, 458 ], [ 460, 461 ], [ 463, 536 ], [ 587, 605 ], [ 625, 633 ], [ 635, 637 ], [ 639, 640 ], [ 642, 651 ], [ 653, 653 ], [ 655, 665 ], [ 670, 689 ], [ 691, 692 ], [ 701, 703 ], [ 713, 718 ], [ 725, 725 ], [ 727, 731 ], [ 875, 897 ], [ 899, 911 ], [ 913, 937 ], [ 939, 940 ], [ 943, 956 ], [ 958, 963 ], [ 965, 967 ], [ 969, 972 ], [ 974, 976 ], [ 978, 979 ], [ 1001, 1002 ], [ 1006, 1007 ], [ 1010, 1011 ], [ 1014, 1040 ], [ 1043, 1044 ], [ 1047, 1048 ], [ 1051, 1052 ], [ 1055, 1093 ], [ 1095, 1149 ], [ 1151, 1189 ], [ 1191, 1255 ], [ 1257, 1302 ], [ 1307, 1313 ], [ 1321, 1321 ], [ 1329, 1338 ], [ 1340, 1344 ], [ 1348, 1355 ], [ 1357, 1362 ], [ 1366, 1366 ], [ 1594, 1603 ] ], [ [ 51, 51 ], [ 63, 63 ], [ 67, 121 ], [ 123, 145 ], [ 147, 161 ], [ 166, 166 ], [ 337, 343 ], [ 445, 446 ], [ 459, 459 ], [ 462, 462 ], [ 537, 586 ], [ 606, 624 ], [ 634, 634 ], [ 638, 638 ], [ 641, 641 ], [ 652, 652 ], [ 654, 654 ], [ 666, 669 ], [ 690, 690 ], [ 693, 700 ], [ 704, 712 ], [ 719, 724 ], [ 726, 726 ], [ 732, 874 ], [ 898, 898 ], [ 912, 912 ], [ 938, 938 ], [ 941, 942 ], [ 957, 957 ], [ 964, 964 ], [ 968, 968 ], [ 973, 973 ], [ 977, 977 ], [ 980, 1000 ], [ 1003, 1005 ], [ 1008, 1009 ], [ 1012, 1013 ], [ 1041, 1042 ], [ 1045, 1046 ], [ 1049, 1050 ], [ 1053, 1054 ], [ 1094, 1094 ], [ 1150, 1150 ], [ 1190, 1190 ], [ 1256, 1256 ], [ 1303, 1306 ], [ 1314, 1320 ], [ 1322, 1328 ], [ 1339, 1339 ], [ 1345, 1347 ], [ 1356, 1356 ], [ 1363, 1365 ], [ 1367, 1593 ] ] ]
9ed319461c0fc993309cd15aa058317578836fa4
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/ItemData.h
6ec2cac485edadba408b86cc0425007ace1b6735
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
GB18030
C++
false
false
15,101
h
#pragma once #include "GameObj.h" #include "ItemType.h" const int MAX_INTIMACY = 255; enum // 附加属性类型枚举 { _SPRITE_ADDITION_PATK = 0, // 火元素精灵--增加物理攻击力 _SPRITE_ADDITION_PDEF = 1, // 土元素精灵--增加物理防御力 _SPRITE_ADDITION_MATK = 2, // 风元素精灵--增加魔法攻击力 _SPRITE_ADDITION_MDEF = 3, // 水元素精灵--增加魔法防御力 _SPRITE_ADDITION_SOUL = 4, // 暗元素精灵--增加精神 }; enum ITEMDATA{ ITEMDATA_ID_=0, // use for insert ITEMDATA_TYPE=1, ITEMDATA_OWNERID, ITEMDATA_PLAYERID, ITEMDATA_AMOUNT, //ITEMDATA_EXP = ITEMDATA_AMOUNT, // 精灵经验 -- 复用表示幻兽亲密度 ITEMDATA_AMOUNTLIMIT, //ITEMDATA_ATTRIB = ITEMDATA_AMOUNTLIMIT, // 精灵附加属性 ATTRIB100 -- 幻兽等级 ITEMDATA_IDENT, ITEMDATA_POSITION, ITEMDATA_GEM1, ITEMDATA_GEM2, ITEMDATA_MAGIC1, ITEMDATA_MAGIC2, ITEMDATA_LUCK = ITEMDATA_MAGIC2, // 幸运 ITEMDATA_MAGIC3, ITEMDATA_ADDITION = ITEMDATA_MAGIC3, // 追加 ITEMDATA_DATA, //ITEMDATA_GROWTH = ITEMDATA_DATA, // 精灵成长率 -- 幻兽成长率系数 //---jinggy---2004-11-19---圣战魔域---铸造系统需求增加的字段---begin ITEMDATA_WARGHOSTEXP, //圣战中的战魂经验值 // 复用表示幻兽生命值 ITEMDATA_GEMTYPE, //圣战中的技能(注入不同状态攻击类宝石实现) // 幻兽经验 ITEMDATA_AVAILABLETIME, //---jinggy---2004-11-19---圣战魔域---铸造系统需求增加的字段---end ///////////////////////////////////// ITEMDATA_INTIMACY=80, //? for mount, NOTE: no this field // for sprite -- add by zlong 2003-12-05 ITEMDATA_EXP = 90, // --> 幻兽经验 ITEMDATA_ATTRIB = 91, ITEMDATA_EUDEMON_LEVEL = 91, // --> 幻兽等级 ITEMDATA_GROWTH = 92, // --> 幻兽成长率系数 ITEMDATA_EUDEMON_LIFE = 93, // 幻兽生命 ITEMDATA_FIDELITY = 94, // 幻兽亲密度 ITEMTYPEDATA_OFFSET=100, // 控制量,请勿使用 ITEMDATA_NAME=101, ITEMDATA_REQ_PROF, // 职业需求 ITEMDATA_LEVEL, ITEMDATA_REQ_LEVEL, // 等级需求 ITEMDATA_SPRITE_LEVEL ITEMDATA_REQ_SEX, // 性别需求 ITEMDATA_REQ_FORCE, // 力量需求 ITEMDATA_REQ_DEX, // 敏捷需求 ITEMDATA_REQ_HEALTH, // 耐力需求 ITEMDATA_REQ_SOUL, // 精神需求 ITEMDATA_MONOPOLY, ITEMDATA_WEIGHT_, // no immediacy ITEMDATA_PRICE, ITEMDATA_ACTION, ITEMDATA_ATTACK_MAX_, //ITEMDATA_GROWTH_ORIGINAL ITEMDATA_ATTACK_MIN_, //ITEMDATA_LEVEXP ITEMDATA_DEFENSE_, ITEMDATA_MAGICATK_MIN_, ITEMDATA_DODGE, // ITEMDATA_ADD_SOUL = ITEMDATA_DODGE, ITEMDATA_LIFE, ITEMDATA_MANA, ITEMDATA_AMOUNT_ORIGINAL, ITEMDATA_AMOUNTLIMIT_ORIGINAL, ITEMDATA_IDENT_ORIGINAL, ITEMDATA_GEM1_ORIGINAL, ITEMDATA_GEM2_ORIGINAL, ITEMDATA_MAGIC1_ORIGINAL, ITEMDATA_MAGIC2_ORIGINAL, ITEMDATA_MAGIC3_ORIGINAL, ITEMDATA_MAGICATK_MAX_, ITEMDATA_MAGICDEF_, ITEMDATA_ATKRANGE, ITEMDATA_ATKSPEED, ITEMDATA_HITRATE, // 命中率 ITEMDATA_MONSTERTYPE, // 幻兽类型id ITEMDATA_TARGET, ITEMDATA_SPRITE_LEVEL = 200, // 精灵等级 装备精灵的玩家的等级必须不能少于精灵的等级×2。 ITEMDATA_GROWTH_ORIGINAL = 201, // 精灵原始成长率 ITEMDATA_LEVEXP = 202, // 精灵升级到下一级需要的经验值 }; // ITEMDATA_MONOPOLY, const DWORD MONOPOLY_MASK = 0x01; const DWORD STORAGE_MASK = 0x02; const DWORD DROP_HINT_MASK = 0x04; const DWORD SELL_HINT_MASK = 0x08; const DWORD NEVER_DROP_WHEN_DEAD_MASK = 0x10; const DWORD SELL_DISABLE_MASK = 0x20; const int MAGIC_NONE = 0; const int GEM_NONE = 0; const int GEM_HOLE = 255; // 物品大的分类 const int ITEMSORT_INVALID = -1; const int ITEMSORT_EXPEND = 10; // 易耗品 const int IETMSORT_FINERY = 1; // 服饰 const int ITEMSORT_WEAPON1 = 4; // 单手武器(武器) const int ITEMSORT_MOUNT = 6; // 坐骑 const int ITEMSORT_OTHER = 7; // 其他, 不能直接使用 // 以下分类已经不使用 const int ITEMSORT_WEAPON2 = -1;//5; // 双手武器 const int ITEMSORT_SHIELD = -1;//9; // 盾牌 // ITEMSORT_FINERY 类别物品 const int ITEMTYPE_HELMET = 10000; // 头盔 const int ITEMTYPE_NECKLACE = 20000; // 项链 const int ITEMTYPE_ARMOR = 30000; // 盔甲 const int ITEMTYPE_BANGLE = 40000; // 手镯 const int ITEMTYPE_MANTLE = 50000; // 披风 const int ITEMTYPE_SHOES = 60000; // 鞋子 // 以下分类已经不使用 const int ITEMTYPE_RING = -1;//50000; // 戒指 // ITEMSORT_EXPEND 类别物品 const int ITEMTYPE_INVALID = -1; // 非法 const int ITEMTYPE_PHYSIC = 10000;//药品 const int ITEMTYPE_MEDICINE_HP = 10000;//补血药 const int ITEMTYPE_MEDICINE_MP = 11000;//补魔法药 const int ITEMTYPE_POISON = 12000;//毒药 const int ITEMTYPE_SCROLL = 20000;//卷轴 const int ITEMTYPE_SCROLL_SPECIAL = 20000;//特殊卷轴,如:回城卷、祝福卷轴等 const int ITEMTYPE_SCROLL_MSKILL = 21000;//魔法师技能卷轴 const int ITEMTYPE_SCROLL_SSKILL = 22000;//战士技能卷轴 const int ITEMTYPE_SCROLL_BSKILL = 23000;//弓箭手技能卷轴 <== 改为异能者 const int ITEMTYPE_GHOSTGEM = 30000; // 魔魂宝石 const int ITEMTYPE_GHOSTGEM_ACTIVE_ATK = 31000; // 状态攻击类 const int ITEMTYPE_GHOSTGEM_PASSIVE_ATK = 32000; // 状态被动类 const int ITEMTYPE_GHOSTGEM_EUDEMON = 33000; // 幻兽类 const int ITEMTYPE_GHOSTGEM_RELEASE = 34000; // 解除类 const int ITEMTYPE_GHOSTGEM_TRACE = 35000; // 追杀类 const int ITEMTYPE_GHOSTGEM_PROTECTIVE = 36000; // 护身类 const int ITEMTYPE_GHOSTGEM_SPECIAL = 37000; // 特殊类 const int ITEMTYPE_GHOSTGEM_EMBEDEQUIP = 38000; // 用于嵌入装备的宝石---jinggy //---jinggy 2004-11-9 --begin---圣战铸造系统用到的 const int ITEMTYPE_GHOSTGEM_FORQUALITY = 1037160; //提高装备品质的宝石 (灵魂晶石) const int ITEMTYPE_GHOSTGEM_FORGHOSTLEVEL = 1037150;//升级装备魔魂等级的宝石 const int ITEMTYPE_GHOSTGEM_UPGRADE_EQUIPLEVEL = 1037170;//幻魔晶石(幻魔晶石type:1037170)来升级武器或装备的等级。 //---jinggy 2004-11-9 --end---圣战铸造系统用到的 const int ITEMTYPE_NOT_DIRECTUSE = 40000;//不可以双击使用的 -- 木材、矿石等资源类 //=================================== const int ITEMTYPE_SPECIAL_USE = 50000; // 大于此编号以上的为其他用途的物品 const int ITEMTYPE_SPRITE = 50000;// 精灵 const int ITEMTYPE_SPRITE_PATK = 50000;// 火元素精灵--增加物理攻击力 const int ITEMTYPE_SPRITE_PDEF = 51000;// 土元素精灵--增加物理防御力 const int ITEMTYPE_SPRITE_MATK = 52000;// 风元素精灵--增加魔法攻击力 const int ITEMTYPE_SPRITE_MDEF = 53000;// 水元素精灵--增加魔法防御力 const int ITEMTYPE_SPRITE_SOUL = 54000;// 暗元素精灵--增加精神 const int ITEMTYPE_SPECIAL = 60000;//特殊物品 const int ITEMTYPE_SPECIAL_VALUABLES = 60000;//特殊贵重物品。如异次元袋 const int ITEMTYPE_SPECIAL_UNREPAIRABLE = 61000;//不可修复的贵重物品 // 幻兽 -- zlong 2004-02-03 const int ITEMTYPE_EUDEMON = 70000; //幻兽 const int ITEMTYPE_EUDEMON_SPEED = 71000; // 速度型 const int ITEMTYPE_EUDEMON_PATK = 72000; // 攻击型 const int ITEMTYPE_EUDEMON_DEF = 73000; // 防御型 const int ITEMTYPE_EUDEMON_MATK = 74000; // 魔法攻击型 const int ITEMTYPE_EUDEMON_BOMB = 75000; // 爆破型 const int ITEMTYPE_EUDEMON_PROTECTIVE = 76000; // 保护型 const int ITEMTYPE_EUDEMON_ATTACH = 77000; // 附身型 const int ITEMTYPE_EUDEMON_VARIATIONAL = 78000; // 变异型 const int ITEMTYPE_EUDEMON_EGG = 80000; // 幻兽蛋 //=================================== /* const int ITEMTYPE_MEDICINE = 00000;// 补药 const int ITEMTYPE_POISON = 10000;// 毒药 const int ITEMTYPE_DART = 20000;// 矢 const int ITEMTYPE_BOOK = 30000;// 秘笈 const int ITEMTYPE_NOTUSE = 40000;// 不用 const int ITEMTYPE_ARROW = 50000;// 箭 const int ITEMTYPE_SPELL = 60000;// 符咒类 const int ITEMTYPE_NOT_DIRECTUSE = 70000;// 不可以双击使用的(如任务物品,宝石,木材等资源类,千位继续分类) const int ITEMTYPE_EX0 = 80000;// 扩展0 const int ITEMTYPE_EX1 = 90000;// 扩展1 */ // ITEMSORT_OTHER 类别物品 const int ITEMTYPE_GEM = 00000;// 宝石物品 const int ITEMTYPE_TASKITEM = 10000;// 任务物品 const int ITEMTYPE_ACTIONITEM = 20000;// Action物品 const int ITEMTYPE_GAMECARD = 80000;// 点卡,月卡 /*///////////////////////////////////////////////////////////////////// //2003-01-13 10:36:24 黄宇航 // Necklace type define const int ITEMTYPE_NECKLACE = 00000;// 项链 const int ITEMTYPE_SACHET = 10000;// 香袋 const int ITEMTYPE_AMULET = 20000;// 护身符 //2003-01-13 10:46:37 黄宇航 // Ring type define const int ITEMTYPE_RING = 00000;// 戒指 const int ITEMTYPE_THUMB_RING = 10000;// 扳指 const int ITEMTYPE_BANGLE = 20000;// 手镯 //2003-01-13 11:05:03 黄宇航 // Singlehand Weapon define const int SWEAPON_NONE = 00000;// 空手 const int SWEAPON_BLADE = 10000;// 刀 const int SWEAPON_AXE = 20000;// 斧 const int SWEAPON_HAMMER = 30000;// 锤 const int SWEAPON_HOOK = 40000;// 钩 const int SWEAPON_CLUB = 50000;// 棒/杵 const int SWEAPON_SWORD = 60000;// 剑 const int SWEAPON_CRUTCH = 70000;// 拐 const int SWEAPON_SCOURGE = 80000;// 鞭/锏 const int SWEAPON_SHORT = 90000;// 短兵器 */ // Doublehand Weapon define const int DWEAPON_BOW = 00000;// 弓 const int DWEAPON_CROSSBOW = 1000;// 弩 const int DWEAPON_BLADE = 10000;// 刀 const int DWEAPON_AXE = 20000;// 斧 const int DWEAPON_HAMMER = 30000;// 锤 const int DWEAPON_HOOK = 40000;// 钩 const int DWEAPON_STAFF = 50000;// 棍 const int DWEAPON_SHOVEL = 60000;// 铲 const int DWEAPON_HALBERD = 70000;// 戟 const int DWEAPON_FORK = 80000;// 叉 const int DWEAPON_SPEAR = 90000;// 枪 // add by zlong 2003-12-01 const int MAX_SPRITE_GROWTH = 500; // 精灵的最大成长率*100 const int MAX_SOUL_SPRITE_GROWTH = 200; // 加精神的精灵最大成长率*100 const int EUDEMON_DEC_FIDELITY_WHEN_DIE = 10; // 幻兽死亡扣10点亲密度 const int EUDEMON_DEC_FIDELITY_WHEN_DEAL = 30; // 幻兽转手要扣30点亲密度 //const int ITEMPOSITION_BACKPACK = 0; // 普通物品背包 //const int ITEMPOSITION_NONE = 0; const int ITEMPOSITION_EQUIPBEGIN = 1; const int ITEMPOSITION_HELMET = 1; // 头盔 const int ITEMPOSITION_NECKLACE = 2; // 项链 const int ITEMPOSITION_ARMOR = 3; // 铠甲 const int ITEMPOSITION_WEAPONR = 4; // 武器 const int ITEMPOSITION_WEAPONL = 5; const int ITEMPOSITION_RINGR = 6; const int ITEMPOSITION_RINGL = 7; // 手镯 const int ITEMPOSITION_SHOES = 8; // 鞋子 const int ITEMPOSITION_MOUNT = 9; const int ITEMPOSITION_SPRITE = 10; // 精灵 -- add by zlong 2003-11-27 const int ITEMPOSITION_MANTLE = 11; // 披风 -- zlong 2004-02-04 const int ITEMPOSITION_EQUIPEND = 12; const int ITEMPOSITION_PACK_BEGIN = 50; const int ITEMPOSITION_BACKPACK = 50; // 普通物品背包 const int ITEMPOSITION_GHOSTGEM_PACK = 51; // 魔魂宝石背包 const int ITEMPOSITION_EUDEMONEGG_PACK = 52; // 幻兽蛋背包 const int ITEMPOSITION_EUDEMON_PACK = 53; // 幻兽背包 const int ITEMPOSITION_PACK_END = 54; const int ITEMPOSITION_PACK_LIMIT = 70; const int ITEMPOSITION_USER_LIMIT = 199; const int ITEMPOSITION_STORAGE = 201; const int ITEMPOSITION_TRUNK = 202; const int ITEMPOSITION_CHEST = 203; const int ITEMPOSITION_PLAYERTASK = 204; // 佣兵任务奖品 const int ITEMPOSITION_EUDEMON_BROODER = 205; // 幻兽孵化器 const int ITEMPOSITION_EUDEMON_STORAGE = 206; // 幻兽存储仓库 const int ITEMPOSITION_AUCTION_STORAGE = 207; // Npc拍买仓库(玩家物品) const int ITEMPOSITION_AUCTION_SYS_STORAGE= 208; // Npc拍买仓库(系统物品) const int ITEMPOSITION_GROUND = 254; // 不存数据库 const int ITEMPOSITION_NONE = 255; // 非法位置 char szItemTable[]; typedef CGameData<ITEMDATA,szItemTable,szID> CGameItemData; enum EUDEMONDATA{ EUDEMONDATA_ID = 0, // 幻兽ID EUDEMONDATA_OWNERID, // 幻兽物品ID EUDEMONDATA_NAME, // 幻兽名字 EUDEMONDATA_RELATIONSHIP, // 与其它幻兽关系 }; char szEudemonTable[]; typedef CGameData<EUDEMONDATA, szEudemonTable, szID> CEudemonData; #include "T_SingleObjSet2.h" #include "T_SingleMap2.h" #include "UserTable.h" #include "ItemAddition.h" class IDatabase; class IRecord; class IRecordset; class CItemData : public CGameObj { protected: CItemData(); virtual ~CItemData(); public: bool Create (IRecord* pDefault, const ItemInfoStruct* pInfo, IRecord* pDefaultEudemonData, bool bInsert=true, OBJID idNew=ID_NONE); // false: 不存数据库 bool Create (IRecord* pDefault, OBJID idType, OBJID idUser, int nPosition, IRecord* pDefaultEudemonData=NULL); bool Create (OBJID idItem, IDatabase* pDb); bool Create (IRecordset* pRes, IDatabase* pDb); bool DeleteRecord (); static bool DeleteItemRecord (OBJID id, IDatabase* pDb); public: // info bool GetInfo (ItemInfoStruct* pInfo); bool SaveInfo (void); public: // get set OBJID GetID() { return m_pData->GetKey(); } int GetInt(ITEMDATA idx); LPCTSTR GetStr(ITEMDATA idx); void SetInt(ITEMDATA idx, int nData, bool bUpdate = false); void SetStr(ITEMDATA idx, LPCTSTR szData, int nSize, bool bUpdate = false); protected: bool IsMount() { return ((m_pData->GetInt(ITEMDATA_TYPE)%10000000)/100000) == ITEMSORT_MOUNT; } // 用于GEM1和INTIMACY分类处理 bool IsSprite() { return ((m_pData->GetInt(ITEMDATA_TYPE)%10000000)/100000) == ITEMSORT_EXPEND && ((m_pData->GetInt(ITEMDATA_TYPE)%100000)/10000)*10000 == ITEMTYPE_SPRITE; } bool IsEudemon() { return ((m_pData->GetInt(ITEMDATA_TYPE)%10000000)/100000) == ITEMSORT_EXPEND && ((m_pData->GetInt(ITEMDATA_TYPE)%100000)/10000)*10000 == ITEMTYPE_EUDEMON; } bool IsEudemonEgg() { return ((m_pData->GetInt(ITEMDATA_TYPE)%10000000)/100000) == ITEMSORT_EXPEND && ((m_pData->GetInt(ITEMDATA_TYPE)%100000)/10000)*10000 == ITEMTYPE_EUDEMON_EGG; } bool LoadEudemonData(OBJID idOwner, IDatabase* pDb); public: bool CreateEudemonData(IRecord* pDefaultData, OBJID idOwner, const char* pszName, bool bInsert=true); protected: // data & type CGameItemData* m_pData; CItemTypeData* m_pType; // CMonsterTypeData* m_pEudemonType; // 幻兽类型数据引用 -- zlong 2004-02-05 // 追加属性——允许为NULL CItemAdditionData* m_pAddition; CEudemonData* m_pEudemonData; // 幻兽数据 };
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 371 ] ] ]
574d63b01ab3d6dcacaddfa93124fe4cce5b626c
3920e5fc5cbc2512701a3d2f52e072fd50debb83
/Source/Common/itkManagedImageFunction.cxx
d7d80628ea44d0874a306510078b1c09b3e3868f
[ "MIT" ]
permissive
amirsalah/manageditk
4063a37d7370dcbcd08bfe9d24d22015d226ceaf
1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761
refs/heads/master
2016-08-12T05:38:03.377086
2010-08-02T08:17:32
2010-08-02T08:17:32
52,595,294
0
0
null
null
null
null
UTF-8
C++
false
false
4,361
cxx
/*============================================================================= NOTE: THIS FILE IS A HANDMADE WRAPPER FOR THE ManagedITK PROJECT. Project: ManagedITK Program: Insight Segmentation & Registration Toolkit Module: itkManagedImageFunction.cxx Language: C++/CLI Author: Dan Mueller Date: $Date: 2008-06-21 09:20:09 +0200 (Sat, 21 Jun 2008) $ Revision: $Revision: 18 $ Portions of this code are covered under the ITK and VTK copyright. See http://www.itk.org/HTML/Copyright.htm for details. See http://www.vtk.org/copyright.php for details. Copyright (c) 2007-2008 Daniel Mueller Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================*/ #pragma once #pragma warning( disable : 4635 ) // Disable warnings about XML doc comments #ifndef __itkManagedImageFunction_cxx #define __itkManagedImageFunction_cxx // Use some managed namespaces #using <mscorlib.dll> #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Reflection; using namespace System::Diagnostics; using namespace System::Collections::Generic; // Include some useful ManagedITK files #include "itkManagedIndex.cxx" #include "itkManagedContinuousIndex.cxx" #include "itkManagedPoint.cxx" #include "itkManagedOffset.cxx" #include "itkManagedPixelType.cxx" #include "itkManagedPixel.cxx" #include "itkManagedImage.cxx" namespace itk { ///<summary> ///This class is a managed replacement for itk::ImageFunction. ///</summary> ///<remarks> ///ImageFunction is a baseclass for all objects that evaluates ///a function of an image at index, continuous index or point. ///</remarks> public ref class itkImageFunction abstract : itkObject { public: ///<summary>Set the input image to the function object.</summary> ///<param name="inputImage">The input image as an itkImage.</param> virtual void SetInputImage(itkImageBase^ inputImage) = 0; ///<summary>Set the input image to the function object.</summary> ///<param name="itkInputImagePtr">The input image as an IntPtr.</param> virtual void SetInputImage( IntPtr itkInputImagePtr ) = 0; /** Get the input image to the function object. */ // TODO: virtual itkImage^ GetInputImage( ) = 0; ///<summary>Evaluate the function at specified physical location.</summary> ///<param name="point">The geometric location in physical space.</param> ///<returns>The pixel value at the given physical location.</returns> virtual itkPixel^ Evaluate( itkPoint^ point ) = 0; ///<summary>Evaluate the function at specified discrete location.</summary> ///<param name="index">The discrete location in image space.</param> ///<returns>The pixel value at the given discrete location.</returns> virtual itkPixel^ EvaluateAtIndex( itkIndex^ index ) = 0; ///<summary>Evaluate the function at specified continuous location.</summary> ///<param name="cindex">The continuous location in image space.</param> ///<returns>The pixel value at the given continuous location.</returns> virtual itkPixel^ EvaluateAtContinuousIndex( itkContinuousIndex^ cindex ) = 0; }; // end ref class } // end namespace itk #endif
[ "dan.muel@a4e08166-d753-0410-af4e-431cb8890a25" ]
[ [ [ 1, 107 ] ] ]
dcabeccb1b3845a6c09f6bea9aee6a7ef87cd8dd
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/act/shrimp_client_t.hpp
e9273dba08804101680f32d49cf3afda70aa8143
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
850
hpp
#ifndef shrimp_client_t_H_INCLUDED #define shrimp_client_t_H_INCLUDED #include <alcor/core/client_base_t.hpp> #include <alcor/core/iniWrapper.h> #include <alcor/math/angle.h> #include "shrimp_server_data_t.hpp" namespace all { namespace act { class shrimp_client_t : public client_base_t { public: shrimp_client_t(char* ini_file = "config/shrimp_client.ini"); void set_robot_on(); void set_robot_standby(); void em_stop(); void em_release(); void set_speed(int); void set_steer(all::math::angle); int get_speed(); all::math::angle get_steer(); bool is_on(); bool is_em(); double get_voltage(); private: void update_shrimp_data(net_packet_ptr_t); void connected_cb(); private: iniWrapper m_ini_config; shrimp_server_data_t m_shrimp_data; }; }} //namespaces #endif
[ "stefano.marra@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 50 ] ] ]
b8fad9a2988fb83dad7251ccb0d0d55af56bbb51
d6eba554d0c3db3b2252ad34ffce74669fa49c58
/Source/Helpers/criticalSection.h
b2c97f30384ec18b2e71a8a6132c8ba98c0f2e60
[]
no_license
nbucciarelli/Polarity-Shift
e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10
8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017
refs/heads/master
2016-09-11T00:24:32.906933
2008-09-26T18:01:01
2008-09-26T18:01:01
3,408,115
1
0
null
null
null
null
UTF-8
C++
false
false
3,141
h
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // File: "criticalSelection.h" // Author: Scott Smallback (SS) // Purpose: Handles the selection of the magnet gun // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <vector> class criticalSectionControl { protected: struct criticalSection { volatile bool locked; bool active; }; std::vector<criticalSection*> criticals; //Singleton protection criticalSectionControl(); criticalSectionControl(const criticalSectionControl&); criticalSectionControl& operator=(const criticalSectionControl&); ~criticalSectionControl(); public: static criticalSectionControl* getInstance(); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "getCriticalSelection" // Last Modified: September 22, 2008 // Purpose: returns the value of the selected object ////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int getCriticalSection(); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "releaseCriticalSelection" // Last Modified: September 22, 2008 // Purpose: releases selected object ////////////////////////////////////////////////////////////////////////////////////////////////////// void releaseCriticalSection(unsigned int id); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "lockSection" // Last Modified: September 22, 2008 // Purpose: When clicked, it locks the object to the magnet gun ////////////////////////////////////////////////////////////////////////////////////////////////////// void lockSection(unsigned int id); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "unlockSelection" // Last Modified: September 22, 2008 // Purpose: when mouse is released it will unlock the object from the gun ////////////////////////////////////////////////////////////////////////////////////////////////////// void unlockSection(unsigned int id); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "isLocked" // Last Modified: September 22, 2008 // Purpose: checks to see if the object is locked ////////////////////////////////////////////////////////////////////////////////////////////////////// bool isLocked(unsigned int id); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "waitForUnlock" // Last Modified: September 22, 2008 // Purpose: waits for the unlocking of the object ////////////////////////////////////////////////////////////////////////////////////////////////////// void waitForUnlock(unsigned int id); };
[ [ [ 1, 69 ] ] ]
6e3f4a035f96b868179a9c1d87534ed8157beeee
62a5260bf242add996041111c92a795f2e5a4e8b
/gframe/event_handler.cpp
fbbb1cd585ced8bc65794f7667104152e61825de
[]
no_license
zh99998/ygocore
cc0d1f8d628ab37e5217aed543966f775d93a8d4
362daff35e17ea338b8873b9cc1ab8ee10bc2c7f
refs/heads/master
2021-01-22T05:24:24.120543
2011-11-27T13:21:34
2011-11-27T13:21:34
3,000,435
6
1
null
null
null
null
UTF-8
C++
false
false
57,140
cpp
#include "client_field.h" #include "math.h" #include "network.h" #include "game.h" #include "tracking.h" extern ygo::Game* mainGame; namespace ygo { bool ClientField::OnEvent(const irr::SEvent& event) { switch(event.EventType) { case irr::EET_GUI_EVENT: { s32 id = event.GUIEvent.Caller->getID(); irr::gui::IGUIEnvironment* env = device->getGUIEnvironment(); switch(event.GUIEvent.EventType) { case irr::gui::EGET_BUTTON_CLICKED: { switch(id) { case BUTTON_CLEAR_LOG: { mainGame->lstLog->clear(); break; } case BUTTON_MODE_EXIT: { mainGame->netManager.CancelHost(); mainGame->device->closeDevice(); break; } case BUTTON_LAN_START_SERVER: { if(mainGame->cbDeckSel->getSelected() == -1) break; if(!mainGame->deckManager.LoadDeck(mainGame->cbDeckSel->getItem(mainGame->cbDeckSel->getSelected()))) { mainGame->stModeStatus->setText(L"无效卡组"); break; } if(!mainGame->chkNoCheckDeck->isChecked() && !mainGame->deckManager.CheckLFList(mainGame->deckManager.deckhost, mainGame->cbLFlist->getSelected())) { mainGame->stModeStatus->setText(L"无效卡组或者卡组不符合禁卡表规范"); break; } if(_wtoi(mainGame->ebStartLP->getText()) == 0) mainGame->ebStartLP->setText(L"8000"); if(_wtoi(mainGame->ebStartHand->getText()) == 0) mainGame->ebStartLP->setText(L"5"); if(_wtoi(mainGame->ebDrawCount->getText()) == 0) mainGame->ebStartLP->setText(L"1"); if(mainGame->netManager.CreateHost()) { mainGame->btnLanStartServer->setEnabled(false); mainGame->btnLanCancelServer->setEnabled(true); mainGame->btnLanConnect->setEnabled(false); mainGame->btnRefreshList->setEnabled(false); mainGame->btnLoadReplay->setEnabled(false); mainGame->btnDeckEdit->setEnabled(false); mainGame->stModeStatus->setText(L"等待连接..."); } break; } case BUTTON_LAN_CANCEL_SERVER: { mainGame->netManager.CancelHost(); mainGame->stModeStatus->setText(L""); break; } case BUTTON_LAN_REFRESH: { if(mainGame->netManager.RefreshHost()) { mainGame->btnLanStartServer->setEnabled(false); mainGame->btnLanConnect->setEnabled(false); mainGame->btnRefreshList->setEnabled(false); mainGame->btnLoadReplay->setEnabled(false); mainGame->btnDeckEdit->setEnabled(false); } break; } case BUTTON_LAN_CONNECT: { if(mainGame->cbDeckSel->getSelected() == -1) break; if(!mainGame->deckManager.LoadDeck(mainGame->cbDeckSel->getItem(mainGame->cbDeckSel->getSelected()))) { mainGame->stModeStatus->setText(L"无效卡组"); break; } if(mainGame->netManager.JoinHost()) { mainGame->btnLanStartServer->setEnabled(false); mainGame->btnLanConnect->setEnabled(false); mainGame->btnRefreshList->setEnabled(false); mainGame->btnLoadReplay->setEnabled(false); mainGame->btnDeckEdit->setEnabled(false); mainGame->stModeStatus->setText(L"连接中..."); } break; } case BUTTON_DECK_EDIT: { if(mainGame->cbDeckSel->getSelected() == -1) break; if(!mainGame->deckManager.LoadDeck(mainGame->cbDeckSel->getItem(mainGame->cbDeckSel->getSelected()))) { mainGame->stModeStatus->setText(L"无法载入卡组"); break; } mainGame->HideElement(mainGame->wModeSelection); mainGame->is_building = true; mainGame->wInfos->setVisible(true); mainGame->wCardImg->setVisible(true); mainGame->wDeckEdit->setVisible(true); mainGame->wFilter->setVisible(true); mainGame->deckBuilder.filterList = mainGame->deckManager._lfList[mainGame->cbLFlist->getSelected()].content;; mainGame->cbDBLFList->setSelected(mainGame->cbLFlist->getSelected()); mainGame->device->setEventReceiver(&mainGame->deckBuilder); mainGame->cbCardType->setSelected(0); mainGame->cbCardType2->setSelected(0); mainGame->cbCardClass->setSelected(0); mainGame->cbAttribute->setSelected(0); mainGame->cbRace->setSelected(0); mainGame->ebAttack->setText(L""); mainGame->ebDefence->setText(L""); mainGame->ebStar->setText(L""); mainGame->cbCardType2->setEnabled(false); mainGame->cbAttribute->setEnabled(false); mainGame->cbRace->setEnabled(false); mainGame->ebAttack->setEnabled(false); mainGame->ebDefence->setEnabled(false); mainGame->ebStar->setEnabled(false); mainGame->deckBuilder.filter_effect = 0; mainGame->deckBuilder.result_string[0] = L'0'; mainGame->deckBuilder.result_string[1] = 0; mainGame->deckBuilder.results.clear(); mainGame->deckBuilder.is_draging = false; mainGame->cbDBDecks->setSelected(mainGame->cbDeckSel->getSelected()); for(int i = 0; i < 32; ++i) mainGame->chkCategory[i]->setChecked(false); break; } case BUTTON_LOAD_REPLAY: { if(mainGame->lstReplayList->getSelected() == -1) break; if(!mainGame->lastReplay.OpenReplay(mainGame->lstReplayList->getListItem(mainGame->lstReplayList->getSelected()))) { mainGame->stModeStatus->setText(L"录像损坏或丢失,无法播放"); break; } mainGame->stModeStatus->setText(L""); Thread::NewThread(Game::ReplayThread, &mainGame->dInfo); break; } case BUTTON_REPLAY_START: { if(!mainGame->dField.is_replaying) break; is_pausing = false; is_paused = false; mainGame->btnReplayStart->setVisible(false); mainGame->btnReplayPause->setVisible(true); mainGame->btnReplayStep->setVisible(false); mainGame->localAction.Set(); break; } case BUTTON_REPLAY_PAUSE: { if(!mainGame->dField.is_replaying) break; is_pausing = true; mainGame->btnReplayStart->setVisible(true); mainGame->btnReplayPause->setVisible(false); mainGame->btnReplayStep->setVisible(true); break; } case BUTTON_REPLAY_STEP: { if(!mainGame->dField.is_replaying) break; is_paused = false; mainGame->localAction.Set(); break; } case BUTTON_REPLAY_EXIT: { if(!mainGame->dField.is_replaying) break; mainGame->dField.is_replaying = false; mainGame->localAction.Set(); break; } case BUTTON_REPLAY_SWAP: { if(!mainGame->dField.is_replaying) break; if(is_paused) ReplaySwap(); else is_swaping = true; break; } case BUTTON_REPLAY_SAVE: { if(mainGame->ebRSName->getText()[0] == 0) break; mainGame->lastReplay.SaveReplay(mainGame->ebRSName->getText()); mainGame->HideElement(mainGame->wReplaySave, true); break; } case BUTTON_REPLAY_CANCEL: { mainGame->HideElement(mainGame->wReplaySave, true); break; } case BUTTON_MSG_OK: { mainGame->HideElement(mainGame->wMessage, true); break; } case BUTTON_YES: { switch(mainGame->dInfo.curMsg) { case MSG_SELECT_YESNO: case MSG_SELECT_EFFECTYN: { mainGame->dInfo.responseI = 1; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wQuery, true); break; } case MSG_SELECT_CHAIN: case MSG_SELECT_CARD: case MSG_SELECT_TRIBUTE: case MSG_SELECT_SUM: { mainGame->HideElement(mainGame->wQuery); break; } } mainGame->HideElement(mainGame->wQuery); break; } case BUTTON_NO: { switch(mainGame->dInfo.curMsg) { case MSG_SELECT_YESNO: case MSG_SELECT_EFFECTYN: { mainGame->dInfo.responseI = 0; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wQuery, true); break; } case MSG_SELECT_CHAIN: { mainGame->dInfo.responseI = -1; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wQuery, true); break; } case MSG_SELECT_CARD: case MSG_SELECT_TRIBUTE: case MSG_SELECT_SUM: { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->HideElement(mainGame->wQuery, true); break; } } mainGame->HideElement(mainGame->wQuery); break; } case BUTTON_POS_AU: { mainGame->dInfo.responseI = POS_FACEUP_ATTACK; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wPosSelect, true); break; } case BUTTON_POS_AD: { mainGame->dInfo.responseI = POS_FACEDOWN_ATTACK; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wPosSelect, true); break; } case BUTTON_POS_DU: { mainGame->dInfo.responseI = POS_FACEUP_DEFENCE; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wPosSelect, true); break; } case BUTTON_POS_DD: { mainGame->dInfo.responseI = POS_FACEDOWN_DEFENCE; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wPosSelect, true); break; } case BUTTON_OPTION_PREV: { selected_option--; mainGame->btnOptionn->setVisible(true); if(selected_option == 0) mainGame->btnOptionp->setVisible(false); mainGame->SetStaticText(mainGame->stOptions, 310, mainGame->textFont, (wchar_t*)mainGame->dataManager.GetDesc(select_options[selected_option])); break; } case BUTTON_OPTION_NEXT: { selected_option++; mainGame->btnOptionp->setVisible(true); if(selected_option == select_options.size() - 1) mainGame->btnOptionn->setVisible(false); mainGame->SetStaticText(mainGame->stOptions, 310, mainGame->textFont, (wchar_t*)mainGame->dataManager.GetDesc(select_options[selected_option])); break; } case BUTTON_OPTION_OK: { if (mainGame->dInfo.curMsg == MSG_SELECT_OPTION) { mainGame->dInfo.responseI = selected_option; mainGame->SetResponseI(); } else if (mainGame->dInfo.curMsg == MSG_SELECT_IDLECMD) { int index = 0; while(activatable_cards[index] != command_card || activatable_descs[index] != select_options[selected_option]) index++; mainGame->dInfo.responseI = (index << 16) + 5; mainGame->SetResponseI(); } else if (mainGame->dInfo.curMsg == MSG_SELECT_BATTLECMD) { int index = 0; while(activatable_cards[index] != command_card || activatable_descs[index] != select_options[selected_option]) index++; mainGame->dInfo.responseI = (index << 16); mainGame->SetResponseI(); } else { int index = 0; while(activatable_cards[index] != command_card || activatable_descs[index] != select_options[selected_option]) index++; mainGame->dInfo.responseI = index; mainGame->SetResponseI(); } mainGame->HideElement(mainGame->wOptions, true); break; } case BUTTON_ANNUMBER_OK: { mainGame->dInfo.responseI = mainGame->cbANNumber->getSelected(); mainGame->SetResponseI(); mainGame->HideElement(mainGame->wANNumber, true); break; } case BUTTON_ANCARD_OK: { mainGame->dInfo.responseI = _wtoi(mainGame->ebANCard->getText()); mainGame->SetResponseI(); mainGame->HideElement(mainGame->wANCard, true); break; } case BUTTON_CMD_ACTIVATE: { mainGame->wCmdMenu->setVisible(false); if(!list_command) { int index = -1; select_options.clear(); for (int i = 0; i < activatable_cards.size(); ++i) { if (activatable_cards[i] == clicked_card) { select_options.push_back(activatable_descs[i]); if (index == -1) index = i; } } if (select_options.size() == 1) { if (mainGame->dInfo.curMsg == MSG_SELECT_IDLECMD) { mainGame->dInfo.responseI = (index << 16) + 5; } else if (mainGame->dInfo.curMsg == MSG_SELECT_BATTLECMD) { mainGame->dInfo.responseI = (index << 16); } else { mainGame->dInfo.responseI = index; } mainGame->SetResponseI(); mainGame->localAction.Set(); } else { mainGame->SetStaticText(mainGame->stOptions, 310, mainGame->textFont, (wchar_t*)mainGame->dataManager.GetDesc(select_options[0])); selected_option = 0; command_card = clicked_card; mainGame->btnOptionp->setVisible(false); mainGame->btnOptionn->setVisible(true); mainGame->ShowElement(mainGame->wOptions); } } else { selectable_cards.clear(); switch(command_location) { case LOCATION_DECK: { for(int i = 0; i < deck[command_controler].size(); ++i) if(deck[command_controler][i]->cmdFlag & COMMAND_ACTIVATE) selectable_cards.push_back(deck[command_controler][i]); break; } case LOCATION_GRAVE: { for(int i = 0; i < grave[command_controler].size(); ++i) if(grave[command_controler][i]->cmdFlag & COMMAND_ACTIVATE) selectable_cards.push_back(grave[command_controler][i]); break; } case LOCATION_REMOVED: { for(int i = 0; i < remove[command_controler].size(); ++i) if(remove[command_controler][i]->cmdFlag & COMMAND_ACTIVATE) selectable_cards.push_back(remove[command_controler][i]); break; } case LOCATION_EXTRA: { for(int i = 0; i < extra[command_controler].size(); ++i) if(extra[command_controler][i]->cmdFlag & COMMAND_ACTIVATE) selectable_cards.push_back(extra[command_controler][i]); break; } } mainGame->wCardSelect->setText(L"请选择要发动效果的卡:"); list_command = COMMAND_ACTIVATE; ShowSelectCard(); } break; } case BUTTON_CMD_SUMMON: { mainGame->wCmdMenu->setVisible(false); if(!clicked_card) break; for(int i = 0; i < summonable_cards.size(); ++i) { if(summonable_cards[i] == clicked_card) { ClearCommandFlag(); mainGame->dInfo.responseI = i << 16; mainGame->SetResponseI(); mainGame->localAction.Set(); break; } } break; } case BUTTON_CMD_SPSUMMON: { mainGame->wCmdMenu->setVisible(false); if(!list_command) { if(!clicked_card) break; for(int i = 0; i < spsummonable_cards.size(); ++i) { if(spsummonable_cards[i] == clicked_card) { ClearCommandFlag(); mainGame->dInfo.responseI = (i << 16) + 1; mainGame->SetResponseI(); mainGame->localAction.Set(); break; } } } else { selectable_cards.clear(); switch(command_location) { case LOCATION_DECK: { for(int i = 0; i < deck[command_controler].size(); ++i) if(deck[command_controler][i]->cmdFlag & COMMAND_SPSUMMON) selectable_cards.push_back(deck[command_controler][i]); break; } case LOCATION_GRAVE: { for(int i = 0; i < grave[command_controler].size(); ++i) if(grave[command_controler][i]->cmdFlag & COMMAND_SPSUMMON) selectable_cards.push_back(grave[command_controler][i]); break; } case LOCATION_EXTRA: { for(int i = 0; i < extra[command_controler].size(); ++i) if(extra[command_controler][i]->cmdFlag & COMMAND_SPSUMMON) selectable_cards.push_back(extra[command_controler][i]); break; } } list_command = COMMAND_SPSUMMON; mainGame->wCardSelect->setText(L"请选择要特殊召唤的怪兽:"); ShowSelectCard(); } break; } case BUTTON_CMD_MSET: { mainGame->wCmdMenu->setVisible(false); if(!clicked_card) break; for(int i = 0; i < msetable_cards.size(); ++i) { if(msetable_cards[i] == clicked_card) { mainGame->dInfo.responseI = (i << 16) + 3; mainGame->SetResponseI(); mainGame->localAction.Set(); break; } } break; } case BUTTON_CMD_SSET: { mainGame->wCmdMenu->setVisible(false); if(!clicked_card) break; for(int i = 0; i < ssetable_cards.size(); ++i) { if(ssetable_cards[i] == clicked_card) { mainGame->dInfo.responseI = (i << 16) + 4; mainGame->SetResponseI(); mainGame->localAction.Set(); break; } } break; } case BUTTON_CMD_REPOS: { mainGame->wCmdMenu->setVisible(false); if(!clicked_card) break; for(int i = 0; i < reposable_cards.size(); ++i) { if(reposable_cards[i] == clicked_card) { mainGame->dInfo.responseI = (i << 16) + 2; mainGame->SetResponseI(); mainGame->localAction.Set(); break; } } break; } case BUTTON_CMD_ATTACK: { mainGame->wCmdMenu->setVisible(false); if(!clicked_card) break; for(int i = 0; i < attackable_cards.size(); ++i) { if(attackable_cards[i] == clicked_card) { mainGame->dInfo.responseI = (i << 16) + 1; mainGame->SetResponseI(); mainGame->localAction.Set(); break; } } break; } case BUTTON_CMD_SHOWLIST: { mainGame->wCmdMenu->setVisible(false); selectable_cards.clear(); switch(command_location) { case LOCATION_MZONE: { ClientCard* pcard = mzone[command_controler][command_sequence]; for(int i = 0; i < pcard->overlayed.size(); ++i) selectable_cards.push_back(pcard->overlayed[i]); myswprintf(formatBuffer, L"查看叠放卡:(%d)", pcard->overlayed.size()); mainGame->wCardSelect->setText(formatBuffer); break; } case LOCATION_GRAVE: { for(int i = grave[command_controler].size() - 1; i >= 0 ; --i) selectable_cards.push_back(grave[command_controler][i]); myswprintf(formatBuffer, L"查看墓地:(%d)", grave[command_controler].size()); mainGame->wCardSelect->setText(formatBuffer); break; } case LOCATION_REMOVED: { for(int i = remove[command_controler].size() - 1; i >= 0 ; --i) selectable_cards.push_back(remove[command_controler][i]); myswprintf(formatBuffer, L"查看除外:(%d)", remove[command_controler].size()); mainGame->wCardSelect->setText(formatBuffer); break; } case LOCATION_EXTRA: { for(int i = extra[command_controler].size() - 1; i >= 0 ; --i) selectable_cards.push_back(extra[command_controler][i]); myswprintf(formatBuffer, L"查看额外:(%d)", extra[command_controler].size()); mainGame->wCardSelect->setText(formatBuffer); break; } } list_command = COMMAND_LIST; ShowSelectCard(true); break; } case BUTTON_BP: { if(mainGame->dInfo.curMsg == MSG_SELECT_IDLECMD) { mainGame->dInfo.responseI = 6; mainGame->SetResponseI(); mainGame->localAction.Set(); } break; } case BUTTON_M2: { if(mainGame->dInfo.curMsg == MSG_SELECT_BATTLECMD) { mainGame->dInfo.responseI = 2; mainGame->SetResponseI(); mainGame->localAction.Set(); } break; } case BUTTON_EP: { if(mainGame->dInfo.curMsg == MSG_SELECT_BATTLECMD) { mainGame->dInfo.responseI = 3; mainGame->SetResponseI(); mainGame->localAction.Set(); } else if(mainGame->dInfo.curMsg == MSG_SELECT_IDLECMD) { mainGame->dInfo.responseI = 7; mainGame->SetResponseI(); mainGame->localAction.Set(); } break; } case BUTTON_CARD_0: case BUTTON_CARD_1: case BUTTON_CARD_2: case BUTTON_CARD_3: case BUTTON_CARD_4: { switch(mainGame->dInfo.curMsg) { case MSG_SELECT_IDLECMD: case MSG_SELECT_BATTLECMD: case MSG_SELECT_CHAIN: { if(list_command == COMMAND_LIST) break; if(list_command == COMMAND_SPSUMMON) { command_card = selectable_cards[id - BUTTON_CARD_0 + mainGame->scrCardList->getPos() / 10]; int index = 0; while(spsummonable_cards[index] != command_card) index++; mainGame->dInfo.responseI = (index << 16) + 1; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wCardSelect, true); break; } if(list_command == COMMAND_ACTIVATE) { int index = -1; command_card = selectable_cards[id - BUTTON_CARD_0 + mainGame->scrCardList->getPos() / 10]; select_options.clear(); for (int i = 0; i < activatable_cards.size(); ++i) { if (activatable_cards[i] == command_card) { select_options.push_back(activatable_descs[i]); if (index == -1) index = i; } } if (select_options.size() == 1) { if (mainGame->dInfo.curMsg == MSG_SELECT_IDLECMD) { mainGame->dInfo.responseI = (index << 16) + 5; } else if (mainGame->dInfo.curMsg == MSG_SELECT_BATTLECMD) { mainGame->dInfo.responseI = (index << 16); } else { mainGame->dInfo.responseI = index; } mainGame->SetResponseI(); mainGame->HideElement(mainGame->wCardSelect, true); } else { mainGame->SetStaticText(mainGame->stOptions, 310, mainGame->textFont, (wchar_t*)mainGame->dataManager.GetDesc(select_options[0])); selected_option = 0; mainGame->btnOptionp->setVisible(false); mainGame->btnOptionn->setVisible(true); mainGame->wCardSelect->setVisible(false); mainGame->ShowElement(mainGame->wOptions); } break; } break; } case MSG_SELECT_CARD: { command_card = selectable_cards[id - BUTTON_CARD_0 + mainGame->scrCardList->getPos() / 10]; if (command_card->is_selected) { command_card->is_selected = false; int i = 0; while(selected_cards[i] != command_card) i++; selected_cards.erase(selected_cards.begin() + i); if(command_card->controler) mainGame->stCardPos[id - BUTTON_CARD_0]->setBackgroundColor(0xffd0d0d0); else mainGame->stCardPos[id - BUTTON_CARD_0]->setBackgroundColor(0xffffffff); } else { command_card->is_selected = true; mainGame->stCardPos[id - BUTTON_CARD_0]->setBackgroundColor(0xffffff00); selected_cards.push_back(command_card); } int sel = selected_cards.size(); if (sel >= select_max) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->HideElement(mainGame->wCardSelect, true); } else if (sel >= select_min) { select_ready = true; mainGame->btnSelectOK->setVisible(true); } else { select_ready = false; mainGame->btnSelectOK->setVisible(false); } break; } case MSG_SELECT_SUM: { command_card = selectable_cards[id - BUTTON_CARD_0 + mainGame->scrCardList->getPos() / 10]; selected_cards.push_back(command_card); if (CheckSelectSum()) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->HideElement(mainGame->wCardSelect, true); } else { mainGame->wCardSelect->setVisible(false); mainGame->dField.ShowSelectCard(); } break; } case MSG_SORT_CHAIN: case MSG_SORT_CARD: { int offset = mainGame->scrCardList->getPos() / 10; command_card = selectable_cards[id - BUTTON_CARD_0 + offset]; if(sort_list[command_card->select_seq]) { select_min--; int sel = sort_list[command_card->select_seq]; sort_list[command_card->select_seq] = 0; for(int i = 0; i < select_max; ++i) if(sort_list[i] > sel) sort_list[i]--; for(int i = 0; i < 5; ++i) { if(offset + i >= select_max) break; if(sort_list[offset + i]) { myswprintf(formatBuffer, L"%d", sort_list[offset + i]); mainGame->stCardPos[i]->setText(formatBuffer); } else mainGame->stCardPos[i]->setText(L""); } } else { select_min++; sort_list[command_card->select_seq] = select_min; myswprintf(formatBuffer, L"%d", select_min); mainGame->stCardPos[id - BUTTON_CARD_0]->setText(formatBuffer); if(select_min == select_max) { for(int i = 0; i < select_max; ++i) mainGame->dInfo.responseB[i] = sort_list[i] - 1; mainGame->SetResponseB(select_max); mainGame->HideElement(mainGame->wCardSelect, true); } } break; } } break; } case BUTTON_CARD_SEL_OK: { if(mainGame->dInfo.curMsg == MSG_SELECT_CARD) { if(select_ready) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->HideElement(mainGame->wCardSelect, true); } break; } else { mainGame->HideElement(mainGame->wCardSelect); break; } } } break; } case irr::gui::EGET_CHECKBOX_CHANGED: { switch(id) { case CHECK_ATTRIBUTE: { int att = 0, filter = 0x1, count = 0; for(int i = 0; i < 7; ++i, filter <<= 1) { if(mainGame->chkAttribute[i]->isChecked()) { att |= filter; count++; } } if(count == announce_count) { mainGame->dInfo.responseI = att; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wANAttribute, true); } break; } case CHECK_RACE: { int rac = 0, filter = 0x1, count = 0; for(int i = 0; i < 22; ++i, filter <<= 1) { if(mainGame->chkRace[i]->isChecked()) { rac |= filter; count++; } } if(count == announce_count) { mainGame->dInfo.responseI = rac; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wANRace, true); } break; } } break; } case irr::gui::EGET_LISTBOX_CHANGED: { switch(id) { case LISTBOX_SERVER_LIST: { int currIdx = mainGame->lstServerList->getSelected(); if(currIdx < 0) break; HostInfo * hi; if(currIdx < (int)mainGame->netManager.hosts.size()) hi = &mainGame->netManager.hosts[currIdx]; else hi = tracking.host(currIdx); if(hi != NULL) { myswprintf(formatBuffer, L"%d.%d.%d.%d", hi->address & 0xff, (hi->address >> 8) & 0xff, (hi->address >> 16) & 0xff, (hi->address >> 24) & 0xff); mainGame->ebJoinIP->setText(formatBuffer); myswprintf(formatBuffer, L"%d", hi->port); mainGame->ebJoinPort->setText(formatBuffer); } break; } } break; } case irr::gui::EGET_SCROLL_BAR_CHANGED: { switch(id) { case SCROLL_CARD_SELECT: { int pos = mainGame->scrCardList->getPos() / 10; for(int i = 0; i < 5; ++i) { if(selectable_cards[i + pos]->code) mainGame->btnCardSelect[i]->setImage(mainGame->imageManager.GetTexture(selectable_cards[i + pos]->code)); else mainGame->btnCardSelect[i]->setImage(mainGame->imageManager.tCover); mainGame->btnCardSelect[i]->setRelativePosition(rect<s32>(30 + i * 125, 55, 30 + 120 + i * 125, 225)); myswprintf(formatBuffer, L"%ls[%d]", DataManager::FormatLocation(selectable_cards[i + pos]->location), selectable_cards[i + pos]->sequence + 1); mainGame->stCardPos[i]->setText(formatBuffer); if(selectable_cards[i + pos]->is_selected) mainGame->stCardPos[i]->setBackgroundColor(0xffffff00); else if(selectable_cards[i + pos]->controler) mainGame->stCardPos[i]->setBackgroundColor(0xffd0d0d0); else mainGame->stCardPos[i]->setBackgroundColor(0xffffffff); } break; } break; } } case irr::gui::EGET_TAB_CHANGED: { switch(id) { case TAB_MODES: { if(mainGame->wModes->getActiveTab() == 1) { if(mainGame->is_refreshing || mainGame->netManager.is_creating_host) break; if(mainGame->netManager.RefreshHost()) { mainGame->btnLanStartServer->setEnabled(false); mainGame->btnLanConnect->setEnabled(false); mainGame->btnRefreshList->setEnabled(false); mainGame->btnLoadReplay->setEnabled(false); mainGame->btnDeckEdit->setEnabled(false); } } else if(mainGame->wModes->getActiveTab() == 2) { mainGame->RefreshReplay(); } break; } } break; } case irr::gui::EGET_ELEMENT_HOVERED: { if(id >= BUTTON_CARD_0 && id <= BUTTON_CARD_4) { int pos = mainGame->scrCardList->getPos() / 10; ClientCard* mcard = selectable_cards[id - BUTTON_CARD_0 + pos]; if(mcard->code) { CardData cd; mainGame->dataManager.GetData(mcard->code, &cd); mainGame->imgCard->setImage(mainGame->imageManager.GetTexture(mcard->code)); myswprintf(formatBuffer, L"%ls[%d]", mainGame->dataManager.GetName(mcard->code), mcard->code); mainGame->stName->setText(formatBuffer); if(cd.type & TYPE_MONSTER) { myswprintf(formatBuffer, L"[%ls] %ls/%ls", DataManager::FormatType(cd.type), DataManager::FormatRace(cd.race), DataManager::FormatAttribute(cd.attribute)); mainGame->stInfo->setText(formatBuffer); formatBuffer[0] = L'['; for(int i = 1; i <= cd.level; ++i) formatBuffer[i] = L'★'; formatBuffer[cd.level + 1] = L']'; formatBuffer[cd.level + 2] = L' '; if(cd.attack < 0 && cd.defence < 0) myswprintf(&formatBuffer[cd.level + 3], L"?/?"); else if(cd.attack < 0) myswprintf(&formatBuffer[cd.level + 3], L"?/%d", cd.defence); else if(cd.defence < 0) myswprintf(&formatBuffer[cd.level + 3], L"%d/?", cd.attack); else myswprintf(&formatBuffer[cd.level + 3], L"%d/%d", cd.attack, cd.defence); mainGame->stDataInfo->setText(formatBuffer); mainGame->stText->setRelativePosition(irr::core::position2di(15, 83)); } else { myswprintf(formatBuffer, L"[%ls]", DataManager::FormatType(cd.type)); mainGame->stInfo->setText(formatBuffer); mainGame->stDataInfo->setText(L""); mainGame->stText->setRelativePosition(irr::core::position2di(15, 60)); } mainGame->SetStaticText(mainGame->stText, 270, mainGame->textFont, (wchar_t*)mainGame->dataManager.GetText(mcard->code)); } else { mainGame->stTip->setVisible(false); mainGame->imgCard->setImage(mainGame->imageManager.tCover); mainGame->stName->setText(L""); mainGame->stInfo->setText(L""); mainGame->stDataInfo->setText(L""); mainGame->stText->setText(L""); } } break; } default: break; } break; } case irr::EET_MOUSE_INPUT_EVENT: { switch(event.MouseInput.Event) { case irr::EMIE_LMOUSE_LEFT_UP: { if(is_replaying) break; if(!mainGame->dInfo.isStarted) break; s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; hovered_location = 0; irr::core::position2di pos(x, y); if(x < 300) break; if(mainGame->wCmdMenu->isVisible() && !mainGame->wCmdMenu->getRelativePosition().isPointInside(pos)) mainGame->wCmdMenu->setVisible(false); if(panel && panel->isVisible()) break; GetHoverField(x, y); if(hovered_location & 0xe) clicked_card = GetCard(hovered_controler, hovered_location, hovered_sequence); else clicked_card = 0; command_controler = hovered_controler; command_location = hovered_location; command_sequence = hovered_sequence; switch(mainGame->dInfo.curMsg) { case MSG_WAITING: { switch(hovered_location) { case LOCATION_MZONE: case LOCATION_SZONE: { if(!clicked_card || clicked_card->overlayed.size() == 0) break; ShowMenu(COMMAND_LIST, x, y); break; } case LOCATION_GRAVE: { if(grave[hovered_controler].size() == 0) break; ShowMenu(COMMAND_LIST, x, y); break; } case LOCATION_REMOVED: { int command_flag = 0; if(remove[hovered_controler].size() == 0) break; ShowMenu(COMMAND_LIST, x, y); break; } case LOCATION_EXTRA: { int command_flag = 0; if(extra[hovered_controler].size() == 0 || hovered_controler != 0) break; ShowMenu(COMMAND_LIST, x, y); break; } } break; } case MSG_SELECT_BATTLECMD: case MSG_SELECT_IDLECMD: case MSG_SELECT_CHAIN: { switch(hovered_location) { case LOCATION_DECK: { int command_flag = 0; for(int i = 0; i < deck[hovered_controler].size(); ++i) command_flag |= deck[hovered_controler][i]->cmdFlag; list_command = 1; ShowMenu(command_flag, x, y); break; } case LOCATION_HAND: case LOCATION_MZONE: case LOCATION_SZONE: { if(!clicked_card) break; int command_flag = clicked_card->cmdFlag; if(clicked_card->overlayed.size()) command_flag |= COMMAND_LIST; list_command = 0; ShowMenu(command_flag, x, y); break; } case LOCATION_GRAVE: { int command_flag = 0; if(grave[hovered_controler].size() == 0) break; for(int i = 0; i < grave[hovered_controler].size(); ++i) command_flag |= grave[hovered_controler][i]->cmdFlag; command_flag |= COMMAND_LIST; list_command = 1; ShowMenu(command_flag, x, y); break; } case LOCATION_REMOVED: { int command_flag = 0; if(remove[hovered_controler].size() == 0) break; for(int i = 0; i < remove[hovered_controler].size(); ++i) command_flag |= remove[hovered_controler][i]->cmdFlag; command_flag |= COMMAND_LIST; list_command = 1; ShowMenu(command_flag, x, y); break; } case LOCATION_EXTRA: { int command_flag = 0; if(extra[hovered_controler].size() == 0) break; for(int i = 0; i < extra[hovered_controler].size(); ++i) command_flag |= extra[hovered_controler][i]->cmdFlag; if(hovered_controler == 0) command_flag |= COMMAND_LIST; list_command = 1; ShowMenu(command_flag, x, y); break; } } break; } case MSG_SELECT_PLACE: case MSG_SELECT_DISFIELD: { if (!(hovered_location & LOCATION_ONFIELD)) break; int flag = 1 << (hovered_sequence + (hovered_controler << 4) + ((hovered_location == LOCATION_MZONE) ? 0 : 8)); if ((flag & selectable_field) > 0) { if ((flag & selected_field) > 0) { selected_field &= ~flag; select_min++; } else { selected_field |= flag; select_min--; if (select_min == 0) { int filter = 1; int p = 0; for (int i = 0; i < 5; ++i, filter <<= 1) { if (selected_field & filter) { mainGame->dInfo.responseB[p] = mainGame->LocalPlayer(0); mainGame->dInfo.responseB[p + 1] = 0x4; mainGame->dInfo.responseB[p + 2] = i; p += 3; } } filter = 0x100; for (int i = 0; i < 6; ++i, filter <<= 1) { if (selected_field & filter) { mainGame->dInfo.responseB[p] = mainGame->LocalPlayer(0); mainGame->dInfo.responseB[p + 1] = 0x8; mainGame->dInfo.responseB[p + 2] = i; p += 3; } } filter = 0x10000; for (int i = 0; i < 5; ++i, filter <<= 1) { if (selected_field & filter) { mainGame->dInfo.responseB[p] = mainGame->LocalPlayer(1); mainGame->dInfo.responseB[p + 1] = 0x4; mainGame->dInfo.responseB[p + 2] = i; p += 3; } } filter = 0x1000000; for (int i = 0; i < 6; ++i, filter <<= 1) { if (selected_field & filter) { mainGame->dInfo.responseB[p] = mainGame->LocalPlayer(1); mainGame->dInfo.responseB[p + 1] = 0x8; mainGame->dInfo.responseB[p + 2] = i; p += 3; } } selectable_field = 0; selected_field = 0; mainGame->SetResponseB(p); mainGame->localAction.Set(); } } } break; } case MSG_SELECT_CARD: case MSG_SELECT_TRIBUTE: { if (!(hovered_location & 0xe) || !clicked_card || !clicked_card->is_selectable) break; if (clicked_card->is_selected) { clicked_card->is_selected = false; int i = 0; while(selected_cards[i] != clicked_card) i++; selected_cards.erase(selected_cards.begin() + i); } else { clicked_card->is_selected = true; selected_cards.push_back(clicked_card); } int min = selected_cards.size(), max = 0; if (mainGame->dInfo.curMsg == MSG_SELECT_CARD) { max = selected_cards.size(); } else { for(int i = 0; i < selected_cards.size(); ++i) max += selected_cards[i]->opParam; } if (min >= select_max) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->localAction.Set(); } else if (max >= select_min) { if(selected_cards.size() == selectable_cards.size()) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->localAction.Set(); } else { select_ready = true; mainGame->stQMessage->setText(L"当前所选的卡已选择条件\n是否要继续选择?"); mainGame->PopupElement(mainGame->wQuery); } } else { select_ready = false; } break; } case MSG_SELECT_COUNTER: { if (!clicked_card || !clicked_card->is_selectable) break; clicked_card->opParam--; mainGame->dInfo.responseB[clicked_card->select_seq]++; if (clicked_card->opParam == 0) clicked_card->is_selectable = false; select_counter_count--; if (select_counter_count == 0) { mainGame->stHintMsg->setVisible(false); mainGame->SetResponseB(selectable_cards.size()); mainGame->localAction.Set(); } else { myswprintf(formatBuffer, L"请移除%d个[%ls]:", select_counter_count, mainGame->dataManager.GetCounterName(select_counter_type)); mainGame->stHintMsg->setText(formatBuffer); } break; } case MSG_SELECT_SUM: { if (!clicked_card) break; if (clicked_card->is_selected) { int i = 0; while(selected_cards[i] != clicked_card) i++; selected_cards.erase(selected_cards.begin() + i); } else if (clicked_card->is_selectable) selected_cards.push_back(clicked_card); else break; if (CheckSelectSum()) { if(selectable_cards.size() == 0) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->localAction.Set(); } else { select_ready = true; mainGame->stQMessage->setText(L"当前所选的卡已选择条件\n是否要继续选择?"); mainGame->PopupElement(mainGame->wQuery); } } else select_ready = false; break; } } break; } case irr::EMIE_RMOUSE_LEFT_UP: { if(is_replaying) break; mainGame->wCmdMenu->setVisible(false); if(mainGame->fadingFrame) break; switch(mainGame->dInfo.curMsg) { case MSG_WAITING: { if(mainGame->wCardSelect->isVisible()) { mainGame->HideElement(mainGame->wCardSelect); } break; } case MSG_SELECT_BATTLECMD: { if(mainGame->wCardSelect->isVisible()) { mainGame->HideElement(mainGame->wCardSelect); } if(mainGame->wOptions->isVisible()) { mainGame->HideElement(mainGame->wOptions); } break; } case MSG_SELECT_IDLECMD: { if(mainGame->wCardSelect->isVisible()) { mainGame->HideElement(mainGame->wCardSelect); } if(mainGame->wOptions->isVisible()) { mainGame->HideElement(mainGame->wOptions); } break; } case MSG_SELECT_YESNO: case MSG_SELECT_EFFECTYN: { mainGame->dInfo.responseI = 0; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wQuery, true); break; } case MSG_SELECT_CARD: { if(selected_cards.size() == 0) { if(select_cancelable) { mainGame->dInfo.responseI = -1; mainGame->SetResponseI(); if(mainGame->wCardSelect->isVisible()) mainGame->HideElement(mainGame->wCardSelect, true); else mainGame->localAction.Set(); } break; } if(mainGame->wQuery->isVisible()) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->HideElement(mainGame->wQuery, true); break; } if(select_ready) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); if(mainGame->wCardSelect->isVisible()) mainGame->HideElement(mainGame->wCardSelect, true); else mainGame->localAction.Set(); } break; } case MSG_SELECT_TRIBUTE: case MSG_SELECT_SUM: { if(mainGame->wQuery->isVisible()) { mainGame->dInfo.responseB[0] = selected_cards.size(); for (int i = 0; i < selected_cards.size(); ++i) mainGame->dInfo.responseB[i + 1] = selected_cards[i]->select_seq; mainGame->SetResponseB(selected_cards.size() + 1); mainGame->HideElement(mainGame->wQuery, true); break; } break; } case MSG_SELECT_CHAIN: { if(mainGame->wCardSelect->isVisible()) { mainGame->HideElement(mainGame->wCardSelect); break; } if(mainGame->wQuery->isVisible()) { mainGame->dInfo.responseI = -1; mainGame->SetResponseI(); mainGame->HideElement(mainGame->wQuery, true); } else { mainGame->PopupElement(mainGame->wQuery); } break; } } break; } case irr::EMIE_MOUSE_MOVED: { if(!mainGame->dInfo.isStarted) break; s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; hovered_location = 0; irr::core::position2di pos(x, y); if(x < 300) break; ClientCard* mcard = 0; if(!panel || !panel->isVisible() || !panel->getRelativePosition().isPointInside(pos)) { GetHoverField(x, y); if(hovered_location & 0xe) mcard = GetCard(hovered_controler, hovered_location, hovered_sequence); else if(hovered_location == LOCATION_GRAVE && grave[hovered_controler].size()) mcard = *(grave[hovered_controler].rbegin()); else if(hovered_location == LOCATION_REMOVED && remove[hovered_controler].size()) { mcard = *(remove[hovered_controler].rbegin()); if(mcard->position & POS_FACEDOWN) mcard = 0; } else mcard = 0; } if(hovered_location == LOCATION_HAND && (mainGame->dInfo.is_shuffling || mainGame->dInfo.curMsg == MSG_SHUFFLE_HAND)) mcard = 0; if(mcard != hovered_card) { if(hovered_card) { if(hovered_card->location == LOCATION_HAND && !mainGame->dInfo.is_shuffling && mainGame->dInfo.curMsg != MSG_SHUFFLE_HAND) { hovered_card->is_hovered = false; MoveCard(hovered_card, 5); } if(hovered_card->equipTarget) hovered_card->equipTarget->is_showequip = false; if(hovered_card->equipped.size()) for(auto cit = hovered_card->equipped.begin(); cit != hovered_card->equipped.end(); ++cit) (*cit)->is_showequip = false; if(hovered_card->cardTarget.size()) for(auto cit = hovered_card->cardTarget.begin(); cit != hovered_card->cardTarget.end(); ++cit) (*cit)->is_showtarget = false; if(hovered_card->ownerTarget.size()) for(auto cit = hovered_card->ownerTarget.begin(); cit != hovered_card->ownerTarget.end(); ++cit) (*cit)->is_showtarget = false; } if(mcard) { if(mcard != clicked_card) mainGame->wCmdMenu->setVisible(false); if(hovered_location == LOCATION_HAND) { mcard->is_hovered = true; MoveCard(mcard, 5); } if(mcard->equipTarget) mcard->equipTarget->is_showequip = true; if(mcard->equipped.size()) for(auto cit = mcard->equipped.begin(); cit != mcard->equipped.end(); ++cit) (*cit)->is_showequip = true; if(mcard->cardTarget.size()) for(auto cit = mcard->cardTarget.begin(); cit != mcard->cardTarget.end(); ++cit) (*cit)->is_showtarget = true; if(mcard->ownerTarget.size()) for(auto cit = mcard->ownerTarget.begin(); cit != mcard->ownerTarget.end(); ++cit) (*cit)->is_showtarget = true; if(mcard->code) { CardData cd; mainGame->dataManager.GetData(mcard->code, &cd); mainGame->imgCard->setImage(mainGame->imageManager.GetTexture(mcard->code)); myswprintf(formatBuffer, L"%ls[%d]", mainGame->dataManager.GetName(mcard->code), mcard->code); mainGame->stName->setText(formatBuffer); if(cd.type & TYPE_MONSTER) { myswprintf(formatBuffer, L"[%ls] %ls/%ls", DataManager::FormatType(cd.type), DataManager::FormatRace(cd.race), DataManager::FormatAttribute(cd.attribute)); mainGame->stInfo->setText(formatBuffer); formatBuffer[0] = L'['; for(int i = 1; i <= cd.level; ++i) formatBuffer[i] = L'★'; formatBuffer[cd.level + 1] = L']'; formatBuffer[cd.level + 2] = L' '; if(cd.attack < 0 && cd.defence < 0) myswprintf(&formatBuffer[cd.level + 3], L"?/?"); else if(cd.attack < 0) myswprintf(&formatBuffer[cd.level + 3], L"?/%d", cd.defence); else if(cd.defence < 0) myswprintf(&formatBuffer[cd.level + 3], L"%d/?", cd.attack); else myswprintf(&formatBuffer[cd.level + 3], L"%d/%d", cd.attack, cd.defence); mainGame->stDataInfo->setText(formatBuffer); mainGame->stText->setRelativePosition(irr::core::position2di(15, 83)); } else { myswprintf(formatBuffer, L"[%ls]", DataManager::FormatType(cd.type)); mainGame->stInfo->setText(formatBuffer); mainGame->stDataInfo->setText(L""); mainGame->stText->setRelativePosition(irr::core::position2di(15, 60)); } mainGame->SetStaticText(mainGame->stText, 270, mainGame->textFont, (wchar_t*)mainGame->dataManager.GetText(mcard->code)); if(mcard->location & 0xe) { std::wstring str; if(mcard->type & TYPE_MONSTER) { myswprintf(formatBuffer, L"%ls[%d]", mainGame->dataManager.GetName(mcard->code), mcard->code); str.append(formatBuffer); if(mcard->alias && mcard->alias != mcard->code) { myswprintf(formatBuffer, L"\n(%ls[%d])", mainGame->dataManager.GetName(mcard->alias), mcard->alias); str.append(formatBuffer); } myswprintf(formatBuffer, L"\n%ls/%ls", mcard->atkstring, mcard->defstring); str.append(formatBuffer); myswprintf(formatBuffer, L"\n★%d %ls/%ls", (mcard->level ? mcard->level : mcard->rank), DataManager::FormatRace(mcard->race), DataManager::FormatAttribute(mcard->attribute)); str.append(formatBuffer); if(mcard->counters.size()) { for(std::map<int, int>::iterator ctit = mcard->counters.begin(); ctit != mcard->counters.end(); ++ctit) { myswprintf(formatBuffer, L"\n[%ls]:%d", mainGame->dataManager.GetCounterName(ctit->first), ctit->second); str.append(formatBuffer); } } if(mcard->turnCounter && (mcard->location & LOCATION_ONFIELD)) { myswprintf(formatBuffer, L"\n回合计数:%d", mcard->turnCounter); str.append(formatBuffer); } } else { myswprintf(formatBuffer, L"%ls[%d]", mainGame->dataManager.GetName(mcard->code), mcard->code); str.append(formatBuffer); if(mcard->alias && mcard->alias != mcard->code) { myswprintf(formatBuffer, L"\n%ls[%d]", mainGame->dataManager.GetName(mcard->alias), mcard->alias); str.append(formatBuffer); } if(mcard->counters.size()) { for(std::map<int, int>::iterator ctit = mcard->counters.begin(); ctit != mcard->counters.end(); ++ctit) { myswprintf(formatBuffer, L"\n[%ls]:%d", mainGame->dataManager.GetCounterName(ctit->first), ctit->second); str.append(formatBuffer); } } if(mcard->turnCounter && (mcard->location & LOCATION_ONFIELD)) { myswprintf(formatBuffer, L"\n回合计数:%d", mcard->turnCounter); str.append(formatBuffer); } } mainGame->stTip->setVisible(true); irr::core::dimension2d<unsigned int> dtip = mainGame->textFont->getDimension(str.c_str()); mainGame->stTip->setRelativePosition(recti(x - 10 - dtip.Width, y - 10 - dtip.Height, x, y)); mainGame->stTip->setText(str.c_str()); } } else { mainGame->stTip->setVisible(false); mainGame->imgCard->setImage(mainGame->imageManager.tCover); mainGame->stName->setText(L""); mainGame->stInfo->setText(L""); mainGame->stDataInfo->setText(L""); mainGame->stText->setText(L""); } } else { mainGame->stTip->setVisible(false); } hovered_card = mcard; } else { if(mainGame->stTip->isVisible()) { irr::core::recti tpos = mainGame->stTip->getRelativePosition(); mainGame->stTip->setRelativePosition(irr::core::position2di(x - tpos.getWidth() - 10, y - tpos.getHeight() - 10)); } } break; } case irr::EMIE_MOUSE_WHEEL: { break; } default: break; } } case irr::EET_KEY_INPUT_EVENT: { switch(event.KeyInput.Key) { case irr::KEY_KEY_A: { mainGame->always_chain = event.KeyInput.PressedDown; break; } case irr::KEY_KEY_S: { mainGame->ignore_chain = event.KeyInput.PressedDown; break; } case irr::KEY_KEY_R: { if(!event.KeyInput.PressedDown) mainGame->textFont->setTransparency(true); break; } } break; } } return false; } void ClientField::GetHoverField(int x, int y) { irr::core::recti sfRect(433, 528, 883, 618); irr::core::recti ofRect(513, 117, 807, 175); irr::core::position2di pos(x, y); if(sfRect.isPointInside(pos)) { int hc = hand[0].size(); if(hc == 0) hovered_location = 0; else if(hc < 7) { int left = 433 + 77 * (6 - hc) / 2; if(x < left) hovered_location = 0; else { int seq = (x - left) / 77; if(seq >= hc) seq = hc - 1; if(x - left - 77 * seq < 68) { hovered_controler = 0; hovered_location = LOCATION_HAND; hovered_sequence = seq; } else hovered_location = 0; } } else { hovered_controler = 0; hovered_location = LOCATION_HAND; if(x >= 817) hovered_sequence = hc - 1; else hovered_sequence = (x - 433) * (hc - 1) / 384; } } else if(ofRect.isPointInside(pos)) { int hc = hand[1].size(); if(hc == 0) hovered_location = 0; else if(hc < 7) { int left = 513 + 50 * (6 - hc) / 2; if(x < left) hovered_location = 0; else { int seq = (x - left) / 50; if(seq >= hc) seq = hc - 1; if(x - left - 50 * seq < 45) { hovered_controler = 1; hovered_location = LOCATION_HAND; hovered_sequence = hc - 1 - seq; } else hovered_location = 0; } } else { hovered_controler = 1; hovered_location = LOCATION_HAND; if(x >= 763) hovered_sequence = 0; else hovered_sequence = hc - 1 - (x - 513) * (hc - 1) / 250; } } else { double screenx = x / 1024.0 * 1.25 - 0.81; double screeny = y / 640.0 * 0.84 - 0.42; double angle = 0.66104316885 - atan(screeny); //0.66104316885 = arctan(7.0/9.0) double vlen = sqrt(1.0 + screeny * screeny); double boardx = 3.95 + 9.0 * screenx / vlen / cos(angle); double boardy = 7.0 - 9.0 * tan(angle); hovered_location = 0; if(boardx >= 0.2 && boardx <= 1.0) { if(boardy >= 2.4 && boardy <= 3.6) { hovered_controler = 0; hovered_location = LOCATION_EXTRA; } else if(boardy >= 1.1 && boardy <= 2.3) { hovered_controler = 0; hovered_location = LOCATION_SZONE; hovered_sequence = 5; } else if(boardy >= -1.0 && boardy <= 0.2) { hovered_controler = 1; hovered_location = LOCATION_REMOVED; } else if(boardy >= -2.3 && boardy <= -1.1) { hovered_controler = 1; hovered_location = LOCATION_GRAVE; } else if(boardy >= -3.6 && boardy <= -2.4) { hovered_controler = 1; hovered_location = LOCATION_DECK; } } else if(boardx >= 6.9 && boardx <= 7.7) { if(boardy >= 2.4 && boardy <= 3.6) { hovered_controler = 0; hovered_location = LOCATION_DECK; } else if(boardy >= 1.1 && boardy <= 2.3) { hovered_controler = 0; hovered_location = LOCATION_GRAVE; } else if(boardy >= -0.2 && boardy <= 1.0) { hovered_controler = 0; hovered_location = LOCATION_REMOVED; } else if(boardy >= -2.3 && boardy <= -1.1) { hovered_controler = 1; hovered_location = LOCATION_SZONE; hovered_sequence = 5; } else if(boardy >= -3.6 && boardy <= -2.4) { hovered_controler = 1; hovered_location = LOCATION_EXTRA; } } else if(boardx >= 1.2 && boardx <= 6.7) { if(boardy > 1.7 && boardy <= 2.9) { hovered_controler = 0; hovered_location = LOCATION_SZONE; hovered_sequence = (boardx - 1.2) / 1.1; if(hovered_sequence > 4) hovered_sequence = 4; } else if(boardy >= 0.5 && boardy <= 1.7) { hovered_controler = 0; hovered_location = LOCATION_MZONE; hovered_sequence = (boardx - 1.2) / 1.1; if(hovered_sequence > 4) hovered_sequence = 4; } else if(boardy >= -1.7 && boardy <= -0.5) { hovered_controler = 1; hovered_location = LOCATION_MZONE; hovered_sequence = 4 - (int)((boardx - 1.2) / 1.1); if(hovered_sequence < 0) hovered_sequence = 0; } else if(boardy >= -2.9 && boardy < -1.7) { hovered_controler = 1; hovered_location = LOCATION_SZONE; hovered_sequence = 4 - (int)((boardx - 1.2) / 1.1); if(hovered_sequence < 0) hovered_sequence = 0; } } } } void ClientField::ShowMenu(int flag, int x, int y) { if(!flag) { mainGame->wCmdMenu->setVisible(false); return; } int height = 1; if(flag & COMMAND_ACTIVATE) { mainGame->btnActivate->setVisible(true); mainGame->btnActivate->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnActivate->setVisible(false); if(flag & COMMAND_SUMMON) { mainGame->btnSummon->setVisible(true); mainGame->btnSummon->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnSummon->setVisible(false); if(flag & COMMAND_SPSUMMON) { mainGame->btnSPSummon->setVisible(true); mainGame->btnSPSummon->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnSPSummon->setVisible(false); if(flag & COMMAND_MSET) { mainGame->btnMSet->setVisible(true); mainGame->btnMSet->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnMSet->setVisible(false); if(flag & COMMAND_SSET) { mainGame->btnSSet->setVisible(true); mainGame->btnSSet->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnSSet->setVisible(false); if(flag & COMMAND_REPOS) { if(clicked_card->position & POS_FACEDOWN) mainGame->btnRepos->setText(L"反转召唤"); else if(clicked_card->position & POS_ATTACK) mainGame->btnRepos->setText(L"守备表示"); else mainGame->btnRepos->setText(L"攻击表示"); mainGame->btnRepos->setVisible(true); mainGame->btnRepos->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnRepos->setVisible(false); if(flag & COMMAND_ATTACK) { mainGame->btnAttack->setVisible(true); mainGame->btnAttack->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnAttack->setVisible(false); if(flag & COMMAND_LIST) { mainGame->btnShowList->setVisible(true); mainGame->btnShowList->setRelativePosition(position2di(1, height)); height += 21; } else mainGame->btnShowList->setVisible(false); panel = mainGame->wCmdMenu; mainGame->wCmdMenu->setVisible(true); mainGame->wCmdMenu->setRelativePosition(irr::core::recti(x - 20 , y - 20 - height, x + 80, y - 20)); } }
[ "[email protected]@a812b692-228c-6283-38e5-8e5dc2e8e749", "[email protected]" ]
[ [ [ 1, 4 ], [ 6, 753 ], [ 756, 756 ], [ 769, 1604 ] ], [ [ 5, 5 ], [ 754, 755 ], [ 757, 768 ] ] ]
09cf3448c7bad000d94e250fb1c2b8db82167eb8
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/Launcher/AniButton.h
b69839d8776a846838efa58ad58ab50ce37197db
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,468
h
#if !defined(AFX_ANIBUTTON_H__C8477D0C_24E5_4A69_96D5_D9803EFFA30E__INCLUDED_) #define AFX_ANIBUTTON_H__C8477D0C_24E5_4A69_96D5_D9803EFFA30E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // AniButton.h : header file // ///////////////////////////////////////////////////////////////////////////// // CAniButton window class CAniButton : public CButton { // Construction public: CAniButton(); // Attributes public: UINT m_nAniID; // ResourceID of the .avi protected: CAnimateCtrl m_AnimateCtrl; // Animation control BOOL m_bPlaying; // Are we playing? // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAniButton) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation public: virtual ~CAniButton(); void LoadAVI(UINT nAniID); BOOL AutoLoad(UINT nID, CWnd* pParent); // Generated message map functions protected: //{{AFX_MSG(CAniButton) afx_msg void OnMouseMove(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ANIBUTTON_H__C8477D0C_24E5_4A69_96D5_D9803EFFA30E__INCLUDED_)
[ [ [ 1, 57 ] ] ]
b478153ff87df0bb412e432173281487c5d8fe46
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/propertycategories.hpp
fb17d476d8ded27a7d742af17be3591a3b2bdc9d
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
5,089
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'PropertyCategories.pas' rev: 6.00 #ifndef PropertyCategoriesHPP #define PropertyCategoriesHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <DesignEditors.hpp> // Pascal unit #include <DesignIntf.hpp> // Pascal unit #include <Contnrs.hpp> // Pascal unit #include <Masks.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <TypInfo.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Propertycategories { //-- type declarations ------------------------------------------------------- class DELPHICLASS TPropertyFilter; class PASCALIMPLEMENTATION TPropertyFilter : public System::TObject { typedef System::TObject inherited; private: Masks::TMask* FMask; TMetaClass*FComponentClass; Typinfo::TTypeInfo *FPropertyType; int FGroup; public: __fastcall TPropertyFilter(const AnsiString APropertyName, TMetaClass* AComponentClass, Typinfo::PTypeInfo APropertyType); __fastcall virtual ~TPropertyFilter(void); bool __fastcall Match(const AnsiString APropertyName, TMetaClass* AComponentClass, Typinfo::PTypeInfo APropertyType); __property TMetaClass* ComponentClass = {read=FComponentClass}; __property Typinfo::PTypeInfo PropertyType = {read=FPropertyType}; }; class DELPHICLASS TPropertyCategory; class PASCALIMPLEMENTATION TPropertyCategory : public System::TObject { typedef System::TObject inherited; private: Contnrs::TObjectList* FList; int FMatchCount; Designeditors::TPropertyEditor* FEditor; bool FEnabled; bool FVisible; int FGroup; AnsiString FName; protected: TPropertyFilter* __fastcall GetFilter(int Index); public: __fastcall TPropertyCategory(const AnsiString AName); __fastcall virtual ~TPropertyCategory(void); TPropertyFilter* __fastcall Add(TPropertyFilter* AFilter); int __fastcall Count(void); bool __fastcall Match(const AnsiString APropertyName, TMetaClass* AComponentClass, Typinfo::PTypeInfo APropertyType); void __fastcall ClearMatches(void); void __fastcall FreeEditorGroup(int AGroup); __property TPropertyFilter* Filters[int Index] = {read=GetFilter}; __property int MatchCount = {read=FMatchCount, nodefault}; __property bool Visible = {read=FVisible, write=FVisible, nodefault}; __property Designeditors::TPropertyEditor* Editor = {read=FEditor, write=FEditor}; __property AnsiString Name = {read=FName}; }; typedef TMetaClass*TPropertyCategoryClass; #pragma option push -b- enum TPropertyCategoryVisibleMode { pcvAll, pcvToggle, pcvNone, pcvNotListed, pcvOnlyListed }; #pragma option pop class DELPHICLASS TPropertyCategoryList; class PASCALIMPLEMENTATION TPropertyCategoryList : public System::TObject { typedef System::TObject inherited; public: TPropertyCategory* operator[](int Index) { return Categories[Index]; } private: Contnrs::TObjectList* FList; TPropertyCategory* FMiscCategory; protected: TPropertyCategory* __fastcall GetCategory(int Index); AnsiString __fastcall GetHiddenCategories(); void __fastcall SetHiddenCategories(const AnsiString Value); public: __fastcall TPropertyCategoryList(void); __fastcall virtual ~TPropertyCategoryList(void); TPropertyCategory* __fastcall FindCategory(const AnsiString ACategoryName); int __fastcall IndexOf(const AnsiString ACategoryName); void __fastcall ClearMatches(void); void __fastcall FreeEditorGroup(int AGroup); TPropertyCategory* __fastcall MiscCategory(void); int __fastcall Count(void); bool __fastcall Match(const AnsiString APropertyName, TMetaClass* AComponentClass, Typinfo::PTypeInfo APropertyType = (void *)(0x0)); bool __fastcall ChangeVisibility(TPropertyCategoryVisibleMode AMode)/* overload */; bool __fastcall ChangeVisibility(TPropertyCategoryVisibleMode AMode, const AnsiString * ANames, const int ANames_Size)/* overload */; __property AnsiString HiddenCategories = {read=GetHiddenCategories, write=SetHiddenCategories}; __property TPropertyCategory* Categories[int Index] = {read=GetCategory/*, default*/}; }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE bool __fastcall IsPropertyInCategory(const AnsiString Category, TMetaClass* ComponentClass, const AnsiString PropertyName)/* overload */; extern PACKAGE bool __fastcall IsPropertyInCategory(const AnsiString Category, const AnsiString ClassName, const AnsiString PropertyName)/* overload */; extern PACKAGE TPropertyCategoryList* __fastcall PropertyCategoryList(void); } /* namespace Propertycategories */ using namespace Propertycategories; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // PropertyCategories
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 132 ] ] ]
c837bcea4822fa1bafdb42aa18f195635bf91c41
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/Game/Dlg_FightGuard.cpp
b003d6f7feb564a7299ab7ffb05fd45bcf7bfd63
[ "Apache-2.0" ]
permissive
notpushkin/palm-heroes
d4523798c813b6d1f872be2c88282161cb9bee0b
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
refs/heads/master
2021-05-31T19:10:39.270939
2010-07-25T12:25:00
2010-07-25T12:25:00
62,046,865
2
1
null
null
null
null
UTF-8
C++
false
false
2,930
cpp
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ #include "stdafx.h" #include "Dlg_FightGuard.h" iDlg_FightGuard::iDlg_FightGuard(iViewMgr* pViewMgr, const iStringT& itemName, const iArmy& guard, PLAYER_ID pid, VISION_LEVEL vl) : iBaseGameDlg(pViewMgr, pid), m_itemName(itemName), m_guard(guard), m_vl(vl) {} void iDlg_FightGuard::OnCreateDlg() { iRect clRect = ClientRect(); sint32 npos = clRect.x + (clRect.w/2-45); AddChild(new iTextButton(m_pMgr,this,iRect(npos,clRect.y2()-DEF_BTN_HEIGHT,40,DEF_BTN_HEIGHT),TRID_YES, DRC_YES)); AddChild(new iTextButton(m_pMgr,this,iRect(npos+50,clRect.y2()-DEF_BTN_HEIGHT,40,DEF_BTN_HEIGHT),TRID_NO, DRC_NO)); } void iDlg_FightGuard::DoCompose(const iRect& clRect) { iRect rc(clRect); // title sint32 th = gTextComposer.TextBoxOut(dlgfc_hdr, gApp.Surface(), m_itemName, iRect(rc.x+5,rc.y,rc.w-10,30))+5; // message th += gTextComposer.TextBoxOut(dlgfc_stopic, gApp.Surface(), iFormat(gTextMgr[TRID_OBJ_GUARDED_BY], m_itemName.CStr()), iRect(rc.x+5,rc.y+th,rc.w-10,30)) + 5; // guards for (uint32 xx=0; xx<7; ++xx) { if (m_guard[xx].IsValid()) { gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), rc.point(), CreatGroup2Text(m_guard[xx].Type(),m_guard[xx].Count(), m_vl), iRect(rc.x+5,rc.y+th,rc.w-10,30), AlignTop); th += 10; } } th += 5; // question th += gTextComposer.TextBoxOut(dlgfc_topic, gApp.Surface(), gTextMgr[TRID_FIGHT_GUARD_QUESTION], iRect(rc.x+5,rc.y+th,rc.w-10,30)); } iSize iDlg_FightGuard::ClientSize() const { sint32 w = 150; sint32 h = 0; // title h += gTextComposer.GetTextBoxSize(m_itemName, w-10, dlgfc_hdr).h + 5; // message h += gTextComposer.GetTextBoxSize(iFormat(gTextMgr[TRID_OBJ_GUARDED_BY], m_itemName.CStr()), w-10, dlgfc_stopic).h + 5; // guards h += m_guard.GroupCount() * 10 + 5; // text 2 h += gTextComposer.GetTextBoxSize(gTextMgr[TRID_FIGHT_GUARD_QUESTION], w-10, dlgfc_topic).h; // ok button h += DEF_BTN_HEIGHT + 15; return iSize(w,h); } void iDlg_FightGuard::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param) { if (cmd == CCI_BTNCLICK) { EndDialog(pView->GetUID()); } }
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 89 ] ] ]
63cfcc50b11587f64174a77dee8bec4f8c84eb8c
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/q3ptrqueue.h
4f6905973c84ea676ad86b5dba1bc810a1e773ac
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,729
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the Qt3Support module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef Q3PTRQUEUE_H #define Q3PTRQUEUE_H #include <Qt3Support/q3glist.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Qt3SupportLight) template<class type> class Q3PtrQueue : protected Q3GList { public: Q3PtrQueue() {} Q3PtrQueue( const Q3PtrQueue<type> &q ) : Q3GList(q) {} ~Q3PtrQueue() { clear(); } Q3PtrQueue<type>& operator=(const Q3PtrQueue<type> &q) { return (Q3PtrQueue<type>&)Q3GList::operator=(q); } bool autoDelete() const { return Q3PtrCollection::autoDelete(); } void setAutoDelete( bool del ) { Q3PtrCollection::setAutoDelete(del); } uint count() const { return Q3GList::count(); } bool isEmpty() const { return Q3GList::count() == 0; } void enqueue( const type *d ) { Q3GList::append(Item(d)); } type *dequeue() { return (type *)Q3GList::takeFirst();} bool remove() { return Q3GList::removeFirst(); } void clear() { Q3GList::clear(); } type *head() const { return (type *)Q3GList::cfirst(); } operator type *() const { return (type *)Q3GList::cfirst(); } type *current() const { return (type *)Q3GList::cfirst(); } #ifdef qdoc protected: virtual QDataStream& read( QDataStream&, Q3PtrCollection::Item& ); virtual QDataStream& write( QDataStream&, Q3PtrCollection::Item ) const; #endif private: void deleteItem( Item d ); }; #if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION) template<> inline void Q3PtrQueue<void>::deleteItem( Q3PtrCollection::Item ) { } #endif template<class type> inline void Q3PtrQueue<type>::deleteItem( Q3PtrCollection::Item d ) { if ( del_item ) delete (type *)d; } QT_END_NAMESPACE QT_END_HEADER #endif // Q3PTRQUEUE_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 99 ] ] ]
b7f4456bee36ba421742f88a9ef90e826697c631
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/gtc/matrix_operation.inl
83222d0455a4a1b4ffb8de5efef231b716e7fa92
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
659
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2009-04-29 // Updated : 2009-04-29 // Licence : This source is under MIT License // File : glm/gtc/matrix_operation.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace gtc{ namespace matrix_operation { }//namespace matrix_operation }//namespace gtc }//namespace glm
[ [ [ 1, 17 ] ] ]
545abac4d1cb728f76e44164dca1f340b024eef2
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/Modules/Infrastructure/MotionRobotHealthProvider.h
7eaeaafee612359a6317386835ee3977acc8c427
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,174
h
/** * @file Modules/Infrastructure/MotionRobotHealthProvider.h * This file declares a module that provides information about the robot's health. * @author <a href="mailto:[email protected]">Tim Laue</a> */ #ifndef __MotionRobotHealth_H__ #define __MotionRobotHealth_H__ #include "Tools/Module/Module.h" #include "Tools/RingBuffer.h" #include "Representations/Infrastructure/RobotHealth.h" MODULE(MotionRobotHealthProvider) PROVIDES(MotionRobotHealth) END_MODULE /** * @class MotionRobotHealthProvider * A module that provides information about the robot's health */ class MotionRobotHealthProvider : public MotionRobotHealthProviderBase { private: /** The main function, called every cycle * @param motionRobotHealth The data struct to be filled */ void update(MotionRobotHealth& motionRobotHealth); RingBuffer<unsigned, 30> timeBuffer; /** Buffered timestamps of previous executions */ //RingBuffer<unsigned, 100> sensorTimeBuffer; /** Buffered timestamps of received sensor data */ public: /** Constructor. */ MotionRobotHealthProvider() {} }; #endif //__MotionRobotHealthProvider_h_
[ "alon@rogue.(none)" ]
[ [ [ 1, 39 ] ] ]
4608fa188e0053d38bf9bc08d34a91d84fa60f07
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/spirit/iterator/impl/file_iterator.ipp
d37d1641559f8b9cc93b5769abf39bcf07038541
[ "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
12,269
ipp
/*============================================================================= Copyright (c) 2003 Giovanni Bajo Copyright (c) 2003 Martin Wille Copyright (c) 2003 Hartmut Kaiser http://spirit.sourceforge.net/ 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) =============================================================================*/ #ifndef BOOST_SPIRIT_FILE_ITERATOR_IPP #define BOOST_SPIRIT_FILE_ITERATOR_IPP #ifdef BOOST_SPIRIT_FILEITERATOR_WINDOWS # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif #include <cstdio> #include <boost/shared_ptr.hpp> #ifdef BOOST_SPIRIT_FILEITERATOR_WINDOWS # include <boost/type_traits/remove_pointer.hpp> #endif #ifdef BOOST_SPIRIT_FILEITERATOR_POSIX # include <sys/types.h> // open, stat, mmap, munmap # include <sys/stat.h> // stat # include <fcntl.h> // open # include <unistd.h> // stat, mmap, munmap # include <sys/mman.h> // mmap, mmunmap #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { /////////////////////////////////////////////////////////////////////////////// namespace fileiter_impl { /////////////////////////////////////////////////////////////////////////////// // // std_file_iterator // // Base class that implements iteration through a file using standard C // stream library (fopen and friends). This class and the following are // the base components on which the iterator is built (through the // iterator adaptor library). // // The opened file stream (FILE) is held with a shared_ptr<>, whose // custom deleter invokes fcose(). This makes the syntax of the class // very easy, especially everything related to copying. // /////////////////////////////////////////////////////////////////////////////// template <typename CharT> class std_file_iterator { public: typedef CharT value_type; std_file_iterator() {} explicit std_file_iterator(std::string fileName) { using namespace std; FILE* f = fopen(fileName.c_str(), "rb"); // If the file was opened, store it into // the smart pointer. if (f) { m_file.reset(f, fclose); m_pos = 0; m_eof = false; update_char(); } } std_file_iterator(const std_file_iterator& iter) { *this = iter; } std_file_iterator& operator=(const std_file_iterator& iter) { m_file = iter.m_file; m_curChar = iter.m_curChar; m_eof = iter.m_eof; m_pos = iter.m_pos; return *this; } // Nasty bug in Comeau up to 4.3.0.1, we need explicit boolean context // for shared_ptr to evaluate correctly operator bool() const { return m_file ? true : false; } bool operator==(const std_file_iterator& iter) const { return (m_file == iter.m_file) && (m_eof == iter.m_eof) && (m_pos == iter.m_pos); } const CharT& get_cur_char(void) const { return m_curChar; } void prev_char(void) { m_pos -= sizeof(CharT); update_char(); } void next_char(void) { m_pos += sizeof(CharT); update_char(); } void seek_end(void) { using namespace std; fseek(m_file.get(), 0, SEEK_END); m_pos = ftell(m_file.get()) / sizeof(CharT); m_eof = true; } void advance(std::ptrdiff_t n) { m_pos += n * sizeof(CharT); update_char(); } std::ptrdiff_t distance(const std_file_iterator& iter) const { return (std::ptrdiff_t)(m_pos - iter.m_pos) / sizeof(CharT); } private: boost::shared_ptr<std::FILE> m_file; std::size_t m_pos; CharT m_curChar; bool m_eof; void update_char(void) { using namespace std; if ((std::size_t)ftell(m_file.get()) != m_pos) fseek(m_file.get(), m_pos, SEEK_SET); m_eof = (fread(&m_curChar, sizeof(CharT), 1, m_file.get()) < 1); } }; /////////////////////////////////////////////////////////////////////////////// // // mmap_file_iterator // // File iterator for memory mapped files, for now implemented on Windows and // POSIX platforms. This class has the same interface of std_file_iterator, // and can be used in its place (in fact, it's the default for Windows and // POSIX). // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // mmap_file_iterator, Windows version #ifdef BOOST_SPIRIT_FILEITERATOR_WINDOWS template <typename CharT> class mmap_file_iterator { public: typedef CharT value_type; mmap_file_iterator() {} explicit mmap_file_iterator(std::string fileName) { HANDLE hFile = ::CreateFileA( fileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if (hFile == INVALID_HANDLE_VALUE) return; // Store the size of the file, it's used to construct // the end iterator m_filesize = ::GetFileSize(hFile, NULL); HANDLE hMap = ::CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, 0, NULL ); if (hMap == NULL) { ::CloseHandle(hFile); return; } LPVOID pMem = ::MapViewOfFile( hMap, FILE_MAP_READ, 0, 0, 0 ); if (pMem == NULL) { ::CloseHandle(hMap); ::CloseHandle(hFile); return; } // We hold both the file handle and the memory pointer. // We can close the hMap handle now because Windows holds internally // a reference to it since there is a view mapped. ::CloseHandle(hMap); // It seems like we can close the file handle as well (because // a reference is hold by the filemap object). ::CloseHandle(hFile); // Store the handles inside the shared_ptr (with the custom destructors) m_mem.reset(static_cast<CharT*>(pMem), ::UnmapViewOfFile); // Start of the file m_curChar = m_mem.get(); } mmap_file_iterator(const mmap_file_iterator& iter) { *this = iter; } mmap_file_iterator& operator=(const mmap_file_iterator& iter) { m_curChar = iter.m_curChar; m_mem = iter.m_mem; m_filesize = iter.m_filesize; return *this; } // Nasty bug in Comeau up to 4.3.0.1, we need explicit boolean context // for shared_ptr to evaluate correctly operator bool() const { return m_mem ? true : false; } bool operator==(const mmap_file_iterator& iter) const { return m_curChar == iter.m_curChar; } const CharT& get_cur_char(void) const { return *m_curChar; } void next_char(void) { m_curChar++; } void prev_char(void) { m_curChar--; } void advance(std::ptrdiff_t n) { m_curChar += n; } std::ptrdiff_t distance(const mmap_file_iterator& iter) const { return m_curChar - iter.m_curChar; } void seek_end(void) { m_curChar = m_mem.get() + (m_filesize / sizeof(CharT)); } private: #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION typedef boost::remove_pointer<HANDLE>::type handle_t; #else typedef void handle_t; #endif boost::shared_ptr<CharT> m_mem; std::size_t m_filesize; CharT* m_curChar; }; #endif // BOOST_SPIRIT_FILEITERATOR_WINDOWS /////////////////////////////////////////////////////////////////////////////// // mmap_file_iterator, POSIX version #ifdef BOOST_SPIRIT_FILEITERATOR_POSIX template <typename CharT> class mmap_file_iterator { private: struct mapping { mapping(void *p, off_t len) : data(p) , size(len) { } CharT const *begin() const { return static_cast<CharT *>(data); } CharT const *end() const { return static_cast<CharT *>(data) + size/sizeof(CharT); } ~mapping() { munmap(data, size); } private: void *data; off_t size; }; public: typedef CharT value_type; mmap_file_iterator() {} explicit mmap_file_iterator(std::string file_name) { // open the file int fd = open(file_name.c_str(), #ifdef O_NOCTTY O_NOCTTY | // if stdin was closed then opening a file // would cause the file to become the controlling // terminal if the filename refers to a tty. Setting // O_NOCTTY inhibits this. #endif O_RDONLY); if (fd == -1) return; // call fstat to find get information about the file just // opened (size and file type) struct stat stat_buf; if ((fstat(fd, &stat_buf) != 0) || !S_ISREG(stat_buf.st_mode)) { // if fstat returns an error or if the file isn't a // regular file we give up. close(fd); return; } // perform the actual mapping void *p = mmap(0, stat_buf.st_size, PROT_READ, MAP_SHARED, fd, 0); // it is safe to close() here. POSIX requires that the OS keeps a // second handle to the file while the file is mmapped. close(fd); if (p == MAP_FAILED) return; mapping *m = 0; try { m = new mapping(p, stat_buf.st_size); } catch(...) { munmap(p, stat_buf.st_size); throw; } m_mem.reset(m); // Start of the file m_curChar = m_mem->begin(); } mmap_file_iterator(const mmap_file_iterator& iter) { *this = iter; } mmap_file_iterator& operator=(const mmap_file_iterator& iter) { m_curChar = iter.m_curChar; m_mem = iter.m_mem; return *this; } // Nasty bug in Comeau up to 4.3.0.1, we need explicit boolean context // for shared_ptr to evaluate correctly operator bool() const { return m_mem ? true : false; } bool operator==(const mmap_file_iterator& iter) const { return m_curChar == iter.m_curChar; } const CharT& get_cur_char(void) const { return *m_curChar; } void next_char(void) { m_curChar++; } void prev_char(void) { m_curChar--; } void advance(signed long n) { m_curChar += n; } long distance(const mmap_file_iterator& iter) const { return m_curChar - iter.m_curChar; } void seek_end(void) { m_curChar = m_mem->end(); } private: boost::shared_ptr<mapping> m_mem; CharT const* m_curChar; }; #endif // BOOST_SPIRIT_FILEITERATOR_POSIX /////////////////////////////////////////////////////////////////////////////// } /* namespace boost::spirit::fileiter_impl */ template <typename CharT, typename BaseIteratorT> file_iterator<CharT,BaseIteratorT> file_iterator<CharT,BaseIteratorT>::make_end(void) { file_iterator iter(*this); iter.base_reference().seek_end(); return iter; } template <typename CharT, typename BaseIteratorT> file_iterator<CharT,BaseIteratorT>& file_iterator<CharT,BaseIteratorT>::operator=(const base_t& iter) { base_t::operator=(iter); return *this; } /////////////////////////////////////////////////////////////////////////////// }} /* namespace boost::spirit */ #endif /* BOOST_SPIRIT_FILE_ITERATOR_IPP */
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 460 ] ] ]
2346b0a883dacbecfb646542fc08027ee4cadc21
fac8de123987842827a68da1b580f1361926ab67
/inc/math/HMVector2_64.h
dbac47674ea1fbbde14c32dd0386041dc94f395b
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
14,922
h
#ifndef HMVECTOR2_64_H #define HMVECTOR2_64_H #include "math/HMath.h" namespace hmath { class v2_64 { public : union { struct { f64 x; f64 y; }; f64 val[2]; }; inline v2_64(); inline v2_64(const f64 fX, const f64 fY ); inline explicit v2_64( const f64 scaler ); inline explicit v2_64( const f64 afCoordinate[2] ); inline explicit v2_64( const int afCoordinate[2] ); inline explicit v2_64( f64* const r ); inline v2_64( const v2_64& rkVector ); inline f64 operator [] ( const size_t i ) const; inline f64& operator [] ( const size_t i ); inline v2_64& operator = ( const v2_64& rkVector ); inline v2_64& operator = ( const f64 fScalar); inline bit operator == ( const v2_64& rkVector ) const; inline bit operator != ( const v2_64& rkVector ) const; inline v2_64 operator + ( const v2_64& rkVector ) const; inline v2_64 operator - ( const v2_64& rkVector ) const; inline v2_64 operator * ( const f64 fScalar ) const; inline v2_64 operator * ( const v2_64& rhs) const; inline v2_64 operator / ( const f64 fScalar ) const; inline v2_64 operator / ( const v2_64& rhs) const; inline const v2_64& operator + () const; inline v2_64 operator - () const; inline friend v2_64 operator * ( const f64 fScalar, const v2_64& rkVector ); inline friend v2_64 operator / ( const f64 fScalar, const v2_64& rkVector ); inline friend v2_64 operator + (const v2_64& lhs, const f64 rhs); inline friend v2_64 operator + (const f64 lhs, const v2_64& rhs); inline friend v2_64 operator - (const v2_64& lhs, const f64 rhs); inline friend v2_64 operator - (const f64 lhs, const v2_64& rhs); inline v2_64& operator += ( const v2_64& rkVector ); inline v2_64& operator += ( const f64 fScaler ); inline v2_64& operator -= ( const v2_64& rkVector ); inline v2_64& operator -= ( const f64 fScaler ); inline v2_64& operator *= ( const f64 fScalar ); inline v2_64& operator *= ( const v2_64& rkVector ); inline v2_64& operator /= ( const f64 fScalar ); inline v2_64& operator /= ( const v2_64& rkVector ); inline f64 len () const; inline f64 sqlen () const; inline f64 dot(const v2_64& vec) const; inline f64 norm(); inline v2_64 mid( const v2_64& vec ) const; inline bit operator < ( const v2_64& rhs ) const; inline bit operator > ( const v2_64& rhs ) const; inline void floor( const v2_64& cmp ); inline void ceil( const v2_64& cmp ); inline v2_64 up(void) const; inline f64 cross( const v2_64& rkVector ) const; inline bit iszerolen(void) const; inline v2_64 reflect(const v2_64& normal) const; static const v2_64 zero; static const v2_64 unitX; static const v2_64 unitY; static const v2_64 neg_unitX; static const v2_64 neg_unitY; static const v2_64 unit; }; v2_64::v2_64() { } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64::v2_64(const f64 fX, const f64 fY ) : x( fX ), y( fY ) { } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64::v2_64( const f64 scaler ) : x( scaler), y( scaler ) { } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64::v2_64( const f64 afCoordinate[2] ) : x( afCoordinate[0] ), y( afCoordinate[1] ) { } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64::v2_64( const int afCoordinate[2] ) { x = (f64)afCoordinate[0]; y = (f64)afCoordinate[1]; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64::v2_64( f64* const r ) : x( r[0] ), y( r[1] ) { } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64::v2_64( const v2_64& rkVector ) : x( rkVector.x ), y( rkVector.y ) { } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64 v2_64::operator [] ( const size_t i ) const { assert( i < 2 ); return *(&x+i); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64& v2_64::operator [] ( const size_t i ) { assert( i < 2 ); return *(&x+i); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator = ( const v2_64& rkVector ) { x = rkVector.x; y = rkVector.y; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator = ( const f64 fScalar) { x = fScalar; y = fScalar; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 bit v2_64::operator == ( const v2_64& rkVector ) const { return ( x == rkVector.x && y == rkVector.y ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 bit v2_64::operator != ( const v2_64& rkVector ) const { return ( x != rkVector.x || y != rkVector.y ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator + ( const v2_64& rkVector ) const { return v2_64( x + rkVector.x, y + rkVector.y); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator - ( const v2_64& rkVector ) const { return v2_64( x - rkVector.x, y - rkVector.y); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator * ( const f64 fScalar ) const { return v2_64( x * fScalar, y * fScalar); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator * ( const v2_64& rhs) const { return v2_64( x * rhs.x, y * rhs.y); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator / ( const f64 fScalar ) const { assert( fScalar != 0.0 ); f64 fInv = f64(1.0) / fScalar; return v2_64( x * fInv, y * fInv); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator / ( const v2_64& rhs) const { return v2_64( x / rhs.x, y / rhs.y); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 const v2_64& v2_64::operator + () const { return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::operator - () const { return v2_64(-x, -y); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 operator * ( const f64 fScalar, const v2_64& rkVector ) { return v2_64( fScalar * rkVector.x,fScalar * rkVector.y ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 operator / ( const f64 fScalar, const v2_64& rkVector ) { return v2_64( fScalar / rkVector.x,fScalar / rkVector.y ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 operator + (const v2_64& lhs, const f64 rhs) { return v2_64( lhs.x + rhs, lhs.y + rhs); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 operator + (const f64 lhs, const v2_64& rhs) { return v2_64( lhs + rhs.x, lhs + rhs.y); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 operator - (const v2_64& lhs, const f64 rhs) { return v2_64( lhs.x - rhs, lhs.y - rhs); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 operator - (const f64 lhs, const v2_64& rhs) { return v2_64( lhs - rhs.x,lhs - rhs.y ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator += ( const v2_64& rkVector ) { x += rkVector.x; y += rkVector.y; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator += ( const f64 fScaler ) { x += fScaler; y += fScaler; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator -= ( const v2_64& rkVector ) { x -= rkVector.x; y -= rkVector.y; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator -= ( const f64 fScaler ) { x -= fScaler; y -= fScaler; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator *= ( const f64 fScalar ) { x *= fScalar; y *= fScalar; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator *= ( const v2_64& rkVector ) { x *= rkVector.x; y *= rkVector.y; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator /= ( const f64 fScalar ) { assert( fScalar != 0.0 ); f64 fInv = f64(1.0) / fScalar; x *= fInv; y *= fInv; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64& v2_64::operator /= ( const v2_64& rkVector ) { x /= rkVector.x; y /= rkVector.y; return *this; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64 v2_64::len () const { return sqrt( x * x + y * y ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64 v2_64::sqlen () const { return x * x + y * y; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64 v2_64::dot(const v2_64& vec) const { return x * vec.x + y * vec.y; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64 v2_64::norm() { f64 fLength = sqrt( x * x + y * y); if ( fLength > 1e-08 ) { f64 fInvLength = f64(1.0) / fLength; x *= fInvLength; y *= fInvLength; } return fLength; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::mid( const v2_64& vec ) const { return v2_64( ( x + vec.x ) * f64(0.5), ( y + vec.y ) * f64(0.5) ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 bit v2_64::operator < ( const v2_64& rhs ) const { if( x < rhs.x && y < rhs.y ) return true; return false; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 bit v2_64::operator > ( const v2_64& rhs ) const { if( x > rhs.x && y > rhs.y ) return true; return false; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 void v2_64::floor( const v2_64& cmp ) { if( cmp.x < x ) x = cmp.x; if( cmp.y < y ) y = cmp.y; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 void v2_64::ceil( const v2_64& cmp ) { if( cmp.x > x ) x = cmp.x; if( cmp.y > y ) y = cmp.y; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::up(void) const { return v2_64 (-y, x); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 f64 v2_64::cross( const v2_64& rkVector ) const { return x * rkVector.y - y * rkVector.x; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 bit v2_64::iszerolen(void) const { f64 sqlen = (x * x) + (y * y); return (sqlen < (1e-06 * 1e-06)); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 v2_64 v2_64::reflect(const v2_64& normal) const { return v2_64( *this - ( 2 * this->dot(normal) * normal ) ); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 }; #endif
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 489 ] ] ]
78a069f27da624ec672ab2a47f663b07a92befbe
6c8c4728e608a4badd88de181910a294be56953a
/RexLogicModule/EventHandlers/MainPanelHandler.h
1504834f30f32b58a862f068d44f61199400a8cb
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
696
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_RexLogic_MainPanelHandler_h #define incl_RexLogic_MainPanelHandler_h #include "RexLogicModule.h" #include <QObject> namespace RexLogic { class MainPanelHandler : public QObject { Q_OBJECT public: MainPanelHandler(Foundation::Framework *framework, RexLogicModule *logic_module); ~MainPanelHandler(); public slots: void LogoutRequested(); void QuitRequested(); private: Foundation::Framework *framework_; RexLogicModule *rex_logic_module_; }; } #endif // incl_RexLogic_MainPanelHandler_h
[ "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 32 ] ] ]
6b8c053df8f387f77fc5d0d2d5731a1e57f0bd1f
fceff9260ff49d2707060241b6f9b927b97db469
/ZombieGentlemen_SeniorProject/entityManager.cpp
0b8b7819a956d3f033f33c5d780a1ea433cbaa1b
[]
no_license
EddyReyes/gentlemen-zombies-senior-project
9f5a6be90f0459831b3f044ed17ef2f085bec679
d88458b716c6eded376b3d44b5385c80deeb9a16
refs/heads/master
2021-05-29T12:13:47.506314
2011-07-04T17:20:38
2011-07-04T17:20:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,666
cpp
#include "entityManager.h" // constructor/destructor entityManager::entityManager() { players = NULL; enemies = NULL; m_stuff = NULL; m_checkPoints = NULL; dxSound = NULL; checkPnt = -1; numPlayers = 0; numEnemies = 0; numStuff = 0; numCheckPoints = 0; victoryCondition = false; } entityManager::~entityManager() { // destroy all ojbects pertaining to each entity removeAll(); enemyFiles.~stringArray(); playerFile.~basic_string(); } // member functions bool entityManager::init(objectManager * a_objMgr, sound * a_sound, std::string a_enemyFiles, std::string a_playerFile, std::string a_stuffFile, std::string a_checkPointFile) { // get pointer for the objectManager objMgr = a_objMgr; dxSound = a_sound; enemyFiles.loadFromTextFile(a_enemyFiles); // make sure there are file names inside the enemy filename string array if(enemyFiles.getSize() == 0) { MessageBox(NULL, "No enemy files were loaded", "Entity Manager Error", MB_OK); return false; } else { playerFile = a_playerFile; stuffFile = a_stuffFile; checkPointFile = a_checkPointFile; loadPlayers(); loadEnemies(0); loadStuff(); loadCheckPoints(); initPlayerSound(); return true; } } void entityManager::update(float timePassed) { bool updateIndexes = false; // update all players for(int i = 0; i < numPlayers; i++) { players[i]->update(timePassed); if(players[i]->getObject()->getCollHistory()->getList() && players[i]->isAlive()) { //check for collision with enemies for(int j = 0; j < numEnemies; j++) { for(int g = 0; g < players[i]->getObject()->getCollHistory()->endOfList(); g++) { if(players[i]->getObject()->getCollHistory()->get(g) == enemies[j]->getObject()->getObjectIndex()) { if(players[i]->hasArmor()) { player * plr = (player*)players[i]; plr->bounce(); plr->removeArmor(); } else players[i]->entityDead(); } if(enemies[j]->getType() == entityTurret) { turret * turr = (turret *)enemies[j]; for(int x =0; x < turr->getNumProjectiles();x++) { if(players[i]->getObject()->getCollHistory()->get(g) == turr->getProjectile(x)->getObject()->getObjectIndex()) { if(players[i]->hasArmor()) { player * plr = (player*)players[i]; plr->bounce(); plr->removeArmor(); } else players[i]->entityDead(); } } } } } //check for collision with stuff for(int j = 0; j < numStuff; j++) { for(int g = 0; g < players[i]->getObject()->getCollHistory()->endOfList(); g++) { if(players[i]->getObject()->getCollHistory()->get(g) == m_stuff[j]->getObject()->getObjectIndex()) { player * ply = (player*)players[i]; switch(m_stuff[j]->getType()) { case stuff_teleporter: teleporter * tel; tel = (teleporter*)m_stuff[j]; players[i]->setPosition(tel->getData()); dxSound->playSound(soundTeleport); break; case stuff_armor: if(!players[i]->hasArmor()) { // if player does not already have armor, give him armor, and remove it from the game world ply->armorPickup(); removeFromStuff(j); updateIndexes = true; } break; case stuff_victory: m_stuff[j]->pickUp(); victoryCondition = true; break; case stuff_key: if(!ply->playerHasKey()) { ply->keyPickup(); removeFromStuff(j); updateIndexes = true; } break; case stuff_door: if(ply->playerHasKey()) { door * dr = (door*)m_stuff[j]; if(!dr->isOpen()) { dr->open(); ply->removeKey(); } } break; default: break; } } } } // check for collision with checkpoints for(int j = 0; j < numCheckPoints; j++) { for(int g = 0; g < players[i]->getObject()->getCollHistory()->endOfList(); g++) { if(players[i]->getObject()->getCollHistory()->get(g) == m_checkPoints[j]->getObject()->getObjectIndex()) { if(!m_checkPoints[j]->isPickedUp()) { m_checkPoints[j]->pickUp(); D3DXVECTOR3 * pos = m_checkPoints[j]->getObject()->getPosition(); players[i]->setDefaultPos(pos); dxSound->playSound(soundCheckPoint); if((checkPnt + 1) == j) // check if checkpoint is consecutive checkPnt = j; else { checkPnt = j; checkOldCheckpoints(); // if not check old checkpoints } } } } } // clear collision history players[i]->getObject()->getCollHistory()->resetList(); } } // update all enemies for(int i = 0; i < numEnemies; i++) { enemies[i]->update(timePassed); if(enemies[i]->getObject()->getCollHistory()->getList() && enemies[i]->isAlive()) { //check for collision with stuff for(int j = 0; j < numStuff; j++) { for(int g = 0; g < enemies[i]->getObject()->getCollHistory()->endOfList(); g++) { if(enemies[i]->getObject()->getCollHistory()->get(g) == m_stuff[j]->getObject()->getObjectIndex()) { if(m_stuff[j]->getType() == stuff_teleporter) { teleporter * tel; tel = (teleporter*)m_stuff[j]; enemies[i]->setPosition(tel->getData()); } } } } //check for collision with enemies for(int j = 0; j < numEnemies; j++) { for(int g = 0; g < enemies[i]->getObject()->getCollHistory()->endOfList(); g++) { if(enemies[i]->getObject()->getCollHistory()->get(g) == enemies[j]->getObject()->getObjectIndex()) { // if enemies collide with each other turn around enemies[i]->flip(); } } } enemies[i]->getObject()->getCollHistory()->resetList(); } } // update all stuff for(int i = 0; i < numStuff; i++) { m_stuff[i]->update(timePassed); m_stuff[i]->getObject()->getCollHistory()->resetList(); } // update all checkpoints for(int i = 0; i < numCheckPoints; i++) { m_checkPoints[i]->update(timePassed); m_checkPoints[i]->getObject()->getCollHistory()->resetList(); } if(updateIndexes) { objMgr->getList()->setObjectIndexes(); } } // load functions void entityManager::loadPlayers() { std::fstream file(playerFile.c_str()); int size = 0; // count the number of strings in the text file file.peek(); while(!file.eof()) { int c; c = file.get(); if(c == '\n' || file.eof()) {size++;} } // clear fstream flags file.clear(); // set fstream get pointer back to the beginning file.seekg(0, std::ios::beg); // check if there is already an existing array if(!players) { // if not create a new list players = new entity * [size]; } else { // create a new array entity ** tempArray; tempArray = new entity * [numPlayers + size]; // copy over array data for(int i = 0; i < numPlayers; i++) { tempArray[i] = players[i]; } // delete old array and transfer new array into players delete [] players; players = tempArray; } for(int i = numPlayers; i < numPlayers + size; i++) { players[i] = new player(); float x, y; file >> x >> y; objMgr->loadObjectsFromTxtFile("defaultPlayer.txt"); objMgr->indexEnd(); objMgr->getObject()->togglePhysics(); players[i]->setObject(objMgr->getObject()); players[i]->setPosition(x, y); players[i]->getObject()->setSprite(0,0); // also set default position for re-spawing players[i]->setDefaultPos(x, y); } numPlayers += size; } void entityManager::loadEnemies(int fileIndex) { if(fileIndex < enemyFiles.getSize()) // check if index is greater than size { std::string * fileName = enemyFiles.getStringPtrAt(fileIndex); std::fstream file(fileName->c_str()); int size = 0; // count the number of strings in the text file file.peek(); while(!file.eof()) { int c; c = file.get(); if(c == '\n' || file.eof()) {size++;} } // clear fstream flags file.clear(); // set fstream get pointer back to the beginning file.seekg(0, std::ios::beg); // make the corresponding amount of entity pointers // check if there is already an existing array if(!enemies) { // if new create a new list enemies = new entity * [size]; } else { // create a new array entity ** tempArray; tempArray = new entity * [numEnemies + size]; // copy over array data for(int i = 0; i < numEnemies; i++) { tempArray[i] = enemies[i]; } // delete old array and transfer new array into players delete [] enemies; enemies = tempArray; } for(int i = numEnemies; i < numEnemies + size; i++) { char enemyType, direction; /********************************************************** * In the future direction and behavior type will change the behavior of the turrets **********************************************************/ float x, y; file >> enemyType >> x >> y >> direction; if(enemyType == 't') // load turret { turret * turr = new turret(); enemies[i] = turr; turr->setWall(direction); // create 5 objects for projectiles, and send them into the turret object ** turrProjectiles = new object *[5]; for(int i = 0; i < 5; i++) { turrProjectiles[i] = NULL; objMgr->loadObjectsFromTxtFile("defaultProjectile.txt"); objMgr->indexEnd(); turrProjectiles[i] = objMgr->getObject(); } turr->setProjectiles(turrProjectiles, 5); objMgr->loadObjectsFromTxtFile("defaultTurret.txt"); } else if(enemyType == 'z') // load ziggy { enemies[i] = new ziggy(); objMgr->loadObjectsFromTxtFile("defaultZiggy.txt"); } else if(enemyType == 'g') // load goomba { enemies[i] = new goomba(); objMgr->loadObjectsFromTxtFile("defaultGoomba.txt"); } else if(enemyType == 'o') // load obstacle { enemies[i] = new obstacle(); objMgr->loadObjectsFromTxtFile("defaultObstacle.txt"); } else if(enemyType == 'r') // load troll { enemies[i] = new troll(); objMgr->loadObjectsFromTxtFile("defaultTroll.txt"); } objMgr->indexEnd(); enemies[i]->setObject(objMgr->getObject()); enemies[i]->getObject()->setSprite(0,0); enemies[i]->setPosition(x, y); enemies[i]->setDefaultPos(x, y); enemies[i]->setDirection(direction); if(enemyType == 'g' || enemyType == 'z' || enemyType == 'r') // turn on physics for goombas and ziggy, and trolls { enemies[i]->getObject()->togglePhysics(); } if(enemyType == 'z') // lower gravity for ziggy's { enemies[i]->getObject()->getPhysics()->setGravity(-10.0f); } if(enemyType == 't') { turret * turr = (turret*)enemies[i]; // hide the projectiles behind the turret turr->hideProjectiles(); } } numEnemies += size; } } void entityManager::loadStuff() { std::fstream file(stuffFile.c_str()); int size = 0; // count the number of strings in the text file file.peek(); while(!file.eof()) { int c; c = file.get(); if(c == '\n' || file.eof()) {size++;} } // clear fstream flags file.clear(); // set fstream get pointer back to the beginning file.seekg(0, std::ios::beg); // check if there is already an existing array if(!m_stuff) { // if not create a new list m_stuff = new stuff * [size]; } else { // create a new array stuff ** tempArray; tempArray = new stuff * [numStuff + size]; // copy over array data for(int i = 0; i < numStuff; i++) { tempArray[i] = m_stuff[i]; } // delete old array and transfer new array into players delete [] m_stuff; m_stuff = tempArray; } for(int i = numStuff; i < numStuff + size; i++) { char stuffType; float x, y, data1, data2; file >> stuffType >> x >> y; if(stuffType == 'a') // load armor { m_stuff[i] = new armor; objMgr->loadObjectsFromTxtFile("defaultArmor.txt"); } else if(stuffType == 'k') // load key { m_stuff[i] = new key; objMgr->loadObjectsFromTxtFile("defaultKey.txt"); } else if(stuffType == 'd') // load door { m_stuff[i] = new door; objMgr->loadObjectsFromTxtFile("defaultDoor.txt"); } else if(stuffType == 't') { // also extract two more pieces of data for teleporter file >> data1 >> data2; teleporter * tel = new teleporter; m_stuff[i] = tel; tel->setData(data1, data2); objMgr->loadObjectsFromTxtFile("defaultTeleporter.txt"); } else if(stuffType == 'v') { m_stuff[i] = new victory(); objMgr->loadObjectsFromTxtFile("defaultVictory.txt"); } objMgr->indexEnd(); m_stuff[i]->setObject(objMgr->getObject()); m_stuff[i]->setPosition(x, y); m_stuff[i]->getObject()->setSprite(0,0); // toggle collision for some m_stuff if(stuffType == 'a' || stuffType == 'k' || stuffType == 't') { m_stuff[i]->getObject()->toggleCollision(); } } numStuff += size; } void entityManager::loadCheckPoints() { std::fstream file(checkPointFile.c_str()); int size = 0; // count the number of strings in the text file file.peek(); while(!file.eof()) { int c; c = file.get(); if(c == '\n' || file.eof()) {size++;} } // clear fstream flags file.clear(); // set fstream get pointer back to the beginning file.seekg(0, std::ios::beg); // check if there is already an existing array if(!m_checkPoints) { // if not create a new list m_checkPoints = new stuff * [size]; } else { // create a new array stuff ** tempArray; tempArray = new stuff * [numCheckPoints + size]; // copy over array data for(int i = 0; i < numCheckPoints; i++) { tempArray[i] = m_checkPoints[i]; } // delete old array and transfer new array into players delete [] m_checkPoints; m_checkPoints = tempArray; } for(int i = numCheckPoints; i < numCheckPoints + size; i++) { float x, y; file >> x >> y; m_checkPoints[i] = new checkpoint; objMgr->loadObjectsFromTxtFile("defaultCheckpoint.txt"); objMgr->indexEnd(); m_checkPoints[i]->setObject(objMgr->getObject()); m_checkPoints[i]->setPosition(x, y); m_checkPoints[i]->getObject()->setSprite(0,0); // toggle collision for some m_stuff m_checkPoints[i]->getObject()->toggleCollision(); } numCheckPoints += size; } // remove entity void entityManager::removeEnemies() { // delete all enemie entities if(enemies) { for(int i = 0; i < numEnemies; i++) { // check if it is a turret, turrets have more objects in thier projectiles if(enemies[i]->getType() == entityTurret) { turret * turr = (turret*)enemies[i]; // must remove all projectile objects first for(int i = 0; i < turr->getNumProjectiles(); i++) { projectile * proj = turr->getProjectile(i); objMgr->popObject(proj->getObject()->getObjectIndex()); // udpate object indexes objMgr->getList()->setObjectIndexes(); } turr->destroyProjectiles(); } // tell object manager to pop that particular objMgr->popObject(enemies[i]->getObject()->getObjectIndex()); // udpate object indexes objMgr->getList()->setObjectIndexes(); enemies[i]->setObject(NULL); delete enemies[i]; enemies[i] = NULL; } delete [] enemies; enemies = NULL; // contract object list to prevent it from growing out of control objMgr->getList()->contractList(); } // reset count data numEnemies = 0; } void entityManager::removePlayers() { // delete all player entities if(players) { for(int i = 0; i < numPlayers; i++) { // tell object manager to pop that particular objMgr->popObject(players[i]->getObject()->getObjectIndex()); // udpate object indexes objMgr->getList()->setObjectIndexes(); players[i]->setObject(NULL); delete players[i]; players[i] = NULL; } delete [] players; players = NULL; // contract object list to prevent it from growing out of control objMgr->getList()->contractList(); } // reset count data numPlayers = 0; } void entityManager::removeStuff() { // delete all player entities if(m_stuff) { for(int i = 0; i < numStuff; i++) { // tell object manager to pop that particular objMgr->popObject(m_stuff[i]->getObject()->getObjectIndex()); // udpate object indexes objMgr->getList()->setObjectIndexes(); m_stuff[i]->setObject(NULL); delete m_stuff[i]; m_stuff[i] = NULL; } delete [] m_stuff; m_stuff = NULL; // contract object list to prevent it from growing out of control objMgr->getList()->contractList(); } // reset count data numStuff = 0; } void entityManager::removeCheckPoints() { // delete all player entities if(m_checkPoints) { for(int i = 0; i < numCheckPoints; i++) { // tell object manager to pop that particular objMgr->popObject(m_checkPoints[i]->getObject()->getObjectIndex()); // udpate object indexes objMgr->getList()->setObjectIndexes(); m_checkPoints[i]->setObject(NULL); delete m_checkPoints[i]; m_checkPoints[i] = NULL; } delete [] m_checkPoints; m_checkPoints = NULL; // contract object list to prevent it from growing out of control objMgr->getList()->contractList(); } // reset count data numCheckPoints = 0; } void entityManager::removeAll() { // remove EVERYTHING removeEnemies(); removePlayers(); removeStuff(); removeCheckPoints(); } void entityManager::removeAllExceptCheckPoints() { // remove EVERYTHING except for checkpoints removeEnemies(); removePlayers(); removeStuff(); } void entityManager::resetPlayers() { for(int i = 0; i < numPlayers; i++) { players[i]->moveToDefaultPos(); players[i]->reset(); } } void entityManager::removeFromStuff(int index) { if(m_stuff) { // move stuff to the end of the list for(int i = index; i < numStuff-1; i++) { stuff * temp = m_stuff[i]; m_stuff[i] = m_stuff[i+1]; m_stuff[i+1] = temp; } // after its at the end of the list, destroy it objMgr->popObject(m_stuff[numStuff-1]->getObject()->getObjectIndex()); m_stuff[numStuff-1]->setObject(NULL); // contract object list to prevent it from growing out of control objMgr->getList()->contractList(); } // decriment stuff by 1 numStuff -= 1; } void entityManager::checkOldCheckpoints() { for(int i = 0; i < checkPnt; i++) { if(!m_checkPoints[i]->isPickedUp()) { m_checkPoints[i]->pickUp(); } } } //accesors entity * entityManager::getEnemy(int index) { if(index >= 0 && index < numEnemies) return enemies[index]; else return NULL; } player * entityManager::getPlayer(int index) { if(index >= 0 && index < numPlayers) return (player*)players[index]; else return NULL; } stuff * entityManager::getStuff(int index) { if(index >= 0 && index < numStuff) return (stuff*)m_stuff[index]; else return NULL; } int entityManager::getCheckPoint(){return checkPnt;} bool entityManager::getVictoryCondition(){return victoryCondition;} void entityManager::initPlayerSound() { for(int i = 0; i < numPlayers; i++) { player * plr = (player*)players[i]; plr->setSound(dxSound); } }
[ "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5", "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5" ]
[ [ [ 1, 108 ], [ 110, 110 ], [ 114, 489 ], [ 491, 496 ], [ 498, 773 ] ], [ [ 109, 109 ], [ 111, 113 ], [ 490, 490 ], [ 497, 497 ] ] ]
6f94836ca9e064299e5d5394c6b43d2bf238e8bc
4561a0f9a0de6a9b75202e1c05a4bd6ba7adabcf
/simd.h
c766f20dbd3485e0b6ac89f3b19cdf1248f04894
[ "MIT" ]
permissive
embarkmobile/ustl-symbian
3a2471a0487ae8d834f44a69debdb4e093215ce0
6d108f5683677d1d6b57705ac08cf1a4f5a37204
refs/heads/master
2020-04-23T15:37:30.148583
2010-12-10T15:35:16
2010-12-10T15:35:16
898,964
1
0
null
null
null
null
UTF-8
C++
false
false
16,524
h
// This file is part of the ustl library, an STL implementation. // // Copyright (C) 2005 by Mike Sharov <[email protected]> // This file is free software, distributed under the MIT License. // /// \file simd.h /// \brief SIMD-type algorithms, with hardware acceleration, if available. /// /// All algorithms are container-based because iterator syntax is just too /// damn verbose and because the specializations need to be able to tell /// how many elements are in the container in order to choose proper SIMD /// instruction set (i.e.: 4 floats select SSE, while 2 floats select 3dNow!) /// Specializations are only for the tuple template because the container /// must be of a fixed and compile-time-known size for the compiler to be /// able to choose the specialization. /// #ifndef SIMD_H_39BE2D970DF4BD00508CCFFB482496F9 #define SIMD_H_39BE2D970DF4BD00508CCFFB482496F9 #include "ulimits.h" #if HAVE_MATH_H #include <math.h> #endif namespace ustl { namespace simd { //---------------------------------------------------------------------- // Generic algorithms //---------------------------------------------------------------------- /// Applies \p op to each element in \p op1. template <typename Ctr, typename UnaryOperation> inline void packop (Ctr& op1, UnaryOperation op) { foreach (typename Ctr::iterator, i, op1) op (*i); } /// Applies \p op to each element in \p op1 and \p op2 and stores in \p op2. template <typename Ctr, typename BinaryOperation> inline void packop (const Ctr& op1, Ctr& op2, BinaryOperation op) { assert (op2.size() <= op1.size()); typename Ctr::const_iterator i1 (op1.begin()); typename Ctr::iterator i2 (op2.begin()); for (; i2 != op2.end(); ++i1, ++i2) *i2 = op (*i2, *i1); } /// Applies \p op to corresponding elements in \p op1 and \p op2 and stores in \p result. template <typename Ctr, typename BinaryOperation> inline void packop (const Ctr& op1, const Ctr& op2, Ctr& result, BinaryOperation op) { assert (op1.size() <= op2.size() && op1.size() <= result.size()); passign (op1, result); packop (op2, result); } /// Copies \p op1 into \p result. template <typename Ctr> inline void passign (const Ctr& op1, Ctr& result) { assert (op1.size() <= result.size()); typename Ctr::iterator d (result.begin()); foreach (typename Ctr::const_iterator, s, op1) *d++ = *s; } /// Copies \p result.size() elements from \p op1 to \p result. template <typename Ctr> inline void ipassign (typename Ctr::const_iterator op1, Ctr& result) { foreach (typename Ctr::iterator, d, result) *d = *op1++; } template <typename Ctr1, typename Ctr2, typename ConvertFunction> inline void pconvert (const Ctr1& op1, Ctr2& op2, ConvertFunction f) { assert (op1.size() <= op2.size()); typename Ctr1::const_iterator i1 (op1.begin()); typename Ctr2::iterator i2 (op2.begin()); for (; i1 != op1.end(); ++i1, ++i2) *i2 = f (*i1); } // Functionoids for SIMD operations, like saturation arithmetic, shifts, etc. STD_BINARY_FUNCTOR (fpadds, T, ((b > numeric_limits<T>::max() - a) ? numeric_limits<T>::max() : a + b)) STD_BINARY_FUNCTOR (fpsubs, T, ((a < numeric_limits<T>::min() + b) ? numeric_limits<T>::min() : a - b)) STD_BINARY_FUNCTOR (fpshl, T, (a << b)) STD_BINARY_FUNCTOR (fpshr, T, (a >> b)) STD_BINARY_FUNCTOR (fpmin, T, (min (a, b))) STD_BINARY_FUNCTOR (fpmax, T, (max (a, b))) STD_BINARY_FUNCTOR (fpavg, T, ((a + b + 1) / 2)) STD_CONVERSION_FUNCTOR (fcast, (D(a))) #if HAVE_MATH_H STD_UNARY_FUNCTOR (fpreciprocal,T, (1 / a)) STD_UNARY_FUNCTOR (fpsqrt, T, (reset_mmx(), T (sqrt (a)))) STD_UNARY_FUNCTOR (fprecipsqrt, T, (reset_mmx(), 1 / T(sqrt (a)))) STD_UNARY_FUNCTOR (fsin, T, (reset_mmx(), T (sin (a)))) STD_UNARY_FUNCTOR (fcos, T, (reset_mmx(), T (cos (a)))) STD_UNARY_FUNCTOR (ftan, T, (reset_mmx(), T (tan (a)))) #if HAVE_RINTF STD_CONVERSION_FUNCTOR (fround, (reset_mmx(), D(rintf(a)))) #else STD_CONVERSION_FUNCTOR (fround, (reset_mmx(), D(rint(a)))) #endif template <> inline int32_t fround<double,int32_t>::operator()(const double& a) const { reset_mmx(); return (int32_t(rint(a))); } #endif template <> inline float fpavg<float>::operator()(const float& a, const float& b) const { return ((a + b) / 2); } template <> inline double fpavg<double>::operator()(const double& a, const double& b) const { return ((a + b) / 2); } #define SIMD_PACKEDOP1(name, operation) \ template <typename Ctr> \ inline void name (Ctr& op1) \ { \ typedef typename Ctr::value_type value_t; \ packop (op1, operation<value_t>()); \ } #define SIMD_PACKEDOP2(name, operation) \ template <typename Ctr> \ inline void name (const Ctr& op1, Ctr& op2) \ { \ typedef typename Ctr::value_type value_t; \ packop (op1, op2, operation<value_t>()); \ } #define SIMD_PACKEDOP3(name, operation) \ template <typename Ctr> \ inline void name (const Ctr& op1, const Ctr& op2, Ctr& result) \ { \ typedef typename Ctr::value_type value_t; \ packop (op1, op2, result, operation<value_t>()); \ } #define SIMD_SINGLEOP1(name, operation) \ template <typename T> \ inline T name (T op) \ { \ operation<T> obj; \ return (obj(op)); \ } #define SIMD_CONVERTOP(name, operation) \ template <typename Ctr1, typename Ctr2> \ inline void name (const Ctr1& op1, Ctr2& op2) \ { \ typedef typename Ctr1::value_type value1_t; \ typedef typename Ctr2::value_type value2_t; \ pconvert (op1, op2, operation<value1_t, value2_t>());\ } SIMD_PACKEDOP2 (padd, plus) SIMD_PACKEDOP2 (psub, minus) SIMD_PACKEDOP2 (pmul, multiplies) SIMD_PACKEDOP2 (pdiv, divides) SIMD_PACKEDOP2 (pand, bitwise_and) SIMD_PACKEDOP2 (por, bitwise_or) SIMD_PACKEDOP2 (pxor, bitwise_xor) SIMD_PACKEDOP2 (pshl, fpshl) SIMD_PACKEDOP2 (pshr, fpshr) SIMD_PACKEDOP2 (psubs, fpsubs) SIMD_PACKEDOP2 (pmin, fpmin) SIMD_PACKEDOP2 (pmax, fpmax) SIMD_PACKEDOP2 (pavg, fpavg) SIMD_PACKEDOP3 (padd, plus) SIMD_PACKEDOP3 (psub, minus) SIMD_PACKEDOP3 (pmul, multiplies) SIMD_PACKEDOP3 (pdiv, divides) SIMD_PACKEDOP3 (pand, bitwise_and) SIMD_PACKEDOP3 (por, bitwise_or) SIMD_PACKEDOP3 (pxor, bitwise_xor) SIMD_PACKEDOP3 (pshl, fpshl) SIMD_PACKEDOP3 (pshr, fpshr) SIMD_PACKEDOP3 (padds, fpadds) SIMD_PACKEDOP3 (psubs, fpsubs) SIMD_PACKEDOP3 (pmin, fpmin) SIMD_PACKEDOP3 (pmax, fpmax) SIMD_PACKEDOP3 (pavg, fpavg) #if HAVE_MATH_H SIMD_PACKEDOP1 (precip, fpreciprocal) SIMD_PACKEDOP1 (psqrt, fpsqrt) SIMD_PACKEDOP1 (precipsqrt, fprecipsqrt) SIMD_PACKEDOP1 (psin, fsin) SIMD_PACKEDOP1 (pcos, fcos) SIMD_PACKEDOP1 (ptan, ftan) SIMD_SINGLEOP1 (srecip, fpreciprocal) SIMD_SINGLEOP1 (ssqrt, fpsqrt) SIMD_SINGLEOP1 (srecipsqrt, fprecipsqrt) SIMD_SINGLEOP1 (ssin, fsin) SIMD_SINGLEOP1 (scos, fcos) SIMD_SINGLEOP1 (stan, ftan) SIMD_CONVERTOP (pround, fround) template <typename T> inline int32_t sround (T op) { fround<T,int32_t> obj; return (obj (op)); } #endif #undef SIMD_SINGLEOP1 #undef SIMD_PACKEDOP3 #undef SIMD_PACKEDOP2 #undef SIMD_PACKEDOP1 //---------------------------------------------------------------------- // Vector types to cast tuple data to //---------------------------------------------------------------------- #if HAVE_VECTOR_EXTENSIONS && __GNUC__ >= 4 #define VECTOR_ATTRIBUTE(mode,vs) __attribute__((vector_size(vs))) #else #define VECTOR_ATTRIBUTE(mode,vs) #endif typedef uint8_t v8qi_t VECTOR_ATTRIBUTE (V8QI,8); typedef uint16_t v4hi_t VECTOR_ATTRIBUTE (V4HI,8); typedef uint16_t v8hi_t VECTOR_ATTRIBUTE (V8HI,16); typedef uint32_t v2si_t VECTOR_ATTRIBUTE (V2SI,8); typedef uint32_t v4si_t VECTOR_ATTRIBUTE (V4SI,16); #if HAVE_INT64_T typedef uint64_t v1di_t VECTOR_ATTRIBUTE (V1DI,8); #endif typedef float v2sf_t VECTOR_ATTRIBUTE (V2SF,8); typedef float v4sf_t VECTOR_ATTRIBUTE (V4SF,16); typedef double v2df_t VECTOR_ATTRIBUTE (V2DF,16); #undef VECTOR_ATTRIBUTE //---------------------------------------------------------------------- // Hardware accelerated specializations //---------------------------------------------------------------------- #define SIMD_PKOP2_SPEC(n, type, optype) \ template <> \ inline void packop (const tuple<n,type>& oin, tuple<n,type>& oout, optype<type>) #define SIMD_PASSIGN_SPEC(n, type) \ template <> \ inline void passign (const tuple<n,type>& oin, tuple<n,type>& oout) #define SIMD_IPASSIGN_SPEC(n, type) \ template <> \ inline void ipassign (tuple<n,type>::const_iterator oin, tuple<n,type>& oout) #define SIMD_CONVERT_SPEC(n, type1, type2, optype) \ template <> \ inline void pconvert (const tuple<n,type1>& oin, tuple<n,type2>& oout, optype<type1,type2>) #if CPU_HAS_MMX #define STD_MMX_ARGS "=m"(oout[0]) : "m"(oin[0]) : "mm0", "st", "memory" #define DBL_MMX_ARGS "=m"(oout[0]), "=m"(oout[2]) : "m"(oin[0]), "m"(oin[2]) : "mm0", "mm1", "st", "st(1)", "memory" #define MMX_PKOP2_SPEC(n,type,optype,instruction) \ SIMD_PKOP2_SPEC(n,type,optype) \ { asm ("movq %0, %%mm0\n\t" #instruction " %1, %%mm0\n\tmovq %%mm0, %0" : STD_MMX_ARGS); reset_mmx(); } #define MMX_DBL_PKOP2_SPEC(n,type,optype,instruction) \ SIMD_PKOP2_SPEC(n,type,optype) \ { asm ("movq %0, %%mm0\n\tmovq %1, %%mm1\n\t" #instruction " %2, %%mm0\n\t" #instruction " %3, %%mm1\n\tmovq %%mm0, %0\n\tmovq %%mm1, %1" : DBL_MMX_ARGS); reset_mmx(); } #define MMX_PASSIGN_SPEC(n,type) \ SIMD_PASSIGN_SPEC(n,type) \ { asm ("movq %1, %%mm0\n\tmovq %%mm0, %0" : STD_MMX_ARGS); reset_mmx(); } #define MMX_DBL_PASSIGN_SPEC(n,type) \ SIMD_PASSIGN_SPEC(n,type) \ { asm ("movq %2, %%mm0\n\tmovq %3, %%mm1\n\tmovq %%mm0, %0\n\tmovq %%mm1, %1" : DBL_MMX_ARGS); reset_mmx(); } #define MMX_IPASSIGN_SPEC(n,type) \ SIMD_IPASSIGN_SPEC(n,type) \ { asm ("movq %1, %%mm0\n\tmovq %%mm0, %0" : STD_MMX_ARGS); reset_mmx(); } #define MMX_DBL_IPASSIGN_SPEC(n,type) \ SIMD_IPASSIGN_SPEC(n,type) \ { asm ("movq %2, %%mm0\n\tmovq %3, %%mm1\n\tmovq %%mm0, %0\n\tmovq %%mm1, %1" : DBL_MMX_ARGS); reset_mmx(); } MMX_PASSIGN_SPEC(8,uint8_t) MMX_PKOP2_SPEC(8,uint8_t,plus,paddb) MMX_PKOP2_SPEC(8,uint8_t,minus,psubb) MMX_PKOP2_SPEC(8,uint8_t,bitwise_and,pand) MMX_PKOP2_SPEC(8,uint8_t,bitwise_or,por) MMX_PKOP2_SPEC(8,uint8_t,bitwise_xor,pxor) MMX_PKOP2_SPEC(8,uint8_t,fpadds,paddusb) MMX_PKOP2_SPEC(8,uint8_t,fpsubs,psubusb) MMX_PASSIGN_SPEC(8,int8_t) MMX_PKOP2_SPEC(8,int8_t,plus,paddb) MMX_PKOP2_SPEC(8,int8_t,minus,psubb) MMX_PKOP2_SPEC(8,int8_t,bitwise_and,pand) MMX_PKOP2_SPEC(8,int8_t,bitwise_or,por) MMX_PKOP2_SPEC(8,int8_t,bitwise_xor,pxor) MMX_PKOP2_SPEC(8,int8_t,fpadds,paddsb) MMX_PKOP2_SPEC(8,int8_t,fpsubs,psubsb) MMX_PASSIGN_SPEC(4,uint16_t) MMX_PKOP2_SPEC(4,uint16_t,plus,paddw) MMX_PKOP2_SPEC(4,uint16_t,minus,psubw) MMX_PKOP2_SPEC(4,uint16_t,bitwise_and,pand) MMX_PKOP2_SPEC(4,uint16_t,bitwise_or,por) MMX_PKOP2_SPEC(4,uint16_t,bitwise_xor,pxor) /// \todo psllw does not work like other operations, it uses the first element for shift count. //MMX_PKOP2_SPEC(4,uint16_t,fpshl,psllw) //MMX_PKOP2_SPEC(4,uint16_t,fpshr,psrlw) MMX_PKOP2_SPEC(4,uint16_t,fpadds,paddusw) MMX_PKOP2_SPEC(4,uint16_t,fpsubs,psubusw) MMX_PASSIGN_SPEC(4,int16_t) MMX_PKOP2_SPEC(4,int16_t,plus,paddw) MMX_PKOP2_SPEC(4,int16_t,minus,psubw) MMX_PKOP2_SPEC(4,int16_t,bitwise_and,pand) MMX_PKOP2_SPEC(4,int16_t,bitwise_or,por) MMX_PKOP2_SPEC(4,int16_t,bitwise_xor,pxor) //MMX_PKOP2_SPEC(4,int16_t,fpshl,psllw) //MMX_PKOP2_SPEC(4,int16_t,fpshr,psrlw) MMX_PKOP2_SPEC(4,int16_t,fpadds,paddsw) MMX_PKOP2_SPEC(4,int16_t,fpsubs,psubsw) MMX_PASSIGN_SPEC(2,uint32_t) MMX_PKOP2_SPEC(2,uint32_t,plus,paddd) MMX_PKOP2_SPEC(2,uint32_t,minus,psubd) MMX_PKOP2_SPEC(2,uint32_t,bitwise_and,pand) MMX_PKOP2_SPEC(2,uint32_t,bitwise_or,por) MMX_PKOP2_SPEC(2,uint32_t,bitwise_xor,pxor) //MMX_PKOP2_SPEC(2,uint32_t,fpshl,pslld) //MMX_PKOP2_SPEC(2,uint32_t,fpshr,psrld) MMX_PASSIGN_SPEC(2,int32_t) MMX_PKOP2_SPEC(2,int32_t,plus,paddd) MMX_PKOP2_SPEC(2,int32_t,minus,psubd) MMX_PKOP2_SPEC(2,int32_t,bitwise_and,pand) MMX_PKOP2_SPEC(2,int32_t,bitwise_or,por) MMX_PKOP2_SPEC(2,int32_t,bitwise_xor,pxor) //MMX_PKOP2_SPEC(2,int32_t,fpshl,pslld) //MMX_PKOP2_SPEC(2,int32_t,fpshr,psrld) MMX_DBL_PKOP2_SPEC(4,uint32_t,plus,paddd) MMX_DBL_PKOP2_SPEC(4,uint32_t,minus,psubd) MMX_DBL_PKOP2_SPEC(4,uint32_t,bitwise_and,pand) MMX_DBL_PKOP2_SPEC(4,uint32_t,bitwise_or,por) MMX_DBL_PKOP2_SPEC(4,uint32_t,bitwise_xor,pxor) //MMX_DBL_PKOP2_SPEC(2,uint32_t,fpshl,pslld) //MMX_DBL_PKOP2_SPEC(2,uint32_t,fpshr,psrld) MMX_DBL_PKOP2_SPEC(4,int32_t,plus,paddd) MMX_DBL_PKOP2_SPEC(4,int32_t,minus,psubd) MMX_DBL_PKOP2_SPEC(4,int32_t,bitwise_and,pand) MMX_DBL_PKOP2_SPEC(4,int32_t,bitwise_or,por) MMX_DBL_PKOP2_SPEC(4,int32_t,bitwise_xor,pxor) //MMX_DBL_PKOP2_SPEC(2,int32_t,fpshl,pslld) //MMX_DBL_PKOP2_SPEC(2,int32_t,fpshr,psrld) #if CPU_HAS_SSE || CPU_HAS_3DNOW MMX_PKOP2_SPEC(8,uint8_t,fpavg,pavgb) MMX_PKOP2_SPEC(8,int8_t,fpavg,pavgb) MMX_PKOP2_SPEC(4,uint16_t,fpavg,pavgw) MMX_PKOP2_SPEC(4,int16_t,fpavg,pavgw) MMX_PKOP2_SPEC(8,uint8_t,fpmin,pminub) MMX_PKOP2_SPEC(8,uint8_t,fpmax,pmaxub) MMX_PKOP2_SPEC(4,int16_t,fpmax,pmaxsw) MMX_PKOP2_SPEC(4,int16_t,fpmin,pminsw) #endif // CPU_HAS_SSE || CPU_HAS_3DNOW #if CPU_HAS_3DNOW MMX_PASSIGN_SPEC(2,float) MMX_PKOP2_SPEC(2,float,plus,pfadd) MMX_PKOP2_SPEC(2,float,minus,pfsub) MMX_PKOP2_SPEC(2,float,multiplies,pfmul) MMX_PKOP2_SPEC(2,float,fpmin,pfmin) MMX_PKOP2_SPEC(2,float,fpmax,pfmax) #ifndef CPU_HAS_SSE MMX_DBL_PKOP2_SPEC(4,float,plus,pfadd) MMX_DBL_PKOP2_SPEC(4,float,minus,pfsub) MMX_DBL_PKOP2_SPEC(4,float,multiplies,pfmul) MMX_DBL_PKOP2_SPEC(4,float,fpmin,pfmin) MMX_DBL_PKOP2_SPEC(4,float,fpmax,pfmax) #endif #endif // CPU_HAS_3DNOW MMX_IPASSIGN_SPEC(8,uint8_t) MMX_IPASSIGN_SPEC(4,uint16_t) MMX_IPASSIGN_SPEC(2,uint32_t) MMX_IPASSIGN_SPEC(2,float) #ifndef CPU_HAS_SSE MMX_DBL_PASSIGN_SPEC(4,float) MMX_DBL_PASSIGN_SPEC(4,uint32_t) MMX_DBL_PASSIGN_SPEC(4,int32_t) MMX_DBL_IPASSIGN_SPEC(4,float) MMX_DBL_IPASSIGN_SPEC(4,uint32_t) MMX_DBL_IPASSIGN_SPEC(4,int32_t) #endif #undef MMX_IPASSIGN_SPEC #undef MMX_PASSIGN_SPEC #undef MMX_PKOP2_SPEC #undef STD_MMX_ARGS #endif // CPU_HAS_MMX #if CPU_HAS_SSE #define STD_SSE_ARGS "=m"(oout[0]) : "m"(oin[0]) : "xmm0", "memory" #define SSE_PKOP2_SPEC(n,type,optype,instruction) \ SIMD_PKOP2_SPEC(n,type,optype) \ { asm ("movups %0, %%xmm0\n\tmovups %1, %%xmm1\n\t" #instruction " %%xmm1, %%xmm0\n\tmovups %%xmm0, %0" : STD_SSE_ARGS);} #define SSE_PASSIGN_SPEC(n,type) \ SIMD_PASSIGN_SPEC(n,type) \ { asm ("movups %1, %%xmm0\n\tmovups %%xmm0, %0" : STD_SSE_ARGS);} #define SSE_IPASSIGN_SPEC(n,type) \ SIMD_IPASSIGN_SPEC(n,type) \ { asm ("movups %1, %%xmm0\n\tmovups %%xmm0, %0" : STD_SSE_ARGS);} SSE_PASSIGN_SPEC(4,float) SSE_PASSIGN_SPEC(4,int32_t) SSE_PASSIGN_SPEC(4,uint32_t) SSE_PKOP2_SPEC(4,float,plus,addps) SSE_PKOP2_SPEC(4,float,minus,subps) SSE_PKOP2_SPEC(4,float,multiplies,mulps) SSE_PKOP2_SPEC(4,float,divides,divps) SSE_PKOP2_SPEC(4,float,bitwise_and,andps) SSE_PKOP2_SPEC(4,float,bitwise_or,orps) SSE_PKOP2_SPEC(4,float,bitwise_xor,xorps) SSE_PKOP2_SPEC(4,float,fpmax,maxps) SSE_PKOP2_SPEC(4,float,fpmin,minps) SIMD_CONVERT_SPEC(4,float,int32_t,fround) { asm ("cvtps2pi %2, %%mm0\n\t" "cvtps2pi %3, %%mm1\n\t" "movq %%mm0, %0\n\t" "movq %%mm1, %1" : DBL_MMX_ARGS); reset_mmx(); } SIMD_CONVERT_SPEC(4,int32_t,float,fround) { asm ("cvtpi2ps %2, %%xmm0\n\t" "shufps $0x4E,%%xmm0,%%xmm0\n\t" "cvtpi2ps %1, %%xmm0\n\t" "movups %%xmm0, %0" : "=m"(oout[0]) : "m"(oin[0]), "m"(oin[2]) : "xmm0", "memory"); } template <> inline int32_t fround<float,int32_t>::operator()(const float& a) const { register int32_t rv; asm ("movss %1, %%xmm0\n\t" "cvtss2si %%xmm0, %0" : "=r"(rv) : "m"(a) : "xmm0" ); return (rv); } template <> inline uint32_t fround<float,uint32_t>::operator()(const float& a) const { register uint32_t rv; asm ("movss %1, %%xmm0\n\t" "cvtss2si %%xmm0, %0" : "=r"(rv) : "m"(a) : "xmm0" ); return (rv); } SSE_IPASSIGN_SPEC(4,float) SSE_IPASSIGN_SPEC(4,int32_t) SSE_IPASSIGN_SPEC(4,uint32_t) #undef SSE_IPASSIGN_SPEC #undef SSE_PASSIGN_SPEC #undef SSE_PKOP2_SPEC #undef STD_SSE_ARGS #endif // CPU_HAS_SSE #undef SIMD_PACKEDOP_SPEC } // namespace simd } // namespace ustl #endif
[ [ [ 1, 459 ] ] ]
41496f905c06fb919da8953e756d1a595e0bf13c
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Contrib/UserInterface/src/Component/Spinner/OSGBoundedRangeSpinnerModel.cpp
472e04cabf7a089f49e970cbacb0f562a752bb5a
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,764
cpp
/*---------------------------------------------------------------------------*\ * OpenSG ToolBox UserInterface * * * * * * * * * * www.vrac.iastate.edu * * * * Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <stdlib.h> #include <stdio.h> #define OSG_COMPILEUSERINTERFACELIB #include "OSGConfig.h" #include "OSGBoundedRangeSpinnerModel.h" #include "OSGDefaultBoundedRangeModel.h" #include <boost/bind.hpp> OSG_BEGIN_NAMESPACE /***************************************************************************\ * Description * \***************************************************************************/ /*! \class OSG::DefaultChangeModel A DefaultChangeModel. */ /***************************************************************************\ * Class variables * \***************************************************************************/ /***************************************************************************\ * Class methods * \***************************************************************************/ /***************************************************************************\ * Instance methods * \***************************************************************************/ Int32 BoundedRangeSpinnerModel::getMaximum(void) const { return _TheBoundedRangeModel->getMaximum(); } Int32 BoundedRangeSpinnerModel::getMinimum(void) const { return _TheBoundedRangeModel->getMinimum(); } Int32 BoundedRangeSpinnerModel::getValue(void) const { return _TheBoundedRangeModel->getValue(); } void BoundedRangeSpinnerModel::setMaximum(Int32 newMaximum) { dettachListenersFromModels(); _TheBoundedRangeModel->setMaximum(newMaximum); _TheSpinnerModel->setMaximum(newMaximum); attachListenersToModels(); } void BoundedRangeSpinnerModel::setMinimum(Int32 newMinimum) { dettachListenersFromModels(); _TheBoundedRangeModel->setMinimum(newMinimum); _TheSpinnerModel->setMinimum(newMinimum); attachListenersToModels(); } void BoundedRangeSpinnerModel::setValue(Int32 newValue) { dettachListenersFromModels(); _TheBoundedRangeModel->setValue(newValue); _TheSpinnerModel->setValue(boost::any(newValue)); attachListenersToModels(); produceStateChanged(); } EventConnection BoundedRangeSpinnerModel::addChangeListener(ChangeListenerPtr l) { _ChangeListeners.insert(l); return EventConnection( boost::bind(&BoundedRangeSpinnerModel::isChangeListenerAttached, this, l), boost::bind(&BoundedRangeSpinnerModel::removeChangeListener, this, l)); } void BoundedRangeSpinnerModel::removeChangeListener(ChangeListenerPtr l) { ChangeListenerSetItor EraseIter(_ChangeListeners.find(l)); if(EraseIter != _ChangeListeners.end()) { _ChangeListeners.erase(EraseIter); } } void BoundedRangeSpinnerModel::produceStateChanged(void) { const ChangeEventUnrecPtr TheEvent = ChangeEvent::create(NULL, getSystemTime()); ChangeListenerSet ModelListenerSet(_ChangeListeners); for(ChangeListenerSetConstItor SetItor(ModelListenerSet.begin()) ; SetItor != ModelListenerSet.end() ; ++SetItor) { (*SetItor)->stateChanged(TheEvent); } } void BoundedRangeSpinnerModel::attachListenersToModels(void) { _TheBoundedRangeModel->addChangeListener(&_BoundedRangeModelChangeListener); _TheSpinnerModel->addChangeListener(&_SpinnerModelChangeListener); } void BoundedRangeSpinnerModel::dettachListenersFromModels(void) { _TheBoundedRangeModel->removeChangeListener(&_BoundedRangeModelChangeListener); _TheSpinnerModel->removeChangeListener(&_SpinnerModelChangeListener); } /*-------------------------------------------------------------------------*\ - private - \*-------------------------------------------------------------------------*/ /*----------------------- constructors & destructors ----------------------*/ BoundedRangeSpinnerModel::BoundedRangeSpinnerModel(void) : _BoundedRangeModelChangeListener(this), _SpinnerModelChangeListener(this) { _TheBoundedRangeModel = DefaultBoundedRangeModel::create(); _TheBoundedRangeModel->setExtent(0); _TheSpinnerModel = Int32SpinnerModelPtr(new Int32SpinnerModel()); _TheSpinnerModel->setStepSize(1); attachListenersToModels(); } BoundedRangeSpinnerModel::BoundedRangeSpinnerModel(const BoundedRangeSpinnerModel &source) : _BoundedRangeModelChangeListener(this), _SpinnerModelChangeListener(this) { _TheBoundedRangeModel = DefaultBoundedRangeModel::create(); _TheBoundedRangeModel->setExtent(source._TheBoundedRangeModel->getExtent()); _TheSpinnerModel = Int32SpinnerModelPtr(new Int32SpinnerModel()); _TheSpinnerModel->setStepSize(source._TheSpinnerModel->getStepSize()); attachListenersToModels(); setMinimum(source.getMinimum()); setMaximum(source.getMaximum()); setValue(source.getValue()); } BoundedRangeSpinnerModel::~BoundedRangeSpinnerModel(void) { dettachListenersFromModels(); } void BoundedRangeSpinnerModel::BoundedRangeModelChangeListener::stateChanged(const ChangeEventUnrecPtr e) { _BoundedRangeSpinnerModel->dettachListenersFromModels(); _BoundedRangeSpinnerModel->_TheSpinnerModel->setMinimum(_BoundedRangeSpinnerModel->_TheBoundedRangeModel->getMinimum()); _BoundedRangeSpinnerModel->_TheSpinnerModel->setMaximum(_BoundedRangeSpinnerModel->_TheBoundedRangeModel->getMaximum()); _BoundedRangeSpinnerModel->_TheSpinnerModel->setValue(boost::any(_BoundedRangeSpinnerModel->_TheBoundedRangeModel->getValue())); _BoundedRangeSpinnerModel->attachListenersToModels(); _BoundedRangeSpinnerModel->produceStateChanged(); } void BoundedRangeSpinnerModel::SpinnerModelChangeListener::stateChanged(const ChangeEventUnrecPtr e) { _BoundedRangeSpinnerModel->dettachListenersFromModels(); _BoundedRangeSpinnerModel->_TheBoundedRangeModel->setMinimum(_BoundedRangeSpinnerModel->_TheSpinnerModel->getMinimum()); _BoundedRangeSpinnerModel->_TheBoundedRangeModel->setMaximum(_BoundedRangeSpinnerModel->_TheSpinnerModel->getMaximum()); _BoundedRangeSpinnerModel->_TheBoundedRangeModel->setValue(_BoundedRangeSpinnerModel->_TheSpinnerModel->getNumber()); _BoundedRangeSpinnerModel->attachListenersToModels(); _BoundedRangeSpinnerModel->produceStateChanged(); } OSG_END_NAMESPACE
[ [ [ 1, 231 ] ] ]
52fdc17717d8853d1d765fc780201830ea21e988
2f650259e71a0f5c040bac1ab5e4a69980df3ff8
/WwiseUnityProject/WwiseUnity/WwiseEngine.hpp
fa34577be7f136c99d41216d700e0dd46298bc57
[]
no_license
Lucyberad/wwiseunity
3f5836355b9b58ec8213cdc7fa130c9c369f09ab
cfcf39e596ddcff11cd5a93b2feb355a2c7c8e83
refs/heads/master
2021-01-16T23:23:00.030957
2011-06-27T09:17:46
2011-06-27T09:17:46
33,073,189
0
0
null
null
null
null
UTF-8
C++
false
false
4,798
hpp
////////////////////////////////////////////////////////////////////// // // Author: Adrien "Lucyberad" Bock. // ////////////////////////////////////////////////////////////////////// #ifndef WWISEUNITY_WWISEENGINE_HPP #define WWISEUNITY_WWISEENGINE_HPP #include <stdlib.h> //for malloc & free #include <windows.h> //for DWORD & others. #include <exception> #include "WwiseUnityTypes.hpp" #include <AK/SoundEngine/Common/AkMemoryMgr.h> // Memory Manager #include <AK/SoundEngine/Common/AkModule.h> // Default memory and stream managers #include <AK/Tools/Common/AkPlatformFuncs.h> // Thread defines #include <AK/SoundEngine/Common/IAkStreamMgr.h> // Streaming Manager #include "AkFilePackageLowLevelIOBlocking.h" // Sample low-level I/O implementation (in $(WWISESDK)/samples/SoundEngine/Win32). #include <AK/SoundEngine/Common/AkSoundEngine.h> // Sound engine #include <AK/MusicEngine/Common/AkMusicEngine.h> // Music Engine #include <AK/SoundEngine/Common/AkTypes.h> #include <AK/SoundEngine/Common/AkSpeakerConfig.h> #ifdef DEBUG #include <AK/Comm/AkCommunication.h> #endif #ifdef WWISEUNITY_VORBIS //if defined, link AkVorbisDecoder.lib #include <AK/Plugin/AkVorbisFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_FLANGER //if defined, link AkFlangerFX.lib #include <AK/Plugin/AkFlangerFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_PARAMETRICEQ //if defined, link AkParametricEQFX.lib #include <AK/Plugin/AkParametricEQFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_DISTORTION //if defined, link AkGuitarDistortionFX.lib #include <AK/Plugin/AkGuitarDistortionFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_MATRIXREVERB //if defined, link AkMatrixReverbFX.lib #include <AK/Plugin/AkMatrixReverbFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_PEAKLIMITER //if defined, link AkPeakLimiterFX.lib #include <AK/Plugin/AkPeakLimiterFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_ROOMVERB //if defined, link AkRoomVerbFX.lib #include <AK/Plugin/AkRoomVerbFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_DELAY //if defined, link AkDelayFX.lib #include <AK/Plugin/AkDelayFXFactory.h> #endif #ifdef WWISEUNITY_PLUGIN_SILENCE #include <AK/Plugin/AkSilenceSourceFactory.h> //if defined, link AkSilenceSource.lib #endif namespace WwiseUnity { class WwiseEngine { private: // We're using the default Low-Level I/O implementation that's part // of the SDK's sample code, with the file package extension CAkFilePackageLowLevelIOBlocking g_lowLevelIO; //This is the File Location Resolver. static WwiseEngine* _singleton; // define the static instance for native interface use public: static WwiseEngine* getInstance(); static void killSingleton(); public: bool Init(); void ProcessAudio(); void Term(); int SetBasePath(WU_STRING basePath); int SetLangSpecificDirName(WU_STRING specificDirName); int LoadBank(WU_STRING bankName); int UnloadBank(WU_STRING bankName); int RegisterGameObject(AkGameObjectID akId, WU_STRING gameObjectLabel); int UnregisterGameObject(AkGameObjectID akId); int UnregisterAllGameObject(); void PostEvent(WU_STRING eventName, AkGameObjectID gameObject); void PostEvent(AkUniqueID eventId, AkGameObjectID gameObject); void SetRTPCValue(WU_STRING rtpcName, AkRtpcValue value); void SetRTPCValue(WU_STRING rtpcName, AkRtpcValue value, AkGameObjectID gameObjectId); void SetRTPCValue(AkRtpcID rtpcId, AkRtpcValue value, AkGameObjectID gameObjectId); void SetState(WU_STRING stateGroup, WU_STRING state); void SetState(AkStateGroupID stateGroupId, AkStateID stateId); void SetSwitch(WU_STRING switchGroupName, WU_STRING switchName, AkGameObjectID gameObjectId); void SetSwitch(AkStateGroupID switchGroupId, AkStateID switchId, AkGameObjectID gameObjectId); int SetListenerPosition(AkListenerPosition& akPosition); int SetListenerPosition(int listenerIndex, AkListenerPosition& akPosition); int SetPosition(AkGameObjectID gameObjectId, AkSoundPosition& position); int SetPosition(AkGameObjectID gameObjectId, AkSoundPosition& position, int listenerIndex); int SetGameObjectActiveListeners(AkGameObjectID gameObjectId, AkUInt32 listenerMask); int PostTrigger( AkTriggerID in_triggerID, AkGameObjectID in_gameObjectID ); int PostTrigger( WU_STRING in_pszTrigger, AkGameObjectID in_gameObjectID ); int SetListenerSpatialization( AkUInt32 in_uIndex, bool in_bSpatialized ); AkChannelMask MyChannelMaskFromNumChannels( unsigned int in_uNumChannels ); unsigned int MyChannelMaskToNumChannels( AkChannelMask in_uChannelMask ); AkChannelMask GetSpeakerConfiguration(); }; } #endif
[ "[email protected]@4ae3ac6d-c3d7-76ed-586d-0242e581c9de", "[email protected]@4ae3ac6d-c3d7-76ed-586d-0242e581c9de" ]
[ [ [ 1, 15 ], [ 20, 20 ], [ 27, 116 ], [ 128, 129 ] ], [ [ 16, 19 ], [ 21, 26 ], [ 117, 127 ], [ 130, 130 ] ] ]
eb61d44dbf8bed246b7550142456d1bdf1daa3fd
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Shape/hkpShape.inl
de600697f1a49b19df61a1871fd482c9e0c46fcc
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,513
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ hkpShape::hkpShape( hkpShapeType type ) { m_userData = 0; m_type = type; } HK_CLASSALIGN16(class) hkAlignedShape: public hkpShape{ hkAlignedShape(); }; hkpShapeType hkpShape::getType() const { return static_cast<const hkAlignedShape*>(this)->m_type; } inline hkUlong hkpShape::getUserData() const { return m_userData; } inline void hkpShape::setUserData( hkUlong data ) { m_userData = data; } void hkpShape::getAabb( const hkTransform& localToWorld, hkReal tolerance, hkAabb& out ) const { #if defined (HK_PLATFORM_SPU) (*m_shapeFunctions[m_type].m_getAabbFunc)(this, localToWorld, tolerance, out ); #else getAabbImpl( localToWorld, tolerance, out ); #endif } hkBool hkpShape::castRay( const hkpShapeRayCastInput& input, hkpShapeRayCastOutput& output ) const { #if defined (HK_PLATFORM_SPU) return (*m_shapeFunctions[m_type].m_castRay)( this, input, output ); #else return castRayImpl( input, output ); #endif } #if defined (HK_PLATFORM_SPU) hkUint32 hkpShape::getCollisionFilterInfo( hkpShapeKey key ) const { return (*m_shapeFunctions[m_type].m_getCollisionFilterInfoFunc)( this, key ); } const hkpShape* hkpShape::getChildShape( hkpShapeKey key, ShapeBuffer& buffer ) const { return (*m_shapeFunctions[m_type].m_getChildShapeFunc)( this, key, buffer ); } #endif /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 78 ] ] ]
1f2cd40791ae045487a869c43d9125ff0b0f5714
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/ipconnmgmt/connection_settings_api/src/cmmgrbc.cpp
513a4b04268f43d957d6857486c71ec0e8a26fc6
[]
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
14,943
cpp
/* * 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: This file contains Hardcoded module implementation. * */ #include <Stiftestinterface.h> #include <SettingServerClient.h> #include "cmmgrbc.h" // ----------------------------------------------------------------------------- // CCmmgrBc::CCmmgrBc // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CCmmgrBc::CCmmgrBc() { } // ----------------------------------------------------------------------------- // CCmmgrBc::ConstructL // Symbian 2nd phase constructor can leave. // // Note: If OOM test case uses STIF Logger, then STIF Logger must be created // with static buffer size parameter (aStaticBufferSize). Otherwise Logger // allocates memory from heap and therefore causes error situations with OOM // testing. For more information about STIF Logger construction, see STIF Users // Guide. // ----------------------------------------------------------------------------- // void CCmmgrBc::ConstructL() { // Read logger settings to check whether test case name is to be appended // to log file name. RSettingServer settingServer; CleanupClosePushL( settingServer ); TInt ret = settingServer.Connect(); if ( ret != KErrNone ) { User::Leave( ret ); } // Parse StifLogger defaults from STIF initialization file. TLoggerSettings loggerSettings; ret = settingServer.GetLoggerSettings( loggerSettings ); if ( ret != KErrNone ) { User::Leave( ret ); } CleanupStack::Pop( &settingServer ); settingServer.Close(); // Close Setting server session. iAddTestCaseTitleToLogName = loggerSettings.iAddTestCaseTitle; iVersionLogged = EFalse; iStdLog = CStifLogger::NewL( KCmmgrBcLogPath, KCmmgrBcLogFile ); iLog = iStdLog; _LIT( KLogStr, "cmmgrbc.dll - Connection Settings API BC tests" ); iLog->Log( KLogStr ); } // ----------------------------------------------------------------------------- // CCmmgrBc::NewL // Two-phased constructor. // ----------------------------------------------------------------------------- // CCmmgrBc* CCmmgrBc::NewL() { CCmmgrBc* self = new (ELeave) CCmmgrBc; CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } // Destructor CCmmgrBc::~CCmmgrBc() { iLog = NULL; delete iStdLog; iStdLog = NULL; delete iTCLog; iTCLog = NULL; } // ----------------------------------------------------------------------------- // CCmmgrBc::InitL // InitL is used to initialize the Test Module. // ----------------------------------------------------------------------------- // TInt CCmmgrBc::InitL( TFileName& /*aIniFile*/, TBool /*aFirstTime*/ ) { _LIT( KLogStr, "cmmgrbc.dll - Initialized" ); iLog->Log( KLogStr ); return KErrNone; } // ----------------------------------------------------------------------------- // CCmmgrBc::GetTestCasesL // GetTestCases is used to inquire test cases from the Test Module. Test cases // are stored to array of test cases. The Test Framework will be the owner of // the data in the RPointerArray after GetTestCases return and it does the // memory deallocation. // ----------------------------------------------------------------------------- // TInt CCmmgrBc::GetTestCasesL( const TFileName& /*aConfig*/, RPointerArray<TTestCaseInfo>& aTestCases ) { // Loop through all test cases and create new TTestCaseInfo items and // append items to aTestCase array. for ( TInt i = 0; Case(i).iMethod; i++ ) { // Allocate new TTestCaseInfo from heap for a testcase definition. TTestCaseInfo* newCase = new (ELeave) TTestCaseInfo(); // PushL TTestCaseInfo to CleanupStack. CleanupStack::PushL( newCase ); // Set number for the testcase. // When the testcase is run, this comes as a parameter to RunTestCaseL. newCase->iCaseNumber = i; // Set title for the test case. This is shown in UI to user. newCase->iTitle.Copy( Case(i).iCaseName ); // Append TTestCaseInfo to the testcase array. After appended // successfully the TTestCaseInfo object is owned (and freed) // by the TestServer. User::LeaveIfError( aTestCases.Append( newCase ) ); // Pop TTestCaseInfo from the CleanupStack. CleanupStack::Pop( newCase ); } _LIT( KLogStr, "cmmgrbc.dll - Loaded %d test cases" ); iLog->Log( KLogStr, aTestCases.Count() ); return KErrNone; } // ----------------------------------------------------------------------------- // CCmmgrBc::RunTestCaseL // RunTestCaseL is used to run an individual test case specified by aCaseNumber. // Test cases that can be run may be requested from Test Module by GetTestCases // method before calling RunTestCase. // ----------------------------------------------------------------------------- // TInt CCmmgrBc::RunTestCaseL( const TInt aCaseNumber, const TFileName& /*aConfig*/, TTestResult& aResult ) { if ( !iVersionLogged ) { SendTestModuleVersion(); iVersionLogged = ETrue; } // Return value TInt execStatus = KErrNone; // Get the pointer to test case function TCaseInfo tmp = Case( aCaseNumber ); _LIT( KLogStartTC, "Starting testcase [%S]" ); iLog->Log( KLogEmptyLine ); iLog->Log( KLogStartTC, &tmp.iCaseName ); // Check that case number was valid if ( tmp.iMethod ) { // Open new log file with test case title in file name if ( iAddTestCaseTitleToLogName ) { // Delete test case logger if exists if ( iTCLog ) { delete iTCLog; iTCLog = NULL; } TFileName logFileName; TName title; TestModuleIf().GetTestCaseTitleL( title ); logFileName.Format( KCmmgrBcLogFileWithTitle, &title ); iTCLog = CStifLogger::NewL( KCmmgrBcLogPath, logFileName ); iLog = iTCLog; } // Valid case was found, call it via function pointer iMethod = tmp.iMethod; TRAPD( err, execStatus = ( this->*iMethod )( aResult ) ); if ( iAddTestCaseTitleToLogName ) { // Restore standard log and destroy test case logger iLog = iStdLog; delete iTCLog; //Close test case log iTCLog = NULL; } User::LeaveIfError( err ); } else { // Valid case was not found, return error. execStatus = KErrNotFound; } // Return case execution status (not the result of the case execution). return execStatus; } // ----------------------------------------------------------------------------- // CCmmgrBc::OOMTestQueryL // Used to check if a particular test case should be run in OOM conditions and // which memory allocations should fail. // ----------------------------------------------------------------------------- // TBool CCmmgrBc::OOMTestQueryL( const TFileName& /*aTestCaseFile*/, const TInt aCaseNumber, TOOMFailureType& /*aFailureType*/, TInt& aFirstMemFailure, TInt& aLastMemFailure ) { aFirstMemFailure = Case( aCaseNumber ).iFirstMemoryAllocation; aLastMemFailure = Case( aCaseNumber ).iLastMemoryAllocation; return Case( aCaseNumber ).iIsOOMTest; } // ----------------------------------------------------------------------------- // CCmmgrBc::OOMTestInitializeL // Used to perform the test environment setup for a particular OOM test case. // Test Modules may use the initialization file to read parameters for Test // Module initialization but they can also have their own configure file or // some other routine to initialize themselves. // // NOTE: User may add implementation for OOM test environment initialization. // Usually no implementation is required. // ----------------------------------------------------------------------------- // void CCmmgrBc::OOMTestInitializeL( const TFileName& /*aTestCaseFile*/, const TInt /*aCaseNumber*/ ) { } // ----------------------------------------------------------------------------- // CCmmgrBc::OOMHandleWarningL // In some cases the heap memory allocation should be skipped, either due to // problems in the OS code or components used by the code being tested, or even // inside the tested components which are implemented this way on purpose (by // design), so it is important to give the tester a way to bypass allocation // failures. // // NOTE: User may add implementation for OOM test warning handling. Usually no // implementation is required. // ----------------------------------------------------------------------------- // void CCmmgrBc::OOMHandleWarningL( const TFileName& /*aTestCaseFile*/, const TInt /*aCaseNumber*/, TInt& /*aFailNextValue*/ ) { } // ----------------------------------------------------------------------------- // CCmmgrBc::OOMTestFinalizeL // Used to perform the test environment cleanup for a particular OOM test case. // // NOTE: User may add implementation for OOM test environment finalization. // Usually no implementation is required. // ----------------------------------------------------------------------------- // void CCmmgrBc::OOMTestFinalizeL( const TFileName& /*aTestCaseFile*/, const TInt /*aCaseNumber*/ ) { } //----------------------------------------------------------------------------- // CCmmgrBc::SendTestModuleVersion // Method used to send version of test module //----------------------------------------------------------------------------- // void CCmmgrBc::SendTestModuleVersion() { #ifdef CMMGRBC_S60_032_SUPPORT TVersion moduleVersion; moduleVersion.iMajor = TEST_MODULE_VERSION_MAJOR; moduleVersion.iMinor = TEST_MODULE_VERSION_MINOR; moduleVersion.iBuild = TEST_MODULE_VERSION_BUILD; _LIT( KTestDllName, "cmmgrbc.dll" ); TFileName moduleName; moduleName = KTestDllName; TBool newVersionOfMethod = ETrue; TestModuleIf().SendTestModuleVersion( moduleVersion, moduleName, newVersionOfMethod ); #endif // CMMGRBC_S60_032_SUPPORT } //----------------------------------------------------------------------------- // CCmmgrBc::SetTestCaseResult // Method used to set test case result according to error count. //----------------------------------------------------------------------------- // TInt CCmmgrBc::SetTestCaseResult( TTestResult& aResult, const TInt aErrorCount ) { _LIT( KLogCaseEnd, "Done, error count %d" ); iLog->Log( KLogCaseEnd, aErrorCount ); if ( aErrorCount != 0 ) { _LIT( KDescription, "Errors detected" ); aResult.SetResult( KErrGeneral, KDescription ); } else { _LIT( KDescription, "All OK" ); aResult.SetResult( KErrNone, KDescription ); } return KErrNone; } //----------------------------------------------------------------------------- // CCmmgrBc::MyDelay // A simple wait. Used to avoid possible CommsDat locked situations. // If no argument is given, waits according to the value defined in // KCmmgrbcDefaultDelayInMs //----------------------------------------------------------------------------- // void CCmmgrBc::MyDelay( const TInt aDelay ) { #ifdef CMMGRBC_ENABLE_DELAYS User::After( aDelay * KCmmgrbcMicroSecondsInMilliSecond ); #endif } // ========================== OTHER EXPORTED FUNCTIONS ========================= // ----------------------------------------------------------------------------- // LibEntryL is a polymorphic Dll entry point // Returns: CTestModuleBase*: Pointer to Test Module object // ----------------------------------------------------------------------------- // EXPORT_C CTestModuleBase* LibEntryL() { return CCmmgrBc::NewL(); } // ----------------------------------------------------------------------------- // SetRequirements handles test module parameters (implements evolution version // 1 for test module's heap and stack sizes configuring). // Returns: TInt: Symbian error code. // ----------------------------------------------------------------------------- // EXPORT_C TInt SetRequirements( CTestModuleParam*& /*aTestModuleParam*/, TUint32& /*aParameterValid*/ ) { /* --------------------------------- NOTE --------------------------------- USER PANICS occurs in test thread creation when: 1) "The panic occurs when the value of the stack size is negative." 2) "The panic occurs if the minimum heap size specified is less than KMinHeapSize". KMinHeapSize: "Functions that require a new heap to be allocated will either panic, or will reset the required heap size to this value if a smaller heap size is specified". 3) "The panic occurs if the minimum heap size specified is greater than the maximum size to which the heap can grow". Other: 1) Make sure that your hardware or Symbian OS is supporting given sizes. e.g. Hardware might support only sizes that are divisible by four. ------------------------------- NOTE end ------------------------------- */ // Normally STIF uses default heap and stack sizes for test thread, see: // KTestThreadMinHeap, KTestThreadMaxHeap and KStackSize. // If needed heap and stack sizes can be configured here by user. Remove // comments and define sizes. /* aParameterValid = KStifTestModuleParameterChanged; CTestModuleParamVer01* param = CTestModuleParamVer01::NewL(); // Stack size param->iTestThreadStackSize= 16384; // 16K stack // Heap sizes param->iTestThreadMinHeap = 4096; // 4K heap min param->iTestThreadMaxHeap = 1048576;// 1M heap max aTestModuleParam = param; */ return KErrNone; } // End of file
[ "none@none" ]
[ [ [ 1, 420 ] ] ]
caac42551e2d73c238f660745f5a23e99128b04b
2a6a2adbc18d74e89152324dacd7ffe190fcd7cc
/old/B(n, k)/B(n, k)/RankSet.h
fbcf3bd50c4079f2352739d87795bb3e6c6221f2
[]
no_license
swenson/Tabloid-Terror
fcb848e2bd9817009f8e0d5312162bd0d7d44825
8880b2af2da6f0635a311105d80f8b94bd7cc072
refs/heads/master
2021-01-16T22:46:01.908023
2010-12-08T02:29:21
2010-12-08T02:29:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,171
h
// RankSet.h: interface for the RankSet class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_RANKSET_H__1E9CDCC3_C3F8_11D5_8A63_0050BA79228E__INCLUDED_) #define AFX_RANKSET_H__1E9CDCC3_C3F8_11D5_8A63_0050BA79228E__INCLUDED_ #include "tabloid.h" #include "chain.h" #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 using namespace std; class RankSet:public list<int> { public: RankSet(); virtual ~RankSet(); Partition Shape(void); friend list<RankSet> ComputeRanks(const int n, const int k); list<tabloid> ComputeTabloids(void); friend chain ConvertFromTabloid(const tabloid t); Perm ReShape(void); list<int> Convert(void); friend ostream &operator<< (ostream &out_file, RankSet &u) { out_file << "\nRankSet: {"; bool flag = false; for (RankSet::const_iterator iter = u.begin(); iter != u.end(); ++iter) { out_file << " " << *iter; } out_file <<"}\n"; return(out_file); } }; list< RankSet > composition(const int n); #endif // !defined(AFX_RANKSET_H__1E9CDCC3_C3F8_11D5_8A63_0050BA79228E__INCLUDED_)
[ "smaug@blue.(none)" ]
[ [ [ 1, 47 ] ] ]
fb2dda667ac3f4e14002a136c7297493b1ab2ff9
8a223ca4416c60f4ad302bc045a182af8b07c2a5
/Orders-ListeningFakeProblem-Cpp/Orders-Untouchable-Cpp/src/Database.cpp
cf72a92d91b495cb944c04be224c7b672281c48d
[]
no_license
sinojelly/sinojelly
8a773afd0fcbae73b1552a217ed9cee68fc48624
ee40852647c6a474a7add8efb22eb763a3be12ff
refs/heads/master
2016-09-06T18:13:28.796998
2010-03-06T13:22:12
2010-03-06T13:22:12
33,052,404
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
/// *************************************************************************** /// Copyright (c) 2009, Industrial Logic, Inc., All Rights Reserved. /// /// This code is the exclusive property of Industrial Logic, Inc. It may ONLY be /// used by students during Industrial Logic's workshops or by individuals /// who are being coached by Industrial Logic on a project. /// /// This code may NOT be copied or used for any other purpose without the prior /// written consent of Industrial Logic, Inc. /// **************************************************************************** #include "Database.h" #include "SimulateAwkwardness.h" void Database::touchDatabase() { // Okay, okay, give us a break. The name of the game is not to implement a real system, it's to teach you // how to extract and override, slip, and fake. int milliseconds = SimulateAwkwardness::randomNumber(2000, 6000); SimulateAwkwardness::delay(milliseconds); }
[ "chenguodong@localhost" ]
[ [ [ 1, 22 ] ] ]
0be11233016f5a5556a69992ee9affcdcba889e5
c1c3866586c56ec921cd8c9a690e88ac471adfc8
/Practise_2005/Xvid.class/XvidDec.cpp
2133b364b7e36a0a7dddc714a95fc6714fc3108e
[]
no_license
rtmpnewbie/lai3d
0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f
b44c9edfb81fde2b40e180a651793fec7d0e617d
refs/heads/master
2021-01-10T04:29:07.463289
2011-03-22T17:51:24
2011-03-22T17:51:24
36,842,700
1
0
null
null
null
null
UTF-8
C++
false
false
3,082
cpp
#include "StdAfx.h" #include ".\xviddec.h" #include "xvid.h" CXvidDec::CXvidDec() { m_width = 0 ; m_height = 0 ; m_image = NULL ; m_dec_handle = NULL ; m_dec_caller = NULL ; } CXvidDec::~CXvidDec() { if(m_image) free(m_image) ; m_image = NULL ; } void CXvidDec::AttachCaller(int width, int height, CXvidDecHandler * dec_caller) { m_width = width ; m_height = height ; m_dec_caller = dec_caller ; if((m_width > 0) && (m_height > 0)) { int image_len = m_width * m_height * 3 ; m_image = (unsigned char *)malloc(image_len) ; memset(m_image, 0, image_len) ; CXvidDec::XVID_GLOBAL_INIT() ; } } bool CXvidDec::Close() { int xerr = 0 ; /* Destroy the encoder instance */ xerr = xvid_decore(m_dec_handle, XVID_ENC_DESTROY, NULL, NULL); return (xerr) ? false : true ; } void CXvidDec::XVID_GLOBAL_INIT() { /*------------------------------------------------------------------------ * XviD core initialization *----------------------------------------------------------------------*/ xvid_gbl_init_t xvid_gbl_init; memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init)); xvid_gbl_init.version = XVID_VERSION; xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ASM ; // force to use asm optimized routine /* Initialize XviD core -- Should be done once per __process__ */ xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL); } bool CXvidDec::Open() { if(!m_dec_caller) return false ; static xvid_dec_create_t xvid_dec_create ; int ret = 0; /*------------------------------------------------------------------------ * XviD encoder initialization *----------------------------------------------------------------------*/ memset(&xvid_dec_create, 0, sizeof(xvid_dec_create_t)); xvid_dec_create.version = XVID_VERSION; /* Width and Height of input frames */ xvid_dec_create.width = m_width ; xvid_dec_create.height = m_height ; ret = xvid_decore(NULL, XVID_DEC_CREATE, &xvid_dec_create, NULL) ; m_dec_handle = xvid_dec_create.handle; return true; } void CXvidDec::Decode(unsigned char * xvid, int xvid_len) { int ret = 0; ret = dec_core(xvid, m_image, xvid_len); if (ret > 0) m_dec_caller->PostDecHandler(m_image, ret) ; } /* raw xvid_encode procedure */ int CXvidDec::dec_core(unsigned char *bitstream,unsigned char *image, int bs_size) { int ret; xvid_dec_frame_t xvid_dec_frame; /* Reset all structures */ memset(&xvid_dec_frame, 0, sizeof(xvid_dec_frame_t)); /* Set version */ xvid_dec_frame.version = XVID_VERSION; //xvid_dec_stats->version = XVID_VERSION; /* No general flags to set */ xvid_dec_frame.general = 0; /* Input stream */ xvid_dec_frame.bitstream = bitstream; xvid_dec_frame.length = bs_size; /* Output frame structure */ xvid_dec_frame.output.plane[0] = image; xvid_dec_frame.output.stride[0] = m_width*3; xvid_dec_frame.output.csp = XVID_CSP_BGR; ret = xvid_decore(m_dec_handle, XVID_DEC_DECODE, &xvid_dec_frame, NULL); return(ret); }
[ "laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5" ]
[ [ [ 1, 107 ] ] ]
c220226a2e1ddb1c6ddf4dad67725020e936e45a
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/include/HydraControls/HydraPaneContainer.h
5167c19ac9eb62b68d4ea5df8d52d93c8bc73386
[]
no_license
john-peterson/hydrairc
5139ce002e2537d4bd8fbdcebfec6853168f23bc
f04b7f4abf0de0d2536aef93bd32bea5c4764445
refs/heads/master
2021-01-16T20:14:03.793977
2010-04-03T02:10:39
2010-04-03T02:10:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
h
#pragma once // TODO: add protected, m_UsingCustomColors, detect systemsetting change and reset the colors of not using custom colors class CHydraPaneContainer : public CPaneContainerImpl<CHydraPaneContainer> { protected: BOOL m_GradientFilled; BOOL m_AlternateStyle; public: typedef CPaneContainerImpl<CHydraPaneContainer> baseClass; DECLARE_WND_CLASS_EX(_T("Hydra_PaneContainer"), 0, -1) CHydraPaneContainer() : m_GradientFilled(0), m_AlternateStyle(1) { ResetColors(); } COLORREF m_TitleColor; COLORREF m_TitleGradientColor; // not used if m_GradientFilled is not enabled. COLORREF m_TextColor; // not used if m_AlternateStyle is not enabled. void SetGradientFill(BOOL NewValue) { m_GradientFilled = NewValue; ResetColors(); } void SetAlternateStyle(BOOL NewValue) { m_AlternateStyle = NewValue; ResetColors();} void ResetColors( void ) { m_TextColor = RGB(0xFF,0xFF,0xFF); // WHITE m_TitleColor = ::GetSysColor(COLOR_ACTIVECAPTION); m_TitleGradientColor = ::GetSysColor(COLOR_GRADIENTACTIVECAPTION); if (!m_GradientFilled) { m_TextColor = ::GetSysColor(COLOR_WINDOWTEXT); m_TitleColor = ::GetSysColor(COLOR_3DFACE); } } // Overrides void DrawPaneTitle(CDCHandle dc); void DrawButtonImage(CDCHandle dc, RECT& rcImage, HPEN hPen); };
[ "hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0" ]
[ [ [ 1, 45 ] ] ]
e4310758c7661f8c1ae1c79c00a9089b006e84e1
221e3e713891c951e674605eddd656f3a4ce34df
/core/OUE/Logger.cpp
413c7aa91c1c732df90ecc0709cdd0386c219e2c
[ "MIT" ]
permissive
zacx-z/oneu-engine
da083f817e625c9e84691df38349eab41d356b76
d47a5522c55089a1e6d7109cebf1c9dbb6860b7d
refs/heads/master
2021-05-28T12:39:03.782147
2011-10-18T12:33:45
2011-10-18T12:33:45
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,738
cpp
/* This source file is part of OneU Engine. Copyright (c) 2011 Ladace Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "OneUPreDef.h" #include "Impl/LoggerDisk.h" #include "String.h" #include <cstdlib> #include <memory> namespace OneU { //ILoggerµ¥Ì¬Ö¸Õë static ILogger * _Logger_pInstance = NULL; extern "C" ONEU_API void Logger_build(Factory<ILogger>::type lf){ if(!_Logger_pInstance){ _Logger_pInstance = lf(); } } extern "C" ONEU_API ILogger& GetLogger() { ONEU_ASSERT( _Logger_pInstance );return *_Logger_pInstance; } extern "C" ONEU_API void Logger_destroy(){ if(_Logger_pInstance != NULL){ ONEU_DELETE _Logger_pInstance; _Logger_pInstance = NULL; } } }
[ "[email protected]@d30a3831-f586-b1a3-add9-2db6dc386f9c" ]
[ [ [ 1, 51 ] ] ]
add22a14d6db9e5d19259c88faa0dd7d6358a64e
71882b6a275379ef37aedd30f4782d6d97831846
/HW3-07233009.cpp
636e0ed8550e49cf2a3f5d53d074ce3ab2b323ef
[]
no_license
adedebali07/C_Programlamaya_Giris
c54a8cd5dcae1de94558c5579925efe1c44008f2
b949528876650b546f974b8ba015af6a035ae7cf
refs/heads/master
2016-09-05T16:25:00.601661
2009-07-20T02:09:43
2009-07-20T02:09:43
null
0
0
null
null
null
null
ISO-8859-9
C++
false
false
2,507
cpp
//07233009 Adem Dedebali #include <stdio.h> #include <conio.h> void main () { char cevap[11] = {"abcdeabcde"}; //Programın içinde gömülü olan cevaplar tanımlanmıştır char cevap2[11]; //Karşılaştırma için kullanılmıştır char dogrusayisi[10]; //Eğer 127 den büyük bir değer olacaksa int olarak tanımlanmalıdır //ancak bellekte boşuna yer kaplamaması için char olarak tanımladım //Hangi soruya kaç kişinin doğru cevap verdiğini sayan değişken int ogrenci = 0; //Kaç öğrenciye bakıldığını gösteren değişken int dogru; //Her bir öğrencinin doğru ve yanlışlarını sayan değişken int i = 0; //Döngü değişkeni char dongucevap = 'e'; //En dış döngünün değişkeni. h olmadığı sürece döngüye girecek for (i=0; i<10; i++) dogrusayisi[i] = 0; //Dizinin her elemanı 0'a eşitlenmiştir for (;;) //Sonsuz döngü { ogrenci++; // Öğrenci sayısı bir artırılır dogru = 0; // Öğrencinin doğru ve yanlış adetleri 0'a eşitlenir for (i=0; i<10; i++) //Öğrencinin her bir soruya verdiği cevabı almak için kurulan döngü { printf ("%2d. soru:", i+1); // Kaçıncı soruda olduğumuzu gösterir cevap2[i] = getche (); // İşlemin hızlı olması açısından cevabı entere basmadan getche() fonksiyonu alır printf ("\n"); if (cevap[i] == cevap2[i]) // Gömülü olan cevapla öğrencinin cevabı karşılaştırılır. Eşitse: { dogru++; // Öğrencinin doğru sayısı 1 artırılır dogrusayisi[i]++; // Genel olarak bu soruya verilen doğru cevaba 1 eklenir } } printf ("\n"); printf ("Dogru : %d\n", dogru); // Doğru sayisi yazdırılır printf ("Yanlis: %d\n", 10 - dogru); //Yanlış sayısı yazdırılır. Soru sayısı değişirse 10 değeri değiştirmelidir printf ("Baska ogrenci girecek misiniz(e/h):"); dongucevap = getche (); // Cevap getche () fonksiyonuna aktarılır printf ("\n"); if (dongucevap == 'h' || dongucevap == 'H') break; // Döngü sonsuz kurulduğu için cevabın H olması durumunda döngüden atar } printf ("_______________________________\n"); printf ("%d ogrencinin sonucuna baktiniz...\n", ogrenci); printf ("Sorularin istatislik sonuclari:\n"); for (i=0; i<10; i++) // Döngüyle soruların istatislik sonuçlarına bakılır printf ("%2d. soruya %d ogrenci dogru, %d ogrenci yanlis cevap vermistir...\n", i+1, dogrusayisi[i], ogrenci - dogrusayisi[i]); }
[ [ [ 1, 46 ] ] ]
263cea5ac770e4a2e4d821f963397d9bfb0ac7c3
65da00cc6f20a83dd89098bb22f8f93c2ff7419b
/HabuGraphics/Library/Include/Object.hpp
65aee16410338997dab29b092b5c32188fcff59e
[]
no_license
skevy/CSC-350-Assignment-5
8b7c42257972d71e3d0cd3e9566e88a1fdcce73c
8091a56694f4b5b8de7e278b64448d4f491aaef5
refs/heads/master
2021-01-23T11:49:35.653361
2011-04-20T02:20:06
2011-04-20T02:20:06
1,638,578
0
0
null
null
null
null
UTF-8
C++
false
false
6,386
hpp
//***************************************************************************// // Object Class Interface // // Created: February 1, 2007 // By: Jeremy M Miller // // Copyright (c) 2007-2010 Jeremy M Miller. All rights reserved. // This source code module, and all information, data, and algorithms // associated with it, are part of BlueHabu technology (tm). // // Usage of HabuGraphics is subject to the appropriate license agreement. // A proprietary/commercial licenses are available. // // HabuGraphics 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. // // HabuGraphics 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 HabuGraphics. If not, see <http://www.gnu.org/licenses/>. //***************************************************************************// #ifndef HABU_GRAPHICS_OBJECT_HPP #define HABU_GRAPHICS_OBJECT_HPP //***************************************************************************// // BlueHabu Technologies Includes #include <HabuMath.hpp> //***************************************************************************// //***************************************************************************// namespace HabuTech { //*************************************************************************// // Object is the base class for all objects in a 3D scene class Object { private: //***********************************************************************// //***********************************************************************// protected: //***********************************************************************// //-----------------------------------------------------------------------// // Describes the position of the object. HabuTech::Vector<float, 4> mPosition; // Position is a vector so we can use HabuMath's Dot function HabuTech::Vector<float, 4> mForwardVector; HabuTech::Vector<float, 4> mRightVector; HabuTech::Vector<float, 4> mUpVector; //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// float mfPitch; float mfYaw; float mfRoll; //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// HabuTech::Matrix<float, 4> mTransformMatrix; //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// void TransformToModelSpace(); void TransformToViewSpace(); //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// /// Name of object std::string mstrName; //-----------------------------------------------------------------------// void Create(const std::string& rstrName); void Clone(const Object& rSource); void Destroy(); //***********************************************************************// public: //***********************************************************************// //-----------------------------------------------------------------------// Object(const std::string& rstrName); Object(const Object& rSource); Object(const Object& rSource, const std::string& rStrDestinationname); virtual ~Object(); //-----------------------------------------------------------------------// Object& Object::operator=(const Object& rSource) { if(this != &rSource) { Clone(rSource); } return *this; } //-----------------------------------------------------------------------// const std::string& Name() const { return mstrName; } void Name(const std::string& rstrName); //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// virtual void RelativePitch(float fAngle); virtual void RelativeRoll(float fAngle); virtual void RelativeYaw(float fAngle); virtual void AbsolutePitch(float fAngle); virtual void AbsoluteRoll(float fAngle); virtual void AbsoluteYaw(float fAngle); //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// virtual void _cdecl Position(float fX, float fY, float fZ); //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// virtual void Move(float fX, float fY, float fZ); /// Moves the object left or right relative to its current orientation virtual void Strafe(float fX); /// Moves the object forward or backwards relative to its current orientation virtual void Advance(float fZ); /// Moves the object up or down relative to its current orientation virtual void Elevate(float fY); //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// virtual void Forward(float fX, float fY, float fZ); virtual void Up(float fX, float fY, float fZ); virtual void Right(float fX, float fY, float fZ); //-----------------------------------------------------------------------// //***********************************************************************// }; // End of class Object //*************************************************************************// } // End of namespace HabuTech //***************************************************************************// #endif HABU_GRAPHICS_OBJECT_HPP
[ [ [ 1, 139 ] ] ]
ba19f4ee46fb22983cb1e98f00472e770dd937cc
918c8a14d31946cef59d68420d0f4a8ed4752001
/waveletshadow/src/CMeshLoader.cpp
f81b0f866cb0c22623bc794b18f132a91d36acad
[]
no_license
rroc/ibrproject
a67b2565402c1eed0c14363633a52c0a81974c0b
69dbaea6e2de7c00e82d9d08fab20341ba21fac5
refs/heads/master
2021-01-01T16:06:46.943270
2009-04-03T20:14:15
2009-04-03T20:14:15
34,713,409
0
0
null
null
null
null
UTF-8
C++
false
false
36,845
cpp
#include "CMeshLoader.h" #include <string> #include "index_t.h" //========// // macros // //========// #define VEC_Add(a, b, c) ((c)[0] = (a)[0] + (b)[0], (c)[1] = (a)[1] + (b)[1], (c)[2] = (a)[2] + (b)[2]) #define VEC_AddTo(a, b) ((a)[0] += (b)[0], (a)[1] += (b)[1], (a)[2] += (b)[2]) #define VEC_AddScalar(a, b, c) ((c)[0] = (a)[0] + (b), (c)[1] = (a)[1] + (b), (c)[2] = (a)[2] + (b)) #define VEC_AddScalarTo(a, b) ((a)[0] += (b), (a)[1] += (b), (a)[2] += (b)) #define VEC_Copy(a, b) ((b)[0] = (a)[0], (b)[1] += (a)[1], (b)[2] += (a)[2]) #define VEC_Cross(a, b, c) ((c)[0] = (a)[1] * (b)[2] - (a)[2] * (b)[1], (c)[1] = (a)[2] * (b)[0] - (a)[0] * (b)[2], (c)[2] = (a)[0] * (b)[1] - (a)[1] * (b)[0]) #define VEC_Divide(a, b, c) ((c)[0] = (a)[0] / (b)[0], (c)[1] = (a)[1] / (b)[1], (c)[2] = (a)[2] / (b)[2]) #define VEC_DivideBy(a, b) ((a)[0] /= (b)[0], (a)[1] /= (b)[1], (a)[2] /= (b)[2]) #define VEC_DivideByScalar(v, s) ((v)[0] /= s, (v)[1] /= s, (v)[2] /= s) #define VEC_DivideScalar(v, s, o) ((o)[0] = (v)[0] / s, (o)[1] = (v)[1] / s, (o)[2] = v[2] / s) #define VEC_DotProduct(a, b) ((a)[0] * (b)[0] + (a)[1] * (b)[1] + (a)[2] * (b)[2]) #define VEC_Dot4(a, b) ((a)[0] * (b)[0] + (a)[1] * (b)[1] + (a)[2] * (b)[2] + (a)[3] * (b)[3]) #define VEC_MidPoint(a, b, c) ((c)[0] = (b)[0] + ((a)[0] - (b)[0]) * 0.5f, (c)[1] = (b)[1] + ((a)[1] - (b)[1]) * 0.5f, (c)[2] = (b)[2] + ((a)[2] - (b)[2]) * 0.5f) #define VEC_Mult(a, b, c) ((c)[0] = (a)[0] * (b)[0], (c)[1] = (a)[1] * (b)[1], (c)[2] = (a)[2] * (b)[2]) #define VEC_MultBy(a, b) ((a)[0] *= (b)[0], (a)[1] *= (b)[1], (a)[2] *= (b)[2]) #define VEC_MultByScalar(v, s) ((v)[0] *= s, (v)[1] *= s, (v)[2] *= s) #define VEC_MultScalar(v, s, o) ((o)[0] = (v)[0] * s, (o)[1] = (v)[1] * s, (o)[2] = v[2] * s) #define VEC_Negate(a, b) ((b)[0] = -(a)[0], (b)[1] = -(a)[1], (b)[2] = -(a)[2]) #define VEC_Scale(v, s, o) ((o)[0] = (v)[0] * s, (o)[1] = (v)[1] * s, (o)[2] = v[2] * s) #define VEC_ScaleBy(v, s) ((v)[0] *= s, (v)[1] *= s, (v)[2] *= s) #define VEC_Set(v, x, y, z) ((v)[0] = x, (v)[1] = y, (v)[2] = z) #define VEC_Subtract(a, b, c) ((c)[0] = (a)[0] - (b)[0], (c)[1] = (a)[1] - (b)[1], (c)[2] = (a)[2] - (b)[2]) #define VEC_SubtractFrom(a, b) ((a)[0] -= (b)[0], (a)[1] -= (b)[1], (a)[2] -= (b)[2]) #define VEC_Magnitude(v) (sqrt((v)[0] * (v)[0] + (v)[1] * (v)[1] + (v)[2] * (v)[2])) #define VEC_Normalize(v) { double __mag = 1.0 / VEC_Magnitude(v); \ (v)[0] *= __mag; (v)[1] *= __mag; (v)[2] *= __mag; } #define VEC_Normalizef(v) { float __mag = 1.0f / (float)VEC_Magnitude(v); \ (v)[0] *= __mag; (v)[1] *= __mag; (v)[2] *= __mag; } typedef int (*TSortFunc)(const void*, const void*); int CompareLong(long* a, long* b) { if (*a > *b) { return 1; } if (*a < *b) { return -1; } return 0; } //FOR NORMAL CALCULATION //--------------------------- int ComparePosition(float *a, float *b) { int i; for (i = 0; i < 3; i++) { if (a[i] > b[i]) { return 1; } if (a[i] < b[i]) { return -1; } } return 0; } //------------------------------------------ #define FREE(p) if (p){ free(p); p = NULL; } CMeshLoader::CMeshLoader(void) { } CMeshLoader::~CMeshLoader(void) { Free3dsData(); if(NULL != iDataInfo ) delete iDataInfo; } void CMeshLoader::Calculate3dsBoundingBox( T3dsInfo* aData ) { for (int i = 0; i < aData->iMeshCount; i++) { CalculateMesh3dsBoundingBox(&aData->iMeshes[i]); if (i == 0) { memcpy(aData->iMax, aData->iMeshes[i].iMax, sizeof(float) * 3); memcpy(aData->iMin, aData->iMeshes[i].iMin, sizeof(float) * 3); } else { for (int j = 0; j < 3; j++) { if (aData->iMeshes[i].iMax[j] > aData->iMax[j]) { aData->iMax[j] = aData->iMeshes[i].iMax[j]; } if (aData->iMeshes[i].iMin[j] < aData->iMin[j]) { aData->iMin[j] = aData->iMeshes[i].iMin[j]; } } } } aData->iCenter[0] = aData->iMin[0] + (aData->iMax[0] - aData->iMin[0]) * 0.5f; aData->iCenter[1] = aData->iMin[1] + (aData->iMax[1] - aData->iMin[1]) * 0.5f; aData->iCenter[2] = aData->iMin[2] + (aData->iMax[2] - aData->iMin[2]) * 0.5f; } void CMeshLoader::CalculateMesh3dsBoundingBox( T3dsMesh* aMesh ) { for( int i = 0; i < aMesh->iVertCount; i++ ) { if( i == 0 ) { memcpy(aMesh->iMax, aMesh->iVertices[i], sizeof(float) * 3); memcpy(aMesh->iMin, aMesh->iVertices[i], sizeof(float) * 3); } else { for(int j = 0; j < 3; j++) { if (aMesh->iVertices[i][j] > aMesh->iMax[j]) { aMesh->iMax[j] = aMesh->iVertices[i][j]; } if (aMesh->iVertices[i][j] < aMesh->iMin[j]) { aMesh->iMin[j] = aMesh->iVertices[i][j]; } } } } aMesh->iCenter[0] = aMesh->iMin[0] + (aMesh->iMax[0] - aMesh->iMin[0]) * 0.5f; aMesh->iCenter[1] = aMesh->iMin[1] + (aMesh->iMax[1] - aMesh->iMin[1]) * 0.5f; aMesh->iCenter[2] = aMesh->iMin[2] + (aMesh->iMax[2] - aMesh->iMin[2]) * 0.5f; } void CMeshLoader::Calculate3dsNormals( T3dsInfo* model) { int i; for (i = 0; i < model->iMeshCount; i++) { CalculateMeshNormals(&model->iMeshes[i]); } } //====================================================================// // compute normals for this mesh taking smoothing groups into account // //====================================================================// void CMeshLoader::CalculateMeshNormals( T3dsMesh* aMesh ) { int i, j, k; int normCount; long (*triRefs)[50]; float (*faceNorms)[3]; float v1[3]; float v2[3]; //======================// // allocate the normals // //======================// aMesh->iNormals = (float(*)[3])malloc(sizeof(float) * 3 * aMesh->iTriCount * 3); if (aMesh->iNormals == NULL) { return; } memset(aMesh->iNormals, 0, sizeof(float) * 3 * aMesh->iTriCount * 3); if (aMesh->iSmooth == NULL) { for (i = 0; i < aMesh->iTriCount; i++) { VEC_Subtract(aMesh->iVertices[aMesh->iTriangles[i][1]], aMesh->iVertices[aMesh->iTriangles[i][0]], v1); VEC_Subtract(aMesh->iVertices[aMesh->iTriangles[i][2]], aMesh->iVertices[aMesh->iTriangles[i][0]], v2); VEC_Cross(v1, v2, aMesh->iNormals[i * 3]); VEC_Normalizef(aMesh->iNormals[i * 3]); memcpy(aMesh->iNormals[i * 3 + 1], aMesh->iNormals[i * 3], sizeof(float) * 3); memcpy(aMesh->iNormals[i * 3 + 2], aMesh->iNormals[i * 3], sizeof(float) * 3); } return; } index_t vertIndex; int vert = 0; int result = 0; //============================================// // index the vertices based on position alone // //============================================// indexArray( &vertIndex, (char*)aMesh->iVertices, sizeof(float) * 3, aMesh->iVertCount, (TSortFunc)ComparePosition ); //============================================================================// // build a table that links each vertex to all triangles that use said vertex // //============================================================================// triRefs = (long(*)[50])malloc(sizeof(long) * 50 * vertIndex.count); if (triRefs == NULL) { return; } memset(triRefs, 0, sizeof(unsigned long) * 50 * vertIndex.count); for (i = 0; i < aMesh->iTriCount; i++) { for (j = 0; j < 3; j++) { vert = indexFind(&vertIndex, aMesh->iVertices[aMesh->iTriangles[i][j]], &result); if (triRefs[vert][0] < 48) { triRefs[vert][0]++; triRefs[vert][triRefs[vert][0]] = i; } } } //========================================// // allocate a buffer for the flat normals // //========================================// faceNorms = (float(*)[3])malloc(sizeof(float) * 3 * aMesh->iTriCount); if ((faceNorms != NULL) && (triRefs != NULL)) { memset(faceNorms, 0, sizeof(float) * 3 * aMesh->iTriCount); //==============================================// // go through every triangle to find its normal // //==============================================// for (i = 0; i < aMesh->iTriCount; i++) { VEC_Subtract(aMesh->iVertices[aMesh->iTriangles[i][1]], aMesh->iVertices[aMesh->iTriangles[i][0]], v1); VEC_Subtract(aMesh->iVertices[aMesh->iTriangles[i][2]], aMesh->iVertices[aMesh->iTriangles[i][0]], v2); VEC_Cross(v1, v2, faceNorms[i]); VEC_Normalizef(faceNorms[i]); } for (i = 0; i < aMesh->iTriCount; i++) { for (j = 0; j < 3; j++) { vert = indexFind(&vertIndex, aMesh->iVertices[aMesh->iTriangles[i][j]], &result); normCount = 0; for (k = 1; k <= triRefs[vert][0]; k++) { if (aMesh->iSmooth[i] == aMesh->iSmooth[triRefs[vert][k]]) { VEC_AddTo(aMesh->iNormals[i * 3 + j], faceNorms[triRefs[vert][k]]); normCount++; } } VEC_DivideByScalar(aMesh->iNormals[i * 3 + j], (float)normCount); VEC_Normalizef(aMesh->iNormals[i * 3 + j]); } } } indexFree(&vertIndex); //==========================================// // free up the local buffers that were used // //==========================================// if (triRefs) { free(triRefs); } if (faceNorms) { free(faceNorms); } } // // PSP SDK does not support cin so the c-style loading is used // int CMeshLoader::Load3Ds( char* aFilename, const float aScale ) { iScale = aScale; iDataInfo = new T3dsInfo(); //read file in binary form iFile = fopen( aFilename, "rb"); //FILE OPENED OK if( iFile ) { printf(" File Found. )\n" ); T3dsChunk chunk; // unsigned char byte[4]; fseek( iFile, 0, SEEK_SET); chunk = ReadChunk(); //fread( &chunk, sizeof( unsigned char ), 2, iFile ); //fread( &byte, sizeof( unsigned char ), 4, iFile ); //chunk.iLength = *(reinterpret_cast<unsigned long*>(&byte) ); // printf(" chunk: 0x%x, %d (%d)\n", chunk.iId, chunk.iLength, sizeof( T3dsChunk ) ); //printf(" chunk: %x %x %x %x %x %x (%d)\n", byte[0], byte[1],byte[2], byte[3],byte[4], byte[5], sizeof( unsigned char ) ); /* for(int i=0;i<15;i++) { // fread( &chunk, sizeof( sizeof( unsigned short )+sizeof( unsigned long ) ), 1, iFile ); fread( &chunk, sizeof( unsigned char ), 2, iFile ); fread( &byte, sizeof( unsigned char ), 4, iFile ); chunk.iLength = *(reinterpret_cast<unsigned long*>(&byte) ); // printf(" chunk: 0x%x, %d (%d)\n", chunk.iId, chunk.iLength, sizeof( T3dsChunk ) ); //printf(" chunk: %x %x %x %x %x %x (%d)\n", byte[0], byte[1],byte[2], byte[3],byte[4], byte[5], sizeof( unsigned char ) ); } return 1; */ //main 3ds (the main) if( 0x4d4d == chunk.iId ) { printf(" 3ds file\n"); ReadChunkArray( chunk.iLength - 6, &CMeshLoader::ReadMain3ds ); } //all done, close the file fclose( iFile ); } //file not found... exit gracefully else { fclose( iFile ); printf(" Mesh File: \"%s\" NOT Found. )\n", aFilename ); return(-1); } printf(" Looking inside the 3ds data...\n"); //Prepare object for (int i = 0; i < iDataInfo->iMeshCount; i++) { RemoveDegenerates( &iDataInfo->iMeshes[i] ); SortTriangles( &iDataInfo->iMeshes[i] ); } iDataInfo->iVertCount = 0; iDataInfo->iTriCount = 0; for (int i = 0; i < iDataInfo->iMeshCount; i++) { iDataInfo->iVertCount += iDataInfo->iMeshes[i].iVertCount; iDataInfo->iTriCount += iDataInfo->iMeshes[i].iTriCount; } printf(" Proceed with normals."); Calculate3dsBoundingBox( iDataInfo ); Calculate3dsNormals( iDataInfo ); // Calculate3dsTangentSpace(output); printf(" Data Ready. (Meshes:%d, Vertices:%d, Triangles:%d)\n", iDataInfo->iMeshCount, iDataInfo->iVertCount, iDataInfo->iTriCount); return iDataInfo->iMeshCount; } //Extract the 3ds data to mesh CMesh* CMeshLoader::GetMesh( int aIndex ) { if( iDataInfo->iMeshCount <= aIndex ) { printf(" Mesh out of bounds:(Max: %d, Wanted: %d)\n", iDataInfo->iMeshCount, aIndex ); return NULL; } CMesh* mesh = new CMesh(); mesh->iName = iDataInfo->iMeshes[aIndex].iName; mesh->iMin.iX = iDataInfo->iMeshes[aIndex].iMin[0]; mesh->iMax.iX = iDataInfo->iMeshes[aIndex].iMax[0]; mesh->iMin.iY = iDataInfo->iMeshes[aIndex].iMin[1]; mesh->iMax.iY = iDataInfo->iMeshes[aIndex].iMax[1]; mesh->iMin.iZ = iDataInfo->iMeshes[aIndex].iMin[2]; mesh->iMax.iZ = iDataInfo->iMeshes[aIndex].iMax[2]; printf("MESH:\"%s\"(%d),MAT:\"%s\"(%d),\tVRT: ", mesh->iName.c_str(), aIndex, iDataInfo->iMaterials[iDataInfo->iMeshes[aIndex].iGroups[0].iMat].iName, iDataInfo->iMeshes[aIndex].iGroups[0].iMat ); mesh->iMaterialColor = TColorRGBA( iDataInfo->iMaterials[iDataInfo->iMeshes[aIndex].iGroups[0].iMat].iDiffuse[0] , iDataInfo->iMaterials[iDataInfo->iMeshes[aIndex].iGroups[0].iMat].iDiffuse[1] , iDataInfo->iMaterials[iDataInfo->iMeshes[aIndex].iGroups[0].iMat].iDiffuse[2] , iDataInfo->iMaterials[iDataInfo->iMeshes[aIndex].iGroups[0].iMat].iDiffuse[3] ); // printf(" Mesh Color: (%f, %f, %f, %f)\n", mesh->iMaterialColor.iR, mesh->iMaterialColor.iG, mesh->iMaterialColor.iB, mesh->iMaterialColor.iA ); //COPY VERTICES // printf(" Copy vertices & normals: "); TVector3 vectorData; for( int i=0, j=iDataInfo->iMeshes[aIndex].iVertCount; i<j; i++) { printf("\b\b\b\b\b\b%6d", i+1 ); //Texture coordinates //container.iTextureCoords.set( // ( *iDataInfo->iMeshes[aIndex].iTexCoords+(i*2) )[0] //, ( *iDataInfo->iMeshes[aIndex].iTexCoords+(i*2) )[1] //); //Vertices vectorData.set( ( *iDataInfo->iMeshes[aIndex].iVertices+(i*3) )[0] ,( *iDataInfo->iMeshes[aIndex].iVertices+(i*3) )[1] ,( *iDataInfo->iMeshes[aIndex].iVertices+(i*3) )[2] ); mesh->addVertex( vectorData ); //normals vectorData.set( ( *iDataInfo->iMeshes[aIndex].iNormals+(i*3) )[0] , ( *iDataInfo->iMeshes[aIndex].iNormals+(i*3) )[1] , ( *iDataInfo->iMeshes[aIndex].iNormals+(i*3) )[2] ); mesh->iVertexNormals.push_back( vectorData ); } //COPY TRIANGLES printf(",TRI: "); for( int i=0, j=iDataInfo->iMeshes[aIndex].iTriCount; i<j; i++ ) { printf("\b\b\b\b\b\b\b\b%8d", i+1 ); mesh->addTriangle( TTriangle( ( *iDataInfo->iMeshes[aIndex].iTriangles+(i*3) )[0] , ( *iDataInfo->iMeshes[aIndex].iTriangles+(i*3) )[1] , ( *iDataInfo->iMeshes[aIndex].iTriangles+(i*3) )[2] ) ); } printf(".\n"); return mesh; } void CMeshLoader::Free3dsData() { int i, j; printf(" Free 3ds\n"); if (iDataInfo->iMeshes) { for (i = 0; i < iDataInfo->iMeshCount; i++) { FREE(iDataInfo->iMeshes[i].iVertices); FREE(iDataInfo->iMeshes[i].iTriangles); FREE(iDataInfo->iMeshes[i].iNormals); FREE(iDataInfo->iMeshes[i].iTangentSpace); FREE(iDataInfo->iMeshes[i].iTexCoords); FREE(iDataInfo->iMeshes[i].iSmooth); if (iDataInfo->iMeshes[i].iGroups) { for (j = 0; j < iDataInfo->iMeshes[i].iGroupCount; j++) { FREE(iDataInfo->iMeshes[i].iGroups[j].iTris); } FREE(iDataInfo->iMeshes[i].iGroups); } } free(iDataInfo->iMeshes); } FREE(iDataInfo->iMaterials); memset(iDataInfo, 0, sizeof(T3dsInfo)); printf(" Mesh Freed.\n"); } void CMeshLoader::RemoveDegenerates(T3dsMesh* aMesh) { int i; int j; int k; int l; long* found; for (i = 0; i < aMesh->iTriCount; i++) { if ((aMesh->iTriangles[i][0] >= aMesh->iVertCount) || (aMesh->iTriangles[i][1] >= aMesh->iVertCount) || (aMesh->iTriangles[i][2] >= aMesh->iVertCount)) { i = i; } } for (i = 0;i < aMesh->iGroupCount; i++) { qsort(aMesh->iGroups[i].iTris, aMesh->iGroups[i].iSize, sizeof(long), (TSortFunc)CompareLong); } for (i = 0; i < aMesh->iTriCount; i++) { if (((aMesh->iTriangles[i][0] == aMesh->iTriangles[i][1]) || (aMesh->iTriangles[i][0] == aMesh->iTriangles[i][2]) || (aMesh->iTriangles[i][1] == aMesh->iTriangles[i][2])) || ((aMesh->iVertices[aMesh->iTriangles[i][0]][0] == aMesh->iVertices[aMesh->iTriangles[i][1]][0]) && (aMesh->iVertices[aMesh->iTriangles[i][0]][1] == aMesh->iVertices[aMesh->iTriangles[i][1]][1]) && (aMesh->iVertices[aMesh->iTriangles[i][0]][2] == aMesh->iVertices[aMesh->iTriangles[i][1]][2])) || ((aMesh->iVertices[aMesh->iTriangles[i][0]][0] == aMesh->iVertices[aMesh->iTriangles[i][2]][0]) && (aMesh->iVertices[aMesh->iTriangles[i][0]][1] == aMesh->iVertices[aMesh->iTriangles[i][2]][1]) && (aMesh->iVertices[aMesh->iTriangles[i][0]][2] == aMesh->iVertices[aMesh->iTriangles[i][2]][2])) || ((aMesh->iVertices[aMesh->iTriangles[i][1]][0] == aMesh->iVertices[aMesh->iTriangles[i][2]][0]) && (aMesh->iVertices[aMesh->iTriangles[i][1]][1] == aMesh->iVertices[aMesh->iTriangles[i][2]][1]) && (aMesh->iVertices[aMesh->iTriangles[i][1]][2] == aMesh->iVertices[aMesh->iTriangles[i][2]][2]))) { if (i != (aMesh->iTriCount - 1)) { memmove(&aMesh->iTriangles[i], &aMesh->iTriangles[i+1], sizeof(long) * 3 * (aMesh->iTriCount - i - 1)); } for (j = 0; j < aMesh->iGroupCount; j++) { found = (long*)bsearch(&i, aMesh->iGroups[j].iTris, aMesh->iGroups[j].iSize, sizeof(long), (TSortFunc)CompareLong); if (found != NULL) { k = ((int)found - (int)aMesh->iGroups[j].iTris) / sizeof(long); if (k < aMesh->iGroups[j].iSize - 1) { memmove(&aMesh->iGroups[j].iTris[k], &aMesh->iGroups[j].iTris[k+1], sizeof(long) * (aMesh->iGroups[j].iSize - k - 1)); } aMesh->iGroups[j].iSize--; for (l = k; l < aMesh->iGroups[j].iSize; l++) { aMesh->iGroups[j].iTris[l]--; } } } aMesh->iTriCount--; i--; } } } //reads an ASCII string from 3ds file void CMeshLoader::ReadString(char* aString) { // printf(" Reading string\n"); int i = 0; do { fread(&aString[i], sizeof(char), 1, iFile); } while ( aString[i++] != '\0'); } //reads a chunk(of defined size) from 3ds file void CMeshLoader::ReadChunkArray(long aLength, void (CMeshLoader::*aCallback)(T3dsChunk*) ) { T3dsChunk chunk; long start; long pos = 0; do { // store the position of the this chunk start = ftell(iFile); // read in the sub chunk // //fread(&chunk, sizeof(T3dsChunk), 1, iFile); chunk = ReadChunk(); // Callback with subchunk id // //CMeshLoader meshLoader; //(meshLoader.*aCallback) ( &chunk ); (this->*aCallback) ( &chunk ); // set the position the next sub chunk // fseek(iFile, start + chunk.iLength, SEEK_SET); // account for this chunk in the position // pos += chunk.iLength; } while (pos < aLength); } //reads a chunk(of defined size) from 3ds file void CMeshLoader::ReadChunkArray(long aLength, void (CMeshLoader::*aCallback)(T3dsChunk*, void*), void* aData) { T3dsChunk chunk; long start; long pos = 0; do { // store the position of the this chunk start = ftell(iFile); // read in the sub chunk // //fread(&chunk, sizeof(T3dsChunk), 1, iFile); chunk = ReadChunk(); // Callback with subchunk id // //CMeshLoader meshLoader; //(meshLoader.*aCallback) (&chunk, aData); (this->*aCallback) (&chunk, aData); // set the position the next sub chunk // fseek(iFile, start + chunk.iLength, SEEK_SET); // account for this chunk in the position // pos += chunk.iLength; } while (pos < aLength); } //evaluate the data that was read void CMeshLoader::InspectChunkArray(long aLength, void (CMeshLoader::*aCallback)(T3dsChunk*) ) { T3dsChunk chunk; long start; long chunkStart; long pos = 0; // record the position of the chunk // chunkStart = ftell(iFile); do { // store the position of the this sub chunk // start = ftell(iFile); // read in the sub chunk // //fread(&chunk, sizeof(T3dsChunk), 1, iFile); chunk = ReadChunk(); // Callback with subchunk id // //CMeshLoader meshLoader; //(meshLoader.*aCallback) (&chunk); (this->*aCallback) (&chunk); // set the position the next sub chunk // fseek(iFile, start + chunk.iLength, SEEK_SET); // account for this chunk in the position // pos += chunk.iLength; } while (pos < aLength); // set the position to the start of this chunk // fseek(iFile, chunkStart, SEEK_SET); } //evaluate the data that was read void CMeshLoader::InspectChunkArray(long aLength, void (CMeshLoader::*aCallback)(T3dsChunk*, void*), void* aData) { T3dsChunk chunk; long start; long chunkStart; long pos = 0; // record the position of the chunk // chunkStart = ftell(iFile); do { // store the position of the this sub chunk // start = ftell(iFile); // read in the sub chunk // //fread(&chunk, sizeof(T3dsChunk), 1, iFile); chunk = ReadChunk(); // Callback with subchunk id // //CMeshLoader meshLoader; //(meshLoader.*aCallback) (&chunk, aData); (this->*aCallback) (&chunk, aData); // set the position the next sub chunk // fseek(iFile, start + chunk.iLength, SEEK_SET); // account for this chunk in the position // pos += chunk.iLength; } while (pos < aLength); // set the position to the start of this chunk // fseek(iFile, chunkStart, SEEK_SET); } //SPECIFIC CHUNK READERS AND INSPECTORS void CMeshLoader::ReadMain3ds(T3dsChunk* aChunk) { int i, j, k; // printf(" ReadMain3ds: 0x%x\n", aChunk->iId); switch (aChunk->iId) { case 0x3d3d: // Edit3ds InspectChunkArray(aChunk->iLength - 6, &CMeshLoader::InspectEdit3ds ); if (iDataInfo->iMeshCount) { iDataInfo->iMeshes = (T3dsMesh*)malloc(sizeof(T3dsMesh) * iDataInfo->iMeshCount); memset(iDataInfo->iMeshes, 0, sizeof(T3dsMesh) * iDataInfo->iMeshCount); } if (iDataInfo->iMaterialCount) { iDataInfo->iMaterials = (T3dsMaterial*)malloc(sizeof(T3dsMaterial) * iDataInfo->iMaterialCount); memset(iDataInfo->iMaterials, 0, sizeof(T3dsMaterial) * iDataInfo->iMaterialCount); } iDataInfo->iMeshCount = 0; iDataInfo->iMaterialCount = 0; ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadEdit3ds); for (i = 0; i < iDataInfo->iMeshCount; i++) { for (j = 0; j < iDataInfo->iMeshes[i].iGroupCount; j++) { for (k = 0; k < iDataInfo->iMaterialCount; k++) { if (!strcmp(iDataInfo->iMeshes[i].iGroups[j].iName, iDataInfo->iMaterials[k].iName)) { iDataInfo->iMeshes[i].iGroups[j].iMat = k; break; } } } } break; default: break; } } //EDIT_3DS void CMeshLoader::ReadEdit3ds(T3dsChunk* aChunk) { // printf(" ReadEdit3ds: 0x%x\n", aChunk->iId); switch (aChunk->iId) { case 0x4000: // EDIT_OBJECT // printf(" edit obj\n"); ReadString(iFileStringData); ReadChunkArray(aChunk->iLength - 6 + strlen(iFileStringData), &CMeshLoader::ReadEditObject); break; case 0xAFFF: // EDIT_MATERIAL // printf(" material\n"); ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadMaterial, static_cast<void*>(&iDataInfo->iMaterials[iDataInfo->iMaterialCount++]) ); break; default: break; }; } void CMeshLoader::InspectEdit3ds(T3dsChunk* aChunk) { // printf(" InspectEdit3ds: 0x%x\n", aChunk->iId); switch (aChunk->iId) { case 0xAFFF: // EDIT_MATERIAL // printf(" material++\n"); iDataInfo->iMaterialCount++; break; case 0x4000: // EDIT_OBJECT // printf(" edit obj\n"); ReadString(iFileStringData); InspectChunkArray(aChunk->iLength - 6 + strlen(iFileStringData), &CMeshLoader::InspectEditObject); break; }; } //EDIT_OBJECT void CMeshLoader::ReadEditObject(T3dsChunk* aChunk) { // printf(" ReadEditObject: 0x%x\n", aChunk->iId); switch (aChunk->iId) { case 0x4100: // TRIANGLE_OBJECT // printf(" triangle obj\n"); strcpy(iDataInfo->iMeshes[iDataInfo->iMeshCount].iName, iFileStringData); // printf("Reading Mesh: %s\n", iFileStringData ); ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadTriangleObject, &iDataInfo->iMeshes[iDataInfo->iMeshCount++]); break; }; } void CMeshLoader::InspectEditObject(T3dsChunk* aChunk) { // printf(" InspectEditObject: 0x%x\n", aChunk->iId); switch (aChunk->iId) { case 0x4100: // EDIT_OBJECT // printf(" edit obj++\n"); iDataInfo->iMeshCount++; break; }; } //MESH ITEMS void CMeshLoader::ReadTriangleObject(T3dsChunk* aChunk, void* aOutput) { T3dsMesh* output = static_cast<T3dsMesh*>( aOutput ); switch (aChunk->iId) { case 0x4110: // VERTEX_LIST // printf(" vert list\n"); ReadVertexList(output); break; case 0x4120: // FACE_LIST // printf(" face list\n"); ReadFaceList(output, aChunk->iLength - 6); break; case 0x4140: // MAPPING_COORDS // printf(" tx coords\n"); ReadTextureCoordinates(output); break; case 0x4160: // LOCAL_AXIS // printf(" local axis\n"); ReadLocalAxis(output); break; case 0x4170: // TEXTURE_INFO // printf(" tx info\n"); //ReadTextureInfo((char*)(pData + lPos + 6)); break; default: break; }; } void CMeshLoader::ReadVertexList(T3dsMesh* output) { unsigned short shNumCoords; fread(&shNumCoords, sizeof(unsigned short), 1, iFile); // printf("---------------\nVertList: %d (float size: %d)\n", shNumCoords, sizeof(float)); output->iVertCount = shNumCoords; output->iVertices = (float(*)[3])malloc(sizeof(float) * 3 * output->iVertCount); float x,y,z; for(int i=0; i<output->iVertCount;i++) { fread( &x, sizeof(float), 1, iFile); fread( &y, sizeof(float), 1, iFile); fread( &z, sizeof(float), 1, iFile); //printf("- %f %f %f\n",x ,y ,z ); (*output->iVertices+(i*3))[0] = x*iScale; (*output->iVertices+(i*3))[1] = y*iScale; (*output->iVertices+(i*3))[2] = z*iScale; } // printf("---------------\n"); } void CMeshLoader::ReadFaceList(T3dsMesh* output, long aLength) { long pos = 6; int i; unsigned short shNumFaces; fread(&shNumFaces, sizeof(unsigned short), 1, iFile); pos += sizeof(unsigned short); output->iTriCount = shNumFaces; output->iTriangles = (long(*)[3])malloc(sizeof(long) * 3 * output->iTriCount); unsigned short verts[4]; for (i = 0; i < shNumFaces; i++) { fread(verts, sizeof(short), 4, iFile); for (int j = 0; j < 3; j++) { output->iTriangles[i][j] = (long)verts[j]; } } pos += sizeof(unsigned short) * 4 * shNumFaces; if (pos < aLength) { InspectChunkArray(pos - 6, &CMeshLoader::InspectFaceSubs, output ); if (output->iGroupCount) { output->iGroups = (T3dsGroup*)malloc(sizeof(T3dsGroup) * output->iGroupCount); memset(output->iGroups, 0, sizeof(T3dsGroup) * output->iGroupCount); if (output->iGroups) { output->iGroupCount = 0; ReadChunkArray(pos - 6, &CMeshLoader::ReadFaceSubs, output); } } } } //FACE_SUBS void CMeshLoader::ReadFaceSubs(T3dsChunk* aChunk, void* aOutput) { T3dsMesh* output = static_cast<T3dsMesh*>( aOutput ); switch (aChunk->iId) { case 0x4130: // MATERIAL_GROUP ReadMaterialGroup(&output->iGroups[output->iGroupCount++]); break; case 0x4150: // SMOOTH_GROUP output->iSmooth = (long*)malloc(sizeof(long) * output->iTriCount); if (output->iSmooth) { fread(output->iSmooth, sizeof(long), output->iTriCount, iFile); } break; }; } void CMeshLoader::InspectFaceSubs(T3dsChunk* aChunk, void* aOutput) { T3dsMesh* output = static_cast<T3dsMesh*>( aOutput ); switch (aChunk->iId) { case 0x4130: // MATERIAL_GROUP output->iGroupCount++; break; }; } void CMeshLoader::ReadLocalAxis(T3dsMesh* output) { fread(output->iAxis, sizeof(float), 9, iFile); fread(output->iPosition, sizeof(float), 3, iFile); } //TEXTURE & MATERIALS void CMeshLoader::ReadTextureCoordinates(T3dsMesh* output) { unsigned short shNumCoords; fread(&shNumCoords, sizeof(unsigned short), 1, iFile); output->iTexCoordCount = shNumCoords; output->iTexCoords = (float(*)[2])malloc(sizeof(float) * 2 * output->iTexCoordCount); fread(output->iTexCoords, sizeof(float), 2 * output->iTexCoordCount, iFile); } void CMeshLoader::ReadTexture(T3dsChunk* aChunk, void* aMaterial) { T3dsMaterial* material = static_cast<T3dsMaterial*>( aMaterial ); switch (aChunk->iId) { case 0xa300: // MAT_MAP_NAME ReadString(material->iTexture); break; case 0xa351: // MAT_MAP_TILING break; case 0xa354: // MAT_MAP_U_SCALE break; case 0xa356: // MAT_MAP_V_SCALE break; case 0xa358: // MAT_MAP_U_OFFSET break; case 0xa35a: // MAT_MAP_V_OFFSET break; case 0xa35c: // MAT_MAP_V_ANG break; }; } void CMeshLoader::ReadColorChunk(T3dsChunk* aChunk, void* aColor) { float* color = static_cast<float*>( aColor ); unsigned char chRGB[3]; switch (aChunk->iId) { case 0x0010: // COLOR_F fread(color, sizeof(float), 3, iFile); break; case 0x0011: // COLOR_24 fread(chRGB, sizeof(char), 3, iFile); color[0] = float(chRGB[0]) / 256.0f; color[1] = float(chRGB[1]) / 256.0f; color[2] = float(chRGB[2]) / 256.0f; break; }; } void CMeshLoader::ReadMaterialGroup(T3dsGroup* aGroup) { unsigned short numFaces; unsigned short face; ReadString(aGroup->iName); // printf("Reading Material Group: %s\n", aGroup->iName ); fread(&numFaces, sizeof(unsigned short), 1, iFile); aGroup->iTris = (long*)malloc(numFaces * sizeof(long)); if (aGroup->iTris) { memset(aGroup->iTris, 0, numFaces * sizeof(long)); aGroup->iSize = numFaces; aGroup->iMat = 0; for (int i = 0; i < numFaces; i++) { fread(&face, sizeof(unsigned short), 1, iFile); aGroup->iTris[i] = face; } } } void CMeshLoader::ReadMaterial(T3dsChunk* aChunk, void* aMaterial) { T3dsMaterial* material = static_cast<T3dsMaterial*>( aMaterial ); switch (aChunk->iId) { case 0xa000: // MAT_NAME ReadString(material->iName); // printf("Reading Material: %s\n", material->iName ); break; case 0xa010: // MAT_AMBIENT ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadColorChunk, material->iAmbient); material->iAmbient[3] = 1.0f; break; case 0xa020: // MAT_DIFFUSE ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadColorChunk, material->iDiffuse); material->iDiffuse[3] = 1.0f; break; case 0xa030: // MAT_SPECULAR ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadColorChunk, material->iSpecular); material->iSpecular[3] = 1.0f; break; case 0xa040: // MAT_SHININESS ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadPercentageChunk, &material->iShininess); material->iShininess *= 140.0f; break; case 0xa041: // MAT_SHIN2PCT break; case 0xa042: // MAT_SHIN3PCT break; case 0xa050: // MAT_TRANSPANENCY break; case 0xa080: // MAT_EMISSION ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadColorChunk, material->iEmission); material->iEmission[3] = 1.0f; break; case 0xa200: // MAT_TEXMAP ReadChunkArray(aChunk->iLength - 6, &CMeshLoader::ReadTexture, aMaterial); break; default: break; }; } void CMeshLoader::ReadPercentageChunk(T3dsChunk* aChunk, void* aValue) { float* value = static_cast<float*>( aValue ); short shPercent; switch (aChunk->iId) { case 0x0030: // INT_PERCENTAGE (short) fread(&shPercent, sizeof(short), 1, iFile); *value = (float)shPercent; break; case 0x0031: // FLOAT_PERCENTAGE fread(value, sizeof(float), 1, iFile); break; default: break; }; *value /= 100.0f; } // sorts triangles by group and then by smoothing group // //======================================================// void CMeshLoader::SortTriangles(T3dsMesh* aData) { // printf(" sort triangles\n"); int result = 0; int next = 0; int nextNext = 0; int i, j; T3dsTriangle* tris; T3dsTriangle* temp; int groupCount; if (aData->iGroupCount == 0) { aData->iGroups = (T3dsGroup*)malloc(sizeof(T3dsGroup)); if (aData->iGroups) { aData->iGroupCount = 1; memset(&aData->iGroups[0], 0, sizeof(T3dsGroup)); aData->iGroups[0].iMat = -1; aData->iGroups[0].iStart = 0; aData->iGroups[0].iSize = aData->iTriCount; aData->iGroups[0].iTris = (long*)malloc(sizeof(long) * aData->iTriCount); for (i = 0; i < aData->iGroups[0].iSize; i++) { aData->iGroups[0].iTris[i] = i; } } if (aData->iSmooth == NULL) { return; } } tris = (T3dsTriangle*)malloc(aData->iTriCount * sizeof(T3dsTriangle)); temp = (T3dsTriangle*)malloc(aData->iTriCount * sizeof(T3dsTriangle)); for (i = 0; i < aData->iTriCount; i++) { memcpy(tris[i].iVerts, aData->iTriangles[i], sizeof(long) * 3); tris[i].iMat = -1; tris[i].iIndex = i; if (aData->iSmooth) { tris[i].iSmooth = aData->iSmooth[i]; } else { tris[i].iSmooth = 0; } } for (i = 0; i < aData->iGroupCount; i++) { for (j = 0; j < aData->iGroups[i].iSize; j++) { tris[aData->iGroups[i].iTris[j]].iMat = aData->iGroups[i].iMat; } } //====================================// // now sort the triangles by material // //====================================// //qsort(tris, aData->iTriCount, sizeof(T3dsTriangle), (int (__cdecl *)(const void *,const void *))SortByMaterial); i = 0; while (i < aData->iTriCount) { result = 0; next = i + 1; while ((next < aData->iTriCount) && (result == 0)) { result = SortByMaterial(&tris[i], &tris[next]); next++; } if (next == aData->iTriCount) { break; } next--; if (result > 0) { result = 0; nextNext = next + 1; while ((nextNext < aData->iTriCount) && (result == 0)) { result = SortByMaterial(&tris[next], &tris[nextNext]); nextNext++; } if (result != 0) { nextNext--; } //==========================================// // copy the less than portion into a buffer // //==========================================// memcpy(temp, &tris[next], (nextNext - next) * sizeof(T3dsTriangle)); //=====================================// // move the greater than portion ahead // //=====================================// memmove(&tris[(nextNext - next) + i], &tris[i], (next - i) * sizeof(T3dsTriangle)); //====================================================// // copy the less than portion back in from the buffer // //====================================================// memcpy(&tris[i], temp, (nextNext - next) * sizeof(T3dsTriangle)); //===================================// // start at the begining of the list // //===================================// i = 0; } else if (result < 0) { i = next; } else { break; } } groupCount = 1; aData->iGroups[0].iMat = tris[0].iMat; aData->iGroups[0].iStart = 0; aData->iGroups[0].iSize = 0; for (i = 0; i < aData->iTriCount; i++) { memcpy(aData->iTriangles[i], tris[i].iVerts, sizeof(long) * 3); if (aData->iSmooth) { aData->iSmooth[i] = tris[i].iSmooth; } if (aData->iGroups[groupCount - 1].iMat != tris[i].iMat) { aData->iGroups[groupCount].iMat = tris[i].iMat; aData->iGroups[groupCount].iStart = i; aData->iGroups[groupCount].iSize = 0; groupCount++; } aData->iGroups[groupCount-1].iSize++; } if (tris) { free(tris); } if (temp) { free(temp); } } int CMeshLoader::SortByMaterial(T3dsTriangle* a, T3dsTriangle* b) { if (a->iMat > b->iMat) { return 1; } if (a->iMat < b->iMat) { return -1; } if (a->iSmooth > b->iSmooth) { return 1; } if (a->iSmooth < b->iSmooth) { return -1; } return 0; } T3dsChunk CMeshLoader::ReadChunk() { T3dsChunk chunk; unsigned char byte[4]; fread( &chunk, sizeof( unsigned char ), 2, iFile ); fread( &byte, sizeof( unsigned char ), 4, iFile ); chunk.iLength = *(reinterpret_cast<unsigned long*>(&byte) ); return chunk; }
[ "onnepoika@5699bb8f-202d-0410-a568-af645a74364e" ]
[ [ [ 1, 1317 ] ] ]
044292f699aa8e853d7bb24e1962b24e543add6e
b67f9fa50b816d0c8a0d6328cafe711c8c21f75e
/trunk/moc/moc_mapadapter.cpp
724bb72d379cf88848ea3380587ae7f8070fd23e
[]
no_license
BackupTheBerlios/osibs-svn
d46db4e3f78fe872f3dad81d2767d8d8e530e831
151911e8fb044c183fca251d226a21cfbf4c6c8f
refs/heads/master
2021-01-20T12:42:52.308488
2011-08-17T19:51:02
2011-08-17T19:51:02
40,800,844
0
0
null
null
null
null
UTF-8
C++
false
false
2,285
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mapadapter.h' ** ** Created: Mon 25. Apr 18:57:06 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../QMapControl/src/mapadapter.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mapadapter.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_qmapcontrol__MapAdapter[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_qmapcontrol__MapAdapter[] = { "qmapcontrol::MapAdapter\0" }; const QMetaObject qmapcontrol::MapAdapter::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_qmapcontrol__MapAdapter, qt_meta_data_qmapcontrol__MapAdapter, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &qmapcontrol::MapAdapter::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *qmapcontrol::MapAdapter::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *qmapcontrol::MapAdapter::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_qmapcontrol__MapAdapter)) return static_cast<void*>(const_cast< MapAdapter*>(this)); return QObject::qt_metacast(_clname); } int qmapcontrol::MapAdapter::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "osiair@cc7348f7-d3be-4701-adbb-128cb98a0978" ]
[ [ [ 1, 69 ] ] ]
b4b85d1d867e5bd178e7b5ed643081a896a94117
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/sense/i_device_driver.h
c8570b21dda443b9f281a252495fd458ae933dd4
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
634
h
#ifndef i_device_driver_H_INCLUDED #define i_device_driver_H_INCLUDED //--------------------------------------------------------------------------- namespace all{ namespace sense{ class i_device_driver; } } //--------------------------------------------------------------------------- #include <string> /// class all::sense::i_device_driver { public: virtual ~i_device_driver(){}; public: /// bool open(const std::string &) {return true;}; /// bool close() {return true;}; }; //--------------------------------------------------------------------------- #endif //i_device_driver_H_INCLUDED
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 24 ] ] ]
37e21135b55d88516c5251fea09a667fdbb2c4bb
a79fbaa0083667aa86d044c588874774ece57f28
/api_arv/examples/mesh_viewer/sources/.svn/text-base/main.cpp.svn-base
43f15fcdc881a4b666f01f359ddfa02d8afba3c7
[]
no_license
VB6Hobbyst7/RVProject
c04b88f27ac8a84f912ec86191574d111cd8fc6c
0e2461da5ae347fb5707d7e8b1ba247a24bd4a9a
refs/heads/master
2021-12-02T07:29:24.001171
2011-01-28T17:04:46
2011-01-28T17:04:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
726
#include "Viewer.h" #include <QApplication> #include <QDesktopWidget> #include <argstream.h> int main(int argc, char** argv) { std::string filename; argstream as(argc, argv); as >> values<std::string>(&filename, "nom du fichier .obj a charger", 1) >> help(); as.defaultErrorHandling(); QApplication application(argc,argv); QString fileName(filename.c_str()); Viewer viewer(fileName); // centrage de la fenetre : QDesktopWidget *desktop = QApplication::desktop(); int ws = desktop->width(), hs = desktop->height(); viewer.move((ws - viewer.width())/2, (hs - viewer.height())/2); viewer.show(); return application.exec(); }
[ "meuh@Rosalie.(none)" ]
[ [ [ 1, 25 ] ] ]
58231ec2f4e5165212a6696ee0bcb85e1a781cd2
8e1e11e08b25e2b76b02769e14fee1a8f299846c
/receive_replies.cpp
b851a1f55ef95d135cc97e81951599e29d4a7ffd
[]
no_license
qiuyan0528/cppbutterfly
e4a609da81dba84024842dca01a1e0a731f89500
4ef85a7644b44805c917e2b3e929c627d5720c9c
refs/heads/master
2016-09-10T00:10:33.100622
2010-03-10T15:21:54
2010-03-10T15:21:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,287
cpp
/* Copyright (c) 2010 Gonzalo Diethelm Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <zmq.hpp> #include <assert.h> #include <stdio.h> int main (int argc, char *argv []) { // Parse command line arguments. if (argc != 4) { printf ("usage: receive_replies <in-interface> " "<sync-interface> <transaction-count>\n"); return 1; } const char *inp_interface = argv [1]; const char *sync_interface = argv [2]; int transaction_count = atoi (argv [3]); assert (transaction_count >= 1); // Create the 0MQ infrastructure. zmq::context_t ctx (1, 1); zmq::socket_t inp_socket (ctx, ZMQ_UPSTREAM); zmq::socket_t out_socket (ctx, ZMQ_DOWNSTREAM); inp_socket.bind (inp_interface); out_socket.connect (sync_interface); while (true) { // Wait for all the replies. for (int counter = 0; counter != transaction_count; ++counter) { zmq::message_t msg; inp_socket.recv (&msg); if ((counter % 10) == 0) { fprintf(stderr, "Received %d messages so far\n", counter); } } // Send the synchronisation messages to 'send_requests' application. zmq::message_t sync(1); out_socket.send (sync); } }
[ [ [ 1, 66 ] ] ]
4eb6f4ed424a599574566a67a18f6120db9a1400
98fb339799882c5959f0342ddb6def10bad37bf8
/Workspace/GC/Windows-GCFEM/GC_FaceOrientationMapper/.svn/text-base/AAM_IC.cpp.svn-base
5f77b7f3899c077cfe1f7e27de9d1e0671995e66
[]
no_license
sreedal/GC
58a849794b8deaafb631a5954c897bb551a1e122
7dcd86584296d6beb9cef0b8e8d8760210e7dab1
refs/heads/master
2016-09-05T21:38:54.911411
2009-12-11T08:34:38
2009-12-11T08:34:38
419,540
0
1
null
null
null
null
UTF-8
C++
false
false
17,025
/**************************************************************************** * AAMLibrary * http://code.google.com/p/aam-library * Copyright (c) 2008-2009 by GreatYao, all rights reserved. ****************************************************************************/ #include "stdafx.h" #include <direct.h> #include "AAM_IC.h" //============================================================================ AAM_IC::AAM_IC() { __Points = 0; __Storage = 0; __update_s0 = 0; __warp_t = 0; __error_t = 0; __search_pq = 0; __delta_pq = 0; __current_s = 0; __update_s = 0; } //============================================================================ AAM_IC::~AAM_IC() { cvReleaseMat(&__Points); cvReleaseMemStorage(&__Storage); cvReleaseMat(&__update_s0); cvReleaseMat(&__warp_t); cvReleaseMat(&__error_t); cvReleaseMat(&__search_pq); cvReleaseMat(&__delta_pq); cvReleaseMat(&__current_s); cvReleaseMat(&__update_s); } //============================================================================ CvMat* AAM_IC::CalcGradIdx() { CvMat* pos= cvCreateMat(__paw.nPix(), 4, CV_32SC1); int i = 0; int width = __paw.Width(), height = __paw.Height(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { if(__paw.Rect(y, x) >= 0) { int *ppos = (int*)(pos->data.ptr + pos->step*i); ppos[0] = (x-1<0) ?-1:__paw.Rect(y, x-1); // left ppos[1] = (x+1>=width) ?-1:__paw.Rect(y, x+1); // right ppos[2] = (y-1<0) ?-1:__paw.Rect(y-1, x); // top ppos[3] = (y+1>=height) ?-1:__paw.Rect(y+1, x); // bottom i++; } } } return pos; } //============================================================================ void AAM_IC::CalcTexGrad(const CvMat* texture, CvMat* dTx, CvMat* dTy) { double* _x = dTx->data.db; double* _y = dTy->data.db; double* t = texture->data.db; CvMat *idx = CalcGradIdx(); for(int i = 0; i < __paw.nPix(); i++) { int *fastp = (int*)(idx->data.ptr + idx->step*i); // x direction if(fastp[0] >= 0 && fastp[1] >= 0) { _x[3*i+0] = (t[3*fastp[1]+0] - t[3*fastp[0]+0])/2; _x[3*i+1] = (t[3*fastp[1]+1] - t[3*fastp[0]+1])/2; _x[3*i+2] = (t[3*fastp[1]+2] - t[3*fastp[0]+2])/2; } else if(fastp[0] >= 0 && fastp[1] < 0) { _x[3*i+0] = t[3*i+0] - t[3*fastp[0]+0]; _x[3*i+1] = t[3*i+1] - t[3*fastp[0]+1]; _x[3*i+2] = t[3*i+2] - t[3*fastp[0]+2]; } else if(fastp[0] < 0 && fastp[1] >= 0) { _x[3*i+0] = t[3*fastp[1]+0] - t[3*i+0]; _x[3*i+1] = t[3*fastp[1]+1] - t[3*i+1]; _x[3*i+2] = t[3*fastp[1]+2] - t[3*i+2]; } else { _x[3*i+0] = 0; _x[3*i+1] = 0; _x[3*i+2] = 0; } // y direction if(fastp[2] >= 0 && fastp[3] >= 0) { _y[3*i+0] = (t[3*fastp[3]+0] - t[3*fastp[2]+0])/2; _y[3*i+1] = (t[3*fastp[3]+1] - t[3*fastp[2]+1])/2; _y[3*i+2] = (t[3*fastp[3]+2] - t[3*fastp[2]+2])/2; } else if(fastp[2] >= 0 && fastp[3] < 0) { _y[3*i+0] = t[3*i+0] - t[3*fastp[2]+0]; _y[3*i+1] = t[3*i+1] - t[3*fastp[2]+1]; _y[3*i+2] = t[3*i+2] - t[3*fastp[2]+2]; } else if(fastp[2] < 0 && fastp[3] >= 0) { _y[3*i+0] = t[3*fastp[3]+0] - t[3*i+0]; _y[3*i+1] = t[3*fastp[3]+1] - t[3*i+1]; _y[3*i+2] = t[3*fastp[3]+2] - t[3*i+2]; } else { _y[3*i+0] = 0; _y[3*i+1] = 0; _y[3*i+2] = 0; } } cvReleaseMat(&idx); } //============================================================================ void AAM_IC::CalcWarpJacobian(CvMat* Jx, CvMat* Jy) { int nPoints = __shape.nPoints(); __sMean.Mat2Point(__shape.GetMean()); __sStar1.resize(nPoints); __sStar2.resize(nPoints); __sStar3.resize(nPoints); __sStar4.resize(nPoints); for(int n = 0; n < nPoints; n++) // Equation (43) { __sStar1[n].x = __sMean[n].x; __sStar1[n].y = __sMean[n].y; __sStar2[n].x = -__sMean[n].y; __sStar2[n].y = __sMean[n].x; __sStar3[n].x = 1; __sStar3[n].y = 0; __sStar4[n].x = 0; __sStar4[n].y = 1; } const CvMat* B = __shape.GetBases(); const CvMat* mean = __shape.GetMean(); cvZero(Jx); cvZero(Jy); for(int i = 0; i < __paw.nPix(); i++) { int tri_idx = __paw.PixTri(i); int v1 = __paw.Tri(tri_idx, 0); int v2 = __paw.Tri(tri_idx, 1); int v3 = __paw.Tri(tri_idx, 2); double *fastJx = (double*)(Jx->data.ptr + Jx->step*i); double *fastJy = (double*)(Jy->data.ptr + Jy->step*i); // Equation (50) dN_dq fastJx[0] = __paw.Alpha(i)*__sStar1[v1].x + __paw.Belta(i)*__sStar1[v2].x + __paw.Gamma(i)*__sStar1[v3].x; fastJy[0] = __paw.Alpha(i)*__sStar1[v1].y + __paw.Belta(i)*__sStar1[v2].y + __paw.Gamma(i)*__sStar1[v3].y; fastJx[1] = __paw.Alpha(i)*__sStar2[v1].x + __paw.Belta(i)*__sStar2[v2].x + __paw.Gamma(i)*__sStar2[v3].x; fastJy[1] = __paw.Alpha(i)*__sStar2[v1].y + __paw.Belta(i)*__sStar2[v2].y + __paw.Gamma(i)*__sStar2[v3].y; fastJx[2] = __paw.Alpha(i)*__sStar3[v1].x + __paw.Belta(i)*__sStar3[v2].x + __paw.Gamma(i)*__sStar3[v3].x; fastJy[2] = __paw.Alpha(i)*__sStar3[v1].y + __paw.Belta(i)*__sStar3[v2].y + __paw.Gamma(i)*__sStar3[v3].y; fastJx[3] = __paw.Alpha(i)*__sStar4[v1].x + __paw.Belta(i)*__sStar4[v2].x + __paw.Gamma(i)*__sStar4[v3].x; fastJy[3] = __paw.Alpha(i)*__sStar4[v1].y + __paw.Belta(i)*__sStar4[v2].y + __paw.Gamma(i)*__sStar4[v3].y; // Equation (51) dW_dp for(int j = 0; j < __shape.nModes(); j++) { fastJx[j+4] = __paw.Alpha(i)*cvmGet(B,j,2*v1) + __paw.Belta(i)*cvmGet(B,j,2*v2) + __paw.Gamma(i)*cvmGet(B,j,2*v3); fastJy[j+4] = __paw.Alpha(i)*cvmGet(B,j,2*v1+1) + __paw.Belta(i)*cvmGet(B,j,2*v2+1) + __paw.Gamma(i)*cvmGet(B,j,2*v3+1); } } } //============================================================================ void AAM_IC::CalcModifiedSD(CvMat* SD, const CvMat* dTx, const CvMat* dTy, const CvMat* Jx, const CvMat* Jy) { int i, j; //create steepest descent images double* _x = dTx->data.db; double* _y = dTy->data.db; double temp; for(i = 0; i < __shape.nModes()+4; i++) { for(j = 0; j < __paw.nPix(); j++) { temp = _x[3*j ]*cvmGet(Jx,j,i) +_y[3*j ]*cvmGet(Jy,j,i); cvmSet(SD,i,3*j,temp); temp = _x[3*j+1]*cvmGet(Jx,j,i) +_y[3*j+1]*cvmGet(Jy,j,i); cvmSet(SD,i,3*j+1,temp); temp = _x[3*j+2]*cvmGet(Jx,j,i) +_y[3*j+2]*cvmGet(Jy,j,i); cvmSet(SD,i,3*j+2,temp); } } //project out appearance variation (and linear lighting parameters) const CvMat* B = __texture.GetBases(); CvMat* V = cvCreateMat(4+__shape.nModes(), __texture.nModes(), CV_64FC1); CvMat SDMat, BMat; cvGEMM(SD, B, 1., NULL, 1., V, CV_GEMM_B_T); // Equation (63),(64) for(i = 0; i < __shape.nModes()+4; i++) { for(j = 0; j < __texture.nModes(); j++) { cvGetRow(SD, &SDMat, i); cvGetRow(B, &BMat, j); cvScaleAdd(&BMat, cvScalar(-cvmGet(V,i,j)), &SDMat, &SDMat); } } cvReleaseMat(&V); } //============================================================================ void AAM_IC::CalcHessian(CvMat* H, const CvMat* SD) { CvMat* HH = cvCreateMat(H->rows, H->cols, CV_64FC1); cvMulTransposed(SD, HH, 0);// Equation (65) cvInvert(HH, H, CV_SVD); cvReleaseMat(&HH); } //============================================================================ void AAM_IC::Train(const file_lists& pts_files, const file_lists& img_files, double scale /* = 1.0 */, double shape_percentage /* = 0.975 */, double texture_percentage /* = 0.975 */) { if(pts_files.size() != img_files.size()) { fprintf(stderr, "ERROE(%s, %d): #Shapes != #Images\n", __FILE__, __LINE__); exit(0); } printf("################################################\n"); printf("Build Inverse Compositional Image Alignmennt Model...\n"); std::vector<AAM_Shape> AllShapes; for(int ii = 0; ii < pts_files.size(); ii++) { AAM_Shape Shape; bool flag = Shape.ReadAnnotations(pts_files[ii]); if(!flag) { IplImage* image = cvLoadImage(img_files[ii].c_str(), -1); Shape.ScaleXY(image->width, image->height); cvReleaseImage(&image); } AllShapes.push_back(Shape); } //building shape and texture distribution model printf("Build point distribution model...\n"); __shape.Train(AllShapes, scale, shape_percentage); printf("Build warp information of mean shape mesh..."); __Points = cvCreateMat (1, __shape.nPoints(), CV_32FC2); __Storage = cvCreateMemStorage(0); __paw.Train(__shape.GetMeanShape(), __Points, __Storage); printf("[%d by %d, triangles #%d, pixels #%d*3]\n", __paw.Width(), __paw.Height(), __paw.nTri(), __paw.nPix()); printf("Build texture distribution model...\n"); __texture.Train(pts_files, img_files, __paw, texture_percentage, true); //calculate gradient of texture printf("Calculating texture gradient...\n"); CvMat* dTx = cvCreateMat(1, __texture.nPixels(), CV_64FC1); CvMat* dTy = cvCreateMat(1, __texture.nPixels(), CV_64FC1); CalcTexGrad(__texture.GetMean(), dTx, dTy); // save gradient image mkdir("Modes"); __paw.SaveWarpTextureToImage("Modes/dTx.jpg", dTx); __paw.SaveWarpTextureToImage("Modes/dTy.jpg", dTy); //calculate warp Jacobian at base shape printf("Calculating warp Jacobian...\n"); CvMat* Jx = cvCreateMat(__paw.nPix(), __shape.nModes()+4, CV_64FC1); CvMat* Jy = cvCreateMat(__paw.nPix(), __shape.nModes()+4, CV_64FC1); CalcWarpJacobian(Jx,Jy); //calculate modified steepest descent image printf("Calculating steepest descent images...\n"); CvMat* SD = cvCreateMat(__shape.nModes()+4, __texture.nPixels(), CV_64FC1); CalcModifiedSD(SD, dTx, dTy, Jx, Jy); //calculate inverse Hessian matrix printf("Calculating Hessian inverse matrix...\n"); CvMat* H = cvCreateMat(__shape.nModes()+4, __shape.nModes()+4, CV_64FC1); CalcHessian(H, SD); //calculate update matrix (multiply inverse Hessian by modified steepest descent image) __G = cvCreateMat(__shape.nModes()+4, __texture.nPixels(), CV_64FC1); cvMatMul(H, SD, __G); //release cvReleaseMat(&Jx); cvReleaseMat(&Jy); cvReleaseMat(&dTx); cvReleaseMat(&dTy); cvReleaseMat(&SD); cvReleaseMat(&H); //alocate memory for on-line fitting stuff __update_s0 = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __inv_pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __warp_t = cvCreateMat(1, __texture.nPixels(), CV_64FC1); __error_t = cvCreateMat(1, __texture.nPixels(), CV_64FC1); __search_pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __delta_pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __current_s = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __update_s = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __lamda = cvCreateMat(1, __texture.nModes(), CV_64FC1); printf("################################################\n\n"); } //============================================================================ void AAM_IC::Fit(const IplImage* image, AAM_Shape& Shape, int max_iter /* = 30 */, bool showprocess /* = false */) { //initialize some stuff double t = gettime; const CvMat* A0 = __texture.GetMean(); CvMat p; cvGetCols(__search_pq, &p, 4, 4+__shape.nModes()); Shape.Point2Mat(__current_s); SetAllParamsZero(); __shape.CalcParams(__current_s, __search_pq); IplImage* Drawimg = 0; for(int iter = 0; iter < max_iter; iter++) { if(showprocess) { if(Drawimg == 0) Drawimg = cvCloneImage(image); else cvCopy(image, Drawimg); Shape.Mat2Point(__current_s); Draw(Drawimg, Shape, 2); mkdir("result"); char filename[100]; sprintf(filename, "result/Iter-%02d.jpg", iter); cvSaveImage(filename, Drawimg); } //check the current shape AAM_Common::CheckShape(__current_s, image->width, image->height); //warp image to mesh shape mesh __paw.CalcWarpTexture(__current_s, image, __warp_t); AAM_TDM::NormalizeTexture(A0, __warp_t); cvSub(__warp_t, A0, __error_t); //calculate updates (and scale to account for linear lighting gain) cvGEMM(__error_t, __G, 1, NULL, 1, __delta_pq, CV_GEMM_B_T); //check for parameter convergence if(cvNorm(__delta_pq) < 1e-6) break; //apply inverse compositional algorithm to update parameters InverseCompose(__delta_pq, __current_s, __update_s); //smooth shape cvAddWeighted(__current_s, 0.9, __update_s, 0.1, 0, __update_s); // 0.4,0.6 //update parameters __shape.CalcParams(__update_s, __search_pq); //calculate constrained new shape __shape.CalcShape(__search_pq, __update_s); //check for shape convergence if(cvNorm(__current_s, __update_s, CV_L2) < 0.001) break; else cvCopy(__update_s, __current_s); } Shape.Mat2Point(__current_s); t = gettime-t; printf("AAM IC Fitting time cost %.3f millisec\n", t); cvReleaseImage(&Drawimg); } //============================================================================ void AAM_IC::SetAllParamsZero() { cvZero(__warp_t); cvZero(__error_t); cvZero(__search_pq); cvZero(__delta_pq); cvZero(__lamda); } //============================================================================ void AAM_IC::InverseCompose(const CvMat* dpq, const CvMat* s, CvMat* NewS) { // Firstly: Estimate the corresponding changes to the base mesh cvConvertScale(dpq, __inv_pq, -1); __shape.CalcShape(__inv_pq, __update_s0); // __update_s0 = N.W(s0, -delta_p, -delta_q) //Secondly: Composing the Incremental Warp with the Current Warp Estimate. double *S0 = __update_s0->data.db; double *S = s->data.db; double *SEst = NewS->data.db; double x, y, xw, yw; int k, tri_idx; int v1, v2, v3; const std::vector<std::vector<int> >& tri = __paw.__tri; const std::vector<std::vector<int> >& vtri = __paw.__vtri; for(int i = 0; i < __shape.nPoints(); i++) { x = 0.0; y = 0.0; k = 0; //The only problem with this approach is which triangle do we use? //In general there will be several triangles that share the i-th vertex. for(k = 0; k < vtri[i].size(); k++)// see Figure (11) { tri_idx = vtri[i][k]; v1 = tri[tri_idx][0]; v2 = tri[tri_idx][1]; v3 = tri[tri_idx][2]; AAM_PAW::Warp(S0[2*i],S0[2*i+1], __sMean[v1].x, __sMean[v1].y,__sMean[v2].x, __sMean[v2].y,__sMean[v3].x, __sMean[v3].y, xw, yw, S[2*v1], S[2*v1+1], S[2*v2], S[2*v2+1], S[2*v3], S[2*v3+1]); x += xw; y += yw; } // average the result so as to smooth the warp at each vertex SEst[2*i] = x/k; SEst[2*i+1] = y/k; } } //============================================================================ void AAM_IC::Draw(IplImage* image, const AAM_Shape& Shape, int type) { if(type == 0) AAM_Common::DrawPoints(image, Shape); else if(type == 1) AAM_Common::DrawTriangles(image, Shape, __paw.__tri); else if(type == 2) { cvGEMM(__error_t, __texture.GetBases(), 1, NULL, 1, __lamda, CV_GEMM_B_T); __texture.CalcTexture(__lamda, __warp_t); AAM_PAW paw; double minV, maxV; cvMinMaxLoc(__warp_t, &minV, &maxV); cvConvertScale(__warp_t, __warp_t, 255/(maxV-minV), -minV*255/(maxV-minV)); paw.Train(Shape, __Points, __Storage, __paw.GetTri(), false); AAM_Common::DrawAppearance(image, Shape, __warp_t, paw, __paw); } else fprintf(stderr, "ERROR(%s, %d): Unsupported drawing type\n", __FILE__, __LINE__); } //============================================================================ void AAM_IC::Write(std::ofstream& os) { __shape.Write(os); __texture.Write(os); __paw.Write(os); __sMean.Write(os); __sStar1.Write(os); __sStar2.Write(os); __sStar3.Write(os); __sStar4.Write(os); os << __G << std::endl; } //============================================================================ void AAM_IC::Read(std::ifstream& is) { __shape.Read(is); __texture.Read(is); __paw.Read(is); int nPoints = __shape.nPoints(); __sMean.resize(nPoints); __sStar1.resize(nPoints); __sStar2.resize(nPoints); __sStar3.resize(nPoints); __sStar4.resize(nPoints); __sMean.Read(is); __sStar1.Read(is); __sStar2.Read(is); __sStar3.Read(is); __sStar4.Read(is); __G = cvCreateMat(__shape.nModes()+4, __texture.nPixels(), CV_64FC1); is >> __G; //alocate memory for on-line fitting stuff __Points = cvCreateMat (1, __shape.nPoints(), CV_32FC2); __Storage = cvCreateMemStorage(0); __update_s0 = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __inv_pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __warp_t = cvCreateMat(1, __texture.nPixels(), CV_64FC1); __error_t = cvCreateMat(1, __texture.nPixels(), CV_64FC1); __search_pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __delta_pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __current_s = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __update_s = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __lamda = cvCreateMat(1, __texture.nModes(), CV_64FC1); }
[ [ [ 1, 533 ] ] ]
27b05e94e1195ddab2b5abbdf4345c7a82446e9c
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Core/Source/ScriptFunctions.h
df217b6562dd5b36441c791737e18117f01b87cb
[]
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
1,663
h
#pragma once namespace Script { //tolua_begin //----------------------------------------------------- extern void lua_break(const char * sDebugInfo); // 设置Entity动画 extern void set_next_anim( unsigned int uEntID, const char* sAnim, float fTimes ); // 加入动画队列(无循环动画) extern void add_anim_queue( unsigned int uEntID, const char* sAnim ); // 对Entity加入特效 extern void add_effect( unsigned int uEntID, unsigned int uEffectID , float fTimes); // 加入全局特效 extern void add_global_effect( unsigned int uEffectID ); // 换装 extern void exchange_avatar( unsigned int uEntID, unsigned int uAvatarID ); // 搜索距离自己最近的敌人 extern void query_near_foeman( unsigned int uEntID, float r ); // 设置spawner参数 extern void set_spawner(unsigned int uEntID, float fInterval, float fDelay, int nMaxCount, unsigned int uSpawnID, bool bFlag); // 设置位置 extern void set_translate(unsigned int uEntID, float x, float z); // 设置计时器 extern void set_timer(unsigned int uEntID, float fTimeStep); // 销毁计时器 extern void kill_timer(unsigned int uEntID); // 杀死entity extern void kill_character(unsigned int uEntID, unsigned int uKiller); // 销毁entity extern void destroy_entity(unsigned int uEntID , float fTimeDelay); // 抛出道具 extern void throw_item(unsigned int uEntID, unsigned int uItem, float fTimeDelay); // 从运动到静止 extern void to_stop(unsigned int uEntID); // 切换背景音乐 extern void change_background_sound(unsigned int uSoundID); //tolua_end };
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 12 ], [ 18, 18 ], [ 22, 23 ], [ 27, 27 ], [ 39, 40 ], [ 42, 57 ] ], [ [ 13, 17 ], [ 19, 21 ], [ 24, 26 ], [ 28, 38 ], [ 41, 41 ] ] ]
635ebf1bed875c6f6713a2a77485a67e682e4200
00b979f12f13ace4e98e75a9528033636dab021d
/zfs/zfs/src/core/http.cc
da2371976c9089f24bfcfe65c1820d103b55935a
[]
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
6,103
cc
#include <core/ziafs_net.hh> #include <core/zia_stringmanager.hh> #include <core/ziafs_debug.hh> #include <core/ziafs_io.hh> #include <vector> #include <sstream> net::http::http() { process_stage_fn = http::first_stage; m_state = STUSLINES; m_data_enco = NULL; } std::string& net::http::operator[](const std::string& key) { std::string str(key); stringmanager::normalize(str); return (m_hdrlines[str]); } std::string& net::http::operator=(const std::string& val) { std::string t = val; return ((std::string&)val); } status::error net::http::first_stage(session* s) { buffer* buf; if (s->m_server->res_manager()->fetch(s->m_client, (void*&)buf) == status::SUCCESS) { if (buf) { s->m_proto->consume(s, *buf); // proto->consum(session, buffer); // session->target = new io::res... // cout << buf->tostring() << endl; delete buf; } } ziafs_return_status(status::SUCCESS); } status::error net::http::second_stage(session* s) { buffer* buf; ziafs_debug_msg("entering in stage 2%s\n", ""); if (((net::http*)s->m_proto)->method() == "GET") { ziafs_debug_msg("No need for this method :%s, walk to the third stage\n",((net::http*)s->m_proto)->method().c_str()); s->m_proto->process_stage_fn = http::third_stage; ziafs_return_status(status::NOTIMPL); } if (s->m_server->res_manager()->fetch(s->m_client, (void*&)buf) == status::SUCCESS) { if (buf) { s->m_proto->consume(s, *buf); delete buf; } } ziafs_return_status(status::NOTIMPL); } status::error net::http::third_stage(session* s) { ziafs_debug_msg("entering in stage 3 wow%s\n", ""); ziafs_return_status(status::NOTIMPL); } status::error net::http::consume(net::session *s, buffer &buf) { std::string ln; if (m_state == BODYDATA) { if (m_data_enco->decode(s, m_line, buf) == status::ENDOFREQUEST) { s->m_proto->process_stage_fn = http::third_stage; ziafs_return_status(status::ENDOFREQUEST); } if (m_data_enco->done() == true) { delete m_data_enco; m_data_enco = NULL; handle_metadata(); } ziafs_return_status(status::SUCCESS); } while (m_line.from_buffer(ln, buf) == true) { ziafs_debug_msg("line : %s\n", ln.c_str()); if (ln.empty()) { process_stage_fn = http::second_stage; ziafs_debug_msg("end of header, go to second stage ;)%s\n", ""); handle_metadata(); m_state = BODYDATA; ziafs_return_status(status::SUCCESS); } if (m_state == HDRLINES) { if (parse_header_line(ln) == status::HEADERLINE_FAILED) { ziafs_debug_msg("HEADER LINE INCORRECT%s\n", ""); } //ziafs_return_status(status::SUCCESS); } if (m_state == STUSLINES) { if (parse_status_line(ln) == status::STATUSLINE_FAILED) { ziafs_debug_msg("STATUS LINE INCORRECT%s\n", ""); } m_state = HDRLINES; //ziafs_return_status(status::SUCCESS); } buf.reset(); //ln.clear(); } ziafs_return_status(status::SUCCESS); } status::error net::http::parse_status_line(std::string& ln) { std::vector<std::string> vec; stringmanager::split(ln, " ", vec); if (vec.size() != 3) { m_uri.status_code() = 400; ziafs_return_status(status::STATUSLINE_FAILED); } m_method = vec[0]; size_t i = vec[1].find("?", 0); if (i != std::string::npos) { m_uri.wwwname() = vec[1].substr(0, i); m_query = vec[1].substr(i + 1, vec[1].length() - i - 1); } stringmanager::unconvert_hexa(m_uri.wwwname()); stringmanager::unconvert_hexa(m_query); m_version = vec[2]; m_uri.status_code() = 200; ziafs_return_status(status::STATUSLINE_SUCCESS); } status::error net::http::parse_header_line(std::string& ln) { std::string key; std::string val; size_t i = ln.find(":", 0); if (i != std::string::npos) { key = ln.substr(0, i); val = ln.substr(i + 1, ln.length() - i - 1); stringmanager::remove_space(val); stringmanager::normalize(key); m_hdrlines[key] = val; } else ziafs_return_status(status::HEADERLINE_FAILED); ziafs_return_status(status::HEADERLINE_SUCCESS); } status::error net::http::produce(buffer &buf) { ziafs_return_status(status::NOTIMPL); } status::error net::http::dump(buffer& buf) { std::ostringstream stream; stream << "STATUS CODE :" << m_uri.status_code() << " WWWNAME :" << m_uri.wwwname() << " QUERY :" << m_query; buf = stream.str(); ziafs_return_status(status::SUCCESS); } status::error net::http::handle_metadata() { if (m_hdrlines["transfer-encoding"] == "chunked") { m_data_enco = new chunked; ziafs_return_status(status::SUCCESS); } if (atoi(m_hdrlines["content-length"].c_str()) > 0) { m_data_enco = new unchunked; ziafs_return_status(status::SUCCESS); } m_uri.status_code() = 411; ziafs_return_status(status::FAILED); } status::error net::http::chunked::decode(net::session*, utils::line& m_line, buffer& buf) { if (m_state == HDRLINE) { std::string ln; if (m_line.from_buffer(ln, buf) == true) { stringmanager::hex_to_int((const std::string&)ln, m_chunk_size); if (!m_chunk_size) { ziafs_return_status(status::ENDOFREQUEST); } m_chunk_size += 2; // \r\n ziafs_debug_msg("chunk size-> %i\n", m_chunk_size); m_line.get_bytes(m_buf); m_state = BODYDATA; } } if (m_state == BODYDATA) { m_buf += buf; if (m_chunk_size == (int)m_buf.size()) { m_done = true; ziafs_debug_msg("FINI CHUNK %s", ""); // std::cout << "SIZE :" << m_buf.size() << "\n" <<m_buf.tostring(); // le buffer a 2 caractere en trop } } ziafs_return_status(status::SUCCESS); } status::error net::http::unchunked::decode(net::session* s,utils::line& m_line, buffer& buf) { if (m_state == FIRSTTIME) { m_line.get_bytes(m_buf); //const std::string t("lala"); m_size = atoi((*(net::http*)s->m_proto)["content-length"].c_str()) + 2; m_state = OTHERTIME; } m_buf += buf; if (m_size == (int)m_buf.size()) { m_done = true; // std::cout << "SIZE :" << m_buf.size() << "\n" << m_buf.tostring(); ziafs_return_status(status::ENDOFREQUEST); } ziafs_return_status(status::SUCCESS); } bool net::http::data_enco::done() { if (m_done) { return true; } else { return false; } }
[ "zapoutix@754ce95b-6e01-0410-81d0-8774ba66fe44", "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 34 ], [ 36, 59 ], [ 61, 226 ], [ 228, 247 ], [ 249, 266 ] ], [ [ 35, 35 ], [ 60, 60 ], [ 227, 227 ], [ 248, 248 ], [ 267, 267 ] ] ]
7e6ec838cbe12f8ec010c4373bb2b87fd0d0277e
18da4b0f8a1f09ff176e77f2c3bc073beffd0525
/YYSocketProxy/ProxyCore.h
65d12480c031f68e75412a7fc4f0b772f8f5b3ee
[]
no_license
myjeffxie/yynetsdk
7ef95384570df959bf56453b34acfdb45fbf9db7
9d6edc080c601ff9caab8edda922bbc604f36654
refs/heads/master
2021-12-09T02:40:16.491623
2011-06-27T06:56:51
2011-06-27T06:56:51
null
0
0
null
null
null
null
GB18030
C++
false
false
1,955
h
/* YYNetSDK 由MicroPop开发 遵循code.google开源协议,可以任意转播和使用 https://yynetsdk.googlecode.com/svn/trunk TCP代理服务器 1.client->N*server,即one client 可以保持和N个server的连接 2.消息中转 3.消息过滤 v1.0.0.1 2011-06-14 [email protected] */ #pragma once #include "export.h" #include "CClientContext.h" #include "CIOBuffer.h" #include "lock.h" #include <list> #include <map> using namespace std; #include "msg.h" #include "myMsg.h" #include <algorithm> typedef list<CClientContext*> ClientContextList; typedef ClientContextList::iterator ClientContextListIt; typedef list<CIOBuffer*> IOBufferList; typedef IOBufferList::iterator IOBufferListIt; class _DLL CProxyCore { public: CProxyCore(void); ~CProxyCore(void); public: bool Start(UINT port,UINT maxOL); bool Stop(); static DWORD WINAPI Listen(LPVOID param); static DWORD WINAPI Worker(LPVOID param); CClientContext * AllocateClient(SOCKET sock); CIOBuffer * AllocateBuffer(IOType type); void ReleaseClient(CClientContext*pClient); void ReleaseBuffer(CIOBuffer*pBuffer); void ProcessIO(CClientContext*pClient,CIOBuffer*pBuffer,DWORD dwSize); void OnHandleMsg(CClientContext* pClient,BYTE *data,int dataLen); bool CreateSocket(CClientContext*pClient,char*ip,char*port); void SendMsg(CClientContext*pClient,BYTE *data,int dataLen); void SendMsg(CClientContext*pClient,CMsg*msg); public: virtual void OnProxyMsg(LPVOID client,CMsg *msg) { printf("recv msg len=%d\n",msg->GetMsgHead().len); } public: //lock CLock m_clientLock; ClientContextList m_clientListFree; ClientContextList m_clientListBusy; //lock CLock m_bufferLock; IOBufferList m_bufferListFree; IOBufferList m_bufferListBusy; UINT m_maxOnlineUser; UINT m_port; HANDLE m_hIOCP; SOCKET m_listenSock; HANDLE m_svrStopEvent; };
[ [ [ 1, 85 ] ] ]
6a3d1174d9a1190fd54b089ef68c6cebd5b1dad6
8a8873b129313b24341e8fa88a49052e09c3fa51
/inc/CacheDatabase.h
14913c3e1c00677302e0bda5eee89ee9ef9b19fd
[]
no_license
flaithbheartaigh/wapbrowser
ba09f7aa981d65df810dba2156a3f153df071dcf
b0d93ce8517916d23104be608548e93740bace4e
refs/heads/master
2021-01-10T11:29:49.555342
2010-03-08T09:36:03
2010-03-08T09:36:03
50,261,329
1
0
null
null
null
null
UTF-8
C++
false
false
3,691
h
/* ============================================================================ Name : CacheDatabase.h Author : 浮生若茶 Version : Copyright : Your copyright notice Description : CCacheDatabase declaration ============================================================================ */ #ifndef CACHEDATABASE_H #define CACHEDATABASE_H #include <e32std.h> #include <e32base.h> #include <d32dbms.h> // RDbStoreDatabase #include <f32file.h> // RFs _LIT(KSelect, "SELECT "); _LIT(KFrom, " FROM "); _LIT(KWhere, " WHERE "); _LIT(KEqual, " = '"); _LIT(KOrderBy, "' ORDER BY "); _LIT(KDot, ", "); //页面缓冲记录 _LIT(KPageCacheTable, "PageCache"); _LIT(KFirstPageCacheTable, "FirstPageCache"); _LIT(KPageCacheFileName, "FileName"); _LIT(KPageCacheFirstType, "FirstTypeId"); _LIT(KPageCacheSecondType, "SecondTypeId"); _LIT(KPageCacheThirdType, "ThirdTypeId"); _LIT(KPageCachePageIndex, "PageIndex"); _LIT(KPageCacheTimeStamp, "TimeStamp"); const int KTitleMaxLength = 60; const int KDescriptionMaxLength = 128; const int KBookItemMaxLength = 256; _LIT(KSeparator,"|"); class CFileStore; class TPageRecord; class CCacheDatabase : public CBase { public: // Constructors and destructor ~CCacheDatabase(); static CCacheDatabase* NewL(CMainEngine& aMainEngine); static CCacheDatabase* NewLC(CMainEngine& aMainEngine); private: CCacheDatabase(CMainEngine& aMainEngine); void ConstructL(); public: TInt OpenDb(const TFileName& aExistingBookFile); TInt CreateDb(const TFileName& aNewBookFile); TInt RemoveDb(const TFileName& aExistingBookFile); TInt Close(); TBool IsOpen() const; ////////////////////////////////////////////////////////////////////////// //记录页缓冲文件 ////////////////////////////////////////////////////////////////////////// //没有记录则添加记录,有记录则更新 TBool AddPageCacheRecord(const TPageRecord& aRecord); //RemovePageCacheRecord //删除与TPageRecord中的索引匹配的记录 TBool RemovePageCacheRecord(const TPageRecord& aRecord); //删除最旧的一条记录,同时返回记录 TBool RemoveOldestPageCacheRecord(TPageRecord& aRecord); //删除所有记录 TBool RemoveAllPageCacheRecord(); //GetPageCacheRecord //aCondition:存放获取记录的条件 //aResult:获取到的记录 TBool GetPageCacheRecord(const TPageRecord& aCondition,TPageRecord& aResult); //返回记录总数 TInt PageCacheRecordCount() const; // TPageRecord GetOldestPageCacheRecord() const; ////////////////////////////////////////////////////////////////////////// //用于页缓冲,缓冲所有栏目的第一页 ////////////////////////////////////////////////////////////////////////// //AddFirstPageCacheRecord //没有记录则添加记录,有记录则更新 TBool AddFirstPageCacheRecord(const TPageRecord& aCondition); TBool RemoveFirstPageCacheRecord(const TPageRecord& aCondition); TBool GetFirstPageCacheRecord(const TPageRecord& aCondition,TPageRecord& aResult); private: //用于页缓冲 void CreatePageCacheTableL(); //void DropPageCacheTable(); //用于页缓冲,缓冲所有栏目的第一页 void CreateFirstPageCacheTableL(); private: // Member data CMainEngine& iMainEngine; RFs iFsSession; /* For use of iFileStore */ RDbStoreDatabase iDb;/* For database operations */ CFileStore* iFileStore; /* For creating and opening database files */ TBool iOpen; /* Flag indicating iBookDb open status*/ }; #endif // CACHEDATABASE_H
[ "sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f" ]
[ [ [ 1, 119 ] ] ]
73cb1e8f93e49cd12007f7de00b2c9156ec1e8ef
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/libproject/Apputility/ApputilityDLL.cpp
42bf642188c782aefacc6dd3852de7a077652aa0
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
442
cpp
// ApputilityDLL.cpp : 定义 DLL 应用程序的入口点。 // #include "stdafx.h" #include "ApputilityDLL.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
[ [ [ 1, 21 ] ] ]
ee9e9fab561f40644b94eb10d512a90819b8830e
b0252ba622183d115d160eb28953189930ebf9c0
/Source/CEvent.h
b39aba8f8311907e1df5c746e797924d95f4224a
[]
no_license
slewicki/khanquest
6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc
f2d68072a1d207f683c099372454add951da903a
refs/heads/master
2020-04-06T03:40:18.180208
2008-08-28T03:43:26
2008-08-28T03:43:26
34,305,386
2
0
null
null
null
null
UTF-8
C++
false
false
2,194
h
////////////////////////////////////////////////////////////////////////// // File: CEvent.h // // Author: Rodney Kite (RK) // // Purpose: The event class for the game. ////////////////////////////////////////////////////////////////////////// #pragma once #include <string> using std::string; typedef string EVENTID; class CEvent { private: EVENTID m_EventID; // The ID of this event. void *m_pParam; // Parameter that is specific to this event. public: ////////////////////////////////////////////////////////////////////////// // Function: CEvent // Last Modified: 7/17/08 // Purpose : Constructor. ////////////////////////////////////////////////////////////////////////// CEvent() { m_EventID = "Nothing Set"; m_pParam = 0; } ////////////////////////////////////////////////////////////////////////// // Function: ~CEvent // Last Modified: 7/17/08 // Purpose : Destructor. ////////////////////////////////////////////////////////////////////////// ~CEvent() { } ////////////////////////////////////////////////////////////////////////// // Function: SetEventParams // Last Modified: 7/17/08 // Purpose : set the event paramaters. ////////////////////////////////////////////////////////////////////////// void SetEventParams(EVENTID eventID, void *pData = 0) { m_EventID = eventID; m_pParam = pData; } ////////////////////////////////////////////////////////////////////////// // Function: Accessors // Last Modified: 7/17/08 // Purpose : Returns the specified type. ////////////////////////////////////////////////////////////////////////// inline void SetEventID(EVENTID eventID) { m_EventID = eventID; } inline void SetParam(void *pParam) { m_pParam = pParam; } ////////////////////////////////////////////////////////////////////////// // Function: Modifiers // Last Modified: 7/17/08 // Purpose: Modifies the specified type. ////////////////////////////////////////////////////////////////////////// inline EVENTID GetEventID(void) { return m_EventID; } inline void *GetParam(void) { return m_pParam; } };
[ "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec" ]
[ [ [ 1, 62 ] ] ]
4386c2e68cd74ea9b31e615a450868d1f4d7cf1d
fea3442c89fa747bdf951ca951da25fc18769768
/gui.h
bb5493207fea55f878f291256b91a53f5416ce3c
[]
no_license
mentat/407
430d5e775d43706e75d5e9fb993deecc1cb99b87
515ddd3a42546f09d7f8b78812e70e08eed8a5ab
refs/heads/master
2021-01-25T10:28:39.924266
2011-03-23T22:32:18
2011-03-23T22:32:18
1,518,565
0
1
null
null
null
null
UTF-8
C++
false
false
3,177
h
// --*-c++-*-- /* Symmetry Groups Software Copyright (C) 2003 Jesse Lovelace <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MA407_GUI_H #define MA407_GUI_H #include "wx/wx.h" #include "wx/html/htmlwin.h" #include "wx/glcanvas.h" #include "wx/listctrl.h" #include "shape.h" #include <GL/gl.h> #include <GL/glu.h> // Define a new application type class MyApp: public wxApp { public: bool OnInit(void); }; // Define a new frame type class SolidGLCanvas; class wxImageList; class MyFrame: public wxFrame { public: MyFrame(wxFrame *frame, const wxString& title, const wxPoint& pos, const wxSize& size, long style = wxDEFAULT_FRAME_STYLE); ~MyFrame(); void OnExit(wxCommandEvent& event); void OnSize(wxSizeEvent& event); void OnTimer(wxTimerEvent& event); void OnSelectShape(wxListEvent& event); void OnListFace(wxCommandEvent& event); void OnOrbit(wxCommandEvent& event); void OnStab(wxCommandEvent& event); void OnRotBox(wxCommandEvent& event); public: void CreateImageList(); /// Load the face data into the choice box void LoadFaceData(); wxHtmlWindow * m_html; int m_count; int m_shapeIndex; wxTimer m_timer; wxImageList * m_imageList; SolidGLCanvas* m_canvas; DECLARE_EVENT_TABLE() }; class SolidGLCanvas: public wxGLCanvas { friend class MyFrame; public: SolidGLCanvas(wxWindow *parent, const wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = "TestGLCanvas"); ~SolidGLCanvas(); void OnPaint(wxPaintEvent& event); void OnSize(wxSizeEvent& event); void OnEraseBackground(wxEraseEvent& event); void OnEnterWindow( wxMouseEvent& event ); void OnMouseEvent( wxMouseEvent& event ); void Render( void ); void InitGL(void); void Rotate( GLfloat deg ); private: // GLvoid glPrint2d(const string& text, float x, float y); GLvoid glPrint(const string& text, bool coords= false, float x=0.0, float y=0.0, float z=0.0); // Custom GL "Print" Routine GLvoid BuildFont(GLvoid); void DrawXYZ(wxPaintDC * dc); Shape * m_shape; bool m_init; /// for fonts GLuint m_base; GLYPHMETRICSFLOAT m_gmf[256]; DECLARE_EVENT_TABLE() }; #endif
[ [ [ 1, 121 ] ] ]