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
abc2f0a00c11516dc3560f70e1703d7fc4880b3b
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/string/string_abstract.h
5b04dd3b093ec154513aef5bcfe8654fafaf4446
[ "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
13,695
h
// Copyright (C) 2006 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_STRINg_ABSTRACT_ #ifdef DLIB_STRINg_ABSTRACT_ #include <string> #include <iostream> #include "../error.h" namespace dlib { // ---------------------------------------------------------------------------------------- class string_cast_error : public error { public: string_cast_error():error(ECAST_TO_STRING) {} }; template < typename T, typename charT, typename traits, typename alloc > const T string_cast ( const std::basic_string<charT,traits,alloc>& str ); /*! requires - T is not a pointer type ensures - returns str converted to T throws - string_cast_error This exception is thrown if string_cast() is unable to convert str into a T. Also, string_cast_error::info == str !*/ // ---------------------------------------------------------------------------------------- class cast_to_string_error : public error { public: cast_to_string_error():error(ECAST_TO_STRING) {} }; template < typename T > const std::string cast_to_string ( const T& item ); /*! requires - T is not a pointer type ensures - returns item converted to std::string throws - cast_to_string_error This exception is thrown if cast_to_string() is unable to convert item into a std::string. !*/ template < typename T > const std::wstring cast_to_wstring ( const T& item ); /*! requires - T is not a pointer type ensures - returns item converted to std::wstring throws - cast_to_string_error This exception is thrown if cast_to_string() is unable to convert item into a std::string. !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::string narrow ( const std::basic_string<charT,traits,alloc>& str ); /*! ensures - returns str as a std::string by converting every character in it to a char. Note that any characters that do not have a mapping to type char will be converted to a space. !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> wrap_string ( const std::basic_string<charT,traits,alloc>& str, const unsigned long first_pad, const unsigned long rest_pad, const unsigned long max_per_line = 79 ); /*! requires - first_pad < max_per_line - rest_pad < max_per_line - rest_pad >= first_pad ensures - returns a copy of str S such that: - S is broken up into lines separated by the \n character. - The first line starts with first_pad space characters. - The second and all subsequent lines start with rest_pad space characters. - The first line is no longer than max_per_line - (rest_pad-first_pad) characters. - The second and all subsequent lines are no longer than max_per_line characters. !*/ // ---------------------------------------------------------------------------------------- template < typename traits typename alloc > const std::basic_string<char,traits,alloc> tolower ( const std::basic_string<char,traits,alloc>& str ); /*! ensures - returns a copy of str S such that: - #S.size() == str.size() - #S[i] == std::tolower(str[i]) !*/ // ---------------------------------------------------------------------------------------- template < typename traits, typename alloc > const std::basic_string<char,traits,alloc> toupper ( const std::basic_string<char,traits,alloc>& str ); /*! ensures - returns a copy of str S such that: - #S.size() == str.size() - #S[i] == std::toupper(str[i]) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> ltrim ( const std::basic_string<charT,traits,alloc>& str, const std::basic_string<charT,traits,alloc>& trim_chars ); /*! ensures - returns a copy of str with any leading trim_chars from the left side of the string removed. !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> ltrim ( const std::basic_string<charT,traits,alloc>& str, const charT* trim_chars = _dT(charT," \t\r\n") ); /*! ensures - returns ltrim(str, std::basic_string<charT,traits,alloc>(trim_chars)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> rtrim ( const std::basic_string<charT,traits,alloc>& str, const std::basic_string<charT,traits,alloc>& trim_chars ); /*! ensures - returns a copy of str with any trailing trim_chars from the right side of the string removed. !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> rtrim ( const std::basic_string<charT,traits,alloc>& str, const charT* trim_chars = _dT(charT," \t\r\n") ); /*! ensures - returns rtrim(str, std::basic_string<charT,traits,alloc>(trim_chars)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> trim ( const std::basic_string<charT,traits,alloc>& str, const std::basic_string<charT,traits,alloc>& trim_chars ); /*! ensures - returns a copy of str with any leading or trailing trim_chars from the ends of the string removed. !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> trim ( const std::basic_string<charT,traits,alloc>& str, const charT* trim_chars = _dT(charT," \t\r\n") ); /*! ensures - returns trim(str, std::basic_string<charT,traits,alloc>(trim_chars)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> rpad ( const std::basic_string<charT,traits,alloc>& str, long pad_length, const std::basic_string<charT,traits,alloc>& pad_string ); /*! ensures - if (pad_length <= str.size()) then - returns str - else - let P be a string defined as follows: - P.size() == pad_length - str.size() - P == (pad_string + pad_string + ... + pad_string).substr(0,pad_length - str.size()) (i.e. P == a string with the above specified size that contains just repitions of the pad_string) - returns the string str + P !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> rpad ( const std::basic_string<charT,traits,alloc>& str, long pad_length, const charT* pad_string = _dT(charT," ") ); /*! ensures - returns rpad(str, pad_length, std::basic_string<charT,traits,alloc>(pad_string)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> lpad ( const std::basic_string<charT,traits,alloc>& str, long pad_length, const std::basic_string<charT,traits,alloc>& pad_string ); /*! ensures - if (pad_length <= str.size()) then - returns str - else - let P be a string defined as follows: - P.size() == pad_length - str.size() - P == (pad_string + pad_string + ... + pad_string).substr(0,pad_length - str.size()) (i.e. P == a string with the above specified size that contains just repitions of the pad_string) - returns the string P + str !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> lpad ( const std::basic_string<charT,traits,alloc>& str, long pad_length, const charT* pad_string = _dT(charT," ") ); /*! ensures - returns lpad(str, pad_length, std::basic_string<charT,traits,alloc>(pad_string)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> pad ( const std::basic_string<charT,traits,alloc>& str, long pad_length, const std::basic_string<charT,traits,alloc>& pad_string ); /*! ensures - let str_size == static_cast<long>(str.size()) - returns rpad( lpad(str, (pad_length-str_size)/2 + str_size, pad_string), pad_length, pad_string); !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> pad ( const std::basic_string<charT,traits,alloc>& str, long pad_length, const charT* pad_string = _dT(charT," ") ); /*! ensures - returns pad(str, pad_length, std::basic_string<charT,traits,alloc>(pad_string)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> left_substr ( const std::basic_string<charT,traits,alloc>& str, const std::basic_string<charT,traits,alloc>& delim ); /*! ensures - let delim_pos = str.find_first_of(delim) - returns str.substr(0,delim_pos) !*/ template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> left_substr ( const std::basic_string<charT,traits,alloc>& str, const charT* delim = _dT(charT," \n\r\t") ); /*! ensures - returns left_substr(str, std::basic_string<charT,traits,alloc>(delim)) !*/ // ---------------------------------------------------------------------------------------- template < typename charT, typename traits, typename alloc > const std::basic_string<charT,traits,alloc> right_substr ( const std::basic_string<charT,traits,alloc>& str, const std::basic_string<charT,traits,alloc>& delim ); /*! ensures - let delim_pos = str.find_last_of(delim) - if (delim_pos == std::string::npos) then - returns "" - else - returns str.substr(delim_pos+1) !*/ template < typename charT, typename traits typename alloc > const std::basic_string<charT,traits,alloc> right_substr ( const std::basic_string<charT,traits,alloc>& str, const charT* delim = _dT(charT," \n\r\t") ); /*! ensures - returns right_substr(str, std::basic_string<charT,traits,alloc>(delim)) !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_STRINg_ABSTRACT_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 437 ] ] ]
f3a4386bd5f55731c8517349f0f221a77bfc43c9
6b83c731acb331c4f7ddd167ab5bb562b450d0f2
/my_inc2/movPlayer.cpp
57a1a629855daac6f8e820842faafd46e01504f9
[]
no_license
weimingtom/toheart2p
fbfb96f6ca8d3102b462ba53d3c9cff16ca509e7
560e99c42fdff23e65f16df6d14df9a9f1868d8e
refs/heads/master
2021-01-10T01:36:31.515707
2007-12-20T15:13:51
2007-12-20T15:13:51
44,464,730
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
15,296
cpp
#include "movPlayer.h" #include <mm_std.h> #include <dshow.h> #pragma comment ( lib, "strmiids.lib" ) MovPlayerWnd *movPlayerWnd = NULL; BOOL MovPlaying = FALSE; int DecodeFlag = 0; int OverLay = 1; void MovPlayerWnd::Release() { if (lpBA) { lpBA->put_Volume( - 10000); Sleep(100); } if (lpMC) { lpMC->Stop(); } if (lpBA != NULL) { lpBA->Release(); lpBA = NULL; } if (lpVW != NULL) { lpVW->Release(); lpVW = NULL; } if (lpME != NULL) { lpME->Release(); lpME = NULL; } if (lpMC != NULL) { lpMC->Release(); lpMC = NULL; } if (lpGB != NULL) { lpGB->Release(); lpGB = NULL; } MovPlaying = FALSE; } //------------------------------------------------------------------------- BOOL MovPlayerWnd::PlayCheck() { long lEventCode; long lParam1; long lParam2; lpME->GetEvent(&lEventCode, &lParam1, &lParam2, 0); if (EC_COMPLETE == lEventCode) { MovPlaying = FALSE; return TRUE; } return FALSE; } //------------------------------------------------------------------------- #define WM_GRAPHNOTIFY WM_APP+1 BOOL MovPlayerWnd::PlayMediaFile(char *file, HWND hWnd) { HRESULT hr; Release(); hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **) &lpGB); if FAILED(hr) { return false; } WCHAR wFile[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, file, - 1, wFile, MAX_PATH); hr = lpGB->RenderFile(wFile, NULL); if FAILED(hr) { return false; } hr = lpGB->QueryInterface(IID_IMediaControl, (void **) &lpMC); hr = lpGB->QueryInterface(IID_IMediaEventEx, (void **) &lpME); hr = lpGB->QueryInterface(IID_IBasicAudio, (void **) &lpBA); hr = lpGB->QueryInterface(IID_IVideoWindow, (void **) &lpVW); if FAILED(hr) { return false; } hr = (lpME->SetNotifyWindow((OAHWND)hWnd, WM_GRAPHNOTIFY, 0) < 0); if FAILED(hr) { return false; } hr = lpVW->put_Owner((long)hWnd); if FAILED(hr) { return false; } hr = lpVW->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); if FAILED(hr) { return false; } RECT client; GetClientRect(hWnd, &client); hr = lpVW->SetWindowPosition(client.left, client.top + 76, client.right, client.bottom - 76 * 2); if FAILED(hr) { return false; } hr = lpMC->Run(); MovPlaying = TRUE; lpVW->put_AutoShow(OATRUE); lpVW->put_Visible(OATRUE); if FAILED(hr) { return false; } return true; } //------------------------------------------------------------------------- #include <mmsystem.h> #include <Aviriff.h> #include <io.h> CMovPlayerFrm *movPlayerFrm = NULL; BOOL MovPlaying2 = FALSE; #define INIT_DIRECTDRAW_STRUCT(x) (ZeroMemory(&x, sizeof(x)), x.dwSize=sizeof(x)) DWORD DDColorMatch(IDirectDrawSurface7 *pdds, COLORREF rgb); DDPIXELFORMAT g_ddpfOverlayFormats[] = { { sizeof(DDPIXELFORMAT), DDPF_FOURCC, MAKEFOURCC('Y', 'U', 'Y', '2'), 0, 0, 0, 0, 0 } , { sizeof(DDPIXELFORMAT), DDPF_FOURCC, MAKEFOURCC('U', 'Y', 'V', 'Y'), 0, 0, 0, 0, 0 } , { sizeof(DDPIXELFORMAT), DDPF_FOURCC, MAKEFOURCC('Y', 'V', '1', '2'), 0, 0, 0, 0, 0 } , { sizeof(DDPIXELFORMAT), DDPF_RGB, 0, 32, 0xff0000, 0x0ff00, 0x00ff, 0 } , { sizeof(DDPIXELFORMAT), DDPF_RGB, 0, 24, 0xff0000, 0x0ff00, 0x00ff, 0 } , { sizeof(DDPIXELFORMAT), DDPF_RGB, 0, 16, 0x7C00, 0x03e0, 0x001F, 0 } , { sizeof(DDPIXELFORMAT), DDPF_RGB, 0, 16, 0xF800, 0x07e0, 0x001F, 0 } , }; int overlay_forcc[] = { XVID_CSP_YUY2, XVID_CSP_UYVY, XVID_CSP_YV12, XVID_CSP_BGRA, XVID_CSP_BGR, XVID_CSP_RGB555, XVID_CSP_RGB565, XVID_CSP_BGR }; CMovPlayerFrm::CMovPlayerFrm() { lpdd = NULL; lpClipper = NULL; lpPrimary = NULL; lpSrcSurface = NULL; readBuf = NULL; fh = NULL; srcWidth = - 1; srcHeight = - 1; wWidth = 800; wHeight = 600; wX = 0; wY = 0; DecodeFlag = 0; } //------------------------------------------------------------------------- CMovPlayerFrm::~CMovPlayerFrm(){} void CMovPlayerFrm::Release() { DecodeFlag = 0; PAC_OpenFileHandle(&fh); if (readBuf) { free(readBuf); readBuf = NULL; } if (memDC) { SelectObject(memDC, oldBmp); DeleteObject(hBmp); DeleteDC(memDC); memDC = NULL; hBmp = NULL; } if (lpSrcSurface) { if (forccNum < 3) { lpSrcSurface->UpdateOverlay(NULL, lpPrimary, NULL, DDOVER_HIDE, NULL); } lpSrcSurface->Release(); } if (lpClipper) { lpClipper->Release(); } if (lpPrimary) { lpPrimary->Release(); } if (lpdd) { lpdd->Release(); } } //------------------------------------------------------------------------- void CMovPlayerFrm::OnPaint() { if (NULL == lpPrimary) { return ; } if (DD_OK == lpPrimary->IsLost()) { if (forccNum < 3) { HDC hDC = ::GetDC(m_hWnd); HBRUSH brush = CreateSolidBrush(RGB(0, 0, 8)); HBRUSH old_brush = (HBRUSH)SelectObject(hDC, brush); PatBlt(hDC, 0, 0, 800, 600, PATCOPY); SelectObject(hDC, old_brush); DrawSurface(GetDeviceCaps(hDC, BITSPIXEL)); DeleteObject(brush); ::ReleaseDC(m_hWnd, hDC); } } else { lpPrimary->Restore(); if (lpSrcSurface) { lpSrcSurface->Restore(); } } } //------------------------------------------------------------------------- struct Chunk { FOURCC ckID; DWORD size; FOURCC type; }; BOOL CMovPlayerFrm::CreateSurface() { HRESULT hr; DDSURFACEDESC2 ddsd; if (NULL == lpdd) { DirectDrawCreateEx(NULL, (void **) &lpdd, IID_IDirectDraw7, NULL); hr = lpdd->SetCooperativeLevel(m_hWnd, DDSCL_NORMAL); } if (NULL == lpPrimary) { INIT_DIRECTDRAW_STRUCT(ddsd); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; hr = lpdd->CreateSurface(&ddsd, &lpPrimary, NULL); lpdd->CreateClipper(0, &lpClipper, NULL); lpClipper->SetHWnd(0, m_hWnd); lpPrimary->SetClipper(lpClipper); } colorMatch = DDColorMatch(lpPrimary, RGB(0, 0, 8)); if (lpSrcSurface) { if (forccNum < 3) { lpSrcSurface->UpdateOverlay(NULL, lpPrimary, NULL, DDOVER_HIDE, NULL); } lpSrcSurface->Release(); } INIT_DIRECTDRAW_STRUCT(ddsd); ddsd.ddsCaps.dwCaps = DDSCAPS_OVERLAY | DDSCAPS_VIDEOMEMORY; ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; ddsd.dwWidth = srcWidth; ddsd.dwHeight = srcHeight; ddsd.dwBackBufferCount = 0; if (OverLay) { forccNum = 0; } else { forccNum = 3; } for (; forccNum < 7; forccNum++) { if (forccNum == 3) { ddsd.ddsCaps.dwCaps = DDSCAPS_SYSTEMMEMORY; } ddsd.ddpfPixelFormat = g_ddpfOverlayFormats[forccNum]; if (forccNum >= 3) { DDSURFACEDESC2 desc; desc.dwSize = sizeof(desc); desc.dwFlags = DDSD_PIXELFORMAT; hr = lpPrimary->GetSurfaceDesc(&desc); if (memcmp(&desc.ddpfPixelFormat, &ddsd.ddpfPixelFormat, sizeof(DDPIXELFORMAT)) != 0) { continue; } } hr = lpdd->CreateSurface(&ddsd, &lpSrcSurface, NULL); if (hr == DD_OK) { break; } } if (forccNum >= 3) { DebugPrintf("オーバーレイサーフェスの作成に失敗しました。ムービーの再生速度が低下します[%d]", forccNum); } if (forccNum == 7) { return FALSE; } return TRUE; } //------------------------------------------------------------------------- BOOL CMovPlayerFrm::OpenMovie(HWND hWnd, char *fname, int x, int y, int w, int h) { m_hWnd = hWnd; wX = x; wY = y; wWidth = w; wHeight = h; ofi = PAC_OpenFileHandle("mov", fname, &fh); if (fh == NULL) { DebugBox(NULL, "ファイルが見つかりませんでした。(%s)", fname); } Chunk aviFileHead; Chunk aviInfo; AVIMAINHEADER aviMainHead; PAC_ReedFileHandle(&fh, &ofi, (BYTE*) &aviFileHead, sizeof(Chunk)); if (MAKEFOURCC('R', 'I', 'F', 'F') != aviFileHead.ckID) { PAC_OpenFileHandle(&fh); return FALSE; } PAC_ReedFileHandle(&fh, &ofi, (BYTE*) &aviInfo, sizeof(Chunk)); PAC_ReedFileHandle(&fh, &ofi, (BYTE*) &aviMainHead, sizeof(AVIMAINHEADER)); fpms = aviMainHead.dwMicroSecPerFrame; srcWidth = aviMainHead.dwWidth; srcHeight = aviMainHead.dwHeight; HDC hDC = ::GetDC(m_hWnd); HBRUSH brush = CreateSolidBrush(RGB(0, 0, 8)); HBRUSH old_brush = (HBRUSH)SelectObject(hDC, brush); PatBlt(hDC, 0, 0, 800, 600, PATCOPY); SelectObject(hDC, old_brush); DeleteObject(brush); ::ReleaseDC(m_hWnd, hDC); if (FALSE == CreateSurface()) { BITMAPINFOHEADER bmpInfo; ZeroMemory(&bmpInfo, sizeof(BITMAPINFOHEADER)); bmpInfo.biSize = sizeof(BITMAPINFOHEADER); bmpInfo.biPlanes = 1; bmpInfo.biBitCount = 24; bmpInfo.biCompression = BI_RGB; bmpInfo.biWidth = srcWidth; bmpInfo.biHeight = - srcHeight; bmpInfo.biSizeImage = srcWidth * srcHeight * 3; hDC = ::GetDC(m_hWnd); memDC = CreateCompatibleDC(hDC); hBmp = CreateDIBSection(hDC, (BITMAPINFO*) &bmpInfo, DIB_RGB_COLORS, (void **) &pBuffer, NULL, NULL); oldBmp = (HBITMAP)SelectObject(memDC, hBmp); ::ReleaseDC(m_hWnd, hDC); } buffer_size = srcWidth * srcHeight * 2; readBuf = (LPBYTE)malloc(buffer_size); xvidDec.Start_XviD(srcWidth, srcHeight, overlay_forcc[forccNum]); read_size = PAC_ReedFileHandle(&fh, &ofi, readBuf, buffer_size); frame_cnt = 0; old_frame = 0; start_time = 0; old_time = 0; skip_cnt = 0; total_skip_cnt = 0; bPause = FALSE; bEnd = FALSE; MovPlaying2 = TRUE; return TRUE; } //------------------------------------------------------------------------- BOOL CMovPlayerFrm::DecodeMovie() { BOOL bSkip = FALSE, bLost = FALSE; HRESULT hr; int ret = FALSE; if (bPause) { return FALSE; } if (bEnd) { return FALSE; } if (skip_cnt) { xvidDec.SetSkip(TRUE); bSkip = TRUE; } if (lpSrcSurface) { DDSURFACEDESC2 ddsd; INIT_DIRECTDRAW_STRUCT(ddsd); if (DD_OK != (hr = lpPrimary->IsLost())) { bLost = TRUE; } else { hr = lpSrcSurface->Lock(NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL); } if (DD_OK != hr || bLost) { xvidDec.SetSkip(TRUE); bSkip = TRUE; } DecodeFlag = 1; ret = xvidDec.DecodeXviD(readBuf, read_size, &rest, (LPBYTE)ddsd.lpSurface, ddsd.lPitch); if (DD_OK == hr) { lpSrcSurface->Unlock(NULL); } } else { ret = xvidDec.DecodeXviD(readBuf, read_size, &rest, pBuffer, srcWidth *3); } xvidDec.SetSkip(FALSE); switch (ret) { case XviD_DEC_NEEDMORE: read_size = PAC_ReedFileHandle(&fh, &ofi, readBuf + rest, buffer_size - rest); break; case XviD_DEC_END: xvidDec.Clear_XviD(); bEnd = TRUE; return FALSE; } DWORD now_time = timeGetTime(); DWORD play_time = DWORD(start_time + frame_cnt * fpms / 1000); if (now_time < play_time && 0 == skip_cnt) { Sleep(play_time - now_time); } else if (frame_cnt > 0 && now_time > play_time + fpms / 1000) { DebugPrintf("skip%d\n", total_skip_cnt++); skip_cnt++; if (skip_cnt >= 20) { skip_cnt = 0; } } else { skip_cnt = 0; } if (bSkip) { frame_cnt++; return FALSE; } return TRUE; } //------------------------------------------------------------------------- BOOL CMovPlayerFrm::DrawMovie() { HDC hDC = NULL; hDC = ::GetDC(m_hWnd); if (lpSrcSurface) { DrawSurface(GetDeviceCaps(hDC, BITSPIXEL)); } else { if (srcWidth == wWidth && srcHeight == wHeight) { BitBlt(hDC, 0, 0, srcWidth, srcHeight, memDC, 0, 0, SRCCOPY); } else { StretchBlt(hDC, 0, 0, wWidth, wHeight, memDC, 0, 0, srcWidth, srcHeight, SRCCOPY); } } if (0 == frame_cnt) { start_time = timeGetTime(); } frame_cnt++; DWORD now_time = timeGetTime(); if (now_time > old_time) { int fps = 1000 / (now_time - old_time) / (frame_cnt - old_frame); } ::ReleaseDC(m_hWnd, hDC); old_time = now_time; old_frame = frame_cnt; return TRUE; } //------------------------------------------------------------------------- DWORD DDColorMatch(IDirectDrawSurface7 *pdds, COLORREF rgb) { COLORREF rgbT; HDC hdc; DWORD dw = CLR_INVALID; DDSURFACEDESC2 ddsd; HRESULT hres; if (rgb != CLR_INVALID && pdds->GetDC(&hdc) == DD_OK) { rgbT = GetPixel(hdc, 0, 0); SetPixel(hdc, 0, 0, rgb); pdds->ReleaseDC(hdc); } ddsd.dwSize = sizeof(ddsd); while ((hres = pdds->Lock(NULL, &ddsd, 0, NULL)) == DDERR_WASSTILLDRAWING) ; if (hres == DD_OK) { dw = *(DWORD*)ddsd.lpSurface; if (ddsd.ddpfPixelFormat.dwRGBBitCount < 32) { dw &= (1 << ddsd.ddpfPixelFormat.dwRGBBitCount) - 1; } pdds->Unlock(NULL); } if (rgb != CLR_INVALID && pdds->GetDC(&hdc) == DD_OK) { SetPixel(hdc, 0, 0, rgbT); pdds->ReleaseDC(hdc); } return dw; } //------------------------------------------------------------------------- BOOL CMovPlayerFrm::DrawSurface(BYTE bpp) { HRESULT ddrval; RECT rs, rd; DDOVERLAYFX ovfx; DDCAPS capsDrv; unsigned int uDestSizeAlign, uSrcSizeAlign; DWORD dwUpdateFlags; if (!lpdd || !lpPrimary || !lpSrcSurface) { return FALSE; } if (DecodeFlag == 0) { return FALSE; } int mx = GetSystemMetrics(SM_CXDLGFRAME); int my = GetSystemMetrics(SM_CYDLGFRAME) + GetSystemMetrics(SM_CYSIZE) + GetSystemMetrics(SM_CYBORDER) *2 +GetSystemMetrics(SM_CYMENUSIZE); GetWindowRect(m_hWnd, &rd); rd.top += wY + my; rd.left += wX + mx; rd.bottom = rd.top + wHeight; rd.right = rd.left + wWidth; rs.left = 0; rs.top = 0; rs.right = srcWidth; rs.bottom = srcHeight; int maxX = GetSystemMetrics(SM_CXSCREEN); int maxY = GetSystemMetrics(SM_CYSCREEN); if (rd.left < 0) { rd.left = 0; } if (rd.top < 0) { rd.top = 0; } if (rd.right > maxX) { rd.right = maxX; } if (rd.bottom > maxY) { rd.bottom = maxY; } INIT_DIRECTDRAW_STRUCT(capsDrv); ddrval = lpdd->GetCaps(&capsDrv, NULL); if (FAILED(ddrval)) { return FALSE; } uDestSizeAlign = capsDrv.dwAlignSizeDest; uSrcSizeAlign = capsDrv.dwAlignSizeSrc; if (capsDrv.dwCaps &DDCAPS_ALIGNSIZESRC && uSrcSizeAlign) { rs.right -= rs.right % uSrcSizeAlign; } if (capsDrv.dwCaps &DDCAPS_ALIGNSIZEDEST && uDestSizeAlign) { rd.right = (int)((rd.right + uDestSizeAlign - 1) / uDestSizeAlign) *uDestSizeAlign; } if (forccNum < 3) { dwUpdateFlags = DDOVER_SHOW | DDOVER_DDFX; INIT_DIRECTDRAW_STRUCT(ovfx); if (bpp >= 16 && (capsDrv.dwCKeyCaps &DDCKEYCAPS_DESTOVERLAY)) { dwUpdateFlags |= DDOVER_KEYDESTOVERRIDE; ovfx.dckDestColorkey.dwColorSpaceLowValue = colorMatch; ovfx.dckDestColorkey.dwColorSpaceHighValue = colorMatch; } ddrval = lpSrcSurface->UpdateOverlay(&rs, lpPrimary, &rd, dwUpdateFlags, &ovfx); } else { ddrval = lpPrimary->Blt(&rd, lpSrcSurface, &rs, 0, NULL); } if (ddrval == DDERR_SURFACELOST) { lpPrimary->Restore(); lpSrcSurface->Restore(); } if (FAILED(ddrval)) { return FALSE; } return TRUE; }
[ "pspbter@13f3a943-b841-0410-bae6-1b2c8ac2799f" ]
[ [ [ 1, 828 ] ] ]
3cc59b62eafcfa0c538c49168dc843281c318429
485c5413e1a4769516c549ed7f5cd4e835751187
/Source/Engine/meshManager.h
6b0e8602af76d99f32020f1d264ef76316143b96
[]
no_license
FranckLetellier/rvstereogram
44d0a78c47288ec0d9fc88efac5c34088af88d41
c494b87ee8ebb00cf806214bc547ecbec9ad0ca0
refs/heads/master
2021-05-29T12:00:15.042441
2010-03-25T13:06:10
2010-03-25T13:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
852
h
/************************************* * * ImacDemo Project * * Created : 20/12/09 * Authors : Franck Letellier * Baptiste Malaga * Fabien Kapala * Helena Duchaussoy * **************************************/ #ifndef __MESHMANAGER_H__ #define __MESHMANAGER_H__ /** * @name meshManager.h * @brief Manager all our mesh * @author Franck Letellier * @date 20/12/09 */ #include <string> #include <map> #include "singleton.h" class ObjMesh; class MeshManager:public Singleton<MeshManager> { friend class Singleton<MeshManager>; public: void loadMesh(const std::string& sName); ObjMesh* getMesh(const std::string& sName); void clear(); private: std::map<std::string,ObjMesh*> m_mMeshs; MeshManager(); virtual ~MeshManager(){clear();}; }; #endif //__MESHMANAGER_H__
[ [ [ 1, 50 ] ] ]
d20056c91379df8c8ef5ec2e6662d184709e0392
f5a3e2fcfe01bfe95d125a903c0af454c1b9cdd6
/SearchWidget.cpp
c4c4c22de0e69afba27ed62c3286ed7c332a3ff8
[]
no_license
congchenutd/congchenmywords
11418c97d3d260d35766cdfbb9968a54f569fad7
29fd31f7e7a99b17fe789e9d97879728ea9dbb80
refs/heads/master
2021-01-02T09:08:59.667661
2011-02-21T02:05:05
2011-02-21T02:05:05
32,358,808
0
0
null
null
null
null
UTF-8
C++
false
false
4,852
cpp
#include "SearchWidget.h" #include "WordList.h" #include "Library.h" #include <QtGui> #include <QtSql> SearchWidget::SearchWidget(QWidget *parent) : QWidget(parent) { initModel(); initView(); initConnection(); } void SearchWidget::initModel() { model = new QStandardItemModel(this); model->setColumnCount(2); model->setHorizontalHeaderLabels(QStringList() << tr("Word") << tr("Explanation")); modelSql = new QSqlTableModel(this); modelSql->setEditStrategy(QSqlTableModel::OnManualSubmit); } void SearchWidget::initView() { ui.setupUi(this); ui.tableView->setModel(model); ui.tableView->horizontalHeader()->setStretchLastSection(true); ui.tableView->sortByColumn(0, Qt::AscendingOrder); } void SearchWidget::initConnection() { connect(ui.tableView, SIGNAL(doubleClicked (const QModelIndex&)), this, SLOT(slotDoubleClicked(const QModelIndex&))); connect(ui.tableView, SIGNAL(clicked(const QModelIndex&)), this, SIGNAL(clicked())); } void SearchWidget::search(const QString& target, SearchOption option) { // search modelSql->setFilter(getFilter(target, option)); modelSql->select(); while(modelSql->canFetchMore()) modelSql->fetchMore(); // copy to model model->setRowCount(0); model->insertRows(0, modelSql->rowCount()); for(int i=0; i<modelSql->rowCount(); ++i) for(int j=0; j<2; ++j) model->setData(model->index(i, j), modelSql->data(modelSql->index(i, j))); sort(); } QString SearchWidget::getFilter(QString target, SearchOption option) const { if(target.isEmpty()) return "0"; if(ChineseList::isChinese(target)) // chinese { QString result; QStringList chineseList = ChineseList(target).getSplitted(); foreach(QString chinese, chineseList) result.append(tr("(explanation LIKE \"%%1%\") OR ").arg(chinese)); return result.left(result.length() - 4); // truncate last " OR " } // english switch(option) { case BEGIN: return tr("word LIKE \"%1%\"").arg(target); case END: return tr("word LIKE \"%%1\"").arg(target); default: return tr("word LIKE \"%%1%\"").arg(target); } } void SearchWidget::slotDoubleClicked(const QModelIndex& idx) { emit doubleClicked( Library::searchEnglish( dictName, model->data(model->index(idx.row(), 0)).toString())); } void SearchWidget::setDictName(const QString& dict) { dictName = dict; modelSql->setTable(dict); modelSql->removeColumns(3, 4); modelSql->removeColumn(0); } void SearchWidget::appendRecord(const QString& english, const QString& chinese) { if(findEnglish(english) == -1) { int lastRow = model->rowCount(); model->insertRow(lastRow); setRecord(lastRow, english, chinese); } } void SearchWidget::delRecord(const QString& english) { int row = findEnglish(english); if(row >= 0) model->removeRow(row); } void SearchWidget::moveRecordsTo(SearchWidget& dest) { QStringList englishsToBeDeleted; QModelIndexList idxs = ui.tableView->selectionModel()->selectedRows(); int lastRow = dest.rowCount(); dest.model->insertRows(lastRow, idxs.size()); foreach(QModelIndex idx, idxs) { QString english = getEnglish(idx.row()); dest.setRecord(lastRow++, english, getChinese(idx.row())); englishsToBeDeleted << english; } dest.sort(); foreach(QString english, englishsToBeDeleted) delRecord(english); // don't delete by rows, because they change while deleting } int SearchWidget::findEnglish(const QString& english) const { QModelIndexList idxs = model->match(model->index(0, 0), Qt::DisplayRole, english, 1, Qt::MatchExactly); return idxs.isEmpty() ? -1 : idxs.front().row(); } void SearchWidget::selectAll(bool select) { if(select) { ui.tableView->selectAll(); ui.tableView->setFocus(); } else ui.tableView->clearSelection(); } void SearchWidget::removeDuplicate(const SearchWidget& other) { for(int i=0; i<other.rowCount(); ++i) delRecord(other.getEnglish(i)); } int SearchWidget::rowCount() const { return model->rowCount(); } void SearchWidget::sort() { ui.tableView->sortByColumn(0, ui.tableView->horizontalHeader()->sortIndicatorOrder()); ui.tableView->resizeColumnToContents(0); } QString SearchWidget::getEnglish(int row) const { return validRow(row) ? model->data(model->index(row, 0)).toString() : QString(); } QString SearchWidget::getChinese(int row) const { return validRow(row) ? model->data(model->index(row, 1)).toString() : QString(); } void SearchWidget::setRecord(int row, const QString& english, const QString& chinese) { if(validRow(row)) { model->setData(model->index(row, 0), english); model->setData(model->index(row, 1), chinese); } } bool SearchWidget::validRow(int row) const { return 0 <= row && row < model->rowCount(); }
[ "congchenutd@33c296ca-c6a8-bfc7-d74f-b3a1fff04ced" ]
[ [ [ 1, 185 ] ] ]
1adcbe5c72284781cfdc9e23d0e5ba0f185d1a18
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/ErrorHandler.h
6c0b4a28239252740fbae6a74a5dc8c190063fc4
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
GB18030
C++
false
false
1,030
h
#ifndef ERRORHANDLER_H_ #define ERRORHANDLER_H_ #include <iostream> #include <string> #include <sstream> #include "G_common_defs.h" using namespace std; #define ERROR_NO_ERROR 0x00000001 class CErrorHandler { public: CErrorHandler() :error_code(ERROR_NO_ERROR),err_str("") { } virtual ~CErrorHandler(void) {} public: virtual Error_str GetLastErrorEx()=0; //要求各派生类实现该函数,一般的,GetLastErrorEx() {return GetLastErrorStr();} // Error_t GetLastError() {return error_code;} Error_str GetLastErrorIdentify() {stringstream stream_value(stringstream::out); stream_value << hex<<error_code;return "ERROR "+stream_value.str();} protected: Error_str GetLastErrorStr() {return err_str;} // void SetLastError(Error_t dwErrcode) {error_code=dwErrcode;} void SetLastErrorStr(Error_str str) {err_str=str;} private: Error_t error_code; //错误码 Error_str err_str; //辅助错误信息 }; //end of ERRORHANDLER_H_ #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 55 ] ] ]
1286e6634c720af1ade3b026183fbe69d8c5864a
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CV/10591.cpp
bdbc19788776b3589ad6d1f6be217b6f7a13528b
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
805
cpp
///////////////////////////////// // 10591 - Happy Number ///////////////////////////////// #include<cstdio> unsigned short int sumsqod[800]; bool happy[] = {0,1,0,0,0,0,0,1,0,0}; unsigned int cnum,init,n,tnum; unsigned int fsqod(unsigned int k){ unsigned int a,ret=0; while(k){ a = (k%10); ret += a*a; k/=10; } return ret; } unsigned int sqod(unsigned int k){ if(sumsqod[k]) return sumsqod[k]; unsigned int a,ret=0; while(k){ a = (k%10); ret += a*a; k/=10; } sumsqod[n] = ret; return ret; } int main(void){ scanf("%u\n",&tnum); while(tnum--){ scanf("%u",&n); cnum++; init = n; n = fsqod(n); while(n > 9) n = sqod(n); if(happy[n]) printf("Case #%u: %u is a Happy number.\n",cnum,init); else printf("Case #%u: %u is an Unhappy number.\n",cnum,init); } return 0; }
[ [ [ 1, 40 ] ] ]
7aae368b4bf2ba2b6086d3ae9b83521e42703e2c
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/Quake 4 SDK/Quake 4 SDK/source/mpgame/Weapon.cpp
1a1d3d79fad2fbe58a926ac544da0bbc160052d2
[]
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
UTF-8
C++
false
false
94,223
cpp
// RAVEN BEGIN // bdube: note that this file is no longer merged with Doom3 updates // // MERGE_DATE 09/30/2004 #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" #include "Weapon.h" #include "Projectile.h" #include "ai/AI.h" #include "ai/AI_Manager.h" #include "client/ClientEffect.h" //#include "../renderer/tr_local.h" /*********************************************************************** rvViewWeapon ***********************************************************************/ // class def CLASS_DECLARATION( idAnimatedEntity, rvViewWeapon ) EVENT( EV_CallFunction, rvViewWeapon::Event_CallFunction ) END_CLASS /*********************************************************************** init ***********************************************************************/ /* ================ rvViewWeapon::rvViewWeapon() ================ */ rvViewWeapon::rvViewWeapon() { modelDefHandle = -1; weapon = NULL; Clear(); fl.networkSync = true; } /* ================ rvViewWeapon::~rvViewWeapon() ================ */ rvViewWeapon::~rvViewWeapon() { Clear(); } /* ================ rvViewWeapon::Spawn ================ */ void rvViewWeapon::Spawn( void ) { GetPhysics()->SetContents( 0 ); GetPhysics()->SetClipMask( 0 ); GetPhysics()->SetClipModel( NULL, 1.0f ); } /* ================ rvViewWeapon::Save ================ */ void rvViewWeapon::Save( idSaveGame *savefile ) const { int i; savefile->WriteInt ( pendingGUIEvents.Num() ); for ( i = 0; i < pendingGUIEvents.Num(); i ++ ) { savefile->WriteString ( pendingGUIEvents[i] ); } // TOSAVE: const idDeclSkin * saveSkin; // TOSAVE: const idDeclSkin * invisSkin; // TOSAVE: const idDeclSkin * saveWorldSkin; // TOSAVE: const idDeclSkin * worldInvisSkin; // TOSAVE: const idDeclSkin * saveHandsSkin; // TOSAVE: const idDeclSkin * handsSkin; // TOSAVE: friend rvWeapon; // TOSAVE: rvWeapon* weapon; } /* ================ rvViewWeapon::Restore ================ */ void rvViewWeapon::Restore( idRestoreGame *savefile ) { int i; int num; savefile->ReadInt ( num ); pendingGUIEvents.SetNum ( num ); for ( i = 0; i < num; i ++ ) { savefile->ReadString ( pendingGUIEvents[i] ); } } /* =============== rvViewWeapon::ClientPredictionThink =============== */ void rvViewWeapon::ClientPredictionThink( void ) { UpdateAnimation(); } /*********************************************************************** Weapon definition management ***********************************************************************/ /* ================ rvViewWeapon::Clear ================ */ void rvViewWeapon::Clear( void ) { DeconstructScriptObject(); scriptObject.Free(); StopAllEffects( ); // TTimo - the weapon doesn't get a proper Event_DisableWeapon sometimes, so the sound sticks // typically, client side instance join in tourney mode just wipes all ents StopSound( SND_CHANNEL_ANY, false ); memset( &renderEntity, 0, sizeof( renderEntity ) ); renderEntity.entityNum = entityNumber; renderEntity.noShadow = true; renderEntity.noSelfShadow = true; renderEntity.customSkin = NULL; // set default shader parms renderEntity.shaderParms[ SHADERPARM_RED ] = 1.0f; renderEntity.shaderParms[ SHADERPARM_GREEN ]= 1.0f; renderEntity.shaderParms[ SHADERPARM_BLUE ] = 1.0f; renderEntity.shaderParms[3] = 1.0f; renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = 0.0f; renderEntity.shaderParms[5] = 0.0f; renderEntity.shaderParms[6] = 0.0f; renderEntity.shaderParms[7] = 0.0f; memset( &refSound, 0, sizeof( refSound_t ) ); refSound.referenceSoundHandle = -1; // setting diversity to 0 results in no random sound. -1 indicates random. refSound.diversity = -1.0f; if ( weapon && weapon->GetOwner ( ) ) { // don't spatialize the weapon sounds refSound.listenerId = weapon->GetOwner( )->GetListenerId(); } animator.ClearAllAnims( gameLocal.time, 0 ); FreeModelDef(); } /* ===================== rvViewWeapon::GetDebugInfo ===================== */ void rvViewWeapon::GetDebugInfo( debugInfoProc_t proc, void* userData ) { // Base class first idAnimatedEntity::GetDebugInfo( proc, userData ); weapon->GetDebugInfo( proc, userData ); } /*********************************************************************** GUIs ***********************************************************************/ /* ================ rvViewWeapon::PostGUIEvent ================ */ void rvViewWeapon::PostGUIEvent( const char* event ) { pendingGUIEvents.Append ( event ); } /*********************************************************************** Model and muzzleflash ***********************************************************************/ /* ================ rvViewWeapon::SetPowerUpSkin ================ */ void rvViewWeapon::SetPowerUpSkin( const char *name ) { /* FIXME saveSkin = renderEntity.customSkin; renderEntity.customSkin = invisSkin; if ( worldModel.GetEntity() ) { saveWorldSkin = worldModel.GetEntity()->GetSkin(); worldModel.GetEntity()->SetSkin( worldInvisSkin ); } */ } /* ================ rvViewWeapon::UpdateSkin ================ */ void rvViewWeapon::UpdateSkin( void ) { /* FIXME renderEntity.customSkin = saveSkin; if ( worldModel.GetEntity() ) { worldModel.GetEntity()->SetSkin( saveWorldSkin ); } */ } /* ================ rvViewWeapon::SetModel ================ */ void rvViewWeapon::SetModel( const char *modelname, int mods ) { assert( modelname ); if ( modelDefHandle >= 0 ) { gameRenderWorld->RemoveDecals( modelDefHandle ); } renderEntity.hModel = animator.SetModel( modelname ); if ( renderEntity.hModel ) { renderEntity.customSkin = animator.ModelDef()->GetDefaultSkin(); animator.GetJoints( &renderEntity.numJoints, &renderEntity.joints ); } else { renderEntity.customSkin = NULL; renderEntity.callback = NULL; renderEntity.numJoints = 0; renderEntity.joints = NULL; } // hide the model until an animation is played Hide(); } /*********************************************************************** State control/player interface ***********************************************************************/ /* ================ rvViewWeapon::Think ================ */ void rvViewWeapon::Think( void ) { // do nothing because the present is called from the player through PresentWeapon } /* ===================== rvViewWeapon::ConvertLocalToWorldTransform ===================== */ void rvViewWeapon::ConvertLocalToWorldTransform( idVec3 &offset, idMat3 &axis ) { if( !weapon ) { idAnimatedEntity::ConvertLocalToWorldTransform( offset, axis ); return; } offset = GetPhysics()->GetOrigin() + offset * weapon->ForeshortenAxis( GetPhysics()->GetAxis() ); axis *= GetPhysics()->GetAxis(); } /* ================ rvViewWeapon::UpdateModelTransform ================ */ void rvViewWeapon::UpdateModelTransform( void ) { idVec3 origin; idMat3 axis; if( !weapon ) { idAnimatedEntity::UpdateModelTransform(); return; } if ( GetPhysicsToVisualTransform( origin, axis ) ) { renderEntity.axis = axis * weapon->ForeshortenAxis( GetPhysics()->GetAxis() ); renderEntity.origin = GetPhysics()->GetOrigin() + origin * renderEntity.axis; } else { renderEntity.axis = weapon->ForeshortenAxis( GetPhysics()->GetAxis() ); renderEntity.origin = GetPhysics()->GetOrigin(); } } /* ================ rvViewWeapon::PresentWeapon ================ */ void rvViewWeapon::PresentWeapon( bool showViewModel ) { // Dont do anything with the weapon while its stale if ( fl.networkStale ) { return; } // RAVEN BEGIN // rjohnson: cinematics should never be done from the player's perspective, so don't think the weapon ( and their sounds! ) if ( gameLocal.inCinematic ) { return; } // RAVEN END // only show the surface in player view renderEntity.allowSurfaceInViewID = weapon->GetOwner()->entityNumber + 1; // crunch the depth range so it never pokes into walls this breaks the machine gun gui renderEntity.weaponDepthHackInViewID = weapon->GetOwner()->entityNumber + 1; weapon->Think(); // present the model if ( showViewModel && !(weapon->wsfl.zoom && weapon->GetZoomGui() ) ) { Present(); } else { FreeModelDef(); } UpdateSound(); } /* ================ rvViewWeapon::WriteToSnapshot ================ */ void rvViewWeapon::WriteToSnapshot( idBitMsgDelta &msg ) const { } /* ================ rvViewWeapon::ReadFromSnapshot ================ */ void rvViewWeapon::ReadFromSnapshot( const idBitMsgDelta &msg ) { } /* ================ rvViewWeapon::ClientStale ================ */ bool rvViewWeapon::ClientStale ( void ) { StopSound( SND_CHANNEL_ANY, false ); if ( weapon ) { weapon->ClientStale( ); } idEntity::ClientStale( ); return false; } /* ================ rvViewWeapon::ClientReceiveEvent ================ */ bool rvViewWeapon::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) { if ( idEntity::ClientReceiveEvent( event, time, msg ) ) { return true; } if ( weapon ) { return weapon->ClientReceiveEvent ( event, time, msg ); } return false; } /*********************************************************************** Script events ***********************************************************************/ /* ===================== rvViewWeapon::Event_CallFunction ===================== */ void rvViewWeapon::Event_CallFunction( const char *funcname ) { if ( weapon ) { stateParms_t parms = {0}; if ( weapon->ProcessState ( funcname, parms ) == SRESULT_ERROR ) { gameLocal.Error ( "Unknown function '%s' on entity '%s'", funcname, GetName() ); } } } /* ================ rvViewWeapon::SetSkin ================ */ void rvViewWeapon::SetSkin( const char *skinname ) { const idDeclSkin *skinDecl; if ( !skinname || !skinname[ 0 ] ) { skinDecl = NULL; } else { skinDecl = declManager->FindSkin( skinname ); } renderEntity.customSkin = skinDecl; UpdateVisuals(); // Set the skin on the world model as well if ( weapon->GetWorldModel() ) { weapon->GetWorldModel()->SetSkin( skinDecl ); } } void rvViewWeapon::SetSkin( const idDeclSkin* skin ) { renderEntity.customSkin = skin; UpdateVisuals(); if( weapon && weapon->GetWorldModel() ) { weapon->GetWorldModel()->SetSkin( skin ); } } /* ================ rvViewWeapon::GetPosition ================ */ void rvViewWeapon::GetPosition( idVec3& origin, idMat3& axis ) const { origin = GetPhysics()->GetOrigin(); axis = GetPhysics()->GetAxis(); } void rvViewWeapon::SetOverlayShader( const idMaterial* material ) { renderEntity.overlayShader = material; } /*********************************************************************** rvWeapon ***********************************************************************/ CLASS_DECLARATION( idClass, rvWeapon ) END_CLASS /* ================ rvWeapon::rvWeapon ================ */ rvWeapon::rvWeapon ( void ) { viewModel = NULL; worldModel = NULL; weaponDef = NULL; #ifdef _XENON aimAssistFOV = 10.0f; #endif memset ( &animDoneTime, 0, sizeof(animDoneTime) ); memset ( &wsfl, 0, sizeof(wsfl) ); memset ( &wfl, 0, sizeof(wfl) ); hitscanAttackDef = -1; forceGUIReload = false; } /* ================ rvWeapon::~rvWeapon ================ */ rvWeapon::~rvWeapon( void ) { int i; // Free all current light defs for ( i = 0; i < WPLIGHT_MAX; i ++ ) { FreeLight ( i ); } // Disassociate with the view model if ( viewModel ) { StopSound( SND_CHANNEL_ANY, false ); viewModel->weapon = NULL; } } /* ================ rvWeapon::Init ================ */ void rvWeapon::Init( idPlayer* _owner, const idDeclEntityDef* def, int _weaponIndex, bool _isStrogg ) { int i; viewModel = _owner->GetWeaponViewModel( ); worldModel = _owner->GetWeaponWorldModel( ); weaponDef = def; owner = _owner; scriptObject = &viewModel->scriptObject; weaponIndex = _weaponIndex; mods = owner->inventory.weaponMods[ weaponIndex ]; isStrogg = _isStrogg; spawnArgs = weaponDef->dict; #ifdef _XENON aimAssistFOV = spawnArgs.GetFloat( "aimAssistFOV", "10.0f" ); #endif // Apply the mod dictionaries for ( i = 0; i < MAX_WEAPONMODS; i ++ ) { const idDict* modDict; if ( !(mods & (1<<i) ) ) { continue; } const char* mod; if ( !spawnArgs.GetString ( va("def_mod%d", i+1), "", &mod ) || !*mod ) { continue; } modDict = gameLocal.FindEntityDefDict ( mod, false ); if ( !modDict ) { continue; } spawnArgs.Copy ( *modDict ); } // Associate the weapon with the view model viewModel->weapon = this; } /* ================ rvWeapon::FindViewModelPositionStyle ================ */ void rvWeapon::FindViewModelPositionStyle( idVec3& viewOffset, idAngles& viewAngles ) const { int viewStyle = g_gunViewStyle.GetInteger(); const char* styleDefName = spawnArgs.GetString( va("def_viewStyle%d", viewStyle) ); const idDict* styleDef = gameLocal.FindEntityDefDict( styleDefName, false ); if( !styleDef ) { styleDefName = spawnArgs.GetString( "def_viewStyle" ); styleDef = gameLocal.FindEntityDefDict( styleDefName, false ); } assert( styleDef ); viewAngles = styleDef->GetAngles( "viewangles" ); viewOffset = styleDef->GetVector( "viewoffset" ); } /* ================ rvWeapon::Spawn ================ */ void rvWeapon::Spawn ( void ) { memset ( &wsfl, 0, sizeof(wsfl) ); memset ( &wfl, 0, sizeof(wfl) ); // RAVEN BEGIN // nrausch: #if defined(_XENON) aimAssistFOV = spawnArgs.GetFloat( "aimAssistFOV", "10.0f" ); #endif // RAVEN END // Initialize variables projectileEnt = NULL; kick_endtime = 0; hideStart = 0.0f; hideEnd = 0.0f; hideOffset = 0.0f; status = WP_HOLSTERED; lastAttack = 0; clipPredictTime = 0; muzzleAxis.Identity(); muzzleOrigin.Zero(); pushVelocity.Zero(); playerViewAxis.Identity(); playerViewOrigin.Zero(); viewModelAxis.Identity(); viewModelOrigin.Zero(); // View viewModelForeshorten = spawnArgs.GetFloat ( "foreshorten", "1" ); FindViewModelPositionStyle( viewModelOffset, viewModelAngles ); // Offsets weaponAngleOffsetAverages = spawnArgs.GetInt( "weaponAngleOffsetAverages", "10" ); weaponAngleOffsetScale = spawnArgs.GetFloat( "weaponAngleOffsetScale", "0.25" ); weaponAngleOffsetMax = spawnArgs.GetFloat( "weaponAngleOffsetMax", "10" ); weaponOffsetTime = spawnArgs.GetFloat( "weaponOffsetTime", "400" ); weaponOffsetScale = spawnArgs.GetFloat( "weaponOffsetScale", "0.005" ); fireRate = SEC2MS ( spawnArgs.GetFloat ( "fireRate" ) ); altFireRate = SEC2MS ( spawnArgs.GetFloat ( "altFireRate" ) ); if( altFireRate == 0 ) { altFireRate = fireRate; } spread = (gameLocal.IsMultiplayer()&&spawnArgs.FindKey("spread_mp"))?spawnArgs.GetFloat ( "spread_mp" ):spawnArgs.GetFloat ( "spread" ); nextAttackTime = 0; // Zoom zoomFov = spawnArgs.GetInt( "zoomFov", "-1" ); zoomGui = uiManager->FindGui ( spawnArgs.GetString ( "gui_zoom", "" ), true ); zoomTime = spawnArgs.GetFloat ( "zoomTime", ".15" ); wfl.zoomHideCrosshair = spawnArgs.GetBool ( "zoomHideCrosshair", "1" ); // Attack related values muzzle_kick_time = SEC2MS( spawnArgs.GetFloat( "muzzle_kick_time" ) ); muzzle_kick_maxtime = SEC2MS( spawnArgs.GetFloat( "muzzle_kick_maxtime" ) ); muzzle_kick_angles = spawnArgs.GetAngles( "muzzle_kick_angles" ); muzzle_kick_offset = spawnArgs.GetVector( "muzzle_kick_offset" ); // General weapon properties wfl.silent_fire = spawnArgs.GetBool( "silent_fire" ); wfl.hasWindupAnim = spawnArgs.GetBool( "has_windup", "0" ); icon = spawnArgs.GetString( "mtr_icon" ); hideTime = SEC2MS( weaponDef->dict.GetFloat( "hide_time", "0.3" ) ); hideDistance = weaponDef->dict.GetFloat( "hide_distance", "-15" ); hideStartTime = gameLocal.time - hideTime; muzzleOffset = weaponDef->dict.GetFloat ( "muzzleOffset", "14" ); // Ammo clipSize = spawnArgs.GetInt( "clipSize" ); ammoRequired = spawnArgs.GetInt( "ammoRequired" ); lowAmmo = spawnArgs.GetInt( "lowAmmo" ); ammoType = GetAmmoIndexForName( spawnArgs.GetString( "ammoType" ) ); maxAmmo = owner->inventory.MaxAmmoForAmmoClass ( owner, GetAmmoNameForIndex ( ammoType ) ); if ( ( ammoType < 0 ) || ( ammoType >= MAX_AMMO ) ) { gameLocal.Warning( "Unknown ammotype for class '%s'", this->GetClassname ( ) ); } // If the weapon has a clip, then fill it up ammoClip = owner->inventory.clip[weaponIndex]; if ( ( ammoClip < 0 ) || ( ammoClip > clipSize ) ) { // first time using this weapon so have it fully loaded to start ammoClip = clipSize; int ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired ); if ( ammoClip > ammoAvail ) { ammoClip = ammoAvail; } } // Complex initializations Initialize InitDefs( ); InitWorldModel( ); InitViewModel( ); // Requires the view model so must be done after it InitLights( ); viewModel->PostGUIEvent( "weapon_init" ); viewModel->PostGUIEvent( "weapon_ammo" ); if ( ammoClip == 0 && AmmoAvailable() == 0 ) { viewModel->PostGUIEvent( "weapon_noammo" ); } stateThread.SetName( va("%s_%s_%s", owner->GetName(), viewModel->GetName ( ), spawnArgs.GetString("classname") ) ); stateThread.SetOwner( this ); forceGUIReload = true; } /* ================ rvWeapon::InitViewModel ================ */ void rvWeapon::InitViewModel( void ) { const char* guiName; const char* temp; int i; const idKeyValue* kv; // Reset view model to clean state viewModel->Clear ( ); // Make sure the sound handle is initted viewModel->refSound.referenceSoundHandle = -1; // Intialize the weapon guis if ( spawnArgs.GetString ( "gui", "", &guiName ) ) { int g = 0; do { viewModel->GetRenderEntity()->gui[g++] = uiManager->FindGui ( guiName, true, false, true ); guiName = spawnArgs.GetString ( va("gui%d", g + 1 ) ); } while ( *guiName && viewModel->GetRenderEntity()->gui[g-1] ); } // Set the view models spawn args viewModel->spawnArgs = weaponDef->dict; // Set the model for the view model if ( isStrogg ) { temp = spawnArgs.GetString ( "model_view_strogg", spawnArgs.GetString ( "model_view" ) ); } else { temp = spawnArgs.GetString ( "model_view" ); } viewModel->SetModel( temp, mods ); // Hide surfaces for ( kv = spawnArgs.MatchPrefix ( "hidesurface", NULL ); kv; kv = spawnArgs.MatchPrefix ( "hidesurface", kv ) ) { viewModel->ProcessEvent ( &EV_HideSurface, kv->GetValue() ); } // Show and Hide the mods for ( i = 0; i < MAX_WEAPONMODS; i ++ ) { const idDict* modDict = gameLocal.FindEntityDefDict ( spawnArgs.GetString ( va("def_mod%d", i+1) ), false ); if ( !modDict ) { continue; } // Hide any show surfaces for mods that arent on if ( !(mods & (1<<i)) ) { for ( kv = modDict->MatchPrefix ( "mod_showsurface", NULL ); kv; kv = modDict->MatchPrefix ( "mod_showsurface", kv ) ) { viewModel->ProcessEvent ( &EV_HideSurface, kv->GetValue() ); // NOTE: HIDING them because we don't have this mod yet } } else { for ( kv = modDict->MatchPrefix ( "mod_hidesurface", NULL ); kv; kv = modDict->MatchPrefix ( "mod_hidesurface", kv ) ) { viewModel->ProcessEvent ( &EV_HideSurface, kv->GetValue() ); } } } // find some joints in the model for locating effects viewAnimator = viewModel->GetAnimator ( ); barrelJointView = viewAnimator->GetJointHandle( spawnArgs.GetString ( "joint_view_barrel", "barrel" ) ); flashJointView = viewAnimator->GetJointHandle( spawnArgs.GetString ( "joint_view_flash", "flash" ) ); ejectJointView = viewAnimator->GetJointHandle( spawnArgs.GetString ( "joint_view_eject", "eject" ) ); guiLightJointView = viewAnimator->GetJointHandle( spawnArgs.GetString ( "joint_view_guiLight", "guiLight" ) ); flashlightJointView = viewAnimator->GetJointHandle( spawnArgs.GetString ( "joint_view_flashlight", "flashlight" ) ); // Eject offset spawnArgs.GetVector ( "ejectOffset", "0 0 0", ejectOffset ); // Setup a skin for the view model if ( spawnArgs.GetString ( "skin", "", &temp ) ) { viewModel->GetRenderEntity()->customSkin = declManager->FindSkin ( temp ); } // make sure we have the correct skin viewModel->UpdateSkin(); } /* ================ rvWeapon::InitLights ================ */ void rvWeapon::InitLights ( void ) { const char* shader; idVec4 color; renderLight_t* light; memset ( lights, 0, sizeof(lights) ); memset ( lightHandles, -1, sizeof(lightHandles) ); // setup gui light light = &lights[WPLIGHT_GUI]; shader = spawnArgs.GetString( "mtr_guiLightShader", "" ); if ( shader && *shader && viewModel->GetRenderEntity()->gui[0] ) { light->shader = declManager->FindMaterial( shader, false ); light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = spawnArgs.GetFloat("glightRadius", "3" ); color = viewModel->GetRenderEntity()->gui[0]->GetLightColor ( ); light->shaderParms[ SHADERPARM_RED ] = color[0] * color[3]; light->shaderParms[ SHADERPARM_GREEN ] = color[1] * color[3]; light->shaderParms[ SHADERPARM_BLUE ] = color[2] * color[3]; light->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; light->pointLight = true; // RAVEN BEGIN // dluetscher: added detail levels to render lights light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; // dluetscher: changed lights to no shadow for performance reasons light->noShadows = true; // RAVEN END light->lightId = WPLIGHT_GUI * 100 + owner->entityNumber; light->allowLightInViewID = owner->entityNumber+1; spawnArgs.GetVector ( "glightOffset", "0 0 0", guiLightOffset ); } // Muzzle flash light = &lights[WPLIGHT_MUZZLEFLASH]; shader = spawnArgs.GetString( "mtr_flashShader", "muzzleflash" ); if ( shader && *shader ) { light->shader = declManager->FindMaterial( shader, false ); spawnArgs.GetVec4( "flashColor", "0 0 0 0", color ); light->shaderParms[ SHADERPARM_RED ] = color[0]; light->shaderParms[ SHADERPARM_GREEN ] = color[1]; light->shaderParms[ SHADERPARM_BLUE ] = color[2]; light->shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f; light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = (float)spawnArgs.GetInt( "flashRadius" ); // RAVEN BEGIN // dluetscher: added detail levels to render lights light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; // dluetscher: changed lights to no shadow for performance reasons light->noShadows = true; // RAVEN END light->pointLight = spawnArgs.GetBool( "flashPointLight", "1" ); if ( !light->pointLight ) { light->target = spawnArgs.GetVector ( "flashTarget" ); light->up = spawnArgs.GetVector ( "flashUp" ); light->right = spawnArgs.GetVector ( "flashRight" ); light->end = light->target; } light->lightId = WPLIGHT_MUZZLEFLASH * 100 + owner->entityNumber; light->allowLightInViewID = owner->entityNumber+1; muzzleFlashTime = SEC2MS( spawnArgs.GetFloat( "flashTime", "0.25" ) ); muzzleFlashEnd = 0; spawnArgs.GetVector ( "flashViewOffset", "0 0 0", muzzleFlashViewOffset ); } // the world muzzle flash is the same, just positioned differently lights[WPLIGHT_MUZZLEFLASH_WORLD] = lights[WPLIGHT_MUZZLEFLASH]; light = &lights[WPLIGHT_MUZZLEFLASH_WORLD]; light->suppressLightInViewID = owner->entityNumber+1; light->allowLightInViewID = 0; light->lightId = WPLIGHT_MUZZLEFLASH_WORLD * 100 + owner->entityNumber; // flashlight light = &lights[WPLIGHT_FLASHLIGHT]; shader = spawnArgs.GetString( "mtr_flashlightShader", "lights/muzzleflash" ); if ( shader && *shader ) { light->shader = declManager->FindMaterial( shader, false ); spawnArgs.GetVec4( "flashlightColor", "0 0 0 0", color ); light->shaderParms[ SHADERPARM_RED ] = color[0]; light->shaderParms[ SHADERPARM_GREEN ] = color[1]; light->shaderParms[ SHADERPARM_BLUE ] = color[2]; light->shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f; light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = (float)spawnArgs.GetInt( "flashlightRadius" ); // RAVEN BEGIN // dluetscher: added detail levels to render lights light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; // dluetscher: changed lights to no shadow for performance reasons light->noShadows = cvarSystem->GetCVarInteger("com_machineSpec") < 3; // RAVEN END light->pointLight = spawnArgs.GetBool( "flashlightPointLight", "1" ); if ( !light->pointLight ) { light->target = spawnArgs.GetVector( "flashlightTarget" ); light->up = spawnArgs.GetVector( "flashlightUp" ); light->right = spawnArgs.GetVector( "flashlightRight" ); light->end = light->target; } light->allowLightInViewID = owner->entityNumber+1; light->lightId = WPLIGHT_FLASHLIGHT * 100 + owner->entityNumber; spawnArgs.GetVector ( "flashlightViewOffset", "0 0 0", flashlightViewOffset ); } // the world muzzle flashlight is the same, just positioned differently lights[WPLIGHT_FLASHLIGHT_WORLD] = lights[WPLIGHT_FLASHLIGHT]; light = &lights[WPLIGHT_FLASHLIGHT_WORLD]; light->suppressLightInViewID = owner->entityNumber+1; light->allowLightInViewID = 0; light->lightId = WPLIGHT_FLASHLIGHT_WORLD * 100 + owner->entityNumber; } /* ================ rvWeapon::InitDefs ================ */ void rvWeapon::InitDefs( void ) { const char* name; const idDeclEntityDef* def; const char* spawnclass; idTypeInfo* cls; // get the projectile attackDict.Clear(); // Projectile if ( spawnArgs.GetString( "def_projectile", "", &name ) && *name ) { def = gameLocal.FindEntityDef( name, false ); if ( !def ) { gameLocal.Warning( "Unknown projectile '%s' for weapon '%s'", name, weaponDef->GetName() ); } else { spawnclass = def->dict.GetString( "spawnclass" ); cls = idClass::GetClass( spawnclass ); if ( !cls || !cls->IsType( idProjectile::GetClassType() ) ) { gameLocal.Warning( "Invalid spawnclass '%s' for projectile '%s' (used by weapon '%s')", spawnclass, name, weaponDef->GetName ( ) ); } else { attackDict = def->dict; } } } else if ( spawnArgs.GetString( "def_hitscan", "", &name ) && *name ) { def = gameLocal.FindEntityDef( name, false ); if ( !def ) { gameLocal.Warning( "Unknown hitscan '%s' for weapon '%s'", name, weaponDef->GetName ( ) ); } else { attackDict = def->dict; hitscanAttackDef = def->Index(); } wfl.attackHitscan = true; } // Alternate projectile attackAltDict.Clear (); if ( spawnArgs.GetString( "def_altprojectile", "", &name ) && *name ) { def = gameLocal.FindEntityDef( name, false ); if ( !def ) { gameLocal.Warning( "Unknown alt projectile '%s' for weapon '%s'", name, weaponDef->GetName() ); } else { spawnclass = def->dict.GetString( "spawnclass" ); cls = idClass::GetClass( spawnclass ); if ( !cls || !cls->IsType( idProjectile::GetClassType() ) ) { gameLocal.Warning( "Invalid spawnclass '%s' for alt projectile '%s' (used by weapon '%s')", spawnclass, name, weaponDef->GetName ( ) ); } else { attackAltDict = def->dict; } } } else if ( spawnArgs.GetString( "def_althitscan", "", &name ) && *name ) { def = gameLocal.FindEntityDef( name, false ); if ( !def ) { gameLocal.Warning( "Unknown hitscan '%s' for weapon '%s'", name, weaponDef->GetName ( ) ); } else { attackAltDict = def->dict; } wfl.attackAltHitscan = true; } // get the melee damage def meleeDistance = spawnArgs.GetFloat( "melee_distance" ); if ( spawnArgs.GetString( "def_melee", "", &name ) && *name ) { meleeDef = gameLocal.FindEntityDef( name, false ); if ( !meleeDef ) { gameLocal.Error( "Unknown melee '%s' for weapon '%s'", name, weaponDef->GetName() ); } } else { meleeDef = NULL; } // get the brass def brassDict.Clear(); if ( spawnArgs.GetString( "def_ejectBrass", "", &name ) && *name ) { def = gameLocal.FindEntityDef( name, false ); if ( !def ) { gameLocal.Warning( "Unknown brass def '%s' for weapon '%s'", name, weaponDef->GetName() ); } else { brassDict = def->dict; // force any brass to spawn as client moveable brassDict.Set( "spawnclass", "rvClientMoveable" ); } } } /* ================ rvWeapon::Think ================ */ void rvWeapon::Think ( void ) { // Cache the player origin and axis playerViewOrigin = owner->firstPersonViewOrigin; playerViewAxis = owner->firstPersonViewAxis; // calculate weapon position based on player movement bobbing owner->CalculateViewWeaponPos( viewModelOrigin, viewModelAxis ); // hide offset is for dropping the gun when approaching a GUI or NPC // This is simpler to manage than doing the weapon put-away animation if ( gameLocal.time - hideStartTime < hideTime ) { float frac = ( float )( gameLocal.time - hideStartTime ) / ( float )hideTime; if ( hideStart < hideEnd ) { frac = 1.0f - frac; frac = 1.0f - frac * frac; } else { frac = frac * frac; } hideOffset = hideStart + ( hideEnd - hideStart ) * frac; } else { hideOffset = hideEnd; } viewModelOrigin += hideOffset * viewModelAxis[ 2 ]; // kick up based on repeat firing MuzzleRise( viewModelOrigin, viewModelAxis ); if ( viewModel ) { // set the physics position and orientation viewModel->GetPhysics()->SetOrigin( viewModelOrigin ); viewModel->GetPhysics()->SetAxis( viewModelAxis ); viewModel->UpdateVisuals(); } else { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); } // Update the zoom variable before updating the script wsfl.zoom = owner->IsZoomed( ); // Only update the state loop on new frames if ( gameLocal.isNewFrame ) { stateThread.Execute( ); } if ( viewModel ) { viewModel->UpdateAnimation( ); } // Clear reload and flashlight flags wsfl.reload = false; wsfl.flashlight = false; // deal with the third-person visible world model // don't show shadows of the world model in first person if ( worldModel && worldModel->GetRenderEntity() ) { // always show your own weapon if( owner->entityNumber == gameLocal.localClientNum ) { worldModel->GetRenderEntity()->suppressLOD = 1; } else { worldModel->GetRenderEntity()->suppressLOD = 0; } if ( gameLocal.IsMultiplayer() && g_skipPlayerShadowsMP.GetBool() ) { // Disable all weapon shadows for the local client worldModel->GetRenderEntity()->suppressShadowInViewID = gameLocal.localClientNum+1; worldModel->GetRenderEntity()->suppressShadowInLightID = WPLIGHT_MUZZLEFLASH * 100 + owner->entityNumber; } else if ( gameLocal.isMultiplayer || g_showPlayerShadow.GetBool() || pm_thirdPerson.GetBool() ) { // Show all weapon shadows worldModel->GetRenderEntity()->suppressShadowInViewID = 0; } else { // Only show weapon shadows for other clients worldModel->GetRenderEntity()->suppressShadowInViewID = owner->entityNumber+1; worldModel->GetRenderEntity()->suppressShadowInLightID = WPLIGHT_MUZZLEFLASH * 100 + owner->entityNumber; } } UpdateGUI(); // Update lights UpdateFlashlight ( ); UpdateMuzzleFlash ( ); // update the gui light renderLight_t& light = lights[WPLIGHT_GUI]; if ( light.lightRadius[0] && guiLightJointView != INVALID_JOINT ) { if ( viewModel ) { idVec4 color = viewModel->GetRenderEntity()->gui[0]->GetLightColor ( ); light.shaderParms[ SHADERPARM_RED ] = color[0] * color[3]; light.shaderParms[ SHADERPARM_GREEN ] = color[1] * color[3]; light.shaderParms[ SHADERPARM_BLUE ] = color[2] * color[3]; GetGlobalJointTransform( true, guiLightJointView, light.origin, light.axis, guiLightOffset ); UpdateLight ( WPLIGHT_GUI ); } else { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); } } // Alert Monsters if the flashlight is one or a muzzle flash is active? if ( !gameLocal.isMultiplayer ) { if ( !owner->fl.notarget && (lightHandles[WPLIGHT_MUZZLEFLASH] != -1 || lightHandles[WPLIGHT_FLASHLIGHT] != -1 ) ) { AlertMonsters ( ); } } } /* ================ rvWeapon::InitWorldModel ================ */ void rvWeapon::InitWorldModel( void ) { idEntity *ent; ent = worldModel; if ( !ent ) { gameLocal.Warning ( "InitWorldModel failed due to missing entity" ); return; } const char *model = spawnArgs.GetString( "model_world" ); const char *attach = spawnArgs.GetString( "joint_attach" ); if ( model[0] && attach[0] ) { ent->Show(); ent->SetModel( model ); ent->GetPhysics()->SetContents( 0 ); ent->GetPhysics()->SetClipModel( NULL, 1.0f ); ent->BindToJoint( owner, attach, true ); ent->GetPhysics()->SetOrigin( vec3_origin ); ent->GetPhysics()->SetAxis( mat3_identity ); // supress model in player views, but allow it in mirrors and remote views renderEntity_t *worldModelRenderEntity = ent->GetRenderEntity(); if ( worldModelRenderEntity ) { worldModelRenderEntity->suppressSurfaceInViewID = owner->entityNumber+1; worldModelRenderEntity->suppressShadowInViewID = owner->entityNumber+1; worldModelRenderEntity->suppressShadowInLightID = WPLIGHT_MUZZLEFLASH * 100 + owner->entityNumber; } } else { ent->SetModel( "" ); ent->Hide(); } // the renderEntity is reused, so the relevant fields (except this one) appear to be correctly reinitialized worldModel->GetRenderEntity()->suppressSurfaceMask = 0; // Cache the world joints worldAnimator = ent->GetAnimator ( ); flashJointWorld = worldAnimator->GetJointHandle ( spawnArgs.GetString ( "joint_world_flash", "flash" ) ); flashlightJointWorld = worldAnimator->GetJointHandle ( spawnArgs.GetString ( "joint_world_flashlight", "flashlight" ) ); ejectJointWorld = worldAnimator->GetJointHandle ( spawnArgs.GetString ( "joint_world_eject", "eject" ) ); } /* ================ rvWeapon::SetState ================ */ void rvWeapon::SetState( const char *statename, int blendFrames ) { stateThread.SetState( statename, blendFrames ); } /* ================ rvWeapon::PostState ================ */ void rvWeapon::PostState( const char* statename, int blendFrames ) { stateThread.PostState( statename, blendFrames ); } /* ===================== rvWeapon::ExecuteState ===================== */ void rvWeapon::ExecuteState ( const char* statename ) { SetState ( statename, 0 ); stateThread.Execute ( ); } /* ================ rvWeapon::UpdateLight ================ */ void rvWeapon::UpdateLight ( int lightID ) { if ( lightHandles[lightID] == -1 ) { lightHandles[lightID] = gameRenderWorld->AddLightDef ( &lights[lightID] ); } else { gameRenderWorld->UpdateLightDef( lightHandles[lightID], &lights[lightID] ); } } /* ================ rvWeapon::FreeLight ================ */ void rvWeapon::FreeLight ( int lightID ) { if ( lightHandles[lightID] != -1 ) { gameRenderWorld->FreeLightDef( lightHandles[lightID] ); lightHandles[lightID] = -1; } } /*********************************************************************** Networking ***********************************************************************/ /* ================ rvWeapon::WriteToSnapshot ================ */ void rvWeapon::WriteToSnapshot( idBitMsgDelta &msg ) const { // this can probably be reduced a bit, there's no clip/reload in MP // it seems that's used to drive some of the weapon model firing animations though (such as RL) msg.WriteBits( ammoClip, ASYNC_PLAYER_INV_CLIP_BITS ); } /* ================ rvWeapon::ReadFromSnapshot ================ */ void rvWeapon::ReadFromSnapshot( const idBitMsgDelta &msg ) { ammoClip = msg.ReadBits( ASYNC_PLAYER_INV_CLIP_BITS ); } /* ================ rvWeapon::SkipFromSnapshot ================ */ void rvWeapon::SkipFromSnapshot ( const idBitMsgDelta &msg ) { msg.ReadBits( ASYNC_PLAYER_INV_CLIP_BITS ); } /* ================ rvWeapon::ClientStale ================ */ void rvWeapon::ClientStale( void ) { } /* ================ rvWeapon::ClientReceiveEvent ================ */ bool rvWeapon::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) { switch( event ) { case EVENT_RELOAD: { if ( gameLocal.time - time < 1000 ) { wsfl.netReload = true; wsfl.netEndReload = false; } return true; } case EVENT_ENDRELOAD: { wsfl.netEndReload = true; return true; } case EVENT_CHANGESKIN: { /* // FIXME: use idGameLocal::ReadDecl int index = msg.ReadLong(); renderEntity.customSkin = ( index != -1 ) ? static_cast<const idDeclSkin *>( declManager->DeclByIndex( DECL_SKIN, index ) ) : NULL; UpdateVisuals(); if ( worldModel.GetEntity() ) { worldModel.GetEntity()->SetSkin( renderEntity.customSkin ); } */ return true; } } return false; } /*********************************************************************** Save / Load ***********************************************************************/ /* ================ rvWeapon::Save ================ */ void rvWeapon::Save ( idSaveGame *savefile ) const { int i; // Flags savefile->Write ( &wsfl, sizeof( wsfl ) ); savefile->Write ( &wfl, sizeof( wfl ) ); // Write all cached joints savefile->WriteJoint ( barrelJointView ); savefile->WriteJoint ( flashJointView ); savefile->WriteJoint ( ejectJointView ); savefile->WriteJoint ( guiLightJointView ); savefile->WriteJoint ( flashlightJointView ); savefile->WriteJoint ( flashJointWorld ); savefile->WriteJoint ( ejectJointWorld ); savefile->WriteJoint ( flashlightJointWorld ); savefile->WriteInt ( status ); savefile->WriteInt ( lastAttack ); // Hide / Show savefile->WriteInt ( hideTime ); savefile->WriteFloat ( hideDistance ); savefile->WriteInt ( hideStartTime ); savefile->WriteFloat ( hideStart ); savefile->WriteFloat ( hideEnd ); savefile->WriteFloat ( hideOffset ); // Write attack related values savefile->WriteVec3 ( pushVelocity ); savefile->WriteInt ( kick_endtime ); savefile->WriteInt ( muzzle_kick_time ); savefile->WriteInt ( muzzle_kick_maxtime ); savefile->WriteAngles ( muzzle_kick_angles ); savefile->WriteVec3 ( muzzle_kick_offset ); savefile->WriteVec3 ( muzzleOrigin ); savefile->WriteMat3 ( muzzleAxis ); savefile->WriteFloat ( muzzleOffset ); projectileEnt.Save ( savefile ); savefile->WriteVec3 ( ejectOffset ); // cnicholson: Added unsaved var savefile->WriteInt ( fireRate ); savefile->WriteFloat ( spread ); // savefile->WriteInt ( nextAttackTime ); // cnicholson: This is set to 0 in restore, so don't save it // cnicholson: These 3 idDicts are setup during restore, no need to save them. // TOSAVE: idDict attackAltDict; // TOSAVE: idDict attackDict; // TOSAVE: idDict brassDict; // Defs // TOSAVE: const idDeclEntityDef * meleeDef; // cnicholson: This is setup in restore, so don't save it savefile->WriteFloat ( meleeDistance ); // Zoom savefile->WriteInt ( zoomFov ); savefile->WriteUserInterface ( zoomGui, true ); savefile->WriteFloat ( zoomTime ); // Lights for ( i = 0; i < WPLIGHT_MAX; i ++ ) { savefile->WriteInt( lightHandles[i] ); savefile->WriteRenderLight( lights[i] ); } savefile->WriteVec3 ( guiLightOffset ); savefile->WriteInt ( muzzleFlashEnd ); savefile->WriteInt ( muzzleFlashTime ); savefile->WriteVec3 ( muzzleFlashViewOffset ); savefile->WriteVec3 ( flashlightViewOffset ); savefile->WriteBool ( flashlightOn ); // cnicholson: Added unsaved var savefile->WriteVec3 ( flashlightViewOffset ); // cnicholson: Added unsaved var // Write ammo values savefile->WriteInt ( ammoType ); savefile->WriteInt ( ammoRequired ); savefile->WriteInt ( clipSize ); savefile->WriteInt ( ammoClip ); savefile->WriteInt ( lowAmmo ); savefile->WriteInt ( maxAmmo ); // multiplayer savefile->WriteInt ( clipPredictTime ); // TOSAVE: Save MP value? // View savefile->WriteVec3 ( playerViewOrigin ); savefile->WriteMat3 ( playerViewAxis ); savefile->WriteVec3 ( viewModelOrigin ); savefile->WriteMat3 ( viewModelAxis ); savefile->WriteAngles ( viewModelAngles ); savefile->WriteVec3 ( viewModelOffset ); // cnicholson: Added unsaved var // Offsets savefile->WriteInt ( weaponAngleOffsetAverages ); savefile->WriteFloat ( weaponAngleOffsetScale ); savefile->WriteFloat ( weaponAngleOffsetMax ); savefile->WriteFloat ( weaponOffsetTime ); savefile->WriteFloat ( weaponOffsetScale ); savefile->WriteString ( icon ); savefile->WriteBool ( isStrogg ); // TOSAVE: idDict spawnArgs; // TOSAVE: idEntityPtr<rvViewWeapon> viewModel; // cnicholson: Setup in restore, no need to save // TOSAVE: idAnimator* viewAnimator; // TOSAVE: idEntityPtr<idAnimatedEntity> worldModel; // cnicholson: Setup in restore, no need to save // TOSAVE: idAnimator* worldAnimator; // TOSAVE: const idDeclEntityDef* weaponDef; // TOSAVE: idScriptObject* scriptObject; savefile->WriteObject ( owner ); savefile->WriteInt ( weaponIndex ); // cnicholson: Added unsaved var savefile->WriteInt ( mods ); // cnicholson: Added unsaved var savefile->WriteFloat ( viewModelForeshorten ); stateThread.Save( savefile ); for ( i = 0; i < ANIM_NumAnimChannels; i++ ) { savefile->WriteInt( animDoneTime[i] ); } savefile->WriteInt ( methodOfDeath ); // cnicholson: Added unsaved var } /* ================ rvWeapon::Restore ================ */ void rvWeapon::Restore ( idRestoreGame *savefile ) { int i; const idDeclEntityDef* def; // General savefile->Read ( &wsfl, sizeof( wsfl ) ); savefile->Read ( &wfl, sizeof( wfl ) ); // Read cached joints savefile->ReadJoint ( barrelJointView ); savefile->ReadJoint ( flashJointView ); savefile->ReadJoint ( ejectJointView ); savefile->ReadJoint ( guiLightJointView ); savefile->ReadJoint ( flashlightJointView ); savefile->ReadJoint ( flashJointWorld ); savefile->ReadJoint ( ejectJointWorld ); savefile->ReadJoint ( flashlightJointWorld ); savefile->ReadInt ( (int&)status ); savefile->ReadInt ( lastAttack ); // Hide / Show savefile->ReadInt ( hideTime ); savefile->ReadFloat ( hideDistance ); savefile->ReadInt ( hideStartTime ); savefile->ReadFloat ( hideStart ); savefile->ReadFloat ( hideEnd ); savefile->ReadFloat ( hideOffset ); // Read attack related values savefile->ReadVec3 ( pushVelocity ); savefile->ReadInt ( kick_endtime ); savefile->ReadInt ( muzzle_kick_time ); savefile->ReadInt ( muzzle_kick_maxtime ); savefile->ReadAngles ( muzzle_kick_angles ); savefile->ReadVec3 ( muzzle_kick_offset ); savefile->ReadVec3 ( muzzleOrigin ); savefile->ReadMat3 ( muzzleAxis ); savefile->ReadFloat ( muzzleOffset ); projectileEnt.Restore ( savefile ); savefile->ReadVec3 ( ejectOffset ); // cnicholson: Added unrestored var savefile->ReadInt ( fireRate ); savefile->ReadFloat ( spread ); nextAttackTime = 0; // Attack Alt Def attackAltDict.Clear( ); wfl.attackAltHitscan = false; def = gameLocal.FindEntityDef( spawnArgs.GetString( "def_altprojectile" ), false ); if ( def ) { attackAltDict = def->dict; } else { def = gameLocal.FindEntityDef( spawnArgs.GetString( "def_althitscan" ), false ); if ( def ) { attackAltDict = def->dict; wfl.attackAltHitscan = true; } } // Attack def attackDict.Clear( ); def = gameLocal.FindEntityDef( spawnArgs.GetString( "def_projectile" ), false ); wfl.attackHitscan = false; if ( def ) { attackDict = def->dict; } else { def = gameLocal.FindEntityDef( spawnArgs.GetString( "def_hitscan" ), false ); if ( def ) { attackDict = def->dict; wfl.attackHitscan = true; } } // Brass Def def = gameLocal.FindEntityDef( spawnArgs.GetString( "def_ejectBrass" ), false ); if ( def ) { brassDict = def->dict; } else { brassDict.Clear(); } // Melee Def meleeDef = gameLocal.FindEntityDef( spawnArgs.GetString( "def_melee" ), false ); savefile->ReadFloat( meleeDistance ); // Zoom savefile->ReadInt ( zoomFov ); savefile->ReadUserInterface ( zoomGui, &spawnArgs ); savefile->ReadFloat ( zoomTime ); // Lights for ( i = 0; i < WPLIGHT_MAX; i ++ ) { savefile->ReadInt ( lightHandles[i] ); savefile->ReadRenderLight( lights[i] ); if ( lightHandles[i] != -1 ) { //get the handle again as it's out of date after a restore! lightHandles[i] = gameRenderWorld->AddLightDef ( &lights[i] ); } } savefile->ReadVec3 ( guiLightOffset ); savefile->ReadInt ( muzzleFlashEnd ); savefile->ReadInt ( muzzleFlashTime ); savefile->ReadVec3 ( muzzleFlashViewOffset ); savefile->ReadVec3 ( flashlightViewOffset ); savefile->ReadBool ( flashlightOn ); // cnicholson: Added unrestored var savefile->ReadVec3 ( flashlightViewOffset ); // cnicholson: Added unrestored var // Read the ammo values savefile->ReadInt ( (int&)ammoType ); savefile->ReadInt ( ammoRequired ); savefile->ReadInt ( clipSize ); savefile->ReadInt ( ammoClip ); savefile->ReadInt ( lowAmmo ); savefile->ReadInt ( maxAmmo ); // multiplayer savefile->ReadInt ( clipPredictTime ); // TORESTORE: Restore MP value? // View savefile->ReadVec3 ( playerViewOrigin ); savefile->ReadMat3 ( playerViewAxis ); savefile->ReadVec3 ( viewModelOrigin ); savefile->ReadMat3 ( viewModelAxis ); savefile->ReadAngles ( viewModelAngles ); savefile->ReadVec3 ( viewModelOffset ); // cnicholson: Added unrestored var // Offsets savefile->ReadInt ( weaponAngleOffsetAverages ); savefile->ReadFloat ( weaponAngleOffsetScale ); savefile->ReadFloat ( weaponAngleOffsetMax ); savefile->ReadFloat ( weaponOffsetTime ); savefile->ReadFloat ( weaponOffsetScale ); savefile->ReadString ( icon ); savefile->ReadBool ( isStrogg ); // TORESTORE: idDict spawnArgs; // TORESTORE: idAnimator* viewAnimator; // TORESTORE: idAnimator* worldAnimator; // TORESTORE: const idDeclEntityDef* weaponDef; // TORESTORE: idScriptObject* scriptObject; // Entities savefile->ReadObject( reinterpret_cast<idClass *&>( owner ) ); viewModel = owner->GetWeaponViewModel ( ); worldModel = owner->GetWeaponWorldModel ( ); savefile->ReadInt ( weaponIndex ); // cnicholson: Added unrestored var savefile->ReadInt ( mods ); // cnicholson: Added unrestored var savefile->ReadFloat ( viewModelForeshorten ); stateThread.Restore( savefile, this ); for ( i = 0; i < ANIM_NumAnimChannels; i++ ) { savefile->ReadInt( animDoneTime[i] ); } savefile->ReadInt ( methodOfDeath ); // cnicholson: Added unrestored var #ifdef _XENON aimAssistFOV = spawnArgs.GetFloat( "aimAssistFOV", "10.0f" ); #endif } /*********************************************************************** State control/player interface ***********************************************************************/ /* ================ rvWeapon::Hide ================ */ void rvWeapon::Hide( void ) { muzzleFlashEnd = 0; if ( viewModel ) { viewModel->Hide(); } if ( worldModel ) { worldModel->Hide ( ); } // Stop flashlight and gui lights FreeLight ( WPLIGHT_GUI ); FreeLight ( WPLIGHT_FLASHLIGHT ); FreeLight ( WPLIGHT_FLASHLIGHT_WORLD ); } /* ================ rvWeapon::Show ================ */ void rvWeapon::Show ( void ) { if ( viewModel ) { viewModel->Show(); } if ( worldModel ) { worldModel->Show(); } } /* ================ rvWeapon::IsHidden ================ */ bool rvWeapon::IsHidden( void ) const { return !viewModel || viewModel->IsHidden(); } /* ================ rvWeapon::HideWorldModel ================ */ void rvWeapon::HideWorldModel ( void ) { if ( worldModel ) { worldModel->Hide(); } } /* ================ rvWeapon::ShowWorldModel ================ */ void rvWeapon::ShowWorldModel ( void ) { if ( worldModel ) { worldModel->Show(); } } /* ================ rvWeapon::LowerWeapon ================ */ void rvWeapon::LowerWeapon( void ) { if ( !wfl.hide ) { hideStart = 0.0f; hideEnd = hideDistance; if ( gameLocal.time - hideStartTime < hideTime ) { hideStartTime = gameLocal.time - ( hideTime - ( gameLocal.time - hideStartTime ) ); } else { hideStartTime = gameLocal.time; } wfl.hide = true; } } /* ================ rvWeapon::RaiseWeapon ================ */ void rvWeapon::RaiseWeapon( void ) { if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->Show(); if ( forceGUIReload ) { forceGUIReload = false; int ammo = AmmoInClip(); for ( int g = 0; g < MAX_RENDERENTITY_GUI && viewModel->GetRenderEntity()->gui[g]; g ++ ) { idUserInterface* gui = viewModel->GetRenderEntity()->gui[g]; if ( gui ) { gui->SetStateInt ( "player_ammo", ammo ); if ( ClipSize ( ) ) { gui->SetStateFloat ( "player_ammopct", (float)ammo / (float)ClipSize() ); gui->SetStateInt ( "player_clip_size", ClipSize() ); } else { gui->SetStateFloat ( "player_ammopct", (float)ammo / (float)maxAmmo ); gui->SetStateInt ( "player_clip_size", maxAmmo ); } gui->SetStateInt ( "player_cachedammo", ammo ); gui->HandleNamedEvent ( "weapon_ammo" ); } } } if ( wfl.hide ) { hideStart = hideDistance; hideEnd = 0.0f; if ( gameLocal.time - hideStartTime < hideTime ) { hideStartTime = gameLocal.time - ( hideTime - ( gameLocal.time - hideStartTime ) ); } else { hideStartTime = gameLocal.time; } wfl.hide = false; } } /* ================ rvWeapon::PutAway ================ */ void rvWeapon::PutAway( void ) { wfl.hasBloodSplat = false; wsfl.lowerWeapon = true; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->PostGUIEvent ( "weapon_lower" ); } /* ================ rvWeapon::Raise ================ */ void rvWeapon::Raise( void ) { wsfl.raiseWeapon = true; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->PostGUIEvent ( "weapon_raise" ); } /* ================ rvWeapon::Flashlight ================ */ void rvWeapon::Flashlight ( void ) { wsfl.flashlight = true; } /* ================ rvWeapon::SetPushVelocity ================ */ void rvWeapon::SetPushVelocity( const idVec3& _pushVelocity ) { pushVelocity = _pushVelocity; } /* ================ rvWeapon::Reload NOTE: this is only for impulse-triggered reload, auto reload is scripted ================ */ void rvWeapon::Reload( void ) { if ( clipSize ) { wsfl.reload = true; } } /* ================ rvWeapon::CancelReload ================ */ void rvWeapon::CancelReload( void ) { wsfl.attack = true; } /* ================ rvWeapon::AutoReload ================ */ bool rvWeapon::AutoReload ( void ) { assert( owner ); // on a network client, never predict reloads of other clients. wait for the server if ( gameLocal.isClient ) { return false; } return gameLocal.userInfo[ owner->entityNumber ].GetBool( "ui_autoReload" ); } /* ================ rvWeapon::NetReload ================ */ void rvWeapon::NetReload ( void ) { assert( owner ); if ( gameLocal.isServer ) { if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->ServerSendEvent( EVENT_RELOAD, NULL, false, -1 ); } } /* =============== rvWeapon::NetEndReload =============== */ void rvWeapon::NetEndReload ( void ) { assert( owner ); if ( gameLocal.isServer ) { if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->ServerSendEvent( EVENT_ENDRELOAD, NULL, false, -1 ); } } /* ================ rvWeapon::SetStatus ================ */ void rvWeapon::SetStatus ( weaponStatus_t _status ) { status = _status; switch ( status ) { case WP_READY: wsfl.raiseWeapon = false; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); break; } viewModel->PostGUIEvent ( "weapon_ready" ); break; case WP_OUTOFAMMO: wsfl.raiseWeapon = false; break; case WP_RELOAD: if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); break; } viewModel->PostGUIEvent ( "weapon_reload" ); break; case WP_HOLSTERED: case WP_RISING: wsfl.lowerWeapon = false; owner->WeaponRisingCallback(); break; case WP_LOWERING: wsfl.raiseWeapon = false; owner->WeaponLoweringCallback(); break; } } /* ================ rvWeapon::OwnerDied ================ */ void rvWeapon::OwnerDied( void ) { CleanupWeapon(); ExecuteState( "OwnerDied" ); if ( viewModel ) { viewModel->StopSound( SCHANNEL_ANY, false ); viewModel->StopAllEffects( ); viewModel->Hide(); } if ( worldModel ) { worldModel->Hide(); } } /* ================ rvWeapon::BeginAttack ================ */ void rvWeapon::BeginAttack( void ) { wsfl.attack = true; if ( status != WP_OUTOFAMMO ) { lastAttack = gameLocal.time; } } /* ================ rvWeapon::EndAttack ================ */ void rvWeapon::EndAttack( void ) { wsfl.attack = false; } /* ================ rvWeapon::isReady ================ */ bool rvWeapon::IsReady( void ) const { return !wfl.hide && ! ( gameLocal.time - hideStartTime < hideTime ) && ( viewModel && !viewModel->IsHidden()) && ( ( status == WP_READY ) || ( status == WP_OUTOFAMMO ) ); } /* ================ rvWeapon::IsReloading ================ */ bool rvWeapon::IsReloading( void ) const { return ( status == WP_RELOAD ); } /* ================ rvWeapon::IsHolstered ================ */ bool rvWeapon::IsHolstered( void ) const { return ( status == WP_HOLSTERED ); } /* ================ rvWeapon::ShowCrosshair ================ */ bool rvWeapon::ShowCrosshair( void ) const { if ( owner->IsZoomed ( ) && zoomGui && wfl.zoomHideCrosshair ) { return false; } return !( status == WP_HOLSTERED ); } /* ===================== rvWeapon::CanDrop ===================== */ bool rvWeapon::CanDrop( void ) const { const char *classname = spawnArgs.GetString( "def_dropItem" ); if ( !classname[ 0 ] ) { return false; } return true; } /* ===================== rvViewWeapon::CanZoom ===================== */ bool rvWeapon::CanZoom( void ) const { #ifdef _XENON // apparently a xenon specific bug in medlabs. return zoomFov != -1 && !IsHidden(); #else return zoomFov != -1; #endif } /*********************************************************************** Visual presentation ***********************************************************************/ /* ================ rvWeapon::MuzzleRise ================ */ void rvWeapon::MuzzleRise( idVec3 &origin, idMat3 &axis ) { int time; float amount; idAngles ang; idVec3 offset; time = kick_endtime - gameLocal.time; if ( time <= 0 ) { return; } if ( muzzle_kick_maxtime <= 0 ) { return; } if ( time > muzzle_kick_maxtime ) { time = muzzle_kick_maxtime; } amount = ( float )time / ( float )muzzle_kick_maxtime; ang = muzzle_kick_angles * amount; offset = muzzle_kick_offset * amount; origin = origin - axis * offset; axis = ang.ToMat3() * axis; } /* ================ rvWeapon::UpdateFlashPosition ================ */ void rvWeapon::UpdateMuzzleFlash ( void ) { // remove the muzzle flash light when it's done if ( gameLocal.time >= muzzleFlashEnd || !gameLocal.GetLocalPlayer() || !owner || gameLocal.GetLocalPlayer()->GetInstance() != owner->GetInstance() ) { FreeLight ( WPLIGHT_MUZZLEFLASH ); FreeLight ( WPLIGHT_MUZZLEFLASH_WORLD ); return; } renderLight_t& light = lights[WPLIGHT_MUZZLEFLASH]; renderLight_t& lightWorld = lights[WPLIGHT_MUZZLEFLASH_WORLD]; light.origin = playerViewOrigin + (playerViewAxis * muzzleFlashViewOffset); light.axis = playerViewAxis; // put the world muzzle flash on the end of the joint, no matter what GetGlobalJointTransform( false, flashJointWorld, lightWorld.origin, lightWorld.axis ); UpdateLight ( WPLIGHT_MUZZLEFLASH ); UpdateLight ( WPLIGHT_MUZZLEFLASH_WORLD ); } /* ================ rvWeapon::UpdateFlashlight ================ */ void rvWeapon::UpdateFlashlight ( void ) { // Turn flashlight off? if (! owner->IsFlashlightOn ( ) ) { FreeLight ( WPLIGHT_FLASHLIGHT ); FreeLight ( WPLIGHT_FLASHLIGHT_WORLD ); return; } renderLight_t& light = lights[WPLIGHT_FLASHLIGHT]; renderLight_t& lightWorld = lights[WPLIGHT_FLASHLIGHT_WORLD]; trace_t tr; // the flash has an explicit joint for locating it GetGlobalJointTransform( true, flashlightJointView, light.origin, light.axis, flashlightViewOffset ); // if the desired point is inside or very close to a wall, back it up until it is clear gameLocal.TracePoint( owner, tr, light.origin - playerViewAxis[0] * 8.0f, light.origin, MASK_SHOT_BOUNDINGBOX, owner ); // be at least 8 units away from a solid light.origin = tr.endpos - (tr.fraction < 1.0f ? (playerViewAxis[0] * 8) : vec3_origin); // put the world muzzle flash on the end of the joint, no matter what if ( flashlightJointWorld != INVALID_JOINT ) { GetGlobalJointTransform( false, flashlightJointWorld, lightWorld.origin, lightWorld.axis ); } else { lightWorld.origin = playerViewOrigin + playerViewAxis[0] * 20.0f; lightWorld.axis = playerViewAxis; } UpdateLight ( WPLIGHT_FLASHLIGHT ); UpdateLight ( WPLIGHT_FLASHLIGHT_WORLD ); } /* ================ rvWeapon::MuzzleFlash ================ */ void rvWeapon::MuzzleFlash ( void ) { renderLight_t& light = lights[WPLIGHT_MUZZLEFLASH]; renderLight_t& lightWorld = lights[WPLIGHT_MUZZLEFLASH_WORLD]; if ( !g_muzzleFlash.GetBool() || flashJointView == INVALID_JOINT || !light.lightRadius[0] ) { return; } if ( g_perfTest_weaponNoFX.GetBool() ) { return; } if ( viewModel ) { // these will be different each fire light.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); light.shaderParms[ SHADERPARM_DIVERSITY ] = viewModel->GetRenderEntity()->shaderParms[ SHADERPARM_DIVERSITY ]; light.noShadows = true; lightWorld.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); lightWorld.shaderParms[ SHADERPARM_DIVERSITY ] = viewModel->GetRenderEntity()->shaderParms[ SHADERPARM_DIVERSITY ]; lightWorld.noShadows = true; // the light will be removed at this time muzzleFlashEnd = gameLocal.time + muzzleFlashTime; } else { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); } UpdateMuzzleFlash ( ); } /* ================ rvWeapon::UpdateGUI ================ */ void rvWeapon::UpdateGUI( void ) { idUserInterface* gui; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } gui = viewModel->GetRenderEntity()->gui[0]; if ( !gui || status == WP_HOLSTERED ) { return; } int g; for ( g = 0; g < MAX_RENDERENTITY_GUI && viewModel->GetRenderEntity()->gui[g]; g ++ ) { gui = viewModel->GetRenderEntity()->gui[g]; if ( gameLocal.localClientNum != owner->entityNumber ) { // if updating the hud for a followed client idPlayer *p = gameLocal.GetLocalPlayer(); if ( !p ) { return; } if ( !p->spectating || p->spectator != owner->entityNumber ) { return; } } int ammo = AmmoInClip(); if ( ammo >= 0 ) { // show remaining ammo if ( gui->State().GetInt ( "player_cachedammo", "-1") != ammo ) { gui->SetStateInt ( "player_ammo", ammo ); if ( ClipSize ( ) ) { gui->SetStateFloat ( "player_ammopct", (float)ammo / (float)ClipSize() ); gui->SetStateInt ( "player_clip_size", ClipSize() ); } else { gui->SetStateFloat ( "player_ammopct", (float)ammo / (float)maxAmmo ); gui->SetStateInt ( "player_clip_size", maxAmmo ); } gui->SetStateInt ( "player_cachedammo", ammo ); gui->HandleNamedEvent ( "weapon_ammo" ); } } // viewModel->GetRenderEntity()->gui[g]->SetStateInt ( "player_clip_size", ClipSize() ); } for ( int i = 0; i < viewModel->pendingGUIEvents.Num(); i ++ ) { gui->HandleNamedEvent( viewModel->pendingGUIEvents[i] ); } viewModel->pendingGUIEvents.Clear(); } /* ================ rvWeapon::UpdateCrosshairGUI ================ */ void rvWeapon::UpdateCrosshairGUI( idUserInterface* gui ) const { // RAVEN BEGIN // cnicholson: Added support for universal crosshair // COMMENTED OUT until Custom crosshair GUI is implemented. if ( g_crosshairCustom.GetBool() ) { // If there's a custom crosshair, use it. gui->SetStateString( "crossImage", g_crosshairCustomFile.GetString()); const idMaterial *material = declManager->FindMaterial( g_crosshairCustomFile.GetString() ); if ( material ) { material->SetSort( SS_GUI ); } } else { gui->SetStateString( "crossImage", spawnArgs.GetString( "mtr_crosshair" ) ); const idMaterial *material = declManager->FindMaterial( spawnArgs.GetString( "mtr_crosshair" ) ); if ( material ) { material->SetSort( SS_GUI ); } } // Original Block //gui->SetStateString ( "crossImage", spawnArgs.GetString ( "mtr_crosshair" ) ); // RAVEN END gui->SetStateString( "crossColor", g_crosshairColor.GetString() ); gui->SetStateInt( "crossOffsetX", spawnArgs.GetInt( "crosshairOffsetX", "0" ) ); gui->SetStateInt( "crossOffsetY", spawnArgs.GetInt( "crosshairOffsetY", "0" ) ); gui->StateChanged( gameLocal.time ); } /* ================ rvWeapon::ForeshortenAxis ================ */ idMat3 rvWeapon::ForeshortenAxis( const idMat3& axis ) const { return idMat3( axis[0] * viewModelForeshorten, axis[1], axis[2] ); } /* ================ rvWeapon::GetAngleOffsets ================ */ void rvWeapon::GetAngleOffsets ( int *average, float *scale, float *max ) { *average = weaponAngleOffsetAverages; *scale = weaponAngleOffsetScale; *max = weaponAngleOffsetMax; } /* ================ rvWeapon::GetTimeOffsets ================ */ void rvWeapon::GetTimeOffsets ( float *time, float *scale ) { *time = weaponOffsetTime; *scale = weaponOffsetScale; } /* ================ rvWeapon::GetGlobalJointTransform This returns the offset and axis of a weapon bone in world space, suitable for attaching models or lights ================ */ bool rvWeapon::GetGlobalJointTransform ( bool view, const jointHandle_t jointHandle, idVec3 &origin, idMat3 &axis, const idVec3& offset ) { if ( view) { // view model if ( viewModel && viewAnimator->GetJointTransform( jointHandle, gameLocal.time, origin, axis ) ) { origin = offset * axis + origin; origin = origin * ForeshortenAxis(viewModelAxis) + viewModelOrigin; axis = axis * viewModelAxis; return true; } } else { // world model if ( worldModel && worldAnimator->GetJointTransform( jointHandle, gameLocal.time, origin, axis ) ) { origin = offset * axis + origin; origin = worldModel->GetPhysics()->GetOrigin() + origin * worldModel->GetPhysics()->GetAxis(); axis = axis * worldModel->GetPhysics()->GetAxis(); return true; } } origin = viewModelOrigin + offset * viewModelAxis; axis = viewModelAxis; return false; } /*********************************************************************** Ammo ***********************************************************************/ /* ================ rvWeapon::GetAmmoIndexForName ================ */ int rvWeapon::GetAmmoIndexForName( const char *ammoname ) { int num; const idDict *ammoDict; assert( ammoname ); ammoDict = gameLocal.FindEntityDefDict( "ammo_types", false ); if ( !ammoDict ) { gameLocal.Error( "Could not find entity definition for 'ammo_types'\n" ); } if ( !ammoname[ 0 ] ) { return 0; } if ( !ammoDict->GetInt( ammoname, "-1", num ) ) { gameLocal.Error( "Unknown ammo type '%s'", ammoname ); } if ( ( num < 0 ) || ( num >= MAX_AMMOTYPES ) ) { gameLocal.Error( "Ammo type '%s' value out of range. Maximum ammo types is %d.\n", ammoname, MAX_AMMOTYPES ); } return num; } /* ================ rvWeapon::GetAmmoNameForNum ================ */ const char* rvWeapon::GetAmmoNameForIndex( int index ) { int i; int num; const idDict *ammoDict; const idKeyValue *kv; char text[ 32 ]; ammoDict = gameLocal.FindEntityDefDict( "ammo_types", false ); if ( !ammoDict ) { gameLocal.Error( "Could not find entity definition for 'ammo_types'\n" ); } sprintf( text, "%d", index ); num = ammoDict->GetNumKeyVals(); for( i = 0; i < num; i++ ) { kv = ammoDict->GetKeyVal( i ); if ( kv->GetValue() == text ) { return kv->GetKey(); } } return NULL; } /* ================ rvWeapon::TotalAmmoCount ================ */ int rvWeapon::TotalAmmoCount ( void ) const { return owner->inventory.HasAmmo( ammoType, 1 ); } /* ================ rvWeapon::AmmoAvailable ================ */ int rvWeapon::AmmoAvailable( void ) const { if ( owner ) { return owner->inventory.HasAmmo( ammoType, ammoRequired ); } else { return 0; } } /* ================ rvWeapon::AmmoInClip ================ */ int rvWeapon::AmmoInClip( void ) const { if ( !clipSize ) { return AmmoAvailable(); } return ammoClip; } /* ================ rvWeapon::ResetAmmoClip ================ */ void rvWeapon::ResetAmmoClip( void ) { ammoClip = -1; } /* ================ rvWeapon::GetAmmoType ================ */ int rvWeapon::GetAmmoType( void ) const { return ammoType; } /* ================ rvWeapon::ClipSize ================ */ int rvWeapon::ClipSize( void ) const { return clipSize; } /* ================ rvWeapon::LowAmmo ================ */ int rvWeapon::LowAmmo() const { return lowAmmo; } /* ================ rvWeapon::AmmoRequired ================ */ int rvWeapon::AmmoRequired( void ) const { return ammoRequired; } /* ================ rvWeapon::SetClip ================ */ void rvWeapon::SetClip ( int amount ) { ammoClip = amount; if ( amount < 0 ) { ammoClip = 0; } else if ( amount > clipSize ) { ammoClip = clipSize; } if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->PostGUIEvent ( "weapon_ammo" ); if ( ammoClip == 0 && AmmoAvailable() == 0 ) { viewModel->PostGUIEvent ( "weapon_noammo" ); } } /* ================ rvWeapon::UseAmmo ================ */ void rvWeapon::UseAmmo( int amount ) { owner->inventory.UseAmmo( ammoType, amount * ammoRequired ); if ( clipSize && ammoRequired ) { ammoClip -= ( amount * ammoRequired ); if ( ammoClip < 0 ) { ammoClip = 0; } } } /* ================ rvWeapon::AddToClip ================ */ void rvWeapon::AddToClip ( int amount ) { int ammoAvail; if ( gameLocal.isClient ) { return; } ammoClip += amount; if ( ammoClip > clipSize ) { ammoClip = clipSize; } ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired ); if ( ammoAvail > 0 && ammoClip > ammoAvail ) { ammoClip = ammoAvail; } if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } viewModel->PostGUIEvent ( "weapon_ammo" ); if ( ammoClip == 0 && AmmoAvailable() == 0 ) { viewModel->PostGUIEvent ( "weapon_noammo" ); } } /*********************************************************************** Attack ***********************************************************************/ /* ================ rvWeapon::Attack ================ */ void rvWeapon::Attack( bool altAttack, int num_attacks, float spread, float fuseOffset, float power ) { idVec3 muzzleOrigin; idMat3 muzzleAxis; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } if ( viewModel->IsHidden() ) { return; } // avoid all ammo considerations on an MP client if ( !gameLocal.isClient ) { // check if we're out of ammo or the clip is empty int ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired ); if ( !ammoAvail || ( ( clipSize != 0 ) && ( ammoClip <= 0 ) ) ) { return; } owner->inventory.UseAmmo( ammoType, ammoRequired ); if ( clipSize && ammoRequired ) { clipPredictTime = gameLocal.time; // mp client: we predict this. mark time so we're not confused by snapshots ammoClip -= 1; } // wake up nearby monsters if ( !wfl.silent_fire ) { gameLocal.AlertAI( owner ); } } // set the shader parm to the time of last projectile firing, // which the gun material shaders can reference for single shot barrel glows, etc viewModel->SetShaderParm ( SHADERPARM_DIVERSITY, gameLocal.random.CRandomFloat() ); viewModel->SetShaderParm ( SHADERPARM_TIMEOFFSET, -MS2SEC( gameLocal.realClientTime ) ); if ( worldModel.GetEntity() ) { worldModel->SetShaderParm( SHADERPARM_DIVERSITY, viewModel->GetRenderEntity()->shaderParms[ SHADERPARM_DIVERSITY ] ); worldModel->SetShaderParm( SHADERPARM_TIMEOFFSET, viewModel->GetRenderEntity()->shaderParms[ SHADERPARM_TIMEOFFSET ] ); } // calculate the muzzle position if ( barrelJointView != INVALID_JOINT && spawnArgs.GetBool( "launchFromBarrel" ) ) { // there is an explicit joint for the muzzle GetGlobalJointTransform( true, barrelJointView, muzzleOrigin, muzzleAxis ); } else { // go straight out of the view muzzleOrigin = playerViewOrigin; muzzleAxis = playerViewAxis; muzzleOrigin += playerViewAxis[0] * muzzleOffset; } // add some to the kick time, incrementally moving repeat firing weapons back if ( kick_endtime < gameLocal.realClientTime ) { kick_endtime = gameLocal.realClientTime; } kick_endtime += muzzle_kick_time; if ( kick_endtime > gameLocal.realClientTime + muzzle_kick_maxtime ) { kick_endtime = gameLocal.realClientTime + muzzle_kick_maxtime; } // add the muzzleflash MuzzleFlash(); // quad damage overlays a sound if ( owner->PowerUpActive( POWERUP_QUADDAMAGE ) ) { viewModel->StartSound( "snd_quaddamage", SND_CHANNEL_VOICE, 0, false, NULL ); } // Muzzle flash effect bool muzzleTint = spawnArgs.GetBool( "muzzleTint" ); viewModel->PlayEffect( "fx_muzzleflash", flashJointView, false, vec3_origin, false, false, EC_IGNORE, muzzleTint ? owner->GetHitscanTint() : vec4_one ); if ( worldModel && flashJointWorld != INVALID_JOINT ) { worldModel->PlayEffect( gameLocal.GetEffect( weaponDef->dict, "fx_muzzleflash_world" ), flashJointWorld, vec3_origin, mat3_identity, false, vec3_origin, false, false, EC_IGNORE, muzzleTint ? owner->GetHitscanTint() : vec4_one ); } owner->WeaponFireFeedback( &weaponDef->dict ); // Inform the gui of the ammo change viewModel->PostGUIEvent ( "weapon_ammo" ); if ( ammoClip == 0 && AmmoAvailable() == 0 ) { viewModel->PostGUIEvent ( "weapon_noammo" ); } // The attack is either a hitscan or a launched projectile, do that now. if ( !gameLocal.isClient ) { idDict& dict = altAttack ? attackAltDict : attackDict; power *= owner->PowerUpModifier( PMOD_PROJECTILE_DAMAGE ); if ( altAttack ? wfl.attackAltHitscan : wfl.attackHitscan ) { Hitscan( dict, muzzleOrigin, muzzleAxis, num_attacks, spread, power ); } else { LaunchProjectiles( dict, muzzleOrigin, muzzleAxis, num_attacks, spread, fuseOffset, power ); } //asalmon: changed to keep stats even in single player statManager->WeaponFired( owner, weaponIndex, num_attacks ); } } /* ================ rvWeapon::LaunchProjectiles ================ */ void rvWeapon::LaunchProjectiles ( idDict& dict, const idVec3& muzzleOrigin, const idMat3& muzzleAxis, int num_projectiles, float spread, float fuseOffset, float power ) { idProjectile* proj; idEntity* ent; int i; float spreadRad; idVec3 dir; idBounds ownerBounds; if ( gameLocal.isClient ) { return; } // Let the AI know about the new attack if ( !gameLocal.isMultiplayer ) { aiManager.ReactToPlayerAttack ( owner, muzzleOrigin, muzzleAxis[0] ); } ownerBounds = owner->GetPhysics()->GetAbsBounds(); spreadRad = DEG2RAD( spread ); idVec3 dirOffset; idVec3 startOffset; spawnArgs.GetVector( "dirOffset", "0 0 0", dirOffset ); spawnArgs.GetVector( "startOffset", "0 0 0", startOffset ); for( i = 0; i < num_projectiles; i++ ) { float ang; float spin; idVec3 dir; idBounds projBounds; idVec3 muzzle_pos; // Calculate a random launch direction based on the spread ang = idMath::Sin( spreadRad * gameLocal.random.RandomFloat() ); spin = (float)DEG2RAD( 360.0f ) * gameLocal.random.RandomFloat(); dir = playerViewAxis[ 0 ] + playerViewAxis[ 2 ] * ( ang * idMath::Sin( spin ) ) - playerViewAxis[ 1 ] * ( ang * idMath::Cos( spin ) ); dir += dirOffset; dir.Normalize(); // If a projectile entity has already been created then use that one, otherwise // spawn a new one based on the given dictionary if ( projectileEnt ) { ent = projectileEnt; ent->Show(); ent->Unbind(); projectileEnt = NULL; } else { dict.SetInt( "instance", owner->GetInstance() ); gameLocal.SpawnEntityDef( dict, &ent, false ); } // Make sure it spawned if ( !ent ) { gameLocal.Error( "failed to spawn projectile for weapon '%s'", weaponDef->GetName ( ) ); } assert ( ent->IsType( idProjectile::GetClassType() ) ); // Create the projectile proj = static_cast<idProjectile*>(ent); proj->Create( owner, muzzleOrigin + startOffset, dir, NULL, owner->extraProjPassEntity ); projBounds = proj->GetPhysics()->GetBounds().Rotate( proj->GetPhysics()->GetAxis() ); // make sure the projectile starts inside the bounding box of the owner if ( i == 0 ) { idVec3 start; float distance; trace_t tr; //RAVEN BEGIN //asalmon: xbox must use muzzle Axis for aim assistance #ifdef _XBOX muzzle_pos = muzzleOrigin + muzzleAxis[ 0 ] * 2.0f; if ( ( ownerBounds - projBounds).RayIntersection( muzzle_pos, muzzleAxis[0], distance ) ) { start = muzzle_pos + distance * muzzleAxis[0]; } #else muzzle_pos = muzzleOrigin + playerViewAxis[ 0 ] * 2.0f; if ( ( ownerBounds - projBounds).RayIntersection( muzzle_pos, playerViewAxis[0], distance ) ) { start = muzzle_pos + distance * playerViewAxis[0]; } #endif //RAVEN END else { start = ownerBounds.GetCenter(); } // RAVEN BEGIN // ddynerman: multiple clip worlds gameLocal.Translation( owner, tr, start, muzzle_pos, proj->GetPhysics()->GetClipModel(), proj->GetPhysics()->GetClipModel()->GetAxis(), MASK_SHOT_RENDERMODEL, owner ); // RAVEN END muzzle_pos = tr.endpos; } // Launch the actual projectile proj->Launch( muzzle_pos + startOffset, dir, pushVelocity, fuseOffset, power ); // Increment the projectile launch count and let the derived classes // mess with it if they want. OnLaunchProjectile ( proj ); } } /* ================ rvWeapon::OnLaunchProjectile ================ */ void rvWeapon::OnLaunchProjectile ( idProjectile* proj ) { owner->AddProjectilesFired( 1 ); if ( proj ) { proj->methodOfDeath = owner->GetCurrentWeapon(); } } /* ================ rvWeapon::Hitscan ================ */ void rvWeapon::Hitscan( const idDict& dict, const idVec3& muzzleOrigin, const idMat3& muzzleAxis, int num_hitscans, float spread, float power ) { idVec3 fxOrigin; idMat3 fxAxis; int i; float ang; float spin; idVec3 dir; int areas[ 2 ]; idBitMsg msg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; // Let the AI know about the new attack if ( !gameLocal.isMultiplayer ) { aiManager.ReactToPlayerAttack( owner, muzzleOrigin, muzzleAxis[0] ); } GetGlobalJointTransform( true, flashJointView, fxOrigin, fxAxis, dict.GetVector( "fxOriginOffset" ) ); if ( gameLocal.isServer ) { assert( hitscanAttackDef >= 0 ); assert( owner && owner->entityNumber < MAX_CLIENTS ); int ownerId = owner ? owner->entityNumber : 0; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.BeginWriting(); msg.WriteByte( GAME_UNRELIABLE_MESSAGE_HITSCAN ); msg.WriteLong( hitscanAttackDef ); msg.WriteBits( ownerId, idMath::BitsForInteger( MAX_CLIENTS ) ); msg.WriteFloat( muzzleOrigin[0] ); msg.WriteFloat( muzzleOrigin[1] ); msg.WriteFloat( muzzleOrigin[2] ); msg.WriteFloat( fxOrigin[0] ); msg.WriteFloat( fxOrigin[1] ); msg.WriteFloat( fxOrigin[2] ); } float spreadRad = DEG2RAD( spread ); idVec3 end; for( i = 0; i < num_hitscans; i++ ) { if( weaponDef->dict.GetBool( "machinegunSpreadStyle" ) ) { float r = gameLocal.random.RandomFloat() * idMath::PI * 2.0f; float u = idMath::Sin( r ) * gameLocal.random.CRandomFloat() * spread * 16; r = idMath::Cos( r ) * gameLocal.random.CRandomFloat() * spread * 16; #ifdef _XBOX end = muzzleOrigin + ( ( 8192 * 16 ) * muzzleAxis[ 0 ] ); end += ( r * muzzleAxis[ 1 ] ); end += ( u * muzzleAxis[ 2 ] ); #else end = muzzleOrigin + ( ( 8192 * 16 ) * playerViewAxis[ 0 ] ); end += ( r * playerViewAxis[ 1 ] ); end += ( u * playerViewAxis[ 2 ] ); #endif dir = end - muzzleOrigin; } else if( weaponDef->dict.GetBool( "shotgunSpreadStyle" ) ) { int radius; float angle; // this may look slightly odd, but ensures with an odd number of pellets we get // two complete circles, and the outer one gets the extra hit int circleHitscans = num_hitscans - (num_hitscans / 2); if (i < circleHitscans) { radius = spread * 14; angle = i * (idMath::TWO_PI / circleHitscans); } else { radius = spread * 6; angle = (i - circleHitscans) * (idMath::TWO_PI / num_hitscans) * 2; } float r = radius * (idMath::Cos(angle) + (gameLocal.random.CRandomFloat() * 0.2f)); float u = radius * (idMath::Sin(angle) + (gameLocal.random.CRandomFloat() * 0.2f)); #ifdef _XBOX end = muzzleOrigin + ( ( 8192 * 16 ) * muzzleAxis[ 0 ] ); end += ( r * muzzleAxis[ 1 ] ); end += ( u * muzzleAxis[ 2 ] ); #else end = muzzleOrigin + ( ( 8192 * 16 ) * playerViewAxis[ 0 ] ); end += ( r * playerViewAxis[ 1 ] ); end += ( u * playerViewAxis[ 2 ] ); #endif dir = end - muzzleOrigin; } else { ang = idMath::Sin( spreadRad * gameLocal.random.RandomFloat() ); spin = (float)DEG2RAD( 360.0f ) * gameLocal.random.RandomFloat(); //RAVEN BEGIN //asalmon: xbox must use the muzzleAxis so the aim can be adjusted for aim assistance #ifdef _XBOX dir = muzzleAxis[ 0 ] + muzzleAxis[ 2 ] * ( ang * idMath::Sin( spin ) ) - muzzleAxis[ 1 ] * ( ang * idMath::Cos( spin ) ); #else dir = playerViewAxis[ 0 ] + playerViewAxis[ 2 ] * ( ang * idMath::Sin( spin ) ) - playerViewAxis[ 1 ] * ( ang * idMath::Cos( spin ) ); #endif //RAVEN END } dir.Normalize(); gameLocal.HitScan( dict, muzzleOrigin, dir, fxOrigin, owner, false, 1.0f, NULL, areas ); if ( gameLocal.isServer ) { msg.WriteDir( dir, 24 ); if ( i == num_hitscans - 1 ) { // NOTE: we emit to the areas of the last hitscan // there is a remote possibility that multiple hitscans for shotgun would cover more than 2 areas, // so in some rare case a client might miss it gameLocal.SendUnreliableMessagePVS( msg, owner, areas[0], areas[1] ); } } } } /* ================ rvWeapon::AlertMonsters ================ */ void rvWeapon::AlertMonsters( void ) { trace_t tr; idEntity *ent; idVec3 end; renderLight_t& muzzleFlash = lights[WPLIGHT_MUZZLEFLASH]; end = muzzleFlash.origin + muzzleFlash.axis * muzzleFlash.target; gameLocal.TracePoint( owner, tr, muzzleFlash.origin, end, CONTENTS_OPAQUE | MASK_SHOT_RENDERMODEL | CONTENTS_FLASHLIGHT_TRIGGER, owner ); if ( g_debugWeapon.GetBool() ) { gameRenderWorld->DebugLine( colorYellow, muzzleFlash.origin, end, 0 ); gameRenderWorld->DebugArrow( colorGreen, muzzleFlash.origin, tr.endpos, 2, 0 ); } if ( tr.fraction < 1.0f ) { ent = gameLocal.GetTraceEntity( tr ); if ( ent->IsType( idAI::GetClassType() ) ) { static_cast<idAI *>( ent )->TouchedByFlashlight( owner ); } else if ( ent->IsType( idTrigger::GetClassType() ) ) { ent->Signal( SIG_TOUCH ); ent->ProcessEvent( &EV_Touch, owner, &tr ); } } // jitter the trace to try to catch cases where a trace down the center doesn't hit the monster end += muzzleFlash.axis * muzzleFlash.right * idMath::Sin16( MS2SEC( gameLocal.time ) * 31.34f ); end += muzzleFlash.axis * muzzleFlash.up * idMath::Sin16( MS2SEC( gameLocal.time ) * 12.17f ); gameLocal.TracePoint( owner, tr, muzzleFlash.origin, end, CONTENTS_OPAQUE | MASK_SHOT_RENDERMODEL | CONTENTS_FLASHLIGHT_TRIGGER, owner ); if ( g_debugWeapon.GetBool() ) { gameRenderWorld->DebugLine( colorYellow, muzzleFlash.origin, end, 0 ); gameRenderWorld->DebugArrow( colorGreen, muzzleFlash.origin, tr.endpos, 2, 0 ); } if ( tr.fraction < 1.0f ) { ent = gameLocal.GetTraceEntity( tr ); if ( ent->IsType( idAI::GetClassType() ) ) { static_cast<idAI *>( ent )->TouchedByFlashlight( owner ); } else if ( ent->IsType( idTrigger::GetClassType() ) ) { ent->Signal( SIG_TOUCH ); ent->ProcessEvent( &EV_Touch, owner, &tr ); } } } /* ================ rvWeapon::EjectBrass ================ */ void rvWeapon::EjectBrass ( void ) { if ( g_brassTime.GetFloat() <= 0.0f || !owner->CanShowWeaponViewmodel() ) { return; } if ( g_perfTest_weaponNoFX.GetBool() ) { return; } if ( gameLocal.isMultiplayer ) { return; } if ( ejectJointView == INVALID_JOINT || !brassDict.GetNumKeyVals() ) { return; } idMat3 axis; idVec3 origin; idVec3 linear_velocity; idVec3 angular_velocity; int brassTime; if ( !GetGlobalJointTransform( true, ejectJointView, origin, axis ) ) { return; } // Spawn the client side moveable for the brass rvClientMoveable* cent = NULL; gameLocal.SpawnClientEntityDef( brassDict, (rvClientEntity**)(&cent), false ); if( !cent ) { return; } cent->SetOwner( GetOwner() ); cent->SetOrigin ( origin + playerViewAxis * ejectOffset ); cent->SetAxis ( playerViewAxis ); // Depth hack the brass to make sure it clips in front of view weapon properly cent->GetRenderEntity()->weaponDepthHackInViewID = GetOwner()->entityNumber + 1; // Clear the depth hack soon after it clears the view cent->PostEventMS ( &CL_ClearDepthHack, 200 ); // Fade the brass out so they dont accumulate brassTime =(int)SEC2MS(g_brassTime.GetFloat() / 2.0f); cent->PostEventMS ( &CL_FadeOut, brassTime, brassTime ); // Generate a good velocity for the brass idVec3 linearVelocity = brassDict.GetVector("linear_velocity").Random( brassDict.GetVector("linear_velocity_range"), gameLocal.random ); cent->GetPhysics()->SetLinearVelocity( GetOwner()->GetPhysics()->GetLinearVelocity() + linearVelocity * cent->GetPhysics()->GetAxis() ); idAngles angularVelocity = brassDict.GetAngles("angular_velocity").Random( brassDict.GetVector("angular_velocity_range"), gameLocal.random ); cent->GetPhysics()->SetAngularVelocity( angularVelocity.ToAngularVelocity() * cent->GetPhysics()->GetAxis() ); } /* ================ rvWeapon::BloodSplat ================ */ bool rvWeapon::BloodSplat( float size ) { float s, c; idMat3 localAxis, axistemp; idVec3 localOrigin, normal; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return false; } if ( wfl.hasBloodSplat ) { return true; } wfl.hasBloodSplat = true; if ( viewModel->modelDefHandle < 0 ) { return false; } if ( !GetGlobalJointTransform( true, ejectJointView, localOrigin, localAxis ) ) { return false; } localOrigin[0] += gameLocal.random.RandomFloat() * -10.0f; localOrigin[1] += gameLocal.random.RandomFloat() * 1.0f; localOrigin[2] += gameLocal.random.RandomFloat() * -2.0f; normal = idVec3( gameLocal.random.CRandomFloat(), -gameLocal.random.RandomFloat(), -1 ); normal.Normalize(); idMath::SinCos16( gameLocal.random.RandomFloat() * idMath::TWO_PI, s, c ); localAxis[2] = -normal; localAxis[2].NormalVectors( axistemp[0], axistemp[1] ); localAxis[0] = axistemp[ 0 ] * c + axistemp[ 1 ] * -s; localAxis[1] = axistemp[ 0 ] * -s + axistemp[ 1 ] * -c; localAxis[0] *= 1.0f / size; localAxis[1] *= 1.0f / size; idPlane localPlane[2]; localPlane[0] = localAxis[0]; localPlane[0][3] = -(localOrigin * localAxis[0]) + 0.5f; localPlane[1] = localAxis[1]; localPlane[1][3] = -(localOrigin * localAxis[1]) + 0.5f; const idMaterial *mtr = declManager->FindMaterial( "textures/decals/duffysplatgun" ); gameRenderWorld->ProjectOverlay( viewModel->modelDefHandle, localPlane, mtr ); return true; } /* ================ rvWeapon::EnterCinematic ================ */ void rvWeapon::EnterCinematic( void ) { if( viewModel ) { viewModel->StopSound( SND_CHANNEL_ANY, false ); } ExecuteState( "EnterCinematic" ); memset( &wsfl, 0, sizeof(wsfl) ); wfl.disabled = true; LowerWeapon(); } /* ================ rvWeapon::ExitCinematic ================ */ void rvWeapon::ExitCinematic( void ) { wfl.disabled = false; ExecuteState ( "ExitCinematic" ); RaiseWeapon(); } /* ================ rvWeapon::NetCatchup ================ */ void rvWeapon::NetCatchup( void ) { ExecuteState ( "NetCatchup" ); } /* =============== rvWeapon::PlayAnim =============== */ void rvWeapon::PlayAnim( int channel, const char *animname, int blendFrames ) { if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } int anim; anim = viewAnimator->GetAnim( animname ); if ( !anim ) { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, viewModel->GetName(), viewModel->GetEntityDefName() ); viewAnimator->Clear( channel, gameLocal.time, FRAME2MS( blendFrames ) ); animDoneTime[channel] = 0; } else { viewModel->Show(); viewAnimator->PlayAnim( channel, anim, gameLocal.time, FRAME2MS( blendFrames ) ); animDoneTime[channel] = viewAnimator->CurrentAnim( channel )->GetEndTime(); // Play the animation on the world model as well if ( worldAnimator ) { worldAnimator->GetAnim( animname ); if ( anim ) { worldAnimator->PlayAnim( channel, anim, gameLocal.time, FRAME2MS( blendFrames ) ); } } } } /* =============== rvWeapon::PlayCycle =============== */ void rvWeapon::PlayCycle( int channel, const char *animname, int blendFrames ) { int anim; if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return; } anim = viewAnimator->GetAnim( animname ); if ( !anim ) { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, viewModel->GetName(), viewModel->GetEntityDefName() ); viewAnimator->Clear( channel, gameLocal.time, FRAME2MS( blendFrames ) ); animDoneTime[channel] = 0; } else { viewModel->Show(); viewAnimator->CycleAnim( channel, anim, gameLocal.time, FRAME2MS( blendFrames ) ); animDoneTime[channel] = viewAnimator->CurrentAnim( channel )->GetEndTime(); // Play the animation on the world model as well if ( worldAnimator ) { anim = worldAnimator->GetAnim( animname ); if ( anim ) { worldAnimator->CycleAnim( channel, anim, gameLocal.time, FRAME2MS( blendFrames ) ); } } } } /* =============== rvWeapon::AnimDone =============== */ bool rvWeapon::AnimDone( int channel, int blendFrames ) { if ( animDoneTime[channel] - FRAME2MS( blendFrames ) <= gameLocal.time ) { return true; } return false; } /* =============== rvWeapon::StartSound =============== */ bool rvWeapon::StartSound ( const char *soundName, const s_channelType channel, int soundShaderFlags, bool broadcast, int *length ) { if ( !viewModel ) { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return false; } return viewModel->StartSound( soundName, channel, soundShaderFlags, broadcast, length ); } /* =============== rvWeapon::StopSound =============== */ void rvWeapon::StopSound( const s_channelType channel, bool broadcast ) { if ( viewModel ) { viewModel->StopSound( channel, broadcast ); } else { common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); } } /* =============== rvWeapon::PlayEffect =============== */ rvClientEffect* rvWeapon::PlayEffect( const char* effectName, jointHandle_t joint, bool loop, const idVec3& endOrigin, bool broadcast ) { if ( viewModel ) { return viewModel->PlayEffect( effectName, joint, loop, endOrigin, broadcast ); } common->Warning( "NULL viewmodel %s\n", __FUNCTION__ ); return 0; } /* ================ rvWeapon::CacheWeapon ================ */ void rvWeapon::CacheWeapon( const char *weaponName ) { const idDeclEntityDef *weaponDef; const char *brassDefName; const char *clipModelName; idTraceModel trm; weaponDef = gameLocal.FindEntityDef( weaponName, false ); if ( !weaponDef ) { return; } // precache the brass collision model brassDefName = weaponDef->dict.GetString( "def_ejectBrass" ); if ( brassDefName[0] ) { const idDeclEntityDef *brassDef = gameLocal.FindEntityDef( brassDefName, false ); if ( brassDef ) { brassDef->dict.GetString( "clipmodel", "", &clipModelName ); if ( idStr::Icmp( clipModelName, SIMPLE_TRI_NAME ) == 0 ) { trm.SetupPolygon( simpleTri, 3 ); } else { if ( !clipModelName[0] ) { clipModelName = brassDef->dict.GetString( "model" ); // use the visual model } // load the trace model collisionModelManager->TrmFromModel( gameLocal.GetMapName(), clipModelName, trm ); } } } const idKeyValue* kv; kv = weaponDef->dict.MatchPrefix( "gui", NULL ); while( kv ) { if ( kv->GetValue().Length() ) { uiManager->FindGui( kv->GetValue().c_str(), true, false, true ); } kv = weaponDef->dict.MatchPrefix( "gui", kv ); } } /* =============================================================================== States =============================================================================== */ CLASS_STATES_DECLARATION ( rvWeapon ) STATE ( "Raise", rvWeapon::State_Raise ) STATE ( "Lower", rvWeapon::State_Lower ) STATE ( "ExitCinematic", rvWeapon::State_ExitCinematic ) STATE ( "NetCatchup", rvWeapon::State_NetCatchup ) STATE ( "EjectBrass", rvWeapon::Frame_EjectBrass ) END_CLASS_STATES /* ================ rvWeapon::State_Raise Raise the weapon ================ */ stateResult_t rvWeapon::State_Raise ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAIT, }; switch ( parms.stage ) { // Start the weapon raising case STAGE_INIT: SetStatus ( WP_RISING ); PlayAnim( ANIMCHANNEL_ALL, "raise", 0 ); return SRESULT_STAGE ( STAGE_WAIT ); case STAGE_WAIT: if ( AnimDone ( ANIMCHANNEL_ALL, 4 ) ) { SetState ( "Idle", 4 ); return SRESULT_DONE; } if ( wsfl.lowerWeapon ) { SetState ( "Lower", 4 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeapon::State_Lower Lower the weapon ================ */ stateResult_t rvWeapon::State_Lower ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAIT, STAGE_WAITRAISE }; switch ( parms.stage ) { case STAGE_INIT: SetStatus ( WP_LOWERING ); PlayAnim ( ANIMCHANNEL_ALL, "putaway", parms.blendFrames ); return SRESULT_STAGE(STAGE_WAIT); case STAGE_WAIT: if ( AnimDone ( ANIMCHANNEL_ALL, 0 ) ) { SetStatus ( WP_HOLSTERED ); return SRESULT_STAGE(STAGE_WAITRAISE); } return SRESULT_WAIT; case STAGE_WAITRAISE: if ( wsfl.raiseWeapon ) { SetState ( "Raise", 0 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ===================== rvWeapon::State_ExitCinematic ===================== */ stateResult_t rvWeapon::State_NetCatchup ( const stateParms_t& parms ) { SetState ( "idle", parms.blendFrames ); return SRESULT_DONE; } /* ===================== rvWeapon::State_ExitCinematic ===================== */ stateResult_t rvWeapon::State_ExitCinematic ( const stateParms_t& parms ) { SetState ( "Idle", 0 ); return SRESULT_DONE; } /* ===================== rvWeapon::Frame_EjectBrass ===================== */ stateResult_t rvWeapon::Frame_EjectBrass( const stateParms_t& parms ) { EjectBrass(); return SRESULT_DONE; } /* ===================== rvWeapon::GetDebugInfo ===================== */ void rvWeapon::GetDebugInfo ( debugInfoProc_t proc, void* userData ) { idClass::GetDebugInfo ( proc, userData ); proc ( "rvWeapon", "state", stateThread.GetState()?stateThread.GetState()->state->name : "<none>", userData ); }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 3346 ] ] ]
30da302affa9fbb01448f3b903874da04630513e
842997c28ef03f8deb3422d0bb123c707732a252
/src/uslsext/USCurve.cpp
eddb9b9bdff9b33d531d3ca436da3c36e5c7e582
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
1,487
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <math.h> #include <uslsext/USCurve.h> //================================================================// // USCurve //================================================================// float CatmullRom ( float a, float b, float c, float d, float t ); USVec2D CatmullRom ( const USVec2D& p0, const USVec2D& p1, const USVec2D& p2, const USVec2D& p3, float t ); //----------------------------------------------------------------// float CatmullRom ( float a, float b, float c, float d, float t ) { float t2 = t * t; float t3 = t2 * t; return 0.5f * ( ( 2.0f * b ) + ( -a + c ) * t + ( 2.0f * a - 5.0f * b + 4.0f * c - d ) * t2 + ( -a + 3.0f * b - 3.0f * c + d ) * t3 ); } //----------------------------------------------------------------// USVec2D CatmullRom ( const USVec2D& p0, const USVec2D& p1, const USVec2D& p2, const USVec2D& p3, float t ) { USVec2D p; float t2 = t * t; float t3 = t2 * t; p.mX = 0.5f * ( ( 2.0f * p1.mX ) + ( -p0.mX + p2.mX ) * t + ( 2.0f * p0.mX - 5.0f * p1.mX + 4.0f * p2.mX - p3.mX ) * t2 + ( -p0.mX + 3.0f * p1.mX - 3.0f * p2.mX + p3.mX ) * t3 ); p.mY = 0.5f * ( ( 2.0f * p1.mY ) + ( -p0.mY + p2.mY ) * t + ( 2.0f * p0.mY - 5.0f * p1.mY + 4.0f * p2.mY - p3.mY ) * t2 + ( -p0.mY + 3.0f * p1.mY - 3.0f * p2.mY + p3.mY ) * t3 ); return p; }
[ [ [ 1, 52 ] ] ]
65efa9807c0ea07794ea910295189b801dc989f0
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/2d/MglImage.cpp
611fe74e4804c0c096c7419d4c537004ef2040de
[]
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
5,448
cpp
////////////////////////////////////////////////////////// // // MglImage // - MglGraphicManager サーフェスクラス // ////////////////////////////////////////////////////////// #include "stdafx.h" #include "MglImage.h" // コンストラクタ CMglImage::CMglImage() { m_nSfcID = g_nSfcCount; g_nSfcCount++; //m_pSurface = NULL; m_bCenterDraw = FALSE; } // デストラクタ CMglImage::~CMglImage() { } //////////////////////////////////////////////////////////////////////////////// // 描画 void CMglImage::Draw( float x, float y, CONST RECT *pSrcRect, D3DCOLOR color, float fScaleX, float fScaleY, float fRotationCenterX, float fRotationCenterY, float fAngle ) { CreateCheck(); LockedCheck(); ///////////////////////////////////////////////////////////////////////// // 2009/03/31 CMglGraphicsManager::DrawSprite()より移動してみた。 // srcRectにNULLを指定された場合はBMP全てをRECTに指定 RECT texFullRect; if ( pSrcRect == NULL || pSrcRect->left == pSrcRect->right || pSrcRect->top == pSrcRect->bottom ) // 2009/03/31 { ZeroMemory(&texFullRect,sizeof(texFullRect)); // サイズ設定 texFullRect.left = 0; texFullRect.top = 0; texFullRect.right = GetBmpWidth(); texFullRect.bottom = GetBmpHeight(); // pSrcRect にポインタを設定 pSrcRect = &texFullRect; } // スケールじゃないバージョン float fRotationCenterXReal = (pSrcRect->right - pSrcRect->left) * fRotationCenterX; float fRotationCenterYReal = (pSrcRect->bottom - pSrcRect->top) * fRotationCenterY; ////////////////////////////////////////////////////////////////////// if ( m_bCenterDraw ){ /*x -= CMglTexture::GetBmpWidth()/2; y -= CMglTexture::GetBmpHeight()/2;*/ // 2008/01/19 拡大縮小の際に中心にならないがわざとなのかなんなのか・・・? //x -= (CMglTexture::GetBmpWidth() - ((1.0f-fScaleX)*CMglTexture::GetBmpWidth())/2); //x -= fScaleX * CMglTexture::GetBmpWidth() / 2; <= NG //y -= fScaleY * CMglTexture::GetBmpHeight() / 2; <= NG x -= fScaleX * fRotationCenterXReal; y -= fScaleY * fRotationCenterYReal; } // CMglGraphicsManager::DrawSprite() 呼び出し m_myudg->SpriteDraw( this, x, y, pSrcRect, color, fScaleX, fScaleY, fRotationCenterXReal, fRotationCenterYReal, fAngle ); } // 絵画(CopyRectを使用) void CMglImage::CopyRectToOther( CMglImage* destSurface, RECT *srcRect, int x, int y ) { CreateCheck(); // Createチェック LockedCheck(); //if ( m_pSurface == NULL ) // MyuThrow( 0, "CMglImage::CopyRectToOther() m_pSurfaceが取得されていません。"); // srcRectにNULLを指定された場合はフルで絵画 D3DXLoadSurfaceFromSurface( destSurface->GetSurfacePtr(), NULL, srcRect, m_pSurface, NULL, srcRect, D3DX_FILTER_POINT, 0 ); /* RECT srcRect2; _Rect(0,0, this->GetBmpWidth(), this->GetBmpHeight(), &srcRect2); D3DXLoadSurfaceFromSurface( destSurface->GetSurfacePtr(), NULL, &srcRect2, this->m_pSurface, NULL, &srcRect2, D3DX_FILTER_POINT, 0 ); */ /* これは全然駄目 d3d->UpdateTexture(this->m_pTexture, destSurface->GetDirect3dTexturePtr()); */ /* RECT _srcRect; if ( srcRect == NULL ) { srcRect = &_srcRect; _Rect( m_nBmpSizeX, m_nBmpSizeY, srcRect ); } POINT destPoint; destPoint.x = x; destPoint.y = y; // そのうちクリッピングさぽーとさせるぅ if ( m_pSurface == destSurface->GetSurfacePtr() ) MyuThrow(0,"CMglImage::CopyRectToOther() destSurfaceに自分自身のサーフェスを指定することは出来ません。"); //if (FAILED(d3d->CopyRects(m_pSurface, srcRect, 1, destSurface, &destPoint))) { //MyuAssert( d3d->CopyRects(m_pSurface, NULL, 1, destSurface, NULL), D3D_OK, MyuAssert( d3d->CopyRects(m_pSurface, srcRect, 1, destSurface->GetSurfacePtr(), &destPoint), D3D_OK, "CMglImage::CopyRectToOther() CopyRect()に失敗" ); */ } // このサーフェスにCopyRect void CMglImage::CopyRectToThis( CMglImage* srcSurface, RECT *srcRect, int x, int y ) { srcSurface->CopyRectToOther( this, srcRect, x, y ); } /* // このサーフェスにCopyRect void CMglImage::CopyRectToThis( CMglImage* srcSurface, RECT *srcRect, int x, int y ) { CreateCheck(); // Createチェック //if ( m_pSurface == NULL ) // MyuThrow( 0, "CMglImage::CopyRectToThis() m_pSurfaceが取得されていません。"); // srcRectにNULLを指定された場合はフルで絵画 RECT _srcRect; if ( srcRect == NULL ) { srcRect = &_srcRect; _Rect( m_nBmpSizeX, m_nBmpSizeY, srcRect ); } POINT destPoint; destPoint.x = x; destPoint.y = y; if ( m_pSurface == srcSurface->GetSurfacePtr() ) MyuThrow(0,"CMglImage::CopyRectToThis() srcSurfaceに自分自身のサーフェスを指定することは出来ません。"); //if (FAILED(d3d->CopyRects(srcSurface, srcRect, 1, m_pSurface, &destPoint))) { MyuAssert( d3d->CopyRects(srcSurface->GetSurfacePtr(), NULL, 0, m_pSurface, NULL), D3D_OK, "CMglImage::CopyRectToThis() CopyRect()に失敗" ); } */ /* どうせフォーマットエラー起こすので未サポート // 絵画(CopyRectを使用) void CMglImage::CopyRect( int x, int y, RECT *srcRect ) { CreateCheck(); // Createチェック CopyRectToOther( x, y, srcRect, m_myudg->_GetBackBuffer() ); } */
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 174 ] ] ]
f7f8c1230921b22c355bad9615aab32aa44b0da6
975d45994f670a7f284b0dc88d3a0ebe44458a82
/Docs/FINAIS/Fonte/servidor/WarBugsServer/WarBugsServer/Includes/CPersonagemJogador.h
35ba5093e5ad6c91df79be638ac50fcf9bb0aac7
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,003
h
#pragma once /* * Classe CPersonagemJogador * * Autor: Eder Figueiredo * * Objetivo: Descrever cada personagem controlado por um jogador * */ #ifndef _CPERSONAGEMJOGADOR_H_ #include <iostream> using namespace std; #include "CClientSocketThread.h" #ifndef _CPERSONAGEM_H_ #include "CPersonagem.h" #ifndef _CPERSONAGEM_H_ class CPersonagem; #endif #endif //#include "CHabilidadesSecundarias.h" //#include "CWarBugObject.h" //#include "CEquipamento.h" //#include "CHabilidades.h" //#include "CBolsa.h" //#include "CItem.h" //#include "CBonusPrimario.h" //#include "CHabilidades.h" //#include "CBonus.h" //#include "CBonusSecundario.h" //#include "CHabilidadesSecundarias.h" //#include "CBonus.h" #ifndef _CQUEST_H_ #include "CQuest.h" //#include "CLealdade.h" #ifndef _CQUEST_H_ class CQuest; #endif #endif #include "CDivisorXP.h" #define _CPERSONAGEMJOGADOR_H_ class CPersonagemJogador : public CPersonagem { CClientSocketThread *_socketJogador; int _skillLevel[3]; int _pontoDistribuir; int _skillPontoDistribuir; CEquipamento *_equip; //CBuff *_status; CLealdade *_lealdade; CQuest *_quest; //irr::core::array<CPersonagemJogador*> *_party; //irr::core::array<CPersonagemJogador*> *_friends; int _jogadorID; //Combate bool _bareHands; int _ataque; int _dano; int _range; int _speed; bool _tradeOn;// = false; bool _tradeConfirmation;// = false; int _idTrader;// = -1; int _idItemTrade;// = -1; int _idMoneyTrade;// = -1; public: CPersonagemJogador(); //Getters int getSkillLevel(int skillIndex); int getAttack(); int getDamage(); bool isTradeOn(); bool isTradeConfirmated(); int getIDTrader(); int getIDItemTrade(); int getIDMoneyTrade(); CLealdade *getLoyalty(); CEquipamento *getEquip(); int getPointsLeft(); int getSkillPointsLeft(); CClientSocketThread *getSocket(); //Setters void setPointsToDistribute(int points); void setSkillPointsToDistribute(int value); void setEquip(CEquipamento *equip); //void setStatus(CBuff *status); void setLoyalty(CLealdade *lealdade); //void setParty(irr::core::array<CPersonagemJogador*> *lista); //void setFriends(irr::core::array<CPersonagemJogador*> *lista); void setPlayer(int playerID); void setBareHands(bool isBareHands); void setAttack(int ataque); void setDamage(int dano); void setRange(int range); void setSpeed(int speed); void setTradeOn(bool value); void setTradeConfirmated(bool value); void setIDTrader(int value); void setIDItemTrade(int value); void setIDMoneyTrade(int value); void setSocket(CClientSocketThread * socket); //Outros Métodos //Manipulação de itens int haveItem(CItem * item); void addItem(CItem *item); void dropItem(CItem *item); void useItem(CItem *item); void equip(CItem *item); void unequip(CItem *item); //Friends Manipulation /*int isFriend(CPersonagemJogador *jogador); void addFriend(CPersonagemJogador *newFriend); void removeFriend(CPersonagemJogador *jogador); //Party Manipulation bool isPartyLeader(); int isPartyMember(CPersonagemJogador* jogador); void addPartyMember (CPersonagemJogador *jogador); void removePartyMember(CPersonagemJogador *jogador); void givePartyAlliesID(irr::core::array<CPersonagemJogador*> *lista); void updateAlliesID(); void createParty(); void joinParty(CPersonagemJogador *lider); void leaveParty(CPersonagemJogador *lider);*/ //Quest void acceptQuest(CQuest *quest); //Speaking void speakToPlayer(CPersonagemJogador *alvo); void speakToNPC(CPersonagem *alvo); //Batalha void takeDamage(int damage, CPersonagem *atkr); int getDEF(); bool tryAttack(); void attack(); //Level Up void updateXP(); bool haveLevelUp(); bool haveLevelDown(); void distibutePoints(int points, int atribute); void distibuteSkillPoints(int points, int skillIndex); void die(); void checkInventory(); void update(); }; #endif
[ [ [ 1, 155 ] ] ]
0eb714dbddffd8fe5b42e5e903c830a2786a3189
5a9924aff39460fa52f1f55ff387d9ab82c3470f
/tibia81/tibia/tibia.h
6f17d5b990c8fdbbeb9bb8a37c13680a9ad7d2ba
[]
no_license
PimentelM/evremonde
170e4f1916b0a1007c6dbe52b578db53bc6e70de
6b56e8461a602ea56f0eae47a96d340487ba987d
refs/heads/master
2021-01-10T16:03:38.410644
2010-12-04T17:31:01
2010-12-04T17:31:01
48,460,569
0
1
null
null
null
null
UTF-8
C++
false
false
6,201
h
#ifndef _TIBIA_H_ #define _TIBIA_H_ #include <string> #include "trainer.h" #include "tibiaconst.h" class CTibia { public: // constructor and deconstructor CTibia(); ~CTibia(); // trainer class CTrainer Trainer; // other bool findTibia(); HWND getTibiaWindow(); // calculations int calcExpForLevel(int level); // booleans bool isOnline(); bool isPlayerFlagged(Flag_t flagType); bool isPlayerFullHp(); bool isPlayerFullMp(); bool isPlayerWalking(); bool isTargetWalking(); bool isTargetVisible(); bool isTargetAlive(); bool isFullLightEnabled(); bool isLevelSpyEnabled(); bool isNameSpyEnabled(); bool isShowInvisibleCreaturesEnabled(); bool isWindowVisible(); // do void doLevelSpyInit(); void doLevelSpyUp(); void doLevelSpyDown(); void doReplaceMapTile(int oldTileId, int newTileId); void doReplaceMapObject(int oldObjectId, int newObjectId); void doShowFishingWater(); void doTreesToBushes(); void doAntiAfk(); void doKey(int virtualKey); void doKeyIme(int virtualKey); void doKeyCombo(int virtualKey, int virtualKeyModifier); void doHotkey(int hotkeyNumber); void doPlayerTurn(Direction_t direction); void doPlayerWalk(Direction_t direction); void doPlayerWalkTo(Location location); void doPlayerStop(); void doPlayerStopTo(); // set void setHotkeyByObject(int hotkeyNumber, int itemId, HotkeyType_t hotkeyType); void setHotkeyByText(int hotkeyNumber, std::string hotkeyText); void setFullLight(bool enable); void setLevelSpy(bool enable); void setNameSpy(bool enable); void setShowInvisibleCreatures(bool enable); void setRsaKey(unsigned char* key); void setFpsLimit(int fps); void setStatusbarText(std::string text); void setStatusbarTimer(int duration); void setLightAmount(LightAmount_t lightAmount); void setMouseId(Mouse_t mouseType); void setTargetId(int id); void setTargetType(CreatureType_t creatureType); void setTargetBattleListId(int id); void setTargetBattleListType(CreatureType_t creatureType); void setTargetFollowId(int id); void setTargetFollowType(CreatureType_t creatureType); void setPlayerBattleList(OffsetCreature_t offset, int value, int bytes); void setPlayerGoTo(Location location); void setPlayerGoToX(int x); void setPlayerGoToY(int y); void setPlayerGoToZ(int z); void setPlayerOutfit(Outfit_t outfitType); void setPlayerOutfitColors(OutfitColor_t head, OutfitColor_t body, OutfitColor_t legs, OutfitColor_t feet); void setPlayerOutfitAddon(OutfitAddon_t outfitAddon); void setPlayerLight(LightColor_t lightColor, LightRadius_t lightRadius); void setPlayerIsWalking(bool enable); void setTargetBattleList(OffsetCreature_t offset, int value, int bytes); void setTargetOutfit(Outfit_t outfitType); void setTargetOutfitAddon(OutfitAddon_t outfitAddon); void setTargetSkull(Skull_t skullType); // get int getHotkeyType(int hotkeyNumber); int getHotkeyByObject(int itemId, HotkeyType_t hotkeyType); int getHotkeyByText(std::string hotkeyText); int getExpToLevelUp(); int getConnectionStatus(); int getMapPointer(); int getWindowPointer(); int getFpsPointer(); std::string getWindowCaption(); int getFpsLimit(); std::string getStatusbarText(); int getStatusbarTimer(); int getLightAmount(); int getMouseId(); int getClickId(); int getClickCount(); int getClickX(); int getClickY(); int getClickZ(); Location getClickLocation(); int getSeeId(); int getSeeCount(); int getSeeX(); int getSeeY(); int getSeeZ(); std::string getSeeText(); Location getSeeLocation(); int getTargetId(); int getTargetType(); int getTargetBattleListId(); int getTargetBattleListType(); int getTargetFollowId(); int getTargetFollowType(); int getModeCombat(); int getModeFollow(); int getModeSecure(); int getTilesToGoCurrent(); int getTilesToGoTotal(); int getPlayerBattleList(OffsetCreature_t offset, int bytes); std::string getPlayerName(); int getPlayerId(); int getPlayerX(); int getPlayerY(); int getPlayerZ(); int getPlayerGoToX(); int getPlayerGoToY(); int getPlayerGoToZ(); int getPlayerExp(); int getPlayerLevel(); int getPlayerLevelPercent(); int getPlayerMagicLevel(); int getPlayerMagicLevelPercent(); int getPlayerHp(); int getPlayerHpMax(); int getPlayerMp(); int getPlayerMpMax(); int getPlayerSoul(); int getPlayerStamina(); int getPlayerCap(); int getPlayerFlags(); int getPlayerFishing(); int getPlayerShielding(); int getPlayerDistance(); int getPlayerAxe(); int getPlayerSword(); int getPlayerClub(); int getPlayerFist(); int getPlayerFishingPercent(); int getPlayerShieldingPercent(); int getPlayerDistancePercent(); int getPlayerAxePercent(); int getPlayerSwordPercent(); int getPlayerClubPercent(); int getPlayerFistPercent(); int getPlayerSlotHead(); int getPlayerSlotNeck(); int getPlayerSlotBackpack(); int getPlayerSlotChest(); int getPlayerSlotRight(); int getPlayerSlotLeft(); int getPlayerSlotLegs(); int getPlayerSlotFeet(); int getPlayerSlotRing(); int getPlayerSlotAmmo(); int getPlayerSlotRightCount(); int getPlayerSlotLeftCount(); int getPlayerSlotAmmoCount(); int getPlayerDirection(); int getPlayerOutfit(); int getPlayerOutfitHead(); int getPlayerOutfitBody(); int getPlayerOutfitLegs(); int getPlayerOutfitFeet(); int getPlayerLightRadius(); int getPlayerLightColor(); int getPlayerHpBar(); int getPlayerWalkSpeed(); int getPlayerSkull(); int getPlayerParty(); Location getPlayerLocation(); int getTargetBattleList(OffsetCreature_t offset, int bytes); std::string getTargetName(); int getTargetX(); int getTargetY(); int getTargetZ(); int getTargetDirection(); int getTargetOutfit(); int getTargetOutfitAddon(); int getTargetHpBar(); int getTargetSkull(); int getTargetParty(); Location getTargetLocation(); Item getItem(int itemId, int itemCount, std::string containerName, bool getNextItem, bool stackItem); }; #endif // #ifndef _TIBIA_H_
[ "evretibia@cc901e99-3b3f-0410-afbc-77a0fa429cc7" ]
[ [ [ 1, 264 ] ] ]
3f847fe8ed7bab1a1b67c0cc3c494d29ae5d1fb1
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/C++/练习/CleanTxtSameInfo/CleanTxtSameInfoView.h
684ee961bc48963f38178e09153a76a101b878d3
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
GB18030
C++
false
false
1,120
h
// CleanTxtSameInfoView.h : CCleanTxtSameInfoView 类的接口 // #pragma once class CCleanTxtSameInfoView : public CView { protected: // 仅从序列化创建 CCleanTxtSameInfoView(); DECLARE_DYNCREATE(CCleanTxtSameInfoView) // 属性 public: CCleanTxtSameInfoDoc* GetDocument() const; // 操作 public: // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 实现 public: virtual ~CCleanTxtSameInfoView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // CleanTxtSameInfoView.cpp 中的调试版本 inline CCleanTxtSameInfoDoc* CCleanTxtSameInfoView::GetDocument() const { return reinterpret_cast<CCleanTxtSameInfoDoc*>(m_pDocument); } #endif
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 49 ] ] ]
7ef40bc13440bcd6b9c3cda5959cbbfc08848e58
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Shape/HeightField/SampledHeightField/hkpSampledHeightFieldBaseCinfo.h
064c9607c3abe0662368a6d454550b2e802a0e1b
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,280
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKCOLLIDE_SHAPE_SAMPLEDHEIGHTFIELD_HKSAMPLEDHEIGHTFIELDBASECINFO_XML_H #define HKCOLLIDE_SHAPE_SAMPLEDHEIGHTFIELD_HKSAMPLEDHEIGHTFIELDBASECINFO_XML_H /// hkpSampledHeightFieldBaseCinfo meta information extern const class hkClass hkpSampledHeightFieldBaseCinfoClass; /// The information needed to construct an hkSampledHeightFieldBase class hkpSampledHeightFieldBaseCinfo { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpSampledHeightFieldBaseCinfo ); /// Default constructor hkpSampledHeightFieldBaseCinfo() { m_scale.set(1.0f, 1.0f, 1.0f); m_xRes = 2; m_zRes = 2; m_minHeight = 0.0f; m_maxHeight = -1.0f; m_useProjectionBasedHeight = false; } // // Members // public: /// The heigthfield scale in x,y,z. hkVector4 m_scale; /// The resolution along x. hkInt32 m_xRes; /// The resolution along z (y up). hkInt32 m_zRes; /// The minimum height returned by the heightfield. hkReal m_minHeight; /// The maximum height returned by the heightfield. Note: If m_maxHeight is set to /// less than m_minHeight than constructor will scan the entire heightfield) hkReal m_maxHeight; /// The method used to calculated the height. /// By default (m_useProjectionBasedHeight = false) the height will be measured by /// projecting the vertex down onto the heightfield and using this pure vertical /// distance. This results in a smooth distance function but fails for steep slopes. As /// a result objects hitting a steep slope can get extra energy. /// By setting m_useProjectionBasedHeight to true, the real distance between the point /// and the triangle will be measured. This allows for steep /// slopes but results in a non continuous distance function, which will cause objects /// to jitter when they cross triangle boundaries, especially objects with a big radius /// like spheres. hkBool m_useProjectionBasedHeight; }; #endif // HKCOLLIDE_SHAPE_SAMPLEDHEIGHTFIELD_HKSAMPLEDHEIGHTFIELDBASECINFO_XML_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 80 ] ] ]
4a494213b36c4334d31a668934c97be435410ece
d8f64a24453c6f077426ea58aaa7313aafafc75c
/GUI/DKGUILabel.h
9e02e50be82fdc54ba2fff9c2f0f14dd3f88661e
[]
no_license
dotted/wfto
5b98591645f3ddd72cad33736da5def09484a339
6eebb66384e6eb519401bdd649ae986d94bcaf27
refs/heads/master
2021-01-20T06:25:20.468978
2010-11-04T21:01:51
2010-11-04T21:01:51
32,183,921
1
0
null
null
null
null
UTF-8
C++
false
false
448
h
#ifndef DK_GUI_LABEL_H #define DK_GUI_LABEL_H #include "GUILabel.h" using namespace GUI; namespace DK_GUI { class CDKGUILabel: public CGUILabel { public: CDKGUILabel(char *caption); ~CDKGUILabel(); virtual GLvoid update(); /* updates the integer value of the label */ GLvoid int_update(GLint x=0); /* sets the integer value of the label */ GLvoid int_set(GLint x=0); }; } #endif // DK_GUI_LABEL_H
[ [ [ 1, 27 ] ] ]
f36074e8f19822d5328d9b710923ed47e4ff798c
b23a27888195014aa5bc123d7910515e9a75959c
/Main/V1.0/3rdLib/LightOPC/callback.cpp
0917cfe1f486bd0abffb2627a2443d4e43617c61
[]
no_license
fostrock/connectspot
c54bb5484538e8dd7c96b76d3096dad011279774
1197a196d9762942c0d61e2438c4a3bca513c4c8
refs/heads/master
2021-01-10T11:39:56.096336
2010-08-17T05:46:51
2010-08-17T05:46:51
50,015,788
1
0
null
null
null
null
UTF-8
C++
false
false
5,450
cpp
/************************************************************************** * * * Light OPC Server development library * * * * Copyright (c) 2000 by Timofei Bondarenko * * General call for callbacks **************************************************************************/ #include "privopc.h" #define loGET_IFACE(to,from,IFACE,model) (((to) = (IFACE*)(from))->AddRef()) /*********************************************************************************/ int LightOPCServer::send_callback(LightOPCGroup *grp, unsigned group_key, loUpdList *upl, int advmask) { int tr = 0; IOPCDataCallback *c_databack = 0; IAdviseSink *c_datatime = 0, *c_dataonly = 0, *c_writecomp = 0; unsigned cform_dtime, cform_donly, cform_wrcompl; OPCHANDLE client_handle; // UL_DEBUG((LOGID, "send_notify(){...")); if (!upl->used) { if (!upl->trqid) return 0; if (S_OK == upl->master_err) upl->master_err = S_FALSE; } if (FAILED(upl->master_err)) upl->master_qual = S_FALSE; if (!grp) { lock_read(); if (0 == (grp = by_handle_g(group_key))) { unlock(); UL_INFO((LOGID, "send_callback(%x) FAILED: No such group")); return 0; } } #if LO_USE_BOTHMODEL && 0 else group_key = grp->ServerHandle; #endif client_handle = grp->ClientHandle; /* There is only client_sched() thread allowed to change connection info under read_lock ! */ if ((advmask & loRQ_CONN_DATABACK) && grp->conn_databack) loGET_IFACE(c_databack, grp->conn_databack, IOPCDataCallback, grp->initphase); if (advmask & (loRQ_CONN_DATA_1 | loRQ_CONN_WRITECOMPL)) { if ((advmask & loRQ_CONN_DATATIME) && grp->conn_datatime) { cform_dtime = se->cform_datatime; loGET_IFACE(c_datatime, grp->conn_datatime, IAdviseSink, grp->initphase); /* ?? advise_present &= ~loRQ_CONN_DATATIME */ } if ((advmask & loRQ_CONN_DATAONLY) && grp->conn_dataonly) { cform_donly = se->cform_dataonly; loGET_IFACE(c_dataonly, grp->conn_dataonly, IAdviseSink, grp->initphase); /* ?? advise_present &= ~loRQ_CONN_DATAONLY */ } if ((advmask & loRQ_CONN_WRITECOMPL) && grp->conn_writecompl) { cform_wrcompl = se->cform_writecompl; loGET_IFACE(c_writecomp, grp->conn_writecompl, IAdviseSink, grp->initphase); /* ?? advise_present &= ~loRQ_CONN_WRITECOMPL */ } } unlock(); // UL_DEBUG((LOGID, "send_notify() #3")); if (c_databack) { HRESULT hr = E_INVALIDARG; switch(advmask & loRQ_OPER_MASK) { case loRQ_OP_REFRESH: hr = c_databack->OnDataChange(upl->trqid, client_handle, upl->master_err, upl->master_qual, upl->used, upl->opchandle, upl->variant, upl->quality, upl->timestamp, upl->errors); break; case loRQ_OP_READ: hr = c_databack->OnReadComplete(upl->transaction_id, client_handle, upl->master_err, upl->master_qual, upl->used, upl->opchandle, upl->variant, upl->quality, upl->timestamp, upl->errors); break; case loRQ_OP_WRITE: hr = c_databack->OnWriteComplete(upl->transaction_id, client_handle, upl->master_err, upl->used, upl->opchandle, upl->errors); break; case loRQ_OP_CANCEL: hr = c_databack->OnCancelComplete(upl->transaction_id, client_handle); break; } c_databack->Release(); if (S_OK == hr) { tr++; UL_DEBUG((LOGID, "OnDataChange2(0x%X) Ok", advmask)); } else { UL_WARNING((LOGID, "%!l OnDataChange2(0x%X) FAILED", hr, advmask)); } // UL_WARNING((LOGID, "OnDataChange() 2 Ok")); } if (advmask & loRQ_CONN_DATA_1) { HGLOBAL gmem = 0; unsigned datasize = 0; if (c_datatime) { // UL_DEBUG((LOGID, "OnDataChange1() with time")); if (0 <= lo_OnDataChange1(upl, client_handle, cform_dtime, 1, c_datatime, &gmem, &datasize)) tr++; c_datatime->Release(); } if (c_dataonly) { // UL_DEBUG((LOGID, "OnDataChange1() without time")); if (0 <= lo_OnDataChange1(upl, client_handle, cform_donly, 0, c_dataonly, &gmem, &datasize)) tr++; c_dataonly->Release(); } if (gmem && (// && (!GlobalSize(gmem) ||*/ GlobalFree(gmem))) //(GlobalFlags(gmem) & (GMEM_INVALID_HANDLE | GMEM_DISCARDED)) || GlobalFree(gmem) ) ) { UL_WARNING((LOGID, "%!L GlobalFree(%X) FAILED flags=0x%X", gmem, GlobalFlags(gmem))); } } else if (c_writecomp) { // UL_DEBUG((LOGID, "OnWriteComplete1()")); if (0 <= lo_OnWriteComplete1(upl, client_handle, cform_wrcompl, c_writecomp, 0)) tr++; c_writecomp->Release(); } // UL_DEBUG((LOGID, "send_datachange() finished}")); return tr; } /**************************************************************************/ /* end of callback.cpp */
[ [ [ 1, 160 ] ] ]
45270ac2348a874a6f1e9111ca25a14c25b02052
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Graphics/PostProcessFilter.h
3a7270d27ad67b55b85111821a31c586954fd8fe
[]
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
1,046
h
#ifndef __SLON_ENGINE_GRAPHICS_POST_PROCESS_FILTER_H__ #define __SLON_ENGINE_GRAPHICS_POST_PROCESS_FILTER_H__ #include "../Utility/referenced.hpp" #include "Forward.h" #include <sgl/RenderTarget.h> namespace slon { namespace graphics { /** Abstract interface for every post process filter */ class PostProcessFilter : public Referenced { public: /** Perform compoumd post effect chain. * @param renderTarget - render target for performing post effect. * For many post effects render target must contain two attachments * at the attachment points 0 and 1 for performing ping-ponging. * @param source - ping pong source texture (0 or 1). * @return number of ping pong switches, usually 1. */ virtual unsigned perform( sgl::RenderTarget* renderTarget, unsigned source ) const = 0; virtual ~PostProcessFilter() {} }; } // namespace graphics } // namespace slon #endif // __SLON_ENGINE_GRAPHICS_POST_PROCESS_FILTER_H__
[ "devnull@localhost" ]
[ [ [ 1, 32 ] ] ]
6754ac15f224542e2af1926aa5e69fe2ff6208f2
2ff4099407bd04ffc49489f22bd62996ad0d0edd
/Project/Code/src/PhotographicToneMapper.cpp
b39671606c9fab3c1e427a693765039c4055c30e
[]
no_license
willemfrishert/imagebasedrendering
13687840a8e5b37a38cc91c3c5b8135f9c1881f2
1cb9ed13b820b791a0aa2c80564dc33fefdc47a2
refs/heads/master
2016-09-10T15:23:42.506289
2007-06-04T11:52:13
2007-06-04T11:52:13
32,184,690
0
1
null
null
null
null
UTF-8
C++
false
false
6,518
cpp
#include <gl/glew.h> #include "ShaderObject.h" #include "ShaderUniformValue.h" #include "ShaderProgram.h" #include "GPUParallelReductor.h" #include "Utility.h" #include "CodecRGBE.h" #include "PhotographicToneMapper.h" PhotographicToneMapper::PhotographicToneMapper(GLuint aOriginalTexture, GLuint aLuminanceTexture, int aWidth, int aHeight) : iOriginalTexture( aOriginalTexture ) , iLuminanceTexture( aLuminanceTexture ) , iWidth( aWidth ) , iHeight( aHeight ) , iPreviousExposure( 1.0 ) , iBaseExposure( 1.0 ) { this->iLogAverageCalculator = new GPUParallelReductor(aWidth, aHeight, "./shader/logsumFP.frag", GL_RGBA_FLOAT32_ATI); initShaders("./shader/photoToneMapper.frag"); } PhotographicToneMapper::~PhotographicToneMapper(void) { delete iLogAverageCalculator; } /** * @param aOriginalTexture * @param aLuminanceTexture */ void PhotographicToneMapper::toneMap(GLuint aOriginalTexture, GLuint aLuminanceTexture) { // Compute Log information: LOG AVERAGE, MIN and MAX float logStatistics[4]; iLogAverageCalculator->processData(aLuminanceTexture, logStatistics); float logAverage = exp( (logStatistics[0] / (float)(iHeight * iWidth))); //printf("Key: %f\t\tLogAverage: %f\t\tPre-Exposure: %f\n", key, logAverage, correctExposure); //printf("Lavg: %f\t\tScale: %f\n", logAverage, scale); //printf("CORRECT: %f\t\CURRENT: %f\t\t NEW: %f\n", correctExposure, iPreviousExposure, newExposure); //printf("LOGAVERAGE: %f\t\logMin: %f\t\t LogMax: %f\n", logAverage, logStatistics[3], logStatistics[2]); float currentExposure = computeCurrentExposure(logAverage, logStatistics[3], logStatistics[2]); iExposureUniform->setValue( currentExposure ); //printf("Exposure: %f\n", currentExposure); iShaderProgram->useProgram(); { renderSceneOnQuad(aOriginalTexture, aLuminanceTexture); } iShaderProgram->disableProgram(); } /** * @param aValue the value of exposure; it will be clamped to [0, 1] */ void PhotographicToneMapper::setExposure(float aValue) { //aValue = aValue > 1.0 ? 1.0 : aValue; aValue = aValue < 0.0 ? 1e-10 : aValue; this->iExposureUniform->setValue( aValue ); printf("Exposure Set: %f\n", aValue); } /** * @return the value of the exposure */ float PhotographicToneMapper::getExposure() { return this->iExposureUniform->getValue(); } /************************************************************************/ /* ****************** PRIVATE METHODS ************** */ /************************************************************************/ /** * @param aLogLAverage the log luminance average * @param aLogLMin the log luminance minimum * @param aLogLMax the log luminance maximum * @return the current scene exposure */ float PhotographicToneMapper::computeCurrentExposure( float aLogLAverage, float aMinLuminance, float aMaxLuminance ) { // Key of the Scene: the log2(log(Luminance)) is on purpose float Log2LMin = Utility::log2(aMinLuminance + 1e-8); float Log2LMax = Utility::log2(aMaxLuminance + 1e-8); #ifdef _DEBUG assert(aLogLAverage >= 1e-8); #endif // _DEBUG float f = (2 * Utility::log2(aLogLAverage) - Log2LMin - Log2LMax) / (Log2LMax - Log2LMin); float key = 1.2f * pow(4.0f, f); static int frameCount = 0; float correctExposure = key / aLogLAverage; Utility::clamp(correctExposure, 0.1f, correctExposure); // store the correct as the base every 0.5 sec if ( frameCount == 0 ) { iBaseExposure = correctExposure; } float deltaExposure = (correctExposure + iBaseExposure) / 2.0f - iPreviousExposure; float ratio = 0.1f; //std::cout << "ratio: " << ratio << "\t\tDELTA: " << deltaExposure << std::endl; float currentExposure = iPreviousExposure + deltaExposure * ratio; //printf("CORRECT: %f\t\CURRENT: %f\t\t NEW: %f\n", correctExposure, iPreviousExposure, currentExposure); //printf("LOG AVERAGE: %f\t MAX: %f\t MIN: %f \tKEY: %f\n", aLogLAverage, aMaxLuminance, aMinLuminance, key); iPreviousExposure = currentExposure; // update frameCount frameCount = (frameCount + 1) % 25; return iPreviousExposure; } void PhotographicToneMapper::enableMultitexturing( GLuint aOriginalTexture, GLuint aLuminanceTexture ) { // enable multitexturing glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, aOriginalTexture); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, aLuminanceTexture); } void PhotographicToneMapper::disableMultitexturing() { // GL_TEXTURE1: Luminance Texture glActiveTexture( GL_TEXTURE1 ); glDisable(GL_TEXTURE_2D); // GL_TEXTURE0: Original Texture glActiveTexture( GL_TEXTURE0 ); //glDisable(GL_TEXTURE_2D); } void PhotographicToneMapper::renderSceneOnQuad(GLuint aOriginalTexture, GLuint aLuminanceTexture) { glMatrixMode( GL_PROJECTION ); glPushMatrix(); { glLoadIdentity(); gluOrtho2D( 0.0f, 1.0f, 0.0f, 1.0f); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); { glLoadIdentity(); // setup flags and bind textures enableMultitexturing(aOriginalTexture, aLuminanceTexture); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f ); glVertex2f(0.0, 0.0); glTexCoord2f(1.0f, 0.0f ); glVertex2f(1.0f, 0.0); glTexCoord2f(1.0f, 1.0f ); glVertex2f(1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f ); glVertex2f(0.0, 1.0f); glEnd(); } //End GL_PROJECTION glPopMatrix(); glMatrixMode( GL_PROJECTION ); } glPopMatrix(); // End GL_PROJECTION glMatrixMode( GL_MODELVIEW ); disableMultitexturing(); } void PhotographicToneMapper::initShaders( string fragmentShaderFilename ) { iShaderProgram = new ShaderProgram(); iOriginalTextureUniform = new ShaderUniformValue<int>(); iExposureUniform = new ShaderUniformValue<float>(); iFragmentShader = new ShaderObject(GL_FRAGMENT_SHADER, fragmentShaderFilename); // Initialize Uniform Variables iOriginalTextureUniform->setValue( 0 ); iOriginalTextureUniform->setName("originalTex"); iExposureUniform->setValue( 1.0f ); iExposureUniform->setName("exposure"); iShaderProgram->attachShader( *iFragmentShader ); iShaderProgram->attachShader( *CodecRGBE::getShaderObject() ); iShaderProgram->addUniformObject( iOriginalTextureUniform ); iShaderProgram->addUniformObject( iExposureUniform ); // after all the shaders have been attached iShaderProgram->buildProgram(); }
[ "jpjorge@15324175-3028-0410-9899-2d1205849c9d" ]
[ [ [ 1, 222 ] ] ]
c6993e098810a364acf68a6c43eb3d914ead9345
c82d009662b7b3da2707a577a3143066d128093a
/numeric/subset/subset.h
9e1f4bf32cda795e4664fb7c40d1aa334848ac25
[]
no_license
canilao/cpp_framework
01a2c0787440d9fca64dbb0fb10c1175a4f7d198
da5c612e8f15f6987be0c925f46e854b2e703d73
refs/heads/master
2021-01-10T13:26:39.376268
2011-02-04T16:26:26
2011-02-04T16:26:26
49,291,836
1
0
null
null
null
null
UTF-8
C++
false
false
22,211
h
/******************************************************************************* \file subset.h \brief Subset solver library. \note C Anilao 02/03/2009 Created. *******************************************************************************/ #ifndef SUBSET_H #define SUBSET_H #include <set> #include <map> #include <vector> #include <numeric> #include <algorithm> #include <exception> namespace numeric { /******************************************************************************* \brief Map of values to counts. \note C Anilao 02/03/2009 Created. *******************************************************************************/ typedef std::map<int, int> TValueMap; /******************************************************************************* \brief A set of unique values that are retrieve from a TValueMap. \note C Anilao 02/03/2009 Created. *******************************************************************************/ typedef std::set<int> TValues; /******************************************************************************* \brief A group of numbers who's sum can represent a range of numbers. \note C Anilao 02/03/2009 Created. *******************************************************************************/ typedef std::vector<int> TBlock; /******************************************************************************* \brief Vector numbers representing a solution to a target number. \note C Anilao 02/03/2009 Created. *******************************************************************************/ typedef std::vector<int> TSolution; /******************************************************************************* \brief A group of number groups who's sum can represent a range of numbers. \note C Anilao 02/03/2009 Created. *******************************************************************************/ typedef std::vector<TBlock> TBlockVector; /******************************************************************************* \brief A set of numbers that are to be used to solve a target number. \note C Anilao 02/03/2009 Created. *******************************************************************************/ typedef std::vector<int> TDispenser; /******************************************************************************* \class Class to solve subsets of groups of numbers. \brief Given a group of numbers and a target number, this class will calculate what group of subset of numbers summed together can equal the target number. *******************************************************************************/ class subset { private: // Given the values and the counts, this represents the optimum number set. TBlock definition; // Low number representable by the definition. int range_low; // High number representable by the definition. int range_high; // The values of the number set. TValues values; // The dispenser that holds all of the numbers. TDispenser master_dispenser; // Maps the value to the count. TValueMap value_map; // The vector of whole blocks. TBlockVector whole_blocks; // The vector of partial blocks. TBlockVector partial_blocks; public: // Constructor. subset(const TValueMap & values); // Destructor. virtual ~subset(); // Gets the range the target should be for the Anilao solver. void GetRange(int & low, int & high); // Gets the optimum set of numbers a block should be for this set. void GetBlockDefinition(TBlock & client_block); // Gets the list of whole blocks. void GetWholeBlockVector(TBlockVector & client_block); // Gets the list of partial blocks. void GetPartialBlockVector(TBlockVector & client_block); // Uses the generic least number algorithm. TSolution LeastSolve(int target); // Algorithm which tries to deplete the values as even as possible. TSolution AnilaoSolve(int target); protected: // Initializes the class. void Initialize(); // Solve with least algorithm, but only on the given dispenser. TSolution LeastSolveOnDispenser(int target, const TDispenser & dispenser) const; // Returns left over. TBlockVector CalculatePartialBlocks(const TDispenser & original_dispenser, TDispenser & left_over); // Returns left over. TBlockVector CalculateWholeBlocks(const TDispenser & original_dispenser, TDispenser & left_over); // Calculates the optimum set of number each block should be. TBlock CalculateDefinition(int & low, int & high); private: // Execute a recursive subset solving algorithm. void SubsetRecurse(TBlock numbers, TBlockVector & result, int target, TSolution & output, int index, int sum); }; /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline subset::subset(const TValueMap & values) : value_map(values) { Initialize(); } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline subset::~subset() {} /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline void subset::GetRange(int & low, int & high) { // Set the values and return. low = range_low; high = range_high; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline void subset::GetBlockDefinition(TBlock & client_block) { client_block = definition; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline void subset::GetWholeBlockVector(TBlockVector & client_block) { client_block = whole_blocks; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline void subset::GetPartialBlockVector(TBlockVector & client_block) { client_block = partial_blocks; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline TSolution subset::LeastSolve(int target) { // Return vector. TSolution ret_vector; // Record of how much we still need to fill. int running_total = target; // Go through all of the values in the value map. for(TValueMap::reverse_iterator iter = value_map.rbegin() ; iter != value_map.rend() ; ++iter) { if(running_total >= iter->first) { // Find out how many we want. int desired_count = running_total / iter->first; // Get as many as we can. int retrieved_count = desired_count > iter->second ? iter->second : desired_count; // Decrement the count because we found a value. if((retrieved_count * iter->first) % running_total != 0) { running_total -= (retrieved_count * iter->first) % running_total; } else { // These numbers. if(retrieved_count > 0) { ret_vector.insert(ret_vector.begin(), retrieved_count, iter->first); } // We have our solution, lets get out. break; } // These numbers. if(retrieved_count > 0) { ret_vector.insert(ret_vector.begin(), retrieved_count, iter->first); } } } // If the total does not equal the target, cannot find a solution. // In this case we will return an empty. if(accumulate(ret_vector.begin(), ret_vector.end(), 0) != target) { ret_vector.clear(); } return ret_vector; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline TSolution subset::LeastSolveOnDispenser(int target, const TDispenser & dispenser) const { TValues values; // Use a set to get the unique value from the dispenser. for(size_t i = 0 ; i < dispenser.size() ; ++i) { values.insert(dispenser[i]); } TValueMap value_map; // We have the unique values from the dispenser, count them and add to // value map. for(TValues::iterator iter = values.begin() ; iter != values.end() ; ++iter) { ptrdiff_t val_count = count(dispenser.begin(), dispenser.end(), *iter); value_map[*iter] = (int) val_count; } // Create a subset class and use LeastSolve(). TSolution ret_solution; try { subset local(value_map); ret_solution = local.LeastSolve(target); } catch(...) {} // Return the solution. return ret_solution; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline TSolution subset::AnilaoSolve(int target) { // Return value. TSolution ret_val; // Will hold the result. TBlockVector result; // Recurse function needs a buffer, unused in this scope. TSolution solution_buffer; // Check partials first. Use GetWholeBlockVector() to get partial dispenser. TDispenser partial_dispenser; CalculateWholeBlocks(master_dispenser, partial_dispenser); TSolution least_solution = LeastSolveOnDispenser(target, partial_dispenser); // Add the solution to the result if there was one. if(!least_solution.empty()) result.push_back(least_solution); if(result.size() == 0) { // We have to try the whole blocks. if(whole_blocks.size() != 0) { // Allocate the results vector and run the algorithm. SubsetRecurse(whole_blocks[0], result, target, solution_buffer, 0, 0); } } if(result.size() > 0) { // Find the result with the largest size. std::map<size_t, size_t> sizes; for(size_t i = 0 ; i < result.size() ; ++i) { sizes[i] = result[i].size(); } // Find the smallest and use it. std::map<size_t, size_t>::iterator smallest_iter = sizes.begin(); for(std::map<size_t, size_t>::iterator iter = sizes.begin() ; iter != sizes.end() ; ++iter) { if(iter->second < smallest_iter->second) { smallest_iter = iter; } } // We have found the largest. ret_val = result[smallest_iter->first]; } return ret_val; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline void subset::Initialize() { // Vector of entries to be removed. std::vector<TValueMap::iterator> to_be_removed; // Find all to be removed. for(TValueMap::iterator iter = value_map.begin() ; iter != value_map.end() ; ++iter) { // Only consider numbers that have counts. if(iter->second <= 0) { // Remove zero counts from the map. to_be_removed.push_back(iter); } } // Physically remove the empty values from value_map. for(std::vector<TValueMap::iterator>::iterator iter = to_be_removed.begin(); iter != to_be_removed.end() ; ++iter) { value_map.erase(*iter); } // If we are empty still, we need to throw an assert. if(value_map.empty()) throw std::exception(); // Get all of the keys and fill the master dispenser. for(TValueMap::iterator iter = value_map.begin() ; iter != value_map.end() ; ++iter) { // Save the values. values.insert(iter->first); // Fill up the master dispenser. master_dispenser.insert(master_dispenser.end(), iter->second, iter->first); } // Calculate our new definition. definition = CalculateDefinition(range_low, range_high); // Calcluate our whole blocks. TDispenser left_over; whole_blocks = CalculateWholeBlocks(master_dispenser, left_over); // Must calculate the partial blocks. TDispenser empty_dispenser; partial_blocks = CalculatePartialBlocks(left_over, empty_dispenser); } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline TBlockVector subset::CalculatePartialBlocks(const TDispenser & original_dispenser, TDispenser & left_over) { // Make a copy of the dispenser. left_over = original_dispenser; TBlockVector retVal; // If we don't match by now, something is wrong. if(definition.size() != value_map.size()) throw std::exception(); int index = 0; TValueMap::iterator highest = value_map.begin(); // Get the highest weighed count. for(TValueMap::iterator iter = value_map.begin() ; iter != value_map.end() ; ++iter, ++index) { // If this count is higher, then we have a new winner. if(iter->second > highest->second) { highest = iter; } } // For each of the highest count, do best to make a full set. for(int i = 0 ; i < highest->second ; ++i) { TBlock new_block; TValues::iterator iter = values.begin(); for(size_t j = 0 ; j < values.size() ; ++j) { // Remove all of the values. for(int k = 0 ; k < definition[j] ; ++k) { // Remove all of the values. TDispenser::iterator value_iter = find(left_over.begin(), left_over.end(), *iter); if(value_iter != left_over.end()) { new_block.push_back(*value_iter); left_over.erase(value_iter); } } ++iter; } if(new_block.size() != 0) retVal.push_back(new_block); } return retVal; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline TBlockVector subset::CalculateWholeBlocks(const TDispenser & original_dispenser, TDispenser & left_over) { // Make a copy of the dispenser. left_over = original_dispenser; TBlockVector retVal; // If we don't match by now, something is wrong. if(definition.size() != value_map.size()) throw std::exception(); int index = 0; TValueMap::iterator lowest = value_map.begin(); int lowest_divisor = definition[0]; // Get the lowest weighed count. for(TValueMap::iterator iter = value_map.begin() ; iter != value_map.end() ; ++iter, ++index) { // Calculate our current weight. int weight = iter->second / definition[index]; // If this weight is lower, then we have a new winner. if(weight < (lowest->second / lowest_divisor)) { lowest = iter; lowest_divisor = definition[index]; } } // Remove all of these number from the left_over dispenser. for(int i = 0 ; i < lowest->second / lowest_divisor ; ++i) { TBlock new_block; TValues::iterator iter = values.begin(); for(size_t j = 0 ; j < values.size() ; ++j) { // Remove all of the values. for(int k = 0 ; k < definition[j] ; ++k) { // Remove all of the values. TDispenser::iterator value_iter = find(left_over.begin(), left_over.end(), *iter); if(value_iter != left_over.end()) { new_block.push_back(*value_iter); left_over.erase(value_iter); } } ++iter; } retVal.push_back(new_block); } return retVal; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline TBlock subset::CalculateDefinition(int & low, int & high) { TBlock local_definition; // The lowest value is the low range, set it now. TValues::const_iterator iter = min_element(values.begin(), values.end()); // Make sure we found something before we dereference. if(values.end() != iter) { low = *iter; } // Used to calculate the definition. int running_count = 0; // For each value, we need find the how many of those numbers we need // to reach the next higher value. e.g. it takes four ones to get to 5. std::vector<int> tempset(values.begin(), values.end()); for(int i = 0 ; i != tempset.size() ; ++i) { try { // Calculate our definition. int gap = tempset.at(i + 1) - running_count; if((gap / tempset.at(i)) == 0) { // In the case we are going to set a zero, set to one. // Because we want to get rid of those values later. running_count += tempset.at(i); local_definition.push_back(1); } else if(((gap / tempset.at(i)) > 0) && (gap % tempset.at(i) > 0)) { // Case to round up. int roundup = (gap / tempset.at(i)) + 1; // Update the count. running_count += roundup * tempset.at(i); // Save our number to our new definition. local_definition.push_back(roundup); } else { // Update the count. running_count += (gap / tempset.at(i)) * tempset.at(i); // Save our number to our new definition. local_definition.push_back(gap / tempset.at(i)); } } catch(...) { // If we are at the last element, set to 1. local_definition.push_back(1); // Get our max range. high = tempset.at(i) + running_count; } } return local_definition; } /******************************************************************************* \brief \note C Anilao 02/03/2009 Created. *******************************************************************************/ inline void subset::SubsetRecurse(TBlock numbers, TBlockVector & result, int target, TSolution & output, int index, int sum) { if (index == numbers.size()) { if(accumulate(output.begin(), output.end(), (int) 0) == target) { std::vector<std::vector<int> >::iterator iter = find(result.begin(), result.end(), output); if(iter == result.end()) result.push_back(output); } return; } // Include numbers[index] TSolution p1 = output; p1.push_back(numbers[index]); SubsetRecurse(numbers, result, target, p1, index + 1, sum + numbers[index]); // Exclude numbers[index] SubsetRecurse(numbers, result, target, output, index + 1, sum); } } #endif
[ "anilaoc@55e5c601-11dd-bd4b-a960-93a593583956" ]
[ [ [ 1, 739 ] ] ]
90fd9bc37d5c9eb1aa30725451a8ec7f0affc885
4a99fa98abd0285bc3b5671f237b932114123340
/physics/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp
c14e1357f11679897637d251454b421b593e8b7a
[]
no_license
automenta/crittergod1.5
937cd925a4ba57b3e8cfa4899a81ba24fe3e4138
4786fe9d621c0e61cdd43ca3a363bfce6510e3c0
refs/heads/master
2020-12-24T16:58:32.854270
2010-04-12T03:25:39
2010-04-12T03:25:39
520,917
1
0
null
null
null
null
UTF-8
C++
false
false
32,936
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btDiscreteDynamicsWorld.h" //collision detection #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" #include "LinearMath/btTransformUtil.h" #include "LinearMath/btQuickprof.h" //rigidbody & constraints #include "BulletDynamics/Dynamics/btRigidBody.h" #include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h" #include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h" #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" #include "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h" #include "BulletDynamics/ConstraintSolver/btHingeConstraint.h" #include "BulletDynamics/ConstraintSolver/btConeTwistConstraint.h" #include "BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h" #include "BulletDynamics/ConstraintSolver/btSliderConstraint.h" #include "LinearMath/btIDebugDraw.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletDynamics/Dynamics/btActionInterface.h" #include "LinearMath/btQuickprof.h" #include "LinearMath/btMotionState.h" btDiscreteDynamicsWorld::btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration) :btDynamicsWorld(dispatcher,pairCache,collisionConfiguration), m_constraintSolver(constraintSolver), m_gravity(0,-10,0), m_localTime(btScalar(1.)/btScalar(60.)), m_synchronizeAllMotionStates(false), m_profileTimings(0) { if (!m_constraintSolver) { void* mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver),16); m_constraintSolver = new (mem) btSequentialImpulseConstraintSolver; m_ownsConstraintSolver = true; } else { m_ownsConstraintSolver = false; } { void* mem = btAlignedAlloc(sizeof(btSimulationIslandManager),16); m_islandManager = new (mem) btSimulationIslandManager(); } m_ownsIslandManager = true; } btDiscreteDynamicsWorld::~btDiscreteDynamicsWorld() { //only delete it when we created it if (m_ownsIslandManager) { m_islandManager->~btSimulationIslandManager(); btAlignedFree( m_islandManager); } if (m_ownsConstraintSolver) { m_constraintSolver->~btConstraintSolver(); btAlignedFree(m_constraintSolver); } } void btDiscreteDynamicsWorld::saveKinematicState(btScalar timeStep) { ///would like to iterate over m_nonStaticRigidBodies, but unfortunately old API allows ///to switch status _after_ adding kinematic objects to the world ///fix it for Bullet 3.x release for (int i=0;i<m_collisionObjects.size();i++) { btCollisionObject* colObj = m_collisionObjects[i]; btRigidBody* body = btRigidBody::upcast(colObj); if (body && body->getActivationState() != ISLAND_SLEEPING) { if (body->isKinematicObject()) { //to calculate velocities next frame body->saveKinematicState(timeStep); } } } } void btDiscreteDynamicsWorld::debugDrawWorld() { BT_PROFILE("debugDrawWorld"); btCollisionWorld::debugDrawWorld(); bool drawConstraints = false; if (getDebugDrawer()) { int mode = getDebugDrawer()->getDebugMode(); if(mode & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits)) { drawConstraints = true; } } if(drawConstraints) { for(int i = getNumConstraints()-1; i>=0 ;i--) { btTypedConstraint* constraint = getConstraint(i); debugDrawConstraint(constraint); } } if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb)) { int i; if (getDebugDrawer() && getDebugDrawer()->getDebugMode()) { for (i=0;i<m_actions.size();i++) { m_actions[i]->debugDraw(m_debugDrawer); } } } } void btDiscreteDynamicsWorld::clearForces() { ///@todo: iterate over awake simulation islands! for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; //need to check if next line is ok //it might break backward compatibility (people applying forces on sleeping objects get never cleared and accumulate on wake-up body->clearForces(); } } ///apply gravity, call this once per timestep void btDiscreteDynamicsWorld::applyGravity() { ///@todo: iterate over awake simulation islands! for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body->isActive()) { body->applyGravity(); } } } void btDiscreteDynamicsWorld::synchronizeSingleMotionState(btRigidBody* body) { btAssert(body); if (body->getMotionState() && !body->isStaticOrKinematicObject()) { //we need to call the update at least once, even for sleeping objects //otherwise the 'graphics' transform never updates properly ///@todo: add 'dirty' flag //if (body->getActivationState() != ISLAND_SLEEPING) { btTransform interpolatedTransform; btTransformUtil::integrateTransform(body->getInterpolationWorldTransform(), body->getInterpolationLinearVelocity(),body->getInterpolationAngularVelocity(),m_localTime*body->getHitFraction(),interpolatedTransform); body->getMotionState()->setWorldTransform(interpolatedTransform); } } } void btDiscreteDynamicsWorld::synchronizeMotionStates() { BT_PROFILE("synchronizeMotionStates"); if (m_synchronizeAllMotionStates) { //iterate over all collision objects for ( int i=0;i<m_collisionObjects.size();i++) { btCollisionObject* colObj = m_collisionObjects[i]; btRigidBody* body = btRigidBody::upcast(colObj); if (body) synchronizeSingleMotionState(body); } } else { //iterate over all active rigid bodies for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body->isActive()) synchronizeSingleMotionState(body); } } } int btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep) { startProfiling(timeStep); BT_PROFILE("stepSimulation"); int numSimulationSubSteps = 0; if (maxSubSteps) { //fixed timestep with interpolation m_localTime += timeStep; if (m_localTime >= fixedTimeStep) { numSimulationSubSteps = int( m_localTime / fixedTimeStep); m_localTime -= numSimulationSubSteps * fixedTimeStep; } } else { //variable timestep fixedTimeStep = timeStep; m_localTime = timeStep; if (btFuzzyZero(timeStep)) { numSimulationSubSteps = 0; maxSubSteps = 0; } else { numSimulationSubSteps = 1; maxSubSteps = 1; } } //process some debugging flags if (getDebugDrawer()) { btIDebugDraw* debugDrawer = getDebugDrawer (); gDisableDeactivation = (debugDrawer->getDebugMode() & btIDebugDraw::DBG_NoDeactivation) != 0; } if (numSimulationSubSteps) { saveKinematicState(fixedTimeStep); applyGravity(); //clamp the number of substeps, to prevent simulation grinding spiralling down to a halt int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps)? maxSubSteps : numSimulationSubSteps; for (int i=0;i<clampedSimulationSteps;i++) { internalSingleStepSimulation(fixedTimeStep); synchronizeMotionStates(); } } else { synchronizeMotionStates(); } clearForces(); #ifndef BT_NO_PROFILE CProfileManager::Increment_Frame_Counter(); #endif //BT_NO_PROFILE return numSimulationSubSteps; } void btDiscreteDynamicsWorld::internalSingleStepSimulation(btScalar timeStep) { BT_PROFILE("internalSingleStepSimulation"); if(0 != m_internalPreTickCallback) { (*m_internalPreTickCallback)(this, timeStep); } ///apply gravity, predict motion predictUnconstraintMotion(timeStep); btDispatcherInfo& dispatchInfo = getDispatchInfo(); dispatchInfo.m_timeStep = timeStep; dispatchInfo.m_stepCount = 0; dispatchInfo.m_debugDraw = getDebugDrawer(); ///perform collision detection performDiscreteCollisionDetection(); calculateSimulationIslands(); getSolverInfo().m_timeStep = timeStep; ///solve contact and other joint constraints solveConstraints(getSolverInfo()); ///CallbackTriggers(); ///integrate transforms integrateTransforms(timeStep); ///update vehicle simulation updateActions(timeStep); updateActivationState( timeStep ); if(0 != m_internalTickCallback) { (*m_internalTickCallback)(this, timeStep); } } void btDiscreteDynamicsWorld::setGravity(const btVector3& gravity) { m_gravity = gravity; for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body->isActive()) { body->setGravity(gravity); } } } btVector3 btDiscreteDynamicsWorld::getGravity () const { return m_gravity; } void btDiscreteDynamicsWorld::addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup,short int collisionFilterMask) { btCollisionWorld::addCollisionObject(collisionObject,collisionFilterGroup,collisionFilterMask); } void btDiscreteDynamicsWorld::removeCollisionObject(btCollisionObject* collisionObject) { btRigidBody* body = btRigidBody::upcast(collisionObject); if (body) removeRigidBody(body); else btCollisionWorld::removeCollisionObject(collisionObject); } void btDiscreteDynamicsWorld::removeRigidBody(btRigidBody* body) { m_nonStaticRigidBodies.remove(body); btCollisionWorld::removeCollisionObject(body); } void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body) { if (!body->isStaticOrKinematicObject()) { body->setGravity(m_gravity); } if (body->getCollisionShape()) { if (!body->isStaticObject()) { m_nonStaticRigidBodies.push_back(body); } else { body->setActivationState(ISLAND_SLEEPING); } bool isDynamic = !(body->isStaticObject() || body->isKinematicObject()); short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter); short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter); addCollisionObject(body,collisionFilterGroup,collisionFilterMask); } } void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body, short group, short mask) { if (!body->isStaticOrKinematicObject()) { body->setGravity(m_gravity); } if (body->getCollisionShape()) { if (!body->isStaticObject()) { m_nonStaticRigidBodies.push_back(body); } else { body->setActivationState(ISLAND_SLEEPING); } addCollisionObject(body,group,mask); } } void btDiscreteDynamicsWorld::updateActions(btScalar timeStep) { BT_PROFILE("updateActions"); for ( int i=0;i<m_actions.size();i++) { m_actions[i]->updateAction( this, timeStep); } } void btDiscreteDynamicsWorld::updateActivationState(btScalar timeStep) { BT_PROFILE("updateActivationState"); for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body) { body->updateDeactivation(timeStep); if (body->wantsSleeping()) { if (body->isStaticOrKinematicObject()) { body->setActivationState(ISLAND_SLEEPING); } else { if (body->getActivationState() == ACTIVE_TAG) body->setActivationState( WANTS_DEACTIVATION ); if (body->getActivationState() == ISLAND_SLEEPING) { body->setAngularVelocity(btVector3(0,0,0)); body->setLinearVelocity(btVector3(0,0,0)); } } } else { if (body->getActivationState() != DISABLE_DEACTIVATION) body->setActivationState( ACTIVE_TAG ); } } } } void btDiscreteDynamicsWorld::addConstraint(btTypedConstraint* constraint,bool disableCollisionsBetweenLinkedBodies) { m_constraints.push_back(constraint); if (disableCollisionsBetweenLinkedBodies) { constraint->getRigidBodyA().addConstraintRef(constraint); constraint->getRigidBodyB().addConstraintRef(constraint); } } void btDiscreteDynamicsWorld::removeConstraint(btTypedConstraint* constraint) { m_constraints.remove(constraint); constraint->getRigidBodyA().removeConstraintRef(constraint); constraint->getRigidBodyB().removeConstraintRef(constraint); } void btDiscreteDynamicsWorld::addAction(btActionInterface* action) { m_actions.push_back(action); } void btDiscreteDynamicsWorld::removeAction(btActionInterface* action) { m_actions.remove(action); } void btDiscreteDynamicsWorld::addVehicle(btActionInterface* vehicle) { addAction(vehicle); } void btDiscreteDynamicsWorld::removeVehicle(btActionInterface* vehicle) { removeAction(vehicle); } void btDiscreteDynamicsWorld::addCharacter(btActionInterface* character) { addAction(character); } void btDiscreteDynamicsWorld::removeCharacter(btActionInterface* character) { removeAction(character); } SIMD_FORCE_INLINE int btGetConstraintIslandId(const btTypedConstraint* lhs) { int islandId; const btCollisionObject& rcolObj0 = lhs->getRigidBodyA(); const btCollisionObject& rcolObj1 = lhs->getRigidBodyB(); islandId= rcolObj0.getIslandTag()>=0?rcolObj0.getIslandTag():rcolObj1.getIslandTag(); return islandId; } class btSortConstraintOnIslandPredicate { public: bool operator() ( const btTypedConstraint* lhs, const btTypedConstraint* rhs ) { int rIslandId0,lIslandId0; rIslandId0 = btGetConstraintIslandId(rhs); lIslandId0 = btGetConstraintIslandId(lhs); return lIslandId0 < rIslandId0; } }; void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) { BT_PROFILE("solveConstraints"); struct InplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback { btContactSolverInfo& m_solverInfo; btConstraintSolver* m_solver; btTypedConstraint** m_sortedConstraints; int m_numConstraints; btIDebugDraw* m_debugDrawer; btStackAlloc* m_stackAlloc; btDispatcher* m_dispatcher; InplaceSolverIslandCallback( btContactSolverInfo& solverInfo, btConstraintSolver* solver, btTypedConstraint** sortedConstraints, int numConstraints, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc, btDispatcher* dispatcher) :m_solverInfo(solverInfo), m_solver(solver), m_sortedConstraints(sortedConstraints), m_numConstraints(numConstraints), m_debugDrawer(debugDrawer), m_stackAlloc(stackAlloc), m_dispatcher(dispatcher) { } InplaceSolverIslandCallback& operator=(InplaceSolverIslandCallback& other) { btAssert(0); (void)other; return *this; } virtual void ProcessIsland(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifolds,int numManifolds, int islandId) { if (islandId<0) { if (numManifolds + m_numConstraints) { ///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,&m_sortedConstraints[0],m_numConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher); } } else { //also add all non-contact constraints/joints for this island btTypedConstraint** startConstraint = 0; int numCurConstraints = 0; int i; //find the first constraint for this island for (i=0;i<m_numConstraints;i++) { if (btGetConstraintIslandId(m_sortedConstraints[i]) == islandId) { startConstraint = &m_sortedConstraints[i]; break; } } //count the number of constraints in this island for (;i<m_numConstraints;i++) { if (btGetConstraintIslandId(m_sortedConstraints[i]) == islandId) { numCurConstraints++; } } ///only call solveGroup if there is some work: avoid virtual function call, its overhead can be excessive if (numManifolds + numCurConstraints) { m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher); } } } }; //sorted version of all btTypedConstraint, based on islandId btAlignedObjectArray<btTypedConstraint*> sortedConstraints; sortedConstraints.resize( m_constraints.size()); int i; for (i=0;i<getNumConstraints();i++) { sortedConstraints[i] = m_constraints[i]; } // btAssert(0); sortedConstraints.quickSort(btSortConstraintOnIslandPredicate()); btTypedConstraint** constraintsPtr = getNumConstraints() ? &sortedConstraints[0] : 0; InplaceSolverIslandCallback solverCallback( solverInfo, m_constraintSolver, constraintsPtr,sortedConstraints.size(), m_debugDrawer,m_stackAlloc,m_dispatcher1); m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds()); /// solve all the constraints for this island m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld(),&solverCallback); m_constraintSolver->allSolved(solverInfo, m_debugDrawer, m_stackAlloc); } void btDiscreteDynamicsWorld::calculateSimulationIslands() { BT_PROFILE("calculateSimulationIslands"); getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher()); { int i; int numConstraints = int(m_constraints.size()); for (i=0;i< numConstraints ; i++ ) { btTypedConstraint* constraint = m_constraints[i]; const btRigidBody* colObj0 = &constraint->getRigidBodyA(); const btRigidBody* colObj1 = &constraint->getRigidBodyB(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { if (colObj0->isActive() || colObj1->isActive()) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(), (colObj1)->getIslandTag()); } } } } //Store the island id in each body getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld()); } #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" class btClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { btCollisionObject* m_me; btScalar m_allowedPenetration; btOverlappingPairCache* m_pairCache; btDispatcher* m_dispatcher; public: btClosestNotMeConvexResultCallback (btCollisionObject* me,const btVector3& fromA,const btVector3& toA,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) : btCollisionWorld::ClosestConvexResultCallback(fromA,toA), m_allowedPenetration(0.0f), m_me(me), m_pairCache(pairCache), m_dispatcher(dispatcher) { } virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace) { if (convexResult.m_hitCollisionObject == m_me) return 1.0f; //ignore result if there is no contact response if(!convexResult.m_hitCollisionObject->hasContactResponse()) return 1.0f; btVector3 linVelA,linVelB; linVelA = m_convexToWorld-m_convexFromWorld; linVelB = btVector3(0,0,0);//toB.getOrigin()-fromB.getOrigin(); btVector3 relativeVelocity = (linVelA-linVelB); //don't report time of impact for motion away from the contact normal (or causes minor penetration) if (convexResult.m_hitNormalLocal.dot(relativeVelocity)>=-m_allowedPenetration) return 1.f; return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace); } virtual bool needsCollision(btBroadphaseProxy* proxy0) const { //don't collide with itself if (proxy0->m_clientObject == m_me) return false; ///don't do CCD when the collision filters are not matching if (!ClosestConvexResultCallback::needsCollision(proxy0)) return false; btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject; //call needsResponse, see http://code.google.com/p/bullet/issues/detail?id=179 if (m_dispatcher->needsResponse(m_me,otherObj)) { ///don't do CCD when there are already contact points (touching contact/penetration) btAlignedObjectArray<btPersistentManifold*> manifoldArray; btBroadphasePair* collisionPair = m_pairCache->findPair(m_me->getBroadphaseHandle(),proxy0); if (collisionPair) { if (collisionPair->m_algorithm) { manifoldArray.resize(0); collisionPair->m_algorithm->getAllContactManifolds(manifoldArray); for (int j=0;j<manifoldArray.size();j++) { btPersistentManifold* manifold = manifoldArray[j]; if (manifold->getNumContacts()>0) return false; } } } } return true; } }; ///internal debugging variable. this value shouldn't be too high int gNumClampedCcdMotions=0; //#include "stdio.h" void btDiscreteDynamicsWorld::integrateTransforms(btScalar timeStep) { BT_PROFILE("integrateTransforms"); btTransform predictedTrans; for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; body->setHitFraction(1.f); if (body->isActive() && (!body->isStaticOrKinematicObject())) { body->predictIntegratedTransform(timeStep, predictedTrans); btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2(); if (body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion) { BT_PROFILE("CCD motion clamping"); if (body->getCollisionShape()->isConvex()) { gNumClampedCcdMotions++; btClosestNotMeConvexResultCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher()); //btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape()); btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape()); sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup; sweepResults.m_collisionFilterMask = body->getBroadphaseProxy()->m_collisionFilterMask; convexSweepTest(&tmpSphere,body->getWorldTransform(),predictedTrans,sweepResults); if (sweepResults.hasHit() && (sweepResults.m_closestHitFraction < 1.f)) { body->setHitFraction(sweepResults.m_closestHitFraction); body->predictIntegratedTransform(timeStep*body->getHitFraction(), predictedTrans); body->setHitFraction(0.f); // printf("clamped integration to hit fraction = %f\n",fraction); } } } body->proceedToTransform( predictedTrans); } } } void btDiscreteDynamicsWorld::predictUnconstraintMotion(btScalar timeStep) { BT_PROFILE("predictUnconstraintMotion"); for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (!body->isStaticOrKinematicObject()) { body->integrateVelocities( timeStep); //damping body->applyDamping(timeStep); body->predictIntegratedTransform(timeStep,body->getInterpolationWorldTransform()); } } } void btDiscreteDynamicsWorld::startProfiling(btScalar timeStep) { (void)timeStep; #ifndef BT_NO_PROFILE CProfileManager::Reset(); #endif //BT_NO_PROFILE } void btDiscreteDynamicsWorld::debugDrawConstraint(btTypedConstraint* constraint) { bool drawFrames = (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawConstraints) != 0; bool drawLimits = (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawConstraintLimits) != 0; btScalar dbgDrawSize = constraint->getDbgDrawSize(); if(dbgDrawSize <= btScalar(0.f)) { return; } switch(constraint->getConstraintType()) { case POINT2POINT_CONSTRAINT_TYPE: { btPoint2PointConstraint* p2pC = (btPoint2PointConstraint*)constraint; btTransform tr; tr.setIdentity(); btVector3 pivot = p2pC->getPivotInA(); pivot = p2pC->getRigidBodyA().getCenterOfMassTransform() * pivot; tr.setOrigin(pivot); getDebugDrawer()->drawTransform(tr, dbgDrawSize); // that ideally should draw the same frame pivot = p2pC->getPivotInB(); pivot = p2pC->getRigidBodyB().getCenterOfMassTransform() * pivot; tr.setOrigin(pivot); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); } break; case HINGE_CONSTRAINT_TYPE: { btHingeConstraint* pHinge = (btHingeConstraint*)constraint; btTransform tr = pHinge->getRigidBodyA().getCenterOfMassTransform() * pHinge->getAFrame(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); tr = pHinge->getRigidBodyB().getCenterOfMassTransform() * pHinge->getBFrame(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); btScalar minAng = pHinge->getLowerLimit(); btScalar maxAng = pHinge->getUpperLimit(); if(minAng == maxAng) { break; } bool drawSect = true; if(minAng > maxAng) { minAng = btScalar(0.f); maxAng = SIMD_2_PI; drawSect = false; } if(drawLimits) { btVector3& center = tr.getOrigin(); btVector3 normal = tr.getBasis().getColumn(2); btVector3 axis = tr.getBasis().getColumn(0); getDebugDrawer()->drawArc(center, normal, axis, dbgDrawSize, dbgDrawSize, minAng, maxAng, btVector3(0,0,0), drawSect); } } break; case CONETWIST_CONSTRAINT_TYPE: { btConeTwistConstraint* pCT = (btConeTwistConstraint*)constraint; btTransform tr = pCT->getRigidBodyA().getCenterOfMassTransform() * pCT->getAFrame(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); tr = pCT->getRigidBodyB().getCenterOfMassTransform() * pCT->getBFrame(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); if(drawLimits) { //const btScalar length = btScalar(5); const btScalar length = dbgDrawSize; static int nSegments = 8*4; btScalar fAngleInRadians = btScalar(2.*3.1415926) * (btScalar)(nSegments-1)/btScalar(nSegments); btVector3 pPrev = pCT->GetPointForAngle(fAngleInRadians, length); pPrev = tr * pPrev; for (int i=0; i<nSegments; i++) { fAngleInRadians = btScalar(2.*3.1415926) * (btScalar)i/btScalar(nSegments); btVector3 pCur = pCT->GetPointForAngle(fAngleInRadians, length); pCur = tr * pCur; getDebugDrawer()->drawLine(pPrev, pCur, btVector3(0,0,0)); if (i%(nSegments/8) == 0) getDebugDrawer()->drawLine(tr.getOrigin(), pCur, btVector3(0,0,0)); pPrev = pCur; } btScalar tws = pCT->getTwistSpan(); btScalar twa = pCT->getTwistAngle(); bool useFrameB = (pCT->getRigidBodyB().getInvMass() > btScalar(0.f)); if(useFrameB) { tr = pCT->getRigidBodyB().getCenterOfMassTransform() * pCT->getBFrame(); } else { tr = pCT->getRigidBodyA().getCenterOfMassTransform() * pCT->getAFrame(); } btVector3 pivot = tr.getOrigin(); btVector3 normal = tr.getBasis().getColumn(0); btVector3 axis1 = tr.getBasis().getColumn(1); getDebugDrawer()->drawArc(pivot, normal, axis1, dbgDrawSize, dbgDrawSize, -twa-tws, -twa+tws, btVector3(0,0,0), true); } } break; case D6_CONSTRAINT_TYPE: { btGeneric6DofConstraint* p6DOF = (btGeneric6DofConstraint*)constraint; btTransform tr = p6DOF->getCalculatedTransformA(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); tr = p6DOF->getCalculatedTransformB(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); if(drawLimits) { tr = p6DOF->getCalculatedTransformA(); const btVector3& center = p6DOF->getCalculatedTransformB().getOrigin(); btVector3 up = tr.getBasis().getColumn(2); btVector3 axis = tr.getBasis().getColumn(0); btScalar minTh = p6DOF->getRotationalLimitMotor(1)->m_loLimit; btScalar maxTh = p6DOF->getRotationalLimitMotor(1)->m_hiLimit; btScalar minPs = p6DOF->getRotationalLimitMotor(2)->m_loLimit; btScalar maxPs = p6DOF->getRotationalLimitMotor(2)->m_hiLimit; getDebugDrawer()->drawSpherePatch(center, up, axis, dbgDrawSize * btScalar(.9f), minTh, maxTh, minPs, maxPs, btVector3(0,0,0)); axis = tr.getBasis().getColumn(1); btScalar ay = p6DOF->getAngle(1); btScalar az = p6DOF->getAngle(2); btScalar cy = btCos(ay); btScalar sy = btSin(ay); btScalar cz = btCos(az); btScalar sz = btSin(az); btVector3 ref; ref[0] = cy*cz*axis[0] + cy*sz*axis[1] - sy*axis[2]; ref[1] = -sz*axis[0] + cz*axis[1]; ref[2] = cz*sy*axis[0] + sz*sy*axis[1] + cy*axis[2]; tr = p6DOF->getCalculatedTransformB(); btVector3 normal = -tr.getBasis().getColumn(0); btScalar minFi = p6DOF->getRotationalLimitMotor(0)->m_loLimit; btScalar maxFi = p6DOF->getRotationalLimitMotor(0)->m_hiLimit; if(minFi > maxFi) { getDebugDrawer()->drawArc(center, normal, ref, dbgDrawSize, dbgDrawSize, -SIMD_PI, SIMD_PI, btVector3(0,0,0), false); } else if(minFi < maxFi) { getDebugDrawer()->drawArc(center, normal, ref, dbgDrawSize, dbgDrawSize, minFi, maxFi, btVector3(0,0,0), true); } tr = p6DOF->getCalculatedTransformA(); btVector3 bbMin = p6DOF->getTranslationalLimitMotor()->m_lowerLimit; btVector3 bbMax = p6DOF->getTranslationalLimitMotor()->m_upperLimit; getDebugDrawer()->drawBox(bbMin, bbMax, tr, btVector3(0,0,0)); } } break; case SLIDER_CONSTRAINT_TYPE: { btSliderConstraint* pSlider = (btSliderConstraint*)constraint; btTransform tr = pSlider->getCalculatedTransformA(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); tr = pSlider->getCalculatedTransformB(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); if(drawLimits) { btTransform tr = pSlider->getCalculatedTransformA(); btVector3 li_min = tr * btVector3(pSlider->getLowerLinLimit(), 0.f, 0.f); btVector3 li_max = tr * btVector3(pSlider->getUpperLinLimit(), 0.f, 0.f); getDebugDrawer()->drawLine(li_min, li_max, btVector3(0, 0, 0)); btVector3 normal = tr.getBasis().getColumn(0); btVector3 axis = tr.getBasis().getColumn(1); btScalar a_min = pSlider->getLowerAngLimit(); btScalar a_max = pSlider->getUpperAngLimit(); const btVector3& center = pSlider->getCalculatedTransformB().getOrigin(); getDebugDrawer()->drawArc(center, normal, axis, dbgDrawSize, dbgDrawSize, a_min, a_max, btVector3(0,0,0), true); } } break; default : break; } return; } void btDiscreteDynamicsWorld::setConstraintSolver(btConstraintSolver* solver) { if (m_ownsConstraintSolver) { btAlignedFree( m_constraintSolver); } m_ownsConstraintSolver = false; m_constraintSolver = solver; } btConstraintSolver* btDiscreteDynamicsWorld::getConstraintSolver() { return m_constraintSolver; } int btDiscreteDynamicsWorld::getNumConstraints() const { return int(m_constraints.size()); } btTypedConstraint* btDiscreteDynamicsWorld::getConstraint(int index) { return m_constraints[index]; } const btTypedConstraint* btDiscreteDynamicsWorld::getConstraint(int index) const { return m_constraints[index]; }
[ [ [ 1, 1080 ] ] ]
a56206931c3903fc1f6af74053690abfd173ad8c
276a89682066266de78e0e2a3fcacb1bb47578da
/tags/7pre1/corbautil/cxx/gsp/sol_gsp_boundedprodcons.h
4ec3d025a060b4898cfb9d670503e0cfa6288720
[]
no_license
BackupTheBerlios/v-q-svn
e886b6e5945f9cc760a526aff8a36c2f59db35ea
c8f787e77272d5da15ef5d91a596b64ce1cf4d36
refs/heads/master
2020-05-31T15:14:58.511327
2006-03-20T20:27:23
2006-03-20T20:27:23
40,824,182
0
0
null
null
null
null
UTF-8
C++
false
false
3,756
h
//----------------------------------------------------------------------- // Copyright IONA Technologies 2002-2004. All rights reserved. // This software is provided "as is". // // File: sol_gsp_boundedprodcons.h // // Policy: BoundedProdCons(int size)[PutOp, GetOp, OtherOp] // // Description: The bounded producer-consumer synchronisation policy. //---------------------------------------------------------------------- #ifndef SOL_GSP_BOUNDEDPRODCONS_H_ #define SOL_GSP_BOUNDEDPRODCONS_H_ //-------- // #include's //-------- #include <synch.h> #include <assert.h> //-------- // Forward declarations //-------- class GSP_BoundedProdCons; class GSP_BoundedProdCons { public: inline GSP_BoundedProdCons(int size); inline ~GSP_BoundedProdCons(); class PutOp { public: inline PutOp(GSP_BoundedProdCons &); inline ~PutOp(); protected: GSP_BoundedProdCons &m_sync; }; class GetOp { public: inline GetOp(GSP_BoundedProdCons &); inline ~GetOp(); protected: GSP_BoundedProdCons &m_sync; }; class OtherOp { public: inline OtherOp(GSP_BoundedProdCons &); inline ~OtherOp(); protected: GSP_BoundedProdCons &m_sync; }; protected: friend class ::GSP_BoundedProdCons::PutOp; friend class ::GSP_BoundedProdCons::GetOp; friend class ::GSP_BoundedProdCons::OtherOp; mutex_t m_mutex; sema_t m_item_count; // counts number of items in buffer sema_t m_free_count; // counts free slots in buffer }; //-------- // Inline implementation of class GSP_BoundedProdCons //-------- inline GSP_BoundedProdCons::GSP_BoundedProdCons(int size) { int status; status = mutex_init(&m_mutex, USYNC_THREAD, 0); assert(status == 0); status = sema_init(&m_item_count, 0, USYNC_THREAD, 0); assert(status == 0); status = sema_init(&m_free_count, size, USYNC_THREAD, 0); assert(status == 0); } inline GSP_BoundedProdCons::~GSP_BoundedProdCons() { int status; status = mutex_destroy(&m_mutex); assert(status == 0); status = sema_destroy(&m_item_count); assert(status == 0); status = sema_destroy(&m_free_count); assert(status == 0); } //-------- // Inline implementation of class GSP_BoundedProdCons::PutOp //-------- inline GSP_BoundedProdCons::PutOp::PutOp(GSP_BoundedProdCons &sync_data) : m_sync(sync_data) { int status; status = sema_wait(&m_sync.m_free_count); assert(status == 0); status = mutex_lock(&m_sync.m_mutex); assert(status == 0); } inline GSP_BoundedProdCons::PutOp::~PutOp() { int status; status = mutex_unlock(&m_sync.m_mutex); assert(status == 0); status = sema_post(&m_sync.m_item_count); assert(status == 0); } //-------- // Inline implementation of class GSP_BoundedProdCons::GetOp //-------- inline GSP_BoundedProdCons::GetOp::GetOp(GSP_BoundedProdCons &sync_data) : m_sync(sync_data) { int status; status = sema_wait(&m_sync.m_item_count); assert(status == 0); status = mutex_lock(&m_sync.m_mutex); assert(status == 0); } inline GSP_BoundedProdCons::GetOp::~GetOp() { int status; status = mutex_unlock(&m_sync.m_mutex); assert(status == 0); status = sema_post(&m_sync.m_free_count); assert(status == 0); } //-------- // Inline implementation of class GSP_BoundedProdCons::OtherOp //-------- inline GSP_BoundedProdCons::OtherOp::OtherOp(GSP_BoundedProdCons &sync_data) : m_sync(sync_data) { int status; status = mutex_lock(&m_sync.m_mutex); assert(status == 0); } inline GSP_BoundedProdCons::OtherOp::~OtherOp() { int status; status = mutex_unlock(&m_sync.m_mutex); assert(status == 0); } #endif
[ "new@36831980-ddd6-0310-a275-bfd50d89a3dc" ]
[ [ [ 1, 214 ] ] ]
107fc83f8a0c6cf3e4b23e2cd2767575576fe206
3bfe835203f793ee00bdf261c26992b1efea69ed
/misc/NetTest/NetTest/message.h
aff2adf67a813d6e290605b833b1ba271eaa333f
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
UTF-8
C++
false
false
454
h
//----------------------------------------------------------------------------- #ifndef MESSAGE_H #define MESSAGE_H //----------------------------------------------------------------------------- template <typename T> class Message { public: Message( bool _reliable = false, bool _toResend = false ) : reliable( _reliable ), toResend( _toResend ) {} void Send() {} bool reliable; bool toResend; }; #endif
[ [ [ 1, 20 ] ] ]
7a19a0ae33b48990a25ed283eeb26e7523149005
15730792376cc6ffa986d6bcb88ba9fd7acf9369
/raytracer3.0.06.no_rec.samp/scene.cpp
0f94fd2f3b8cf53b2ce584d28e019bce9b087ba1
[]
no_license
markrosoft/se-195-project-ray-tracer
0b8c14422e52aa5ede17a158c6ef7521934ce029
0712d443be8c0da986ab1315a257740fbb3a653d
refs/heads/master
2021-01-10T07:14:00.513175
2011-11-18T06:42:15
2011-11-18T06:42:15
43,331,160
0
0
null
null
null
null
UTF-8
C++
false
false
9,196
cpp
// ----------------------------------------------------------- // scene.cpp // 2004 - Jacco Bikker - [email protected] - www.bik5.com - <>< // ----------------------------------------------------------- #define _CRT_SECURE_NO_WARNINGS 1 #include "common.h" #include "string.h" #include "raytracer.h" #include "scene.h" float m_WX1, m_WY1, m_WX2, m_WY2, m_DX, m_DY, m_SX, m_SY; Scene* m_Scene; Pixel* m_Dest = NULL; TracedRay TracedRays[TRACEDEPTH]; int m_Width, m_Height, m_CurrLine, m_PPos; //Primitive** m_LastRow; //vector3 * dummy_vector = NULL; vector3 * camera = NULL; // ----------------------------------------------------------- // Primitive class implementation // ----------------------------------------------------------- //void Primitive_SetName( Primitive * p, char* a_Name ) //{ // free(p->m_Name); // p->m_Name = _strdup(a_Name); //} void Primitive_GetNormal(vector3 *newvec, Primitive p, vector3 a_Pos ) { if (p.type == SPHERE) { newvec->x = a_Pos.x - p.m_Centre.x; newvec->y = a_Pos.y - p.m_Centre.y; newvec->z = a_Pos.z - p.m_Centre.z; newvec->x *= p.m_RRadius; newvec->y *= p.m_RRadius; newvec->z *= p.m_RRadius; } else { if (p.type == PLANE) { newvec->x = p.m_Plane.N.x; newvec->y = p.m_Plane.N.y; newvec->z = p.m_Plane.N.z; } else { newvec->x = 0; newvec->y = 0; newvec->z = 0; } } } void Primitive_Create(Primitive *p, PRIMTYPE type, float center_normal_x, float center_normal_y, float center_normal_z, float radius_depth, float color_r, float color_g, float color_b, float refl, float refr, float rIndex, float diff, float spec, bool isLight) { p->type = type; p->m_Light = isLight ? 1 : 0; p->m_Material.m_Color.x = color_r; p->m_Material.m_Color.y = color_g; p->m_Material.m_Color.z = color_b; p->m_Material.m_Refl = refl; p->m_Material.m_Refr = refr; p->m_Material.m_RIndex = rIndex; p->m_Material.m_Diff = diff; p->m_Material.m_Spec = spec; bool isSphere = (type == SPHERE); p->m_Centre.x = isSphere ? center_normal_x : 0; p->m_Centre.y = isSphere ? center_normal_y : 0; p->m_Centre.z = isSphere ? center_normal_z : 0; p->m_Radius = isSphere ? radius_depth : 0; p->m_SqRadius = isSphere ? radius_depth*radius_depth : 0; p->m_RRadius = isSphere ? ((radius_depth > 0) ? 1.0f/radius_depth : 0) : 0; p->m_Plane.D = isSphere ? 0 : radius_depth; p->m_Plane.N.x = isSphere ? 0 : center_normal_x; p->m_Plane.N.y = isSphere ? 0 : center_normal_y; p->m_Plane.N.z = isSphere ? 0 : center_normal_z; } vector3 Primitive_GetCentre(Primitive *p) { return p->m_Centre; } float Primitive_GetSqRadius(Primitive *p) { return p->m_SqRadius; } float Primitive_GetD(Primitive *p) { return p->m_Plane.D; } // ----------------------------------------------------------- // Material class implementation // ----------------------------------------------------------- void Material_Set(Material *m) { m->m_Color.x = 0.2f; m->m_Color.y = 0.2f; m->m_Color.z = 0.2f; m->m_Refl = 0.0f; m->m_Diff = 0.2f; m->m_RIndex = 1.5f; } void Material_SetColor(Material * m, float r, float g, float b) { m->m_Color.x = r; m->m_Color.y = g; m->m_Color.z = b; } float Material_GetSpecular(Material * m) { return 1.0f - m->m_Diff; } //Material * Primitive_GetMaterial(Primitive *p) { return p->m_Material; } PRIMTYPE Primitive_GetType(Primitive *p) { return p->type; } // ----------------------------------------------------------- // Sphere primitive methods // ----------------------------------------------------------- int Primitive_Intersect(Primitive *p, Ray * a_Ray, float * a_Dist) { vector3 dummy_vector; dummy_vector.x = 0; dummy_vector.y = 0; dummy_vector.z = 0; if (p->type == SPHERE) { dummy_vector.x = a_Ray->m_Origin.x; dummy_vector.y = a_Ray->m_Origin.y; dummy_vector.z = a_Ray->m_Origin.z; //vector3_minusEquals(dummy_vector, p->m_Centre); //vector3 * v = vector3_minus(Ray_GetOrigin(a_Ray), p->m_Centre); dummy_vector.x -= p->m_Centre.x; dummy_vector.y -= p->m_Centre.y; dummy_vector.z -= p->m_Centre.z; float b = vector3_Dot(dummy_vector, a_Ray->m_Direction); b = -b; float det = (b * b) - vector3_Dot( dummy_vector, dummy_vector ) + p->m_SqRadius; //free(v); int retval = MISS; if (det > 0) { det = sqrtf( det ); float i1 = b - det; float i2 = b + det; if (i2 > 0) { if (i1 < 0) { if (i2 < *a_Dist) { *a_Dist = i2; retval = INPRIM; } } else { if (i1 < *a_Dist) { *a_Dist = i1; retval = HIT; } } } } return retval; } else { if (p->type == PLANE) { float d = vector3_Dot( p->m_Plane.N, a_Ray->m_Direction); if (d != 0) { float dist = -(vector3_Dot( p->m_Plane.N, a_Ray->m_Origin ) + p->m_Plane.D) / d; if (dist > 0) { if (dist < *a_Dist) { *a_Dist = dist; return HIT; } } } return MISS; } else { return MISS; } } } // ----------------------------------------------------------- // Scene class implementation // ----------------------------------------------------------- Scene * Scene_Create(void) { Scene *s = (Scene *) malloc(sizeof(Scene)); return s; } void TracedRays_init(void){ for (int i = 0; i < TRACEDEPTH; ++i) { TracedRays[i].color.x = 0; TracedRays[i].color.y = 0; TracedRays[i].color.z = 0; TracedRays[i].refl = 0; TracedRays[i].refl_index = 0; } } int Scene_GetNrPrimitives(Scene *s) { return s->m_Primitives; } void Scene_InitScene() { m_Scene = Scene_Create(); // set number of primitives int maxx, maxy; maxx = maxy = 0; //maxx = 30; maxy = 15; //maxx = 10; maxy = 2; m_Scene->m_Primitive = (Primitive *) malloc (sizeof(Primitive)*50); int pc = 0; // floor plane Primitive_Create(&(m_Scene->m_Primitive[pc++]), PLANE , 0.0f, 0.75f, 0.0f, 4.4f, 0.6f, 0.6f, 0.6f, 0.0f, 0.0f, 0.0f, 0.4f, 1.8f, false); // light source center Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, 0.0f, 6.5f, 22.0f, 0.35f, 0.85f, 0.85f, 0.85f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, true); // big sphere Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, 3.4f, -3.40f, 23.0f, 2.5f, 0.08f, 0.08f, 0.08f, 1.9f, 1.0f, 2.3f, 0.0f, 0.0f, false); //Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, 03.4f, -3.40f, 23.0f, 2.5f, 0.08f, 0.08f, 0.08f, 1.5f, 1.0f, 2.3f, 0.2f, 0.2f, false); // small sphere 5 Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -0.7f, -4.90f, 27.0f, 1.0f, 0.07f, 0.17f, 0.07f, 0.1f, 1.5f, 2.3f, 0.2f, 0.8f, false); // small sphere Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -3.4f, -3.40f, 29.0f, 2.5f, 1.0f, 1.0f, 1.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, false); // small sphere 2 Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, 0.5f, -4.10f, 29.0f, 1.5f, 1.5f, 0.7f, 0.7f, 0.1f, 0.0f, 0.0f, 0.2f, 0.2f, false); // small sphere 3 Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -6.0f, -4.10f, 32.0f, 1.5f, 0.7f, 0.7f, 1.7f, 0.2f, 0.0f, 0.0f, 0.2f, 0.2f, false); // small sphere 4 Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -6.7f, -4.90f, 29.0f, 1.0f, 0.07f, 0.17f, 0.07f, 0.1f, 1.5f, 2.3f, 0.2f, 0.8f, false); // small sphere 6 Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, 6.4f, -4.90f, 18.0f, 1.0f, 0.18f, 0.18f, 0.18f, 1.7f, 1.0f, 2.6f, 1.8f, 0.0f, false); // left wall Primitive_Create(&(m_Scene->m_Primitive[pc++]), PLANE, 0.7f, 0.0f, 0.0f, 5.4f, 1.0f, 0.6f, 0.6f, 0.0f, 0.0f, 0.0f, 0.8f, 1.5f, false); // right wall Primitive_Create(&(m_Scene->m_Primitive[pc++]), PLANE, -0.7f, 0.0f, 0.0f, 5.4f, 0.7f, 0.6f, 1.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.8f, false); // top wall Primitive_Create(&(m_Scene->m_Primitive[pc++]), PLANE, 0.0f, -0.8f, 0.0f, 5.4f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.2f, 0.8f, false); // back wall Primitive_Create(&(m_Scene->m_Primitive[pc++]), PLANE, 0.0f, 0.0f, -0.14f, 5.4f, 2.5f, 2.5f, 2.5f, 0.0f, 0.0f, 0.0f, 1.2f, 0.8f, false); // front wall Primitive_Create(&(m_Scene->m_Primitive[pc++]), PLANE, 0.0f, 0.0f, 0.72f, 5.4f, 0.1f, 0.1f, 0.1f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, false); // light source right Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -3.0f, 6.5f, 22.0f, 0.35f, 0.85f, 0.85f, 0.85f, 0.0f, 0.0f, 0.0f, 0.0f, 1.8f, true); // light source left Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, 3.0f, 6.5f, 22.0f, 0.35f, 0.85f, 0.85f, 0.85f, 0.0f, 0.0f, 0.0f, 0.0f, 1.8f, true); // light source ground back Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -5.8f, -5.55f, 31.0f, 0.35f, 1.15f, 0.35f, 0.35f, 1.0f, 1.0f, 2.3f, 0.0f, 1.8f, true); int x = 0; int y = 0; for (y = 0; y < maxy; ++y) { for (x = 0; x < maxx; x++) { int index = 5 + x + (y*maxx); Primitive_Create(&(m_Scene->m_Primitive[pc++]), SPHERE, -15.0f+(x*1.0f), 10.0f-(y*1.0f), 23, 0.5f, 0.8f+0.3f*x, 2.6f-0.02f*x+0.05f*y, 0.5f+0.01f*y, 0.0f, 0.0f, 1.5f, 0.1f, 0.1f, false); } } m_Scene->m_Primitives = pc + (maxx*maxy); }
[ [ [ 1, 274 ] ] ]
0bfc00027c5c00b4dbd203e73ea8c11896864fff
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/capcom/cpsr.cpp
7e0aa9cc2cddd65854ffbdb7052a48a298039f38
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
3,878
cpp
#include "cps.h" // CPS Scroll2 with Row scroll support unsigned char *CpsrBase = NULL; // Tile data base int nCpsrScrX = 0, nCpsrScrY = 0; // Basic scroll info unsigned short *CpsrRows = NULL; // Row scroll table, 0x400 words long int nCpsrRowStart = 0; // Start of row scroll (can wrap?) static int nShiftY = 0; static int EndLineInfo = 0; struct CpsrLineInfo CpsrLineInfo[15]; static void GetRowsRange(int *pnStart,int *pnWidth,int nRowFrom,int nRowTo) { int i, nStart, nWidth; // Get the range of scroll values within nRowCount rows // Start with zero range nStart = swapWord(CpsrRows[nRowFrom & 0x3ff]) & 0x3ff; nWidth = 0; for (i = nRowFrom; i< nRowTo; i++) { int nViz, nDiff; nViz = swapWord(CpsrRows[i & 0x3ff]) & 0x3ff; // Work out if this is on the left or the right of our start point. nDiff = nViz - nStart; // clip to 10-bit signed nDiff = ((nDiff + 0x200) & 0x3ff) - 0x200; if (nDiff >= 0) { // On the right if (nDiff >= nWidth) // expand width to cover it nWidth = nDiff; } else { // On the left nStart = (nStart + nDiff) & 0x3ff; nWidth -= nDiff; // expand width to cover it } } if (nWidth > 0x400) nWidth = 0x400; *pnStart = nStart; *pnWidth = nWidth; } static int PrepareRows() { int y, r; struct CpsrLineInfo *pli; // Calculate the amount of pixels to shift each // row of the tile lines, assuming we draw tile x at // (x-pli->nTileStart)<<4 - i.e. 0, 16, ... r = nShiftY - 0x10; for (y = -1, pli = CpsrLineInfo; y < EndLineInfo; y++, pli++) { int ty, nMaxLeft = 0, nMaxRight = 0; // Maximum row scroll left and right on this line short *pr; if (CpsrRows == NULL) // No row shift - all the same { int v = (pli->nTileStart << 4) - nCpsrScrX; nMaxLeft = nMaxRight = v; for (ty = 0, pr = pli->Rows; ty < 16; ty++, pr++) *pr=(short)v; } else { for (ty = 0, pr = pli->Rows; ty < 16; ty++, pr++, r++) { if (r>=0 && r<nEndline) // Get the row offset, if it's in range { int v; v = (pli->nTileStart << 4) - nCpsrScrX; v -= swapWord(CpsrRows[(nCpsrRowStart + r) & 0x3ff]); // clip to 10-bit signed v = ((v + 0x200) & 0x3ff) - 0x200; *pr=(short)v; if (v < nMaxLeft) nMaxLeft = v; else if (v > nMaxRight) nMaxRight = v; } else { *pr=0; } } } pli->nMaxLeft = nMaxLeft; pli->nMaxRight = nMaxRight; } return 0; } // Prepare to draw Scroll 2 with rows, by seeing how much // row scroll each tile line uses (pli->nStart/nWidth), // and finding which tiles are visible onscreen (pli->nTileStart/End). int CpsrPrepare() { int y; struct CpsrLineInfo *pli; if (CpsrBase == NULL) return 1; if (Cps&1) { nEndline = 224; EndLineInfo = 14; } else { EndLineInfo = ((nEndline + 15) >> 4); } nShiftY = 0x10 - (nCpsrScrY & 0x0f); for (y = -1, pli = CpsrLineInfo; y < EndLineInfo; y++, pli++) { int nStart = 0, nWidth = 0; if (CpsrRows != NULL) { int nRowFrom,nRowTo; // Find out which rows we need to check nRowFrom = (y << 4) + nShiftY; nRowTo = nRowFrom + 0x10; if (nRowFrom < 0) nRowFrom = 0; if (nRowTo > nEndline) nRowTo = nEndline; // Shift by row table start offset nRowFrom += nCpsrRowStart; nRowTo += nCpsrRowStart; // Find out what range of scroll values there are for this line GetRowsRange(&nStart,&nWidth,nRowFrom,nRowTo); } nStart = (nStart + nCpsrScrX) & 0x3ff; // Save info in CpsrLineInfo table pli->nStart = nStart; pli->nWidth = nWidth; // Find range of tiles to draw to see whole width: pli->nTileStart=nStart>>4; pli->nTileEnd=(nStart+nWidth+0x18f)>>4; } PrepareRows(); return 0; }
[ [ [ 1, 165 ] ] ]
78b73a5e556e18a1edb03c9bb489e40a3da27bd2
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/Aran/DungeonInterface.cpp
75126a141ea6dfc2cafa68e6df24cc64b23bcb16
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
154
cpp
#include "AranPCH.h" #include "DungeonInterface.h" DungeonInterface::DungeonInterface(void) { } DungeonInterface::~DungeonInterface(void) { }
[ [ [ 1, 10 ] ] ]
9deca07e3e13c708274aa4bf5813d831017dfe1e
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/ConstraintSolver/Constraint/hkpConstraintQueryIn.h
5dc85cb2c18a213e204ce941b969d52539d48e94
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,848
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_CONSTRAINTSOLVER2_CONSTRAINT_QUERY_IN_H #define HK_CONSTRAINTSOLVER2_CONSTRAINT_QUERY_IN_H #include <Common/Base/hkBase.h> #include <Common/Base/Types/Physics/hkStepInfo.h> #include <Physics/ConstraintSolver/Solve/hkpSolverInfo.h> class hkpVelocityAccumulator; /// The time information, the constraints get access to class hkpConstraintQueryStepInfo { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CONSTRAINT_SOLVER, hkpConstraintQueryStepInfo ); /// The delta time of each solvers substep HK_ALIGN16( hkPadSpu<float> m_substepDeltaTime ); hkPadSpu<float> m_microStepDeltaTime; /// The 1.0f/m_substepDeltaTime hkPadSpu<float> m_substepInvDeltaTime; hkPadSpu<float> m_frameDeltaTime; hkPadSpu<float> m_frameInvDeltaTime; hkPadSpu<float> m_invNumSteps; hkPadSpu<float> m_invNumStepsTimesMicroSteps; // = 1.0f/(numSubsteps*numMicroSteps) // a factor all rhs should be multiplied hkPadSpu<float> m_rhsFactor; // a factor all invMasses should be multiplied hkPadSpu<float> m_virtMassFactor; // a factor for all rhs used for friction calculations hkPadSpu<float> m_frictionRhsFactor; }; #define HK_ACCUMULATOR_OFFSET_TO_INDEX(offset) hkObjectIndex(unsigned(offset) / sizeof(hkpVelocityAccumulator)) /// The input structure to hkConstraints::buildJacobian. class hkpConstraintQueryIn: public hkpConstraintQueryStepInfo { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CONSTRAINT_SOLVER, hkpConstraintQueryIn ); hkpConstraintQueryIn() { } /// The velocity accumulator of bodyA. Typically this is a hkpVelocityAccumulator HK_ALIGN16( hkPadSpu<const hkpVelocityAccumulator*> m_bodyA ); /// The velocity accumulator of bodyB. Typically this is a hkpVelocityAccumulator hkPadSpu<const hkpVelocityAccumulator*> m_bodyB; /// the transform of rigid body A, identity transform if not available hkPadSpu<const hkTransform*> m_transformA; /// the transform of rigid body N, identity transform if not available hkPadSpu<const hkTransform*> m_transformB; /// the current global solver settings hkPadSpu<hkReal> m_tau; /// the current global solver settings hkPadSpu<hkReal> m_damping; /// if this class is used with the hkdynamics library, this points to an hkpConstraintInstance hkPadSpu<class hkpConstraintInstance*> m_constraintInstance; /// if this class is used with the hkdynamics library, this points to an hkpConstraintRuntime hkPadSpu<void*> m_constraintRuntime; // Data to be written to the header schema hkPadSpu<hkUint32> m_accumulatorAIndex; hkPadSpu<hkUint32> m_accumulatorBIndex; hkPadSpu<HK_CPU_PTR(void*)> m_constraintRuntimeInMainMemory; #if defined( HK_PLATFORM_HAS_SPU) hkPadSpu<HK_CPU_PTR(struct hkpConstraintAtom*)> m_atomInMainMemory; #endif inline void set( const hkpSolverInfo& si, const hkStepInfo& stepInfo ) { m_substepDeltaTime = si.m_deltaTime; m_microStepDeltaTime = si.m_deltaTime * si.m_invNumMicroSteps; m_substepInvDeltaTime = si.m_invDeltaTime; m_invNumSteps = si.m_invNumSteps; m_invNumStepsTimesMicroSteps = si.m_invNumSteps * si.m_invNumMicroSteps; m_tau = si.m_tau; m_damping = si.m_damping; m_rhsFactor = si.m_tauDivDamp * si.m_invDeltaTime; m_virtMassFactor = si.m_damping; m_frictionRhsFactor = si.m_frictionTauDivDamp * si.m_invDeltaTime; m_frameDeltaTime = stepInfo.m_deltaTime; m_frameInvDeltaTime = stepInfo.m_invDeltaTime; } }; #endif // HK_CONSTRAINTSOLVER2_CONSTRAINT_QUERY_IN_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 127 ] ] ]
6630cd2c8e4ca964d5eea14f786d7e23e5f53ff8
60365cfb5278ec1dfcc07a5b3e07f3c9d680fa2a
/xlview/SettingFileAssoc.cpp
924a31a0574e6e29f75211e43228b42dcfe5855f
[]
no_license
cyberscorpio/xlview
6c01e96dbf225cfbc2be1cc15a8b70c61976eb46
a4b5088ce049695de2ed7ed191162e6034326381
refs/heads/master
2021-01-01T16:34:47.787022
2011-04-28T13:34:25
2011-04-28T13:34:25
38,444,399
0
0
null
null
null
null
UTF-8
C++
false
false
10,563
cpp
#include <assert.h> #include <algorithm> #include <tuple> #include <Windows.h> #include <WindowsX.h> #include <Uxtheme.h> #include <Vssym32.h> #include "libxl/include/Language.h" #include "libxl/include/ui/ResMgr.h" #include "libxl/include/ui/Gdi.h" #include "Settings.h" #include "SettingFileAssoc.h" #pragma comment (lib, "UxTheme.lib") static const int TAB_PADDING_X = 4; static const int TAB_PADDING_Y = 8; static const int TAB_MARGIN_Y = 8; static const int TAB_MARGIN_X = 8; /////////////////////////////////////////////////////////////////////////////// // fOR wINDOWS xP // tuple <ID, "ext1;ext2;ext3...", "default progid"> static std::tuple<UINT, const xl::tchar *, const xl::tchar *> s_extTable[] = { std::make_tuple(IDC_CHECKBOX_JPG, _T("jpg;jpeg;jfif"), _T("jpegfile")), std::make_tuple(IDC_CHECKBOX_PNG, _T("png"), _T("pngfile")), }; void CFileAssociationDialogXp::_Check4Association () { for (size_t i = 0; i < COUNT_OF(s_extTable); ++ i) { HWND hWnd = GetDlgItem(std::get<0>(s_extTable[i])); if (hWnd == NULL) { continue; } xl::ExplodeT<xl::tchar>::ValueT exts = xl::explode(_T(";"), std::get<1>(s_extTable[i])); bool isDefault = true; for (auto it = exts.begin(); it != exts.end(); ++ it) { if (!isDefault4Xp(*it)) { isDefault = false; break; } } Button_SetCheck(hWnd, isDefault ? BST_CHECKED : BST_UNCHECKED); } } void CFileAssociationDialogXp::_OnCheckboxChange () { bool changed = false; for (size_t i = 0; i < COUNT_OF(s_extTable); ++ i) { HWND hWnd = GetDlgItem(std::get<0>(s_extTable[i])); if (hWnd == NULL) { continue; } xl::ExplodeT<xl::tchar>::ValueT exts = xl::explode(_T(";"), std::get<1>(s_extTable[i])); bool isDefault = true; for (auto it = exts.begin(); it != exts.end(); ++ it) { if (!isDefault4Xp(*it)) { isDefault = false; break; } } bool checked = Button_GetCheck(hWnd) == BST_CHECKED; if (checked != isDefault) { changed = true; break; } } HWND hWnd = GetDlgItem(IDC_BUTTON_APPLY); ::EnableWindow(hWnd, changed); } void CFileAssociationDialogXp::_OnApply () { for (size_t i = 0; i < COUNT_OF(s_extTable); ++ i) { HWND hWnd = GetDlgItem(std::get<0>(s_extTable[i])); if (hWnd == NULL) { continue; } bool checked = Button_GetCheck(hWnd) == BST_CHECKED; xl::ExplodeT<xl::tchar>::ValueT exts = xl::explode(_T(";"), std::get<1>(s_extTable[i])); for (auto it = exts.begin(); it != exts.end(); ++ it) { if (isDefault4Xp(*it) != checked) { if (checked) { setDefault4Xp(*it); } else { restoreDefault4Xp(*it, std::get<2>(s_extTable[i])); } } } } HWND hWnd = GetDlgItem(IDC_BUTTON_APPLY); ::EnableWindow(hWnd, false); } CFileAssociationDialogXp::CFileAssociationDialogXp () : m_hWndTab(NULL) { } CFileAssociationDialogXp::~CFileAssociationDialogXp () { } void CFileAssociationDialogXp::setTabWindow (HWND hWndTab) { assert(hWndTab != NULL); m_hWndTab = hWndTab; } LRESULT CFileAssociationDialogXp::OnInitDialog (UINT, WPARAM, LPARAM, BOOL &) { bool isRegistered = isAppRegistered(); HWND hStatic = GetDlgItem(isRegistered ? IDC_STATIC_FILEASSOC : IDC_STATIC_REINSTALL); assert(hStatic != NULL); DWORD dwStyle = ::GetWindowLong(hStatic, GWL_STYLE); dwStyle |= SS_CENTER; ::SetWindowLong(hStatic, GWL_STYLE, dwStyle); HWND hButton = GetDlgItem(IDC_BUTTON_APPLY); assert(hButton); // Save the check box HWNDs UINT checkbox_ids[] = { IDC_CHECKBOX_JPG, IDC_CHECKBOX_PNG, }; for (int i = 0; i < COUNT_OF(checkbox_ids); ++ i) { HWND hWnd = GetDlgItem(checkbox_ids[i]); assert(hWnd != NULL); m_checkBoxes.push_back(hWnd); } if (isRegistered) { ::ShowWindow(hStatic, SW_SHOW); ::ShowWindow(hButton, SW_SHOW); std::for_each(m_checkBoxes.begin(), m_checkBoxes.end(), [] (HWND hWnd) { ::ShowWindow(hWnd, SW_SHOW); }); } else { ::ShowWindow(hStatic, SW_SHOW); } xl::tchar text[MAX_PATH]; xl::CLanguage *pLanguage = xl::CLanguage::getInstance(); HWND hWnds[] = {hStatic, hButton}; for (int i = 0; i < COUNT_OF(hWnds); ++ i) { HWND hWnd = hWnds[i]; ::GetWindowText(hWnd, text, MAX_PATH); xl::tstring lang = pLanguage->getString(text); ::SetWindowText(hWnd, lang.c_str()); } std::for_each(m_checkBoxes.begin(), m_checkBoxes.end(), [=, &text] (HWND hWnd) { ::GetWindowText(hWnd, text, MAX_PATH); xl::tstring lang = pLanguage->getString(text); ::SetWindowText(hWnd, lang.c_str()); }); _Check4Association(); return TRUE; } LRESULT CFileAssociationDialogXp::OnSize (UINT, WPARAM, LPARAM, BOOL &) { bool isRegistered = isAppRegistered(); HWND hStatic = GetDlgItem(isRegistered ? IDC_STATIC_FILEASSOC : IDC_STATIC_REINSTALL); assert(hStatic != NULL); HWND hButton = GetDlgItem(IDC_BUTTON_APPLY); assert(hButton); CRect rc; GetClientRect(&rc); rc.DeflateRect(TAB_PADDING_X, TAB_PADDING_Y); CRect rcStatic; ::GetClientRect(hStatic, &rcStatic); CRect rcButton; ::GetClientRect(hButton, &rcButton); if (!isRegistered) { ::MoveWindow(hStatic, rc.left, rc.top, rc.Width(), rc.Height(), TRUE); } else { int x = rc.Width() - rcButton.Width(); int y = rc.Height() - rcButton.Height(); ::MoveWindow(hButton, x, y, rcButton.Width(), rcButton.Height(), TRUE); x = TAB_MARGIN_X + rc.left; y = TAB_MARGIN_Y + rc.top; int width = rc.Width() - TAB_MARGIN_X - TAB_PADDING_X * 2; ::MoveWindow(hStatic, x, y, rcStatic.Width(), rcStatic.Height(), TRUE); y += TAB_MARGIN_Y * 2 + rcStatic.Height(); x += TAB_MARGIN_X; std::for_each(m_checkBoxes.begin(), m_checkBoxes.end(), [=, &rc, &y](HWND hWnd) { CRect rect; ::GetWindowRect(hWnd, &rect); rect.MoveToXY(x, y); y += rect.Height() + TAB_MARGIN_Y; ::MoveWindow(hWnd, rect.left, rect.top, width, rect.Height(), TRUE); }); } return 0; } LRESULT CFileAssociationDialogXp::OnCommand (UINT, WPARAM wParam, LPARAM, BOOL &bHandled) { WORD code = HIWORD(wParam); code = code; WORD id = LOWORD(wParam); switch (id) { case IDC_BUTTON_APPLY: _OnApply(); break; case IDC_CHECKBOX_JPG: case IDC_CHECKBOX_PNG: _OnCheckboxChange(); break; default: bHandled = false; break; } return 0; } LRESULT CFileAssociationDialogXp::OnEraseBkGnd (UINT, WPARAM, LPARAM, BOOL &) { return TRUE; } LRESULT CFileAssociationDialogXp::OnCtlColor (UINT, WPARAM wParam, LPARAM lParam, BOOL &) { HWND hCtrl = (HWND)lParam; HDC hdc = (HDC)wParam; bool isCheckbox = false; for (auto it = m_checkBoxes.begin(); it != m_checkBoxes.end(); ++ it) { if (hCtrl == *it) { isCheckbox = true; break; } } if (isCheckbox) { if (!IsAppThemed() || !IsThemeActive()) { ::SetBkMode((HDC)wParam, TRANSPARENT); } else { HTHEME hTheme = OpenThemeData(hCtrl, L"TAB"); if (hTheme != NULL) { CRect rc, rcTab; ::GetWindowRect(hCtrl, &rc); ::ScreenToClient(m_hWndTab, &rc.TopLeft()); ::ScreenToClient(m_hWndTab, &rc.BottomRight()); int x = -rc.left; int y = -rc.top; rc.MoveToXY(0, 0); ::GetWindowRect(m_hWndTab, &rcTab); rcTab.MoveToXY(0, 0); TabCtrl_AdjustRect(m_hWndTab, FALSE, &rcTab); rcTab.MoveToXY(x + rcTab.left, y + rcTab.top); DrawThemeBackground(hTheme, hdc, TABP_PANE, 0, &rcTab, &rc); CloseThemeData(hTheme); } } } else if (hCtrl == GetDlgItem(IDC_STATIC_REINSTALL) || hCtrl == GetDlgItem(IDC_STATIC_FILEASSOC)) { ::SetBkMode(hdc, TRANSPARENT); } return (LRESULT)::GetStockObject(NULL_BRUSH); } /////////////////////////////////////////////////////////////////////////////// // fOR vISTA aND wINDOWS 7 void CFileAssociationDialogVista::_LaunchSysFileAssociationDialog () { if (!launchAssociationOnVista()) { HWND hStatic = GetDlgItem(IDC_STATIC_REINSTALL); assert(hStatic != NULL); xl::tchar prompt[MAX_PATH]; ::GetWindowText(hStatic, prompt, MAX_PATH); MessageBox(prompt, NULL, MB_OK | MB_ICONERROR); } } CFileAssociationDialogVista::CFileAssociationDialogVista () { } CFileAssociationDialogVista::~CFileAssociationDialogVista () { } LRESULT CFileAssociationDialogVista::OnInitDialog (UINT, WPARAM, LPARAM, BOOL &) { HWND hStatic = GetDlgItem(IDC_STATIC_REINSTALL); assert(hStatic != NULL); DWORD dwStyle = ::GetWindowLong(hStatic, GWL_STYLE); dwStyle |= SS_CENTER; ::SetWindowLong(hStatic, GWL_STYLE, dwStyle); HWND hButton = GetDlgItem(IDC_BUTTON_FILEASSOC); assert(hButton); if (!isAppRegistered()) { ::ShowWindow(hStatic, SW_SHOW); ::ShowWindow(hButton, SW_HIDE); } else { ::ShowWindow(hStatic, SW_HIDE); ::ShowWindow(hButton, SW_SHOW); } xl::tchar text[MAX_PATH]; xl::CLanguage *pLanguage = xl::CLanguage::getInstance(); HWND hWnds[] = {hStatic, hButton}; for (int i = 0; i < COUNT_OF(hWnds); ++ i) { HWND hWnd = hWnds[i]; ::GetWindowText(hWnd, text, MAX_PATH); xl::tstring lang = pLanguage->getString(text); ::SetWindowText(hWnd, lang.c_str()); } return TRUE; } LRESULT CFileAssociationDialogVista::OnSize (UINT, WPARAM, LPARAM, BOOL &) { HWND hStatic = GetDlgItem(IDC_STATIC_REINSTALL); assert(hStatic != NULL); HWND hButton = GetDlgItem(IDC_BUTTON_FILEASSOC); assert(hButton); CRect rc; GetClientRect(&rc); rc.DeflateRect(TAB_PADDING_X, TAB_PADDING_Y); CRect rcStatic; ::GetClientRect(hStatic, &rcStatic); CRect rcButton; ::GetClientRect(hButton, &rcButton); if (!isAppRegistered()) { int y = (rc.Height() - rcStatic.Height()) / 2; ::MoveWindow(hStatic, rc.left, y, rc.Width(), rc.Height(), TRUE); } else { int x = (rc.Width() - rcButton.Width()) / 2; int y = (rc.Height() - rcButton.Height()) / 2; ::MoveWindow(hButton, x, y, rcButton.Width(), rcButton.Height(), TRUE); } return 0; } LRESULT CFileAssociationDialogVista::OnCommand (UINT, WPARAM wParam, LPARAM, BOOL &bHandled) { WORD code = HIWORD(wParam); code = code; WORD id = LOWORD(wParam); switch (id) { case IDC_BUTTON_FILEASSOC: _LaunchSysFileAssociationDialog(); break; default: bHandled = false; break; } return 0; } LRESULT CFileAssociationDialogVista::OnEraseBkGnd (UINT, WPARAM, LPARAM, BOOL &) { return TRUE; } LRESULT CFileAssociationDialogVista::OnCtlColorStatic (UINT, WPARAM wParam, LPARAM, BOOL &) { HDC hdc = (HDC)wParam; ::SetBkMode(hdc, TRANSPARENT); return (LRESULT)::GetStockObject(NULL_BRUSH); }
[ [ [ 1, 381 ] ] ]
b8fdf7a2c36b70eae3be06ea27a90c32e37b1c9e
1e62164424822d8df6b628cbc4cad9a4fe76cf38
/Source Code/CameraPose_OpenCV2.2/testopencv3_match_feather/main.cpp
06494042a0a01acd5a65d80b185e594ce480b1d8
[]
no_license
truongngoctuan/lv2007tm
b41b8cd54360a6dd966f158a7434cfe853627df0
9fa1af79f265dd589e8300017ab857fcfe4fe846
refs/heads/master
2021-01-10T01:58:50.292831
2011-07-30T13:43:17
2011-07-30T13:43:17
48,728,564
0
0
null
null
null
null
UTF-8
C++
false
false
8,514
cpp
#include <fstream> #include <iostream> //#include "ItemManager.h" #include <vector> #include "Util.h" #include <string> //#include "TestIsConnectable.h" #include <cv.h> #include <highgui.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include "SURFMatching.h" using namespace std; using namespace cv; //using for RANSAC Threshold in IsConnectable function //#define DISTANCE_THRES 100 //#define TAN_ANGLE_THRES 0.3 bool IsSameTransitionVector2(float V1x, float V1y, float V2x, float V2y, float fDISTANCE_THRES, float fTAN_ANGLE_THRES) { float fDistance1 = sqrt((float)(V1x * V1x + V1y *V1y)); float fDistance2 = sqrt((float)(V2x * V2x + V2y *V2y)); float ftanAngle1, ftanAngle2; if (IsAlmostEqual(V1x, 0, 0.001)) { if (V1y > 0) { ftanAngle1 = 1; } else { ftanAngle1 = -1; } } else { ftanAngle1 = V1y / V1x; } if (IsAlmostEqual(V2x, 0, 0.001)) { if (V2y > 0) { ftanAngle2 = 1; } else { ftanAngle2 = -1; } } else { ftanAngle2 = V2y / V2x; } if (IsAlmostEqual(fDistance1, fDistance2, fDISTANCE_THRES) && IsAlmostEqual(ftanAngle1, ftanAngle2, fTAN_ANGLE_THRES) && V1y * V2y >= 0)//loai bo truong hop x_am, y_duong va x_duong, y_am --> 2 truong hop dau van thoa dk { return true; } return false; } bool Surf(string strImg1, string strImg2, bool bShowResult = true, float fDISTANCE_THRES = 100, float fTAN_ANGLE_THRES = 0.3) { //img1 string ThisstrFileName = strImg1; CvSeq *ThisimageKeypoints; CvSeq *ThisimageDescriptors; CvMemStorage* Thisstorage; Thisstorage = cvCreateMemStorage(0); IplImage* object = cvLoadImage(ThisstrFileName.c_str(), CV_LOAD_IMAGE_GRAYSCALE ); if(!object) { //"Can not load !!!" } CvSURFParams params = cvSURFParams(0, 0); cvExtractSURF( object, 0, &ThisimageKeypoints, &ThisimageDescriptors, Thisstorage, params ); cvReleaseImage(&object); //------------------------------------------------------------------ //img2 string TargetstrFileName = strImg2; CvSeq *TargetimageKeypoints; CvSeq *TargetimageDescriptors; CvMemStorage* Targetstorage; Targetstorage = cvCreateMemStorage(0); IplImage* object2 = cvLoadImage(TargetstrFileName.c_str(), CV_LOAD_IMAGE_GRAYSCALE ); if(!object) { //"Can not load !!!" } CvSURFParams params2 = cvSURFParams(0, 0); cvExtractSURF( object2, 0, &TargetimageKeypoints, &TargetimageDescriptors, Targetstorage, params2 ); cvReleaseImage(&object2); //------------------------------------------------------------------ vector<int> ptpairs; myfindPairs(TargetimageKeypoints, TargetimageDescriptors, ThisimageKeypoints, ThisimageDescriptors, ptpairs ); CvMat *points1 = cvCreateMat(1, ptpairs.size() / 2, CV_32FC2); CvMat *points2 = cvCreateMat(1, ptpairs.size() / 2, CV_32FC2); for(int i = 0, j = 0; i < (int)ptpairs.size(); i += 2, j++ ) { CvSURFPoint* r1 = (CvSURFPoint*)cvGetSeqElem( ThisimageKeypoints, ptpairs[i+1] ); CvSURFPoint* r2 = (CvSURFPoint*)cvGetSeqElem( TargetimageKeypoints, ptpairs[i] ); points1->data.fl[j*2] = r1->pt.x; points1->data.fl[j*2 + 1] = r1->pt.y; points2->data.fl[j*2] = r2->pt.x; points2->data.fl[j*2 + 1] = r2->pt.y; } //---------------------------------------------------- //RANSAC here unsigned int N = 4000000000;//Near inf int sample_count =0; int pickedIndex = -1; int inlier_number=0; int max_inlier = 0; int max_inlier_pos= -1; int points_number = points1->cols; float e; float P = 0.99; //Probability we select at least one set off all inliers //bool IsDraw = true; //calculate transition vector CvMat* TV = cvCreateMat(2,points_number,CV_32F); CvPoint2D32f* pt1 = (CvPoint2D32f*)points1->data.fl; CvPoint2D32f* pt2 = (CvPoint2D32f*)points2->data.fl; for (int i = 0; i < points_number; i++) { CV_MAT_ELEM(*TV, float, 0, i) = pt1[i].x - pt2[i].x; CV_MAT_ELEM(*TV, float, 1, i) = pt1[i].y - pt2[i].y; } //Determine N- the number of loop srand(time(NULL)); while(sample_count<N) { inlier_number = 0; //pick one pickedIndex = rand() % points_number; //Count the number of inliers for(int i = 0; i < points_number; i++) { float x1 = CV_MAT_ELEM(*TV, float, 0, pickedIndex); float y1 = CV_MAT_ELEM(*TV, float, 1, pickedIndex); float x2 = CV_MAT_ELEM(*TV, float, 0, i); float y2 = CV_MAT_ELEM(*TV, float, 1, i); if (IsSameTransitionVector2(x1, y1, x2, y2, fDISTANCE_THRES, fTAN_ANGLE_THRES)) { inlier_number++; } } e = float(inlier_number)/points_number; N = (log(1-P))/(log(1-pow(e,1)));//hinh nhu chua chinh xac if (inlier_number > max_inlier) { max_inlier = inlier_number; max_inlier_pos = pickedIndex; } sample_count++; } CvMat* ransac_points1 = cvCreateMat(1, max_inlier, CV_32FC2); CvMat* ransac_points2 = cvCreateMat(1, max_inlier, CV_32FC2); CvPoint2D32f* r_pt1 = (CvPoint2D32f*)ransac_points1->data.fl; CvPoint2D32f* r_pt2 = (CvPoint2D32f*)ransac_points2->data.fl; int icounter = 0; for (int i = 0; i < points_number; i++) { float x1 = CV_MAT_ELEM(*TV, float, 0, max_inlier_pos); float y1 = CV_MAT_ELEM(*TV, float, 1, max_inlier_pos); float x2 = CV_MAT_ELEM(*TV, float, 0, i); float y2 = CV_MAT_ELEM(*TV, float, 1, i); if (IsSameTransitionVector2(x1, y1, x2, y2, fDISTANCE_THRES, fTAN_ANGLE_THRES)) { //add into new arr points r_pt1[icounter].x = pt1[i].x; r_pt1[icounter].y = pt1[i].y; r_pt2[icounter].x = pt2[i].x; r_pt2[icounter].y = pt2[i].y; icounter++; } } //---------------------------------------------------- //draw matches points if (bShowResult) { cvNamedWindow("Object Correspond", 1); CvScalar colors[] = {{{255,255,255}}}; IplImage* object = cvLoadImage(ThisstrFileName.c_str(), CV_LOAD_IMAGE_GRAYSCALE ); IplImage* image = cvLoadImage(TargetstrFileName.c_str(), CV_LOAD_IMAGE_GRAYSCALE ); IplImage* object_color = cvCreateImage(cvGetSize(object), 8, 3); cvCvtColor( object, object_color, CV_GRAY2BGR ); CvPoint src_corners[4] = {{0,0}, {object->width,0}, {object->width, object->height}, {0, object->height}}; CvPoint dst_corners[4]; IplImage* correspond = cvCreateImage( cvSize(image->width + object->width, object->height), 8, 1 ); cvSetImageROI( correspond, cvRect( 0, 0, object->width, object->height ) ); cvCopy( object, correspond ); cvSetImageROI( correspond, cvRect( object->width, 0, correspond->width, correspond->height ) ); cvCopy( image, correspond ); cvResetImageROI( correspond ); for(int i = 0; i < max_inlier; i++) { CvPoint2D32f pt2Temp; pt2Temp.x = r_pt2[i].x + object->width; pt2Temp.y = r_pt2[i].y; cvLine(correspond, cvPointFrom32f(r_pt1[i]), cvPointFrom32f(pt2Temp), colors[0]); } cvShowImage( "Object Correspond", correspond ); waitKey(0); cvDestroyWindow("Object Correspond"); } //------------------------------- //write to file ofstream m_stream; m_stream.open("pairs.txt",ios::out); m_stream << max_inlier<<endl; for(int i = 0; i < max_inlier; i++) { CvPoint p1 = cvPointFrom32f(r_pt1[i]); CvPoint p2 = cvPointFrom32f(r_pt2[i]); m_stream << p1.x << " "<<p1.y<< " " << p2.x << " "<<p2.y<< endl; } m_stream.close(); //------------------------------- cout<<"max_inlier"<<max_inlier<<"/"<<points_number<<" percent: "<< (float)max_inlier / (float)points_number<<endl; TRACKING(("max_inlier" + Str_itoa(max_inlier) + "/" + Str_itoa(points_number)).c_str()); if ( max_inlier >= 8) { cout<<"connectable"<<endl; TRACKING("connectable"); return true; } else { cout<<"not connectable"<<endl; TRACKING("not connectable"); return false; } } int main(int argc, char* argv[]) { //http://opencv.willowgarage.com/wiki/VisualC%2B%2B_VS2010 //http://opencv.willowgarage.com/wiki/VisualC%2B%2B //config như hướng dẫn, tuy nhiên cần cập nhật theo tên mới //link > input >addition dependences: opencv_core220d.lib;opencv_highgui220d.lib;%(AdditionalDependencies) try { if(argc == 3) { Surf(argv[1], argv[2]); } else if (argc == 6) { Surf(argv[1], argv[2], atoi(argv[3]), atof(argv[4]), atof(argv[5])); } else { cout<<"no argc matched"<<endl; } } catch(string str) { cout<<str<<endl; } }
[ "[email protected]", "tntuan0712494@a2cfd237-d426-27f4-20f1-81bcd826f934" ]
[ [ [ 1, 2 ], [ 4, 4 ], [ 14, 14 ], [ 16, 16 ], [ 20, 20 ], [ 25, 25 ], [ 28, 28 ], [ 32, 32 ], [ 34, 34 ], [ 102, 102 ], [ 122, 122 ], [ 165, 165 ], [ 167, 167 ], [ 178, 178 ], [ 181, 181 ], [ 201, 201 ], [ 205, 205 ], [ 294, 295 ] ], [ [ 3, 3 ], [ 5, 13 ], [ 15, 15 ], [ 17, 19 ], [ 21, 24 ], [ 26, 27 ], [ 29, 31 ], [ 33, 33 ], [ 35, 101 ], [ 103, 121 ], [ 123, 164 ], [ 166, 166 ], [ 168, 177 ], [ 179, 180 ], [ 182, 200 ], [ 202, 204 ], [ 206, 293 ] ] ]
d4adffe33814f9831fcfe51841a8a8b0a3475ee8
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Multimedia/MmfRecTest/src/mmfrectest.h
2f6815826ec28fdc0d859216efef70b338106591
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
2,882
h
// mmfrectest.h // #ifndef __MMFRECTEST_H #define __MMFRECTEST_H void MainL(); /** This class implements a state machine that records a short clip using each format that the system supports. For each record format that the system supports, it will record 2s of audio to a file, then 2s of audio into a descriptor. It will then move onto the next format. It is necessary to implement this as a state machine as we get asynchronous callbacks via MoscoStateChangeEvent which we have to wait for before we can continue to the next step. For each record format, we go through these states in order: 1. EInitFile - while the file recording is initialised 2. (after the MoscoStateChangeEvent callback) ERecordFile - on a 2s timer while recording takes place 3. EDoOpenDesc - while recording into a descriptor is initialised 4. (after the MoscoStateChangeEvent callback) ERecordDesc - again on a 2s timer. The logic implemented here is probably somewhat more complex that would be necessary for any normal recording, but it demonstrates the principal of how to use the recording API. */ class CMMFRecordTest : public CBase, public MMdaObjectStateChangeObserver { public: static CMMFRecordTest* NewLC(); virtual ~CMMFRecordTest(); void Go(); virtual void MoscoStateChangeEvent(CBase* aObject, TInt aPreviousState, TInt aCurrentState, TInt aErrorCode); private: enum TState { ENone, EDoOpenFile, EInitFile, ERecordFile, EDoOpenDesc, EInitDesc, ERecordDesc, ENext, EDone }; private: CMMFRecordTest(); void ConstructL(); void GetPluginInformationL(); void Printf(TRefByValue<const TDesC16> aFmt, ...); static TInt Callback(TAny* self); void DoCallbackL(); void NextState(TState aState); void InitializeFileL(); void InitializeDesL(); void DeleteFileL(const TDesC& aFileName); TBool GetNextFormatUid(); void Next(); private: /** The current state of the object */ TState iState; /** Used to generate asynchronous callbacks to move between states */ CAsyncCallBack* iCallBack; /** Timer used while recording is in progress */ CPeriodic* iTimer; /** Console used to output messages as the program runs */ CConsoleBase* iConsole; /** The recorder utility which performs all recording */ CMdaAudioRecorderUtility* iRecorder; TCallBack iCbFn; TInt iControllerIndex; TInt iFormatIndex; TUid iControllerUid; TUid iDestinationFormatUid; RMMFControllerImplInfoArray iControllers; RFs iFs; TInt iFileNum; TBuf<0x10> iExtension; TBuf<0x20> iFileName; TBuf<0x100> iFormattingBuf; TBuf8<0x1000> iRecBuf; }; class TTruncateOverflow : public TDes16Overflow { virtual void Overflow(TDes16& /*aDes*/) {}; }; #endif //__MMFRECTEST_H
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 101 ] ] ]
b7c79265251192044ff9ede1e760e95f3bbe3372
09ea547305ed8be9f8aa0dc6a9d74752d660d05d
/smf/smfservermodule/smfserver/server/smfsettingshandler.cpp
8b1b1b1e4b40dcdc3a55bb5a0c7565c4d4b8726e
[]
no_license
SymbianSource/oss.FCL.sf.mw.socialmobilefw
3c49e1d1ae2db8703e7c6b79a4c951216c9c5019
7020b195cf8d1aad30732868c2ed177e5459b8a8
refs/heads/master
2021-01-13T13:17:24.426946
2010-10-12T09:53:52
2010-10-12T09:53:52
72,676,540
0
0
null
null
null
null
UTF-8
C++
false
false
2,386
cpp
/** * Copyright (c) 2010 Sasken Communication Technologies Ltd. * All rights reserved. * This component and the accompanying materials are made available * under the terms of the "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: * Chandradeep Gandhi, Sasken Communication Technologies Ltd - Initial contribution * * Contributors: * Manasij Roy, Nalina Hariharan * * Description: * Reads/Writes settings key in a platform independent way */ #include "smfsettingshandler.h" #ifdef __FOR_SYMBIAN_CR_USAGE__ #include "smfsettingshandler_symbian.h" #else #include "smfsettingshandler_qt.h" #endif SmfSettingsHandler::SmfSettingsHandler(QObject *parent) { Q_UNUSED(parent) #ifdef __FOR_SYMBIAN_CR_USAGE__ m_repository = CSettingsRepository::NewL(); #else m_repository = new SmfSettingsRepositoryQt(this); #endif } SmfSettingsHandler::~SmfSettingsHandler() { if(m_repository) { delete m_repository; m_repository = NULL; } } void SmfSettingsHandler::SetAuthExpirationValue(QString & aVal) { m_repository->SetAuthExpirationValue(aVal); } void SmfSettingsHandler::SetRoamingStatusforDataTransfer(QString & aStatus) { m_repository->SetRoamingStatusforDataTransfer(aStatus); } QString SmfSettingsHandler::GetMaxDataTransferLimit() const { return m_repository->GetMaxDataTransferLimit(); } void SmfSettingsHandler::SetUploadFileType(QString & aFileType) { m_repository->SetUploadFileType(aFileType); } QString SmfSettingsHandler::GetUploadFileType() const { return m_repository->GetUploadFileType(); } void SmfSettingsHandler::SetMaxDataTransferLimit(QString & aVal) { m_repository->SetMaxDataTransferLimit(aVal); } void SmfSettingsHandler::GetPluginDetails(QMap<QString,QString>& aDetails) const { m_repository->GetPluginDetails(aDetails); } QString SmfSettingsHandler::GetAuthExpirationValue() const { return m_repository->GetAuthExpirationValue(); } void SmfSettingsHandler::SetPluginDetails(QString & aPluginName, QString & aPluginStatus) { m_repository->SetPluginDetails(aPluginName,aPluginStatus); } QString SmfSettingsHandler::GetRoamingStatusforDataTransfer() const { return m_repository->GetRoamingStatusforDataTransfer(); }
[ "[email protected]", "none@none" ]
[ [ [ 1, 18 ], [ 22, 22 ], [ 24, 24 ], [ 26, 27 ], [ 30, 31 ], [ 33, 50 ], [ 52, 92 ] ], [ [ 19, 21 ], [ 23, 23 ], [ 25, 25 ], [ 28, 29 ], [ 32, 32 ], [ 51, 51 ] ] ]
f927d6c2d759b123e58887e05dc62cd46dcf2a38
dadae22098e24c412a8d8d4133c8f009a8a529c9
/tp2/src/vector4.h
544f0d2149d25a9f6f0a9afef336cb7a35af3b96
[]
no_license
maoueh/PHS4700
9fe2bdf96576975b0d81e816c242a8f9d9975fbc
2c2710fcc5dbe4cd496f7329379ac28af33dc44d
refs/heads/master
2021-01-22T22:44:17.232771
2009-10-06T18:49:30
2009-10-06T18:49:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,313
h
#ifndef VECTOR4_H #define VECTOR4_H #include "common.h" template <class Real> class Vector4 { public: static const Vector4 ZERO; static const Vector4 UNIT_X; static const Vector4 UNIT_Y; static const Vector4 UNIT_Z; static const Vector4 UNIT_W; inline Vector4(); inline Vector4(Real x, Real y, Real z, Real w = 1.0f); inline explicit Vector4(Real* coordinates); // Takes a four element <Real> array inline explicit Vector4(Real scalar, Real w = 1.0f); inline Vector4(const Vector4& other); inline Real x() const; inline Real& x(); inline Real y() const; inline Real& y(); inline Real z() const; inline Real& z(); inline Real w() const; inline Real& w(); inline void set(Real scalar, Real w = 1.0f); inline void set(Real x, Real y, Real z); inline void set(Real x, Real y, Real z, Real w); inline void set(Real* coordinates); // Takes a four element <Real> array inline void set2(Real* coordinates); // Takes a two element <Real> array inline void set3(Real* coordinates); // Takes a three element <Real> array inline void assignTo(Real* values); // Assign the array received with the components of the vector inline Vector4& operator= (const Vector4& rightSide); inline operator const Real* () const; inline operator Real* (); inline Real operator[] (INT index) const; inline Real& operator[] (INT index); inline BOOL operator== (const Vector4& rightSide) const; inline BOOL operator!= (const Vector4& rightSide) const; inline Vector4& operator+= (const Vector4& rightSide); inline Vector4& operator-= (const Vector4& rightSide); inline Vector4& operator*= (Real scalar); inline Vector4& operator/= (Real scalar); inline Vector4 operator- () const; inline Vector4 operator+ (const Vector4& rightSide) const; inline Vector4 operator- (const Vector4& rightSide) const; inline Vector4 operator* (Real scalar) const; inline Vector4 operator/ (Real scalar) const; // Be careful : the length is not squarred, use magnitude for the squarred value inline Real length() const; inline Real magnitude() const; inline Vector4 normalize() const; inline static Real scalarProduct(Vector4& leftSide, const Vector4& rightSide); // Same as dotProduct inline static Real dotProduct(Vector4& leftSide, const Vector4& rightSide); // Same as scalarProduct inline static Vector4 vectorProduct(Vector4& leftSide, const Vector4& rightSide); // Same as crossProduct inline static Vector4 crossProduct(Vector4& leftSide, const Vector4& rightSide); // Same as vectorProduct inline static Real distance(Vector4& leftSide, const Vector4& rightSide); Real components[4]; }; template <class Real> Vector4<Real> operator* (Real scalar, const Vector4<Real>& rightSide); template <class Real> Vector4<Real> operator/ (Real scalar, const Vector4<Real>& rightSide); template <class Real> ostream& operator<< (ostream& outputStream, const Vector4<Real>& vector); #include "vector4.inl" typedef Vector4<FLOAT> Vector4f; typedef Vector4<DOUBLE> Vector4d; typedef Vector4<FLOAT> Vector; #endif
[ [ [ 1, 91 ] ] ]
47169630002a0e1e9bcb3dfa74bb811b4d48ed58
c436aa4235117da3d21fafeeafd96076ee8fea78
/AutoHotkey.cpp
34c89c42f78ef9489a474f3e9961bd5522960054
[]
no_license
tinku99/ahkmingw
95bb91840b5b596f7c9c2e42b9fd6f554dc99623
8ee59d8a0c4262bab2069953514bda8ed116116d
refs/heads/master
2020-12-30T14:56:10.907187
2010-02-16T10:37:34
2010-02-16T10:37:34
290,514
3
1
null
null
null
null
UTF-8
C++
false
false
17,866
cpp
/* AutoHotkey Copyright 2003-2008 Chris Mallett ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ #ifndef DLLN #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_hInstance = hInstance; InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(sizeof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; #ifndef AUTOHOTKEYSC #ifdef _DEBUG //char *script_filespec = "C:\\Util\\AutoHotkey.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\GUI Demo.ahk"; char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\MAIN.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Expressions.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Line Continuation.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\DllCall.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\RegExMatch & RegExReplace.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Win commands, all cases.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\GUI Date.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\GUI ListView.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\OnMessage.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Send command.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Ref\\ImageSearch\\TEST SUITE\\MAIN.ahk"; //char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\New Text Document.ahk"; #else char *script_filespec = NULL; // Set default as "unspecified/omitted". #endif #endif // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). char var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; for (int i = 1; i < __argc; ++i) // Start at 1 because 0 contains the program name. { param = __argv[i]; // For performance and convenience. if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, sprintf(var_name, "%d", script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!stricmp(param, "/R") || !stricmp(param, "/restart")) restart_mode = true; else if (!stricmp(param, "/F") || !stricmp(param, "/force")) g_ForceLaunch = true; else if (!stricmp(param, "/ErrorStdOut")) g_script.mErrorStdOut = true; #ifndef AUTOHOTKEYSC // i.e. the following switch is recognized only by AutoHotkey.exe (especially since recognizing new switches in compiled scripts can break them, unlike AutoHotkey.exe). else if (!stricmp(param, "/iLib")) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= __argc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/crease the file unconditionally and keep it open until exit. if ( !(g_script.mIncludeLibraryFunctionsThenExit = fopen(__argv[i], "w")) ) // Can't open the temp file. return CRITICAL_ERROR; } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. #ifdef AUTOHOTKEYSC --i; // Make the loop process this item again so that it will be treated as a script param. #else script_filespec = param; // The first unrecognized switch must be the script filespec, by design. #endif } } #ifndef AUTOHOTKEYSC if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = strlen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { char *cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!stricmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } #endif // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar("0")) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); global_init(g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: #ifdef AUTOHOTKEYSC if (g_script.Init("", restart_mode) != OK) #else if (g_script.Init(script_filespec, restart_mode) != OK) // Set up the basics of the script, using the above. #endif return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, &g, sizeof(global_struct)); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else LineNumberType load_result = g_script.LoadFromFile(script_filespec == NULL); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox("An older instance of this script is already running. Replace it with this" " instance?\nNote: To avoid this message, see #SingleInstance in the help file." , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: ASK_INSTANCE_TO_CLOSE(w_existing, reason_to_close_prior); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(20); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox("Could not close the previous instance of this script. Keep waiting?", 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle("comctl32"), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) g_script.mIsReadyToExecute = true; // This is done only now for error reporting purposes in Hotkey.cpp. // Run the auto-execute part at the top of the script (this call might never return): ResultType result = g_script.AutoExecSection(); // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless the OnExit subroutine doesn't exit: if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(result == FAIL ? EXIT_ERROR : EXIT_EXIT); // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "backround thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(g); // Start with a "clean slate" in both g and g_default. CopyMemory(&g_default, &g, sizeof(global_struct)); // Above has set g.IsPaused==false in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, we do not set it to NONE right before launching each new hotkey subroutine because // it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value of // ErrorLevel set by another). This reset was also done by LoadFromFile(), but we do it again // here in case the auto-exectute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Since we're about to enter the script's idle state, set the "idle thread" to // be minimum priority so that it can always be "interrupted" (though technically, // there is no actual idle quasi-thread, so it can't really be interrupted): g.Priority = PRIORITY_MINIMUM; g.ThreadIsCritical = false; // v1.0.38.04: Prevent the idle thread from being seen as uninterruptible. g.AllowTimers = true; // v1.0.40.01: Similar to above. g.AllowThreadToBeInterrupted = true; // This is the primary line, the one above is not strictly necessary (just for maintainability). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } #endif
[ [ [ 1, 324 ] ] ]
8755e5b54ac329bdcade22f2c6676d8a84bc3f28
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/openexr/src/IlmImf/ImfStdIO.cpp
f36b52bc0537023e9f436a6b480b599ec5e24dd0
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
4,720
cpp
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // Low-level file input and output for OpenEXR // based on C++ standard iostreams. // //----------------------------------------------------------------------------- #include <ImfStdIO.h> #include "Iex.h" #include <errno.h> using namespace std; namespace Imf { namespace { void clearError () { errno = 0; } bool checkError (istream &is) { if (!is) { if (errno) Iex::throwErrnoExc(); return false; } return true; } void checkError (ostream &os) { if (!os) { if (errno) Iex::throwErrnoExc(); throw Iex::ErrnoExc ("File output failed."); } } } // namespace StdIFStream::StdIFStream (const char fileName[]): IStream (fileName), _is (new ifstream (fileName, ios_base::binary)), _deleteStream (true) { if (!*_is) { delete _is; Iex::throwErrnoExc(); } } StdIFStream::StdIFStream (ifstream &is, const char fileName[]): IStream (fileName), _is (&is), _deleteStream (false) { // empty } StdIFStream::~StdIFStream () { if (_deleteStream) delete _is; } bool StdIFStream::read (char c[/*n*/], int n) { if (!*_is) throw Iex::InputExc ("Unexpected end of file."); clearError(); _is->read (c, n); return checkError (*_is); } Int64 StdIFStream::tellg () { return std::streamoff (_is->tellg()); } void StdIFStream::seekg (Int64 pos) { _is->seekg ((std::streamoff)pos); checkError (*_is); } void StdIFStream::clear () { _is->clear(); } StdOFStream::StdOFStream (const char fileName[]): OStream (fileName), _os (new ofstream (fileName, ios_base::binary)), _deleteStream (true) { if (!*_os) { delete _os; Iex::throwErrnoExc(); } } StdOFStream::StdOFStream (ofstream &os, const char fileName[]): OStream (fileName), _os (&os), _deleteStream (false) { // empty } StdOFStream::~StdOFStream () { if (_deleteStream) delete _os; } void StdOFStream::write (const char c[/*n*/], int n) { clearError(); _os->write (c, n); checkError (*_os); } Int64 StdOFStream::tellp () { return std::streamoff (_os->tellp()); } void StdOFStream::seekp (Int64 pos) { _os->seekp ((std::streamoff)pos); checkError (*_os); } StdOSStream::StdOSStream (): OStream ("(string)") { // empty } void StdOSStream::write (const char c[/*n*/], int n) { clearError(); _os.write (c, n); checkError (_os); } Int64 StdOSStream::tellp () { return std::streamoff (_os.tellp()); } void StdOSStream::seekp (Int64 pos) { _os.seekp ((std::streamoff)pos); checkError (_os); } } // namespace Imf
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 234 ] ] ]
13d0fc4ad69931f2f1c25d31ec2cb5cfb93f6cba
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlNormalCompression.h
edffefe7e77d155174729c6640931df6c251a836
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
2,159
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLNORMALCOMPRESSION_H #define WMLNORMALCOMPRESSION_H #include "WmlSystem.h" namespace Wml { // Compress unit-length normal vectors (x,y,z) to 16-bit quantities. 3 bits // are used to identify the octant containing the vector, the other 13 bits // are used for the mantissa. WML_ITEM void CompressNormal (double dX, double dY, double dZ, unsigned short& rusIndex); WML_ITEM void UncompressNormal (unsigned short usIndex, double& rdX, double& rdY, double& rdZ); // An example of how to use the compression. This shows the maximum error is // about 10-degrees between the original and the compressed-then-uncompressed // vector. // //void TestCompression () //{ // const int iS = 1024; // double dDotMin = 1.0; // int iXMin = iS, iYMin = iS; // // for (int iY = 0; iY < iS; iY++) // { // double dY0 = iY/(double)iS; // for (int iX = 0; iX < iS; iX++) // { // double dX0 = iX/(double)iS; // double dZ0 = 1.0 - dX0*dX0 - dY0*dY0; // if ( dZ0 >= 0.0 ) // { // dZ0 = sqrt(dZ0); // // unsigned short usIndex; // CompressNormal(dX0,dY0,dZ0,usIndex); // assert( usIndex < 8192 ); // // double dX1, dY1, dZ1; // UncompressNormal(usIndex,dX1,dY1,dZ1); // // double dDot = dX0*dX1+dY0*dY1+dZ0*dZ1; // if ( dDot < dDotMin ) // { // dDotMin = dDot; // iXMin = iX; // iYMin = iY; // } // } // } // } // // // S = 16384, dotmin = 0.98474228151906 (about 10-degrees error) //} } #endif
[ [ [ 1, 72 ] ] ]
a1d072227d024d1f455ce17cfebd2743a5e78870
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/SplitterControl.cpp
8669fdff181da116162b7a8b418e3f7fbc1a7aec
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,770
cpp
//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 "SplitterControl.h" #include "UserMsgs.h" #include ".\splittercontrol.h" #include "emule.h" #include "emuledlg.h" #include "FaceManager.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSplitterControl HCURSOR CSplitterControl::m_hcurMoveVert = NULL; HCURSOR CSplitterControl::m_hcurMoveHorz = NULL; BEGIN_MESSAGE_MAP(CSplitterControl, CStatic) ON_WM_PAINT() ON_WM_MOUSEMOVE() ON_WM_SETCURSOR() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() //ON_CONTROL_REFLECT(STN_DBLCLK, OnStnDblclick) END_MESSAGE_MAP() CSplitterControl::CSplitterControl() { // Mouse is pressed down or not ? m_bIsPressed = FALSE; // Min and Max range of the splitter. m_nMin = m_nMax = -1; m_bNormalDraw = TRUE; } CSplitterControl::~CSplitterControl() { } void CSplitterControl::Create(DWORD dwStyle, const CRect &rect, CWnd *pParent, UINT nID) { CRect rc = rect; dwStyle |= SS_NOTIFY; // Determine default type base on it's size. m_nType = (rc.Width() < rc.Height()) ? SPS_VERTICAL : SPS_HORIZONTAL; if (m_nType == SPS_VERTICAL) rc.right = rc.left + GetVBreadth(); else // SPS_HORIZONTAL rc.bottom = rc.top + GetHBreadth(); CStatic::Create(_T(""), dwStyle, rc, pParent, nID); if (!m_hcurMoveVert) { m_hcurMoveVert = AfxGetApp()->LoadStandardCursor(IDC_SIZEWE); m_hcurMoveHorz = AfxGetApp()->LoadStandardCursor(IDC_SIZENS); } // force the splitter not to be splited. SetRange(0, 0, -1); } int CSplitterControl::SetStyle(int nStyle) { int m_nOldStyle = m_nType; m_nType = nStyle; return m_nOldStyle; } int CSplitterControl::GetStyle() { return m_nType; } void CSplitterControl::OnPaint() { CPaintDC dc(this); // device context for painting CRect rcClient; GetClientRect(rcClient); Draw(&dc, &rcClient); } void CSplitterControl::OnMouseMove(UINT nFlags, CPoint point) { if (m_bIsPressed) { CWindowDC dc(NULL); DrawLine(&dc, m_nX, m_nY); CPoint pt = point; ClientToScreen(&pt); GetParent()->ScreenToClient(&pt); if (pt.x < m_nMin) pt.x = m_nMin; if (pt.y < m_nMin) pt.y = m_nMin; if (pt.x > m_nMax) pt.x = m_nMax; if (pt.y > m_nMax) pt.y = m_nMax; GetParent()->ClientToScreen(&pt); m_nX = pt.x; m_nY = pt.y; DrawLine(&dc, m_nX, m_nY); } CStatic::OnMouseMove(nFlags, point); } BOOL CSplitterControl::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { if (nHitTest == HTCLIENT) { (m_nType == SPS_VERTICAL) ? ::SetCursor(m_hcurMoveVert) : ::SetCursor(m_hcurMoveHorz); return 0; } else return CStatic::OnSetCursor(pWnd, nHitTest, message); } void CSplitterControl::OnLButtonDown(UINT nFlags, CPoint point) { CStatic::OnLButtonDown(nFlags, point); m_bIsPressed = TRUE; SetCapture(); CRect rcWnd; GetWindowRect(rcWnd); if (m_nType == SPS_VERTICAL) m_nX = rcWnd.left + rcWnd.Width() / 2; else m_nY = rcWnd.top + rcWnd.Height() / 2; if (m_nType == SPS_VERTICAL) m_nSavePos = m_nX; else m_nSavePos = m_nY; CWindowDC dc(NULL); DrawLine(&dc, m_nX, m_nY); } void CSplitterControl::OnLButtonUp(UINT nFlags, CPoint point) { if (m_bIsPressed) { ClientToScreen(&point); CWindowDC dc(NULL); DrawLine(&dc, m_nX, m_nY); CPoint pt(m_nX, m_nY); m_bIsPressed = FALSE; CWnd *pOwner = GetOwner(); if (pOwner && IsWindow(pOwner->m_hWnd)) { CRect rc; pOwner->GetClientRect(rc); pOwner->ScreenToClient(&pt); MoveWindowTo(pt); int delta; if (m_nType == SPS_VERTICAL) delta = m_nX - m_nSavePos; else delta = m_nY - m_nSavePos; SPC_NMHDR nmsp; nmsp.hdr.hwndFrom = m_hWnd; nmsp.hdr.idFrom = GetDlgCtrlID(); nmsp.hdr.code = UM_SPN_SIZED; nmsp.delta = delta; pOwner->SendMessage(WM_NOTIFY, nmsp.hdr.idFrom, (LPARAM)&nmsp); } } CStatic::OnLButtonUp(nFlags, point); ReleaseCapture(); } void CSplitterControl::DrawLine(CDC* pDC, int /*x*/, int /*y*/) { int nRop = pDC->SetROP2(R2_NOTXORPEN); CRect rcWnd; GetWindowRect(rcWnd); CPen pen; pen.CreatePen(0, 1, RGB(200, 200, 200)); CPen *pOP = pDC->SelectObject(&pen); int d = 1; if (m_nType == SPS_VERTICAL) { pDC->MoveTo(m_nX - d, rcWnd.top); pDC->LineTo(m_nX - d, rcWnd.bottom); pDC->MoveTo(m_nX + d, rcWnd.top); pDC->LineTo(m_nX + d, rcWnd.bottom); } else // m_nType == SPS_HORIZONTAL { pDC->MoveTo(rcWnd.left, m_nY - d); pDC->LineTo(rcWnd.right, m_nY - d); pDC->MoveTo(rcWnd.left, m_nY + d); pDC->LineTo(rcWnd.right, m_nY + d); } pDC->SetROP2(nRop); pDC->SelectObject(pOP); } void CSplitterControl::Draw(CDC *pDC, const CRect &rect) { if (m_bNormalDraw) { //pDC->FillSolidRect(rect, ::GetSysColor(COLOR_3DFACE)); pDC->FillSolidRect(rect, ::GetSysColor(COLOR_3DFACE)); pDC->Draw3dRect(rect, GetSysColor(COLOR_BTNHIGHLIGHT), GetSysColor(COLOR_BTNSHADOW)); } else { if (SPS_VERTICAL == GetStyle()) CFaceManager::GetInstance()->DrawImage(II_SPLITER_V, pDC->GetSafeHdc(), rect, 2); else if (SPS_HORIZONTAL == GetStyle()) CFaceManager::GetInstance()->DrawImage(II_SPLITER_H, pDC->GetSafeHdc(), rect, 2); } } void CSplitterControl::MoveWindowTo(CPoint pt) { CRect rc; GetWindowRect(rc); CWnd* pParent; pParent = GetParent(); if (!pParent || !::IsWindow(pParent->m_hWnd)) return; pParent->ScreenToClient(rc); if (m_nType == SPS_VERTICAL) { int nMidX = (rc.left + rc.right) / 2; int dx = pt.x - nMidX; rc.OffsetRect(dx, 0); } else { int nMidY = (rc.top + rc.bottom) / 2; int dy = pt.y - nMidY; rc.OffsetRect(0, dy); } MoveWindow(rc); } void CSplitterControl::ChangeWidth(CWnd *pWnd, int dx, DWORD dwFlag) { CWnd* pParent = pWnd->GetParent(); if (pParent && ::IsWindow(pParent->m_hWnd)) { CRect rcWnd; pWnd->GetWindowRect(rcWnd); pParent->ScreenToClient(rcWnd); if (dwFlag == CW_LEFTALIGN) rcWnd.right += dx; else if (dwFlag == CW_RIGHTALIGN) rcWnd.left -= dx; pWnd->MoveWindow(rcWnd); } } void CSplitterControl::ChangeHeight(CWnd *pWnd, int dy, DWORD dwFlag) { CWnd* pParent = pWnd->GetParent(); if (pParent && ::IsWindow(pParent->m_hWnd)) { CRect rcWnd; pWnd->GetWindowRect(rcWnd); pParent->ScreenToClient(rcWnd); if (dwFlag == CW_TOPALIGN) rcWnd.bottom += dy; else if (dwFlag == CW_BOTTOMALIGN) rcWnd.top -= dy; pWnd->MoveWindow(rcWnd); } else ASSERT(0); } void CSplitterControl::ChangePos(CWnd* pWnd, int dx, int dy) { CWnd* pParent = pWnd->GetParent(); if (pParent && ::IsWindow(pParent->m_hWnd)) { CRect rcWnd; pWnd->GetWindowRect(rcWnd); pParent->ScreenToClient(rcWnd); rcWnd.OffsetRect(-dx, dy); pWnd->MoveWindow(rcWnd); } } void CSplitterControl::SetRange(int nMin, int nMax) { m_nMin = nMin; m_nMax = nMax; } // Set splitter range from (nRoot - nSubtraction) to (nRoot + nAddition) // If (nRoot < 0) // nRoot = <current position of the splitter> void CSplitterControl::SetRange(int nSubtraction, int nAddition, int nRoot) { if (nRoot < 0) { CRect rcWnd; GetWindowRect(rcWnd); if (m_nType == SPS_VERTICAL) nRoot = rcWnd.left + rcWnd.Width() / 2; else // if m_nType == SPS_HORIZONTAL nRoot = rcWnd.top + rcWnd.Height() / 2; } m_nMin = nRoot - nSubtraction; m_nMax = nRoot + nAddition; } UINT CSplitterControl::GetHBreadth() { CSize size; if (CFaceManager::GetInstance()->GetImageSize(II_SPLITER_H, size)) return size.cy; else return 0; } UINT CSplitterControl::GetVBreadth() { CSize size; if (CFaceManager::GetInstance()->GetImageSize(II_SPLITER_V, size)) return size.cx; else return 0; }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 368 ] ] ]
2b6988bc6dfae1e33252300374c6fc62f4bd8f6f
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/OgreMaxLoader/Include/ApplicationUtilities.hpp
3ff920d07cf42a33b941ac593d75a2be2a1cb192
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
1,851
hpp
/* * OgreMaxViewer - An Ogre 3D-based viewer for .scene and .mesh files * Copyright 2008 Derek Nedelman * * This code is available under the OgreMax Free License: * -You may use this code for any purpose, commercial or non-commercial. * -If distributing derived works (that use this source code) in binary or source code form, * you must give the following credit in your work's end-user documentation: * "Portions of this work provided by OgreMax (www.ogremax.com)" * * Derek Nedelman assumes no responsibility for any harm caused by using this code. * * OgreMaxViewer was written by Derek Nedelman and released at www.ogremax.com */ #ifndef OgreMax_ApplicationUtilities_INCLUDED #define OgreMax_ApplicationUtilities_INCLUDED //Includes--------------------------------------------------------------------- #include <OgreCamera.h> #include <OgreString.h> #include <OgrePixelFormat.h> //Classes---------------------------------------------------------------------- namespace OgreMax { /** * Utility functions implemented in a way that's specific to how the * application operates */ class ApplicationUtilities { public: /** Copies the relevant camera settings from one camera to another */ static void CopyCameraSettings ( Ogre::Camera* destinationCamera, const Ogre::Camera* sourceCamera ); /** * Chooses the best shadow texture pixel format based on the camera setup * @return Returns true if a pixel format was selected, false otherwise */ static bool ChooseShadowPixelFormat ( Ogre::PixelFormat& pixelFormat, const Ogre::String& cameraSetup ); }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 55 ] ] ]
5129ac26136d7174cc23e71c4c63adb239ab63cc
20cf43a2e1854d71696a6264dea4ea8cbfdb16f2
/WinNT/comm_nt/ui_groupchatwindow.h
8cd58800516989101f525e1a8a041799c79d8ac5
[]
no_license
thebruno/comm-nt
fb0ece0a8d36715a8f0199ba3ce9f37859170ee3
6ba36941b123c272efe8d81b55555d561d8842f4
refs/heads/master
2016-09-07T19:00:59.817929
2010-01-14T20:38:58
2010-01-14T20:38:58
32,205,785
0
0
null
null
null
null
UTF-8
C++
false
false
2,217
h
/******************************************************************************** ** Form generated from reading ui file 'groupchatwindow.ui' ** ** Created: Fri 16. Oct 22:00:34 2009 ** by: Qt User Interface Compiler version 4.5.3 ** ** WARNING! All changes made in this file will be lost when recompiling ui file! ********************************************************************************/ #ifndef UI_GROUPCHATWINDOW_H #define UI_GROUPCHATWINDOW_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHeaderView> #include <QtGui/QMainWindow> #include <QtGui/QMenuBar> #include <QtGui/QStatusBar> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_groupchatwindow { public: QWidget *centralwidget; QMenuBar *menubar; QStatusBar *statusbar; void setupUi(QMainWindow *groupchatwindow) { if (groupchatwindow->objectName().isEmpty()) groupchatwindow->setObjectName(QString::fromUtf8("groupchatwindow")); groupchatwindow->resize(800, 600); centralwidget = new QWidget(groupchatwindow); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); groupchatwindow->setCentralWidget(centralwidget); menubar = new QMenuBar(groupchatwindow); menubar->setObjectName(QString::fromUtf8("menubar")); menubar->setGeometry(QRect(0, 0, 800, 22)); groupchatwindow->setMenuBar(menubar); statusbar = new QStatusBar(groupchatwindow); statusbar->setObjectName(QString::fromUtf8("statusbar")); groupchatwindow->setStatusBar(statusbar); retranslateUi(groupchatwindow); QMetaObject::connectSlotsByName(groupchatwindow); } // setupUi void retranslateUi(QMainWindow *groupchatwindow) { groupchatwindow->setWindowTitle(QApplication::translate("groupchatwindow", "MainWindow", 0, QApplication::UnicodeUTF8)); Q_UNUSED(groupchatwindow); } // retranslateUi }; namespace Ui { class groupchatwindow: public Ui_groupchatwindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_GROUPCHATWINDOW_H
[ "konrad.balys@08f01046-b83b-11de-9b33-83dc4fd2bb11" ]
[ [ [ 1, 67 ] ] ]
29be3b04aa0c04b63c6b7677e595da802ededb7f
38763b01d06c87ff1164877f57fc22d0da2927e4
/src/imageb_player/imgproc/frmProcSinal.cpp
f7631e734247badeea34ac5ec9be54f82e7b6cf1
[]
no_license
JPSGoncalves/ImageB
48b31b83bb1c032394c14e1df5ed90e2a285a521
135ccb9847f9e3394f2391417885d753a5b3a930
refs/heads/master
2023-03-17T03:57:10.299812
2011-07-20T16:59:41
2011-07-20T16:59:41
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,599
cpp
#include <QtGui> #include <QStringList> #include "frmProcSinal.h" #include "ui_frmProcSinal.h" #include "setupsinal.h" //! the max size of vector to be plotted const int PLOT_SIZE = 1000; //! default constructor, initializes class variables frmProcSinal::frmProcSinal(QWidget *parent) { setupUi(this); loadData(); configPlots(); connect(cRamp1, SIGNAL(valueChanged(double)), this, SLOT(chgData()) ); connect(cRamp2, SIGNAL(valueChanged(double)), this, SLOT(chgData()) ); connect(cAtWinStart, SIGNAL(valueChanged(double)), this, SLOT(chgData()) ); connect(cAtWinEnd, SIGNAL(valueChanged(double)), this, SLOT(chgData()) ); connect(cLimiar, SIGNAL(valueChanged(double)), this, SLOT(chgData()) ); connect(botCancel, SIGNAL(clicked()), this, SLOT(close())); connect(botApply, SIGNAL(clicked()), this, SLOT(botApplyClicked())); connect(botReset, SIGNAL(clicked()), this, SLOT(botResetClicked())); } //! makes a local copy of signal_setup variable void frmProcSinal::loadData() { // cout << "rf:" << signal_setup.getRFData().nRow() << "gain:" << signal_setup.getGainVector().nRow() << // " lim: " << signal_setup.getThresholdVec().nRow() << " env:" << signal_setup.getEnv().nRow() << // "env_gain: " << signal_setup.getEnvGain().nRow() << endl; ssetup.copyData(signal_setup, ssetup); } //! reads and prepare all data for plotting void frmProcSinal::configPlots() { rfdata = ssetup.getRFData(); limiar = ssetup.getThresholdVec(); env = ssetup.getEnv(); gain = ssetup.getGainVector(); env_gain = ssetup.getEnvGain(); double d_rfdata[PLOT_SIZE]; double d_env[PLOT_SIZE]; double d_limiar[PLOT_SIZE]; double d_gain[PLOT_SIZE]; double d_env_gain[PLOT_SIZE]; double axis_x[PLOT_SIZE]; for (int j=0; j < PLOT_SIZE; j++ ) { d_limiar[j] = limiar(j+1); d_rfdata[j] = rfdata(j+1); d_env[j] = env(j+1); axis_x[j] = j; d_gain[j] = gain(j+1); d_env_gain[j] = env_gain(j+1); } //seta componentes gráficos do formulário cRamp1->setValue(ssetup.s_ramp); cRamp2->setValue(ssetup.e_ramp); cAtWinStart->setValue(ssetup.s_att); cAtWinEnd->setValue(ssetup.e_att); lineAtVal->setText(QString::number(ssetup.att_factor)); cLimiar->setValue(ssetup.v_limiar); //clear plots plotRF->clear(); plotEnv->clear(); plotGain->clear(); plotSinal->clear(); // Insert new curves QwtPlotCurve *cRF = new QwtPlotCurve("RF"); QwtPlotCurve *cEnv = new QwtPlotCurve("Envelope"); QwtPlotCurve *cLim = new QwtPlotCurve("Limiar"); QwtPlotCurve *cGain = new QwtPlotCurve("Curva Ganho"); QwtPlotCurve *cEnvGain = new QwtPlotCurve("Ganho no Evelope"); cEnv->attach(plotEnv); cLim->attach(plotEnv); cEnvGain->attach(plotSinal); cGain->attach(plotGain); cRF->attach(plotRF); // Set curve styles cRF->setPen(QPen(Qt::red)); cEnv->setPen(QPen(Qt::blue)); cLim->setPen(QPen(Qt::red)); cGain->setPen(QPen(Qt::blue)); cEnvGain->setPen(QPen(Qt::black)); // Attach (don't copy) data. Both curves use the same x array. cRF->setData(axis_x, d_rfdata, PLOT_SIZE); cEnv->setData(axis_x, d_env, PLOT_SIZE); cLim->setData(axis_x,d_limiar,PLOT_SIZE); cGain->setData(axis_x,d_gain,PLOT_SIZE); cEnvGain->setData(axis_x,d_env_gain,PLOT_SIZE); plotRF->replot(); plotEnv->replot(); plotGain->replot(); plotSinal->replot(); proc_data = imageB.procData2BMode(env_gain); //objeto retorna uma imagem redimensionada QImage image = imageB.getBModeImage(211,121, proc_data, 0); imageLabel->setPixmap(QPixmap::fromImage(image));//seta a imagem a ser exibida imageLabel->adjustSize(); setDefault = false; //flag controla a atualização dos controles gráficos, utilizada para resetar os componentes } void frmProcSinal::writeMatrixData(Matrix mat, string filename ) { ofstream dataf(filename.c_str()); if (mat.nCol() == 1) { for(int i=1; i<=mat.nRow(); i++ ) dataf << mat(i) << endl; } else { for (int lin=1; lin <= mat.nRow(); lin++) { //grava linhas e colunas for(int col=1; col <= mat.nCol(); col++) dataf << mat(lin,col) << '\t'; dataf << endl; } } } //! reads new configurations from from and refreshes main variables for processing void frmProcSinal::chgData() { //ssetup.setRFData(rfdata); //imgproc.writeMatrixData(mat,"mat.txt"); //imgproc.writeMatrixData(rfdata,"rfdata.txt"); if (! setDefault) { ssetup.setGain(rfdata.nRow(),(int)(cRamp1->value()),(int)(cRamp2->value())); imgproc.writeMatrixData(ssetup.getGainVector(),"gain.txt"); ssetup.setAttenuation((int)(cAtWinStart->value()),(int)(cAtWinEnd->value()),lineAtVal->text().toDouble()); ssetup.setThreshold((double)(cLimiar->value())); ssetup.applyGainLimiar(); configPlots(); } } //! perform Signal Processing void frmProcSinal::botApplyClicked() { signal_setup = ssetup; emit setupChanged(); //emite sinal para atualização da imagem this->close(); } //! resets configuration void frmProcSinal::botResetClicked() { setDefault = true; ssetup.setDefaults(); configPlots(); }
[ [ [ 1, 194 ] ] ]
379f5a33f146df8abf6ccf84932d1f1189061958
16ba8e891c084c827148d9c6cd6981a29772cb29
/KaraokeMachine/trunk/tools/KMPackageBuilder/src/DialogSongPackageEdit.h
d82d4f51476b4a6aa91263e5ce706e7cc26a823b
[]
no_license
RangelReale/KaraokeMachine
efa1d5d23d0759762f3d6f590e114396eefdb28a
abd3b05d7af8ebe8ace15e888845f1ca8c5e481f
refs/heads/master
2023-06-29T20:32:56.869393
2008-09-16T18:09:40
2008-09-16T18:09:40
37,156,415
1
0
null
null
null
null
UTF-8
C++
false
false
1,140
h
#ifndef _H_DIALOGSONGPACKAGEEDIT_H_ #define _H_DIALOGSONGPACKAGEEDIT_H_ #include <sstream> #include <wx/wx.h> #include <wx/spinctrl.h> #include "KMSong.h" using namespace KaraokeMachine; class KMPB_SongPackageEditDialog : public wxDialog { DECLARE_EVENT_TABLE() public: KMPB_SongPackageEditDialog( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& caption = wxT("Song Package"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX ); ~KMPB_SongPackageEditDialog(); void Init(); void CreateControls(); void Load(KMSongPackage *package); void Save(KMSongPackage *package); virtual bool TransferDataToWindow(); virtual bool TransferDataFromWindow(); protected: enum { ID_FIRST = wxID_HIGHEST, ID_DEFAULTID, ID_TITLE, ID_AUTHOR, ID_DESCRIPTION, }; private: unsigned int defaultid_; wxString title_, author_, description_; }; #endif //_H_DIALOGSONGPACKAGEEDIT_H_
[ "hitnrun@6277c508-b546-0410-9041-f9c9960c1249" ]
[ [ [ 1, 44 ] ] ]
e64773b91e5ea42b2437fda751e41fc7b87e2298
2d212a074917aad8c57ed585e6ce8e2073aa06c6
/cgworkshop/src/fe/FeatureExtraction.cpp
305b858b1649b7ad50120f833cf94a63840e4c26
[]
no_license
morsela/cgworkshop
b31c9ec39419edcedfaed81468c923436528e538
cdf9ef2a9b2d9c389279fe0e38fb9c8bc1d86d89
refs/heads/master
2021-07-29T01:37:24.739450
2007-09-09T13:44:54
2007-09-09T13:44:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,478
cpp
#include "FeatureExtraction.h" #include "cvgabor.h" #include <math.h> // TODO: // Make sure everything everywhere is cleaned up nicely. ////////////////////////////////////////////////////////////////////////////////////// inline double round2( double d ) { return floor( d + 0.5 ); } ////////////////////////////////////////////////////////////////////////////////////// /* static void displayImage(char * title, IplImage * pImg) { cvNamedWindow(title, 1); IplImage* pNewImg = cvCreateImage(cvSize(pImg->width,pImg->height),IPL_DEPTH_8U,1); cvConvertScale(pImg,pNewImg,1,0); cvShowImage(title,pImg); cvWaitKey(0); cvDestroyWindow(title); cvReleaseImage(&pNewImg); } */ ////////////////////////////////////////////////////////////////////////////////////// /* static void saveChannel(char * title, CvMat * pMat) { printf("\nsaveChannel in\n"); CvMat * p8UMat = cvCreateMat( pMat->rows,pMat->cols, CV_8U ); // Convert to unsigned char, 0..255 cvConvertScale(pMat,p8UMat,255,0); // Attach our data to an image header IplImage tImg; cvInitImageHeader(&tImg,cvSize(pMat->cols,pMat->rows),IPL_DEPTH_8U,1); tImg.imageData = (char*) p8UMat->data.ptr; // TODO: Remove this, only a test displayImage(title, &tImg); printf("saveChannel: Saving pchannel to: %s\n", title); if (!cvSaveImage(title,&tImg)) printf("saveChannel: Could not save: %s\n",title); cvReleaseMat(&p8UMat); printf("saveChannel out\n"); } */ ////////////////////////////////////////////////////////////////////////////////////// // TODO: Make sure working...... // Image seems alright, but not perfect void CFeatureExtraction::CalcHistogram(IplImage * pImg, CvMat * pHistogram) { printf("\nCFeatureExtraction::CalcHistogram in\n"); int nBins = 10; int step = pImg->widthStep; int channels = m_nChannels; int w = m_nWidth; int h = m_nHeight; uchar * pData = (uchar *)pImg->imageData; cvSetZero(pHistogram); for (int y=0; y<h; y++) { for (int x=0;x<w; x++) { for (int k=0;k<channels;k++) { // Get appropriate bin for current pixel uchar val = pData[y*step+x*channels+k]; uchar bin = val*nBins/256; // Go over a 5x5 patch, increase appropriate bin by 1 for (int j=y-2;j<=y+2;j++) { int rj = j; // Symmetric mirroring if (rj<0) rj = -rj; if (rj >= h) rj = 2*h-rj-1; for (int i=x-2;i<=x+2;i++) { int ri = i; // Symmetric mirroring if (ri<0) ri = -ri; if (ri >= w) ri = 2*w-ri-1; int row = rj*w+ri; pHistogram->data.fl[row*pHistogram->cols +k*nBins+bin]+=1; } } } } } printf("CFeatureExtraction::CalcHistogram out\n"); } ////////////////////////////////////////////////////////////////////////////////////// bool CFeatureExtraction::GetGaborResponse(IplImage *pGrayImg, IplImage *pResImg, float orientation, float freq, float sx, float sy) { // Create the filter CvGabor *pGabor = new CvGabor(orientation, freq, sx, sy); //pGabor->show(CV_GABOR_REAL); // Convolution pGabor->Apply(pGrayImg, pResImg, CV_GABOR_MAG); return true; } ////////////////////////////////////////////////////////////////////////////////////// bool CFeatureExtraction::GetGaborResponse(CvMat * pGaborMat) { float* pMatPos; int idx = 0; printf("\nCFeatureExtraction::GetGaborResponse in\n"); // Convert our image to grayscale (Gabor doesn't care about colors! I hope?) IplImage *pGrayImg = cvCreateImage(cvSize(m_pSrcImg->width,m_pSrcImg->height), IPL_DEPTH_32F, 1); cvCvtColor(m_pSrcImgFloat,pGrayImg,CV_BGR2GRAY); // The output image IplImage *reimg = cvCreateImage(cvSize(pGrayImg->width,pGrayImg->height), IPL_DEPTH_32F, 1); double freq = 0.4; int freq_steps = 4; int ori_count = 6; double ori_space = PI/ori_count; int i,j; for (i=0;i<freq_steps;i++) { double bw = (2 * freq) / 3; double sx = round2(0.5 / PI / pow(bw,2)); double sy = round2(0.5 * log(2.0) / pow(PI,2.0) / pow(freq,2.0) / (pow(tan(ori_space / 2),2.0))); for (j=0;j<ori_count;j++) { double ori = j*ori_space; GetGaborResponse(pGrayImg, reimg, ori, freq, sx, sy); // This being a test and all, display the image // displayImage(title, reimg); //char filename[255]; //sprintf(filename, "gabor%02d.bmp", idx+1); //cvSaveImage(filename,reimg); // Concat the new vector to the result matrix int k; pMatPos = (float *) pGaborMat->data.fl; float * pResData = (float *) reimg->imageData; for (k=0;k<reimg->width*reimg->height;k++) { pMatPos[idx] = (float) pResData[0]; pMatPos += 24; pResData++; } idx++; } freq /= 2; } // Release cvReleaseImage(&reimg); cvReleaseImage(&pGrayImg); printf("CFeatureExtraction::GetGaborResponse out\n"); return true; } ////////////////////////////////////////////////////////////////////////////////////// // TODO: Would fail if m_nChannels != 3 // RGB to LAB bool CFeatureExtraction::GetColorChannels(CvMat * pChannels, CvMat * pColorChannelsArr[]) { printf("\nCFeatureExtraction::GetColorChannels in\n"); int nSize = COLOR_CHANNEL_NUM; // Convert to LAB color space IplImage *pLabImg = cvCreateImage(cvSize(m_pSrcImg->width,m_pSrcImg->height), IPL_DEPTH_32F, nSize); cvCvtColor(m_pSrcImgFloat,pLabImg,CV_BGR2Lab); // Put the 32F lab image data in a matrix header CvMat srcMat; cvInitMatHeader(&srcMat, m_nWidth*m_nHeight, nSize , CV_32F, (float*)pLabImg->imageData ); // This matrix would hold the values represented in the new basis we've found //CvMat * pResultMat = cvCreateMat( m_nWidth*m_nHeight, nSize , CV_32F ); CvMat * pResultMat = pChannels; // Actual calculation DoPCA(&srcMat, pResultMat, nSize, COLOR_CHANNEL_NUM); // Extracting the 3 primary channels //GetChannels(pResultMat, pColorChannelsArr, nSize, COLOR_CHANNEL_NUM); // Useful releasing cvReleaseImage(&pLabImg); printf("CFeatureExtraction::GetColorChannels out\n"); return true; } ////////////////////////////////////////////////////////////////////////////////////// bool CFeatureExtraction::GetTextureChannels(CvMat * pChannels, CvMat * pTextureChannelsArr[]) { printf("\nCFeatureExtraction::GetTextureChannels in\n"); int gaborSize = 24; int histSize = 30; int vectorSize = gaborSize+histSize; // Calc the full histogram vectors CvMat * pHistMat = cvCreateMat( m_nWidth*m_nHeight, histSize , CV_32F ); CalcHistogram(m_pSrcImg, pHistMat); // Do we need to normalize? // cvNormalize(pHistMat, pHistMat, 0, 1, CV_MINMAX); CvMat * pGaborMat = cvCreateMat (m_nWidth * m_nHeight, gaborSize, CV_32F); GetGaborResponse(pGaborMat); // Do we need to normalize? //cvNormalize(pGaborMat, pGaborMat, 0, 1, CV_MINMAX); // Our merged matrix CvMat * pTextureMat = cvCreateMat( m_nWidth*m_nHeight, vectorSize , CV_32F ); // Combine into a single matrix MergeMatrices(pGaborMat, pHistMat, pTextureMat); // This matrix would hold the values represented in the new basis we've found //CvMat * pResultMat = cvCreateMat( m_nWidth*m_nHeight, TEXTURE_CHANNEL_NUM , CV_32F ); CvMat * pResultMat = pChannels; // Actual calculation DoPCA(pTextureMat, pResultMat, vectorSize, TEXTURE_CHANNEL_NUM); // Extracting the 3 primary channels //GetChannels(pResultMat, pTextureChannelsArr, TEXTURE_CHANNEL_NUM, TEXTURE_CHANNEL_NUM); cvReleaseMat(&pHistMat); cvReleaseMat(&pGaborMat); cvReleaseMat(&pTextureMat); printf("CFeatureExtraction::GetTextureChannels out\n"); return true; } ////////////////////////////////////////////////////////////////////////////////////// bool CFeatureExtraction::DoPCA(CvMat * pMat, CvMat * pResultMat, int nSize, int nExpectedSize) { printf("\nCFeatureExtraction::DoPCA in\n"); int i; printf("DoPCA: Sort our data sets in a vector each\n"); // Sort our data sets in a vector each CvMat ** pDataSet = new CvMat*[m_nWidth*m_nHeight]; float * pData = pMat->data.fl; for (i=0;i<m_nWidth*m_nHeight;i++) { pDataSet[i] = (CvMat*) malloc(sizeof(CvMat)); cvInitMatHeader(pDataSet[i], 1, nSize, CV_32FC1, &pData[i*nSize]); } printf("DoPCA: Calc covariance matrix\n"); // Calc covariance matrix CvMat* pCovMat = cvCreateMat( nSize, nSize, CV_32F ); CvMat* pMeanVec = cvCreateMat( 1, nSize, CV_32F ); cvCalcCovarMatrix( (const void **)pDataSet, m_nWidth*m_nHeight, pCovMat, pMeanVec, CV_COVAR_SCALE | CV_COVAR_NORMAL ); cvReleaseMat(&pMeanVec); printf("DoPCA: Do the SVD decomposition\n"); // Do the SVD decomposition CvMat* pMatW = cvCreateMat( nSize, 1, CV_32F ); CvMat* pMatV = cvCreateMat( nSize, nSize, CV_32F ); CvMat* pMatU = cvCreateMat( nSize, nSize, CV_32F ); cvSVD(pCovMat, pMatW, pMatU, pMatV, CV_SVD_MODIFY_A+CV_SVD_V_T); cvReleaseMat(&pCovMat); cvReleaseMat(&pMatW); cvReleaseMat(&pMatV); printf("DoPCA: Extract the requested number of dominant eigen vectors\n"); // Extract the requested number of dominant eigen vectors CvMat* pEigenVecs = cvCreateMat( nSize, nExpectedSize, CV_32F ); for (i=0;i<nSize;i++) memcpy(&pEigenVecs->data.fl[i*nExpectedSize], &pMatU->data.fl[i*nSize], nExpectedSize*sizeof(float)); printf("DoPCA: Transform to the new basis\n"); // Transform to the new basis cvMatMul(pMat, pEigenVecs, pResultMat); cvReleaseMat(&pMatU); cvReleaseMat(&pEigenVecs); for (i = 0; i < m_nHeight * m_nWidth; i++) delete [] pDataSet[i]; delete [] pDataSet; printf("CFeatureExtraction::DoPCA out\n"); return true; } ////////////////////////////////////////////////////////////////////////////////////// bool CFeatureExtraction::MergeMatrices(CvMat * pMatrix1, CvMat * pMatrix2, CvMat * pResultMat) { printf("\nCFeatureExtraction::MergeMatrices in\n"); // Go over row by row, concat the two matrices char * pResData= (char *) pResultMat->data.ptr; char * pData1 = (char *) pMatrix1->data.ptr; char * pData2 = (char *) pMatrix2->data.ptr; int step1 = pMatrix1->step; int step2 = pMatrix2->step; int i; for (i=0;i<pResultMat->rows;i++) { memcpy(pResData, pData1, step1); pResData+=step1; pData1+=step1; memcpy(pResData, pData2, step2); pResData+=step2; pData2+=step2; } printf("\nCFeatureExtraction::MergeMatrices out\n"); return true; } // TODO: Fix this. bool CFeatureExtraction::MergeMatrices(CvMat * pMatrix1, CvMat * pMatrix2, CvMat * pMatrix3, CvMat * pResultMat) { printf("\nCFeatureExtraction::MergeMatrices3 in\n"); // Go over row by row, concat the two matrices char * pResData= (char *) pResultMat->data.ptr; char * pData1 = (char *) pMatrix1->data.ptr; char * pData2 = (char *) pMatrix2->data.ptr; char * pData3 = (char *) pMatrix3->data.ptr; int step1 = pMatrix1->step / pMatrix1->cols; int step2 = pMatrix2->step / pMatrix2->cols; int step3 = pMatrix3->step / pMatrix3->cols; int i; for (i=0;i<pResultMat->rows;i++) { memcpy(pResData, pData1, step1); pResData+=step1; pData1+=step1; memcpy(pResData, pData2, step2); pResData+=step2; pData2+=step2; memcpy(pResData, pData3, step3); pResData+=step3; pData3+=step3; } printf("\nCFeatureExtraction::MergeMatrices out\n"); return true; } ////////////////////////////////////////////////////////////////////////////////////// CFeatureExtraction::CFeatureExtraction(IplImage * pSrcImg) { int i; printf("\nCFeatureExtraction::CFeatureExtraction in\n"); m_pSrcImg = pSrcImg; // Extract parameters m_nChannels = m_pSrcImg->nChannels; m_nWidth = m_pSrcImg->width; m_nHeight = m_pSrcImg->height; printf("CFeatureExtraction: m_nChannels=%d, m_nWidth=%d, m_nHeight=%d\n", m_nChannels, m_nWidth, m_nHeight); // Scale to a 32bit float image (needed for later stages) m_pSrcImgFloat = cvCreateImage(cvSize(m_nWidth,m_nHeight),IPL_DEPTH_32F,3); cvConvertScale(m_pSrcImg,m_pSrcImgFloat,1.0,0); for (i=0;i<3;i++) m_pColorChannelsArr[i] = cvCreateMat( m_nHeight , m_nWidth , CV_32F ); for (i = 0; i < 3; i++) m_pTextureChannelsArr[i] = cvCreateMat(m_nHeight, m_nWidth, CV_32F); m_pTextureChannels = cvCreateMat(m_nHeight * m_nWidth, TEXTURE_CHANNEL_NUM, CV_32F); m_pColorChannels = cvCreateMat(m_nHeight * m_nWidth, COLOR_CHANNEL_NUM, CV_32F); m_pPrincipalChannels = cvCreateMat(m_nHeight * m_nWidth, COLOR_CHANNEL_NUM+TEXTURE_CHANNEL_NUM, CV_32F); printf("CFeatureExtraction::CFeatureExtraction out\n"); } ////////////////////////////////////////////////////////////////////////////////////// CFeatureExtraction::~CFeatureExtraction() { int i; cvReleaseImage(&m_pSrcImgFloat); for (i=0;i<3;i++) cvReleaseMat(&m_pColorChannelsArr[i]); for (i=0;i<3;i++) cvReleaseMat(&m_pTextureChannelsArr[i]); cvReleaseMat(&m_pTextureChannels); cvReleaseMat(&m_pColorChannels); cvReleaseMat(&m_pPrincipalChannels); } ////////////////////////////////////////////////////////////////////////////////////// bool CFeatureExtraction::Run() { printf("\nCFeatureExtraction::Run in\n"); GetColorChannels(m_pColorChannels, m_pColorChannelsArr); GetTextureChannels(m_pTextureChannels, m_pTextureChannelsArr); MergeMatrices(m_pColorChannels, m_pTextureChannels, m_pPrincipalChannels); printf("CFeatureExtraction::out in\n"); return true; } //////////////////////////////////////////////////////////////////////////////////////
[ "ikirsh@60b542fb-872c-0410-bfbb-43802cb78f6e", "morsela@60b542fb-872c-0410-bfbb-43802cb78f6e", "erancho@60b542fb-872c-0410-bfbb-43802cb78f6e" ]
[ [ [ 1, 6 ], [ 9, 14 ], [ 16, 28 ], [ 30, 55 ], [ 57, 58 ], [ 60, 68 ], [ 70, 79 ], [ 81, 114 ], [ 117, 129 ], [ 133, 133 ], [ 136, 189 ], [ 192, 197 ], [ 199, 201 ], [ 203, 212 ], [ 214, 220 ], [ 225, 225 ], [ 227, 230 ], [ 233, 236 ], [ 238, 253 ], [ 255, 256 ], [ 260, 262 ], [ 265, 276 ], [ 278, 316 ], [ 322, 388 ], [ 391, 392 ], [ 396, 407 ], [ 410, 410 ], [ 413, 413 ], [ 415, 419 ], [ 431, 431 ], [ 433, 438 ], [ 441, 444 ], [ 446, 454 ] ], [ [ 7, 8 ], [ 15, 15 ], [ 29, 29 ], [ 56, 56 ], [ 59, 59 ], [ 69, 69 ], [ 80, 80 ], [ 115, 116 ], [ 130, 132 ], [ 134, 135 ], [ 190, 191 ], [ 198, 198 ], [ 213, 213 ], [ 221, 224 ], [ 226, 226 ], [ 231, 232 ], [ 237, 237 ], [ 254, 254 ], [ 257, 259 ], [ 263, 264 ], [ 277, 277 ], [ 317, 321 ], [ 389, 390 ], [ 393, 395 ], [ 408, 409 ], [ 411, 412 ], [ 414, 414 ], [ 420, 430 ], [ 432, 432 ], [ 439, 440 ], [ 445, 445 ], [ 455, 456 ] ], [ [ 202, 202 ] ] ]
f0ca34b24f81c6069b2d7b8bc1ee0fdd01b22ece
9d58409162a450f5dd162c43cfe0dc7c12c00e14
/src/BDUtils.cpp
eda955c64382dbc71668bc930aaf1e600ffb5ce1
[]
no_license
robharper/beat-detect
0f8e9c6feb64e52409972117bed9417795057c76
2f0905d3b657155521c1f4c354b1f75d48d63b04
refs/heads/master
2021-01-01T20:06:05.435288
2011-08-07T17:48:07
2011-08-07T17:48:07
2,169,522
17
2
null
null
null
null
UTF-8
C++
false
false
2,807
cpp
#include "stdafx.h" #include "BDUtils.h" #include <math.h> // Parameters BDParamsType g_BDParams; HRESULT InitializeSettings() { // Onset Detection: // Onset detection minimum onset distance // Onset detection threshold top and bottom levels for hysteresis g_BDParams.flOnsetDetectResetTime = 0.1f; // 100 ms g_BDParams.flOnsetDetectThreshHigh = 0.06f; // 0.06 is From Sepannen g_BDParams.flOnsetDetectThreshLow = -0.035f; // From Sepannen g_BDParams.nOnsetSamplingRate = 441; // Onset Detection and Assembly: // Min onset distance g_BDParams.flOnsetCombineMinDist = 0.05f; // 50 ms g_BDParams.flOnsetCombineMinOnset = 0.1f; // Variable Sampler // Starting Sample Period g_BDParams.fEnableVarSampler = TRUE; g_BDParams.flVarSamplerStartPeriod = 0.02f; // 50 Hz g_BDParams.flVarSamplerMaxErrorTime = 0.06f; // DETERMINE EXPERIMENTALLY: Max jitter offset = ~3 samples g_BDParams.flExpectationStdDevSamples = 2; // From Cemgil et al g_BDParams.flExpectationDeviancePercent = 0.08f; // From Krumhansl, 2000 g_BDParams.flVarSamplerGainProp = 1.0f; // Proportional Gain g_BDParams.flVarSamplerGainDiff = 1.0f; // Differential Gain // Fuzzy onset triangle width g_BDParams.flFuzzyOnsetWidth = g_BDParams.flVarSamplerStartPeriod; // Maximum difference in node periods that consitutes an identical node g_BDParams.flNodeMaxDiff = 0.01f; // Timing Nets: // Loop alpha, beta, time constant // Loop integrator alpha, beta g_BDParams.flLoopInitValue = (FLOAT)pow(2, -5); g_BDParams.flLoopMaxValue = 1 - g_BDParams.flLoopInitValue; // CSN within Timing Nets g_BDParams.flCSNAlpha = 5.0f; g_BDParams.flCSNMinLink = -0.03f; g_BDParams.flCSNMaxLink = 0.04f; g_BDParams.flCSNInputLink = 0.2f; g_BDParams.flCSNDecay = 0.8f; g_BDParams.flCSNMinAct = -1; g_BDParams.flCSNMaxAct = 1; g_BDParams.flCSNOutputTimeThresh = 1.0f; // One second as best required to be selected // Beat Detection Logic for within a loop // Threshold weight between max and loop mean // Minimum threshold allowed g_BDParams.flBeatOutputMinThresh = 0.0f; // // IOI Statistics Collector: // max onset tracking time, histogram halflife // dominant IOI list threshold low and high g_BDParams.flIOIMaxOnsetTime = 1.2f; g_BDParams.flIOIHistHalflife = 2.0f; g_BDParams.flIOIDomThreshRatio = 0.25f; // Performance Measures // g_BDParams.fTrackPerformance = FALSE; g_BDParams.flTrackBeginOffset = 8.0f; g_BDParams.nTrackChangeNode = 0; return S_OK; }
[ [ [ 1, 79 ] ] ]
c3199d72eae07eceed576484e7b378d38fbad9bd
f4b649f3f48ad288550762f4439fcfffddc08d0e
/eRacer/Source/Graphics/SkyBox.h
547382a78762472e97244f6c187c09ba6f4f2376
[]
no_license
Knio/eRacer
0fa27c8f7d1430952a98ac2896ab8b8ee87116e7
65941230b8bed458548a920a6eac84ad23c561b8
refs/heads/master
2023-09-01T16:02:58.232341
2010-04-26T23:58:20
2010-04-26T23:58:20
506,897
1
0
null
null
null
null
UTF-8
C++
false
false
562
h
/** * @file SkyBox.h * @brief Definition of the SkyBox class * * @date 07.02.2010 * @author: Ole Rehmsen */ #pragma once #include "Mesh.h" #include "Camera.h" namespace Graphics { /** * @brief A skybox that always centers around a camera */ class SkyBox : public Renderable { public: SkyBox(); void Init(Mesh* mesh); /** * @brief draw the sky box * * @param device * the device to draw to */ virtual void Draw(IDirect3DDevice9* device) const; bool initialized; private: Mesh* mesh_; }; }
[ [ [ 1, 39 ] ] ]
3a97cb339f1650967949316726c4aae2202aae8b
1536bdbfb912d9bec8cea8c85d144033570bcb62
/agent/browser/ie/urlBlast/UrlMgrFile.cpp
c92a6714e91bf279a0e0a74215721a0ed7763fc3
[]
no_license
sdo-ops/WebPageTest-mirror-
ad6efec365471072ce62b6ecaa4c1eb4f2808794
16bcff6e67a49bc84611cedd3f2d7224893ef021
refs/heads/master
2020-12-24T13:28:49.940398
2011-02-20T16:37:45
2011-02-20T16:37:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,498
cpp
#include "StdAfx.h" #include "UrlMgrFile.h" #include "zip/zip.h" class CUrlMgrFileContext { public: CUrlMgrFileContext(void): hUrlFile(NULL) , fvonly(false) , showProgress(true) , runs(0) , currentRun(0) {} ~CUrlMgrFileContext(void){} CString urlFile; CString scriptFile; CString fileBase; CString serverDir; CString fileRunBase; HANDLE hUrlFile; bool fvonly; bool showProgress; DWORD runs; DWORD currentRun; }; /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CUrlMgrFile::CUrlMgrFile(CLog &logRef):CUrlMgrBase(logRef) { } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CUrlMgrFile::~CUrlMgrFile(void) { } /*----------------------------------------------------------------------------- Do the startup initialization -----------------------------------------------------------------------------*/ void CUrlMgrFile::Start() { // figure out what our working diriectory is TCHAR path[MAX_PATH]; if( SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path)) ) { PathAppend(path, _T("urlblast")); CreateDirectory(path, NULL); lstrcat(path, _T("\\")); workDir = path; // delete everything in the folder to make sure we don't collect cruft WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(workDir + _T("*.*"), &fd); if( hFind ) { do { if( !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) DeleteFile(workDir + fd.cFileName); }while( FindNextFile(hFind, &fd) ); FindClose(hFind); } } } /*----------------------------------------------------------------------------- Load an url from the pagetest file -----------------------------------------------------------------------------*/ bool CUrlMgrFile::GetNextUrl(CTestInfo &info) { bool ret = false; bool includeObject = true; bool progress = false; bool fvonly = false; bool saveEverything = true; bool captureVideo = false; DWORD runs = 0; HANDLE hUrlFile = INVALID_HANDLE_VALUE; WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(urlFilesDir + _T("*.url"), &fd); if( hFind != INVALID_HANDLE_VALUE ) { do { progress = true; bool saveHTML = false; bool saveCookies = false; if( !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) { // build the file name TCHAR szFile[MAX_PATH]; lstrcpy(szFile, urlFilesDir + fd.cFileName); hUrlFile = CreateFile(szFile, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if( hUrlFile != INVALID_HANDLE_VALUE ) { DWORD len = GetFileSize(hUrlFile,NULL); if( len ) { LPBYTE szUrl = (LPBYTE)malloc(len + 1); if( szUrl ) { memset(szUrl, 0, len+1); DWORD read; if( ReadFile(hUrlFile, szUrl, len, &read, 0) ) { // tokenize the file - first line is the url CString file((const char *)szUrl); free(szUrl); int pos = 0; CString line = file.Tokenize(_T("\r\n"), pos); while( pos >= 0 ) { line.Trim(); if( info.url.IsEmpty() ) info.url = line; else { int index = line.Find('='); if( index != -1 ) { CString key = line.Left(index); CString value = line.Right(line.GetLength() - index - 1); key.Trim(); value.Trim(); if( !key.IsEmpty() && !value.IsEmpty() ) { if( !key.CompareNoCase(_T("DOMElement")) ) info.domElement = value; else if( !key.CompareNoCase(_T("fvonly")) ) { if( _ttol(value) ) fvonly = true; } else if( !key.CompareNoCase(_T("object")) ) { if( !_ttol(value) ) includeObject = false; } else if( !key.CompareNoCase(_T("images")) ) { if( !_ttol(value) ) saveEverything = false; } else if( !key.CompareNoCase(_T("progress")) ) { if( !_ttol(value) ) progress = false; } else if( !key.CompareNoCase(_T("Event Name")) ) info.eventText = value; else if( !key.CompareNoCase(_T("web10")) ) { if( _ttol(value) ) info.urlType = 1; } else if( !key.CompareNoCase(_T("ignoreSSL")) ) info.ignoreSSL = _ttol(value); else if( !key.CompareNoCase(_T("connections")) ) info.connections = _ttol(value); else if( !key.CompareNoCase(_T("Harvest Links")) ) info.harvestLinks = _ttol(value) != 0; else if( !key.CompareNoCase(_T("Harvest Cookies")) ) saveCookies = _ttol(value) != 0; else if( !key.CompareNoCase(_T("Save HTML")) ) saveHTML = _ttol(value) != 0; else if( !key.CompareNoCase(_T("Block")) ) info.block = value; else if( !key.CompareNoCase(_T("Basic Auth")) ) info.basicAuth = value; else if( !key.CompareNoCase(_T("runs")) ) runs = _ttol(value); else if( !key.CompareNoCase(_T("Capture Video")) ) { if( _ttol(value) ) captureVideo = true; } else if( !key.CompareNoCase(_T("Host")) ) info.host = value; } } } // on to the next line line = file.Tokenize(_T("\r\n"), pos); } if( info.url.GetLength() > 2 ) if( info.url.Find(_T("://")) == -1 ) info.url = CString(_T("http://")) + info.url; } else free(szUrl); } } if( info.url.IsEmpty() ) { CloseHandle(hUrlFile); DeleteFile(szFile); hUrlFile = INVALID_HANDLE_VALUE; } else { CUrlMgrFileContext * context = new CUrlMgrFileContext; info.context = context; context->urlFile = szFile; context->hUrlFile = hUrlFile; context->fvonly = fvonly; context->showProgress = progress; if( !runs ) runs = 1; context->runs = runs; context->currentRun = 1; // build the log file name LPTSTR ext = PathFindExtension(szFile); if( ext != szFile ) *ext = 0; TCHAR * pFile = PathFindFileName(szFile); context->fileBase = pFile; *pFile = 0; context->serverDir = szFile; context->fileRunBase = context->fileBase; if( context->fileBase.Find(_T('-')) == -1 ) context->fileRunBase += _T("-1"); info.logFile = workDir + context->fileRunBase; if( info.eventText.IsEmpty() ) info.eventText = _T("Run_1"); if( includeObject ) info.includeObjectData = 1; else info.includeObjectData = 0; info.saveEverything = saveEverything; info.captureVideo = captureVideo; // if we are running a script, locate the full path to the file if( info.url.Left(9).MakeLower() == _T("script://") ) { info.runningScript = true; info.scriptFile = info.url.Mid(9); LocateFile(info.scriptFile); info.url = CString(_T("script://")) + info.scriptFile; } // figure out the links file if we are harvesting links if( info.harvestLinks ) info.linksFile = workDir + context->fileRunBase + _T("_links.txt"); if( saveHTML ) info.htmlFile = workDir + context->fileRunBase; if( saveCookies ) info.cookiesFile = workDir + context->fileRunBase; // write the "started" file if( context->showProgress ) { HANDLE hProgress = CreateFile(context->urlFile + _T(".started"), GENERIC_WRITE, 0, &nullDacl, CREATE_ALWAYS, 0, 0); if( hProgress != INVALID_HANDLE_VALUE ) CloseHandle(hProgress); } ret = true; } } } }while(!ret && FindNextFile(hFind, &fd)); FindClose(hFind); } return ret; } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ bool CUrlMgrFile::RunRepeatView(CTestInfo &info) { bool ret = true; if( info.context ) { CUrlMgrFileContext * context = (CUrlMgrFileContext *)info.context; ret = !(context->fvonly); if( ret ) { info.logFile += _T("_Cached"); if( info.harvestLinks ) info.linksFile = workDir + context->fileRunBase + _T("_Cached_links.txt"); if( !info.htmlFile.IsEmpty() ) info.htmlFile = workDir + context->fileRunBase + _T("_Cached"); if( !info.cookiesFile.IsEmpty() ) info.cookiesFile = workDir + context->fileRunBase + _T("_Cached"); } } return ret; } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CUrlMgrFile::UrlFinished(CTestInfo &info) { if( info.context ) { CUrlMgrFileContext * context = (CUrlMgrFileContext *)info.context; if( context->currentRun >= context->runs ) info.done = true; else { info.done = false; // get ready for another run context->currentRun++; CString runText; runText.Format(_T("%d"), context->currentRun); context->fileRunBase = context->fileBase + CString(_T("-")) + runText; info.logFile = workDir + context->fileRunBase; info.eventText = CString(_T("Run_")) + runText; if( info.harvestLinks ) info.linksFile = workDir + context->fileRunBase + _T("_links.txt"); if( !info.htmlFile.IsEmpty() ) info.htmlFile = workDir + context->fileRunBase; if( !info.cookiesFile.IsEmpty() ) info.cookiesFile = workDir + context->fileRunBase; } // clean up if we're actually done if( info.done ) { UploadResults(info); // delete the script file if we need to if( !context->scriptFile.IsEmpty() ) DeleteFile( context->scriptFile ); // clean up the test file CloseHandle(context->hUrlFile); DeleteFile(context->urlFile); delete context; } } } /*----------------------------------------------------------------------------- Find the fully qualified path for the given file -----------------------------------------------------------------------------*/ bool CUrlMgrFile::LocateFile(CString& file) { bool ret = false; // try relative to the url files directory if( !urlFilesDir.IsEmpty() ) { CString filePath = urlFilesDir + file; HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) { file = filePath; ret = true; CloseHandle(hFile); } } // now try opening the file relative to where we are running from if( !ret ) { TCHAR szFile[MAX_PATH]; if( GetModuleFileName(NULL, szFile, _countof(szFile)) ) { *PathFindFileName(szFile) = 0; CString filePath = szFile; filePath += file; HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) { file = filePath; ret = true; CloseHandle(hFile); } } } // try an absolute path if it wasn't relative if( !ret ) { HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) { ret = true; CloseHandle(hFile); } } return ret; } /*----------------------------------------------------------------------------- Upload the test results that we have so far -----------------------------------------------------------------------------*/ void CUrlMgrFile::UploadResults(CTestInfo &info) { if( info.context ) { CUrlMgrFileContext * context = (CUrlMgrFileContext *)info.context; // upload the results if( !context->serverDir.IsEmpty() && !workDir.IsEmpty() && !context->fileBase.IsEmpty() ) { // zip up all of the files CString zipFilePath = workDir + context->fileBase + _T(".zip"); zipFile file = zipOpen(CT2A(zipFilePath), APPEND_STATUS_CREATE); if( file ) { WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(workDir + context->fileBase + _T("*.*"), &fd); if( hFind != INVALID_HANDLE_VALUE ) { do { CString filePath = workDir + fd.cFileName; if( filePath.CompareNoCase(zipFilePath) ) { HANDLE hFile = CreateFile( filePath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) { DWORD size = GetFileSize(hFile, 0); if( size ) { BYTE * mem = (BYTE *)malloc(size); if( mem ) { DWORD bytes; if( ReadFile(hFile, mem, size, &bytes, 0) && size == bytes ) { CString archiveName = fd.cFileName; int index = archiveName.Find(_T("-")); if( index >= 0 ) archiveName = archiveName.Mid(index + 1); // add the file to the archive if( !zipOpenNewFileInZip( file, CT2A(archiveName), 0, 0, 0, 0, 0, 0, Z_DEFLATED, Z_BEST_COMPRESSION ) ) { // write the file to the archive zipWriteInFileInZip( file, mem, size ); zipCloseFileInZip( file ); } } free(mem); } } CloseHandle( hFile ); } DeleteFile(filePath); } }while(FindNextFile(hFind, &fd)); FindClose(hFind); } // close the zip archive zipClose(file, 0); } // upload the actual zip file MoveFileEx(zipFilePath, context->serverDir + context->fileBase + _T(".zip"), MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING); } } }
[ "[email protected]@aac4e670-4c05-fb8f-3594-08f7db841d5f" ]
[ [ [ 1, 492 ] ] ]
d9b5788af4605361d68b1a0115d160a7910474aa
8f5d0d23e857e58ad88494806bc60c5c6e13f33d
/FMod/cSoundManager.cpp
9018573c830ae9e57d1ff95f27fde0a4c4bc48e2
[]
no_license
markglenn/projectlife
edb14754118ec7b0f7d83bd4c92b2e13070dca4f
a6fd3502f2c2713a8a1a919659c775db5309f366
refs/heads/master
2021-01-01T15:31:30.087632
2011-01-30T16:03:41
2011-01-30T16:03:41
1,704,290
1
1
null
null
null
null
UTF-8
C++
false
false
1,715
cpp
#include "cSoundManager.h" #include "../Core/cLog.h" #include "fmod.h" #include "fmod_errors.h" ///////////////////////////////////////////////////////////////////////////////////// cSoundManager::cSoundManager(void) : m_initialized (0) ///////////////////////////////////////////////////////////////////////////////////// { } ///////////////////////////////////////////////////////////////////////////////////// cSoundManager::~cSoundManager(void) ///////////////////////////////////////////////////////////////////////////////////// { DeInitialize (); } ///////////////////////////////////////////////////////////////////////////////////// bool cSoundManager::Initialize() ///////////////////////////////////////////////////////////////////////////////////// { if (m_initialized) return true; // Check the version number if (FSOUND_GetVersion() < FMOD_VERSION) { LOG()->Print ("Error : You are using the wrong DLL version! You should be using FMOD %.02f\n", FMOD_VERSION); return false; } // Initialize to 44kHz, 64bit if (!FSOUND_Init (44100, 64, FSOUND_INIT_GLOBALFOCUS)) { LOG()->Print ("%s\n", FMOD_ErrorString(FSOUND_GetError())); return false; } LOG()->Print ("Successfully initialized the FMOD sound manager."); m_initialized = true; return true; } ///////////////////////////////////////////////////////////////////////////////////// bool cSoundManager::DeInitialize() ///////////////////////////////////////////////////////////////////////////////////// { if (m_initialized) { FSOUND_Close (); m_initialized = false; LOG()->Print ("Successfully de-initialized the FMOD sound manager."); } return true; }
[ [ [ 1, 59 ] ] ]
a26d5929dbffdbe1815f2ab2a665dee980a0b617
5a48b6a95f18598181ef75dba2930a9d1720deae
/LuaEngine/Header/MainDependency.h
3562b2a71591a247560ae852b3380fff3c37b904
[]
no_license
CBE7F1F65/f980f016e8cbe587c9148f07b799438c
078950c80e3680880bc6b3751fcc345ebc8fe8e5
1aaed5baef10a5b9144f20603d672ea5ac76b3cc
refs/heads/master
2021-01-15T10:42:46.944415
2010-08-28T19:25:48
2010-08-28T19:25:48
32,192,651
0
0
null
null
null
null
UTF-8
C++
false
false
859
h
#ifndef _MAINDEPENDENCY_H #define _MAINDEPENDENCY_H #include "Const.h" #include "../../../hge/include/hge.h" #include "../../../hge/include/hgefont.h" #include "../../../hge/include/hgesprite.h" #include "../../../hge/include/hgeeffectsystem.h" #pragma warning(disable:4244) #pragma warning(disable:4800) #pragma warning(disable:504) #pragma comment(lib, "winmm.lib") #ifdef _DEBUG #pragma comment(lib, "hge_d.lib") #pragma comment(lib, "hgehelp_d.lib") #else #pragma comment(lib, "hge.lib") #pragma comment(lib, "hgehelp.lib") #endif // _DEBUG #pragma comment(lib, "bass.lib") #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") #include <windows.h> #include <vector> #include <list> #include <xstring> using namespace std; #include "../LuaPlus/LuaPlus/LuaPlus.h" using namespace LuaPlus; #endif
[ "CBE7F1F65@120521f8-859b-11de-8382-973a19579e60" ]
[ [ [ 1, 37 ] ] ]
9de5a9b849dbcc6418814df282b2c4ea11c757fb
57855d23617d6a65298c2ae3485ba611c51809eb
/Zen/plugins/ZBoostNetworking/src/Endpoint.cpp
3641b8fd8b159553629c810c8c187ba5fa974fca
[]
no_license
Azaezel/quillus-daemos
7ff4261320c29e0125843b7da39b7b53db685cd5
8ee6eac886d831eec3acfc02f03c3ecf78cc841f
refs/heads/master
2021-01-01T20:35:04.863253
2011-04-08T13:46:40
2011-04-08T13:46:40
32,132,616
2
0
null
null
null
null
UTF-8
C++
false
false
3,401
cpp
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Zen Enterprise Framework // // Copyright (C) 2001 - 2009 Tony Richards // Copyright (C) 2008 - 2009 Matthew Alan Gray // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // Tony Richards [email protected] // Matthew Alan Gray [email protected] //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #include <boost/asio.hpp> #include "Endpoint.hpp" #include "HyperTextTransportProtocolService.hpp" #include <Zen/Core/Utility/runtime_exception.hpp> #include <Zen/Enterprise/Networking/I_Address.hpp> #include <Zen/Enterprise/AppServer/I_ProtocolService.hpp> #include <sstream> //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Zen { namespace Enterprise { namespace AppServer { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ Endpoint::Endpoint(wpProtocolService_type _pProtocolAdapter, const boost::asio::ip::tcp::endpoint& _endpoint) : m_pProtocolAdapter(_pProtocolAdapter) , m_endpoint(_endpoint) , m_isLocal(true) { std::stringstream endpointStream; endpointStream << _endpoint; m_endpointString = endpointStream.str(); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ Endpoint::~Endpoint() { } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ boost::asio::ip::tcp::endpoint& Endpoint::getEndpoint() { return m_endpoint; } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ Endpoint::wpProtocolService_type Endpoint::getProtocolAdapter() const { return m_pProtocolAdapter; } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ const Zen::Networking::I_Address& Endpoint::getAddress() const { throw new Utility::runtime_exception("Endpoint::getAddress(): Error, not implemented."); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void Endpoint::setIsLocal(bool _isLocal) { m_isLocal = _isLocal; } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ bool Endpoint::isLocal() const { return m_isLocal; } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace AppServer } // namespace Enterprise } // namespace Zen //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
[ "sgtflame@Sullivan" ]
[ [ [ 1, 98 ] ] ]
fc9c27ceb5c1573efb48577ce042b8be56c11351
8a8873b129313b24341e8fa88a49052e09c3fa51
/src/CoCoappview.cpp
bbae84c8e1d63c7c067a8d6ff4a2ffb87166c33c
[]
no_license
flaithbheartaigh/wapbrowser
ba09f7aa981d65df810dba2156a3f153df071dcf
b0d93ce8517916d23104be608548e93740bace4e
refs/heads/master
2021-01-10T11:29:49.555342
2010-03-08T09:36:03
2010-03-08T09:36:03
50,261,329
1
0
null
null
null
null
UTF-8
C++
false
false
9,055
cpp
/* ============================================================================ Name : CoCoView.cpp Author : 浮生若茶 Version : Copyright : Your copyright notice Description : Application view ============================================================================ */ // INCLUDE FILES #include <coemain.h> #include "CoCoAppView.h" #include "MainEngine.h" #include "MainWindow.h" #include "Graphic.h" #include "EditorsManager.h" #include "PreDefine.h" #include "TypeDefine.h" #include <aknenv.h> #include <avkon.hrh> const TInt KRedrawInterval = 100000; // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CCoCoAppView::NewL() // Two-phased constructor. // ----------------------------------------------------------------------------- // CCoCoAppView* CCoCoAppView::NewL( const TRect& aRect ) { CCoCoAppView* self = CCoCoAppView::NewLC( aRect ); CleanupStack::Pop( self ); return self; } // ----------------------------------------------------------------------------- // CCoCoAppView::NewLC() // Two-phased constructor. // ----------------------------------------------------------------------------- // CCoCoAppView* CCoCoAppView::NewLC( const TRect& aRect ) { CCoCoAppView* self = new ( ELeave ) CCoCoAppView; CleanupStack::PushL( self ); self->ConstructL( aRect ); return self; } // ----------------------------------------------------------------------------- // CCoCoAppView::ConstructL() // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // void CCoCoAppView::ConstructL( const TRect& /*aRect*/ ) { // Create a window for this application view CreateWindowL(); // Set the windows size //SetRect( aRect ); ApplicationStartL(); SetExtentToWholeScreen(); // Activate the window, which makes it ready to be drawn ActivateL(); } // ----------------------------------------------------------------------------- // CCoCoAppView::CCoCoAppView() // C++ default constructor can NOT contain any code, that might leave. // ----------------------------------------------------------------------------- // CCoCoAppView::CCoCoAppView() { // No implementation required } // ----------------------------------------------------------------------------- // CCoCoAppView::~CCoCoAppView() // Destructor. // ----------------------------------------------------------------------------- // CCoCoAppView::~CCoCoAppView() { ApplicationEnd(); // No implementation required } // ----------------------------------------------------------------------------- // CCoCoAppView::Draw() // Draws the display. // ----------------------------------------------------------------------------- // void CCoCoAppView::Draw( const TRect& /*aRect*/ ) const { CWindowGc& gc = SystemGc(); CGraphic& graphic = iMainEngine->Graphic(); const CFbsBitmap* offScreenBitmap = graphic.GetOffScreenBitmap(); gc.BitBlt(TPoint(0,0),offScreenBitmap); } // ----------------------------------------------------------------------------- // CCoCoAppView::SizeChanged() // Called by framework when the view size is changed. // ----------------------------------------------------------------------------- // void CCoCoAppView::SizeChanged() { //事件发生时需要调用SetExtentToWholeScreen(),将导致无穷嵌套递归 //所以不能直接调用界面的SizeChanged(),而在定时器里调用 iSizeChanged = ETrue; } TKeyResponse CCoCoAppView::OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType) { //iMainEngine->WriteLog16(_L("CCoCoAppView::OfferKeyEventL")); ASSERT(iCurWindow); TKeyResponse keyResponse = EKeyWasNotConsumed; CEditorsManager& editorsManager = iMainEngine->EditorsManager(); if(aKeyEvent.iCode != '*' || aKeyEvent.iCode != '#') { keyResponse = editorsManager.OfferKeyEventL(aKeyEvent,aType); } if(keyResponse == EKeyWasNotConsumed && aType == EEventKey) { ASSERT(iCurWindow); //iMainEngine->WriteLog16(_L("CCoCoAppView::OfferKeyEventL iCurWindow->KeyEventL pre")); TBool result = iCurWindow->KeyEventL(aKeyEvent.iCode); //iMainEngine->WriteLog16(_L("CCoCoAppView::OfferKeyEventL iCurWindow->KeyEventL End")); keyResponse = result ? EKeyWasConsumed : EKeyWasNotConsumed; } if(keyResponse) { RequestDraw(); } //iMainEngine->WriteLog16(_L("CCoCoAppView::OfferKeyEventL End")); return keyResponse; } TInt CCoCoAppView::CountComponentControls() const { CEditorsManager& editorsManager = iMainEngine->EditorsManager(); return editorsManager.CountComponentControls(); } CCoeControl* CCoCoAppView::ComponentControl(TInt aIndex) const { CEditorsManager& editorsManager = iMainEngine->EditorsManager(); return editorsManager.ComponentControl(aIndex); } ////////////////////////////////////////////////////////////////////////// //From MTimerNotifier ////////////////////////////////////////////////////////////////////////// TBool CCoCoAppView::DoPeriodTask() { //iMainEngine->WriteLog16(_L("CCoCoAppView::DoPeriodTask")); ASSERT(NULL != iMainEngine); if(iSizeChanged) { SetExtentToWholeScreen(); iMainEngine->SetScreenRect(Rect()); iMainWindow->SizeChanged(); iIsDraw = ETrue; iSizeChanged = EFalse; // TBuf<10> buf; // buf.AppendNum(Rect().Width()); // buf.Append(_L(":")); // buf.AppendNum(Rect().Height()); // // //User::InfoPrint(buf); } if(iIsDraw) { ////UtilityTools::InfoPrint(iDrawCount++); DrawWindow(); iIsDraw = EFalse; } //iMainEngine->WriteLog16(_L("CCoCoAppView::DoPeriodTask End")); return ETrue; } ////////////////////////////////////////////////////////////////////////// //public ////////////////////////////////////////////////////////////////////////// void CCoCoAppView::RequestDraw() { iIsDraw = ETrue; } void CCoCoAppView::SetCurWindow(CWindow* aWindow) { ASSERT(aWindow); //必须有一个界面作为当前界面, if(iCurWindow) //除了第一次调用,iCurWindow总是应该有值的 { iCurWindow->Deactivate(); } iCurWindow = aWindow; iCurWindow->ActivateL(); //iCurWindow->SizeChanged(); RequestDraw(); } CWindow* CCoCoAppView::CurWindow() const { ASSERT(iCurWindow); return iCurWindow; } TInt CCoCoAppView::GetEditorInputMethod() { MAknEditingStateIndicator * ei = CAknEnv::Static()->EditingStateIndicator() ; if (!ei) return 0; CAknIndicatorContainer *ic = ei->IndicatorContainer(); if (!ic) return 0; if(ic->IndicatorState(S_uid(EAknNaviPaneEditorIndicatorNumberCase))) { //to do ... if input method = "123"; return 1; } else if(ic->IndicatorState(S_uid(EAknNaviPaneEditorIndicatorTextCase))) { //to do ... if input method = "Abc"; return 2; } else if(ic->IndicatorState(S_uid(EAknNaviPaneEditorIndicatorLowerCase))) { //to do ... if input method = "abc"; return 3; } else if(ic->IndicatorState(S_uid(EAknNaviPaneEditorIndicatorUpperCase))) { //to do ... if input method = "ABC"; return 4; } else if(ic->IndicatorState(S_uid(EAknNaviPaneEditorIndicatorT9) )) { //to do ... if input method = T9 (即拼音和笔画) return 5; } return 0; } //下面两个函数似乎无效 void CCoCoAppView::SetClippingRect(const TRect& aRect) { ActivateGc(); CWindowGc& gc = SystemGc(); gc.SetClippingRect(aRect); DeactivateGc(); } void CCoCoAppView::SetClippingRegion(const TRegion& aRegion) { ActivateGc(); CWindowGc& gc = SystemGc(); gc.SetClippingRegion(aRegion); DeactivateGc(); } void CCoCoAppView::CancelClipping() { ActivateGc(); CWindowGc& gc = SystemGc(); gc.CancelClippingRect(); gc.CancelClippingRegion(); DeactivateGc(); } ////////////////////////////////////////////////////////////////////////// //private ////////////////////////////////////////////////////////////////////////// void CCoCoAppView::ApplicationStartL() { UtilityTools::WriteLogsL(_L("CCoCoAppView::ApplicationStartL 0")); iMainEngine = CMainEngine::NewL(*this); UtilityTools::WriteLogsL(_L("CCoCoAppView::ApplicationStartL 1")); iMainWindow = CMainWindow::NewL(*iMainEngine,*this); UtilityTools::WriteLogsL(_L("CCoCoAppView::ApplicationStartL 2")); iTimer = CNotifyTimer::NewL(*this); iTimer->Start(KRedrawInterval); UtilityTools::WriteLogsL(_L("CCoCoAppView::ApplicationStartL 3")); iIsDraw = ETrue; } void CCoCoAppView::ApplicationEnd() { delete iMainWindow; iMainWindow = NULL; delete iMainEngine; iMainEngine = NULL; delete iTimer; iTimer = NULL; } void CCoCoAppView::DrawWindow() const { ASSERT(iCurWindow); CGraphic& graphic = iMainEngine->Graphic(); iCurWindow->Draw(graphic); DrawNow(); } // End of File
[ "sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f" ]
[ [ [ 1, 319 ] ] ]
ac6c785226fb7cbb314ee651d88182d1127d9232
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/GUI/GUIExtrasMenu.h
dba984ab45d6ab02f32c94701554e619049c3507
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
597
h
#ifndef GUIEXTRASMENUH_H #define GUIEXTRASMENUH_H #include "GUIDefs.h" #include "GUIWindow.h" #include "../OUAN.h" namespace OUAN{ const std::string STRING_KEY_LABEL="EXTRAS_SCREEN_LABEL"; const std::string STRING_KEY_BACK="EXTRAS_SCREEN_BACK"; const std::string CEGUIWIN_ID_LABEL="OUANExtras/CreditLabel"; const std::string CEGUIWIN_ID_BACK="OUANExtras/Back"; class GUIExtrasMenu: public GUIWindow { public: void bindEvents(); bool onBackToMenu(const CEGUI::EventArgs& args); void initGUI(GameStatePtr parentGameState); void setStrings(); }; } #endif
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 23 ] ] ]
6b00d831d38c3986442f8ad9bf3d085c7d1b7fb4
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/wce/win_net.cpp
6938a8148e824b0faccace14387c6c96168f1714
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
23,782
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // net_wins.c #include "../game/q_shared.h" #include "../qcommon/qcommon.h" #include "win_local.h" #include<winsock.h> static WSADATA winsockdata; static qboolean winsockInitialized = qfalse; static qboolean usingSocks = qfalse; static qboolean networkingEnabled = qfalse; static cvar_t *net_noudp; static cvar_t *net_noipx; static cvar_t *net_socksEnabled; static cvar_t *net_socksServer; static cvar_t *net_socksPort; static cvar_t *net_socksUsername; static cvar_t *net_socksPassword; static struct sockaddr socksRelayAddr; static SOCKET ip_socket; static SOCKET socks_socket; static SOCKET ipx_socket; #define MAX_IPS 16 static int numIP; static byte localIP[MAX_IPS][4]; //============================================================================= /* ==================== NET_ErrorString ==================== */ char *NET_ErrorString( void ) { int code; code = WSAGetLastError(); switch( code ) { case WSAEINTR: return "WSAEINTR"; case WSAEBADF: return "WSAEBADF"; case WSAEACCES: return "WSAEACCES"; case WSAEDISCON: return "WSAEDISCON"; case WSAEFAULT: return "WSAEFAULT"; case WSAEINVAL: return "WSAEINVAL"; case WSAEMFILE: return "WSAEMFILE"; case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK"; case WSAEINPROGRESS: return "WSAEINPROGRESS"; case WSAEALREADY: return "WSAEALREADY"; case WSAENOTSOCK: return "WSAENOTSOCK"; case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ"; case WSAEMSGSIZE: return "WSAEMSGSIZE"; case WSAEPROTOTYPE: return "WSAEPROTOTYPE"; case WSAENOPROTOOPT: return "WSAENOPROTOOPT"; case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT"; case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT"; case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP"; case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT"; case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT"; case WSAEADDRINUSE: return "WSAEADDRINUSE"; case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL"; case WSAENETDOWN: return "WSAENETDOWN"; case WSAENETUNREACH: return "WSAENETUNREACH"; case WSAENETRESET: return "WSAENETRESET"; case WSAECONNABORTED: return "WSWSAECONNABORTEDAEINTR"; case WSAECONNRESET: return "WSAECONNRESET"; case WSAENOBUFS: return "WSAENOBUFS"; case WSAEISCONN: return "WSAEISCONN"; case WSAENOTCONN: return "WSAENOTCONN"; case WSAESHUTDOWN: return "WSAESHUTDOWN"; case WSAETOOMANYREFS: return "WSAETOOMANYREFS"; case WSAETIMEDOUT: return "WSAETIMEDOUT"; case WSAECONNREFUSED: return "WSAECONNREFUSED"; case WSAELOOP: return "WSAELOOP"; case WSAENAMETOOLONG: return "WSAENAMETOOLONG"; case WSAEHOSTDOWN: return "WSAEHOSTDOWN"; case WSASYSNOTREADY: return "WSASYSNOTREADY"; case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED"; case WSANOTINITIALISED: return "WSANOTINITIALISED"; case WSAHOST_NOT_FOUND: return "WSAHOST_NOT_FOUND"; case WSATRY_AGAIN: return "WSATRY_AGAIN"; case WSANO_RECOVERY: return "WSANO_RECOVERY"; case WSANO_DATA: return "WSANO_DATA"; default: return "NO ERROR"; } } void NetadrToSockadr( netadr_t *a, struct sockaddr *s ) { memset( s, 0, sizeof(*s) ); if( a->type == NA_BROADCAST ) { ((struct sockaddr_in *)s)->sin_family = AF_INET; ((struct sockaddr_in *)s)->sin_port = a->port; ((struct sockaddr_in *)s)->sin_addr.s_addr = INADDR_BROADCAST; } else if( a->type == NA_IP ) { ((struct sockaddr_in *)s)->sin_family = AF_INET; ((struct sockaddr_in *)s)->sin_addr.s_addr = *(int *)&a->ip; ((struct sockaddr_in *)s)->sin_port = a->port; } } void SockadrToNetadr( struct sockaddr *s, netadr_t *a ) { if (s->sa_family == AF_INET) { a->type = NA_IP; *(int *)&a->ip = ((struct sockaddr_in *)s)->sin_addr.s_addr; a->port = ((struct sockaddr_in *)s)->sin_port; } } /* ============= Sys_StringToAdr idnewt GFIXED(192,246).GFIXED(40,70) GFIXED(12121212,121212121212) ============= */ #define DO(src,dest) \ copy[0] = s[src]; \ copy[1] = s[src + 1]; \ sscanf (copy, "%x", &val); \ ((struct sockaddr_ipx *)sadr)->dest = val qboolean Sys_StringToSockaddr( const char *s, struct sockaddr *sadr ) { struct hostent *h; memset( sadr, 0, sizeof( *sadr ) ); ((struct sockaddr_in *)sadr)->sin_family = AF_INET; ((struct sockaddr_in *)sadr)->sin_port = 0; if( s[0] >= '0' && s[0] <= '9' ) { *(int *)&((struct sockaddr_in *)sadr)->sin_addr = inet_addr(s); } else { if( ( h = gethostbyname( s ) ) == 0 ) { return 0; } *(int *)&((struct sockaddr_in *)sadr)->sin_addr = *(int *)h->h_addr_list[0]; } return qtrue; } #undef DO /* ============= Sys_StringToAdr idnewt GFIXED(192,246).GFIXED(40,70) ============= */ qboolean Sys_StringToAdr( const char *s, netadr_t *a ) { struct sockaddr sadr; if ( !Sys_StringToSockaddr( s, &sadr ) ) { return qfalse; } SockadrToNetadr( &sadr, a ); return qtrue; } //============================================================================= /* ================== Sys_GetPacket Never called by the game logic, just the system event queing ================== */ int recvfromCount; qboolean Sys_GetPacket( netadr_t *net_from, msg_t *net_message ) { int ret; struct sockaddr from; int fromlen; int net_socket; int protocol; int err; for( protocol = 0 ; protocol < 2 ; protocol++ ) { if( protocol == 0 ) { net_socket = ip_socket; } else { net_socket = ipx_socket; } if( !net_socket ) { continue; } fromlen = sizeof(from); recvfromCount++; // performance check ret = recvfrom( net_socket, (char *)(net_message->data), net_message->maxsize, 0, (struct sockaddr *)&from, &fromlen ); if (ret == SOCKET_ERROR) { err = WSAGetLastError(); if( err == WSAEWOULDBLOCK || err == WSAECONNRESET ) { continue; } Com_Printf( "NET_GetPacket: %s\n", NET_ErrorString() ); continue; } if ( net_socket == ip_socket ) { memset( ((struct sockaddr_in *)&from)->sin_zero, 0, 8 ); } if ( usingSocks && net_socket == ip_socket && memcmp( &from, &socksRelayAddr, fromlen ) == 0 ) { if ( ret < 10 || net_message->data[0] != 0 || net_message->data[1] != 0 || net_message->data[2] != 0 || net_message->data[3] != 1 ) { continue; } net_from->type = NA_IP; net_from->ip[0] = net_message->data[4]; net_from->ip[1] = net_message->data[5]; net_from->ip[2] = net_message->data[6]; net_from->ip[3] = net_message->data[7]; net_from->port = *(short *)&net_message->data[8]; net_message->readcount = 10; } else { SockadrToNetadr( &from, net_from ); net_message->readcount = 0; } if( ret == net_message->maxsize ) { Com_Printf( "Oversize packet from %s\n", NET_AdrToString (*net_from) ); continue; } net_message->cursize = ret; return qtrue; } return qfalse; } //============================================================================= static char socksBuf[4096]; /* ================== Sys_SendPacket ================== */ void Sys_SendPacket( int length, const void *data, netadr_t to ) { int ret; struct sockaddr addr; SOCKET net_socket; if( to.type == NA_BROADCAST ) { net_socket = ip_socket; } else if( to.type == NA_IP ) { net_socket = ip_socket; } else if( to.type == NA_IPX ) { net_socket = ipx_socket; } else if( to.type == NA_BROADCAST_IPX ) { net_socket = ipx_socket; } else { Com_Error( ERR_FATAL, "Sys_SendPacket: bad address type" ); return; } if( !net_socket ) { return; } NetadrToSockadr( &to, &addr ); if( usingSocks && to.type == NA_IP ) { socksBuf[0] = 0; // reserved socksBuf[1] = 0; socksBuf[2] = 0; // fragment (not fragmented) socksBuf[3] = 1; // address type: IPV4 *(int *)&socksBuf[4] = ((struct sockaddr_in *)&addr)->sin_addr.s_addr; *(short *)&socksBuf[8] = ((struct sockaddr_in *)&addr)->sin_port; memcpy( &socksBuf[10], data, length ); ret = sendto( net_socket, socksBuf, length+10, 0, &socksRelayAddr, sizeof(socksRelayAddr) ); } else { ret = sendto( net_socket, (const char *)data, length, 0, &addr, sizeof(addr) ); } if( ret == SOCKET_ERROR ) { int err = WSAGetLastError(); // wouldblock is silent if( err == WSAEWOULDBLOCK ) { return; } // some PPP links do not allow broadcasts and return an error if( ( err == WSAEADDRNOTAVAIL ) && ( ( to.type == NA_BROADCAST ) || ( to.type == NA_BROADCAST_IPX ) ) ) { return; } Com_Printf( "NET_SendPacket: %s\n", NET_ErrorString() ); } } //============================================================================= /* ================== Sys_IsLANAddress LAN clients will have their rate var ignored ================== */ qboolean Sys_IsLANAddress( netadr_t adr ) { int i; if( adr.type == NA_LOOPBACK ) { return qtrue; } if( adr.type == NA_IPX ) { return qtrue; } if( adr.type != NA_IP ) { return qfalse; } // choose which comparison to use based on the class of the address being tested // any local adresses of a different class than the address being tested will fail based on the first byte if( adr.ip[0] == 127 && adr.ip[1] == 0 && adr.ip[2] == 0 && adr.ip[3] == 1 ) { return qtrue; } // Class A if( (adr.ip[0] & 0x80) == 0x00 ) { for ( i = 0 ; i < numIP ; i++ ) { if( adr.ip[0] == localIP[i][0] ) { return qtrue; } } // the RFC1918 class a block will pass the above test return qfalse; } // Class B if( (adr.ip[0] & 0xc0) == 0x80 ) { for ( i = 0 ; i < numIP ; i++ ) { if( adr.ip[0] == localIP[i][0] && adr.ip[1] == localIP[i][1] ) { return qtrue; } // also check against the RFC1918 class b blocks if( adr.ip[0] == 172 && localIP[i][0] == 172 && (adr.ip[1] & 0xf0) == 16 && (localIP[i][1] & 0xf0) == 16 ) { return qtrue; } } return qfalse; } // Class C for ( i = 0 ; i < numIP ; i++ ) { if( adr.ip[0] == localIP[i][0] && adr.ip[1] == localIP[i][1] && adr.ip[2] == localIP[i][2] ) { return qtrue; } // also check against the RFC1918 class c blocks if( adr.ip[0] == 192 && localIP[i][0] == 192 && adr.ip[1] == 168 && localIP[i][1] == 168 ) { return qtrue; } } return qfalse; } /* ================== Sys_ShowIP ================== */ void Sys_ShowIP(void) { int i; for (i = 0; i < numIP; i++) { Com_Printf( "IP: %i.%i.%i.%i\n", localIP[i][0], localIP[i][1], localIP[i][2], localIP[i][3] ); } } //============================================================================= /* ==================== NET_IPSocket ==================== */ int NET_IPSocket( char *net_interface, int port ) { SOCKET newsocket; struct sockaddr_in address; int i = 1; int err; u_long nb = qtrue; if( net_interface ) { Com_Printf( "Opening IP socket: %s:%i\n", net_interface, port ); } else { Com_Printf( "Opening IP socket: localhost:%i\n", port ); } if( ( newsocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == INVALID_SOCKET ) { err = WSAGetLastError(); if( err != WSAEAFNOSUPPORT ) { Com_Printf( "WARNING: UDP_OpenSocket: socket: %s\n", NET_ErrorString() ); } return 0; } // make it non-blocking if( ioctlsocket( newsocket, FIONBIO, &nb ) == SOCKET_ERROR ) { Com_Printf( "WARNING: UDP_OpenSocket: ioctl FIONBIO: %s\n", NET_ErrorString() ); return 0; } // make it broadcast capable if( setsockopt( newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i) ) == SOCKET_ERROR ) { Com_Printf( "WARNING: UDP_OpenSocket: setsockopt SO_BROADCAST: %s\n", NET_ErrorString() ); return 0; } if( !net_interface || !net_interface[0] || !Q_stricmp(net_interface, "localhost") ) { address.sin_addr.s_addr = INADDR_ANY; } else { Sys_StringToSockaddr( net_interface, (struct sockaddr *)&address ); } if( port == PORT_ANY ) { address.sin_port = 0; } else { address.sin_port = htons( (short)port ); } address.sin_family = AF_INET; if( bind( newsocket, (const sockaddr *)&address, sizeof(address) ) == SOCKET_ERROR ) { Com_Printf( "WARNING: UDP_OpenSocket: bind: %s\n", NET_ErrorString() ); closesocket( newsocket ); return 0; } return newsocket; } /* ==================== NET_OpenSocks ==================== */ void NET_OpenSocks( int port ) { struct sockaddr_in address; int err; struct hostent *h; int len; qboolean rfc1929; unsigned char buf[64]; usingSocks = qfalse; Com_Printf( "Opening connection to SOCKS server.\n" ); if ( ( socks_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) == INVALID_SOCKET ) { err = WSAGetLastError(); Com_Printf( "WARNING: NET_OpenSocks: socket: %s\n", NET_ErrorString() ); return; } h = gethostbyname( net_socksServer->string ); if ( h == NULL ) { err = WSAGetLastError(); Com_Printf( "WARNING: NET_OpenSocks: gethostbyname: %s\n", NET_ErrorString() ); return; } if ( h->h_addrtype != AF_INET ) { Com_Printf( "WARNING: NET_OpenSocks: gethostbyname: address type was not AF_INET\n" ); return; } address.sin_family = AF_INET; address.sin_addr.s_addr = *(int *)h->h_addr_list[0]; address.sin_port = htons( (short)net_socksPort->integer ); if ( connect( socks_socket, (struct sockaddr *)&address, sizeof( address ) ) == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: connect: %s\n", NET_ErrorString() ); return; } // send socks authentication handshake if ( *net_socksUsername->string || *net_socksPassword->string ) { rfc1929 = qtrue; } else { rfc1929 = qfalse; } buf[0] = 5; // SOCKS version // method count if ( rfc1929 ) { buf[1] = 2; len = 4; } else { buf[1] = 1; len = 3; } buf[2] = 0; // method #1 - method id #00: no authentication if ( rfc1929 ) { buf[2] = 2; // method #2 - method id #02: username/password } if ( send( socks_socket, (const char *)buf, len, 0 ) == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() ); return; } // get the response len = recv( socks_socket, (char *) buf, 64, 0 ); if ( len == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() ); return; } if ( len != 2 || buf[0] != 5 ) { Com_Printf( "NET_OpenSocks: bad response\n" ); return; } switch( buf[1] ) { case 0: // no authentication break; case 2: // username/password authentication break; default: Com_Printf( "NET_OpenSocks: request denied\n" ); return; } // do username/password authentication if needed if ( buf[1] == 2 ) { int ulen; int plen; // build the request ulen = strlen( net_socksUsername->string ); plen = strlen( net_socksPassword->string ); buf[0] = 1; // username/password authentication version buf[1] = ulen; if ( ulen ) { memcpy( &buf[2], net_socksUsername->string, ulen ); } buf[2 + ulen] = plen; if ( plen ) { memcpy( &buf[3 + ulen], net_socksPassword->string, plen ); } // send it if ( send( socks_socket, (const char *)buf, 3 + ulen + plen, 0 ) == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() ); return; } // get the response len = recv( socks_socket, (char *)buf, 64, 0 ); if ( len == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() ); return; } if ( len != 2 || buf[0] != 1 ) { Com_Printf( "NET_OpenSocks: bad response\n" ); return; } if ( buf[1] != 0 ) { Com_Printf( "NET_OpenSocks: authentication failed\n" ); return; } } // send the UDP associate request buf[0] = 5; // SOCKS version buf[1] = 3; // command: UDP associate buf[2] = 0; // reserved buf[3] = 1; // address type: IPV4 *(int *)&buf[4] = INADDR_ANY; *(short *)&buf[8] = htons( (short)port ); // port if ( send( socks_socket, (const char *)buf, 10, 0 ) == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() ); return; } // get the response len = recv( socks_socket, (char *)buf, 64, 0 ); if( len == SOCKET_ERROR ) { err = WSAGetLastError(); Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() ); return; } if( len < 2 || buf[0] != 5 ) { Com_Printf( "NET_OpenSocks: bad response\n" ); return; } // check completion code if( buf[1] != 0 ) { Com_Printf( "NET_OpenSocks: request denied: %i\n", buf[1] ); return; } if( buf[3] != 1 ) { Com_Printf( "NET_OpenSocks: relay address is not IPV4: %i\n", buf[3] ); return; } ((struct sockaddr_in *)&socksRelayAddr)->sin_family = AF_INET; ((struct sockaddr_in *)&socksRelayAddr)->sin_addr.s_addr = *(int *)&buf[4]; ((struct sockaddr_in *)&socksRelayAddr)->sin_port = *(short *)&buf[8]; memset( ((struct sockaddr_in *)&socksRelayAddr)->sin_zero, 0, 8 ); usingSocks = qtrue; } /* ===================== NET_GetLocalAddress ===================== */ void NET_GetLocalAddress( void ) { char hostname[256]; struct hostent *hostInfo; int error; char *p; int ip; int n; if( gethostname( hostname, 256 ) == SOCKET_ERROR ) { error = WSAGetLastError(); return; } hostInfo = gethostbyname( hostname ); if( !hostInfo ) { error = WSAGetLastError(); return; } Com_Printf( "Hostname: %s\n", hostInfo->h_name ); n = 0; while( ( p = hostInfo->h_aliases[n++] ) != NULL ) { Com_Printf( "Alias: %s\n", p ); } if ( hostInfo->h_addrtype != AF_INET ) { return; } numIP = 0; while( ( p = hostInfo->h_addr_list[numIP] ) != NULL && numIP < MAX_IPS ) { ip = ntohl( *(int *)p ); localIP[ numIP ][0] = p[0]; localIP[ numIP ][1] = p[1]; localIP[ numIP ][2] = p[2]; localIP[ numIP ][3] = p[3]; Com_Printf( "IP: %i.%i.%i.%i\n", ( ip >> 24 ) & 0xff, ( ip >> 16 ) & 0xff, ( ip >> 8 ) & 0xff, ip & 0xff ); numIP++; } } /* ==================== NET_OpenIP ==================== */ void NET_OpenIP( void ) { cvar_t *ip; int port; int i; ip = Cvar_Get( "net_ip", "localhost", CVAR_LATCH ); port = Cvar_Get( "net_port", va( "%i", PORT_SERVER ), CVAR_LATCH )->integer; // automatically scan for a valid port, so multiple // dedicated servers can be started without requiring // a different net_port for each one for( i = 0 ; i < 10 ; i++ ) { ip_socket = NET_IPSocket( ip->string, port + i ); if ( ip_socket ) { Cvar_SetValue( "net_port", MAKE_LFIXED(port + i) ); if ( net_socksEnabled->integer ) { NET_OpenSocks( port + i ); } NET_GetLocalAddress(); return; } } Com_Printf( "WARNING: Couldn't allocate IP port\n"); } /* ==================== NET_IPXSocket ==================== */ int NET_IPXSocket( int port ) { return 0; } /* ==================== NET_OpenIPX ==================== */ void NET_OpenIPX( void ) { } //=================================================================== /* ==================== NET_GetCvars ==================== */ static qboolean NET_GetCvars( void ) { qboolean modified; modified = qfalse; if( net_noudp && net_noudp->modified ) { modified = qtrue; } net_noudp = Cvar_Get( "net_noudp", "0", CVAR_LATCH | CVAR_ARCHIVE ); if( net_noipx && net_noipx->modified ) { modified = qtrue; } net_noipx = Cvar_Get( "net_noipx", "0", CVAR_LATCH | CVAR_ARCHIVE ); if( net_socksEnabled && net_socksEnabled->modified ) { modified = qtrue; } net_socksEnabled = Cvar_Get( "net_socksEnabled", "0", CVAR_LATCH | CVAR_ARCHIVE ); if( net_socksServer && net_socksServer->modified ) { modified = qtrue; } net_socksServer = Cvar_Get( "net_socksServer", "", CVAR_LATCH | CVAR_ARCHIVE ); if( net_socksPort && net_socksPort->modified ) { modified = qtrue; } net_socksPort = Cvar_Get( "net_socksPort", "1080", CVAR_LATCH | CVAR_ARCHIVE ); if( net_socksUsername && net_socksUsername->modified ) { modified = qtrue; } net_socksUsername = Cvar_Get( "net_socksUsername", "", CVAR_LATCH | CVAR_ARCHIVE ); if( net_socksPassword && net_socksPassword->modified ) { modified = qtrue; } net_socksPassword = Cvar_Get( "net_socksPassword", "", CVAR_LATCH | CVAR_ARCHIVE ); return modified; } /* ==================== NET_Config ==================== */ void NET_Config( qboolean enableNetworking ) { qboolean modified; qboolean stop; qboolean start; // get any latched changes to cvars modified = NET_GetCvars(); if( net_noudp->integer && net_noipx->integer ) { enableNetworking = qfalse; } // if enable state is the same and no cvars were modified, we have nothing to do if( enableNetworking == networkingEnabled && !modified ) { return; } if( enableNetworking == networkingEnabled ) { if( enableNetworking ) { stop = qtrue; start = qtrue; } else { stop = qfalse; start = qfalse; } } else { if( enableNetworking ) { stop = qfalse; start = qtrue; } else { stop = qtrue; start = qfalse; } networkingEnabled = enableNetworking; } if( stop ) { if ( ip_socket && ip_socket != INVALID_SOCKET ) { closesocket( ip_socket ); ip_socket = 0; } if ( socks_socket && socks_socket != INVALID_SOCKET ) { closesocket( socks_socket ); socks_socket = 0; } if ( ipx_socket && ipx_socket != INVALID_SOCKET ) { closesocket( ipx_socket ); ipx_socket = 0; } } if( start ) { if (! net_noudp->integer ) { NET_OpenIP(); } if (! net_noipx->integer ) { NET_OpenIPX(); } } } /* ==================== NET_Init ==================== */ void NET_Init( void ) { int r; r = WSAStartup( MAKEWORD( 1, 1 ), &winsockdata ); if( r ) { Com_Printf( "WARNING: Winsock initialization failed, returned %d\n", r ); return; } winsockInitialized = qtrue; Com_Printf( "Winsock Initialized\n" ); // this is really just to get the cvars registered NET_GetCvars(); //FIXME testing! NET_Config( qtrue ); } /* ==================== NET_Shutdown ==================== */ void NET_Shutdown( void ) { if ( !winsockInitialized ) { return; } NET_Config( qfalse ); WSACleanup(); winsockInitialized = qfalse; } /* ==================== NET_Sleep sleeps msec or until net socket is ready ==================== */ void NET_Sleep( int msec ) { } /* ==================== NET_Restart_f ==================== */ void NET_Restart( void ) { NET_Config( networkingEnabled ); }
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 949 ] ] ]
8e79ca36f6c255564c5959d54c9a7fb8f8a666c4
915d454b5f3099ea8d12f291fd79dab0688f9b6c
/TheCodeForTheProject/MazeWindow/MazeWindow/MazeForm.h
d7d140032db9bad5a539639a9d8e4115621c7369
[]
no_license
johnballantyne/mazegeneration483w
e60593bbbeac2fe4589bace2076c1d8620b8b5d5
dddbbb8b9e919ba2c7b3977e230c7afd545073cd
refs/heads/master
2021-01-23T14:03:59.843199
2009-12-14T01:56:57
2009-12-14T01:56:57
39,958,368
0
0
null
null
null
null
UTF-8
C++
false
false
9,533
h
#pragma once #include<stdlib.h> #include<string.h> #include <msclr/marshal.h> using namespace System; using namespace msclr::interop; namespace MazeWindow { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for MazeForm /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class MazeForm : public System::Windows::Forms::Form { public: MazeForm(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~MazeForm() { if (components) { delete components; } } private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::TextBox^ LengthBox; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Button^ ExitButton; private: System::Windows::Forms::Button^ GenerateButton; private: System::Windows::Forms::ComboBox^ GenerateBox; private: System::Windows::Forms::ComboBox^ SolveBox; protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->label1 = (gcnew System::Windows::Forms::Label()); this->LengthBox = (gcnew System::Windows::Forms::TextBox()); this->label3 = (gcnew System::Windows::Forms::Label()); this->label4 = (gcnew System::Windows::Forms::Label()); this->ExitButton = (gcnew System::Windows::Forms::Button()); this->GenerateButton = (gcnew System::Windows::Forms::Button()); this->GenerateBox = (gcnew System::Windows::Forms::ComboBox()); this->SolveBox = (gcnew System::Windows::Forms::ComboBox()); this->SuspendLayout(); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(13, 13); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(93, 13); this->label1->TabIndex = 0; this->label1->Text = L"Maze Dimensions:"; this->label1->TextAlign = System::Drawing::ContentAlignment::TopCenter; this->label1->Click += gcnew System::EventHandler(this, &MazeForm::label1_Click); // // LengthBox // this->LengthBox->Location = System::Drawing::Point(107, 10); this->LengthBox->MaxLength = 3; this->LengthBox->Name = L"LengthBox"; this->LengthBox->Size = System::Drawing::Size(30, 20); this->LengthBox->TabIndex = 1; this->LengthBox->WordWrap = false; // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(13, 43); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(101, 13); this->label3->TabIndex = 4; this->label3->Text = L"Generating Method:"; // // label4 // this->label4->AutoSize = true; this->label4->Location = System::Drawing::Point(13, 70); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(84, 13); this->label4->TabIndex = 6; this->label4->Text = L"Solving Method:"; // // ExitButton // this->ExitButton->Location = System::Drawing::Point(188, 155); this->ExitButton->Name = L"ExitButton"; this->ExitButton->Size = System::Drawing::Size(75, 23); this->ExitButton->TabIndex = 12; this->ExitButton->Text = L"Exit"; this->ExitButton->UseVisualStyleBackColor = true; this->ExitButton->Click += gcnew System::EventHandler(this, &MazeForm::ExitButton_Click); // // GenerateButton // this->GenerateButton->Location = System::Drawing::Point(107, 155); this->GenerateButton->Name = L"GenerateButton"; this->GenerateButton->Size = System::Drawing::Size(75, 23); this->GenerateButton->TabIndex = 11; this->GenerateButton->Text = L"Generate!"; this->GenerateButton->UseVisualStyleBackColor = true; this->GenerateButton->Click += gcnew System::EventHandler(this, &MazeForm::GenerateButton_Click); // // GenerateBox // this->GenerateBox->FormattingEnabled = true; this->GenerateBox->Items->AddRange(gcnew cli::array< System::Object^ >(2) {L"Recursive Division (biased)", L"Recursive Division (unbiased)"}); this->GenerateBox->Location = System::Drawing::Point(115, 40); this->GenerateBox->Name = L"GenerateBox"; this->GenerateBox->Size = System::Drawing::Size(148, 21); this->GenerateBox->TabIndex = 5; this->GenerateBox->SelectedIndexChanged += gcnew System::EventHandler(this, &MazeForm::GenerateBox_SelectedIndexChanged); // // SolveBox // this->SolveBox->FormattingEnabled = true; this->SolveBox->Items->AddRange(gcnew cli::array< System::Object^ >(2) {L"Right-Hand Rule", L"Left-Hand Rule"}); this->SolveBox->Location = System::Drawing::Point(115, 67); this->SolveBox->Name = L"SolveBox"; this->SolveBox->Size = System::Drawing::Size(148, 21); this->SolveBox->TabIndex = 7; this->SolveBox->SelectedIndexChanged += gcnew System::EventHandler(this, &MazeForm::SolveBox_SelectedIndexChanged); // // MazeForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(285, 190); this->Controls->Add(this->SolveBox); this->Controls->Add(this->GenerateButton); this->Controls->Add(this->ExitButton); this->Controls->Add(this->label4); this->Controls->Add(this->label3); this->Controls->Add(this->GenerateBox); this->Controls->Add(this->LengthBox); this->Controls->Add(this->label1); this->Name = L"MazeForm"; this->Text = L"MazeNavigator"; this->Load += gcnew System::EventHandler(this, &MazeForm::MazeForm_Load_1); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { } /*private: System::Void InitializeComponent() { this->SuspendLayout(); // // MazeForm // this->ClientSize = System::Drawing::Size(292, 266); this->Name = L"MazeForm"; this->Load += gcnew System::EventHandler(this, &MazeForm::MazeForm_Load); this->ResumeLayout(false); }*/ private: System::Void MazeForm_Load(System::Object^ sender, System::EventArgs^ e) { } private: System::Void MazeForm_Load_1(System::Object^ sender, System::EventArgs^ e) { } private: System::Void GenerateBox_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void GenerateButton_Click(System::Object^ sender, System::EventArgs^ e) { marshal_context^ context = gcnew marshal_context(); const char* len; len = context->marshal_as<const char*>( LengthBox->Text ); const char* gen; gen = context->marshal_as<const char*>( GenerateBox->Text ); const char* solve; solve = context->marshal_as<const char*>( SolveBox->Text ); //const char* color; //color = context->marshal_as<const char*>( ColorBox->Text ); int sendGen, sendSolve; int length = atoi( len ); if( length < 2 || length > 100 ) { MessageBox::Show( "Please enter a dimension between 2 and 100.", "Entry Error", MessageBoxButtons::OK, MessageBoxIcon::Exclamation ); return; } if( length % 2 == 1 ) length--; if( strcmp( gen, "Recursive Division (biased)" ) == 0 ) sendGen = 1; else if( strcmp( gen, "Recursive Division (unbiased)" ) == 0 ) sendGen = 2; else { MessageBox::Show( "Please select a generation algorithm.", "Entry Error", MessageBoxButtons::OK, MessageBoxIcon::Exclamation ); return; } if( strcmp( solve, "Right-Hand Rule" ) == 0 ) sendSolve = 1; else if( strcmp( solve, "Left-Hand Rule" ) == 0 ) sendSolve = 2; else { MessageBox::Show( "Please select a solving algorithm.", "Entry Error", MessageBoxButtons::OK, MessageBoxIcon::Exclamation ); return; } //open the program String^ thing = "MazeNavigator.exe " + length + " " + sendGen + " " + sendSolve; const char* sysCall; sysCall = context->marshal_as<const char*>( thing ); //MessageBox::Show( thing, "Success!", MessageBoxButtons::OK, MessageBoxIcon::Exclamation ); system( sysCall ); } private: System::Void ExitButton_Click(System::Object^ sender, System::EventArgs^ e) { exit(0); } private: System::Void SolveBox_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { } }; }
[ "vash7ehstampede@f1cf40a4-bd93-11de-8784-f7ad4773dbab" ]
[ [ [ 1, 270 ] ] ]
4c009066c384a4cc37cb11be33162dc7e72cb600
58ef4939342d5253f6fcb372c56513055d589eb8
/WallpaperChanger/WallpaperChange/source/SMS/src/smsdatagramsender.cpp
c2a0196f47e03d634ad86d4ad818db9c4cf469cd
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,065
cpp
/* * ============================================================================== * Name : smsdatagramsender.cpp * Part of : * Interface : * Description : * Version : * * Copyright (c) 2007 Symbian Ltd. All rights reserved. * ============================================================================== */ // INCLUDE FILES #include "smsdatagramsender.h" #include "OKCDebug.h" #include "SMSDef.h" const TUid KSMSDatagramServiceImplementationUID = { 0x101FA9C3 }; _LIT(KPanicSMSSender,"SMSSender"); CSmsDatagramSender* CSmsDatagramSender::NewL( MSmsDatagramSenderObserver& aMsgOvserver) { CSmsDatagramSender* self = new (ELeave) CSmsDatagramSender(aMsgOvserver); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(); return self; } void CSmsDatagramSender::ConstructL() { CActiveScheduler::Add(this); // add to active scheduler } CSmsDatagramSender::CSmsDatagramSender(MSmsDatagramSenderObserver& aMsgOvserver) : CActive(EPriorityStandard), iMsgObserver(aMsgOvserver) { } CSmsDatagramSender::~CSmsDatagramSender() { Cancel(); delete iDatagram; delete iSendService; } void CSmsDatagramSender::SendAsyncL(const TDesC& aMessage, const TDesC& aPhoneNumber) { __ASSERT_ALWAYS(!IsActive(),User::Panic(KPanicSMSSender,KErrInUse)); delete iDatagram; iDatagram = NULL; iDatagram = CDatagram::NewL(aMessage, aPhoneNumber); // and now send it asynchronously delete iSendService; iSendService = NULL; iSendService = CSMSDatagramService::NewL(); iSendService->SendL(iDatagram, iStatus); SetActive(); } void CSmsDatagramSender::DoCancel() { delete iSendService; iSendService = NULL; } void CSmsDatagramSender::RunL() { TInt status = iStatus.Int(); if (status == KErrNone) { User::LeaveIfError(iStatus.Int()); TBuf<KMaxSMSSize> sendBuf; sendBuf.Copy(iDatagram->GetData()); iMsgObserver.MsgSentL(sendBuf); } else iMsgObserver.MsgSentErr(status); } // End of File
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 90 ] ] ]
8f155917bc9c0da3864131dafdc37efc7521f234
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleGui/PC/PCWinWindow.h
b9b494b89ab51298c110110d157638cb77fa729f
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
h
/*------------------------------------------------ Base class for creating/controlling win32 windows -------------------------------------------------*/ #pragma once #include "PCWinControl.h" namespace Win32 { class GWindow; }; class Win32::GWindow : public Win32::GWinControl { public: GWindow(TRefRef InstanceRef) : GWinControl (InstanceRef) {} ~GWindow() {} virtual u32 DefaultFlags() { return GWinControlFlags::ClientEdge|GWinControlFlags::OverlappedWindow; }; virtual const TChar* ClassName() { return TLCharString("Window"); }; virtual Bool Init(TPtr<GWinControl>& pOwner, u32 Flags); // window is overloaded to create class };
[ [ [ 1, 29 ] ] ]
c2f5f487bd36415e14c7bd2534cb0a2c6b512705
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/drivers/qt/TeInitRasterQtDecoder.cpp
48a7f3e9ca5be0e16c4fbcce2b1ef0f363f63627
[]
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
UTF-8
C++
false
false
185
cpp
#include <TeDecoderQtImage.h> #include <map> void TeInitRasterQtDecoder(); void TeInitRasterQtDecoder() { static TeDecoderQtImageFactory theDecoderQtImageFactory("QT"); }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 11 ] ] ]
836e2455d1527c024a3bd1c20083b5a34207b3e4
8103a6a032f7b3ec42bbf7a4ad1423e220e769e0
/Prominence/AnimatedSprite.cpp
0b75ee818f2855f60fab1639cc0c7a6cfcb4eacf
[]
no_license
wgoddard/2d-opengl-engine
0400bb36c2852ce4f5619f8b5526ba612fda780c
765b422277a309b3d4356df2e58ee8db30d91914
refs/heads/master
2016-08-08T14:28:07.909649
2010-06-17T19:13:12
2010-06-17T19:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,345
cpp
#include "AnimatedSprite.h" namespace Prominence { AnimatedSprite::AnimatedSprite(ResourceManager & rm, Renderer & renderer, Logger & logger, std::string xml_file) : Sprite(rm, renderer), m_Logger(logger) { TiXmlDocument doc(xml_file.c_str()); if (!doc.LoadFile()) { m_Logger.Outputf(P_WARNING, OTHER, "Failed to load XML %s.\n", xml_file.c_str()); } TiXmlElement * root = doc.FirstChildElement("sprites"); TiXmlElement * sprite = root->FirstChildElement("sprite"); m_Name = sprite->Attribute("Name"); TiXmlElement * elem = sprite->FirstChildElement("texture"); TiXmlElement * rect = sprite->FirstChildElement("rect"); if (rect == NULL) { m_Logger.Outputf(P_WARNING, OTHER, "%s (%s) has no bounding rect.\n", sprite->Attribute("Name"), xml_file); throw("No bounding"); } float rW, rH = 5.0f; m_PolyDef = new b2PolygonDef(); rW = atof(rect->Attribute("Width")) / 2.0f / PIXELS_PER_UNIT; rH = atof(rect->Attribute("Height")) / 2.0f / PIXELS_PER_UNIT; m_PolyDef->SetAsBox(rW, rH); m_PolyDef->density = 1.0f; if (elem == 0) { //std::cout << "No textures?? error.\n"; m_Logger.Outputf(P_ERROR, OTHER, "%s has no textures.\n", sprite->Attribute("Name")); exit(0); } struct texture { Texture * loaded_tex; Uint32 width; Uint32 height; }; std::vector <texture *> textures; do { texture * tex = new texture; tex->loaded_tex = m_ResourceManager.GetTexture(elem->Attribute("File")); tex->width = atoi(elem->Attribute("Width")); tex->height = atoi(elem->Attribute("Height")); textures.push_back(tex); } while (elem = elem->NextSiblingElement("texture")); elem = sprite->FirstChildElement("sequence"); if (elem == NULL) { std::cout << "No sequences? error.\n"; exit(0); } do { Sequence *seq = new Sequence(); seq->name = elem->Attribute("Name"); seq->returnLoopFrame = atoi(elem->Attribute("Return_Loop_Frame")); seq->loops = atoi(elem->Attribute("Loops")); //std::cout << seq->name << '\n'; TiXmlElement * frameElem = elem->FirstChildElement("frame"); if (frameElem == 0) std::cout << "No frames. Error.\n"; do { Frame * frame = new Frame(); frame->time = atof(frameElem->Attribute("Time")); //Tex_X="206" Tex_Y="549" Width="39" Height="54" Anchor_X="19.5" Anchor_Y="27" Texture="0" /> int tex_x = atoi(frameElem->Attribute("Tex_X")); int tex_y = atoi(frameElem->Attribute("Tex_Y")); float width = atof(frameElem->Attribute("Width")); float scalex = atof(frameElem->Attribute("ScaleX")); width *= scalex; float height = atof(frameElem->Attribute("Height")); float scaley = atof(frameElem->Attribute("ScaleY")); height *= scaley; int texindex = atoi(frameElem->Attribute("Texture")); float xAnchor = atof(frameElem->Attribute("Anchor_X")); float yAnchor = atof(frameElem->Attribute("Anchor_Y")); Texture * texid = textures[texindex]->loaded_tex; frame->texture = texid; //GLfloat color[4] = {0}; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { frame->quad.v[i].color[j] = 0.5f; } } frame->quad.z = 0.5f; frame->width = width / FPU; frame->height = height / FPU; frame->xAnchor = xAnchor / FPU * scalex; frame->yAnchor = yAnchor / FPU * scaley; int texW = textures[texindex]->width; texW *= scalex; int texH = textures[texindex]->height; texH *= scaley; frame->quad.v[0].tx = (GLfloat)tex_x / texW; frame->quad.v[0].ty = (GLfloat)tex_y / texH; frame->quad.v[1].tx = (GLfloat)(tex_x + width) / texW; frame->quad.v[1].ty = (GLfloat)tex_y / texH; frame->quad.v[2].tx = (GLfloat)(tex_x + width) / texW; frame->quad.v[2].ty = (GLfloat)(tex_y + height) / texH; frame->quad.v[3].tx = (GLfloat)tex_x / texW; frame->quad.v[3].ty = (GLfloat)(tex_y + height) / texH; seq->frames.push_back(frame); } while (frameElem = frameElem->NextSiblingElement("frame")); sequences.push_back(seq); } while(elem = elem->NextSiblingElement("sequence")); //clean up temp texture list std::vector<texture *>::iterator i; for (i = textures.begin(); i != textures.end(); ++i) { delete (*i); } //std::cout << elem->Attribute("File") << "\nblabla\n"; } AnimatedSprite::~AnimatedSprite(void) { std::vector<Sequence *>::iterator i; for (i = sequences.begin(); i != sequences.end(); ++i) { std::vector<Frame *>::iterator j; for (j = (*i)->frames.begin(); j != (*i)->frames.end(); ++j) { delete (*j); } delete (*i); } delete m_PolyDef; } int32 AnimatedSprite::GetSequence(std::string sequence_name) { for (unsigned int i = 0; i < sequences.size(); ++i) { if (sequences[i]->name == sequence_name) { return i; } } m_Logger.Outputf(P_WARNING, OTHER, "Failed to find sequence %s in sprite %s of %i sequences\n", sequence_name.c_str(), m_Name.c_str(), sequences.size()); return -1; } void AnimatedSprite::Render(GLfloat x, GLfloat y, Uint32 sequence, Uint32 frame, bool hflip) { Frame * workingFrame = sequences[sequence]->frames[frame]; x -= workingFrame->xAnchor; y -= workingFrame->yAnchor; Quad quad = workingFrame->quad; float width = workingFrame->width; float height = workingFrame->height; quad.v[0].x = x; quad.v[0].y = y; //quad.v[0].tx = 0; quad.v[0].ty = 0; quad.v[0].x = 0; quad.v[0].y = 0; quad.v[0].color[3] = 0; //quad.v[1].tx = 1; quad.v[1].ty = 0; quad.v[1].x = x+width; quad.v[1].y = y; //quad.v[1].color[3] = 0; //quad.v[2].tx = 1; quad.v[2].ty = 1; quad.v[2].x = x+width; quad.v[2].y = y+height;// quad.v[2].color[3] = 0; //quad.v[3].tx = 0; quad.v[3].ty = 1; quad.v[3].x = x; quad.v[3].y = y+height; //quad.v[3].color[3] = 0; //std::cout << "rendering " << m_CurrentSequence->frames[m_CurrentFrame]->texture->GetId() << '\n'; if (hflip) { GLfloat temp = quad.v[0].tx; quad.v[0].tx = quad.v[1].tx; quad.v[1].tx = temp; temp = quad.v[2].tx; quad.v[2].tx = quad.v[3].tx; quad.v[3].tx = temp; } m_Renderer.AddQuad(workingFrame->texture, quad); } }
[ "William@18b72257-4ce5-c346-ae33-905a28f88ba6" ]
[ [ [ 1, 214 ] ] ]
7f880e2bfb5d35f3afa839533d13d4744ebdc651
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/gerbview/edit.cpp
51c8b98d1409e6e40522b7e8579d77e193f3ec95
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
8,893
cpp
/******************************************************/ /* edit.cpp: fonctions generales de l'edition du PCB */ /******************************************************/ #include "fctsys.h" #include "common.h" #include "gerbview.h" #include "pcbplot.h" #include "id.h" #include "protos.h" static void Process_Move_Item(WinEDA_GerberFrame * frame, EDA_BaseStruct *DrawStruct, wxDC * DC); /************************************************************************/ void WinEDA_GerberFrame::OnLeftClick(wxDC * DC, const wxPoint& MousePos) /************************************************************************/ /* Traite les commandes declenchée par le bouton gauche de la souris, quand un outil est deja selectionné */ { EDA_BaseStruct * DrawStruct = GetScreen()->m_CurrentItem; wxString msg; if ( m_ID_current_state == 0 ) { if ( DrawStruct && DrawStruct->m_Flags ) // Commande "POPUP" en cours { switch (DrawStruct->m_StructType ) { default: msg.Printf( wxT("WinEDA_GerberFrame::ProcessCommand err: Struct %d, m_Flags = %X"), (unsigned) DrawStruct->m_StructType, (unsigned) DrawStruct->m_Flags); DisplayError(this, msg ); } } else { GetScreen()->m_CurrentItem = DrawStruct = GerberGeneralLocateAndDisplay(); } } switch ( m_ID_current_state ) { case 0: break; case ID_NO_SELECT_BUTT: break; case ID_PCB_DELETE_ITEM_BUTT: DrawStruct = GerberGeneralLocateAndDisplay(); if ( DrawStruct == NULL ) break; if ( DrawStruct->m_StructType == TYPETRACK ) { Delete_Segment(DC, (TRACK *) DrawStruct ); GetScreen()->m_CurrentItem = NULL; GetScreen()->SetModify(); } break; default : DisplayError(this, wxT("WinEDA_GerberFrame::ProcessCommand error")); SetToolID( 0, wxCURSOR_ARROW, wxEmptyString); break; } } /********************************************************************************/ void WinEDA_GerberFrame::Process_Special_Functions(wxCommandEvent& event) /********************************************************************************/ /* Traite les selections d'outils et les commandes appelees du menu POPUP */ { int id = event.GetId(); int layer = GetScreen()->m_Active_Layer; GERBER_Descr * gerber_layer = g_GERBER_Descr_List[layer]; wxPoint pos; wxClientDC dc(DrawPanel); DrawPanel->PrepareGraphicContext(&dc); wxGetMousePosition(&pos.x, &pos.y); pos.y += 20; switch ( id ) // Arret eventuel de la commande de déplacement en cours { case wxID_CUT: case wxID_COPY: case ID_POPUP_DELETE_BLOCK: case ID_POPUP_PLACE_BLOCK: case ID_POPUP_ZOOM_BLOCK: case ID_POPUP_INVERT_BLOCK: case ID_POPUP_ROTATE_BLOCK: case ID_POPUP_COPY_BLOCK: break; case ID_POPUP_CANCEL_CURRENT_COMMAND: if( GetScreen()->ManageCurseur && GetScreen()->ForceCloseManageCurseur ) { GetScreen()->ForceCloseManageCurseur(this, &dc); } /* ne devrait pas etre execute, sauf bug */ if (m_CurrentScreen->BlockLocate.m_Command != BLOCK_IDLE) { m_CurrentScreen->BlockLocate.m_Command = BLOCK_IDLE; m_CurrentScreen->BlockLocate.m_State = STATE_NO_BLOCK; m_CurrentScreen->BlockLocate.m_BlockDrawStruct = NULL; } if (m_ID_current_state == 0 ) SetToolID(0, wxCURSOR_ARROW, wxEmptyString); else SetCursor(DrawPanel->m_PanelCursor = DrawPanel->m_PanelDefaultCursor); break; default: // Arret dea commande de déplacement en cours if( GetScreen()->ManageCurseur && GetScreen()->ForceCloseManageCurseur ) { GetScreen()->ForceCloseManageCurseur(this, &dc); } SetToolID(0, wxCURSOR_ARROW, wxEmptyString); break; } switch ( id ) // Traitement des commandes { case ID_EXIT : Close(TRUE); break; case ID_NEW_PROJECT: case ID_LOAD_PROJECT: Files_io(event); break; case ID_PCB_GLOBAL_DELETE: Erase_Current_Layer(&dc, TRUE); break; case wxID_CUT: break; case wxID_COPY: break; case wxID_PASTE: // HandleBlockBegin(&dc, BLOCK_PASTE); break; case ID_UNDO_BUTT: UnDeleteItem(&dc); break; case ID_GET_TOOLS: // InstallToolsFrame(this, wxPoint(-1,-1) ); break; case ID_FIND_ITEMS: // InstallFindFrame(this, pos); break; case ID_BUS_BUTT: SetToolID( id, wxCURSOR_PENCIL, wxT("Add Tracks")); break; case ID_LINE_COMMENT_BUTT: SetToolID( id, wxCURSOR_PENCIL, wxT("Add Drawing")); break; case ID_TEXT_COMMENT_BUTT: SetToolID( id, wxCURSOR_PENCIL, wxT("Add Text")); break; case ID_NO_SELECT_BUTT: SetToolID( 0, 0, wxEmptyString); break; case ID_POPUP_CLOSE_CURRENT_TOOL: SetToolID( 0, wxCURSOR_ARROW, wxEmptyString); break; case ID_POPUP_CANCEL_CURRENT_COMMAND: break; case ID_POPUP_END_LINE: DrawPanel->MouseToCursorSchema(); // EndSegment(&dc); break; case ID_POPUP_PCB_DELETE_TRACKSEG: DrawPanel->MouseToCursorSchema(); if ( GetScreen()->m_CurrentItem == NULL) break; Delete_Segment(&dc, (TRACK*)GetScreen()->m_CurrentItem); GetScreen()->m_CurrentItem = NULL; GetScreen()->SetModify(); break; case ID_PCB_DELETE_ITEM_BUTT: SetToolID( id, wxCURSOR_PENCIL, wxT("Delete item")); break; case ID_POPUP_SCH_MOVE_ITEM_REQUEST: DrawPanel->MouseToCursorSchema(); Process_Move_Item(this, GetScreen()->m_CurrentItem, &dc); break; case ID_TOOLBARH_PCB_SELECT_LAYER: { GetScreen()->m_Active_Layer = m_SelLayerBox->GetSelection(); DrawPanel->Refresh(TRUE); break; } case ID_TOOLBARH_GERBER_SELECT_TOOL: if ( gerber_layer ) { int tool = m_SelLayerTool->GetSelection(); if ( tool > 0 ) tool = tool - 1 + FIRST_DCODE; else tool = 0; gerber_layer->m_Selected_Tool = tool; DrawPanel->Refresh(TRUE); } else DisplayError(this, _("No layer selected") ); break; case ID_GERBVIEW_SHOW_LIST_DCODES: Liste_D_Codes(&dc); break; case ID_GERBVIEW_SHOW_SOURCE: if ( gerber_layer ) { wxString editorname = GetEditorName(); if ( ! editorname.IsEmpty() ) ExecuteFile(this, editorname, gerber_layer->m_FileName); } break; case ID_POPUP_PLACE_BLOCK: GetScreen()->BlockLocate.m_Command = BLOCK_MOVE; DrawPanel->m_AutoPAN_Request = FALSE; HandleBlockPlace(&dc); break; case ID_POPUP_COPY_BLOCK: GetScreen()->BlockLocate.m_Command = BLOCK_COPY; m_CurrentScreen->BlockLocate.SetMessageBlock(this); DrawPanel->m_AutoPAN_Request = FALSE; HandleBlockEnd(&dc); break; case ID_POPUP_ZOOM_BLOCK: GetScreen()->BlockLocate.m_Command = BLOCK_ZOOM; m_CurrentScreen->BlockLocate.SetMessageBlock(this); m_CurrentScreen->BlockLocate.SetMessageBlock(this); HandleBlockEnd(&dc); break; case ID_POPUP_DELETE_BLOCK: GetScreen()->BlockLocate.m_Command = BLOCK_DELETE; m_CurrentScreen->BlockLocate.SetMessageBlock(this); HandleBlockEnd(&dc); break; default: wxMessageBox( wxT("WinEDA_GerberFrame::Process_Special_Functions error")); break; } SetToolbars(); } /****************************************************************/ static void Process_Move_Item(WinEDA_GerberFrame * frame, EDA_BaseStruct *DrawStruct, wxDC * DC) /****************************************************************/ { if ( DrawStruct == NULL ) return; frame->DrawPanel->MouseToCursorSchema(); switch ( DrawStruct->m_StructType ) { default: wxString msg; msg.Printf( wxT("WinEDA_LibeditFrame::Move_Item Error: Bad DrawType %d"), DrawStruct->m_StructType); DisplayError(frame, msg ); break; } } /**************************************************************************/ void WinEDA_GerberFrame::OnLeftDClick(wxDC * DC, const wxPoint& MousePos) /**************************************************************************/ /* Appelé sur un double click: pour un élément editable (textes, composant): appel de l'editeur correspondant. pour une connexion en cours: termine la connexion */ { EDA_BaseStruct * DrawStruct = GetScreen()->m_CurrentItem; wxClientDC dc(DrawPanel); DrawPanel->PrepareGraphicContext(&dc); switch ( m_ID_current_state ) { case 0: if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) ) { DrawStruct = GerberGeneralLocateAndDisplay(); } if ( (DrawStruct == NULL) || (DrawStruct->m_Flags != 0) ) break; // Element localisé switch ( DrawStruct->m_StructType ) { default: break; } break; // end case 0 case ID_BUS_BUTT: case ID_WIRE_BUTT: // if ( DrawStruct && (DrawStruct->m_Flags & IS_NEW) ) // EndSegment(DC); break; } }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 350 ] ] ]
c343ddc7e0cebf85d1900bca2127c72149bcc5ef
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qitemeditorfactory.h
faed230dd64a3ae5b595dbdf80bcfd2414b3871a
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,113
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QITEMEDITORFACTORY_H #define QITEMEDITORFACTORY_H #include <QtCore/qmetaobject.h> #include <QtCore/qbytearray.h> #include <QtCore/qhash.h> #include <QtCore/qvariant.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_ITEMVIEWS class QWidget; class Q_GUI_EXPORT QItemEditorCreatorBase { public: virtual ~QItemEditorCreatorBase() {} virtual QWidget *createWidget(QWidget *parent) const = 0; virtual QByteArray valuePropertyName() const = 0; }; template <class T> class QItemEditorCreator : public QItemEditorCreatorBase { public: inline QItemEditorCreator(const QByteArray &valuePropertyName); inline QWidget *createWidget(QWidget *parent) const { return new T(parent); } inline QByteArray valuePropertyName() const { return propertyName; } private: QByteArray propertyName; }; template <class T> class QStandardItemEditorCreator: public QItemEditorCreatorBase { public: inline QStandardItemEditorCreator() : propertyName(T::staticMetaObject.userProperty().name()) {} inline QWidget *createWidget(QWidget *parent) const { return new T(parent); } inline QByteArray valuePropertyName() const { return propertyName; } private: QByteArray propertyName; }; template <class T> Q_INLINE_TEMPLATE QItemEditorCreator<T>::QItemEditorCreator(const QByteArray &avaluePropertyName) : propertyName(avaluePropertyName) {} class Q_GUI_EXPORT QItemEditorFactory { public: inline QItemEditorFactory() {} virtual ~QItemEditorFactory(); virtual QWidget *createEditor(QVariant::Type type, QWidget *parent) const; virtual QByteArray valuePropertyName(QVariant::Type type) const; void registerEditor(QVariant::Type type, QItemEditorCreatorBase *creator); static const QItemEditorFactory *defaultFactory(); static void setDefaultFactory(QItemEditorFactory *factory); private: QHash<QVariant::Type, QItemEditorCreatorBase *> creatorMap; }; #endif // QT_NO_ITEMVIEWS QT_END_NAMESPACE QT_END_HEADER #endif // QITEMEDITORFACTORY_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 124 ] ] ]
bdbe835de653ceb7c2d3bfed32b8db92b915169d
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleRender/TRenderNodePathNetwork.cpp
9863205ab0798feb46e3460862fe2357f8e4a2bc
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,420
cpp
#include "TRenderNodePathNetwork.h" #include <TootleAsset/TPath.h> #define PATH_DIRECTION_ARROW_LENGTH 1.0f // how big are the triangles #define PATH_DIRECTION_ARROW_WIDTH 1.0f // how big are the triangles #define PATH_DIRECTION_ARROW_HALFWIDTH (PATH_DIRECTION_ARROW_WIDTH*0.5f) #define PATH_DIRECTION_ARROW_RATE 10.f // draw a triangle every N metres TLRender::TRenderNodePathNetwork::TRenderNodePathNetwork(TRefRef RenderNodeRef,TRefRef TypeRef) : TRenderNodeDebugMesh ( RenderNodeRef, TypeRef ), m_EnableMarkers ( TRUE ) { } //--------------------------------------------------------- // init //--------------------------------------------------------- void TLRender::TRenderNodePathNetwork::Initialise(TLMessaging::TMessage& Message) { // do inherited init first to create mesh etc TRenderNodeDebugMesh::Initialise( Message ); // debug the points on the path GetRenderFlags().Clear( TLRender::TRenderNode::RenderFlags::DepthRead ); GetRenderFlags().Clear( TLRender::TRenderNode::RenderFlags::EnableCull ); // read marker setting Message.ImportData("Markers", m_EnableMarkers ); // see if a path network asset has been specified (do this last!) TRef PathNetworkRef; if ( Message.ImportData("PathNetwork", PathNetworkRef ) ) SetPathNetwork( PathNetworkRef ); } //--------------------------------------------------------- // change the path network asset //--------------------------------------------------------- void TLRender::TRenderNodePathNetwork::SetPathNetwork(TRefRef PathNetworkRef) { // no change if ( m_PathNetworkRef == PathNetworkRef ) return; // clean up old stuff GetMeshAsset()->Empty(); m_PathNodeVertex.Empty(); // set new ref m_PathNetworkRef = PathNetworkRef; // been set to no-path, so nothing to do if ( !m_PathNetworkRef.IsValid() ) return; // get the path network asset TLAsset::TPathNetwork* pPathNetwork = TLAsset::GetAsset<TLAsset::TPathNetwork>( m_PathNetworkRef ); if ( !pPathNetwork ) { TLDebug_Break("Missing Path asset for TRenderNodePathNetwork"); return; } // create the debug mesh for the asset InitMeshFromPathNetwork( *pPathNetwork ); } //--------------------------------------------------------- // catch asset changes //--------------------------------------------------------- void TLRender::TRenderNodePathNetwork::ProcessMessage(TLMessaging::TMessage& Message) { // handle inherited messages TRenderNodeDebugMesh::ProcessMessage( Message ); } //--------------------------------------------------------- // create the debug mesh for the asset //--------------------------------------------------------- void TLRender::TRenderNodePathNetwork::InitMeshFromPathNetwork(TLAsset::TPathNetwork& PathNetwork) { TLAsset::TMesh& Mesh = *GetMeshAsset(); TPtrArray<TLPath::TPathNode>& PathNodes = PathNetwork.GetNodeArray(); for ( u32 n=0; n<PathNodes.GetSize(); n++ ) { TLPath::TPathNode& PathNode = *PathNodes[n]; // get/add vertex for this node... s32 Vertex = GetPathNodeVertex( PathNetwork, PathNode ); if ( Vertex < 0 ) continue; // create lines to the links TArray<TLPath::TPathNodeLink>& NodeLinks = PathNode.GetLinks(); for ( u32 i=0; i<NodeLinks.GetSize(); i++ ) { TLPath::TPathNodeLink& PathLink = NodeLinks[i]; // get the index of the link, if it's less than N then we've already processed this node, and therefore // we already have a line connecting them both. s32 LinkNodeIndex = PathNodes.FindIndex( PathLink.GetLinkNodeRef() ); if ( LinkNodeIndex < (s32)n ) continue; // get vertex of node TLPath::TPathNode& LinkPathNode = *PathNodes[LinkNodeIndex]; s32 LinkVertex = GetPathNodeVertex( PathNetwork, LinkPathNode ); if ( LinkVertex < 0 ) continue; // create line between nodes Mesh.GenerateLine( Vertex, LinkVertex ); if ( m_EnableMarkers ) { // draw markers along the line // if the link is one way, then add arrows along the line TLPath::TDirection::Type Direction = PathLink.GetDirection(); // reverse line direction if direction is backwards const float2& FromPos = (Direction != TLPath::TDirection::Backward) ? PathNode.GetPosition() : LinkPathNode.GetPosition(); const float2& ToPos = (Direction != TLPath::TDirection::Backward) ? LinkPathNode.GetPosition() : PathNode.GetPosition(); // get dir and length float2 LineDir( ToPos - FromPos ); float LineLength = LineDir.Length(); LineDir.Normalise(); THeapArray<float> ArrowOffsets; // not gonna fit on more than 1 arrow, just add one in the middle if ( LineLength <= PATH_DIRECTION_ARROW_RATE ) { ArrowOffsets.Add( LineLength * 0.5f ); } else { // add an arrow every so often... float ArrowCountf = LineLength / PATH_DIRECTION_ARROW_RATE; u32 ArrowCount = (u32)ArrowCountf; float Offset = (ArrowCountf - (float)ArrowCount) / 2.f; // use remainder to center arrows along line // offset half way as well Offset += PATH_DIRECTION_ARROW_RATE / 2.f; for ( u32 i=0; i<ArrowCount; i++ ) ArrowOffsets.Add( Offset + ((float)i*PATH_DIRECTION_ARROW_RATE) ); } // draw an arrow along the path for ( u32 i=0; i<ArrowOffsets.GetSize(); i++ ) { float2 ArrowHeadPos = FromPos + (LineDir * (ArrowOffsets[i] + PATH_DIRECTION_ARROW_LENGTH) ); float2 ArrowTailPos = FromPos + (LineDir * ArrowOffsets[i] ); float2 ArrowLeft = LineDir.GetAntiClockwise() * PATH_DIRECTION_ARROW_HALFWIDTH; float2 ArrowTailLeft = ArrowTailPos + ArrowLeft; float2 ArrowTailRight = ArrowTailPos - ArrowLeft; if ( Direction == TLPath::TDirection::Any ) { // draw a quad instead of an arrow when it's any direction float2 ArrowHeadLeft = ArrowHeadPos + ArrowLeft; float2 ArrowHeadRight = ArrowHeadPos - ArrowLeft; // make up quad // this line is corrupting mem! Mesh.GenerateQuad( ArrowHeadLeft.xyz(0.f), ArrowHeadRight.xyz(0.f), ArrowTailRight.xyz(0.f), ArrowTailLeft.xyz(0.f) ); } else { // make up triangle TLAsset::TMesh::Triangle* pTriangle = Mesh.GetTriangles().AddNew(); pTriangle->x = Mesh.AddVertex( ArrowHeadPos.xyz(0.f) ); pTriangle->y = Mesh.AddVertex( ArrowTailLeft.xyz(0.f) ); pTriangle->z = Mesh.AddVertex( ArrowTailRight.xyz(0.f) ); } } } } } } //--------------------------------------------------------- // return vertex for this path node - if it doesn't exist, create it //--------------------------------------------------------- s32 TLRender::TRenderNodePathNetwork::GetPathNodeVertex(TLAsset::TPathNetwork& PathNetwork,TLPath::TPathNode& PathNode) { TRefRef PathNodeRef = PathNode.GetNodeRef(); // lookup existing vertex u16* pVertexIndex = m_PathNodeVertex.Find( PathNodeRef ); if ( pVertexIndex ) return (s32)( *pVertexIndex ); // doesn't exist, create new vertex... // add vertex to mesh s32 VertexIndex = GetMeshAsset()->AddVertex( PathNode.GetPosition().xyz(0.f) ); // failed to add vertex? if ( VertexIndex == -1 ) return -1; // add index to the lookup table so we keep a record of it m_PathNodeVertex.Add( PathNodeRef, (u16)VertexIndex ); return VertexIndex; }
[ [ [ 1, 21 ], [ 23, 24 ], [ 26, 35 ], [ 37, 77 ], [ 79, 80 ], [ 82, 220 ] ], [ [ 22, 22 ], [ 25, 25 ], [ 36, 36 ], [ 78, 78 ], [ 81, 81 ] ] ]
9a12b02eba2437f700b776fdbf9b4ee7b64e2c92
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Stellar_/code/Render/resources/resourceloader.cc
a525d108c627245b7f470dd4bfb7b37d542d3937
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
3,945
cc
//------------------------------------------------------------------------------ // resourceloader.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "resources/resourceloader.h" #include "resources/resource.h" //#include "resources/resourcesaver.h" namespace Resources { ImplementClass(Resources::ResourceLoader, 'RSLD', Core::RefCounted); //------------------------------------------------------------------------------ /** */ ResourceLoader::ResourceLoader() : state(Resource::Initial) { // empty } //------------------------------------------------------------------------------ /** */ ResourceLoader::~ResourceLoader() { s_assert(!this->IsAttachedToResource()); } //------------------------------------------------------------------------------ /** */ void ResourceLoader::OnAttachToResource(const Ptr<Resource>& res) { s_assert(!this->IsAttachedToResource()); this->resource = res; } //------------------------------------------------------------------------------ /** */ void ResourceLoader::OnRemoveFromResource() { s_assert(this->IsAttachedToResource()); if (Resource::Pending == this->GetState()) { this->OnLoadCancelled(); } this->resource = 0; } //------------------------------------------------------------------------------ /** */ bool ResourceLoader::IsAttachedToResource() const { return this->resource.isvalid(); } //------------------------------------------------------------------------------ /** */ const Ptr<Resource>& ResourceLoader::GetResource() const { return this->resource; } //------------------------------------------------------------------------------ /** This method should be overriden in a subclass and indicates whether the resource loader supports asynchronous resource loading. If asynchronous loading is requested, the OnLoadRequested() method will return immediately and the Resource object will be put into Pending state. Afterwards, the Resource object needs to poll the ResourceLoader using the OnPending method, which will eventually setup the Resource object. */ bool ResourceLoader::CanLoadAsync() const { return false; } //------------------------------------------------------------------------------ /** This method is called by our Resource object to perform a synchronous or initiate an asynchronous load. When performing a synchronous load, the method should setup the Resource and go into the Done state (or Failed state when the load has failed). In asynchronous mode, the method should put the resource loader into the Pending state. */ bool ResourceLoader::OnLoadRequested() { return true; } //------------------------------------------------------------------------------ /** This method is called by our Resource object if a pending asynchronous load should be cancelled. */ void ResourceLoader::OnLoadCancelled() { this->SetState(Resource::Cancelled); } //------------------------------------------------------------------------------ /** This method should be called at some time after OnLoadRequested() as long as the ResourceLoader is in the Pending state. This will check whether the asynchronous loader job has finished, and if yes, setup the Resource object, bringing it from the Pending into the Loaded state. If something goes wrong, the ResourceLoader will go into the Failed state. If the outstanding loader job isn't finished yet, the ResourceLoader should remain in Pending state, and the method should return false. Otherwise the Resource should be initialized, and the method should return true. */ bool ResourceLoader::OnPending() { return false; } } // namespace Resources
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 131 ] ] ]
ffb18068028a617d692fd920b3be9a4f39450cc7
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/TestWAH/TestExceptions.cpp
ceecc44c2bb5eaa83a87a0a1d02ec9beb4834153
[]
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,685
cpp
#include "TestExceptions.h" using namespace std; TestCompressionExceptions::TestCompressionExceptions(void) { } TestCompressionExceptions::~TestCompressionExceptions(void) { } void TestCompressionExceptions::TestSuite() { //TestCovertingExceptions(); TestNullExceptions(); } void TestCompressionExceptions::TestCovertingExceptions() { WrapDataSource * source = CreateDataSource(); try{ CompressionHandler::ConvertTo(source,BitStreamInfo::NULL_COMP); } catch(invalid_compression_type_exception & ex) { cout <<"To string : " << ex.toString() << endl; } catch(...) { cout <<"All exceptions caught" << endl; } } void TestCompressionExceptions::TestNullExceptions() { try{ CompressionHandler::ConvertTo(NULL,BitStreamInfo::VERTICAL_STREAM_FORMAT); } catch(null_operand_exception & ex) { cout <<"To string : " << ex.toString() << endl; } catch(...) { cout <<"All exceptions caught" << endl; } } WrapDataSource * TestCompressionExceptions::CreateDataSource() { /* LoadSavedDataSources *lsd = new LoadSavedDataSources(ConfigurationReader::ReadConfiguration(ConfigurationReader::METAFILE_NAME), ConfigurationReader::ReadConfiguration(ConfigurationReader::DATAFILE_NAME)); DataSources *dsLoaded = lsd->loadSavedEncodedData(); return (*dsLoaded)(ConfigurationReader::ReadConfiguration(ConfigurationReader::FILE_NAME));*/ return Utils::CreateDataSource(ConfigurationReader::ReadConfiguration(ConfigurationReader::DATAFILE_NAME), ConfigurationReader::ReadConfiguration(ConfigurationReader::METAFILE_NAME), ConfigurationReader::ReadConfiguration(ConfigurationReader::FILE_NAME)); }
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 61 ] ] ]
6537e9197a18661fa7a47293c0dfa97869e80f64
da5547e6a2b8b329be1f3975fc93faea6e40660c
/UIlib/UIAnim.cpp
b5586a5539bd567469bbfc77c473e1012bc79e9a
[]
no_license
hackerlank/directui
5599b673d7273e743ea48baf6c301df12d770e74
c5d55e8dfda86355b731d5af5166b8b3786f5187
refs/heads/master
2020-01-23T21:35:28.834222
2011-04-02T01:47:01
2011-04-02T01:47:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,951
cpp
#include "stdafx.h" #include "UIAnim.h" #if (_MSC_VER < 1300) #pragma comment(lib, "Delayimp.lib") #pragma comment(linker, "/DelayLoad:d3d9.dll") #endif // _MSC_VER #pragma comment(lib, "d3d9.lib") ///////////////////////////////////////////////////////////////////////////////////// // // #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1) #ifndef PI #define PI 3.1415926535897932384626433832795029L #endif ///////////////////////////////////////////////////////////////////////////////////// // CAnimJobUI::CAnimJobUI(const CAnimJobUI& src) { *this = src; } CAnimJobUI::CAnimJobUI(UITYPE_ANIM AnimType, DWORD dwStartTick, DWORD dwDuration, COLORREF clrBack, COLORREF clrKey, RECT rcFrom, int xtrans, int ytrans, int ztrans, int alpha, FLOAT zrot) { this->AnimType = AnimType; this->dwStartTick = dwStartTick; this->dwDuration = dwDuration; data.plot.clrBack = clrBack; data.plot.clrKey = clrKey; data.plot.rcFrom = rcFrom; data.plot.mFrom.xtrans = xtrans; data.plot.mFrom.ytrans = ytrans; data.plot.mFrom.ztrans = ztrans; data.plot.mFrom.alpha = alpha; data.plot.mFrom.zrot = zrot; data.plot.iInterpolate = INTERPOLATE_COS; } ///////////////////////////////////////////////////////////////////////////////////// // // CAnimationSpooler::CAnimationSpooler() : m_hWnd(NULL), m_bIsAnimating(false), m_bIsInitialized(false), m_pD3D(NULL), m_p3DDevice(NULL), m_p3DBackSurface(NULL), m_nBuffers(0) { ::ZeroMemory(m_p3DVertices, sizeof(m_p3DVertices)); ::ZeroMemory(m_p3DTextures, sizeof(m_p3DTextures)); } CAnimationSpooler::~CAnimationSpooler() { Term(); } bool CAnimationSpooler::Init(HWND hWnd) { ASSERT(::IsWindow(hWnd)); if( m_bIsInitialized ) return true; // This is our master window m_hWnd = hWnd; // Gather window information RECT rcWindow = { 0 }; ::GetWindowRect(hWnd, &rcWindow); if( ::IsRectEmpty(&rcWindow) ) return false; // Is window topmost? HWND hWndFocus = hWnd; while( ::GetParent(hWndFocus) != NULL ) hWndFocus = ::GetParent(hWndFocus); // Is DirectX v9 available at all? HMODULE hMod = ::LoadLibrary(_T("D3D9.DLL")); if( hMod == NULL ) return false; ::FreeLibrary(hMod); // Initialize Direct3D // Fortunately we can delay-load the DirectX9 library so we // don't actually have a link dependency on it. if( m_pD3D != NULL ) m_pD3D->Release(); m_pD3D = ::Direct3DCreate9(D3D_SDK_VERSION); if( m_pD3D == NULL ) return false; HRESULT Hr; D3DDISPLAYMODE d3ddm = { 0 }; Hr = m_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm); if( FAILED(Hr) ) return false; m_ColorFormat = d3ddm.Format; Hr = m_pD3D->CheckDeviceType(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_ColorFormat, m_ColorFormat, TRUE); if( FAILED(Hr) ) return false; D3DPRESENT_PARAMETERS d3dpp = { 0 }; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;; //D3DSWAPEFFECT_FLIP d3dpp.Windowed = TRUE; d3dpp.hDeviceWindow = hWnd; d3dpp.BackBufferCount = 1; d3dpp.BackBufferFormat = m_ColorFormat; d3dpp.EnableAutoDepthStencil = FALSE; d3dpp.AutoDepthStencilFormat = D3DFMT_D16; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; Hr = m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWndFocus, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &m_p3DDevice); if( FAILED(Hr) ) return false; // Check device caps D3DCAPS9 caps; Hr = m_p3DDevice->GetDeviceCaps(&caps); if( caps.MaxTextureWidth < 128 ) return false; if( (caps.Caps3 & D3DCAPS3_COPY_TO_VIDMEM) == 0 ) return false; if( FAILED(Hr) ) return false; // Set viewport D3DVIEWPORT9 vp; vp.X = vp.Y = 0; vp.Width = rcWindow.right - rcWindow.left; vp.Height = rcWindow.bottom - rcWindow.top; vp.MinZ = 0.0; vp.MaxZ = 1.0; Hr = m_p3DDevice->SetViewport(&vp); if( FAILED(Hr) ) return false; // Set the render flags. m_p3DDevice->SetRenderState(D3DRS_COLORVERTEX, TRUE); m_p3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); m_p3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); m_p3DDevice->SetRenderState(D3DRS_ZENABLE, TRUE); // Set miscellaneous render states m_p3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_p3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); m_p3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); m_p3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); m_p3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); m_p3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); m_p3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); m_p3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); // Use alpha from texture m_p3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); // Use vertex alpha m_p3DDevice->SetVertexShader(NULL); // Signal go... m_bIsInitialized = true; return true; } void CAnimationSpooler::Term() { // Get rid of the animation jobs int i; for( i = 0; i < m_aJobs.GetSize(); i++ ) delete static_cast<CAnimJobUI*>(m_aJobs[i]); m_aJobs.Empty(); // Release Direct3D references for( i = 0; i < m_nBuffers; i++ ) { m_p3DVertices[i]->Release(); m_p3DTextures[i]->Release(); } m_nBuffers = 0; if( m_p3DBackSurface != NULL ) m_p3DBackSurface->Release(); m_p3DBackSurface = NULL; if( m_p3DDevice != NULL ) m_p3DDevice->Release(); m_p3DDevice = NULL; if( m_pD3D != NULL ) m_pD3D->Release(); m_pD3D = NULL; // Almost done... m_bIsAnimating = false; m_bIsInitialized = false; } bool CAnimationSpooler::AddJob(CAnimJobUI* pJob) { return m_aJobs.Add(pJob); } bool CAnimationSpooler::IsAnimating() const { return m_bIsAnimating; } bool CAnimationSpooler::IsJobScheduled() const { return m_aJobs.GetSize() > 0 && !m_bIsAnimating; } bool CAnimationSpooler::PrepareAnimation(HWND hWnd) { if( !m_bIsInitialized ) return false; // Release old image of window if( m_p3DBackSurface != NULL ) m_p3DBackSurface->Release(); m_p3DBackSurface= NULL; // Create the backdrop surface RECT rcClient; ::GetClientRect(m_hWnd, &rcClient); int cx = rcClient.right - rcClient.left; int cy = rcClient.bottom - rcClient.top; HRESULT Hr = m_p3DDevice->CreateOffscreenPlainSurface(cx, cy, m_ColorFormat, D3DPOOL_SYSTEMMEM, &m_p3DBackSurface, NULL); if( FAILED(Hr) ) return false; // Paint the background HDC hDC = NULL; Hr = m_p3DBackSurface->GetDC(&hDC); if( FAILED(Hr) ) return false; ::SendMessage(hWnd, WM_PRINTCLIENT, (WPARAM) hDC, PRF_CHECKVISIBLE | PRF_CLIENT | PRF_ERASEBKGND | PRF_CHILDREN); m_p3DBackSurface->ReleaseDC(hDC); // Allow each job to prepare its 3D objects for( int i = 0; i < m_aJobs.GetSize(); i++ ) { CAnimJobUI* pJob = static_cast<CAnimJobUI*>(m_aJobs[i]); switch( pJob->AnimType ) { case UIANIMTYPE_FLAT: if( !PrepareJob_Flat(pJob) ) return false; break; } } // Assign start time DWORD dwTick = ::timeGetTime(); for( int j = 0; j < m_aJobs.GetSize(); j++ ) { CAnimJobUI* pJob = static_cast<CAnimJobUI*>(m_aJobs[j]); pJob->dwStartTick += dwTick; } m_bIsAnimating = true; return true; } bool CAnimationSpooler::Render() { if( !m_bIsAnimating ) return false; if( !m_bIsInitialized ) return false; // Get render target HRESULT Hr; LPDIRECT3DSURFACE9 p3DTargetSurface; Hr = m_p3DDevice->GetRenderTarget(0, &p3DTargetSurface); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DSurface9> RefTargetSurface = p3DTargetSurface; // Copy backdrop Hr = m_p3DDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,255), 1.0f, 0L); Hr = m_p3DDevice->UpdateSurface(m_p3DBackSurface, NULL, p3DTargetSurface, NULL); // Here begins the rendering loop. Hr = m_p3DDevice->BeginScene(); if( FAILED(Hr) ) return false; int nAnimated = 0; DWORD dwTick = ::timeGetTime(); for( int i = 0; i < m_aJobs.GetSize(); i++ ) { const CAnimJobUI* pJob = static_cast<CAnimJobUI*>(m_aJobs[i]); if( dwTick < pJob->dwStartTick ) continue; DWORD dwTickNow = MIN(dwTick, pJob->dwStartTick + pJob->dwDuration); switch( pJob->AnimType ) { case UIANIMTYPE_FLAT: RenderJob_Flat(pJob, p3DTargetSurface, dwTickNow); break; } if( dwTick < pJob->dwStartTick + pJob->dwDuration ) nAnimated++; } m_p3DDevice->EndScene(); m_p3DDevice->Present(NULL, NULL, NULL, NULL); // No more frames to animate? if( nAnimated == 0 ) Term(); return true; } void CAnimationSpooler::CancelJobs() { Term(); } ///////////////////////////////////////////////////////////////////////////////////// // // static double LinearInterpolate(double y1, double y2, double mu) { return y1 * (1.0 - mu) + y2 * mu; } static double CosineInterpolate(double y1, double y2, double mu) { double mu2 = (1.0 - cos(mu * PI)) / 2.0; return y1 * (1.0 - mu2) + y2 * mu2; } ///////////////////////////////////////////////////////////////////////////////////// // // COLORREF CAnimationSpooler::TranslateColor(LPDIRECT3DSURFACE9 pSurface, COLORREF clrColor) const { ASSERT(pSurface); if( clrColor == CLR_INVALID ) return clrColor; // The only way to actually determine what color a certain RGB value gets, is // to put a pixel on the surface and taste it. HDC hDC = NULL; HRESULT Hr = pSurface->GetDC(&hDC); if( FAILED(Hr) ) return false; COLORREF clrOld = ::GetPixel(hDC, 0, 0); ::SetPixel(hDC, 0, 0, clrColor); clrColor = ::GetPixel(hDC, 0,0); ::SetPixel(hDC, 0, 0, clrOld); pSurface->ReleaseDC(hDC); return clrColor; } bool CAnimationSpooler::SetColorKey(LPDIRECT3DTEXTURE9 pTexture, LPDIRECT3DSURFACE9 pSurface, int iTexSize, COLORREF clrColorKey) { ASSERT(pTexture); ASSERT(pSurface); if( clrColorKey == CLR_INVALID ) return true; // Get colorkey's red, green, and blue components // and put the colorkey in the texture's native format DWORD r = GetRValue(clrColorKey); DWORD g = GetGValue(clrColorKey); DWORD b = GetBValue(clrColorKey); DWORD dwColorKey = D3DCOLOR_ARGB(255,r,g,b); HRESULT Hr; LPDIRECT3DTEXTURE9 pTex = NULL; Hr = m_p3DDevice->CreateTexture(iTexSize, iTexSize, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &pTex, NULL); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DTexture9> RefTex = pTex; LPDIRECT3DSURFACE9 pTexSurf = NULL; Hr = pTex->GetSurfaceLevel(0, &pTexSurf); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DSurface9> RefTexSurf = pTexSurf; Hr = m_p3DDevice->GetRenderTargetData(pSurface, pTexSurf); if( FAILED(Hr) ) return false; // Lock the texture and scan through each pixel, replacing the colorkey pixels D3DLOCKED_RECT d3dlr; Hr = pTex->LockRect(0, &d3dlr, 0, 0); if( FAILED(Hr) ) return false; DWORD* pBits = static_cast<DWORD*>(d3dlr.pBits); for( int y = 0; y < iTexSize; y++ ) { for( int x = 0; x < iTexSize; x++ ) { if( pBits[x] == dwColorKey ) pBits[x] = 0x00000000; } pBits += d3dlr.Pitch / sizeof(DWORD); } pTex->UnlockRect(0); // Copy modified data back POINT pt = { 0, 0 }; RECT rcDest = { 0, 0, iTexSize, iTexSize }; Hr = m_p3DDevice->UpdateSurface(pTexSurf, &rcDest, pSurface, &pt); return false; } bool CAnimationSpooler::PrepareJob_Flat(CAnimJobUI* pJob) { // Determine actual colorkey pJob->data.plot.clrKey = TranslateColor(m_p3DBackSurface, pJob->data.plot.clrKey); // Prepare surfaces HRESULT Hr; RECT rc = pJob->data.plot.rcFrom; int cx = rc.right - rc.left; int cy = rc.bottom - rc.left; FLOAT z = 0.1f; FLOAT rhw = 1.0f / (z * 990.0f + 10.0f); D3DCOLOR col = 0xffffffff; // Determine texture size int iTexSize = 128; if( cx < 64 ) iTexSize = 64; if( cx < 32 ) iTexSize = 32; FLOAT fTexSize = (FLOAT) iTexSize; // Start building tiles pJob->iBufferStart = m_nBuffers; for( int x = rc.left; x < rc.right; x += iTexSize ) { for( int y = rc.top; y < rc.bottom; y += iTexSize ) { RECT rcTile = { x, y, MIN(rc.right, x + iTexSize), MIN(rc.bottom, y + iTexSize) }; // Adjust texture coordinates, because last tile may only use parts // of the texture... FLOAT tcoordx = (iTexSize - (x + fTexSize - rc.right)) / fTexSize; FLOAT tcoordy = (iTexSize - (y + fTexSize - rc.bottom)) / fTexSize; if( tcoordx > 1.0f ) tcoordx = 1.0f; if( tcoordy > 1.0f ) tcoordy = 1.0f; // Create the vertex buffer CUSTOMFAN verts = { { rcTile.left - 0.5f, rcTile.top - 0.5f, z, rhw, col, 0.0f, 0.0f }, { rcTile.right - 0.5f, rcTile.top - 0.5f, z, rhw, col, tcoordx, 0.0f }, { rcTile.right - 0.5f, rcTile.bottom - 0.5f, z, rhw, col, tcoordx, tcoordy }, { rcTile.left - 0.5f, rcTile.bottom - 0.5f, z, rhw, col, 0.0f, tcoordy } }; LPDIRECT3DVERTEXBUFFER9 pVertex = NULL; Hr = m_p3DDevice->CreateVertexBuffer(4 * sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &pVertex, NULL); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DVertexBuffer9> RefVertex = pVertex; memcpy(m_fans[m_nBuffers], verts, sizeof(verts)); LPDIRECT3DTEXTURE9 pTex1 = NULL; Hr = m_p3DDevice->CreateTexture(iTexSize, iTexSize, 1, 0, m_ColorFormat, D3DPOOL_DEFAULT, &pTex1, NULL); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DTexture9> RefTex1 = pTex1; LPDIRECT3DSURFACE9 pTexSurf1 = NULL; Hr = pTex1->GetSurfaceLevel(0, &pTexSurf1); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DSurface9> RefTexSurf1 = pTexSurf1; POINT pt = { 0, 0 }; Hr = m_p3DDevice->UpdateSurface(m_p3DBackSurface, &rcTile, pTexSurf1, &pt); if( FAILED(Hr) ) return false; LPDIRECT3DTEXTURE9 pTex2 = NULL; RECT rcDest = { 0, 0, rcTile.right - rcTile.left, rcTile.bottom - rcTile.top }; Hr = m_p3DDevice->CreateTexture(iTexSize, iTexSize, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pTex2, NULL); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DTexture9> RefTex2 = pTex2; LPDIRECT3DSURFACE9 pTexSurf2 = NULL; Hr = pTex2->GetSurfaceLevel(0, &pTexSurf2); if( FAILED(Hr) ) return false; CSafeRelease<IDirect3DSurface9> RefTexSurf2 = pTexSurf2; Hr = m_p3DDevice->StretchRect(pTexSurf1, &rcDest, pTexSurf2, &rcDest, D3DTEXF_NONE); if( FAILED(Hr) ) return false; // Replace colorkey pixels with alpha SetColorKey(pTex2, pTexSurf2, iTexSize, pJob->data.plot.clrKey); // Finally, assign the texture m_p3DTextures[m_nBuffers] = RefTex2.Detach(); m_p3DVertices[m_nBuffers] = RefVertex.Detach(); m_nBuffers++; } } pJob->iBufferEnd = m_nBuffers; ASSERT(m_nBuffers<MAX_BUFFERS); // Clear the background so the sprite can take its place COLORREF clrBack = pJob->data.plot.clrBack; if( clrBack != CLR_INVALID) { HDC hDC = NULL; Hr = m_p3DBackSurface->GetDC(&hDC); if( FAILED(Hr) ) return false; HBRUSH hBrush = ::CreateSolidBrush(clrBack); ::FillRect(hDC, &rc, hBrush); ::DeleteObject(hBrush); m_p3DBackSurface->ReleaseDC(hDC); } return true; } bool CAnimationSpooler::RenderJob_Flat(const CAnimJobUI* pJob, LPDIRECT3DSURFACE9 /*pSurface*/, DWORD dwTick) { RECT rc = pJob->data.plot.rcFrom; FLOAT mu = (FLOAT)(pJob->dwStartTick + pJob->dwDuration - dwTick) / (FLOAT) pJob->dwDuration; FLOAT scale1 = 0.0; if( pJob->data.plot.iInterpolate == CAnimJobUI::INTERPOLATE_LINEAR ) scale1 = (FLOAT) LinearInterpolate(0.0, 1.0, mu); if( pJob->data.plot.iInterpolate == CAnimJobUI::INTERPOLATE_COS ) scale1 = (FLOAT) CosineInterpolate(0.0, 1.0, mu); FLOAT scale2 = 1.0f - scale1; D3DVECTOR ptCenter = { rc.left + ((rc.right - rc.left) / 2.0f), rc.top + ((rc.bottom - rc.top) / 2.0f) }; FLOAT xtrans = (FLOAT) pJob->data.plot.mFrom.xtrans * scale1; FLOAT ytrans = (FLOAT) pJob->data.plot.mFrom.ytrans * scale1; FLOAT ztrans = 1.0f + ((FLOAT) abs(pJob->data.plot.mFrom.ztrans) * (pJob->data.plot.mFrom.ztrans >= 0.0 ? scale1 : scale2)); FLOAT fSin = (FLOAT) sin(pJob->data.plot.mFrom.zrot * scale1); FLOAT fCos = (FLOAT) cos(pJob->data.plot.mFrom.zrot * scale1); DWORD clrAlpha = ((DWORD)(0xFF - (FLOAT) abs(pJob->data.plot.mFrom.alpha) * (pJob->data.plot.mFrom.alpha >= 0 ? scale1 : scale2)) << 24) | 0xffffff; HRESULT Hr = 0; for( int iBuffer = pJob->iBufferStart; iBuffer < pJob->iBufferEnd; iBuffer++ ) { // Lock the vertex buffer and apply transformation LPDIRECT3DVERTEXBUFFER9 pVBuffer = m_p3DVertices[iBuffer]; LPVOID pVertices = NULL; Hr = pVBuffer->Lock(0, sizeof(CUSTOMFAN), &pVertices, 0); if( FAILED(Hr) ) return false; CUSTOMFAN verts; memcpy(verts, m_fans[iBuffer], sizeof(CUSTOMFAN)); for( int i = 0; i < sizeof(CUSTOMFAN) / sizeof(CUSTOMVERTEX); i++ ) { verts[i].x -= ptCenter.x; verts[i].y -= ptCenter.y; verts[i].x += xtrans; // Translate verts[i].y += ytrans; verts[i].x = verts[i].x * ztrans; // Scale verts[i].y = verts[i].y * ztrans; FLOAT x = verts[i].x; FLOAT y = verts[i].y; // Rotate around Z verts[i].x = x * fCos - y * fSin; verts[i].y = x * fSin + y * fCos; verts[i].x += ptCenter.x; verts[i].y += ptCenter.y; verts[i].color = clrAlpha; } memcpy(pVertices, verts, sizeof(CUSTOMFAN)); pVBuffer->Unlock(); // Paint it Hr = m_p3DDevice->SetStreamSource(0, pVBuffer, 0, sizeof(CUSTOMVERTEX)); Hr = m_p3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX); Hr = m_p3DDevice->SetTexture(0, m_p3DTextures[iBuffer]); Hr = m_p3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2); } return true; }
[ [ [ 1, 494 ] ] ]
de597a46bc848c86e2d9c3d09641064d5bea1baa
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_appsharing/include/CxAppSharingWin.h
9ebe3d1b1cdd5df63909fdc3f1026b7f96f45eca
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
h
/* CxAppSharingWin.h ** ---------- ** Windows only part of CxAppSharing ** ** ** Author : Guilherme Cox <[email protected]> ** Updated: Wed Dec 6 17:25:34 BRST 2006 */ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #include <windows.h> #include <tchar.h> #include "DebugWin.h" #include "resource.h" #pragma once #ifndef __ASCLIENTWIN__ #define __ASCLIENTWIN__ #define SZ_AS_CLASSNAME _T("ASCLIENT") #define SZ_AS_CAPTION _T("Application Sharing - IPTV") #define SZ_MIRROR_DRIVERNAME _T("CxDD Mirror Driver") // DrvEscape defines #define MAP_READ 0x20001 #define MAP_EVENT 0x20004 #define UNMAP_EVENT 0x20008 //#define MAP_RECTACK 0x20010 //#define MAP_TEST 0x20020 #define MAPFILE_SIZE 20000 #define MAP_FILENAME L"CxVideo.dat" /////////////////////////////////////////////////////////////////////////////// // DebugWin class DebugWin; // hInstance extern HINSTANCE g_hInstance; #endif //__ASCLIENTWIN__
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 45 ] ] ]
26036e9647f3b5610ebe7037a61d9cc5426ee276
8aa65aef3daa1a52966b287ffa33a3155e48cc84
/Source/Terrain/Terrain.cpp
aab1d409d6716a877f292fa048ef2dc5c84875b7
[]
no_license
jitrc/p3d
da2e63ef4c52ccb70023d64316cbd473f3bd77d9
b9943c5ee533ddc3a5afa6b92bad15a864e40e1e
refs/heads/master
2020-04-15T09:09:16.192788
2009-06-29T04:45:02
2009-06-29T04:45:02
37,063,569
1
0
null
null
null
null
UTF-8
C++
false
false
14,021
cpp
#include "Includes.h" #include "Terrain.h" namespace P3D { namespace World { Logger Terrain::logger(L"World.Terrain"); int gPatchRebuilds = 0; Terrain::Terrain(World* world) : Entity(world) { _sizeX = 0; _sizeY = 0; _meshStepX = 0; _meshStepY = 0; _map = NULL; _patches = NULL; _patchesSX = _patchesSY = 0; _quadRoot = NULL; _selLeft = _selSizeX = _selDown = _selSizeY = 0; _curSel = NULL; _activeBuffer = NULL; _activeIndexBuffer = NULL; _memoryUsed = 0; _quadNodeCount = 0; _vbTotalSize = 0; //_program = NULL; //ShaderLoader loader; //_program = loader.Load("Shaders/Shader.xml"); } Terrain::~Terrain() { DestroyPatches(); if (_map) free(_map); //if (_program) _program->Release(); } void Terrain::GetVertex(uint x, uint y, TerrainVertex& vertex) const { Vector pos; GetVertexPosition(x, y, pos); vertex.x = pos.x; vertex.y = pos.y; vertex.z = pos.z; vertex.lz = vertex.z; vertex.level = TerrainPatch::LOD_LEVELS; bool xBorder = (x % (TerrainPatch::PATCH_SIZE - 1)) == 0; bool yBorder = (y % (TerrainPatch::PATCH_SIZE - 1)) == 0; vertex.tx = float(x) / _sizeX; vertex.ty = 1.0f - float(y) / _sizeY; int step = (TerrainPatch::PATCH_SIZE - 1) / 2; int level = TerrainPatch::LOD_LEVELS - 1; while (true) { if ((x % step) == 0 && (y % step) == 0) { // found lod where vertex is knot vertex // classify bool sx = (x % (step*2)) == 0; bool sy = (y % (step*2)) == 0; if (!sx && !sy) vertex.lz = (GetVertexZ(x + step, y - step) + GetVertexZ(x - step, y + step))/2; if (sx && !sy) vertex.lz = (GetVertexZ(x, y - step) + GetVertexZ(x, y + step))/2; if (!sx && sy) vertex.lz = (GetVertexZ(x - step, y) + GetVertexZ(x + step, y))/2; if (!sx || !sy) { vertex.level = (float)level; break; } } if (step == 1) break; step = step / 2; level--; } } void Terrain::Load(const wchar* file, int width, int height, float meshStepX, float meshStepY) { logger.info() << L"Loading " << width << L"x" << height << L" terrain from '" << file << L"'..."; // reset stats _memoryUsed = 0; _quadNodeCount = 0; _vbTotalSize = 0; _mapSizeX = width; _mapSizeY = height; _sizeX = ((width - 1) / TerrainPatch::PATCH_SIZE) * TerrainPatch::PATCH_SIZE + 1; _sizeY = ((height - 1) / TerrainPatch::PATCH_SIZE) * TerrainPatch::PATCH_SIZE + 1; _meshStepX = meshStepX; _meshStepY = meshStepY; _centerX = _sizeX * _meshStepX / 2.0f - _meshStepX / 2.0f; _centerY = _sizeY * _meshStepY / 2.0f - _meshStepY / 2.0f; // create and load map { logger.info() << L"Loading height map (" << width * height * sizeof(HeightMapPixel) << L" bytes)..."; _map = (HeightMapPixel*)malloc(width * height * sizeof(HeightMapPixel)); _memoryUsed += width * height * sizeof(HeightMapPixel); FILE* f = _wfopen(file, L"rb"); fread(_map, width*height*sizeof(HeightMapPixel), 1, f); fclose(f); } CreatePatches(); } void Terrain::ReleaseClusters() { for (ClustersIterator i = _clusters.begin(); i != _clusters.end(); i++) { i->second.VB->Release(); i->second.IB->Release(); } _clusters.clear(); } bool Terrain::ShouldMakeNewVB(uint sx, uint sy) const { uint vertexCount = ((sx * (PATCH_SIZE - 1) + 1) * (sy * (PATCH_SIZE - 1) + 1)); return vertexCount < (uint)MAX_VERTICES_IN_VB; } // Allocate new vertex buffer for node with borders specified. Terrain::PatchCluster* Terrain::AllocateNewCluster(int left, int right, int down, int up) { // create VB VertexBuffer* vb = new VertexBuffer(); TerrainVertex::BuildVertexDescription(vb->Element); vb->Initialize((right - left + 1) * (up - down + 1), BUFFER_STATIC); // create IB IndexBuffer* ib = new IndexBuffer(); ib->Element.Size = sizeof(TerrainPatch::IndexType); // create cluster PatchCluster cluster; cluster.Left = left; cluster.Down = down; cluster.SizeX = right - left + 1; cluster.SizeY = up - down + 1; cluster.VB = vb; cluster.IB = ib; cluster.IBSize = 0; // add cluster _clusters[vb] = cluster; SetIndexSelector(vb); // make VB active for index selection BufferUpdater<VertexBuffer, TerrainVertex> v(vb); for (int x = left; x <= right; x++) { for (int y = down; y <= up; y++) { GetVertex(x, y, v[GetVertexIndex(x, y)]); } } _vbTotalSize += (cluster.SizeX * cluster.SizeY) * sizeof(TerrainVertex); return &_clusters[vb]; } void Terrain::CreatePatches() { _patchesSX = _sizeX / (PATCH_SIZE - 1); _patchesSY = _sizeY / (PATCH_SIZE - 1); logger.info() << L"Building " << _patchesSX << L"x" << _patchesSY << L" patch list (" << _patchesSX * _patchesSY * (sizeof(void*) + sizeof(TerrainPatch)) << L" bytes)..."; if (_patchesSX == 0 || _patchesSY == 0) return; // create array of pointers _patches = new TerrainPatch*[_patchesSX * _patchesSY]; _memoryUsed += (sizeof(void*) + sizeof(TerrainPatch)) * _patchesSX * _patchesSY; // create patches for (uint y = 0; y < _patchesSY; y++) { for (uint x = 0; x < _patchesSX; x++) { _patches[y * _patchesSX + x] = new TerrainPatch(this, x * (PATCH_SIZE - 1), y * (PATCH_SIZE - 1)); } } // link patches for (uint y = 0; y < _patchesSY; y++) { for (uint x = 0; x < _patchesSX; x++) { TerrainPatch* cur = _patches[y * _patchesSX + x]; if (x < _patchesSX - 1) cur->_right = _patches[y * _patchesSX + x + 1]; if (x > 0) cur->_left = _patches[y * _patchesSX + x - 1]; if (y < _patchesSY - 1) cur->_down = _patches[(y + 1) * _patchesSX + x]; if (y > 0) cur->_up = _patches[(y - 1) * _patchesSX + x]; } } // link into quad tree logger.info() << L"Building terrain quad tree..."; _quadRoot = BuildQuadTree(0, _patchesSX, 0, _patchesSY, NULL); logger.info() << L"Creating index buffers..."; for (ClustersIterator i = _clusters.begin(); i != _clusters.end(); i++) i->second.IB->Initialize(i->second.IBSize, BUFFER_DYNAMIC); // calculate total AABB logger.info() << L"Calculating bounding boxes..."; _quadRoot->CalculateBoundingBox(); logger.info() << L"Terrain building complete!"; logger.info() << L"Total RAM used : " << _memoryUsed / 1024 << L" Kb."; logger.info() << L"Quad Nodes used: " << _quadNodeCount <<L" (" << _quadNodeCount*sizeof(QuadTreeNode) / 1024 << L" Kb total)."; logger.info() << L"Vertex Buffers used: " << _clusters.size() << L" (" << _vbTotalSize / 1024 << L" Kb total)."; logger.info() << L"Index Buffers used : " << _clusters.size() << L" (" << _patchesSX*_patchesSY*TerrainPatch::MAX_INDICES_COUNT * sizeof(TerrainPatch::IndexType) / 1024 << L" Kb total)."; } void Terrain::DestroyPatches() { if (!_patches) return; // release quad tree if (_quadRoot) _quadRoot->DeleteQuadNode(); _quadRoot = NULL; // delete patches for (uint i = 0; i < _patchesSY * _patchesSX; i++) { delete _patches[i]; } delete[] _patches; _patches = NULL; // release vertex buffers ReleaseClusters(); } QuadTreeNodeBase* Terrain::BuildQuadTree(int left, int right, int down, int up, PatchCluster* cluster) { PatchCluster* newCluster = NULL; if (cluster != NULL) newCluster = cluster; else { int nodeSX = right - left; int nodeSY = up - down; if (ShouldMakeNewVB(nodeSX, nodeSY)) newCluster = AllocateNewCluster(left * (PATCH_SIZE - 1), right * (PATCH_SIZE - 1), down * (PATCH_SIZE - 1), up * (PATCH_SIZE - 1)); } // leaf? if (((left + 1) == right) && ((down + 1)== up)) { ASSERT(newCluster != NULL); TerrainPatch* cur = _patches[down * _patchesSX + left]; cur->VB = newCluster->VB; cur->_indexOffset = newCluster->IBSize; cur->IB = newCluster->IB; newCluster->IBSize += TerrainPatch::MAX_INDICES_COUNT; return cur; } // new node _memoryUsed += sizeof(QuadTreeNode); _quadNodeCount++; QuadTreeNode* node = new QuadTreeNode(); // center... int cx, cy; cx = (left + right) / 2; cy = (down + up) / 2; node->LeftDown = BuildQuadTree(left, max(cx, left+1), down, max(cy, down+1), newCluster); node->LeftUp = BuildQuadTree(left, max(cx, left+1), cy, up, newCluster); node->RightDown = BuildQuadTree(cx, right, down, max(cy, down+1), newCluster); node->RightUp = BuildQuadTree(cx, right, cy, up, newCluster); return node; } void Terrain::RecalculateBoundingBox(AABB& box) { if (_quadRoot) box = _quadRoot->BoundingBox; else box.SetImpossible(); } void Terrain::DoRender(const RendererContext& params) { if (!_patches) return; gPatchRebuilds = 0; // get camera const Camera* camera = GetWorld()->GetActiveCamera(); // get transform from camera space to terrain space QTransform camToWorld = camera->GetTransformToWorldSpace(); QTransform worldToObj = GetTransformToWorldSpace(); worldToObj.Invert(); Transform camToObj(worldToObj * camToWorld); Transform objToCam = camToObj; objToCam.Invert(); _renderer.Render(_quadRoot, *camera, camToObj, objToCam); _activeBuffer = NULL; _activeIndexBuffer = NULL; // calculate errors for (uint i = 0; i < _renderer.VisibleLeafs.size(); ++i) { TerrainPatch* cur = (TerrainPatch*)_renderer.VisibleLeafs[i]; cur->CalculateLOD(camToObj); } // make patches with common side have lods differ no more than by 1 // TODO: optimize! while (true) { int changes = 0; for (uint i = 0; i < _renderer.VisibleLeafs.size(); ++i) { TerrainPatch* cur = (TerrainPatch*)_renderer.VisibleLeafs[i]; changes += cur->NormalizeLOD(); } if (changes <= 0) break; } // rebuild IB for new lod levels for (uint i = 0; i < _renderer.VisibleLeafs.size(); ++i) { TerrainPatch* cur = (TerrainPatch*)_renderer.VisibleLeafs[i]; if (cur->ShouldRebuidIB()) cur->RebuildIndexBuffer(); } //if (_program) _program->Activate(); // render all patches for (uint i = 0; i < _renderer.VisibleLeafs.size(); ++i) { TerrainPatch* cur = (TerrainPatch*)_renderer.VisibleLeafs[i]; cur->Render(); } //if (_program) _program->Deactivate(); if (_activeBuffer) { _activeBuffer->Deactivate(); _activeBuffer = NULL; } if (_activeIndexBuffer) { _activeIndexBuffer->Deactivate(); _activeIndexBuffer = NULL; } } } }
[ "vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1" ]
[ [ [ 1, 392 ] ] ]
1958d443571d225ae2dcb048090d9e798f824c1c
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/oglGameVars.h
5895a613aed1e1031a335c9548f5c8514bd241d1
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
4,095
h
#ifndef OGLGAMEVARS_H #define OGLGAMEVARS_H #include <fstream> #include <cstring> #include <iostream> #include <string> #include <vector> #include <cstring> // doesn't work for some reason on alot of systems //#include "GLFT_Font.h" #include "oglSpriteFont.h" #include "oglTexture2D.h" #define GameVars oglGameVars::Instance() #define imageSize 100 #define entityVisionRadius 15 using namespace std; //=========================== // oglGameVars // This class is based on // the singleton design pattern // popularized in the GoF book: // "Design Patterns". // - CJV enum entityType{RED, BLUE, GOD}; enum marbleUI // enumerator for the cases where the user selects a piece { MUI_NULL, // nothing to draw here, move along MUI_SELECTED, // user selected a piece, show it MUI_POSSIBILITY // user selected a piece, where can they put it? }; class oglGameVars { public: static oglGameVars* Instance(); protected: oglGameVars(); oglGameVars(const oglGameVars&); oglGameVars& operator= (const oglGameVars&); private: static oglGameVars* pinstance; //=============================================== // Non singleton functions and data members here //=============================================== public: void parseMeIntoRows(vector<std::string*> *storageContainer, std::string stringToParse, int numCharsPerRow, bool autoFeed = true); void loadFonts(); void init(); oglSpriteFont fontArial32; oglSpriteFont fontArial24; oglSpriteFont fontArial18; oglSpriteFont fontArial16; oglSpriteFont fontArial12; oglSpriteFont fontDigital64; oglSpriteFont fontOurs; oglSpriteFont fontDigital200; oglSpriteFont fontDigital32; oglSpriteFont fontDigital16; oglSpriteFont fontDigital12; oglSpriteFont fontArialRed12; oglSpriteFont fontArialRed14; oglTexture2D* bacardi; //======================= // Marble Game oglTexture2D* emptyImage; // no marble at this position oglTexture2D* marbleImage; // marble occupying the space oglTexture2D* selectedImage; // user selected a marble to move oglTexture2D* possibilityImage; // highlight empty spaces that the user can move to oglTexture2D* boardImage; // the board we're playing on oglTexture2D* hintButton; // image to display the hint button oglTexture2D* undoButton; // image to display the undo button oglTexture2D* resetButton; // image to display the reset button //======================= // RockPaperScissors Game oglTexture2D* RPSBG; // background for RPS game oglTexture2D* RPSRock; // rock image oglTexture2D* RPSPaper; // paper image oglTexture2D* RPSScissors; // scissors image oglTexture2D* playerWins; oglTexture2D* cpuWins; oglTexture2D* tieHand; //======================= // RedvBlue Game oglTexture2D* rvbTile; oglTexture2D* rvbObstacle; oglTexture2D* rvbNullTile; oglTexture2D* rvbBlackTile; oglTexture2D* rvbEntityArrow; oglTexture2D* rvbEntityBlue; oglTexture2D* rvbEntityBlueN; oglTexture2D* rvbEntityRed; oglTexture2D* rvbEntityRedN; oglTexture2D* rvbEntitySelected; oglTexture2D* rvbEntityTarget; oglTexture2D* rvbSelectionPix; oglTexture2D* rvbHeyYouWithTheFace; oglTexture2D* redPathImg; oglTexture2D* bluePathImg; oglTexture2D* redActive; oglTexture2D* blueActive; oglTexture2D* godActive; oglTexture2D* fog; oglTexture2D* redPixel; oglTexture2D* greenPixel; oglTexture2D* yellowPixel; oglTexture2D* healthBorder; oglTexture2D* deadIcon; oglTexture2D* pistolShotImg; oglTexture2D* riffleShotImg; oglTexture2D* shottyShotImg; oglTexture2D* helpScreen; oglTexture2D* helpButton; double getDistanceToTarget(double xPos, double yPos, double targetXPos, double targetYPos); double dAbs(double something); entityType mySide; private: }; #endif // OGLGAMEVARS_H
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241", "davidbmoss@5457d560-9b84-11de-b17c-2fd642447241", "DavidBMoss@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 16 ], [ 19, 28 ], [ 30, 110 ], [ 112, 114 ], [ 127, 128 ], [ 134, 134 ], [ 138, 143 ] ], [ [ 17, 17 ], [ 136, 136 ] ], [ [ 18, 18 ], [ 29, 29 ], [ 111, 111 ], [ 115, 126 ], [ 129, 133 ], [ 135, 135 ], [ 137, 137 ] ] ]
c68352c1c911d9958b4ecd9c832c434499517818
0f7af923b9d3a833f70dd5ab6f9927536ac8e31c
/ elistestserver/MyListCtrl.cpp
4b9791ac2d1a580305007979e8ba49f1f5a0d3f7
[]
no_license
empiredan/elistestserver
c422079f860f166dd3fcda3ced5240d24efbd954
cfc665293731de94ff308697f43c179a4a2fc2bb
refs/heads/master
2016-08-06T07:24:59.046295
2010-01-25T16:40:32
2010-01-25T16:40:32
32,509,805
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
// MyListCtrl.cpp : implementation file // #include "stdafx.h" #include "ELISTestServer.h" #include "MyListCtrl.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // MyListCtrl MyListCtrl::MyListCtrl() { } MyListCtrl::~MyListCtrl() { } BEGIN_MESSAGE_MAP(MyListCtrl, CListCtrl) //{{AFX_MSG_MAP(MyListCtrl) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // MyListCtrl message handlers /* void MyListCtrl::OnPaint() { CRect r; int n,n0,n1; CListCtrl::OnPaint(); n0=GetTopIndex(); n1=GetCountPerPage(); n1+=n0; CDC*dc=GetDC();//Don't use the CPaintDC for(n=n0;n!=n1;n++) { if(GetItemState(n,LVIS_SELECTED)!=LVIS_SELECTED) continue; GetItemRect(n,&r,LVIR_BOUNDS); r.InflateRect(-2,0); dc->SelectStockObject(HOLLOW_BRUSH); dc->Rectangle(&r); } } */
[ "EmpireDaniel@3065b396-e208-11de-81d3-db62269da9c1" ]
[ [ [ 1, 53 ] ] ]
935ad5c076f044b5877a297d25443132b5e49c52
5e8bab6db6ed2cdc1c12ccb5c6e9f27f5adf4904
/c++/src/iaas_functions/imagetools.h
d8492835e6c503c0f0dc70136b8a3d86da0683ec
[]
no_license
lucacavazzana/iaasfog
bcfe1f9fc6857aaf1b040e13f1ffa2325f8e33bf
801c710c568d2b9bcfe14e3dd34b6edee5dbccb4
refs/heads/master
2021-03-12T23:56:28.435433
2011-06-12T17:40:32
2011-06-12T17:40:32
40,448,028
0
0
null
null
null
null
UTF-8
C++
false
false
9,184
h
#ifndef _IMAGETOOLS_H_ #define _IMAGETOOLS_H_ /** * @file imagetools.h * @date Feb 04, 2009 * @author Alessandro Stranieri * * Functions mainly use to perform different operations on images. * They implement algorithms to compute images transformation, perform projective geometry computations * and retrieve set of values. */ /** * Returns the distance between two points * * @param point1 First point * @param point2 Second point * @return The distance */ template <class P> double iaasTwoPointsDistance(P point1, P point2) { double x1 = point1.x; double x2 = point2.x; double y1 = point1.y; double y2 = point2.y; return sqrt(iaasSquare<double>(y2 - y1) + iaasSquare<double>(x2 - x1)); } CvPoint2D32f iaasPointAlongLine(CvMat *line, CvPoint2D32f firstPoint, CvPoint2D32f lastPoint, float pixelDistance); /** * Returns the angle between two lines * * @param line1 First line * @param line2 Second line * @return The angle */ double iaasTwoLinesAngle(CvMat* line1, CvMat* line2); void iaasDrawFlowFeature(IplImage* image, featureMovement &feat); /** * Returns the distance between a point and a line * * @param line A line * @param point A point * @return The distance */ template <class P> double iaasPointLineDistance(CvMat* line, P point) { double a, b, c, d, *data, x, y; data = line->data.db; a = data[0]; b = data[1]; c = data[2]; x = point.x; y = point.y; d = fabs(a * x + b * y + c) / sqrt(iaasSquare<double>(a) + iaasSquare<double>(b)); return d; } template <class P> double iaasMahalanobisPointLineDistance(CvMat* line, P point) { double result = 0; double* buf = new double[4]; double* buf2 = new double[4]; const CvArr *tempArray[2]; tempArray[0]=line; tempArray[1]=line; CvMat covMatrix = cvMat(2, 2, CV_64FC1, buf); CvMat covMean = cvMat(2, 2, CV_64FC1, buf2); printf("LOL\n"); fflush(stdout); cvCalcCovarMatrix(tempArray, 2, &covMatrix, &covMean, CV_COVAR_SCALE); printf("Matrix: %f \n", covMatrix.data.db[0]); fflush(stdout); cvInvert(&covMatrix, &covMatrix, CV_SVD); printf("LOL\n"); fflush(stdout); double* data = new double[3]; data[0] = point.x; data[1] = point.y; data[2] = 1; CvMat pointHom = cvMat(3, 1, CV_64FC1, data); printf("LOL\n"); fflush(stdout); result = cvMahalonobis(&pointHom, line, &covMatrix); printf("Result: %f", result);fflush(stdout); return result; } /** * Compute the parameters of a line joining two points * * @param p1 First point * @param p2 Second point * @param joinLine The joining line */ void iaasJoiningLine(CvPoint2D32f p1, CvPoint2D32f p2, CvMat* joinLine); /** * Compute the parameters of a line fitting two or more points * * @param list array of points to be fitted * @param nPoints number of points in list * @param joinLine pointer to the best line found * @return The intersection point */ void iaasBestJoiningLine(CvPoint2D32f *list, int nPoints, CvMat* joinLine); /** * Returns the point where the two lines intersects * * @post If intersection point is at infinity, (-1,-1) is returned * * @param line1 First line * @param line2 Second line * @return The intersection point */ CvPoint2D32f iaasIntersectionPoint(CvMat *line1, CvMat *line2); /** * Returns the point nearest to ppoint and laying on line joining point1 and point2 * @param point1 first point to generate line * @param point2 second point to generate line * @param ppoint point to project over line * @return The new point found */ CvPoint2D32f iaasProjectPointToLine(CvPoint2D32f point1, CvPoint2D32f point2, CvPoint2D32f ppoint); /** * Returns the point nearest to oldPoint and laying on line * @param oldPoint point to project over line * @param line parameters of line * @return The new point found */ CvPoint2D32f iaasProjectPointToLine(CvPoint2D32f oldPoint, CvMat *line); /** * Computes and return the centroid of a set points * * @param points Array of points * @param point_count Number of points * @return The Centroid */ template <class P> CvPoint2D32f iaasCentroid(P *points, int num_points){ double xC, yC; CvPoint2D32f point; int sum = 0; xC = yC = 0.0; for(int i = 0; i < num_points; i++){ if(!(points[i].x == -1 && points[i].y == -1)){ xC += points[i].x; yC += points[i].y; sum++; } } xC = xC/sum; yC = yC/sum; point = cvPoint2D32f(xC, yC); return point; } /** * Returns true if the point is in Field of View * * @param point Point to check * @param offset Optional offset from border * @return True if point is in Field of View of image */ template <typename T>bool iaasPointIsInFOV(const T point, int offset=0); /** * Returns true if the corner tracked in two frames is * getting coherently farer from the vanishing point. * * @param p Point in the first frame * @param q Point in the second frame * @param vp Vanishing point * @return True is movement is coherent with vanishing point position */ template <class P> bool iaasIsMotionCoherent(P p, P q, P vp){ //Points on the same Y of vanishing point if (p.y == vp.y) { if (q.y == vp.y) { if (p.x > vp.x) { if (q.x > p.x) { return true; } } else if (p.x < vp.x) { if (q.x < p.x) { return true; } } } } //Points on the same X of vanishing point if (p.x == vp.x) { if (q.x == vp.x) { if (p.y > vp.y) { if (q.y > p.y) { return true; } } else if (p.y < vp.y) { if (q.y < p.y) { return true; } } } } //Points under vanishing point if (p.y > vp.y) { if (q.y > p.y) { if (p.x > vp.x) { if (q.x > p.x) return true; } else if (p.x < vp.x) { if (q.x < p.x) return true; } } } //Points over vanishing point if (p.y < vp.y) { if (q.y < p.y) { if (p.x > vp.x) { if (q.x > p.x) return true; } else if (p.x < vp.x) { if (q.x < p.x) return true; } } } return false; } /** * Draws a line on the image. * Given the line parameters, if visible draws the line on the image. * @param image * @param line */ void iaasDrawStraightLine(IplImage* image, CvMat* line); /** * Draws the flow field on an image. * Given two arrays of coordinates of the same corners tracked in two images, it draws the vectors connecting the points. * * @param image The image to draw on * @param cornersA Points in the first image * @param cornersB Points in the second image * @param corners_count Number of points * @param track_status Tracked/not tracked flags array * @param color Color of the vectors(default RED) * @param f_line Flag: true to draw the line joining two points */ void iaasDrawFlowField(IplImage* image, CvPoint2D32f *cornersA, CvPoint2D32f *cornersB, int corners_count, char *track_status, CvScalar color = CV_RGB(255,0,0), bool f_line = false); void iaasDrawFlowFieldNew(IplImage* image, list<featureMovement> listFeatures, CvScalar color, bool f_line=false); void drawFeatures(IplImage *image, CvPoint2D32f *points, int size); /** * Draw ROI on image. Useful for debugging purposes. * * @param image * @param color */ void iaasDrawROI(IplImage* image, CvScalar color=CV_RGB(0,0,0)); void iaasCoordinates2DToHom(CvPoint* point, CvMat* array); void iaasCoordinatesHomTo2D(CvMat* array, CvPoint* point); /** * Given an image and a set of points, fills an array with the lowest eigenvalues of the auto-correlation * matrix of the derivative image at those points. * * @param image A grey-scale image, must be single channel * @param corners A set of points * @param track_status Tracked/Not tracked flag array * @param n_points Number of points * @param values On returns contains the eigenvalues */ void iaasGetACMinEigVals(IplImage *image, CvPoint2D32f *corners, char *track_status, int n_points, float *values); /** * Given an image and a set of points, fills an array with the grey values of the image at those points. * * @param image A grey-scale image * @param corners A set of points * @param track_status Tracked/Not tracked flag array * @param n_points Number of points * @param values On returns contains grey values */ void iaasGetGreyValues(IplImage *image, CvPoint2D32f *corners, char *track_status, int n_points, float *values); /** * If the input images have the same height, attach them and returns * the resulting image. * * @pre image0 and image1 must have same height * @param image0 First image * @param image1 Image to attach * @return The two images attached */ IplImage* iaasAddImage(IplImage *image0, IplImage *image1); /** * This method is used to display the Mean time to impact. * It add a black stripe at the bottom of the input image and writes the * given value. Returns the actual image to display. * * @param image An image * @param tti The mean time to impact * @return The image to display */ IplImage* iaasAddTTIDisplay(IplImage *image, double tti); #endif //_IMAGETOOLS_H_
[ [ [ 1, 324 ] ] ]
bee5cf5248f394f6d5231da618a097538be6648a
2b32433353652d705e5558e7c2d5de8b9fbf8fc3
/Kurs/SERG9321/TASK09.CPP
1fa55b614e76724cb7d6a54bfcf99a3c6571f48c
[]
no_license
smarthaert/d-edit
70865143db2946dd29a4ff52cb36e85d18965be3
41d069236748c6e77a5a457280846a300d38e080
refs/heads/master
2020-04-23T12:21:51.180517
2011-01-30T00:37:18
2011-01-30T00:37:18
35,532,200
0
0
null
null
null
null
IBM866
C++
false
false
2,900
cpp
// Задан линейный односвязный список, каждый элемент которого // (В информационной части) содержит указатель на строку. // Необходимо написать программу, удаляющую из списка все узлы, // которым соответствуют строки, // содержащие введенный с клавиатуры символ. #include <stdio.h> #include <conio.h> // ---=== Линейный односвязный список ===--- struct StrList { char *Data; StrList *Next; }; // ---=== Список ===--- StrList *Root = NULL; // ---=== Добавление нового элемента в конец списка ===--- void AddEnd( char *Str ) { StrList *Current,*Buffer; // - Заведение нового элемента - // Buffer = new StrList; Buffer->Data = Str; Buffer->Next = NULL; // - Присоединение элемента к существующему списку - if (Root!=NULL) { Current = Root; while (Current->Next != NULL) Current = Current->Next; Current->Next = Buffer; } else Root = Buffer; } // ---=== Удаление всего списка ===--- void DelAll() { StrList *Buffer; // Пока в списке остались элементы while (Root!=NULL) { // Удаляем первый элемент Buffer = Root; Root = Root->Next; delete Buffer; }; }; // ---=== Удаление элементов содержащих символ Symbol ===--- void Del_Sym( char Symbol ) { StrList *Current = Root,*Buffer = NULL; char *Str; int i; printf("Удаляем все строки содержащие '%c'\n",Symbol); // - Ищем нужный нам элемент - while (Current!=NULL) { Str = Current->Data; for(i = 0;Str[i]!=0 && Str[i]!=Symbol;i++); // - И удаляем его ... - if (Str[i]==Symbol) { if (Buffer==NULL) { Root = Current->Next; } else Buffer->Next = Current->Next; delete Current; Current = Buffer; } Buffer = Current; Current = Current->Next; } }; // ---=== Просмотр всего списка (поэлементно) ===--- void Show() { StrList *Current = Root; printf("---=== Выводим список на экран ===---\n"); while (Current!=NULL) { printf("%s\n",Current->Data); Current = Current->Next; } }; // ---=== Основная программа ===--- void main() { AddEnd("ABC"); AddEnd("DEF"); AddEnd("GHI"); AddEnd("TEST"); Show(); printf("Введите символ !\n"); char C = getch(); Del_Sym(C); Show(); DelAll(); };
[ [ [ 1, 104 ] ] ]
ec0826815426785f68837e1b3ac92a9eefb946f0
38794c3c38c9c9abfd7206ad353aaae0c0b33f18
/Trab1_a_Inicial/Printer.cpp
2c63d10c54b7eebd3bc5b021088618b05115ef4a
[]
no_license
Highvolt/laig-part1
37e765cb2705b206c36f987e255ab453abf00dfb
0e07a6fc2c086f49131907767c463d298ff72b1f
refs/heads/master
2021-01-10T20:26:08.520711
2011-09-21T11:29:09
2011-09-21T11:29:09
32,182,761
0
0
null
null
null
null
UTF-8
C++
false
false
91
cpp
#include "Printer.h" Printer::Printer(void) { } Printer::~Printer(void) { }
[ [ [ 1, 11 ] ] ]
fdceeca9f9c544c12eb8ea61d58da4e6782257bd
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/SettingsSaver.cpp
e38fa4def96fa79b71e5c90982b6d06a7e241c4e
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
11,481
cpp
//this file is part of eMule //Copyright (C)2002 Merkur ( [email protected] / 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 "SettingsSaver.h" #include "PartFile.h" #include "emule.h" #include "Preferences.h" // for thePrefs #include "emuledlg.h" // for theApp.emuledlg #include "log.h" // for log #include "Ini2.h" #include "DownloadQueue.h" /* This class has been rewritten by Stulle */ CSettingsSaver::CSettingsSaver(void){} CSettingsSaver::~CSettingsSaver(void){} void CSettingsSaver::LoadSettings() { CPartFile* cur_file ; int iTryImport = 0; // 0 = no; 1 = import; 2 = delete CString IniFilePath; IniFilePath.Format(L"%sFileSettings.ini", thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); CIni ini(IniFilePath); CString OldFilePath; OldFilePath.Format(_T("%s\\%s\\"), thePrefs.GetTempDir(), _T("Extra Lists")); if(!PathFileExists(IniFilePath)) iTryImport = 1; else if(PathFileExists(OldFilePath)) // we assume if the default contains this all else do. iTryImport = 2; for (POSITION pos = theApp.downloadqueue->filelist.GetHeadPosition();pos != 0;){ cur_file = theApp.downloadqueue->filelist.GetNext(pos); if(iTryImport == 1) { ImportOldSettings(cur_file); continue; // next item } else if(iTryImport == 2) { DeleteOldSettings(cur_file); } ini.SetSection(cur_file->GetPartMetFileName()); cur_file->SetEnableAutoDropNNS(ini.GetBool(L"NNS",thePrefs.GetEnableAutoDropNNSDefault())); cur_file->SetAutoNNS_Timer(ini.GetInt(L"NNSTimer",thePrefs.GetAutoNNS_TimerDefault())); cur_file->SetMaxRemoveNNSLimit((uint16)ini.GetInt(L"NNSLimit",thePrefs.GetMaxRemoveNNSLimitDefault())); cur_file->SetEnableAutoDropFQS(ini.GetBool(L"FQS",thePrefs.GetEnableAutoDropFQSDefault())); cur_file->SetAutoFQS_Timer(ini.GetInt(L"FQSTimer",thePrefs.GetAutoFQS_TimerDefault())); cur_file->SetMaxRemoveFQSLimit((uint16)ini.GetInt(L"FQSLimit",thePrefs.GetMaxRemoveFQSLimitDefault())); cur_file->SetEnableAutoDropQRS(ini.GetBool(L"QRS",thePrefs.GetEnableAutoDropQRSDefault())); cur_file->SetAutoHQRS_Timer(ini.GetInt(L"QRSTimer",thePrefs.GetAutoHQRS_TimerDefault())); cur_file->SetMaxRemoveQRS((uint16)ini.GetInt(L"MaxQRS",thePrefs.GetMaxRemoveQRSDefault())); cur_file->SetMaxRemoveQRSLimit((uint16)ini.GetInt(L"QRSLimit",thePrefs.GetMaxRemoveQRSLimitDefault())); cur_file->SetGlobalHL(ini.GetBool(L"GlobalHL",thePrefs.GetGlobalHlDefault())); cur_file->SetHQRXman(ini.GetBool(L"XmanHQR",thePrefs.GetHQRXmanDefault())); cur_file->SetFollowTheMajority(ini.GetInt(L"FTM",-1)); } if(iTryImport > 0) { for (int i=0;i<thePrefs.tempdir.GetCount();i++) { CString sSivkaFileSettingsPath = CString(thePrefs.GetTempDir(i)) + _T("\\") + SIVKAFOLDER; if (PathFileExists(sSivkaFileSettingsPath.GetBuffer()) && !::RemoveDirectory(sSivkaFileSettingsPath.GetBuffer())) { CString strError; strError.Format(_T("Failed to delete sivka extra lists directory \"%s\" - %s"), sSivkaFileSettingsPath, GetErrorMessage(GetLastError())); AfxMessageBox(strError, MB_ICONERROR); } } } } bool CSettingsSaver::SaveSettings() { CPartFile* cur_file ; bool bAborted = false; CString strFileSettingsIniFilePath; strFileSettingsIniFilePath.Format(L"%sFileSettings.ini", thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); (void)_tremove(strFileSettingsIniFilePath); if(theApp.downloadqueue->filelist.GetCount()<=0) // nothing to save here return true; // everything's fine CStdioFile ini; CString buffer; if(ini.Open(strFileSettingsIniFilePath,CFile::modeCreate | CFile::modeWrite | CFile::shareExclusive | CFile::typeText)) { ini.WriteString(_T("[General]\r\n")); buffer.Format(_T("FileSettingsVersion=%i\r\n"),1); ini.WriteString(buffer); for (POSITION pos = theApp.downloadqueue->filelist.GetHeadPosition();pos != 0;){ cur_file = theApp.downloadqueue->filelist.GetNext(pos); if(!cur_file) // NULL-pointer? we deleted the file, break { AddDebugLogLine(false,_T("CSettingsSaver cur_file == NULL? wtf?!")); bAborted = true; break; } try // i just hope we don't need this { buffer.Format(_T("[%s]\r\n"),cur_file->GetPartMetFileName()); ini.WriteString(buffer); buffer.Format(_T("NNS=%i\r\n"),cur_file->GetEnableAutoDropNNS()?1:0); ini.WriteString(buffer); buffer.Format(_T("NNSTimer=%u\r\n"),cur_file->GetAutoNNS_Timer()); ini.WriteString(buffer); buffer.Format(_T("NNSLimit=%u\r\n"),cur_file->GetMaxRemoveNNSLimit()); ini.WriteString(buffer); buffer.Format(_T("FQS=%i\r\n"),cur_file->GetEnableAutoDropFQS()?1:0); ini.WriteString(buffer); buffer.Format(_T("FQSTimer=%u\r\n"),cur_file->GetAutoFQS_Timer()); ini.WriteString(buffer); buffer.Format(_T("FQSLimit=%u\r\n"),cur_file->GetMaxRemoveFQSLimit()); ini.WriteString(buffer); buffer.Format(_T("QRS=%i\r\n"),cur_file->GetEnableAutoDropQRS()?1:0); ini.WriteString(buffer); buffer.Format(_T("QRSTimer=%u\r\n"),cur_file->GetAutoHQRS_Timer()); ini.WriteString(buffer); buffer.Format(_T("MaxQRS=%u\r\n"),cur_file->GetMaxRemoveQRS()); ini.WriteString(buffer); buffer.Format(_T("QRSLimit=%u\n"),cur_file->GetMaxRemoveQRSLimit()); ini.WriteString(buffer); buffer.Format(_T("GlobalHL=%i\r\n"),cur_file->GetGlobalHL()?1:0); ini.WriteString(buffer); buffer.Format(_T("XmanHQR=%i\r\n"),cur_file->GetHQRXman()?1:0); ini.WriteString(buffer); buffer.Format(_T("FTM=%i\r\n"),cur_file->GetFollowTheMajority()); ini.WriteString(buffer); } catch(...) // and if we do we break and log { bAborted = true; AddDebugLogLine(true,_T("We had to catch an error in SettingsSaver::SaveSettings()! Report this please!")); break; } } ini.Close(); } else bAborted = true; return !bAborted; // report if we had to abort, this is no good } /* IMPORT OLD */ #pragma warning(disable:4296) // expression is always true void CSettingsSaver::ImportOldSettings(CPartFile* file) { SettingsList daten; CString datafilepath; datafilepath.Format(_T("%s\\%s\\%s.sivka"), file->GetTempPath(), _T("Extra Lists"), file->GetPartMetFileName()); CString strLine; CStdioFile f; if (!f.Open(datafilepath, CFile::modeReadWrite | CFile::typeText)) return; while(f.ReadString(strLine)) { if (strLine.GetAt(0) == _T('#')) continue; int pos = strLine.Find(_T('\n')); if (pos == -1) continue; CString strData = strLine.Left(pos); CSettingsData* newdata = new CSettingsData(_tstol(strData)); daten.AddTail(newdata); } f.Close(); POSITION pos = daten.GetHeadPosition(); if(!pos) return; if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1) { file->SetEnableAutoDropNNS((((CSettingsData*)daten.GetAt(pos))->dwData)!=0); } else file->SetEnableAutoDropNNS(thePrefs.GetEnableAutoDropNNSDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 0 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 60000) file->SetAutoNNS_Timer(((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetAutoNNS_Timer(thePrefs.GetAutoNNS_TimerDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 50 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 100) file->SetMaxRemoveNNSLimit((uint16)((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetMaxRemoveNNSLimit(thePrefs.GetMaxRemoveNNSLimitDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1) { file->SetEnableAutoDropFQS((((CSettingsData*)daten.GetAt(pos))->dwData)!=0); } else file->SetEnableAutoDropFQS(thePrefs.GetEnableAutoDropFQSDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 0 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 60000) file->SetAutoFQS_Timer(((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetAutoFQS_Timer(thePrefs.GetAutoFQS_TimerDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 50 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 100) file->SetMaxRemoveFQSLimit((uint16)((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetMaxRemoveFQSLimit(thePrefs.GetMaxRemoveFQSLimitDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1) { file->SetEnableAutoDropQRS((((CSettingsData*)daten.GetAt(pos))->dwData)!=0); } else file->SetEnableAutoDropQRS(thePrefs.GetEnableAutoDropQRSDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 0 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 60000) file->SetAutoHQRS_Timer(((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetAutoHQRS_Timer(thePrefs.GetAutoHQRS_TimerDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 1000 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 10000) file->SetMaxRemoveQRS((uint16)((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetMaxRemoveQRS(thePrefs.GetMaxRemoveQRSDefault()); daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 50 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 100) file->SetMaxRemoveQRSLimit((uint16)((CSettingsData*)daten.GetAt(pos))->dwData); else file->SetMaxRemoveQRSLimit(thePrefs.GetMaxRemoveQRSLimitDefault()); if(daten.GetCount() > 10) // emulate StulleMule <= v2.2 files { // ==> Global Source Limit (customize for files) - Stulle daten.GetNext(pos); if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1) { file->SetGlobalHL((((CSettingsData*)daten.GetAt(pos))->dwData)!=0); } else file->SetGlobalHL(thePrefs.GetGlobalHlDefault()); // <== Global Source Limit (customize for files) - Stulle } else file->SetGlobalHL(thePrefs.GetGlobalHlDefault()); while (!daten.IsEmpty()) delete daten.RemoveHead(); if (_tremove(datafilepath)) if (errno != ENOENT) AddLogLine(true, _T("Failed to delete %s, you will need to do this manually"), datafilepath); } #pragma warning(default:4296) // expression is always true void CSettingsSaver::DeleteOldSettings(CPartFile* file) { CString datafilepath; datafilepath.Format(_T("%s\\%s\\%s.sivka"), file->GetTempPath(), _T("Extra Lists"), file->GetPartMetFileName()); if (_tremove(datafilepath)) if (errno != ENOENT) AddLogLine(true, _T("Failed to delete %s, you will need to do this manually"), datafilepath); }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 298 ] ] ]
f1705a61af4991dd8238b8016bb42df59e26af3b
e308022538f7dff783343789e3b17499e793ac86
/src/darken.cpp
e2fb07d5cf9199e1319603c4200f64932dbac11e
[]
no_license
bremarv/opencl_homework
a9f22f6a68f477f3688133a690b1f63272c8f7f5
0177ec634b4962877a8513752f292da0e1c49550
refs/heads/master
2020-04-20T08:17:23.796881
2010-06-03T16:38:09
2010-06-03T16:38:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
483
cpp
#include <stdexcept> #include <iostream> #include "DarkenManager.h" #include "GL/freeglut.h" DarkenManager manager; void render() { manager.render(); glutSwapBuffers(); } void idle() { glutPostRedisplay(); } int main(int argc, char **argv) { try { manager.init(argc, argv); glutDisplayFunc(render); glutIdleFunc(idle); glutMainLoop(); } catch (std::exception &e) { std::string err = e.what(); std::cout << err.c_str() << std::endl; } return 0; }
[ [ [ 1, 37 ] ] ]
85fb1765779ccfd15db1616b1598e20dee847f82
8b68ff41fd39c9cf20d27922bb9f8b9d2a1c68e9
/TWL/include/wnd.h
03133ec1e3e32ff4a80d9499bb45941e596d723e
[]
no_license
dandycheung/dandy-twl
2ec6d500273b3cb7dd6ab9e5a3412740d73219ae
991220b02f31e4ec82760ece9cd974103c7f9213
refs/heads/master
2020-12-24T15:06:06.260650
2009-05-20T14:46:07
2009-05-20T14:46:07
32,625,192
0
0
null
null
null
null
UTF-8
C++
false
false
42,176
h
////////////////////////////////////////////////////////////////////////// // This is a part of the Tiny Window Library(TWL). // Copyright (C) 2003-2005 Dandy Cheung // [email protected] // All rights reserved. // #ifndef __WND_H__ #define __WND_H__ #pragma once #ifndef __cplusplus #error TWL requires C++ compilation (use a .cpp suffix) #endif #include <windows.h> #include <tchar.h> #include "modutil.h" #include "trcdbg.h" namespace TWL { class CWindow { public: static RECT rcDefault; HWND m_hWnd; CWindow(HWND hWnd = NULL) { m_hWnd = hWnd; } CWindow& operator=(HWND hWnd) { m_hWnd = hWnd; return *this; } static LPCTSTR GetWndClassName() { return NULL; } void Attach(HWND hWndNew) { ASSERT(::IsWindow(hWndNew)); m_hWnd = hWndNew; } HWND Detach() { HWND hWnd = m_hWnd; m_hWnd = NULL; return hWnd; } HWND Create(LPCTSTR lpstrWndClass, HWND hWndParent, RECT& rcPos, LPCTSTR szWindowName = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, UINT nID = 0, LPVOID lpCreateParam = NULL, HINSTANCE hInstance = GetModuleInstance()) { m_hWnd = ::CreateWindowEx(dwExStyle, lpstrWndClass, szWindowName, dwStyle, rcPos.left, rcPos.top, rcPos.right - rcPos.left, rcPos.bottom - rcPos.top, hWndParent, (HMENU)nID, hInstance, lpCreateParam); return m_hWnd; } HWND Create(LPCTSTR lpstrWndClass, HWND hWndParent, LPRECT lpRect = NULL, LPCTSTR szWindowName = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, HMENU hMenu = NULL, LPVOID lpCreateParam = NULL, HINSTANCE hInstance = GetModuleInstance()) { if(lpRect == NULL) lpRect = &rcDefault; m_hWnd = ::CreateWindowEx(dwExStyle, lpstrWndClass, szWindowName, dwStyle, lpRect->left, lpRect->top, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, hWndParent, hMenu, hInstance, lpCreateParam); return m_hWnd; } BOOL DestroyWindow() { ASSERT(::IsWindow(m_hWnd)); if(!::DestroyWindow(m_hWnd)) return FALSE; m_hWnd = NULL; return TRUE; } // Attributes operator HWND() const { return m_hWnd; } DWORD GetStyle() const { ASSERT(::IsWindow(m_hWnd)); return (DWORD)::GetWindowLong(m_hWnd, GWL_STYLE); } DWORD GetExStyle() const { ASSERT(::IsWindow(m_hWnd)); return (DWORD)::GetWindowLong(m_hWnd, GWL_EXSTYLE); } LONG GetWindowLong(int nIndex) const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowLong(m_hWnd, nIndex); } LONG SetWindowLong(int nIndex, LONG dwNewLong) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowLong(m_hWnd, nIndex, dwNewLong); } WORD GetWindowWord(int nIndex) const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowWord(m_hWnd, nIndex); } WORD SetWindowWord(int nIndex, WORD wNewWord) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowWord(m_hWnd, nIndex, wNewWord); } // Message Functions LRESULT SendMessage(UINT message, WPARAM wParam = 0, LPARAM lParam = 0) { ASSERT(::IsWindow(m_hWnd)); return ::SendMessage(m_hWnd,message,wParam,lParam); } BOOL PostMessage(UINT message, WPARAM wParam = 0, LPARAM lParam = 0) { ASSERT(::IsWindow(m_hWnd)); return ::PostMessage(m_hWnd,message,wParam,lParam); } BOOL SendNotifyMessage(UINT message, WPARAM wParam = 0, LPARAM lParam = 0) { ASSERT(::IsWindow(m_hWnd)); return ::SendNotifyMessage(m_hWnd, message, wParam, lParam); } // support for C style macros static LRESULT SendMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { ASSERT(::IsWindow(hWnd)); return ::SendMessage(hWnd, message, wParam, lParam); } // Window Text Functions BOOL SetWindowText(LPCTSTR lpszString) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowText(m_hWnd, lpszString); } int GetWindowText(LPTSTR lpszStringBuf, int nMaxCount) const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowText(m_hWnd, lpszStringBuf, nMaxCount); } int GetWindowTextLength() const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowTextLength(m_hWnd); } // Font Functions void SetFont(HFONT hFont, BOOL bRedraw = TRUE) { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_SETFONT, (WPARAM)hFont, MAKELPARAM(bRedraw, 0)); } HFONT GetFont() const { ASSERT(::IsWindow(m_hWnd)); return (HFONT)::SendMessage(m_hWnd, WM_GETFONT, 0, 0); } // Menu Functions (non-child windows only) HMENU GetMenu() const { ASSERT(::IsWindow(m_hWnd)); return ::GetMenu(m_hWnd); } BOOL SetMenu(HMENU hMenu) { ASSERT(::IsWindow(m_hWnd)); return ::SetMenu(m_hWnd, hMenu); } BOOL DrawMenuBar() { ASSERT(::IsWindow(m_hWnd)); return ::DrawMenuBar(m_hWnd); } HMENU GetSystemMenu(BOOL bRevert) const { ASSERT(::IsWindow(m_hWnd)); return ::GetSystemMenu(m_hWnd, bRevert); } BOOL HiliteMenuItem(HMENU hMenu, UINT uItemHilite, UINT uHilite) { ASSERT(::IsWindow(m_hWnd)); return ::HiliteMenuItem(m_hWnd, hMenu, uItemHilite, uHilite); } // Window Size and Position Functions BOOL IsIconic() const { ASSERT(::IsWindow(m_hWnd)); return ::IsIconic(m_hWnd); } BOOL IsZoomed() const { ASSERT(::IsWindow(m_hWnd)); return ::IsZoomed(m_hWnd); } BOOL MoveWindow(int x, int y, int nWidth, int nHeight, BOOL bRepaint = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::MoveWindow(m_hWnd, x, y, nWidth, nHeight, bRepaint); } BOOL MoveWindow(LPCRECT lpRect, BOOL bRepaint = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::MoveWindow(m_hWnd, lpRect->left, lpRect->top, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, bRepaint); } BOOL SetWindowPos(HWND hWndInsertAfter, int x, int y, int cx, int cy, UINT nFlags) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowPos(m_hWnd, hWndInsertAfter, x, y, cx, cy, nFlags); } BOOL SetWindowPos(HWND hWndInsertAfter, LPCRECT lpRect, UINT nFlags) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowPos(m_hWnd, hWndInsertAfter, lpRect->left, lpRect->top, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, nFlags); } UINT ArrangeIconicWindows() { ASSERT(::IsWindow(m_hWnd)); return ::ArrangeIconicWindows(m_hWnd); } BOOL BringWindowToTop() { ASSERT(::IsWindow(m_hWnd)); return ::BringWindowToTop(m_hWnd); } BOOL GetWindowRect(LPRECT lpRect) const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowRect(m_hWnd, lpRect); } BOOL GetClientRect(LPRECT lpRect) const { ASSERT(::IsWindow(m_hWnd)); return ::GetClientRect(m_hWnd, lpRect); } BOOL GetWindowPlacement(WINDOWPLACEMENT FAR* lpwndpl) const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowPlacement(m_hWnd, lpwndpl); } BOOL SetWindowPlacement(const WINDOWPLACEMENT FAR* lpwndpl) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowPlacement(m_hWnd, lpwndpl); } // Coordinate Mapping Functions BOOL ClientToScreen(LPPOINT lpPoint) const { ASSERT(::IsWindow(m_hWnd)); return ::ClientToScreen(m_hWnd, lpPoint); } BOOL ClientToScreen(LPRECT lpRect) const { ASSERT(::IsWindow(m_hWnd)); if(!::ClientToScreen(m_hWnd, (LPPOINT)lpRect)) return FALSE; return ::ClientToScreen(m_hWnd, ((LPPOINT)lpRect)+1); } BOOL ScreenToClient(LPPOINT lpPoint) const { ASSERT(::IsWindow(m_hWnd)); return ::ScreenToClient(m_hWnd, lpPoint); } BOOL ScreenToClient(LPRECT lpRect) const { ASSERT(::IsWindow(m_hWnd)); if(!::ScreenToClient(m_hWnd, (LPPOINT)lpRect)) return FALSE; return ::ScreenToClient(m_hWnd, ((LPPOINT)lpRect)+1); } int MapWindowPoints(HWND hWndTo, LPPOINT lpPoint, UINT nCount) const { ASSERT(::IsWindow(m_hWnd)); return ::MapWindowPoints(m_hWnd, hWndTo, lpPoint, nCount); } int MapWindowPoints(HWND hWndTo, LPRECT lpRect) const { ASSERT(::IsWindow(m_hWnd)); return ::MapWindowPoints(m_hWnd, hWndTo, (LPPOINT)lpRect, 2); } // Update and Painting Functions HDC BeginPaint(LPPAINTSTRUCT lpPaint) { ASSERT(::IsWindow(m_hWnd)); return ::BeginPaint(m_hWnd, lpPaint); } void EndPaint(LPPAINTSTRUCT lpPaint) { ASSERT(::IsWindow(m_hWnd)); ::EndPaint(m_hWnd, lpPaint); } HDC GetDC() { ASSERT(::IsWindow(m_hWnd)); return ::GetDC(m_hWnd); } HDC GetWindowDC() { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowDC(m_hWnd); } int ReleaseDC(HDC hDC) { ASSERT(::IsWindow(m_hWnd)); return ::ReleaseDC(m_hWnd, hDC); } void Print(HDC hDC, DWORD dwFlags) const { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_PRINT, (WPARAM)hDC, dwFlags); } void PrintClient(HDC hDC, DWORD dwFlags) const { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_PRINTCLIENT, (WPARAM)hDC, dwFlags); } BOOL UpdateWindow() { ASSERT(::IsWindow(m_hWnd)); return ::UpdateWindow(m_hWnd); } void SetRedraw(BOOL bRedraw = TRUE) { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_SETREDRAW, (WPARAM)bRedraw, 0); } BOOL GetUpdateRect(LPRECT lpRect, BOOL bErase = FALSE) { ASSERT(::IsWindow(m_hWnd)); return ::GetUpdateRect(m_hWnd, lpRect, bErase); } int GetUpdateRgn(HRGN hRgn, BOOL bErase = FALSE) { ASSERT(::IsWindow(m_hWnd)); return ::GetUpdateRgn(m_hWnd, hRgn, bErase); } BOOL Invalidate(BOOL bErase = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::InvalidateRect(m_hWnd, NULL, bErase); } BOOL InvalidateRect(LPCRECT lpRect, BOOL bErase = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::InvalidateRect(m_hWnd, lpRect, bErase); } BOOL ValidateRect(LPCRECT lpRect) { ASSERT(::IsWindow(m_hWnd)); return ::ValidateRect(m_hWnd, lpRect); } void InvalidateRgn(HRGN hRgn, BOOL bErase = TRUE) { ASSERT(::IsWindow(m_hWnd)); ::InvalidateRgn(m_hWnd, hRgn, bErase); } BOOL ValidateRgn(HRGN hRgn) { ASSERT(::IsWindow(m_hWnd)); return ::ValidateRgn(m_hWnd, hRgn); } BOOL ShowWindow(int nCmdShow) { ASSERT(::IsWindow(m_hWnd)); return ::ShowWindow(m_hWnd, nCmdShow); } BOOL IsWindowVisible() const { ASSERT(::IsWindow(m_hWnd)); return ::IsWindowVisible(m_hWnd); } BOOL ShowOwnedPopups(BOOL bShow = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::ShowOwnedPopups(m_hWnd, bShow); } HDC GetDCEx(HRGN hRgnClip, DWORD flags) { ASSERT(::IsWindow(m_hWnd)); return ::GetDCEx(m_hWnd, hRgnClip, flags); } BOOL LockWindowUpdate(BOOL bLock = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::LockWindowUpdate(bLock ? m_hWnd : NULL); } BOOL RedrawWindow(LPCRECT lpRectUpdate = NULL, HRGN hRgnUpdate = NULL, UINT flags = RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE) { ASSERT(::IsWindow(m_hWnd)); return ::RedrawWindow(m_hWnd, lpRectUpdate, hRgnUpdate, flags); } // Timer Functions UINT SetTimer(UINT nIDEvent, UINT nElapse) { ASSERT(::IsWindow(m_hWnd)); return ::SetTimer(m_hWnd, nIDEvent, nElapse, NULL); } BOOL KillTimer(UINT nIDEvent) { ASSERT(::IsWindow(m_hWnd)); return ::KillTimer(m_hWnd, nIDEvent); } // Window State Functions BOOL IsWindowEnabled() const { ASSERT(::IsWindow(m_hWnd)); return ::IsWindowEnabled(m_hWnd); } BOOL EnableWindow(BOOL bEnable = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::EnableWindow(m_hWnd, bEnable); } HWND SetActiveWindow() { ASSERT(::IsWindow(m_hWnd)); return ::SetActiveWindow(m_hWnd); } HWND SetCapture() { ASSERT(::IsWindow(m_hWnd)); return ::SetCapture(m_hWnd); } HWND SetFocus() { ASSERT(::IsWindow(m_hWnd)); return ::SetFocus(m_hWnd); } // Dialog-Box Item Functions BOOL CheckDlgButton(int nIDButton, UINT nCheck) { ASSERT(::IsWindow(m_hWnd)); return ::CheckDlgButton(m_hWnd, nIDButton, nCheck); } BOOL CheckRadioButton(int nIDFirstButton, int nIDLastButton, int nIDCheckButton) { ASSERT(::IsWindow(m_hWnd)); return ::CheckRadioButton(m_hWnd, nIDFirstButton, nIDLastButton, nIDCheckButton); } int DlgDirList(LPTSTR lpPathSpec, int nIDListBox, int nIDStaticPath, UINT nFileType) { ASSERT(::IsWindow(m_hWnd)); return ::DlgDirList(m_hWnd, lpPathSpec, nIDListBox, nIDStaticPath, nFileType); } int DlgDirListComboBox(LPTSTR lpPathSpec, int nIDComboBox, int nIDStaticPath, UINT nFileType) { ASSERT(::IsWindow(m_hWnd)); return ::DlgDirListComboBox(m_hWnd, lpPathSpec, nIDComboBox, nIDStaticPath, nFileType); } BOOL DlgDirSelect(LPTSTR lpString, int nCount, int nIDListBox) { ASSERT(::IsWindow(m_hWnd)); return ::DlgDirSelectEx(m_hWnd, lpString, nCount, nIDListBox); } BOOL DlgDirSelectComboBox(LPTSTR lpString, int nCount, int nIDComboBox) { ASSERT(::IsWindow(m_hWnd)); return ::DlgDirSelectComboBoxEx(m_hWnd, lpString, nCount, nIDComboBox); } UINT GetDlgItemInt(int nID, BOOL* lpTrans = NULL, BOOL bSigned = TRUE) const { ASSERT(::IsWindow(m_hWnd)); return ::GetDlgItemInt(m_hWnd, nID, lpTrans, bSigned); } UINT GetDlgItemText(int nID, LPTSTR lpStr, int nMaxCount) const { ASSERT(::IsWindow(m_hWnd)); return ::GetDlgItemText(m_hWnd, nID, lpStr, nMaxCount); } HWND GetNextDlgGroupItem(HWND hWndCtl, BOOL bPrevious = FALSE) const { ASSERT(::IsWindow(m_hWnd)); return ::GetNextDlgGroupItem(m_hWnd, hWndCtl, bPrevious); } HWND GetNextDlgTabItem(HWND hWndCtl, BOOL bPrevious = FALSE) const { ASSERT(::IsWindow(m_hWnd)); return ::GetNextDlgTabItem(m_hWnd, hWndCtl, bPrevious); } UINT IsDlgButtonChecked(int nIDButton) const { ASSERT(::IsWindow(m_hWnd)); return ::IsDlgButtonChecked(m_hWnd, nIDButton); } LRESULT SendDlgItemMessage(int nID, UINT message, WPARAM wParam = 0, LPARAM lParam = 0) { ASSERT(::IsWindow(m_hWnd)); return ::SendDlgItemMessage(m_hWnd, nID, message, wParam, lParam); } BOOL SetDlgItemInt(int nID, UINT nValue, BOOL bSigned = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::SetDlgItemInt(m_hWnd, nID, nValue, bSigned); } BOOL SetDlgItemText(int nID, LPCTSTR lpszString) { ASSERT(::IsWindow(m_hWnd)); return ::SetDlgItemText(m_hWnd, nID, lpszString); } // Scrolling Functions int GetScrollPos(int nBar) const { ASSERT(::IsWindow(m_hWnd)); return ::GetScrollPos(m_hWnd, nBar); } BOOL GetScrollRange(int nBar, LPINT lpMinPos, LPINT lpMaxPos) const { ASSERT(::IsWindow(m_hWnd)); return ::GetScrollRange(m_hWnd, nBar, lpMinPos, lpMaxPos); } BOOL ScrollWindow(int xAmount, int yAmount, LPCRECT lpRect = NULL, LPCRECT lpClipRect = NULL) { ASSERT(::IsWindow(m_hWnd)); return ::ScrollWindow(m_hWnd, xAmount, yAmount, lpRect, lpClipRect); } int ScrollWindowEx(int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, HRGN hRgnUpdate, LPRECT lpRectUpdate, UINT uFlags) { ASSERT(::IsWindow(m_hWnd)); return ::ScrollWindowEx(m_hWnd, dx, dy, lpRectScroll, lpRectClip, hRgnUpdate, lpRectUpdate, uFlags); } int ScrollWindowEx(int dx, int dy, UINT uFlags, LPCRECT lpRectScroll = NULL, LPCRECT lpRectClip = NULL, HRGN hRgnUpdate = NULL, LPRECT lpRectUpdate = NULL) { ASSERT(::IsWindow(m_hWnd)); return ::ScrollWindowEx(m_hWnd, dx, dy, lpRectScroll, lpRectClip, hRgnUpdate, lpRectUpdate, uFlags); } int SetScrollPos(int nBar, int nPos, BOOL bRedraw = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::SetScrollPos(m_hWnd, nBar, nPos, bRedraw); } BOOL SetScrollRange(int nBar, int nMinPos, int nMaxPos, BOOL bRedraw = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::SetScrollRange(m_hWnd, nBar, nMinPos, nMaxPos, bRedraw); } BOOL ShowScrollBar(UINT nBar, BOOL bShow = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::ShowScrollBar(m_hWnd, nBar, bShow); } BOOL EnableScrollBar(UINT uSBFlags, UINT uArrowFlags = ESB_ENABLE_BOTH) { ASSERT(::IsWindow(m_hWnd)); return ::EnableScrollBar(m_hWnd, uSBFlags, uArrowFlags); } // Window Access Functions HWND ChildWindowFromPoint(POINT point) const { ASSERT(::IsWindow(m_hWnd)); return ::ChildWindowFromPoint(m_hWnd, point); } HWND ChildWindowFromPointEx(POINT point, UINT uFlags) const { ASSERT(::IsWindow(m_hWnd)); return ::ChildWindowFromPointEx(m_hWnd, point, uFlags); } HWND GetTopWindow() const { ASSERT(::IsWindow(m_hWnd)); return ::GetTopWindow(m_hWnd); } HWND GetWindow(UINT nCmd) const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindow(m_hWnd, nCmd); } HWND GetLastActivePopup() const { ASSERT(::IsWindow(m_hWnd)); return ::GetLastActivePopup(m_hWnd); } BOOL IsChild(HWND hWnd) const { ASSERT(::IsWindow(m_hWnd)); return ::IsChild(m_hWnd, hWnd); } HWND GetParent() const { ASSERT(::IsWindow(m_hWnd)); return ::GetParent(m_hWnd); } HWND SetParent(HWND hWndNewParent) { ASSERT(::IsWindow(m_hWnd)); return ::SetParent(m_hWnd, hWndNewParent); } // Window Tree Access int GetDlgCtrlID() const { ASSERT(::IsWindow(m_hWnd)); return ::GetDlgCtrlID(m_hWnd); } int SetDlgCtrlID(int nID) { ASSERT(::IsWindow(m_hWnd)); return (int)::SetWindowLong(m_hWnd, GWL_ID, nID); } HWND GetDlgItem(int nID) const { ASSERT(::IsWindow(m_hWnd)); return ::GetDlgItem(m_hWnd, nID); } // Alert Functions BOOL FlashWindow(BOOL bInvert) { ASSERT(::IsWindow(m_hWnd)); return ::FlashWindow(m_hWnd, bInvert); } int MessageBox(LPCTSTR lpszText, LPCTSTR lpszCaption = _T(""), UINT nType = MB_OK) { ASSERT(::IsWindow(m_hWnd)); return ::MessageBox(m_hWnd, lpszText, lpszCaption, nType); } // Clipboard Functions BOOL ChangeClipboardChain(HWND hWndNewNext) { ASSERT(::IsWindow(m_hWnd)); return ::ChangeClipboardChain(m_hWnd, hWndNewNext); } HWND SetClipboardViewer() { ASSERT(::IsWindow(m_hWnd)); return ::SetClipboardViewer(m_hWnd); } BOOL OpenClipboard() { ASSERT(::IsWindow(m_hWnd)); return ::OpenClipboard(m_hWnd); } // Caret Functions BOOL CreateCaret(HBITMAP hBitmap) { ASSERT(::IsWindow(m_hWnd)); return ::CreateCaret(m_hWnd, hBitmap, 0, 0); } BOOL CreateSolidCaret(int nWidth, int nHeight) { ASSERT(::IsWindow(m_hWnd)); return ::CreateCaret(m_hWnd, (HBITMAP)0, nWidth, nHeight); } BOOL CreateGrayCaret(int nWidth, int nHeight) { ASSERT(::IsWindow(m_hWnd)); return ::CreateCaret(m_hWnd, (HBITMAP)1, nWidth, nHeight); } BOOL HideCaret() { ASSERT(::IsWindow(m_hWnd)); return ::HideCaret(m_hWnd); } BOOL ShowCaret() { ASSERT(::IsWindow(m_hWnd)); return ::ShowCaret(m_hWnd); } #ifdef _INC_SHELLAPI // Drag-Drop Functions void DragAcceptFiles(BOOL bAccept = TRUE) { ASSERT(::IsWindow(m_hWnd)); ::DragAcceptFiles(m_hWnd, bAccept); } #endif // Icon Functions HICON SetIcon(HICON hIcon, BOOL bBigIcon = TRUE) { ASSERT(::IsWindow(m_hWnd)); return (HICON)::SendMessage(m_hWnd, WM_SETICON, bBigIcon, (LPARAM)hIcon); } HICON GetIcon(BOOL bBigIcon = TRUE) const { ASSERT(::IsWindow(m_hWnd)); return (HICON)::SendMessage(m_hWnd, WM_GETICON, bBigIcon, 0); } // Help Functions BOOL WinHelp(LPCTSTR lpszHelp, UINT nCmd = HELP_CONTEXT, DWORD dwData = 0) { ASSERT(::IsWindow(m_hWnd)); return ::WinHelp(m_hWnd, lpszHelp, nCmd, dwData); } BOOL SetWindowContextHelpId(DWORD dwContextHelpId) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowContextHelpId(m_hWnd, dwContextHelpId); } DWORD GetWindowContextHelpId() const { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowContextHelpId(m_hWnd); } // Hot Key Functions int SetHotKey(WORD wVirtualKeyCode, WORD wModifiers) { ASSERT(::IsWindow(m_hWnd)); return (int)::SendMessage(m_hWnd, WM_SETHOTKEY, MAKEWORD(wVirtualKeyCode, wModifiers), 0); } DWORD GetHotKey() const { ASSERT(::IsWindow(m_hWnd)); return ::SendMessage(m_hWnd, WM_GETHOTKEY, 0, 0); } // Misc. Operations //N new BOOL GetScrollInfo(int nBar, LPSCROLLINFO lpScrollInfo) { ASSERT(::IsWindow(m_hWnd)); return ::GetScrollInfo(m_hWnd, nBar, lpScrollInfo); } BOOL SetScrollInfo(int nBar, LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE) { ASSERT(::IsWindow(m_hWnd)); return ::SetScrollInfo(m_hWnd, nBar, lpScrollInfo, bRedraw); } BOOL IsDialogMessage(LPMSG lpMsg) { ASSERT(::IsWindow(m_hWnd)); return ::IsDialogMessage(m_hWnd, lpMsg); } void NextDlgCtrl() const { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_NEXTDLGCTL, 0, 0L); } void PrevDlgCtrl() const { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_NEXTDLGCTL, 1, 0L); } void GotoDlgCtrl(HWND hWndCtrl) const { ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, WM_NEXTDLGCTL, (WPARAM)hWndCtrl, 1L); } BOOL ResizeClient(int nWidth, int nHeight, BOOL bRedraw = TRUE) { ASSERT(::IsWindow(m_hWnd)); RECT rcWnd; if(!GetClientRect(&rcWnd)) return FALSE; if(nWidth != -1) rcWnd.right = nWidth; if(nHeight != -1) rcWnd.bottom = nHeight; if(!::AdjustWindowRectEx(&rcWnd, GetStyle(), (!(GetStyle() & WS_CHILD) && (GetMenu() != NULL)), GetExStyle())) return FALSE; UINT uFlags = SWP_NOZORDER | SWP_NOMOVE; if(!bRedraw) uFlags |= SWP_NOREDRAW; return SetWindowPos(NULL, 0, 0, rcWnd.right - rcWnd.left, rcWnd.bottom - rcWnd.top, uFlags); } int GetWindowRgn(HRGN hRgn) { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowRgn(m_hWnd, hRgn); } int SetWindowRgn(HRGN hRgn, BOOL bRedraw = FALSE) { ASSERT(::IsWindow(m_hWnd)); return ::SetWindowRgn(m_hWnd, hRgn, bRedraw); } HDWP DeferWindowPos(HDWP hWinPosInfo, HWND hWndInsertAfter, int x, int y, int cx, int cy, UINT uFlags) { ASSERT(::IsWindow(m_hWnd)); return ::DeferWindowPos(hWinPosInfo, m_hWnd, hWndInsertAfter, x, y, cx, cy, uFlags); } DWORD GetWindowThreadID() { ASSERT(::IsWindow(m_hWnd)); return ::GetWindowThreadProcessId(m_hWnd, NULL); } DWORD GetWindowProcessID() { ASSERT(::IsWindow(m_hWnd)); DWORD dwProcessID; ::GetWindowThreadProcessId(m_hWnd, &dwProcessID); return dwProcessID; } BOOL IsWindow() { return ::IsWindow(m_hWnd); } BOOL IsWindowUnicode() { ASSERT(::IsWindow(m_hWnd)); return ::IsWindowUnicode(m_hWnd); } BOOL IsParentDialog() { ASSERT(::IsWindow(m_hWnd)); TCHAR szBuf[8]; // "#32770" + NUL character GetClassName(GetParent(), szBuf, sizeof(szBuf)/sizeof(TCHAR)); return lstrcmp(szBuf, _T("#32770")) == 0; } BOOL ShowWindowAsync(int nCmdShow) { ASSERT(::IsWindow(m_hWnd)); return ::ShowWindowAsync(m_hWnd, nCmdShow); } HWND GetDescendantWindow(int nID) const { ASSERT(::IsWindow(m_hWnd)); // GetDlgItem recursive (return first found) // breadth-first for 1 level, then depth-first for next level // use GetDlgItem since it is a fast USER function HWND hWndChild, hWndTmp; CWindow wnd; if((hWndChild = ::GetDlgItem(m_hWnd, nID)) != NULL) { if(::GetTopWindow(hWndChild) != NULL) { // children with the same ID as their parent have priority wnd.Attach(hWndChild); hWndTmp = wnd.GetDescendantWindow(nID); if(hWndTmp != NULL) return hWndTmp; } return hWndChild; } // walk each child for(hWndChild = ::GetTopWindow(m_hWnd); hWndChild != NULL; hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT)) { wnd.Attach(hWndChild); hWndTmp = wnd.GetDescendantWindow(nID); if(hWndTmp != NULL) return hWndTmp; } return NULL; // not found } void SendMessageToDescendants(UINT message, WPARAM wParam = 0, LPARAM lParam = 0, BOOL bDeep = TRUE) { CWindow wnd; for(HWND hWndChild = ::GetTopWindow(m_hWnd); hWndChild != NULL; hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT)) { ::SendMessage(hWndChild, message, wParam, lParam); if(bDeep && ::GetTopWindow(hWndChild) != NULL) { // send to child windows after parent wnd.Attach(hWndChild); wnd.SendMessageToDescendants(message, wParam, lParam, bDeep); } } } BOOL CenterWindow(HWND hWndCenter = NULL) { ASSERT(::IsWindow(m_hWnd)); // determine owner window to center against DWORD dwStyle = GetStyle(); if(hWndCenter == NULL) { if(dwStyle & WS_CHILD) hWndCenter = ::GetParent(m_hWnd); else hWndCenter = ::GetWindow(m_hWnd, GW_OWNER); } // get coordinates of the window relative to its parent RECT rcDlg; ::GetWindowRect(m_hWnd, &rcDlg); RECT rcArea; RECT rcCenter; HWND hWndParent; if(!(dwStyle & WS_CHILD)) { // don't center against invisible or minimized windows if(hWndCenter != NULL) { DWORD dwStyle = ::GetWindowLong(hWndCenter, GWL_STYLE); if(!(dwStyle & WS_VISIBLE) || (dwStyle & WS_MINIMIZE)) hWndCenter = NULL; } // center within screen coordinates ::SystemParametersInfo(SPI_GETWORKAREA, NULL, &rcArea, NULL); if(hWndCenter == NULL) rcCenter = rcArea; else ::GetWindowRect(hWndCenter, &rcCenter); } else { // center within parent client coordinates hWndParent = ::GetParent(m_hWnd); ASSERT(::IsWindow(hWndParent)); ::GetClientRect(hWndParent, &rcArea); ASSERT(::IsWindow(hWndCenter)); ::GetClientRect(hWndCenter, &rcCenter); ::MapWindowPoints(hWndCenter, hWndParent, (POINT*)&rcCenter, 2); } int DlgWidth = rcDlg.right - rcDlg.left; int DlgHeight = rcDlg.bottom - rcDlg.top; // find dialog's upper left based on rcCenter int xLeft = (rcCenter.left + rcCenter.right) / 2 - DlgWidth / 2; int yTop = (rcCenter.top + rcCenter.bottom) / 2 - DlgHeight / 2; // if the dialog is outside the screen, move it inside if(xLeft < rcArea.left) xLeft = rcArea.left; else if(xLeft + DlgWidth > rcArea.right) xLeft = rcArea.right - DlgWidth; if(yTop < rcArea.top) yTop = rcArea.top; else if(yTop + DlgHeight > rcArea.bottom) yTop = rcArea.bottom - DlgHeight; // map screen coordinates to child coordinates return ::SetWindowPos(m_hWnd, NULL, xLeft, yTop, -1, -1, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); } BOOL ModifyStyle(DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0) { ASSERT(::IsWindow(m_hWnd)); DWORD dwStyle = ::GetWindowLong(m_hWnd, GWL_STYLE); DWORD dwNewStyle = (dwStyle & ~dwRemove) | dwAdd; if(dwStyle == dwNewStyle) return FALSE; ::SetWindowLong(m_hWnd, GWL_STYLE, dwNewStyle); if(nFlags != 0) { ::SetWindowPos(m_hWnd, NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | nFlags); } return TRUE; } BOOL ModifyStyleEx(DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0) { ASSERT(::IsWindow(m_hWnd)); DWORD dwStyle = ::GetWindowLong(m_hWnd, GWL_EXSTYLE); DWORD dwNewStyle = (dwStyle & ~dwRemove) | dwAdd; if(dwStyle == dwNewStyle) return FALSE; ::SetWindowLong(m_hWnd, GWL_EXSTYLE, dwNewStyle); if(nFlags != 0) { ::SetWindowPos(m_hWnd, NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | nFlags); } return TRUE; } HWND GetTopLevelParent() const { ASSERT(::IsWindow(m_hWnd)); HWND hWndParent = m_hWnd; HWND hWndTmp; while((hWndTmp = ::GetParent(hWndParent)) != NULL) hWndParent = hWndTmp; return hWndParent; } HWND GetTopLevelWindow() const { ASSERT(::IsWindow(m_hWnd)); HWND hWndParent; HWND hWndTmp = m_hWnd; do { hWndParent = hWndTmp; hWndTmp = (::GetWindowLong(hWndParent, GWL_STYLE) & WS_CHILD) ? ::GetParent(hWndParent) : ::GetWindow(hWndParent, GW_OWNER); } while(hWndTmp != NULL); return hWndParent; } }; _declspec(selectany) RECT CWindow::rcDefault = { CW_USEDEFAULT, CW_USEDEFAULT, 0, 0 }; // foreward declares class CPoint; class CRect; ///////////////////////////////////////////////////////////////////////////// // CSize - Wrapper for Windows SIZE structure. class CSize : public tagSIZE { public: // Constructors CSize(); CSize(int initCX, int initCY); CSize(SIZE initSize); CSize(POINT initPt); CSize(DWORD dwSize); // Operations BOOL operator==(SIZE size) const; BOOL operator!=(SIZE size) const; void operator+=(SIZE size); void operator-=(SIZE size); void SetSize(int CX, int CY); // Operators returning CSize values CSize operator+(SIZE size) const; CSize operator-(SIZE size) const; CSize operator-() const; // Operators returning CPoint values CPoint operator+(POINT point) const; CPoint operator-(POINT point) const; // Operators returning CRect values CRect operator+(const RECT* lpRect) const; CRect operator-(const RECT* lpRect) const; }; ///////////////////////////////////////////////////////////////////////////// // CPoint - Wrapper for Windows POINT structure. class CPoint : public tagPOINT { public: // Constructors CPoint(); CPoint(int initX, int initY); CPoint(POINT initPt); CPoint(SIZE initSize); CPoint(DWORD dwPoint); // Operations void Offset(int xOffset, int yOffset); void Offset(POINT point); void Offset(SIZE size); BOOL operator==(POINT point) const; BOOL operator!=(POINT point) const; void operator+=(SIZE size); void operator-=(SIZE size); void operator+=(POINT point); void operator-=(POINT point); void SetPoint(int X, int Y); // Operators returning CPoint values CPoint operator+(SIZE size) const; CPoint operator-(SIZE size) const; CPoint operator-() const; CPoint operator+(POINT point) const; // Operators returning CSize values CSize operator-(POINT point) const; // Operators returning CRect values CRect operator+(const RECT* lpRect) const; CRect operator-(const RECT* lpRect) const; }; ///////////////////////////////////////////////////////////////////////////// // CRect - Wrapper for Windows RECT structure. class CRect : public tagRECT { public: // Constructors CRect(); CRect(int l, int t, int r, int b); CRect(const RECT& srcRect); CRect(LPCRECT lpSrcRect); CRect(POINT point, SIZE size); CRect(POINT topLeft, POINT bottomRight); // Attributes (in addition to RECT members) int Width() const; int Height() const; CSize Size() const; CPoint& TopLeft(); CPoint& BottomRight(); const CPoint& TopLeft() const; const CPoint& BottomRight() const; CPoint CenterPoint() const; // convert between CRect and LPRECT/LPCRECT (no need for &) operator LPRECT(); operator LPCRECT() const; BOOL IsRectEmpty() const; BOOL IsRectNull() const; BOOL PtInRect(POINT point) const; // Operations void SetRect(int x1, int y1, int x2, int y2); void SetRect(POINT topLeft, POINT bottomRight); void SetRectEmpty(); void CopyRect(LPCRECT lpSrcRect); BOOL EqualRect(LPCRECT lpRect) const; void InflateRect(int x, int y); void InflateRect(SIZE size); void InflateRect(LPCRECT lpRect); void InflateRect(int l, int t, int r, int b); void DeflateRect(int x, int y); void DeflateRect(SIZE size); void DeflateRect(LPCRECT lpRect); void DeflateRect(int l, int t, int r, int b); void OffsetRect(int x, int y); void OffsetRect(SIZE size); void OffsetRect(POINT point); void NormalizeRect(); // absolute position of rectangle void MoveToY(int y); void MoveToX(int x); void MoveToXY(int x, int y); void MoveToXY(POINT point); // operations that fill '*this' with result BOOL IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2); BOOL UnionRect(LPCRECT lpRect1, LPCRECT lpRect2); BOOL SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2); // Additional Operations void operator=(const RECT& srcRect); BOOL operator==(const RECT& rect) const; BOOL operator!=(const RECT& rect) const; void operator+=(POINT point); void operator+=(SIZE size); void operator+=(LPCRECT lpRect); void operator-=(POINT point); void operator-=(SIZE size); void operator-=(LPCRECT lpRect); void operator&=(const RECT& rect); void operator|=(const RECT& rect); // Operators returning CRect values CRect operator+(POINT point) const; CRect operator-(POINT point) const; CRect operator+(LPCRECT lpRect) const; CRect operator+(SIZE size) const; CRect operator-(SIZE size) const; CRect operator-(LPCRECT lpRect) const; CRect operator&(const RECT& rect2) const; CRect operator|(const RECT& rect2) const; CRect MulDiv(int nMultiplier, int nDivisor) const; }; ///////////////////////////////////////////////////////////////////////////// // CSize, CPoint, CRect Implementation // CSize inline CSize::CSize() { /* random filled */ } inline CSize::CSize(int initCX, int initCY) { cx = initCX; cy = initCY; } inline CSize::CSize(SIZE initSize) { *(SIZE*)this = initSize; } inline CSize::CSize(POINT initPt) { *(POINT*)this = initPt; } inline CSize::CSize(DWORD dwSize) { cx = (short)LOWORD(dwSize); cy = (short)HIWORD(dwSize); } inline BOOL CSize::operator==(SIZE size) const { return (cx == size.cx && cy == size.cy); } inline BOOL CSize::operator!=(SIZE size) const { return (cx != size.cx || cy != size.cy); } inline void CSize::operator+=(SIZE size) { cx += size.cx; cy += size.cy; } inline void CSize::operator-=(SIZE size) { cx -= size.cx; cy -= size.cy; } inline void CSize::SetSize(int CX, int CY) { cx = CX; cy = CY; } inline CSize CSize::operator+(SIZE size) const { return CSize(cx + size.cx, cy + size.cy); } inline CSize CSize::operator-(SIZE size) const { return CSize(cx - size.cx, cy - size.cy); } inline CSize CSize::operator-() const { return CSize(-cx, -cy); } inline CPoint CSize::operator+(POINT point) const { return CPoint(cx + point.x, cy + point.y); } inline CPoint CSize::operator-(POINT point) const { return CPoint(cx - point.x, cy - point.y); } inline CRect CSize::operator+(const RECT* lpRect) const { return CRect(lpRect) + *this; } inline CRect CSize::operator-(const RECT* lpRect) const { return CRect(lpRect) - *this; } // CPoint inline CPoint::CPoint() { /* random filled */ } inline CPoint::CPoint(int initX, int initY) { x = initX; y = initY; } inline CPoint::CPoint(POINT initPt) { *(POINT*)this = initPt; } inline CPoint::CPoint(SIZE initSize) { *(SIZE*)this = initSize; } inline CPoint::CPoint(DWORD dwPoint) { x = (short)LOWORD(dwPoint); y = (short)HIWORD(dwPoint); } inline void CPoint::Offset(int xOffset, int yOffset) { x += xOffset; y += yOffset; } inline void CPoint::Offset(POINT point) { x += point.x; y += point.y; } inline void CPoint::Offset(SIZE size) { x += size.cx; y += size.cy; } inline BOOL CPoint::operator==(POINT point) const { return (x == point.x && y == point.y); } inline BOOL CPoint::operator!=(POINT point) const { return (x != point.x || y != point.y); } inline void CPoint::operator+=(SIZE size) { x += size.cx; y += size.cy; } inline void CPoint::operator-=(SIZE size) { x -= size.cx; y -= size.cy; } inline void CPoint::operator+=(POINT point) { x += point.x; y += point.y; } inline void CPoint::operator-=(POINT point) { x -= point.x; y -= point.y; } inline void CPoint::SetPoint(int X, int Y) { x = X; y = Y; } inline CPoint CPoint::operator+(SIZE size) const { return CPoint(x + size.cx, y + size.cy); } inline CPoint CPoint::operator-(SIZE size) const { return CPoint(x - size.cx, y - size.cy); } inline CPoint CPoint::operator-() const { return CPoint(-x, -y); } inline CPoint CPoint::operator+(POINT point) const { return CPoint(x + point.x, y + point.y); } inline CSize CPoint::operator-(POINT point) const { return CSize(x - point.x, y - point.y); } inline CRect CPoint::operator+(const RECT* lpRect) const { return CRect(lpRect) + *this; } inline CRect CPoint::operator-(const RECT* lpRect) const { return CRect(lpRect) - *this; } // CRect inline CRect::CRect() { /* random filled */ } inline CRect::CRect(int l, int t, int r, int b) { left = l; top = t; right = r; bottom = b; } inline CRect::CRect(const RECT& srcRect) { ::CopyRect(this, &srcRect); } inline CRect::CRect(LPCRECT lpSrcRect) { ::CopyRect(this, lpSrcRect); } inline CRect::CRect(POINT point, SIZE size) { right = (left = point.x) + size.cx; bottom = (top = point.y) + size.cy; } inline CRect::CRect(POINT topLeft, POINT bottomRight) { left = topLeft.x; top = topLeft.y; right = bottomRight.x; bottom = bottomRight.y; } inline int CRect::Width() const { return right - left; } inline int CRect::Height() const { return bottom - top; } inline CSize CRect::Size() const { return CSize(right - left, bottom - top); } inline CPoint& CRect::TopLeft() { return *((CPoint*)this); } inline CPoint& CRect::BottomRight() { return *((CPoint*)this + 1); } inline const CPoint& CRect::TopLeft() const { return *((CPoint*)this); } inline const CPoint& CRect::BottomRight() const { return *((CPoint*)this + 1); } inline CPoint CRect::CenterPoint() const { return CPoint((left + right) / 2, (top + bottom) / 2); } inline CRect::operator LPRECT() { return this; } inline CRect::operator LPCRECT() const { return this; } inline BOOL CRect::IsRectEmpty() const { return ::IsRectEmpty(this); } inline BOOL CRect::IsRectNull() const { return (left == 0 && right == 0 && top == 0 && bottom == 0); } inline BOOL CRect::PtInRect(POINT point) const { return ::PtInRect(this, point); } inline void CRect::SetRect(int x1, int y1, int x2, int y2) { ::SetRect(this, x1, y1, x2, y2); } inline void CRect::SetRect(POINT topLeft, POINT bottomRight) { ::SetRect(this, topLeft.x, topLeft.y, bottomRight.x, bottomRight.y); } inline void CRect::SetRectEmpty() { ::SetRectEmpty(this); } inline void CRect::CopyRect(LPCRECT lpSrcRect) { ::CopyRect(this, lpSrcRect); } inline BOOL CRect::EqualRect(LPCRECT lpRect) const { return ::EqualRect(this, lpRect); } inline void CRect::InflateRect(int x, int y) { ::InflateRect(this, x, y); } inline void CRect::InflateRect(SIZE size) { ::InflateRect(this, size.cx, size.cy); } inline void CRect::DeflateRect(int x, int y) { ::InflateRect(this, -x, -y); } inline void CRect::DeflateRect(SIZE size) { ::InflateRect(this, -size.cx, -size.cy); } inline void CRect::OffsetRect(int x, int y) { ::OffsetRect(this, x, y); } inline void CRect::OffsetRect(POINT point) { ::OffsetRect(this, point.x, point.y); } inline void CRect::OffsetRect(SIZE size) { ::OffsetRect(this, size.cx, size.cy); } inline BOOL CRect::IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2) { return ::IntersectRect(this, lpRect1, lpRect2);} inline BOOL CRect::UnionRect(LPCRECT lpRect1, LPCRECT lpRect2) { return ::UnionRect(this, lpRect1, lpRect2); } inline void CRect::operator=(const RECT& srcRect) { ::CopyRect(this, &srcRect); } inline BOOL CRect::operator==(const RECT& rect) const { return ::EqualRect(this, &rect); } inline BOOL CRect::operator!=(const RECT& rect) const { return !::EqualRect(this, &rect); } inline void CRect::operator+=(POINT point) { ::OffsetRect(this, point.x, point.y); } inline void CRect::operator+=(SIZE size) { ::OffsetRect(this, size.cx, size.cy); } inline void CRect::operator+=(LPCRECT lpRect) { InflateRect(lpRect); } inline void CRect::operator-=(POINT point) { ::OffsetRect(this, -point.x, -point.y); } inline void CRect::operator-=(SIZE size) { ::OffsetRect(this, -size.cx, -size.cy); } inline void CRect::operator-=(LPCRECT lpRect) { DeflateRect(lpRect); } inline void CRect::operator&=(const RECT& rect) { ::IntersectRect(this, this, &rect); } inline void CRect::operator|=(const RECT& rect) { ::UnionRect(this, this, &rect); } inline CRect CRect::operator+(POINT pt) const { CRect rect(*this); ::OffsetRect(&rect, pt.x, pt.y); return rect; } inline CRect CRect::operator-(POINT pt) const { CRect rect(*this); ::OffsetRect(&rect, -pt.x, -pt.y); return rect; } inline CRect CRect::operator+(SIZE size) const { CRect rect(*this); ::OffsetRect(&rect, size.cx, size.cy); return rect; } inline CRect CRect::operator-(SIZE size) const { CRect rect(*this); ::OffsetRect(&rect, -size.cx, -size.cy); return rect; } inline CRect CRect::operator+(LPCRECT lpRect) const { CRect rect(this); rect.InflateRect(lpRect); return rect; } inline CRect CRect::operator-(LPCRECT lpRect) const { CRect rect(this); rect.DeflateRect(lpRect); return rect; } inline CRect CRect::operator&(const RECT& rect2) const { CRect rect; ::IntersectRect(&rect, this, &rect2); return rect; } inline CRect CRect::operator|(const RECT& rect2) const { CRect rect; ::UnionRect(&rect, this, &rect2); return rect; } inline BOOL CRect::SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2) { return ::SubtractRect(this, lpRectSrc1, lpRectSrc2); } inline void CRect::NormalizeRect() { int nTemp; if (left > right) { nTemp = left; left = right; right = nTemp; } if (top > bottom) { nTemp = top; top = bottom; bottom = nTemp; } } inline void CRect::MoveToY(int y) { bottom = Height() + y; top = y; } inline void CRect::MoveToX(int x) { right = Width() + x; left = x; } inline void CRect::MoveToXY(int x, int y) { MoveToX(x); MoveToY(y); } inline void CRect::MoveToXY(POINT pt) { MoveToX(pt.x); MoveToY(pt.y); } inline void CRect::InflateRect(LPCRECT lpRect) { left -= lpRect->left; top -= lpRect->top; right += lpRect->right; bottom += lpRect->bottom; } inline void CRect::InflateRect(int l, int t, int r, int b) { left -= l; top -= t; right += r; bottom += b; } inline void CRect::DeflateRect(LPCRECT lpRect) { left += lpRect->left; top += lpRect->top; right -= lpRect->right; bottom -= lpRect->bottom; } inline void CRect::DeflateRect(int l, int t, int r, int b) { left += l; top += t; right -= r; bottom -= b; } inline CRect CRect::MulDiv(int nMultiplier, int nDivisor) const { return CRect( ::MulDiv(left, nMultiplier, nDivisor), ::MulDiv(top, nMultiplier, nDivisor), ::MulDiv(right, nMultiplier, nDivisor), ::MulDiv(bottom, nMultiplier, nDivisor)); } }; // namespace TWL #endif // __WND_H__
[ "dandycheung@9b253700-4547-11de-82b9-170f4fd74ac7" ]
[ [ [ 1, 1602 ] ] ]
f19a293dd62af32dd1ff1c56474bb81a7c3c3444
028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32
/src/drivers/parodius.cpp
5b8e0e356eca3a6cb48f61e04d77bf58605e8f26
[]
no_license
neonichu/iMame4All-for-iPad
72f56710d2ed7458594838a5152e50c72c2fb67f
4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611
refs/heads/master
2020-04-21T07:26:37.595653
2011-11-26T12:21:56
2011-11-26T12:21:56
2,855,022
4
0
null
null
null
null
UTF-8
C++
false
false
13,456
cpp
#include "../vidhrdw/parodius.cpp" /*************************************************************************** Parodius (Konami GX955) (c) 1990 Konami driver by Nicola Salmoria ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "cpu/konami/konami.h" /* for the callback and the firq irq definition */ #include "vidhrdw/konamiic.h" /* prototypes */ static void parodius_init_machine( void ); static void parodius_banking( int lines ); int parodius_vh_start( void ); void parodius_vh_stop( void ); void parodius_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); static int videobank; static unsigned char *ram; static int parodius_interrupt(void) { if (K052109_is_IRQ_enabled()) return interrupt(); else return ignore_interrupt(); } static READ_HANDLER( bankedram_r ) { if (videobank & 0x01) { if (videobank & 0x04) return paletteram_r(offset + 0x0800); else return paletteram_r(offset); } else return ram[offset]; } static WRITE_HANDLER( bankedram_w ) { if (videobank & 0x01) { if (videobank & 0x04) paletteram_xBBBBBGGGGGRRRRR_swap_w(offset + 0x0800,data); else paletteram_xBBBBBGGGGGRRRRR_swap_w(offset,data); } else ram[offset] = data; } static READ_HANDLER( parodius_052109_053245_r ) { if (videobank & 0x02) return K053245_r(offset); else return K052109_r(offset); } static WRITE_HANDLER( parodius_052109_053245_w ) { if (videobank & 0x02) K053245_w(offset,data); else K052109_w(offset,data); } static WRITE_HANDLER( parodius_videobank_w ) { //if (videobank & 0xf8) logerror("%04x: videobank = %02x\n",cpu_get_pc(),data); /* bit 0 = select palette or work RAM at 0000-07ff */ /* bit 1 = select 052109 or 053245 at 2000-27ff */ /* bit 2 = select palette bank 0 or 1 */ videobank = data; } static WRITE_HANDLER( parodius_3fc0_w ) { //if ((data & 0xf4) != 0x10) logerror("%04x: 3fc0 = %02x\n",cpu_get_pc(),data); /* bit 0/1 = coin counters */ coin_counter_w(0,data & 0x01); coin_counter_w(1,data & 0x02); /* bit 3 = enable char ROM reading through the video RAM */ K052109_set_RMRD_line( ( data & 0x08 ) ? ASSERT_LINE : CLEAR_LINE ); /* other bits unknown */ } static READ_HANDLER( parodius_sound_r ) { /* If the sound CPU is running, read the status, otherwise just make it pass the test */ if (Machine->sample_rate != 0) return K053260_r(2 + offset); else return offset ? 0x00 : 0x80; } static WRITE_HANDLER( parodius_sh_irqtrigger_w ) { cpu_cause_interrupt(1,0xff); } static void nmi_callback(int param) { cpu_set_nmi_line(1,ASSERT_LINE); } static WRITE_HANDLER( sound_arm_nmi_w ) { // sound_nmi_enabled = 1; cpu_set_nmi_line(1,CLEAR_LINE); timer_set(TIME_IN_USEC(50),0,nmi_callback); /* kludge until the K053260 is emulated correctly */ } static READ_HANDLER( speedup_r ) { int data = memory_region(REGION_CPU1)[0x1837]; if ( cpu_get_pc() == 0xa400 && data == 0 ) cpu_spinuntil_int(); return data; } /********************************************/ static struct MemoryReadAddress parodius_readmem[] = { { 0x0000, 0x07ff, bankedram_r }, { 0x1837, 0x1837, speedup_r }, { 0x0800, 0x1fff, MRA_RAM }, { 0x3f8c, 0x3f8c, input_port_0_r }, { 0x3f8d, 0x3f8d, input_port_1_r }, { 0x3f8e, 0x3f8e, input_port_4_r }, { 0x3f8f, 0x3f8f, input_port_2_r }, { 0x3f90, 0x3f90, input_port_3_r }, { 0x3fa0, 0x3faf, K053244_r }, { 0x3fc0, 0x3fc0, watchdog_reset_r }, { 0x3fcc, 0x3fcd, parodius_sound_r }, /* K053260 */ { 0x2000, 0x27ff, parodius_052109_053245_r }, { 0x2000, 0x5fff, K052109_r }, { 0x6000, 0x9fff, MRA_BANK1 }, /* banked ROM */ { 0xa000, 0xffff, MRA_ROM }, /* ROM */ { -1 } /* end of table */ }; static struct MemoryWriteAddress parodius_writemem[] = { { 0x0000, 0x07ff, bankedram_w, &ram }, { 0x0800, 0x1fff, MWA_RAM }, { 0x3fa0, 0x3faf, K053244_w }, { 0x3fb0, 0x3fbf, K053251_w }, { 0x3fc0, 0x3fc0, parodius_3fc0_w }, { 0x3fc4, 0x3fc4, parodius_videobank_w }, { 0x3fc8, 0x3fc8, parodius_sh_irqtrigger_w }, { 0x3fcc, 0x3fcd, K053260_w }, { 0x2000, 0x27ff, parodius_052109_053245_w }, { 0x2000, 0x5fff, K052109_w }, { 0x6000, 0x9fff, MWA_ROM }, /* banked ROM */ { 0xa000, 0xffff, MWA_ROM }, /* ROM */ { -1 } /* end of table */ }; static struct MemoryReadAddress parodius_readmem_sound[] = { { 0x0000, 0xefff, MRA_ROM }, { 0xf000, 0xf7ff, MRA_RAM }, { 0xf801, 0xf801, YM2151_status_port_0_r }, { 0xfc00, 0xfc2f, K053260_r }, { -1 } /* end of table */ }; static struct MemoryWriteAddress parodius_writemem_sound[] = { { 0x0000, 0xefff, MWA_ROM }, { 0xf000, 0xf7ff, MWA_RAM }, { 0xf800, 0xf800, YM2151_register_port_0_w }, { 0xf801, 0xf801, YM2151_data_port_0_w }, { 0xfa00, 0xfa00, sound_arm_nmi_w }, { 0xfc00, 0xfc2f, K053260_w }, { -1 } /* end of table */ }; /*************************************************************************** Input Ports ***************************************************************************/ INPUT_PORTS_START( parodius ) PORT_START /* PLAYER 1 INPUTS */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER1 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 ) PORT_START /* PLAYER 2 INPUTS */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 ) PORT_START /* DSW #1 */ PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x02, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 4C_3C ) ) PORT_DIPSETTING( 0x0f, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 3C_4C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0x0d, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0b, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x09, DEF_STR( 1C_7C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x50, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x40, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 4C_3C ) ) PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x30, DEF_STR( 3C_4C ) ) PORT_DIPSETTING( 0x70, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0xe0, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x60, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0xd0, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0xb0, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0xa0, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x90, DEF_STR( 1C_7C ) ) // PORT_DIPSETTING( 0x00, "No Use" ) PORT_START /* DSW #2 */ PORT_DIPNAME( 0x03, 0x02, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x03, "2" ) PORT_DIPSETTING( 0x02, "3" ) PORT_DIPSETTING( 0x01, "4" ) PORT_DIPSETTING( 0x00, "7" ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x04, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x18, 0x18, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x18, "20000 80000" ) PORT_DIPSETTING( 0x10, "30000 100000" ) PORT_DIPSETTING( 0x08, "20000" ) PORT_DIPSETTING( 0x00, "70000" ) PORT_DIPNAME( 0x60, 0x40, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x60, "Easy" ) PORT_DIPSETTING( 0x40, "Normal" ) PORT_DIPSETTING( 0x20, "Difficult" ) PORT_DIPSETTING( 0x00, "Very Difficult" ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START /* DSW #3 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Flip_Screen ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, "Upright Controls" ) PORT_DIPSETTING( 0x20, "Single" ) PORT_DIPSETTING( 0x00, "Dual" ) PORT_SERVICE( 0x40, IP_ACTIVE_LOW ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END /*************************************************************************** Machine Driver ***************************************************************************/ static struct YM2151interface ym2151_interface = { 1, /* 1 chip */ 3579545, /* 3.579545 MHz */ { YM3012_VOL(100,MIXER_PAN_LEFT,100,MIXER_PAN_RIGHT) }, { 0 }, }; static struct K053260_interface k053260_interface = { 3579545, REGION_SOUND1, /* memory region */ { MIXER(70,MIXER_PAN_LEFT), MIXER(70,MIXER_PAN_RIGHT) }, // sound_nmi_callback }; static struct MachineDriver machine_driver_parodius = { /* basic machine hardware */ { { CPU_KONAMI, /* 053248 */ 3000000, /* ? */ parodius_readmem,parodius_writemem,0,0, parodius_interrupt,1 }, { CPU_Z80 | CPU_AUDIO_CPU, 3579545, parodius_readmem_sound, parodius_writemem_sound,0,0, ignore_interrupt,0 /* IRQs are triggered by the main CPU */ /* NMIs are triggered by the 053260 */ } }, 60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */ parodius_init_machine, /* video hardware */ 64*8, 32*8, { 14*8, (64-14)*8-1, 2*8, 30*8-1 }, 0, /* gfx decoded by konamiic.c */ 2048, 2048, 0, VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE, 0, parodius_vh_start, parodius_vh_stop, parodius_vh_screenrefresh, /* sound hardware */ SOUND_SUPPORTS_STEREO,0,0,0, { { SOUND_YM2151, &ym2151_interface }, { SOUND_K053260, &k053260_interface } } }; /*************************************************************************** Game ROMs ***************************************************************************/ ROM_START( parodius ) ROM_REGION( 0x51000, REGION_CPU1 ) /* code + banked roms + palette RAM */ ROM_LOAD( "955e01.bin", 0x10000, 0x20000, 0x49baa334 ) ROM_LOAD( "955e02.bin", 0x30000, 0x18000, 0x14010d6f ) ROM_CONTINUE( 0x08000, 0x08000 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the sound CPU */ ROM_LOAD( "955e03.bin", 0x0000, 0x10000, 0x940aa356 ) ROM_REGION( 0x100000, REGION_GFX1 ) /* graphics ( don't dispose as the program can read them ) */ ROM_LOAD( "955d07.bin", 0x000000, 0x080000, 0x89473fec ) /* characters */ ROM_LOAD( "955d08.bin", 0x080000, 0x080000, 0x43d5cda1 ) /* characters */ ROM_REGION( 0x100000, REGION_GFX2 ) /* graphics ( don't dispose as the program can read them ) */ ROM_LOAD( "955d05.bin", 0x000000, 0x080000, 0x7a1e55e0 ) /* sprites */ ROM_LOAD( "955d06.bin", 0x080000, 0x080000, 0xf4252875 ) /* sprites */ ROM_REGION( 0x80000, REGION_SOUND1 ) /* 053260 samples */ ROM_LOAD( "955d04.bin", 0x00000, 0x80000, 0xe671491a ) ROM_END /*************************************************************************** Game driver(s) ***************************************************************************/ static void parodius_banking(int lines) { unsigned char *RAM = memory_region(REGION_CPU1); int offs = 0; //if (lines & 0xf0) logerror("%04x: setlines %02x\n",cpu_get_pc(),lines); offs = 0x10000 + (((lines & 0x0f)^0x0f) * 0x4000); if (offs >= 0x48000) offs -= 0x40000; cpu_setbank( 1, &RAM[offs] ); } static void parodius_init_machine( void ) { unsigned char *RAM = memory_region(REGION_CPU1); konami_cpu_setlines_callback = parodius_banking; paletteram = &memory_region(REGION_CPU1)[0x48000]; videobank = 0; /* init the default bank */ cpu_setbank(1,&RAM[0x10000]); } static void init_parodius(void) { konami_rom_deinterleave_2(REGION_GFX1); konami_rom_deinterleave_2(REGION_GFX2); } GAME( 1990, parodius, 0, parodius, parodius, parodius, ROT0, "Konami", "Parodius DA! (Japan)" )
[ [ [ 1, 437 ] ] ]
d788b85c972286235ad20a8d8fa525571376040c
4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8
/Trunk/Battle Cars/Battle Cars/Source/CCharacterSelection.h
396f077438d858687899d5f672c382f32d0d09f6
[]
no_license
FiveFourFive/battle-cars
5f2046e7afe5ac50eeeb9129b87fcb4b2893386c
1809cce27a975376b0b087a96835347069fe2d4c
refs/heads/master
2021-05-29T19:52:25.782568
2011-07-28T17:48:39
2011-07-28T17:48:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
h
#ifndef CHARACTER_H_ #define CHARACTER_H_ #include "IGameState.h" #include <vector> using namespace std; class CSGD_TextureManager; class CPrintFont; class CSGD_FModManager; class CSGD_DirectInput; class CXboxInput; class CPlayer; class CCharacterSelection : public IGameState { private: CSGD_TextureManager* m_pTM; CPrintFont* m_pPF; CSGD_FModManager* m_pFM; CSGD_DirectInput* m_pDI; vector<CPlayer*> m_vPlayerList; bool isAvailable[4]; CPlayer* currPlayer; CPlayer* m_player1; CPlayer* m_player2; int m_nBGImageID; int m_nFontID; int m_nSelection; int m_nMenuSelect; int m_nMenuMove; int m_nIncorrectSelection; bool m_bPlayer1_turn; bool m_bPlayer2_turn; // Make it a Singleton CCharacterSelection(); ~CCharacterSelection(); CCharacterSelection& operator=(const CCharacterSelection&); CCharacterSelection(const CCharacterSelection&); public: static CCharacterSelection* GetInstance(); void Enter(void); void Exit(void); bool Input(void); void Update(float fElapsedTime); void Render(void); bool HandleEnter(void); bool LoadCharacters(); bool IsPlayer1Selecting(){ return m_bPlayer1_turn; } bool IsPlayer2Selecting(){ return m_bPlayer2_turn; } CPlayer* GetPlayer1(){ return m_player1;} CPlayer* GetPlayer2(){ return m_player2;} vector<CPlayer*> GetList() { return m_vPlayerList;} }; #endif
[ "[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330", "[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330" ]
[ [ [ 1, 29 ], [ 31, 69 ] ], [ [ 30, 30 ] ] ]
f5306cedd5f49c0c2b5bd36a3de187b7e32b63de
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Source/Base/Field/OSGPathType.h
a15caf3630a02583c13fa7636cf2241e545830f4
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,159
h
/*---------------------------------------------------------------------------*\ * OpenSG Toolbox Toolbox * * * * * * * * * * www.vrac.iastate.edu * * * * Authors: David Kabala * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ #ifndef _OSG_PATH_TYPE_H_ #define _OSG_PATH_TYPE_H_ #ifdef __sgi #pragma once #endif //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "OSGConfig.h" #include "OSGBaseDef.h" #include "OSGFieldType.h" #include "OSGBaseFieldTraits.h" #include "OSGDataType.h" #include "OSGSField.h" #include "OSGMField.h" #include <boost/filesystem/path.hpp> #include <boost/filesystem/exception.hpp> OSG_BEGIN_NAMESPACE typedef boost::filesystem::path BoostPath; // The FieldDataTraits class contains the methods needed to implement // the features a Field data element needs to have template <> struct FieldTraits<BoostPath> : public FieldTraitsTemplateBase<BoostPath> { // Static DataType descriptor, see OSGNewFieldType.cpp for implementation static DataType _type; typedef FieldTraits<std::string> Self; // Define whether string conversions are available. It is strongly // recommended to implement both. enum { Convertible = (Self::ToStreamConvertible | Self::FromStringConvertible) }; // access method for the DataType static OSG_BASE_DLLMAPPING DataType &getType (void) { return _type; } // Access to the names of the actual Fields static const Char8 *getSName (void) { return "SFBoostPath"; } static const Char8 *getMName (void) { return "MFBoostPath"; } // Create a default instance of the class, needed for Field creation static BoostPath getDefault (void) { return BoostPath(); } // This is where it gets interesting: the conversion functions // String conversion // Output inVal into outVal // the exact mapping doesn't matter, // Our recommendation is to output as a string, // i.e. start and stop with ", as this simplifies integration into the // OSG Loader. static void putToStream(const BoostPath &inVal, OutStream &outVal) { FieldTraits<std::string>::putToStream(inVal.string(), outVal); } // Setup outVal from the contents of inVal // For complicated classes it makes sense to implement this function // as a class method and just call that from here static bool getFromCString( BoostPath &outVal, const Char8 *&inVal) { std::string PathString(""); if( FieldTraits<std::string>::getFromCString(PathString, inVal) ) { try { outVal = PathString; return true; } catch(boost::filesystem::filesystem_error& error) { SWARNING << "ERROR in creating file path from string:" << error.what() << std::endl; return false; } } else { return false; } } // Binary conversion // Return the size of the binary version in byte // There are two versions of this function, one for a single object, // one for an array of objects static UInt32 getBinSize(const BoostPath & obj) { return FieldTraits<std::string>::getBinSize(obj.string()); } static UInt32 getBinSize (const BoostPath *obj, UInt32 num) { //Size: //Sum of all the objs UInt32 SizeSum(0); for(UInt32 i = 0; i < num; ++i) { SizeSum += FieldTraits<std::string>::getBinSize(obj[i].string()); } return SizeSum; } // Copy the object into the BinaryDataHandler // the BDH has a number of methods to add a simple type to the stream // just use those and use the same order to read them back in. // Again there are two versions, one for a single object, one for an // array of objects static void copyToBin( BinaryDataHandler &bdh, const BoostPath &obj) { FieldTraits<std::string>::copyToBin(bdh, obj.string()); } static void copyToBin( BinaryDataHandler &bdh, const BoostPath *objs, UInt32 num) { for(UInt32 i = 0; i < num; ++i) { copyToBin(bdh, objs[i]); } } // Copy the object from the BinaryDataHandler // the BDH has a number of methods to get a simple type from the stream // just use those and use the same order you used to write them out. // Again there are two versions, one for a single object, one for an // array of objects static void copyFromBin(BinaryDataHandler &bdh, BoostPath &obj) { std::string PathString(""); FieldTraits<std::string>::copyFromBin(bdh, PathString); try { obj = PathString; } catch(boost::filesystem::filesystem_error& error) { SWARNING << "ERROR in creating file path from binary:" << error.what() << std::endl; } } static void copyFromBin(BinaryDataHandler &bdh, BoostPath *objs, UInt32 num) { for(UInt32 i = 0; i < num; ++i) { copyFromBin(bdh, objs[i]); } } }; #ifndef DOXYGEN_SHOULD_SKIP_THIS // Here the actual Field types are declared // You don't always have to have both, either is fine typedef SField<BoostPath> SFBoostPath; typedef MField<BoostPath> MFBoostPath; #else // these are the doxygen hacks /*! \ingroup GrpBaseFieldSingle \ingroup GrpLibOSGBase */ struct SFBoostPath : public SField<BoostPath> {}; struct MFBoostPath : public MField<BoostPath> {}; #endif // these are the doxygen hacks OSG_END_NAMESPACE #endif /* _OSG_PATH_TYPE_H_ */
[ [ [ 1, 28 ], [ 31, 38 ], [ 41, 41 ], [ 45, 45 ], [ 48, 53 ], [ 55, 60 ], [ 62, 65 ], [ 68, 69 ], [ 72, 73 ], [ 75, 76 ], [ 79, 80 ], [ 82, 82 ], [ 84, 93 ], [ 96, 96 ], [ 98, 102 ], [ 104, 106 ], [ 108, 133 ], [ 135, 135 ], [ 137, 138 ], [ 140, 145 ], [ 147, 156 ], [ 158, 158 ], [ 160, 162 ], [ 164, 178 ], [ 180, 181 ], [ 183, 194 ], [ 196, 204 ], [ 207, 209 ], [ 212, 212 ], [ 214, 214 ], [ 218, 218 ], [ 220, 222 ] ], [ [ 29, 30 ], [ 39, 40 ], [ 42, 44 ], [ 46, 47 ], [ 66, 67 ], [ 70, 71 ], [ 74, 74 ], [ 83, 83 ], [ 95, 95 ], [ 97, 97 ], [ 107, 107 ], [ 136, 136 ], [ 146, 146 ], [ 159, 159 ], [ 182, 182 ], [ 205, 206 ], [ 213, 213 ], [ 215, 215 ], [ 219, 219 ], [ 223, 223 ] ], [ [ 54, 54 ], [ 61, 61 ], [ 77, 78 ], [ 81, 81 ], [ 94, 94 ], [ 103, 103 ], [ 134, 134 ], [ 139, 139 ], [ 157, 157 ], [ 163, 163 ], [ 179, 179 ], [ 195, 195 ], [ 210, 211 ], [ 216, 217 ] ], [ [ 224, 225 ] ] ]
fb29fc9aacd6b3b0563bba829d0bc452b910d8c9
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.7/cbear.berlios.de/windows/registry/hkey.hpp
d8cc5530f11dcbe24674b225151ce70e1e44311a
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
5,290
hpp
#ifndef CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_HKEY_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_HKEY_HPP_INCLUDED #include <Winreg.h> #include <cbear.berlios.de/policy/main.hpp> #include <cbear.berlios.de/windows/base.hpp> #include <cbear.berlios.de/windows/lpstr.hpp> #include <cbear.berlios.de/windows/exception.hpp> #include <cbear.berlios.de/windows/select.hpp> #include <cbear.berlios.de/windows/security_attributes.hpp> #include <cbear.berlios.de/windows/registry/disposition.hpp> #include <cbear.berlios.de/windows/registry/sam.hpp> #include <cbear.berlios.de/windows/registry/options.hpp> #include <cbear.berlios.de/windows/registry/value.hpp> // RegCloseKey, ... #pragma comment(lib, "advapi32.lib") namespace cbear_berlios_de { namespace windows { namespace registry { class hkey: public policy::wrap<hkey, ::HKEY> { typedef policy::wrap<hkey, ::HKEY> wrap_type; public: BOOST_STATIC_ASSERT(sizeof(int)>=sizeof(internal_type)); enum enumeration_type { classes_root = reinterpret_cast<std::ptrdiff_t>(HKEY_CLASSES_ROOT), current_user = reinterpret_cast<std::ptrdiff_t>(HKEY_CURRENT_USER), local_machine = reinterpret_cast<std::ptrdiff_t>(HKEY_LOCAL_MACHINE), users = reinterpret_cast<std::ptrdiff_t>(HKEY_USERS), performance_data = reinterpret_cast<std::ptrdiff_t>(HKEY_PERFORMANCE_DATA), //performance_text = // reinterpret_cast<std::ptrdiff_t>(HKEY_PERFORMANCE_TEXT), //performance_nlstext = // reinterpret_cast<std::ptrdiff_t>(HKEY_PERFORMANCE_NLSTEXT), current_config = reinterpret_cast<std::ptrdiff_t>(HKEY_CURRENT_CONFIG), dyn_data = reinterpret_cast<std::ptrdiff_t>(HKEY_DYN_DATA), }; typedef wrap_type::internal_type internal_type; hkey() {} hkey(enumeration_type X): wrap_type(internal_type(X)) {} template<class Char> class create_options { public: basic_lpstr<const Char> class_; registry::options options; registry::sam sam; windows::security_attributes security_attributes; create_options() {} create_options( basic_lpstr<const Char> class_, registry::options options, registry::sam sam, windows::security_attributes security_attributes): class_(class_), options(options), sam(sam), security_attributes(security_attributes) { } }; class create_result; template<class Char> create_result create( basic_lpstr<const Char> SubKey, const create_options<Char> &Options) const { create_result Result; exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegCreateKeyEx)( //HKEY hKey, this->internal(), // LPCTSTR lpSubKey, SubKey.get(), //DWORD Reserved, 0, //LPTSTR lpClass, const_cast<Char *>(Options.class_.get()), //DWORD dwOptions, Options.options.internal(), //REGSAM samDesired, Options.sam.internal(), //LPSECURITY_ATTRIBUTES lpSecurityAttributes, Options.security_attributes.get(), //PHKEY phkResult, &Result.hkey.internal(), //LPDWORD lpdwDisposition, &Result.disposition.internal())); return Result; } template<class Char> hkey connect(const basic_lpstr<const Char> &X) const { hkey Result; exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegConnectRegistry)( X.internal(), this->internal(), &Result.internal())); return Result; } template<class Char> hkey open(const basic_lpstr<const Char> &SubKey, sam Sam) const { hkey Result; exception::throw_if(CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegOpenKeyEx)( this->internal(), SubKey.get(), 0, Sam.internal(), &Result.internal())); return Result; } template<class Char> void delete_(const basic_lpstr<const Char> &X) const { exception::throw_if(CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegDeleteKey)( this->internal(), X.get())); } void flush() const { exception::throw_if(::RegFlushKey(this->internal())); } void close() const { exception::throw_if(::RegCloseKey(this->internal())); } template<class Char, class DataType> void set_value( const basic_lpstr<const Char> &ValueName, const DataType &Data) const { typedef data<Char> data_type; typedef typename data_type::properties_type properties_type; properties_type Properties = data_type::properties(Data); exception::throw_if(CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, RegSetValueEx)( this->internal(), ValueName.get(), 0, Properties.id.get(), Properties.begin, Properties.size)); } template<class Char> void set_value(const value<Char> &Value) const { this->set_value<Char>(Value.first, Value.second); } template<class Char> void set_value(const data<Char> &Data) const { this->set_value(basic_lpstr<const Char>(), Data); } template<class Char> void delete_value(const basic_lpstr<const Char> &ValueName) { exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegDeleteValue)( this->internal(), ValueName.get())); } void delete_value() { this->delete_value(lpcstr_t()); } }; class hkey::create_result { public: hkey hkey; disposition disposition; }; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 204 ] ] ]
c8b45b4ffc7c61d10995779f6c6e397b1d72c4a9
028d6009f3beceba80316daa84b628496a210f8d
/uidesigner/com.nokia.sdt.referenceprojects.test/data/settings_list_3_0/reference/src/settings_list_3_0AppUi.cpp
90d75eec41010fab9fe267d196ba563b298811aa
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,807
cpp
// [[[ begin generated region: do not modify [Generated System Includes] #include <eikmenub.h> #include <akncontext.h> #include <akntitle.h> #include <settings_list_3_0.rsg> // ]]] end generated region [Generated System Includes] // [[[ begin generated region: do not modify [Generated User Includes] #include "settings_list_3_0AppUi.h" #include "settings_list_3_0.hrh" #include "Settings_list_3_0SettingItemListView.h" // ]]] end generated region [Generated User Includes] // [[[ begin generated region: do not modify [Generated Constants] // ]]] end generated region [Generated Constants] /** * Construct the Csettings_list_3_0AppUi instance */ Csettings_list_3_0AppUi::Csettings_list_3_0AppUi() { // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } /** * The appui's destructor removes the container from the control * stack and destroys it. */ Csettings_list_3_0AppUi::~Csettings_list_3_0AppUi() { // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } // [[[ begin generated function: do not modify void Csettings_list_3_0AppUi::InitializeContainersL() { iSettings_list_3_0SettingItemListView = CSettings_list_3_0SettingItemListView::NewL(); AddViewL( iSettings_list_3_0SettingItemListView ); SetDefaultViewL( *iSettings_list_3_0SettingItemListView ); } // ]]] end generated function /** * Handle a command for this appui (override) * @param aCommand command id to be handled */ void Csettings_list_3_0AppUi::HandleCommandL( TInt aCommand ) { // [[[ begin generated region: do not modify [Generated Code] TBool commandHandled = EFalse; switch ( aCommand ) { // code to dispatch to the AppUi's menu and CBA commands is generated here default: break; } if ( !commandHandled ) { if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit ) { Exit(); } } // ]]] end generated region [Generated Code] } /** * Override of the HandleResourceChangeL virtual function */ void Csettings_list_3_0AppUi::HandleResourceChangeL( TInt aType ) { CAknViewAppUi::HandleResourceChangeL( aType ); // [[[ begin generated region: do not modify [Generated Code] // ]]] end generated region [Generated Code] } /** * Override of the HandleKeyEventL virtual function * @return EKeyWasConsumed if event was handled, EKeyWasNotConsumed if not * @param aKeyEvent * @param aType */ TKeyResponse Csettings_list_3_0AppUi::HandleKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ) { // The inherited HandleKeyEventL is private and cannot be called // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] return EKeyWasNotConsumed; } /** * Override of the HandleViewDeactivation virtual function * * @param aViewIdToBeDeactivated * @param aNewlyActivatedViewId */ void Csettings_list_3_0AppUi::HandleViewDeactivation( const TVwsViewId& aViewIdToBeDeactivated, const TVwsViewId& aNewlyActivatedViewId ) { CAknViewAppUi::HandleViewDeactivation( aViewIdToBeDeactivated, aNewlyActivatedViewId ); // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } /** * @brief Completes the second phase of Symbian object construction. * Put initialization code that could leave here. */ void Csettings_list_3_0AppUi::ConstructL() { // [[[ begin generated region: do not modify [Generated Contents] BaseConstructL( EAknEnableSkin ); InitializeContainersL(); // ]]] end generated region [Generated Contents] }
[ [ [ 1, 132 ] ] ]
d0f431769d9259860a092e1fcc75414255c007e0
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/infostudio/InfoStudio/test/main.cpp
e71e5c33eadc3b63ec633d6a6d3bb3300bec50fe
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
246
cpp
#include <windows.h> extern void test_querymap(); extern void test_core(); int main(int, char**) { HRESULT hRes = ::CoInitialize(NULL); ::DefWindowProc(NULL, 0, 0, 0L); test_core(); test_querymap(); return 0; }
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 14 ] ] ]
e0a535252d45e4d91bc8ff988230db8289bb36ed
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziahttpd-mod/src/dataman/resource_report.cc
cbb3d3e81e75789caaa7ec0190550a1a6a9e6802
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
2,111
cc
// // resource_report.cc for in // // Made by texane // Login <[email protected]> // // Started on Wed Nov 23 13:53:31 2005 texane // Last update Fri Dec 02 13:41:07 2005 texane // #include <string> #include <dataman/buffer.hh> #include <dataman/resource.hh> using std::string; using dataman::buffer; dataman::report::report(unsigned int stcode) { stcode_ = stcode; formed_ = false; } dataman::report::~report() {} bool dataman::report::open(openmode_t omode, error_t& err) { // ! // Generate a more elaborated function err = ESUCCESS; if (omode != O_FETCHONLY) { // This kind of resource cannot be // opened in a wriable mode. err = OPNOTSUP; return false; } if (formed_ == true) { err = ALREADYOPENED; return false; } switch (stcode_) { case 404: buf_ = "<html><body><h1>404 Not Found</h1></body></html>"; break; default: buf_ = "<html><body><h1>Default Report Page</h1></body></html>"; break; } formed_ = true; return true; } bool dataman::report::fetch(buffer& buf, unsigned int nbytes, error_t& err) { string substr; err = ESUCCESS; if (buf_.size() == 0) { err = EOFETCHING; return true; } // Normalize the size if (buf_.size() < nbytes) nbytes = buf_.size(); // Take the substring and remove // nbytes from the buffer substr.append(buf_, 0, nbytes); buf_.erase(0, nbytes); buf = substr; return true; } bool dataman::report::fetch(buffer& buf, error_t& err) { err = ESUCCESS; buf = buf_; return true; } bool dataman::report::feed(buffer&, error_t& err) { // This kind of resource cannot // be fed; This is an in memory // buffer, generated only by the // core server. err = OPNOTSUP; return false; } bool dataman::report::close(error_t&) { // release the allocated memory // for the buffer (for the moment, // there is no memory, store in .data) return true; }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 120 ] ] ]
519602f753027496db0b2ad6a3dd1011463edb51
c63c4fed502fd4cbf82acc7901ba0d72b0338bdb
/Create/Controller/EmssController.h
9339b498af25c050f4de71c34a7537da611fed10
[]
no_license
seeyousystems/core
7436a38fb09ea08f5d29cf8db2490c92f48d9267
baddc89a366ad769a1a9c9a59c14f28291b81971
refs/heads/master
2020-05-17T19:11:57.814200
2011-05-06T04:00:59
2011-05-06T04:00:59
1,517,217
1
4
null
null
null
null
UTF-8
C++
false
false
2,844
h
/* * EmssController.h * * The role of the EmssController is relatively simple: continuously and * frequently retrieve sensor data and send movement commands while making * sure to operate safely at all times. The main method for controlling * the robot with the EmssController implementation is via the * setWheelSpeed(...) method. This allows a Core module to set the desired * wheel speed which is then transmitted by the controller to the hardware. * If an unsafe movement is detected, such as driving down a drop or against * a wall, the Controller will ignore any further commands until a reversing * command is desired which is deemed safe. The EmssController will never take * any counter-action to an unsafe command, it will just ignore the command. * This delegates the resolving of an unsafe situation to other modules such * as the Navigation module. * * =========================================================================== * * Copyright 2008-2009 Daniel Kruesi (Dan Krusi) and David Grob * * This file is part of the emms framework. * * The emms framework 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. * * The emms framework 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 software. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef EMSSCONTROLLER_H_ #define EMSSCONTROLLER_H_ #include "Controller.h" #include <QTime> class EmssController: public Controller { Q_OBJECT public: // Variables enum { Idle, WheelDrive, EmergencyStop } mode; short Lwheel; short Rwheel; QTime lastDebugInfo; // Configurations / properties / settings bool debugInfoEnabled; int debugInfoInterval; int bumperCollisionOffset; double cliffCollisionOpacity; int cliffCollisionSize; double bumperCollisionOpacity; int bumperCollisionSize; bool emergencyStopEnabled; double robotWallSensorRange; int robotDiameter; double wallCollisionOpacity; int wallCollisionSize; double irCollisionOpacity; int irCollisionSize; double openAreaOpacity; int openAreaSize; public: EmssController(Create *create, int speed, int interval); ~EmssController(); virtual void process(); private: virtual void emergencyStop(); public slots: virtual void setWheelSpeed(int Lwheel, int Rwheel); }; #endif /* EMSSCONTROLLER_H_ */
[ [ [ 1, 87 ] ] ]
0aa47e88a2e5c8bb17e5e5c903b1ab1fa45a518f
77d0b0ac21a9afdf667099c3cad0f9bbb483dc25
/include/iglu/tscroll.h
106b65542f00854fb4d3135277b8834a8294c625
[]
no_license
martinribelotta/oneshot
21e218bbdfc310bad4a531dcd401ad28625ead75
81bde2718b6dac147282cce8a1c945187b0b2ccf
refs/heads/master
2021-05-27T23:29:43.732068
2010-05-24T04:36:10
2010-05-24T04:36:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,719
h
/* * IGLU Iterfaz Grafica Libre del Usuario. * Copyright (C) 2005 Martin Alejandro Ribelotta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _igluTScroll_h #define _igluTScroll_h #include <iglu/tview.h> #include <iglu/commands.h> #define VScroll 'H' #define HScroll 'V' #define SizeBar 16 #define isChangeUp(x) ((x&0x80000000)!=0L) #define isChangeDown(x) ((x&0x80000000)==0L) #define ScrollValue(x) (x&0x7FFFFFFF) class TScroll: public TView { protected: char hv; int setPosForPoint (TPoint& pos); void getCursorGeomOf (TRect& r, int p); void getCursorGeom (TRect& r); public: long max, min, pos, inc; TScroll (TPoint p, int len, int _hv); virtual void Draw (); virtual void MouseEvent (TEvent&); virtual void TimerEvent (TEvent&); virtual void GotFocus (); virtual void LostFocus (); virtual void resize( int w, int h ); virtual void RecuestAlign( TRect& a, TRect& b ); void SetPos (int); }; #endif /* _igluTScroll_h */
[ [ [ 1, 57 ] ] ]
0000998bdc1327e2cb7cf72ae708c6a7a401f316
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/component/jsjsrendercomponent.cpp
07624dabd79edd3ea76ab66ee007b4b43168b7e8
[]
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
1,680
cpp
#include "precompiled.h" #include "component/jsrendercomponent.h" #include "component/jscomponent.h" #include "entity/jsentity.h" using namespace jscomponent; using namespace component; using namespace script; namespace jscomponent { static bool parseDesc(JSContext* cx, JSObject* obj, JSRenderComponent::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 = { "JSRenderComponent", 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}, WRAPPED_LINK(transform, JSRenderComponent, PosComponent), JS_PS_END }; static JSFunctionSpec class_methods[] = { // JS_FN("name", function, nargs, flags, minargs), JS_FS_END }; } ScriptedObject::ScriptClass JSRenderComponent::m_scriptClass = { &class_ops, class_properties, class_methods, NULL }; REGISTER_SCRIPT_INIT(JSRenderComponent, initClass, 20); static void initClass(ScriptEngine* engine) { RegisterScriptClass<JSRenderComponent, Component>(engine); jsentity::RegisterCreateFunction(engine, "createJSRenderComponent", createComponent<JSRenderComponent>); } bool jscomponent::parseDesc(JSContext* cx, JSObject* obj, JSRenderComponent::desc_type& desc) { GetProperty(cx, obj, "transform", desc.transformComponent); return true; }
[ [ [ 1, 64 ] ] ]
f7c2de332d262424f8da396fcbe618824e43096d
7a2144d11ce57a5286381d91d71b15592de3e7eb
/glm/test/gtc/gtc_half_float.cpp
e8df77c7666931b13b0da161449c08c656a1284c
[ "MIT" ]
permissive
ryanschmitty/RDSTracer
25449db75d2caf2bdbed317f9fa271bb8deda67c
19fddc911c7d193e055ff697c15d76b83ce0b33a
refs/heads/master
2021-01-10T20:38:23.050262
2011-09-20T23:19:46
2011-09-20T23:19:46
1,627,984
0
1
null
null
null
null
UTF-8
C++
false
false
672
cpp
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2010-09-16 // Updated : 2010-09-16 // Licence : This source is under MIT licence // File : test/gtc/matrix_transform.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #define GLM_MESSAGES #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> int main() { int Failed = 0; return Failed; }
[ [ [ 1, 19 ] ] ]
9c0d179e93f7c186d2c740bb1e24936f67124cf4
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndMiniGame.cpp
0bef24962844bfe09f0bd1ee70fb0b4a6e7a7a80
[]
no_license
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
UHC
C++
false
false
48,832
cpp
#include "stdafx.h" #include "defineText.h" #include "AppDefine.h" #include "WndManager.h" #include "WndMiniGame.h" #include "MiniGame.h" #include "defineSound.h" #include "DPClient.h" extern CDPClient g_DPlay; #ifdef __EVE_MINIGAME /************************* CWndKawiBawiBoGame *************************/ CWndKawiBawiBoGame::CWndKawiBawiBoGame() { m_nWinningCount = 0; m_nWinningMaxCount = 0; m_nCount = 0; m_nDelay = 1; m_nMyChoice = KAWI; m_nComChoice = KAWI; m_strChoice[0].Format(" %s", prj.GetText( TID_GAME_KAWIBAWIBO_KAWI )); m_strChoice[1].Format(" %s", prj.GetText( TID_GAME_KAWIBAWIBO_BAWI )); m_strChoice[2].Format(" %s", prj.GetText( TID_GAME_KAWIBAWIBO_BO )); m_pWndGameWin = NULL; m_nStatus = 0; m_nResult = -1; m_nPrevResult = -1; m_bCheckCoupon = TRUE; m_dwRItemId = -1; m_dwRNextItemId = -1; m_nItemCount = -1; m_nNextItemCount = -1; } CWndKawiBawiBoGame::~CWndKawiBawiBoGame() { if(m_pWndGameWin != NULL) SAFE_DELETE(m_pWndGameWin); } void CWndKawiBawiBoGame::OnDestroy() { } BOOL CWndKawiBawiBoGame::Process() { int nCom = -1; if(m_nStatus == 1) //Start버튼 누를 경우 컴퓨터의 선택이 회전하도록 함. { if(m_nCount > m_nDelay) { if(m_nResult > -1) { if(m_nDelay < 20) { PLAYSND( "InfOpen.wav" ); m_nDelay += 1; } else { PLAYSND( "InfOpen.wav" ); nCom = prj.m_MiniGame.GetKawibawiboYou(m_nMyChoice, m_nResult); } } m_nComChoice++; ( m_nComChoice > 2 ) ? m_nComChoice = 0 : m_nComChoice; m_pStComChoice->SetTitle( m_strChoice[m_nComChoice] ); if(m_nComChoice == nCom) { m_nStatus = 2; m_nDelay = 40; } m_nCount = 0; } m_nCount++; } else if(m_nStatus == 2) //Com의 결과가 보여지고 바로 사라지거나 하기 때문에 약간의 Delay를 줌 { if(m_nCount > m_nDelay) { if(m_nResult == CMiniGame::KAWIBAWIBO_WIN) { PlayMusic( BGM_IN_FITUP ); CreateWinningWnd(); } else if(m_nResult == CMiniGame::KAWIBAWIBO_DRAW) { EnableAllBtn(); } else if(m_nResult == CMiniGame::KAWIBAWIBO_LOST) { g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_KAWIBAWIBO_DEFEAT ) ); m_nWinningCount = 0; EnableAllBtn(); RefreshInfo(); } m_nStatus = 0; m_nDelay = 1; m_nResult = -1; } m_nCount++; } return TRUE; } void CWndKawiBawiBoGame::OnDraw( C2DRender* p2DRender ) { CTexture* pTexture; CString strMyPath, strComPath; for(int i=0; i<2; i++) { int nChoice; CString* pstr; if(i == 0) { nChoice = m_nMyChoice; pstr = &strMyPath; switch(nChoice) { case KAWI: *pstr = MakePath( DIR_ICON, "Icon_Kawi1.dds"); break; case BAWI: *pstr = MakePath( DIR_ICON, "Icon_Bawi1.dds"); break; case BO: *pstr = MakePath( DIR_ICON, "Icon_Bo1.dds"); break; } } else if(i == 1) { nChoice = m_nComChoice; pstr = &strComPath; switch(nChoice) { case KAWI: *pstr = MakePath( DIR_ICON, "Icon_Kawi2.dds"); break; case BAWI: *pstr = MakePath( DIR_ICON, "Icon_Bawi2.dds"); break; case BO: *pstr = MakePath( DIR_ICON, "Icon_Bo2.dds"); break; } } } if(strMyPath.GetLength() > 0) { pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, strMyPath, 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( WIDC_STATIC_MY )->rect.left + 3, GetWndCtrl( WIDC_STATIC_MY )->rect.top + 8 ) ); } if(strComPath.GetLength() > 0) { pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, strComPath, 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( WIDC_STATIC_COM )->rect.left + 3, GetWndCtrl( WIDC_STATIC_COM )->rect.top + 8 ) ); } } void CWndKawiBawiBoGame::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 m_pStWinningCount = (CWndStatic*)GetDlgItem( WIDC_WINNING_COUNT ); m_pStMyChoice = (CWndStatic*)GetDlgItem( WIDC_MY_CHOICE ); m_pStComChoice = (CWndStatic*)GetDlgItem( WIDC_COM_CHOICE ); RefreshInfo(); MoveParentCenter(); } BOOL CWndKawiBawiBoGame::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MINIGAME_KAWIBAWIBO, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndKawiBawiBoGame::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndKawiBawiBoGame::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndKawiBawiBoGame::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndKawiBawiBoGame::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndKawiBawiBoGame::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if(message == WNM_CLICKED) { switch(nID) { case WIDC_BTN_LEFT: m_nMyChoice--; ( m_nMyChoice < 0 ) ? m_nMyChoice = 2 : m_nMyChoice; RefreshInfo(); break; case WIDC_BTN_RIGHT: m_nMyChoice++; ( m_nMyChoice > 2 ) ? m_nMyChoice = 0 : m_nMyChoice; RefreshInfo(); break; case WIDC_BTN_START: if(m_bCheckCoupon && g_pPlayer->IsPlayer() && g_pPlayer->m_Inventory.GetAtItemId( II_SYS_SYS_EVE_KAWIBAWIBO ) == NULL) { g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_KAWIBAWIBO_STARTGUID1 ) ); Destroy(); } DisableAllBtn(); m_nStatus = 1; //컴퓨터의 선택을 화면상에 돌리기 위함. g_DPlay.SendKawibawiboStart(); //DpClient에 정보를 넘겨 가위바위보 결과를 기다림. break; case WTBID_CLOSE: if( m_nWinningCount > 0 || m_nStatus != 0 || m_nPrevResult == CMiniGame::KAWIBAWIBO_DRAW ) return FALSE; break; } } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndKawiBawiBoGame::ReceiveResult(int nResult, int nItemCount, int nNextItemCount, DWORD dwItemId, DWORD dwNextItemId) { if(nResult == CMiniGame::KAWIBAWIBO_FAILED) { g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_KAWIBAWIBO_STARTGUID1 ) ); Destroy(); } else { if(nResult == CMiniGame::KAWIBAWIBO_DRAW) m_bCheckCoupon = FALSE; else if(nResult == CMiniGame::KAWIBAWIBO_LOST || nResult == CMiniGame::KAWIBAWIBO_WIN) m_bCheckCoupon = TRUE; m_nPrevResult = m_nResult = nResult; m_nItemCount = nItemCount; m_nNextItemCount = nNextItemCount; m_dwRItemId = dwItemId; m_dwRNextItemId = dwNextItemId; } } void CWndKawiBawiBoGame::CreateWinningWnd() { m_nWinningCount++; RefreshInfo(); if(m_pWndGameWin != NULL) SAFE_DELETE(m_pWndGameWin); m_pWndGameWin = new CWndKawiBawiBoGameWin; m_pWndGameWin->Initialize(this); m_pWndGameWin->SetInfo(m_nItemCount, m_nNextItemCount, m_dwRItemId, m_dwRNextItemId, m_nWinningCount, m_nWinningMaxCount); } void CWndKawiBawiBoGame::RefreshInfo() { CString temp; temp.Format(prj.GetText(TID_GAME_KWAIBAWIBO_WINCOUNT), m_nWinningCount); m_pStWinningCount->SetTitle( temp ); m_pStMyChoice->SetTitle( m_strChoice[m_nMyChoice] ); m_pStComChoice->SetTitle( m_strChoice[m_nComChoice] ); } void CWndKawiBawiBoGame::DisableAllBtn() { CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_LEFT ); pButton->EnableWindow(FALSE); pButton = (CWndButton*)GetDlgItem( WIDC_BTN_RIGHT ); pButton->EnableWindow(FALSE); pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); } void CWndKawiBawiBoGame::EnableAllBtn() { CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_LEFT ); pButton->EnableWindow(TRUE); pButton = (CWndButton*)GetDlgItem( WIDC_BTN_RIGHT ); pButton->EnableWindow(TRUE); pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(TRUE); } /************************* CWndKawiBawiBoGameWin *************************/ CWndKawiBawiBoGameWin::CWndKawiBawiBoGameWin() { m_pWndGame = NULL; m_dwItemID = -1; m_dwNextItemID = -1; m_nItemCount = -1; m_nNextItemCount = -1; } CWndKawiBawiBoGameWin::~CWndKawiBawiBoGameWin() { } void CWndKawiBawiBoGameWin::OnDestroy() { if(m_pWndGame != NULL) { m_pWndGame->RefreshInfo(); m_pWndGame->EnableAllBtn(); } } void CWndKawiBawiBoGameWin::OnDraw( C2DRender* p2DRender ) { if(m_dwItemID != -1 && m_dwNextItemID != -1) { ItemProp* pItemProp; CTexture* pTexture; CPoint point; pItemProp = prj.GetItemProp( m_dwItemID ); if(pItemProp != NULL) { point = CPoint( GetWndCtrl( WIDC_CURRENT_PRESENT )->rect.left + 16, GetWndCtrl( WIDC_CURRENT_PRESENT )->rect.top + 16 ); pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, pItemProp->szIcon), 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, point); if(m_nItemCount > 1) { TCHAR szTemp[ 32 ]; _stprintf( szTemp, prj.GetText(TID_GAME_KWAIBAWIBO_PRESENT_NUM), m_nItemCount ); CSize size = m_p2DRender->m_pFont->GetTextExtent( szTemp ); m_p2DRender->TextOut( point.x + 36 - size.cx, point.y + 48 - size.cy, szTemp, 0xff0000ff ); } } pItemProp = prj.GetItemProp( m_dwNextItemID ); if(pItemProp != NULL) { point = CPoint( GetWndCtrl( WIDC_NEXT_PRESENT )->rect.left + 16, GetWndCtrl( WIDC_NEXT_PRESENT )->rect.top + 16 ); pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, pItemProp->szIcon), 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, point); if(m_nNextItemCount > 1) { TCHAR szTemp[ 32 ]; _stprintf( szTemp, prj.GetText(TID_GAME_KWAIBAWIBO_PRESENT_NUM), m_nNextItemCount ); CSize size = m_p2DRender->m_pFont->GetTextExtent( szTemp ); m_p2DRender->TextOut( point.x + 36 - size.cx, point.y + 48 - size.cy, szTemp, 0xff0000ff ); } } } } void CWndKawiBawiBoGameWin::OnMouseWndSurface(CPoint point) { CItemElem itemElem; CRect rectHittest = GetWndCtrl(WIDC_CURRENT_PRESENT)->rect; if( rectHittest.PtInRect(point) ) { itemElem.m_dwItemId = m_dwItemID; itemElem.m_nItemNum = 1; CPoint point2 = point; ClientToScreen( &point2 ); ClientToScreen( &rectHittest ); g_WndMng.PutToolTip_Item( &itemElem, point2, &rectHittest ); } rectHittest = GetWndCtrl(WIDC_NEXT_PRESENT)->rect; if( rectHittest.PtInRect(point) ) { itemElem.m_dwItemId = m_dwNextItemID; itemElem.m_nItemNum = 1; CPoint point2 = point; ClientToScreen( &point2 ); ClientToScreen( &rectHittest ); g_WndMng.PutToolTip_Item( &itemElem, point2, &rectHittest ); } } void CWndKawiBawiBoGameWin::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 CWndKawiBawiBoGame* pWndGame = (CWndKawiBawiBoGame*)GetWndBase( APP_MINIGAME_KAWIBAWIBO ); if(pWndGame != NULL) { CRect rectRoot = pWndGame->m_pWndRoot->GetLayoutRect(); CRect rectGame = pWndGame->GetWindowRect( TRUE ); CPoint ptMove; CPoint ptGame; CRect rect = GetWindowRect( TRUE ); int wndWidth = rect.Width(); if(rectRoot.right - rectGame.right < wndWidth) { ptGame = rectGame.TopLeft(); ptMove = ptGame + CPoint(-(10+wndWidth), 0); } else { ptGame = rectGame.BottomRight(); ptMove = ptGame + CPoint(10, -rectGame.Height()); } Move( ptMove ); } CWndStatic* pStatic; CWndText* pText; pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC3 ); pStatic->SetTitle(prj.GetText(TID_GMAE_KAWIBAWIBO_CUR_PRESENT)); pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC4 ); pStatic->SetTitle(prj.GetText(TID_GAME_KWAIBAWIBO_NXT_PRESENT)); pText = (CWndEdit*)GetDlgItem( WIDC_TEXT_GUID ); pText->SetString(prj.GetText( TID_GAME_KAWIBAWIBO_GUID1 )); pText->AddString(prj.GetText( TID_GAME_KAWIBAWIBO_GUID2 ), 0xffff0000); } BOOL CWndKawiBawiBoGameWin::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { m_pWndGame = (CWndKawiBawiBoGame*)pWndParent; // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MINIGAME_KAWIBAWIBO_WIN, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndKawiBawiBoGameWin::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndKawiBawiBoGameWin::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndKawiBawiBoGameWin::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndKawiBawiBoGameWin::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndKawiBawiBoGameWin::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if(message == WNM_CLICKED) { switch(nID) { case WIDC_BTN_END: //End일 경우 상품을 받는다. g_DPlay.SendKawibawiboGetItem(); if(m_pWndGame != NULL) { //m_pWndGame->m_nWinningCount = 0; m_pWndGame->m_bCheckCoupon = TRUE; } Destroy(); break; case WIDC_BTN_NEXT: //Next일 경우 승수를 증가시키고 다시 게임을 진행한다. if(m_pWndGame != NULL) { //m_pWndGame->m_nWinningCount++; m_pWndGame->m_bCheckCoupon = FALSE; } Destroy(); break; case WTBID_CLOSE: return FALSE; break; } } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndKawiBawiBoGameWin::SetInfo(int nItemCount, int nNextItemCount, DWORD dwItemId, DWORD dwNextItemId, int nWinningCount, int nWinningMaxCount) { m_nItemCount = nItemCount; m_nNextItemCount = nNextItemCount; m_dwItemID = dwItemId; m_dwNextItemID = dwNextItemId; if(nWinningCount >= nWinningMaxCount) { CWndButton* pWndButton = (CWndButton*)GetDlgItem(WIDC_BTN_NEXT); assert(pWndButton != NULL); pWndButton->EnableWindow(FALSE); } } /****************************** CWndKawiBawiBoGameConfirm *******************************/ CWndKawiBawiBoGameConfirm::CWndKawiBawiBoGameConfirm() { } CWndKawiBawiBoGameConfirm::~CWndKawiBawiBoGameConfirm() { } void CWndKawiBawiBoGameConfirm::OnDestroy() { } void CWndKawiBawiBoGameConfirm::OnDraw( C2DRender* p2DRender ) { } void CWndKawiBawiBoGameConfirm::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 CRect rect = GetClientRect(); int x = m_rectClient.Width() / 2; int y = m_rectClient.Height() - 30; CSize size = CSize(60,25); CRect rect2_1( x - size.cx - 10, y, ( x - size.cx - 10 ) + size.cx, y + size.cy ); CRect rect2_2( x + 10 , y, ( x + 10 ) + size.cx, y + size.cy ); rect.DeflateRect( 10, 10, 10, 35 ); m_wndText.AddWndStyle( WBS_VSCROLL ); m_wndText.Create( WBS_NODRAWFRAME, rect, this, 0 ); m_strText = prj.GetText( TID_GAME_KAWIBAWIBO_STARTGUID2 ); m_wndText.SetString( m_strText, 0xff000000 ); m_wndText.ResetString(); m_wndButton1.Create("OK" , 0, rect2_1, this, IDOK ); m_wndButton2.Create("CANCEL", 0, rect2_2, this, IDCANCEL); m_wndButton1.SetTexture( m_pApp->m_pd3dDevice, MakePath( DIR_THEME, "ButtOk.tga" ) ); m_wndButton2.SetTexture( m_pApp->m_pd3dDevice, MakePath( DIR_THEME, "ButtCancel.tga" ) ); m_wndButton1.FitTextureSize(); m_wndButton2.FitTextureSize(); MoveParentCenter(); } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndKawiBawiBoGameConfirm::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MESSAGEBOX, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndKawiBawiBoGameConfirm::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndKawiBawiBoGameConfirm::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndKawiBawiBoGameConfirm::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndKawiBawiBoGameConfirm::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndKawiBawiBoGameConfirm::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == IDOK ) { SAFE_DELETE( g_WndMng.m_pWndKawiBawiBoGame ); g_WndMng.m_pWndKawiBawiBoGame = new CWndKawiBawiBoGame; g_WndMng.m_pWndKawiBawiBoGame->Initialize(); } else if( nID == IDCANCEL ) { //그냥 종료 } Destroy(); return CWndNeuz::OnChildNotify( message, nID, pLResult ); } /************************* CWndFindWordGame *************************/ CWndFindWordGame::CWndFindWordGame() { for(int i=0; i<5; i++) { m_itemID[i] = -1; m_pItemElem[i] = NULL; } m_pStaticID[0] = WIDC_WORD_NUM1; m_pStaticID[1] = WIDC_WORD_NUM2; m_pStaticID[2] = WIDC_WORD_NUM3; m_pStaticID[3] = WIDC_WORD_NUM4; m_pStaticID[4] = WIDC_WORD_NUM5; m_nSelectCtrl = -1; m_pText = NULL; m_nPublic = 0; m_bGetFirst = FALSE; m_bStart = TRUE; m_pWndInventory = NULL; } CWndFindWordGame::~CWndFindWordGame() { } void CWndFindWordGame::OnDestroy() { for(int i=0; i<5; i++) { if(m_pItemElem[i] != NULL) { if( !g_pPlayer->m_vtInfo.IsTrading( m_pItemElem[i] ) ) m_pItemElem[i]->SetExtra(0); m_pItemElem[i] = NULL; } } if(m_pWndInventory != NULL) m_pWndInventory->m_wndItemCtrl.SetDieFlag(FALSE); } void CWndFindWordGame::SetFirstWord(int nPublic, char nChar) { m_nPublic = nPublic; m_firstwordID = nChar - 'A' + II_SYS_SYS_EVE_A_CARD; m_bGetFirst = TRUE; } BOOL CWndFindWordGame::Process() { if(m_bStart) { BOOL checkfull = TRUE; CWndButton* pButton; for(int i=0; i<5; i++) { if(m_pItemElem[i] == NULL) checkfull = FALSE; } if(checkfull) { pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(TRUE); m_bStart = FALSE; } else { pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); m_bStart = FALSE; } } return TRUE; } void CWndFindWordGame::OnDraw( C2DRender* p2DRender ) { ItemProp* pItemProp; CTexture* pTexture; //현재 선택된 Ctrl 기억하기. CPoint point = GetMousePoint(); m_nSelectCtrl = HitTest( point ); //Server로 부터 받은 힌트 단어는 흐리게 그리기. if(m_bGetFirst) { pItemProp = prj.GetItemProp( m_firstwordID ); if(pItemProp != NULL) { pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, pItemProp->szIcon), 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( m_pStaticID[m_nPublic] )->rect.left, GetWndCtrl( m_pStaticID[m_nPublic] )->rect.top ), 100 ); } } //나머지 올려진 단어 그리기. for(int i=0; i<5; i++) { if(m_pItemElem[i] != NULL) { pItemProp = m_pItemElem[i]->GetProp(); if(pItemProp != NULL) { pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, pItemProp->szIcon), 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( m_pStaticID[i] )->rect.left, GetWndCtrl( m_pStaticID[i] )->rect.top ) ); } } } } BOOL CWndFindWordGame::OnDropIcon( LPSHORTCUT pShortcut, CPoint point ) { CItemElem* pItemElem = (CItemElem*)g_pPlayer->GetItemId( pShortcut->m_dwId ); if(pItemElem != NULL && (pItemElem->GetProp()->dwID >= II_SYS_SYS_EVE_A_CARD && pItemElem->GetProp()->dwID <= II_SYS_SYS_EVE_Z_CARD)) { if( m_nSelectCtrl > -1 && m_itemID[m_nSelectCtrl] == -1) { m_pItemElem[m_nSelectCtrl] = pItemElem; pItemElem->SetExtra(pItemElem->GetExtra()+1); m_itemID[m_nSelectCtrl] = pItemElem->GetProp()->dwID; m_bStart = TRUE; } } return TRUE; } void CWndFindWordGame::OnLButtonDblClk( UINT nFlags, CPoint point ) { if(m_nSelectCtrl > -1 && m_itemID[m_nSelectCtrl] != -1) { m_itemID[m_nSelectCtrl] = -1; if(m_pItemElem[m_nSelectCtrl] != NULL) { m_pItemElem[m_nSelectCtrl]->SetExtra(m_pItemElem[m_nSelectCtrl]->GetExtra()-1); m_pItemElem[m_nSelectCtrl] = NULL; m_bStart = TRUE; } } } void CWndFindWordGame::SetWord(CItemElem* pItemElem) { int nNum = -1; for(int i=0; i<5; i++) { if(m_itemID[i] == -1) { nNum = i; i = 5; } } if(nNum != -1) { m_itemID[nNum] = pItemElem->GetProp()->dwID; m_pItemElem[nNum] = pItemElem; pItemElem->SetExtra(pItemElem->GetExtra()+1); m_bStart = TRUE; } } void CWndFindWordGame::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 m_pText = (CWndText *)GetDlgItem( WIDC_TEXT_DESC ); m_nQuestionID = 0; CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); SetDescription(NULL); g_DPlay.SendAlphabetOpenWnd(); m_pWndInventory = (CWndInventory*)GetWndBase( APP_INVENTORY ); if(m_pWndInventory != NULL) m_pWndInventory->m_wndItemCtrl.SetDieFlag(TRUE); MoveParentCenter(); } BOOL CWndFindWordGame::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MINIGAME_WORD, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndFindWordGame::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndFindWordGame::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndFindWordGame::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndFindWordGame::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndFindWordGame::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if(message == WNM_CLICKED) { if(nID == WIDC_BTN_START) { BOOL checkall = TRUE; for(int i=0; i<5; i++) { if(m_pItemElem[i] == NULL) checkall = FALSE; else m_itemID[i] = m_pItemElem[i]->m_dwObjId; } if(checkall) { CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); g_DPlay.SendAlphabetStart(m_itemID , 5, m_nQuestionID); //서버로 해당 글자들의 ID를 묶어서 보낸다. } else g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_MINIGAME_EMPTY_ERROR ) ); //글자가 빠져있다면 Error Message를 띄운다. } } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } int CWndFindWordGame::HitTest( CPoint point ) { int rtn_val = -1; for(int i=0; i<5; i++) { if( GetWndCtrl( m_pStaticID[i] )->rect.PtInRect( point ) ) { rtn_val = i; i = 5; } } return rtn_val; } void CWndFindWordGame::SetDescription( CHAR* szChar ) { CScript scanner; BOOL checkflag; if( szChar == NULL ) { checkflag = scanner.Load( MakePath( DIR_CLIENT, _T( "MiniGameFindWordDesc.inc" ) )); szChar = scanner.m_pProg; } else checkflag = TRUE; if(m_pText != NULL && checkflag) { m_pText->m_string.AddParsingString( szChar ); m_pText->ResetString(); } } void CWndFindWordGame::ReceiveResult(int nResult, DWORD dwItemId, int nItemCount) { if(nResult == CMiniGame::ALPHABET_FAILED) g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_FINDWORD_FAIL ) ); else if(nResult == CMiniGame::ALPHABET_NOTENOUGH_MONEY) g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_LACKMONEY ) ); else { CString message; message.Format(prj.GetText( TID_GAME_PUZZLE_GIVEPRESENT )); g_WndMng.OpenMessageBox( message ); } Destroy(); } /************************* CWndDiceGame *************************/ CWndDiceGame::CWndDiceGame() { m_nSelectCtrl = -1; m_pWndDiceTender = NULL; m_pWndMessageBox = NULL; m_nCount = 0; m_nDelay = 1; m_nStatus = -1; m_nDiceNum = 0; m_nPrizePenya = 0; m_nAlpha = 0; m_nDiceChoiceNum = -1; m_bReciveResult = FALSE; m_bSendStart = FALSE; m_bEnd = FALSE; m_bFlsh = TRUE; m_pText = NULL; for(int i=0; i<6; i++) { m_nPenya[i] = 0; m_pCost[i] = NULL; m_pRCost[i] = NULL; } m_pBtnID[0] = WIDC_BTN_NUM1; m_pBtnID[1] = WIDC_BTN_NUM2; m_pBtnID[2] = WIDC_BTN_NUM3; m_pBtnID[3] = WIDC_BTN_NUM4; m_pBtnID[4] = WIDC_BTN_NUM5; m_pBtnID[5] = WIDC_BTN_NUM6; m_pStaticID[0] = WIDC_STATIC2; m_pStaticID[1] = WIDC_STATIC3; m_pStaticID[2] = WIDC_STATIC4; m_pStaticID[3] = WIDC_STATIC5; m_pStaticID[4] = WIDC_STATIC6; m_pStaticID[5] = WIDC_STATIC7; m_pStaticRID[0] = WIDC_STATIC8; m_pStaticRID[1] = WIDC_STATIC9; m_pStaticRID[2] = WIDC_STATIC10; m_pStaticRID[3] = WIDC_STATIC11; m_pStaticRID[4] = WIDC_STATIC12; m_pStaticRID[5] = WIDC_STATIC13; m_pStaticNum[0] = WIDC_STATIC14; m_pStaticNum[1] = WIDC_STATIC15; m_pStaticNum[2] = WIDC_STATIC16; m_pStaticNum[3] = WIDC_STATIC17; m_pStaticNum[4] = WIDC_STATIC18; m_pStaticNum[5] = WIDC_STATIC19; m_strPathDice[0] = MakePath( DIR_ICON, "Icon_1Dice90X90.dds"); m_strPathDice[1] = MakePath( DIR_ICON, "Icon_2Dice90X90.dds"); m_strPathDice[2] = MakePath( DIR_ICON, "Icon_3Dice90X90.dds"); m_strPathDice[3] = MakePath( DIR_ICON, "Icon_4Dice90X90.dds"); m_strPathDice[4] = MakePath( DIR_ICON, "Icon_5Dice90X90.dds"); m_strPathDice[5] = MakePath( DIR_ICON, "Icon_6Dice90X90.dds"); m_strPathDiceNum[0] = MakePath( DIR_ICON, "Icon_1Dice1.dds"); m_strPathDiceNum[1] = MakePath( DIR_ICON, "Icon_2Dice2.dds"); m_strPathDiceNum[2] = MakePath( DIR_ICON, "Icon_3Dice3.dds"); m_strPathDiceNum[3] = MakePath( DIR_ICON, "Icon_4Dice4.dds"); m_strPathDiceNum[4] = MakePath( DIR_ICON, "Icon_5Dice5.dds"); m_strPathDiceNum[5] = MakePath( DIR_ICON, "Icon_6Dice6.dds"); //Default m_nMinPenya = 1000000; m_nMaxPenya = 100000000; m_nMultiple = 5; } CWndDiceGame::~CWndDiceGame() { if(m_pWndDiceTender != NULL) SAFE_DELETE(m_pWndDiceTender); if(m_pWndMessageBox != NULL) SAFE_DELETE(m_pWndMessageBox); } void CWndDiceGame::OnDestroy() { g_DPlay.SendFiveSystemDestroyWnd(); } void CWndDiceGame::SetMinMaxPenya(int nMinPenya, int nMaxPenya, int nMultiple) { m_nMinPenya = nMinPenya; m_nMaxPenya = nMaxPenya; m_nMultiple = nMultiple; CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(TRUE); } void CWndDiceGame::OnDraw( C2DRender* p2DRender ) { CTexture* pTexture; CString strPath; strPath = m_strPathDice[m_nDiceNum]; if(strPath.GetLength() > 0) { pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, strPath, 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( WIDC_STATIC_DICE )->rect.left + 3, GetWndCtrl( WIDC_STATIC_DICE )->rect.top + 4 ) ); } for(int i=0; i<6; i++) { strPath = m_strPathDiceNum[i]; if(strPath.GetLength() > 0) { pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, strPath, 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( m_pStaticNum[i] )->rect.left, GetWndCtrl( m_pStaticNum[i] )->rect.top) ); } } //선택된 숫자에 대한 표시. if(m_bEnd) { if(m_nDiceChoiceNum > -1) { D3DXCOLOR color; if( m_bFlsh == TRUE ) { m_nAlpha += 15; if( m_nAlpha > 230 ) { m_nAlpha = 230; m_bFlsh = FALSE; } } else { m_nAlpha -= 15; if( m_nAlpha < 70 ) { m_nAlpha = 70; m_bFlsh = TRUE; } } color = D3DCOLOR_ARGB( m_nAlpha, 240, 255, 255 ); CRect rect; LPWNDCTRL lpWndCtrl; lpWndCtrl = GetWndCtrl( m_pStaticID[m_nDiceChoiceNum] ); rect = lpWndCtrl->rect; p2DRender->RenderFillRect( rect, color ); lpWndCtrl = GetWndCtrl( m_pStaticRID[m_nDiceChoiceNum] ); rect = lpWndCtrl->rect; p2DRender->RenderFillRect( rect, color ); lpWndCtrl = GetWndCtrl( m_pStaticNum[m_nDiceChoiceNum] ); rect = lpWndCtrl->rect; rect.bottom -= 3; //실제 이미지가 rect보다 공간이 남으므로 조정 rect.right -= 3; p2DRender->RenderFillRect( rect, color ); } } } void CWndDiceGame::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 m_pCost[0] = (CWndText*)GetDlgItem( WIDC_COST_NUM1 ); m_pCost[1] = (CWndText*)GetDlgItem( WIDC_COST_NUM2 ); m_pCost[2] = (CWndText*)GetDlgItem( WIDC_COST_NUM3 ); m_pCost[3] = (CWndText*)GetDlgItem( WIDC_COST_NUM4 ); m_pCost[4] = (CWndText*)GetDlgItem( WIDC_COST_NUM5 ); m_pCost[5] = (CWndText*)GetDlgItem( WIDC_COST_NUM6 ); m_pRCost[0] = (CWndText*)GetDlgItem( WIDC_RCOST_NUM1 ); m_pRCost[1] = (CWndText*)GetDlgItem( WIDC_RCOST_NUM2 ); m_pRCost[2] = (CWndText*)GetDlgItem( WIDC_RCOST_NUM3 ); m_pRCost[3] = (CWndText*)GetDlgItem( WIDC_RCOST_NUM4 ); m_pRCost[4] = (CWndText*)GetDlgItem( WIDC_RCOST_NUM5 ); m_pRCost[5] = (CWndText*)GetDlgItem( WIDC_RCOST_NUM6 ); for(int i=0; i<6; i++) { m_pCost[i]->EnableWindow(FALSE); m_pRCost[i]->EnableWindow(FALSE); } m_pText = (CWndText *)GetDlgItem( WIDC_TEXT_DESC ); SetDescription(NULL); CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); RefreshInfo(); //서버로 창이 열렸음을 보낸다. g_DPlay.SendFiveSystemOpenWnd(); MoveParentCenter(); } BOOL CWndDiceGame::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MINIGAME_DICE, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndDiceGame::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndDiceGame::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndDiceGame::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndDiceGame::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndDiceGame::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if(message == WNM_CLICKED) { m_nSelectCtrl = -1; switch(nID) { case WIDC_BTN_NUM1: m_nSelectCtrl = 0; break; case WIDC_BTN_NUM2: m_nSelectCtrl = 1; break; case WIDC_BTN_NUM3: m_nSelectCtrl = 2; break; case WIDC_BTN_NUM4: m_nSelectCtrl = 3; break; case WIDC_BTN_NUM5: m_nSelectCtrl = 4; break; case WIDC_BTN_NUM6: m_nSelectCtrl = 5; break; case WIDC_BTN_START: BOOL checkusable = FALSE; int i; for(i=0; i<6; i++) { if(m_nPenya[i] > 0) checkusable = TRUE; } if(checkusable) { CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); for(int i=0; i<6; i++) { pButton = (CWndButton*)GetDlgItem( m_pBtnID[i] ); pButton->EnableWindow(FALSE); } m_nStatus = 0; //컴퓨터의 선택을 화면상에 돌리기 위함. } else g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_DICEGAME_ERROR ) ); break; } if(m_nSelectCtrl >= 0 && m_nSelectCtrl < 6) { //금액 임력 창을 띄운다. if(m_pWndDiceTender != NULL) SAFE_DELETE(m_pWndDiceTender); m_pWndDiceTender = new CWndDiceGameTender; m_pWndDiceTender->Initialize(this); m_pWndDiceTender->SetSelectNum(m_nSelectCtrl); m_pWndDiceTender->SetMinMaxPenya(m_nMinPenya, m_nMaxPenya); } } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndDiceGame::RefreshInfo() { CString strtemp; for(int i=0; i<6; i++) { strtemp.Format("%d", m_nPenya[i]); strtemp = GetNumberFormatEx(strtemp); m_pCost[i]->SetString(strtemp, 0xff4d4dff); strtemp.Format("%d", m_nPenya[i] * m_nMultiple); strtemp = GetNumberFormatEx(strtemp); m_pRCost[i]->SetString(strtemp, 0xff9932cd); } } void CWndDiceGame::RefreshCtrl() { CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(TRUE); for(int i=0; i<6; i++) { pButton = (CWndButton*)GetDlgItem( m_pBtnID[i] ); pButton->EnableWindow(TRUE); } m_pWndMessageBox = NULL; m_bEnd = FALSE; m_bSendStart = FALSE; } void CWndDiceGame::CheckPenyaUsuable(int nPenya, int nSelect) { //서버로 해당 금액을 전송하여 유효성 여부를 검사 받는다. g_DPlay.SendFiveSystemBet(nSelect, nPenya); } void CWndDiceGame::SetTenderPenya(int nSelect, int nPenya) { if(nSelect >= 0 && nSelect < 6) { m_nPenya[nSelect] = nPenya; RefreshInfo(); } //나머지 값이 올경우 Error값임. } void CWndDiceGame::ReceiveResult(int nDiceNum, int nPenya) { if(nDiceNum >= 0 && nDiceNum < 6) { m_nDiceNum = nDiceNum; m_nDiceChoiceNum = nDiceNum; m_nPrizePenya = nPenya; m_bReciveResult = TRUE; } } BOOL CWndDiceGame::Process() { //Start버튼 누를 경우 컴퓨터의 선택이 회전하도록 함. if(m_nStatus == 0) { if(m_nCount%4 == 0) { if(m_nCount > 170) { m_nCount = 0; m_nStatus = 1; } else { PLAYSND( "InfOpen.wav" ); int randnum = rand() % 6; if(randnum == m_nDiceNum) { randnum++; ( randnum > 5 ) ? randnum = 0 : randnum; } m_nDiceNum = randnum; } } m_nCount++; } else if(m_nStatus == 1) { if(m_nCount > m_nDelay) { if(m_nDelay < 30) { PLAYSND( "InfOpen.wav" ); m_nDelay += 1; } else { PLAYSND( "InfOpen.wav" ); m_nStatus = 2; m_nDelay = 30; } int randnum = rand() % 6; if(randnum == m_nDiceNum) { randnum++; ( randnum > 5 ) ? randnum = 0 : randnum; } m_nDiceNum = randnum; m_nCount = 0; } m_nCount++; } else if(m_nStatus == 2) //Com의 결과가 보여지고 바로 사라지거나 하기 때문에 약간의 Delay를 줌 { if(m_nCount > m_nDelay) { if(m_bReciveResult) { CString message; if(m_nPenya[m_nDiceChoiceNum] > 0) { CString strPenya; strPenya.Format("%d", m_nPrizePenya); strPenya = GetNumberFormatEx(strPenya); message.Format(prj.GetText( TID_GAME_DICEGAME_SUCCESS ), m_nDiceChoiceNum + 1, strPenya ); PlayMusic( BGM_IN_FITUP ); } else message.Format(prj.GetText( TID_GAME_DICEGAME_FAIL )); if(m_pWndMessageBox != NULL) SAFE_DELETE( m_pWndMessageBox ); m_pWndMessageBox = new CWndDiceGameMessage; m_pWndMessageBox->Initialize( message, this, MB_OK ); m_nStatus = -1; m_nDelay = 1; m_bReciveResult = FALSE; m_bEnd = TRUE; } else { if(!m_bSendStart) //서버로 주사위 게임의 시작을 알린다. { g_DPlay.SendFiveSystemStart(); m_bSendStart = TRUE; } } } m_nCount++; } return TRUE; } void CWndDiceGame::SetDescription( CHAR* szChar ) { CScript scanner; BOOL checkflag; checkflag = scanner.Load( MakePath( DIR_CLIENT, _T( "MiniGameDiceDesc.inc" ) )); szChar = scanner.m_pProg; if(m_pText != NULL && checkflag) { m_pText->m_string.AddParsingString( szChar ); m_pText->ResetString(); } } void CWndDiceGame::ResetPenya() { for(int i=0; i<6; i++) m_nPenya[i] = 0; } /************************* CWndDiceGameTender *************************/ CWndDiceGameTender::CWndDiceGameTender() { m_pDiceGame = NULL; m_nTenderPenya = 0; m_nSelect = -1; } CWndDiceGameTender::~CWndDiceGameTender() { } void CWndDiceGameTender::OnDestroy() { } void CWndDiceGameTender::OnDraw( C2DRender* p2DRender ) { } void CWndDiceGameTender::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 CWndEdit* pWndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT ); pWndEdit->SetFocus(); MoveParentCenter(); } void CWndDiceGameTender::SetMinMaxPenya(int nMinPenya, int nMaxPenya) { m_nMinPenya = nMinPenya; m_nMaxPenya = nMaxPenya; } BOOL CWndDiceGameTender::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { m_pDiceGame = (CWndDiceGame*)pWndParent; // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_TRADE_GOLD, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndDiceGameTender::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndDiceGameTender::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndDiceGameTender::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndDiceGameTender::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndDiceGameTender::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_OK || message == EN_RETURN ) { CWndEdit* pWndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT ); CString string = pWndEdit->GetString(); m_nTenderPenya = _ttoi( string ); if( m_nTenderPenya < m_nMinPenya && m_nTenderPenya != 0) { string.Format( _T( prj.GetText(TID_GAME_DICETENDER_ERROR) ), m_nMinPenya ); g_WndMng.OpenMessageBox( string ); } else { if(m_nSelect > -1 && m_pDiceGame != NULL) { CWndEdit* pWndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT ); CString string = pWndEdit->GetString(); m_nTenderPenya = _ttoi( string ); m_pDiceGame->CheckPenyaUsuable(m_nTenderPenya, m_nSelect); } Destroy(); } } else if( nID == WIDC_EDIT ) { CWndEdit* pWndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT ); CString string = pWndEdit->GetString(); int m_nTenderPenya = _ttoi( string ); if(m_nTenderPenya > m_nMaxPenya) //입찰 금액이 최대 입찰 금액을 초과할 경우 m_nTenderPenya = m_nMaxPenya; string.Format("%d", m_nTenderPenya); pWndEdit->SetString(string); } else if( nID == WIDC_CANCEL ) Destroy(); return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndDiceGameTender::SetSelectNum(int nSelect) { CString string; m_nSelect = nSelect; CWndEdit* pWndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT ); string.Format("%d", m_pDiceGame->m_nPenya[m_nSelect]); pWndEdit->SetString(string); } /************************* CWndDiceGameMessage *************************/ CWndDiceGameMessage::CWndDiceGameMessage() { } CWndDiceGameMessage::~CWndDiceGameMessage() { } void CWndDiceGameMessage::OnDestroy() { } void CWndDiceGameMessage::OnDraw( C2DRender* p2DRender ) { } void CWndDiceGameMessage::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 CRect rect = GetClientRect(); int x = m_rectClient.Width() / 2; int y = m_rectClient.Height() - 30; CSize size = CSize(60,25); CRect rect1( x - ( size.cx / 2), y, ( x - ( size.cx / 2 ) ) + size.cx, y + size.cy ); rect.DeflateRect( 10, 10, 10, 35 ); m_wndText.AddWndStyle( WBS_VSCROLL ); m_wndText.Create( WBS_NODRAWFRAME, rect, this, 0 ); m_wndText.SetString( m_strText, 0xff000000 ); m_wndText.ResetString(); m_wndButton.Create("OK", 0, rect1, this, IDOK); m_wndButton.SetTexture( m_pApp->m_pd3dDevice, MakePath( DIR_THEME, "ButtOk.tga" ) ); m_wndButton.FitTextureSize(); CWndDiceGame* pWndGame = (CWndDiceGame*)GetWndBase( APP_MINIGAME_DICE ); if(pWndGame != NULL) { CRect rectGame = pWndGame->GetWindowRect( TRUE ); CPoint ptGame = rectGame.BottomRight(); CPoint ptMove; ptMove = ptGame - CPoint(290, 150); Move( ptMove ); } } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndDiceGameMessage::Initialize( LPCTSTR lpszMessage, CWndBase* pWndParent, DWORD nType ) { // Daisy에서 설정한 리소스로 윈도를 연다. m_strText = lpszMessage; return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MESSAGEBOX, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndDiceGameMessage::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndDiceGameMessage::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndDiceGameMessage::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndDiceGameMessage::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndDiceGameMessage::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == IDOK ) { CWndDiceGame* pWndGame = (CWndDiceGame*)GetWndBase( APP_MINIGAME_DICE ); if(pWndGame != NULL) { pWndGame->ResetPenya(); pWndGame->RefreshCtrl(); pWndGame->RefreshInfo(); } Destroy(); } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } /************************* CWndPuzzleGame *************************/ CWndPuzzleGame::CWndPuzzleGame() { for(int i=0; i<9; i++) m_pItemElem[i] = NULL; m_pStaticID[0] = WIDC_PIC_NUM1; m_pStaticID[1] = WIDC_PIC_NUM2; m_pStaticID[2] = WIDC_PIC_NUM3; m_pStaticID[3] = WIDC_PIC_NUM4; m_pStaticID[4] = WIDC_PIC_NUM5; m_pStaticID[5] = WIDC_PIC_NUM6; m_pStaticID[6] = WIDC_PIC_NUM7; m_pStaticID[7] = WIDC_PIC_NUM8; m_pStaticID[8] = WIDC_PIC_NUM9; m_nSelectCtrl = -1; m_pText = NULL; m_bStart = TRUE; m_pWndInventory = NULL; } CWndPuzzleGame::~CWndPuzzleGame() { } void CWndPuzzleGame::OnDestroy() { for(int i=0; i<9; i++) { if(m_pItemElem[i] != NULL) { if( !g_pPlayer->m_vtInfo.IsTrading( m_pItemElem[i] ) ) m_pItemElem[i]->SetExtra(0); m_pItemElem[i] = NULL; } } if(m_pWndInventory != NULL) m_pWndInventory->m_wndItemCtrl.SetDieFlag(FALSE); } void CWndPuzzleGame::SetPuzzle(vector<DWORD> vPuzzle) { int i=0; std::vector<DWORD>::iterator iter = vPuzzle.begin(); while(iter != vPuzzle.end()) { m_itemID[i] = *iter; i++; iter++; } } BOOL CWndPuzzleGame::Process() { if(m_bStart) { BOOL checkfull = TRUE; CWndButton* pButton; for(int i=0; i<9; i++) { if(m_pItemElem[i] == NULL) checkfull = FALSE; } if(checkfull) { pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(TRUE); m_bStart = FALSE; } else { pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); m_bStart = FALSE; } } return TRUE; } void CWndPuzzleGame::OnDraw( C2DRender* p2DRender ) { //현재 선택된 Ctrl 기억하기. CPoint point = GetMousePoint(); m_nSelectCtrl = HitTest( point ); //나머지 올려진 퍼즐 그리기. ItemProp* pItemProp; CTexture* pTexture; for(int i=0; i<9; i++) { if(m_pItemElem[i] != NULL) { pItemProp = prj.GetItemProp( m_itemID[i] ); if(pItemProp != NULL) { //아이템 아이콘이 아닌 큰 크기의 그림이 따로 들어갈 경우 여기를 수정. pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, pItemProp->szIcon), 0xffff00ff ); if(pTexture != NULL) pTexture->Render( p2DRender, CPoint( GetWndCtrl( m_pStaticID[i] )->rect.left, GetWndCtrl( m_pStaticID[i] )->rect.top ) ); } } } } BOOL CWndPuzzleGame::OnDropIcon( LPSHORTCUT pShortcut, CPoint point ) { CItemElem* pItemElem = (CItemElem*)g_pPlayer->GetItemId( pShortcut->m_dwId ); //if( ::GetLanguage() == LANG_KOR ) { int nNum = 0; for(int i=0; i<9; i++) { if(m_pItemElem[i] == NULL && m_itemID[i] == pItemElem->m_dwItemId) { if(pItemElem->m_nItemNum > nNum) { m_itemID[i] = pItemElem->GetProp()->dwID; m_pItemElem[i] = pItemElem; nNum++; } else i = 9; } } if(nNum > 0) { pItemElem->SetExtra(nNum); m_bStart = TRUE; } } /* else { int nNum = -1; for(int i=0; i<9; i++) { if(m_pItemElem[i] == NULL && m_itemID[i] == pItemElem->m_dwItemId) { nNum = i; i = 9; } } if(nNum != -1) { m_itemID[nNum] = pItemElem->GetProp()->dwID; m_pItemElem[nNum] = pItemElem; pItemElem->SetExtra(1); m_bStart = TRUE; } } */ return TRUE; } void CWndPuzzleGame::OnLButtonDblClk( UINT nFlags, CPoint point ) { if(m_nSelectCtrl > -1 && m_itemID[m_nSelectCtrl] != -1) { if(m_pItemElem[m_nSelectCtrl] != NULL) { //if( ::GetLanguage() == LANG_KOR ) { DWORD dwItemId = m_pItemElem[m_nSelectCtrl]->m_dwItemId; for(int i=0; i<9; i++) { if(m_itemID[i] == dwItemId) { m_pItemElem[i]->SetExtra(0); m_pItemElem[i] = NULL; } } } /* else { m_pItemElem[m_nSelectCtrl]->SetExtra(0); m_pItemElem[m_nSelectCtrl] = NULL; m_bStart = TRUE; } */ } } } void CWndPuzzleGame::SetPicture(CItemElem* pItemElem) { //if( ::GetLanguage() == LANG_KOR ) { int nNum = 0; for(int i=0; i<9; i++) { if(m_pItemElem[i] == NULL && m_itemID[i] == pItemElem->m_dwItemId) { if(pItemElem->m_nItemNum > nNum) { m_itemID[i] = pItemElem->GetProp()->dwID; m_pItemElem[i] = pItemElem; nNum++; } else i = 9; } } if(nNum > 0) { pItemElem->SetExtra(nNum); m_bStart = TRUE; } } /* else { int nNum = -1; for(int i=0; i<9; i++) { if(m_pItemElem[i] == NULL && m_itemID[i] == pItemElem->m_dwItemId) { nNum = i; i = 9; } } if(nNum != -1) { m_itemID[nNum] = pItemElem->GetProp()->dwID; m_pItemElem[nNum] = pItemElem; pItemElem->SetExtra(pItemElem->GetExtra()+1); m_bStart = TRUE; } } */ } void CWndPuzzleGame::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 m_pText = (CWndText *)GetDlgItem( WIDC_TEXT_DESC ); CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); SetDescription(NULL); g_DPlay.SendReassembleOpenWnd(); MoveParentCenter(); } BOOL CWndPuzzleGame::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_MINIGAME_PUZZLE, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndPuzzleGame::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndPuzzleGame::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndPuzzleGame::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndPuzzleGame::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndPuzzleGame::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if(message == WNM_CLICKED) { if(nID == WIDC_BTN_START) { BOOL checkall = TRUE; for(int i=0; i<9; i++) { if(m_pItemElem[i] == NULL) checkall = FALSE; } if(checkall) { CWndButton* pButton; pButton = (CWndButton*)GetDlgItem( WIDC_BTN_START ); pButton->EnableWindow(FALSE); //서버로 해당 글자들의 ID를 묶어서 보낸다. for(int i=0; i<9; i++) { m_objItemID[i] = m_pItemElem[i]->m_dwObjId; } g_DPlay.SendReassembleStart(m_objItemID, 9); } else { //글자가 빠져있다면 Error Message를 띄운다. g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_MINIGAME_EMPTY_ERROR ) ); } } } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } int CWndPuzzleGame::HitTest( CPoint point ) { int rtn_val = -1; for(int i=0; i<9; i++) { if( GetWndCtrl( m_pStaticID[i] )->rect.PtInRect( point ) ) { rtn_val = i; i = 9; } } return rtn_val; } void CWndPuzzleGame::ReceiveResult() { g_WndMng.OpenMessageBox( prj.GetText( TID_GAME_PUZZLE_GIVEPRESENT ) ); PlayMusic( BGM_IN_FITUP ); Destroy(); } void CWndPuzzleGame::SetDescription( CHAR* szChar ) { CScript scanner; BOOL checkflag; checkflag = scanner.Load( MakePath( DIR_CLIENT, _T( "MiniGamePuzzleDesc.inc" ) )); szChar = scanner.m_pProg; if(m_pText != NULL && checkflag) { m_pText->m_string.AddParsingString( szChar ); m_pText->ResetString(); } } #endif //__EVE_MINIGAME
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 1952 ] ] ]
d65994d385627610888f4329d753e697a7029f8b
b9047929ed6f6e784cdddc2d27fb5943e93c7512
/soapClient.cpp
11e70584edeb1fd8d63a83e0126a64ab2a1fd867
[]
no_license
ipupiara/GrowboxCommonSoap
f4a688d80c457107a7a376269f87acb82f4df016
69ff1b57390c5d4f1687ed8f85386a6ec9e142d6
refs/heads/master
2020-12-24T13:21:34.006807
2011-01-12T18:36:17
2011-01-12T18:36:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,256
cpp
/* soapClient.cpp Generated by gSOAP 2.7.9a from getStates.h Copyright(C) 2000-2006, Robert van Engelen, Genivia Inc. All Rights Reserved. This part of the software is released under one of the following licenses: GPL, the gSOAP public license, or Genivia's license for commercial use. */ #include "soapH.h" SOAP_SOURCE_STAMP("@(#) soapClient.cpp ver 2.7.9a 2006-12-03 08:58:28 GMT") SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns__getGrowBoxInfo(struct soap *soap, const char *soap_endpoint, const char *soap_action, GrowBoxInfo *Result) { struct ns__getGrowBoxInfo soap_tmp_ns__getGrowBoxInfo; if (!soap_endpoint) soap_endpoint = "http://services.xmethods.net/soap"; soap->encodingStyle = ""; soap_begin(soap); soap_serializeheader(soap); soap_serialize_ns__getGrowBoxInfo(soap, &soap_tmp_ns__getGrowBoxInfo); if (soap_begin_count(soap)) return soap->error; if (soap->mode & SOAP_IO_LENGTH) { if (soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put_ns__getGrowBoxInfo(soap, &soap_tmp_ns__getGrowBoxInfo, "ns:getGrowBoxInfo", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap)) return soap->error; } if (soap_end_count(soap)) return soap->error; if (soap_connect(soap, soap_endpoint, soap_action) || soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put_ns__getGrowBoxInfo(soap, &soap_tmp_ns__getGrowBoxInfo, "ns:getGrowBoxInfo", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap) || soap_end_send(soap)) return soap_closesock(soap); if (!Result) return soap_closesock(soap); Result->soap_default(soap); if (soap_begin_recv(soap) || soap_envelope_begin_in(soap) || soap_recv_header(soap) || soap_body_begin_in(soap)) return soap_closesock(soap); Result->soap_get(soap, "GrowBoxInfo", ""); if (soap->error) { if (soap->error == SOAP_TAG_MISMATCH && soap->level == 2) return soap_recv_fault(soap); return soap_closesock(soap); } if (soap_body_end_in(soap) || soap_envelope_end_in(soap) || soap_end_recv(soap)) return soap_closesock(soap); return soap_closesock(soap); } /* End of soapClient.cpp */
[ "duenda@.(none)" ]
[ [ [ 1, 63 ] ] ]
66f4a011da4fbf7b2cd52b8e3e467dfde88ba96c
7e6387a7495e89ec42acc99ea6d8736a69d96d72
/solverCode/slvPressureCorrection.cpp
0b41329116f3da07b7cfa6f6890f0d7fcf7b0013
[]
no_license
erkg/virtualflowlab
2a491d71fdf8e7db6dab243560fadbb8cd731943
a540d4ecd076327f98cb7e3044422e7b4d33efbb
refs/heads/master
2016-08-11T07:12:51.924920
2010-07-22T14:40:24
2010-07-22T14:40:24
55,049,199
0
0
null
null
null
null
UTF-8
C++
false
false
6,045
cpp
/***************************************************************************** Reference Book: An Introduction to Computational Fluid Dynamics. The Finite Volume Method, H.K. Versteeg and W. Malalasekere (page 143) *****************************************************************************/ #include "slvFunctions.h" void PressureCorrectionMatrix(double** &PresCrctWest, double** &PresCrctEast, double** &PresCrctSouth, double** &PresCrctNorth, double** &PresCrctCenter, double** &PresCrctSource, double** UmomaCenter, double** VmomaCenter, double** Uvel, double** Vvel, double** &PresCrctdJi, double** &PresCrctdjI, double** UmomaWest, double** UmomaEast, double** UmomaSouth, double** UmomaNorth, double** VmomaWest, double** VmomaEast, double** VmomaSouth, double** VmomaNorth, bool PressureCorrectFlag) { /***************************************************************************** This function forms the pressure correction matrix. It calculates 4 neigbor node and 1 center node coefficient arrays. IMPORTANT: For SIMPLER algorithm this function is also used to calculate coefficinents of pressure (as well as pressure correction) equation. PressureCorrectFlag variable controls this. If it is eaual to 0 pressure equation, if it is equal to 1 pressure correction equation is formed. *****************************************************************************/ /***************************************************************************** IMPORTANT : Coefficient arrays use more than required space bacause not all pressure nodes are computational nodes. Coefficients of the boundary nodes remain the same, but it is done this way for ease of understanding *****************************************************************************/ /***************************************************************************** Here two new arrays are formed to be used in the coefficients of pressure correction matrix as explained in the reference book. They are used in both pressure corection and velocity corection. *****************************************************************************/ if (solverAlgorithm == 1 || solverAlgorithm == 2) { // SIMPLE and SIMPLEC // For x direction and u momentum for(int J=1; J<NumJ-1; J++) { for(int i=1; i<Numi-1; i++) { PresCrctdJi[J][i] = (Yji[J][i] - Yji[J-1][i]) / UmomaCenter[J][i]; } } // For y direction and v momentum for(int j=1; j<Numj-1; j++) { for(int I=1; I<NumI-1; I++) { PresCrctdjI[j][I] = (Xji[j][I] - Xji[j][I-1]) / VmomaCenter[j][I]; } } } else if (solverAlgorithm == 3) { // SIMPLER for(int J=1; J<NumJ-1; J++) { for(int i=1; i<Numi-1; i++) { PresCrctdJi[J][i] = (Yji[J][i] - Yji[J-1][i]) / (UmomaCenter[J][i] - (UmomaWest[J][i] + UmomaEast[J][i] + UmomaSouth[J][i] + UmomaNorth[J][i])); } } for(int j=1; j<Numj-1; j++) { for(int I=1; I<NumI-1; I++) { PresCrctdjI[j][I] = (Xji[j][I] - Xji[j][I-1]) / (VmomaCenter[j][I] - (VmomaWest[j][I] + VmomaEast[j][I] + VmomaSouth[j][I] + VmomaNorth[j][I])); } } } /***************************************************************************** At this point the matrix for the pressure correction is formed. IMPORTANT: This matrix is no different than the momentum matrices solved before. However, pressure correction matrix (PJICorrect) is always formed of zeros as an initial condition. It is implemented in PressureVelocityCorrecter function but it is important to mention it now. *****************************************************************************/ for(int J=1; J<NumJ-1; J++) { for(int I=1; I<NumI-1; I++) { PresCrctWest[J][I] = PresCrctdJi[J][I-1] * density * (Yji[J][I-1] - Yji[J-1][I-1]); PresCrctEast[J][I] = PresCrctdJi[J][I] * density * (Yji[J][I] - Yji[J-1][I]); PresCrctSouth[J][I] = PresCrctdjI[J-1][I] * density * (Xji[J-1][I] - Xji[J-1][I-1]); PresCrctNorth[J][I] = PresCrctdjI[J][I] * density * (Xji[J][I] - Xji[J][I-1]); PresCrctCenter[J][I] = PresCrctWest[J][I] + PresCrctEast[J][I] + PresCrctSouth[J][I] + PresCrctNorth[J][I]; PresCrctSource[J][I] = density * (- Uvel[J][I] * (Yji[J][I] - Yji[J-1][I] ) + Uvel[J][I-1] * (Yji[J][I-1] - Yji[J-1][I-1] ) - Vvel[J][I] * (Xji[J][I] - Xji[J][I-1] ) + Vvel[J-1][I] * (Xji[J-1][I] - Xji[J-1][I-1])); } } // This outlet BC part is necessary only for the pressure correction equation. if (PressureCorrectFlag) { // OUTLET BC (Part 4/4) for(int J=1; J<NumJ-1; J++) { if (BoundaryRight[J][0] == 3) { PresCrctEast[J][NumI-2] = 0; PresCrctWest[J][NumI-2] = 0; } if (BoundaryLeft[J][0] == 3) { PresCrctEast[J][1] = 0; // These values are already zero PresCrctWest[J][1] = 0; } } for(int I=1; I<NumI-1; I++) { if (BoundaryTop[NumJ-2][I] == 3) { PresCrctNorth[NumJ-2][I] = 0; PresCrctSouth[NumJ-2][I] = 0; } if (BoundaryBottom[1][I] == 3) { PresCrctNorth[1][I] = 0; PresCrctSouth[1][I] = 0; } } } } // End of function PressureCorrectionMatrix()
[ "cuneytsert@76eae623-603d-0410-ac33-4f885805322a" ]
[ [ [ 1, 126 ] ] ]
7b083648955d90a45b4382bb7dc8330e569b6d57
7ee1bcc17310b9f51c1a6be0ff324b6e297b6c8d
/Source/AfxScratchApp.cpp
e287832e2599a14931405106de6ca7790dcd8e46
[]
no_license
SchweinDeBurg/afx-scratch
895585e98910f79127338bdca5b19c5e36921453
3181b779b4bb36ef431e5ce39e297cece1ca9cca
refs/heads/master
2021-01-19T04:50:48.770595
2011-06-18T05:14:22
2011-06-18T05:14:22
32,185,218
0
0
null
null
null
null
UTF-8
C++
false
false
9,034
cpp
// AfxScratch application. // Copyright (c) 2004-2011 by Elijah Zarezky, // All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // AfxScratchApp.cpp - implementation of the CAfxScratchApp class ////////////////////////////////////////////////////////////////////////////////////////////// // PCH includes #include "stdafx.h" ////////////////////////////////////////////////////////////////////////////////////////////// // resource includes #include "Resource.h" ////////////////////////////////////////////////////////////////////////////////////////////// // other includes #include "AfxScratchApp.h" #include "MainDialog.h" ////////////////////////////////////////////////////////////////////////////////////////////// // misc defines #define SZ_MUTEX_APP_INST_NAME _T("AfxScratch.Instance.655393D6-3C2F-43E5-AEC3-29FCDC0AA439") ////////////////////////////////////////////////////////////////////////////////////////////// // debugging support #if defined(_DEBUG) #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif // _DEBUG ////////////////////////////////////////////////////////////////////////////////////////////// // object model IMPLEMENT_DYNAMIC(CAfxScratchApp, CWinApp) ////////////////////////////////////////////////////////////////////////////////////////////// // message map BEGIN_MESSAGE_MAP(CAfxScratchApp, CWinApp) END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////////////////////////// // construction/destruction CAfxScratchApp::CAfxScratchApp(void): m_hMutexAppInst(NULL) { #if defined(AFXSCRATCH_DETOURED) if (RegQueryCatchpit() > 0) { Detoured(); (PVOID&)m_pfnLoadLibrary = ::DetourFindFunction("kernel32.dll", STRINGIZE(LoadLibrary)); (PVOID&)m_pfnLoadLibraryEx = ::DetourFindFunction("kernel32.dll", STRINGIZE(LoadLibraryEx)); DetourTransactionBegin(); DetourUpdateThread(::GetCurrentThread()); DetourAttach(reinterpret_cast<PVOID*>(&m_pfnLoadLibrary), &CAfxScratchApp::LoadLibrary); DetourAttach(reinterpret_cast<PVOID*>(&m_pfnLoadLibraryEx), &CAfxScratchApp::LoadLibraryEx); DetourTransactionCommit(); } #endif // AFXSCRATCH_DETOURED } CAfxScratchApp::~CAfxScratchApp(void) { #if defined(AFXSCRATCH_DETOURED) if (!IsCatchpitEmpty()) { DetourTransactionBegin(); DetourUpdateThread(::GetCurrentThread()); DetourDetach(reinterpret_cast<PVOID*>(&m_pfnLoadLibrary), &CAfxScratchApp::LoadLibrary); DetourDetach(reinterpret_cast<PVOID*>(&m_pfnLoadLibraryEx), &CAfxScratchApp::LoadLibraryEx); DetourTransactionCommit(); } #endif // AFXSCRATCH_DETOURED } ////////////////////////////////////////////////////////////////////////////////////////////// // operations HICON CAfxScratchApp::LoadSmIcon(LPCTSTR pszResName) { HINSTANCE hInstRes = AfxGetResourceHandle(); int cxSmIcon = ::GetSystemMetrics(SM_CXSMICON); int cySmIcon = ::GetSystemMetrics(SM_CYSMICON); HANDLE hSmIcon = ::LoadImage(hInstRes, pszResName, IMAGE_ICON, cxSmIcon, cySmIcon, 0); return (static_cast<HICON>(hSmIcon)); } HICON CAfxScratchApp::LoadSmIconFromFile(LPCTSTR pszFileName) { int cxSmIcon = ::GetSystemMetrics(SM_CXSMICON); int cySmIcon = ::GetSystemMetrics(SM_CYSMICON); HANDLE hSmIcon = ::LoadImage(NULL, pszFileName, IMAGE_ICON, cxSmIcon, cySmIcon, LR_LOADFROMFILE); return (static_cast<HICON>(hSmIcon)); } void CAfxScratchApp::GetVersionString(CString& strDest) { TCHAR szExeName[_MAX_PATH]; DWORD dwHandle; CString strValueName; void* pvVerString; UINT cchFileVer; ::GetModuleFileName(AfxGetInstanceHandle(), szExeName, _MAX_PATH); DWORD cbSize = ::GetFileVersionInfoSize(szExeName, &dwHandle); BYTE* pbVerInfo = new BYTE[cbSize]; ::GetFileVersionInfo(szExeName, dwHandle, cbSize, pbVerInfo); strValueName.LoadString(IDS_FILE_VERSION); ::VerQueryValue(pbVerInfo, strValueName.GetBuffer(0), &pvVerString, &cchFileVer); strValueName.ReleaseBuffer(); strDest = reinterpret_cast<LPCTSTR>(pvVerString); delete[] pbVerInfo; } ////////////////////////////////////////////////////////////////////////////////////////////// // overridables BOOL CAfxScratchApp::InitInstance(void) { SetRegistryKey(IDS_REGISTRY_KEY); m_hMutexAppInst = ::CreateMutex(NULL, TRUE, SZ_MUTEX_APP_INST_NAME); if (m_hMutexAppInst == NULL) { AfxMessageBox(IDS_APP_INIT_FAILED, MB_OK | MB_ICONSTOP); return (FALSE); } else if (::GetLastError() == ERROR_ALREADY_EXISTS) { if (AfxMessageBox(IDS_OTHER_APP_INSTANCE, MB_YESNO | MB_ICONWARNING) == IDNO) { ::CloseHandle(m_hMutexAppInst); return (FALSE); } } AfxOleInit(); CMainDialog dlgMain; m_pMainWnd = &dlgMain; dlgMain.DoModal(); AfxOleTerm(FALSE); ::CloseHandle(m_hMutexAppInst); m_hMutexAppInst = NULL; return (FALSE); } int CAfxScratchApp::ExitInstance(void) { return (__super::ExitInstance()); } ////////////////////////////////////////////////////////////////////////////////////////////// // implementation helpers #if defined(AFXSCRATCH_DETOURED) CAfxScratchApp::PFN_LOAD_LIBRARY CAfxScratchApp::m_pfnLoadLibrary(NULL); CAfxScratchApp::PFN_LOAD_LIBRARY_EX CAfxScratchApp::m_pfnLoadLibraryEx(NULL); HMODULE WINAPI CAfxScratchApp::LoadLibrary(LPCTSTR pszFileName) { TRACE(_T("*** CAfxScratchApp::LoadLibrary(%s)\n"), pszFileName); CAfxScratchApp* pApp = DYNAMIC_DOWNCAST(CAfxScratchApp, AfxGetApp()); ASSERT(pApp != NULL); CString strFileNameLower(::PathFindFileName(pszFileName)); strFileNameLower.MakeLower(); DWORD fCatch = FALSE; if (pApp->m_mapCatchpit.Lookup(strFileNameLower, fCatch) && fCatch != 0) { ::SetLastError(ERROR_FILE_NOT_FOUND); return (NULL); } else { return (m_pfnLoadLibrary(pszFileName)); } } HMODULE WINAPI CAfxScratchApp::LoadLibraryEx(LPCTSTR pszFileName, HANDLE hFile, DWORD fdwFlags) { TRACE(_T("*** CAfxScratchApp::LoadLibraryEx(%s, 0x%08X, 0x%08X)\n"), pszFileName, hFile, fdwFlags); CAfxScratchApp* pApp = DYNAMIC_DOWNCAST(CAfxScratchApp, AfxGetApp()); ASSERT(pApp != NULL); CString strFileNameLower(::PathFindFileName(pszFileName)); strFileNameLower.MakeLower(); DWORD fCatch = FALSE; if (pApp->m_mapCatchpit.Lookup(strFileNameLower, fCatch) && fCatch != 0) { ::SetLastError(ERROR_FILE_NOT_FOUND); return (NULL); } else { return (m_pfnLoadLibraryEx(pszFileName, hFile, fdwFlags)); } } INT_PTR CAfxScratchApp::RegQueryCatchpit(void) { CString strKeyName; CRegKey regKey; m_mapCatchpit.RemoveAll(); // build the name of the registry key... ::LoadString(::GetModuleHandle(NULL), IDS_REGISTRY_KEY, strKeyName.GetBuffer(_MAX_PATH), _MAX_PATH); strKeyName.ReleaseBuffer(); strKeyName.Insert(0, _T("Software\\")); strKeyName += _T("\\AfxScratch\\Catchpit"); // ...and then open this key regKey.Create(HKEY_CURRENT_USER, strKeyName); DWORD cNumValues = 0; if (::RegQueryInfoKey(regKey, 0, 0, 0, 0, 0, 0, &cNumValues, 0, 0, 0, 0) == ERROR_SUCCESS) { for (DWORD i = 0; i < cNumValues; ++i) { TCHAR szValueName[_MAX_PATH] = { 0 }; DWORD cchNameLen = _countof(szValueName); DWORD fdwValueType = REG_NONE; if (::RegEnumValue(regKey, i, szValueName, &cchNameLen, 0, &fdwValueType, 0, 0) == ERROR_SUCCESS) { if (fdwValueType == REG_DWORD) { DWORD fCatch = FALSE; regKey.QueryDWORDValue(szValueName, fCatch); _tcslwr_s(szValueName, cchNameLen + 1); m_mapCatchpit.SetAt(szValueName, fCatch); } } } } return (m_mapCatchpit.GetCount()); } #endif // AFXSCRATCH_DETOURED ////////////////////////////////////////////////////////////////////////////////////////////// // diagnostic services #if defined(_DEBUG) void CAfxScratchApp::AssertValid(void) const { // first perform inherited validity check... CWinApp::AssertValid(); // ...and then verify our own state as well } void CAfxScratchApp::Dump(CDumpContext& dumpCtx) const { try { // first invoke inherited dumper... CWinApp::Dump(dumpCtx); // ...and then dump own unique members } catch (CFileException* pXcpt) { pXcpt->ReportError(); pXcpt->Delete(); } } #endif // _DEBUG ////////////////////////////////////////////////////////////////////////////////////////////// // the one and only application object static CAfxScratchApp g_appAfxScratch; // end of file
[ "Elijah Zarezky@9edebcd1-9b41-0410-8d36-53a5787adf6b", "Elijah@9edebcd1-9b41-0410-8d36-53a5787adf6b" ]
[ [ [ 1, 4 ], [ 17, 278 ], [ 280, 288 ], [ 290, 306 ] ], [ [ 5, 16 ], [ 279, 279 ], [ 289, 289 ] ] ]
cb41a798732153df12a42fe813af533396d9fc2f
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Base/Utils/LerpAnimator2D.cpp
208744250d739ad9bdc814e2d57e506b81ab20d0
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
#include "Utils/LerpAnimator2D.h" #include <cmath> void CLerpAnimator2D::SetValues (Vect2f initValue, Vect2f endValue, float totalTime, ETypeFunction type) { assert( totalTime > 0); m_vInitValue = initValue; m_vEndValue = endValue; m_fTotalTime = totalTime; m_fElapsedTime = 0.f; m_eFunction = type; } bool CLerpAnimator2D::Update (float deltaTime, Vect2f &value) { m_fElapsedTime += deltaTime; bool finish = false; if (m_fElapsedTime >= m_fTotalTime) { finish = true; m_fElapsedTime = m_fTotalTime; } //mu [0-1] float mu = 0.f; mu = m_fElapsedTime/m_fTotalTime; //En funcion del tiempo la siguiente funcion nos retorna un valor entre 0-1. switch(m_eFunction) { case FUNC_CONSTANT: { //Linear //nothing to do } break; case FUNC_INCREMENT: { mu = mathUtils::PowN(mu,m_uDegree); } break; case FUNC_DECREMENT: { mu = pow(mu,(float)(1/m_uDegree)); } break; } value = m_vInitValue.GetLerp(m_vEndValue,mu); return finish; }
[ [ [ 1, 54 ] ] ]
fe7442822661933d1baee04ebde900417fa43f73
4b51d32f40ef5a36c98a53d2a1eab7e6f362cb00
/Common/CodigosPipe.h
7640e60f57c5356e73bda0b1891110286afe7ff4
[]
no_license
damian-pisaturo/datos7506
bcff7f1e9e69af8051ebf464107b92f91be560e4
a67aac89eccd619cdc02a7e6940980f346981895
refs/heads/master
2016-09-06T16:48:18.612868
2007-12-10T22:12:28
2007-12-10T22:12:28
32,679,551
0
0
null
null
null
null
UTF-8
C++
false
false
350
h
#ifndef CODIGOSPIPE_H_ #define CODIGOSPIPE_H_ class CodigosPipe { public: static const unsigned short BUFFER_SIZE = 1024; static const char COD_FIN_CLAVE = -1; static const char COD_FIN_BLOQUE = -2; static const char COMIENZO_OPERADOR = -3; static const char FIN_OPERADOR = -4; }; #endif /*CODIGOSPIPE_H_*/
[ "manugarciacab@4ef8b2a0-b237-0410-b753-5dc98fa25004", "nahuel.grisolia@4ef8b2a0-b237-0410-b753-5dc98fa25004", "dpisaturo@4ef8b2a0-b237-0410-b753-5dc98fa25004" ]
[ [ [ 1, 4 ], [ 16, 17 ] ], [ [ 5, 10 ], [ 14, 15 ] ], [ [ 11, 13 ] ] ]
637c5fb49935ad4155ab3de5390a279e7fe93c15
59abf9cf4595cc3d2663fcb38bacd328ab6618af
/3Party/bin2c.cpp
92ea0608107ca9a8959310aee6e1b0978b18a372
[]
no_license
DrDrake/mcore3d
2ce53148ae3b9c07a3d48b15b3f1a0eab7846de6
0bab2c59650a815d6a5b581a2c2551d0659c51c3
refs/heads/master
2021-01-10T17:08:00.014942
2011-03-18T09:16:28
2011-03-18T09:16:28
54,134,775
0
0
null
null
null
null
UTF-8
C++
false
false
1,625
cpp
/* * bin2c: A Program to convert binary data into C source code * Copyright 2004 by Adrian Prantl <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c */ #include <stdio.h> #include <stdlib.h> char* self = 0; void usage() { printf("Usage:\n%s input_binary_file output_c_file symbol_name\n\n", self); } void bail_out(const char* s1, const char* s2) { fprintf(stderr, "%s: FATAL ERROR:\n%s%s\n", self, s1, s2); exit(1); } int main(int argc, char** argv) { FILE *fi, *fo; int c, i; self = argv[0]; if (argc != 4) { usage(); return 1; } if ((fi = fopen(argv[1], "rb")) == 0) bail_out("Cannot open input file ", argv[1]); if ((fo = fopen(argv[2], "w")) == 0) bail_out("Cannot open output file ", argv[2]); if ((c = fgetc(fi)) != EOF) { // fprintf(fo, "extern volatile unsigned char _binary_%s_start[];\n", argv[3]); fprintf(fo, "static const unsigned char _binary_%s_start[] = {\n", argv[3]); fprintf(fo, c<16 ? " 0x%x" : "0x%x", (unsigned char)c); } i = 1; while ((c = fgetc(fi)) != EOF) { if (i < 12) fprintf(fo, c<16 ? ", 0x%x" : ",0x%x", (unsigned char)c); else { fprintf(fo, c<16 ? ",\n 0x%x" : ",\n0x%x", (unsigned char)c); i = 0; } i++; } fprintf(fo, " };\n"); printf("converted %s\n", argv[1]); return 0; }
[ "mtlung@080b3119-2d51-0410-af92-4d39592ae298" ]
[ [ [ 1, 68 ] ] ]
e0325ab4d984a7ba94129f524364ca374a002f9c
619843aa55e023fe4eb40a3f1b59da6bcb993a54
/reactor/reactor_server_test.cc
128ca56146fff1e482f1df74e7ba1722fcf95eb3
[]
no_license
pengvan/xiao5geproject
82271ceb18d2c9ea7abb960c41e883ad54a7e8c6
3e28c80f0af5d11eb1c03c569e040dda33966e4a
refs/heads/master
2016-09-11T02:19:09.285543
2011-06-17T07:05:34
2011-06-17T07:05:34
38,201,768
0
0
null
null
null
null
GB18030
C++
false
false
5,714
cc
#ifndef REACTOR_TIME_SERVER_H_ #define REACTOR_TIME_SERVER_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #include <errno.h> #ifdef __linux__ #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #endif #include <string> #include "test_common.h" /// @file reactor_server_test.cc /// @brief 用reactor实现的时间server,用telnet协议 /// @author zeshengwu<[email protected]> /// @date 2011-03-28 /// reactor对象 reactor::Reactor g_reactor; /// 读/写数据用到的buffer const size_t kBufferSize = 1024; char g_read_buffer[kBufferSize]; char g_write_buffer[kBufferSize]; class RequestHandler : public reactor::EventHandler { public: /// 构造函数 RequestHandler(reactor::handle_t handle) : EventHandler(), m_handle(handle) {} /// 获取该handler所对应的句柄 virtual reactor::handle_t GetHandle() const { return m_handle; } /// 向客户端回应答 virtual void HandleWrite() { memset(g_write_buffer, 0, sizeof(g_write_buffer)); int len = sprintf(g_write_buffer, "current time: %d\r\n", (int)time(NULL)); len = send(m_handle, g_write_buffer, len, 0); if (len > 0) { fprintf(stderr, "send response to client, fd=%d\n", (int)m_handle); g_reactor.RegisterHandler(this, reactor::kReadEvent); } else { ReportSocketError("send"); } } /// 读客户端发过来的数据 virtual void HandleRead() { memset(g_read_buffer, 0, sizeof(g_read_buffer)); int len = recv(m_handle, g_read_buffer, kBufferSize, 0); if (len > 0) { if (strncasecmp("time", g_read_buffer, 4) == 0) { g_reactor.RegisterHandler(this, reactor::kWriteEvent); } else if (strncasecmp("exit", g_read_buffer, 4) == 0) { close(m_handle); g_reactor.RemoveHandler(this); delete this; } else { fprintf(stderr, "Invalid request: %s", g_read_buffer); close(m_handle); g_reactor.RemoveHandler(this); delete this; } } else { ReportSocketError("recv"); } } virtual void HandleError() { fprintf(stderr, "client %d closed\n", m_handle); close(m_handle); g_reactor.RemoveHandler(this); delete this; } private: reactor::handle_t m_handle; ///< handler句柄 }; class TimeServer : public reactor::EventHandler { public: /// 构造函数 TimeServer(const char * ip, unsigned short port) : EventHandler(), m_ip(ip), m_port(port) {} /// 启动server,开始工作 bool Start() { /// 初始化handle m_handle = socket(AF_INET, SOCK_STREAM, 0); if (!IsValidHandle(m_handle)) { ReportSocketError("socket"); return false; } /// 绑定ip/port struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(m_port); addr.sin_addr.s_addr = inet_addr(m_ip.c_str()); if (bind(m_handle, (struct sockaddr *)&addr, sizeof(addr)) < 0) { ReportSocketError("bind"); return false; } /// 监听 if (listen(m_handle, 10) < 0) { ReportSocketError("listen"); return false; } return true; } /// 获取该handler所对应的句柄 virtual reactor::handle_t GetHandle() const { return m_handle; } /// 处理读事件的回调函数: accept到新请求 virtual void HandleRead() { struct sockaddr addr; #if defined(_WIN32) int addrlen = sizeof(addr); #elif defined(__linux__) socklen_t addrlen = sizeof(addr); #endif reactor::handle_t handle = accept(m_handle, &addr, &addrlen); if (!IsValidHandle(handle)) { ReportSocketError("accept"); } else { RequestHandler * handler = new RequestHandler(handle); if (g_reactor.RegisterHandler(handler, reactor::kReadEvent) != 0) { fprintf(stderr, "error: register handler failed\n"); delete handler; } } } private: reactor::handle_t m_handle; ///< 服务器句柄 std::string m_ip; ///< 服务器ip unsigned short m_port; ///< 服务器监听端口 }; int main(int argc, char ** argv) { if (argc < 3) { fprintf(stderr, "usage: %s ip port\n", argv[0]); return EXIT_FAILURE; } #ifdef _WIN32 WSADATA wsa_data; if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) { fprintf(stderr, "WSAStartup() error: %d\n", WSAGetLastError()); return false; } #endif TimeServer server(argv[1], atoi(argv[2])); if (!server.Start()) { fprintf(stderr, "start server failed\n"); return EXIT_FAILURE; } fprintf(stderr, "server started!\n"); while (1) { g_reactor.RegisterHandler(&server, reactor::kReadEvent); g_reactor.HandleEvents(100); } #ifdef _WIN32 WSACleanup(); #endif return EXIT_SUCCESS; } #endif // REACTOR_TIME_SERVER_H_
[ "wuzesheng86@a907dffe-942c-7992-d486-e995bdc504d8" ]
[ [ [ 1, 224 ] ] ]
4aff0e1435f674ee018807511d490b8ee93b8efd
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/Display/Effect.cpp
98c0b117136fd039a1b9a08b5bdff0c548a874d8
[]
no_license
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,416
cpp
#include "stdafx.h" #include "../Core/Scripting.h" #include "../Display/Camera.h" #include "../Display/Effect.h" #include "../Display/EffectParam.h" #include "../Core/File.h" #include "../Core/Util.h" namespace ElixirEngine { //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- DisplayMemoryBuffer::DisplayMemoryBuffer() : m_pBuffer(NULL), m_uCapacity(0), m_uSize(0) { } DisplayMemoryBuffer::~DisplayMemoryBuffer() { if (NULL != m_pBuffer) { delete[] m_pBuffer; } } //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- DisplayMaterialManager::StructData::StructData() : m_pData(NULL), m_uSize(0) { } //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- DisplayEffectInclude::DisplayEffectInclude() : CoreObject(), ID3DXInclude(), m_vBuffers() { } DisplayEffectInclude::~DisplayEffectInclude() { } bool DisplayEffectInclude::Create(const boost::any& _rConfig) { return true; } void DisplayEffectInclude::Release() { } HRESULT DisplayEffectInclude::Open( D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT * pBytes ) { string strFileName; FS::ComposePath(strFileName, Display::GetInstance()->GetMaterialManager()->GetEffectIncludeBasePath(), string(pFileName)); FilePtr pFile = NULL; HRESULT hResult = (false == strFileName.empty()) ? S_OK : E_FAIL; if (SUCCEEDED(hResult)) { pFile = FS::GetRoot()->OpenFile(strFileName, FS::EOpenMode_READTEXT); hResult = (NULL != pFile) ? S_OK : E_FAIL; } if (SUCCEEDED(hResult)) { int sSize = pFile->Size(); char* pSourceCode = new char[sSize]; sSize = pFile->Read(pSourceCode, sSize); FS::GetRoot()->CloseFile(pFile); m_vBuffers.push_back(pSourceCode); *ppData = pSourceCode; *pBytes = sSize; } return hResult; } HRESULT DisplayEffectInclude::Close( LPCVOID pData ) { CharPtr pSourceCode = (CharPtr)pData; CharPtrVec::iterator iSourceCode = find(m_vBuffers.begin(), m_vBuffers.end(), pSourceCode); HRESULT hResult = (m_vBuffers.end() != iSourceCode) ? S_OK : E_FAIL; if (SUCCEEDED(hResult)) { delete[] pSourceCode; m_vBuffers.erase(iSourceCode); } return hResult; } //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- DisplayEffect::DisplayEffect(DisplayRef _rDisplay) : CoreObject(), m_strName(), m_mSemantics(), m_rDisplay(_rDisplay), m_pEffect(NULL), m_vRenderList(), m_mHandles(), m_hCurrentTechnique(NULL) { } DisplayEffect::~DisplayEffect() { } bool DisplayEffect::Create(const boost::any& _rConfig) { CreateInfo* pInfo = boost::any_cast<CreateInfo*>(_rConfig); FilePtr pFile = NULL; bool bResult = (NULL != pInfo); if (false != bResult) { Release(); pFile = FS::GetRoot()->OpenFile(pInfo->m_strPath, pInfo->m_bIsText ? FS::EOpenMode_READTEXT : FS::EOpenMode_READBINARY); bResult = (NULL != pFile); } if (false != bResult) { int sSize = pFile->Size(); char* pSourceCode = new char[sSize]; sSize = pFile->Read(pSourceCode, sSize); FS::GetRoot()->CloseFile(pFile); BufferPtr pCompilErrors; HRESULT hResult = D3DXCreateEffect( m_rDisplay.GetDevicePtr(), pSourceCode, sSize, NULL, // D3DXMACRO Defines, m_rDisplay.GetMaterialManager()->GetEffectIncludeInterface(), // LPD3DXINCLUDE Includes, /*D3DXSHADER_SKIPOPTIMIZATION | */D3DXSHADER_DEBUG | D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, NULL, // LPD3DXEFFECTPOOL Pool, &m_pEffect, &pCompilErrors); delete[] pSourceCode; bResult = SUCCEEDED(hResult); if (false == bResult) { char* ptr = static_cast<char*>(pCompilErrors->GetBufferPointer()); vsoutput(__FUNCTION__" : %s\n", ptr); } else { m_pEffect->SetStateManager((LPD3DXEFFECTSTATEMANAGER)m_rDisplay.GetStateManagerInterface()); m_hCurrentTechnique = NULL; m_strName = pInfo->m_strPath; m_mSemantics[0] = string(""); bResult = GetParameters(); } if (NULL != pCompilErrors) { pCompilErrors->Release(); } } return bResult; } void DisplayEffect::Update() { } void DisplayEffect::Release() { if (NULL != m_pEffect) { m_pEffect->Release(); m_pEffect = NULL; } m_mSemantics.clear(); m_mHandles.clear(); } void DisplayEffect::RenderRequest(DisplayMaterialPtr _pDisplayMaterial) { if (m_vRenderList.end() == find(m_vRenderList.begin(), m_vRenderList.end(), _pDisplayMaterial)) { m_vRenderList.push_back(_pDisplayMaterial); } } void DisplayEffect::Render() { #if 0 struct RenderMaterialFunction { void operator() (DisplayMaterialPtr _pDisplayMaterial) { _pDisplayMaterial->Render(); } }; for_each(m_vRenderList.begin(), m_vRenderList.end(), RenderMaterialFunction()); #else DisplayMaterialPtrVec::iterator iMaterial = m_vRenderList.begin(); DisplayMaterialPtrVec::iterator iEnd = m_vRenderList.end(); while (iEnd != iMaterial) { (*iMaterial)->Render(); ++iMaterial; } #endif m_vRenderList.clear(); } EffectPtr DisplayEffect::GetEffect() { return m_pEffect; } Handle DisplayEffect::GetHandleBySemanticKey(const Key& _uKey) { HandleMap::iterator iHandle = m_mHandles.find(_uKey); return ((m_mHandles.end() != iHandle) ? iHandle->second : NULL); } HandleMapRef DisplayEffect::GetHandles() { return m_mHandles; } const string& DisplayEffect::GetNameBySemanticKey(const Key& _uKey) { map<Key, string>::const_iterator iPair = m_mSemantics.find(_uKey); if (m_mSemantics.end() != iPair) { return iPair->second; } return m_mSemantics[0]; } Handle DisplayEffect::GetTechniqueByName(const char* _pszName) { return m_pEffect->GetTechniqueByName(_pszName); } void DisplayEffect::SetTechnique(Handle _hTechnique) { if (m_hCurrentTechnique != _hTechnique) { m_pEffect->SetTechnique(_hTechnique); m_hCurrentTechnique = _hTechnique; } } bool DisplayEffect::GetTechniqueDesc(Handle _hTechnique, D3DXTECHNIQUE_DESC* _pDesc) { return SUCCEEDED(m_pEffect->GetTechniqueDesc(_hTechnique, _pDesc)); } bool DisplayEffect::GetParameters() { EffectDesc oEffectDesc; bool bResult = SUCCEEDED(m_pEffect->GetDesc(&oEffectDesc)); if (false != bResult) { EffectParamDesc oParamDesc; Key uSemanticKey; Handle hParam; for (UInt i = 0 ; oEffectDesc.Parameters > i ; ++i) { hParam = m_pEffect->GetParameter(NULL, i); bResult = (NULL != hParam) && SUCCEEDED(m_pEffect->GetParameterDesc(hParam, &oParamDesc)); if (false == bResult) { vsoutput(__FUNCTION__" : %s, could not access parameter #%u\n", m_strName.c_str(), i); break; } if (NULL != oParamDesc.Semantic) { uSemanticKey = MakeKey(string(oParamDesc.Semantic)); bResult = (NULL == GetHandleBySemanticKey(uSemanticKey)); } else { continue; } if (false == bResult) { vsoutput(__FUNCTION__" : %s, could not access %s parameter handle\n", m_strName.c_str(), oParamDesc.Name); break; } m_mHandles[uSemanticKey] = hParam; m_mSemantics[uSemanticKey] = string(oParamDesc.Semantic); } } return bResult; } }
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 329 ] ] ]
56a4376cda6afaef7cd245c0d75a59ec840c2b3d
cfa6cdfaba310a2fd5f89326690b5c48c6872a2a
/Sources/Server/M-Server Manager/Sources/Manager/SQLMgr.cpp
cee67226902c088c0ece75e95dab575b06322845
[]
no_license
asdlei00/project-jb
1cc70130020a5904e0e6a46ace8944a431a358f6
0bfaa84ddab946c90245f539c1e7c2e75f65a5c0
refs/heads/master
2020-05-07T21:41:16.420207
2009-09-12T03:40:17
2009-09-12T03:40:17
40,292,178
0
0
null
null
null
null
UTF-8
C++
false
false
3,587
cpp
#include "stdafx.h" #include "SQLMgr.h" CSQLMgr::CSQLMgr() { } CSQLMgr::~CSQLMgr() { } HRESULT CSQLMgr::InitSQLMgr() { m_SQLDB.InitSQL("root", "1124", "mmuser"); m_SQLFriendDB.InitSQL("root", "1124", "friendinfo"); return S_OK; } void CSQLMgr::ReleaseSQLMgr() { m_SQLDB.ReleaseSQL(); m_SQLFriendDB.ReleaseSQL(); } bool CSQLMgr::IsValidAdminIDFromDB(const char* pszID) { char query[256]; sprintf(query, "SELECT id FROM mainsadmin WHERE id = '%s'", pszID); char * res = m_SQLDB.GetRow(query); if(res == NULL) { return false; } return true; } bool CSQLMgr::IsValidAdminPWFromDB(const char* pszID, const char* passwords) { char query[256]; sprintf(query, "SELECT passwords FROM mainsadmin WHERE id = '%s'", pszID); char* res = m_SQLDB.GetRow(query); res[strlen(res)-1] = NULL; if(strcmp(res, passwords) == 0) { return true; } return false; } bool CSQLMgr::IsValidUserIDFromDB(char* pszID) { char query[256]; for(int i = 0; i < MAX_ID_SIZE; i++) { if(pszID[i] == '0') pszID[i] = NULL; } sprintf(query, "SELECT id FROM userinfo WHERE id = '%s'", pszID); char* res = m_SQLDB.GetRow(query); if(res == NULL) { return true; } return false; } bool CSQLMgr::AddClientUser(const char* pszID, const char* passwords) { char query[256]; sprintf(query, "INSERT INTO userinfo VALUES('%d', '%s', '%s', '%s')", 0, pszID, "NONE", passwords); int query_stat = m_SQLDB.Query(query); if(query_stat != 0) return false; return true; } bool CSQLMgr::CheckUser(const char* pszID, const char* passwords) { char query[256]; sprintf(query, "SELECT passwords FROM userinfo WHERE id = '%s'", pszID); char* res = m_SQLDB.GetRow(query); if(res == NULL) return false; res[strlen(res)-1] = NULL; if(strcmp(passwords, res) == 0) return true; return false; } bool CSQLMgr::CreateTableFriendDB(const char* pszID) { char query[256]; char table[256]; memset(table, 0, 256); sprintf(table, "%s_friend_list", pszID); sprintf(query, "CREATE TABLE %s(id VARCHAR(32) PRIMARY KEY, msg VARCHAR(128), verify INT, deny INT)", table); int query_stat = m_SQLFriendDB.Query(query); if(query_stat != 0) return false; return true; } bool CSQLMgr::AddFriendUser(const char* pszID, const char* pszFriendID, char* pszMessage, bool bVerify, bool bDeny) { char query[256]; char table[256]; memset(table, 0, 256); sprintf(table, "%s_friend_list", pszID); sprintf(query, "INSERT INTO %s VALUES('%s', '%s', '%d', '%d')", table, pszFriendID, pszMessage, bVerify, bDeny); int query_stat = m_SQLFriendDB.Query(query); if(query_stat != 0) return false; return true; } bool CSQLMgr::UpdateFriendUser(const char* pszID, const char* pszFriendID, bool bVerify, bool bDeny) { char query[256]; char table[256]; memset(table, 0, 256); sprintf(table, "%s_friend_list", pszID); sprintf(query, "UPDATE %s SET verify = %d deny = %d WHERE id = '%s', table, pszFriendID, bVerify, bDeny"); int query_stat = m_SQLFriendDB.Query(query); if(query_stat != 0) return false; return true; } bool CSQLMgr::DeleteFriendUser(const char* pszID, const char* pszFriendID) { char query[256]; char table[256]; memset(table, 0, 256); sprintf(table, "%s_friend_list", pszID); sprintf(query, "DELETE FROM %s WHERE id = '%s'", table, pszFriendID, pszFriendID); int query_stat = m_SQLFriendDB.Query(query); if(query_stat != 0) return false; return true; }
[ [ [ 1, 16 ], [ 18, 24 ], [ 26, 27 ], [ 29, 33 ], [ 35, 43 ], [ 45, 59 ], [ 178, 178 ] ], [ [ 17, 17 ], [ 25, 25 ], [ 28, 28 ], [ 34, 34 ], [ 44, 44 ], [ 60, 177 ] ] ]
7a9edf632182146246ca0a38eb7110aaef3962e2
6c8c4728e608a4badd88de181910a294be56953a
/SupportModules/ConsoleEvents.h
70baff56d41a916c9751f59960ffa9812c8f8005
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
908
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_SupportModules_ConsoleEvents_h #define incl_SupportModules_ConsoleEvents_h //#include "StableHeaders.h" #include "EventDataInterface.h" namespace Console { namespace Events { static const event_id_t EVENT_CONSOLE_TOGGLE = 0x01; static const event_id_t EVENT_CONSOLE_PRINT_LINE = 0x02; static const event_id_t EVENT_CONSOLE_COMMAND_ISSUED = 0x03; static const event_id_t EVENT_CONSOLE_CONSOLE_VIEW_INITIALIZED = 0x04; } /// Event data interface for Consolemessages class ConsoleEventData : public Foundation::EventDataInterface { public: ConsoleEventData(const std::string string) : message(string) {} virtual ~ConsoleEventData() {} std::string message; }; } #endif
[ "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 2 ], [ 21, 21 ], [ 34, 34 ] ], [ [ 3, 5 ], [ 7, 20 ], [ 22, 33 ] ], [ [ 6, 6 ] ] ]
fce1d3b4473a1f5c4cec6e17a1b0627c9758cb08
2c9e29d0cdae3e532ff969c0de530b5b8084b61e
/psp/sound.cpp
ba550b12de2c0a30e33c9422068cc3e28dfba627
[]
no_license
Sondro/kurok
1695a976700f6c9732a761d33d092a679518e23b
59da1adb94e1132c5a2215b308280bacd7a3c812
refs/heads/master
2022-02-01T17:41:12.584690
2009-08-03T01:19:05
2009-08-03T01:19:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,944
cpp
/* Copyright (C) 1996-1997 Id Software, Inc. Copyright (C) 2007 Peter Mackay and Chris Swindle. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <pspaudiolib.h> #include <pspdebug.h> #include <pspkernel.h> extern "C" { #include "../quakedef.h" } namespace quake { namespace sound { struct Sample { short left; short right; }; static const unsigned int channelCount = 2; static const unsigned int inputBufferSize = 16384; #ifdef NORMAL_MODE static const unsigned int inputFrequency = 11025; #else static const unsigned int inputFrequency = 22050; #endif static const unsigned int outputFrequency = 44100; static const unsigned int inputSamplesPerOutputSample = outputFrequency / inputFrequency; static Sample inputBuffer[inputBufferSize]; static volatile unsigned int samplesRead; static inline void copySamples(const Sample* first, const Sample* last, Sample* destination) { switch (inputSamplesPerOutputSample) { case 1: memcpy(destination, first, (last - first) * sizeof(Sample)); break; case 2: for (const Sample* source = first; source != last; ++source) { const Sample sample = *source; *destination++ = sample; *destination++ = sample; } break; case 4: for (const Sample* source = first; source != last; ++source) { const Sample sample = *source; *destination++ = sample; *destination++ = sample; *destination++ = sample; *destination++ = sample; } break; default: break; } } static void fillOutputBuffer(void* buffer, unsigned int samplesToWrite, void* userData) { // Where are we writing to? Sample* const destination = static_cast<Sample*> (buffer); // Where are we reading from? const Sample* const firstSampleToRead = &inputBuffer[samplesRead]; // How many samples to read? const unsigned int samplesToRead = samplesToWrite / inputSamplesPerOutputSample; // Going to wrap past the end of the input buffer? const unsigned int samplesBeforeEndOfInput = inputBufferSize - samplesRead; if (samplesToRead > samplesBeforeEndOfInput) { // Yes, so write the first chunk from the end of the input buffer. copySamples( firstSampleToRead, firstSampleToRead + samplesBeforeEndOfInput, &destination[0]); // Write the second chunk from the start of the input buffer. const unsigned int samplesToReadFromBeginning = samplesToRead - samplesBeforeEndOfInput; copySamples( &inputBuffer[0], &inputBuffer[samplesToReadFromBeginning], &destination[samplesBeforeEndOfInput * inputSamplesPerOutputSample]); } else { // No wrapping, just copy. copySamples( firstSampleToRead, firstSampleToRead + samplesToRead, &destination[0]); } // Update the read offset. samplesRead = (samplesRead + samplesToRead) % inputBufferSize; } } } using namespace quake; using namespace quake::sound; qboolean SNDDMA_Init(void) { // Set up Quake's audio. shm = &sn; shm->channels = channelCount; shm->samplebits = 16; shm->speed = inputFrequency; shm->soundalive = qtrue; shm->splitbuffer = qfalse; shm->samples = inputBufferSize * channelCount; shm->samplepos = 0; shm->submission_chunk = 1; shm->buffer = (unsigned char *) inputBuffer; // Initialise the audio system. This initialises it for the CD audio module // too. pspAudioInit(); // Set the channel callback. // Sound effects use channel 0, CD audio uses channel 1. pspAudioSetChannelCallback(0, fillOutputBuffer, 0); return qtrue; } void SNDDMA_Shutdown(void) { // Clear the mixing buffer so we don't get any noise during cleanup. memset(inputBuffer, 0, sizeof(inputBuffer)); // Clear the channel callback. pspAudioSetChannelCallback(0, 0, 0); // Stop the audio system? pspAudioEndPre(); // Insert a false delay so the thread can be cleaned up. sceKernelDelayThread(50 * 1000); // Shut down the audio system. pspAudioEnd(); } int SNDDMA_GetDMAPos(void) { return samplesRead * channelCount; } void SNDDMA_Submit(void) { }
[ [ [ 1, 183 ] ] ]
e767b7e2c7348b39de36d38d6883cfa947103424
5399d919f33bca564bd309c448f1151e7fb6aa27
/server/thread/ThreadWindows.cpp
6349ecef16af71298327893386c98282739d45fa
[]
no_license
hotgloupi/zhttpd
bcbc37283ebf0fb401417fa1799f7f7bb286f0d5
0437ac2e34dde89abab26665df9cbee1777f1d44
refs/heads/master
2021-01-25T05:57:49.958146
2011-01-03T14:22:05
2011-01-03T14:22:05
963,056
4
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
#ifdef _WIN32 #include <Windows.h> #include <stdexcept> #include "thread/ITask.hpp" #include "utils/NonCopyable.hpp" #include "thread/ThreadWindows.hpp" using namespace zhttpd; using namespace zhttpd::implementation; DWORD Thread::_run(Thread* thread) { thread->_callback_instance->run(); return 0; } Thread::Thread(ITask* instance) : _callback_instance(instance), _running(true) { this->_thread = ::CreateThread(NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(Thread::_run), this, 0, 0); if (this->_thread == 0) throw std::runtime_error(std::string("CreateThread fail with code: ") + (int)::GetLastError()); } void Thread::join() { if (!this->_running) return; ::WaitForSingleObject(this->_thread, INFINITE); this->_running = false; } void Thread::quit() { if (this->_thread) { ::TerminateThread(this->_thread, 0); this->_thread = 0; } this->_running = false; } Thread::~Thread() { this->quit(); } #endif // _WIN32
[ [ [ 1, 56 ] ] ]
53b204964c62119a333cfc74483877d6da001f9d
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/video/ImageCacheEntry.cpp
43b9509649b2b60ec786b990b5645b710d0e8d0e
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
1,642
cpp
// ImageCacheEntry.cpp // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert 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, version 2 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #include "ImageCacheEntry.h" #include "SDL/SDL_video.h" /** * Ensure that the pointers start off pointing somewhere that's safe to * delete. */ ImageCacheEntry::ImageCacheEntry() { // Set pointer to NULL image = 0; // Set pointer to NULL shadow = 0; } /** * Frees the surfaces. If the destructor is invoked by * a copy of the main instance, the program will most likely * crash or otherwise mess up horribly. */ ImageCacheEntry::~ImageCacheEntry() { // If pointer are not NULL if (image != 0) { // Free surface SDL_FreeSurface(image); // Set pointer to NULL image = NULL; } // If pointer are not NULL if (shadow != 0) { // Free surface SDL_FreeSurface(shadow); // Set pointer to NULL shadow = NULL; } } /** * This function exists because we don't have shared pointers. */ void ImageCacheEntry::clear() { image = 0; shadow = 0; }
[ [ [ 1, 66 ] ] ]
fd3f74c03758db53b4f475aea9d89d17c03c0645
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/gfx2/nd3d9server_resource.cc
3c1c3aff7af943d17c8bf47e5386a4cbfcfa5a37
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,586
cc
//------------------------------------------------------------------------------ // nd3d9server_resource.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "precompiled/pchndirect3d9.h" #include "gfx2/nd3d9server.h" #include "resource/nresourceserver.h" #include "gfx2/nmesh2.h" #include "gfx2/nfont2.h" #include "gfx2/nd3d9mesharray.h" #include "gfx2/nd3d9shader.h" #include "gfx2/nd3d9occlusionquery.h" //------------------------------------------------------------------------------ /** Create a new shared mesh object. If the object already exists, its refcount is increment. @param rsrcName a resource name (used for resource sharing) @return pointer to a nD3D9Mesh2 object */ nMesh2* nD3D9Server::NewMesh(const char* rsrcName) { return (nMesh2*) this->refResource->NewResource("nd3d9mesh", rsrcName, nResource::Mesh); } //------------------------------------------------------------------------------ /** Create a new mesh array object. @return pointer to a nD3D9MeshArray object */ nMeshArray* nD3D9Server::NewMeshArray(const char* rsrcName) { return ((nMeshArray*) this->refResource->NewResource("nd3d9mesharray", rsrcName, nResource::Mesh)); } //------------------------------------------------------------------------------ /** Create a new shared texture object. If the object already exists, its refcount is incremented. @param rsrcName a resource name (used for resource sharing) @return pointer to a nD3D9Texture2 object */ nTexture2* nD3D9Server::NewTexture(const char* rsrcName) { return (nTexture2*) this->refResource->NewResource("nd3d9texture", rsrcName, nResource::Texture); } //------------------------------------------------------------------------------ /** Create a new shared shader object. If the object already exists, its refcount is incremented. @param rsrcName a resource name (used for resource sharing) @return pointer to a nD3D9Shader2 object */ nShader2* nD3D9Server::NewShader(const char* rsrcName) { return (nShader2*) this->refResource->NewResource("nd3d9shader", rsrcName, nResource::Shader); } //------------------------------------------------------------------------------ /** Create a new shared font object. If the object already exists, its refcount is incremented. @param rsrcName a resource name (used for resource sharing) @return pointer to a nD3D9Shader2 object */ nFont2* nD3D9Server::NewFont(const char* rsrcName, const nFontDesc& fontDesc) { nFont2* font = (nFont2*) this->refResource->NewResource("nd3d9font", rsrcName, nResource::Font); n_assert(font); font->SetFontDesc(fontDesc); return font; } //------------------------------------------------------------------------------ /** Create a new render target object. @param rsrcName a resource name for resource sharing @param width width of render target @param height height of render target @param format pixel format of render target @param usageFlags a combination of nTexture2::Usage flags */ nTexture2* nD3D9Server::NewRenderTarget(const char* rsrcName, int width, int height, nTexture2::Format format, int usageFlags) { nTexture2* renderTarget = (nTexture2*) this->refResource->NewResource("nd3d9texture", rsrcName, nResource::Texture); n_assert(renderTarget); if (!renderTarget->IsLoaded()) { n_assert(0 != (usageFlags & (nTexture2::RenderTargetColor | nTexture2::RenderTargetDepth | nTexture2::RenderTargetStencil))); renderTarget->SetUsage( static_cast<ushort>( usageFlags ) ); renderTarget->SetWidth( static_cast<ushort>( width ) ); renderTarget->SetHeight( static_cast<ushort>( height ) ); renderTarget->SetDepth(1); renderTarget->SetFormat(format); renderTarget->SetType(nTexture2::TEXTURE_2D); bool success = renderTarget->Load(); if (!success) { renderTarget->Release(); return 0; } } return renderTarget; } //------------------------------------------------------------------------------ /** Create a new occlusion query object. @return pointer to a new occlusion query object */ nOcclusionQuery* nD3D9Server::NewOcclusionQuery() { return n_new(nD3D9OcclusionQuery); } //------------------------------------------------------------------------------ /** Create a new occlusion query object. @return pointer to a new occlusion query object */ IDirect3DVertexDeclaration9* nD3D9Server::NewVertexDeclaration(const int vertexComponentMask) { IDirect3DVertexDeclaration9* d3d9vdecl(0); if (this->vertexDeclarationCache.HasKey(vertexComponentMask)) { d3d9vdecl = this->vertexDeclarationCache.GetElement(vertexComponentMask); d3d9vdecl->AddRef(); return d3d9vdecl; } const int maxElements = nMesh2::NumVertexComponents; D3DVERTEXELEMENT9 decl[maxElements]; int curElement = 0; int curOffset = 0; int index; for (index = 0; index < maxElements; index++) { int mask = (1<<index); if (vertexComponentMask & mask) { decl[curElement].Stream = 0; n_assert( curOffset <= int( 0xffff ) ); decl[curElement].Offset = static_cast<WORD>( curOffset ); decl[curElement].Method = D3DDECLMETHOD_DEFAULT; switch (mask) { case nMesh2::Coord: decl[curElement].Type = D3DDECLTYPE_FLOAT3; decl[curElement].Usage = D3DDECLUSAGE_POSITION; decl[curElement].UsageIndex = 0; curOffset += 3 * sizeof(float); break; case nMesh2::Coord4: decl[curElement].Type = D3DDECLTYPE_FLOAT4; decl[curElement].Usage = D3DDECLUSAGE_POSITION; decl[curElement].UsageIndex = 0; curOffset += 4 * sizeof(float); break; case nMesh2::Normal: decl[curElement].Type = D3DDECLTYPE_FLOAT3; decl[curElement].Usage = D3DDECLUSAGE_NORMAL; decl[curElement].UsageIndex = 0; curOffset += 3 * sizeof(float); break; case nMesh2::Tangent: decl[curElement].Type = D3DDECLTYPE_FLOAT3; decl[curElement].Usage = D3DDECLUSAGE_TANGENT; decl[curElement].UsageIndex = 0; curOffset += 3 * sizeof(float); break; case nMesh2::Binormal: decl[curElement].Type = D3DDECLTYPE_FLOAT3; decl[curElement].Usage = D3DDECLUSAGE_BINORMAL; decl[curElement].UsageIndex = 0; curOffset += 3 * sizeof(float); break; case nMesh2::Color: decl[curElement].Type = D3DDECLTYPE_FLOAT4; decl[curElement].Usage = D3DDECLUSAGE_COLOR; decl[curElement].UsageIndex = 0; curOffset += 4 * sizeof(float); break; case nMesh2::Uv0: decl[curElement].Type = D3DDECLTYPE_FLOAT2; decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD; decl[curElement].UsageIndex = 0; curOffset += 2 * sizeof(float); break; case nMesh2::Uv1: decl[curElement].Type = D3DDECLTYPE_FLOAT2; decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD; decl[curElement].UsageIndex = 1; curOffset += 2 * sizeof(float); break; case nMesh2::Uv2: decl[curElement].Type = D3DDECLTYPE_FLOAT2; decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD; decl[curElement].UsageIndex = 2; curOffset += 2 * sizeof(float); break; case nMesh2::Uv3: decl[curElement].Type = D3DDECLTYPE_FLOAT2; decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD; decl[curElement].UsageIndex = 3; curOffset += 2 * sizeof(float); break; case nMesh2::Weights: decl[curElement].Type = D3DDECLTYPE_FLOAT4; decl[curElement].Usage = D3DDECLUSAGE_BLENDWEIGHT; decl[curElement].UsageIndex = 0; curOffset += 4 * sizeof(float); break; case nMesh2::JIndices: decl[curElement].Type = D3DDECLTYPE_FLOAT4; decl[curElement].Usage = D3DDECLUSAGE_BLENDINDICES; decl[curElement].UsageIndex = 0; curOffset += 4 * sizeof(float); break; default: n_error("Unknown vertex component in vertex component mask"); break; } curElement++; } } // write vertex declaration terminator element, see D3DDECL_END() macro in d3d9types.h for details decl[curElement].Stream = 0xff; decl[curElement].Offset = 0; decl[curElement].Type = D3DDECLTYPE_UNUSED; decl[curElement].Method = 0; decl[curElement].Usage = 0; decl[curElement].UsageIndex = 0; n_dxverify2(//gfxServer->d3d9Device->CreateVertexDeclaration(decl, &(this->vertexDeclaration)), this->d3d9Device->CreateVertexDeclaration(decl, &d3d9vdecl), "CreateVertexDeclaration() failed in nD3D9Mesh" ); d3d9vdecl->AddRef(); this->vertexDeclarationCache.Add(vertexComponentMask, d3d9vdecl); return d3d9vdecl; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 275 ] ] ]
f37e7e3899b3cf588f2087a0141c789a76f180a3
6e563096253fe45a51956dde69e96c73c5ed3c18
/Sockets/StreamSocket.cpp
536c16b56f516de86b646fd2f409c1cb6d1be9ea
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,635
cpp
/** ** \file StreamSocket.cpp ** \date 2008-12-20 ** \author [email protected] **/ /* Copyright (C) 2008-2009 Anders Hedstrom This library is made available under the terms of the GNU GPL, with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. If you would like to use this library in a closed-source application, a separate license agreement is available. For information about the closed-source license agreement for the C++ sockets library, please visit http://www.alhem.net/Sockets/license.html and/or email [email protected]. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "StreamSocket.h" #include "ISocketHandler.h" #ifdef SOCKETS_NAMESPACE namespace SOCKETS_NAMESPACE { #endif StreamSocket::StreamSocket(ISocketHandler& h) : Socket(h) ,m_bConnecting(false) ,m_connect_timeout(5) ,m_flush_before_close(true) ,m_connection_retry(0) ,m_retries(0) ,m_call_on_connect(false) ,m_b_retry_connect(false) ,m_line_protocol(false) ,m_shutdown(0) { } StreamSocket::~StreamSocket() { } void StreamSocket::SetConnecting(bool x) { if (x != m_bConnecting) { m_bConnecting = x; if (x) { SetTimeout( GetConnectTimeout() ); } else { SetTimeout( 0 ); } } } bool StreamSocket::Connecting() { return m_bConnecting; } bool StreamSocket::Ready() { if (GetSocket() != INVALID_SOCKET && !Connecting() && !CloseAndDelete()) return true; return false; } void StreamSocket::SetConnectTimeout(int x) { m_connect_timeout = x; } int StreamSocket::GetConnectTimeout() { return m_connect_timeout; } void StreamSocket::SetFlushBeforeClose(bool x) { m_flush_before_close = x; } bool StreamSocket::GetFlushBeforeClose() { return m_flush_before_close; } int StreamSocket::GetConnectionRetry() { return m_connection_retry; } void StreamSocket::SetConnectionRetry(int x) { m_connection_retry = x; } int StreamSocket::GetConnectionRetries() { return m_retries; } void StreamSocket::IncreaseConnectionRetries() { m_retries++; } void StreamSocket::ResetConnectionRetries() { m_retries = 0; } void StreamSocket::SetCallOnConnect(bool x) { Handler().AddList(GetSocket(), LIST_CALLONCONNECT, x); m_call_on_connect = x; } bool StreamSocket::CallOnConnect() { return m_call_on_connect; } void StreamSocket::SetRetryClientConnect(bool x) { Handler().AddList(GetSocket(), LIST_RETRY, x); m_b_retry_connect = x; } bool StreamSocket::RetryClientConnect() { return m_b_retry_connect; } void StreamSocket::SetLineProtocol(bool x) { m_line_protocol = x; } bool StreamSocket::LineProtocol() { return m_line_protocol; } void StreamSocket::SetShutdown(int x) { m_shutdown = x; } int StreamSocket::GetShutdown() { return m_shutdown; } #ifdef SOCKETS_NAMESPACE } // namespace SOCKETS_NAMESPACE { #endif
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 201 ] ] ]
60a8f840390868ebcfd6be75f3946b5ac177a1ef
9429a0e1b44f45cff3c5272383ee45ba60189226
/relative_file/src/main.cpp
4ace5db63b7464bf15e76f4570a6b57fe921e00f
[]
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,318
cpp
#include <iostream> #include <cstdlib> #include <sstream> #include "ArchivoLexico.h" #include "LexicoData.h" using namespace std; //TIPO DE RAGISTRO DE ARCHIVO_LEXICO. int main(int argc, char *argv[]) { // string cadena; // cout << "nombre para el archivo : " << endl; // cin >> cadena; //ArchivoLexico *ptrArch = new ArchivoLexico( cadena , sizeof(DatoLexico) ); /* cout << "ARCHIVO : " << endl; cout << "nombre :" << ptrArch->getNombre() << endl; cout << "tamanio :" << ptrArch->getTamanio() << endl; cout << "estado :" << ptrArch->getEstado(); */ LexicoData dato; ArchivoLexico *ptrArch = new ArchivoLexico( "Z.dat" , ESCRIBIR ); try { for( int i=1; i <= 5 ; i++ ) { dato.id = i*5; ostringstream os; os << i; dato.termino = "termino " + os.str(); ptrArch->escribir( dato ); } } catch ( string a ) { cout << endl << a << endl ; } delete ptrArch; ptrArch = new ArchivoLexico( "Z.dat" , LEER ); try { ptrArch->comenzarLectura(); for( int i=1; i <= 5 ; i++ ) { ptrArch->leer( dato ); cout << "REGISTRO: " << i << " - id: " << dato.id << " - palabra: " << dato.termino << endl; } } catch ( string a ) { cout << endl << a << endl ; } delete ptrArch; return 0; }
[ "pablorusso@732baeec-bf1d-0410-89bf-576031c28093" ]
[ [ [ 1, 63 ] ] ]
9bcccb4de6be5cbac371b470c0c7248ed37409af
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十三章 复制控制/20090217_习题13.9_赋值操作符.cpp
b4e66789381260fd42482bddd0c3f3e3e3cd0ebd
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
281
cpp
struct NoName { NoNane(): pstring(new std::string), i(0), d(0) { } private: std::string *pstring; int i; double d; }; NoName& NoName::operator=(const NoNane &rhs) { pstring = new std::string; *pstring = *(rhs.pstring); i = rhs.i; d = rhs.d; return *this; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 16 ] ] ]
7bf6545ca7e0f507f97586b5866aef768cfb344f
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/7-Zip/CPP/7zip/Archive/Tar/TarUpdate.cpp
16ec83eced2b7660484d4de54707d3172c3bef32
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
3,876
cpp
// TarUpdate.cpp #include "StdAfx.h" #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" #include "../../Compress/CopyCoder.h" #include "TarOut.h" #include "TarUpdate.h" namespace NArchive { namespace NTar { HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, const CObjectVector<NArchive::NTar::CItemEx> &inputItems, const CObjectVector<CUpdateItem> &updateItems, IArchiveUpdateCallback *updateCallback) { COutArchive outArchive; outArchive.Create(outStream); UInt64 complexity = 0; int i; for(i = 0; i < updateItems.Size(); i++) { const CUpdateItem &ui = updateItems[i]; if (ui.NewData) complexity += ui.Size; else complexity += inputItems[ui.IndexInArchive].GetFullSize(); } RINOK(updateCallback->SetTotal(complexity)); NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; CLocalProgress *lps = new CLocalProgress; CMyComPtr<ICompressProgressInfo> progress = lps; lps->Init(updateCallback, true); CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; CMyComPtr<CLimitedSequentialInStream> inStreamLimited(streamSpec); streamSpec->SetStream(inStream); complexity = 0; for(i = 0; i < updateItems.Size(); i++) { lps->InSize = lps->OutSize = complexity; RINOK(lps->SetCur()); const CUpdateItem &ui = updateItems[i]; CItem item; if (ui.NewProps) { item.Mode = ui.Mode; item.Name = ui.Name; item.User = ui.User; item.Group = ui.Group; if (ui.IsDir) { item.LinkFlag = NFileHeader::NLinkFlag::kDirectory; item.Size = 0; } else { item.LinkFlag = NFileHeader::NLinkFlag::kNormal; item.Size = ui.Size; } item.MTime = ui.Time; item.DeviceMajorDefined = false; item.DeviceMinorDefined = false; item.UID = 0; item.GID = 0; memmove(item.Magic, NFileHeader::NMagic::kEmpty, 8); } else item = inputItems[ui.IndexInArchive]; if (ui.NewData) { item.Size = ui.Size; if (item.Size == (UInt64)(Int64)-1) return E_INVALIDARG; } else item.Size = inputItems[ui.IndexInArchive].Size; if (ui.NewData) { CMyComPtr<ISequentialInStream> fileInStream; HRESULT res = updateCallback->GetStream(ui.IndexInClient, &fileInStream); if (res != S_FALSE) { RINOK(res); RINOK(outArchive.WriteHeader(item)); if (!ui.IsDir) { RINOK(copyCoder->Code(fileInStream, outStream, NULL, NULL, progress)); if (copyCoderSpec->TotalSize != item.Size) return E_FAIL; RINOK(outArchive.FillDataResidual(item.Size)); } } complexity += ui.Size; RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); } else { const CItemEx &existItemInfo = inputItems[ui.IndexInArchive]; UInt64 size; if (ui.NewProps) { RINOK(outArchive.WriteHeader(item)); RINOK(inStream->Seek(existItemInfo.GetDataPosition(), STREAM_SEEK_SET, NULL)); size = existItemInfo.Size; } else { RINOK(inStream->Seek(existItemInfo.HeaderPosition, STREAM_SEEK_SET, NULL)); size = existItemInfo.GetFullSize(); } streamSpec->Init(size); RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); if (copyCoderSpec->TotalSize != size) return E_FAIL; RINOK(outArchive.FillDataResidual(existItemInfo.Size)); complexity += size; } } return outArchive.WriteFinishHeader(); } }}
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 139 ] ] ]
e0d0dabbd2bb31c77618d4528383dbe331a79fff
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/main.cpp
20b81690751d7db8802ba9e359e451d71adbb94a
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include "lexer.h" #include "parser.h" #include "tree.h" #include <fstream> #include <iostream> #include <vector> Lexer* lexer = new Lexer(); Parser* parser = new Parser(); Tree<Token>* ast; int main() { std::string source_data, t_src; std::ifstream sourcefile ("example.txt"); //open the source file if ( sourcefile.is_open() ) { while ( !sourcefile.eof() ) { getline (sourcefile, t_src); source_data += t_src; } sourcefile.close(); } //call the lexer Lexer::getInstance()->init(source_data); Parser::getInstance()->parse(); delete lexer; delete parser; return 0; }
[ [ [ 1, 33 ] ] ]