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
99b75f7f01dd0cb08619c5d9dd6d973eb547514f
3ecc6321b39e2aedb14cb1834693feea24e0896f
/src/world.cpp
f25d0eea4e6a4dcdecef8aec33f714c190198e87
[]
no_license
weimingtom/forget3d
8c1d03aa60ffd87910e340816d167c6eb537586c
27894f5cf519ff597853c24c311d67c7ce0aaebb
refs/heads/master
2021-01-10T02:14:36.699870
2011-06-24T06:21:14
2011-06-24T06:21:14
43,621,966
1
1
null
null
null
null
UTF-8
C++
false
false
14,084
cpp
/***************************************************************************** * Copyright (C) 2009 The Forget3D Project by Martin Foo ([email protected]) * ALL RIGHTS RESERVED * * License I * Permission to use, copy, modify, and distribute this software for * any purpose and WITHOUT a fee is granted under following requirements: * - You make no money using this software. * - The authors and/or this software is credited in your software or any * work based on this software. * * Licence II * Permission to use, copy, modify, and distribute this software for * any purpose and WITH a fee is granted under following requirements: * - As soon as you make money using this software, you have to pay a * licence fee. Until this point of time, you can use this software * without a fee. * Please contact Martin Foo ([email protected]) for further details. * - The authors and/or this software is credited in your software or any * work based on this software. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS * BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER, * INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR * REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT THE AUTHORS HAVE * BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. *****************************************************************************/ #include "world.h" namespace F3D { /** * World class for all games using F3D. */ World* World::m_instance = NULL; World::World() : #ifndef ANDROID_NDK m_display(EGL_NO_DISPLAY), m_context(EGL_NO_CONTEXT), m_surface(EGL_NO_SURFACE), #endif m_width(0), m_height(0), m_bgred(0.0f), m_bggreen(0.0f), m_bgblue(0.0f), m_bgalpha(0.5f), m_fovy(60.0f), m_znear(1.0f), m_zfar(1000.0f), m_cameras(NULL), m_fog(NULL), m_light(NULL) { #ifdef DEBUG printf("World constructor...\n"); #endif setCameraCount(1); setActiveCamera(0); } World::~World() { deinitEGL(); DELETEANDNULL(m_cameras, true); DELETEANDNULL(m_fog, false); DELETEANDNULL(m_light, false); #ifdef DEBUG printf("World destructor...\n"); #endif } World* World::getInstance() { if (m_instance == NULL) { m_instance = new World(); } return m_instance; } void World::release() { if (m_instance != NULL) delete m_instance; m_instance = NULL; } void World::setBgColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { m_bgred = red; m_bggreen = green; m_bgblue = blue; m_bgalpha = alpha; } // camera functions void World::setCameraCount(int cameraCount) { if (m_cameras != NULL) { delete[] m_cameras; m_cameras = NULL; } if (cameraCount > 0) { #ifdef DEBUG printf("World create [%d] cameras ...\n", cameraCount); #endif m_cameraCount = cameraCount; // create meshs m_cameras = new Camera[m_cameraCount]; } } int World::getCameraCount() { return m_cameraCount; } Camera *World::getCamera(int cameraIndex) { return &m_cameras[cameraIndex]; } void World::setActiveCamera(int cameraIndex) { m_cameraIndex = cameraIndex; } Camera *World::getActiveCamera() { return &m_cameras[m_cameraIndex]; } void World::setFog(Fog* fog) { m_fog = fog; } void World::setLight(Light* light) { m_light = light; } bool World::initEGL() { #ifndef ANDROID_NDK EGLint config_nums = -1; EGLint maj_ver; EGLint min_ver; EGLConfig config; #ifdef _WIN32_WCE EGLint config_attribs[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, EGL_DEPTH_SIZE, 16, EGL_BUFFER_SIZE, 16, EGL_ALPHA_SIZE, EGL_DONT_CARE, EGL_STENCIL_SIZE, EGL_DONT_CARE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; #elif defined(WIN32) EGLint config_attribs[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_ALPHA_SIZE, EGL_DONT_CARE, EGL_STENCIL_SIZE, EGL_DONT_CARE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; #else EGLint config_attribs[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 0, EGL_NONE }; #endif #ifdef USE_WRAPPER_GL int result = Utils::initGlWrapper(); if (!result) { #ifdef DEBUG MessageBox(0, TEXT("Import EGL & GL functions error!\nAnd ensure you have a GPU!"), TEXT("Error"), MB_OK); #endif return false; } #endif // !USE_WRAPPER_GL //start init EGL #if (defined(WIN32) || defined(_WIN32_WCE)) && defined(IS_DC_EGL) HDC hdc = GetDC( m_hwnd ); m_display = eglGetDisplay( (NativeDisplayType)hdc ); #else m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); #endif #ifndef USE_VINCENT if (!checkEglError("eglGetDisplay")) return false; #endif eglInitialize(m_display, &maj_ver, &min_ver); #ifdef DEBUG printf("maj_ver: %d, min_ver: %d\n", maj_ver, min_ver); #if (defined(WIN32) || defined(_WIN32_WCE)) TCHAR infoStr[1024]; wsprintf(infoStr, TEXT("maj_ver: %d, min_ver: %d"), maj_ver, min_ver); MessageBox(m_hwnd, infoStr, TEXT("EGL Info"), MB_OK); #endif #endif if (!checkEglError("eglInitialize")) return false; eglGetConfigs(m_display, NULL, 0, &config_nums); #ifdef DEBUG printf("config_nums: %d\n", config_nums); #if (defined(WIN32) || defined(_WIN32_WCE)) wsprintf(infoStr, TEXT("config_nums: %d"), config_nums); MessageBox(m_hwnd, infoStr, TEXT("EGL Info"), MB_OK); #endif #endif if (!checkEglError("eglGetConfigs")) return false; eglChooseConfig(m_display, config_attribs, &config, 1, &config_nums); if (!checkEglError("eglChooseConfig")) return false; #if (defined(WIN32) || defined(_WIN32_WCE)) m_surface = eglCreateWindowSurface(m_display, config, m_hwnd, NULL); #else m_surface = eglCreateWindowSurface(m_display, config, android_createDisplaySurface(), NULL); #endif if (!checkEglError("eglCreateWindowSurface")) return false; m_context = eglCreateContext(m_display, config, NULL, NULL); if (!checkEglError("eglCreateContext")) return false; eglMakeCurrent(m_display, m_surface, m_surface, m_context); if (!checkEglError("eglMakeCurrent")) return false; eglQuerySurface(m_display, m_surface, EGL_WIDTH, &m_width); eglQuerySurface(m_display, m_surface, EGL_HEIGHT, &m_height); #ifdef DEBUG printf("********EGL info********\n"); printf("EGL_VENDOR\t: %s\n", eglQueryString(m_display, EGL_VENDOR)); printf("EGL_VERSION\t: %s\n", eglQueryString(m_display, EGL_VERSION)); printf("EGL_EXTENSIONS\t: %s\n", eglQueryString(m_display, EGL_EXTENSIONS)); #ifndef USE_VINCENT printf("EGL_CLIENT_APIS\t: %s\n", eglQueryString(m_display, EGL_CLIENT_APIS)); #endif printf("m_width\t\t: %d\n", m_width); printf("m_height\t: %d\n", m_height); #if (defined(WIN32) || defined(_WIN32_WCE)) wsprintf(infoStr, TEXT("m_width: %d, m_height: %d"), m_width, m_height); MessageBox(m_hwnd, infoStr, TEXT("EGL Info"), MB_OK); CHAR infoChr[1024]; sprintf(infoChr, "EGL_VENDOR: %s\nEGL_VERSION: %s\nEGL_EXTENSIONS: %s", eglQueryString(m_display, EGL_VENDOR), eglQueryString(m_display, EGL_VERSION), eglQueryString(m_display, EGL_EXTENSIONS)); Utils::asciiToWchar(infoStr, infoChr); MessageBox(m_hwnd, infoStr, TEXT("EGL Info"), MB_OK); #endif #endif checkEglError("eglAll"); #endif return true; } bool World::initGL() { // Initialize viewport and projection. glViewport( 0, 0, m_width, m_height ); //set the matrix mode gluPerspective(); //reset the matrix mode glMatrixMode(GL_MODELVIEW); //GL_PROJECTION,GL_MODELVIEW glLoadIdentity(); // set some init status glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glShadeModel(GL_SMOOTH);//GL_SMOOTH,GL_FLAT //glEnable(GL_CULL_FACE); //glCullFace(GL_FRONT); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //GL_FASTEST GL_NICEST #ifdef DEBUG #if (defined(WIN32) || defined(_WIN32_WCE)) TCHAR infoStr[1024]; CHAR infoChr[1024]; sprintf(infoChr, "GL_VENDOR: %s\nGL_RENDERER: %s\nGL_VERSION: %s\nGL_EXTENSIONS: %s", glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_EXTENSIONS)); Utils::asciiToWchar(infoStr, infoChr); MessageBox(m_hwnd, infoStr, TEXT("GL Info"), MB_OK); #endif printf("********GL info********\n"); printf("GL_VENDOR\t: %s\n", glGetString(GL_VENDOR)); printf("GL_RENDERER\t: %s\n", glGetString(GL_RENDERER)); printf("GL_VERSION\t: %s\n", glGetString(GL_VERSION)); printf("GL_EXTENSIONS\t: %s\n", glGetString(GL_EXTENSIONS)); #endif return true; } void World::deinitEGL() { #ifndef ANDROID_NDK eglMakeCurrent(m_display, NULL, NULL, NULL); eglDestroyContext(m_display, m_context); eglDestroySurface(m_display, m_surface); eglTerminate(m_display); #endif #ifdef USE_WRAPPER_GL Utils:: deinitGlWrapper(); #endif //USE_WRAPPER_GL } #if (defined(WIN32) || defined(_WIN32_WCE)) bool World::init(HWND hwnd) { m_hwnd = hwnd; #else bool World::init() { #endif if (!initEGL()) { #ifdef DEBUG printf("initEGL() error!\n"); #if (defined(WIN32) || defined(_WIN32_WCE)) MessageBox(hwnd, TEXT("Init EGL error!"), TEXT("Error"), MB_OK); #endif #endif // !DEBUG return false; } #if defined(DEBUG) && (defined(WIN32) || defined(_WIN32_WCE)) MessageBox(hwnd, TEXT("Init EGL ok, start init GL!"), TEXT("Info"), MB_OK); #endif initGL(); return true; } void World::setSize(int width, int height) { m_width = width; m_height = height; } void World::resize(int width, int height) { setSize(width, height); //after resize screen, call initGL() again initGL(); } int World::getWidth() { return m_width; } int World::getHeight() { return m_height; } void World::setPerspective(GLfloat fovy, GLfloat znear, GLfloat zfar) { m_fovy = fovy; m_znear = znear; m_zfar = zfar; } void World::gluPerspective() { // Start in projection mode. GLfloat xmin, xmax, ymin, ymax; GLfloat aspect = (GLfloat)m_width / (GLfloat)m_height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); ymax = (float) (m_znear * tan(m_fovy * M_PI / 360.0)); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; #ifdef DEBUG printf("glFrustumf()\t: %.3f, %.3f, %.3f, %.3f, %.3f, %.3f\n", xmin, xmax, ymin, ymax, m_znear, m_zfar); #endif glFrustumf(xmin, xmax, ymin, ymax, m_znear, m_zfar); } bool World::checkEglError(const char *name) { #ifndef ANDROID_NDK unsigned err = eglGetError(); if (err != EGL_SUCCESS) { #ifdef DEBUG printf("%s() error: 0x%4x!\n", name, err); #if (defined(WIN32) || defined(_WIN32_WCE)) TCHAR errorStr[512]; wsprintf(errorStr, TEXT("%s() error: 0x%4x!"), name, err); MessageBox(m_hwnd, errorStr, TEXT("GL Info"), MB_OK); #endif /* defined(WIN32) || defined(_WIN32_WCE) */ #endif /* DEBUG */ return false; } else { return true; } #else return true; #endif // !ANDROID_NDK } void World::prepareRender() { // Set the screen background color. glClearColor(m_bgred, m_bggreen, m_bgblue, m_bgalpha); glClearDepthf(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); m_cameras[m_cameraIndex].gluLookAt(); if (m_fog != NULL) { glEnable(GL_FOG); m_fog->initFog(); } else glDisable(GL_FOG); if (m_light != NULL) { glEnable(GL_LIGHTING); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); m_light->initLight(); } else { glDisable(GL_LIGHTING); glDisable(GL_NORMALIZE); glDisable(GL_COLOR_MATERIAL); } } void World::finishRender() { #ifndef ANDROID_NDK eglSwapBuffers(m_display, m_surface); #endif } }
[ "i25ffz@8907dee8-4f14-11de-b25e-a75f7371a613" ]
[ [ [ 1, 468 ] ] ]
62687741734fa2256932c432ff42f36710492807
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/timers.hpp
28d4dbf041019da6d1ca1ebc5bdc66b7dac9ae33
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
UTF-8
C++
false
false
892
hpp
#ifndef TIMERS_HPP #define TIMERS_HPP #include "core/container/application_item.hpp" #include "core/createble_i.hpp" #include "core/samp/pawn/pawn_plugin_i.hpp" #include <boost/date_time/posix_time/posix_time.hpp> class timers : public application_item , public createble_i , public pawn::plugin_on_tick_i { public: typedef std::tr1::shared_ptr<timers> ptr; static ptr instance(); timers(); virtual ~timers(); public: // createble_i virtual void create(); public: // plugin_on_tick_i virtual void plugin_on_tick(); private: boost::posix_time::ptime time_last_250; boost::posix_time::ptime time_last_500; boost::posix_time::ptime time_last_1000; boost::posix_time::ptime time_last_5000; boost::posix_time::ptime time_last_15000; boost::posix_time::ptime time_last_60000; }; #endif // TIMERS_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 33 ] ] ]
4e5cefe5262ebe5dce98ce9e1916214b59c7a6e2
7d349e6342c084a4d11234a0aa0846db41c50303
/themeagent/Observable.h
0a3ba201c5e54d0e7bfc19f92bae5fb63c29a89d
[]
no_license
Tobbe/themeagent
8f72641228a9cbb4c57e3bcd7475aee5f755eb3d
cbdbf93859ee7ef5d43330da7dd270f7b966f0b2
refs/heads/master
2020-12-24T17:44:42.819782
2009-04-18T22:38:58
2009-04-18T22:38:58
97,412
3
0
null
null
null
null
UTF-8
C++
false
false
247
h
#ifndef OBSERVABLE_H_ #define OBSERVABLE_H_ #include <vector> class Observable { private: std::vector<class Observer*> observers; public: void addObserver(class Observer *o); void notifyObservers(const Observable *o); }; #endif
[ [ [ 1, 15 ] ] ]
af25030f653a716f55135c4a28b42fc063d61941
be7eb51cea272a091523a4f85fbd5a2dfa107c95
/Classes/WindowCapture.cpp
eca1b33f53decb233c2a6c199aacb0784d717206
[]
no_license
HousonCao/screendump
e517714a4fd357d6608384442a8ab2b1a35e7d75
483c400a5769cea568a2246aa8054006ad6a40ae
refs/heads/master
2021-01-18T17:55:14.002682
2010-10-12T19:01:02
2010-10-12T19:01:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,617
cpp
#include "stdafx.h" #include "afxwin.h" #include "WindowCapture.h" #include "gdiplus.h" #include "OSCheck.h" using namespace Gdiplus; // Throws CResourceException if GDIStartup failed. WindowCapture::WindowCapture(GlobalSettings gs) { lastGdiStatus = Aborted; // Initialized to anything not "Ok" so that StartGDI is the *only* one to be able to change it to "Ok". programSettings = gs; gdiStartupInput.GdiplusVersion = 1; gdiStartupInput.DebugEventCallback = NULL; gdiStartupInput.SuppressBackgroundThread = FALSE; gdiStartupInput.SuppressExternalCodecs = FALSE; if(!StartGDI()) { AfxThrowResourceException(); } } WindowCapture::~WindowCapture() { StopGDI(); } BOOL WindowCapture::StartGDI() { lastGdiStatus = GdiplusStartup(&gdiToken, &gdiStartupInput, NULL); return (lastGdiStatus == Ok); } void WindowCapture::StopGDI() { if(lastGdiStatus == Ok) { GdiplusShutdown(gdiToken); lastGdiStatus = Aborted; } } BOOL WindowCapture::CaptureScreen(const CString& filename) { CSize captureArea(GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN)); return DoCapture(CPoint(0, 0), captureArea, filename); } BOOL WindowCapture::CaptureWindow(const CString& filename) { HWND hWnd = NULL; hWnd = ::GetForegroundWindow(); if(!hWnd) { return FALSE; } CRect rect; GetWindowRect(hWnd, &rect); rect.NormalizeRect(); return DoCapture(CPoint(rect.left, rect.top), CSize(rect.Width(), rect.Height()), filename); } BOOL WindowCapture::DoCapture(const POINT& coords, const SIZE& areaSize, const CString& filename) { CDC dc; HDC hdc = GetDC(NULL); dc.Attach(hdc); // Create a memory DC into which the bitmap will be captured CDC memDC; memDC.CreateCompatibleDC(&dc); // If there is already a bitmap, delete it as we are going to replace it CBitmap bmp; bmp.DeleteObject(); ICONINFO info; GetIconInfo((HICON)::GetCursor(), &info); CURSORINFO cursor; cursor.cbSize = sizeof(CURSORINFO); GetCursorInfo(&cursor); bmp.CreateCompatibleBitmap(&dc, areaSize.cx, areaSize.cy); CBitmap * oldbm = memDC.SelectObject(&bmp); // Before we copy the image in, we blank the bitmap to // the background fill color memDC.FillSolidRect(&CRect(0,0,areaSize.cx, areaSize.cy), RGB(255,255,255)); // Copy the window image from the window DC into the memory DC memDC.BitBlt(0, 0, areaSize.cx, areaSize.cy, &dc, coords.x, coords.y, SRCCOPY|CAPTUREBLT); if(programSettings.bWantCursor) { // We need to compensate for pointer position if we're taking a screenshot of a region/window. // The super sad news is that: 1) you have to consider all icons as 32x32 as that's a Windows // spec thing, 2) THEY ARE NOT TOP ALIGNED. God dammit, was it so hard to make all standard cursors // top aligned? That magic "10" you see down here was compensating for the default mouse cursor. // I'm even thinking of letting it be adjustable. It's so irritating, I don't even want to think // about doing math or whatever to figure out where the actual tip of the arrow is. // PS: Turns out the dafault icons under Vista/7 are actually top aligned. That's why we check // and ajust accordingly. int osVersion = OSCheck::GetMajorOSVersion(); // 6 is Vista int offsetX = (osVersion >= 6) ? 0 : 10; int offsetY = (osVersion >= 6) ? 0 : 10; CPoint cursorOffset(cursor.ptScreenPos.x - coords.x - offsetX, cursor.ptScreenPos.y - coords.y - offsetY); // Now draw the image of the cursor that we captured during // the mouse move. DrawIcon will draw a cursor as well. memDC.DrawIcon(cursorOffset, (HICON)cursor.hCursor); } memDC.SelectObject(oldbm); Bitmap outputBitMap(bmp, NULL); if(programSettings.bWantClipboard) { if(OpenClipboard(NULL)) { EmptyClipboard(); SetClipboardData(CF_BITMAP, bmp); CloseClipboard(); } } BOOL success = DumpImage(&outputBitMap, filename); DeleteObject(bmp.Detach()); DeleteDC(dc.Detach()); DeleteDC(memDC.Detach()); return success; } int WindowCapture::GetEncoderClsid(const WCHAR* format, CLSID* pClsid) { UINT num = 0; // number of image encoders UINT size = 0; // size of the image encoder array in bytes ImageCodecInfo* pImageCodecInfo = NULL; GetImageEncodersSize(&num, &size); if(size == 0) return -1; // Failure pImageCodecInfo = (ImageCodecInfo*)(malloc(size)); if(pImageCodecInfo == NULL) return -1; // Failure GetImageEncoders(num, size, pImageCodecInfo); for(UINT j = 0; j < num; ++j) { if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 ) { *pClsid = pImageCodecInfo[j].Clsid; free(pImageCodecInfo); return j; // Success } } free(pImageCodecInfo); return -1; // Failure } BOOL WindowCapture::DumpImage(Bitmap* aBmp, const CString& filename) { // MSDN NOTE: //When you create an EncoderParameters object, you must allocate enough memory //to hold all of the EncoderParameter objects that will eventually be placed in //the array. For example, if you want to create an EncoderParameters object that will //hold an array of five EncoderParameter objects, you should use code similar to the following: // EncoderParameters* pEncoderParameters = (EncoderParameters*) // malloc(sizeof(EncoderParameters) + 4 * sizeof(EncoderParameter)); CString fullFilePath(filename); EncoderParameters eParams; // Since we use only 1 parameter we don't need the fancy malloc stuff CLSID encoderClsid; BOOL extAppend = FALSE; // Check if the file extension was already provided to avoid double appending it. switch (programSettings.sEnc) { case sEncBMP: if (fullFilePath.GetLength() > 4) { extAppend = (fullFilePath.Right(4) == _T(".bmp")) ? FALSE : TRUE; } else { extAppend = TRUE; } fullFilePath += extAppend ? _T(".bmp") : _T(""); GetEncoderClsid(_T("image/bmp"), &encoderClsid); eParams.Count = 0; break; case sEncPNG: if (fullFilePath.GetLength() > 4) { extAppend = (fullFilePath.Right(4) == _T(".png")) ? FALSE : TRUE; } else { extAppend = TRUE; } fullFilePath += extAppend ? _T(".png") : _T(""); GetEncoderClsid(_T("image/png"), &encoderClsid); eParams.Count = 0; break; case sEncJPEG: if (fullFilePath.GetLength() > 4) { extAppend = (fullFilePath.Right(4) == _T(".jpg")) ? FALSE : TRUE; } else { extAppend = TRUE; } fullFilePath += extAppend ? _T(".jpg") : _T(""); GetEncoderClsid(_T("image/jpeg"), &encoderClsid); eParams.Count = 1; eParams.Parameter[0].Guid = EncoderQuality; eParams.Parameter[0].NumberOfValues = 1; eParams.Parameter[0].Type = EncoderParameterValueTypeLong; eParams.Parameter[0].Value = &programSettings.lJpgQuality; break; } Status stat = aBmp->Save(fullFilePath, &encoderClsid, &eParams); return stat == Ok; } void WindowCapture::UpdateSettings(const GlobalSettings& settings) { programSettings = settings; }
[ [ [ 1, 4 ], [ 6, 7 ], [ 10, 11 ], [ 13, 27 ], [ 44, 44 ], [ 47, 48 ], [ 50, 59 ], [ 61, 62 ], [ 64, 64 ], [ 135, 167 ], [ 169, 181 ], [ 186, 187 ], [ 198, 202 ], [ 213, 217 ], [ 228, 232 ], [ 234, 236 ], [ 244, 244 ] ], [ [ 5, 5 ], [ 8, 9 ], [ 12, 12 ], [ 28, 43 ], [ 45, 46 ], [ 49, 49 ], [ 60, 60 ], [ 63, 63 ], [ 65, 134 ], [ 168, 168 ], [ 182, 185 ], [ 188, 197 ], [ 203, 212 ], [ 218, 227 ], [ 233, 233 ], [ 237, 243 ] ] ]
89361aa31096ab56f4ae284f007811010cd2dd9b
c497f6d85bdbcbb21e93ae701c5570f16370f0ae
/Sync/Lets_try_all_engine/backup/Clear/SatMde.hpp
d8e2bec3923f4ed8074a67296b4b6cd59d893632
[]
no_license
mfkiwl/gpsgyan_fork
91b380cf3cfedb5d1aac569c6284bbf34c047573
f7c850216c16b49e01a0653b70c1905b5b6c2587
refs/heads/master
2021-10-15T08:32:53.606124
2011-01-19T16:24:18
2011-01-19T16:24:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,995
hpp
/* * File name : satMDE.hpp * * Abstract : This file contains definitions of structures and Global classes * Struchers used in the Gpsgyan project. * * Compiler : Visual C++ Version 9.0 * * Compiler options : Default * * Pragmas : None used * * H/W Platform : IBM PC * * Portability : No Operating system call used. * No machine specific instruction used. * No compiler specific routines used. * Hence Portable. * * Authors : Priyank Kumar * * * Version history : Base version * Priyank Kumar November 2009 * * References : None * * Functions called : None * Library Used : GPStk * Copyright 2009, The University of Texas at Austin * */ /* GPSTk Library*/ #include "DayTime.hpp" #include "SatID.hpp" #include "Position.hpp" #include "SatMdeMac.hpp" #include "SatMedtypes.hpp" #include "MSCData.hpp" #include "MSCStream.hpp" #include "FFIdentifier.hpp" //#include "TropModel.hpp" #include "IonoModel.hpp" //#include "IonoModelStore.hpp" #include "Geodetic.hpp" #include "SunPosition.hpp" /*C++ Systems Include files*/ #include <iostream> #include <string> #include <map> #include <vector> /*GPSGyan Include files*/ #include "EngineFramework.hpp" using namespace gpstk; class SatMDE: public EngineFramework { public: NEW_EXCEPTION_CLASS(ExcSatMDE , gpstk::Exception); SatMDE(const string& applName) throw() : EngineFramework( applName, "this computes satellite Position , Velocity and time for the specified receiever position and time") {}; // bool initialize(int argc, char *argv[]) throw(); // virtual void process(); void GetPassiveInput(satMDE_psvIstruct &ref_psv); void GetActiveInput(satMDE_actIstruct &ref_act); void GetPassiveParam(); void GetActiveParam(); void InputInfToEngine(Kind kind); // think of argv and argc implementation //virtual void runEngine(); void InputParamToEngine(Kind kind);// throw(InvalidParameter); //bool runEngine() throw(); //void outputInfFromEngine(std::ostream & s ,const std::string & data); void outputInfFromEngine(std::ostream & s ); //void OutputDumpOfEngine(); // Public Data memebers engineHealthMonitor satMDE_probe; std::vector<satMDE_ostruct> satMDE_oData; std::vector<SatID> visibleSV; bool visiblityComputed; satMDE_actIstruct ref_act; satMDE_psvIstruct ref_psv; double alpha[4],beta[4],iono_freq; DayTime inp_time ; double usr_elev; std::vector<int> error_number; //std::string op_inf; protected : //void EngineControl(Kind kind); void VerifyIpToEngine() throw(ExcSatMDE); // void prepareIpToEngine() ; void MethodOfEngine() throw(ExcSatMDE); void SatMDE_ExpHandler(ExcSatMDE &e); // Fromatted File Printing std::string print_content(satMDE_ostruct &ostruct); std::string print_header(); void updateLocals(const Xvt& satXvt ,const Xvt& rxXvt); double ComputeCorrectedRange(Xvt& satXvt , Xvt& rxXvt); double getIonoCorrections(double alpha[],double beta[],DayTime Tr, Xvt &rxPos, double elevation, double azimuth,gpstk::IonoModel::Frequency ); void ComputePhaseAndDoppler(int sat_index,double rangeRate); //double getTropoCorrections( TropModel *pTropModel, double elevation ); //void ComputeSvVisiblity(); int findSvPrvRange(SatID vis_svid); double ComputePhaseWindUpDelay(int sat_index,DayTime time); double getWindUp( const SatID& satid, const DayTime& time, const Triple& sat, const Triple& sunPosition, const Position& posRx); // void validateOpOfEngine(); // void PrepareOpOfEngine() ; //virtual void dump(std::ostream &s); private : satMDE_actIstruct satMDE_ai; satMDE_psvIstruct satMDE_pi; unsigned int visSV; std::vector<satMDE_ostruct> satMDE_pData; std::vector<SatID> rejectedSV; std::vector<satMDE_range> prevRange,prange; bool timeToCompute; bool newSV; bool isThisFirstTime; int visCounter; double rawrange; double elevation; double azimuth; double elevationGeodetic; double azimuthGeodetic; Triple cosines; double ionoL1,carrierDopplerL1,codeDopplerCaL1; double ionoL2,carrierDopplerL2,codeDopplerCaL2; double ionoL5,carrierDopplerL5,codeDopplerPyL5; // Error Value double minElev; Position tempPos; map<SatID, phaseData> phase_station; map<SatID, phaseData> phase_satellite; //int IIR_Sat[12] ; bool IIR; //double phaseWindUp; };
[ "priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7" ]
[ [ [ 1, 190 ] ] ]
e0a5d9d56888458277954fe2132f3cf5756001a4
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/UILayer/CreditsThread.cpp
f7f0a21c058aee0d8eca1d1abfd4a43da40e7e17
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
20,175
cpp
/* * $Id: CreditsThread.cpp 5056 2008-03-20 04:03:12Z thilon $ * * this file is part of eMule * Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "stdafx.h" #include "emule.h" #include "CreditsThread.h" #include "OtherFunctions.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // define mask color #define MASK_RGB (COLORREF)0xFFFFFF ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNAMIC(CCreditsThread, CGDIThread) BEGIN_MESSAGE_MAP(CCreditsThread, CGDIThread) //{{AFX_MSG_MAP(CCreditsThread) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() CCreditsThread::CCreditsThread(CWnd* pWnd, HDC hDC, CRect rectScreen) : CGDIThread(pWnd,hDC) { m_rectScreen = rectScreen; m_rgnScreen.CreateRectRgnIndirect(m_rectScreen); m_nScrollPos = 0; m_pbmpOldBk = NULL; m_pbmpOldCredits = NULL; m_pbmpOldScreen = NULL; m_pbmpOldMask = NULL; m_nCreditsBmpWidth = 0; m_nCreditsBmpHeight = 0; } CCreditsThread::~CCreditsThread() { } BOOL CCreditsThread::InitInstance() { InitThreadLocale(); BOOL bResult = CGDIThread::InitInstance(); // NOTE: Because this is a separate thread, we have to delete our GDI objects here (while // the handle maps are still available.) if(m_dcBk.m_hDC != NULL && m_pbmpOldBk != NULL) { m_dcBk.SelectObject(m_pbmpOldBk); m_pbmpOldBk = NULL; m_bmpBk.DeleteObject(); } if(m_dcScreen.m_hDC != NULL && m_pbmpOldScreen != NULL) { m_dcScreen.SelectObject(m_pbmpOldScreen); m_pbmpOldScreen = NULL; m_bmpScreen.DeleteObject(); } if(m_dcCredits.m_hDC != NULL && m_pbmpOldCredits != NULL) { m_dcCredits.SelectObject(m_pbmpOldCredits); m_pbmpOldCredits = NULL; m_bmpCredits.DeleteObject(); } if(m_dcMask.m_hDC != NULL && m_pbmpOldMask != NULL) { m_dcMask.SelectObject(m_pbmpOldMask); m_pbmpOldMask = NULL; m_bmpMask.DeleteObject(); } // clean up the fonts we created for(int n = 0; n < m_arFonts.GetSize(); n++) { m_arFonts.GetAt(n)->DeleteObject(); delete m_arFonts.GetAt(n); } m_arFonts.RemoveAll(); return bResult; } // wait for vertical retrace // makes scrolling smoother, especially at fast speeds // NT does not like this at all void waitvrt(void) { __asm { mov dx,3dah VRT: in al,dx test al,8 jnz VRT NoVRT: in al,dx test al,8 jz NoVRT } } void CCreditsThread::SingleStep() { // if this is our first time, initialize the credits if(m_dcCredits.m_hDC == NULL) { CreateCredits(); } // track scroll position static int nScrollY = 0; // timer variables LARGE_INTEGER nFrequency; LARGE_INTEGER nStart; LARGE_INTEGER nEnd; int nTimeInMilliseconds; BOOL bTimerValid; nStart.QuadPart = 0; if(!QueryPerformanceFrequency(&nFrequency)) { bTimerValid = FALSE; } else { bTimerValid = TRUE; // get start time QueryPerformanceCounter(&nStart); } CGDIThread::m_csGDILock.Lock(); { PaintBk(&m_dcScreen); m_dcScreen.BitBlt(0, 0, m_nCreditsBmpWidth, m_nCreditsBmpHeight, &m_dcCredits, 0, nScrollY, SRCINVERT); m_dcScreen.BitBlt(0, 0, m_nCreditsBmpWidth, m_nCreditsBmpHeight, &m_dcMask, 0, nScrollY, SRCAND); m_dcScreen.BitBlt(0, 0, m_nCreditsBmpWidth, m_nCreditsBmpHeight, &m_dcCredits, 0, nScrollY, SRCINVERT); // wait for vertical retrace if(m_bWaitVRT) waitvrt(); m_dc.BitBlt(m_rectScreen.left, m_rectScreen.top, m_rectScreen.Width(), m_rectScreen.Height(), &m_dcScreen, 0, 0, SRCCOPY); GdiFlush(); } CGDIThread::m_csGDILock.Unlock(); // continue scrolling nScrollY += m_nScrollInc; if(nScrollY >= m_nCreditsBmpHeight) nScrollY = 0; // scrolling up if(nScrollY < 0) nScrollY = m_nCreditsBmpHeight; // scrolling down // delay scrolling by the specified time if(bTimerValid) { QueryPerformanceCounter(&nEnd); nTimeInMilliseconds = (int)((nEnd.QuadPart - nStart.QuadPart) * 1000 / nFrequency.QuadPart); if(nTimeInMilliseconds < m_nDelay) { Sleep(m_nDelay - nTimeInMilliseconds); } } else { Sleep(m_nDelay); } } void CCreditsThread::PaintBk(CDC* pDC) { //save background the first time if (m_dcBk.m_hDC == NULL) { m_dcBk.CreateCompatibleDC(&m_dc); m_bmpBk.CreateCompatibleBitmap(&m_dc, m_rectScreen.Width(), m_rectScreen.Height()); m_pbmpOldBk = m_dcBk.SelectObject(&m_bmpBk); m_dcBk.BitBlt(0, 0, m_rectScreen.Width(), m_rectScreen.Height(), &m_dc, m_rectScreen.left, m_rectScreen.top, SRCCOPY); } pDC->BitBlt(0, 0, m_rectScreen.Width(), m_rectScreen.Height(), &m_dcBk, 0, 0, SRCCOPY); } void CCreditsThread::CreateCredits() { InitFonts(); InitColors(); InitText(); m_dc.SelectClipRgn(&m_rgnScreen); m_dcScreen.CreateCompatibleDC(&m_dc); m_bmpScreen.CreateCompatibleBitmap(&m_dc, m_rectScreen.Width(), m_rectScreen.Height()); m_pbmpOldScreen = m_dcScreen.SelectObject(&m_bmpScreen); m_nCreditsBmpWidth = m_rectScreen.Width(); m_nCreditsBmpHeight = CalcCreditsHeight(); m_dcCredits.CreateCompatibleDC(&m_dc); m_bmpCredits.CreateCompatibleBitmap(&m_dc, m_nCreditsBmpWidth, m_nCreditsBmpHeight); m_pbmpOldCredits = m_dcCredits.SelectObject(&m_bmpCredits); m_dcCredits.FillSolidRect(0, 0, m_nCreditsBmpWidth, m_nCreditsBmpHeight, MASK_RGB); CFont* pOldFont; pOldFont = m_dcCredits.SelectObject(m_arFonts.GetAt(0)); m_dcCredits.SetBkMode(TRANSPARENT); int y = 0; int nFont; int nColor; int nLastFont = -1; int nLastColor = -1; int nTextHeight = m_dcCredits.GetTextExtent(_T("Wy")).cy; for(int n = 0; n < m_arCredits.GetSize(); n++) { CString sType = m_arCredits.GetAt(n).Left(1); if(sType == 'B') { // it's a bitmap CBitmap bmp; if(! bmp.LoadBitmap(m_arCredits.GetAt(n).Mid(2))) { CString str; str.Format(_T("Could not find bitmap resource \"%s\". Be sure to assign the bitmap a QUOTED resource name"), m_arCredits.GetAt(n).Mid(2)); AfxMessageBox(str); return; } BITMAP bmInfo; bmp.GetBitmap(&bmInfo); CDC dc; dc.CreateCompatibleDC(&m_dcCredits); CBitmap* pOldBmp = dc.SelectObject(&bmp); // draw the bitmap m_dcCredits.BitBlt((m_rectScreen.Width() - bmInfo.bmWidth) / 2, y, bmInfo.bmWidth, bmInfo.bmHeight, &dc, 0, 0, SRCCOPY); dc.SelectObject(pOldBmp); bmp.DeleteObject(); y += bmInfo.bmHeight; } else if(sType == 'S') { // it's a vertical space y += _ttoi(m_arCredits.GetAt(n).Mid(2)); } else { // it's a text string nFont = _ttoi(m_arCredits.GetAt(n).Left(2)); nColor = _ttoi(m_arCredits.GetAt(n).Mid(3,2)); if(nFont != nLastFont) { m_dcCredits.SelectObject(m_arFonts.GetAt(nFont)); nTextHeight = m_arFontHeights.GetAt(nFont); } if(nColor != nLastColor) { m_dcCredits.SetTextColor(m_arColors.GetAt(nColor)); } CRect rect(0, y, m_rectScreen.Width(), y + nTextHeight); m_dcCredits.DrawText(m_arCredits.GetAt(n).Mid(6), &rect, DT_CENTER); y += nTextHeight; } } m_dcCredits.SetBkColor(MASK_RGB); m_dcCredits.SelectObject(pOldFont); // create the mask bitmap m_dcMask.CreateCompatibleDC(&m_dcScreen); m_bmpMask.CreateBitmap(m_nCreditsBmpWidth, m_nCreditsBmpHeight, 1, 1, NULL); // select the mask bitmap into the appropriate dc m_pbmpOldMask = m_dcMask.SelectObject(&m_bmpMask); // build mask based on transparent color m_dcMask.BitBlt(0, 0, m_nCreditsBmpWidth, m_nCreditsBmpHeight, &m_dcCredits, 0, 0, SRCCOPY); } void CCreditsThread::InitFonts() { // create each font we'll need and add it to the fonts array CDC dcMem; dcMem.CreateCompatibleDC(&m_dc); CFont* pOldFont; int nTextHeight; LOGFONT lf; // font 0 // SMALL ARIAL CFont* font0 = new CFont; memset((void*)&lf, 0, sizeof(lf)); lf.lfHeight = 12; lf.lfWeight = 500; lf.lfQuality = NONANTIALIASED_QUALITY; _tcscpy(lf.lfFaceName, _T("Arial")); font0->CreateFontIndirect(&lf); m_arFonts.Add(font0); pOldFont = dcMem.SelectObject(font0); nTextHeight = dcMem.GetTextExtent(_T("Wy")).cy; m_arFontHeights.Add(nTextHeight); // font 1 // MEDIUM BOLD ARIAL CFont* font1 = new CFont; memset((void*)&lf, 0, sizeof(lf)); lf.lfHeight = 14; lf.lfWeight = 600; lf.lfQuality = NONANTIALIASED_QUALITY; _tcscpy(lf.lfFaceName, _T("Arial")); font1->CreateFontIndirect(&lf); m_arFonts.Add(font1); dcMem.SelectObject(font1); nTextHeight = dcMem.GetTextExtent(_T("Wy")).cy; m_arFontHeights.Add(nTextHeight); // font 2 // LARGE ITALIC HEAVY BOLD TIMES ROMAN CFont* font2 = new CFont; memset((void*)&lf, 0, sizeof(lf)); lf.lfHeight = 16; lf.lfWeight = 700; //lf.lfItalic = TRUE; lf.lfQuality = ANTIALIASED_QUALITY; _tcscpy(lf.lfFaceName, _T("Arial")); font2->CreateFontIndirect(&lf); m_arFonts.Add(font2); dcMem.SelectObject(font2); nTextHeight = dcMem.GetTextExtent(_T("Wy")).cy; m_arFontHeights.Add(nTextHeight); // font 3 CFont* font3 = new CFont; memset((void*)&lf, 0, sizeof(lf)); lf.lfHeight = 25; lf.lfWeight = 900; lf.lfQuality = ANTIALIASED_QUALITY; _tcscpy(lf.lfFaceName, _T("Arial")); font3->CreateFontIndirect(&lf); m_arFonts.Add(font3); dcMem.SelectObject(font3); nTextHeight = dcMem.GetTextExtent(_T("Wy")).cy; m_arFontHeights.Add(nTextHeight); dcMem.SelectObject(pOldFont); } void CCreditsThread::InitColors() { // define each color we'll be using m_arColors.Add(PALETTERGB(0, 0, 0)); // 0 = BLACK m_arColors.Add(PALETTERGB(90, 90, 90)); // 1 = very dark gray m_arColors.Add(PALETTERGB(128, 128, 128)); // 2 = DARK GRAY m_arColors.Add(PALETTERGB(192, 192, 192)); // 3 = LIGHT GRAY m_arColors.Add(PALETTERGB(200, 50, 50)); // 4 = very light gray m_arColors.Add(PALETTERGB(255, 255, 128)); // 5 white m_arColors.Add(PALETTERGB(0, 0, 128)); // 6 dark blue m_arColors.Add(PALETTERGB(128, 128, 255)); // 7 light blue m_arColors.Add(PALETTERGB(0, 106, 0)); // 8 dark green } void CCreditsThread::InitText() { // 1st pair of digits identifies the font to use // 2nd pair of digits identifies the color to use // B = Bitmap // S = Space (moves down the specified number of pixels) CString sTmp; /* You may NOT modify this copyright message. You may add your name, if you changed or improved this code, but you mot not delete any part of this message, make it invisible etc. */ // start at the bottom of the screen sTmp.Format(_T("S:%d"), m_rectScreen.Height()); m_arCredits.Add(sTmp); sTmp.Format(_T("03:00:%s"),GetResString(IDS_CAPTION)); m_arCredits.Add(sTmp); sTmp.Format(_T("02:06:Version %s"),CGlobalVariable::GetCurVersionLong()); m_arCredits.Add(sTmp); m_arCredits.Add(_T("01:06:Copyright (C) 2002-2008 VeryCD")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:00:VeryCD Teams")); m_arCredits.Add(_T("01:06:China: .o¦Ï§°¡ð.NET")); m_arCredits.Add(_T("01:06:aho~~aho~")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Chocobo")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:GGSoSo")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Huby")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:KERNEL1983")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:SearchDream")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Soar")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:thilon")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:YunCheng")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:WangNa")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:nightsuns")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:04:UI Design")); m_arCredits.Add(_T("01:06:China: richy")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:04:Developers")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Unknown1")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Ornis")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:04:Tester")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Monk")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Daan")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Elandal")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Frozen_North")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:kayfam")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Khandurian")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Masta2002")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:mrLabr")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Nesi-San")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:SeveredCross")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Skynetman")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:04:Retired Members")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Merkur (the Founder)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:tecxx")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Pach2")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Juanjo")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Barry")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Dirus")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:04:Thanks to these programmers")); m_arCredits.Add(_T("02:04:for publishing useful codeparts")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Paolo Messina (ResizableDialog class)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:6:PJ Naughter (HttpDownload Dialog)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Jim Connor (Scrolling Credits)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Yury Goltsman (extended Progressbar)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Magomed G. Abdurakhmanov (Hyperlink ctrl)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Arthur Westerman (Titled menu)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Tim Kosse (AsyncSocket-Proxysupport)")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:Keith Rule (Memory DC)")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:07:And thanks to the following")); m_arCredits.Add(_T("02:07:people for translating eMule")); m_arCredits.Add(_T("02:07:into different languages:")); m_arCredits.Add(_T("S:20")); m_arCredits.Add(_T("01:06:Arabic: Dody")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Albanian: Besmir")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Basque: TXiKi")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Breton: KAD-Korvigello?an Drouizig")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Bulgarian: DapKo, Dumper")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Catalan: LeChuck")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Chinese simplyfied: Tim Chen, Qilu T.")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Chinese Traditional: CML, Donlong, Ryan")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Czech: Patejl")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Danish: Tiede, Cirrus, Itchy")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Estonian: Symbio")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Dutch: Mr.Bean")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Finnish: Nikerabbit")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:French: Motte, Emzc, Lalrobin")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Galician: Juan, Emilio R.")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Greek: Michael Papadakis")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Italian: Trevi, FrankyFive")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Japanese: DukeDog, Shinro T.")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Hebrew: Avi-3k")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Hungarian: r0ll3r")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Korean: pooz")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Latvian: Zivs")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Lithuanian: Daan")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Maltese: Reuben")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Norwegian (Bokmal): Iznogood")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Norwegian (Nynorsk): Hallvor")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Polish: Tomasz \"TMouse\" Broniarek")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Portugese: Filipe, Luís Claro")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Portugese Brasilian: DarthMaul,Brasco")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Romanian: Dragos")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Russian: T-Mac, BRMAIL")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Slowenian: Rok Kralj")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Spanish Castellano: Azuredraco, Javier L., |_Hell_|")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Swedish: Andre")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Turkish: Burak Y.")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Ukrainian: Kex")); m_arCredits.Add(_T("S:05")); m_arCredits.Add(_T("01:06:Vietnamese: Paul Tran HQ Loc")); m_arCredits.Add(_T("S:50")); m_arCredits.Add(_T("02:04:Part of easyMule is based on Kademlia:")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("02:04:Peer-to-peer routing based on the XOR metric.")); m_arCredits.Add(_T("S:10")); m_arCredits.Add(_T("01:06:Copyright (C) 2002 Petar Maymounkov")); m_arCredits.Add(_T("S:5")); m_arCredits.Add(_T("01:06:http://kademlia.scs.cs.nyu.edu")); // pause before repeating m_arCredits.Add(_T("S:100")); } int CCreditsThread::CalcCreditsHeight() { int nHeight = 0; for(int n = 0; n < m_arCredits.GetSize(); n++) { CString sType = m_arCredits.GetAt(n).Left(1); if(sType == 'B') { // it's a bitmap CBitmap bmp; if (! bmp.LoadBitmap(m_arCredits.GetAt(n).Mid(2))) { CString str; str.Format(_T("Could not find bitmap resource \"%s\". Be sure to assign the bitmap a QUOTED resource name"), m_arCredits.GetAt(n).Mid(2)); AfxMessageBox(str); return -1; } BITMAP bmInfo; bmp.GetBitmap(&bmInfo); nHeight += bmInfo.bmHeight; } else if(sType == 'S') { // it's a vertical space nHeight += _ttoi(m_arCredits.GetAt(n).Mid(2)); } else { // it's a text string int nFont = _ttoi(m_arCredits.GetAt(n).Left(2)); nHeight += m_arFontHeights.GetAt(nFont); } } return nHeight; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 681 ] ] ]
b7f2fbe9e000ce369b4158bba11c2eea6543d35c
582d6ee710677872456df6a4265ce6c8b74e2a64
/irc/irc.cpp
30da958b5dd2bda25266547ef6d39c307c3b02e2
[]
no_license
Alvo/OFPMonitor
1069b25570323020fc60aad89b37336e2f6ebb04
6f750d6d6ebb943fdd1908203a8b1950c34568ba
refs/heads/master
2020-04-02T22:30:18.455535
2011-05-12T21:31:25
2011-05-12T21:31:25
903,925
0
0
null
null
null
null
UTF-8
C++
false
false
16,798
cpp
#include <list> #include <iostream.h> #include "Unit1.h" #include "Unit2.h" #include "irc.h" #include <vector.h> #include <set.h> #include <time.h> #include <sstream> //#define DEBUG_MSG #ifdef DEBUG_MSG #define INPUTOUT 1 #else #define INPUTOUT 0 #endif extern int tcpsocket(void) ; extern unsigned long dnsdb(char *host); extern unsigned long resolv(char *host) ; static DWORD WINAPI irc_ThreadProc( LPVOID lpThreadParameter ); /* Thread which is always active and detects disconnects from network */ static DWORD WINAPI irc_ThreadProc_ReconnectWatchThread( LPVOID lpThreadParameter ); /* 0: thread not started, 1: thread started, will stay as 1 forever */ static int rReconnectWatchThread_started = 0; static struct irc_thread__parm * ircThreadInstance ; static void getplayername( ); static void start_conversation( int sd, char * name ); static void sendMessage(const char * xmsg); static string after(string& in, string& needle); static string before(string& in, string& needle); static int starts(string& in, string& needle); static string currentTimeString(); static string plrname_localtoirc( char * name ); static string name_irctolocal(string& n); static string allowedExtraCharacters = "_-[]^"; struct irc_thread__parm { TForm1 * tform1 ; vector<string> messages; vector<string> userz; vector<string> playersParted; vector<string> playersJoined; set<string> userzSorted; string hoscht; int updatePlayers; int sd; int loggedIn; void consume(char* c, int i); int sentVersion; public: irc_thread__parm():sentVersion(0),updatePlayers(0){ } int sendString(string&); }; static char playerName[1024]; void chat_client_disconnect() { if (ircThreadInstance && ircThreadInstance->sd) { closesocket(ircThreadInstance->sd); ircThreadInstance->sd = 0; ircThreadInstance->hoscht.clear(); } } bool chat_client_connect() { getplayername(); if (!ircThreadInstance) { ircThreadInstance = new irc_thread__parm(); } int temporarySocket = tcpsocket(); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); int ip = resolv(Form1->getChatHost().c_str()); addr.sin_addr.s_addr = ip; addr.sin_port = htons(Form1->getChatPort()); addr.sin_family = AF_INET; int connectRes = connect(temporarySocket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); if( connectRes >= 0 && temporarySocket) { ircThreadInstance->sd = temporarySocket; CreateThread(0, 0, irc_ThreadProc, ircThreadInstance, 0, 0); if (!rReconnectWatchThread_started) { rReconnectWatchThread_started = 1; CreateThread(0, 0, irc_ThreadProc_ReconnectWatchThread, 0, 0, 0); } return true; } else { closesocket(temporarySocket); } return false; } static string name_irctolocal(string& n) { string playername = n; if (starts(playername , "@")){ playername = after(playername , "@"); } string k(ofpprefix); int p = playername.find(k, 0); if (p >= 0) { return string(playername, p + k.size()); } return playername; } string plrname_localtoirc( char * name ) { string n ( name ); for(int i = 0; i < n.size(); i++){ char c = n.at(i); int isSmall = c >= 'a' && c <= 'z'; int isBig = c >= 'A' && c <= 'Z'; int isNum = c >= '0' && c <= '9'; int extra = Form1->doNameFilter(allowedExtraCharacters.c_str(), c); if (!isSmall && !isBig && !(i > 1 && isNum) && !extra){ n[i] = '_'; } } return ofpprefix + n; } void appendText( TForm1 * tform1, string& msg ) { TMemo *tr = tform1->MemoChatOutput; tr->Lines->Add(msg.c_str()); } static string currentTimeString() { time_t rawtime; struct tm * timeinfo; char buffer [80]; time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (buffer, 80, "%H:%M", timeinfo); return buffer; } void chat_client_timercallback(void * t) { TForm1 *tform1 = (TForm1 *) t; if (ircThreadInstance && ircThreadInstance->messages.size() > 0) { vector<string> m (ircThreadInstance->messages); ircThreadInstance->messages.clear(); //string privMsgNeedle = "PRIVMSG #" + channelname_operationflashpoint1 + " :"; string privMsgNeedle = Form1->getChatChannel().c_str(); privMsgNeedle = "PRIVMSG #" + privMsgNeedle + " :"; for(int i = 0; i < m.size(); i++) { string& omsg = m.at(i); if (INPUTOUT) { appendText(tform1, omsg); } string cmsg = omsg; string playername; int fnd = 0; if ((fnd = cmsg.find(privMsgNeedle,0)) >= 0) { cmsg = string(cmsg, fnd + privMsgNeedle.size()); int emp = omsg.find("!", 1); playername = string(omsg, 1, emp - 1); playername = name_irctolocal(playername); if(!Form1->isChatUserBlocked(playername.c_str())) { cmsg = currentTimeString() + " - " + playername + ": " + cmsg; appendText(tform1, cmsg); if(Form1->doNameFilter(cmsg.c_str(), playerName) || Form1->doNameFilter(cmsg.c_str(), (ofpprefix + plrname_localtoirc(playerName)).c_str())) { tform1->ChatNotification(cmsg.c_str()); } } } } } if (0 && ircThreadInstance && ircThreadInstance->userz.size() > 0) { vector<string> m (ircThreadInstance->userz); ircThreadInstance->userz.clear(); for(int i = 0; i < m.size(); i++) { TStringGrid *tssg = tform1->StringGrid3; int rc = tssg->RowCount; tssg->RowCount = rc + 1; string& stre = m.at(i); string convertedPlayerName = name_irctolocal( stre ); tssg->Cells[0][rc] = convertedPlayerName.c_str(); } } if (ircThreadInstance->updatePlayers) { ircThreadInstance->updatePlayers = 0; set<string> userzSortedCopy = set<string>(ircThreadInstance->userzSorted); TStringGrid *tssg = tform1->StringGrid3; tssg->RowCount = userzSortedCopy.size(); // convert to vector vector<string> ulist(userzSortedCopy.begin(), userzSortedCopy.end()); for(int i = 0; i < ulist.size(); i++) { tssg->Cells[0][i] = ulist[i].c_str(); } } if (ircThreadInstance->playersParted.size() > 0) { vector<string> pp = vector<string>(ircThreadInstance->playersParted); ircThreadInstance->playersParted.clear(); for(int i = 0; i < pp.size(); i++) { //ircThreadInstance->sendString string text = currentTimeString() + " ******* " + pp.at(i) + " "; text += WINDOW_SETTINGS->getGuiString("STRING_CHAT_LEFT").c_str(); text += " ******"; appendText(tform1, text); } } if (ircThreadInstance->playersJoined.size() > 0) { vector<string> pp = vector<string>(ircThreadInstance->playersJoined); ircThreadInstance->playersJoined.clear(); for(int i = 0; i < pp.size(); i++) { //ircThreadInstance->sendString string text = currentTimeString() + " ******* " + pp.at(i) + " "; text += WINDOW_SETTINGS->getGuiString("STRING_CHAT_JOINED").c_str(); text += " ******"; appendText(tform1, text); } } } DWORD WINAPI irc_ThreadProc (LPVOID lpdwThreadParam__ ) { struct irc_thread__parm * p_parm = (struct irc_thread__parm *) lpdwThreadParam__; if(p_parm->sd) { start_conversation(p_parm->sd, playerName); char buff [1<<10]; int r; while(p_parm->sd && (r = recv(p_parm->sd, buff, sizeof(buff), 0)) > 0){ p_parm->consume(buff, r); } } } DWORD WINAPI irc_ThreadProc_ReconnectWatchThread (LPVOID lpdwThreadParam__ ) { while(true) { Sleep(300 * 1000); // sleep longer time until nickname in use is solved if (ircThreadInstance && ircThreadInstance->sd) { int r = ircThreadInstance->sendString("PING " + ircThreadInstance->hoscht); if (r < 0) { // could not set send, trying to reconnect ircThreadInstance->userz.clear(); ircThreadInstance->playersParted.clear(); ircThreadInstance->playersJoined.clear(); ircThreadInstance->userzSorted.clear(); ircThreadInstance->updatePlayers = 1; ircThreadInstance->messages.push_back( currentTimeString( ) + " - trying to reconnect" ); chat_client_connect(); } } } } int irc_thread__parm::sendString(string& s) { return send(sd, s.c_str(), s.length(), 0); } void start_conversation( int sd, char * name ) { string ircName = plrname_localtoirc(name); stringstream ss; ss << "CAP LS\n" << "NICK " << ircName << "\n" << "USER " << ircName << " 0 * :" << ircName << "\n" << "CAP REQ :multi-prefix\n" << "CAP END\n" << "USERHOST "<< ircName << "\n" << "JOIN #" << Form1->getChatChannel() << "\n" << "MODE #" << Form1->getChatChannel() << "\n"; string msg = ss.str(); int s = send(sd, msg.c_str(), msg.length(), 0); return; } void getplayername() { String currentOFPPlayer = WINDOW_SETTINGS->getCurrentPlayerName(); if(currentOFPPlayer.IsEmpty()) { string tmp = "Guest" + currentTimeString(); strcpy(playerName, tmp.c_str()); } else { strcpy(playerName, currentOFPPlayer.c_str()); } return; } static vector<string> explode(string s){ vector<string> r; if(s.size() > 0){ int p = 0; int t = 0; while(p < s.size() && (t = s.find("\r\n", p) ) > p) { string line (s, p, t-p); r.push_back( line ); p = t + 2; } if (p < s.size() - 1) { r.push_back( string(s, p, s.size() - p) ); } } return r; } static string readPlayerFromLine(string& s){ string name = after(s, ":"); name = before(name, "!"); name = name_irctolocal(name); return name; } void irc_thread__parm::consume(char* c2, int i2) { vector<string> msgs = explode( string(c2, i2) ); int it = 0; for(;it < msgs.size(); it++ ){ string& s = msgs.at(it); if (hoscht.size() == 0) { int p = s.find(" NOTICE" , 0); if (p > 0) { hoscht = string( s , 0, p ); } } //string playerzNeedle( hoscht + " 353 " ); string body = after(s , " "); if (starts(body , "353 ")) { string ps2 = after( body , ":" ); while (ps2.size() > 0 ) { int isLastPlayer = ps2.find( " " , 0 ) == -1; string player; if (isLastPlayer) { player = ps2; } else { player = before(ps2, " "); } player = name_irctolocal(player); userz.push_back(player); userzSorted.insert(player); updatePlayers = 1; if (isLastPlayer) { break; } ps2 = after(ps2, " "); } } else if ( starts(body , "QUIT ") ){ string name = readPlayerFromLine(s); playersParted.push_back(name); userzSorted.erase(name); updatePlayers = 1; } else if ( starts(body , "433 ")) { string ps2 = after( body , ":" ); appendText(Form1, ps2); Form1->MENUITEM_MAINMENU_CHAT_DISCONNECT->Click(); } int pingFind = s.find("PING " + hoscht, 0) ; int joinFind = s.find(" JOIN ", 0) ; int partFind = s.find(" PART ", 0) ; int endNameListFind = s.find("End of /NAMES list.",0); if (pingFind == 0) { // sending pong string pong ("PONG " + hoscht + "\r\n"); send(sd, pong.c_str(), pong.length(), 0); } else if (!sentVersion && endNameListFind >= 0) { sentVersion = 1; sendMessage( ("Logged in with " + Application->Title).c_str()); } else if (joinFind > 0) { string name = readPlayerFromLine(s); playersJoined.push_back(name); userzSorted.insert(name); updatePlayers = 1; } else if (partFind > 0) { string name = readPlayerFromLine(s); playersParted.push_back(name); userzSorted.erase(name); updatePlayers = 1; } messages.push_back(s); } } void sendMessage(const char *xmsg) { string msg( xmsg ); string channel = Form1->getChatChannel().c_str(); msg = "PRIVMSG #" + channel + " :" + msg + "\r\n"; send(ircThreadInstance->sd, msg.c_str(), msg.length(), 0); } void chat_client_pressedReturnKey(void *t, const char *msg) { TForm1 *tform1 = (TForm1 *) t; if (ircThreadInstance && ircThreadInstance->sd) { sendMessage(msg); appendText(tform1, currentTimeString( ) + " - " + playerName + ": " + msg); } } static string after(string& in, string& needle) { int i = in.find(needle, 0); if (i >= 0) { return string(in, i + needle.length()); } return ""; } static string before(string& in, string& needle) { int i = in.find(needle, 0); if (i > 0) { return string(in, 0, i); } return ""; } static int starts(string& in, string& needle) { return in.find(needle, 0) == 0; }
[ "Owe@core2.(none)", "[email protected]" ]
[ [ [ 1, 421 ] ], [ [ 422, 422 ] ] ]
a8b32dc523b84a4eb828d8d1c820228eaeaabbbf
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/WrapperDX/Buffer/VertexBufferEx.h
9e2082246378f27b69d1fdea4eb6654d787a3dc7
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
#ifndef _VERTEX_BUFFER_EX_ #define _VERTEX_BUFFER_EX_ #ifndef _VERTEX_BUFFER_ #include "WrapperDx/Buffer/VertexBuffer.h" #endif class VertexBufferEx : public VertexBuffer { public: VertexBufferEx(); virtual ~VertexBufferEx(); virtual HRESULT Create(unsigned int size, unsigned int nElts, const void * data, bool IsFlaggedStreamOutput = false); virtual HRESULT Destroy(); void Bind(); void * Map(); void Unmap(); }; #endif // _VERTEX_BUFFER_EX_
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 23 ] ] ]
39d5cd827070c1787dfe86f07a8dac3685aeb7b2
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/GSARTagLayoutFilter/GSARTagLayoutFilterProp.cpp
845a7eceaad5db95a46daf24ba6d194a147212ac
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
4,190
cpp
#include "stdafx.h" #include "GSARTagLayoutFilterProp.h" #include "GSARTagLayoutFilterApp.h" IMPLEMENT_DYNAMIC(GSARTagLayoutFilterProp, GSMFCProp) extern CGSARTagLayoutFilterApp theApp; void GSARTagLayoutFilterProp::DoDataExchange(CDataExchange* pDX) { __super::DoDataExchange(pDX); DDX_Control(pDX, IDC_slrBlackLevel, m_slrBlackLevel); DDX_Control(pDX, IDC_txtBlackLevel, m_txtBlackLevel); DDX_Control(pDX, IDC_cbFPS, m_cbFPS); } BOOL GSARTagLayoutFilterProp::OnInitDialog() { BOOL ret = __super::OnInitDialog(); return ret; } BEGIN_MESSAGE_MAP(GSARTagLayoutFilterProp, GSMFCProp) ON_CBN_SELCHANGE(IDC_cbFPS, &GSARTagLayoutFilterProp::OnCbnSelchangecbfps) ON_NOTIFY(NM_CUSTOMDRAW, IDC_slrBlackLevel, &GSARTagLayoutFilterProp::OnNMCustomdrawslrblacklevel) END_MESSAGE_MAP() GSARTagLayoutFilterProp::GSARTagLayoutFilterProp(IUnknown *pUnk) : GSMFCProp(NAME("GSARTagLayoutFilterProp"), pUnk), m_pFilter(0) { } GSARTagLayoutFilterProp::~GSARTagLayoutFilterProp() { if (m_pFilter != NULL) { m_pFilter->Release(); m_pFilter = NULL; } } //override CBasePropertyPage Method HRESULT GSARTagLayoutFilterProp::OnConnect(IUnknown *pUnk) { //override CBasePropertyPage Method if (pUnk == NULL) { return E_POINTER; } if (m_pFilter == NULL) { pUnk->QueryInterface(IID_IGSARTagLayoutFilter, reinterpret_cast<void**>(&m_pFilter)); return S_OK; } return S_OK; } HRESULT GSARTagLayoutFilterProp::OnDisconnect(void) { if (m_pFilter != NULL) { m_pFilter->Release(); m_pFilter = NULL; } return S_OK; } BOOL GSARTagLayoutFilterProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return TRUE; } HRESULT GSARTagLayoutFilterProp::OnActivate(void) { if (m_pFilter != NULL) EnableWindow(TRUE); else EnableWindow(FALSE); m_slrBlackLevel.SetRange(0, 10, FALSE); m_cbFPS.AddString(L"500"); m_cbFPS.AddString(L"120"); m_cbFPS.AddString(L"60"); m_cbFPS.AddString(L"30"); m_cbFPS.AddString(L"20"); m_cbFPS.AddString(L"15"); m_cbFPS.AddString(L"10"); m_cbFPS.AddString(L"5"); GetSetting(); return S_OK; } HRESULT GSARTagLayoutFilterProp::OnApplyChanges(void) { return S_OK; } CUnknown *WINAPI GSARTagLayoutFilterProp::CreateInstance(LPUNKNOWN punk, HRESULT *phr) { ASSERT(phr); // assuming we don't want to modify the data GSARTagLayoutFilterProp *pNewObject = new GSARTagLayoutFilterProp(punk); if(pNewObject == NULL) { if (phr) *phr = E_OUTOFMEMORY; } return pNewObject; } HRESULT GSARTagLayoutFilterProp::GetSetting() { if (m_pFilter == NULL) return E_FAIL; WCHAR str[MAX_PATH] = {0}; float blackLevel = m_pFilter->GetBlackLevel(); int nBlackLevel = blackLevel*10; m_slrBlackLevel.SetPos(nBlackLevel); swprintf_s(str, MAX_PATH, L"%.1f", blackLevel); m_txtBlackLevel.SetWindowText(str); float fps = m_pFilter->GetFrameRate(); int cbCount = m_cbFPS.GetCount(); double cbFPS; int chooseIdx = -1; float minError = 1000; for (int i =0 ; i< cbCount; i++) { m_cbFPS.GetLBText(i, str); swscanf_s(str, L"%lf", &cbFPS); if (abs(fps - cbFPS) < minError) { chooseIdx = i; minError = abs(fps - cbFPS); } } if (chooseIdx != -1) m_cbFPS.SetCurSel(chooseIdx); return S_OK; } void GSARTagLayoutFilterProp::OnCbnSelchangecbfps() { if (m_pFilter == NULL) return; int idx = m_cbFPS.GetCurSel(); WCHAR str[MAX_PATH] = {0}; m_cbFPS.GetLBText(idx, str); double cbFps = 0; swscanf_s(str, L"%lf", &cbFps); m_pFilter->SetFrameRate(cbFps); } void GSARTagLayoutFilterProp::OnNMCustomdrawslrblacklevel(NMHDR *pNMHDR, LRESULT *pResult) { LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR); // TODO: Add your control notification handler code here *pResult = 0; if (m_pFilter == NULL) return ; WCHAR str[MAX_PATH] = {0}; int nBlackLevel = m_slrBlackLevel.GetPos(); float blackLevel = nBlackLevel*0.1; m_pFilter->SetBlackLevel(blackLevel); m_slrBlackLevel.SetPos(nBlackLevel); swprintf_s(str, MAX_PATH, L"%.1f", blackLevel); m_txtBlackLevel.SetWindowText(str); }
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 185 ] ] ]
91d281563e413f19ea140c677ec0c7161c0623a6
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/objects/yokes/minimus/MinimusScriptYoke.h
ff6db5c43cae27a87aa4a400185f51876d5b7d21
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
h
/*** * hesperus: MinimusScriptYoke.h * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #ifndef H_HESP_MINIMUSSCRIPTYOKE #define H_HESP_MINIMUSSCRIPTYOKE #include <ASXEngine.h> #include <ASXRefType.h> #include <source/level/objects/base/IYoke.h> #include <source/level/objects/base/ObjectID.h> namespace hesp { //#################### FORWARD DECLARATIONS #################### class ObjectManager; class MinimusScriptYoke : public IYoke, public ASXRefType<MinimusScriptYoke> { //#################### PRIVATE VARIABLES #################### private: ObjectID m_objectID; ObjectManager *m_objectManager; ASXEngine_Ptr m_engine; ASXModule_Ptr m_module; bool m_initialised; IYoke_Ptr m_subyoke; //#################### CONSTRUCTORS #################### public: MinimusScriptYoke(const ObjectID& objectID, ObjectManager *objectManager, const std::string& scriptName, const ASXEngine_Ptr& engine); //#################### PUBLIC METHODS #################### public: void add_ref(); std::vector<ObjectCommand_Ptr> generate_commands(InputState& input, const std::vector<CollisionPolygon_Ptr>& polygons, const OnionTree_CPtr& tree, const NavManager_CPtr& navManager); static void register_for_scripting(const ASXEngine_Ptr& engine); void release(); static std::string type_string(); //#################### SCRIPT INTERFACE #################### private: void clear_subyoke(); void goto_position(double x, double y, double z); bool subyoke_active() const; bool subyoke_exists() const; }; } #endif
[ [ [ 1, 55 ] ] ]
c89b54c846da6ebbcef011e7ad48002fb2959586
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Samples/NPR/App.cpp
2720b634d3ff9f5c54c887043472a5f8c8786108
[]
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,859
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: App.cpp Version: 0.03 Info: This demo presents 2D non-photorealistic rendering. --------------------------------------------------------------------------- */ #include "App.h" #include "nGENE.h" #include <sstream> App::App() { } //---------------------------------------------------------------------- App::~App() { cleanup(); } //---------------------------------------------------------------------- void App::cleanup() { } //---------------------------------------------------------------------- void App::createApplication() { // In this demo we hide standard config dialog. FrameworkWin32::suppressConfigDialog(); FrameworkWin32::createApplication(); Maths::setAngleUnit(Maths::ANGLE_RADIAN); Renderer::getSingleton().setClearColour(Colour::COLOUR_BLACK); SceneManager* sm = Engine::getSingleton().getSceneManager(0); // Let's create camera with orthogonal projection. // This way we can easily achieve 2D look of the scene. // Important thing to note is from now on, we have to think // in pixels instead of abstract units. Camera2D* cam = (Camera2D*)sm->createCamera(L"Camera2D", L"Camera"); cam->setVelocity(1000.0f); cam->setPosition(100.0f, -0.5f, -300.0f); cam->setUp(Vector3::UNIT_Y); Quaternion rot(Vector3(0.0f, 1.0f, 0.0f), Maths::PI / 4.0f); Quaternion rot2(Vector3(1.0f, 0.0f, 0.0f), Maths::PI / 4.0f); Quaternion rotFinal = rot * rot2; rotFinal.normalize(); if(Maths::abs <float>(rotFinal.x - cam->getRotation().x) > 0.001f || Maths::abs <float>(rotFinal.y - cam->getRotation().y) > 0.001f || Maths::abs <float>(rotFinal.z - cam->getRotation().z) > 0.001f || Maths::abs <float>(rotFinal.w - cam->getRotation().w) > 0.001f) { cam->setRotation(rotFinal); } cam->getFrustumPtr()->setNear(0.0f); cam->getFrustumPtr()->setFar(12000.0f); cam->updateCamera(); sm->getRootNode()->addChild(L"Camera", cam); Engine::getSingleton().setActiveCamera(static_cast<Camera*>(sm->getNode(L"Camera"))); // Create directional light NodeLight* pLight = sm->createLight(LT_DIRECTIONAL); pLight->setPosition(0.0f, 0.0f, 0.0f); pLight->setDirection(Vector3(-0.5f, -1.0f, 0.5f)); Colour clrWorld(204, 204, 204); pLight->setColour(clrWorld); pLight->setRadius(10000.0f); pLight->setCastShadows(false); sm->getRootNode()->addChild(L"WorldLight", pLight); Renderer::getSingleton().addLight(pLight); pLight = sm->createLight(LT_POINT); pLight->setColour(Colour::COLOUR_GREEN); pLight->setPosition(150.0f, 100.0f, 0.0f); pLight->setRadius(1000.0f); pLight->setCastShadows(false); sm->getRootNode()->addChild(L"PointLightGreen", pLight); Renderer::getSingleton().addLight(pLight); pLight = sm->createLight(LT_POINT); pLight->setColour(Colour::COLOUR_MAGENTA); pLight->setPosition(800.0f, 100.0f, 0.0f); pLight->setRadius(1000.0f); pLight->setCastShadows(false); sm->getRootNode()->addChild(L"PointLightGreen2", pLight); Renderer::getSingleton().addLight(pLight); NodeMesh <MeshLoadPolicyXFile>* pWall = sm->createMesh <MeshLoadPolicyXFile>(L"wall_with_pillars.x"); pWall->setScale(80.00001f, 80.1f, 80.00001f); Material* mat = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"normalMap"); for(uint i = 0; i < 10; ++i) pWall->getSurface(i)->setMaterial(mat); Material* mat2 = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"parallaxOcclusionMap"); Surface* surf = pWall->getSurface(L"surface_10"); surf->setMaterial(mat2); surf = pWall->getSurface(L"surface_11"); surf->setMaterial(mat); surf = pWall->getSurface(L"surface_12"); surf->setMaterial(mat); sm->getRootNode()->addChild(L"Wall", *pWall); NodeMesh <MeshLoadPolicyXFile>* pSculp = sm->createMesh <MeshLoadPolicyXFile>(L"statue.x"); pSculp->setPosition(700.0f, -0.5f, 2.0f); pSculp->setScale(20.0f, 20.0f, 20.0f); surf = pSculp->getSurface(L"surface_2"); surf->setMaterial(mat); sm->getRootNode()->addChild(L"Statue", *pSculp); Engine::getSingleton().getRenderer().setCullingMode(CULL_NONE); // Add input listener m_pInputListener = new MyInputListener(); m_pInputListener->setApp(this); InputSystem::getSingleton().addInputListener(m_pInputListener); // Post-processing - that is what cause water color appearance of the image Material* pMaterial = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"waterColor"); postWaterColor.priority = 0; postWaterColor.material = pMaterial; postWaterColor.material->setEnabled(true); pMaterial = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"pencilStroke"); postPencil.priority = 0; postPencil.material = pMaterial; postPencil.material->setEnabled(false); ((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess"))->addToRender(&postWaterColor); ((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess"))->addToRender(&postPencil); // Set window caption Window* pWindow = Renderer::getSingleton().getWindow(0); pWindow->setWindowCaption(L"Non-photorealistic rendering"); // Create GUI m_pFont = new GUIFont(L"gui_default_font.fnt"); GUIManager::getSingleton().setFont(m_pFont); GUIManager::getSingleton().addWindow(&m_Window); GUIManager::getSingleton().setActiveMaterial(MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"gui_default_active")); GUIManager::getSingleton().setInactiveMaterial(MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"gui_default_inactive")); } //----------------------------------------------------------------------
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 156 ] ] ]
97484090d4c463a13c9a7962b8d412ad107734a2
93eac58e092f4e2a34034b8f14dcf847496d8a94
/ncl30-cpp/ncl30-generator/include/generables/ContextNodeGenerator.h
0d3af0fa1698fb32a6f6b9e0759ef26ebc0a85a7
[]
no_license
lince/ginga-srpp
f8154049c7e287573f10c472944315c1c7e9f378
5dce1f7cded43ef8486d2d1a71ab7878c8f120b4
refs/heads/master
2020-05-27T07:54:24.324156
2011-10-17T13:59:11
2011-10-17T13:59:11
2,576,332
0
0
null
null
null
null
UTF-8
C++
false
false
3,372
h
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file ContextNodeGenerator.h * @author Caio Viel * @date 29-01-10 */ #ifndef _CONTEXTNODEGENERATOR_H #define _CONTEXTNODEGENERATOR_H #include "ncl/components/ContextNode.h" #include "ncl/NclDocument.h" using namespace ::br::pucrio::telemidia::ncl::components; #include "Generable.h" #include "ContentNodeGenerator.h" #include "SwitchNodeGenerator.h" #include "CausalLinkGenerator.h" #include "PropertyAnchorGenerator.h" #include "PortGenerator.h" #include "GeneratorUtil.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generator { class ContextNodeGenerator : public ContextNode { public: /** * Gera o código XML da entidade NCL nó de contexto. * @return Uma string contendo o código NCL gerado. */ string generateCode(NclDocument* nclDocument); /** * Gera o código XML da entidade NCL Body. * @return Uma string contendo o código NCL gerado. */ string generateBodyCode(NclDocument* nclDocument); private: /** * Gera o código XML da interno dos nós de contexto e body. * @return Uma string contendo o código NCL gerado. */ string interCodeGenerate(NclDocument* nclDocument); }; } } } } } #endif /* _CONTEXTNODEGENERATOR_H */
[ [ [ 1, 106 ] ] ]
e02c9a3e226eee9dbe83c33fdec06f060c6af314
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/ImportData.cpp
26ef7d4de5567c6bf23bfe1c6f2dcae21733c936
[]
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
GB18030
C++
false
false
36,536
cpp
// ImportData.cpp : implementation file // Tel:13366898744 #include "stdafx.h" #include "CTaiShanApp.h" #include "ImportData.h" #include "mainfrm.h" #include "CTaiKlineFileKLine.h" #include "SBDestination.h" #include "BrowseForFolder.h" #include <stdio.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int shijianflag=0; IMPLEMENT_DYNCREATE(CImportData, CPropertyPage) CImportData::CImportData() : CPropertyPage(CImportData::IDD) { //{{AFX_DATA_INIT(CImportData) m_importAll = 0; m_install_end = 0; m_install_start = 0; //}}AFX_DATA_INIT pDoc=CMainFrame::m_taiShanDoc ; m_Shanghai=FALSE; m_Shenzhen=FALSE; m_nImportorcancel=0; m_bImport=TRUE; } CImportData::~CImportData() { } void CImportData::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CImportData) DDX_Control(pDX, 1012, m_button1); DDX_Control(pDX, IDC_INSTALLEND, m_ctrlTimeEnd); DDX_Control(pDX, IDC_INSTALLSTART, m_ctrlTimeStart); DDX_Control(pDX, IDC_LIST, m_listfw); DDX_Control(pDX, IDOK, m_okbutton); DDX_Control(pDX, IDC_PROGRESS1, m_progress1); DDX_Control(pDX, 1042, m_ComboDatatype); DDX_Control(pDX, 1011, m_ComboFiletype); DDX_Control(pDX, 1008, m_DataSource); DDX_Radio(pDX, 1013, m_importAll); DDX_DateTimeCtrl(pDX, IDC_INSTALLEND, m_install_end); DDX_DateTimeCtrl(pDX, IDC_INSTALLSTART, m_install_start); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CImportData, CPropertyPage) //{{AFX_MSG_MAP(CImportData) ON_CBN_SELCHANGE(1011, OnSelchangedatatype) ON_CBN_SELCHANGE(1042, OnSelchangedataformat) ON_LBN_SETFOCUS(IDC_LIST, OnSetfocusfwxz) ON_EN_SETFOCUS(1008, OnSetfocus) ON_BN_CLICKED(1013, Onqbyr) ON_BN_CLICKED(1014, Onsdyr) ON_EN_SETFOCUS(1019, OnSetfocusup) ON_EN_SETFOCUS(1020, OnSetfocusdown) ON_BN_CLICKED(IDOK, Onimport) ON_BN_CLICKED(1012, OnButtonSearchfixdata) ON_NOTIFY(NM_CLICK, IDC_LIST, OnClickList) ON_WM_HELPINFO() //}}AFX_MSG_MAP //ON_MESSAGE(WM_DRAWLIST,drawzqsc) END_MESSAGE_MAP() void CImportData::OnOK() { CPropertyPage::OnOK(); } BOOL CImportData::OnInitDialog() { CPropertyPage::OnInitDialog(); ((CComboBox *)GetDlgItem(1042))->SetCurSel(0); ((CComboBox *)GetDlgItem(1011))->SetCurSel(0); m_ComboDatatype.InsertString( 0, "数据格式"); m_ComboDatatype.InsertString( 1, "钱龙数据格式"); m_ComboDatatype.InsertString( 2, "分析家数据格式"); m_ComboDatatype.InsertString( 3, "汇金数据格式"); m_ComboDatatype.InsertString( 4, "胜龙数据格式"); m_ComboDatatype.SetCurSel(0); m_DataSource.ReplaceSel(pDoc->m_CurrentWorkDirectory+"\\StockData.day"); m_importAll = 0; GetDlgItem(IDC_INSTALLSTART)->EnableWindow(FALSE); GetDlgItem(IDC_INSTALLEND)->EnableWindow(FALSE); m_install_start=CTime(1990,1,1,1,1,1); m_install_end =CTime::GetCurrentTime(); LVITEM myitem; myitem.mask=LVIF_TEXT|LVIF_IMAGE; myitem.iSubItem=0; myitem.iImage=6; m_listfw.SetImageList(pDoc->m_imagelist,LVSIL_SMALL); CString stockgroup[]={"上海","深圳","创业"}; for(int i=0;i<3;i++) { myitem.iItem=i; if(i==2) myitem.iImage=9; myitem.pszText=(LPTSTR)stockgroup[i].GetBuffer(stockgroup[i].GetLength()); m_listfw.InsertItem(&myitem); if(i==2) m_stockrange.Add(FALSE); else m_stockrange.Add(TRUE); } UpdateData(FALSE); return TRUE; } void CImportData::OnSelchangedatatype() { if( ((CComboBox*)GetDlgItem(1011))->GetCurSel()==0 ) { m_DataSource.SetWindowText(pDoc->m_CurrentWorkDirectory+"\\StockData.day"); GetDlgItem(1042)->EnableWindow(TRUE); GetDlgItem(1013)->EnableWindow(TRUE); GetDlgItem(1014)->EnableWindow(TRUE); if(shijianflag==1) { GetDlgItem(IDC_INSTALLSTART)->EnableWindow(TRUE); GetDlgItem(IDC_INSTALLEND)->EnableWindow(TRUE); } } else if( ((CComboBox*)GetDlgItem(1011))->GetCurSel()==1 ) { m_DataSource.SetWindowText(pDoc->m_CurrentWorkDirectory+"\\StockData.min"); GetDlgItem(1042)->EnableWindow(FALSE); GetDlgItem(1013)->EnableWindow(TRUE); GetDlgItem(1014)->EnableWindow(TRUE); if(shijianflag==1) { GetDlgItem(IDC_INSTALLSTART)->EnableWindow(TRUE); GetDlgItem(IDC_INSTALLEND)->EnableWindow(TRUE); } } else if( ((CComboBox*)GetDlgItem(1011))->GetCurSel()==2 ) { m_DataSource.SetWindowText("C:\\"); GetDlgItem(1042)->EnableWindow(FALSE); GetDlgItem(1013)->EnableWindow(FALSE); GetDlgItem(1014)->EnableWindow(FALSE); if(shijianflag==1) { GetDlgItem(IDC_INSTALLSTART)->EnableWindow(FALSE); GetDlgItem(IDC_INSTALLEND)->EnableWindow(FALSE); } } } void CImportData::OnSelchangedataformat() { switch( m_ComboDatatype.GetCurSel( ) ) { case 0: m_DataSource.SetSel(0,-1); m_DataSource.ReplaceSel(pDoc->m_CurrentWorkDirectory+"\\StockData.day"); if(m_ComboFiletype.GetCount()==1) { m_ComboFiletype.InsertString(1,"五分钟数据"); m_ComboFiletype.InsertString(2,"一分钟数据"); } break; case 1: m_DataSource.SetSel(0,-1); m_DataSource.ReplaceSel("C:\\"); if(m_ComboFiletype.GetCount()==3) { m_ComboFiletype.DeleteString(1); m_ComboFiletype.DeleteString(1); } break; case 2: m_DataSource.SetSel(0,-1); m_DataSource.ReplaceSel("C:\\superstk.dad"); if(m_ComboFiletype.GetCount()==3) { m_ComboFiletype.DeleteString(1); m_ComboFiletype.DeleteString(1); } break; case 3: m_DataSource.SetSel(0,-1); m_DataSource.ReplaceSel("C:\\HUIJIN"); if(m_ComboFiletype.GetCount()==3) { m_ComboFiletype.DeleteString(1); m_ComboFiletype.DeleteString(1); } break; case 4: m_DataSource.SetSel(0,-1); m_DataSource.ReplaceSel("C:\\SLON"); if(m_ComboFiletype.GetCount()==3) { m_ComboFiletype.DeleteString(1); m_ComboFiletype.DeleteString(1); } break; } } void CImportData::OnSetfocusfwxz() { } void CImportData::OnSetfocus() { } void CImportData::Onqbyr() { GetDlgItem(IDC_INSTALLSTART)->EnableWindow(FALSE); GetDlgItem(IDC_INSTALLEND)->EnableWindow(FALSE); shijianflag=0; } void CImportData::Onsdyr() { GetDlgItem(IDC_INSTALLSTART)->EnableWindow(TRUE); GetDlgItem(IDC_INSTALLEND)->EnableWindow(TRUE); shijianflag=1; } void CImportData::OnSetfocusup() { } void CImportData::OnSetfocusdown() { } void CImportData::Onimport() { BOOL IsChange=FALSE; if( pDoc->m_systemOption.autoday==TRUE ) { pDoc->m_systemOption.autoday=FALSE; IsChange=TRUE; } UpdateData(TRUE); m_Shanghai=FALSE; m_Shenzhen=FALSE; m_nImportorcancel++; if(m_nImportorcancel>1) { GetDlgItem(IDOK)->SetWindowText("导入"); return; } int length=m_stockrange.GetSize(); for (int i=0;i<length;i++) if(m_stockrange.GetAt(i)==TRUE) if(i==0) m_Shanghai=TRUE; else if (i==1) m_Shenzhen=TRUE; if (m_Shanghai==FALSE&&m_Shenzhen==FALSE) { AfxMessageBox("请选择范围! "); m_nImportorcancel=0; return ; } if(m_install_start<=0||m_install_end<=0) { AfxMessageBox("时间设置错误!"); m_nImportorcancel=0; return; } int BeginDate=atoi(m_install_start.Format("%Y%m%d")); int EndDate =atoi(m_install_end.Format("%Y%m%d")); CTime CurrentTime=CTime::GetCurrentTime(); if (shijianflag==1) if(BeginDate > EndDate) { AfxMessageBox("时间颠倒,请重新设置!"); m_nImportorcancel=0; return; } else if(m_install_start>CurrentTime) { AfxMessageBox("开始时间不正确,请重新设置!"); m_nImportorcancel=0; return; } if( ((CComboBox*)GetDlgItem(1011))->GetCurSel()==0 ) { CString srcfilename; switch (m_ComboDatatype.GetCurSel()) { case 0: m_DataSource.GetWindowText(srcfilename); if( srcfilename.IsEmpty() ) { AfxMessageBox("文件名不应为空!"); m_nImportorcancel=0; return; } if(IsFileType(srcfilename)!=0) { AfxMessageBox("非合法日线数据!"); m_nImportorcancel=0; return; } if( srcfilename[0]=='a'||srcfilename[0]=='b'||srcfilename[0]=='A'||srcfilename[0]=='B') { if( !InstallFromFloppyDisk(srcfilename) ) { AfxMessageBox("安装没能正常进行!",MB_ICONASTERISK); m_nImportorcancel=0; return; } srcfilename="c:\\source.day"; } else { srcfilename.MakeLower(); if( srcfilename.Find("tl_disk") != -1 ) { if( ! InstallFromSeveralDiskfile(srcfilename) ) { AfxMessageBox("安装没能正常进行!",MB_ICONASTERISK); m_nImportorcancel=0; return; } srcfilename="c:\\source.day"; } } GetDlgItem(IDOK)->SetWindowText("取消"); InstallWanshen(srcfilename, BeginDate, EndDate); m_nImportorcancel=0; GetDlgItem(IDOK)->SetWindowText("导入"); break; case 1: m_DataSource.GetWindowText(srcfilename); GetDlgItem(IDOK)->SetWindowText("取消"); InstallQianlong(srcfilename, BeginDate, EndDate); m_progress1.SetPos(0); if(m_nImportorcancel==1) m_nImportorcancel=0; GetDlgItem(IDOK)->SetWindowText("导入"); break; case 2: m_DataSource.GetWindowText(srcfilename); GetDlgItem(IDOK)->SetWindowText("取消"); InstallFenxijia(srcfilename, BeginDate, EndDate); m_nImportorcancel=0; GetDlgItem(IDOK)->SetWindowText("导入"); break; case 3: m_DataSource.GetWindowText(srcfilename); GetDlgItem(IDOK)->SetWindowText("取消"); InstallHuijin(srcfilename, BeginDate, EndDate); m_nImportorcancel=0; GetDlgItem(IDOK)->SetWindowText("导入"); break; case 4: m_DataSource.GetWindowText(srcfilename); GetDlgItem(IDOK)->SetWindowText("取消"); InstallShenglong(srcfilename, BeginDate, EndDate); m_nImportorcancel=0; GetDlgItem(IDOK)->SetWindowText("导入"); break; default: AfxMessageBox("没有选择安装数据的类型!"); break; } } else if( ((CComboBox*)GetDlgItem(1011))->GetCurSel()==1 ) { InstallMinteData(); m_nImportorcancel=0; } else { CString SrcFileName; m_DataSource.GetWindowText(SrcFileName); CFileFind finder; if(!finder.FindFile(SrcFileName+"\\*.1mn")) { AfxMessageBox("找不到文件!"); m_nImportorcancel=0; return ; } InstallMin(SrcFileName); m_progress1.SetRange(0,100); m_progress1.SetPos(100); m_progress1.SetPos(0); m_nImportorcancel=0; } if( IsChange ) pDoc->m_systemOption.autoday=FALSE; } void CImportData::OnButtonSearchfixdata() { UpdateData(TRUE); CString filename; if(((CComboBox*)GetDlgItem(1011))->GetCurSel()==2||(m_ComboDatatype.GetCurSel()==1||m_ComboDatatype.GetCurSel()==3||m_ComboDatatype.GetCurSel()==4) &&((CComboBox*)GetDlgItem(1011))->GetCurSel()!=1) { CSBDestination sb(m_hWnd, IDS_BFF_TITLE); sb.SetFlags(BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT); sb.SetInitialSelection(m_news); if (sb.SelectFolder()) { m_news.TrimRight (" "); m_news.TrimRight ("\r\n"); m_news.TrimRight (";"); m_news.TrimRight (" "); CString sNews = sb.GetSelectedFolder(); m_news = sNews; } } else { CString DefExt="*.day"; CString FileName; CString Filter="日线数据(*.day)|*.day||"; if(((CComboBox*)GetDlgItem(1011))->GetCurSel()==0) { FileName=pDoc->m_Directory.CurrentDir; FileName+="StockData.day"; } else if(((CComboBox*)GetDlgItem(1011))->GetCurSel()==1) { FileName=pDoc->m_Directory.CurrentDir; FileName+="StockData.min"; DefExt="*.min"; Filter="5分钟K线数据(*.min)|*.min||"; } int nSel = m_ComboDatatype.GetCurSel(); if(nSel == 2) { FileName=pDoc->m_Directory.CurrentDir; FileName+="StockData.dad"; DefExt="*.dad"; Filter="分析家日线数据(*.dad)|*.dad||"; } CFileDialog bOpenFileDialog(TRUE,(LPCSTR)DefExt, (LPCTSTR)FileName, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_NOCHANGEDIR, (LPCSTR)Filter,this); if(bOpenFileDialog.DoModal()==IDOK) { filename=bOpenFileDialog.GetPathName(); CString fname=bOpenFileDialog.GetFileName(); CString NewFileName=filename; NewFileName.TrimRight(fname); strcpy(pDoc->m_Directory.CurrentDir,NewFileName.GetBuffer(0)); } } if(((CComboBox*)GetDlgItem(1011))->GetCurSel()==2||m_ComboDatatype.GetCurSel()==1||m_ComboDatatype.GetCurSel()==3||m_ComboDatatype.GetCurSel()==4) filename=m_news; m_DataSource.SetSel(0,-1); m_DataSource.ReplaceSel(filename); m_DataSource.GetWindowText(SourceFileName); UpdateData(FALSE); } BOOL CImportData::InstallFromFloppyDisk(CString FloppyFileName,bool bDayKline) { int NumOfDisks=0, nDisk=0; CFile SrcFile; CFile DestFile; CString sExd = ".day"; if(bDayKline==false) sExd = ".min"; if( !DestFile.Open("c:\\source"+sExd,CFile::modeWrite|CFile::modeCreate) ) { AfxMessageBox("打开文件出错!"); return 0; } int IndexOfDisk=1; int nRepeat=0; do { CString str; str.Format("%d",IndexOfDisk); AfxMessageBox("插入第 "+str+" 号磁盘。"); CFileFind finder; BOOL bWorking=finder.FindFile(FloppyFileName.Left(3)+"*.*"); while(bWorking) { bWorking=finder.FindNextFile(); FloppyFileName=finder.GetFilePath(); } if( !SrcFile.Open(FloppyFileName,CFile::modeRead) ) { AfxMessageBox("打开文件出错!"); return 0; } SrcFile.Read(&NumOfDisks,4); SrcFile.Read(&nDisk,4); int LengthOfFile=SrcFile.GetLength(); if( nDisk != IndexOfDisk ) { nRepeat++; AfxMessageBox("重新插入第"+str+"张磁盘。"); SrcFile.Close(); if( nRepeat>5) return 0; continue; } LengthOfFile-=8; BYTE *Buffer=new BYTE[LengthOfFile]; SrcFile.Read(Buffer,LengthOfFile); SrcFile.Close(); DestFile.Write(Buffer,LengthOfFile); delete []Buffer; IndexOfDisk++; nRepeat=0; }while(NumOfDisks>nDisk); DestFile.Close(); return 1; } void CImportData::InstallWanshen(CString srcfilename, int BeginDate, int EndDate) { { BOOL IsSoft=FALSE; CString SourceFilename=srcfilename; m_DataSource.GetWindowText(SourceFilename); if( SourceFilename[0]=='a'||SourceFilename[0]=='b'||SourceFilename[0]=='A'||SourceFilename[0]=='B') { SourceFilename="c:\\source.day"; IsSoft=TRUE; } CString StrName=SourceFilename; StrName.MakeLower(); if( StrName.Find("tl_disk") != -1 ) { SourceFilename="c:\\source.day"; IsSoft=TRUE; } CFile SourceFile; if(!SourceFile.Open(SourceFilename,CFile::modeRead)) { AfxMessageBox("路径中包括错误的路径,请重新设置"); return; } int NumStock=0 ; int FileID; SourceFile.Read(&FileID,4); //if( FileID!=FILEID22) //{ // AfxMessageBox("非"+g_strCompanyName+"日线数据格式!"); // return; //} SourceFile.Read(&NumStock,sizeof(int)); SourceFile.Seek(16,CFile::begin); m_progress1.SetRange(0,NumStock); int NumKline=0; char StockName[8]; Kline wanshen; CTime tm; int wMarketType; for( int nStock=0; nStock<NumStock; nStock++) { MSG message; if( PeekMessage( & message, NULL,0,0,PM_REMOVE) ) { TranslateMessage(&message); DispatchMessage(&message); } if(m_nImportorcancel==2) return; m_progress1.SetPos(nStock); m_InstallArray.RemoveAll(); SourceFile.Read(StockName,8); SourceFile.Read(&wMarketType,sizeof(int)); SourceFile.Read(&NumKline,4); for( int nKline=0; nKline<NumKline; nKline++) { SourceFile.Read( &wanshen,sizeof(Kline) ); m_InstallArray.Add(wanshen); } CString symbol(StockName); if(StockName[0]=='8'&&(StockName[1]=='k'||StockName[1]=='K')) continue; InstallStockKlineEach( symbol,wMarketType, BeginDate, EndDate); } SourceFile.Close(); m_progress1.SetPos(0); if(IsSoft) SourceFile.Remove(SourceFilename); } } int CImportData::InstallFromSeveralDiskfile(CString FileName,bool bDayKline) { int NumOfDisks=0, nDisk=0; CFile SrcFile; CFile DestFile; CString sExd = ".day"; if(bDayKline==false) sExd = ".min"; if( !DestFile.Open("c:\\source"+sExd,CFile::modeWrite|CFile::modeCreate) ) { AfxMessageBox("打开文件出错!"); return 0; } int IndexOfDisk=1; int nRepeat=0; do { CString str; str.Format("%d",IndexOfDisk); if(IndexOfDisk<11) FileName.Delete( FileName.GetLength()-5 ); else FileName.Delete( FileName.GetLength()-6,2 ); FileName.Insert( FileName.GetLength()-4, str ); if( !SrcFile.Open(FileName,CFile::modeRead) ) { AfxMessageBox("打开文件出错!"); return 0; } SrcFile.Read(&NumOfDisks,4); SrcFile.Read(&nDisk,4); int LengthOfFile=SrcFile.GetLength(); if( nDisk != IndexOfDisk ) { SrcFile.Close(); return 0; } LengthOfFile-=8; BYTE *Buffer=new BYTE[LengthOfFile]; SrcFile.Read(Buffer,LengthOfFile); SrcFile.Close(); int nid = *((int*)Buffer); DestFile.Write(Buffer,LengthOfFile); delete []Buffer; IndexOfDisk++; nRepeat=0; }while(NumOfDisks>nDisk); DestFile.Close(); return 1; } void CImportData::InstallStockKlineEach(CString symbol,int wMarketType,int BeginDate,int EndDate,bool bDayKline) { if(symbol == "") return; char symb[10]; strcpy(symb,symbol); DWORD dwKind=CSharesInformation::GetStockKind(wMarketType,symb); if(wMarketType == 0) dwKind = CFormularCompute::GetStockKind(symb); CTaiKlineFileKLine* pFile = CTaiKlineFileKLine::GetFilePointer (symbol,dwKind,bDayKline); CTime tm; int nFixStyle=GetCheckedRadioButton(1013,1014); switch(nFixStyle) { case 1014: { for( int i=0;i<m_InstallArray.GetSize();i++) { tm=m_InstallArray[i].day; if( atoi( tm.Format("%Y%m%d") ) < BeginDate ) { m_InstallArray.RemoveAt(i); i--; } else break; } int nSize=m_InstallArray.GetSize(); while( nSize-- ) { tm=m_InstallArray[nSize].day; if( atoi( tm.Format("%Y%m%d") ) > EndDate ) m_InstallArray.RemoveAt(nSize); else break; } if( m_InstallArray.GetSize() ==0 ) break; } case 1013 : { std::string code(symbol); pFile ->WriteKLine(code,m_InstallArray.GetData(),m_InstallArray.GetSize(),CTaiKlineFileKLine::overWriteAll); } break; } } void CImportData::InstallQianlong(CString srcfilename, int BeginDate, int EndDate) { if (shijianflag==1) if( BeginDate<19700101 ||BeginDate>20380101 || EndDate <19700101 ||EndDate >20380101 || BeginDate > EndDate ) { AfxMessageBox("必须输入正确的时间!",MB_ICONASTERISK); return; } { int NumFile=0; CString FinderName; CFileFind finder; m_DataSource.GetWindowText(FinderName); if(!finder.FindFile(FinderName+"\\*.*")) { AfxMessageBox("打开文件出错,请检查相关设置!"); return; } BOOL bwork = finder.FindFile(FinderName+"\\*.*"); while( bwork ) { bwork=finder.FindNextFile(); NumFile++; } if( !NumFile ) { AfxMessageBox("没有要安装的数据!"); return; } m_progress1.SetRange32(0,NumFile); m_progress1.SetPos(0); Kline Wanshen; CString StockName; CString szTime; CTime tm; BOOL bWorking = finder.FindFile(srcfilename+"\\*.day"); while( bWorking ) { MSG message; if( PeekMessage( & message, NULL,0,0,PM_REMOVE) ) { TranslateMessage(&message); DispatchMessage(&message); } if(m_nImportorcancel==2) return; // m_InstallArray.RemoveAll(); m_progress1.OffsetPos(1); bWorking=finder.FindNextFile(); CString QianlongFileName=finder.GetFilePath(); CFile QianlongFile((LPCTSTR)QianlongFileName,CFile::modeRead); int FileLength=QianlongFile.GetLength(); StockName=finder.GetFileTitle(); if( StockName.GetLength() !=6&&StockName.GetLength() !=4 ) continue; m_InstallArray.RemoveAll(); int numKline=FileLength/40; if( numKline <= 0 ) { QianlongFile.Close(); continue; } QIANLONG* Qianlong=new QIANLONG[numKline]; QianlongFile.Read( Qianlong, sizeof(QIANLONG)*numKline ); QianlongFile.Close(); LONG time; for( int i=0; i < numKline; i++) { if( GetStockTime(Qianlong[i].dwDate,time) && Qianlong[i].dwLow >0 && Qianlong[i].dwVolume >0 ) { Wanshen.day = time; Wanshen.open = (float)(Qianlong[i].dwOpen/1000.0); Wanshen.high = (float)(Qianlong[i].dwHigh/1000.0); Wanshen.low = (float)(Qianlong[i].dwLow/1000.0); Wanshen.close = (float)(Qianlong[i].dwClose/1000.0); Wanshen.vol = (float)(Qianlong[i].dwVolume); Wanshen.amount = (float)(Qianlong[i].dwAmount*1000.0); Wanshen.advance= Qianlong[i].wUp; Wanshen.decline= Qianlong[i].wDown; m_InstallArray.Add(Wanshen); } } delete []Qianlong; StockName.MakeUpper(); InstallStockKlineEach( StockName, 0,BeginDate, EndDate); } m_progress1.SetPos(0); } } BOOL CImportData::GetStockTime(int ymd, LONG& tm) { if( ymd<20380101 && ymd > 19901201 ) { CTime time( ymd/10000, (ymd%10000)/100, ymd%100, 9, 30, 0); tm=time.GetTime(); return 1; } else return 0; } void CImportData::InstallFenxijia(CString srcfilename ,int BeginDate, int EndDate) { CFile SourceFile; if(IsFileType(srcfilename)!=3) { AfxMessageBox("不是分析家日线数据文件格式!"); return; } if(!SourceFile.Open(srcfilename,CStkFile::modeRead)) { AfxMessageBox("打开文件出错,请检查相关设置!"); return; } int NumStock=0; int Flag1; SourceFile.Read(&Flag1,4); if(Flag1!=872159628) { AfxMessageBox("不是分析家日线数据文件格式!"); return; } SourceFile.Seek(8,CFile::begin); SourceFile.Read(&NumStock,sizeof(int)); int NumKlinesOfFxj = (SourceFile.GetLength()-16)/32; if( NumKlinesOfFxj<0 ) return; SourceFile.Seek(16,CFile::begin); Kline *tianlong=new Kline[NumKlinesOfFxj]; SourceFile.Read(tianlong,32*NumKlinesOfFxj); m_progress1.SetRange32(0,NumStock); CTime tm; tm=CTime::GetCurrentTime(); int CurrentDate=atoi(tm.Format("%Y%m%d")); int nFixStyle=GetCheckedRadioButton(IDC_RADIO_COVER,IDC_RADIO_INSTALLDATE); {// CString StockSymbol,PreStockSymbol; for( int i=0;i<NumKlinesOfFxj;i++) { if( tianlong[i].day == -1 ) { m_progress1.OffsetPos(1); MSG message; if( PeekMessage( & message, NULL,0,0,PM_REMOVE) ) { TranslateMessage(&message); DispatchMessage(&message); } if(m_nImportorcancel==2) { SourceFile.Close(); delete []tianlong; return; } StockSymbol=(char*)&tianlong[i]+6; if(StockSymbol.GetLength () == 6||StockSymbol.GetLength () == 4) { InstallStockKlineEach( PreStockSymbol,0, BeginDate, EndDate); m_InstallArray.RemoveAll(); } PreStockSymbol=StockSymbol; } else { tm=tianlong[i].day; if( tm>0 && atoi(tm.Format("%Y%m%d")) <=CurrentDate ) m_InstallArray.Add(tianlong[i]); } } } delete []tianlong; m_progress1.SetPos(0); SourceFile.Close(); } void CImportData::InstallHuijin(CString srcfilename, int BeginDate, int EndDate) { if (shijianflag==1) { if( BeginDate<19700101 ||BeginDate>20380101|| EndDate <19700101 ||EndDate>20380101 ) { AfxMessageBox("必须输入正确的时间!"); return; } if( BeginDate>EndDate) { AfxMessageBox("输入时间非法!",MB_ICONASTERISK); return; } } { int NumFile=0; CString FinderName; CFileFind finder; m_DataSource.GetWindowText(FinderName); if(!finder.FindFile(FinderName+"\\*.*")) { AfxMessageBox("打开文件出错,请检查相关设置!"); return; } BOOL bwork = finder.FindFile(FinderName+"\\*.*"); while( bwork ) { bwork=finder.FindNextFile(); NumFile++; } if( !NumFile ) { AfxMessageBox("没有要安装的数据!"); return; } m_progress1.SetRange32(0,NumFile); Kline Tianlong; CString StockName; CString szTime; CTime tm; BOOL bWorking = finder.FindFile(srcfilename+"\\*.*"); while( bWorking ) { MSG message; if( PeekMessage( & message, NULL,0,0,PM_REMOVE) ) { TranslateMessage(&message); DispatchMessage(&message); } if(m_nImportorcancel==2) return; // m_InstallArray.RemoveAll(); m_progress1.OffsetPos(1); bWorking=finder.FindNextFile(); CString HuijinFileName=finder.GetFilePath(); CFile HuijinFile(HuijinFileName,CFile::modeRead); int FileLength=HuijinFile.GetLength(); StockName=finder.GetFileTitle(); if( StockName.GetLength()!=8 && StockName.GetLength()!=6) continue; //if not shanghai , then return. StockName=StockName.Right(StockName.GetLength()-2); m_InstallArray.RemoveAll(); int numKline=FileLength/29; if( numKline<=0 ) { HuijinFile.Close(); continue; } HUIJIN hj; HUIJIN* huijin=new HUIJIN[numKline]; for( int j=0; j < numKline; j++) { HuijinFile.Read( &hj, 29 ); huijin[j]=hj; } HuijinFile.Close(); LONG time; for( int i=0; i < numKline; i++) { if( GetStockTime(huijin[i].nDate,time) ) { Tianlong.day = time; Tianlong.open = huijin[i].fOpen; Tianlong.high = huijin[i].fHigh; Tianlong.low = huijin[i].fLow; Tianlong.close = huijin[i].fClose; Tianlong.vol = (float)huijin[i].nVolume; Tianlong.amount = (float)(huijin[i].nVolume*huijin[i].fMean*100.0); Tianlong.advance= 0; Tianlong.decline= 0; m_InstallArray.Add(Tianlong); } } delete []huijin; // if(m_InstallArray.GetSize()==0) continue; InstallStockKlineEach( StockName,0, BeginDate, EndDate); } } m_progress1.SetPos(0); } void CImportData::InstallShenglong(CString srcfilename, int BeginDate, int EndDate) { if (shijianflag==1) if( BeginDate<19700101 ||BeginDate>20380101|| EndDate <19700101 ||EndDate >20380101|| BeginDate>EndDate ) { AfxMessageBox("非法输入!重新输入正确的时间!"); return; } { int NumFile=0; CString FinderName; CFileFind finder; m_DataSource.GetWindowText(FinderName); if(!finder.FindFile(FinderName+"\\*.day")) { AfxMessageBox("打开文件出错,请检查相关设置!"); return; } BOOL bwork = finder.FindFile(FinderName+"\\*.day"); while( bwork ) { bwork=finder.FindNextFile(); NumFile++; } if( !NumFile ) { AfxMessageBox("没有要安装的数据!"); return; } m_progress1.SetRange32(0,NumFile); m_progress1.SetPos(0); CString StockName, /*股票代码*/ szTime; CTime tm; BOOL bWorking = finder.FindFile(srcfilename+"\\*.day"); while( bWorking ) { MSG message; if( PeekMessage( & message, NULL,0,0,PM_REMOVE) ) { TranslateMessage(&message); DispatchMessage(&message); } if(m_nImportorcancel==2) return; m_InstallArray.RemoveAll(); m_progress1.OffsetPos(1); bWorking=finder.FindNextFile(); CString ShenglongFileName=finder.GetFilePath(); CFile ShenglongFile(ShenglongFileName,CFile::modeRead); int FileLength=ShenglongFile.GetLength(); StockName=finder.GetFileTitle(); if( StockName.GetLength() != 6&&StockName.GetLength() != 4 ) continue; int NumShenglong=FileLength/sizeof(SHENGLONG); if( NumShenglong <= 0 ) { ShenglongFile.Close(); continue; } SHENGLONG* SLarray=new SHENGLONG[NumShenglong]; ShenglongFile.Read( SLarray, sizeof(SHENGLONG)*NumShenglong ); ShenglongFile.Close(); Kline wsh; for( int i=0; i < NumShenglong; i++) { if( ShenglongToTianlong(SLarray[i],wsh) ) m_InstallArray.Add(wsh); } delete []SLarray; if( m_InstallArray.GetSize()==0 ) continue; InstallStockKlineEach( StockName,0, BeginDate, EndDate); } } m_progress1.SetPos(0); } BOOL CImportData::ShenglongToTianlong(SHENGLONG shenglong,Kline& Wanshen) { shenglong.date=~shenglong.date; shenglong.oprice=~shenglong.oprice; shenglong.cprice=~shenglong.cprice; shenglong.hprice=~shenglong.hprice; shenglong.lprice=~shenglong.lprice; shenglong.tovalue=~shenglong.tovalue; shenglong.tohands=~shenglong.tohands; shenglong.topiece=~shenglong.topiece; LONG tm; if( GetStockTime(shenglong.date,tm) ) { Wanshen.day = tm; Wanshen.open = float(shenglong.oprice/1000.0); Wanshen.high = float(shenglong.hprice/1000.0); Wanshen.low = float(shenglong.lprice/1000.0); Wanshen.close = float(shenglong.cprice/1000.0); Wanshen.vol = float(shenglong.tohands); Wanshen.amount = float(shenglong.tovalue*1000.0); Wanshen.advance= 0; Wanshen.decline= 0; return 1; } return 0; } void CImportData::InstallMinteData() { CString SourceFilename,srcfilename; m_DataSource.GetWindowText(SourceFilename); srcfilename = SourceFilename; BOOL IsSoft=FALSE; if(IsFileType(srcfilename)!=1) { AfxMessageBox("非合法五分钟数据!"); return; } if( srcfilename.Mid(0,3)=="a:\\"||srcfilename.Mid(0,3)=="b:\\"||srcfilename.Mid(0,3)=="A:\\"||srcfilename.Mid(0,3)=="B:\\") { if( !InstallFromFloppyDisk(srcfilename,false) ) { AfxMessageBox("安装没能正常进行!",MB_ICONASTERISK); return; } IsSoft=TRUE; srcfilename="c:\\source.min"; } else { srcfilename.MakeLower(); if( srcfilename.Find("tl_disk") != -1 ) { if( ! InstallFromSeveralDiskfile(srcfilename,false) ) { AfxMessageBox("安装没能正常进行!",MB_ICONASTERISK); return; } IsSoft=TRUE; srcfilename="c:\\source.min"; } } UpdateData(TRUE); CFile SourceFile; if(!SourceFile.Open(srcfilename,CFile::modeRead)) { AfxMessageBox("路径中包括错误的路径,请重新设置!"); return; } int NumStock=0 ; int FileID; SourceFile.Read(&FileID,4); //if( FileID!=FILEID22) //{ // AfxMessageBox("非"+g_strCompanyName+"五分钟数据格式!"); // return; //} SourceFile.Read(&NumStock,sizeof(int)); m_progress1.SetRange32(0,NumStock); int NumKline=0; char StockName[8]; Kline wanshen; CTime tm; // add begin46 int wMarketType; // add end46 for( int nStock=0; nStock<NumStock; nStock++) { MSG message; if( PeekMessage( & message, NULL,0,0,PM_REMOVE) ) { TranslateMessage(&message); DispatchMessage(&message); } m_progress1.SetPos(nStock); m_InstallArray.RemoveAll(); SourceFile.Read(StockName,7); // add begin46 SourceFile.Read(&wMarketType,sizeof(int)); // add end46 SourceFile.Read(&NumKline,4); SourceFile.Seek(8,CFile::current); for( int nKline=0; nKline<NumKline*48; nKline++) { SourceFile.Read( &wanshen,sizeof(Kline) ); m_InstallArray.Add(wanshen); } if(NumKline<=0) continue; CString symbol(StockName); if(StockName[0]=='8'&&(StockName[1]=='k'||StockName[1]=='K')) continue; CTime tm(m_InstallArray[0].day); int BeginDate = atoi(tm.Format ("%Y%m%d")); tm = (m_InstallArray[m_InstallArray.GetSize()-1].day); int EndDate = atoi(tm.Format ("%Y%m%d")); InstallStockKlineEach( symbol,wMarketType ,BeginDate, EndDate,false); } SourceFile.Close(); if(IsSoft==TRUE) SourceFile.Remove(srcfilename); m_progress1.SetPos(0); } void CImportData::InstallMin(CString lpStockSymbol) { CFileFind finder; BOOL bWorking; CString StockOpenPath; if(!(bWorking=finder.FindFile(lpStockSymbol+"\\*.1mn"))) { AfxMessageBox(" 不存在分时数据文件!"); return ; } int NumFile=0; while(bWorking) { bWorking=finder.FindNextFile(); NumFile++; } if( !NumFile ) { AfxMessageBox("没有要安装的数据!"); return; } bWorking=finder.FindFile(lpStockSymbol+"\\*.1mn"); // m_progress1.SetRange(0,NumFile); m_progress1.SetPos(0); while(bWorking) { bWorking=finder.FindNextFile(); StockOpenPath=finder.GetFilePath(); CString Stocklen=finder.GetFileTitle(); InstallOneMinStock(StockOpenPath); m_progress1.OffsetPos(1); } } void CImportData::InstallOneMinStock(CString FilePath) { CFile StockFile; CReportData* pcdat1; CdatOld pcdat2; if(!StockFile.Open(FilePath,CFile::modeRead|CFile::shareDenyNone)) { return; } StockFile.Read(&pcdat2,sizeof(CdatOld)); StockFile.Close(); if( ! CMainFrame::m_taiShanDoc->m_sharesInformation.Lookup(pcdat2.id, pcdat1,pcdat2.kind) ) return; pcdat1->lastclmin=239; pcdat1->rdp=pcdat2.rdp; strcpy(pcdat1->id,pcdat2.id); // add begin46 pcdat1->kind=pcdat2.kind; // add end46 strcpy(pcdat1->name,pcdat2.name); strcpy(pcdat1->Gppyjc,pcdat2.Gppyjc); // pcdat1->ystc=pcdat2.ystc; pcdat1->opnp=pcdat2.opnp; pcdat1->higp=pcdat2.higp; pcdat1->lowp=pcdat2.lowp; pcdat1->nowp=pcdat2.nowp; pcdat1->nowv=pcdat2.nowv; pcdat1->totv=pcdat2.totv; pcdat1->totp=pcdat2.totp; pcdat1->pbuy1=pcdat2.pbuy1; pcdat1->vbuy1=pcdat2.vbuy1; pcdat1->pbuy2=pcdat2.pbuy2; pcdat1->vbuy2=pcdat2.vbuy2; pcdat1->pbuy3=pcdat2.pbuy3; pcdat1->vbuy3=pcdat2.vbuy3; pcdat1->psel1=pcdat2.psel1; pcdat1->vsel1=pcdat2.vsel1; pcdat1->psel2=pcdat2.psel2; pcdat1->vsel2=pcdat2.vsel2; pcdat1->psel3=pcdat2.psel3; pcdat1->vsel3=pcdat2.vsel3; pcdat1->accb=pcdat2.accb; pcdat1->accs=pcdat2.accs; pcdat1->volume5=pcdat2.volume5; pcdat1->rvol=pcdat2.rvol; pcdat1->dvol=pcdat2.dvol; pcdat1->lastclmin=pcdat2.lastclmin; pcdat1->initdown=pcdat2.initdown; pcdat1->InOut=pcdat2.InOut; for(int i=0;i<240;i++) { pcdat1->m_Kdata1[i].Price=pcdat2.m_Kdata[i].Price; pcdat1->m_Kdata1[i].Amount=pcdat2.m_Kdata[i].Amount; pcdat1->m_Kdata1[i].Volume=pcdat2.m_Kdata[i].Volume; } } int CImportData::IsFileType(CString Filename) { Filename.TrimRight(" "); if(Filename.Right(4)==".day"||Filename.Right(4)==".DAY") return 0; else if(Filename.Right(4)==".min"||Filename.Right(4)==".min") return 1; else if(Filename.Right(4)==".1mn"||Filename.Right(4)==".1MN") return 2; else if(Filename.Right(4)==".dad"||Filename.Right(4)==".DAD") return 3; else return 4; } void CImportData::OnClickList(NMHDR* pNMHDR, LRESULT* pResult) { int ItemIndex=m_listfw.GetNextItem(-1,LVNI_SELECTED); if (ItemIndex==-1) return; LVITEM myitem; myitem.mask=LVIF_TEXT|LVIF_IMAGE; myitem.iSubItem=0; if(m_stockrange.GetAt(ItemIndex)==TRUE) { myitem.iImage=9; m_stockrange.SetAt(ItemIndex,FALSE); } else { myitem.iImage=6; m_stockrange.SetAt(ItemIndex,TRUE); } CString stockgroup[]={"上海","深圳","创业"}; myitem.iItem=ItemIndex; myitem.pszText=(LPTSTR)stockgroup[ItemIndex].GetBuffer(stockgroup[ItemIndex].GetLength()); // m_listfw.SetItem(&myitem); m_listfw.Update(ItemIndex); *pResult = 0; } BOOL CImportData::OnHelpInfo(HELPINFO* pHelpInfo) { DoHtmlHelp(this);return TRUE; }
[ [ [ 1, 1576 ] ] ]
41cece89d854803951e19fbc68decdc6c2d372fe
9fb229975cc6bd01eb38c3e96849d0c36985fa1e
/Tools/MergeCar/MergeCar.cpp
7ddba0010eb60aa2580e95a2d1ebbca131b74b64
[]
no_license
Danewalker/ahr
3758bf3219f407ed813c2bbed5d1d86291b9237d
2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6
refs/heads/master
2016-09-13T08:03:43.040624
2010-07-21T15:44:41
2010-07-21T15:44:41
56,323,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
// MergeCar.cpp : Defines the entry point for the console application. // #pragma warning (disable:4786) #include "stdafx.h" #include "stdio.h" #include "TgaReader.h" #include "TgaWriter.h" #include "ImageProcess.h" #include "Surface.h" #include "windows.h" #include "CarExporter.h" int main(int argc, char* argv[]) { std::string name; std::string inPath; std::string outPath; std::string inFile; std::string outFile; if(argc<2){ printf("Usage: MergeCar <car name> [input path [output path]]\n"); return 1; }else{ if(argc>=2){ name=argv[1]; } if(argc>=3){ inPath=argv[2]; }else{ char str [1024]; ::GetCurrentDirectory(1024,str); inPath=str; } if(argc>=4){ outPath=argv[3]; }else{ outPath=inPath; } } inFile=name+".txt"; outFile=name+".car"; CCarExporter exporter(inPath, outPath); exporter.Export(inFile, outFile); return 0; } /* class CLayer { virtual void Apply(CSurface& surface); }; class CLayerSet : public CLayer { public: virtual void Apply(CSurface& surface); protected: vector<CLayer*> m_Layers; }; class CNormalLayer : public CLayer { public: virtual void Apply(CSurface& surface); protected: string m_File; }; class CMaskLayer : public CLayer { public: virtual void Apply(CSurface& surface); protected: string m_File; int m_Color1; int m_Color2; }; class COverlayLayer : public CLayer { public: virtual void Apply(CSurface& surface); protected: string m_File; }; class CBackgroundLayer : public CLayer { public: virtual void Apply(CSurface& surface); protected: int m_Color1; int m_Color2; }; */
[ "jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae" ]
[ [ [ 1, 115 ] ] ]
7491dd2befad9f76a6233488c58e406e53ac5416
da48afcbd478f79d70767170da625b5f206baf9a
/tbmessage/websend/src3/EditUserDlg.h
a307848fb3eaa55e1011c6cd3b3a0b0c04fe33b3
[]
no_license
haokeyy/fahister
5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04
c71dc56a30b862cc4199126d78f928fce11b12e5
refs/heads/master
2021-01-10T19:09:22.227340
2010-05-06T13:17:35
2010-05-06T13:17:35
null
0
0
null
null
null
null
GB18030
C++
false
false
636
h
#pragma once #include "explorer_ocx.h" // CEditUserDlg 对话框 class CEditUserDlg : public CDialog { DECLARE_DYNAMIC(CEditUserDlg) public: CEditUserDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CEditUserDlg(); virtual BOOL OnInitDialog(); // 对话框数据 enum { IDD = IDD_DLG_EDIT_USER }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 CString szUuid; DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); afx_msg void OnTimer(UINT_PTR nIDEvent); CExplorerOcx m_expChkCode; afx_msg void OnBnClickedButton1(); };
[ "[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395" ]
[ [ [ 1, 30 ] ] ]
d69a8db61517d1901d9b597c72d9d94962dea98b
3daaefb69e57941b3dee2a616f62121a3939455a
/_package_test/test/StdAfx.cpp
627e8de2343bccdf05b1fc60fa7a64bf97513e7b
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
447
cpp
// stdafx.cpp : 標準インクルードファイルを含むソース ファイル // test.pch 生成されるプリコンパイル済ヘッダー // stdafx.obj 生成されるプリコンパイル済タイプ情報 //#define DWORD_PTR DWORD* #include "stdafx.h" // TODO: STDAFX.H に含まれていて、このファイルに記述されていない // ヘッダーファイルを追加してください。
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 9 ] ] ]
7fc115ab4a927c6e37e9711ed26ed77850b5acd2
37c757f24b674f67edd87b75b996d8d5015455cb
/Server/sources/listenThread.cpp
de5999efd59b7fa5b607ad2897e45f348f8436ce
[]
no_license
SakuraSinojun/cotalking
1118602313f85d1c49d73e1603cf6642bc15f36d
37354d99db6b7033019fd0aaccec84e68aee2adf
refs/heads/master
2021-01-10T21:20:50.269547
2011-04-07T06:15:04
2011-04-07T06:15:04
32,323,167
0
0
null
null
null
null
UTF-8
C++
false
false
2,416
cpp
#include <pthread.h> #include <memory.h> #include "../include/listenThread.h" TS_ListenThread::TS_ListenThread() { sockfd = 0; epfd = 0; mngSock = NULL; } TS_ListenThread::~TS_ListenThread() { if (sockfd) close(sockfd); if (epfd) close(epfd); } bool TS_ListenThread::setNonBlock(int sockfd) { if (sockfd < 1) return false; int opts = fcntl(sockfd, F_GETFL); if (opts == -1) return false; opts = opts | O_NONBLOCK; if (fcntl(sockfd, F_SETFL, opts) < 0) return false; return true; } int TS_ListenThread::init(int nport, void *mng) { if (nport < 10 || mng == NULL) return -1; mngSock = (TS_MngSock *)mng; sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd == -1) return -11; struct sockaddr_in serAddr; bzero(&serAddr, sizeof(struct sockaddr)); serAddr.sin_family = AF_INET; serAddr.sin_port = htons(nport); serAddr.sin_addr.s_addr = INADDR_ANY; int nRet = bind(sockfd, (sockaddr *)&serAddr, sizeof(sockaddr)); if (nRet == -1) { perror("bind"); return -12; } printf("bind at TCP port %d\n", nport); nRet = listen(sockfd, 128); if (nRet == -1) return -13; // epoll epfd = epoll_create(256); if (epfd == -1) return -21; struct epoll_event ev; bzero(&ev, sizeof(ev)); ev.data.fd = sockfd; ev.events = EPOLLIN | EPOLLET; nRet = epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &ev); if (nRet == -1) return false; return true; } void TS_ListenThread::run() { struct sockaddr_in addr; socklen_t len; if (epfd == 0) return; int ndfs, intLoop, acptSock; struct epoll_event events[10]; while (isRunning) { ndfs = epoll_wait(epfd, events, 10, 500); //actually.just one socket; ndfs == 1; for (intLoop = 0; intLoop < ndfs; intLoop ++) { if (events[intLoop].data.fd != sockfd) //why? impossible! continue; len = sizeof(addr); acptSock = accept(sockfd , (struct sockaddr *)&addr, &len); if(acptSock == -1) { continue; } printf("%s:%d connected.\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); if (mngSock != NULL) mngSock->allocateSock(acptSock); } } }
[ "SakuraSinojun@02eed91f-dd82-7cf9-bfd0-73567c4360d3" ]
[ [ [ 1, 114 ] ] ]
6e1a4c8a9ad8c2848bee300a955dbe3c6695641d
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_Editor/fusionforever_editor.cpp
96b497f05c6defe45b0fe4e72a7121fbd781b80f
[]
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,743
cpp
#include "fusionforever_editor.h" #include <qtimer.h> #include <SectionTypes.h> #include <SectionMetadata.h> #include "SectionButton.h" #include "SectionPopup.h" #include "ToolboxPopup.h" #include <set> #include <QFileDialog> #include "ScenarioDialog.h" #include <stdlib.h> #include <fstream> #include <QCoreApplication> FusionForever_Editor::FusionForever_Editor(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { ui.setupUi(this); scenario_dialog_ = new ScenarioDialog(this); scenario_dialog_->setModal(true); QTimer* timer = new QTimer(this); timer->setInterval(25); QObject::connect(timer, SIGNAL(timeout()), ui.fusionForeverWidget, SLOT(Tick())); timer->start(); QList<QAction*> popup_actions; popup_actions.push_back(ui.actionDelete_selection); popup_actions.push_back(ui.actionRemove); selection_menu_ = new SectionPopup(this, popup_actions); toolbox_menu_ = new ToolboxPopup(this, ui.actionReplace, ui.actionAdd_as_parent, ui.actionAdd_as_child); QObject::connect(ui.fusionForeverWidget, SIGNAL(selectionChanged(Section*, std::vector<Section*>)), selection_menu_, SLOT(selectionChanged(Section*, std::vector<Section*>))); QObject::connect(ui.fusionForeverWidget, SIGNAL(selectionChanged(Section*)), ui.propertiesList, SLOT(selectionChanged(Section*))); QObject::connect(ui.fusionForeverWidget, SIGNAL(selectionChanged(Section*)), toolbox_menu_, SLOT(selectionChanged(Section*))); QObject::connect(ui.fusionForeverWidget, SIGNAL(rightClick()), selection_menu_, SLOT(show_popup())); QObject::connect(ui.fusionForeverWidget, SIGNAL(initialisedSections(std::vector<std::pair<std::string, QPixmap*> >, std::vector<std::pair<std::string, QPixmap*> >)), this, SLOT(reloadSectionList(std::vector<std::pair<std::string, QPixmap*> >, std::vector<std::pair<std::string, QPixmap*> >))); QObject::connect(ui.fusionForeverWidget, SIGNAL(initialisedSections(std::vector<std::pair<std::string, QPixmap*> >, std::vector<std::pair<std::string, QPixmap*> >)), ui.propertiesList, SLOT(receiveSectionPixmaps(std::vector<std::pair<std::string, QPixmap*> >, std::vector<std::pair<std::string, QPixmap*> >))); QObject::connect(selection_menu_, SIGNAL(select_item(int)), ui.fusionForeverWidget, SLOT(SelectSection(int))); QObject::connect(toolbox_menu_, SIGNAL(sigInsert_after(std::string)), ui.fusionForeverWidget, SLOT(AddSection(std::string))); QObject::connect(toolbox_menu_, SIGNAL(sigInsert_before(std::string)), ui.fusionForeverWidget, SLOT(InsertSection(std::string))); QObject::connect(toolbox_menu_, SIGNAL(sigReplace(std::string)), ui.fusionForeverWidget, SLOT(ReplaceSection(std::string))); QObject::connect(ui.actionDelete_selection, SIGNAL(triggered()), ui.fusionForeverWidget, SLOT(DeleteSelection())); QObject::connect(ui.actionRemove, SIGNAL(triggered()), ui.fusionForeverWidget, SLOT(RemoveSelection())); QObject::connect(ui.actionSet_snap_to_0_5, SIGNAL(triggered()), this, SLOT(setGridSize0_5())); QObject::connect(ui.actionSet_snap_to_1, SIGNAL(triggered()), this, SLOT(setGridSize1())); QObject::connect(ui.actionSet_snap_to_2_5, SIGNAL(triggered()), this, SLOT(setGridSize2_5())); QObject::connect(ui.actionIncrease_snap, SIGNAL(triggered()), ui.fusionForeverWidget, SLOT(IncreaseGridSize())); QObject::connect(ui.actionDecrease_snap, SIGNAL(triggered()), ui.fusionForeverWidget, SLOT(DecreaseGridSize())); QObject::connect(ui.actionCut, SIGNAL(triggered()), ui.fusionForeverWidget, SLOT(CutSection())); QObject::connect(ui.actionPaste, SIGNAL(triggered()), ui.fusionForeverWidget, SLOT(PasteSection())); QObject::connect(ui.actionSave, SIGNAL(triggered()), this, SLOT(saveShip())); QObject::connect(ui.actionSave_As, SIGNAL(triggered()), this, SLOT(saveShipAs())); QObject::connect(ui.actionNew, SIGNAL(triggered()), this, SLOT(newShip())); QObject::connect(ui.actionOpen, SIGNAL(triggered()), this, SLOT(openShip())); QObject::connect(ui.actionConfigure, SIGNAL(triggered()), scenario_dialog_, SLOT(showDialog())); QObject::connect(ui.actionTry, SIGNAL(triggered()), this, SLOT(tryShip())); QObject::connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(exitEditor())); } FusionForever_Editor::~FusionForever_Editor() { } void FusionForever_Editor::reloadSectionList(std::vector<std::pair<std::string, QPixmap*> > _icons, std::vector<std::pair<std::string, QPixmap*> > _core_icons) { std::set<std::string> tag_list; std::map<std::string, std::vector<std::pair<std::string, QPixmap*> > > tag_entries; /* Build Core list */ for(std::vector<std::pair<std::string, QPixmap*> >::iterator it = _core_icons.begin(); it != _core_icons.end(); ++it) { SectionButton* itemButton = new SectionButton(ui.pageCores, it->first.c_str(), it->first.c_str(), *it->second); ui.gridLayoutCores->addWidget(itemButton); QObject::connect(itemButton, SIGNAL(sectionClicked(std::string)), ui.fusionForeverWidget, SLOT(ReplaceCore(std::string))); } /* Build section list, and compile tags */ for(std::vector<std::pair<std::string, QPixmap*> >::iterator it = _icons.begin(); it != _icons.end(); ++it) { SectionButton* itemButton = new SectionButton(ui.pageAll, it->first.c_str(), it->first.c_str(), *it->second); ui.gridLayoutAll->addWidget(itemButton); QObject::connect(itemButton, SIGNAL(sectionClicked(std::string)), ui.fusionForeverWidget, SLOT(AddSection(std::string))); QObject::connect(itemButton, SIGNAL(sectionRightClick(std::string)), toolbox_menu_, SLOT(show_popup(std::string))); std::vector<std::string> tags = SectionMetadata::GetTags(it->first); for(std::vector<std::string>::iterator tag = tags.begin(); tag != tags.end(); ++tag) { tag_list.insert(*tag); tag_entries[*tag].push_back(*it); } } /* Build tag list */ for(std::set<std::string>::iterator it = tag_list.begin(); it != tag_list.end(); ++it) { QWidget* toolbox_page = new QWidget(); QVBoxLayout* toolbox_page_layout = new QVBoxLayout(toolbox_page); toolbox_page_layout->setSpacing(3); toolbox_page_layout->setMargin(0); ui.toolBoxSections->addItem(toolbox_page, it->c_str()); for(std::vector<std::pair<std::string, QPixmap*> >::iterator it2 = tag_entries[*it].begin(); it2 != tag_entries[*it].end(); ++it2) { QPushButton* itemButton = new SectionButton(toolbox_page, it2->first.c_str(), it2->first.c_str(), *it2->second); toolbox_page_layout->addWidget(itemButton); QObject::connect(itemButton, SIGNAL(sectionClicked(std::string)), ui.fusionForeverWidget, SLOT(AddSection(std::string))); QObject::connect(itemButton, SIGNAL(sectionRightClick(std::string)), toolbox_menu_, SLOT(show_popup(std::string))); } QSpacerItem* spacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); toolbox_page_layout->addItem(spacer); } } /* Action handlers */ void FusionForever_Editor::saveShip() { if(filename_.length() == 0) { QString filename = QFileDialog::getSaveFileName(this, "Save Ship", "./Scripts/Ships/", "XMLShip format (*.xmlShip)"); if(filename.length() != 0) { filename_ = filename.toStdString(); ui.fusionForeverWidget->Save(filename_); } } else { ui.fusionForeverWidget->Save(filename_); } } void FusionForever_Editor::saveShipAs() { QString filename = QFileDialog::getSaveFileName(this, "Save Ship", "./Scripts/Ships/", "XMLShip format (*.xmlShip)"); if(filename.length() != 0) { filename_ = filename.toStdString(); ui.fusionForeverWidget->Save(filename_); } } void FusionForever_Editor::newShip() { ui.fusionForeverWidget->New(); filename_ = ""; } void FusionForever_Editor::openShip() { QString filename = QFileDialog::getOpenFileName(this, "Save Ship", "./Scripts/Ships/", "XMLShip format (*.xmlShip)"); filename_ = filename.toStdString(); if(filename_.length() > 0) ui.fusionForeverWidget->Open(filename_); } void FusionForever_Editor::tryShip() { ui.fusionForeverWidget->Save("Scripts/Ships/EditorTemp.xmlShip"); std::ofstream challenge = std::ofstream("Scripts/Challenges/EditorTemp.luaChallenge"); challenge << scenario_dialog_->GetScenarioString(); challenge.close(); std::string launch_cmd = "FusionForever_bin.exe -s Scripts/Challenges/EditorTemp.luaChallenge"; system(launch_cmd.c_str()); } void FusionForever_Editor::setGridSize0_5() { ui.fusionForeverWidget->SetGridSize(0.5f); } void FusionForever_Editor::setGridSize1() { ui.fusionForeverWidget->SetGridSize(1.0f); } void FusionForever_Editor::setGridSize2_5() { ui.fusionForeverWidget->SetGridSize(2.5f); } void FusionForever_Editor::exitEditor() { QCoreApplication::exit(0); }
[ [ [ 1, 201 ] ] ]
008a70fa913836ff17b28a5fec3cddd443abec0f
5e710ea036da9a0817e99b74dd1530756fada273
/lukas-kanade-openmp-sse2/Codigo/cv/src/cvlkpyramid_paa_omp.cpp
fcbeddf68b1ca53f7110942bece3e011c26cf035
[]
no_license
pabloinigoblasco/lukas-kanade-openmp-sse2
7ff3722087bbc51ba98ef349e5ef4f25c09a0e19
634be1442dc9784880a088f325c0122b1f909fbe
refs/heads/master
2016-09-06T18:50:52.799641
2009-02-03T17:19:41
2009-02-03T17:19:41
40,632,484
0
1
null
null
null
null
UTF-8
C++
false
false
33,923
cpp
/*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. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, 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 materials provided with the distribution. // // * The name of Intel Corporation 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*/ #include "_cv.h" #include <float.h> #include <stdio.h> //For testing purposses we define this here #ifndef MINGW //#define EN_ASM_1 //#define EN_ASM_2 //#define EN_ASM_3 //#define EN_ASM_4 #endif //#ifdef _OPENMP static void intersect_paa( CvPoint2D32f pt, CvSize win_size, CvSize imgSize, CvPoint* min_pt, CvPoint* max_pt ) { CvPoint ipt; ipt.x = cvFloor( pt.x ); ipt.y = cvFloor( pt.y ); ipt.x -= win_size.width; ipt.y -= win_size.height; win_size.width = win_size.width * 2 + 1; win_size.height = win_size.height * 2 + 1; min_pt->x = MAX( 0, -ipt.x ); min_pt->y = MAX( 0, -ipt.y ); max_pt->x = MIN( win_size.width, imgSize.width - ipt.x ); max_pt->y = MIN( win_size.height, imgSize.height - ipt.y ); } static int icvMinimalPyramidSize_paa( CvSize imgSize ) { return cvAlign(imgSize.width,8) * imgSize.height / 3; } static void icvInitPyramidalAlgorithm_paa( const CvMat* imgA, const CvMat* imgB, CvMat* pyrA, CvMat* pyrB, int level, CvTermCriteria * criteria, int max_iters, int flags, uchar *** imgI, uchar *** imgJ, int **step, CvSize** size, double **scale, uchar ** buffer ) { CV_FUNCNAME( "icvInitPyramidalAlgorithm_paa" ); __BEGIN__; const int ALIGN = 8; int pyrBytes, bufferBytes = 0, elem_size; int level1 = level + 1; int i; CvSize imgSize, levelSize; *buffer = 0; *imgI = *imgJ = 0; *step = 0; *scale = 0; *size = 0; /* check input arguments */ if( ((flags & CV_LKFLOW_PYR_A_READY) != 0 && !pyrA) || ((flags & CV_LKFLOW_PYR_B_READY) != 0 && !pyrB) ) CV_ERROR( CV_StsNullPtr, "Some of the precomputed pyramids are missing" ); if( level < 0 ) CV_ERROR( CV_StsOutOfRange, "The number of pyramid layers is negative" ); switch( criteria->type ) { case CV_TERMCRIT_ITER: criteria->epsilon = 0.f; break; case CV_TERMCRIT_EPS: criteria->max_iter = max_iters; break; case CV_TERMCRIT_ITER | CV_TERMCRIT_EPS: break; default: assert( 0 ); CV_ERROR( CV_StsBadArg, "Invalid termination criteria" ); } /* compare squared values */ criteria->epsilon *= criteria->epsilon; /* set pointers and step for every level */ pyrBytes = 0; imgSize = cvGetSize(imgA); elem_size = CV_ELEM_SIZE(imgA->type); levelSize = imgSize; for( i = 1; i < level1; i++ ) { levelSize.width = (levelSize.width + 1) >> 1; levelSize.height = (levelSize.height + 1) >> 1; int tstep = cvAlign(levelSize.width,ALIGN) * elem_size; pyrBytes += tstep * levelSize.height; } assert( pyrBytes <= imgSize.width * imgSize.height * elem_size * 4 / 3 ); /* buffer_size = <size for patches> + <size for pyramids> */ bufferBytes = (int)((level1 >= 0) * ((pyrA->data.ptr == 0) + (pyrB->data.ptr == 0)) * pyrBytes + (sizeof(imgI[0][0]) * 2 + sizeof(step[0][0]) + sizeof(size[0][0]) + sizeof(scale[0][0])) * level1); CV_CALL( *buffer = (uchar *)cvAlloc( bufferBytes )); *imgI = (uchar **) buffer[0]; *imgJ = *imgI + level1; *step = (int *) (*imgJ + level1); *scale = (double *) (*step + level1); *size = (CvSize *)(*scale + level1); imgI[0][0] = imgA->data.ptr; imgJ[0][0] = imgB->data.ptr; step[0][0] = imgA->step; scale[0][0] = 1; size[0][0] = imgSize; if( level > 0 ) { uchar *bufPtr = (uchar *) (*size + level1); uchar *ptrA = pyrA->data.ptr; uchar *ptrB = pyrB->data.ptr; if( !ptrA ) { ptrA = bufPtr; bufPtr += pyrBytes; } if( !ptrB ) ptrB = bufPtr; levelSize = imgSize; /* build pyramids for both frames */ for( i = 1; i <= level; i++ ) { int levelBytes; CvMat prev_level, next_level; levelSize.width = (levelSize.width + 1) >> 1; levelSize.height = (levelSize.height + 1) >> 1; size[0][i] = levelSize; step[0][i] = cvAlign( levelSize.width, ALIGN ) * elem_size; scale[0][i] = scale[0][i - 1] * 0.5; levelBytes = step[0][i] * levelSize.height; imgI[0][i] = (uchar *) ptrA; ptrA += levelBytes; if( !(flags & CV_LKFLOW_PYR_A_READY) ) { prev_level = cvMat( size[0][i-1].height, size[0][i-1].width, CV_8UC1 ); next_level = cvMat( size[0][i].height, size[0][i].width, CV_8UC1 ); cvSetData( &prev_level, imgI[0][i-1], step[0][i-1] ); cvSetData( &next_level, imgI[0][i], step[0][i] ); cvPyrDown( &prev_level, &next_level ); } imgJ[0][i] = (uchar *) ptrB; ptrB += levelBytes; if( !(flags & CV_LKFLOW_PYR_B_READY) ) { prev_level = cvMat( size[0][i-1].height, size[0][i-1].width, CV_8UC1 ); next_level = cvMat( size[0][i].height, size[0][i].width, CV_8UC1 ); cvSetData( &prev_level, imgJ[0][i-1], step[0][i-1] ); cvSetData( &next_level, imgJ[0][i], step[0][i] ); cvPyrDown( &prev_level, &next_level ); } } } __END__; } static void icvCalcIxIy_32f_paa( const float* src, int src_step, float* dstX, float* dstY, int dst_step, CvSize src_size, const float* smooth_k, float* buffer0 ) { int src_width = src_size.width, dst_width = src_size.width-2; int x, height = src_size.height - 2; float* buffer1 = buffer0 + src_width; src_step /= sizeof(src[0]); dst_step /= sizeof(dstX[0]); for( ; height--; src += src_step, dstX += dst_step, dstY += dst_step ) { const float* src2 = src + src_step; const float* src3 = src + src_step*2; #ifndef EN_ASM_4 for( x = 0; x < src_width; x++ ) { float t0 = (src3[x] + src[x])*smooth_k[0] + src2[x]*smooth_k[1]; float t1 = src3[x] - src[x]; buffer0[x] = t0; buffer1[x] = t1; } #else __asm { mov edi, smooth_k movss xmm7, [edi] //smooth_k[0] shufps xmm7, xmm7, 0h movss xmm6, [edi+4] //smooth_k[1] shufps xmm6, xmm6, 0h } for( x = 0; x < src_width; x+=4 ) { __asm { mov eax, x mov esi,src3 mov edi,src movups xmm1, [esi+eax*TYPE float] movups xmm5, [edi+eax*TYPE float] addps xmm1, xmm5 //xmm1 is t0 but needs more calculation movups xmm2, [esi+eax*TYPE float] mov esi,src2 subps xmm2, xmm5 //xmm2 is t1 and is ready to use mulps xmm1, xmm7 //(src3[x] + src[x])*smooth_k[0] movups xmm4, [esi+eax*TYPE float] mulps xmm4, xmm6 mov edi,buffer1 mov esi,buffer0 addps xmm1, xmm4 //t0 fully worked movups [edi+eax*TYPE float],xmm2 movups [esi+eax*TYPE float], xmm1 } } for(; x < src_width; x++ ) { float t0 = (src3[x] + src[x])*smooth_k[0] + src2[x]*smooth_k[1]; float t1 = src3[x] - src[x]; buffer0[x] = t0; buffer1[x] = t1; } #endif #ifndef EN_ASM_4 for( x = 0; x < dst_width; x++ ) { float t0 = buffer0[x+2] - buffer0[x]; float t1 = (buffer1[x] + buffer1[x+2])*smooth_k[0] + buffer1[x+1]*smooth_k[1]; dstX[x] = t0; dstY[x] = t1; } #else for( x = 0; x < dst_width; x+=4 ) { __asm { mov eax, x mov esi, buffer0 mov edi, buffer1 movups xmm1, [esi+eax*TYPE float+8] movups xmm5, [esi+eax*TYPE float] movups xmm2, [edi+eax*TYPE float] movups xmm4, [edi+eax*TYPE float+8] subps xmm1, xmm5 //t0 addps xmm2, xmm4 //buffer1[x] + buffer1[x+2] movups xmm5, [edi+eax*TYPE float +4] mulps xmm2, xmm7 //(buffer1[x] + buffer1[x+2])*smooth_k[0] mov esi, dstX mov edi, dstY mulps xmm5,xmm6 //buffer1[x+1]*smooth_k[1] addps xmm2, xmm5 //t1 movups [esi+eax*TYPE float], xmm1 movups [edi+eax*TYPE float], xmm2 } } for(; x < dst_width; x++ ) { float t0 = buffer0[x+2] - buffer0[x]; float t1 = (buffer1[x] + buffer1[x+2])*smooth_k[0] + buffer1[x+1]*smooth_k[1]; dstX[x] = t0; dstY[x] = t1; } #endif } } #ifdef EN_ASM_1 inline void en_asm_1(const float* pi,const float* pj,const float* ix,const float* iy,double& _bxx,double& _byx,CvSize jsz) { double _bx=0,_by=0; __asm{ mov eax, jsz.width shr eax, 2 //Divide _by 4 to get the number of iterations to optimize shl eax, 4 //Multiply by 16 to get the number of bytes to process //4 floats per iteration (16 bytes per iteration) mov edx, jsz.width shl edx, 2 //Total number of bytes to process mov ecx, 0h//counter. Bytes processed ln4_lesmult_opt: cmp ecx, eax jge ln4_lesmult_norm //If ecx >= eax go to normal iterations //t calculation mov esi, pi add esi, ecx movups xmm1, [esi] mov esi, pj add esi, ecx movups xmm2, [esi] subps xmm1, xmm2 movaps xmm2, xmm1 shufps xmm1, xmm1, 04h shufps xmm2, xmm2, 0eh cvtps2pd xmm1, xmm1 //t[x+1], t[0] cvtps2pd xmm2, xmm2 //t[x+3], t[x+2] //_bx += t * ix[x]; mov esi, ix add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm1 mulpd xmm4, xmm2 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, _bx //store it! movsd _bx, xmm3 //_by += t * iy[x]; mov esi, iy add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm1 mulpd xmm4, xmm2 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, _by //store it! movsd _by, xmm3 add ecx, 16 jmp ln4_lesmult_opt ln4_lesmult_norm: cmp ecx, edx jge ln4_lesmult_fin //If ecx >= edx go to normal iterations //double t = pi[x] - pj[x]; mov esi, pi add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mov esi, pj add esi, ecx movss xmm2, [esi] cvtss2sd xmm2, xmm2 subsd xmm1, xmm2 movsd xmm0, xmm1 //_bx += (double) (t * ix[x]); mov esi, ix add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mulsd xmm1, xmm0 addsd xmm1, _bx movsd _bx, xmm1 //_by += (double) (t * iy[x]); mov esi, iy add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mulsd xmm1, xmm0 addsd xmm1, _by movsd _by, xmm1 add ecx, 4 jmp ln4_lesmult_norm ln4_lesmult_fin: } _bxx+=_bx; _byx+=_by; } #endif #ifdef EN_ASM_2 inline void en_asm_2(double& _bxx,double& _byx,double& Gxxr,double& Gyyr,double& Gxyr,const float* ix,const float* iy,const float* pi,const float* pj,CvSize jsz) { double Gxx=0,Gyy=0,Gxy=0; double _bx=0,_by=0; __asm{ mov eax, jsz.width shr eax, 2 //Divide _by 4 to get the number of iterations to optimize shl eax, 4 //Multiply by 16 to get the number of bytes to process //4 floats per iteration (16 bytes per iteration) mov edx, jsz.width shl edx, 2 //Total number of bytes to process mov ecx, 0h//counter. Bytes processed ln4_block2_opt: cmp ecx, eax jge ln4_block2_norm //If ecx >= eax go to normal iterations //t calculation mov esi, pi add esi, ecx movups xmm1, [esi] mov esi, pj add esi, ecx movups xmm2, [esi] subps xmm1, xmm2 movaps xmm2, xmm1 shufps xmm1, xmm1, 04h shufps xmm2, xmm2, 0eh cvtps2pd xmm1, xmm1 //t[x+1], t[0] cvtps2pd xmm2, xmm2 //t[x+3], t[x+2] //_bx += t * ix[x]; mov esi, ix add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm1 mulpd xmm4, xmm2 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, _bx //store it! movsd _bx, xmm3 //_by += t * iy[x]; mov esi, iy add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm1 mulpd xmm4, xmm2 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, _by //store it! movsd _by, xmm3 //Gxx += ix[x] * ix[x]; mov esi, ix add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm3 mulpd xmm4, xmm4 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, Gxx movsd Gxx, xmm3 //Gxy += ix[x] * iy[x]; mov esi, ix add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles mov esi, iy add esi, ecx movups xmm5, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm6, xmm5 //make a copy //We make each xmm to be two array items shufps xmm5, xmm5, 04h//0000 0100 shufps xmm6, xmm6, 0eh//0000 1110 cvtps2pd xmm5, xmm5 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm6, xmm6 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm5 mulpd xmm4, xmm6 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, Gxy movsd Gxy, xmm3 //Gyy += iy[x] * iy[x]; mov esi, iy add esi, ecx movups xmm3, [esi] //ix[x+3], ix[x+2], ix[x+1], ix[x+0] //conversion to double movaps xmm4, xmm3 //make a copy //We make each xmm to be two array items shufps xmm3, xmm3, 04h//0000 0100 shufps xmm4, xmm4, 0eh//0000 1110 cvtps2pd xmm3, xmm3 //xmm3 is ix[x+1],ix[x+0] to doubles cvtps2pd xmm4, xmm4 //xmm4 is ix[x+3],ix[x+2] to doubles //make the mults with t => xmm1*xmm3 and xmm2*xmm4 mulpd xmm3, xmm3 mulpd xmm4, xmm4 //add them addpd xmm3, xmm4 movapd xmm4, xmm3 //copy shufpd xmm4, xmm3, 1h//0000 0001 reverse addpd xmm3, xmm4 //xmm3 is now to doubles with the same value //We add the variable addsd xmm3, Gyy movsd Gyy, xmm3 add ecx, 16 jmp ln4_block2_opt ln4_block2_norm: cmp ecx, edx jge ln4_block2_fin //If ecx >= ebx go to normal iterations //double t = pi[x] - pj[x]; mov esi, pi add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mov esi, pj add esi, ecx movss xmm2, [esi] cvtss2sd xmm2, xmm2 subsd xmm1, xmm2 movsd xmm0, xmm1 //_bx += (double) (t * ix[x]); mov esi, ix add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mulsd xmm1, xmm0 addsd xmm1, _bx movsd _bx, xmm1 //_by += (double) (t * iy[x]); mov esi, iy add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mulsd xmm1, xmm0 addsd xmm1, _by movsd _by, xmm1 //Gxx += ix[x] * ix[x]; mov esi, ix add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mulsd xmm1, xmm1 addsd xmm1, Gxx movsd Gxx, xmm1 //Gxy += ix[x] * iy[x]; mov esi, ix add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mov esi, iy add esi, ecx movss xmm2, [esi] cvtss2sd xmm2, xmm2 mulsd xmm1, xmm2 addsd xmm1, Gxy movsd Gxy, xmm1 //Gyy += iy[x] * iy[x]; mov esi, iy add esi, ecx movss xmm1, [esi] cvtss2sd xmm1, xmm1 mulsd xmm1, xmm1 addsd xmm1, Gyy movsd Gyy, xmm1 add ecx, 4 jmp ln4_block2_norm ln4_block2_fin: } Gxxr+=Gxx; Gyyr+=Gyy; Gxyr+=Gxy; _bxx+=_bx; _byx+=_by; } #endif /*PAA version*/ CV_IMPL void cvCalcOpticalFlowPyrLK_paa_omp( const void* arrA, const void* arrB, void* pyrarrA, void* pyrarrB, const CvPoint2D32f * featuresA, CvPoint2D32f * featuresB, int count, CvSize winSize, int level, char *status, float *error, CvTermCriteria criteria, int flags ) { /////////////////////////////////////////////////////////// //Var decl and initialization /////////////////////////////////////////////////////////// uchar *pyrBuffer = 0; uchar *buffer = 0; float* _error = 0; char* _status = 0; void* ipp_optflow_state = 0; CV_FUNCNAME( "cvCalcOpticalFlowPyrLK_paa" ); __BEGIN__; const int MAX_ITERS = 100; CvMat stubA, *imgA = (CvMat*)arrA; CvMat stubB, *imgB = (CvMat*)arrB; CvMat pstubA, *pyrA = (CvMat*)pyrarrA; CvMat pstubB, *pyrB = (CvMat*)pyrarrB; CvSize imgSize; static const float smoothKernel[] = { 0.09375, 0.3125, 0.09375 }; /* 3/32, 10/32, 3/32 */ int bufferBytes = 0; uchar **imgI = 0; uchar **imgJ = 0; int *step = 0; double *scale = 0; CvSize* size = 0; int threadCount = cvGetNumThreads(); float* _patchI[CV_MAX_THREADS]; float* _patchJ[CV_MAX_THREADS]; float* _Ix[CV_MAX_THREADS]; float* _Iy[CV_MAX_THREADS]; int i, l; CvSize patchSize = cvSize( winSize.width * 2 + 1, winSize.height * 2 + 1 ); int patchLen = patchSize.width * patchSize.height; int srcPatchLen = (patchSize.width + 2)*(patchSize.height + 2); CV_CALL( imgA = cvGetMat( imgA, &stubA )); CV_CALL( imgB = cvGetMat( imgB, &stubB )); if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 ) CV_ERROR( CV_StsUnsupportedFormat, "Image type not supported" ); if( !CV_ARE_TYPES_EQ( imgA, imgB )) CV_ERROR( CV_StsUnmatchedFormats, "images have different format" ); if( !CV_ARE_SIZES_EQ( imgA, imgB )) CV_ERROR( CV_StsUnmatchedSizes, "Images have different size" ); if( imgA->step != imgB->step ) CV_ERROR( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" ); imgSize = cvGetMatSize( imgA ); if( pyrA ) { CV_CALL( pyrA = cvGetMat( pyrA, &pstubA )); if( pyrA->step*pyrA->height < icvMinimalPyramidSize_paa( imgSize ) ) CV_ERROR( CV_StsBadArg, "pyramid A has insufficient size" ); } else { pyrA = &pstubA; pyrA->data.ptr = 0; } if( pyrB ) { CV_CALL( pyrB = cvGetMat( pyrB, &pstubB )); if( pyrB->step*pyrB->height < icvMinimalPyramidSize_paa( imgSize ) ) CV_ERROR( CV_StsBadArg, "pyramid B has insufficient size" ); } else { pyrB = &pstubB; pyrB->data.ptr = 0; } //count -> Number of tracked points. Number of points of the images (pixel count??) if( count == 0 ) EXIT; if( !featuresA || !featuresB ) CV_ERROR( CV_StsNullPtr, "Some of arrays of point coordinates are missing" ); if( count < 0 ) CV_ERROR( CV_StsOutOfRange, "The number of tracked points is negative or zero" ); if( winSize.width <= 1 || winSize.height <= 1 ) CV_ERROR( CV_StsBadSize, "Invalid search window size" ); for( i = 0; i < threadCount; i++ ) _patchI[i] = _patchJ[i] = _Ix[i] = _Iy[i] = 0; CV_CALL( icvInitPyramidalAlgorithm_paa( imgA, imgB, pyrA, pyrB, level, &criteria, MAX_ITERS, flags, &imgI, &imgJ, &step, &size, &scale, &pyrBuffer )); if( !status ) CV_CALL( status = _status = (char*)cvAlloc( count*sizeof(_status[0]) )); /* buffer_size = <size for patches> + <size for pyramids> */ bufferBytes = (srcPatchLen + patchLen * 3) * sizeof( _patchI[0][0] ) * threadCount; CV_CALL( buffer = (uchar*)cvAlloc( bufferBytes )); //Some kind of buffer initiallization to give each thread a piece of these //Pyramid buffer?? for( i = 0; i < threadCount; i++ ) { _patchI[i] = i == 0 ? (float*)buffer : _Iy[i-1] + patchLen; _patchJ[i] = _patchI[i] + srcPatchLen; _Ix[i] = _patchJ[i] + patchLen; _Iy[i] = _Ix[i] + patchLen; } memset( status, 1, count ); if( error ) memset( error, 0, count*sizeof(error[0]) ); if( !(flags & CV_LKFLOW_INITIAL_GUESSES) ) memcpy( featuresB, featuresA, count*sizeof(featuresA[0])); /////////////////////////////////////////////////////////// //Image processing /////////////////////////////////////////////////////////// /* do processing from top pyramid level (smallest image) to the bottom (original image) */ for( l = level; l >= 0; l-- ) { CvSize levelSize = size[l]; int levelStep = step[l]; #pragma omp parallel for num_threads(threadCount) schedule(static) for( i = 0; i < count; i++ ) //LN1 { CvPoint2D32f v; CvPoint minI, maxI, minJ, maxJ; CvSize isz, jsz; int pt_status; CvPoint2D32f u; CvPoint prev_minJ = { -1, -1 }, prev_maxJ = { -1, -1 }; double Gxx = 0, Gxy = 0, Gyy = 0, D = 0, minEig = 0; float prev_mx = 0, prev_my = 0; int j, x, y; //Looks like this gets his thread number and works over a piece of data //of the complete set int threadIdx = cvGetThreadNum(); float* patchI = _patchI[threadIdx]; float* patchJ = _patchJ[threadIdx]; float* Ix = _Ix[threadIdx]; float* Iy = _Iy[threadIdx]; v.x = featuresB[i].x; v.y = featuresB[i].y; if( l < level ) { //If is not the last level (simple images) v.x += v.x; v.y += v.y; } else { //If it is the last level (original image) v.x = (float)(v.x * scale[l]); v.y = (float)(v.y * scale[l]); } pt_status = status[i]; if( !pt_status ) continue; minI = maxI = minJ = maxJ = cvPoint( 0, 0 ); u.x = (float) (featuresA[i].x * scale[l]); u.y = (float) (featuresA[i].y * scale[l]); intersect_paa( u, winSize, levelSize, &minI, &maxI ); isz = jsz = cvSize(maxI.x - minI.x + 2, maxI.y - minI.y + 2); u.x += (minI.x - (patchSize.width - maxI.x + 1))*0.5f; u.y += (minI.y - (patchSize.height - maxI.y + 1))*0.5f; if( isz.width < 3 || isz.height < 3 || icvGetRectSubPix_8u32f_C1R( imgI[l], levelStep, levelSize, patchI, isz.width*sizeof(patchI[0]), isz, u ) < 0 ) { /* point is outside the image. take the next */ status[i] = 0; continue; } //Calcula el gradiente de intensidad en x e y icvCalcIxIy_32f_paa( patchI, isz.width*sizeof(patchI[0]), Ix, Iy, (isz.width-2)*sizeof(patchI[0]), isz, smoothKernel, patchJ ); for( j = 0; j < criteria.max_iter; j++ ) //LN2 { //NOTE: Variables bx and by have been renamed to _bx and _by respectively to avoid //confusion in the inline assembly with the register bx (16bit part of ebx) that //was causing a lot of headaches double _bx = 0, _by = 0; float mx, my; CvPoint2D32f _v; intersect_paa( v, winSize, levelSize, &minJ, &maxJ ); minJ.x = MAX( minJ.x, minI.x ); minJ.y = MAX( minJ.y, minI.y ); maxJ.x = MIN( maxJ.x, maxI.x ); maxJ.y = MIN( maxJ.y, maxI.y ); jsz = cvSize(maxJ.x - minJ.x, maxJ.y - minJ.y); _v.x = v.x + (minJ.x - (patchSize.width - maxJ.x + 1))*0.5f; _v.y = v.y + (minJ.y - (patchSize.height - maxJ.y + 1))*0.5f; if( jsz.width < 1 || jsz.height < 1 || icvGetRectSubPix_8u32f_C1R( imgJ[l], levelStep, levelSize, patchJ, jsz.width*sizeof(patchJ[0]), jsz, _v ) < 0 ) { /* point is outside image. take the next */ pt_status = 0; break; } if( maxJ.x == prev_maxJ.x && maxJ.y == prev_maxJ.y && minJ.x == prev_minJ.x && minJ.y == prev_minJ.y ) { for( y = 0; y < jsz.height; y++ )//LN3 { //Why it uses const??? float* pi = patchI + (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1; float* pj = patchJ + y*jsz.width; float* ix = Ix + (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x; float* iy = Iy + (ix - Ix); #ifndef EN_ASM_1 for( x = 0; x < jsz.width; x++ )//LN4 { double t = pi[x] - pj[x]; _bx += t * ix[x]; _by += t * iy[x]; } #else en_asm_1(pi,pj,ix,iy,_bx,_by,jsz); #endif } } else { Gxx = Gyy = Gxy = 0; for( y = 0; y < jsz.height; y++ )//LN3 { const float* pi = patchI + (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1; const float* pj = patchJ + y*jsz.width; const float* ix = Ix + (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x; const float* iy = Iy + (ix - Ix); #ifndef EN_ASM_2 for( x = 0; x < jsz.width; x++ )//LN4 { double t = pi[x] - pj[x]; _bx += (double) (t * ix[x]); _by += (double) (t * iy[x]); Gxx += ix[x] * ix[x]; Gxy += ix[x] * iy[x]; Gyy += iy[x] * iy[x]; } #else en_asm_2(_bx,_by,Gxx,Gyy,Gxy,ix,iy,pi,pj,jsz); #endif } D = Gxx * Gyy - Gxy * Gxy; if( D < DBL_EPSILON ) { pt_status = 0; break; } // Adi Shavit - 2008.05 if( flags & CV_LKFLOW_GET_MIN_EIGENVALS ) minEig = (Gyy + Gxx - sqrt((Gxx-Gyy)*(Gxx-Gyy) + 4.*Gxy*Gxy))/(2*jsz.height*jsz.width); D = 1. / D; prev_minJ = minJ; prev_maxJ = maxJ; } mx = (float) ((Gyy * _bx - Gxy * _by) * D); my = (float) ((Gxx * _by - Gxy * _bx) * D); v.x += mx; v.y += my; if( mx * mx + my * my < criteria.epsilon ) break; if( j > 0 && fabs(mx + prev_mx) < 0.01 && fabs(my + prev_my) < 0.01 ) { v.x -= mx*0.5f; v.y -= my*0.5f; break; } prev_mx = mx; prev_my = my; } featuresB[i] = v; status[i] = (char)pt_status; if( l == 0 && error && pt_status ) { /* calc error */ double err = 0; if( flags & CV_LKFLOW_GET_MIN_EIGENVALS ) { err = minEig; } else { for( y = 0; y < jsz.height; y++ ) {//LN3 const float * pi = patchI + (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1; const float * pj = patchJ + y*jsz.width; #ifndef EN_ASM_3 for( x = 0; x < jsz.width; x++ ) {//LN4 double t = pi[x] - pj[x]; err += t * t; } #else __asm{ mov eax, jsz.width shr eax, 2 //Divide _by 4 to get the number of iterations to optimize shl eax, 4 //Multiply by 16 to get the number of bytes to process //4 floats per iteration (16 bytes per iteration) mov edx, jsz.width shl edx, 2 //Total number of bytes to process mov ecx, 0h//counter. Bytes processed ln4_block3_opt: cmp ecx, eax jge ln4_block3_norm //If ecx >= eax go to normal iterations //t calculation mov esi, pi add esi, ecx movups xmm1, [esi] mov esi, pj add esi, ecx movups xmm2, [esi] subps xmm1, xmm2 movaps xmm2, xmm1 shufps xmm1, xmm1, 04h shufps xmm2, xmm2, 0eh cvtps2pd xmm1, xmm1 //t[x+1], t[0] cvtps2pd xmm2, xmm2 //t[x+3], t[x+2] //err += t * t; mulpd xmm1, xmm1 //t[x+1]*t[x+1], t[x]*t[x] mulpd xmm2, xmm2 //add them addpd xmm1, xmm2 movapd xmm2, xmm1 //copy shufpd xmm2, xmm1, 1h//0000 0001 reverse addpd xmm1, xmm2 //xmm1 is now to doubles with the same value //We add the variable addsd xmm1, err movsd err, xmm1 add ecx, 16 jmp ln4_block3_opt ln4_block3_norm: cmp ecx, edx jge ln4_block3_fin mov esi, pi //load pi array address add esi, ecx //add counter to address movss xmm1, [esi] //load 1 floats from pi mov esi, pj add esi, ecx movss xmm2, [esi] //Load 1 floats from pj subss xmm1, xmm2 //1 subs cvtss2sd xmm1, xmm1 mulsd xmm1, xmm1 //(pi[x]-pj[x])^2 addsd xmm1, err movsd err, xmm1 add ecx, 4 //Add the number of processed bytes jmp ln4_block3_norm //Fin de bucle ln4_block3_fin: } #endif } err = sqrt(err); } error[i] = (float)err; } } //************** Point processing loop End ************** } // end of pyramid levels loop (l) __END__; if( ipp_optflow_state ) icvOpticalFlowPyrLKFree_8u_C1R_p( ipp_optflow_state ); cvFree( &pyrBuffer ); cvFree( &buffer ); cvFree( &_error ); cvFree( &_status ); } //#endif /* End of file. */
[ "pibgeus@ce9d1b04-dfe2-11dd-ab07-b19b4dad1b3d" ]
[ [ [ 1, 1168 ] ] ]
9f348e708212a474d5d10344d8ccbaf8d447d52f
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/ui/include/UiSubsystem.h
9271c68469d93db01be355efcc9fce4e235e7105
[ "ClArtistic", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
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
ISO-8859-1
C++
false
false
3,408
h
/* 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. */ #ifndef __UiSubsystem_H__ #define __UiSubsystem_H__ #include "UiPrerequisites.h" #include "World.h" #include <OgreSingleton.h> #include "CharacterController.h" #include "GameTask.h" // Gar nicht schön, aber ansonsten gibt es unnötige Abhängigkeiten, // wenn man die Header hier inkludiert. namespace CEGUI { class OgreCEGUIRenderer; class OgreCEGUIResourceProvider; class System; } namespace rl { class CommandMapper; class Creature; class GameActor; class GameObject; class InputManager; class Person; class RBCombat; class RTCombat; class WindowFactory; class WindowManager; class _RlUiExport UiSubsystem : public SceneChangeListener, protected Ogre::Singleton<UiSubsystem>, protected GameTask { public: static const char* CEGUI_ROOT; /** Default Constructor */ UiSubsystem(); /** Default Deconstructor */ virtual ~UiSubsystem(); /** Returns the Singleton */ static UiSubsystem & getSingleton(void); static UiSubsystem * getSingletonPtr(void); void useDefaultAction(GameObject* obj, Creature* actor); void usePickedObjectDefaultActions(); void toggleObjectPicking(); CEGUI::OgreCEGUIRenderer* getGUIRenderer(); Person* getActiveCharacter() const; void setActiveCharacter(Person* person); CharacterController* getCharacterController() const; CharacterController::ControllerType getCharacterControllerType() const; /** * Aendert den CharacterController, wird sofort durchgefuehrt * kann Probleme bei Ausfuehrung innerhalb eines Controllers geben, * dann ist @see requestCharacterControllerSwitch empfohlen */ void setCharacterController(CharacterController::ControllerType type); /** * Aendert den CharacterController nach dem naechsten Frame */ void requestCharacterControllerSwitch(CharacterController::ControllerType type); void update(); /// from SceneChangeListener void onBeforeClearScene(); void run(Ogre::Real elapsedTime); private: CharacterController* mCharacterController; CharacterController::ControllerType mCharacterControllerType; GameActor* mHero; Person* mCharacter; // Singletons InputManager* mInputManager; WindowFactory* mWindowFactory; WindowManager* mWindowManager; CommandMapper* mCommandMapper; CEGUI::OgreCEGUIRenderer* mGuiRenderer; CEGUI::OgreCEGUIResourceProvider* mGuiResourceProvider; CEGUI::System* mGuiSystem; void initializeUiSubsystem(); void runTest(); }; } #endif
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 114 ] ] ]
9c8b2f4b094e4e03e24ff3a113f3c80ef6c21b12
68127d36b179fd5548a1e593e2c20791db6b48e3
/cppBuilder/energizado/energizadoauto1.cpp
93f4ba3d4e150d2cc95eef2beb832769029d2410
[]
no_license
renatomb/engComp
fa50b962dbdf4f9387fd02a28b3dc130b683ed02
b533c876b50427d44cfdb92c507a6e74b1b7fa79
refs/heads/master
2020-04-11T06:22:05.209022
2006-04-26T13:40:08
2018-12-13T04:25:08
161,578,821
1
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop USERES("energizadoauto1.res"); USEFORM("energizadoauto.cpp", Form1); USEFORM("Unit2.cpp", Form2); USEFORM("Unit3.cpp", Form3); //--------------------------------------------------------------------------- WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { try { Application->Initialize(); Application->CreateForm(__classid(TForm1), &Form1); Application->CreateForm(__classid(TForm2), &Form2); Application->CreateForm(__classid(TForm3), &Form3); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } return 0; } //---------------------------------------------------------------------------
[ [ [ 1, 26 ] ] ]
7844ca01af910f438bb722a2e8d60784d79878dc
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Shared/GuiProt/GuiProtMessageHandler.cpp
7f4cdc5cd546bca140c0076f2279f5a6ce520e20
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,789
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GuiProt/GuiProtMessageHandler.h" #include "GuiProt/GuiProtMess.h" int32 GuiProtMessageHandler::SendMessage(isab::GuiProtMess &mess, GuiProtMessageReceiver* callback) { int32 reqId = m_sender->SendMessageL(mess); m_reqList[reqId] = callback; return reqId; } void GuiProtMessageHandler::DisownMessage(GuiProtMessageReceiver* callback) { GPMReceiverList::iterator it = m_reqList.begin(); while (it != m_reqList.end()) { GuiProtMessageReceiver* item = (*it).second; if (item == callback) { /* Erase it. */ int32 reqId = (*it).first; it++; m_reqList.erase(reqId); } else { it++; } } } int32 GuiProtMessageHandler::SendMessage(isab::GuiProtMess &mess) { return m_sender->SendMessageL(mess); } bool GuiProtMessageHandler::GuiProtReceiveMessage(isab::GuiProtMess *mess) { bool handled = false; { int32 reqId = mess->getMessageID(); GPMReceiverList::iterator it = m_reqList.find(reqId); if (it != m_reqList.end()) { GuiProtMessageReceiver* item = (*it).second; m_reqList.erase(it); handled = item->GuiProtReceiveMessage(mess); } } { /* Otherwise, check if anyone has registered for this type of message. */ int32 type = mess->getMessageType(); GPMReceiverMultiMap::iterator it = m_typeMap.lower_bound(type); while (it != m_typeMap.end() && (*it).first == type) { ((*it).second)->GuiProtReceiveMessage(mess); it++; } } return handled; } void GuiProtMessageHandler::RegisterReceiver( GuiProtMessageReceiver* callback, int32 type) { m_typeMap.insert( std::make_pair( type, callback ) ); } void GuiProtMessageHandler::DeregisterReceiver( GuiProtMessageReceiver* callback, int32 type) { GPMReceiverMultiMap::iterator it = m_typeMap.lower_bound(type); while (it != m_typeMap.end() && (*it).second == callback) { GPMReceiverMultiMap::iterator tempit = it; it++; m_typeMap.erase(tempit); } } GuiProtMessageHandler::~GuiProtMessageHandler() { m_reqList.clear(); m_typeMap.clear(); }
[ [ [ 1, 101 ] ] ]
63b841ef61c10cee716285f4747743d38d87c015
56baf30355c13e5154027ee3b354513b9ae422f4
/applicationlogic.h
72e329e70781759b6ebf7522794d430ad7193e98
[]
no_license
Tallefer/cuteauthenticator
1087d9753d3fd44adc51bc588f78831df15cb26a
596adfd2d840bd47cdcbf9dc3342bc7092bb5ccf
refs/heads/master
2016-08-03T20:39:49.703523
2011-03-20T10:04:47
2011-03-20T10:04:47
35,008,557
0
0
null
null
null
null
UTF-8
C++
false
false
1,062
h
#ifndef APPLICATIONLOGIC_H #define APPLICATIONLOGIC_H #include <QObject> #include "qmlapplicationviewer.h" #include "roleitemmodel.h" #include <QDeclarativeEngine> #include <QDeclarativeContext> #include <QSettings> #include <QDebug> struct AccountsKeys { enum AccountsRoles { NameRole = Qt::UserRole + 1, SecretKeyRole, }; }; class ApplicationLogic : public QObject { Q_OBJECT public: explicit ApplicationLogic(QObject *parent = 0); ~ApplicationLogic() { m_accountsmodel->deleteLater(); m_viewer.deleteLater(); m_ctxt->deleteLater(); m_accountsmodel->clear(); } signals: public slots: void addAccount(QString name, QString secretkey); void removeAccount(int index); protected: QHash<int, QByteArray> m_roleNames; RoleItemModel* m_accountsmodel; QmlApplicationViewer m_viewer; QDeclarativeContext* m_ctxt; QSettings settings; QList<QStandardItem*> m_items; }; #endif // APPLICATIONLOGIC_H
[ "[email protected]@9c31be44-14c4-d9b1-5e2f-0b3f72e17b30" ]
[ [ [ 1, 47 ] ] ]
997626049d22adc66d1995bea41830d19680ce49
67298ca8528b753930a3dc043972dceab5e45d6a
/FileSharing/src/FileServer.cpp
baaf2657bd64c812a64fc83ffe77330d6353a826
[]
no_license
WhyKay92/cs260assignment3
3cf28dd92b9956b2cd4f850652651cb11f25c753
77ad90cd2dc0b44f3ba0a396dc8399021de4faa5
refs/heads/master
2021-05-30T14:59:21.297733
2010-12-13T09:18:17
2010-12-13T09:18:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,931
cpp
/*! * @File FileServer.cpp * @Author Michael Travaglione * @Date 11 November 2010 * @Brief Implementation of object containing the sever which maintains the file transfer application */ #include "shared.hpp" // BaseErrExcep #include "FileServer.hpp" unsigned FileServer::transID_ = 0; void FileServer::Init( void ) { try { server_.Init(); } catch(BaseErrExcep& e) { throw e; } } ///////////////////////////////////// void FileServer::Run(void) { bool run = true; try { while(run) { server_.Update(); std::deque<NetworkMessage> currentMessages; server_.GetMessages(currentMessages); for(std::deque<NetworkMessage>::iterator it = currentMessages.begin(); it != currentMessages.end(); ++it) ProcMessage((*it)); } } catch(BaseErrExcep& e) { throw e; } } ///////////////////////////////////// void FileServer::Close(void) { try { server_.Close(); } catch(BaseErrExcep& e) { throw e; } } ///////////////////////////////////// void FileServer::ProcMessage(NetworkMessage& msg) { switch(msg.type_) { case NetworkMessage::JOIN: { // convert network message into known type MsgJoin join; msg >> join; // add the files from the new client to the master list - *assumes no duplicates* u32 numFiles = join.data_.fileCount_; FileOwner owner; owner.conID_ = msg.conID_; owner.sockAddr_ = join.data_.udpAddr_; for(unsigned i = 0; i < numFiles; ++i) { masterFileList_.insert(std::make_pair(join.data_.files_[i].fileName_, owner)); fileNames_[msg.conID_].push_back(join.data_.files_[i].fileName_); } printf("\nNew user connected. %d files added to server.\n\n", numFiles); printf("Available files from all clients:\n"); printf("=================================\n"); PrintMasterList(); SendMasterList(msg.conID_); } break; case NetworkMessage::REQ_FILES: printf("\nClient requesting file list...\n\n"); SendMasterList(msg.conID_); break; case NetworkMessage::QUIT: printf("\nClient is quitting server...\n\n", fileNames_[msg.conID_].size()); break; case NetworkMessage::DISCON: RemoveFiles(msg.conID_); printf("\nLost connection to client. %d files removed.\n\n", fileNames_[msg.conID_].size()); printf("Updated list of files: \n"); printf("====================== \n\n"); PrintMasterList(); break; case NetworkMessage::GET: { MsgGet get; msg >> get; FileCont::iterator it = masterFileList_.find(get.data_.name_.fileName_); if(it != masterFileList_.end()) { FileOwner fileSender; fileSender = it->second; MsgInformReceiver informRecv; strcpy(informRecv.data_.fileName_, get.data_.name_.fileName_); informRecv.data_.sender_ = fileSender.sockAddr_; informRecv.data_.transferID_ = transID_; informRecv.type_ = NetworkMessage::INFORM_RECEIVER; NetworkMessage recvMsg; recvMsg.conID_ = msg.conID_; recvMsg << informRecv; server_.SendMessage(recvMsg); MsgInformSender informSender; strcpy(informSender.data_.fileName_, get.data_.name_.fileName_); informSender.data_.recipient_ = get.data_.recvAddr_; informSender.data_.transferID_ = transID_; informSender.type_ = NetworkMessage::INFORM_SENDER; NetworkMessage sendMsg; sendMsg.conID_ = fileSender.conID_; sendMsg << informSender; server_.SendMessage(sendMsg); ++transID_; } } break; } } ///////////////////////////////////// void FileServer::SendMasterList(u32 conID) { // set up the message to send MsgServerFiles serverFiles; // number of file names to send serverFiles.data_.fileCount_ = masterFileList_.size(); // type of message serverFiles.type_ = NetworkMessage::SERVER_FILES; // copy each filename on the master list into the data of the message unsigned i = 0; for(FileCont::iterator it2 = masterFileList_.begin(); it2 != masterFileList_.end(); ++it2) { strcpy(serverFiles.data_.files_[i].fileName_, it2->first.c_str()); ++i; } // now need to convert the message into a generic network message NetworkMessage newMsg; // set the connection id so the server knows who to send to newMsg.conID_ = conID; // convert to known type newMsg << serverFiles; // send to the clients server_.BroadcastMessage(newMsg); } ///////////////////////////////////// void FileServer::RemoveFiles(u32 conID) { FileNameCont::iterator it = fileNames_.find(conID); if(it != fileNames_.end()) { std::vector<std::string>& names = it->second; for(std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) masterFileList_.erase((*it)); } } ///////////////////////////////////// void FileServer::PrintMasterList(void) { for(FileCont::iterator it = masterFileList_.begin(); it != masterFileList_.end(); ++it) printf("%s\n", it->first.c_str()); printf("\n"); }
[ [ [ 1, 203 ] ] ]
87b0d4ca5b6a50339335646519e2b0ec1e51b8b0
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/serialization/example/demo_portable_archive.cpp
c15a8ab31cd2b8a7d4f18ab6f67c56d5231c48c1
[ "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
1,685
cpp
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // // demo_portable_archive.cpp // // (C) Copyright 2002-4 Robert Ramey - http://www.rrsd.com . // 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) // should pass compilation and execution #include <sstream> #define BOOST_ARCHIVE_SOURCE #include "portable_binary_oarchive.hpp" #include "portable_binary_iarchive.hpp" #include <cstdlib> #include <boost/config.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::rand; } #endif // the following is required to be sure the "EXPORT" works if it is used #define CUSTOM_ARCHIVE_TYPES portable_binary_oarchive,portable_binary_iarchive class A { friend class boost::serialization::access; int i; unsigned int ui; long l; unsigned long ul; template<class Archive> void serialize(Archive & ar, const unsigned int /* version */){ ar & i & ui & l & ul ; } public: bool operator==(const A & rhs) const { return i == rhs.i && ui == rhs.ui && l == rhs.l && ul == rhs.ul ; } A() : i(std::rand()), ui(std::rand()), l(std::rand()), ul(std::rand()) {} }; int main( int /* argc */, char* /* argv */[] ) { const A a; A a1; std::stringstream ss; { portable_binary_oarchive pboa(ss); pboa << a; } { portable_binary_iarchive pbia(ss); pbia >> a1; } return !(a == a1); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 68 ] ] ]
f351aa38e0b7b42b9972219564b48c7a6d0d1ca3
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/C45ModelSelection.h
9d2f71e56b49b55e4cbb83f3af4ff17283c429d2
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
1,623
h
#pragma once #include "datasource.h" #include "ModelSelection.h" #include "BitStreamInfo.h" #include "classifiersplitmodel.h" #include "Utils.h" /************************************************************************ * Class :C45ModelSelection * Author :Amila De Silva * Subj : * Class for selecting a C4.5-type split for a given dataset. * * Version: 1 ************************************************************************/ class C45ModelSelection : public ModelSelection { public: /*** * Constructor */ C45ModelSelection(void); /*** * Destructor */ ~C45ModelSelection(void); /** * Initializes the split selection method with the given parameters. * * minNoObj minimum number of instances that have to occur in at least two * subsets induced by split * allData FULL training dataset (necessary for * selection of split points). * useMDLcorrection whether to use MDL adjustement when * finding splits on numeric attributes */ _declspec(dllexport) C45ModelSelection(int minNoObj, DataSource * allData, BitStreamInfo * _existence_bitmap, bool useMDLcorrection) ; /** * Selects C4.5-type split for the given dataset. */ _declspec(dllexport) ClassifierSplitModel * selectModel(DataSource * _data,BitStreamInfo * _existence_bitmap); private: /** Minimum number of objects in interval. */ int m_minNoObj; /** Use MDL correction? */ bool m_useMDLcorrection; /** All the training data */ DataSource * m_allData; /** Existence Bitmap */ BitStreamInfo * m_existence_bitmap; };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 61 ] ] ]
5b07b042d479088907fbe3e5671597ae27f870b3
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/3rdparty/wxWidgets/include/wx/setup.h
16c8a8b27f53fe9cfc89303a2218b25d513e6fa6
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
46,945
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/setup.h // Purpose: Configuration for the library // Author: Julian Smart // Modified by: // Created: 01/02/97 // RCS-ID: $Id: setup0.h 43908 2006-12-11 06:19:27Z RD $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_SETUP_H_ #define _WX_SETUP_H_ /* --- start common options --- */ // ---------------------------------------------------------------------------- // global settings // ---------------------------------------------------------------------------- // define this to 0 when building wxBase library - this can also be done from // makefile/project file overriding the value here #ifndef wxUSE_GUI #define wxUSE_GUI 1 #endif // wxUSE_GUI // ---------------------------------------------------------------------------- // compatibility settings // ---------------------------------------------------------------------------- // This setting determines the compatibility with 2.4 API: set it to 1 to // enable it but please consider updating your code instead. // // Default is 0 // // Recommended setting: 0 (please update your code) #define WXWIN_COMPATIBILITY_2_4 0 // This setting determines the compatibility with 2.6 API: set it to 0 to // flag all cases of using deprecated functions. // // Default is 1 but please try building your code with 0 as the default will // change to 0 in the next version and the deprecated functions will disappear // in the version after it completely. // // Recommended setting: 0 (please update your code) #define WXWIN_COMPATIBILITY_2_6 0 // MSW-only: Set to 0 for accurate dialog units, else 1 for old behaviour when // default system font is used for wxWindow::GetCharWidth/Height() instead of // the current font. // // Default is 0 // // Recommended setting: 0 #define wxDIALOG_UNIT_COMPATIBILITY 0 // ---------------------------------------------------------------------------- // debugging settings // ---------------------------------------------------------------------------- // Generic comment about debugging settings: they are very useful if you don't // use any other memory leak detection tools such as Purify/BoundsChecker, but // are probably redundant otherwise. Also, Visual C++ CRT has the same features // as wxWidgets memory debugging subsystem built in since version 5.0 and you // may prefer to use it instead of built in memory debugging code because it is // faster and more fool proof. // // Using VC++ CRT memory debugging is enabled by default in debug mode // (__WXDEBUG__) if wxUSE_GLOBAL_MEMORY_OPERATORS is *not* enabled (i.e. is 0) // and if __NO_VC_CRTDBG__ is not defined. // If 1, enables wxDebugContext, for writing error messages to file, etc. If // __WXDEBUG__ is not defined, will still use the normal memory operators. // // Default is 0 // // Recommended setting: 0 #define wxUSE_DEBUG_CONTEXT 0 // If 1, enables debugging versions of wxObject::new and wxObject::delete *IF* // __WXDEBUG__ is also defined. // // WARNING: this code may not work with all architectures, especially if // alignment is an issue. This switch is currently ignored for mingw / cygwin // // Default is 0 // // Recommended setting: 1 if you are not using a memory debugging tool, else 0 #define wxUSE_MEMORY_TRACING 0 // In debug mode, cause new and delete to be redefined globally. // If this causes problems (e.g. link errors which is a common problem // especially if you use another library which also redefines the global new // and delete), set this to 0. // This switch is currently ignored for mingw / cygwin // // Default is 0 // // Recommended setting: 0 #define wxUSE_GLOBAL_MEMORY_OPERATORS 0 // In debug mode, causes new to be defined to be WXDEBUG_NEW (see object.h). If // this causes problems (e.g. link errors), set this to 0. You may need to set // this to 0 if using templates (at least for VC++). This switch is currently // ignored for mingw / cygwin / CodeWarrior // // Default is 0 // // Recommended setting: 0 #define wxUSE_DEBUG_NEW_ALWAYS 0 // [PCSX2 Extension (Win32-specific)] // Tells wxWidgets to use private heaps for wxString and wxObject. This is very // useful for two reasons: it tends to be a good speedup, since these objects // allocate a lot of small blocks that fragment the global heap, and it also // bypasses the CRT, which avoids heap pollution when looking for memory leaks. // Typically wxWidgets is leak-free so you only want your own app's blocks in // the global CRT heap. // // Default is 1. // // Recommended Setting: 1 (wxWidgets developers my find it useful to use 0). // #define wxUSE_PRIVATE_HEAP 1 // wxHandleFatalExceptions() may be used to catch the program faults at run // time and, instead of terminating the program with a usual GPF message box, // call the user-defined wxApp::OnFatalException() function. If you set // wxUSE_ON_FATAL_EXCEPTION to 0, wxHandleFatalExceptions() will not work. // // This setting is for Win32 only and can only be enabled if your compiler // supports Win32 structured exception handling (currently only VC++ does) // // Default is 1 // // Recommended setting: 1 if your compiler supports it. #define wxUSE_ON_FATAL_EXCEPTION 0 // Set this to 1 to be able to generate a human-readable (unlike // machine-readable minidump created by wxCrashReport::Generate()) stack back // trace when your program crashes using wxStackWalker // // Default is 1 if supported by the compiler. // // Recommended setting: 1, set to 0 if your programs never crash #define wxUSE_STACKWALKER 1 // Set this to 1 to compile in wxDebugReport class which allows you to create // and optionally upload to your web site a debug report consisting of back // trace of the crash (if wxUSE_STACKWALKER == 1) and other information. // // Default is 1 if supported by the compiler. // // Recommended setting: 1, it is compiled into a separate library so there // is no overhead if you don't use it #define wxUSE_DEBUGREPORT 1 // ---------------------------------------------------------------------------- // Unicode support // ---------------------------------------------------------------------------- // Set wxUSE_UNICODE to 1 to compile wxWidgets in Unicode mode: wxChar will be // defined as wchar_t, wxString will use Unicode internally. If you set this // to 1, you must use wxT() macro for all literal strings in the program. // // Unicode is currently only fully supported under Windows NT/2000/XP // (Windows 9x doesn't support it and the programs compiled in Unicode mode // will not run under 9x -- but see wxUSE_UNICODE_MSLU below). // // Default is 0 // // Recommended setting: 0 (unless you only plan to use Windows NT/2000/XP) #ifndef wxUSE_UNICODE #define wxUSE_UNICODE 0 #endif // Setting wxUSE_WCHAR_T to 1 gives you some degree of Unicode support without // compiling the program in Unicode mode. More precisely, it will be possible // to construct wxString from a wide (Unicode) string and convert any wxString // to Unicode. // // Default is 1 // // Recommended setting: 1 #define wxUSE_WCHAR_T 1 // ---------------------------------------------------------------------------- // global features // ---------------------------------------------------------------------------- // Compile library in exception-safe mode? If set to 1, the library will try to // behave correctly in presence of exceptions (even though it still will not // use the exceptions itself) and notify the user code about any unhandled // exceptions. If set to 0, propagation of the exceptions through the library // code will lead to undefined behaviour -- but the code itself will be // slightly smaller and faster. // // Note that like wxUSE_THREADS this option is automatically set to 0 if // wxNO_EXCEPTIONS is defined. // // Default is 1 // // Recommended setting: depends on whether you intend to use C++ exceptions // in your own code (1 if you do, 0 if you don't) #define wxUSE_EXCEPTIONS 1 // Set wxUSE_EXTENDED_RTTI to 1 to use extended RTTI // // Default is 0 // // Recommended setting: 0 (this is still work in progress...) #define wxUSE_EXTENDED_RTTI 0 // Set wxUSE_STL to 1 to derive wxList(Foo) and wxArray(Foo) from // std::list<Foo*> and std::vector<Foo*>, with a compatibility interface, // and for wxHashMap to be implemented with templates. // // Default is 0 // // Recommended setting: YMMV #define wxUSE_STL 1 // Support for message/error logging. This includes wxLogXXX() functions and // wxLog and derived classes. Don't set this to 0 unless you really know what // you are doing. // // Default is 1 // // Recommended setting: 1 (always) #define wxUSE_LOG 1 // Recommended setting: 1 #define wxUSE_LOGWINDOW 0 // Recommended setting: 1 #define wxUSE_LOGGUI 0 // Recommended setting: 1 #define wxUSE_LOG_DIALOG 0 // Support for command line parsing using wxCmdLineParser class. // // Default is 1 // // Recommended setting: 1 (can be set to 0 if you don't use the cmd line) #define wxUSE_CMDLINE_PARSER 1 // Support for multithreaded applications: if 1, compile in thread classes // (thread.h) and make the library a bit more thread safe. Although thread // support is quite stable by now, you may still consider recompiling the // library without it if you have no use for it - this will result in a // somewhat smaller and faster operation. // // Notice that if wxNO_THREADS is defined, wxUSE_THREADS is automatically reset // to 0 in wx/chkconf.h, so, for example, if you set USE_THREADS to 0 in // build/msw/config.* file this value will have no effect. // // Default is 1 // // Recommended setting: 0 unless you do plan to develop MT applications #define wxUSE_THREADS 1 // If enabled, compiles wxWidgets streams classes // // wx stream classes are used for image IO, process IO redirection, network // protocols implementation and much more and so disabling this results in a // lot of other functionality being lost. // // Default is 1 // // Recommended setting: 1 as setting it to 0 disables many other things #define wxUSE_STREAMS 1 // Use standard C++ streams if 1 instead of wx streams in some places. If // disabled (default), wx streams are used everywhere and wxWidgets doesn't // depend on the standard streams library. // // Notice that enabling this does not replace wx streams with std streams // everywhere, in a lot of places wx streams are used no matter what. // // Default is 0 // // Recommended setting: 1 if you use the standard streams anyhow and so // dependency on the standard streams library is not a // problem #define wxUSE_STD_IOSTREAM 0 // Enable conversion to standard C++ string if 1. // // Default is 1 for most compilers. // // Currently the Digital Mars and Watcom compilers come without standard C++ // library headers by default, wxUSE_STD_STRING can be set to 1 if you do have // them (e.g. from STLPort). // // VC++ 5.0 does include standard C++ library header, however they produce // many warnings that can't be turned off when compiled at warning level 4. #if defined(__DMC__) || defined(__WATCOMC__) \ || (defined(_MSC_VER) && _MSC_VER < 1200) #define wxUSE_STD_STRING 0 #else #define wxUSE_STD_STRING 1 #endif // Support for positional parameters (e.g. %1$d, %2$s ...) in wxVsnprintf. // Note that if the system's implementation does not support positional // parameters, setting this to 1 forces the use of the wxWidgets implementation // of wxVsnprintf. The standard vsnprintf() supports positional parameters on // many Unix systems but usually doesn't under Windows. // // Positional parameters are very useful when translating a program since using // them in formatting strings allow translators to correctly reorder the // translated sentences. // // Default is 1 // // Recommended setting: 1 if you want to support multiple languages #define wxUSE_PRINTF_POS_PARAMS 1 // ---------------------------------------------------------------------------- // non GUI features selection // ---------------------------------------------------------------------------- // Set wxUSE_LONGLONG to 1 to compile the wxLongLong class. This is a 64 bit // integer which is implemented in terms of native 64 bit integers if any or // uses emulation otherwise. // // This class is required by wxDateTime and so you should enable it if you want // to use wxDateTime. For most modern platforms, it will use the native 64 bit // integers in which case (almost) all of its functions are inline and it // almost does not take any space, so there should be no reason to switch it // off. // // Recommended setting: 1 #define wxUSE_LONGLONG 1 // Set wxUSE_(F)FILE to 1 to compile wx(F)File classes. wxFile uses low level // POSIX functions for file access, wxFFile uses ANSI C stdio.h functions. // // Default is 1 // // Recommended setting: 1 (wxFile is highly recommended as it is required by // i18n code, wxFileConfig and others) #define wxUSE_FILE 1 #define wxUSE_FFILE 1 // Use wxFSVolume class providing access to the configured/active mount points // // Default is 1 // // Recommended setting: 1 (but may be safely disabled if you don't use it) #define wxUSE_FSVOLUME 0 // Use wxStandardPaths class which allows to retrieve some standard locations // in the file system // // Default is 1 // // Recommended setting: 1 (may be disabled to save space, but not much) #define wxUSE_STDPATHS 1 // use wxTextBuffer class: required by wxTextFile #define wxUSE_TEXTBUFFER 1 // use wxTextFile class: requires wxFile and wxTextBuffer, required by // wxFileConfig #define wxUSE_TEXTFILE 1 // i18n support: _() macro, wxLocale class. Requires wxTextFile. #define wxUSE_INTL 1 // Set wxUSE_DATETIME to 1 to compile the wxDateTime and related classes which // allow to manipulate dates, times and time intervals. wxDateTime replaces the // old wxTime and wxDate classes which are still provided for backwards // compatibility (and implemented in terms of wxDateTime). // // Note that this class is relatively new and is still officially in alpha // stage because some features are not yet (fully) implemented. It is already // quite useful though and should only be disabled if you are aiming at // absolutely minimal version of the library. // // Requires: wxUSE_LONGLONG // // Default is 1 // // Recommended setting: 1 #define wxUSE_DATETIME 1 // Set wxUSE_TIMER to 1 to compile wxTimer class // // Default is 1 // // Recommended setting: 1 #define wxUSE_TIMER 1 // Use wxStopWatch clas. // // Default is 1 // // Recommended setting: 1 (needed by wxSocket) #define wxUSE_STOPWATCH 1 // Setting wxUSE_CONFIG to 1 enables the use of wxConfig and related classes // which allow the application to store its settings in the persistent // storage. Setting this to 1 will also enable on-demand creation of the // global config object in wxApp. // // See also wxUSE_CONFIG_NATIVE below. // // Recommended setting: 1 #define wxUSE_CONFIG 1 // If wxUSE_CONFIG is 1, you may choose to use either the native config // classes under Windows (using .INI files under Win16 and the registry under // Win32) or the portable text file format used by the config classes under // Unix. // // Default is 1 to use native classes. Note that you may still use // wxFileConfig even if you set this to 1 - just the config object created by // default for the applications needs will be a wxRegConfig or wxIniConfig and // not wxFileConfig. // // Recommended setting: 1 #define wxUSE_CONFIG_NATIVE 1 // If wxUSE_DIALUP_MANAGER is 1, compile in wxDialUpManager class which allows // to connect/disconnect from the network and be notified whenever the dial-up // network connection is established/terminated. Requires wxUSE_DYNAMIC_LOADER. // // Default is 1. // // Recommended setting: 1 #define wxUSE_DIALUP_MANAGER 0 // Compile in classes for run-time DLL loading and function calling. // Required by wxUSE_DIALUP_MANAGER. // // This setting is for Win32 only // // Default is 1. // // Recommended setting: 1 #define wxUSE_DYNLIB_CLASS 1 // experimental, don't use for now #define wxUSE_DYNAMIC_LOADER 0 // Set to 1 to use socket classes #define wxUSE_SOCKETS 1 // Set to 1 to enable virtual file systems (required by wxHTML) #define wxUSE_FILESYSTEM 0 // Set to 1 to enable virtual ZIP filesystem (requires wxUSE_FILESYSTEM) #define wxUSE_FS_ZIP 0 // Set to 1 to enable virtual archive filesystem (requires wxUSE_FILESYSTEM) #define wxUSE_FS_ARCHIVE 0 // Set to 1 to enable virtual Internet filesystem (requires wxUSE_FILESYSTEM) #define wxUSE_FS_INET 0 // wxArchive classes for accessing archives such as zip and tar #define wxUSE_ARCHIVE_STREAMS 1 // Set to 1 to compile wxZipInput/OutputStream classes. #define wxUSE_ZIPSTREAM 1 // Set to 1 to compile wxTarInput/OutputStream classes. #define wxUSE_TARSTREAM 1 // Set to 1 to compile wxZlibInput/OutputStream classes. Also required by // wxUSE_LIBPNG #define wxUSE_ZLIB 1 // If enabled, the code written by Apple will be used to write, in a portable // way, float on the disk. See extended.c for the license which is different // from wxWidgets one. // // Default is 1. // // Recommended setting: 1 unless you don't like the license terms (unlikely) #define wxUSE_APPLE_IEEE 1 // Joystick support class #define wxUSE_JOYSTICK 1 // wxFontMapper class #define wxUSE_FONTMAP 1 // wxMimeTypesManager class #define wxUSE_MIMETYPE 0 // wxProtocol and related classes: if you want to use either of wxFTP, wxHTTP // or wxURL you need to set this to 1. // // Default is 1. // // Recommended setting: 1 #define wxUSE_PROTOCOL 1 // The settings for the individual URL schemes #define wxUSE_PROTOCOL_FILE 1 #define wxUSE_PROTOCOL_FTP 1 #define wxUSE_PROTOCOL_HTTP 1 // Define this to use wxURL class. #define wxUSE_URL 1 // Define this to use native platform url and protocol support. // Currently valid only for MS-Windows. // Note: if you set this to 1, you can open ftp/http/gopher sites // and obtain a valid input stream for these sites // even when you set wxUSE_PROTOCOL_FTP/HTTP to 0. // Doing so reduces the code size. // // This code is experimental and subject to change. #define wxUSE_URL_NATIVE 0 // Support for wxVariant class used in several places throughout the library, // notably in wxDataViewCtrl API. // // Default is 1. // // Recommended setting: 1 unless you want to reduce the library size as much as // possible in which case setting this to 0 can gain up to 100KB. #define wxUSE_VARIANT 1 // Support for regular expression matching via wxRegEx class: enable this to // use POSIX regular expressions in your code. You need to compile regex // library from src/regex to use it under Windows. // // Default is 0 // // Recommended setting: 1 if your compiler supports it, if it doesn't please // contribute us a makefile for src/regex for it #define wxUSE_REGEX 0 // wxSystemOptions class #define wxUSE_SYSTEM_OPTIONS 1 // wxSound class #define wxUSE_SOUND 0 // Use wxMediaCtrl // // Default is 1. // // Recommended setting: 1 #define wxUSE_MEDIACTRL 0 // Use GStreamer for Unix (req a lot of dependancies) // // Default is 0 // // Recommended setting: 1 (wxMediaCtrl won't work by default without it) #define wxUSE_GSTREAMER 0 // Use wxWidget's XRC XML-based resource system. Recommended. // // Default is 1 // // Recommended setting: 1 (requires wxUSE_XML) #define wxUSE_XRC 0 // XML parsing classes. Note that their API will change in the future, so // using wxXmlDocument and wxXmlNode in your app is not recommended. // // Default is the same as wxUSE_XRC, i.e. 1 by default. // // Recommended setting: 1 (required by XRC) #define wxUSE_XML wxUSE_XRC // Use wxWidget's AUI docking system // // Default is 1 // // Recommended setting: 1 #define wxUSE_AUI 1 // Enable the new wxGraphicsPath and wxGraphicsContext classes for an advanced // 2D drawing API. (Still somewhat experimental) // // Please note that on Windows you will need to link with gdiplus.lib (use // USE_GDIPLUS=1 for makefile builds) and distribute gdiplus.dll with your // application if you want it to be runnable on pre-XP systems. // // Default is 0 // // Recommended setting: 1 #ifndef wxUSE_GRAPHICS_CONTEXT #define wxUSE_GRAPHICS_CONTEXT 0 #endif // ---------------------------------------------------------------------------- // Individual GUI controls // ---------------------------------------------------------------------------- // You must set wxUSE_CONTROLS to 1 if you are using any controls at all // (without it, wxControl class is not compiled) // // Default is 1 // // Recommended setting: 1 (don't change except for very special programs) #define wxUSE_CONTROLS 1 // wxPopupWindow class is a top level transient window. It is currently used // to implement wxTipWindow // // Default is 1 // // Recommended setting: 1 (may be set to 0 if you don't wxUSE_TIPWINDOW) #define wxUSE_POPUPWIN 1 // wxTipWindow allows to implement the custom tooltips, it is used by the // context help classes. Requires wxUSE_POPUPWIN. // // Default is 1 // // Recommended setting: 1 (may be set to 0) #define wxUSE_TIPWINDOW 1 // Each of the settings below corresponds to one wxWidgets control. They are // all switched on by default but may be disabled if you are sure that your // program (including any standard dialogs it can show!) doesn't need them and // if you desperately want to save some space. If you use any of these you must // set wxUSE_CONTROLS as well. // // Default is 1 // // Recommended setting: 1 #define wxUSE_ANIMATIONCTRL 1 // wxAnimationCtrl #define wxUSE_BUTTON 1 // wxButton #define wxUSE_BMPBUTTON 1 // wxBitmapButton #define wxUSE_CALENDARCTRL 1 // wxCalendarCtrl #define wxUSE_CHECKBOX 1 // wxCheckBox #define wxUSE_CHECKLISTBOX 1 // wxCheckListBox (requires wxUSE_OWNER_DRAWN) #define wxUSE_CHOICE 1 // wxChoice #define wxUSE_COLLPANE 1 // wxCollapsiblePane #define wxUSE_COLOURPICKERCTRL 1 // wxColourPickerCtrl #define wxUSE_COMBOBOX 1 // wxComboBox #define wxUSE_DATAVIEWCTRL 0 // wxDataViewCtrl #define wxUSE_DATEPICKCTRL 1 // wxDatePickerCtrl #define wxUSE_DIRPICKERCTRL 1 // wxDirPickerCtrl #define wxUSE_FILEPICKERCTRL 1 // wxFilePickerCtrl #define wxUSE_FONTPICKERCTRL 0 // wxFontPickerCtrl #define wxUSE_GAUGE 1 // wxGauge #define wxUSE_HYPERLINKCTRL 1 // wxHyperlinkCtrl #define wxUSE_LISTBOX 1 // wxListBox #define wxUSE_LISTCTRL 1 // wxListCtrl #define wxUSE_RADIOBOX 1 // wxRadioBox #define wxUSE_RADIOBTN 1 // wxRadioButton #define wxUSE_SCROLLBAR 1 // wxScrollBar #define wxUSE_SEARCHCTRL 1 // wxSearchCtrl #define wxUSE_SLIDER 1 // wxSlider #define wxUSE_SPINBTN 1 // wxSpinButton #define wxUSE_SPINCTRL 1 // wxSpinCtrl #define wxUSE_STATBOX 1 // wxStaticBox #define wxUSE_STATLINE 1 // wxStaticLine #define wxUSE_STATTEXT 1 // wxStaticText #define wxUSE_STATBMP 1 // wxStaticBitmap #define wxUSE_TEXTCTRL 1 // wxTextCtrl #define wxUSE_TOGGLEBTN 1 // requires wxButton #define wxUSE_TREECTRL 1 // wxTreeCtrl // Use a status bar class? Depending on the value of wxUSE_NATIVE_STATUSBAR // below either wxStatusBar95 or a generic wxStatusBar will be used. // // Default is 1 // // Recommended setting: 1 #define wxUSE_STATUSBAR 1 // Two status bar implementations are available under Win32: the generic one // or the wrapper around native control. For native look and feel the native // version should be used. // // Default is 1 for the platforms where native status bar is supported. // // Recommended setting: 1 (there is no advantage in using the generic one) #define wxUSE_NATIVE_STATUSBAR 1 // wxToolBar related settings: if wxUSE_TOOLBAR is 0, don't compile any toolbar // classes at all. Otherwise, use the native toolbar class unless // wxUSE_TOOLBAR_NATIVE is 0. // // Default is 1 for all settings. // // Recommended setting: 1 for wxUSE_TOOLBAR and wxUSE_TOOLBAR_NATIVE. #define wxUSE_TOOLBAR 1 #define wxUSE_TOOLBAR_NATIVE 1 // wxNotebook is a control with several "tabs" located on one of its sides. It // may be used to logically organise the data presented to the user instead of // putting everything in one huge dialog. It replaces wxTabControl and related // classes of wxWin 1.6x. // // Default is 1. // // Recommended setting: 1 #define wxUSE_NOTEBOOK 1 // wxListbook control is similar to wxNotebook but uses wxListCtrl instead of // the tabs // // Default is 1. // // Recommended setting: 1 #define wxUSE_LISTBOOK 1 // wxChoicebook control is similar to wxNotebook but uses wxChoice instead of // the tabs // // Default is 1. // // Recommended setting: 1 #define wxUSE_CHOICEBOOK 1 // wxTreebook control is similar to wxNotebook but uses wxTreeCtrl instead of // the tabs // // Default is 1. // // Recommended setting: 1 #define wxUSE_TREEBOOK 1 // wxToolbook control is similar to wxNotebook but uses wxToolBar instead of // tabs // // Default is 1. // // Recommended setting: 1 #define wxUSE_TOOLBOOK 0 // wxTabDialog is a generic version of wxNotebook but it is incompatible with // the new class. It shouldn't be used in new code. // // Default is 0. // // Recommended setting: 0 (use wxNotebook) #define wxUSE_TAB_DIALOG 0 // wxGrid class // // Default is 1, set to 0 to cut down compilation time and binaries size if you // don't use it. // // Recommended setting: 1 // #define wxUSE_GRID 0 // wxMiniFrame class: a frame with narrow title bar // // Default is 1. // // Recommended setting: 1 (it doesn't cost almost anything) #define wxUSE_MINIFRAME 1 // wxComboCtrl and related classes: combobox with custom popup window and // not necessarily a listbox. // // Default is 1. // // Recommended setting: 1 but can be safely set to 0 except for wxUniv where it // it used by wxComboBox #define wxUSE_COMBOCTRL 1 // wxOwnerDrawnComboBox is a custom combobox allowing to paint the combobox // items. // // Default is 1. // // Recommended setting: 1 but can be safely set to 0, except where it is // needed as a base class for generic wxBitmapComboBox. #define wxUSE_ODCOMBOBOX 1 // wxBitmapComboBox is a combobox that can have images in front of text items. // // Default is 1. // // Recommended setting: 1 but can be safely set to 0 #define wxUSE_BITMAPCOMBOBOX 1 // ---------------------------------------------------------------------------- // Miscellaneous GUI stuff // ---------------------------------------------------------------------------- // wxAcceleratorTable/Entry classes and support for them in wxMenu(Bar) #define wxUSE_ACCEL 1 // Hotkey support (currently Windows only) #define wxUSE_HOTKEY 1 // Use wxCaret: a class implementing a "cursor" in a text control (called caret // under Windows). // // Default is 1. // // Recommended setting: 1 (can be safely set to 0, not used by the library) #define wxUSE_CARET 1 // Use wxDisplay class: it allows enumerating all displays on a system and // their geometries as well as finding the display on which the given point or // window lies. // // Default is 1. // // Recommended setting: 1 if you need it, can be safely set to 0 otherwise #define wxUSE_DISPLAY 0 // Miscellaneous geometry code: needed for Canvas library #define wxUSE_GEOMETRY 1 // Use wxImageList. This class is needed by wxNotebook, wxTreeCtrl and // wxListCtrl. // // Default is 1. // // Recommended setting: 1 (set it to 0 if you don't use any of the controls // enumerated above, then this class is mostly useless too) #define wxUSE_IMAGLIST 1 // Use wxMenu, wxMenuBar, wxMenuItem. // // Default is 1. // // Recommended setting: 1 (can't be disabled under MSW) #define wxUSE_MENUS 1 // Use wxSashWindow class. // // Default is 1. // // Recommended setting: 1 #define wxUSE_SASH 0 // Use wxSplitterWindow class. // // Default is 1. // // Recommended setting: 1 #define wxUSE_SPLITTER 0 // Use wxToolTip and wxWindow::Set/GetToolTip() methods. // // Default is 1. // // Recommended setting: 1 #define wxUSE_TOOLTIPS 1 // wxValidator class and related methods #define wxUSE_VALIDATORS 0 // ---------------------------------------------------------------------------- // common dialogs // ---------------------------------------------------------------------------- // On rare occasions (e.g. using DJGPP) may want to omit common dialogs (e.g. // file selector, printer dialog). Switching this off also switches off the // printing architecture and interactive wxPrinterDC. // // Default is 1 // // Recommended setting: 1 (unless it really doesn't work) #define wxUSE_COMMON_DIALOGS 1 // wxBusyInfo displays window with message when app is busy. Works in same way // as wxBusyCursor #define wxUSE_BUSYINFO 1 // Use single/multiple choice dialogs. // // Default is 1 // // Recommended setting: 1 (used in the library itself) #define wxUSE_CHOICEDLG 1 // Use colour picker dialog // // Default is 1 // // Recommended setting: 1 #define wxUSE_COLOURDLG 1 // wxDirDlg class for getting a directory name from user #define wxUSE_DIRDLG 1 // TODO: setting to choose the generic or native one // Use file open/save dialogs. // // Default is 1 // // Recommended setting: 1 (used in many places in the library itself) #define wxUSE_FILEDLG 1 // Use find/replace dialogs. // // Default is 1 // // Recommended setting: 1 (but may be safely set to 0) #define wxUSE_FINDREPLDLG 0 // Use font picker dialog // // Default is 1 // // Recommended setting: 1 (used in the library itself) #define wxUSE_FONTDLG 1 // Use wxMessageDialog and wxMessageBox. // // Default is 1 // // Recommended setting: 1 (used in the library itself) #define wxUSE_MSGDLG 1 // progress dialog class for lengthy operations #define wxUSE_PROGRESSDLG 1 // support for startup tips (wxShowTip &c) #define wxUSE_STARTUP_TIPS 1 // text entry dialog and wxGetTextFromUser function #define wxUSE_TEXTDLG 1 // number entry dialog #define wxUSE_NUMBERDLG 0 // splash screen class #define wxUSE_SPLASH 1 // wizards #define wxUSE_WIZARDDLG 1 // Compile in wxAboutBox() function showing the standard "About" dialog. // // Default is 1 // // Recommended setting: 1 but can be set to 0 to save some space if you don't // use this function #define wxUSE_ABOUTDLG 0 // ---------------------------------------------------------------------------- // Metafiles support // ---------------------------------------------------------------------------- // Windows supports the graphics format known as metafile which is, though not // portable, is widely used under Windows and so is supported by wxWin (under // Windows only, of course). Win16 (Win3.1) used the so-called "Window // MetaFiles" or WMFs which were replaced with "Enhanced MetaFiles" or EMFs in // Win32 (Win9x, NT, 2000). Both of these are supported in wxWin and, by // default, WMFs will be used under Win16 and EMFs under Win32. This may be // changed by setting wxUSE_WIN_METAFILES_ALWAYS to 1 and/or setting // wxUSE_ENH_METAFILE to 0. You may also set wxUSE_METAFILE to 0 to not compile // in any metafile related classes at all. // // Default is 1 for wxUSE_ENH_METAFILE and 0 for wxUSE_WIN_METAFILES_ALWAYS. // // Recommended setting: default or 0 for everything for portable programs. #define wxUSE_METAFILE 1 #define wxUSE_ENH_METAFILE 1 #define wxUSE_WIN_METAFILES_ALWAYS 0 // ---------------------------------------------------------------------------- // Big GUI components // ---------------------------------------------------------------------------- // Set to 0 to disable MDI support. // // Requires wxUSE_NOTEBOOK under platforms other than MSW. // // Default is 1. // // Recommended setting: 1, can be safely set to 0. #define wxUSE_MDI 0 // Set to 0 to disable document/view architecture #define wxUSE_DOC_VIEW_ARCHITECTURE 1 // Set to 0 to disable MDI document/view architecture // // Requires wxUSE_MDI && wxUSE_DOC_VIEW_ARCHITECTURE #define wxUSE_MDI_ARCHITECTURE 0 // Set to 0 to disable print/preview architecture code #define wxUSE_PRINTING_ARCHITECTURE 0 // wxHTML sublibrary allows to display HTML in wxWindow programs and much, // much more. // // Default is 1. // // Recommended setting: 1 (wxHTML is great!), set to 0 if you want compile a // smaller library. #define wxUSE_HTML 0 // Setting wxUSE_GLCANVAS to 1 enables OpenGL support. You need to have OpenGL // headers and libraries to be able to compile the library with wxUSE_GLCANVAS // set to 1. Note that for some compilers (notably Microsoft Visual C++) you // will need to manually add opengl32.lib and glu32.lib to the list of // libraries linked with your program if you use OpenGL. // // Default is 0. // // Recommended setting: 1 if you intend to use OpenGL, 0 otherwise #define wxUSE_GLCANVAS 0 // wxRichTextCtrl allows editing of styled text. // // Default is 1. // // Recommended setting: 1, set to 0 if you want compile a // smaller library. #define wxUSE_RICHTEXT 1 // ---------------------------------------------------------------------------- // Data transfer // ---------------------------------------------------------------------------- // Use wxClipboard class for clipboard copy/paste. // // Default is 1. // // Recommended setting: 1 #define wxUSE_CLIPBOARD 1 // Use wxDataObject and related classes. Needed for clipboard and OLE drag and // drop // // Default is 1. // // Recommended setting: 1 #define wxUSE_DATAOBJ 1 // Use wxDropTarget and wxDropSource classes for drag and drop (this is // different from "built in" drag and drop in wxTreeCtrl which is always // available). Requires wxUSE_DATAOBJ. // // Default is 1. // // Recommended setting: 1 #define wxUSE_DRAG_AND_DROP 1 // Use wxAccessible for enhanced and customisable accessibility. // Depends on wxUSE_OLE. // // Default is 0. // // Recommended setting (at present): 0 #define wxUSE_ACCESSIBILITY 0 // ---------------------------------------------------------------------------- // miscellaneous settings // ---------------------------------------------------------------------------- // wxSingleInstanceChecker class allows to verify at startup if another program // instance is running (it is only available under Win32) // // Default is 1 // // Recommended setting: 1 (the class is tiny, disabling it won't save much // space) #define wxUSE_SNGLINST_CHECKER 0 #define wxUSE_DRAGIMAGE 1 #define wxUSE_IPC 0 // 0 for no interprocess comms #define wxUSE_HELP 1 // 0 for no help facility // Should we use MS HTML help for wxHelpController? If disabled, neither // wxCHMHelpController nor wxBestHelpController are available. // // Default is 1 under MSW, 0 is always used for the other platforms. // // Recommended setting: 1, only set to 0 if you have trouble compiling // wxCHMHelpController (could be a problem with really ancient compilers) #define wxUSE_MS_HTML_HELP 0 // Use wxHTML-based help controller? #define wxUSE_WXHTML_HELP 0 #define wxUSE_RESOURCES 0 // 0 for no wxGetResource/wxWriteResource #define wxUSE_CONSTRAINTS 0 // 0 for no window layout constraint system #define wxUSE_SPLINES 1 // 0 for no splines #define wxUSE_MOUSEWHEEL 1 // Include mouse wheel support // ---------------------------------------------------------------------------- // postscript support settings // ---------------------------------------------------------------------------- // Set to 1 for PostScript device context. #define wxUSE_POSTSCRIPT 0 // Set to 1 to use font metric files in GetTextExtent #define wxUSE_AFM_FOR_POSTSCRIPT 0 // ---------------------------------------------------------------------------- // database classes // ---------------------------------------------------------------------------- // Define 1 to use ODBC classes #define wxUSE_ODBC 0 // For backward compatibility reasons, this parameter now only controls the // default scrolling method used by cursors. This default behavior can be // overriden by setting the second param of wxDB::wxDbGetConnection() or // wxDb() constructor to indicate whether the connection (and any wxDbTable()s // that use the connection) should support forward only scrolling of cursors, // or both forward and backward support for backward scrolling cursors is // dependent on the data source as well as the ODBC driver being used. #define wxODBC_FWD_ONLY_CURSORS 0 // Default is 0. Set to 1 to use the deprecated classes, enum types, function, // member variables. With a setting of 1, full backward compatibility with the // 2.0.x release is possible. It is STRONGLY recommended that this be set to 0, // as future development will be done only on the non-deprecated // functions/classes/member variables/etc. #define wxODBC_BACKWARD_COMPATABILITY 0 // ---------------------------------------------------------------------------- // other compiler (mis)features // ---------------------------------------------------------------------------- // Set this to 0 if your compiler can't cope with omission of prototype // parameters. // // Default is 1. // // Recommended setting: 1 (should never need to set this to 0) #define REMOVE_UNUSED_ARG 1 // VC++ 4.2 and above allows <iostream> and <iostream.h> but you can't mix // them. Set to 1 for <iostream.h>, 0 for <iostream>. Note that VC++ 7.1 // and later doesn't support wxUSE_IOSTREAMH == 1 and so <iostream> will be // used anyhow. // // Default is 1. // // Recommended setting: whatever your compiler likes more #define wxUSE_IOSTREAMH 1 // ---------------------------------------------------------------------------- // image format support // ---------------------------------------------------------------------------- // wxImage supports many different image formats which can be configured at // compile-time. BMP is always supported, others are optional and can be safely // disabled if you don't plan to use images in such format sometimes saving // substantial amount of code in the final library. // // Some formats require an extra library which is included in wxWin sources // which is mentioned if it is the case. // Set to 1 for wxImage support (recommended). #define wxUSE_IMAGE 1 // Set to 1 for PNG format support (requires libpng). Also requires wxUSE_ZLIB. #define wxUSE_LIBPNG 1 // Set to 1 for JPEG format support (requires libjpeg) #define wxUSE_LIBJPEG 1 // Set to 1 for TIFF format support (requires libtiff) #define wxUSE_LIBTIFF 0 // Set to 1 for TGA format support (loading only) #define wxUSE_TGA 1 // Set to 1 for GIF format support #define wxUSE_GIF 0 // Set to 1 for PNM format support #define wxUSE_PNM 0 // Set to 1 for PCX format support #define wxUSE_PCX 0 // Set to 1 for IFF format support (Amiga format) #define wxUSE_IFF 0 // Set to 1 for XPM format support #define wxUSE_XPM 0 // Set to 1 for MS Icons and Cursors format support #define wxUSE_ICO_CUR 1 // Set to 1 to compile in wxPalette class #define wxUSE_PALETTE 1 // ---------------------------------------------------------------------------- // wxUniversal-only options // ---------------------------------------------------------------------------- // Set to 1 to enable compilation of all themes, this is the default #define wxUSE_ALL_THEMES 1 // Set to 1 to enable the compilation of individual theme if wxUSE_ALL_THEMES // is unset, if it is set these options are not used; notice that metal theme // uses Win32 one #define wxUSE_THEME_GTK 0 #define wxUSE_THEME_METAL 0 #define wxUSE_THEME_MONO 0 #define wxUSE_THEME_WIN32 0 /* --- end common options --- */ // ---------------------------------------------------------------------------- // Windows-only settings // ---------------------------------------------------------------------------- // Set wxUSE_UNICODE_MSLU to 1 if you're compiling wxWidgets in Unicode mode // and want to run your programs under Windows 9x and not only NT/2000/XP. // This setting enables use of unicows.dll from MSLU (MS Layer for Unicode, see // http://www.microsoft.com/globaldev/handson/dev/mslu_announce.mspx). Note // that you will have to modify the makefiles to include unicows.lib import // library as the first library (see installation instructions in install.txt // to learn how to do it when building the library or samples). // // If your compiler doesn't have unicows.lib, you can get a version of it at // http://libunicows.sourceforge.net // // Default is 0 // // Recommended setting: 0 (1 if you want to deploy Unicode apps on 9x systems) #ifndef wxUSE_UNICODE_MSLU #define wxUSE_UNICODE_MSLU 0 #endif // Set this to 1 if you want to use wxWidgets and MFC in the same program. This // will override some other settings (see below) // // Default is 0. // // Recommended setting: 0 unless you really have to use MFC #define wxUSE_MFC 0 // Set this to 1 for generic OLE support: this is required for drag-and-drop, // clipboard, OLE Automation. Only set it to 0 if your compiler is very old and // can't compile/doesn't have the OLE headers. // // Default is 1. // // Recommended setting: 1 #define wxUSE_OLE 1 // Set this to 1 to enable wxAutomationObject class. // // Default is 1. // // Recommended setting: 1 if you need to control other applications via OLE // Automation, can be safely set to 0 otherwise #define wxUSE_OLE_AUTOMATION 0 // Set this to 1 to enable wxActiveXContainer class allowing to embed OLE // controls in wx. // // Default is 1. // // Recommended setting: 1, required by wxMediaCtrl #define wxUSE_ACTIVEX 0 // wxDC cacheing implementation #define wxUSE_DC_CACHEING 1 // Set this to 1 to enable the use of DIB's for wxBitmap to support // bitmaps > 16MB on Win95/98/Me. Set to 0 to use DDB's only. #define wxUSE_DIB_FOR_BITMAP 0 // Set this to 1 to enable wxDIB class used internally for manipulating // wxBitmao data. // // Default is 1, set it to 0 only if you don't use wxImage neither // // Recommended setting: 1 (without it conversion to/from wxImage won't work) #define wxUSE_WXDIB 1 // Set to 0 to disable PostScript print/preview architecture code under Windows // (just use Windows printing). #define wxUSE_POSTSCRIPT_ARCHITECTURE_IN_MSW 0 // Set this to 1 to use RICHEDIT controls for wxTextCtrl with style wxTE_RICH // which allows to put more than ~32Kb of text in it even under Win9x (NT // doesn't have such limitation). // // Default is 1 for compilers which support it // // Recommended setting: 1, only set it to 0 if your compiler doesn't have // or can't compile <richedit.h> #define wxUSE_RICHEDIT 1 // Set this to 1 to use extra features of richedit v2 and later controls // // Default is 1 for compilers which support it // // Recommended setting: 1 #define wxUSE_RICHEDIT2 1 // Set this to 1 to enable support for the owner-drawn menu and listboxes. This // is required by wxUSE_CHECKLISTBOX. // // Default is 1. // // Recommended setting: 1, set to 0 for a small library size reduction #define wxUSE_OWNER_DRAWN 1 // Set to 1 to compile MS Windows XP theme engine support #define wxUSE_UXTHEME 1 // Set to 1 to auto-adapt to MS Windows XP themes where possible // (notably, wxNotebook pages) #define wxUSE_UXTHEME_AUTO 1 // Set to 1 to use InkEdit control (Tablet PC), if available // PCSX2 note: Warning!! Causes crashes on Vista/Win7 if a user has a tablet connected. --air // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=435344 #define wxUSE_INKEDIT 0 // ---------------------------------------------------------------------------- // Generic versions of native controls // ---------------------------------------------------------------------------- // Set this to 1 to be able to use wxDatePickerCtrlGeneric in addition to the // native wxDatePickerCtrl // // Default is 0. // // Recommended setting: 0, this is mainly used for testing #define wxUSE_DATEPICKCTRL_GENERIC 0 // ---------------------------------------------------------------------------- // Crash debugging helpers // ---------------------------------------------------------------------------- // Set this to 1 to be able to use wxCrashReport::Generate() to create mini // dumps of your program when it crashes (or at any other moment) // // Default is 1 if supported by the compiler (VC++ and recent BC++ only). // // Recommended setting: 1, set to 0 if your programs never crash #define wxUSE_CRASHREPORT 0 // ---------------------------------------------------------------------------- // obsolete settings // ---------------------------------------------------------------------------- // NB: all settings in this section are obsolete and should not be used/changed // at all, they will disappear // Define 1 to use bitmap messages. #define wxUSE_BITMAP_MESSAGE 1 #endif // _WX_SETUP_H_
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 1365 ] ] ]
2c602c635bbdc4c83a520a73809e63482785d11d
62207628c4869e289975cc56be76339a31525c5d
/Source/Star Foxes Skeleton/mainShipClass.cpp
e396e6d4aa24376403b5499ed90c09251c6ae714
[]
no_license
dieno/star-foxes
f596e5c6b548fa5bb4f5d716b73df6285b2ce10e
eb6a12c827167fd2b7dd63ce19a1f15d7b7763f8
refs/heads/master
2021-01-01T16:39:47.800555
2011-05-29T03:51:35
2011-05-29T03:51:35
32,129,303
0
0
null
null
null
null
UTF-8
C++
false
false
12,726
cpp
#include "mainShipClass.h" #include "directXClass.h" float MainShipClass::afterburnerSpeed_ = 5.0f; /* D3DXVECTOR3 MainShipClass::vRight_ = D3DXVECTOR3(1.0f,0.0f,0.0f); D3DXVECTOR3 MainShipClass::vUp_ = D3DXVECTOR3(0.0f,1.0f,0.0f); D3DXVECTOR3 MainShipClass::vDirection_ = D3DXVECTOR3(0.0f,0.0f,1.0f); */ void MainShipClass::Draw(D3DXMATRIX mView, bool displayHealth) { renderSelf(); drawProjectiles(); if(displayHealth) drawHealthbar(mView); } void MainShipClass::renderSelf() { if(!isBlinkedOut) { // Setup the world, view, and projection matrices setupWorld(); // Meshes are divided into subsets, one for each material. Render them in // a loop for( DWORD i=0; i<g_dwNumMaterials; i++ ) { // Set the material and texture for this subset g_pDevice->SetMaterial( &g_pMeshMaterials[i] ); g_pDevice->SetTexture( 0, g_pMeshTextures[i] ); // Draw the mesh subset g_pMesh->DrawSubset( i ); } } } void MainShipClass::Update(float timeDelta) { if (blinkState != 0 && timeGetTime() - blinkStartTime > 100.0f) { isBlinkedOut = false; blinkStartTime = timeGetTime(); blinkState == 1; //directXClass::SetError(TEXT("end blink!")); } else if (blinkState == 1 && timeGetTime() - blinkStartTime > 100.0f) { isBlinkedOut = true; blinkStartTime = timeGetTime(); blinkState == 2; //directXClass::SetError(TEXT("end blink!")); } else if (blinkState == 2 && timeGetTime() - blinkStartTime > 100.0f) { isBlinkedOut = false; //blinkStartTime = timeGetTime(); blinkState == 0; //directXClass::SetError(TEXT("end blink!")); } //directXClass::SetError(TEXT("curTime: %f startTime: %f"), timeGetTime(), blinkStartTime); D3DXVECTOR3 vRotationAmount(0.0f, 0.0f, 0.0f); vRotationAmount = vRotation_ * RotationRate_ * timeDelta; //if(vUp_.y < 0) //vRotationAmount.x = -vRotationAmount.x; yaw(vRotationAmount.x); pitch(vRotationAmount.y); //directXClass::SetError(TEXT("vRot: x: %f, y: %f, z: %f"),vRotationAmount.x,vRotationAmount.y,vRotationAmount.z); //updateRotation(&vRotationAmount); D3DXVECTOR3 force = vDirection_ * thrustAmount_ * MaxForce_; D3DXVECTOR3 acceleration = force / Mass_; vVelocity_ += acceleration * timeDelta; vVelocity_ *= Drag_; vPosition_ += vVelocity_ * timeDelta; updateProjectiles(timeDelta); updateHealthbar(); } void MainShipClass::updateRotation(D3DXVECTOR3 *vRotation) { if((*vRotation).z != 0.0f) { if((*vRotation).z < 0.0f) { (*vRotation).z += 0.01f; if((*vRotation).z >= 0.01f) (*vRotation).z = 0.0f; } else { (*vRotation).z -= 0.01f; if((*vRotation).z <= 0.01f) (*vRotation).z = 0.0f; } if((*vRotation).z > D3DX_PI) (*vRotation).z = -D3DX_PI; if((*vRotation).z < -D3DX_PI) (*vRotation).z = D3DX_PI; } if((*vRotation).x != 0.0f) { if((*vRotation).x < 0.0f) { (*vRotation).x += 0.01f; if((*vRotation).x >= 0.01f) (*vRotation).x = 0.0f; } else { (*vRotation).x -= 0.01f; if((*vRotation).x <= 0.01f) (*vRotation).x = 0.0f; } if((*vRotation).x > D3DX_PI) (*vRotation).x = -D3DX_PI; if((*vRotation).x < -D3DX_PI) (*vRotation).x = D3DX_PI; } } void MainShipClass::pitch(float angle) { D3DXQUATERNION Q; D3DXQuaternionRotationAxis(&Q, &vRight_, angle); D3DXMATRIX T; D3DXMatrixRotationQuaternion(&T, &Q); D3DXVec3TransformCoord(&vUp_, &vUp_, &T); D3DXVec3TransformCoord(&vDirection_, &vDirection_, &T); } void MainShipClass::yaw(float angle) { D3DXQUATERNION Q; D3DXQuaternionRotationAxis(&Q, &vUp_, angle); D3DXMATRIX T; D3DXMatrixRotationQuaternion(&T, &Q); D3DXVec3TransformCoord(&vRight_, &vRight_, &T); D3DXVec3TransformCoord(&vDirection_, &vDirection_, &T); } void MainShipClass::roll(float angle) { D3DXQUATERNION Q; D3DXQuaternionRotationAxis(&Q, &vDirection_, angle); D3DXMATRIX T; D3DXMatrixRotationQuaternion(&T, &Q); D3DXVec3TransformCoord(&vRight_, &vRight_, &T); D3DXVec3TransformCoord(&vUp_, &vUp_, &T); } void MainShipClass::updateWorldMatrix() { D3DXVec3Normalize(&vDirection_, &vDirection_); D3DXVec3Cross(&vUp_, &vDirection_, &vRight_); D3DXVec3Normalize(&vUp_, &vUp_); D3DXVec3Cross(&vRight_, &vUp_, &vDirection_); D3DXVec3Normalize(&vRight_, &vRight_); //directXClass::SetError(TEXT("up: X: %f, Y: %f, Z: %f dir: X: %f, Y: %f, Z: %f right: X: %f, Y: %f, Z: %f"), vUp_.x, vUp_.y, vUp_.z, vDirection_.x, vDirection_.y, vDirection_.z, vRight_.x, vRight_.y, vRight_.z); //directXClass::SetError(TEXT("----------------------")); D3DXMATRIX mScale; D3DXMatrixIdentity(&mScale); D3DXMatrixScaling(&mScale, vScale_.x, vScale_.y, vScale_.z); D3DXMATRIX mRotate; D3DXMatrixIdentity(&mRotate); mRotate(0, 0) = vRight_.x; mRotate(0, 1) = vUp_.x; mRotate(0, 2) = vDirection_.x; mRotate(0, 3) = 0.0f; mRotate(1, 0) = vRight_.y; mRotate(1, 1) = vUp_.y; mRotate(1, 2) = vDirection_.y; mRotate(1, 3) = 0.0f; mRotate(2, 0) = vRight_.z; mRotate(2, 1) = vUp_.z; mRotate(2, 2) = vDirection_.z; mRotate(2, 3) = 0.0f; mRotate(3, 0) = 0.0f; mRotate(3, 1) = 0.0f; mRotate(3, 2) = 0.0f; mRotate(3, 3) = 1.0f; D3DXMATRIX mTransposedRotate; D3DXMatrixTranspose(&mTransposedRotate, &mRotate); D3DXMATRIX mTranslate; D3DXMatrixIdentity(&mTranslate); D3DXMatrixTranslation(&mTranslate, vPosition_.x, vPosition_.y, vPosition_.z); mWorld_ = mScale * mTransposedRotate * mTranslate;//mScale * mRotate ; shipBound.drawNodes(mWorld_, vPosition_); } void MainShipClass::setupWorld() { updateWorldMatrix(); g_pDevice->SetTransform(D3DTS_WORLD, &mWorld_); shipBound.drawNodes(mWorld_, vPosition_); D3DXMatrixIdentity(&mWorld_); } void MainShipClass::reset() { vScale_ = D3DXVECTOR3(1.0f, 1.0f, 1.0f); vPosition_ = D3DXVECTOR3(0.0f, 0.0f, 0.0f); vRotation_ = D3DXVECTOR3(0.0f, 0.0f, 0.0f); vDirection_ = D3DXVECTOR3(0.0f, 0.0f, 1.0f); vUp_ = D3DXVECTOR3(0.0f, 1.0f, 0.0f); vRight_ = D3DXVECTOR3(1.0f, 0.0f, 0.0f); vVelocity_ = D3DXVECTOR3(0.0f, 0.0f, 0.0f); D3DXMatrixIdentity(&mWorld_); } void MainShipClass::bankRight(bool active) { if(active) { vRotation_.x = 1.0f; //directXClass::SetError(TEXT("up: X: %f, Y: %f, Z: %f dir: X: %f, Y: %f, Z: %f right: X: %f, Y: %f, Z: %f"), vUp_.x, vUp_.y, vUp_.z, vDirection_.x, vDirection_.y, vDirection_.z, vRight_.x, vRight_.y, vRight_.z); } else { vRotation_.x = 0.0f; } } void MainShipClass::bankLeft(bool active) { if(active) { vRotation_.x = -1.0f; //directXClass::SetError(TEXT("up: X: %f, Y: %f, Z: %f dir: X: %f, Y: %f, Z: %f right: X: %f, Y: %f, Z: %f"), vUp_.x, vUp_.y, vUp_.z, vDirection_.x, vDirection_.y, vDirection_.z, vRight_.x, vRight_.y, vRight_.z); } else { vRotation_.x = 0.0f; } } void MainShipClass::bankUp(bool active) { if(active) { if(Y_AXIS_INVERTED) vRotation_.y = -1.0f; else vRotation_.y = 1.0f; // directXClass::SetError(TEXT("up: X: %f, Y: %f, Z: %f dir: X: %f, Y: %f, Z: %f right: X: %f, Y: %f, Z: %f"), vUp_.x, vUp_.y, vUp_.z, vDirection_.x, vDirection_.y, vDirection_.z, vRight_.x, vRight_.y, vRight_.z); } else { vRotation_.y = 0.0f; } } void MainShipClass::bankDown(bool active) { if(active) { if(Y_AXIS_INVERTED) vRotation_.y = 1.0f; else vRotation_.y = -1.0f; //directXClass::SetError(TEXT("up: X: %f, Y: %f, Z: %f dir: X: %f, Y: %f, Z: %f right: X: %f, Y: %f, Z: %f"), vUp_.x, vUp_.y, vUp_.z, vDirection_.x, vDirection_.y, vDirection_.z, vRight_.x, vRight_.y, vRight_.z); } else { vRotation_.y = 0.0f; } } void MainShipClass::boost(bool active) { if(active) { thrustAmount_ = 0.001f; //directXClass::SetError(TEXT("up: X: %f, Y: %f, Z: %f dir: X: %f, Y: %f, Z: %f right: X: %f, Y: %f, Z: %f"), vUp_.x, vUp_.y, vUp_.z, vDirection_.x, vDirection_.y, vDirection_.z, vRight_.x, vRight_.y, vRight_.z); } else { thrustAmount_ = 0.000f; } } void MainShipClass::loadProjectile(LPD3DXMESH mesh, D3DMATERIAL9* meshMat, LPDIRECT3DTEXTURE9* meshTex, DWORD meshNumMat) { g_pMesh2 = mesh; g_pMeshMaterials2 = g_pMeshMaterials; g_pMeshTextures2 = meshTex; g_dwNumMaterials2 = meshNumMat; } void MainShipClass::shoot(float timeDelta) { if(timeToShoot <= 0.0f) { updateWorldMatrix(); Projectile newProjectile(g_pDevice, g_pMesh2, g_pMeshMaterials2, g_pMeshTextures2, g_dwNumMaterials2, vDirection_, mWorld_); projectileList.push_back(newProjectile); timeToShoot = SHOOT_SPEED; } } void MainShipClass::updateProjectiles(float timeDelta) { timeToShoot -= timeDelta; std::list<Projectile>::iterator it = projectileList.begin(); while(it != projectileList.end()) { (*it).Update(timeDelta); if((*it).getTimeToLive() < 0.0f) { it = projectileList.erase(it); } else { ++it; } } } void MainShipClass::drawProjectiles() { for(std::list<Projectile>::iterator it = projectileList.begin(); it != projectileList.end(); ++it) { (*it).Draw(); } } void MainShipClass::startBlinking() { if(!isBlinkedOut) { blinkStartTime = timeGetTime(); isBlinkedOut = true; blinkState = 8; //directXClass::SetError(TEXT("start blink!")); } } void MainShipClass::initHealthbar() { D3DXCreateTextureFromFile(g_pDevice, TEXT("EnemyHealth.bmp"), &healthbarTex); g_pDevice->SetFVF(CUSTOMFVF); CUSTOMVERTEX vertices[] = { { -1.7f, 1.7f, 0.0f, 0.0f, 0.0f, }, { 1.7f, 1.7f, 0.0f, 1.0f, 0.0f, }, { -1.7f, 1.2f, 0.0f, 0.0f, 1.0f, }, { 1.7f, 1.2f, 0.0f, 1.0f, 1.0f, }, }; // create a vertex buffer interface called i_buffer g_pDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX), 0, CUSTOMFVF, D3DPOOL_MANAGED, &v_buffer, NULL); VOID* pVoid; // a void pointer // lock v_buffer and load the vertices into it v_buffer->Lock(0, 0, (void**)&pVoid, 0); memcpy(pVoid, vertices, sizeof(vertices)); v_buffer->Unlock(); } void MainShipClass::drawHealthbar(D3DXMATRIX mView) { D3DXMATRIX mTranslate; D3DXMatrixTranslation(&mTranslate, vPosition_.x, vPosition_.y, vPosition_.z); D3DXMATRIX orientation; D3DXMatrixInverse(&orientation, NULL, &mView); //view is your camera view matrix. orientation._41=0; orientation._42=0; orientation._43=0; orientation._14=0;orientation._24=0;orientation._34=0;orientation._44=1; //now orientation is the rotation matrix for the cube to keep it facing the camera. //it basicly just "unrotates" g_pDevice->SetMaterial( &g_pMeshMaterials[0] ); g_pDevice->SetTransform(D3DTS_WORLD, &(orientation * mTranslate));//&(mWorld * mTranslate)); g_pDevice->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX)); g_pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } void MainShipClass::updateHealthbar() { currentHealthPos = (((float) currentHealth / (float) maxHealth) * 3.4f) - 1.7f; CUSTOMVERTEX vertices[] = { { -1.7f, 1.7f, 0.0f, 0.0f, 0.0f, }, { currentHealthPos, 1.7f, 0.0f, 1.0f, 0.0f, }, { -1.7f, 1.2f, 0.0f, 0.0f, 1.0f, }, { currentHealthPos, 1.2f, 0.0f, 1.0f, 1.0f, }, }; // create a vertex buffer interface called i_buffer g_pDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX), 0, CUSTOMFVF, D3DPOOL_MANAGED, &v_buffer, NULL); VOID* pVoid; // a void pointer // lock v_buffer and load the vertices into it v_buffer->Lock(0, 0, (void**)&pVoid, 0); memcpy(pVoid, vertices, sizeof(vertices)); v_buffer->Unlock(); } /*void MainShipClass::setupWorld() { D3DXMATRIXA16 rotationY; D3DXMATRIXA16 rotationX; D3DXMATRIXA16 rotationZ; D3DXMATRIXA16 translate; D3DXMATRIXA16 translate2; D3DXMATRIXA16 translate3; D3DXMATRIX scale = directXClass::Translate(0, 0, 0); scale(0,0) = 0.25f; scale(1,1) = 0.25f; scale(2,2) = 0.25f; D3DXMatrixRotationY( &rotationY, rotationAboutYMesh1 ); D3DXMatrixRotationX( &rotationX, rotationAboutXMesh1 ); D3DXMatrixRotationZ( &rotationZ, rotationAboutZMesh1 ); translate = directXClass::Translate(translateXMesh1, translateYMesh1, translateZMesh1); D3DXMatrixTranslation(&translate2, 0.0f, 0.0f, -1.5f); D3DXMatrixTranslation(&translate3, 0.0f, 0.0f, 1.5f); g_pDevice->SetTransform( D3DTS_WORLD, &(translate2 * rotationZ * rotationY * rotationX * translate3 * (scale * translate))); }*/
[ "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a", "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a", "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a", "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a" ]
[ [ [ 1, 4 ], [ 19, 37 ], [ 40, 56 ], [ 293, 293 ], [ 298, 298 ], [ 305, 305 ], [ 350, 358 ], [ 441, 445 ], [ 448, 455 ] ], [ [ 5, 5 ], [ 9, 9 ], [ 182, 183 ], [ 217, 217 ], [ 240, 240 ], [ 253, 253 ], [ 270, 270 ], [ 286, 286 ], [ 299, 299 ] ], [ [ 6, 8 ], [ 10, 18 ], [ 38, 39 ], [ 57, 181 ], [ 184, 203 ], [ 205, 211 ], [ 214, 216 ], [ 218, 239 ], [ 241, 252 ], [ 254, 269 ], [ 271, 285 ], [ 287, 292 ], [ 294, 297 ], [ 300, 304 ], [ 306, 349 ], [ 359, 440 ], [ 446, 447 ], [ 456, 463 ] ], [ [ 204, 204 ], [ 212, 213 ] ] ]
76a445636a5a5046927394cf1c596bef2b5929f8
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/trunk/engine/core/include/MergeableMeshObject.h
4e03132f765afff25ead305e07f2b8db0774d865
[ "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
1,590
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __MergeableMeshObject_H__ #define __MergeableMeshObject_H__ #include "CorePrerequisites.h" #include <map> #include "CoreDefines.h" #include "MeshObject.h" namespace rl { class _RlCoreExport MergeableMeshObject : public MeshObject { public: MergeableMeshObject(const Ogre::String& name, const Ogre::String& meshname); ~MergeableMeshObject(); void addSubmesh(const Ogre::String& partname, const Ogre::String& meshfile); void removeSubmesh(const Ogre::String& partToRemove); void replaceSubmesh(const Ogre::String& partToReplace, const Ogre::String& substituteMeshname); void setBaseMeshPart(const Ogre::String& partname); private: Ogre::MeshPtr mBaseMesh; MeshPartMap mMeshes; Ogre::String mCombinedMeshName; void switchTo(const Ogre::MeshPtr& newMesh); void updateMesh(); }; } #endif //__MergeableMeshObject_H__
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 50 ] ] ]
92e9ce5b7d3782732bce6f8652076d33db2b8719
080941f107281f93618c30a7aa8bec9e8e2d8587
/include/linestrips2lines.h
969d315a92c19971270ceb0e2c96cfc2f07aac9f
[ "MIT" ]
permissive
scoopr/COLLADA_Refinery
6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4
3a5ad1a81e0359f9025953e38e425bc10b5bf6c5
refs/heads/master
2021-01-22T01:55:14.642769
2009-03-10T21:31:04
2009-03-10T21:31:04
194,828
2
0
null
null
null
null
UTF-8
C++
false
false
2,097
h
/* The MIT License Copyright 2006 Sony Computer Entertainment Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __LINESTRIPS2LINES_H__ #define __LINESTRIPS2LINES_H__ // Collada API includes #include "dae.h" #include "dom/domCOLLADA.h" #include "conditionerBase.h" #include "defines.h" //using namespace std; class Linestrips2lines : public ConditionerBase { public: REF_EXPORT bool init(); REF_EXPORT int execute(); REF_EXPORT std::string getBaseName() const { return "Linestrips2lines"; } REF_EXPORT std::string getDescription() const { return "turn all linestrips to lines"; } REF_EXPORT std::string getCategory() const { return "geometry processing"; } }; class Linestrips2linesProxy : public ConditionerCreator { REF_EXPORT std::string getBaseName() const { return "Linestrips2lines"; } REF_EXPORT std::string getDescription() const { return "turn all linestrips to lines"; } REF_EXPORT std::string getCategory() const { return "geometry processing"; } REF_EXPORT Conditioner *create() const { return new Linestrips2lines(); } }; #endif //__LINESTRIPS2LINES_H__
[ "alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4", "sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4" ]
[ [ [ 1, 1 ], [ 23, 54 ] ], [ [ 2, 22 ] ] ]
7d5dc13caff699b10a9dfcea42b4263746a6f28d
9429a0e1b44f45cff3c5272383ee45ba60189226
/stage/ArchivoLexico.h
47526f537bf0d4dcf68f36d979c237bb8077700f
[]
no_license
pablorusso/doogle
b9ffe65f37bf6e745fa40a5d91dac0f7bf9e4c6e
95fe715107e7618c7517bf41d66f2d98e8e8ec57
refs/heads/master
2016-09-06T11:15:26.289325
2006-12-04T15:24:57
2006-12-04T15:24:57
32,188,634
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
h
#ifndef __ARCHIVOLEXICO_H__ #define __ARCHIVOLEXICO_H__ #include <fstream> #include <string> #include "ArchivoConsts.h" #include "LexicoData.h" class ArchivoLexico { private: std::fstream _fstream; std::string _nombre; int _modo; int _posicionSecuencial; int _tamanio; int _cantRegistros; int posicionLogicaAReal( int posicion ); void validarModo( int modoBuscado ); int escribirImpl( LexicoData &data ); void leerImpl( LexicoData& data ); LexicoData *buscarTerminoImpl( string word, LexicoData &foundData, int minimo, int maximo ); public: ArchivoLexico( std::string nombre, int modo ); void comenzarLectura(); void leerPosicion( int posicion, LexicoData &data ); bool leer( LexicoData &data ); int escribirPosicion( int posicion, LexicoData &data ); int escribir( LexicoData &data ); bool fin(); void mergeWith( std::string newLexName, WordPair words, LexicalPair &mergedItems, ArchivoLexico *stopWords ); LexicoData *buscarTermino( string word, LexicoData &foundData ); ~ArchivoLexico(); }; #endif
[ "pablorusso@732baeec-bf1d-0410-89bf-576031c28093" ]
[ [ [ 1, 39 ] ] ]
e32beb039fbbea1aaa29b59c9e642f2c28fad76c
fa134e5f64c51ccc1c2cac9b9cb0186036e41563
/GT/XMLReader.cpp
89c41eb9f3f877bb9a3b41ada22076b2002d44be
[]
no_license
dlsyaim/gradthes
70b626f08c5d64a1d19edc46d67637d9766437a6
db6ba305cca09f273e99febda4a8347816429700
refs/heads/master
2016-08-11T10:44:45.165199
2010-07-19T05:44:40
2010-07-19T05:44:40
36,058,688
0
1
null
null
null
null
UTF-8
C++
false
false
18,696
cpp
#include "stdafx.h" #include <stdio.h> #include <algorithm> #include <atlbase.h> #include <msxml2.h> #include <iostream> #include <GL\gl.h> #include <vector> #include <string> #include <comutil.h> #include "XMLReader.h" #include "Layer.h" #include "Transformation.h" #include "TextureTGA.h" #include "RPM.h" #include "FuelKnob.h" #include "MagneticCompass.h" #include "VerticalVelocityIndicator.h" #include "TurnCoordinator.h" #include "AttitudeGyro.h" #include "DirectionalGyro.h" #include "BrakeIndicator.h" #include "FlapsIndicator.h" #include "Altimeter.h" #include "ControlPositionIndicator.h" #include "AirspeedIndicator.h" #include "Util.h" XMLReader::XMLReader(void) { } XMLReader::~XMLReader(void) { CoUninitialize(); } BOOL XMLReader::initializeParser(void) { try { // Start COM. Must initialize the COM library before they can call COM library functions HRESULT hr = CoInitialize(NULL); if (FAILED(hr)) { throw "Initialize failed"; } // Create an instance of the parser hr = spXMLDOM.CoCreateInstance(__uuidof(DOMDocument)); if (FAILED(hr)) { throw "Unable to create XML parser object"; } if (spXMLDOM.p == NULL) { throw "Unable to create XML parser object"; } return TRUE; } catch (char *lpstrError) { std::cout << lpstrError << std::endl; return FALSE; } } // Load the Panel into memory. void XMLReader::loadPanel(char *szPathName, Panel* pl) { try { // Load the XML document file... VARIANT_BOOL bSuccess = false; HRESULT hr = spXMLDOM->load(CComVariant(szPathName), &bSuccess); if (FAILED(hr)) { throw "Unable to load XML document into the parser"; } if (!bSuccess) { throw "Unable to load XML document into the parser"; } // Construct search string CComBSTR bstrSS(L"PropertyList"); CComPtr<IXMLDOMNode> spXMLNode; CComPtr<IXMLDOMNodeList> spXMLNodeList; hr = spXMLDOM->selectSingleNode(bstrSS, &spXMLNode); if (FAILED(hr)) { throw "Unable to locate PropertyList node"; } if (spXMLNode.p == NULL) { throw "Unable to locate PropertyList node"; } hr = spXMLNode->get_childNodes(&spXMLNodeList); if (FAILED(hr)) { throw "Unable to get the child nodes"; } if (spXMLNodeList.p == NULL) { throw "Unable to get the child nodes"; } long len; hr = spXMLNodeList->get_length(&len); if (FAILED(hr)) { throw "Unable to get the number of children"; } // The name of the element. CComBSTR nodeName; // The value of the element. CComVariant varValue(VT_EMPTY); // If assigned through & operator, then the smart pointer must be NULL. spXMLNode = NULL; while (!FAILED(spXMLNodeList->nextNode(&spXMLNode))) { if (spXMLNode.p == NULL) { break; } hr = spXMLNode->get_nodeName(&nodeName); if (FAILED(hr)) { throw "Unable to get the element name"; } hr = spXMLNode->get_nodeTypedValue(&varValue); if (FAILED(hr)) { throw "Unable to get eh element value"; } // W2T is the original text conversion macros. USES_CONVERSION; LPTSTR lpstrVal = W2T(varValue.bstrVal); if (nodeName == L"name") { pl->setName(lpstrVal); } else if (nodeName == L"background") { pl->setBg(lpstrVal); } else if (nodeName == L"w") { pl->setW(atoi((const char*)lpstrVal)); } else if (nodeName == L"h") { pl->setH(atoi((const char*)lpstrVal)); } else if (nodeName == L"y-offset") { pl->setYoffset(atoi((const char*)lpstrVal)); } else if (nodeName == L"view-height") { pl->setViewHeight(atoi((const char*)lpstrVal)); } // This line is very important. spXMLNode must be set to NULL. spXMLNode = NULL; } // Load instruments loadInstruments("PropertyList/instruments/instrument", pl->getInLi()); } catch (char *lpstrError){ std::cout << lpstrError << std::endl; } catch (...) { std::cout << "Unknown error in loading Panel" << std::endl; } } // Load instruments belonging to one Panel. void XMLReader::loadInstruments(char *szQueryString, instrumentList* inLi) { try { // Construct search string CComBSTR bstrSS (szQueryString); // Declare some variables. CComPtr<IXMLDOMNode> spXMLNode; CComPtr<IXMLDOMNodeList> spXMLNodeList; HRESULT hr = spXMLDOM->selectNodes(bstrSS, &spXMLNodeList); if (FAILED(hr)) { throw "Unable to locate PropertyList/instruments/instrument nodes"; } if (spXMLNodeList.p == NULL) { throw "Unable to locate PropertyList/instruments/instrument nodes"; } long numOfInst; hr = spXMLNodeList->get_length(&numOfInst); if (FAILED(hr)) { throw "Unable to get the length of the node list"; } // The name of the attributes. CComBSTR attrName(L"include"); CComBSTR nodeName; CComVariant varValue(VT_EMPTY); // Iterate the node list CComPtr<IXMLDOMNode> spXMLChildNode; CComPtr<IXMLDOMNodeList> spXMLChildNodeList; CComPtr<IXMLDOMElement> spXMLElement; spXMLNode = NULL; while (!FAILED(spXMLNodeList->nextNode(&spXMLNode))) { if (spXMLNode.p == NULL) { break; } Instrument* intr; spXMLElement = spXMLNode; if (spXMLElement.p == NULL) { throw "Unable to convert node to element"; } hr = spXMLElement->getAttribute(attrName, &varValue); if (FAILED(hr)) { throw "Unable to get the value of the attribute"; } USES_CONVERSION; LPTSTR attrLVal = W2T(varValue.bstrVal); hr = spXMLNode->get_childNodes(&spXMLChildNodeList); if (FAILED(hr)) { throw "Unable to get the child node list"; } spXMLChildNode = NULL; while (!FAILED(spXMLChildNodeList->nextNode(&spXMLChildNode))) { if (spXMLChildNode.p == NULL) { break; } hr = spXMLChildNode->get_nodeName(&nodeName); hr = spXMLChildNode->get_nodeTypedValue(&varValue); USES_CONVERSION; LPTSTR lpstrVal = W2T(varValue.bstrVal); if (nodeName == L"name") { if (!strcmp((const char*)lpstrVal, "RPM Gauge")) { intr = new RPM(); } else if (!strcmp((const char*)lpstrVal, "Fuel Mixture Knob")) { intr = new FuelKnob(); } else if (!strcmp((const char*)lpstrVal, "Flaps Control")) { intr = new FlapsIndicator(); } else if (!strcmp((const char*)lpstrVal, "Brake Indicator Light")) { intr = new BrakeIndicator(); } else if (!strcmp((const char*)lpstrVal, "Control Position Indicators")) { intr = new ControlPositionIndicator(); } else if (!strcmp((const char*)lpstrVal, "Airspeed Indicator")) { intr = new AirspeedIndicator(); } else if (!strcmp((const char*)lpstrVal, "Attitude Gyro")) { intr = new AttitudeGyro(); } else if (!strcmp((const char*)lpstrVal, "Altimeter")) { intr = new Altimeter(); } else if (!strcmp((const char*)lpstrVal, "Turn Coordinator")) { intr = new TurnCoordinator(); } else if (!strcmp((const char*)lpstrVal, "Directional Gyro")) { intr = new DirectionalGyro(); } else if (!strcmp((const char*)lpstrVal, "Vertical Velocity Indicator")) { intr = new VerticalVelocityIndicator(); } else if (!strcmp((const char*)lpstrVal, "Magnetic Compass")) { intr = new MagneticCompass(); } } else if (nodeName == L"x") { intr->setX(atoi((const char*)lpstrVal)); } else if (nodeName == L"y") { intr->setY(atoi((const char*)lpstrVal)); } else if (nodeName == L"w") { intr->setWidth(atoi((const char*)lpstrVal)); } else if (nodeName == L"h") { intr->setHeight(atoi((const char*)lpstrVal)); } spXMLChildNode = NULL; } intr->setInPath(attrLVal); inLi->push_back(intr); spXMLChildNodeList = NULL; spXMLNode = NULL; } // Load each Instrument instrumentList::iterator inLiIt; for (inLiIt = inLi->begin(); inLiIt != inLi->end(); inLiIt++) { loadInstrument((*inLiIt)->getInPath().c_str(), (*inLiIt)); } } catch (char *lpstrErr) { // Some error... std::cout << lpstrErr << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } } // Load each instruments. void XMLReader::loadInstrument(const char *szPathName, Instrument *instr) { try { // Load the XML document file... VARIANT_BOOL bSuccess = false; HRESULT hr = spXMLDOM->load(CComVariant(szPathName), &bSuccess); if (FAILED(hr)) { throw "Unable to load XML document into the parser "; } if (!bSuccess) { throw "Unable to load XML document into the parser "; } // Construct search string CComBSTR bstrSS(L"PropertyList"); CComPtr<IXMLDOMNode> spXMLNode; CComPtr<IXMLDOMNodeList> spXMLNodeList; hr = spXMLDOM->selectSingleNode(bstrSS, &spXMLNode); if (FAILED(hr)) { throw "Unable to locate PropertyList"; } if (spXMLNode.p == NULL) { throw "Unable to locate PropertyList"; } hr = spXMLNode->get_childNodes(&spXMLNodeList); if (FAILED(hr)) { throw "Unable to get the node list"; } CComBSTR nodeName; CComVariant nodeValue(VT_EMPTY); spXMLNode = NULL; while (!FAILED(spXMLNodeList->nextNode(&spXMLNode))) { if (spXMLNode.p == NULL) { break; } hr = spXMLNode->get_nodeName(&nodeName); hr = spXMLNode->get_nodeTypedValue(&nodeValue); USES_CONVERSION; LPTSTR lpstrVal = W2T(nodeValue.bstrVal); // We just need name, w-base, h-base. if (nodeName == L"name") { instr->setFullName(lpstrVal); } else if (nodeName == L"w-base") { instr->setW_base(atoi((const char*)lpstrVal)); } else if (nodeName == L"h-base") { instr->setH_base(atoi((const char*)lpstrVal)); } else { break; } spXMLNode = NULL; } // load layers loadLayers("PropertyList/layers/layer", instr, instr->getW_scale(), instr->getH_scale()); } catch (char* lpstrError) { std::cout << lpstrError << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } } // Load all of layers. void XMLReader::loadLayers(char *szQueryString, Instrument* instr, float w_scale, float h_scale) { try { layerList *ll = instr->getLl(); // Construct search string CComBSTR bstrSS(szQueryString); CComPtr<IXMLDOMNode> spXMLNode, spXMLChildNode, spXMLGChildNode; CComPtr<IXMLDOMNodeList> spXMLNodeList, spXMLChildNodeList, spXMLGChildNodeList; HRESULT hr = spXMLDOM->selectNodes(bstrSS, &spXMLNodeList); if (FAILED(hr)) { throw "Unable to locate PropertyList/layers/layer"; } if (spXMLNodeList.p == NULL) { throw "Unable to locate PropertyList/layers/layer"; } CComBSTR nodeName; CComVariant nodeValue(VT_EMPTY); spXMLNode = NULL; while (!FAILED(spXMLNodeList->nextNode(&spXMLNode))) { if (spXMLNode.p == NULL) { break; } Layer *la = new Layer(instr->getWidth(), instr->getHeight()); hr = spXMLNode->get_childNodes(&spXMLChildNodeList); spXMLChildNode = NULL; while (!FAILED(spXMLChildNodeList->nextNode(&spXMLChildNode))) { if (spXMLChildNode.p == NULL) { break; } hr = spXMLChildNode->get_nodeName(&nodeName); hr = spXMLChildNode->get_nodeTypedValue(&nodeValue); USES_CONVERSION; LPTSTR lpstrVal = W2T(nodeValue.bstrVal); if (nodeName == L"name") { la->setName(lpstrVal); } else if (nodeName == L"texture") { spXMLGChildNodeList = NULL; hr = spXMLChildNode->get_childNodes(&spXMLGChildNodeList); while (!FAILED(spXMLGChildNodeList->nextNode(&spXMLGChildNode))){ if (spXMLGChildNode.p == NULL) { break; } hr = spXMLGChildNode->get_nodeTypedValue(&nodeValue); hr = spXMLGChildNode->get_nodeName(&nodeName); USES_CONVERSION; LPTSTR _lpstrVal = W2T(nodeValue.bstrVal); if (nodeName == L"path") { la->getTex()->setPath(_lpstrVal); la->getTex()->loadTexture(); //la->getTex()->loadTexture(texId); } else if (nodeName == L"x1") { la->getTex()->setX1((float)atof((const char*)_lpstrVal)); } else if (nodeName == L"y1") { la->getTex()->setY1((float)atof((const char*)_lpstrVal)); } else if (nodeName == L"x2") { la->getTex()->setX2((float)atof((const char*)_lpstrVal)); } else if (nodeName == L"y2") { la->getTex()->setY2((float)atof((const char*)_lpstrVal)); } spXMLGChildNode = NULL; } } else if (nodeName == L"w") { la->setW((int)(atoi((const char*)lpstrVal) * w_scale)); } else if (nodeName == L"h") { la->setH((int)(atoi((const char*)lpstrVal) * h_scale)); } else if (nodeName == L"transformations") { loadTransformations(spXMLChildNode, la, w_scale, h_scale); } else if (nodeName == L"type") { if (!strcmp((const char*)lpstrVal, "switch")) { la->setType(Layer::SWITCH); loadSwitchLayer(la, w_scale, h_scale); } else if (!strcmp((const char*)lpstrVal, "text")) { la->setType(Layer::TEXT); // Because the text type layer has no textures associating with it, so set the tex member to be NULL la->setTex(NULL); } else if (!strcmp((const char*)lpstrVal, "built-in")) { la->setType(Layer::BUILT_IN); // Because the built-in type layer has no textures associating with it, so set the tex member to be NULL la->setTex(NULL); } } spXMLChildNode = NULL; } ll->push_back(la); spXMLChildNodeList = NULL; spXMLNode = NULL; } // sort the Layer list sort(ll->begin(), ll->end(), descend); } catch (char *lpstrError) { std::cout << lpstrError << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } } // Load switch Layer void XMLReader::loadSwitchLayer(Layer* _la, float w_scale, float h_scale) { try { // Construct the search string. CComBSTR bstrSS(L"PropertyList/layers/layer/layer"); CComPtr<IXMLDOMNode> spXMLNode, spXMLChildNode, spXMLGChildNode; CComPtr<IXMLDOMNodeList> spXMLNodeList, spXMLChildNodeList, spXMLGChildNodeList; HRESULT hr = spXMLDOM->selectNodes(bstrSS, &spXMLNodeList); if (FAILED(hr)) { throw "Unable to locate PropertyList/layers/layer/layer"; } if (spXMLNodeList.p == NULL) { throw "Unable to locate PropertyList/layers/layer/layer"; } layerList* ll = new layerList(); _la->setSwitchLayers(ll); CComBSTR nodeName; CComVariant nodeValue(VT_EMPTY); spXMLNode = NULL; while (!FAILED(spXMLNodeList->nextNode(&spXMLNode))) { if (spXMLNode.p == NULL) { break; } Layer *la = new Layer(_la->getW(), _la->getH()); hr = spXMLNode->get_childNodes(&spXMLChildNodeList); while (!FAILED(spXMLChildNodeList->nextNode(&spXMLChildNode))) { if (spXMLChildNode.p == NULL) { break; } spXMLChildNode->get_nodeName(&nodeName); spXMLChildNode->get_nodeTypedValue(&nodeValue); USES_CONVERSION; LPTSTR lpstrVal = W2T(nodeValue.bstrVal); if (nodeName == L"name") { la->setName(lpstrVal); } else if (nodeName == L"texture") { spXMLGChildNodeList = NULL; spXMLChildNode->get_childNodes(&spXMLGChildNodeList); while (!FAILED(spXMLGChildNodeList->nextNode(&spXMLGChildNode))){ if (spXMLGChildNode.p == NULL) { break; } hr = spXMLGChildNode->get_nodeTypedValue(&nodeValue); hr = spXMLGChildNode->get_nodeName(&nodeName); USES_CONVERSION; LPTSTR _lpstrVal = W2T(nodeValue.bstrVal); if (nodeName == L"path") { la->getTex()->setPath(_lpstrVal); la->getTex()->loadTexture(); //la->getTex()->loadTexture(texId); } else if (nodeName == L"x1") { la->getTex()->setX1((float)atof((const char*)_lpstrVal)); } else if (nodeName == L"y1") { la->getTex()->setY1((float)atof((const char*)_lpstrVal)); } else if (nodeName == L"x2") { la->getTex()->setX2((float)atof((const char*)_lpstrVal)); } else if (nodeName == L"y2") { la->getTex()->setY2((float)atof((const char*)_lpstrVal)); } spXMLGChildNode = NULL; } } else if (nodeName == L"w") { la->setW((int)(atoi((const char*)lpstrVal) * w_scale)); } else if (nodeName == L"h") { la->setH((int)(atoi((const char*)lpstrVal) * h_scale)); } else if (nodeName == L"transformations") { loadTransformations(spXMLChildNode, la, w_scale, h_scale); } spXMLChildNode = NULL; } ll->push_back(la); spXMLChildNodeList = NULL; spXMLNode = NULL; } // sort the Layer list sort(ll->begin(), ll->end(), descend); } catch (char *lpstrError) { std::cout << lpstrError << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } } // Load transformations' parameters such as offset, min, max and scale. void XMLReader::loadTransformations(IXMLDOMNode *spXMLDOMNode, Layer *la, float w_scale, float h_scale) { try { CComPtr<IXMLDOMNode> spXMLNode = spXMLDOMNode; CComPtr<IXMLDOMNode> spXMLCNode; CComPtr<IXMLDOMNodeList> spXMLNodeList, spXMLCNodeList; CComBSTR nodeName; CComVariant nodeVal (VT_EMPTY); HRESULT hr = spXMLNode->get_childNodes(&spXMLNodeList); spXMLNode = NULL; while (!FAILED(spXMLNodeList->nextNode(&spXMLNode))) { if (spXMLNode.p == NULL) { break; } Transformation *tr = new Transformation(w_scale, h_scale); spXMLCNodeList = NULL; hr = spXMLNode->get_childNodes(&spXMLCNodeList); spXMLCNode = NULL; while (!FAILED(spXMLCNodeList->nextNode(&spXMLCNode))) { if (spXMLCNode.p == NULL) { break; } hr = spXMLCNode->get_nodeName(&nodeName); hr = spXMLCNode->get_nodeTypedValue(&nodeVal); USES_CONVERSION; LPTSTR lpstrVal = W2T(nodeVal.bstrVal); // Recently just need type, offset, min, max, scale. if (nodeName == L"type") { tr->setType(lpstrVal); } else if (nodeName == L"offset") { tr->setOffset(atoi((const char*)lpstrVal)); } else if (nodeName == L"min") { tr->setMinR(atof((const char*)lpstrVal)); } else if (nodeName == L"max") { tr->setMaxR(atof((const char*)lpstrVal)); } else if (nodeName == L"scale") { tr->setScale(atof((const char*)lpstrVal)); } spXMLCNode = NULL; } la->getTl()->push_back(tr); spXMLNode = NULL; } } catch (char *lpstrError) { std::cout << lpstrError << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } } void XMLReader::TESTHR(HRESULT hr) { if (FAILED(hr)) { throw hr; } }
[ "[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6" ]
[ [ [ 1, 611 ] ] ]
fc3c466cf931e86e590ce5f822d7d619bde38e6b
191d4160cba9d00fce9041a1cc09f17b4b027df5
/ZeroLag/ZeroLag/SignScan.cpp
8c2426d58e9bcb8507b56c993646e13c2d4ec09b
[]
no_license
zapline/zero-lag
f71d35efd7b2f884566a45b5c1dc6c7eec6577dd
1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4
refs/heads/master
2021-01-22T16:45:46.430952
2011-05-07T13:22:52
2011-05-07T13:22:52
32,774,187
3
2
null
null
null
null
WINDOWS-1252
C++
false
false
4,848
cpp
#include "StdAfx.h" #include "SignScan.h" #include "MicrosoftVerify.h" CSignScan::CSignScan(void) { InitFunc(); HideHave = TRUE; } CSignScan::~CSignScan(void) { } bool CSignScan::ProcessFile(const char *filename) { TCHAR *temp = new TCHAR[strlen(filename)+1]; MByteToWChar(filename,temp,(DWORD)strlen(filename)+1); if (CheckFileTrust(temp) == TRUE && HideHave == FALSE) { pList->InsertItem(m_DisplayCount,L""); pList->SetItemText(m_DisplayCount,0,temp); pList->EnsureVisible(m_DisplayCount, FALSE); pList->SetItemText(m_DisplayCount,1,L"ÓÐ"); m_DisplayCount++; } else { pList->InsertItem(m_DisplayCount,L""); pList->SetItemText(m_DisplayCount,0,temp); pList->EnsureVisible(m_DisplayCount, FALSE); pList->SetItemText(m_DisplayCount,1,L"Ÿo"); m_DisplayCount++; } m_nFileCount++; delete[] temp; return TRUE; } void CSignScan::ProcessDir(const char *currentdir,const char *parentdir) { m_nSubdirCount++; } BOOL CSignScan::CheckFileTrust( LPCWSTR lpFileName ) { BOOL bRet = FALSE; WINTRUST_DATA wd = { 0 }; WINTRUST_FILE_INFO wfi = { 0 }; WINTRUST_CATALOG_INFO wci = { 0 }; CATALOG_INFO ci = { 0 }; HCATADMIN hCatAdmin = NULL; if ( !CryptCATAdminAcquireContext( &hCatAdmin, NULL, 0 ) ) { return FALSE; } HANDLE hFile = CreateFileW( lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if ( INVALID_HANDLE_VALUE == hFile ) { CryptCATAdminReleaseContext( hCatAdmin, 0 ); return FALSE; } DWORD dwCnt = 100; BYTE byHash[100]; CryptCATAdminCalcHashFromFileHandle( hFile, &dwCnt, byHash, 0 ); CloseHandle( hFile ); LPWSTR pszMemberTag = new WCHAR[dwCnt * 2 + 1]; for ( DWORD dw = 0; dw < dwCnt; ++dw ) { wsprintfW( &pszMemberTag[dw * 2], L"%02X", byHash[dw] ); } HCATINFO hCatInfo = CryptCATAdminEnumCatalogFromHash( hCatAdmin, byHash, dwCnt, 0, NULL ); if ( NULL == hCatInfo ) { wfi.cbStruct= sizeof( WINTRUST_FILE_INFO ); wfi.pcwszFilePath = lpFileName; wfi.hFile = NULL; wfi.pgKnownSubject = NULL; wd.cbStruct = sizeof( WINTRUST_DATA ); wd.dwUnionChoice= WTD_CHOICE_FILE; wd.pFile = &wfi; wd.dwUIChoice = WTD_UI_NONE; wd.fdwRevocationChecks = WTD_REVOKE_NONE; wd.dwStateAction= WTD_STATEACTION_IGNORE; //wd.dwProvFlags = WTD_SAFER_FLAG; //“þximoÕf£¬¿ÉÄÜŒ§Ö¿¨ËÀ wd.dwProvFlags = 0; wd.hWVTStateData= NULL; wd.pwszURLReference = NULL; } else { CryptCATCatalogInfoFromContext( hCatInfo, &ci, 0 ); wci.cbStruct = sizeof( WINTRUST_CATALOG_INFO ); wci.pcwszCatalogFilePath = ci.wszCatalogFile; wci.pcwszMemberFilePath = lpFileName; wci.pcwszMemberTag= pszMemberTag; wd.cbStruct = sizeof( WINTRUST_DATA ); wd.dwUnionChoice= WTD_CHOICE_CATALOG; wd.pCatalog = &wci; wd.dwUIChoice = WTD_UI_NONE; wd.fdwRevocationChecks = WTD_STATEACTION_VERIFY; wd.dwProvFlags = 0; wd.hWVTStateData= NULL; wd.pwszURLReference = NULL; } GUID action = WINTRUST_ACTION_GENERIC_VERIFY_V2; HRESULT hr = WinVerifyTrust( NULL, &action, &wd ); bRet = SUCCEEDED( hr ); if ( NULL != hCatInfo ) { CryptCATAdminReleaseCatalogContext( hCatAdmin, hCatInfo, 0 ); } CryptCATAdminReleaseContext( hCatAdmin, 0 ); delete[] pszMemberTag; return bRet; } BOOL CSignScan::InitFunc() { HMODULE dllHandle = NULL; dllHandle = LoadLibrary(L"wintrust.dll"); if (NULL == dllHandle) { //printf("LoadLibrary wintrust.dll error!%d\n",GetLastError()); return FALSE; } (FARPROC &)CryptCATAdminAcquireContext = GetProcAddress(dllHandle,"CryptCATAdminAcquireContext"); (FARPROC &)CryptCATAdminReleaseContext = GetProcAddress(dllHandle,"CryptCATAdminReleaseContext"); (FARPROC &)CryptCATAdminCalcHashFromFileHandle = GetProcAddress(dllHandle,"CryptCATAdminCalcHashFromFileHandle"); (FARPROC &)CryptCATAdminEnumCatalogFromHash = GetProcAddress(dllHandle,"CryptCATAdminEnumCatalogFromHash"); (FARPROC &)CryptCATAdminReleaseCatalogContext = GetProcAddress(dllHandle,"CryptCATAdminReleaseCatalogContext"); (FARPROC &)CryptCATCatalogInfoFromContext = GetProcAddress(dllHandle,"CryptCATCatalogInfoFromContext"); (FARPROC &)WinVerifyTrust = GetProcAddress(dllHandle,"WinVerifyTrust"); if (CryptCATAdminAcquireContext == NULL || CryptCATAdminReleaseContext == NULL || CryptCATAdminCalcHashFromFileHandle == NULL || CryptCATAdminEnumCatalogFromHash == NULL || CryptCATAdminReleaseCatalogContext == NULL || CryptCATCatalogInfoFromContext == NULL || WinVerifyTrust == NULL) { //printf("GetProcAddress error 1%d\n",GetLastError()); return FALSE; } return TRUE; }
[ "Administrator@PC-200201010241" ]
[ [ [ 1, 160 ] ] ]
ae1dd6bb63c12a30f3d67d3f4148a9ffdced1d8d
ac12251d20c26624305043453386812170b3d890
/src/monobind/scope.hpp
8d40562065f60b6e7dd69330486faf1aa7e4191e
[]
no_license
minuowa/mono-embed
3a891bbccb3c5d14744f828ae655c6320b91b5a6
5d7df7262653bdd95cf1805645c877f30a937ca8
refs/heads/master
2021-01-18T06:45:59.137348
2011-05-05T20:23:11
2011-05-05T20:23:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,345
hpp
/** * Copyright (c) 2007 Virgile 'xen' Bello * http://monobind.sourceforge.net * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef MONOBIND_SCOPE_HPP #define MONOBIND_SCOPE_HPP #include <vector> #include <boost/shared_ptr.hpp> namespace monobind { struct scope_info { public: virtual ~scope_info() {} virtual void register_( MonoImage* monoImage, MonoDomain* monoDomain, const std::string& currentScope ) {} virtual void registerChildren( MonoImage* monoImage, MonoDomain* monoDomain, const std::string& thisScope ); private: friend class scope; friend class module; std::vector< boost::shared_ptr< scope_info > > m_children; boost::shared_ptr< scope_info > m_next; }; class scope { public: scope() : m_scopeInfos( new scope_info ) { } scope( const boost::shared_ptr< scope_info >& scopeInfos ) : m_scopeInfos( scopeInfos ) { } scope( const scope& s ) : m_scopeInfos( s.m_scopeInfos ) { } scope& operator[]( const scope& s ) { m_scopeInfos->m_children.push_back( s.m_scopeInfos ); return *this; } scope& operator,( scope& s ); protected: static std::vector< boost::shared_ptr< void > > ms_wrappers; boost::shared_ptr< scope_info > m_scopeInfos; friend class module; }; } #endif
[ [ [ 1, 79 ] ] ]
bca1903719b5504874386b5f045cc5d54c34c41c
3dca0a6382ea348a8617be05e1bfa6f4ed70d77c
/include/PgeFontManager.h
0179516e48fc1050c05417498c2509cfff9e4dfe
[]
no_license
David-Haim-zz/pharaoh-game-engine
9c766916559f9c74667e981b9b3f03b43920bc4e
b71db3fd99ebad0ab40a0888360d560748f63131
refs/heads/master
2021-05-29T15:17:23.043407
2011-01-23T17:53:39
2011-01-23T17:53:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,493
h
/*! $Id$ * @file PgeFontManager.h * @author Chad M. Draper * @date December 5, 2008 * @brief Stores font definitions for the engine. * */ #ifndef PGEFONTMANAGER_H #define PGEFONTMANAGER_H #include "PgeTypes.h" #include "PgeSharedPtr.h" //#include "PgeTileMap.h" #include "PgeSingleton.h" //#include <map> namespace PGE { /** @class Font Stores information for a specific bitmap font. @remarks It is not possible to change attributes such as bold, italic, or underline after a font is created. Since the font is rendered as a tile map, it could be scaled, but it is still ideal to create the font as close to the desired size as possible. @remarks It is recommeded that the font's descriptive name include all attributes defining the font, though this is not required. It just makes it more meaningful to users. For example: <pre> Arial 12pt bold underline italic </pre> */ class _PgeExport Font { public: String mDescription; //typedef SharedPtr< TileMap > TileMapPtr; //TileMapPtr mTileMap; /** Constructor */ Font(); /** Load the font from a data file */ /** Print a string using the font */ }; /** @class FontManager Bitmap fonts are handled similarly to tile maps, but require some extra handling to print strings. The FontManager class is sublclassed from TileManager, and has additional functionality, primarily a PrintString method. @remarks The input data file should be a simple xml file containing any of the folloring tags <UL> <LI>name - Name of the font. required.</LI> <LI>dataFile - Name of the data file, which descibes the layout of the font in the texture. This may have a "type" attribute with one of the following values: <UL> <LI>cbfgBinFile (Binary Font Data File exported from Codeheads' Bitmap Font Generator)</LI> <LI>cbfgBffFile (Proprietary file format used by CBFG. Only the font data is read, and the texture must be a separate image file.)</LI> </UL> If no type or data file is given, then it is assumed that the image contains all 256 ASCII characters, which is used by LMNOpc.com's Bitmap Font Builder. <LI>imageFile - Name of the image file containing the font glyphs.</LI> </UL> so a sample font definition file would look something like: <CODE> <?xml version="1.0" encoding="ISO-8859-1" ?> <font> <name>Arial</name> <dataFile type="cbfgBinFile">Arial.dat</cbfgBinFile> <imageFile>Arial.tga</dataFile> </font> </CODE> @remarks If no data file is listed to describe the font, but an image is given, then the image is assumed to have all 256 ASCII characters, in a 16x16 grid. This is equivalent to the LMNOpc.com's format. */ class _PgeExport FontManager : public Singleton< FontManager > { public: /** Constructor */ FontManager(); /** Override singleton retrieval to avoid link errors */ static FontManager& GetSingleton(); /** Override singleton pointer retrieval to avoid link errors */ static FontManager* GetSingletonPtr(); /** Load a font into the manager */ bool LoadFont( const String& fontDataFile ); /** Print a string to the current display using a specified font. If the font is not available, it will fail and return false. */ bool PrintString( const String& fontName, const Real& posX, const Real& posY, const String& msg ); }; // /** The font class is what actually holds the data for each font. It is // responsible for loading the font, and for rendering strings using the // font. // // @remarks // The input data file should be a simple xml file containing any of // the folloring tags // // <UL> // <LI>name - Name of the font. required.</LI> // <LI>dataFile - Name of the data file, which descibes the // layout of the font in the texture. This // may have a "type" attribute with one of // the following values: // <UL> // <LI>cbfgBinFile (Binary Font Data File exported from Codeheads' Bitmap Font Generator)</LI> // <LI>cbfgBffFile (Proprietary file format used by CBFG. Only the font data is read, and the texture must be a separate image file.)</LI> // </UL> // If no type is given, then it is assumed that the image // contains all 256 ASCII characters, which is used by LMNOpc.com's // Bitmap Font Builder. // <LI>imageFile - Name of the image file containing the font glyphs.</LI> // </UL> // // so a sample font definition file would look something like: // <CODE> // <?xml version="1.0" encoding="ISO-8859-1" ?> // <font> // <name>Arial</name> // <dataFile type="cbfgBinFile">Arial.dat</cbfgBinFile> // <imageFile>Arial.tga</dataFile> // </font> // </CODE> // // @remarks // If no data file is listed to describe the font, but an image is // given, then the image is assumed to have all 256 ASCII characters, // in a 16x16 grid. This is equivalent to the LMNOpc.com's format. // */ // class Font // { // private: // friend class FontManager; // String mFontName; ///< Identifier for the font // // public: // /** Constructor */ // Font(); // /** Constructor */ // Font( const String& fontDataFile ); // /** Destructor */ // ~Font(); // // /** Open a data file and load the font information */ // void GenerateFont( const String& fontDataFile ); // // /** Render a string to the display using the font */ // void RenderString( Int posX, Int posY, const String& msg ) const; // // }; // class Font // // /** @class FontManager // A collection of fonts. // // The font manager stores and maintains all loaded fonts. // // @remarks // There is no limitation on the number of font managers. Typically, // the font manager will exist in a game state, and be destroyed when // the state ends. // */ // class FontManager // { // private: // typedef SharedPtr< Font > FontPtr; // typedef std::map< String, FontPtr > FontMap // FontMap mFontMap; ///< Map containing loaded fonts // // public: // /** Constructor */ // FontManager(); // /** Destructor */ // virtual ~FontManager(); // // /** Add a font to the manager */ // void AddFont( Font* newFont ); // // /** Load a font and add it to the manager */ // void AddFont( const String& fontDataFile ); // // /** Return a raw pointer to a named font, or null if the font does not exist */ // Font* GetFont( const String& fontName ); // // /** Remove a font from the manager */ // void RemoveFont( const String& fontName ); // // /** Remove all fonts */ // void RemoveAllFonts(); // // /** Render a string with a named font */ // void RenderString( const String& fontName, Int posX, Int posY, const String& msg ) const; // // }; // class FontManager } // namespace PGE #endif // PGEFONTMANAGER_H
[ "pharaohgameengine@555db735-7c4c-0410-acd0-0358cc0c1ac3" ]
[ [ [ 1, 222 ] ] ]
af0249633e86f4613b13b446b9b51e40db7a3daf
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/UnitTests/UnitTest_ItemBox_Info/DemoKeeper.h
b13a5bb266d4e8ac342be501b88007ff9e37aef2
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
381
h
/*! @file @author George Evmenov @date 08/2000 */ #ifndef __DEMO_KEEPER_H__ #define __DEMO_KEEPER_H__ #include "BaseManager.h" namespace demo { class DemoKeeper : public base::BaseManager { public: virtual void createScene(); virtual void destroyScene(); virtual void setupResources(); }; } // namespace demo #endif // __DEMO_KEEPER_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 24 ] ] ]
a8411906c0f9bc1f02885f60b5e163acf8738dab
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/PlasmaBolt.h
5d62ddfff3389850d996d80b8e20079d6b0e27fd
[]
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
397
h
#pragma once #include "projectile.h" class PlasmaBolt : public Projectile { protected: static bool initialised_; static int fill_dl_; static int fill_verts_index_; virtual void InitialiseGraphics(); public: PlasmaBolt(Vector3f _position); virtual ~PlasmaBolt(void); virtual void Hit(std::vector<Decoration_ptr>& _spawn, std::vector<Projectile_ptr>& _projectile_spawn); };
[ "Edward Woolhouse@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7" ]
[ [ [ 1, 14 ], [ 16, 16 ] ], [ [ 15, 15 ] ] ]
ebefcdd7a14c9501730b28363e3a0a47c7bab3d9
294d277502d9d0d2ca1f3535d3517d7d21a9141a
/mt_random.cpp
c9522caceb099e2b3fb405bbb6d50490aae1570c
[]
no_license
grigory/midas-landmarks
57b818646ebfe7c0022eb3ad9546052ed53bc550
3a8c4148968077b87b7aab50860ff07d7f43aa7c
refs/heads/master
2021-01-20T22:31:26.157819
2010-08-10T21:21:22
2010-08-10T21:21:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
// (c) Microsoft Corporation. All rights reserved. #include "mt_random.h" const unsigned long int MTRandom::maxvalue = (unsigned long int)(-1); const unsigned long int MTRandom::MATRIX_A = 0x9908b0dfUL; /* constant vector a */ const unsigned long int MTRandom::UPPER_MASK = 0x80000000UL; /* most significant w-r bits */ const unsigned long int MTRandom::LOWER_MASK = 0x7fffffffUL; /* least significant r bits */ unsigned long MTRandom::mt[N]; /* the array for the state vector */ int MTRandom::mti=N+1; /* mti==N+1 means mt[N] is not initialized */
[ [ [ 1, 13 ] ] ]
d32cf0b9dd3664da141d6b28a58344ca37e68901
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/ytk_bak/BatDown/src/PostView.cpp
48ea3ad61b2deb7422669b115f151dedd704d332
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include "PostView.h" #include "QHeaderView.h" PostView::PostView(BatDown *app, QWidget *parent) : QTableView(parent), BatDownBase(app) { m_pModel = new PostModel(app); setModel(m_pModel); setSelectionBehavior(QAbstractItemView::SelectRows); horizontalHeader()->setStretchLastSection(true); setAlternatingRowColors(true); setColumnWidth(0, 45); setColumnWidth(1, 300); setColumnWidth(2, 45); connect( this, SIGNAL(doubleClicked(const QModelIndex &)),this, SLOT(onDblClick(const QModelIndex &)) ); } PostView::~PostView() { } void PostView::onDblClick(const QModelIndex &idx) { }
[ "yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 26 ] ] ]
299fa76cc0a5190c6722d6efcb5c63e408480019
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/src/Tdk/Header Files/TdkAbstractProcessEvent.h
b6407e4a73be8730b2433e2a85c76d3683b03789
[]
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
1,492
h
/****************************************************************************** * FUNCATE - GIS development team * * @(#) TdkAbstractProcessEvent.h * ******************************************************************************* * * $Rev$: * * $Author: rui.gregorio $: * * $Date: 2010/03/22 12:13:07 $: * ******************************************************************************/ // Elaborated by Rui Mauricio Gregório #ifndef __TDK_ABSTRACT_PROCESS_EVENT #define __TDK_ABSTRACT_PROCESS_EVENT #include <string> using namespace std; //! \class TdkAbstractProcessEvent /*! Abstract class to create a process status dialog */ class TdkAbstractProcessEvent { public : //! \brief Constructor TdkAbstractProcessEvent(){}; //! \brief Destructor virtual ~TdkAbstractProcessEvent(){}; //! \brief processStatusEvent /*! Abstract method to show the process status \param maxValue maximum value \param currentValue current value */ virtual void processStatusEvent(const long &maxValue, const long &currentValue) = 0; //! \brief buildingGeometryEvent /*! Method to dispatch the building Geometry Event to informate the current geometry in building process \param representation representation type \param geom_id geometry identify \param object_id string identify */ virtual void buildingGeometryEvent(const short &representation, const long &geom_id, const std::string &object_id)=0; }; #endif
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 58 ] ] ]
5cef94ae9d67b1b6b649e06c1c814bde585ffc86
4b98127905e3ff9546ee7948b83ce066c6383cd3
/DatamodulePool/CBDemos/IWDemo/uMainForm.cpp
dac6d97d517c5f79ba3ad23646654ad4e537d1d0
[]
no_license
thecocce/delphipooling
c9860600865ef92d548ae6d0fade180a6db93680
1473fa4f67033fc6fe02af488bb964758e2ece69
refs/heads/master
2016-08-05T02:24:50.350657
2007-01-20T19:45:23
2007-01-20T19:45:23
39,019,641
0
0
null
null
null
null
UTF-8
C++
false
false
2,196
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "uMainForm.h" #include "ServerController.h" #include "uPooledModule.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "IWBaseControl" #pragma link "IWBaseHTMLControl" #pragma link "IWCompButton" #pragma link "IWCompEdit" #pragma link "IWCompLabel" #pragma link "IWControl" #pragma link "IWExtCtrls" #pragma link "IWVCLBaseControl" #pragma link "jpeg" #pragma link "IWDBExtCtrls" #pragma resource "*.dfm" //--------------------------------------------------------------------------- __fastcall TfrmMain::TfrmMain(TComponent* Owner) : TIWAppForm(Owner) { } //--------------------------------------------------------------------------- void setAsMainForm() { TfrmMain::SetAsMainForm(__classid(TfrmMain)); } #pragma startup setAsMainForm void __fastcall TfrmMain::IWAppFormCreate(TObject *Sender) { CurrentRec = 0; FillFields(CurrentRec); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::btnPriorClick(TObject *Sender) { FillFields(CurrentRec--); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::btnNextClick(TObject *Sender) { FillFields(CurrentRec++); } //--------------------------------------------------------------------------- void TfrmMain::FillFields(long NewRec) { TIWServerController *sc; TdmPooled *dm; char c; sc = (TIWServerController*)GServerController; dm = (TdmPooled*)(sc->Pool->Lock()); try { if(NewRec < 0) { NewRec = 0; } if(NewRec > dm->Table1->RecordCount-1) { NewRec = dm->Table1->RecordCount-1; } dm->Table1->First(); dm->Table1->MoveBy(NewRec); edtCommon->Text = dm->Table1->FieldByName("Common_Name")->AsString; edtSpecies->Text = dm->Table1->FieldByName("Species Name")->AsString; imgFish->Picture->Assign(dm->Table1->FieldByName("Graphic")); } __finally { sc->Pool->Unlock(dm); } }
[ "arcanasupport@375fe88c-7d27-0410-9089-0d2ae9628485" ]
[ [ [ 1, 79 ] ] ]
593a7b8b95abb944434cf5d2ad1e3b778b753ff2
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/ouan-tests/OgreSceneLoader/OrbitCameraController.h
5f59d6a86588f774d82431e62acdccc12bfc0665
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
UTF-8
C++
false
false
762
h
#ifndef __ORBIT_CAMERA_CONTROLLER__H__ #define __ORBIT_CAMERA_CONTROLLER__H__ namespace Ogre { class Camera; class SceneNode; } class OrbitCameraController { public: OrbitCameraController( Ogre::Camera* camera ); virtual ~OrbitCameraController(); void setLookAtPosition( const float x, const float y, const float z ); void resetOrientation(); void setOrientation( const float yawDegrees, const float pitchDegrees ); void addOrientation( const float yawDegrees, const float pitchDegrees ); void setDistance( const float distance ); void addDistance( const float distance ); private: Ogre::Camera* m_camera; Ogre::SceneNode* m_lookAtNode; Ogre::SceneNode* m_yawNode; Ogre::SceneNode* m_pitchNode; }; #endif
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 34 ] ] ]
9f37e40da3c34072ea0d5a046a3e0fd0f41108c0
dde32744a06bb6697823975956a757bd6c666e87
/bwapi/SCProjects/BTHAIModule/Source/GoliathAgent.h
1d512b16054d7fb9c40fb4e552fae6247f4aa3b9
[]
no_license
zarac/tgspu-bthai
30070aa8f72585354ab9724298b17eb6df4810af
1c7e06ca02e8b606e7164e74d010df66162c532f
refs/heads/master
2021-01-10T21:29:19.519754
2011-11-16T16:21:51
2011-11-16T16:21:51
2,533,389
0
0
null
null
null
null
UTF-8
C++
false
false
618
h
#ifndef __GOLIATHAGENT_H__ #define __GOLIATHAGENT_H__ #include <BWAPI.h> #include "UnitAgent.h" using namespace BWAPI; using namespace std; /** The GoliathAgent handles Terran Goliath units. * * Implemented special abilities: * - Targets air unit first if there are any nearby. * * Author: Johan Hagelback ([email protected]) */ class GoliathAgent : public UnitAgent { private: public: GoliathAgent(Unit* mUnit); /** Called each update to issue orders. */ void computeActions(); /** Returns the unique type name for unit agents. */ string getTypeName(); }; #endif
[ "rymdpung@.(none)" ]
[ [ [ 1, 30 ] ] ]
37fd478185e1c5d60bdb06d23b02ae0abf8b1c58
928b250a42ffbe1d1c1009b4af7fd3f6a1f46266
/forlijia/forlijia/forlijia/forlijia.h
ed380c51d01869f31706dce44cc79081093bff97
[]
no_license
jimcoly/comyitian
81044cc6e5d06613e1f2bda8b658457e8337ab8f
6f70e202907be1071d3310bfe1441567ebffed1e
refs/heads/master
2020-05-31T17:54:26.448254
2011-09-01T07:28:07
2011-09-01T07:28:07
33,866,360
0
0
null
null
null
null
UTF-8
C++
false
false
516
h
// forlijia.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CforlijiaApp: // See forlijia.cpp for the implementation of this class // class CforlijiaApp : public CWinApp { public: CforlijiaApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CforlijiaApp theApp;
[ "sdy63420@3919fc08-f352-11de-9907-777483041811" ]
[ [ [ 1, 31 ] ] ]
35ee3511f333c9201ad402253bcbf1a3b66689c8
80716d408715377e88de1fc736c9204b87a12376
/TspLib3/Src/Conn.cpp
4cd2d697902ec25a479c0f3fc3b472f9b032a08d
[]
no_license
junction/jn-tapi
b5cf4b1bb010d696473cabcc3d5950b756ef37e9
a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4
refs/heads/master
2021-03-12T23:38:01.037779
2011-03-10T01:08:40
2011-03-10T01:08:40
199,317
2
2
null
null
null
null
UTF-8
C++
false
false
34,701
cpp
/******************************************************************************/ // // CONN.CPP - Source file for the TSPIConnection class object. // // Copyright (C) 1994-2004 JulMar Entertainment Technology, Inc. // All rights reserved // // This file contains all the code for the base connection object upon // which the phone and line connections are derived. // // This source code is intended only as a supplement to the // TSP++ Class Library product documentation. This source code cannot // be used in part or whole in any form outside the TSP++ library. // /******************************************************************************/ /*---------------------------------------------------------------------------*/ // INCLUDE FILES /*---------------------------------------------------------------------------*/ #include "stdafx.h" /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::CTSPIConnection // // Constructor // CTSPIConnection::CTSPIConnection() : CTSPIBaseObject(), m_pDevice(0), m_dwDeviceID(0xffffffff), m_strName(_T("")), m_dwFlags(0), m_pExtVerInfo(0), m_dwNegotiatedVersion(0) { }// CTSPIConnection::CTSPIConnection /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::~CTSPIConnection // // Destructor // CTSPIConnection::~CTSPIConnection() { delete m_pExtVerInfo; }// CTSPIConnection::~CTSPIConnection /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::Init // // Initialize the connection. Each CTSPIConnection is owned by a // specific device and has a positional identifier which is set by // TAPI. // void CTSPIConnection::Init(CTSPIDevice* pDevice, DWORD dwDeviceId) { m_pDevice = pDevice; m_dwDeviceID = dwDeviceId; GetSP()->MapConnectionToID(dwDeviceId, this); // Now walk the requst map and add all the requests to our map // We do this for performance so we don't scan the map when requests // are actually being processed. The structures built by the macros // should be stored in a discardable page (INIT_DATA) which would get // paged out after initialization is complete. const tsplib_REQMAP* pRequests = GetRequestList(); TRequestMap* pMap = GetRequestMap(); _TSP_ASSERTE(pMap != NULL); if (pMap != NULL && pMap->empty() && pRequests != NULL) { while (pRequests->nRequest != 0) { (*pMap)[pRequests->nRequest] = (tsplib_REQPROC) pRequests->fpReq; ++pRequests; } } }// CTSPIConnection::Init /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::NegotiateVersion // // This negotiates the TSP version for this line or phone device // Override this to allow for different devices to support different // versions of TAPI functions. // LONG CTSPIConnection::NegotiateVersion(DWORD dwLoVersion, DWORD dwHiVersion, LPDWORD lpdwTSPIVersion) { // Do a SERVICE PROVIDER negotiation. *lpdwTSPIVersion = GetSP()->GetSupportedVersion(); if (dwLoVersion > *lpdwTSPIVersion) // The app is too new for us return LINEERR_INCOMPATIBLEAPIVERSION; // If the version supported is LESS than what we support, then drop to the // version it allows. The library can handle down to TAPI 1.3. if (dwHiVersion < *lpdwTSPIVersion) { if (dwHiVersion < TAPIVER_13) return LINEERR_INCOMPATIBLEAPIVERSION; *lpdwTSPIVersion = dwHiVersion; } // Save off the negotiated version m_dwNegotiatedVersion = *lpdwTSPIVersion; // Everything looked Ok. return 0; }// CTSPIConnection::NegotiateVersion /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::NegotiateExtVersion // // This negotiates the extended version for this line or phone device // LONG CTSPIConnection::NegotiateExtVersion(DWORD dwTSPIVersion, DWORD dwLoVersion, DWORD dwHiVersion, LPDWORD lpdwExtVersion) { // Set it to zero *lpdwExtVersion = 0; // Ok, device Id looks ok, do the version negotiation. If the // line isn't open yet, use the supported TSP version. DWORD dwNegotiatedVersion = (m_dwNegotiatedVersion==0) ? GetSP()->GetSupportedVersion() : m_dwNegotiatedVersion; if (dwTSPIVersion != dwNegotiatedVersion) return LINEERR_INCOMPATIBLEAPIVERSION; // If we have extension information then attempt to negotiate to it. if (m_pExtVerInfo == NULL) return LINEERR_OPERATIONUNAVAIL; // If we already have a selected extension then restrict the available // version reporting to that specific version. if (m_pExtVerInfo->dwSelectedExtVersion != 0) { if (dwLoVersion > m_pExtVerInfo->dwSelectedExtVersion || dwHiVersion < m_pExtVerInfo->dwSelectedExtVersion) return LINEERR_INCOMPATIBLEEXTVERSION; *lpdwExtVersion = m_pExtVerInfo->dwSelectedExtVersion; } // Otherwise allow the range supported. else { // If the lowest version the app can negotiate to isn't supported // by us then refuse to negotiate. The app is too new. if (dwLoVersion > m_pExtVerInfo->dwMaxExtVersion) return LINEERR_INCOMPATIBLEAPIVERSION; // If the highest version supported by the app is less than our // lowest supported version then fail - the app is too old. if (dwHiVersion < m_pExtVerInfo->dwMinExtVersion) return LINEERR_INCOMPATIBLEAPIVERSION; // The lo/hi version is within our range. *lpdwExtVersion = min(dwHiVersion, max(m_pExtVerInfo->dwMaxExtVersion, dwLoVersion)); } return 0; }// CTSPIConnection::NegotiateExtVersion //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::GetExtensionID // // This function returns the extension ID that the service provider // supports for the indicated line/phone device. // LONG CTSPIConnection::GetExtensionID(DWORD /*dwTSPIVersion*/, LPEXTENSIONID lpExtensionID) { // If we have extension information available, then provide it to the user. if (m_pExtVerInfo == NULL) { ZeroMemory(lpExtensionID, sizeof(EXTENSIONID)); } else { CopyMemory(lpExtensionID, &m_pExtVerInfo->ExtensionID, sizeof(EXTENSIONID)); } return 0; }// CTSPIConnection::GetExtensionID ///////////////////////////////////////////////////////////////////////////// // CTSPIConnection::SelectExtVersion // // This function selects the indicated Extension version for the // indicated line or phone device. Subsequent requests operate according to that // Extension version. // LONG CTSPIConnection::SelectExtVersion(DWORD dwExtVersion) { // Save off the new version for structure manipulation later. if (m_pExtVerInfo == NULL) return LINEERR_OPERATIONUNAVAIL; // Validate the extension version information. if (dwExtVersion != 0 && dwExtVersion < m_pExtVerInfo->dwMinExtVersion || dwExtVersion > m_pExtVerInfo->dwMaxExtVersion) return LINEERR_INCOMPATIBLEEXTVERSION; // Save of the selected extension level m_pExtVerInfo->dwSelectedExtVersion = dwExtVersion; return 0; }// CTSPIConnection::SelectExtVersion ///////////////////////////////////////////////////////////////////////////// // CTSPIConnection::SetExtVersion // // This function sets up the extension information reported by this device. // void CTSPIConnection::SetExtVersionInfo(DWORD dwMinVersion, DWORD dwMaxVersion, DWORD dwExtensionID0,DWORD dwExtensionID1, DWORD dwExtensionID2, DWORD dwExtensionID3) { if (m_pExtVerInfo == NULL) m_pExtVerInfo = new TExtVersionInfo; m_pExtVerInfo->dwMinExtVersion = min(dwMinVersion, dwMaxVersion); m_pExtVerInfo->dwSelectedExtVersion = 0; m_pExtVerInfo->dwMaxExtVersion = max(dwMaxVersion, dwMinVersion); m_pExtVerInfo->ExtensionID.dwExtensionID0 = dwExtensionID0; m_pExtVerInfo->ExtensionID.dwExtensionID1 = dwExtensionID1; m_pExtVerInfo->ExtensionID.dwExtensionID2 = dwExtensionID2; m_pExtVerInfo->ExtensionID.dwExtensionID3 = dwExtensionID3; }// CTSPIConnection::SetExtVersion /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::GetIcon // // This function retrieves a service device-specific icon for display // in user-interface dialogs. // LONG CTSPIConnection::GetIcon (const TString& /*strDevClass*/, LPHICON /*lphIcon*/) { // Return not available, TAPI will supply a default icon. return 0; }// CTSPIConnection::GetIcon /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::AddAsynchRequest // // This method inserts a new asynchronous request into our request // list, and if the connection has no pending requests, sends it to the // device. // int CTSPIConnection::AddAsynchRequest(CTSPIRequest* pRequest) { // If the request is NULL, then return an error. if (pRequest == NULL) return 0; // Determine the position of the request // Lock the line/phone object and arrays CEnterCode sLock(this); // If this is a DROP request, then move it to the front of the queue, otherwise // it gets placed at the end. int iPos = 0; if (pRequest->GetCommand() == REQUEST_DROPCALL) { // If there are requests, insert this drop command after the // last "running" request so we wait for it to complete. // This stops us from killing a request while some other worker thread // is processing it. for (TRequestList::iterator pPos = m_lstAsynchRequests.begin(); pPos != m_lstAsynchRequests.end(); ++pPos) { if ((*pPos)->GetState() == STATE_NOTPROCESSED) break; iPos++; } } else iPos = -1; // End of the list sLock.Unlock(); // Give the line or phone or device a chance to re-shuffle existing requests. if (OnNewRequest (pRequest, &iPos) == false) { #ifdef _DEBUG _TSP_DTRACEX(TRC_REQUESTS, _T("%s: Request canceled by OnNewRequest %s"), m_strName.c_str(), pRequest->Dump().c_str()); #endif pRequest->DecRef(); return 0; } // Insert the request into our list. If the worker function returns // a true response then automatically begin this request on the current // thread. Otherwise simply let it be queued. if (AddAsynchRequest(pRequest, iPos)) { // Ship it to the ReceiveData. We will simply use the thread we are // on since we are guaranteed that it is TAPISRV.EXE. // Unless overridden, this will end up in ProcessData. ReceiveData(); } return 1; }// CTSPIConnection::AddAsynchRequest /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::AddAsynchRequest // // Add the listed asynch request to the list and return whether to // immediately start the request. This function is overridable for // providers which need to examine the request be starting it. // bool CTSPIConnection::AddAsynchRequest (CTSPIRequest* pReq, int iPos) /*throw()*/ { CEnterCode Key(this); // Synch access to object // Validate the position. int iTotal = m_lstAsynchRequests.size(); if (iPos > iTotal) iPos = -1; // If the request is to be added to the FRONT. if (iPos == 0) { // Add to front, always START this request. try { m_lstAsynchRequests.push_front(pReq); } catch(...) { return false; } return true; } // Otherwise, add to the end and start the request only if we don't // have other active requests already running. This is so we don't // interrupt some response from the device which is associated with a // particular running request by invoking a new command. else if (iPos == -1) { try { m_lstAsynchRequests.push_back(pReq); } catch(...) { return false; } return (++iTotal == 1); } // Or somewhere between, don't ever start this request. else { TRequestList::iterator pPos; // Locate the proper position. Walk the list until we find // the proper element. for (pPos = m_lstAsynchRequests.begin(); pPos != m_lstAsynchRequests.end() && iPos; ++pPos, --iPos) ; try { if (pPos == m_lstAsynchRequests.end()) m_lstAsynchRequests.push_back(pReq); else m_lstAsynchRequests.insert(pPos, pReq); } catch(...) { return false; } } return false; }// CTSPIConnection::AddAsynchRequest /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::CompleteRequest // // Complete a specific request and information TAPI through the // asynchronous completion callback that the request is finished. // This function optionally removes the request (deletes it). // void CTSPIConnection::CompleteRequest(CTSPIRequest* pReq, LONG lResult, bool fTellTapi, bool fRemoveRequest) { _TSP_ASSERTE(pReq != NULL); _TSP_ASSERTE(*((LPDWORD)pReq) != 0xdddddddd); // Object has been deleted! CEnterCode sReqLock(pReq); // Lock the request bool fIsCurrentRequest = (GetCurrentRequest() == pReq); bool fSendResponse = (!pReq->HaveSentResponse() && fTellTapi); // Check to see if the request was deleted or completed previously. if (pReq->GetState() == STATE_COMPLETED) return; // Remove the request from our list. if (fRemoveRequest) { // Since we are removing the request, mark it as COMPLETED and then // remove it from our array of requests. pReq->SetState(STATE_COMPLETED); RemoveRequest(pReq); } // Unlock the request here so that blocked threads will be released // in case we are going to delete this request. sReqLock.Unlock(); // Unblock any threads waiting on this to complete. This will cause our // thread to relinquish its time-slice in order to let the other threads // come alive and return our result code. // This will also cause the 'OnRequestComplete' method of the connection, // address, and call to be invoked. pReq->Complete (lResult, fTellTapi); // Tell TAPI the result of the operation. We do this AFTER we have removed the // request since TAPISRV.EXE tends to reuse handles quickly. if (fSendResponse) { _TSP_ASSERTE(GetDeviceInfo() != NULL); GetDeviceInfo()->OnAsynchRequestComplete(lResult, pReq); } // Delete the request now if asked to. if (fRemoveRequest) { // Deallocate the request pReq->DecRef(); // If we still have requests waiting to run on this line, start the // next available request. if (GetRequestCount() > 0 && fIsCurrentRequest) ReceiveData(); } }// CTSPIConnection::CompleteRequest /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::CompleteCurrentRequest // // This method informs TAPI of the completion of an asynchronous // task and optionally removes and starts the next task in the // list. // bool CTSPIConnection::CompleteCurrentRequest(LONG lResult, bool fTellTapi, bool fRemoveRequest) { // If the request list is not empty, then grab the head request and complete it. CTSPIRequest* pReq = GetCurrentRequest(TRUE); if (pReq != NULL) { // Unblock any threads waiting on this request to complete. CompleteRequest (pReq, lResult, fTellTapi, fRemoveRequest); pReq->DecRef(); return true; } return false; }// CTSPIConnection::CompleteCurrentRequest /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::RemovePendingRequests // // Removes any pending requests for the specified connection. // void CTSPIConnection::RemovePendingRequests(CTSPICallAppearance* pCall, int iReqType, LONG lErrorCode, bool fOnlyIfReqNotStarted, const CTSPIRequest* pcurrRequest) { // Don't allow other threads to mess with the request list // while we are deleting requests. CEnterCode sLock(this); // Walk through all the requests in the list matching them up to the connection object // and the optional call appearance and request type. We need to make multiple passes // since we are removing requests as we go - so we start over from the top each time. for (;;) { // Walk through the list and find the first request which matches the // requested criteria. CTSPIRequest* pReq = NULL; for (TRequestList::iterator posCurr = m_lstAsynchRequests.begin(); posCurr != m_lstAsynchRequests.end(); ++posCurr) { if ((*posCurr) != pcurrRequest && IsMatchingRequest ((*posCurr), pCall, iReqType, fOnlyIfReqNotStarted)) { pReq = (*posCurr); break; } } // If we found no requests in the list, then exit. if (pReq == NULL) break; // Otherwise, delete this request. #ifdef _DEBUG _TSP_DTRACE(_T("%s: Removing pending request %s"), m_strName.c_str(), pReq->Dump().c_str()); #endif // See if this request has started. We assume that // the state will be changed. if (pReq->GetState() != STATE_INITIAL) { // The request has at least started, tell the service // provider that we are CANCELING the request. It // can do anything it needs to do on this call with the request. OnCancelRequest (pReq); } // Remove the request. RemoveRequest(pReq); // Tell TAPI that the request is canceled. if (!pReq->HaveSentResponse()) GetDeviceInfo()->OnAsynchRequestComplete(lErrorCode, pReq); // Unblock anyone waiting on this request to finish. pReq->Complete (lErrorCode, true); // Delete the request pReq->DecRef(); } }// CTSPIConnection::RemovePendingRequests /////////////////////////////////////////////////////////////////////////////// // CTSPIConnection::IsMatchingRequest // // Determine if the request matches a set of criteria. This is called // to delete the request. DO NOT CALL THIS FOR ANY OTHER PURPOSE - // SPECIAL CHECKS ARE DONE FOR EMBEDDED CALL APPEARANCES IN REQUEST // PARAMETERS! // bool CTSPIConnection::IsMatchingRequest (CTSPIRequest* pReq, CTSPICallAppearance* pCall, int nRequest, bool fOnlyIfReqNotStarted) { // First do the simple matching. if ((pCall == NULL || (pCall && pReq->GetCallInfo() == pCall)) && (nRequest == REQUEST_ALL || nRequest == pReq->GetCommand()) && (fOnlyIfReqNotStarted == false || pReq->GetState() == STATE_NOTPROCESSED)) return true; // If the request has already been started, and we are only interested in // non-started events, then ignore the request. if (fOnlyIfReqNotStarted && pReq->GetState() != STATE_NOTPROCESSED) return false; // Now see if this call is the target of a command in a parameter // block. The only two requests where this happens are transfer // and conference events. In both these cases, the events need // to be removed or modified to reflect that the call is no longer // available. if (pCall != NULL) { if (nRequest == REQUEST_ALL || nRequest == pReq->GetCommand()) { switch (pReq->GetCommand()) { // If the SETUPXFER hasn't completed, then the consultant call // is not yet valid. This call will be transitioned to IDLE // by the dropping of the REAL call, and the request would be deleted // from the above test since the REQUEST block is always inserted // on the REAL call appearance. If this is the consultant call // that is wanting to delete the request, then we need to // simply set the consultant call to NULL in the setupXfer block, // it will automatically be detached from the call appearance by // the CTSPICallAppearance::Drop method. case REQUEST_SETUPXFER: { RTSetupTransfer* pTrans = dynamic_cast<RTSetupTransfer*>(pReq); if (pTrans->GetConsultationCall() == pCall) pTrans->m_pConsult = NULL; break; } // Otherwise, if this is a CompleteTransfer request, then // this call could be either the consultant call or the // created conference call. The consultant call SHOULD be // valid and connected to the REAL call appearance. The // conference would not been attached - it is simply an // object at this point. // // If this is the consultant call requesting deletion, then // transition the conference call to idle (if available) and // return this block for deletion. // // Else if this is the conference call requesting deletion, // then simply remove the conference pointer in the request // block and allow the call to proceed (as a straight transfer // to the consultant call). case REQUEST_COMPLETEXFER: { RTCompleteTransfer* pTransfer = dynamic_cast<RTCompleteTransfer*>(pReq); if (pTransfer->GetConsultationCall() == pCall) { if (pTransfer->GetConferenceCall() != NULL && pTransfer->GetTransferMode() == LINETRANSFERMODE_CONFERENCE) pTransfer->GetConferenceCall()->SetCallState(LINECALLSTATE_IDLE); return true; } else if (pTransfer->GetConferenceCall() == pCall) return true; break; } // If this is a SetupConference command, then the request is // always inserted on the CONFERENCE call handle, so we need to // check for the consultation and REAL call appearances. If // this is the real call asking for the deletion, then the conference // call is considered invalid (since it hasn't been completed). case REQUEST_SETUPCONF: { RTSetupConference* pConf = dynamic_cast<RTSetupConference*>(pReq); // If it is the REAL call being dropped, then the // entire request becomes invalid. Idle the conference // and consultant call and delete this request. if (pConf->GetOriginalCall() == pCall) { pConf->GetConferenceCall()->SetCallState(LINECALLSTATE_IDLE); pConf->GetConsultationCall()->SetCallState(LINECALLSTATE_IDLE); return true; } // If it is the consultant call, then simply remove it // from the call structure, but allow the conference to // still be setup - the request can be invalidated later // by the service provider (when it processes this) if that // type of conference is not allowed. else if (pConf->GetConsultationCall() == pCall) { pConf->GetConferenceCall()->DetachCall(); pCall->DetachCall(); pConf->m_pConsult = NULL; } break; } // Else if this is an ADD TO CONFERENCE request, then we // only have a consultant call to add to the conference. If // it gets dropped, then delete the request case REQUEST_ADDCONF: { RTAddToConference* pConf = dynamic_cast<RTAddToConference*>(pReq); if (pConf->GetConsultationCall() == pCall) return true; break; } // Default handler default: break; } } } // Request didn't match. return false; }// CTSPIConnection::IsMatchingRequest /////////////////////////////////////////////////////////////////////////////// // CTSPIConnection::FindRequest // // Locate a request packet based on a call appearance and command type. // CTSPIRequest* CTSPIConnection::FindRequest(CTSPICallAppearance* pCall, int nReqType) const { // Walk through all the requests and see if any match our connection, call, request criteria. CEnterCode sLock(this); // Synch access to object for (TRequestList::const_iterator posCurr = m_lstAsynchRequests.begin(); posCurr != m_lstAsynchRequests.end(); ++posCurr) { // If this request doesn't match what we are searching for, then skip it. if ((pCall && (*posCurr)->GetCallInfo() != pCall) || (nReqType != REQUEST_ALL && nReqType != (*posCurr)->GetCommand())) continue; return (*posCurr); } return NULL; }// CTSPIConnection::FindRequest /////////////////////////////////////////////////////////////////////////////// // CTSPIConnection::GetCurrentRequest // // Return the head request in our asynch request list. Override // this function if you want to skip certain requests. // CTSPIRequest* CTSPIConnection::GetCurrentRequest(BOOL fAddRef) const { CEnterCode sLock(this); // Synch access to object if (m_lstAsynchRequests.empty() == true) return NULL; CTSPIRequest* pRequest = m_lstAsynchRequests.front(); if (fAddRef) pRequest->AddRef(); return pRequest; }// CTSPIConnection::GetCurrentRequest /////////////////////////////////////////////////////////////////////////////// // CTSPIConnection::GetRequest // // Get a specific request based on a position. // CTSPIRequest* CTSPIConnection::GetRequest(unsigned int iPos, BOOL fAddRef) const { CEnterCode sLock(this); // Synch access to object if (m_lstAsynchRequests.size() > iPos) { for (TRequestList::const_iterator posCurr = m_lstAsynchRequests.begin(); posCurr != m_lstAsynchRequests.end(); ++posCurr) { if (iPos-- == 0) { CTSPIRequest* pRequest = (*posCurr); if (pRequest->GetState() == STATE_NOTPROCESSED) pRequest->SetState(STATE_INITIAL); if (fAddRef) pRequest->AddRef(); return pRequest; } } } return NULL; }// CTSPIConnection::GetRequest //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::WaitForAllRequests // // Wait for pending requests to complete on the specifid line/call // of the specifid type. // void CTSPIConnection::WaitForAllRequests(CTSPICallAppearance* pCall, int nRequest) { CEnterCode Key(this, false); // Synch access to object for(;;) { _TSP_VERIFY(Key.Lock() == true); TRequestList::iterator posCurr; for (posCurr = m_lstAsynchRequests.begin(); posCurr != m_lstAsynchRequests.end(); ++posCurr) { CTSPIRequest* pRequest = (*posCurr); if ((pCall == NULL || pRequest->GetCallInfo() == pCall) && (nRequest == REQUEST_ALL || pRequest->GetCommand() == nRequest)) { pRequest->AddRef(); Key.Unlock(); pRequest->WaitForCompletion(INFINITE); pRequest->DecRef(); break; } } if (posCurr == m_lstAsynchRequests.end()) break; } }// CTSPIConnection::WaitForAllRequests //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::AddDeviceClass // // Add a STRING data object to our device class list // int CTSPIConnection::AddDeviceClass (LPCTSTR pszClass, LPCTSTR lpszBuff, DWORD dwType) { if (dwType == -1L) { CTSPILineConnection* pLine = dynamic_cast<CTSPILineConnection*>(this); if (pLine != NULL) dwType = pLine->m_LineCaps.dwStringFormat; else { CTSPIPhoneConnection* pPhone = dynamic_cast<CTSPIPhoneConnection*>(this); if (pPhone != NULL) dwType = pPhone->m_PhoneCaps.dwStringFormat; } } return AddDeviceClass (pszClass, dwType, const_cast<LPVOID>(reinterpret_cast<LPCVOID>(lpszBuff)), (lstrlen(lpszBuff)+1) * sizeof(TCHAR)); }// CTSPIConnection::AddDeviceClass /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::OnNewRequest // // A new request is being added to our connection object. The derived // provider may override this function or CTSPIDevice::OnNewRequest or // the CServiceProvider::OnNewRequest function to catch these and perform // some function BEFORE the request has officially been added. // // If false is returned, the request will be canceled. // bool CTSPIConnection::OnNewRequest (CTSPIRequest* pReq, int* piPos) { return GetDeviceInfo()->OnNewRequest (this, pReq, piPos); }// CTSPIConnection::OnNewRequest //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::OpenDevice // // This method is called when lineOpen or phoneOpen is called. // bool CTSPIConnection::OpenDevice() { // Default behavior is to pass onto the device class. This allows for // a single device object to control access for ALL connections (i.e. // a modem style device). return GetDeviceInfo()->OpenDevice (this); }// CTSPIConnection::Open //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::CloseDevice // // This method is called when the last line/phone connection object is // closed. It will not be called if multiple lines/phones are open on this // device. // bool CTSPIConnection::CloseDevice () { // Default behavior is to pass onto the device class. This allows for // a single device object to control access for ALL connections (i.e. // a modem style device). return GetDeviceInfo()->CloseDevice (this); }// CTSPIConnection::Close //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::OnTimer // // This is invoked by our periodic timer called from the device manager // object (m_pDevice). // void CTSPIConnection::OnTimer() { /* Do nothing */ }// CTSPIConnection::OnTimer //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::OnCancelRequest // // This is called when a request is canceled on this line/phone. // void CTSPIConnection::OnCancelRequest (CTSPIRequest* pReq) { GetDeviceInfo()->OnCancelRequest(pReq); }// CTSPIConnection::OnCancelRequest //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::ReceiveData // // Data has been received by the device. This method looks in our created // TSPIREQ map and forwards the request to the appropriate function handler. // // We assume (since most devices work this way) that we only handle a // single device request at a time (i.e. we don't issue commands for // another TAPI requests on the same line before waiting for completion // of the first. If your TSP design wants to do this you should replace // the implementation of this function in your device object. // bool CTSPIConnection::ReceiveData(LPCVOID lpBuff) { // Get the current request from the handler list. Note that if you // wish to alter the logic associated with the current request (i.e. // some sort of priority) then you can override the GetCurrentRequest() // function used here to retrieve the top request. CTSPIRequest* pRequest = GetCurrentRequest(TRUE); if (pRequest != NULL) { // Set the state as initial if this request has not been processed before. // WARNING: This step is important and must be done in any derived code !!! if (pRequest->GetState() == STATE_NOTPROCESSED) pRequest->SetState(STATE_INITIAL); // Dispatch the request. if (DispatchRequest(pRequest, lpBuff)) { pRequest->DecRef(); return true; } pRequest->DecRef(); } // No handler managed the request, forward the event to the unsolicited handler return (lpBuff != NULL) ? UnsolicitedEvent(lpBuff) : false; }// CTSPIConnection::ReceiveData //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::DispatchRequest // // This dispatches the requests to the proper "OnXXX" handler in the // derived TSP code. // bool CTSPIConnection::DispatchRequest(CTSPIRequest* pRequest, LPCVOID lpBuff) { // Get the request map TRequestMap* pMap = GetRequestMap(); _TSP_ASSERTE(pMap != NULL); // Look in our request map and see if we have a handler for // this TAPI request type (REQUEST_xxx). Note we don't need to lock // any semaphore here because the request map is fixed -- it should never // change in the lifetime of the provider. TRequestMap::iterator theIterator = pMap->find(pRequest->GetCommand()); if (theIterator != pMap->end()) { // Pass the request onto our handler. If it returns TRUE, then // skip the unsolicited handler. tsplib_REQPROC func = (*theIterator).second; if (func != NULL) { if ((this->*func)(pRequest, lpBuff)) return true; } // Otherwise we had an entry in our map but the function pointer // is NULL. This is used for auto functions (functions which are // exported and handled by the library). Simply complete the request. else CompleteRequest(pRequest, 0); } // If we do not have a handler for this request then it is exported from // the .DEF file but no ON_TSPI_REQUEST handler is in place, give a warning // and finish the request with operation failed. else { #ifdef _DEBUG _TSP_DTRACE(_T("%s: Missing ON_TSPI_REQUEST handler for %s"), m_strName.c_str(), pRequest->Dump().c_str()); #endif if (IsLineDevice()) { CompleteRequest(pRequest, LINEERR_OPERATIONFAILED); } else { _TSP_ASSERTE(IsPhoneDevice()); CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED); } } return false; }// CTSPIConnection::DispatchRequest //////////////////////////////////////////////////////////////////////////// // CTSPIConnection::UnsolicitedEvent // // Data has been received by the device but there is not a pending // request which is available to process the data // bool CTSPIConnection::UnsolicitedEvent (LPCVOID /*lpBuff*/) { return false; }// CTSPIConnection::UnsolicitedEvent /////////////////////////////////////////////////////////////////////////// // CTSPIConnection::GetID // // This method returns device information about the device and its // associated resource handles. // LONG CTSPIConnection::GetID(const TString& strDevClass, LPVARSTRING lpDeviceID, HANDLE hTargetProcess) { DEVICECLASSINFO* pDeviceClass = GetDeviceClass(strDevClass.c_str()); if (pDeviceClass != NULL) return GetSP()->CopyDeviceClass (pDeviceClass, lpDeviceID, hTargetProcess); if (IsLineDevice()) { return LINEERR_INVALDEVICECLASS; } else { _TSP_ASSERTE(IsPhoneDevice()); return PHONEERR_INVALDEVICECLASS; } }// CTSPIConnection::GetID
[ "Owner@.(none)" ]
[ [ [ 1, 990 ] ] ]
8b185f1be8fa0abb2c8fd807689c32e74c857fcc
deb8ef49795452ff607023c6bce8c3e8ed4c8360
/Projects/UAlbertaBot/Source/micromanagement/OverlordManager.cpp
176b0b4487d27f98c5d68df3283c73716bdf8980
[]
no_license
timburr1/ou-skynet
f36ed7996c21f788a69e3ae643b629da7d917144
299a95fae4419429be1d04286ea754459a9be2d6
refs/heads/master
2020-04-19T22:58:46.259980
2011-12-06T20:10:34
2011-12-06T20:10:34
34,360,542
0
0
null
null
null
null
UTF-8
C++
false
false
8,918
cpp
#include "Common.h" #include "OverlordManager.h" #define FOROVERLORDS(A) foreach(Unit * A, Broodwar->self()->getUnits()) if (A->getType() == UnitTypes::Zerg_Overlord) #define FORENEMYUNITS(A) foreach(Unit * A, Broodwar->getAllUnits()) if (A->getPlayer() != Broodwar->self()) using namespace BWAPI; OverlordManager * OverlordManager::instance = NULL; OverlordManager::OverlordManager() { range = 15; xi = range/2; yi = range/2; overlordScout = NULL; } // get an instance of this OverlordManager * OverlordManager::getInstance() { // if the instance doesn't exist, create it if (!OverlordManager::instance) { OverlordManager::instance = new OverlordManager(); } return OverlordManager::instance; } void OverlordManager::update() { ++frame; for (int x=xi; x<Broodwar->mapWidth(); x+=range) for (int y=yi; y<Broodwar->mapHeight(); y+=range) { Broodwar->drawDot(BWAPI::CoordinateType::Map, x*32, y*32, BWAPI::Colors::Green); } // if our overlord is scouting if (overlordScout) { // if we know the enemy's main base location if (UnitInfoState::getInstance()->getMainBaseLocation(BWAPI::Broodwar->enemy())) { // get the overlord back home overlordScout->attackMove(BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation())); overlordScout = NULL; } } if (frame % 30 == 0) { std::map<BWAPI::Unit *, BWAPI::Position>::iterator it1; std::map<BWAPI::Unit *, bool>::iterator it2; // for each overlord FOROVERLORDS (o) { bool shouldFlee = false; Position fleeVector; // find its assigned position it1 = overlord_positions.find(o); // find whether it's tethered it2 = overlord_tethered.find(o); UnitVector nearEnemies; threats.clear(); // if it has a position and a tether flag if (it1 != overlord_positions.end() && it2 != overlord_tethered.end()) { // get all of the enemy units within range of the overlord MapGrid::getInstance()->GetUnits(nearEnemies, o->getPosition(), UnitTypes::Zerg_Overlord.sightRange() + 200, false, true); for (size_t i(0); i<nearEnemies.size(); ++i) { if (nearEnemies[i]->getType().airWeapon() != BWAPI::WeaponTypes::None) { shouldFlee = true; } } // if it's tethered if (it2->second) { // if there's a unit which can attack it, move away from it if (shouldFlee) { Position op = o->getPosition(); Position away = op + getFleeVector(threats, o); o->attackMove(away); Broodwar->drawTextMap(o->getPosition().x(), o->getPosition().y(), "Fleeing"); // if there's no attacking unit nearby } else { // move to tethered position o->attackMove(it1->second); Broodwar->drawTextMap(o->getPosition().x(), o->getPosition().y(), "Tethered"); } } } } } } // what to do when an overlord is created void OverlordManager::onOverlordCreate(Unit * unit) { // assign the overlord to the nearest unoccupied position overlord_positions[unit] = closestUnoccupiedPosition(unit); // tether it tetherOverlord(unit); } // what to do when an overlord is destroyed void OverlordManager::onOverlordDestroy(Unit * unit) { // erase its assignment from the maps overlord_positions.erase(unit); overlord_tethered.erase(unit); } void OverlordManager::setAttackPosition(BWAPI::Position attackPosition) { UnitVector overlords; FOROVERLORDS(o) { overlords.push_back(o); } std::sort(overlords.begin(), overlords.end(), OverlordCompareDistance(attackPosition)); int numOverlordsOnAttack = 2; // find the closest number of overlords to the attack Position for (size_t i(0); (int)i<numOverlordsOnAttack && i<overlords.size(); ++i) { BWAPI::Position pos(attackPosition.x() - i*200, attackPosition.y() - i*200); // untether the overlord untetherOverlord(overlords[i]); // send it to the attack position overlords[i]->move(pos); // draw a circle on it so we know where it is BWAPI::Broodwar->drawCircleMap(overlords[i]->getPosition().x(), overlords[i]->getPosition().y(), 10, BWAPI::Colors::Red, true); } } void OverlordManager::tetherAllOverlords() { FOROVERLORDS(o) { // if the overlord current has a tether option if (overlord_tethered.find(o) != overlord_tethered.end()) { // tether it overlord_tethered.find(o)->second = true; } } } // tether an overlord into its assigned position void OverlordManager::tetherOverlord(Unit * unit) { overlord_tethered[unit] = true; } // untether an overlord, free to do other things void OverlordManager::untetherOverlord(Unit * unit) { overlord_tethered[unit] = false; } BWAPI::Unit * OverlordManager::getClosestOverlord(BWAPI::Position p) { BWAPI::Unit * overlord = NULL; double distance = 1000000; FOROVERLORDS(o) { if (!overlord || o->getDistance(p) < distance) { overlord = o; distance = o->getDistance(p); } } return overlord; } // returns the closest unassigned position to the unit Position OverlordManager::closestUnoccupiedPosition(Unit * unit) { // placeholders double minDist = ( Broodwar->mapWidth() + Broodwar->mapWidth() ) * 32; Position closest; // for each of our positions for (int x=xi; x<Broodwar->mapWidth(); x+=range) for (int y=yi; y<Broodwar->mapHeight(); y+=range) { Position temp(x*32,y*32); // which is the closest unassigned position? if (unit->getDistance(temp) < minDist && !overlordAssigned(temp)) { minDist = unit->getDistance(temp); closest = temp; } } // return it return closest; } // is there an overlord within distance 'dist' of position p? bool OverlordManager::overlordNear(Position p, double dist) { // for each overlord FOROVERLORDS(unit) { // if it's closer, return true if (unit->getDistance(p) < dist) return true; } // otherwise return false return false; } // is there an overlord within distance 'dist' of position p? bool OverlordManager::overlordAssigned(BWAPI::Position p) { // for each overlord assignment for (std::map<BWAPI::Unit *,BWAPI::Position>::iterator it = overlord_positions.begin(); it != overlord_positions.end(); it++) { // return true if we've already assigned it if (p == it->second) return true; } // otherwise return false return false; } void OverlordManager::onStart() { // get starting locations std::set< TilePosition > startLocations = Broodwar->getStartLocations(); TilePosition scout(0,0); // get the first starting location that isn't ours foreach (TilePosition tp, startLocations) { // if it's not our start position if (tp != Broodwar->self()->getStartLocation()) { // set the spot to scout as this position and break scout = tp; break; } } // do clever stuff with starting units FOROVERLORDS(o) { // send first overlord to scout //overlordScout = o; //o->attackMove(scout); break; } } void OverlordManager::fillAirThreats(std::vector<AirThreat> & threats, UnitVector & candidates) { // for each of the candidate units foreach(BWAPI::Unit * e, candidates) { // default threat AirThreat threat; threat.unit = e; threat.weight = 1; // get the air weapon of the unit BWAPI::WeaponType airWeapon(e->getType().airWeapon()); // if it's a bunker, weight it as if it were 4 marines if(e->getType() == BWAPI::UnitTypes::Terran_Bunker) { airWeapon = BWAPI::WeaponTypes::Gauss_Rifle; threat.weight = 4; } // weight the threat based on the highest DPS if(airWeapon != BWAPI::WeaponTypes::None) { threat.weight *= (static_cast<double>(airWeapon.damageAmount()) / airWeapon.damageCooldown()); threats.push_back(threat); } } } double2 OverlordManager::getFleeVector(const std::vector<AirThreat> & threats, BWAPI::Unit * overlord) { double2 fleeVector(0,0); foreach(const AirThreat & threat, threats) { // Get direction from enemy to mutalisk const double2 direction(overlord->getPosition() - threat.unit->getPosition()); // Divide direction by square distance, weighting closer enemies higher // Dividing once normalises the vector // Dividing a second time reduces the effect of far away units const double distanceSq(direction.lenSq()); if(distanceSq > 0) { // Enemy influence is direction to flee from enemy weighted by danger posed by enemy const double2 enemyInfluence( (direction / distanceSq) * threat.weight ); fleeVector = fleeVector + enemyInfluence; } } if(fleeVector.lenSq() == 0) { // Flee towards our base fleeVector = double2(1,0); } fleeVector.normalise(); BWAPI::Position p1(overlord->getPosition()); BWAPI::Position p2(p1 + fleeVector * 100); return fleeVector; }
[ "[email protected]@ce23f72d-95c0-fd94-fabd-fc6dce850bd1" ]
[ [ [ 1, 340 ] ] ]
5ad8f1a58f5c38c9a3039b1d3448e24583e05c1b
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/LWcommon/FileLib.cpp
949b662e58d4858ddbdbbf950449b5d2ffb358ba
[]
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
405
cpp
#include "StdAfx.h" #include "FileLib.h" namespace FileLib { bool FileExists(std::string ToCheck) { if ( ToCheck == "" ) return false; std::ifstream FOpener; FOpener.open(ToCheck.c_str()); if (FOpener.is_open()) { FOpener.close(); return true; } else return false; } }
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 20 ] ] ]
62e9d97a07d3e62816e294485c4b70816a2d5b1a
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Database/Detail/UtilitySerialization.h
2e7d420fb56643b79ae1ff5a42a8aef5ef732b84
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
3,335
h
#ifndef __SLON_ENGINE_DATABASE_DETAIL_UTILITY_SERIALIZATION_H__ #define __SLON_ENGINE_DATABASE_DETAIL_UTILITY_SERIALIZATION_H__ #include "../../Utility/Algorithm/aabb_tree.hpp" #include "SGLSerialization.h" namespace slon { namespace database { // math serialization template<typename LeafData, typename RealType, typename Func> void serialize(OArchive& ar, const char* name, const aabb_tree<LeafData, RealType>& tree, Func leafSerializer) { typedef typename aabb_tree<LeafData, RealType>::volume_node volume_node; ar.openChunk(name); const volume_node* node = tree.get_root(); while (node) { ar.openChunk("volume_node"); serialize(ar, "volume", node->get_bounds()); bool leaf = node->is_leaf(); ar.writeChunk("leaf", &leaf); if (leaf) { leafSerializer(ar, node->as_leaf()->data); ar.closeChunk(); // go up until we find nonvisited right child const volume_node* parent = node->get_parent(); while (parent && parent->get_child(1) == node) { node = parent; parent = node->get_parent(); ar.closeChunk(); } if (parent) { node = parent->get_child(1); } else { node = 0; } } else { node = node->get_child(0); } } ar.closeChunk(); } template<typename LeafData, typename RealType, typename Func> typename aabb_tree<LeafData, RealType>::volume_node* deserialize_aabb_tree_node(IArchive& ar, Func leafDeserializer) { typedef typename aabb_tree<LeafData, RealType>::volume_node volume_node; typedef typename aabb_tree<LeafData, RealType>::leaf_node leaf_node; typedef typename aabb_tree<LeafData, RealType>::aabb_type aabb_type; volume_node* node = 0; aabb_type volume; deserialize(ar, "volume", volume); bool leaf; ar.readChunk("leaf", &leaf); if (leaf) { node = new leaf_node(volume, leafDeserializer(ar)); } else { IArchive::chunk_info info; node = new volume_node(volume); ar.openChunk("volume_node", info); node->set_child( 0, deserialize_aabb_tree_node<LeafData, RealType>(ar, leafDeserializer) ); ar.closeChunk(); ar.openChunk("volume_node", info); node->set_child( 1, deserialize_aabb_tree_node<LeafData, RealType>(ar, leafDeserializer) ); ar.closeChunk(); } return node; } template<typename LeafData, typename RealType, typename Func> void deserialize(IArchive& ar, const char* name, aabb_tree<LeafData, RealType>& tree, Func leafDeserializer) { IArchive::chunk_info info; if ( !ar.openChunk(name, info) ) { throw serialization_error("Can't open AABB tree chunk"); } typename aabb_tree<LeafData, RealType>::volume_node* root = 0; if ( ar.openChunk("volume_node", info) ) { root = deserialize_aabb_tree_node<LeafData, RealType>(ar, leafDeserializer); ar.closeChunk(); } tree.set_root(root); ar.closeChunk(); } } // namespace slon } // namespace database #endif // __SLON_ENGINE_DATABASE_DETAIL_UTILITY_SERIALIZATION_H__
[ "devnull@localhost" ]
[ [ [ 1, 106 ] ] ]
403c5fbcffb4257e87888c68af05d2707f891d81
f95341dd85222aa39eaa225262234353f38f6f97
/ScreenSavers/Flurry/Sources/Flurry/FlurryCluster.cpp
c455cd283b970d7924aa46052140e31166a5f5c2
[]
no_license
Templier/threeoaks
367b1a0a45596b8fe3607be747b0d0e475fa1df2
5091c0f54bd0a1b160ddca65a5e88286981c8794
refs/heads/master
2020-06-03T11:08:23.458450
2011-10-31T04:33:20
2011-10-31T04:33:20
32,111,618
0
0
null
null
null
null
UTF-8
C++
false
false
5,954
cpp
/////////////////////////////////////////////////////////////////////////////////////////////// // // Flurry : Settings class // // Encapsulate the Flurry code away from the non-Flurry-specific screensaver // code. Glue clode around the single flurry cluster that's what the core // code knows how to render. // // Copyright (c) 2003, Matt Ginzton // Copyright (c) 2005-2008, Julien Templier // All rights reserved. // /////////////////////////////////////////////////////////////////////////////////////////////// // * $LastChangedRevision$ // * $LastChangedDate$ // * $LastChangedBy$ /////////////////////////////////////////////////////////////////////////////////////////////// // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // o Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // o 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. // o Neither the name of the author 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 "FlurryCluster.h" #include "FlurryPreset.h" #include "FlurrySettings.h" #include "TimeSupport.h" #include <math.h> // unconfuse cpp, which will see it inside extern "C" with __cplusplus defined extern "C" { #include "Core/gl_saver.h" } using namespace Flurry; /////////////////////////////////////////////////////////////////////////// // // public functions /* * Note: the Flurry base code keeps everything in a global variable named * info. We want to instance it, for multimon support (several separate * Flurries), so we allocate several such structures, but to avoid changing * the base code, we set info = current->globals before calling into it. * Obviously, not thread safe. */ Cluster::Cluster(const ClusterSpec& spec, Settings* settings) { oldFrameTime = TimeInSecondsSinceStart(); maxFrameProgressInMs = settings->maxFrameProgressInMs; data = Alloc(); // specialize data->numStreams = spec.nStreams; data->currentColorMode = (ColorModes)spec.color; data->streamExpansion = spec.thickness; data->star->rotSpeed = spec.speed; } Cluster::~Cluster() { for (int i = 0; i < MAXNUMPARTICLES; i++) { free(data->p[i]); } free(data->s); free(data->star); for (int i = 0; i < 64; i++) { free(data->spark[i]); } free(data); } void Cluster::SetSize(int width, int height) { // make this flurry cluster current BecomeCurrent(); // resize it GLResize(width, height); } void Cluster::PrepareToAnimate() { // make this flurry cluster current BecomeCurrent(); // initialize it GLSetupRC(); } void Cluster::AnimateOneFrame() { // make this flurry cluster current BecomeCurrent(); // Calculate the amount of progress made since the last frame // The Flurry core code does this itself, but we do our own calculation // here, and if we don't like the answer, we adjust our copy and then // tell the timer to lie so that when the core code reads it, it gets // the adjusted value. double newFrameTime = TimeInSecondsSinceStart(); double deltaFrameTime = newFrameTime - oldFrameTime; if (maxFrameProgressInMs > 0) { double maxFrameTime = maxFrameProgressInMs / 1000.0; double overtime = deltaFrameTime - maxFrameTime; if (overtime > 0) { _RPT3(_CRT_WARN, "Delay: hiding %g seconds (last=%g limit=%g)\n", overtime, deltaFrameTime, maxFrameTime); TimeSupport_HideHostDelay(overtime); deltaFrameTime -= overtime; newFrameTime -= overtime; } } oldFrameTime = newFrameTime; // dim the existing screen contents glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4d(0.0, 0.0, 0.0, 5.0 * deltaFrameTime); glRectd(0, 0, info->sys_glWidth, info->sys_glHeight); // then render the new frame blended over what's already there GLRenderScene(); glFlush(); } CoreData *Cluster::Alloc() { CoreData *flurry = (CoreData *)malloc(sizeof *flurry); flurry->flurryRandomSeed = RandFlt(0.0f, 300.0f); flurry->numStreams = 5; flurry->streamExpansion = 100; flurry->currentColorMode = tiedyeColorMode; for (int i = 0; i < MAXNUMPARTICLES; i++) { flurry->p[i] = (struct Particle *)malloc(sizeof(Particle)); } flurry->s = (struct SmokeV *)malloc(sizeof(SmokeV)); InitSmoke(flurry->s); flurry->star = (struct Star *)malloc(sizeof(Star)); InitStar(flurry->star); flurry->star->rotSpeed = 1.0; for (int i = 0; i < 64; i++) { flurry->spark[i] = (struct Spark *)malloc(sizeof(Spark)); InitSpark(flurry->spark[i]); } return flurry; } void Cluster::BecomeCurrent() { info = data; }
[ "julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d" ]
[ [ [ 1, 188 ] ] ]
03f1f55d6b73bcde7f44dce57cb3984ec3149a4a
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/instructions/SLL.h
76f54a2aeab2f8a612403f2c60de2b62d2beed07
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
h
template< > struct AllegrexInstructionTemplate< 0x00000000, 0xffe0003f > : AllegrexInstructionUnknown { static AllegrexInstructionTemplate &self() { static AllegrexInstructionTemplate insn; return insn; } static AllegrexInstruction *get_instance() { return &AllegrexInstructionTemplate::self(); } virtual AllegrexInstruction *instruction(u32 opcode) { return this; } virtual char const *opcode_name() { return "SLL"; } virtual void interpret(Processor &processor, u32 opcode); virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment); protected: AllegrexInstructionTemplate() {} }; typedef AllegrexInstructionTemplate< 0x00000000, 0xffe0003f > AllegrexInstruction_SLL; namespace Allegrex { extern AllegrexInstruction_SLL &SLL; } #ifdef IMPLEMENT_INSTRUCTION AllegrexInstruction_SLL &Allegrex::SLL = AllegrexInstruction_SLL::self(); #endif
[ [ [ 1, 41 ] ] ]
e249cade58dfb3c06f7bd8435ce8638f28d47bc2
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/wave/samples/list_includes/list_includes.hpp
26aa168e4bac87ee5cd15ad5bffc48e0c8dade12
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,718
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Sample: List include dependencies of a given source file Configuration data http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(LIST_INCLUDES_HPP_843DB412_3AA8_4BCF_8081_AA4A5FDE0BE7_INCLUDED) #define LIST_INCLUDES_HPP_843DB412_3AA8_4BCF_8081_AA4A5FDE0BE7_INCLUDED /////////////////////////////////////////////////////////////////////////////// // include often used files from the stdlib #include <iostream> #include <fstream> #include <string> #include <vector> #include <set> /////////////////////////////////////////////////////////////////////////////// // include boost config #include <boost/config.hpp> // global configuration information /////////////////////////////////////////////////////////////////////////////// // build version #include "list_includes_version.hpp" /////////////////////////////////////////////////////////////////////////////// // configure this app here (global configuration constants) #include "list_includes_config.hpp" /////////////////////////////////////////////////////////////////////////////// // include required boost libraries #include <boost/assert.hpp> #include <boost/pool/pool_alloc.hpp> #endif // !defined(LIST_INCLUDES_HPP_843DB412_3AA8_4BCF_8081_AA4A5FDE0BE7_INCLUDED)
[ "metrix@Blended.(none)" ]
[ [ [ 1, 42 ] ] ]
cffc55b96fb1552f92cc3be01a0cdb04303a2c12
744de6bcb690e1b499bae6f5d32a4eedb87eb2e6
/FaceRecognition/FaceRecognitionDlg.cpp
e638c3e86788e5678234007033e37b56a4b123ff
[]
no_license
zinking/myfacedetection
b627a4ccc2af4de9c5bdf0b02da648078e2d14c6
12180761a5f5a193359ba43dd591e52eebd65751
refs/heads/master
2021-01-19T14:29:53.176953
2008-12-03T09:09:13
2008-12-03T09:09:13
32,133,342
0
0
null
null
null
null
GB18030
C++
false
false
24,054
cpp
// FaceRecognitionDlg.cpp : 实现文件 // #include "stdafx.h" #include "FaceRecognition.h" #include "FaceRecognitionDlg.h" #include "facerecognitiondlg.h" #include "CvApp.h" #include "cv.h" #include "highgui.h" #include <stdlib.h> #ifdef _DEBUG #define new DEBUG_NEW #endif int FRAMEPERSECOND= 15; // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CFaceRecognitionDlg 对话框 CFaceRecognitionDlg::CFaceRecognitionDlg(CWnd* pParent /*=NULL*/) : CDialog(CFaceRecognitionDlg::IDD, pParent) // , m_path(_T("")) , m_openPath(_T("")) , m_savePath(_T("")) , m_videoPath(_T("")) , m_bDetect(FALSE) { m_pCv1= NULL; m_pCv2= NULL; m_pCv3= NULL; m_pCv4= NULL; m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } CFaceRecognitionDlg::~CFaceRecognitionDlg() { if(m_pCv1 != NULL) delete m_pCv1; if(m_pCv2 != NULL) delete m_pCv2; if(m_pCv3 != NULL) delete m_pCv3; if(m_pCv4 != NULL) delete m_pCv4; } void CFaceRecognitionDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); // DDX_Text(pDX, IDC_PATH, m_path); DDX_Text(pDX, IDC_OPENPATH, m_openPath); DDX_Text(pDX, IDC_SAVEPATH, m_savePath); DDX_Text(pDX, IDC_VIDEOPATH, m_videoPath); // DDX_Radio(pDX, IDC_RADIODETECT, m_bDetect); DDX_Control(pDX, IDC_CHECKDETECT, m_checkDetect); DDX_Control(pDX, IDC_CHECK2, m_checkPause); DDX_Control(pDX, IDC_CHECKPROFILE, m_checkProfile); DDX_Control(pDX, IDC_CHECKFRONTAL, m_checkFrontal); DDX_Control(pDX, IDC_SLIDER1, m_slFrameRate); } BEGIN_MESSAGE_MAP(CFaceRecognitionDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_OPEN, OnBnClickedOpen) ON_BN_CLICKED(IDOK, OnBnClickedOk) ON_BN_CLICKED(IDC_SAVE, OnBnClickedSave) // ON_BN_CLICKED(IDC_DETECT, OnBnClickedDetect) ON_BN_CLICKED(IDC_CAM, OnBnClickedCam) ON_WM_TIMER() ON_BN_CLICKED(IDC_OPENVEDIO, OnBnClickedOpenvedio) // ON_BN_CLICKED(IDC_SAVEVEDIO, OnBnClickedSavevedio) ON_BN_CLICKED(IDC_SAVECAM, OnBnClickedSavecam) // ON_BN_CLICKED(IDC_PAUSE, OnBnClickedPause) // ON_BN_CLICKED(IDC_CEASE, OnBnClickedCease) ON_BN_CLICKED(IDC_RADIODETECT, OnBnClickedRadiodetect) ON_BN_CLICKED(IDC_RADIODETECT2, OnBnClickedRadiodetect2) ON_BN_CLICKED(IDC_CHECKDETECT, OnBnClickedCheckdetect) ON_BN_CLICKED(IDC_CHECK2, OnBnClickedCheck2) ON_BN_CLICKED(IDC_About, OnBnClickedAbout) ON_BN_CLICKED(IDC_CHECKPROFILE, OnBnClickedCheckprofile) ON_BN_CLICKED(IDC_CHECKFRONTAL, OnBnClickedCheckfrontal) ON_BN_CLICKED(IDC_OPEN_TRAIN, &CFaceRecognitionDlg::OnBnClickedOpenTrain) ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_SLDFRAMERATE, &CFaceRecognitionDlg::OnNMReleasedcaptureSldframerate) END_MESSAGE_MAP() // CFaceRecognitionDlg 消息处理程序 BOOL CFaceRecognitionDlg::OnInitDialog() { CDialog::OnInitDialog(); // 将\“关于...\”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 // m_checkDetect.SetCheck(0); //复选框设置未选中 // m_checkPause.SetCheck(0); m_checkDetect.EnableWindow(FALSE); m_checkPause.EnableWindow(FALSE); m_checkProfile.EnableWindow(FALSE); m_checkFrontal.EnableWindow(FALSE); return TRUE; // 除非设置了控件的焦点,否则返回 TRUE } void CFaceRecognitionDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CFaceRecognitionDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标显示。 HCURSOR CFaceRecognitionDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } //打开图片文件 void CFaceRecognitionDlg::OnBnClickedOpen() { // TODO: 在此添加控件通知处理程序代码 CFileDialog fileDlg(TRUE, _T("*.bmp"), "", OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY, "Image Files (*.jpg; *.bmp)|*.jpg; *.bmp|All Files (*.*)|*.*||", NULL); //设置打开对话框的标题 char title[]= {"打开图片"}; fileDlg.m_pOFN->lpstrTitle= title; if(fileDlg.DoModal()==IDOK) { CString pathName= fileDlg.GetPathName(); m_openPath= pathName; UpdateData(FALSE); m_pCv1=new CCvApp(pathName, 0); // m_pCv1->display(pathName); cvvNamedWindow(pathName, 1); //显示图片 IplImage* pImg= m_pCv1->getImage(); if(pImg) { if(m_bDetect) cvvShowImage(pathName, m_pCv1->detectFace(pImg)); else cvvShowImage(pathName, pImg); } // m_path= pathName; //display picture in picture control // DrawPicToHDC(m_pCv->getImage(), IDC_PICTURE); } } //打开视频文件 void CFaceRecognitionDlg::OnBnClickedOpenvedio() { // TODO: 在此添加控件通知处理程序代码 m_slFrameRate.SetRange(1, 24 ); UpdateData(TRUE); CFileDialog fileDlg(TRUE, _T("*.avi"), "", OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY, "Vedio Files (*.avi)|*.avi|All Files (*.*)|*.*||", NULL); //设置打开对话框的标题 char title[]= {"打开视频"}; fileDlg.m_pOFN->lpstrTitle= title; if(fileDlg.DoModal()==IDOK) { // m_checkProfile.EnableWindow(TRUE); CString pathName= fileDlg.GetPathName(); m_videoPath= pathName; UpdateData(FALSE); m_pCv2=new CCvApp(m_videoPath, 1); if(!m_pCv2) { MessageBox("Memeory Allocated Failure !"); return; } if(!m_pCv2->getCapture()) return; cvNamedWindow(m_videoPath, 1); CvCapture* capture= m_pCv2->getCapture(); if( capture) { // Images to capture the frame from vedio file IplImage* frame = NULL; IplImage* frame_copy = NULL; IplImage* detect_frame= NULL; int numFrame= 0; int index= 0; // Capture from the vedio file. for(;;) { if( !cvGrabFrame( capture )) break; frame = cvRetrieveFrame( capture ); if( !frame ) break; if( !frame_copy ) frame_copy = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); // Check the origin of image. If top left, copy the image frame to frame_copy. if( frame->origin == IPL_ORIGIN_TL ) cvCopy( frame, frame_copy, 0 ); // Else flip and copy the image else cvFlip( frame, frame_copy, 0 ); //suppose there is no face in the current frame m_pCv2->exit= FALSE; //do not draw the face cvShowImage(m_videoPath, frame_copy); if(!m_bDetect) cvShowImage(m_videoPath, frame_copy); //draw the face else { //capture only one frame from the continuous 6 frames numFrame++; UpdateData(TRUE); FRAMEPERSECOND = m_slFrameRate.GetPos(); if( numFrame < FRAMEPERSECOND ) continue; else numFrame= 0; detect_frame= m_pCv2->detectFace(frame_copy); cvShowImage(m_videoPath, detect_frame); IplImage* save_frame=NULL; if(m_pCv2->exit) { index++; char* str=new char[50]; itoa(index,str,10); CString type= ".jpg"; CString picName=(CString)str+type; save_frame = cvCreateImage( cvSize(detect_frame->width,detect_frame->height), IPL_DEPTH_8U, detect_frame->nChannels ); cvCopy(detect_frame, save_frame, NULL); //cvSaveImage(picName,save_frame); } // delete str; } // Wait for a while before proceeding to the next frame if( cvWaitKey( 30 ) >= 0 ) { // m_checkProfile.EnableWindow(FALSE); break; } } cvReleaseImage( &frame_copy ); cvReleaseCapture(&capture); } } } //保存图片文件 void CFaceRecognitionDlg::OnBnClickedSave() { // TODO: 在此添加控件通知处理程序代码 //注意输入文件名时要加上后缀名, 否则会出现异常 CFileDialog fileDlg(FALSE, _T("*.jpg"), 0, OFN_HIDEREADONLY|OFN_EXPLORER|OFN_OVERWRITEPROMPT, "Image Files (*.jpg; *.bmp)|*.jpg;*.bmp||", NULL); char title[]= {"保存图片"}; fileDlg.m_pOFN->lpstrTitle=title; if(!m_pCv1) { MessageBox("Current Image is NULL!"); return; } IplImage* pImg= m_pCv1->getImage(); if(!pImg) { MessageBox("Current Image is NULL!"); return; } else { if(fileDlg.DoModal()==IDOK) { CString pathName=fileDlg.GetPathName(); m_savePath= pathName; if(m_bDetect) cvSaveImage(m_savePath, m_pCv1->detectFace(pImg)); else cvSaveImage(m_savePath,pImg); } } UpdateData(FALSE); } //保存视频文件 /*void CFaceRecognitionDlg::OnBnClickedSavevedio() { // TODO: 在此添加控件通知处理程序代码 CFileDialog fileDlg(FALSE, _T("*.avi"), 0, OFN_HIDEREADONLY|OFN_EXPLORER|OFN_OVERWRITEPROMPT, "Video Files (*.avi)|*.avi||", NULL); char title[]= {"视频另存为"}; fileDlg.m_pOFN->lpstrTitle=title; if(fileDlg.DoModal()==IDOK) { CString pathName=fileDlg.GetPathName(); if(m_pCv->getCapture()!= NULL) { CvCapture* capture=m_pCv->getCapture(); IplImage* frame,*frame_copy = 0; frame= cvQueryFrame(capture); CvVideoWriter* videoWriter; videoWriter= cvCreateVideoWriter(pathName, -1, 2.50, cvSize(frame->width, frame->height), 1); // Capture from the video file. for(;;) { // Capture the frame and load it in IplImage if( !cvGrabFrame( capture )) break; frame = cvRetrieveFrame( capture ); // If the frame does not exist, quit the loop if( !frame ) break; // Allocate framecopy as the same size of the frame if( !frame_copy ) frame_copy = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); // Check the origin of image. If top left, copy the image frame to frame_copy. if( frame->origin == IPL_ORIGIN_TL ) cvCopy( frame, frame_copy, 0 ); // Else flip and copy the image else cvFlip( frame, frame_copy, 0 ); //写入一帧到视频文件 cvWriteFrame(videoWriter, m_pCv->detectFace(frame_copy)); // Wait for a while before proceeding to the next frame if( cvWaitKey( 10 ) >= 0 ) break; } cvReleaseImage( &frame_copy ); cvReleaseVideoWriter(&videoWriter); } } }*/ //退出程序 void CFaceRecognitionDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 // if(m_pCv != NULL) // delete m_pCv; cvDestroyAllWindows(); OnOK(); } /*//检测人脸 void CFaceRecognitionDlg::OnBnClickedDetect() { // TODO: 在此添加控件通知处理程序代码 if(m_pCv != NULL ) { IplImage* pImg; IplImage* pDrawImg; pImg= m_pCv->getImage(); pDrawImg= m_pCv->detectFace( pImg ); if( pImg != NULL) cvShowImage(m_openPath, &pDrawImg); CvCapture* capture; capture= m_pCv->getCapture(); if( capture != NULL) m_pCv->detect= TRUE; } else MessageBox("Image/CAM Loading Failure!"); }*/ //打开摄像头 void CFaceRecognitionDlg::OnBnClickedCam() { // TODO: 在此添加控件通知处理程序代码 m_pCv3= new CCvApp("",2); if(m_pCv3 && m_pCv3->getCamCapture()) { m_checkDetect.EnableWindow(TRUE); m_checkPause.EnableWindow(TRUE); m_pCv3->display(""); CString fileName="CAM"; CvCapture* camcapture= m_pCv3->getCamCapture(); //显示窗口 cvvNamedWindow(fileName, 1); //显示视频 if( camcapture) { // Images to capture the frame from vedio file IplImage* frame = NULL; IplImage* frame_copy = NULL; IplImage* cur_frame= NULL; // Capture from the vedio file. for(;;) { // Capture the frame and load it in IplImage if( !cvGrabFrame( camcapture )) break; frame = cvRetrieveFrame( camcapture ); // If the frame does not exist, quit the loop if( !frame ) break; // Allocate framecopy as the same size of the frame if( !frame_copy ) frame_copy = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); // Check the origin of image. If top left, copy the image frame to frame_copy. if( frame->origin == IPL_ORIGIN_TL ) cvCopy( frame, frame_copy, 0 ); // Else flip and copy the image else cvFlip( frame, frame_copy, 0 ); //display //cvNamedWindow(fileName, 1); //do not draw the face if(!m_pCv3->pause) { if(!m_pCv3->detect) cvShowImage(fileName, frame_copy); //draw the face else cvShowImage(fileName, m_pCv3->detectFace(frame_copy)); cur_frame=cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); cvCopy(frame_copy, cur_frame, NULL); } else { cvShowImage(fileName, cur_frame); cvWaitKey( 10 ); continue; } // Wait for a while before proceeding to the next frame if( cvWaitKey( 10 ) >= 0 ) { delete m_pCv3; m_pCv3= NULL; m_checkDetect.EnableWindow(FALSE); m_checkPause.EnableWindow(FALSE); break; } /* //pause capturing frames if( pause ) cvShowImage(fileName, frame_copy); else continue;*/ } cvReleaseImage( &frame_copy ); cvReleaseCapture(&camcapture); } } } //从摄像头保存视频(检测出人脸) void CFaceRecognitionDlg::OnBnClickedSavecam() { // TODO: 在此添加控件通知处理程序代码 CFileDialog fileDlg(FALSE, _T("*.avi"), 0, OFN_HIDEREADONLY|OFN_EXPLORER|OFN_OVERWRITEPROMPT, "Video Files (*.avi)|*.avi||", NULL); m_pCv4= new CCvApp("", 2); if(!m_pCv4) { MessageBox("Memeory Allocated Failure!"); return; } //capturing cam failure if(m_pCv4->getCamCapture() == NULL) return; m_checkDetect.EnableWindow(TRUE); m_checkPause.EnableWindow(TRUE); char title[]= {"Save Video as"}; fileDlg.m_pOFN->lpstrTitle=title; if(fileDlg.DoModal()==IDOK) { CString pathName=fileDlg.GetPathName(); if(m_pCv4->getCamCapture()!= NULL) { CvCapture* capture=m_pCv4->getCamCapture(); IplImage* frame,*frame_copy = 0; IplImage* cur_frame= NULL; frame= cvQueryFrame(capture); CvVideoWriter* videoWriter; videoWriter= cvCreateVideoWriter(pathName, -1, 2.50, cvSize(frame->width, frame->height), 1); // Capture from the video file. for(;;) { // Capture the frame and load it in IplImage if( !cvGrabFrame( capture )) break; frame = cvRetrieveFrame( capture ); // If the frame does not exist, quit the loop if( !frame ) break; // Allocate framecopy as the same size of the frame if( !frame_copy ) frame_copy = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); // Check the origin of image. If top left, copy the image frame to frame_copy. if( frame->origin == IPL_ORIGIN_TL ) cvCopy( frame, frame_copy, 0 ); // Else flip and copy the image else cvFlip( frame, frame_copy, 0 ); //写入一帧到视频文件 if(! m_pCv4->pause ) { cvNamedWindow("Capturing...", 1); if(m_pCv4->detect) { IplImage* pImg=m_pCv4->detectFace(frame_copy); cvShowImage("Capturing...",pImg); cvWriteFrame(videoWriter, pImg); } else { cvShowImage("Capturing...",frame_copy); cvWriteFrame(videoWriter, frame_copy); } cur_frame=cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); cvCopy(frame_copy, cur_frame, NULL); } else { cvShowImage("Capturing...", cur_frame); cvWaitKey( 10 ); continue; } // Wait for a while before proceeding to the next frame if( cvWaitKey( 10 ) >= 0 ) { // MessageBox("Vedio has been done!"); cvDestroyWindow("Capturing..."); cvNamedWindow("Capturing Done", 1); cvShowImage("Capturing Done", frame_copy); delete m_pCv4; m_pCv4= NULL; m_checkDetect.EnableWindow(FALSE); m_checkPause.EnableWindow(FALSE); break; } // cvWaitKey(40); } cvReleaseImage( &frame_copy ); cvReleaseCapture(&capture); cvReleaseVideoWriter(&videoWriter); } } // delete m_pCv; } void CFaceRecognitionDlg::OnTimer(UINT nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CDialog::OnTimer(nIDEvent); } //在图片控件内显示图片 void CFaceRecognitionDlg::DrawPicToHDC(IplImage *img,UINT ID) { CDC *pDC = GetDlgItem(ID)->GetDC(); HDC hDC= pDC->GetSafeHdc(); CRect rect; GetDlgItem(ID)->GetClientRect(&rect); CvvImage cimg; cimg.CopyOf(img); cimg.DrawToHDC(hDC,&rect); /* 在视图中显示 CDC *pDC = GetDC(); HDC hDC= pDC->GetSafeHdc(); CRect rect; GetClientRect(&rect); CvvImage cimg; cimg.CopyOf(img); cimg.DrawToHDC(hDC,&rect); */ } /* void CFaceRecognitionDlg::OnBnClickedPause() { // TODO: 在此添加控件通知处理程序代码 // if(!m_pCv->pause) // m_pCv->pause= TRUE; // else // m_pCv->pause= FALSE; } void CFaceRecognitionDlg::OnBnClickedCease() { // TODO: 在此添加控件通知处理程序代码 if(m_pCv3) m_pCv3->cease= TRUE; if(m_pCv4) m_pCv4->cease= TRUE; } */ void CFaceRecognitionDlg::OnBnClickedRadiodetect() { // TODO: 在此添加控件通知处理程序代码 m_bDetect= FALSE; m_checkFrontal.EnableWindow(FALSE); m_checkProfile.EnableWindow(FALSE); if(m_pCv1 && m_pCv1->getImage()) cvvShowImage(m_openPath, m_pCv1->getImage()); } void CFaceRecognitionDlg::OnBnClickedRadiodetect2() { // TODO: 在此添加控件通知处理程序代码 m_bDetect= TRUE; m_checkFrontal.EnableWindow(TRUE); m_checkProfile.EnableWindow(TRUE); if(m_pCv1 && m_pCv1->getImage()) { IplImage* img=m_pCv1->getImage(); IplImage* copy = cvCreateImage( cvSize(img->width,img->height), IPL_DEPTH_8U, img->nChannels ); cvCopy(img, copy, NULL); cvvShowImage(m_openPath, m_pCv1->detectFace(copy)); } } void CFaceRecognitionDlg::OnBnClickedCheckdetect() { // TODO: 在此添加控件通知处理程序代码 if(m_pCv3 && m_pCv3->getCamCapture()) { m_pCv3->frontal= TRUE; if( m_pCv3->detect ) { // MessageBox("draw the face"); m_pCv3->detect= FALSE; } else { // MessageBox("do not draw the face"); m_pCv3->detect= TRUE; } } if(m_pCv4 && m_pCv4->getCamCapture()) { m_pCv4->frontal= TRUE; if( m_pCv4->detect ) { // MessageBox("draw the face"); m_pCv4->detect= FALSE; } else { // MessageBox("do not draw the face"); m_pCv4->detect= TRUE; } } // else // MessageBox("CAM has not be Loaded!"); } void CFaceRecognitionDlg::OnBnClickedCheck2() { // TODO: 在此添加控件通知处理程序代码 if(m_pCv3 && m_pCv3->getCamCapture()) { if( m_pCv3->pause ) { // MessageBox("draw the face"); m_pCv3->pause= FALSE; } else { // MessageBox("do not draw the face"); m_pCv3->pause= TRUE; } } if(m_pCv4 && m_pCv4->getCamCapture()) { if( m_pCv4->pause ) { // MessageBox("draw the face"); m_pCv4->pause= FALSE; } else { // MessageBox("do not draw the face"); m_pCv4->pause= TRUE; } } } void CFaceRecognitionDlg::OnBnClickedAbout() { // TODO: 在此添加控件通知处理程序代码 CAboutDlg dlg; dlg.DoModal(); } void CFaceRecognitionDlg::OnBnClickedCheckprofile() { // TODO: 在此添加控件通知处理程序代码 if(m_pCv1 && m_pCv1->getImage()) { if( m_pCv1->profile ) { // MessageBox("draw the face"); m_pCv1->profile= FALSE; } else { // MessageBox("do not draw the face"); m_pCv1->profile= TRUE; } IplImage* img=m_pCv1->getImage(); IplImage* copy = cvCreateImage( cvSize(img->width,img->height), IPL_DEPTH_8U, img->nChannels ); cvCopy(img, copy, NULL); cvvShowImage(m_openPath, m_pCv1->detectFace(copy)); } if(m_pCv2 && m_pCv2->getCapture()) { if( m_pCv2->profile ) { // MessageBox("draw the face"); m_pCv2->profile= FALSE; } else { // MessageBox("do not draw the face"); m_pCv2->profile= TRUE; } } } void CFaceRecognitionDlg::OnBnClickedCheckfrontal() { // TODO: 在此添加控件通知处理程序代码 if(m_pCv1 && m_pCv1->getImage()) { if( m_pCv1->frontal ) { // MessageBox("draw the face"); m_pCv1->frontal= FALSE; } else { // MessageBox("do not draw the face"); m_pCv1->frontal= TRUE; } IplImage* img=m_pCv1->getImage(); IplImage* copy = cvCreateImage( cvSize(img->width,img->height), IPL_DEPTH_8U, img->nChannels ); cvCopy(img, copy, NULL); cvvShowImage(m_openPath, m_pCv1->detectFace(copy)); } if(m_pCv2 && m_pCv2->getCapture()) { if( m_pCv2->frontal ) { // MessageBox("draw the face"); m_pCv2->frontal= FALSE; } else { // MessageBox("do not draw the face"); m_pCv2->frontal= TRUE; } } } void CFaceRecognitionDlg::OnBnClickedOpenTrain() { // TODO: Add your control notification handler code here m_pCv1->OpenTrainFile(); } void CFaceRecognitionDlg::OnNMReleasedcaptureSldframerate(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: 在此添加控件通知处理程序代码 *pResult = 0; }
[ "zinking3@b2a41f76-c118-11dd-8bad-cde060d8fd3c" ]
[ [ [ 1, 1002 ] ] ]
4fd428d4f80fe483788bc4cc9b694e42bfe5c4b9
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_Reflection_RuntimeMethodInfo.h
c582c9ff66b7d52d2c7fe84afcdcbb6b620ee833
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
h
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #ifndef _CORLIB_NATIVE_SYSTEM_REFLECTION_RUNTIMEMETHODINFO_H_ #define _CORLIB_NATIVE_SYSTEM_REFLECTION_RUNTIMEMETHODINFO_H_ namespace System { namespace Reflection { struct RuntimeMethodInfo { // Helper Functions to access fields of managed object // Declaration of stubs. These functions are implemented by Interop code developers static UNSUPPORTED_TYPE get_ReturnType( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ); }; } } #endif //_CORLIB_NATIVE_SYSTEM_REFLECTION_RUNTIMEMETHODINFO_H_
[ [ [ 1, 29 ] ] ]
d2c8ea81429ba1a626b4ef5e982a839e04b3fa44
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/DocumentTypeImpl.hpp
5f68b3b61a4f3a31dd3942a37434b0dab1c9adb3
[]
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
2,922
hpp
#ifndef DocumentTypeImpl_HEADER_GUARD_ #define DocumentTypeImpl_HEADER_GUARD_ /* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DocumentTypeImpl.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire // DOM API, or DOM_*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include "ParentNode.hpp" XERCES_CPP_NAMESPACE_BEGIN class NamedNodeMapImpl; class DEPRECATED_DOM_EXPORT DocumentTypeImpl: public ParentNode { private: DOMString name; NamedNodeMapImpl *entities; NamedNodeMapImpl *notations; NamedNodeMapImpl *elements; DOMString publicId; DOMString systemId; DOMString internalSubset; bool intSubsetReading; virtual void setPublicId(const DOMString& value); virtual void setSystemId(const DOMString& value); virtual void setInternalSubset(const DOMString &value); bool isIntSubsetReading(); friend class DOMParser; public: DocumentTypeImpl(DocumentImpl *, const DOMString &); DocumentTypeImpl(DocumentImpl *, const DOMString &qualifiedName, //DOM Level 2 const DOMString &publicId, const DOMString &systemId); DocumentTypeImpl(const DocumentTypeImpl &other, bool deep=false); virtual ~DocumentTypeImpl(); virtual bool isDocumentTypeImpl(); virtual NodeImpl * cloneNode(bool deep); virtual void setOwnerDocument(DocumentImpl *doc); virtual DOMString getNodeName(); virtual short getNodeType(); virtual NamedNodeMapImpl * getEntities(); virtual DOMString getName(); virtual NamedNodeMapImpl * getNotations(); virtual NamedNodeMapImpl * getElements(); virtual void setReadOnly(bool readOnly, bool deep); //Introduced in DOM Level 2 virtual DOMString getPublicId(); virtual DOMString getSystemId(); virtual DOMString getInternalSubset(); }; XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 90 ] ] ]
d55df4b426233d52a13543b5ea0039861f8b74c3
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/svm/svm_abstract.h
c51a8f74d3c2d5c48817042848581310b80ccdb5
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
16,369
h
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_SVm_ABSTRACT_ #ifdef DLIB_SVm_ABSTRACT_ #include <cmath> #include <limits> #include <sstream> #include "../matrix/matrix_abstract.h" #include "../algs.h" #include "../serialize.h" #include "function_abstract.h" #include "kernel_abstract.h" namespace dlib { // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class invalid_svm_nu_error : public dlib::error { /*! WHAT THIS OBJECT REPRESENTS This object is an exception class used to indicate that a value of nu used for svm training is incompatible with a particular data set. this->nu will be set to the invalid value of nu used. !*/ public: invalid_svm_nu_error(const std::string& msg, double nu_) : dlib::error(msg), nu(nu_) {}; const double nu; }; // ---------------------------------------------------------------------------------------- template < typename T > typename T::type maximum_nu ( const T& y ); /*! requires - T == a matrix object or an object convertible to a matrix via vector_to_matrix() - y.nc() == 1 - y.nr() > 1 - for all valid i: - y(i) == -1 or +1 ensures - returns the maximum valid nu that can be used with the svm_nu_trainer and the training set labels from the given y vector. (i.e. 2.0*min(number of +1 examples in y, number of -1 examples in y)/y.nr()) !*/ // ---------------------------------------------------------------------------------------- bool template < typename T, typename U > bool is_binary_classification_problem ( const T& x, const U& x_labels ); /*! requires - T == a matrix or something convertible to a matrix via vector_to_matrix() - U == a matrix or something convertible to a matrix via vector_to_matrix() ensures - returns true if all of the following are true and false otherwise: - x.nc() == 1 (i.e. x is a column vector) - x_labels.nc() == 1 (i.e. x_labels is a column vector) - x.nr() == x_labels.nr() - x.nr() > 1 - for all valid i: - x_labels(i) == -1 or +1 !*/ // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename K > class svm_nu_trainer { /*! REQUIREMENTS ON K is a kernel function object as defined in dlib/svm/kernel_abstract.h WHAT THIS OBJECT REPRESENTS This object implements a trainer for a nu support vector machine for solving binary classification problems. The implementation of the nu-svm training algorithm used by this object is based on the following excellent papers: - Chang and Lin, Training {nu}-Support Vector Classifiers: Theory and Algorithms - Chih-Chung Chang and Chih-Jen Lin, LIBSVM : a library for support vector machines, 2001. Software available at http://www.csie.ntu.edu.tw/~cjlin/libsvm !*/ public: typedef K kernel_type; typedef typename kernel_type::scalar_type scalar_type; typedef typename kernel_type::sample_type sample_type; typedef typename kernel_type::mem_manager_type mem_manager_type; typedef decision_function<kernel_type> trained_function_type; svm_nu_trainer ( ); /*! ensures - This object is properly initialized and ready to be used to train a support vector machine. - #get_nu() == 0.1 - #get_cache_size() == 200 - #get_epsilon() == 0.001 !*/ svm_nu_trainer ( const kernel_type& kernel, const scalar_type& nu ); /*! requires - 0 < nu <= 1 ensures - This object is properly initialized and ready to be used to train a support vector machine. - #get_kernel() == kernel - #get_nu() == nu - #get_cache_size() == 200 - #get_epsilon() == 0.001 !*/ void set_cache_size ( long cache_size ); /*! requires - cache_size > 0 ensures - #get_cache_size() == cache_size !*/ const long get_cache_size ( ) const; /*! ensures - returns the number of megabytes of cache this object will use when it performs training via the this->train() function. (bigger values of this may make training go faster but won't affect the result. However, too big a value will cause you to run out of memory, obviously.) !*/ void set_epsilon ( scalar_type eps ); /*! requires - eps > 0 ensures - #get_epsilon() == eps !*/ const scalar_type get_epsilon ( ) const; /*! ensures - returns the error epsilon that determines when training should stop. Generally a good value for this is 0.001. Smaller values may result in a more accurate solution but take longer to execute. !*/ void set_kernel ( const kernel_type& k ); /*! ensures - #get_kernel() == k !*/ const kernel_type& get_kernel ( ) const; /*! ensures - returns a copy of the kernel function in use by this object !*/ void set_nu ( scalar_type nu ); /*! requires - 0 < nu <= 1 ensures - #get_nu() == nu !*/ const scalar_type get_nu ( ) const; /*! ensures - returns the nu svm parameter. This is a value between 0 and 1. It is the parameter that determines the trade off between trying to fit the training data exactly or allowing more errors but hopefully improving the generalization ability of the resulting classifier. For more information you should consult the papers referenced above. !*/ template < typename in_sample_vector_type, typename in_scalar_vector_type > const decision_function<kernel_type> train ( const in_sample_vector_type& x, const in_scalar_vector_type& y ) const; /*! requires - is_binary_classification_problem(x,y) == true - x == a matrix or something convertible to a matrix via vector_to_matrix(). Also, x should contain sample_type objects. - y == a matrix or something convertible to a matrix via vector_to_matrix(). Also, y should contain scalar_type objects. ensures - trains a nu support vector classifier given the training samples in x and labels in y. Training is done when the error is less than get_epsilon(). - returns a decision function F with the following properties: - if (new_x is a sample predicted have +1 label) then - F(new_x) >= 0 - else - F(new_x) < 0 throws - invalid_svm_nu_error This exception is thrown if get_nu() > maximum_nu(y) - std::bad_alloc !*/ void swap ( svm_nu_trainer& item ); /*! ensures - swaps *this and item !*/ }; template <typename K> void swap ( svm_nu_trainer<K>& a, svm_nu_trainer<K>& b ) { a.swap(b); } /*! provides a global swap !*/ // ---------------------------------------------------------------------------------------- template < typename trainer_type, typename in_sample_vector_type, typename in_scalar_vector_type > const probabilistic_decision_function<typename trainer_type::kernel_type> train_probabilistic_decision_function ( const trainer_type& trainer, const in_sample_vector_type& x, const in_scalar_vector_type& y, const long folds ) /*! requires - 1 < folds <= x.nr() - is_binary_classification_problem(x,y) == true - trainer_type == some kind of trainer object (e.g. svm_nu_trainer) ensures - trains a nu support vector classifier given the training samples in x and labels in y. - returns a probabilistic_decision_function that represents the trained svm. - The parameters of the probability model are estimated by performing k-fold cross validation. - The number of folds used is given by the folds argument. throws - any exceptions thrown by trainer.train() - std::bad_alloc !*/ // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // Miscellaneous functions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename trainer_type, typename in_sample_vector_type, typename in_scalar_vector_type > const matrix<typename trainer_type::scalar_type, 1, 2, typename trainer_type::mem_manager_type> cross_validate_trainer ( const trainer_type& trainer, const in_sample_vector_type& x, const in_scalar_vector_type& y, const long folds ); /*! requires - is_binary_classification_problem(x,y) == true - 1 < folds <= x.nr() - trainer_type == some kind of trainer object (e.g. svm_nu_trainer) ensures - performs k-fold cross validation by using the given trainer to solve the given binary classification problem for the given number of folds. Each fold is tested using the output of the trainer and the average classification accuracy from all folds is returned. - The accuracy is returned in a column vector, let us call it R. Both quantities in R are numbers between 0 and 1 which represent the fraction of examples correctly classified. R(0) is the fraction of +1 examples correctly classified and R(1) is the fraction of -1 examples correctly classified. - The number of folds used is given by the folds argument. throws - any exceptions thrown by trainer.train() - std::bad_alloc !*/ // ---------------------------------------------------------------------------------------- template < typename dec_funct_type, typename in_sample_vector_type, typename in_scalar_vector_type > const matrix<typename dec_funct_type::scalar_type, 1, 2, typename dec_funct_type::mem_manager_type> test_binary_decision_function ( const dec_funct_type& trainer, const in_sample_vector_type& x_test, const in_scalar_vector_type& y_test ); /*! requires - is_binary_classification_problem(x_test,y_test) == true - dec_funct_type == some kind of decision function object (e.g. decision_function) ensures - tests the given decision function by calling on the x_test and y_test samples. - The test accuracy is returned in a column vector, let us call it R. Both quantities in R are numbers between 0 and 1 which represent the fraction of examples correctly classified. R(0) is the fraction of +1 examples correctly classified and R(1) is the fraction of -1 examples correctly classified. throws - std::bad_alloc !*/ // ---------------------------------------------------------------------------------------- template < typename T, typename U > void randomize_samples ( T& samples, U& labels ); /*! requires - T == a matrix object that contains a swappable type - U == a matrix object that contains a swappable type - samples.nc() == 1 - labels.nc() == 1 - samples.nr() == labels.nr() ensures - randomizes the order of the samples and labels but preserves the pairing between each sample and its label - for all valid i: - let r == the random index samples(i) was moved to. then: - #labels(r) == labels(i) !*/ // ---------------------------------------------------------------------------------------- template < typename T > void randomize_samples ( T& samples ); /*! requires - T == a matrix object that contains a swappable type - samples.nc() == 1 ensures - randomizes the order of the elements inside samples !*/ // ---------------------------------------------------------------------------------------- template < typename T, typename U > void randomize_samples ( T& samples, U& labels ); /*! requires - T == an object compatible with std::vector that contains a swappable type - U == an object compatible with std::vector that contains a swappable type - samples.size() == labels.size() ensures - randomizes the order of the samples and labels but preserves the pairing between each sample and its label - for all valid i: - let r == the random index samples[i] was moved to. then: - #labels[r] == labels[i] !*/ // ---------------------------------------------------------------------------------------- template < typename T > void randomize_samples ( T& samples ); /*! requires - T == an object compatible with std::vector that contains a swappable type ensures - randomizes the order of the elements inside samples !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_SVm_ABSTRACT_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 450 ] ] ]
6990dd88ccd001cf4a9f6d08b1536b4583deecd0
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/IFCCurve.cpp
c91c47105e74ca2bb358d4a6ae4fbbe4ace9dd6c
[ "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
20,177
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 IFCProfile.cpp * @brief Read profile and curves entities from IFC files */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER #include "IFCUtil.h" namespace Assimp { namespace IFC { namespace { // -------------------------------------------------------------------------------- // Conic is the base class for Circle and Ellipse // -------------------------------------------------------------------------------- class Conic : public Curve { public: // -------------------------------------------------- Conic(const IfcConic& entity, ConversionData& conv) : Curve(entity,conv) { aiMatrix4x4 trafo; ConvertAxisPlacement(trafo,*entity.Position,conv); // for convenience, extract the matrix rows location = aiVector3D(trafo.a4,trafo.b4,trafo.c4); p[0] = aiVector3D(trafo.a1,trafo.b1,trafo.c1); p[1] = aiVector3D(trafo.a2,trafo.b2,trafo.c2); p[2] = aiVector3D(trafo.a3,trafo.b3,trafo.c3); } public: // -------------------------------------------------- bool IsClosed() const { return true; } // -------------------------------------------------- size_t EstimateSampleCount(float a, float b) const { ai_assert(InRange(a) && InRange(b)); a = fmod(a,360.f); b = fmod(b,360.f); return static_cast<size_t>( fabs(ceil(( b-a)) / conv.settings.conicSamplingAngle) ); } // -------------------------------------------------- ParamRange GetParametricRange() const { return std::make_pair(0.f,360.f); } protected: aiVector3D location, p[3]; }; // -------------------------------------------------------------------------------- // Circle // -------------------------------------------------------------------------------- class Circle : public Conic { public: // -------------------------------------------------- Circle(const IfcCircle& entity, ConversionData& conv) : Conic(entity,conv) , entity(entity) { } public: // -------------------------------------------------- aiVector3D Eval(float u) const { u = -conv.angle_scale * u; return location + entity.Radius*(::cos(u)*p[0] + ::sin(u)*p[1]); } private: const IfcCircle& entity; }; // -------------------------------------------------------------------------------- // Ellipse // -------------------------------------------------------------------------------- class Ellipse : public Conic { public: // -------------------------------------------------- Ellipse(const IfcEllipse& entity, ConversionData& conv) : Conic(entity,conv) , entity(entity) { } public: // -------------------------------------------------- aiVector3D Eval(float u) const { u = -conv.angle_scale * u; return location + entity.SemiAxis1*::cos(u)*p[0] + entity.SemiAxis2*::sin(u)*p[1]; } private: const IfcEllipse& entity; }; // -------------------------------------------------------------------------------- // Line // -------------------------------------------------------------------------------- class Line : public Curve { public: // -------------------------------------------------- Line(const IfcLine& entity, ConversionData& conv) : Curve(entity,conv) , entity(entity) { ConvertCartesianPoint(p,entity.Pnt); ConvertVector(v,entity.Dir); } public: // -------------------------------------------------- bool IsClosed() const { return false; } // -------------------------------------------------- aiVector3D Eval(float u) const { return p + u*v; } // -------------------------------------------------- size_t EstimateSampleCount(float a, float b) const { ai_assert(InRange(a) && InRange(b)); // two points are always sufficient for a line segment return a==b ? 1 : 2; } // -------------------------------------------------- void SampleDiscrete(TempMesh& out,float a, float b) const { ai_assert(InRange(a) && InRange(b)); if (a == b) { out.verts.push_back(Eval(a)); return; } out.verts.reserve(out.verts.size()+2); out.verts.push_back(Eval(a)); out.verts.push_back(Eval(b)); } // -------------------------------------------------- ParamRange GetParametricRange() const { const float inf = std::numeric_limits<float>::infinity(); return std::make_pair(-inf,+inf); } private: const IfcLine& entity; aiVector3D p,v; }; // -------------------------------------------------------------------------------- // CompositeCurve joins multiple smaller, bounded curves // -------------------------------------------------------------------------------- class CompositeCurve : public BoundedCurve { typedef std::pair< boost::shared_ptr< BoundedCurve >, bool > CurveEntry; public: // -------------------------------------------------- CompositeCurve(const IfcCompositeCurve& entity, ConversionData& conv) : BoundedCurve(entity,conv) , entity(entity) , total() { curves.reserve(entity.Segments.size()); BOOST_FOREACH(const IfcCompositeCurveSegment& curveSegment,entity.Segments) { // according to the specification, this must be a bounded curve boost::shared_ptr< Curve > cv(Curve::Convert(curveSegment.ParentCurve,conv)); boost::shared_ptr< BoundedCurve > bc = boost::dynamic_pointer_cast<BoundedCurve>(cv); if (!bc) { IFCImporter::LogError("expected segment of composite curve to be a bounded curve"); continue; } if ( (std::string)curveSegment.Transition != "CONTINUOUS" ) { IFCImporter::LogDebug("ignoring transition code on composite curve segment, only continuous transitions are supported"); } curves.push_back( CurveEntry(bc,IsTrue(curveSegment.SameSense)) ); total += bc->GetParametricRangeDelta(); } if (curves.empty()) { throw CurveError("empty composite curve"); } } public: // -------------------------------------------------- aiVector3D Eval(float u) const { if (curves.empty()) { return aiVector3D(); } float acc = 0; BOOST_FOREACH(const CurveEntry& entry, curves) { const ParamRange& range = entry.first->GetParametricRange(); const float delta = range.second-range.first; if (u < acc+delta) { return entry.first->Eval( entry.second ? (u-acc) + range.first : range.second-(u-acc)); } acc += delta; } // clamp to end return curves.back().first->Eval(curves.back().first->GetParametricRange().second); } // -------------------------------------------------- size_t EstimateSampleCount(float a, float b) const { ai_assert(InRange(a) && InRange(b)); size_t cnt = 0; float acc = 0; BOOST_FOREACH(const CurveEntry& entry, curves) { const ParamRange& range = entry.first->GetParametricRange(); const float delta = range.second-range.first; if (a <= acc+delta && b >= acc) { const float at = std::max(0.f,a-acc), bt = std::min(delta,b-acc); cnt += entry.first->EstimateSampleCount( entry.second ? at + range.first : range.second - bt, entry.second ? bt + range.first : range.second - at ); } acc += delta; } return cnt; } // -------------------------------------------------- void SampleDiscrete(TempMesh& out,float a, float b) const { ai_assert(InRange(a) && InRange(b)); const size_t cnt = EstimateSampleCount(a,b); out.verts.reserve(out.verts.size() + cnt); BOOST_FOREACH(const CurveEntry& entry, curves) { const size_t cnt = out.verts.size(); entry.first->SampleDiscrete(out); if (!entry.second && cnt != out.verts.size()) { std::reverse(out.verts.begin()+cnt,out.verts.end()); } } } // -------------------------------------------------- ParamRange GetParametricRange() const { return std::make_pair(0.f,total); } private: const IfcCompositeCurve& entity; std::vector< CurveEntry > curves; float total; }; // -------------------------------------------------------------------------------- // TrimmedCurve can be used to trim an unbounded curve to a bounded range // -------------------------------------------------------------------------------- class TrimmedCurve : public BoundedCurve { public: // -------------------------------------------------- TrimmedCurve(const IfcTrimmedCurve& entity, ConversionData& conv) : BoundedCurve(entity,conv) , entity(entity) , ok() { base = boost::shared_ptr<const Curve>(Curve::Convert(entity.BasisCurve,conv)); typedef boost::shared_ptr<const STEP::EXPRESS::DataType> Entry; // for some reason, trimmed curves can either specify a parametric value // or a point on the curve, or both. And they can even specify which of the // two representations they prefer, even though an information invariant // claims that they must be identical if both are present. // oh well. bool have_param = false, have_point = false; aiVector3D point; BOOST_FOREACH(const Entry sel,entity.Trim1) { if (const EXPRESS::REAL* const r = sel->ToPtr<EXPRESS::REAL>()) { range.first = *r; have_param = true; break; } else if (const IfcCartesianPoint* const r = sel->ResolveSelectPtr<IfcCartesianPoint>(conv.db)) { ConvertCartesianPoint(point,*r); have_point = true; } } if (!have_param) { if (!have_point || !base->ReverseEval(point,range.first)) { throw CurveError("IfcTrimmedCurve: failed to read first trim parameter, ignoring curve"); } } have_param = false, have_point = false; BOOST_FOREACH(const Entry sel,entity.Trim2) { if (const EXPRESS::REAL* const r = sel->ToPtr<EXPRESS::REAL>()) { range.second = *r; have_param = true; break; } else if (const IfcCartesianPoint* const r = sel->ResolveSelectPtr<IfcCartesianPoint>(conv.db)) { ConvertCartesianPoint(point,*r); have_point = true; } } if (!have_param) { if (!have_point || !base->ReverseEval(point,range.second)) { throw CurveError("IfcTrimmedCurve: failed to read second trim parameter, ignoring curve"); } } agree_sense = IsTrue(entity.SenseAgreement); if( !agree_sense ) { std::swap(range.first,range.second); } // "NOTE In case of a closed curve, it may be necessary to increment t1 or t2 // by the parametric length for consistency with the sense flag." if (base->IsClosed()) { if( range.first > range.second ) { range.second += base->GetParametricRangeDelta(); } } maxval = range.second-range.first; ai_assert(maxval >= 0); } public: // -------------------------------------------------- aiVector3D Eval(float p) const { ai_assert(InRange(p)); return base->Eval( TrimParam(p) ); } // -------------------------------------------------- size_t EstimateSampleCount(float a, float b) const { ai_assert(InRange(a) && InRange(b)); return base->EstimateSampleCount(TrimParam(a),TrimParam(b)); } // -------------------------------------------------- ParamRange GetParametricRange() const { return std::make_pair(0.f,maxval); } private: // -------------------------------------------------- float TrimParam(float f) const { return agree_sense ? f + range.first : range.second - f; } private: const IfcTrimmedCurve& entity; ParamRange range; float maxval; bool agree_sense; bool ok; boost::shared_ptr<const Curve> base; }; // -------------------------------------------------------------------------------- // PolyLine is a 'curve' defined by linear interpolation over a set of discrete points // -------------------------------------------------------------------------------- class PolyLine : public BoundedCurve { public: // -------------------------------------------------- PolyLine(const IfcPolyline& entity, ConversionData& conv) : BoundedCurve(entity,conv) , entity(entity) { points.reserve(entity.Points.size()); aiVector3D t; BOOST_FOREACH(const IfcCartesianPoint& cp, entity.Points) { ConvertCartesianPoint(t,cp); points.push_back(t); } } public: // -------------------------------------------------- aiVector3D Eval(float p) const { ai_assert(InRange(p)); const size_t b = static_cast<size_t>(floor(p)); if (b == points.size()-1) { return points.back(); } const float d = p-static_cast<float>(b); return points[b+1] * d + points[b] * (1.f-d); } // -------------------------------------------------- size_t EstimateSampleCount(float a, float b) const { ai_assert(InRange(a) && InRange(b)); return static_cast<size_t>( ceil(b) - floor(a) ); } // -------------------------------------------------- ParamRange GetParametricRange() const { return std::make_pair(0.f,static_cast<float>(points.size()-1)); } private: const IfcPolyline& entity; std::vector<aiVector3D> points; }; } // anon // ------------------------------------------------------------------------------------------------ Curve* Curve :: Convert(const IFC::IfcCurve& curve,ConversionData& conv) { if(curve.ToPtr<IfcBoundedCurve>()) { if(const IfcPolyline* c = curve.ToPtr<IfcPolyline>()) { return new PolyLine(*c,conv); } if(const IfcTrimmedCurve* c = curve.ToPtr<IfcTrimmedCurve>()) { return new TrimmedCurve(*c,conv); } if(const IfcCompositeCurve* c = curve.ToPtr<IfcCompositeCurve>()) { return new CompositeCurve(*c,conv); } //if(const IfcBSplineCurve* c = curve.ToPtr<IfcBSplineCurve>()) { // return new BSplineCurve(*c,conv); //} } if(curve.ToPtr<IfcConic>()) { if(const IfcCircle* c = curve.ToPtr<IfcCircle>()) { return new Circle(*c,conv); } if(const IfcEllipse* c = curve.ToPtr<IfcEllipse>()) { return new Ellipse(*c,conv); } } if(const IfcLine* c = curve.ToPtr<IfcLine>()) { return new Line(*c,conv); } // XXX OffsetCurve2D, OffsetCurve3D not currently supported return NULL; } #ifdef _DEBUG // ------------------------------------------------------------------------------------------------ bool Curve :: InRange(float u) const { const ParamRange range = GetParametricRange(); if (IsClosed()) { ai_assert(range.first != std::numeric_limits<float>::infinity() && range.second != std::numeric_limits<float>::infinity()); u = range.first + fmod(u-range.first,range.second-range.first); } return u >= range.first && u <= range.second; } #endif // ------------------------------------------------------------------------------------------------ float Curve :: GetParametricRangeDelta() const { const ParamRange& range = GetParametricRange(); return range.second - range.first; } // ------------------------------------------------------------------------------------------------ size_t Curve :: EstimateSampleCount(float a, float b) const { ai_assert(InRange(a) && InRange(b)); // arbitrary default value, deriving classes should supply better suited values return 16; } // ------------------------------------------------------------------------------------------------ float RecursiveSearch(const Curve* cv, const aiVector3D& val, float a, float b, unsigned int samples, float threshold, unsigned int recurse = 0, unsigned int max_recurse = 15) { ai_assert(samples>1); const float delta = (b-a)/samples, inf = std::numeric_limits<float>::infinity(); float min_point[2] = {a,b}, min_diff[2] = {inf,inf}; float runner = a; for (unsigned int i = 0; i < samples; ++i, runner += delta) { const float diff = (cv->Eval(runner)-val).SquareLength(); if (diff < min_diff[0]) { min_diff[1] = min_diff[0]; min_point[1] = min_point[0]; min_diff[0] = diff; min_point[0] = runner; } else if (diff < min_diff[1]) { min_diff[1] = diff; min_point[1] = runner; } } ai_assert(min_diff[0] != inf && min_diff[1] != inf); if ( fabs(a-min_point[0]) < threshold || recurse >= max_recurse) { return min_point[0]; } // fix for closed curves to take their wrap-over into account if (cv->IsClosed() && fabs(min_point[0]-min_point[1]) > cv->GetParametricRangeDelta()*0.5 ) { const Curve::ParamRange& range = cv->GetParametricRange(); const float wrapdiff = (cv->Eval(range.first)-val).SquareLength(); if (wrapdiff < min_diff[0]) { const float t = min_point[0]; min_point[0] = min_point[1] > min_point[0] ? range.first : range.second; min_point[1] = t; } } return RecursiveSearch(cv,val,min_point[0],min_point[1],samples,threshold,recurse+1,max_recurse); } // ------------------------------------------------------------------------------------------------ bool Curve :: ReverseEval(const aiVector3D& val, float& paramOut) const { // note: the following algorithm is not guaranteed to find the 'right' parameter value // in all possible cases, but it will always return at least some value so this function // will never fail in the default implementation. // XXX derive threshold from curve topology const float threshold = 1e-4f; const unsigned int samples = 16; const ParamRange& range = GetParametricRange(); paramOut = RecursiveSearch(this,val,range.first,range.second,samples,threshold); return true; } // ------------------------------------------------------------------------------------------------ void Curve :: SampleDiscrete(TempMesh& out,float a, float b) const { ai_assert(InRange(a) && InRange(b)); const size_t cnt = std::max(static_cast<size_t>(0),EstimateSampleCount(a,b)); out.verts.reserve( out.verts.size() + cnt ); float p = a, delta = (b-a)/cnt; for(size_t i = 0; i < cnt; ++i, p += delta) { out.verts.push_back(Eval(p)); } } // ------------------------------------------------------------------------------------------------ bool BoundedCurve :: IsClosed() const { return false; } // ------------------------------------------------------------------------------------------------ void BoundedCurve :: SampleDiscrete(TempMesh& out) const { const ParamRange& range = GetParametricRange(); ai_assert(range.first != std::numeric_limits<float>::infinity() && range.second != std::numeric_limits<float>::infinity()); return SampleDiscrete(out,range.first,range.second); } } // IFC } // Assimp #endif // ASSIMP_BUILD_NO_IFC_IMPORTER
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f", "klickverbot@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 570 ], [ 572, 594 ], [ 596, 610 ], [ 612, 620 ], [ 623, 625 ], [ 627, 663 ] ], [ [ 571, 571 ], [ 595, 595 ], [ 611, 611 ], [ 621, 622 ], [ 626, 626 ] ] ]
f1915b009169a6516364cbf4b753aaebdb2c8d40
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/extras/collision/collision_dll/vmap/AABSPTree.h
f951f6e6864e9b9a32d6e72afe7fe3bcaf7380cb
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
64,208
h
/** @file AABSPTree.h @maintainer Morgan McGuire, [email protected] @created 2004-01-11 @edited 2005-02-24 Copyright 2000-2005, Morgan McGuire. All rights reserved. */ #ifndef G3D_AABSPTREE_H #define G3D_AABSPTREE_H #include "G3D/platform.h" #include "G3D/Array.h" #include "G3D/Table.h" #include "G3D/Vector3.h" #include "G3D/AABox.h" #include "G3D/Sphere.h" #include "G3D/Box.h" #include "G3D/Triangle.h" #include "G3D/GCamera.h" //#include "G3D/BinaryInput.h" //#include "G3D/BinaryOutput.h" #include "G3D/CollisionDetection.h" #include <algorithm> #include <climits> #include <cstring> #include "RayIntersectionIterator.h" #ifdef _ASSEMBLER_DEBUG #ifndef g_df extern FILE *g_df; #endif #endif inline void getBounds(const G3D::Vector3& v, G3D::AABox& out) { out = G3D::AABox(v); } inline void getBounds(const G3D::AABox& a, G3D::AABox& out) { out = a; } inline void getBounds(const G3D::Sphere& s, G3D::AABox& out) { s.getBounds(out); } inline void getBounds(const G3D::Box& b, G3D::AABox& out) { b.getBounds(out); } inline void getBounds(const G3D::Triangle& t, G3D::AABox& out) { t.getBounds(out); } namespace G3D { /** A set that supports spatial queries using an axis-aligned BSP tree for speed. AABSPTree is as powerful as but more general than a Quad Tree, Oct Tree, or KD Tree, but less general than an unconstrained BSP tree (which is much slower to create). Internally, objects are arranged into an axis-aligned BSP-tree according to their axis-aligned bounds. This increases the cost of insertion to O(log n) but allows fast overlap queries. <B>Template Parameters</B> <DT>The template parameter <I>T</I> must be one for which the following functions are overloaded: <P><CODE>void ::getBounds(const T&, G3D::AABox&);</CODE> <DT><CODE>bool operator==(const T&, const T&);</CODE> <DT><CODE>size_t ::hashCode(const T&);</CODE> <DT><CODE>T::T();</CODE> <I>(public constructor of no arguments)</I> <B>Moving %Set Members</B> <DT>It is important that objects do not move without updating the AABSPTree. If the axis-aligned bounds of an object are about to change, AABSPTree::remove it before they change and AABSPTree::insert it again afterward. For objects where the hashCode and == operator are invariant with respect to the 3D position, you can use the AABSPTree::update method as a shortcut to insert/remove an object in one step after it has moved. Note: Do not mutate any value once it has been inserted into AABSPTree. Values are copied interally. All AABSPTree iterators convert to pointers to constant values to reinforce this. If you want to mutate the objects you intend to store in a AABSPTree simply insert <I>pointers</I> to your objects instead of the objects themselves, and ensure that the above operations are defined. (And actually, because values are copied, if your values are large you may want to insert pointers anyway, to save space and make the balance operation faster.) <B>Dimensions</B> Although designed as a 3D-data structure, you can use the AABSPTree for data distributed along 2 or 1 axes by simply returning bounds that are always zero along one or more dimensions. */ template<class T> class AABSPTree { private: public: /** Wrapper for a value that includes a cache of its bounds. */ class Handle { public: T value; /** The bounds of each object are constrained to AABox::maxFinite */ AABox bounds; /** Center of bounds. We cache this value to avoid recomputing it during the median sort, and because MSVC 6 std::sort goes into an infinite loop if we compute the midpoint on the fly (possibly a floating point roundoff issue, where B<A and A<B both are true).*/ Vector3 center; Handle() {} inline Handle(const T& v) : value(v) { getBounds(v, bounds); bounds = bounds.intersect(AABox::maxFinite()); center = bounds.center(); } }; /** Returns the bounds of the sub array. Used by makeNode. */ static AABox computeBounds( const Array<Handle>& point, int beginIndex, int endIndex) { Vector3 lo = Vector3::inf(); Vector3 hi = -lo; for (int p = beginIndex; p <= endIndex; ++p) { lo = lo.min(point[p].bounds.low()); hi = hi.max(point[p].bounds.high()); } return AABox(lo, hi); } /** A sort predicate that returns true if the midpoint of the first argument is less than the midpoint of the second along the specified axis. Used by makeNode. */ class CenterLT { public: Vector3::Axis sortAxis; CenterLT(Vector3::Axis a) : sortAxis(a) {} inline bool operator()(const Handle& a, const Handle& b) const { return a.center[sortAxis] < b.center[sortAxis]; } }; /** A sort predicate based on a box's location on the specified axis. Each box is given a value -1, 0, or 1 based on whether it is strictly less than, overlapping, or strictly greater than the value on the specified axis. This predicate compares the values for two boxes. The result is that the array is separated into three contiguous (though possibly empty) groups: less than, overlapping, or greater than. */ class PivotLT { public: Vector3::Axis sortAxis; float sortLocation; PivotLT(Vector3::Axis a, float l) : sortAxis(a), sortLocation(l) {} inline int location(const AABox& box) const { if(box.low()[sortAxis] < sortLocation) { if(box.high()[sortAxis] < sortLocation) { return -1; } else { return 0; } } else if(box.low()[sortAxis] > sortLocation) { return 1; } else { return 0; } } inline bool operator()(const Handle&a, const Handle& b) const { const AABox& A = a.bounds; const AABox& B = b.bounds; return location(A) < location(B); } }; class Node { public: /** Spatial bounds on all values at this node and its children, based purely on the parent's splitting planes. May be infinite */ AABox splitBounds; Vector3::Axis splitAxis; /** Location along the specified axis */ float splitLocation; /** child[0] contains all values strictly smaller than splitLocation along splitAxis. child[1] contains all values strictly larger. Both may be NULL if there are not enough values to bother recursing. */ Node* child[2]; /** Array of values at this node (i.e. values straddling the split plane + all values if this is a leaf node). */ Array<Handle> valueArray; /** Creates node with NULL children */ Node() { splitAxis = Vector3::X_AXIS; splitLocation = 0; splitBounds = AABox(-Vector3::inf(), Vector3::inf()); for (int i = 0; i < 2; ++i) { child[i] = NULL; } } /** Doesn't clone children. */ Node(const Node& other) : valueArray(other.valueArray) { splitAxis = other.splitAxis; splitLocation = other.splitLocation; splitBounds = other.splitBounds; for (int i = 0; i < 2; ++i) { child[i] = NULL; } } /** Copies the specified subarray of pt into point, NULLs the children. Assumes a second pass will set splitBounds. */ Node(const Array<Handle>& pt, int beginIndex, int endIndex) { splitAxis = Vector3::X_AXIS; splitLocation = 0; for (int i = 0; i < 2; ++i) { child[i] = NULL; } int n = endIndex - beginIndex + 1; valueArray.resize(n); for (int i = n - 1; i >= 0; --i) { valueArray[i] = pt[i + beginIndex]; } } /** Deletes the children (but not the values) */ ~Node() { for (int i = 0; i < 2; ++i) { delete child[i]; } } /** Returns true if this node is a leaf (no children) */ inline bool isLeaf() const { return (child[0] == NULL) && (child[1] == NULL); } /** Recursively appends all handles and children's handles to the array. */ void getHandles(Array<Handle>& handleArray) const { handleArray.append(valueArray); for (int i = 0; i < 2; ++i) { if (child[i] != NULL) { child[i]->getHandles(handleArray); } } } void verifyNode(const Vector3& lo, const Vector3& hi) { // debugPrintf("Verifying: split %d @ %f [%f, %f, %f], [%f, %f, %f]\n", // splitAxis, splitLocation, lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); debugAssert(lo == splitBounds.low()); debugAssert(hi == splitBounds.high()); for (int i = 0; i < valueArray.length(); ++i) { const AABox& b = valueArray[i].bounds; for(int axis = 0; axis < 3; ++axis) { debugAssert(b.low()[axis] <= b.high()[axis]); debugAssert(b.low()[axis] >= lo[axis]); debugAssert(b.high()[axis] <= hi[axis]); } } if (child[0] || child[1]) { debugAssert(lo[splitAxis] < splitLocation); debugAssert(hi[splitAxis] > splitLocation); } Vector3 newLo = lo; newLo[splitAxis] = splitLocation; Vector3 newHi = hi; newHi[splitAxis] = splitLocation; if (child[0] != NULL) { child[0]->verifyNode(lo, newHi); } if (child[1] != NULL) { child[1]->verifyNode(newLo, hi); } } #if 0 /** Stores the locations of the splitting planes (the structure but not the content) so that the tree can be quickly rebuilt from a previous configuration without calling balance. */ static void serializeStructure(const Node* n, BinaryOutput& bo) { if (n == NULL) { bo.writeUInt8(0); } else { bo.writeUInt8(1); n->splitBounds.serialize(bo); serialize(n->splitAxis, bo); bo.writeFloat32(n->splitLocation); for (int c = 0; c < 2; ++c) { serializeStructure(n->child[c], bo); } } } /** Clears the member table */ static Node* deserializeStructure(BinaryInput& bi) { if (bi.readUInt8() == 0) { return NULL; } else { Node* n = new Node(); n->splitBounds.deserialize(bi); deserialize(n->splitAxis, bi); n->splitLocation = bi.readFloat32(); for (int c = 0; c < 2; ++c) { n->child[c] = deserializeStructure(bi); } } } #endif /** Returns the deepest node that completely contains bounds. */ Node* findDeepestContainingNode(const AABox& bounds) { // See which side of the splitting plane the bounds are on if (bounds.high()[splitAxis] < splitLocation) { // Bounds are on the low side. Recurse into the child // if it exists. if (child[0] != NULL) { return child[0]->findDeepestContainingNode(bounds); } } else if (bounds.low()[splitAxis] > splitLocation) { // Bounds are on the high side, recurse into the child // if it exists. if (child[1] != NULL) { return child[1]->findDeepestContainingNode(bounds); } } // There was no containing child, so this node is the // deepest containing node. return this; } /** Appends all members that intersect the box. If useSphere is true, members that pass the box test face a second test against the sphere. */ void getIntersectingMembers( const AABox& box, const Sphere& sphere, Array<T>& members, bool useSphere) const { // Test all values at this node for (int v = 0; v < valueArray.size(); ++v) { const AABox& bounds = valueArray[v].bounds; if (bounds.intersects(box) && (! useSphere || bounds.intersects(sphere))) { members.append(valueArray[v].value); } } // If the left child overlaps the box, recurse into it if ((child[0] != NULL) && (box.low()[splitAxis] < splitLocation)) { child[0]->getIntersectingMembers(box, sphere, members, useSphere); } // If the right child overlaps the box, recurse into it if ((child[1] != NULL) && (box.high()[splitAxis] > splitLocation)) { child[1]->getIntersectingMembers(box, sphere, members, useSphere); } } /** Recurse through the tree, assigning splitBounds fields. */ void assignSplitBounds(const AABox& myBounds) { splitBounds = myBounds; AABox childBounds[2]; myBounds.split(splitAxis, splitLocation, childBounds[0], childBounds[1]); for (int c = 0; c < 2; ++c) { if (child[c]) { child[c]->assignSplitBounds(childBounds[c]); } } } }; /** Recursively subdivides the subarray. Begin and end indices are inclusive. Call assignSplitBounds() on the root node after making a tree. */ Node* makeNode(Array<Handle>& point, int beginIndex, int endIndex, int valuesPerNode, int numMeanSplits) { Node* node = NULL; if (endIndex - beginIndex + 1 <= valuesPerNode) { // Make a new leaf node node = new Node(point, beginIndex, endIndex); // Set the pointers in the memberTable for (int i = beginIndex; i <= endIndex; ++i) { memberTable.set(point[i].value, node); } } else { // Make a new internal node node = new Node(); const AABox bounds = computeBounds(point, beginIndex, endIndex); const Vector3 extent = bounds.high() - bounds.low(); Vector3::Axis splitAxis = extent.primaryAxis(); double splitLocation; if (numMeanSplits > 0) { // Compute the mean along the axis splitLocation = (bounds.high()[splitAxis] + bounds.low()[splitAxis]) / 2.0; } else { // Compute the median along the axis // Sort only the subarray std::sort( point.getCArray() + beginIndex, point.getCArray() + endIndex + 1, CenterLT(splitAxis)); // Intentional integer divide int midIndex = (beginIndex + endIndex) / 2; // Choose the split location between the two middle elements const Vector3 median = (point[midIndex].bounds.high() + point[iMin(midIndex + 1, point.size() - 1)].bounds.low()) * 0.5; splitLocation = median[splitAxis]; } // Re-sort around the split. This will allow us to easily // test for overlap std::sort( point.getCArray() + beginIndex, point.getCArray() + endIndex + 1, PivotLT(splitAxis, splitLocation)); // Some number of nodes may actually overlap the midddle, so // they must be found and added to *this* node, not one of // its children int overlapBeginIndex, overlapEndIndex; for (overlapBeginIndex = beginIndex; (overlapBeginIndex <= endIndex) && (point[overlapBeginIndex].bounds.high()[splitAxis] < splitLocation); ++overlapBeginIndex) {} for (overlapEndIndex = endIndex; (overlapEndIndex >= beginIndex) && (point[overlapEndIndex].bounds.low()[splitAxis] > splitLocation); --overlapEndIndex) {} #ifdef _ASSEMBLER_DEBUG fprintf(::g_df,"splitLocation: %f, beginIndex: %d, endIndex:%d, overlapBeginIndex: %d, overlapEndIndex: %d\n",splitLocation, beginIndex, endIndex, overlapBeginIndex, overlapEndIndex); if(beginIndex == 220) { float oldf = -100000.0f; for (int xxx = beginIndex; (xxx <= endIndex); ++xxx) { fprintf(::g_df," xxx:%d, point[xxx].bounds.high()[splitAxis]: %f\n",xxx, point[xxx].bounds.high()[splitAxis]); if(oldf > point[xxx].bounds.high()[splitAxis]) { fprintf(::g_df," huch ...\n"); } oldf = point[xxx].bounds.high()[splitAxis]; } } #endif // put overlapping boxes in this node for (int i = overlapBeginIndex; i <= overlapEndIndex; ++i) { node->valueArray.push(point[i]); memberTable.set(point[i].value, node); } node->splitAxis = splitAxis; node->splitLocation = splitLocation; if (overlapBeginIndex > beginIndex) { node->child[0] = makeNode(point, beginIndex, overlapBeginIndex - 1, valuesPerNode, numMeanSplits - 1); } if (overlapEndIndex < endIndex) { node->child[1] = makeNode(point, overlapEndIndex + 1, endIndex, valuesPerNode, numMeanSplits - 1); } } return node; } /** Recursively clone the passed in node tree, setting pointers for members in the memberTable as appropriate. called by the assignment operator. */ Node* cloneTree(Node* src) { Node* dst = new Node(*src); // Make back pointers for (int i = 0; i < dst->valueArray.size(); ++i) { memberTable.set(dst->valueArray[i].value, dst); } // Clone children for (int i = 0; i < 2; ++i) { if (src->child[i] != NULL) { dst->child[i] = cloneTree(src->child[i]); } } return dst; } /** Maps members to the node containing them */ Table<T, Node*> memberTable; Node* root; /** To construct a balanced tree, insert the elements and then call AABSPTree::balance(). */ AABSPTree() : root(NULL) {} AABSPTree(const AABSPTree& src) : root(NULL) { *this = src; } AABSPTree& operator=(const AABSPTree& src) { delete root; // Clone tree takes care of filling out the memberTable. root = cloneTree(src.root); } ~AABSPTree() { clear(); } /** Throws out all elements of the set. */ void clear() { memberTable.clear(); delete root; root = NULL; } size_t size() const { return memberTable.size(); } /** Inserts an object into the set if it is not already present. O(log n) time. Does not cause the tree to be balanced. */ void insert(const T& value) { if (contains(value)) { // Already in the set return; } Handle h(value); if (root == NULL) { // This is the first node; create a root node root = new Node(); } Node* node = root->findDeepestContainingNode(h.bounds); // Insert into the node node->valueArray.append(h); // Insert into the node table memberTable.set(value, node); } /** Inserts each elements in the array in turn. If the tree begins empty (no structure and no elements), this is faster than inserting each element in turn. You still need to balance the tree at the end.*/ void insert(const Array<T>& valueArray) { if (root == NULL) { // Optimized case for an empty tree; don't bother // searching or reallocating the root node's valueArray // as we incrementally insert. root = new Node(); root->valueArray.resize(valueArray.size()); for (int i = 0; i < valueArray.size(); ++i) { // Insert in opposite order so that we have the exact same // data structure as if we inserted each (i.e., order is reversed // from array). root->valueArray[valueArray.size() - i - 1] = Handle(valueArray[i]); memberTable.set(valueArray[i], root); } } else { // Insert at appropriate tree depth. for (int i = 0; i < valueArray.size(); ++i) { insert(valueArray[i]); } } } /** Returns true if this object is in the set, otherwise returns false. O(1) time. */ bool contains(const T& value) { return memberTable.containsKey(value); } /** Removes an object from the set in O(1) time. It is an error to remove members that are not already present. May unbalance the tree. Removing an element never causes a node (split plane) to be removed... nodes are only changed when the tree is rebalanced. This behavior is desirable because it allows the split planes to be serialized, and then deserialized into an empty tree which can be repopulated. */ void remove(const T& value) { debugAssertM(contains(value), "Tried to remove an element from a " "AABSPTree that was not present"); Array<Handle>& list = memberTable[value]->valueArray; // Find the element and remove it for (int i = list.length() - 1; i >= 0; --i) { if (list[i].value == value) { list.fastRemove(i); break; } } memberTable.remove(value); } /** If the element is in the set, it is removed. The element is then inserted. This is useful when the == and hashCode methods on <I>T</I> are independent of the bounds. In that case, you may call update(v) to insert an element for the first time and call update(v) again every time it moves to keep the tree up to date. */ void update(const T& value) { if (contains(value)) { remove(value); } insert(value); } /** Rebalances the tree (slow). Call when objects have moved substantially from their original positions (which unbalances the tree and causes the spatial queries to be slow). @param valuesPerNode Maximum number of elements to put at a node. @param numMeanSplits numMeanSplits = 0 gives a fully axis aligned BSP-tree, where the balance operation attempts to balance the tree so that every splitting plane has an equal number of left and right children (i.e. it is a <B>median</B> split along that axis). This tends to maximize average performance. You can override this behavior by setting a number of <B>mean</B> (average) splits. numMeanSplits = MAX_INT creates a full oct-tree, which tends to optimize peak performance at the expense of average performance. It tends to have better clustering behavior when members are not uniformly distributed. */ void balance(int valuesPerNode = 5, int numMeanSplits = 3) { if (root == NULL) { // Tree is empty return; } Array<Handle> handleArray; root->getHandles(handleArray); // Delete the old tree clear(); root = makeNode(handleArray, 0, handleArray.size() - 1, valuesPerNode, numMeanSplits); // Walk the tree, assigning splitBounds. We start with unbounded // space. root->assignSplitBounds(AABox::maxFinite()); #ifdef _DEBUG root->verifyNode(Vector3::minFinite(), Vector3::maxFinite()); #endif } private: /** @param parentMask The mask that this node returned from culledBy. */ static void getIntersectingMembers( const Array<Plane>& plane, Array<T>& members, Node* node, uint32 parentMask) { int dummy; if (parentMask == 0) { // None of these planes can cull anything for (int v = node->valueArray.size() - 1; v >= 0; --v) { members.append(node->valueArray[v].value); } // Iterate through child nodes for (int c = 0; c < 2; ++c) { if (node->child[c]) { getIntersectingMembers(plane, members, node->child[c], 0); } } } else { // Test values at this node against remaining planes for (int v = node->valueArray.size() - 1; v >= 0; --v) { if (! node->valueArray[v].bounds.culledBy(plane, dummy, parentMask)) { members.append(node->valueArray[v].value); } } uint32 childMask = 0xFFFFFF; // Iterate through child nodes for (int c = 0; c < 2; ++c) { if (node->child[c] && ! node->child[c]->splitBounds.culledBy(plane, dummy, parentMask, childMask)) { // This node was not culled getIntersectingMembers(plane, members, node->child[c], childMask); } } } } public: /** Returns all members inside the set of planes. @param members The results are appended to this array. */ void getIntersectingMembers(const Array<Plane>& plane, Array<T>& members) const { if (root == NULL) { return; } getIntersectingMembers(plane, members, root, 0xFFFFFF); } /** Typically used to find all visible objects inside the view frustum (see also GCamera::getClipPlanes)... i.e. all objects <B>not<B> culled by frustum. Example: <PRE> Array<Object*> visible; tree.getIntersectingMembers(camera.frustum(), visible); // ... Draw all objects in the visible array. </PRE> @param members The results are appended to this array. */ void getIntersectingMembers(const GCamera::Frustum& frustum, Array<T>& members) const { Array<Plane> plane; for (int i = 0; i < frustum.faceArray.size(); ++i) { plane.append(frustum.faceArray[i].plane); } getIntersectingMembers(plane, members); } /** C++ STL style iterator variable. See beginBoxIntersection(). The iterator overloads the -> (dereference) operator, so this acts like a pointer to the current member. */ // This iterator turns Node::getIntersectingMembers into a // coroutine. It first translates that method from recursive to // stack based, then captures the system state (analogous to a Scheme // continuation) after each element is appended to the member array, // and allowing the computation to be restarted. class BoxIntersectionIterator { private: friend class AABSPTree<T>; /** True if this is the "end" iterator instance */ bool isEnd; /** The box that we're testing against. */ AABox box; /** Node that we're currently looking at. Undefined if isEnd is true. */ Node* node; /** Nodes waiting to be processed */ // We could use backpointers within the tree and careful // state management to avoid ever storing the stack-- but // it is much easier this way and only inefficient if the // caller uses post increment (which they shouldn't!). Array<Node*> stack; /** The next index of current->valueArray to return. Undefined when isEnd is true.*/ int nextValueArrayIndex; BoxIntersectionIterator() : isEnd(true) {} BoxIntersectionIterator(const AABox& b, const Node* root) : box(b), isEnd(root == NULL), nextValueArrayIndex(-1), node(const_cast<Node*>(root)) { // We intentionally start at the "-1" index of the current node // so we can use the preincrement operator to move ourselves to // element 0 instead of repeating all of the code from the preincrement // method. Note that this might cause us to become the "end" // instance. ++(*this); } public: inline bool operator!=(const BoxIntersectionIterator& other) const { return ! (*this == other); } bool operator==(const BoxIntersectionIterator& other) const { if (isEnd) { return other.isEnd; } else if (other.isEnd) { return false; } else { // Two non-end iterators; see if they match. This is kind of // silly; users shouldn't call == on iterators in general unless // one of them is the end iterator. if ((box != other.box) || (node != other.node) || (nextValueArrayIndex != other.nextValueArrayIndex) || (stack.length() != other.stack.length())) { return false; } // See if the stacks are the same for (int i = 0; i < stack.length(); ++i) { if (stack[i] != other.stack[i]) { return false; } } // We failed to find a difference; they must be the same return true; } } /** Pre increment. */ BoxIntersectionIterator& operator++() { ++nextValueArrayIndex; bool foundIntersection = false; while (! isEnd && ! foundIntersection) { // Search for the next node if we've exhausted this one while ((! isEnd) && (nextValueArrayIndex >= node->valueArray.length())) { // If we entered this loop, then the iterator has exhausted the elements at // node (possibly because it just switched to a child node with no members). // This loop continues until it finds a node with members or reaches // the end of the whole intersection search. // If the right child overlaps the box, push it onto the stack for // processing. if ((node->child[1] != NULL) && (box.high()[node->splitAxis] > node->splitLocation)) { stack.push(node->child[1]); } // If the left child overlaps the box, push it onto the stack for // processing. if ((node->child[0] != NULL) && (box.low()[node->splitAxis] < node->splitLocation)) { stack.push(node->child[0]); } if (stack.length() > 0) { // Go on to the next node (which may be either one of the ones we // just pushed, or one from farther back the tree). node = stack.pop(); nextValueArrayIndex = 0; } else { // That was the last node; we're done iterating isEnd = true; } } // Search for the next intersection at this node until we run out of children while (! isEnd && ! foundIntersection && (nextValueArrayIndex < node->valueArray.length())) { if (box.intersects(node->valueArray[nextValueArrayIndex].bounds)) { foundIntersection = true; } else { ++nextValueArrayIndex; // If we exhaust this node, we'll loop around the master loop // to find a new node. } } } return *this; } /** Post increment (much slower than preincrement!). */ BoxIntersectionIterator operator++(int) { BoxIntersectionIterator old = *this; ++this; return old; } /** Overloaded dereference operator so the iterator can masquerade as a pointer to a member */ const T& operator*() const { alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); return node->valueArray[nextValueArrayIndex].value; } /** Overloaded dereference operator so the iterator can masquerade as a pointer to a member */ T const * operator->() const { alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); return &(stack.last()->valueArray[nextValueArrayIndex].value); } /** Overloaded cast operator so the iterator can masquerade as a pointer to a member */ operator T*() const { alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); return &(stack.last()->valueArray[nextValueArrayIndex].value); } }; /** Iterates through the members that intersect the box */ BoxIntersectionIterator beginBoxIntersection(const AABox& box) const { return BoxIntersectionIterator(box, root); } BoxIntersectionIterator endBoxIntersection() const { // The "end" iterator instance return BoxIntersectionIterator(); } /** Appends all members whose bounds intersect the box. See also AABSPTree::beginBoxIntersection. */ void getIntersectingMembers(const AABox& box, Array<T>& members) const { if (root == NULL) { return; } root->getIntersectingMembers(box, Sphere(Vector3::ZERO, 0), members, false); } /** @param members The results are appended to this array. */ void getIntersectingMembers(const Sphere& sphere, Array<T>& members) const { if (root == NULL) { return; } AABox box; sphere.getBounds(box); root->getIntersectingMembers(box, sphere, members, true); } /** See AABSPTree::beginRayIntersection */ class RayIntersectionIterator { private: friend class AABSPTree<T>; /** The stack frame contains all the info needed to resume computation for the RayIntersectionIterator */ struct StackFrame { const Node* node; /** the total checking bounds for this frame */ float minTime; /** minTime^2 */ float minTime2; float maxTime; /** what we're checking right now, either from minTime to the split, or from the split to maxTime (more or less... there are edge cases) */ float startTime; float endTime; /** endTime^2 */ float endTime2; int nextChild; /** current index into node's valueArray */ int valIndex; /** cache intersection values when they're checked on the preSide, split so they don't need to be checked again after the split. */ Array<float> intersectionCache; void init(const Node* inNode, const Ray& ray, float inMinTime, float inMaxTime) { node = inNode; minTime = inMinTime; maxTime = inMaxTime; minTime2 = square(minTime); valIndex = -1; intersectionCache.resize(node->valueArray.length()); if (node->child[0] == NULL && node->child[1] == NULL) { startTime = minTime; endTime = maxTime; endTime2 = square(maxTime); nextChild = -1; return; } Vector3::Axis splitAxis = node->splitAxis; double splitLocation = node->splitLocation; // this is the time along the ray until the split. // could be negative if the split is behind. double splitTime = (splitLocation - ray.origin[splitAxis]) / ray.direction[splitAxis]; // If splitTime <= minTime we'll never reach the // split, so set it to inf so as not to confuse endTime. // It will be noted below that when splitTime is inf // only one of this node's children will be searched // (the pre child). Therefore it is critical that // the correct child is gone too. if (splitTime <= minTime) { splitTime = inf(); } startTime = minTime; endTime = min((double)maxTime, splitTime); endTime2 = square(endTime); double rayLocation = ray.origin[splitAxis] + ray.direction[splitAxis] * minTime; if (rayLocation == splitLocation) { // We're right on the split. Look ahead. rayLocation = ray.origin[splitAxis] + ray.direction[splitAxis] * maxTime; } if (rayLocation == splitLocation) { // right on the split, looking exactly along // it, so consider no children. nextChild = -1; } else if(rayLocation <= splitLocation) { nextChild = 0; } else { nextChild = 1; } } }; public: /** A minimum bound on the distance to the intersection. */ double minDistance; /** A maximum bound on the distance to the intersection. */ double maxDistance; /** Counts how many bounding box intersection tests have been made so far. */ int debugCounter; private: Ray ray; bool isEnd; Array<StackFrame> stack; int stackLength; int stackIndex; int breakFrameIndex; bool skipAABoxTests; double boxMaxDist2; RayIntersectionIterator(const Ray& r, const Node* root, double pMaxTime, bool skip) : minDistance(0), maxDistance(G3D::inf()), debugCounter(0), ray(r), isEnd(root == NULL), stackLength(20), stackIndex(0), breakFrameIndex(-1), skipAABoxTests(skip) { stack.resize(stackLength); stack[stackIndex].init(root, ray, 0, G3D::inf()); boxMaxDist2 = pMaxTime*pMaxTime; ++(*this); } public: /* public so we can have empty ones */ RayIntersectionIterator() : isEnd(true) {} inline bool operator!=(const RayIntersectionIterator& other) const { return ! (*this == other); } /** Compares two iterators, but will only return true if both are at the end. */ bool operator==(const RayIntersectionIterator& other) const { if (isEnd) { return other.isEnd; } return false; } /** Marks the node where the most recent intersection occurred. If the iterator exhausts this node it will stop and set itself to the end iterator. Use this after you find a true intersection to stop the iterator from searching more than necessary. <B>Beta API-- subject to change</B> */ // In theory this method could be smarter: the caller could pass in // the distance of the actual collision and the iterator would keep // itself from checking nodes or boxes beyond that distance. void markBreakNode() { breakFrameIndex = stackIndex; } /** Clears the break node. Can be used before or after the iterator stops from a break. <B>Beta API-- subject to change</B> */ void clearBreakNode() { if (breakFrameIndex < 0) { return; } if (isEnd && stackIndex >= 0) { isEnd = false; } breakFrameIndex = -1; } RayIntersectionIterator& operator++() { alwaysAssertM(!isEnd, "Can't increment the end element of an iterator"); StackFrame* s = &stack[stackIndex]; // leave the loop if: // end is reached (ie: stack is empty) // found an intersection while (true) { ++s->valIndex; if (s->valIndex >= s->node->valueArray.length()) { // This node is exhausted, look at its // children. Node* child = (s->nextChild >= 0) ? s->node->child[s->nextChild] : NULL; double childStartTime = s->startTime; double childEndTime = s->endTime; if (s->endTime < s->maxTime) { // we can come back to this frame, // so reset it s->valIndex = -1; s->startTime = s->endTime; s->endTime = s->maxTime; s->endTime2 = square(s->maxTime); s->nextChild = (s->nextChild >= 0) ? (1 - s->nextChild) : -1; // this could be changed somehow, // since Array already does the // power-of-two growth stuff if (stackIndex == stackLength) { stackLength *= 2; stack.resize(stackLength); } } else { // tail-recursion: we won't come // back to this frame, so we can // remove it. if (stackIndex == breakFrameIndex) { // This will be the case if the // break frame is set on a node, but // the node is exhausted so it won't // be put on the stack. Here we // decrement the break frame so that // the break occurs when the current // frame's parent is resumed. --breakFrameIndex; } --stackIndex; } // There could have been a resize on the array, so // do not use s (pointer into the array)! if (child != NULL) { ++stackIndex; stack[stackIndex].init( child, ray, childStartTime, childEndTime); } if ((stackIndex < 0) || (stackIndex == breakFrameIndex)) { isEnd = true; break; } s = &stack[stackIndex]; continue; } if (skipAABoxTests) { // No AABox test-- return everything minDistance = s->startTime; maxDistance = s->endTime; break; } else { double t2; // this can be an exact equals because the two // variables are initialized to the same thing if (s->startTime == s->minTime) { Vector3 location; bool insiteOk; Vector3 mynormal; if ( VMAP::MyCollisionDetection::collisionLocationForMovingPointFixedAABox( ray.origin, ray.direction, s->node->valueArray[s->valIndex].bounds, location,insiteOk, mynormal )) { // Optimization: store t-squared t2 = (location - ray.origin).squaredLength(); } else { t2 = inf(); } if(t2 > boxMaxDist2) t2=inf(); // too far off //t = ray.intersectionTime(s->node->valueArray[s->valIndex].bounds); s->intersectionCache[s->valIndex] = t2; ++debugCounter; } else { t2 = s->intersectionCache[s->valIndex]; } // use minTime here because intersection may be // detected pre-split, but be valid post-split, too. if ((t2 >= s->minTime2) && (t2 < s->endTime2)) { // Gives slightly tighter bounds but runs slower: // minDistance = max(t, s->startTime); minDistance = s->startTime; maxDistance = s->endTime; break; } } } return *this; } /** Overloaded dereference operator so the iterator can masquerade as a pointer to a member */ const T& operator*() const { alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); return stack[stackIndex].node->valueArray[stack[stackIndex].valIndex].value; } /** Overloaded dereference operator so the iterator can masquerade as a pointer to a member */ T const * operator->() const { alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); return &(stack[stackIndex].node->valueArray[stack[stackIndex].valIndex].value); } /** Overloaded cast operator so the iterator can masquerade as a pointer to a member */ operator T*() const { alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); return &(stack[stackIndex].node->valueArray[stack[stackIndex].valIndex].value); } }; /** Generates a RayIntersectionIterator that produces successive elements from the set whose bounding boxes are intersected by the ray. Typically used for ray tracing, hit-scan, and collision detection. The elements are generated mostly in the order that they are hit by the ray, so that iteration may end abruptly when the closest intersection to the ray origin has been reached. Because the elements within a given kd-tree node are unordered, iteration may need to proceed a little past the first member returned in order to find the closest intersection. The iterator doesn't automatically find the first intersection because it is looking at bounding boxes, not the true intersections. When the caller finds a true intersection it should call markBreakNode() on the iterator. This will stop the iterator (setting it to the end iterator) when the current node and relevant children are exhausted. Complicating the matter further, some members straddle the plane. The iterator produces these members <I>twice</I>. The first time it is produced the caller should only consider intersections on the near side of the split plane. The second time, the caller should only consider intersections on the far side. The minDistance and maxDistance fields specify the range on which intersections should be considered. Be aware that they may be inf or zero. An example of how to use the iterator follows. Almost all ray intersection tests will have identical structure. <PRE> void findFirstIntersection( const Ray& ray, Object*& firstObject, double& firstTime) { firstObject = NULL; firstDistance = inf(); typedef AABSPTree<Object*>::RayIntersectionIterator IT; const IT end = tree.endRayIntersection(); for (IT obj = tree.beginRayIntersection(ray); obj != end; ++obj) { // (preincrement is *much* faster than postincrement!) // Call your accurate intersection test here. It is guaranteed // that the ray hits the bounding box of obj. (*obj) has type T, // so you can call methods directly using the "->" operator. double t = obj->distanceUntilIntersection(ray); // Often methods like "distanceUntilIntersection" can be made more // efficient by providing them with the time at which to start and // to give up looking for an intersection; that is, // obj.minDistance and iMin(firstDistance, obj.maxDistance). static const double epsilon = 0.00001; if ((t < firstDistance) && (t <= obj.maxDistance + epsilon) && (t >= obj.minDistance - epsilon)) { // This is the new best collision time firstObject = obj; firstDistance = t; // Tell the iterator that we've found at least one // intersection. It will finish looking at all // objects in this node and then terminate. obj.markBreakNode(); } } } </PRE> @param skipAABoxTests Set to true when the intersection test for a member is faster than an AABox-ray intersection test. In that case, the iterator will not use a bounding box test on values that are returned. Leave false (the default) for objects with slow intersection tests. In that case, the iterator guarantees that the ray hits the bounds of any object returned. @cite Implementation by Pete Hopkins */ RayIntersectionIterator beginRayIntersection(const Ray& ray, double pMaxTime, bool skipAABoxTests = false) const { return RayIntersectionIterator(ray, root, pMaxTime, skipAABoxTests); } RayIntersectionIterator endRayIntersection() const { return RayIntersectionIterator(); } /** Returns an array of all members of the set. See also AABSPTree::begin. */ void getMembers(Array<T>& members) const { memberTable.getKeys(members); } /** C++ STL style iterator variable. See begin(). Overloads the -> (dereference) operator, so this acts like a pointer to the current member. */ class Iterator { private: friend class AABSPTree<T>; // Note: this is a Table iterator, we are currently defining // Set iterator typename Table<T, Node*>::Iterator it; Iterator(const typename Table<T, Node*>::Iterator& it) : it(it) {} public: inline bool operator!=(const Iterator& other) const { return !(*this == other); } bool operator==(const Iterator& other) const { return it == other.it; } /** Pre increment. */ Iterator& operator++() { ++it; return *this; } /** Post increment (slower than preincrement). */ Iterator operator++(int) { Iterator old = *this; ++(*this); return old; } const T& operator*() const { return it->key; } T* operator->() const { return &(it->key); } operator T*() const { return &(it->key); } }; /** C++ STL style iterator method. Returns the first member. Use preincrement (++entry) to get to the next element (iteration order is arbitrary). Do not modify the set while iterating. */ Iterator begin() const { return Iterator(memberTable.begin()); } /** C++ STL style iterator method. Returns one after the last iterator element. */ Iterator end() const { return Iterator(memberTable.end()); } }; #define KDTreeSet AABSPTree } #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 29 ], [ 32, 1164 ], [ 1166, 1608 ] ], [ [ 30, 31 ], [ 1165, 1165 ] ] ]
6547bd4e2dbef29ccacf03f859c9ec954f689d8a
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/src/OpenGL/VertexDeclarationGL.cpp
0382722c1322264a15fc7b74a3e7ecf3bd9f5dd2
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
7,476
cpp
/*******************************************************************************/ /** * @file VertexDeclarationGL.cpp. * * @brief OpenGL 頂点宣言データクラスソースファイル. * * @date 2008/07/20. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #include "Ngl/OpenGL/VertexDeclarationGL.h" #include "Ngl/OpenGL/BufferGL.h" using namespace Ngl; using namespace Ngl::OpenGL; /*=========================================================================*/ /** * @brief コンストラクタ * * @param[in] desc 頂点宣言データ記述子の配列. * @param[in] numDesc 頂点宣言データ記述子配列の要素数. */ VertexDeclarationGL::VertexDeclarationGL( const VertexDeclarationDesc desc[], unsigned int numDesc ): desc_( &desc[0], &desc[numDesc] ), elements_( numDesc ) { for( unsigned int i=0; i<numDesc; ++i ){ elements_[i] = toElement( desc_[i] ); } } /*=========================================================================*/ /** * @brief デストラクタ * * @param[in] なし. */ VertexDeclarationGL::~VertexDeclarationGL() {} /*=========================================================================*/ /** * @brief 頂点宣言データの個数を取得 * * @param[in] なし. * @return 個数. */ unsigned int VertexDeclarationGL::size() const { return (unsigned int)desc_.size(); } /*=========================================================================*/ /** * @brief 記述子を取得 * * @param[in] index 取得する記述子のインデックス番号. * @return 記述子. */ const VertexDeclarationDesc& VertexDeclarationGL::desc( unsigned int index ) const { return desc_[index]; } /*=========================================================================*/ /** * @brief 頂点バッファストリームの設定 * * @param[in] streams 設定する頂点ストリーム記述子配列. * @param[in] start 設定開始配列位置. * @return なし. */ void VertexDeclarationGL::setVertexStream( const VertexStreamDesc streams[], unsigned int start ) { // 頂点ストリームのリセット resetVertexStream(); // 頂点バッファを設定する for( VertexDeclarationArray::iterator i = elements_.begin(); i !=elements_.end(); ++i ){ setVertexBuffer( *i, streams[ (*i).stream ], start ); } } /*=========================================================================*/ /** * @brief 頂点バッファストリームのリセット * * @param[in] なし. * @return なし. */ void VertexDeclarationGL::resetVertexStream() { // 頂点配列を無効にする for( GLuint attr=0; attr<VERTEX_DECLARATION_MAX; ++attr ){ glDisableVertexAttribArray( attr ); } } /*=========================================================================*/ /** * @brief 頂点バッファの設定 * * @param[in] element 頂点宣言要素構造体. * @param[in] stream 頂点ストリーム記述子. * @param[in] start 開始位置. * @return なし. */ void VertexDeclarationGL::setVertexBuffer( const VertexDeclarationGL::Element& element, const VertexStreamDesc& stream, unsigned int start ) { // 頂点バッファをバインドする glBindBufferARB( GL_ARRAY_BUFFER_ARB, static_cast< BufferGL* >( stream.buffer )->buffer() ); // 頂点データ配列を有効にする glEnableVertexAttribArrayARB( element.attrib ); // 頂点バッファを設定する GLubyte* base = 0; glVertexAttribPointerARB( element.attrib, element.format.size, element.format.type, element.format.normalized, stream.stride, &base[ start * stream.stride + stream.offset + element.offset ] ); // 頂点バッファのバインドを解除 glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); } /*=========================================================================*/ /** * @brief 頂点宣言記述子を変換 * * @param[in] desc 変換する頂点宣言記述子構造体. * @return 変換後の頂点宣言要素構造体. */ VertexDeclarationGL::Element VertexDeclarationGL::toElement( const VertexDeclarationDesc& desc ) { Element element; element.attrib = toAttrib( desc.semantic ) + desc.index; element.format = toVertexFormat( desc.type ); element.offset = desc.offset; element.stream = desc.stream; return element; } /*=========================================================================*/ /** * @brief 頂点セマンティックを変換 * * @param[in] semantic 変換する頂点セマンティックフラグ. * @return 変換後のOpenGL頂点セマンティック. */ GLuint VertexDeclarationGL::toAttrib( VertexSemantic semantic ) { static const unsigned int attribs[] = { 0, // VERTEX_FORMAT_POSITION = 0 1, // VERTEX_FORMAT_BLENDWEIGHT = 1 2, // VERTEX_FORMAT_NORMAL = 2 3, // VERTEX_FORMAT_COLOR = 3 3, // VERTEX_FORMAT_DIFFUSE = 4 4, // VERTEX_FORMAT_SPECULAR = 5 5, // VERTEX_FORMAT_TESSFACTOR = 6 5, // VERTEX_FORMAT_FOGCOORD = 7 6, // VERTEX_FORMAT_PSIE = 8 7, // VERTEX_FORMAT_BLENDINDICES = 9 8, // VERTEX_FORMAT_TEXCOORD = 10 14, // VERTEX_FORMAT_TANGENT = 11 15 // VERTEX_FORMAT_BINORMAL = 12 }; return attribs[ semantic ]; } /*=========================================================================*/ /** * @brief 頂点タイプを変換 * * @param[in] type 変換する頂点タイプフラグ. * @return 変換後の頂点フォーマット構造体. */ const VertexDeclarationGL::VertexFormat& VertexDeclarationGL::toVertexFormat( VertexType type ) { static const VertexFormat vertexFormats[] = { { GL_FLOAT, 1, GL_FALSE }, // VERTEX_TYPE_FLOAT1 = 0 { GL_FLOAT, 2, GL_FALSE }, // VERTEX_TYPE_FLOAT2 = 1 { GL_FLOAT, 3, GL_FALSE }, // VERTEX_TYPE_FLOAT3 = 2 { GL_FLOAT, 4, GL_FALSE }, // VERTEX_TYPE_FLOAT4 = 3 { GL_BYTE, 4, GL_FALSE }, // VERTEX_TYPE_BYTE4 = 4 { GL_BYTE, 4, GL_TRUE }, // VERTEX_TYPE_BYTE4N = 5 { GL_UNSIGNED_BYTE, 4, GL_FALSE }, // VERTEX_TYPE_UBYTE4 = 6 { GL_UNSIGNED_BYTE, 4, GL_TRUE }, // VERTEX_TYPE_UBYTE4N = 7 { GL_SHORT, 2, GL_FALSE }, // VERTEX_TYPE_SHORT2 = 8 { GL_SHORT, 2, GL_TRUE }, // VERTEX_TYPE_SHORT2N = 9 { GL_UNSIGNED_SHORT, 2, GL_FALSE }, // VERTEX_TYPE_USHORT2 = 10 { GL_UNSIGNED_SHORT, 2, GL_TRUE }, // VERTEX_TYPE_USHORT2N = 11 { GL_SHORT, 4, GL_FALSE }, // VERTEX_TYPE_SHORT4 = 12 { GL_SHORT, 4, GL_TRUE }, // VERTEX_TYPE_SHORT4N = 13 { GL_UNSIGNED_SHORT, 4, GL_FALSE }, // VERTEX_TYPE_USHORT4 = 14 { GL_UNSIGNED_SHORT, 4, GL_TRUE }, // VERTEX_TYPE_USHORT4N = 15 { GL_INT, 1, GL_FALSE }, // VERTEX_TYPE_INT1 = 16 { GL_INT, 2, GL_FALSE }, // VERTEX_TYPE_INT2 = 17 { GL_INT, 3, GL_FALSE }, // VERTEX_TYPE_INT3 = 18 { GL_INT, 4, GL_FALSE }, // VERTEX_TYPE_INT4 = 19 { GL_UNSIGNED_INT, 1, GL_FALSE }, // VERTEX_TYPE_UINT1 = 20 { GL_UNSIGNED_INT, 2, GL_FALSE }, // VERTEX_TYPE_UINT2 = 21 { GL_UNSIGNED_INT, 3, GL_FALSE }, // VERTEX_TYPE_UINT3 = 22 { GL_UNSIGNED_INT, 4, GL_FALSE } // VERTEX_TYPE_UINT4 = 23 }; return vertexFormats[ type ]; } /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 239 ] ] ]
d02d6ca71f79496c8af5799731d2a22dbe6f66da
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HaohanITPlayer/private/DVR/UploadFileMgr.cpp
dd4c00f91be29c6213011492d27ad3060ed874eb
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,672
cpp
// UploadFileMgr.cpp: implementation of the CUploadFileMgr class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "UploadFileMgr.h" //#ifdef _DEBUG //#undef THIS_FILE //static char THIS_FILE[]=__FILE__; //#define new DEBUG_NEW //#endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CUploadFileMgr g_UploadFileMgr; CUploadFileMgr::CUploadFileMgr() : m_UploadFile(MAX_UPLOADFILE_NUM) { } CUploadFileMgr::~CUploadFileMgr() { } INT CUploadFileMgr::UploadCfgFile(int userID, LPCTSTR dvrIP, int dvrPort,int fileType, int channel, LPCTSTR imageName ) { CUploadFile* pUploadFile = NULL; DWORD dwLock = m_csLock.Lock(90*1000); if( dwLock != WAIT_OBJECT_0 )//²»ÄÜ»ñµÃËø { return HHV_ERROR_ENTER_CSLOCK; } int index = 0; index = GetIdleIndex( ); if( index < 0) { m_csLock.Unlock(); return index; } pUploadFile = new CUploadFile(); if( NULL == pUploadFile ) { m_csLock.Unlock(); return HHV_ERROR_POORMEMORY; } m_UploadFile[index] = pUploadFile; m_csLock.Unlock(); int ret = pUploadFile->UploadCfgFile(index, userID, dvrIP, dvrPort, fileType, channel, imageName); if( ret < 0) { CAutoLock_Mutex lc(&m_csLock); delete pUploadFile; m_UploadFile[index] = NULL; return ret; } return index; } int CUploadFileMgr::GetIdleIndex() { for(int i = 0; i < MAX_UPLOADFILE_NUM; i++) { if( m_UploadFile[i] == NULL ) return i; } return HHV_ERROR_NOIDLEPLAYER; }
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 75 ] ] ]
ce95b7b2e61de5c525c35721c7e0a95d42c117b0
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/WorkerThread.cpp
500728c3da23aa4231c200982409056fa964f827
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,837
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: WorkerThread.cpp Version: 0.01 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "WorkerThread.h" #include "Task.h" namespace nGENE { WorkerThread::WorkerThread(const string& _name): m_pTask(NULL), m_bProcessing(true), m_Fill(0, 1), m_Empty(1, 1), m_stName(_name) { } //---------------------------------------------------------------------- void WorkerThread::run() { Thread::setName(m_stName); while(m_bProcessing) { // Suspend thread until there is task to perform m_Fill.lock(); m_CriticalSection.lock(); if(m_pTask) { // Perform Task itself m_pTask->update(); // Mark task as completed m_pTask->complete(); m_pTask = NULL; } m_CriticalSection.unlock(); m_Empty.release(1); } signal(); } //---------------------------------------------------------------------- void WorkerThread::setProcessing(bool _value) { m_bProcessing = _value; } //---------------------------------------------------------------------- Task* WorkerThread::getTask() { SharedObject sharedObj(&m_CriticalSection); return m_pTask; } //---------------------------------------------------------------------- void WorkerThread::setTask(Task* _task) { m_Empty.lock(); m_CriticalSection.lock(); m_pTask = _task; if(m_pTask->getAffinityMask()) setAffinityMask(m_pTask->getAffinityMask()); m_CriticalSection.unlock(); m_Fill.release(1); } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 82 ] ] ]
48b54a879c299ec992a5d2321505ddf710f0a91b
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/tools/3dsMax/exportMesh/IGameExporter.h
fae19f2902e195b4040f1a1a53dc7db1794e8200
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,216
h
#ifndef __GAME_EXPORTER_H #define __GAME_EXPORTER_H #include "globals.h" #include <IGame.h> #include <IGameObject.h> #include <IGameProperty.h> #include <IGameControl.h> #include <IGameModifier.h> #include <IConversionManager.h> #include <IGameError.h> #include <string> #include <d3d9.h> #include <d3d9types.h> #include <d3dx9math.h> #include <d3dx9mesh.h> #include "MeshProcessor.h" struct SExportOptions { public: SExportOptions() : mUnitMultiplier(0.001f), //mUseLocalSpace(0), mDoPositions(1), mDoNormals(1), mDoTangents(0), mDoBinormals(0), mTangentsUseUV(0), mColorEncodeNTB(0), mDoSkin(1), mCreate1BoneSkin(1), mStripBipFromBones(1), mSkinBones(4) , mDebugOutput(0) { mDoUVs[0] = 1; for( int i = 1; i < mproc::UV_COUNT; ++i ) mDoUVs[i] = 0; } public: // Multiply units from Max with this. float mUnitMultiplier; // Local object space or world space? //int mUseLocalSpace; // Mesh components to export int mDoPositions; int mDoNormals, mDoTangents, mDoBinormals; int mTangentsUseUV; // use UVs for tangents (0=base, 1=next active, etc.) int mColorEncodeNTB; // encode normals/tangents/binormals as colors? int mDoUVs[mproc::UV_COUNT]; // base UV, next active, etc. int mDoSkin; // export skin weights and skeleton? int mCreate1BoneSkin; // Create 1-bone skin if there's no skinning info? int mStripBipFromBones; // strip "Bip??" from bone names? int mSkinBones; // how many bones/vert int mDebugOutput; // output debug file }; struct SNodeInfo { public: SNodeInfo( IGameNode& n, IGameMesh& m ) : node(&n), mesh(&m), weights(0), indices(0), bones(0) { assert( node && mesh ); } ~SNodeInfo() { if( weights ) delete[] weights; if( indices ) delete[] indices; if( bones ) delete bones; } bool isSkinned() const { return (bones) && (bones->Count() > 0) && (maxBonesPerVert > 0); } void createSelfSkin( int meshIndex ) { assert( !isSkinned() ); int nverts = mesh->GetNumberOfVerts(); weights = new D3DXVECTOR3[nverts]; indices = new DWORD[nverts]; bones = new Tab<IGameNode*>(); for( int i = 0; i < nverts; ++i ) { weights[i].x = 1.0f; weights[i].y = 0.0f; weights[i].z = 0.0f; indices[i] = meshIndex; } bones->Append( 1, &node ); maxBonesPerVert = 1; } public: // The node IGameNode* node; // The mesh object IGameMesh* mesh; // These may be NULL if not skinned. D3DXVECTOR3* weights; // for each vertex DWORD* indices; // for each vertex Tab<IGameNode*>* bones; int maxBonesPerVert; }; class IGameExporter : public SceneExport { public: IGameExporter(); virtual ~IGameExporter(); // SceneExport interface from 3dsMax SDK virtual int ExtCount(); // Number of extensions supported virtual const TCHAR* Ext(int n); // Extension #n (i.e. "3DS") virtual const TCHAR* LongDesc(); // Long ASCII description (i.e. "Autodesk 3D Studio File") virtual const TCHAR* ShortDesc(); // Short ASCII description (i.e. "3D Studio") virtual const TCHAR* AuthorName(); // ASCII Author name virtual const TCHAR* CopyrightMessage(); // ASCII Copyright message virtual const TCHAR* OtherMessage1(); // Other message #1 virtual const TCHAR* OtherMessage2(); // Other message #2 virtual unsigned int Version(); // Version number * 100 (i.e. v3.01 = 301) virtual void ShowAbout(HWND hWnd); // Show DLL's "About..." box virtual BOOL SupportsOptions(int ext, DWORD options); virtual int DoExport(const TCHAR *name,ExpInterface *ei,Interface *i, BOOL suppressPrompts=FALSE, DWORD options=0); private: typedef Tab<IGameNode*> TNodeTab; typedef Tab<SNodeInfo*> TNodeInfoTab; /// Return NULL on success, msg. otherwise const char* gatherNode( IGameNode* node ); /// Return NULL on success, msg. otherwise const char* gatherMesh( SNodeInfo& info ); /// Return NULL on success, msg. otherwise //const char* processNode( IGameNode* node ); void gatherSkin( SNodeInfo& info ); /// Return NULL on success, msg. otherwise const char* meshCreate(); /// Return NULL on success, msg. otherwise const char* meshAddNode( SNodeInfo& info, int& vertOffset, int& triOffset ); /// Return NULL on success, msg. otherwise const char* meshProcess(); /// Return NULL on success, msg. otherwise const char* meshWrite(); /// Return NULL on success, msg. otherwise const char* cleanupMem(); const char* writeMeshData( ID3DXMesh& mesh, DWORD formatBits ); const char* writeSkinData( /*IGameSkin& skin, */TNodeTab& bones, int maxBonesPerVert ); static void reorderBones( TNodeTab& inBones, TNodeTab& outBones ); static void recurseAddBones( TNodeTab& inBones, int boneIdx, TNodeTab& outBones ); BOOL readConfig(); void writeConfig(); TSTR getCfgFilename(); void debugMsg( const char* msg, ... ) const; public: static HWND hParams; IGameScene* mGameScene; FILE* mFile; SExportOptions mOptions; int mCurrNodeProgress; IDirect3D9* mDx; IDirect3DDevice9* mDxDevice; // Gathered info TNodeInfoTab mNodes; int mTotalVerts; int mTotalTris; int mTotalMaxBonesPerVert; // Mesh construction and processing //D3DXVECTOR3* mMeshWeights; //DWORD* mMeshIndices; TNodeTab mMeshBones; Tab<IGameMaterial*> mMeshMats; mproc::CMesh mMesh; bool mMeshHasUVs[mproc::UV_COUNT]; bool mShowPrompts; bool mExportSelected; std::string mDebugFileName; }; #define IGAMEEXPORTER_CLASS_ID Class_ID(0x44170490, 0x34fc5fdd) class IGameExporterClassDesc : public ClassDesc2 { public: int IsPublic() { return TRUE; } void* Create(BOOL loading = FALSE) { return new IGameExporter(); } const TCHAR * ClassName() { return GetString(IDS_CLASS_NAME); } SClass_ID SuperClassID() { return SCENE_EXPORT_CLASS_ID; } Class_ID ClassID() { return IGAMEEXPORTER_CLASS_ID; } const TCHAR* Category() { return GetString(IDS_CATEGORY); } const TCHAR* InternalName() { return _T("IMMeshExport"); } // returns fixed parsable name (scripter-visible name) HINSTANCE HInstance() { return hInstance; } // returns owning module handle }; #endif
[ [ [ 1, 205 ] ] ]
ee1b748399379e6ba6b8011902675460a3baec17
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/axctrls.hpp
716b990dc899ef8e80a873176eaacf7724dab9a1
[]
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
15,683
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'AxCtrls.pas' rev: 6.00 #ifndef AxCtrlsHPP #define AxCtrlsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Menus.hpp> // Pascal unit #include <StdVCL.hpp> // Pascal unit #include <ExtCtrls.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <ComObj.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <ActiveX.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <Variants.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- #include <objsafe.h> #include <ocidl.h> namespace Axctrls { //-- type declarations ------------------------------------------------------- class DELPHICLASS TOleStream; class PASCALIMPLEMENTATION TOleStream : public Classes::TStream { typedef Classes::TStream inherited; private: _di_IStream FStream; protected: _di_IStream __fastcall GetIStream(); public: __fastcall TOleStream(const _di_IStream Stream); virtual int __fastcall Read(void *Buffer, int Count); virtual int __fastcall Write(const void *Buffer, int Count); virtual int __fastcall Seek(int Offset, Word Origin)/* overload */; public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TOleStream(void) { } #pragma option pop /* Hoisted overloads: */ public: inline __int64 __fastcall Seek(const __int64 Offset, Classes::TSeekOrigin Origin){ return TStream::Seek(Offset, Origin); } }; typedef void __fastcall (__closure *TDefinePropertyPage)(const GUID &GUID); __dispinterface IAmbientDispatch; typedef System::DelphiInterface<IAmbientDispatch> _di_IAmbientDispatch; __dispinterface INTERFACE_UUID("{00020400-0000-0000-C000-000000000046}") IAmbientDispatch : public IDispatch { }; class DELPHICLASS TPropertyPage; class DELPHICLASS TPropertyPageImpl; class PASCALIMPLEMENTATION TPropertyPageImpl : public System::TAggregatedObject { typedef System::TAggregatedObject inherited; private: TPropertyPage* FPropertyPage; _di_IPropertyPageSite FPageSite; bool FActive; bool FModified; void __fastcall Modified(void); protected: HRESULT __stdcall SetPageSite(const _di_IPropertyPageSite pageSite); HRESULT __stdcall Activate(HWND hwndParent, const Types::TRect &rc, BOOL bModal); HRESULT __stdcall Deactivate(void); HRESULT __stdcall GetPageInfo(/* out */ tagPROPPAGEINFO &pageInfo); HRESULT __stdcall SetObjects(int cObjects, Activex::PUnknownList pUnkList); HRESULT __stdcall Show(int nCmdShow); HRESULT __stdcall Move(const Types::TRect &rect); HRESULT __stdcall IsPageDirty(void); HRESULT __stdcall Apply(void); HRESULT __stdcall Help(wchar_t * pszHelpDir); HRESULT __stdcall TranslateAccelerator(Windows::PMsg msg); HRESULT __stdcall EditProperty(int dispid); public: virtual void __fastcall InitPropertyPage(void); __property TPropertyPage* PropertyPage = {read=FPropertyPage, write=FPropertyPage}; public: #pragma option push -w-inl /* TAggregatedObject.Create */ inline __fastcall TPropertyPageImpl(const System::_di_IInterface Controller) : System::TAggregatedObject(Controller) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TPropertyPageImpl(void) { } #pragma option pop private: void *__IPropertyPage2; /* IPropertyPage2 */ public: operator IPropertyPage2*(void) { return (IPropertyPage2*)&__IPropertyPage2; } operator IPropertyPage*(void) { return (IPropertyPage*)&__IPropertyPage2; } operator IInterface*(void) { return (IInterface*)&__IPropertyPage2; } }; class PASCALIMPLEMENTATION TPropertyPage : public Forms::TCustomForm { typedef Forms::TCustomForm inherited; private: TPropertyPageImpl* FActiveXPropertyPage; OleVariant FOleObject; Classes::TInterfaceList* FOleObjects; HIDESBASE MESSAGE void __fastcall CMChanged(Controls::TCMChanged &Msg); public: __fastcall virtual TPropertyPage(Classes::TComponent* AOwner); __fastcall virtual ~TPropertyPage(void); void __fastcall Modified(void); virtual void __fastcall UpdateObject(void); virtual void __fastcall UpdatePropertyPage(void); __property OleVariant OleObject = {read=FOleObject}; __property Classes::TInterfaceList* OleObjects = {read=FOleObjects, write=FOleObjects}; void __fastcall EnumCtlProps(const GUID &PropType, Classes::TStrings* PropNames); __published: __property ActiveControl ; __property AutoScroll = {default=1}; __property Caption ; __property ClientHeight ; __property ClientWidth ; __property Ctl3D = {default=1}; __property Color ; __property Enabled = {default=1}; __property Font ; __property Height ; __property HorzScrollBar ; __property OldCreateOrder ; __property KeyPreview = {default=0}; __property PixelsPerInch ; __property ParentFont = {default=0}; __property PopupMenu ; __property PrintScale = {default=1}; __property Scaled = {default=1}; __property ShowHint ; __property VertScrollBar ; __property Visible = {default=0}; __property Width ; __property OnActivate ; __property OnClick ; __property OnClose ; __property OnContextPopup ; __property OnCreate ; __property OnDblClick ; __property OnDestroy ; __property OnDeactivate ; __property OnDragDrop ; __property OnDragOver ; __property OnHide ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnPaint ; __property OnResize ; __property OnShow ; public: #pragma option push -w-inl /* TCustomForm.CreateNew */ inline __fastcall virtual TPropertyPage(Classes::TComponent* AOwner, int Dummy) : Forms::TCustomForm(AOwner, Dummy) { } #pragma option pop public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TPropertyPage(HWND ParentWindow) : Forms::TCustomForm(ParentWindow) { } #pragma option pop }; typedef TMetaClass*TPropertyPageClass; class DELPHICLASS TCustomAdapter; class PASCALIMPLEMENTATION TCustomAdapter : public System::TInterfacedObject { typedef System::TInterfacedObject inherited; private: System::_di_IInterface FOleObject; int FConnection; System::_di_IInterface FNotifier; protected: bool Updating; virtual void __fastcall Changed(void); void __fastcall ConnectOleObject(System::_di_IInterface OleObject); void __fastcall ReleaseOleObject(void); virtual void __fastcall Update(void) = 0 ; public: __fastcall TCustomAdapter(void); __fastcall virtual ~TCustomAdapter(void); }; class DELPHICLASS TAdapterNotifier; class PASCALIMPLEMENTATION TAdapterNotifier : public System::TInterfacedObject { typedef System::TInterfacedObject inherited; private: TCustomAdapter* FAdapter; protected: HRESULT __stdcall OnChanged(int dispid); HRESULT __stdcall OnRequestEdit(int dispid); public: __fastcall TAdapterNotifier(TCustomAdapter* Adapter); public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TAdapterNotifier(void) { } #pragma option pop private: void *__IPropertyNotifySink; /* IPropertyNotifySink */ public: operator IPropertyNotifySink*(void) { return (IPropertyNotifySink*)&__IPropertyNotifySink; } }; __interface IFontAccess; typedef System::DelphiInterface<IFontAccess> _di_IFontAccess; __interface INTERFACE_UUID("{CBA55CA0-0E57-11D0-BD2F-0020AF0E5B81}") IFontAccess : public IInterface { public: virtual void __fastcall GetOleFont(_di_IFontDisp &OleFont) = 0 ; virtual void __fastcall SetOleFont(const _di_IFontDisp OleFont) = 0 ; }; class DELPHICLASS TFontAdapter; class PASCALIMPLEMENTATION TFontAdapter : public TCustomAdapter { typedef TCustomAdapter inherited; private: Graphics::TFont* FFont; protected: void __fastcall GetOleFont(_di_IFontDisp &OleFont); void __fastcall SetOleFont(const _di_IFontDisp OleFont); virtual void __fastcall Changed(void); virtual void __fastcall Update(void); public: __fastcall TFontAdapter(Graphics::TFont* Font); public: #pragma option push -w-inl /* TCustomAdapter.Destroy */ inline __fastcall virtual ~TFontAdapter(void) { } #pragma option pop private: void *__IChangeNotifier; /* Graphics::IChangeNotifier */ void *__IFontAccess; /* Axctrls::IFontAccess */ public: operator IFontAccess*(void) { return (IFontAccess*)&__IFontAccess; } operator IChangeNotifier*(void) { return (IChangeNotifier*)&__IChangeNotifier; } }; __interface IPictureAccess; typedef System::DelphiInterface<IPictureAccess> _di_IPictureAccess; __interface INTERFACE_UUID("{795D4D31-43D7-11D0-9E92-0020AF3D82DA}") IPictureAccess : public IInterface { public: virtual void __fastcall GetOlePicture(_di_IPictureDisp &OlePicture) = 0 ; virtual void __fastcall SetOlePicture(const _di_IPictureDisp OlePicture) = 0 ; }; class DELPHICLASS TPictureAdapter; class PASCALIMPLEMENTATION TPictureAdapter : public TCustomAdapter { typedef TCustomAdapter inherited; private: Graphics::TPicture* FPicture; protected: void __fastcall GetOlePicture(_di_IPictureDisp &OlePicture); void __fastcall SetOlePicture(const _di_IPictureDisp OlePicture); virtual void __fastcall Update(void); public: __fastcall TPictureAdapter(Graphics::TPicture* Picture); public: #pragma option push -w-inl /* TCustomAdapter.Destroy */ inline __fastcall virtual ~TPictureAdapter(void) { } #pragma option pop private: void *__IChangeNotifier; /* Graphics::IChangeNotifier */ void *__IPictureAccess; /* Axctrls::IPictureAccess */ public: operator IPictureAccess*(void) { return (IPictureAccess*)&__IPictureAccess; } operator IChangeNotifier*(void) { return (IChangeNotifier*)&__IChangeNotifier; } }; class DELPHICLASS TOleGraphic; class PASCALIMPLEMENTATION TOleGraphic : public Graphics::TGraphic { typedef Graphics::TGraphic inherited; private: _di_IPicture FPicture; int __fastcall GetMMHeight(void); int __fastcall GetMMWidth(void); protected: virtual void __fastcall Changed(System::TObject* Sender); virtual void __fastcall Draw(Graphics::TCanvas* ACanvas, const Types::TRect &Rect); virtual bool __fastcall GetEmpty(void); virtual int __fastcall GetHeight(void); virtual HPALETTE __fastcall GetPalette(void); virtual bool __fastcall GetTransparent(void); virtual int __fastcall GetWidth(void); virtual void __fastcall SetHeight(int Value); virtual void __fastcall SetPalette(HPALETTE Value); virtual void __fastcall SetWidth(int Value); public: virtual void __fastcall Assign(Classes::TPersistent* Source); virtual void __fastcall LoadFromFile(const AnsiString Filename); virtual void __fastcall LoadFromStream(Classes::TStream* Stream); virtual void __fastcall SaveToStream(Classes::TStream* Stream); virtual void __fastcall LoadFromClipboardFormat(Word AFormat, unsigned AData, HPALETTE APalette); virtual void __fastcall SaveToClipboardFormat(Word &AFormat, unsigned &AData, HPALETTE &APalette); __property int MMHeight = {read=GetMMHeight, nodefault}; __property int MMWidth = {read=GetMMWidth, nodefault}; __property _di_IPicture Picture = {read=FPicture, write=FPicture}; public: #pragma option push -w-inl /* TGraphic.Create */ inline __fastcall virtual TOleGraphic(void) : Graphics::TGraphic() { } #pragma option pop public: #pragma option push -w-inl /* TPersistent.Destroy */ inline __fastcall virtual ~TOleGraphic(void) { } #pragma option pop }; class DELPHICLASS TStringsAdapter; class PASCALIMPLEMENTATION TStringsAdapter : public Comobj::TAutoIntfObject { typedef Comobj::TAutoIntfObject inherited; private: Classes::TStrings* FStrings; protected: void __fastcall ReferenceStrings(Classes::TStrings* S); void __fastcall ReleaseStrings(void); HRESULT __safecall Get_ControlDefault(int Index, OleVariant &Get_ControlDefault_result); HRESULT __safecall Set_ControlDefault(int Index, const OleVariant Value); HRESULT __safecall Count(int &Count_result); HRESULT __safecall Get_Item(int Index, OleVariant &Get_Item_result); HRESULT __safecall Set_Item(int Index, const OleVariant Value); HRESULT __safecall Remove(int Index); HRESULT __safecall Clear(void); HRESULT __safecall Add(const OleVariant Item, int &Add_result); HRESULT __safecall _NewEnum(System::_di_IInterface &_NewEnum_result); public: __fastcall TStringsAdapter(Classes::TStrings* Strings); public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TStringsAdapter(void) { } #pragma option pop private: void *__IStrings; /* Stdvcl::IStrings */ void *__IStringsAdapter; /* Classes::IStringsAdapter */ public: operator IStringsAdapter*(void) { return (IStringsAdapter*)&__IStringsAdapter; } operator IStrings*(void) { return (IStrings*)&__IStrings; } }; class DELPHICLASS TReflectorWindow; class PASCALIMPLEMENTATION TReflectorWindow : public Controls::TWinControl { typedef Controls::TWinControl inherited; private: Controls::TControl* FControl; bool FInSize; MESSAGE void __fastcall WMGetDlgCode(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall WMSetFocus(Messages::TWMSetFocus &Message); HIDESBASE MESSAGE void __fastcall WMSize(Messages::TWMSize &Message); protected: virtual void __fastcall CreateParams(Controls::TCreateParams &Params); public: __fastcall TReflectorWindow(HWND ParentWindow, Controls::TControl* Control); public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TReflectorWindow(HWND ParentWindow) : Controls::TWinControl(ParentWindow) { } #pragma option pop #pragma option push -w-inl /* TWinControl.Destroy */ inline __fastcall virtual ~TReflectorWindow(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE GUID Class_DColorPropPage; extern PACKAGE GUID Class_DFontPropPage; extern PACKAGE GUID Class_DPicturePropPage; extern PACKAGE GUID Class_DStringPropPage; extern PACKAGE HWND __fastcall ParkingWindow(void); extern PACKAGE void __fastcall EnumDispatchProperties(_di_IDispatch Dispatch, const GUID &PropType, int VTCode, Classes::TStrings* PropList); extern PACKAGE void __fastcall GetOleFont(Graphics::TFont* Font, _di_IFontDisp &OleFont); extern PACKAGE void __fastcall SetOleFont(Graphics::TFont* Font, _di_IFontDisp OleFont); extern PACKAGE void __fastcall GetOlePicture(Graphics::TPicture* Picture, _di_IPictureDisp &OlePicture); extern PACKAGE void __fastcall SetOlePicture(Graphics::TPicture* Picture, _di_IPictureDisp OlePicture); extern PACKAGE void __fastcall GetOleStrings(Classes::TStrings* Strings, Stdvcl::_di_IStrings &OleStrings); extern PACKAGE void __fastcall SetOleStrings(Classes::TStrings* Strings, Stdvcl::_di_IStrings OleStrings); } /* namespace Axctrls */ using namespace Axctrls; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // AxCtrls
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 473 ] ] ]
ea2e944e83b45ce6efe1845a6ece21fea545cb39
ac474685ade4f5adab2953c801f1b443727e1fec
/widm/FfrmMain.h
5dd119fae53afaf4e96c1e86386a1235c759725c
[]
no_license
BackupTheBerlios/widm
88377ad54732f456673e891396d8ecc0ccaed6c6
5f66676a39d0d1427d70765247d51496d3d4543c
refs/heads/master
2016-09-10T19:44:41.182944
2005-02-20T19:00:30
2005-02-20T19:00:30
40,045,056
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
h
//--------------------------------------------------------------------------- #ifndef FfrmMainH #define FfrmMainH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Menus.hpp> #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class TfrmMain : public TForm { __published: // IDE-managed Components TMainMenu *mnuMain; TMenuItem *Bestand1; TMenuItem *Nieuwewerkomgeving1; TMenuItem *Opslaanwerkomgeving1; TMenuItem *Sluitenwerkcomgeving1; TMenuItem *N1; TMenuItem *Afsluiten1; TMenuItem *Opslaanals1; TPanel *Panel1; TButton *Button1; TButton *Button2; void __fastcall Button1Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TfrmMain(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TfrmMain *frmMain; //--------------------------------------------------------------------------- #endif
[ "meilof" ]
[ [ [ 1, 35 ] ] ]
1564ccdf85f25ee845a14c1a829697f05be8e195
2f650259e71a0f5c040bac1ab5e4a69980df3ff8
/WwiseUnityProject/WwiseUnity/WwiseUnity_DllExport.cpp
ac079b020ae4105ccf371d25b039587e9ef65d64
[]
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
35
cpp
#include "WwiseUnity_DllExport.h"
[ "[email protected]@4ae3ac6d-c3d7-76ed-586d-0242e581c9de" ]
[ [ [ 1, 1 ] ] ]
92d65c471fdc8469be7cf4168ac0bc207e19302f
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/test/unit/utExport.h
2d43f92ef8e2bc58511da77caf240d7095fd3525
[ "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
817
h
#ifndef INCLUDED_UT_EXPORT_H #define INCLUDED_UT_EXPORT_H #ifndef ASSIMP_BUILD_NO_EXPORT #include <export.h> #include <export.hpp> using namespace Assimp; class ExporterTest : public CPPUNIT_NS :: TestFixture { CPPUNIT_TEST_SUITE (ExporterTest); CPPUNIT_TEST (testExportToFile); CPPUNIT_TEST (testExportToBlob); CPPUNIT_TEST (testCppExportInterface); CPPUNIT_TEST (testCExportInterface); CPPUNIT_TEST_SUITE_END (); public: void setUp (void); void tearDown (void); protected: void testExportToFile (void); void testExportToBlob (void); void testCppExportInterface (void); void testCExportInterface (void); private: const aiScene* pTest; Assimp::Exporter* ex; Assimp::Importer* im; }; #endif #endif
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 41 ] ] ]
024bbf148734c6ef0ef3dde66910fd66741631fa
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/config/test/boost_no_raw_literals.ipp
96cfd2d96bc90e41e82883c92e549b03f403e8cb
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
614
ipp
// (C) Copyright Beman Dawes 2008 // Use, modification and distribution are 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) // See http://www.boost.org/libs/config for more information. // MACRO: BOOST_NO_RAW_LITERALS // TITLE: C++0x raw string literals unavailable // DESCRIPTION: The compiler does not support C++0x raw string literals namespace boost_no_raw_literals { int test() { const char* s = R"[abc]"; const wchar_t* ws = LR"[abc]"; return 0; } }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 22 ] ] ]
483616da191f8c88ca3d5773946a5a5733a22e3f
03b001592deac331cc5f277f6365501f7b3871de
/UVa/network Piva.cpp
4af8c1886addf76913c2ead359df73cc8611d6ce
[]
no_license
raphamontana/usp-raphael
1ba2cb88737ae1730dd6e8c62a5c56f3da4cfe25
5ffff4ae5c60b69c1d0535d4c79c1c7dfa6dbf25
refs/heads/master
2021-01-01T06:38:42.606950
2010-05-11T23:59:08
2010-05-11T23:59:08
32,346,740
0
0
null
null
null
null
ISO-8859-10
C++
false
false
2,134
cpp
/* ========================================================================= */ /* Raphael Montanari nš USP: 5890010 */ /* Network Connections */ /* ========================================================================= */ #include <cstdio> #include <cstring> #include <set> #include <algorithm> using namespace std; int main() { int casos; int nComputadores; int pc[1000]; int no1, no2; int sim, nao; int j, k, sai; int g; scanf("%d", &casos); while (casos--) { sim = nao = sai = 0; scanf("\n%d", &nComputadores); for (j = 1; j <= nComputadores; j++) pc[j] = 0; g = 1; while (!sai) { if (scanf("\nc %d %d", &no1, &no2) == 2) { if (pc[no1] == 0) { if (pc[no2] == 0) { pc[no1] = g; pc[no2] = g; g++; } else pc[no1] = pc[no2]; } else { if (pc[no2] == 0) pc[no2] = pc[no1]; else { k = pc[no1]; for (j = 1; j <= nComputadores; j++) if (k == pc[j]) pc[j] = pc[no2]; } } } else if (scanf("\nq %d %d", &no1, &no2) == 2) if (pc[no1] == pc[no2] && pc[no1] != 0) sim++; else nao++; else sai++; } printf("%d,%d\n", sim, nao); if (casos) printf("\n"); } }
[ "[email protected]@ba5301f2-bfe1-11dd-871e-457e4afae058" ]
[ [ [ 1, 71 ] ] ]
533d9569fbff8596ce2733c97558336aae6bd209
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctesteh/inc/bctestehappUi.h
403b8fd2951c6f5553505f032b88e6202a8f8f24
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Test BC for Template control API. * */ #ifndef C_BCTESTEHAPPUI_H #define C_BCTESTEHAPPUI_H #include <aknviewappui.h> class CBCTestEHView; /** * Application UI class * * @lib bctestutil.lib */ class CBCTestEHAppUi : public CAknViewAppUi { public: // Constructors and destructor /** * ctor */ CBCTestEHAppUi(); /** * symbian 2nd ctor */ void ConstructL(); /** * dtor */ virtual ~CBCTestEHAppUi(); private: /** * From CEikAppUi */ void HandleCommandL( TInt aCommand ); private: // data /** * pointor to the view. * own */ CBCTestEHView* iView; }; #endif // C_BCTESTEHAPPUI_H // End of File
[ "none@none" ]
[ [ [ 1, 68 ] ] ]
1cab68855e01cbdcd2fb48e4691e9f942a98e02d
4dd44d686f1b96f8e6edae3769369a89013f6bc1
/ocass/libocc/cc_wrk.cpp
bd4f5372fac246eac5c4ffdfe69c254d2411b099
[]
no_license
bactq/ocass
e1975533a69adbd1b4d1f9fd1bd88647039fff82
116565ea7c554b11b0a696f185d3a6376e0161dc
refs/heads/master
2021-01-10T14:04:02.179429
2007-07-14T16:03:23
2007-07-14T16:03:23
45,017,357
0
0
null
null
null
null
UTF-8
C++
false
false
4,623
cpp
/* * OCASS - Microsoft Office Communicator Assistant * (http://code.google.com/p/ocass/) * * Copyright (C) 2007 Le Xiongjia * * 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, see <http://www.gnu.org/licenses/>. * * Le Xiongjia ([email protected] [email protected]) * */ #include "ca_types.h" #include "ca_ofc.h" #include "liboch.h" #include "cc_inner.h" static void CC_UpdateState(CCWrk *pCWrk, CCWrkState wrkState) { EnterCriticalSection(&pCWrk->wrkCS); if (wrkState != pCWrk->wrkState) { pCWrk->stateStartTime = time(NULL); pCWrk->wrkState = wrkState; pCWrk->bStateDirty = TRUE; } LeaveCriticalSection(&pCWrk->wrkCS); } static void CC_UpdateSpyWrkState(CCWrk *pCWrk, DWORD dwProcId) { CCWrkState wrkState = CC_WRK_STATE_CORPSE; CASpyRun *pSR = NULL; CAErrno caErr; /* read state from shared mem */ EnterCriticalSection(&pCWrk->wrkCS); if (NULL == pCWrk->pSR) { caErr = CA_SRAttach(&pSR); if (CA_ERR_SUCCESS != caErr) { wrkState = CC_WRK_STATE_CORPSE; goto EXIT; } wrkState = CC_WRK_STATE_WORKING; pCWrk->pSR = pSR; goto EXIT; } wrkState = CC_WRK_STATE_WORKING; EXIT: LeaveCriticalSection(&pCWrk->wrkCS); CC_UpdateState(pCWrk, wrkState); } static BOOL CH_PInjectCancelCb(void *pCbCtx) { CCWrk *pCWrk = (CCWrk *)pCbCtx; if (NULL == pCWrk) { return FALSE; } return (pCWrk->bStopWrkTh ? TRUE : FALSE); } static void CC_DoInject(CCWrk *pCWrk, DWORD dwProcId) { CAErrno caErr; CC_UpdateState(pCWrk, CC_WRK_STATE_INJECTING); caErr = CH_PInject(dwProcId, pCWrk, CH_PInjectCancelCb); if (CA_ERR_SUCCESS == caErr) { CC_UpdateState(pCWrk, CC_WRK_STATE_INJECTED); } else { CC_UpdateState(pCWrk, CC_WRK_STATE_INJECT_FAILED); } } static void CC_DoWrk(CCWrk *pCWrk, CCWrkMod wrkMod) { CAErrno caErr; DWORD dwOFCProcId; BOOL bResult; if (!(CC_WRK_MOD_DETECT & wrkMod)) { return; } caErr = CA_OFCGetRunProcId(&dwOFCProcId); if (CA_ERR_SUCCESS != caErr) { /* not running */ CC_UpdateState(pCWrk, CC_WRK_STATE_NOT_RUNNING); return; } bResult = CA_OFCProcIsAttached(dwOFCProcId); if (!bResult) { if (CC_WRK_MOD_INJECT & wrkMod) { CC_DoInject(pCWrk, dwOFCProcId); } else { CC_UpdateState(pCWrk, CC_WRK_STATE_NOT_INJECTED); } return; } CC_UpdateSpyWrkState(pCWrk, dwOFCProcId); } DWORD WINAPI CC_WrkThread(void *pThArg) { CCWrkMod wrkMod; CCWrk *pCWrk = (CCWrk *)pThArg; DWORD dwThExit = CA_THREAD_EXIT_OK; DWORD dwWait; DWORD dwWrkCycle = 1000 * 3; for (;;) { if (pCWrk->bStopWrkTh) { break; } dwWait = WaitForSingleObject(pCWrk->hWrkEvt, dwWrkCycle); if (pCWrk->bStopWrkTh) { break; } if (WAIT_FAILED == dwWait) { Sleep(1000); } CC_GetWrkMod(pCWrk, &wrkMod); if (CC_WRK_MOD_PAUSE & wrkMod) { continue; } CC_DoWrk(pCWrk, wrkMod); } return dwThExit; } CA_DECLARE(const TCHAR*) CC_StateDesc(CCWrkState wrkState) { switch (wrkState) { case CC_WRK_STATE_IDLE: case CC_WRK_STATE_NOT_RUNNING: case CC_WRK_STATE_NOT_INJECTED: return TEXT("Prepare Inject"); case CC_WRK_STATE_INJECTING: return TEXT("Injecting"); case CC_WRK_STATE_WORKING: case CC_WRK_STATE_INJECTED: return TEXT("Injected"); case CC_WRK_STATE_CORPSE: case CC_WRK_STATE_INJECT_FAILED: return TEXT("Injection failed"); default: return TEXT("Unknown"); } }
[ "lexiongjia@4b591cd5-a833-0410-8603-c1928dc92378" ]
[ [ [ 1, 194 ] ] ]
9e3ca9b6b95084e8dd2874c2620ab7998d4e738d
282057a05d0cbf9a0fe87457229f966a2ecd3550
/EIBRelay/include/RelayHandler.h
db292f9792a47bde867c37ac148e387dd18ff7af
[]
no_license
radtek/eibsuite
0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd
4504fcf4fa8c7df529177b3460d469b5770abf7a
refs/heads/master
2021-05-29T08:34:08.764000
2011-12-06T20:42:06
2011-12-06T20:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,628
h
#ifndef __RELAY_HANDLER_HEADER__ #define __RELAY_HANDLER_HEADER__ #include "RelayServerConfig.h" #include "JTC.h" #include "GenericServer.h" #include "Socket.h" #define MAX_CONNS 10 class CRelayInputHandler; class CRelayDataInputHandler; class CRelayOutputHandler; // This class is responsible to maintain a single KNX/IP connection with remote client class CRelayHandler : public CGenericServer, public JTCMonitor { public: CRelayHandler(); virtual ~CRelayHandler(); virtual void Start(); void Init(CRelayServerConfig* server_conf, CLogFile* log_file); void Close(); bool Connect(); const CString& GetLocalCtrlAddr() const { return _input_handler->GetLocalCtrlAddr(); } int GetLocalCtrlPort() const { return _input_handler->GetLocalCtrlPort(); } private: typedef struct { bool is_connected; unsigned char id; unsigned char channelid; unsigned char recv_sequence; unsigned char send_sequence; CString _remote_ctrl_addr; int _remote_ctrl_port; CString _remote_data_addr; int _remote_data_port; JTCMonitor state_monitor; CTime _timeout; }ConnectionState; private: void InitState(ConnectionState* s); void OnClientConnectionClose(); public: class CRelayInputHandler : public JTCThread { public: CRelayInputHandler(); virtual ~CRelayInputHandler(); virtual void run(); void Close(); void Init(); int GetLocalCtrlPort() const { return _local_port; } const CString& GetLocalCtrlAddr() const { return _local_addr; } void SetParent(CRelayHandler* relay) { _relay = relay; } void SendTunnelToClient(const CCemi_L_Data_Frame& frame, ConnectionState* s); private: void HandleDisconnectRequest(unsigned char* buffer, int max_len); void HandleSearchRequest(unsigned char* buffer, int max_len); void HandleConnectRequest(unsigned char* buffer, int max_len); void HandleConnectionStateRequest(unsigned char* buffer, int max_len); void HandleTunnelRequest(unsigned char* buffer, int max_len); void HandleDisconnectResponse(unsigned char* buffer, int max_len); void HandleTunnelAck(unsigned char* buffer, int max_len); void HandleDescriptionRequest(unsigned char* buffer, int max_len); private: CRelayHandler* _relay; bool _stop; UDPSocket _sock; CString _local_addr; //used for Control + Data channels int _local_port; //used for Control + Data channels }; //This handler will be response of receiving data from the EIBServer and writing //out this data to the connected client class CRelayOutputHandler : public JTCThread { public: CRelayOutputHandler(); virtual ~CRelayOutputHandler(); virtual void run(); void Close(); void SetParent(CRelayHandler* relay) { _relay = relay; } private: CRelayHandler* _relay; bool _stop; }; typedef JTCHandleT<CRelayHandler::CRelayInputHandler> CRelayInputHandlerHandle; typedef JTCHandleT<CRelayHandler::CRelayOutputHandler> CRelayOutputHandlerHandle; private: void SendTunnelToClient(const CCemi_L_Data_Frame& frame, ConnectionState* s) { _input_handler->SendTunnelToClient(frame, s); } public: void Broadcast(const CCemi_L_Data_Frame& frame); ConnectionState* GetState(int channel); ConnectionState* AllocateNewState(const CString& source_ip, int sourc_port); void FreeConnection(ConnectionState* s); void CheckConnectionsCleanup(); private: CRelayServerConfig* _server_conf; CLogFile* _log_file; CRelayInputHandlerHandle _input_handler; CRelayOutputHandlerHandle _data_output_handler; ConnectionState* _states[MAX_CONNS]; }; #endif
[ [ [ 1, 121 ] ] ]
520918da53ab0e38c803f27e4bf1d065f3a0fec2
46885801c2459416e82517f93b7d452d78b33aff
/source/win32main.cpp
ad83f424ad6bd3d760b46fe8973dbf213f7db372
[]
no_license
libercv/smallengine
aabe92d4743789e8eab4a65d86d5a838ddc2aded
c1645fb99db213b419a81d4815a6645e1be89fe9
refs/heads/master
2021-01-10T08:09:05.991405
2009-04-01T14:52:59
2009-04-01T14:52:59
36,439,082
0
0
null
null
null
null
UTF-8
C++
false
false
267
cpp
#include "win32main.h" int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // PENDIENTE: implementar un Init() Small::Engine::Instance().Run(); // PENDIENTE: implementar un Destroy() }
[ "daviddq@3342a6a6-5e2d-0410-95e1-bf50fdd259a6" ]
[ [ [ 1, 12 ] ] ]
8b7a75fa7c066de0f86f73808dbc41166748e990
7b582dab2e88912f8b47f8513b10674b0907b988
/Native/MulticastProxyActiveX/stdafx.h
de004574d620a919ee486403dc56facd8f28e27d
[ "MS-PL" ]
permissive
mdavid/ProjectStarlight-CodePlex-clone
26ad6e820f681e272e353536c791a6e70da0a4e3
afdbc25aa0df521be85a63ff26ed693aaf98fa6b
refs/heads/master
2020-05-21T13:00:41.707375
2010-08-13T04:09:31
2010-08-13T04:09:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,538
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef STRICT #define STRICT #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows XP or later. #define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. #define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. #endif #define _ATL_APARTMENT_THREADED #define _ATL_NO_AUTOMATIC_NAMESPACE #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlcom.h> #include <atlwin.h> #include <atltypes.h> #include <atlctl.h> #include <atlhost.h> #include <Wininet.h> using namespace ATL;
[ "SND\\mpoindexter_cp@ffd33b8c-2492-42e0-bdc5-587b920b7d6d" ]
[ [ [ 1, 44 ] ] ]
dd2ff2f1538ff47abc22ec4bd73159bcf7df2afe
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
/include/idData.h
ce891ab4efd939f8a38ffaf7cacb568dc89348b4
[]
no_license
ipodyaco/prorata
bd52105499c3fad25781d91952def89a9079b864
1f17015d304f204bd5f72b92d711a02490527fe6
refs/heads/master
2021-01-10T09:48:25.454887
2010-05-11T19:19:40
2010-05-11T19:19:40
48,766,766
0
0
null
null
null
null
UTF-8
C++
false
false
3,171
h
#ifndef IDDATA_H #define IDDATA_H #include <string> #include <iostream> #include <algorithm> #include <sstream> #include <vector> #include <list> #include "chromatogram.h" #include "dtaSelectReader.h" #include "msData.h" using namespace std; // forward declaration class DTASelectReader; /* * a function object, which is passed to the generic algorithm sort() to sort * a vector of Identification pointers. the Identification pointers are sorted by * their first MSMS scan number */ class lessID { public: // overload the operator () // return true if the MSMS scan number of ID1 is less then that of ID2. // return false, otherwise. bool operator() ( const Identification * pID1, const Identification * pID2 ) const { unsigned long int iMSMSscanID1 = pID1->vMS2Scoring[pID1->iFirstMS2].iMSMSscan; unsigned long int iMSMSscanID2 = pID2->vMS2Scoring[pID2->iFirstMS2].iMSMSscan; if( iMSMSscanID1 < iMSMSscanID2 ) return true; else return false; } }; /* * a class for holding all Identification data in a list * it should be used by calling functions in the following steps * 1) setFilename(): populate the list with DTASelectReader or other ID readers * 2) setRetentionTime(): set the retention time for each MSMS scan * 3) consolidateIDlist(): consolidate the list by removing redundance identification and merging adjacent MS2 scans * 4) getIDvector(): retrieve a subset of the list in the sorted order */ class IDdata { public: IDdata(); /* * free memory */ ~IDdata(); /* * set the filename for a MS/MS identification results * and select appropriet ID reader to populate the Identification list */ bool setFilename( string sFilename ); /* * consolidate the identification list by merging identifications for * the same peptide at the same charge state identified at about the same time from the same MS file * the merged Identifications most likely come from the different isotopologues of the same peptide */ void consolidateIDlist( MSdata * pMSdata ); /* * get a vector of identifications from a mzXML/mzData file * the identification is sorted by their first MS/MS scan number */ bool getIDvector( string sBaseFilename, vector< Identification * > & vpIDvector ); /* * debug function * print out all Identification to a temp file logTemp.txt */ void showMeAll(); private: // a list containing all ID instances's pointer list< Identification * > lpIDlist; // set the iFirstMS2 and iLastMS2 for an Identification void setFirstAndLastMS2( Identification * pID ); // is this ID's filename matching the BaseFile name? bool isFilenameMatched( string sBaseFilename, const Identification * pID ); // are the two Identifications from the same mzXML file and close in their retention time? bool isMS2Adjacent( Identification * pID0, Identification * pID1); // merge the two IDs void mergeID( Identification * pID0, Identification * pID1 ); void setRetentionTime( MSdata *pMSdata ); }; #endif //IDDATA_H
[ "chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a" ]
[ [ [ 1, 104 ] ] ]
7d6d1c99a04475a088ee1ba8fbdd0db976fa1d82
e52b0e0e87fbeb76edd0f11a7e1b03d25027932e
/src/System.cpp
bc1459ce00e323f98266bb381f9fdec737512d05
[]
no_license
zerotri/Maxwell_Game_old
d9aaa4c38ee1b99fe9ddb6f777737229dc6eebeb
da7a02ff25697777efe285973e5cecba14154b6c
refs/heads/master
2021-01-25T05:22:45.278629
2008-02-07T03:11:01
2008-02-07T03:11:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,438
cpp
#include "System.h" #include <stdarg.h> #include <stdio.h> bool SysCallBack::_FrameFunc(){return false;}; bool SysCallBack::_Render(){return false;}; System* LogSys = 0; System::System() { _logFile = fopen( "mgame.log", "w" ); LogSys = this; } System::~System() { fclose(_logFile); } int System::Init() { nFPS=0; return true; } void System::Run() { bOverloadedFuncs = api->Sys_OverloadFuncs(); if(!_private_FrameFunc) { Log("System::Run: No frame function defined"); return; } if(bOverloadedFuncs) { api->Sys_Run(); return; } bActive=true; float fTime=0.0f; float t0fps, cfps; float t0=t0fps=api->Sys_GetTicks(); float dt=cfps=0; float fDeltaTime; float nFixedDelta; int nLastTime=api->Sys_GetTicks(); // MAIN LOOP Log("System::Run()! Running Main Loop"); for(;;) { // If HGE window is focused or we have the "don't suspend" state - process the main loop if(bActive) { // Ensure we have at least 1ms time step // to not confuse user's code with 0 do { dt=api->Sys_GetTicks() - t0; } while(dt < 1); // If we reached the time for the next frame // or we just run in unlimited FPS mode, then // do the stuff frameTime = (float)(api->Sys_GetTicks() - nLastTime)/1000.0f; nLastTime = api->Sys_GetTicks(); //Log("System::Run()! Checking nFixedDelta, %i", SDL_GetTicks()); //if(dt >= nFixedDelta) { //Log("System::Run()! About to run frame"); // fDeltaTime = time step in seconds returned by Timer_GetDelta fDeltaTime=dt/1000.0f; // Cap too large time steps usually caused by lost focus to avoid jerks if(fDeltaTime > 0.2f) { fDeltaTime = nFixedDelta ? nFixedDelta/1000.0f : 0.01f; } // Update time counter returned Timer_GetTime fTime += fDeltaTime; // Store current time for the next frame // and count FPS t0=api->Sys_GetTicks(); if(t0-t0fps <= 1000.0f) cfps++; else { nFPS=(int)cfps; cfps=0; t0fps=t0; Log("FPS: %i", nFPS); } // Do user's stuff if(!_private_FrameFunc->_FrameFunc()) break; // If we use VSYNC - we could afford a little // sleep to lower CPU usage // if(!bWindowed && nHGEFPS==HGEFPS_VSYNC) Sleep(1); } // If we have a fixed frame rate and the time // for the next frame isn't too close, sleep a bit /*else { if(nFixedDelta && dt+3 < nFixedDelta) Sleep(1); }*/ } // If main loop is suspended - just sleep a bit // (though not too much to allow instant window // redraw if requested by OS) else Sleep(1); } bActive=false; End(); return; } int System::FPS() { return nFPS; } time_type System::getFrameTime() { if(bOverloadedFuncs) { return api->Sys_GetDelta(); }else return (time_type)(frameTime*1000.0f); } void System::End() { Log("Shutting Down..."); } void System::SetFrameFunc(SysCallBack* frameFunc) { _private_FrameFunc = frameFunc; } void System::Sleep(int count) { api->Sys_Sleep(count); } void System::SetAPI(API_Base* _api) { api = _api; } void System::Log(char* format,...) { char _strbuf[256]; ///create va_list and load all arguments va_list ap; va_start(ap, format); vsprintf(_strbuf,format, ap); /// Call vprintf va_end(ap); /// Cleanup the va_list fprintf(_logFile,"%s\n",_strbuf); fflush(_logFile); }
[ [ [ 1, 161 ] ] ]
551643268e4f3c8df6c9863b1b7e1141babe435e
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/component/jscontactcallbackcomponent.cpp
7650c0db3dfc21bd17c5d1e1c9544387b2288636
[]
no_license
tstivers/eXistenZ
eb2da9d6d58926b99495319080e13f780862fca0
2f5df51fb71d44c3e2689929c9249d10223f8d56
refs/heads/master
2021-09-02T22:50:36.733142
2010-11-16T06:47:24
2018-01-04T00:51:21
116,196,014
0
0
null
null
null
null
UTF-8
C++
false
false
3,736
cpp
#include "precompiled.h" #include "component/jscontactcallbackcomponent.h" #include "component/jscomponent.h" #include "entity/jsentity.h" #include "script/jsfunction.h" using namespace jscomponent; using namespace component; using namespace script; namespace jsscript { inline jsval to_jsval(JSContext* cx, function<void(Component*, const ContactCallbackEventArgs&)> callback) { // TODO: figure out how to handle this return JSVAL_NULL; } inline bool jsval_to_(JSContext* cx, jsval v, function<void(Component*, const ContactCallbackEventArgs&)>* out) { if(!JSVAL_IS_OBJECT(v) || !JS_ObjectIsFunction(cx, JSVAL_TO_OBJECT(v))) { JS_ReportError(cx, "action must be a function"); return false; } shared_ptr<jsscript::jsfunction<void(Component*, const ContactCallbackEventArgs&)>> call(new jsscript::jsfunction<void(Component*, const ContactCallbackEventArgs&)>(cx, NULL, v)); *out = bind(&jsscript::jsfunction<void(Component*, const ContactCallbackEventArgs&)>::operator(), call, _1, _2); return true; } inline jsval to_jsval(JSContext* cx, component::Component* object) { return object ? OBJECT_TO_JSVAL(object->getScriptObject()) : JSVAL_NULL; } inline jsval to_jsval(JSContext* cx, weak_reference<component::Component> object) { return object ? OBJECT_TO_JSVAL(object->getScriptObject()) : JSVAL_NULL; } inline jsval to_jsval(JSContext* cx, const component::ContactCallbackEventArgs& object) { JS_EnterLocalRootScope(cx); JSObject* args = JS_NewObject(cx, NULL, NULL, NULL); jsval otherComponent = to_jsval(cx, object.otherComponent); jsval contactForce = to_jsval(cx, object.contactForce); JS_SetProperty(cx, args, "otherComponent", &otherComponent); JS_SetProperty(cx, args, "contactForce", &contactForce); JS_LeaveLocalRootScopeWithResult(cx, OBJECT_TO_JSVAL(args)); return OBJECT_TO_JSVAL(args); } } namespace jscomponent { static bool parseDesc(JSContext* cx, JSObject* obj, ContactCallbackComponent::desc_type& desc); // method declarations // static JSBool classMethod(JSContext *cx, uintN argc, jsval *vp); // property declarations // static JSBool propGetter(JSContext *cx, JSObject *obj, jsval id, jsval *vp); static JSClass class_ops = { "ContactCallbackComponent", JSCLASS_HAS_RESERVED_SLOTS(1), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; static JSPropertySpec class_properties[] = { // {"name", id, flags, getter, setter}, {"onContact", 4, JSPROP_PERMANENT | JSPROP_ENUMERATE | JSPROP_SHARED, PropertyGetter<ContactCallbackComponent, function<void(Component*, const ContactCallbackEventArgs&)>, &ContactCallbackComponent::getCallback>, PropertySetter<ContactCallbackComponent, function<void(Component*, const ContactCallbackEventArgs&)>, &ContactCallbackComponent::setCallback>}, JS_PS_END }; static JSFunctionSpec class_methods[] = { // JS_FN("name", function, nargs, flags, minargs), JS_FS_END }; } ScriptedObject::ScriptClass ContactCallbackComponent::m_scriptClass = { &class_ops, class_properties, class_methods, NULL }; REGISTER_SCRIPT_INIT(ContactCallbackComponent, initClass, 20); static void initClass(ScriptEngine* engine) { RegisterScriptClass<ContactCallbackComponent, Component>(engine); jsentity::RegisterCreateFunction(engine, "createContactCallbackComponent", createComponent<ContactCallbackComponent>); } bool jscomponent::parseDesc(JSContext* cx, JSObject* obj, ContactCallbackComponent::desc_type& desc) { GetProperty(cx, obj, "callback", desc.callback); return true; }
[ [ [ 1, 112 ] ] ]
bcef4ac8261be8eac45446271afa446ae783995f
279b68f31b11224c18bfe7a0c8b8086f84c6afba
/playground/barfan/findik-poc-4/response_parser.cpp
04a0342f74904a64d90a57810c77e143d9bf6716
[]
no_license
bogus/findik
83b7b44b36b42db68c2b536361541ee6175bb791
2258b3b3cc58711375fe05221588d5a068da5ea8
refs/heads/master
2020-12-24T13:36:19.550337
2009-08-16T21:46:57
2009-08-16T21:46:57
32,120,100
0
0
null
null
null
null
UTF-8
C++
false
false
8,298
cpp
#include <string> #include <boost/lexical_cast.hpp> #include "response_parser.hpp" #include "response.hpp" #include "parser_util.hpp" #include <iostream> namespace findik { namespace io { response_parser::response_parser() : state_(http_version_start), status_code_(""), chunked_line_length_(0), chunked_line_length_str_("") { } void response_parser::reset() { state_ = http_version_start; status_code_ = ""; chunked_line_length_ = 0; chunked_line_length_str_ = ""; } boost::tribool response_parser::consume(response& resp, char input) { switch (state_) { case http_version_start: if (input == 'H') { state_ = http_version_t_1; return boost::indeterminate; } else return false; case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return boost::indeterminate; } else { return false; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return boost::indeterminate; } else { return false; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return boost::indeterminate; } else { return false; } case http_version_slash: if (input == '/') { resp.http_version_major = 0; resp.http_version_minor = 0; state_ = http_version_major_start; return boost::indeterminate; } else { return false; } case http_version_major_start: if (is_digit(input)) { resp.http_version_major = resp.http_version_major * 10 + input - '0'; state_ = http_version_major; return boost::indeterminate; } else { return false; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return boost::indeterminate; } else if (is_digit(input)) { resp.http_version_major = resp.http_version_major * 10 + input - '0'; return boost::indeterminate; } else { return false; } case http_version_minor_start: if (is_digit(input)) { resp.http_version_minor = resp.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return boost::indeterminate; } else { return false; } case http_version_minor: if (input == ' ') { state_ = status_code_start; return boost::indeterminate; } else if (is_digit(input)) { resp.http_version_minor = resp.http_version_minor * 10 + input - '0'; return boost::indeterminate; } else { return false; } case status_code_start: if (is_digit(input)) { state_ = status_code; status_code_.push_back(input); return boost::indeterminate; } else return false; case status_code: if (input == ' ') { resp.status_code = (response::status_type) boost::lexical_cast< unsigned int >(status_code_); status_code_ = ""; state_ = status_line_start; return boost::indeterminate; } else if (is_digit(input)){ status_code_.push_back(input); return boost::indeterminate; } else return false; case status_line_start: if (isalpha(input)) { state_ = status_line; resp.status_line.push_back(input); return boost::indeterminate; } else return false; case status_line: if (isalpha(input) || input == ' ') { resp.status_line.push_back(input); return boost::indeterminate; } else if (input == '\r') { state_ = expecting_newline_1; return boost::indeterminate; } else return false; case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return boost::indeterminate; } else { return false; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return boost::indeterminate; } else if (!resp.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return boost::indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return false; } else { resp.headers.push_back(header()); resp.headers.back().name.push_back(input); state_ = header_name; return boost::indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return boost::indeterminate; } else if (input == ' ' || input == '\t') { return boost::indeterminate; } else if (is_ctl(input)) { return false; } else { state_ = header_value; resp.headers.back().value.push_back(input); return boost::indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return boost::indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return false; } else { resp.headers.back().name.push_back(input); return boost::indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return boost::indeterminate; } else { return false; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return boost::indeterminate; } else if (is_ctl(input)) { return false; } else { resp.headers.back().value.push_back(input); return boost::indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return boost::indeterminate; } else { return false; } case expecting_newline_3: if (input != '\n') return false; if (resp.is_chunked()) { state_ = chunked_size_start; return boost::indeterminate; } else if (resp.has_content()) { if (resp.content_length() == 0) return true; state_ = content; return boost::indeterminate; } else return true; case content: resp.push_to_content(input); if (resp.content_raw().size() < resp.content_length()) return boost::indeterminate; else return true; case chunked_size_start: if (is_hex(input)) { state_ = chunked_size; chunked_line_length_str_.push_back(input); resp.push_to_content(input); return boost::indeterminate; } else return false; case chunked_size: if (is_hex(input)) { chunked_line_length_str_.push_back(input); resp.push_to_content(input); return boost::indeterminate; } else if (input == 32) // some implementations use paddings (0x20) between CRLF and size { resp.push_to_content(input); return boost::indeterminate; } else if (input == '\r') { resp.push_to_content(input); chunked_line_length_ = hex2int(chunked_line_length_str_); chunked_line_length_str_ = ""; state_ = chunked_newline_1; return boost::indeterminate; } else return false; case chunked_newline_1: if (input == '\n') { resp.push_to_content(input); if (chunked_line_length_ == 0) return true; state_ = chunked_line; return boost::indeterminate; } else return false; case chunked_line: resp.push_to_content(input); chunked_line_length_--; if (chunked_line_length_ == 0) { state_ = chunked_newline_2; } return boost::indeterminate; case chunked_newline_2: if (input == '\r') { resp.push_to_content(input); state_ = chunked_newline_3; return boost::indeterminate; } else return false; case chunked_newline_3: if (input == '\n') { resp.push_to_content(input); state_ = chunked_size_start; return boost::indeterminate; } else return false; default: return false; } } } // namespace server3 } // namespace http
[ "barfan@d40773b4-ada0-11de-b0a2-13e92fe56a31" ]
[ [ [ 1, 380 ] ] ]
ef2ce9be65a0d0e70f56a30fb30895a3af4f8e80
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nopengl/src/opengl/nglmesh_main.cc
dbebb3cf2dce57c8c33bd37bf716f07bd8b5de40
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
17,893
cc
//------------------------------------------------------------------------------ // nglmesh_main.cc // (c) 2004-2006 Oleg Khryptul (Haron) //------------------------------------------------------------------------------ #include "opengl/nglmesh.h" #include "opengl/nglserver2.h" #include "opengl/ngltexture.h" #include "opengl/nglextensionserver.h" nNebulaClass(nGLMesh, "nmesh2"); const ushort nGLMesh::componentSize[] = {3,3,2,2,2,2,4,3,3,4,4}; //------------------------------------------------------------------------------ /** */ inline int firstSetBitPos(uint n) { int i, res; res = -1; // there is no setted bits for(i = 0; i < 32; i++) { if (n & (1 << i)) { res = i; break; } } return res; } //------------------------------------------------------------------------------ /** */ nGLMesh::nGLMesh() : VBMapFlag(false), IBMapFlag(false), vertexBuffer(0), indexBuffer(0), privVertexBuffer(0), privIndexBuffer(0), texCoordNum(0), texCoordFirst(Uv0) { this->componentOffset = n_new_array(ushort, firstSetBitPos(nMesh2::AllComponents + 1)); } //------------------------------------------------------------------------------ /** */ nGLMesh::~nGLMesh() { if (this->IsLoaded()) { this->Unload(); } n_delete_array(this->componentOffset); } //------------------------------------------------------------------------------ /** nGLMesh support asynchronous resource loading. */ bool nGLMesh::CanLoadAsync() const { return true; } //------------------------------------------------------------------------------ /** This method is either called directly from the nResource::Load() method (in synchronous mode), or from the loader thread (in asynchronous mode). The method must try to validate its resources, set the valid and pending flags, and return a success code. This method may be called from a thread. */ bool nGLMesh::LoadResource() { n_assert(!this->IsLoaded()); n_assert(0 == this->vertexBuffer); n_assert(0 == this->indexBuffer); bool success = nMesh2::LoadResource(); if (success) { // create the vertex declaration from the vertex component mask this->CreateVertexDeclaration(); } return success; } //------------------------------------------------------------------------------ /** Unload the gl resources. Make sure that the resource are properly disconnected from the graphics server. This method is called from nResource::Unload() which serves as a wrapper for synchronous and asynchronous mode. This method will NEVER be called from a thread though. */ void nGLMesh::UnloadResource() { n_assert(this->IsLoaded()); nMesh2::UnloadResource(); //TODO: whats with buffers that got invalid during mapping? // release the resources if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { if (this->vertexBuffer) { glDeleteBuffersARB(1,&this->vertexBuffer); this->vertexBuffer = 0; } if (this->indexBuffer) { glDeleteBuffersARB(1,&this->indexBuffer); this->indexBuffer = 0; } n_gltrace("nGLMesh::UnloadResource()."); } // release private buffers (if this is a ReadOnly mesh) if (this->privVertexBuffer) { n_free(this->privVertexBuffer); this->privVertexBuffer = 0; } if (this->privIndexBuffer) { n_free(this->privIndexBuffer); this->privIndexBuffer = 0; } this->SetState(Unloaded); } //------------------------------------------------------------------------------ /** This method is called when the gl device is lost. We only need to react if our vertex and index buffers are not in GL's managed pool. In this case, we need to unload ourselves... */ void nGLMesh::OnLost() { if (WriteOnly & this->vertexUsage) { this->UnloadResource(); this->SetState(Lost); } } //------------------------------------------------------------------------------ /** This method is called when the gl device has been restored. If our buffers are in the GL's default pool, we need to restore ourselves as well, and we need to set our state to empty, because the buffers contain no data. */ void nGLMesh::OnRestored() { if (WriteOnly & this->vertexUsage) { this->SetState(Unloaded); this->LoadResource(); this->SetState(Empty); } } //------------------------------------------------------------------------------ /** Create a gl vertex buffer. */ void nGLMesh::CreateVertexBuffer() { n_assert(this->vertexBufferByteSize > 0); n_assert(0 == this->privVertexBuffer); n_assert(0 == this->vertexBuffer); if ((ReadOnly & this->vertexUsage) || !N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { // this is a read-only mesh which will never be rendered // and only read-accessed by the CPU, allocate private // vertex buffer this->privVertexBuffer = n_malloc(this->vertexBufferByteSize); n_assert(this->privVertexBuffer); this->vertexPtr = this->privVertexBuffer; } else { glGenBuffersARB(1, &(this->vertexBuffer)); //n_printf("nGLMesh::CreateVertexBuffer(): buffer:%i.\n",this->vertexBuffer); //bind the buffer, so that all following commands aply on this buffer glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vertexBuffer); //select usage type GLenum bufferUsage = GL_STATIC_DRAW_ARB; //default if (WriteOnly & this->vertexUsage) { bufferUsage = GL_DYNAMIC_DRAW_ARB; } // create the vertex buffer glBufferDataARB(GL_ARRAY_BUFFER_ARB, this->vertexBufferByteSize, NULL, bufferUsage); int glVBufSize; glGetBufferParameterivARB(GL_ARRAY_BUFFER_ARB, GL_BUFFER_SIZE_ARB, &glVBufSize); n_assert(glVBufSize == this->vertexBufferByteSize); glBindBufferARB(GL_ARRAY_BUFFER_ARB, NULL); this->vertexPtr = 0; } n_gltrace("nGLMesh::CreateVertexBuffer()."); } //------------------------------------------------------------------------------ /** Create a index buffer. */ void nGLMesh::CreateIndexBuffer() { n_assert(this->indexBufferByteSize > 0); n_assert(0 == this->indexBuffer); n_assert(0 == this->privIndexBuffer); if ((ReadOnly & this->indexUsage) || !N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { n_printf("nGLMesh::CreateIndexBuffer: NO vbo_support.\n"); // this is a read-only mesh which will never be rendered // and only read-accessed by the CPU, allocate private // index buffer this->privIndexBuffer = n_malloc(this->indexBufferByteSize); n_assert(this->privIndexBuffer); this->indexPtr = this->privIndexBuffer; } else { //create indexBuffer glGenBuffersARB(1, &(this->indexBuffer)); //n_printf("nGLMesh::CreateIndexBuffer(): buffer:%i.\n",this->indexBuffer); //bind the buffer, so that all following commands aply on this buffer glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->indexBuffer); //select usage type GLenum bufferUsage = GL_STATIC_DRAW_ARB; //default if (WriteOnly == this->indexUsage) { bufferUsage = GL_DYNAMIC_DRAW_ARB; } // create the index buffer glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->indexBufferByteSize, NULL, bufferUsage); int glIBufSize; glGetBufferParameterivARB(GL_ELEMENT_ARRAY_BUFFER_ARB, GL_BUFFER_SIZE_ARB, &glIBufSize); n_assert(glIBufSize == this->indexBufferByteSize); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, NULL); this->indexPtr = 0; } n_gltrace("nGLMesh::CreateIndexBuffer()."); } //------------------------------------------------------------------------------ /** calculate vertex element offsets for loaded mesh */ void nGLMesh::CreateVertexDeclaration() { //n_printf("componentOffset[ "); int i, s = 0; for (i = 0; i < firstSetBitPos(nMesh2::AllComponents + 1); i++) if (this->vertexComponentMask & (1 << i)) { componentOffset[i] = s; //n_printf("(%d):%d,%d ", i, s, componentSize[i]); s += componentSize[i]; } //n_printf("]\n"); if (this->vertexComponentMask & Uv3){texCoordNum=1; texCoordFirst = Uv3;} if (this->vertexComponentMask & Uv2){texCoordNum++; texCoordFirst = Uv2;} if (this->vertexComponentMask & Uv1){texCoordNum++; texCoordFirst = Uv1;} if (this->vertexComponentMask & Uv0){texCoordNum++; texCoordFirst = Uv0;} } //------------------------------------------------------------------------------ /** Lock the gl vertex buffer and return pointer to it. */ float* nGLMesh::LockVertices() { this->LockMutex(); n_assert((this->vertexBuffer || this->privVertexBuffer) && !this->VBMapFlag); float* retval = 0; this->VBMapFlag = true; if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vertexBuffer); void* ptr = glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB); n_gltrace("nGLMesh::LockVertices()."); n_assert(ptr); retval = (float*) ptr; } else { retval = (float*) this->privVertexBuffer; } this->UnlockMutex(); return retval; } //------------------------------------------------------------------------------ /** Unlock the gl vertex buffer locked by nGLMesh::LockVertices(). */ void nGLMesh::UnlockVertices() { this->LockMutex(); n_assert((this->vertexBuffer || this->privVertexBuffer) && this->VBMapFlag); this->VBMapFlag = false; if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glUnmapBufferARB(GL_ARRAY_BUFFER_ARB); glBindBufferARB(GL_ARRAY_BUFFER_ARB, NULL); n_gltrace("nGLMesh::UnlockVertices()."); } this->UnlockMutex(); } //------------------------------------------------------------------------------ /** Lock the gl index buffer and return pointer to it. */ ushort* nGLMesh::LockIndices() { this->LockMutex(); n_assert((this->indexBuffer || this->privIndexBuffer) && !this->IBMapFlag); ushort* retval = 0; this->IBMapFlag = true; if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->indexBuffer); void* ptr = glMapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB); n_gltrace("nGLMesh::LockIndices()."); n_assert(ptr); retval = (ushort*) ptr; } else { retval = (ushort*) this->privIndexBuffer; } this->UnlockMutex(); return retval; } //------------------------------------------------------------------------------ /** Unlock the gl index buffer locked by nD3D9Mesh::LockIndices(). */ void nGLMesh::UnlockIndices() { this->LockMutex(); n_assert((this->indexBuffer || this->privIndexBuffer) && this->IBMapFlag); this->IBMapFlag = false; if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glUnmapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, NULL); n_gltrace("nGLMesh::UnlockIndices()."); } this->UnlockMutex(); } //----------------------------------------------------------------------------- /** Set gl vertices */ bool nGLMesh::SetVertices(int vertexStart) { if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vertexBuffer); } int stride = this->GetVertexWidth() * sizeof(GLfloat); if (this->vertexComponentMask & Coord) { glVertexPointer(this->componentSize[firstSetBitPos(Coord)],//3, GL_FLOAT, stride, this->VertexOffset(0, Coord)); glEnableClientState(GL_VERTEX_ARRAY); } if (this->vertexComponentMask & Normal) { glNormalPointer(GL_FLOAT, stride, this->VertexOffset(0, Normal)); glEnableClientState(GL_NORMAL_ARRAY); } // we work with texture only if mesh has tex coordinates if (this->texCoordNum > 0) { //glEnableClientState(GL_TEXTURE_COORD_ARRAY); // binding textures int stage; // TODO: check this for situation when textures not placed one by one in gfx->refTextures for (stage = 0; stage < this->texCoordNum; stage++) { nGLTexture* tex = (nGLTexture*)nGfxServer2::Instance()->GetRenderTarget(stage); if (tex) { int res = tex->ApplyCoords( stage, this->componentSize[firstSetBitPos(Uv0 << stage)], stride, this->VertexOffset(0, this->texCoordFirst + stage)); if (res == -1) { n_gltrace("nGLMesh::SetVertices()."); return false; } if (res == 0) break; } } glEnableClientState(GL_TEXTURE_COORD_ARRAY); } if (this->vertexComponentMask & Color) { glColorPointer(this->componentSize[firstSetBitPos(Color)],//4, GL_FLOAT, stride, this->VertexOffset(0, Color)); glEnableClientState(GL_COLOR_ARRAY); } //n_printf("VStride(%s)\n", stride); n_gltrace("nGLMesh::SetVertices()."); return true; } //----------------------------------------------------------------------------- /** Unset gl vertices */ void nGLMesh::UnsetVertices() { // we work with texture only if mesh has tex coordinates if (this->texCoordNum > 0) { // clear the texture stage and release p-buffer int stage; for (stage = 0; stage < this->texCoordNum; stage++) { nGLTexture* tex = (nGLTexture*)nGfxServer2::Instance()->GetRenderTarget(stage); if (tex) { int res = tex->UnApplyCoords(stage); if (res <= 0) break; } } } /* if (this->vertexComponentMask & Coord) glDisableClientState(GL_VERTEX_ARRAY); if (this->vertexComponentMask & Normal) glDisableClientState(GL_NORMAL_ARRAY); if (texCoordNum > 0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (this->vertexComponentMask & Color) glDisableClientState(GL_COLOR_ARRAY); */ glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, NULL); } n_gltrace("nGLMesh::UnsetVertices()."); } //----------------------------------------------------------------------------- /** Set gl indices */ bool nGLMesh::SetIndices(int indexStart) { if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->indexBuffer); } //int stride = sizeof(GLushort); //this->numIndices * sizeof(GLushort); //glIndexPointer(GL_UNSIGNED_BYTE, stride, this->IndexOffset(indexStart)); //this->privIndexBuffer glEnableClientState(GL_INDEX_ARRAY); //n_printf("IStride(%s)\n", stride); n_gltrace("nGLMesh::SetIndices()."); return true; } //----------------------------------------------------------------------------- /** Unset gl indices */ void nGLMesh::UnsetIndices() { glDisableClientState(GL_INDEX_ARRAY); if (N_GL_EXTENSION_SUPPORTED(GL_ARB_vertex_buffer_object)) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, NULL); } n_gltrace("nGLMesh::UnsetIndices()."); } //----------------------------------------------------------------------------- /** calculate vertex element offset */ void* nGLMesh::VertexOffset(int vertexStart, int component) { int cm = this->vertexComponentMask & component; n_assert2(cm < AllComponents, "You have tried to get a buffer offset for a not possible type!!! this is a hard fail!\n"); //float* basePtr = (float*)this->privVertexBuffer + vertexStart * this->vertexWidth + componentOffset[firstSetBitPos(cm)]; char* basePtr = (char*)this->vertexPtr + componentOffset[firstSetBitPos(cm)] + vertexStart * this->GetVertexWidth(); return (void*) basePtr; } //----------------------------------------------------------------------------- /** calculate index offset */ void* nGLMesh::IndexOffset(int indexStart) { return (void*)((char*)this->indexPtr + indexStart * sizeof(GLshort)); } //------------------------------------------------------------------------------ /** Compute the byte size of the mesh data */ int nGLMesh::GetByteSize() { if (this->IsValid()) { int vertexBufferSize = this->GetNumVertices() * this->GetVertexWidth() * sizeof(float); int indexBufferSize = this->GetNumIndices() * sizeof(ushort); return vertexBufferSize + indexBufferSize + nMesh2::GetByteSize(); } else { return 0; } }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 588 ] ] ]
9fe2c9cdfe835c9b4fc4ab7cdee96b4347203df4
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/singleplayer/utils/vgui/include/VGUI_ToggleButton.h
824d73186b64d55da6387af7d8399e80d50f2759
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
540
h
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #ifndef VGUI_TOGGLEBUTTON_H #define VGUI_TOGGLEBUTTON_H #include<VGUI.h> #include<VGUI_Button.h> namespace vgui { class VGUIAPI ToggleButton : public Button { public: ToggleButton(const char* text,int x,int y,int wide,int tall); ToggleButton(const char* text,int x,int y); }; } #endif
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 26 ] ] ]
b640b5dfe9fb9adeae2e4ae8bbd0cefa36f6af50
ae239aeeb8dcf7212d432791b959ef709888f99a
/v1.0/AIType1.cpp
310731cbcf3a7489c5b67b0da50f020506d1b0cc
[]
no_license
arunaupul/merrimack-college-csc4910-sp2010
6a9fff2280494048997728b36a214271a2a8f8fc
a77d9fbb00538c98b7d61a61e91854e2dee1e748
refs/heads/master
2016-08-07T19:18:11.144431
2010-05-04T23:44:38
2010-05-04T23:44:38
35,337,837
0
0
null
null
null
null
UTF-8
C++
false
false
3,222
cpp
#include "AIType1.h" #include "GameEnums.h" #include "GameDude.h" #include "ScoreManager.h" #define TRIGGER_DISTANCE 2 #define LEFT false #define RIGHT true #define MOVE_DISTANCE 0.005 #define FALL_SPEED 0.03 AIType1::AIType1( const Square & startingPos , unsigned int leftTextureId , unsigned int rightTextureId ) : AIObject( startingPos , leftTextureId ), m_direction( LEFT ) { m_textureIds[0] = leftTextureId; m_textureIds[1] = rightTextureId; } AIType1::~AIType1() { } void AIType1::Update( int ticks ) { if( m_active && !m_killed ) { if( m_vStatus == VS_NONE ) { m_currentLocation.left += (double)ticks * MOVE_DISTANCE * ( m_direction ? 1.0 : -1.0 ); m_currentLocation.right += (double)ticks * MOVE_DISTANCE * ( m_direction ? 1.0 : -1.0 ); } if( m_vStatus == VS_FALLING ) { m_currentLocation.top -= (double)ticks * FALL_SPEED; m_currentLocation.bottom -= (double)ticks * FALL_SPEED; } if( m_currentLocation.bottom < m_gameFloor ) { m_killed = true; } } } bool AIType1::Trigger( double xOffset ) { if( !m_active && !m_killed && m_currentLocation.left - xOffset <= TRIGGER_DISTANCE ) { m_active = true; return true; } return false; } bool AIType1::Collide( CollisionSideEnum side , int damage ) { if( side == CS_BOTTOM ) { if( damage == -1 ) { m_vStatus = VS_NONE; } } else if( side == CS_RIGHT && m_direction == RIGHT && damage == -1 ) { SwitchDirections( LEFT ); } else if( side == CS_LEFT && m_direction == LEFT && damage == -1 ) { SwitchDirections( RIGHT ); } else if( damage > 0 && !m_killed ) { m_killed = true; ScoreManager::Instance()->AddToScore( 15 , SO_AI_TYPE_1 ); } return false; } bool AIType1::CheckCollision( CollisionObject * object ) { if( !m_active || m_killed ) { return false; } GameDude * gameDude = 0; if( gameDude = dynamic_cast<GameDude *>( object ) ) { Square objectPos = gameDude->GetCurrentPosition(); if( m_currentLocation.top - objectPos.bottom <= 0.5 && m_currentLocation.top - objectPos.bottom >= -0.5 && ( ( m_currentLocation.left <= objectPos.left && m_currentLocation.right >= objectPos.left ) || ( m_currentLocation.right >= objectPos.right && m_currentLocation.left <= objectPos.right ) ) ) { if( gameDude->GetVerticalStatus() == VS_FALLING ) { gameDude->Collide( CS_BOTTOM , 0 ); Collide( CS_TOP , 1 ); } else { gameDude->Collide( CS_BOTTOM , 1 ); Collide( CS_TOP , 0 ); } return true; } else if( ( ( objectPos.bottom >= m_currentLocation.bottom && objectPos.bottom <= m_currentLocation.top ) || ( objectPos.top >= m_currentLocation.bottom && objectPos.top <= m_currentLocation.top ) ) && ( ( objectPos.left >= m_currentLocation.left && objectPos.left <= m_currentLocation.right ) || ( objectPos.right >= m_currentLocation.left && objectPos.right <= m_currentLocation.right ) ) ) { gameDude->Collide( CS_TOP , 1 ); Collide( CS_TOP , 0 ); } } return false; } void AIType1::SwitchDirections( bool direction ) { m_direction = direction; m_textureId = m_textureIds[direction]; }
[ "rfleming71@06d672e2-d70c-11de-b7b1-656321ec08b8" ]
[ [ [ 1, 124 ] ] ]
78bbb4bcba13c8a8c98735988f3418fe4bfbd714
5f7bfc86d39f4eba96d2eac2d23d4be5da95482b
/ipee/iPee/iPeeDlg.h
2efe63636198a50d058267227789a21e62a1bcf7
[]
no_license
syagev/ipee
4432810662340d5cac40adee8ad4beb64eaec496
4d2013b179f564189ac0b23b326443167214e469
refs/heads/master
2021-01-23T14:04:23.532011
2009-10-16T15:26:58
2009-10-16T15:26:58
32,187,660
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
h
#pragma once #include "afxwin.h" #include "iPeeCV.h" #include "afxcmn.h" ///////////////////////////////////////////// // CiPeeDlg dialog - the main application's dialog, makes up // for the iPee's system control panel class CiPeeDlg : public CDialog { public: //default constructor CiPeeDlg(CWnd* pParent = NULL); //dialog Data enum { IDD = IDD_IPEE_DIALOG }; //-- Fields ---------------- protected: HICON m_hIcon; //the app's icon (loaded from resource) CBrush* m_pBgBrush; //background brush for UI coloring CEdit m_txtStatus; //status textbox CTabCtrl m_tabCtrl; //main tab-control CDialog* m_pdlgTabs[4]; //the tabs in the main dlg int m_iCurTab; //the currently selected tab public: CiPeeCV* m_piPeeCV; //the iPee CV engine instance //-- Methods --------------- public: void AppendStatus(LPCTSTR lpStatus); //-- Event Handlers -------- protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); afx_msg void OnDestroy(); afx_msg void OnPaint(); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); afx_msg HCURSOR OnQueryDragIcon(); public: afx_msg void OnMnuLoadEngine(); afx_msg void OnMnuUnloadEngine(); afx_msg void OnMnuRestartEngine(); afx_msg void OnMnuStartCAM(); afx_msg void OniPeeEvt(WPARAM iMsgCode, LPARAM pMsgData); afx_msg void OnTcnSelchangeTab(NMHDR *pNMHDR, LRESULT *pResult); //message map implementation DECLARE_MESSAGE_MAP() afx_msg void OnMnuStopCAM(); };
[ "syagev@e8544548-9470-11de-a998-73bdc75c5f85" ]
[ [ [ 1, 56 ] ] ]
aa53a7ca470d9597d1a0f2c5c7f7fae05e4d5024
c4da0878cc154162ef24f3601755396038bff5c1
/Challenge.cpp
662d38db5027a577ab2917ad8fe6d3bdfb01871d
[]
no_license
splinterofchaos/Gravity-Battle
e19c166fa5b130c43e9a8150cca36ea23e0046f0
1fb26743be4a6f39eae095dc1bb42bfdc64511a0
refs/heads/master
2016-09-06T04:12:35.568646
2011-10-23T17:01:48
2011-10-23T17:01:48
935,258
1
0
null
null
null
null
UTF-8
C++
false
false
3,645
cpp
#include "Challenge.h" #include "draw_shape.h" #include "Draw.h" Package::WeakGoalPtr Package::goal; Package::WeakPackagePtr Package::pack; const float Package::RADIUS_TO_START = 200; const float Obsticle::SIZE = 15; const float Goal::SIZE = 23; Package::Package( const vector_type& pos, const vector_type& ) : Orbital( pos, vector_type(0,0), false ) { activationDelay = 1; started = false; isMovable = false; reachedGoal = false; } Package::State Package::on_off_screen( State s ) { if( isActive ) return Orbital::on_off_screen( s ); return s; } void Package::move( float dt ) { std::tr1::shared_ptr<Player> target = Orbital::target.lock(); if( !started && target && magnitude(target->s-s) < RADIUS_TO_START+target->radius() ) { started = true; isMovable = true; isActive = true; } Orbital::move( dt ); } void Package::draw() { Orbital::draw(); if( !started ) { glTranslatef( s.x(), s.y(), 0 ); glColor3f( 1, 1, 1 ); const int N_VERTS = 40; draw_loop( RADIUS_TO_START, RADIUS_TO_START + 10, N_VERTS ); glLoadIdentity(); } } Package::value_type Package::mass() { return 40; } Color Package::color() { return Color( 0.7, 0.5, 0.2, 1 ); } void Package::collide_with( CircleActor& collider ) { if( &collider == goal.lock().get() ) { isMovable = false; reachedGoal = true; } else { deleteMe = true; } } Obsticle::Obsticle( const vector_type& pos, const vector_type& ) : Orbital( pos, vector_type(0,0), false ) { isMovable = false; isActive = true; activationDelay = 0; } void Obsticle::move( float dt ) { collisionChecked = false; const float MAX_VEL = 0.55f; if( magnitude( v ) > MAX_VEL ) v = magnitude( v, MAX_VEL ); s += v*dt; state( Orbital::on_off_screen( state() ) ); } Color Obsticle::color() { return Color( 1, 1, 1 ); } Obsticle::value_type Obsticle::radius() const { return SIZE; } void Obsticle::collide_with( CircleActor& other ) { if( collisionChecked ) return; Obsticle* otherPtr = dynamic_cast<Obsticle*>( &other ); if( otherPtr ) otherPtr->collisionChecked = true; isMovable = true; other.isMovable = true; Vector<float,2> diff = other.s - s; float d = magnitude( diff ); float combRad = other.radius() + radius(); // Move them off each other. s -= magnitude( diff, magnitude(diff) - combRad + 1.01 ); Vector<float,2> mtd = diff * (((radius() + other.radius())-d)/d); Vector<float,2> vel = v - other.v; float vn = vel * unit(mtd); if( vn < 0 ) // They are moving away from each other. No extra work needed. return; float i = vn * ( mass() + other.mass() ); Vector<float,2> impulse = mtd * i; v -= impulse / mass(); other.v += impulse / other.mass(); } Goal::Goal( const vector_type& pos, const vector_type& ) : Obsticle( pos, vector_type(0,0) ) { isMovable = false; isActive = true; activationDelay = 0; } Color Goal::color() { return Color( 0.3, 1.8, 0.8 ); } Goal::value_type Goal::mass() { return 50; } Goal::value_type Goal::radius() const { return SIZE; } void Goal::collide_with( CircleActor& other ) { if( &other == Package::pack.lock().get() ) deleteMe = true; else Obsticle::collide_with( other ); }
[ [ [ 1, 9 ], [ 11, 175 ] ], [ [ 10, 10 ] ] ]
bce9544573673ca26d9500414d8d7769829a49f3
d9f1cc8e697ae4d1c74261ae6377063edd1c53f8
/src/ai/AStar.h
36027c00aef078a60b7987a101c275032a51a3b4
[]
no_license
commel/opencombat2005
344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022
d72fc2b0be12367af34d13c47064f31d55b7a8e0
refs/heads/master
2023-05-19T05:18:54.728752
2005-12-01T05:11:44
2005-12-01T05:11:44
375,630,282
0
0
null
null
null
null
UTF-8
C++
false
false
9,083
h
#pragma once #include <ai\Path.h> #include <stdlib.h> #include <assert.h> #include <memory.h> #include <world\Element.h> /** * In our implementation of the A* algorithm, we use a hash table for the * Closed list, because we want fast Insertions, Removals, and Queries. For * the open list, we use a priority queue for fast insertion and removals from * a binary heap, and we also use a hash table for fast queries. */ class AStar { public: AStar(void); virtual ~AStar(void); // Finds a path from (x0,y0) to (x1,y1), using the method // (prone, med, etc) found in level // // XXX/SGW: Add a flag to optimize for speed/cover/danger etc Path *FindPath(int x0, int y0, int x1, int y1, Element::Level level); protected: // This is the node structure that determines our path struct Node { int X, Y; // The A* heuristics float F,G,H; // Pointers to my parent and my children. We are a rectangular // tile based game so we have potentially 8 children struct Node *Parent; // The index of this node in the binary heap int HeapIndex; // Pointers to next and previous hash nodes struct Node *HashNext, *HashPrev; // Pointer to the next node in the memory list struct Node *MemNext; }; // Returns the best node off our open list Node *GetBestNode(); // Generates candidate nodes from the given node void GenerateSuccessors(Node *node); // Can we move to a particular tile? bool CanMove(int x, int y); // Generate a trial move to a particular tile void DoMove(Node *node, int x, int y); // Gets the cost of moving to tile (x,y) float GetTerrainCost(int x, int y); // Generates a heuristic for the cost remaining to // (_destx, _destY) float Heuristic(int x, int y); // Allocates and frees nodes Node *AllocateNode(); void FreeNode(Node *node); class Hash { public: Hash(int size, AStar *astar) { _astar = astar; _size = size; _nodes = (Node **) calloc(_size, sizeof(Node *)); } ~Hash() { } void Insert(Node *node) { unsigned int idx = HashFunction(node); node->HashNext = _nodes[idx]; if(node->HashNext != NULL) { node->HashNext->HashPrev = node; } _nodes[idx] = node; } Node *Remove(int x, int y) { unsigned int idx = HashFunction(x,y); Node *p = _nodes[idx]; while(p != NULL) { if(p->X == x && p->Y == y) { if(p->HashPrev != NULL) { p->HashPrev->HashNext = p->HashNext; if(p->HashNext != NULL) { p->HashNext->HashPrev = p->HashPrev; } } else { _nodes[idx] = p->HashNext; if(p->HashNext != NULL) { p->HashNext->HashPrev = NULL; } } return p; } p = p->HashNext; } return NULL; } Node *Find(int x, int y) { unsigned int idx = HashFunction(x,y); Node *p = _nodes[idx]; while(p != NULL) { if(p->X == x && p->Y == y) { return p; } p = p->HashNext; } return NULL; } void Clear() { memset(_nodes, 0, _size*sizeof(Node *)); } void DeepClear() { for(int i = 0; i < _size; ++i) { while(_nodes[i] != NULL) { Node *n = _nodes[i]; _nodes[i] = _nodes[i]->HashNext; _astar->FreeNode(n); } } } unsigned int HashFunction(Node *n) { return (n->X << 16 | n->Y) % _size; } unsigned int HashFunction(int x, int y) { return (x << 16 | y) % _size; } private: Node **_nodes; int _size; AStar *_astar; }; // A MinHeap class that we can use class MinHeap { public: // Some definitions for child checking #define Left(i) ((i) << 1) #define Right(i) (((i) << 1) + 1) #define Parent(i) ((i) >> 1) // Creates a new heap of the given size MinHeap(int maxSize, AStar *astar) { assert (0 < maxSize); _astar = astar; _heapNodes = (HeapNode **) calloc (maxSize+1, sizeof(HeapNode *)); if(NULL == _heapNodes) { _size = 0; _last = 0; } else { _size = maxSize; _last = 0; } _hash = new Hash(60013,astar); _freeHeapNodes = NULL; } // Destroys this heap ~MinHeap() { if(NULL != _heapNodes) { while(0 < _last) { if(NULL != _heapNodes[_last]) { free(_heapNodes[_last]); } --_last; } free(_heapNodes); } } // Inserts a new node into the heap. Returns the index at which // the node was inserted int Insert(Node *data, float priority) { // Create a new node for this data HeapNode *newNode = AllocateHeapNode(); newNode->Priority = priority; newNode->Data = data; ++_last; // Is the heap full? // XXX/GWS: I have written the code here, however, I do not // want these to be dynamic heaps, so I have also // added an assert to make sure we never hit this case assert(_last <= _size); #ifdef USE_DYNAMIC_HEAP if(_last > _size) { // Resize heap _heapNodes = (HeapNode **)realloc(_heapNodes, sizeof(HeapNode *)*(_size*2 + 1)); if(NULL == _heapNodes) { throw "Could not reallocate heap" } _size = _size*2; } #endif int i = _last; while((i > 1) && (_heapNodes[Parent(i)]->Priority >= newNode->Priority)) { _heapNodes[i] = _heapNodes[Parent(i)]; _heapNodes[i]->Data->HeapIndex = i; i = Parent(i); } _heapNodes[i] = newNode; _heapNodes[i]->Data->HeapIndex = i; _hash->Insert(data); return i; } // Gets the number of nodes in the heap int GetNumNodes() { return _last; } // Extracts the node with the max priority from the heap Node *ExtractMin() { if(0 >= _last) { throw "Heap is empty"; } HeapNode *max = _heapNodes[1]; _heapNodes[1] = _heapNodes[_last]; _heapNodes[1]->Data->HeapIndex = 1; --_last; SiftDown(1); _hash->Remove(max->Data->X, max->Data->Y); // Resize the heap if it is less than a quarter full. // XXX/GWS: I don't want to use this part of the code. // so I have assert'd it out for now. In the future, // I might relax these constraints and allow it // to occur #ifdef USE_DYNAMIC_HEAP if((_last*4) < _size) { // Resize heap to a half _heapNodes = (HeapNode **) realloc(_heapNodes, (1 + _size/2)*sizeof(HeapNode *)); if(NULL == _heapNodes) { throw "Error resizing heap"; } } #endif Node *n = max->Data; FreeHeapNode(max); return n; } // Removes a given index from the heap Node *RemoveIndex(int i) { if(0 >= _last) { throw "Heap is empty"; } else if(i > _last) { throw "Index out of bounds"; } HeapNode *rv = _heapNodes[i]; _heapNodes[i] = _heapNodes[_last]; _heapNodes[i]->Data->HeapIndex = i; --_last; SiftDown(i); _hash->Remove(rv->Data->X, rv->Data->Y); return rv->Data; } Node *Find(int x, int y) { return _hash->Find(x, y); } void Clear() { // Need to release all of our heap nodes for(int i = 1; i <= _last; ++i) { _astar->FreeNode(_heapNodes[i]->Data); _heapNodes[i]->Data = NULL; FreeHeapNode(_heapNodes[i]); } _last = 0; _hash->Clear(); } private: struct HeapNode { float Priority; Node *Data; HeapNode *MemNext; }; HeapNode *AllocateHeapNode() { if(_freeHeapNodes == NULL) { return (HeapNode *) calloc(1, sizeof(HeapNode)); } else { HeapNode *n = _freeHeapNodes; _freeHeapNodes = _freeHeapNodes->MemNext; return n; } } void FreeHeapNode(HeapNode *node) { node->MemNext = _freeHeapNodes; _freeHeapNodes = node; } // This function is the iterative version of Heapify() void SiftDown(int i) { int k, j, n; assert (1 <= i); k = i; n = _last; do { j = k; if((Left(j) <= n) && (_heapNodes[Left(j)]->Priority <= _heapNodes[k]->Priority)) { k = Left(j); } if((Right(j) <= n) && (_heapNodes[Right(j)]->Priority <= _heapNodes[k]->Priority)) { k = Right(j); } _heapNodes[0] = _heapNodes[j]; _heapNodes[0]->Data->HeapIndex = 0; _heapNodes[j] = _heapNodes[k]; _heapNodes[j]->Data->HeapIndex = j; _heapNodes[k] = _heapNodes[0]; _heapNodes[k]->Data->HeapIndex = k; } while (j != k); } Hash *_hash; int _size; int _last; HeapNode **_heapNodes; HeapNode *_freeHeapNodes; AStar *_astar; }; // end class MinHeap // Our list of OPEN nodes. This is a sorted list with respect // to f MinHeap *_openNodes; // Out list of CLOSED nodes Hash *_closedNodes; // Our destination nodes int _destX, _destY; // Keep track of free Nodes Node *_freeNodes; long _nFreeNodes, _nAllocatedNodes; // The current level we are using Element::Level _level; };
[ "opencombat" ]
[ [ [ 1, 426 ] ] ]
8f3ee5abcf7801bb882745df6f1a55e97edf80b4
3eae1d8c99d08bca129aceb7c2269bd70e106ff0
/trunk/Codes/CLR/Include/TinyCLR_Interop.h
f8d4fee600b172478a8b21223996cd92bf18b8ed
[]
no_license
yuaom/miniclr
9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082
4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1
refs/heads/master
2023-06-07T09:10:33.703929
2010-12-27T14:41:18
2010-12-27T14:41:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,919
h
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef _TINYCLR_INTEROP_H_ #define _TINYCLR_INTEROP_H_ #include <tinyhal.h> #include <TinyCLR_ErrorCodes.h> /////////////////////////////////////////////////////////////////////////////////////////////////// void TINYCLR_DEBUG_PROCESS_EXCEPTION( HRESULT hr, LPCSTR szFunc, LPCSTR szFile, int line ); #if defined(PLATFORM_WINDOWS) || defined(PLATFORM_WINCE) #define TINYCLR_LEAVE() { if(FAILED(hr)) TINYCLR_DEBUG_PROCESS_EXCEPTION( hr, NULL, NULL, 0 ); goto TinyCLR_Cleanup; } #define TINYCLR_RETURN() return hr #else #if defined(TINYCLR_TRACE_HRESULT) #define TINYCLR_LEAVE() { if(FAILED(hr)) TINYCLR_DEBUG_PROCESS_EXCEPTION( hr, __func__, __FILE__, __LINE__ ); goto TinyCLR_Cleanup; } #define TINYCLR_RETURN() return hr #else #define TINYCLR_LEAVE() goto TinyCLR_Cleanup #define TINYCLR_RETURN() return hr #endif #endif #define TINYCLR_HEADER() HRESULT hr #define TINYCLR_CHECK_HRESULT(expr) { if(FAILED(hr = (expr))) TINYCLR_LEAVE(); } #define TINYCLR_EXIT_ON_SUCCESS(expr) { if(SUCCEEDED(hr = (expr))) TINYCLR_LEAVE(); } #define TINYCLR_SET_AND_LEAVE(expr) { hr = (expr); TINYCLR_LEAVE(); } #define TINYCLR_CLEANUP() hr = S_OK; TinyCLR_Cleanup: #define TINYCLR_CLEANUP_END() TINYCLR_RETURN() #define TINYCLR_NOCLEANUP() TINYCLR_CLEANUP(); TINYCLR_CLEANUP_END() #define TINYCLR_NOCLEANUP_NOLABEL() hr = S_OK; TINYCLR_RETURN() #define FAULT_ON_NULL(ptr) if(!(ptr)) TINYCLR_SET_AND_LEAVE(CLR_E_NULL_REFERENCE) #define FAULT_ON_NULL_ARG(ptr) if(!(ptr)) TINYCLR_SET_AND_LEAVE(CLR_E_ARGUMENT_NULL) // Correspondence between CLR C# and C++ native types: // CLR Type C/C++ type C/C++ Ref Type // System.Byte UINT8 UINT8& // System.UInt16 UINT16 UINT16& // System.UInt32 UINT32 UINT32& // System.UInt64 UINT64 UINT64& // System.Char CHAR CHAR & // System.SByte INT8 INT8 & // System.Int16 INT16 INT16& // System.Int32 INT32 INT32& // System.Int64 INT64 INT64& // System.Single float float& // System.Double double double& // System.String const CHAR * CHAR * // System.Byte[] UINT8 * Same as C/C++ type // Forward declaration for managed stack frame. // This is internal CLR type, reference to managed stack frame is exposed to marshaling code. struct CLR_RT_StackFrame; /********************************************************************** ** ** Forward structure declarations . ** CLR_RT_HeapBlock - generic structure that keeps C# basic types ** CLR_RT_HeapBlock_NativeEventDispatcher - Object that supports managed callback initiated by Interrupts **********************************************************************/ struct CLR_RT_HeapBlock; struct CLR_RT_HeapBlock_NativeEventDispatcher; // Do not support marshaling of struct and class. For these types we create params of CLR_RT_HeapBlock* // and then set it to zero. typedef CLR_RT_HeapBlock* UNSUPPORTED_TYPE; #define CLR_RT_HEAP_BLOCK_SIZE 12 #define TINYCLR_NATIVE_DECLARE(mtd) static HRESULT mtd( CLR_RT_StackFrame& stack ) typedef HRESULT (*CLR_RT_MethodHandler)( CLR_RT_StackFrame& stack ); struct CLR_RT_NativeAssemblyData { // Assembly name or static name provided by driver developer to enable interrups. const char *m_szAssemblyName; // Check sum for the assembly. UINT32 m_checkSum; // Pointer to array of functions that implement native methods. // It could be different type of the function depending if it is assembly Interop Method // or function enabling Interrupts by user driver. const void *m_pNativeMethods; }; // Looks up in interop assemblies table for assembly with specified name. const CLR_RT_NativeAssemblyData *GetAssemblyNativeData( const char *lpszAssemblyName ); // C++ by value parameters ( not reference types ). /********************************************************************** ** ** Functions: Interop_Marshal_* ** ** Synopsis: This group of functions retrienves by value parameters ( not reference types ) ** Each function gets reference to managed stack frame in index of parameter to extract. ** The C++ value is returned in "param". ** ** Arguments: [stackFrame] - Reference to the managed stack frame. ** [paramIndex] - Index of parameter passed from managed code. This parameter will be updated now. ** [param] - Reference to native C++ variable. Filled by the function. ** This variable is filled with value passed from managed code. ** ** Returns: S_OK on success or error in case of paramter mismatch or invalid data passed from managed code. **********************************************************************/ HRESULT Interop_Marshal_bool ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, bool &param ); HRESULT Interop_Marshal_UINT8 ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, UINT8 &param ); HRESULT Interop_Marshal_UINT16( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, UINT16 &param ); HRESULT Interop_Marshal_UINT32( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, UINT32 &param ); HRESULT Interop_Marshal_UINT64( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, UINT64 &param ); HRESULT Interop_Marshal_CHAR ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CHAR &param ); HRESULT Interop_Marshal_INT8 ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, INT8 &param ); HRESULT Interop_Marshal_INT16 ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, INT16 &param ); HRESULT Interop_Marshal_INT32 ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, INT32 &param ); HRESULT Interop_Marshal_INT64 ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, INT64 &param ); HRESULT Interop_Marshal_float ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, float &param ); HRESULT Interop_Marshal_double( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, double &param ); HRESULT Interop_Marshal_LPCSTR( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, LPCSTR &param ); // For unsupported types we set param to NULL. HRESULT Interop_Marshal_UNSUPPORTED_TYPE( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, UNSUPPORTED_TYPE &param ); /********************************************************************** ** ** Functions: Interop_Marshal_*_ARRAY ** ** Synopsis: This group of functions retrienves C++ by value parameters ( not reference types ) ** Each function gets reference to managed stack frame in index of parameter to extract. ** The C++ value is returned in "param". ** ** Arguments: [stackFrame] - Reference to the managed stack frame. ** [paramIndex] - Index of parameter passed from managed code. This parameter will be updated now. ** [pByteParam] - Reference to pointer filled by the function. ** On return pParam points to native C++ array with values passed from managed code. ** This variable is filled with value passed from managed code. ** [arraySize] - Count of elements in array. Filled by the function. ** ** Returns: S_OK on success or error in case of paramter mismatch or invalid data passed from managed code. **********************************************************************/ template <class T> class CLR_RT_TypedArray { T *m_pData; UINT32 m_ElemCount; friend HRESULT Interop_Marshal_bool_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<UINT8> &typedArray ); friend HRESULT Interop_Marshal_UINT8_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<UINT8> &typedArray ); friend HRESULT Interop_Marshal_UINT16_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<UINT16> &typedArray ); friend HRESULT Interop_Marshal_UINT32_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<UINT32> &typedArray ); friend HRESULT Interop_Marshal_UINT64_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<UINT64> &typedArray ); friend HRESULT Interop_Marshal_CHAR_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<CHAR> &typedArray ); friend HRESULT Interop_Marshal_INT8_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<INT8> &typedArray ); friend HRESULT Interop_Marshal_INT16_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<INT16> &typedArray ); friend HRESULT Interop_Marshal_INT32_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<INT32> &typedArray ); friend HRESULT Interop_Marshal_INT64_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<INT64> &typedArray ); friend HRESULT Interop_Marshal_float_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<float> &typedArray ); friend HRESULT Interop_Marshal_double_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray<double> &typedArray ); public : CLR_RT_TypedArray() { m_pData = NULL; m_ElemCount = 0; } T GetValue( UINT32 i ) { return m_pData[ i ];} void SetValue( UINT32 i, T &val ) { m_pData[ i ] = val; } T& operator[]( UINT32 i ) { return m_pData[ i ];} UINT32 GetSize() { return m_ElemCount; } // Direct access to buffer is provided for cases when other // native functions require access to buffer and cannot use CLR_RT_TypedArray object T *GetBuffer() { return m_pData; } }; typedef CLR_RT_TypedArray<CHAR> CLR_RT_TypedArray_CHAR; typedef CLR_RT_TypedArray<UINT8> CLR_RT_TypedArray_UINT8; typedef CLR_RT_TypedArray<UINT16> CLR_RT_TypedArray_UINT16; typedef CLR_RT_TypedArray<UINT32> CLR_RT_TypedArray_UINT32; typedef CLR_RT_TypedArray<UINT64> CLR_RT_TypedArray_UINT64; typedef CLR_RT_TypedArray<INT8> CLR_RT_TypedArray_INT8; typedef CLR_RT_TypedArray<INT16> CLR_RT_TypedArray_INT16; typedef CLR_RT_TypedArray<INT32> CLR_RT_TypedArray_INT32; typedef CLR_RT_TypedArray<INT64> CLR_RT_TypedArray_INT64; typedef CLR_RT_TypedArray<float> CLR_RT_TypedArray_float; typedef CLR_RT_TypedArray<double> CLR_RT_TypedArray_double; HRESULT Interop_Marshal_bool_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_UINT8 &typedArray ); HRESULT Interop_Marshal_UINT8_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_UINT8 &typedArray ); HRESULT Interop_Marshal_UINT16_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_UINT16 &typedArray ); HRESULT Interop_Marshal_UINT32_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_UINT32 &typedArray ); HRESULT Interop_Marshal_UINT64_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_UINT64 &typedArray ); HRESULT Interop_Marshal_CHAR_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_CHAR &typedArray ); HRESULT Interop_Marshal_INT8_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_INT8 &typedArray ); HRESULT Interop_Marshal_INT16_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_INT16 &typedArray ); HRESULT Interop_Marshal_INT32_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_INT32 &typedArray ); HRESULT Interop_Marshal_INT64_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_INT64 &typedArray ); HRESULT Interop_Marshal_float_ARRAY ( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_float &typedArray ); HRESULT Interop_Marshal_double_ARRAY( const CLR_RT_StackFrame &stackFrame, UINT32 paramIndex, CLR_RT_TypedArray_double &typedArray ); /********************************************************************** ** ** Functions: SetResult_* ** ** Synopsis: This group of functions set value returned by managed method call. ** Value passed to this function will be the return value of the managed function. ** ** Arguments: [stackFrame] - Reference to the managed stack frame. ** [value] - Return value. This value is stored on managed stack frame and passed to managed code. **********************************************************************/ void SetResult_bool ( CLR_RT_StackFrame &stackFrame, bool value ); void SetResult_CHAR ( CLR_RT_StackFrame &stackFrame, CHAR value ); void SetResult_INT8 ( CLR_RT_StackFrame &stackFrame, INT8 value ); void SetResult_INT16 ( CLR_RT_StackFrame &stackFrame, INT16 value ); void SetResult_INT32 ( CLR_RT_StackFrame &stackFrame, INT32 value ); void SetResult_INT64 ( CLR_RT_StackFrame &stackFrame, INT64 value ); void SetResult_UINT8 ( CLR_RT_StackFrame &stackFrame, UINT8 value ); void SetResult_UINT16( CLR_RT_StackFrame &stackFrame, UINT16 value ); void SetResult_UINT32( CLR_RT_StackFrame &stackFrame, UINT32 value ); void SetResult_UINT64( CLR_RT_StackFrame &stackFrame, UINT64 value ); void SetResult_float ( CLR_RT_StackFrame &stackFrame, float value ); void SetResult_double( CLR_RT_StackFrame &stackFrame, double value ); void SetResult_LPCSTR( CLR_RT_StackFrame &stackFrame, LPCSTR value ); /********************************************************************** ** ** Functions: Interop_Marshal_LoadRef_* ** ** Synopsis: This group of functions pointer to reference parameter passed from managed code. ** On return of this function pParam points to reference parameter of managed code. ** Native code can retrieve and modidy the reference parameter using pParam ** ** Arguments: [stackFrame] - Reference to the managed stack frame. ** [paramIndex] - Index of parameter passed from managed code. This parameter will be updated now. ** [pByteParam] - Reference to pointer filled by the function. ** On return pParam points to native C++ array with values passed from managed code. ** This variable is filled with value passed from managed code. ** [pParam] - Address of reference parameter passed from managed code. Filled by the function. ** ** Returns: S_OK on success or error in case of paramter mismatch or invalid data passed from managed code. **********************************************************************/ HRESULT Interop_Marshal_bool_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, UINT8 *&pParam ); HRESULT Interop_Marshal_UINT8_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, UINT8 *&pParam ); HRESULT Interop_Marshal_UINT16_ByRef( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, UINT16 *&pParam ); HRESULT Interop_Marshal_UINT32_ByRef( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, UINT32 *&pParam ); HRESULT Interop_Marshal_UINT64_ByRef( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, UINT64 *&pParam ); HRESULT Interop_Marshal_CHAR_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, CHAR *&pParam ); HRESULT Interop_Marshal_INT8_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, INT8 *&pParam ); HRESULT Interop_Marshal_INT16_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, INT16 *&pParam ); HRESULT Interop_Marshal_INT32_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, INT32 *&pParam ); HRESULT Interop_Marshal_INT64_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, INT64 *&pParam ); HRESULT Interop_Marshal_float_ByRef ( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, float *&pParam ); HRESULT Interop_Marshal_double_ByRef( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, double *&pParam ); // For unsuppoted types return NULL reference HRESULT Interop_Marshal_UNSUPPORTED_TYPE_ByRef( const CLR_RT_StackFrame &stackFrame, void *pHeapBlock, UINT32 paramIndex, UNSUPPORTED_TYPE *&pParam ); /********************************************************************** ** ** Function: Interop_Marshal_StoreRef ** ** Synopsis: This function is used to store updated parameter or basic type passed by reference from managed code. ** It stores data from heap block pointed by pVoidHeapBlock back to the managed stack frame. ** ** Arguments: [stackFrame] - Reference to the managed stack frame. ** [pVoidHeapBlock] - Pointer to heap block that keeps updated basic type value ** [paramIndex] - Index of parameter passed from managed code. This parameter will be updated now. ** ** Returns: S_OK on success or error from StoreToReference. Error return would cause exception thrown in managed code. **********************************************************************/ HRESULT Interop_Marshal_StoreRef( CLR_RT_StackFrame &stackFrame, void *pVoidHeapBlock, UINT32 paramIndex ); /********************************************************************** ** ** Function: Interop_Marshal_RetrieveManagedObject ** ** Synopsis: Retrieves pointer to managed object from managed stack frame. ** ** Arguments: [stackFrame] - Reference to the managed stack frame. ** ** Returns: Pointer to managed object or NULL in case of error. **********************************************************************/ CLR_RT_HeapBlock* Interop_Marshal_RetrieveManagedObject( CLR_RT_StackFrame &stackFrame ); /********************************************************************** ** ** Functions: Interop_Marshal_GetField_ ** ** Synopsis: Retrieves C++ reference ( pointer ) to the field in managed object. ** ** Arguments: [pThis] - Pointer to the managed object retrieved by Interop_Marshal_RetrieveManagedObject. ** [fieldIndex] - Field index. ** ** Returns: Reference to the field. **********************************************************************/ UINT8 &Interop_Marshal_GetField_bool ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); UINT8 &Interop_Marshal_GetField_UINT8 ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); UINT16 &Interop_Marshal_GetField_UINT16( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); UINT32 &Interop_Marshal_GetField_UINT32( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); UINT64 &Interop_Marshal_GetField_UINT64( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); CHAR &Interop_Marshal_GetField_CHAR ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); INT8 &Interop_Marshal_GetField_INT8 ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); INT16 &Interop_Marshal_GetField_INT16 ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); INT32 &Interop_Marshal_GetField_INT32 ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); INT64 &Interop_Marshal_GetField_INT64 ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); float &Interop_Marshal_GetField_float ( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); double &Interop_Marshal_GetField_double( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); // For all other unsupported types we always return NULL reference. UNSUPPORTED_TYPE &Interop_Marshal_GetField_UNSUPPORTED_TYPE( CLR_RT_HeapBlock *pThis, UINT32 fieldIndex ); /********************************************************************** ** ** Function Signatures that should be supported by drivers to enable managed callbacks. ** ** InitializeInterruptsProc ** This driver function is called in native code by constructor of managed NativeEventDispatcher object. ** Parameters: ** [pContext] - Pointer to the context that should be passed to the ISR ( INterrupt Service Routine ). ** [userData] - User data passed to constructor of NativeEventDispatcher. **********************************************************************/ typedef HRESULT (*InitializeInterruptsProc )( CLR_RT_HeapBlock_NativeEventDispatcher *pContext, UINT64 userData ); /********************************************************************** ** EnableorDisableInterruptsProc ** This function is called by EnableInterrupt/DisableInterrupt functions of managed NativeEventDispatcher object. ** It should enable or disable HW interrupts. ** [pContext] - Pointer to the context, same as passed to InitializeInterruptsProc ** [fEnable] - If "true" - enable interrupts ** If "false" - disable interrupts **********************************************************************/ typedef HRESULT (*EnableorDisableInterruptsProc)( CLR_RT_HeapBlock_NativeEventDispatcher *pContext, bool fEnable ); /********************************************************************** ** ** CleanupInterruptsProc ** This function is called to release hardware that generates interrups and release associated resources ** [pContext] - Pointer to the context, same as passed to InitializeInterruptsProc ** **********************************************************************/ typedef HRESULT (*CleanupInterruptsProc)( CLR_RT_HeapBlock_NativeEventDispatcher *pContext ); /********************************************************************** ** ** InterruptServiceProc ** This is the prototype for the interrupt service routie. ** [pContext] - Pointer to the context, same as passed to InitializeInterruptsProc ** ** This function should call SaveNativeEventToHALQueue in order to create managed callback. ** The minimal implementation for this function would be: ** static void ISR_TestProc( CLR_RT_HeapBlock_NativeEventDispatcher *pContext ) ** ** { ** GLOBAL_LOCK(irq); ** // To do - Initialize userData1 and userData2 to userData. ** UINT32 userData1; ** UINT32 userData2; ** // Saves data to queue. Each call to SaveNativeEventToHALQueue initiates managed callback. ** SaveNativeEventToHALQueue( pContext, userData1, userData2 ); ** } **********************************************************************/ typedef HRESULT (*InterruptServiceProc)( CLR_RT_HeapBlock_NativeEventDispatcher *pContext ); /********************************************************************** ** ** Structure that keeps pointers to driver functions. ** The driver functions are accessed by CLR through global instance of this structure. ** See Spot_InteropSample_Native_Microsoft_SPOT_Interop_TestCallback.cpp file for use of this structure. ** **********************************************************************/ struct CLR_RT_DriverInterruptMethods { InitializeInterruptsProc m_InitProc; EnableorDisableInterruptsProc m_EnableProc; CleanupInterruptsProc m_CleanupProc; }; // Randomly generated 32 bit number. // This check sum validates that m_pNativeMethods points to CLR_RT_DriverInterruptMethods structure #define DRIVER_INTERRUPT_METHODS_CHECKSUM 0xf32f4c3e // Creates instance of CLR_RT_HeapBlock_NativeEventDispatcher. CLR_RT_HeapBlock_NativeEventDispatcher *CreateNativeEventInstance( CLR_RT_StackFrame& stack ); // Saves data from ISR. The data from this queue is used to call managed callbacks. // Should be called from ISR. void SaveNativeEventToHALQueue( CLR_RT_HeapBlock_NativeEventDispatcher *pContext, UINT32 data1, UINT32 data2 ); // Cleans up the data in the queue after interrupts were closed and no managed callbacks are expected. void CleanupNativeEventsFromHALQueue( CLR_RT_HeapBlock_NativeEventDispatcher *pContext ); void CLR_RetrieveCurrentMethod( UINT32& assmIdx, UINT32& methodIdx ); void CLR_SoftReboot(); void CLR_DebuggerBreak(); #endif // _TINYCLR_INTEROP_H_
[ [ [ 1, 418 ] ] ]
ba6d3e205d502360e3a54e2b34252157d2ea5775
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/004.cpp
b179ca41016dab27dc879cfc1f20c67b3fb66adf
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
11,288
cpp
///////////////////////////////////////////////////////////////////// // Mapper 4 // much of this is based on the DarcNES source. thanks, nyef :) void NES_mapper4_Init() { g_NESmapper.Reset = NES_mapper4_Reset; g_NESmapper.MemoryReadLow = NES_mapper4_MemoryReadLow; g_NESmapper.MemoryWrite = NES_mapper4_MemoryWrite; g_NESmapper.HSync = NES_mapper4_HSync; } void NES_mapper4_Reset() { int i; g_NESmapper.Mapper4.patch = 0; if(NES_crc32() == 0xdebea5a6 || // Ninja Ryukenden 2 - Ankoku no Jashin Ken NES_crc32() == 0xc5fea9f2) // Dai2Ji - Super Robot Taisen { g_NESmapper.Mapper4.patch = 1; } if(NES_crc32() == 0xd7a97b38 ) // Chou Jinrou Senki - Warwolf { g_NESmapper.Mapper4.patch = 2; } if(NES_crc32() == 0xeb2dba63 ) // VS TKO Boxing { g_NESmapper.Mapper4.patch = 3; g_NESmapper.Mapper4.vs_index = 0; } if(NES_crc32() == 0x135adf7c) // VS Atari RBI Baseball { g_NESmapper.Mapper4.patch = 4; g_NESmapper.Mapper4.vs_index = 0; } /* if(NES_crc32() == 0xb42feeb4 ){ g_NESmapper.Mapper4.patch = 5; g_NES.frame_irq_disenabled = 1; } */ // clear registers FIRST!!! for(i = 0; i < 8; i++) g_NESmapper.Mapper4.regs[i] = 0x00; // set CPU bank pointers g_NESmapper.Mapper4.prg0 = 0; g_NESmapper.Mapper4.prg1 = 1; NES_mapper4_MMC3_set_CPU_banks(); // set VROM banks if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper4.chr01 = 0; g_NESmapper.Mapper4.chr23 = 2; g_NESmapper.Mapper4.chr4 = 4; g_NESmapper.Mapper4.chr5 = 5; g_NESmapper.Mapper4.chr6 = 6; g_NESmapper.Mapper4.chr7 = 7; NES_mapper4_MMC3_set_PPU_banks(); } else { g_NESmapper.Mapper4.chr01 = g_NESmapper.Mapper4.chr23 = g_NESmapper.Mapper4.chr4 = g_NESmapper.Mapper4.chr5 = g_NESmapper.Mapper4.chr6 = g_NESmapper.Mapper4.chr7 = 0; } g_NESmapper.Mapper4.irq_enabled = 0; g_NESmapper.Mapper4.irq_counter = 0; g_NESmapper.Mapper4.irq_latch = 0; } uint8 NES_mapper4_MemoryReadLow(uint32 addr) { if(g_NESmapper.Mapper4.patch == 3) { // VS TKO Boxing security if(addr == 0x5E00) { g_NESmapper.Mapper4.vs_index = 0; return 0x00; } else if(addr == 0x5E01) { uint8 security_data[32] = { 0xff, 0xbf, 0xb7, 0x97, 0x97, 0x17, 0x57, 0x4f, 0x6f, 0x6b, 0xeb, 0xa9, 0xb1, 0x90, 0x94, 0x14, 0x56, 0x4e, 0x6f, 0x6b, 0xeb, 0xa9, 0xb1, 0x90, 0xd4, 0x5c, 0x3e, 0x26, 0x87, 0x83, 0x13, 0x00 }; return security_data[(g_NESmapper.Mapper4.vs_index++) & 0x1F]; } } else if(g_NESmapper.Mapper4.patch == 4) { // VS Atari RBI Baseball security if(addr == 0x5E00) { g_NESmapper.Mapper4.vs_index = 0; return 0xFF; } else if(addr == 0x5E01) { switch(g_NESmapper.Mapper4.vs_index++) { case 0x09: return 0x6F; default: return 0xB4; } } } return (uint8)(addr >> 8); } void NES_mapper4_MemoryWrite(uint32 addr, uint8 data) { switch(addr & 0xE001) { case 0x8000: { g_NESmapper.Mapper4.regs[0] = data; NES_mapper4_MMC3_set_PPU_banks(); NES_mapper4_MMC3_set_CPU_banks(); } break; case 0x8001: { uint32 bank_num; g_NESmapper.Mapper4.regs[1] = data; bank_num = g_NESmapper.Mapper4.regs[1]; switch(g_NESmapper.Mapper4.regs[0] & 0x07) { case 0x00: { //if(num_1k_VROM_banks) { bank_num &= 0xfe; g_NESmapper.Mapper4.chr01 = bank_num; NES_mapper4_MMC3_set_PPU_banks(); } } break; case 0x01: { //if(num_1k_VROM_banks) { bank_num &= 0xfe; g_NESmapper.Mapper4.chr23 = bank_num; NES_mapper4_MMC3_set_PPU_banks(); } } break; case 0x02: { //if(num_1k_VROM_banks) { g_NESmapper.Mapper4.chr4 = bank_num; NES_mapper4_MMC3_set_PPU_banks(); } } break; case 0x03: { //if(num_1k_VROM_banks) { g_NESmapper.Mapper4.chr5 = bank_num; NES_mapper4_MMC3_set_PPU_banks(); } } break; case 0x04: { //if(num_1k_VROM_banks) { g_NESmapper.Mapper4.chr6 = bank_num; NES_mapper4_MMC3_set_PPU_banks(); } } break; case 0x05: { //if(num_1k_VROM_banks) { g_NESmapper.Mapper4.chr7 = bank_num; NES_mapper4_MMC3_set_PPU_banks(); } } break; case 0x06: { g_NESmapper.Mapper4.prg0 = bank_num; NES_mapper4_MMC3_set_CPU_banks(); } break; case 0x07: { g_NESmapper.Mapper4.prg1 = bank_num; NES_mapper4_MMC3_set_CPU_banks(); } break; } } break; case 0xA000: { g_NESmapper.Mapper4.regs[2] = data; if(data & 0x40) { LOG("MAP4 MIRRORING: 0x40 ???" << endl); } if(NES_ROM_get_mirroring() != NES_PPU_MIRROR_FOUR_SCREEN) { if(data & 0x01) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } } } break; case 0xA001: { g_NESmapper.Mapper4.regs[3] = data; if(data & 0x80) { // enable save RAM $6000-$7FFF } else { // disable save RAM $6000-$7FFF } } break; case 0xC000: g_NESmapper.Mapper4.regs[4] = data; g_NESmapper.Mapper4.irq_counter = g_NESmapper.Mapper4.regs[4]; break; case 0xC001: g_NESmapper.Mapper4.regs[5] = data; g_NESmapper.Mapper4.irq_latch = g_NESmapper.Mapper4.regs[5]; break; case 0xE000: g_NESmapper.Mapper4.regs[6] = data; g_NESmapper.Mapper4.irq_enabled = 0; break; case 0xE001: g_NESmapper.Mapper4.regs[7] = data; g_NESmapper.Mapper4.irq_enabled = 1; break; default: LOG("MAP4: UNKNOWN: " << HEX(addr,4) << " = " << HEX(data) << endl); break; } } void NES_mapper4_HSync(uint32 scanline) { if(g_NESmapper.Mapper4.irq_enabled) { if((scanline >= 0) && (scanline <= 239)) { if(NES_PPU_spr_enabled() || NES_PPU_bg_enabled()) { if(g_NESmapper.Mapper4.patch == 1) { if(!(--g_NESmapper.Mapper4.irq_counter)) { g_NESmapper.Mapper4.irq_counter = g_NESmapper.Mapper4.irq_latch; NES6502_DoIRQ(); } } else if(g_NESmapper.Mapper4.patch == 2) { if(--g_NESmapper.Mapper4.irq_counter == 0x01) { g_NESmapper.Mapper4.irq_counter = g_NESmapper.Mapper4.irq_latch; NES6502_DoIRQ(); } } else { if(!(g_NESmapper.Mapper4.irq_counter--)) { g_NESmapper.Mapper4.irq_counter = g_NESmapper.Mapper4.irq_latch; NES6502_DoIRQ(); } } } } } } void NES_mapper4_MMC3_set_CPU_banks() { if(g_NESmapper.Mapper4.regs[0] & 0x40) { g_NESmapper.set_CPU_banks4(g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.Mapper4.prg1, g_NESmapper.Mapper4.prg0,g_NESmapper.num_8k_ROM_banks-1); } else { g_NESmapper.set_CPU_banks4(g_NESmapper.Mapper4.prg0,g_NESmapper.Mapper4.prg1, g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); } } void NES_mapper4_MMC3_set_PPU_banks() { if(g_NESmapper.num_1k_VROM_banks) { if(g_NESmapper.Mapper4.regs[0] & 0x80) { g_NESmapper.set_PPU_banks8(g_NESmapper.Mapper4.chr4,g_NESmapper.Mapper4.chr5,g_NESmapper.Mapper4.chr6,g_NESmapper.Mapper4.chr7, g_NESmapper.Mapper4.chr01,g_NESmapper.Mapper4.chr01+1,g_NESmapper.Mapper4.chr23,g_NESmapper.Mapper4.chr23+1); } else { g_NESmapper.set_PPU_banks8(g_NESmapper.Mapper4.chr01,g_NESmapper.Mapper4.chr01+1,g_NESmapper.Mapper4.chr23,g_NESmapper.Mapper4.chr23+1, g_NESmapper.Mapper4.chr4,g_NESmapper.Mapper4.chr5,g_NESmapper.Mapper4.chr6,g_NESmapper.Mapper4.chr7); } } else { if(g_NESmapper.Mapper4.regs[0] & 0x80) { g_NESmapper.set_VRAM_bank(0, g_NESmapper.Mapper4.chr4); g_NESmapper.set_VRAM_bank(1, g_NESmapper.Mapper4.chr5); g_NESmapper.set_VRAM_bank(2, g_NESmapper.Mapper4.chr6); g_NESmapper.set_VRAM_bank(3, g_NESmapper.Mapper4.chr7); g_NESmapper.set_VRAM_bank(4, g_NESmapper.Mapper4.chr01+0); g_NESmapper.set_VRAM_bank(5, g_NESmapper.Mapper4.chr01+1); g_NESmapper.set_VRAM_bank(6, g_NESmapper.Mapper4.chr23+0); g_NESmapper.set_VRAM_bank(7, g_NESmapper.Mapper4.chr23+1); } else { g_NESmapper.set_VRAM_bank(0, g_NESmapper.Mapper4.chr01+0); g_NESmapper.set_VRAM_bank(1, g_NESmapper.Mapper4.chr01+1); g_NESmapper.set_VRAM_bank(2, g_NESmapper.Mapper4.chr23+0); g_NESmapper.set_VRAM_bank(3, g_NESmapper.Mapper4.chr23+1); g_NESmapper.set_VRAM_bank(4, g_NESmapper.Mapper4.chr4); g_NESmapper.set_VRAM_bank(5, g_NESmapper.Mapper4.chr5); g_NESmapper.set_VRAM_bank(6, g_NESmapper.Mapper4.chr6); g_NESmapper.set_VRAM_bank(7, g_NESmapper.Mapper4.chr7); } } } #define MAP4_ROM(ptr) (((ptr)-NES_ROM_get_ROM_banks()) >> 13) #define MAP4_VROM(ptr) (((ptr)-NES_ROM_get_VROM_banks()) >> 10) #define MAP4_VRAM(ptr) (((ptr)-NES_PPU_get_patt()) >> 10) void NES_mapper4_SNSS_fixup() // HACK HACK HACK HACK { nes6502_context context; NES6502_GetContext(&context); g_NESmapper.Mapper4.prg0 = MAP4_ROM(context.mem_page[(g_NESmapper.Mapper4.regs[0] & 0x40) ? 6 : 4]); g_NESmapper.Mapper4.prg1 = MAP4_ROM(context.mem_page[5]); if(g_NESmapper.num_1k_VROM_banks) { if(g_NESmapper.Mapper4.regs[0] & 0x80) { g_NESmapper.Mapper4.chr01 = MAP4_VROM(g_PPU.PPU_VRAM_banks[4]); g_NESmapper.Mapper4.chr23 = MAP4_VROM(g_PPU.PPU_VRAM_banks[6]); g_NESmapper.Mapper4.chr4 = MAP4_VROM(g_PPU.PPU_VRAM_banks[0]); g_NESmapper.Mapper4.chr5 = MAP4_VROM(g_PPU.PPU_VRAM_banks[1]); g_NESmapper.Mapper4.chr6 = MAP4_VROM(g_PPU.PPU_VRAM_banks[2]); g_NESmapper.Mapper4.chr7 = MAP4_VROM(g_PPU.PPU_VRAM_banks[3]); } else { g_NESmapper.Mapper4.chr01 = MAP4_VROM(g_PPU.PPU_VRAM_banks[0]); g_NESmapper.Mapper4.chr23 = MAP4_VROM(g_PPU.PPU_VRAM_banks[2]); g_NESmapper.Mapper4.chr4 = MAP4_VROM(g_PPU.PPU_VRAM_banks[4]); g_NESmapper.Mapper4.chr5 = MAP4_VROM(g_PPU.PPU_VRAM_banks[5]); g_NESmapper.Mapper4.chr6 = MAP4_VROM(g_PPU.PPU_VRAM_banks[6]); g_NESmapper.Mapper4.chr7 = MAP4_VROM(g_PPU.PPU_VRAM_banks[7]); } } else { if(g_NESmapper.Mapper4.regs[0] & 0x80) { g_NESmapper.Mapper4.chr01 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[4]); g_NESmapper.Mapper4.chr23 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[6]); g_NESmapper.Mapper4.chr4 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[0]); g_NESmapper.Mapper4.chr5 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[1]); g_NESmapper.Mapper4.chr6 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[2]); g_NESmapper.Mapper4.chr7 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[3]); } else { g_NESmapper.Mapper4.chr01 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[0]); g_NESmapper.Mapper4.chr23 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[2]); g_NESmapper.Mapper4.chr4 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[4]); g_NESmapper.Mapper4.chr5 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[5]); g_NESmapper.Mapper4.chr6 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[6]); g_NESmapper.Mapper4.chr7 = MAP4_VRAM(g_PPU.PPU_VRAM_banks[7]); } } } /////////////////////////////////////////////////////////////////////
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 433 ] ] ]
6a7f4e09851cf121ad0a12c172e66384a9e8df95
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Core/ZipFile.hpp
bc51c0324a2b7ae042e9172b95aec889c558e0f3
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
hpp
#ifndef ZIPFILE_HPP #define ZIPFILE_HPP #include <boost/cstdint.hpp> #include <boost/any.hpp> #include "File.hpp" #include "../../ThirdParty/Zip/unzip.h" namespace Spiral { /*! @class IZipFile @brief treats input source as a zip file */ class IZipFile : public IFile { public: IZipFile( HZIP handle, ZIPENTRY* entryInfo, int fileIdx ); private: HZIP m_zipHandle; ZIPENTRY m_entryInfo; boost::int32_t m_fileIdx; bool m_isEof; /*! @brief reads num bytes from a file @return num bytes read */ virtual boost::int32_t DoRead ( boost::int8_t* buffer, ///< pointer to a buffer to recieve data boost::int32_t count ///< number of bytes to read ); /*! @brief gets the size of the file @return size of the file */ virtual boost::uint32_t DoSize() const; /*! @brief moves the read cursor */ virtual void DoSeek ( seek_e position, ///< starting position to seek boost::int32_t bytes ///< number of bytes to seek ); /*! @brief closes the file */ virtual void DoClose(); /*! @brief end of file @return true if end of file reached */ virtual bool DoEof()const { return m_isEof; } }; } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 76 ] ] ]
543ef06310df9ccef0148984bf2f7c3173e188a1
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
/src/GUI/proRataXmlProcessor.h
5c99c8f1bd5810a5c62246b43e170c7eb4a43a3b
[]
no_license
ipodyaco/prorata
bd52105499c3fad25781d91952def89a9079b864
1f17015d304f204bd5f72b92d711a02490527fe6
refs/heads/master
2021-01-10T09:48:25.454887
2010-05-11T19:19:40
2010-05-11T19:19:40
48,766,766
0
0
null
null
null
null
UTF-8
C++
false
false
1,721
h
#ifndef XMLPROCESSOR_H #define XMLPROCESSOR_H #include <QtXml> #include <QDomDocument> #include <QDomNode> #include <QDomElement> #include <QString> #include <QFile> #include "proRataProteinTuple.h" #include "proRataPeptideTuple.h" #include <iostream> using namespace std; class ProRataXmlProcessors { public: ProRataXmlProcessors( const QString & qsFilename ); ProRataXmlProcessors(); ~ProRataXmlProcessors(); void setFilename( const QString & qsFilename ); bool processProtein( QDomElement &qdeProtein ); bool processPeptide( QDomElement &qdePeptide ); ProRataProteinTuple * getNextProtein(); ProRataPeptideTuple * getNextPeptide(); ProRataProteinTuple * getProtein( const QString & qsLocus ); ProRataPeptideTuple * getPeptide( const QString & qsLocus, const QString & qsChromatogramId ); QString getText( QDomElement &qdeTag, const QString & qsTagName ); void setProtein( const QString & qsLocus ); void setPeptide( const QString & qsLocus, const QString & qsChromatogramId ); void resetPointers(); private: bool processFile( const QString & qsFilename ); void goToProteinNode( const QString & qsLocus ); void goToPeptideNode( const QString & qsChromatogramId ); QDomDocument qddResults; QDomElement qdeRoot; QDomElement qdeFirstProteinElement; QDomElement qdeFirstPeptideElement; QDomElement qdeCurrentProteinElement; QDomElement qdeCurrentPeptideElement; QDomNode qdnSelectedProtein; QDomNode qdnSelectedPeptide; ProRataProteinTuple * prptProteinSeletedData; ProRataPeptideTuple * prdtPeptideSeletedData; QString qsFilename; }; #endif //XMLPROCESSOR_H
[ "chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a" ]
[ [ [ 1, 71 ] ] ]
d4e56802cca1cfffdfbad2afd01c6d6cd5f62a36
6eef3e34d3fe47a10336a53df1a96a591b15cd01
/ASearch/Index/IndexOptions.hpp
2c6891b54c74061d011fe23e8728c62c5e048565
[]
no_license
praveenmunagapati/alkaline
25013c233a80b07869e0fdbcf9b8dfa7888cc32e
7cf43b115d3e40ba48854f80aca8d83b67f345ce
refs/heads/master
2021-05-27T16:44:12.356701
2009-10-29T11:23:09
2009-10-29T11:23:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,564
hpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved ______________________________________________ written by Daniel Doubrovkine - [email protected] */ #ifndef ALKALINE_INDEX_OPTIONS_HPP #define ALKALINE_INDEX_OPTIONS_HPP #include <platform/include.hpp> #include <String/String.hpp> #include <Mutex/Atomic.hpp> class CIndexOptions { friend class CIndex; friend class CSite; private: bool m_GatherEmail; bool m_GatherEmailAll; CAtomic m_ModifiedCount; // number of modified files bool m_Modified; int m_RetryCount; bool m_FreeAlpha; bool m_CGI; bool m_SkipParseLinks; bool m_NSF; bool m_EmptyLinks; bool m_Insens; int m_Limit; int m_Timeout; bool m_Verbose; CString m_Proxy; // proxy settings CVector<CString> m_IndexingExts; CString m_IndexFile; CString m_IndexHTML; CString m_CurrentFilenameNdx; CString m_CurrentFilenameInf; CString m_CurrentFilenameUrt; CString m_CurrentFilenameLnx; public: CIndexOptions(void); ~CIndexOptions(void); }; #endif
[ [ [ 1, 50 ] ] ]
33ded369fa5fed132a8c1f2d7b2f0bd574db1de9
3856c39683bdecc34190b30c6ad7d93f50dce728
/server/UI_PacketState.cpp
a815bac9ab061774650c10f990b678c98d33656d
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
#include "stdafx.h" #include "UI_PacketState.h" CUI_PacketState::CUI_PacketState() { } CUI_PacketState::~CUI_PacketState() { } VOID CUI_PacketState::Draw() { cout << "PacketState Draw()" << endl; }
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 21 ] ] ]
6efffb2f499263bcb99929ff8a0eacb6d4cf2bd0
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/core_billiard/CameraCommonImp.cpp
b8adbaf50c9ab8a33c61c899a228f5b671cda410
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
#include "stdafx.h" #include "my_render_imp.h" namespace my_render_imp { CameraCommonImp::CameraCommonImp() { aspect_ = 16.0f / 9.0f; zNear_ = 0.01f; zFar_ = 10.0f * 100.f; } float CameraCommonImp::getZNear() { return zNear_; } float CameraCommonImp::getZFar() { return zFar_; } float CameraCommonImp::getAspect() { return aspect_; } void CameraCommonImp::setZNear(float nearf) { zNear_ = nearf; } void CameraCommonImp::setZFar(float farf) { zFar_ = farf; } void CameraCommonImp::setAspect(float aspect) { aspect_ = aspect;} }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 23 ] ] ]
ca6137fa94518026c373b33c9bdb1833571488fb
45c0d7927220c0607531d6a0d7ce49e6399c8785
/GlobeFactory/src/useful/clock.cc
39b24736f7d50f899b09df8f3dfe2cf2409550fb
[]
no_license
wavs/pfe-2011-scia
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
refs/heads/master
2021-01-25T07:08:36.552423
2011-01-17T20:23:43
2011-01-17T20:23:43
39,025,134
0
0
null
null
null
null
UTF-8
C++
false
false
2,462
cc
#include "clock.hh" #include "timer.hh" #include "macro.hh" #include "templated_function.hh" #include "log.hh" #include <SDL/SDL.h> //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Clock::Clock() : AVERAGE_COUNT(10), MElapsTime(0.0f), MCurTime(0.0f), MStartTime(0.0f) { } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Clock::~Clock() { LOG_ASSERT(MTimers.empty()); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Clock::Initialize() { SDL_Init(SDL_INIT_TIMER); MStartTime = SDL_GetTicks() / 1000.0f; MCurTime = MStartTime; for (unsigned i = 0; i < AVERAGE_COUNT; ++i) MElapsTimeQueue.push_back(0.0f); MElapsTime = 0.0f; LOG_RESUME("Clock ", "Clock initialized"); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Clock::Update() { float curTime = SDL_GetTicks() / 1000.0f; float realElapsTime = curTime - MCurTime; MElapsTimeQueue.pop_front(); MElapsTimeQueue.push_back(realElapsTime); MElapsTime = 0.0f; foreach(it, MElapsTimeQueue) MElapsTime += *it; MElapsTime /= MElapsTimeQueue.size(); MCurTime = curTime; foreach(it, MTimers) (*it)->Update(MElapsTime); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Timer* Clock::CreateTimer() { Timer* timer = new Timer(); MTimers.push_back(timer); return timer; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Clock::DeleteTimer(Timer* parTimer) { LOG_ASSERT(parTimer != NULL); LOG_ASSERT(misc::find(parTimer, MTimers)); MTimers.remove(parTimer); delete parTimer; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------
[ "creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc" ]
[ [ [ 1, 90 ] ] ]
ed54be74bbba83528b1ed259185d6c21bd0aacb6
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/MyGUIEngine/include/MyGUI_ILayer.h
96cb7476ffd24e521e8e38ed64827740adcc33ac
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
2,257
h
/*! @file @author Albert Semenov @date 02/2008 */ /* This file is part of MyGUI. MyGUI 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. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __MYGUI_I_LAYER_H__ #define __MYGUI_I_LAYER_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_Types.h" #include "MyGUI_IRenderTarget.h" #include "MyGUI_ILayerNode.h" #include "MyGUI_ISerializable.h" namespace MyGUI { class ILayerItem; class MYGUI_EXPORT ILayer : public ISerializable { MYGUI_RTTI_DERIVED( ILayer ) public: ILayer() { } virtual ~ILayer() { } // имя леера const std::string& getName() const { return mName; } // создаем дочерний нод virtual ILayerNode* createChildItemNode() = 0; // удаляем дочерний нод virtual void destroyChildItemNode(ILayerNode* _node) = 0; // поднимаем дочерний нод virtual void upChildItemNode(ILayerNode* _node) = 0; // список детей virtual EnumeratorILayerNode getEnumerator() const = 0; // возвращает виджет по позиции virtual ILayerItem* getLayerItemByPoint(int _left, int _top) const = 0; // возвращает позицию в координатах леера virtual IntPoint getPosition(int _left, int _top) const = 0; // возвращает размер леера virtual const IntSize& getSize() const = 0; // рисует леер virtual void renderToTarget(IRenderTarget* _target, bool _update) = 0; virtual void dumpStatisticToLog() { } protected: std::string mName; }; } // namespace MyGUI #endif // __MYGUI_I_LAYER_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 81 ] ] ]
bd1adb9a03e3b75343833e25c41ac62503506782
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/Tool/DataBaseTool/TabSheet.h
0d8276aebeaf49597f65dd312ced132471952c52
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
#pragma once // CTabSheet #define MAXPAGE 16 class CTabSheet : public CTabCtrl { DECLARE_DYNAMIC(CTabSheet) public: CTabSheet(); virtual ~CTabSheet(); int GetCurSel(); int SetCurSel(int nItem); void Show(); void SetRect(); BOOL AddPage(LPCTSTR title, CDialog *pDialog, UINT ID); protected: LPCTSTR m_Title[MAXPAGE]; UINT m_IDD[MAXPAGE]; CDialog* m_pPages[MAXPAGE]; int m_nNumOfPages; int m_nCurrentPage; protected: //{{AFX_MSG(CTabSheet) afx_msg void OnLButtonDown(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ [ [ 1, 35 ] ] ]
1f300a094871a115bc8fea6e3feb049ce1b167b0
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/TokenEditor/BitList.h
0fe8b37ef33f29b6dae8495b9de5f91bb9e614dc
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,115
h
//-------------------------------------------------------------------------------- // // Copyright (c) 2000 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- #ifndef _BITLIST_H_ #define _BITLIST_H_ //-------------------------------------------------------------------------------- class CBitCell { public: bool m_bIsSet; CString m_sName; }; //-------------------------------------------------------------------------------- class CBitList { public: enum { MIN = 1, MAX = 32, NUM_OF_CELLS = 6, MAXPOS = MAX - NUM_OF_CELLS }; public: CBitCell m_cells[MAX]; int m_nTopLine; public: CBitList(); void ConfigureScrollBar(CScrollBar*); void SetScrollBarPos(CScrollBar*, int, bool = true); void DoLineDown(int, CScrollBar*); void DoLineUp(int, CScrollBar*); void DoPageDown(int, CScrollBar*); void DoPageUp(int, CScrollBar*); void DoThumbTrack(int, CScrollBar*); void DoThumbPos(int, CScrollBar*); }; #endif //_BITLIST_H_
[ [ [ 1, 50 ] ] ]
6651ddd1a2c2a0c00aded7aa0fe5aeef4407a247
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/extensions/mysql/mysql/MyDriver.h
17dc04aaa556be57eafd058cd63583a770419dda
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,667
h
/** * vim: set ts=4 : * ============================================================================= * SourceMod MySQL Extension * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #ifndef _INCLUDE_SM_MYSQL_DRIVER_H_ #define _INCLUDE_SM_MYSQL_DRIVER_H_ #include <IDBDriver.h> #include <sm_platform.h> #if defined PLATFORM_WINDOWS #include <winsock.h> #endif #include <mysql.h> #include <sh_string.h> #include <sh_list.h> using namespace SourceMod; using namespace SourceHook; #define M_CLIENT_MULTI_RESULTS ((1) << 17) /* Enable/disable multi-results */ class MyDatabase; class MyDriver : public IDBDriver { public: MyDriver(); public: //IDBDriver IDatabase *Connect(const DatabaseInfo *info, bool persistent, char *error, size_t maxlength); const char *GetIdentifier(); const char *GetProductName(); Handle_t GetHandle(); IdentityToken_t *GetIdentity(); bool IsThreadSafe(); bool InitializeThreadSafety(); void ShutdownThreadSafety(); public: void Shutdown(); void RemoveFromList(MyDatabase *pdb, bool persistent); private: Handle_t m_MyHandle; List<MyDatabase *> m_TempDbs; List<MyDatabase *> m_PermDbs; }; extern MyDriver g_MyDriver; unsigned int strncopy(char *dest, const char *src, size_t count); #endif //_INCLUDE_SM_MYSQL_DRIVER_H_
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 79 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ] ] ]
0d371141371e6f39ca500f9d6e4c3cdf7fa60359
5f28f9e0948b026058bafe651ba0ce03971eeafa
/LindsayAR Client Final/ARToolkitPlus/src/core/arDetectMarker2.cpp
bf989cbcf9466d42fc3e2a2c2bf1a77461db349a
[]
no_license
TheProjecter/surfacetoar
cbe460d9f41a2f2d7a677a697114e4eea7516218
4ccba52e55b026b63473811319ceccf6ae3fbc1f
refs/heads/master
2020-05-17T15:41:31.087874
2010-11-08T00:09:25
2010-11-08T00:09:25
42,946,053
0
0
null
null
null
null
UTF-8
C++
false
false
11,031
cpp
/** * Copyright (C) 2010 ARToolkitPlus Authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Daniel Wagner */ #include "Tracker.h" #include <cstdio> namespace ARToolKitPlus { static int get_vertex( int x_coord[], int y_coord[], int st, int ed, ARFloat thresh, int vertex[], int *vnum); ARMarkerInfo2* Tracker::arDetectMarker2(int16_t *limage, int label_num, int *label_ref, int *warea, ARFloat *wpos, int *wclip, int area_max, int area_min, ARFloat factor, int *marker_num) { ARMarkerInfo2 *pm; int xsize, ysize; int marker_num2; int i, j, ret; ARFloat d; if( arImageProcMode == AR_IMAGE_PROC_IN_HALF ) { area_min /= 4; area_max /= 4; xsize = arImXsize / 2; ysize = arImYsize / 2; } else { xsize = arImXsize; ysize = arImYsize; } marker_num2 = 0; for(i=0; i<label_num; i++ ) { if( warea[i] < area_min || warea[i] > area_max ) continue; if( wclip[i*4+0] == 1 || wclip[i*4+1] == xsize-2 ) continue; if( wclip[i*4+2] == 1 || wclip[i*4+3] == ysize-2 ) continue; ret = arGetContour( limage, label_ref, i+1, &(wclip[i*4]), &(marker_infoTWO[marker_num2])); if( ret < 0 ) continue; ret = check_square( warea[i], &(marker_infoTWO[marker_num2]), factor ); if( ret < 0 ) continue; marker_infoTWO[marker_num2].area = warea[i]; marker_infoTWO[marker_num2].pos[0] = wpos[i*2+0]; marker_infoTWO[marker_num2].pos[1] = wpos[i*2+1]; marker_num2++; if(marker_num2==MAX_IMAGE_PATTERNS) break; } for( i=0; i < marker_num2; i++ ) { for( j=i+1; j < marker_num2; j++ ) { d = (marker_infoTWO[i].pos[0] - marker_infoTWO[j].pos[0]) * (marker_infoTWO[i].pos[0] - marker_infoTWO[j].pos[0]) + (marker_infoTWO[i].pos[1] - marker_infoTWO[j].pos[1]) * (marker_infoTWO[i].pos[1] - marker_infoTWO[j].pos[1]); if( marker_infoTWO[i].area > marker_infoTWO[j].area ) { if( d < marker_infoTWO[i].area / 4 ) { marker_infoTWO[j].area = 0; } } else { if( d < marker_infoTWO[j].area / 4 ) { marker_infoTWO[i].area = 0; } } } } for( i=0; i < marker_num2; i++ ) { if( marker_infoTWO[i].area == 0.0 ) { for( j=i+1; j < marker_num2; j++ ) { marker_infoTWO[j-1] = marker_infoTWO[j]; } marker_num2--; } } if( arImageProcMode == AR_IMAGE_PROC_IN_HALF ) { pm = &(marker_infoTWO[0]); for( i = 0; i < marker_num2; i++ ) { pm->area *= 4; pm->pos[0] *= 2.0; pm->pos[1] *= 2.0; for( j = 0; j< pm->coord_num; j++ ) { pm->x_coord[j] *= 2; pm->y_coord[j] *= 2; } pm++; } } *marker_num = marker_num2; return( &(marker_infoTWO[0]) ); } int Tracker::arGetContour(int16_t *limage, int *label_ref, int label, int clip[4], ARMarkerInfo2 *marker_infoTWO) { static const int xdir[8] = { 0, 1, 1, 1, 0,-1,-1,-1}; static const int ydir[8] = {-1,-1, 0, 1, 1, 1, 0,-1}; //static int wx[AR_CHAIN_MAX]; //static int wy[AR_CHAIN_MAX]; int16_t *p1; int xsize, ysize; int sx, sy, dir; int dmax, d, v1 = 0; int i, j; if( arImageProcMode == AR_IMAGE_PROC_IN_HALF ) { xsize = arImXsize / 2; ysize = arImYsize / 2; } else { xsize = arImXsize; ysize = arImYsize; } j = clip[2]; p1 = &(limage[j*xsize+clip[0]]); for( i = clip[0]; i <= clip[1]; i++, p1++ ) { if( *p1 > 0 && label_ref[(*p1)-1] == label ) { sx = i; sy = j; break; } } if( i > clip[1] ) { printf("??? 1\n"); return(-1); } marker_infoTWO->coord_num = 1; marker_infoTWO->x_coord[0] = sx; marker_infoTWO->y_coord[0] = sy; dir = 5; for(;;) { p1 = &(limage[marker_infoTWO->y_coord[marker_infoTWO->coord_num-1] * xsize + marker_infoTWO->x_coord[marker_infoTWO->coord_num-1]]); dir = (dir+5)%8; for(i=0;i<8;i++) { if( p1[ydir[dir]*xsize+xdir[dir]] > 0 ) break; dir = (dir+1)%8; } if( i == 8 ) { printf("??? 2\n"); return(-1); } marker_infoTWO->x_coord[marker_infoTWO->coord_num] = marker_infoTWO->x_coord[marker_infoTWO->coord_num-1] + xdir[dir]; marker_infoTWO->y_coord[marker_infoTWO->coord_num] = marker_infoTWO->y_coord[marker_infoTWO->coord_num-1] + ydir[dir]; if( marker_infoTWO->x_coord[marker_infoTWO->coord_num] == sx && marker_infoTWO->y_coord[marker_infoTWO->coord_num] == sy ) break; marker_infoTWO->coord_num++; if( marker_infoTWO->coord_num == AR_CHAIN_MAX-1 ) { printf("??? 3\n"); return(-1); } } dmax = 0; for(i=1;i<marker_infoTWO->coord_num;i++) { d = (marker_infoTWO->x_coord[i]-sx)*(marker_infoTWO->x_coord[i]-sx) + (marker_infoTWO->y_coord[i]-sy)*(marker_infoTWO->y_coord[i]-sy); if( d > dmax ) { dmax = d; v1 = i; } } for(i=0;i<v1;i++) { arGetContour_wx[i] = marker_infoTWO->x_coord[i]; arGetContour_wy[i] = marker_infoTWO->y_coord[i]; } for(i=v1;i<marker_infoTWO->coord_num;i++) { marker_infoTWO->x_coord[i-v1] = marker_infoTWO->x_coord[i]; marker_infoTWO->y_coord[i-v1] = marker_infoTWO->y_coord[i]; } for(i=0;i<v1;i++) { marker_infoTWO->x_coord[i-v1+marker_infoTWO->coord_num] = arGetContour_wx[i]; marker_infoTWO->y_coord[i-v1+marker_infoTWO->coord_num] = arGetContour_wy[i]; } marker_infoTWO->x_coord[marker_infoTWO->coord_num] = marker_infoTWO->x_coord[0]; marker_infoTWO->y_coord[marker_infoTWO->coord_num] = marker_infoTWO->y_coord[0]; marker_infoTWO->coord_num++; return 0; } int Tracker::check_square(int area, ARMarkerInfo2 *marker_infoTWO, ARFloat factor) { int sx, sy; int dmax, d, v1; int vertex[10], vnum; int wv1[10], wvnum1, wv2[10], wvnum2, v2; ARFloat thresh; int i; dmax = 0; v1 = 0; sx = marker_infoTWO->x_coord[0]; sy = marker_infoTWO->y_coord[0]; for(i=1;i<marker_infoTWO->coord_num-1;i++) { d = (marker_infoTWO->x_coord[i]-sx)*(marker_infoTWO->x_coord[i]-sx) + (marker_infoTWO->y_coord[i]-sy)*(marker_infoTWO->y_coord[i]-sy); if( d > dmax ) { dmax = d; v1 = i; } } thresh = (ARFloat)(area/0.75) * (ARFloat)0.01 * factor; vnum = 1; vertex[0] = 0; wvnum1 = 0; wvnum2 = 0; if( get_vertex(marker_infoTWO->x_coord, marker_infoTWO->y_coord, 0, v1, thresh, wv1, &wvnum1) < 0 ) { return(-1); } if( get_vertex(marker_infoTWO->x_coord, marker_infoTWO->y_coord, v1, marker_infoTWO->coord_num-1, thresh, wv2, &wvnum2) < 0 ) { return(-1); } if( wvnum1 == 1 && wvnum2 == 1 ) { vertex[1] = wv1[0]; vertex[2] = v1; vertex[3] = wv2[0]; } else if( wvnum1 > 1 && wvnum2 == 0 ) { v2 = v1 / 2; wvnum1 = wvnum2 = 0; if( get_vertex(marker_infoTWO->x_coord, marker_infoTWO->y_coord, 0, v2, thresh, wv1, &wvnum1) < 0 ) { return(-1); } if( get_vertex(marker_infoTWO->x_coord, marker_infoTWO->y_coord, v2, v1, thresh, wv2, &wvnum2) < 0 ) { return(-1); } if( wvnum1 == 1 && wvnum2 == 1 ) { vertex[1] = wv1[0]; vertex[2] = wv2[0]; vertex[3] = v1; } else { return(-1); } } else if( wvnum1 == 0 && wvnum2 > 1 ) { v2 = (v1 + marker_infoTWO->coord_num-1) / 2; wvnum1 = wvnum2 = 0; if( get_vertex(marker_infoTWO->x_coord, marker_infoTWO->y_coord, v1, v2, thresh, wv1, &wvnum1) < 0 ) { return(-1); } if( get_vertex(marker_infoTWO->x_coord, marker_infoTWO->y_coord, v2, marker_infoTWO->coord_num-1, thresh, wv2, &wvnum2) < 0 ) { return(-1); } if( wvnum1 == 1 && wvnum2 == 1 ) { vertex[1] = v1; vertex[2] = wv1[0]; vertex[3] = wv2[0]; } else { return(-1); } } else { return(-1); } marker_infoTWO->vertex[0] = vertex[0]; marker_infoTWO->vertex[1] = vertex[1]; marker_infoTWO->vertex[2] = vertex[2]; marker_infoTWO->vertex[3] = vertex[3]; marker_infoTWO->vertex[4] = marker_infoTWO->coord_num-1; return(0); } static int get_vertex( int x_coord[], int y_coord[], int st, int ed, ARFloat thresh, int vertex[], int *vnum) { ARFloat d, dmax; ARFloat a, b, c; int i, v1 = 0; a = (ARFloat)(y_coord[ed] - y_coord[st]); b = (ARFloat)(x_coord[st] - x_coord[ed]); c = (ARFloat)(x_coord[ed]*y_coord[st] - y_coord[ed]*x_coord[st]); dmax = 0; for(i=st+1;i<ed;i++) { d = a*x_coord[i] + b*y_coord[i] + c; if( d*d > dmax ) { dmax = d*d; v1 = i; } } if( dmax/(a*a+b*b) > thresh ) { if( get_vertex(x_coord, y_coord, st, v1, thresh, vertex, vnum) < 0 ) return(-1); if( (*vnum) > 5 ) return(-1); vertex[(*vnum)] = v1; (*vnum)++; if( get_vertex(x_coord, y_coord, v1, ed, thresh, vertex, vnum) < 0 ) return(-1); } return(0); } } // namespace ARToolKitPlus
[ [ [ 1, 340 ] ] ]
7771281d405a4a51fc430d840deef691464ff6f2
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/NxOgre/rendersystems/ogre/OGRE3DPointRenderable.h
5b4583f597fdcf64f29d0fe12ad7cb03dcf4f3e1
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
UTF-8
C++
false
false
6,444
h
/** File: OGRE3DPointRenderable.h Created on: 18-May-09 Author: Robin Southern "betajaen" Copyright (c) 2008-2009 Robin Southern Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef OGRE3D_POINTRENDERABLE_H #define OGRE3D_POINTRENDERABLE_H #include "NxOgre.h" #include "OGRE3DCommon.h" #include <OgreSimpleRenderable.h> /** \brief A OGRE3D RenderSystem implementation of the PointRenderable class. */ class OGRE3DExportClass OGRE3DPointRenderable : NxOgre::PointerClass<_OGRE3DPointRenderable>, public NxOgre::PointRenderable { friend class OGRE3DRenderSystem; public: using ::NxOgre::PointerClass<_OGRE3DPointRenderable>::operator new; using ::NxOgre::PointerClass<_OGRE3DPointRenderable>::operator delete; public: /** \brief Text */ void render(const NxOgre::Vec3&, const NxOgre::Quat&); /** \brief Add a pre-existing node to the node. \note If this node is a child of another, it will remove the node for you. */ void addSceneNode(Ogre::SceneNode*); /** \brief Add a pre-existing node to the node using a string as an identifier. \note If this node is a child of another, it will remove the node for you. */ void addSceneNode(const Ogre::String&); /** \brief Add a pre-existing entity to the node. \note If this entity is already attached to another scenenode it will remove it for you. */ void addEntity(Ogre::Entity*); /** \brief Add a movable object to this node. \note If this movable object is already attached to another scenenode it will remove it for you. */ void addMovableObject(Ogre::MovableObject*); /** \brief Removes a node from the node */ void removeSceneNode(Ogre::SceneNode*); /** \brief Removes a node from the node using a string as an identifier */ void removeSceneNode(const Ogre::String&); /** \brief Remove an entity from the node, but don't delete it */ void removeEntity(Ogre::Entity*); /** \brief Remove an entity from the node, but don't delete it, using a string as an identifier. */ void removeEntity(const Ogre::String&); /** \brief Destroys an entity from the node. */ void destroyEntity(Ogre::Entity*); /** \brief Destroys an entity from the node, using a string as an identifier. */ void destroyEntity(const Ogre::String&); /** \brief Remove an MovableObject from the node, but don't delete it. */ void removeMovableObject(Ogre::MovableObject*); /** \brief Remove an MovableObject from the node, but don't delete it, using a string as an identifier. */ void removeMovableObject(const Ogre::String&); /** \brief Destroys an MovableObject from the node. */ void destroyMovableObject(Ogre::MovableObject*); /** \brief Destroys an MovableObject from the node. */ void destroyMovableObject(const Ogre::String&); /** \brief Get the Node. */ Ogre::SceneNode* getNode(); /** \brief Get the SceneManager used. */ Ogre::SceneManager* getSceneManager(); /** \brief Get the SceneManager used. */ OGRE3DRenderSystem* getRenderSystem(); /** \brief */ OGRE3DPointRenderable(OGRE3DRenderSystem*, const Ogre::String& ogre_mesh_name); /** \brief Alternate/Default constructor. */ OGRE3DPointRenderable(OGRE3DRenderSystem*, Ogre::MovableObject*); /** \brief Alternate/Default constructor. * OUAN HACK */ OGRE3DPointRenderable(OGRE3DRenderSystem*, Ogre::SceneNode*); /** \brief */ ~OGRE3DPointRenderable(void); protected: // functions /** \internal */ inline Ogre::Entity* fetchEntity(const Ogre::String& name); /** \internal */ inline void destroyNode(Ogre::SceneNode*); /** \internal */ inline void parseMovableObject(Ogre::MovableObject*); protected: /** \brief SceneNode appointed to this OGRE3DPointRenderable. */ Ogre::SceneNode* mNode; /** \brief RenderSystem */ OGRE3DRenderSystem* mRenderSystem; }; #endif /* */
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 194 ] ] ]
0dcaa7ac4b647664c1fa6362d82cea9cb995fb41
2391d12c7d1de6f0b542c2c3b171fa286d84f433
/CTextureManager.h
edd1e9e9b12b5f7b8d1003fe87b1bfdb3c255c19
[]
no_license
DadyaIgor/ddblivion
cc0405cb062c7ec8e019c4fd820a6cdd34e4dfec
4450e54ae55e6888e5feda6b6550c8943c274fb1
refs/heads/master
2021-01-10T18:03:02.470209
2010-05-05T08:49:53
2010-05-05T08:49:53
46,456,895
0
0
null
null
null
null
UTF-8
C++
false
false
682
h
#ifndef CLASSTEXTUREMANAGER #define CLASSTEXTUREMANAGER class CTexture { public: CTexture(); ~CTexture(); public: unsigned long LoadLTEX(unsigned long); unsigned long LoadDirect(char *); unsigned long Get_FormID(); char *Get_Filename(); ID3D10ShaderResourceView *Get_Texture(); protected: unsigned long formID; ID3D10ShaderResourceView *pTexture; char *filename; }; class CTextureManager { public: CTextureManager(); ~CTextureManager(); CTexture *Load_LTEX(unsigned long); CTexture *Load_Direct(char *); CTexture *GetDefaultTexture(); protected: vector<CTexture *> texture_list; vector<CTexture *> texture2_list; }; #endif
[ [ [ 1, 37 ] ] ]
178495dbdccb9ff42eefa108dba64cd277393c05
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/Panel/Panel.h
07fd46d5b514b1a406ae53b14703e7f6b8229816
[]
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
2,324
h
#pragma once #include "../LWcommon/Lightwave3D.h" #include "lwdisplay.h" #include "Observer.h" class Control; /** * Panel base class. * @author David Forstenlechner * @date 2002-2003 */ class Panel : public Observable, public Observer { public: /** * Constructor. * @param name Name to be shown in title bar. * @param INFlags -Flags */ Panel( const char *name="Default", int INFlags=0 ); /** * Flags for Panel Creation. */ /* * Values: * - Blocking * - Cancel * - Frame * - MouseTrap * - NoButton */ enum Flag { Blocking=PANF_BLOCKING, /**< Open() return delayed until Panel is closed. */ Cancel=PANF_CANCEL, /**< Show Continue button. */ Frame=PANF_FRAME, /**< Windowing system title bar. */ MouseTrap=PANF_MOUSETRAP, /**< Tracking mouse input */ NoButton=PANF_NOBUTT /**< No Continue or Continue/Cancel buttons. */ }; virtual ~Panel(void); LWPanelID pan; bool CreatePanel(std::string &PanelName); virtual int Open(); virtual void Close(); int ShowPanel(); void Redraw(); virtual void Update( Observable* theChangedSubject ); virtual void OnDraw(int drawmode); virtual void OnMouseEvent(int event, int x, int y); virtual void OnKeyDown(unsigned short key); virtual void OnPanelClosed(void); static void PanelClosed_Callback( LWPanelID panel, void *UserData ); static void PanelDraw_Callback( LWPanelID panel, void *userdata, int drawmode ); static void PanelMouse_Callback( LWPanelID panel, void *userdata, int qualifiers, int x, int y ); static void PanelMouseMove_Callback( LWPanelID panel, void *userdata, int qualifiers, int x, int y ); static void PanelKeyDown_Callback( LWPanelID panel, void *userdata, unsigned short key ); void SetPanWidth(int widht); void SetPanHeight(int height); void GetPanelPosition( int &x, int &y); int Flags; HWND ThisWindow; std::string PanelName; bool IsDragging; int LastMouseX; int LastMouseY; bool IsClosing(void); LWPanelID GetPanelID(); bool Closing; static string PanelClassName; };
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 83 ] ] ]
4a635e342c697789d8396bba84d7b12d904c8c11
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/include/TRTKDTree.inl
2ef80fadbd99044a999e13f4a3ed2e43a455e6b9
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
6,036
inl
//===================================================================================================================== // // TRTKDTree.inl // // Implementation of class: TinyRT::KDTree // // Part of the TinyRT raytracing library. // Author: Joshua Barczak // Copyright 2009 Joshua Barczak. All rights reserved. // // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== namespace TinyRT { //===================================================================================================================== // // Constructors/Destructors // //===================================================================================================================== template< class ObjectSet_T > KDTree<ObjectSet_T>::KDTree() : m_nNodesInUse(0), m_nNodeArraySize(0), m_nObjectRefsInUse(0), m_nObjectRefArraySize(0) { } //===================================================================================================================== // // Public Methods // //===================================================================================================================== //===================================================================================================================== //===================================================================================================================== template< class ObjectSet_T > typename KDTree<ObjectSet_T>::NodeHandle KDTree<ObjectSet_T>::Initialize( const AxisAlignedBox& rRootAABB ) { if( m_nNodeArraySize < 1 ) { m_pNodes.resize( 100, m_nNodeArraySize ); m_nNodeArraySize = 100; } m_pNodes[0].MakeLeafNode(0,0); m_nNodesInUse = 1; m_nObjectRefsInUse = 0; m_aabb = rRootAABB; return 0; } //===================================================================================================================== //===================================================================================================================== template< class ObjectSet_T > std::pair< typename KDTree<ObjectSet_T>::NodeHandle, typename KDTree<ObjectSet_T>::NodeHandle > KDTree<ObjectSet_T>::MakeInnerNode( NodeHandle hNode, float fSplitPlane, uint nSplitAxis ) { m_nNodesInUse += 2; if( m_nNodeArraySize < m_nNodesInUse ) { uint nNewSize = std::max( m_nNodeArraySize*2, m_nNodesInUse ); m_pNodes.resize( nNewSize, m_nNodeArraySize ); m_nNodeArraySize = nNewSize; } NodeHandle hLeft = m_nNodesInUse - 2; m_pNodes[hNode].MakeInnerNode( hLeft, fSplitPlane, nSplitAxis ); return std::pair< NodeHandle, NodeHandle > ( hLeft, hLeft+1 ); } //===================================================================================================================== //===================================================================================================================== template< class ObjectSet_T > typename KDTree<ObjectSet_T>::obj_id* KDTree<ObjectSet_T>::MakeLeafNode( typename KDTree<ObjectSet_T>::NodeHandle n, typename KDTree<ObjectSet_T>::obj_id nObjCount ) { uint nStart = m_nObjectRefsInUse; m_nObjectRefsInUse += nObjCount; if( m_nObjectRefArraySize < m_nObjectRefsInUse ) { uint nNewSize = std::max( m_nObjectRefArraySize*2, m_nObjectRefsInUse ); m_pObjectRefs.resize( nNewSize, m_nObjectRefArraySize ); m_nObjectRefArraySize = nNewSize; } m_pNodes[n].MakeLeafNode( nStart, nObjCount ); return &m_pObjectRefs[nStart]; } //===================================================================================================================== //===================================================================================================================== template< class ObjectSet_T > template< class KDTreeBuilder_T > void KDTree<ObjectSet_T>::Build( ObjectSet_T* pObjects, KDTreeBuilder_T& rBuilder ) { m_nStackDepth = rBuilder.BuildTree( pObjects, this ); } //===================================================================================================================== //===================================================================================================================== template< class ObjectSet_T > bool KDTree<ObjectSet_T>::Validate() { for( uint i=0; i<m_nNodesInUse; i++ ) { const Node* pN = &m_pNodes[i]; if( pN->IsLeaf() ) { if( pN->GetChildren() >= m_nNodesInUse-1 ) return false; } else { if( pN->GetObjectCount() > 0 && pN->GetFirstObject() + pN->GetObjectCount() >= m_nObjectRefsInUse ) return false; } } return true; } //===================================================================================================================== // // Protected Methods // //===================================================================================================================== //===================================================================================================================== // // Private Methods // //===================================================================================================================== }
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
[ [ [ 1, 144 ] ] ]
411b5924320ed94f6de7f75bc1c2683c78ca13d8
d800e6c00854f9ba7b7bd49fd692b702987e9a53
/StrBuilder.h
56aa97670f3eec08a1b2de92943e07edcd356b66
[]
no_license
pmer/be
8b81982832b39c5071cb034c08844cd7abafb122
5780c74d5957f94bfc9a3ae9d04c960e5e96bbec
refs/heads/master
2020-04-16T13:07:07.555836
2011-02-27T13:09:21
2011-02-27T13:09:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,067
h
#ifndef STRBUILDER_H #define STRBUILDER_H class StrBuilder { public: // Constructors // StrBuilder(); StrBuilder(int len); // StrBuilder(const char* str); // StrBuilder(Str& str); // Deconstructor ~StrBuilder(); // Methods int length(); void buffer(int len); void empty(); void free(); char* copy(); operator const char*(); // Operators // char& operator [](int index); // StrBuilder& operator =(const char* str); // StrBuilder& operator =(Str& str); StrBuilder& operator +=(const char* str); StrBuilder& operator +=(bool b); StrBuilder& operator +=(char c); StrBuilder& operator +=(short i); StrBuilder& operator +=(long i); StrBuilder& operator +=(unsigned long i); StrBuilder& operator +=(long long i); bool operator ==(const char* str); // bool operator ==(Str& str); bool operator !=(const char* str); // bool operator !=(Str& str); // bool operator !(); private: inline void expand(int len); // Members char* data; int len; int alloc; }; #endif // STRBUILDER_H
[ [ [ 1, 58 ] ] ]