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
6ad888e15c1e8bfe7e7df3bfe1ec468e7962e6fb
067ff5708784b1fd2595957de78518e87073ccb4
/Capture_Estimator/Capture_Estimator/ErrVisualize.cpp
05f8ab3ebeadc41aeaef81f6e3cef293187d9005
[]
no_license
wolfmanu/opencvthesis
637a6a6ead5c839e731faca19ae0dd3e59e33cd3
c4e806d6369b4ed80ebadce1684e32f147eafce4
refs/heads/master
2016-09-05T22:38:07.528951
2010-09-10T12:01:49
2010-09-10T12:01:49
32,142,213
0
0
null
null
null
null
UTF-8
C++
false
false
10,583
cpp
/*--------------------------------------------------------------------------- Program.......: ErrVisualizeApp.exe File..........: ErrVisualize.cpp Purpose.......: ErrVisualize class implementation Author........: P. Lanza Modified......: P. Lanza Created.......: 30/08/2005 Last Changed..: 06/09/2005 Copyright.....: License.......: ---------------------------------------------------------------------------*/ #include "ErrVisualize.h" #include <iostream> #include <list> // STL list #include <fstream> #include <time.h> // for time functions #include <windows.h> // for GUI messages using namespace std; //Initialisation of the Singleton at the end of this file! //With this initialisation we avoid a lot of troubles during the linking // with others classes other ErrVisualizeTest. ErrVisualize::ErrVisualize(bool val) : debugInfo(val), timeInfo(true), decoratedInfo(true), emulatedInfo(false), GUIInfo(0), lasterrNum(0), lastnline(9999) { lastMsgString=" "; outString=" "; lastnfile="no file name available"; ltime=0; type='e'; retValue=-1; } int ErrVisualize::msg( const std::string& input, // message int errNum, // number error const std::string& level, // level specification: F, E, W, A M const std::string& nfile, // typically filename from __FILE__ const int nline) { // typically line number from __LINE__ ostringstream tmp; // local varible to build the string lastMsgString=input; // evaluate the input message in accordance with the decoratedInfo flag if (decoratedInfo) {// This means that the output string should be visualised on standard stream tmp<<" ------------start error message-------------------"<<endl; } // evaluate the input message in accordance with the debugInfo flag if (debugInfo) {// I find <info> in the message received tmp<<input<<endl; type=level[0]; type=tolower(type); switch (type){ case 'f' : tmp<<"Fatal error in "; break; case 'e' : tmp<<"Error in "; break; case 'w' : tmp<<"Warning in "; break; case 'a' : tmp<<"Assertion in "; break; case 'm' : tmp<<"Message error in "; break; case 'i' : break; default : tmp<<"Error in "; break; } tmp<<nfile<<" at line "<<nline; } else { tmp<<input; } tmp<<endl; // add a carriege return // evaluate the input message in accordance with the TimeInfo flag if (timeInfo) {// attach the time information time(&ltime); tmp<<ctime(&ltime)<<endl; } // re-evaluate the input message in accordance with the DecoratedInfo flag if (decoratedInfo) {// This means that the output string should be visualised on standard stream tmp<<" ------------end error message---------------------"<<endl; } // evaluate the input message in accordance with the spec ( call spec) // call output for visualize the message outString=tmp.str(); lasterrNum=errNum; lastnfile=nfile, lastnline=nline; retValue=out(); // call the output method (potrebe chiamarlo mettendo in evidenza il livello di errore return retValue; } int ErrVisualize::out() { switch (GUIInfo) { case 0: cerr<<outString<<endl; break; case 1: retValue=GUImsg(); break; // only GUI case 2: cerr<<outString<<endl; retValue=GUImsg(); break; //GUI and cerr default: cerr<<outString<<endl; break; // only cerr } // now I call emulation() wheter the emulated flag is enabled. if (emulatedInfo) { emulation(); }; return retValue; // } const string ErrVisualize::lastMsg() {return outString;} // output const string ErrVisualize::moreDetails(const int details) { ostringstream tmp; // local varible to build the string // return a string to the caller as default message. tmp<<" No more information on the kind of error indicated ( number "; tmp<<details<<" ) are available now!"; outString=tmp.str(); return outString; // return by value ( String is a little obj) } // get and set functions relative to DebugInfo private variable bool ErrVisualize::getDebugInfo() {return debugInfo; }; void ErrVisualize::setDebugInfo(const bool value) {debugInfo=value; }; // enable disable functions relative to DebugInfo void ErrVisualize::enableDebugInfo() {setDebugInfo(true); }; void ErrVisualize::disableDebugInfo() {setDebugInfo(false); }; // get and set functions relative to timeInfo private variable bool ErrVisualize::getTimeInfo() {return timeInfo; }; void ErrVisualize::setTimeInfo(const bool value) {timeInfo=value; }; // enable disable functions relative to TimeInfo void ErrVisualize::enableTimeInfo() {setTimeInfo(true); } void ErrVisualize::disableTimeInfo() {setTimeInfo(false); } // get and set functions relative to decoratedInfo private variable bool ErrVisualize::getDecoratedInfo() {return decoratedInfo; }; void ErrVisualize::setDecoratedInfo(const bool value) {decoratedInfo=value; }; // enable disable functions relative to DecoratedInfo void ErrVisualize::enableDecoratedInfo() {setDecoratedInfo(true); } void ErrVisualize::disableDecoratedInfo() {setDecoratedInfo(false); } // get and set functions relative to emulatedInfo private variable bool ErrVisualize::getEmulatedInfo() {return emulatedInfo; }; void ErrVisualize::setEmulatedInfo(const bool value) {emulatedInfo=value; firstMsg=true; }; // enable disable functions relative to DebugInfo void ErrVisualize::enableEmulatedInfo() {setEmulatedInfo(true); } void ErrVisualize::disableEmulatedInfo() {setEmulatedInfo(false); } // get and set functions relative to decoratedInfo private variable int ErrVisualize::getGUIInfo() {return GUIInfo; }; void ErrVisualize::setGUIInfo(const int value) { if ((value<0) || (value>=3)) { // there is an input error!! ostringstream tmp; // local varible to build the string tmp<<"The GUIInfo value shall be limited within 1 to 2 included values."<<endl; tmp<<"The input value is "<<value<<endl; msg( tmp.str(), 100, "E", __FILE__, __LINE__ ); // ERROR(tmp.str(),100); } else { GUIInfo=value; } }; int ErrVisualize::GUImsg() { //it is called only by out() method // this function is enbled in this version of the ErrVisualize class. // all error messages are sent to cerr // //cerr<<outString<<endl; // verify that kind of error should be visualised: // evaluate the input message in accordance with the debugInfo flag int retValue = -1; switch (type){ case 'f' : retValue = printf("OpenCV and IP library Fatal Error"); break; case 'e' : retValue = printf("OpenCV and IP library Fatal Error"); break; case 'w' : retValue = printf("OpenCV and IP library Warning"); break; case 'a' : retValue = printf("OpenCV and IP library Assert Condition Failed"); break; case 'm' : retValue = printf("OpenCV and IP library Message"); break; case 'i' : retValue = printf("OpenCV and IP library Information"); break; default: retValue = printf("OpenCV and IP library Fatal Error"); break; } //f: retValue doesn't matter //e: retValue doesn't matter //f: retValue doesn't matter //w: retValue doesn't matter //a: retValue Abort Retry Ignore //m: retValue Yes No Cancel //i: retValue doesn't matter //default: retValue doesn't matter return retValue; /* only for information // all MessageBox function styles are avialbale on MSDN site MessageBox(NULL, "Oh my God, goodbye, cruel world!", "Pg Window", MB_OK); // Information MessageBox(NULL, "Icon question OKCANCEL", "Error!",MB_ICONQUESTION | MB_OKCANCEL); MessageBox(NULL, "Icon asterisk YESNO", "Error!",MB_ICONASTERISK | MB_YESNO); MessageBox(NULL, "Icon asterisk YESNOCANCEL", "Error!",MB_ICONASTERISK | MB_YESNOCANCEL); MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONINFORMATION | MB_OK); MessageBox(NULL, "Window Abort Retry Ignore...", "Error!",MB_ABORTRETRYIGNORE | MB_OK); // for Errors MessageBox(NULL, "Icon Error", "Error!",MB_ICONERROR | MB_OK ); */ } void ErrVisualize::emulation() { //it is called only by out() method static list<int> errNumList; list<int>::iterator pos; ofstream outf; static int nummsg=0; if (firstMsg) { //that it is the first Msg to process as Emulation time_t timeloc; // local variable // the flag is updated: firstMsg=false; // clear the list container errNumList.erase(errNumList.begin(), errNumList.end()); // insert the first element into the list errNumList.push_back(lasterrNum); // Open a file stream where to store all messages outf.open("ErrorMsgLog.txt", ios::out); // ASSERTFILE(outf,"ErrorMsgLog.txt"); time(&timeloc); // local variable outf<<endl<<endl<<"New session of Error Messages Log file "<<endl; outf<<ctime(&ltime)<<endl<<endl; nummsg=1; } else { outf.open("ErrorMsgLog.txt", ios::out| ios::app); // search if another element with the same number is already existing //Il find() non esiste... //pos = find(errNumList.begin(), errNumList.end(), lasterrNum); //if (pos==errNumList.end()) { errNumList.push_back(lasterrNum); //} //else { // error message // // write a message into the file stream // // re open the file stream each time for more security // // outf.open("ErrorMsgLog.txt", ios::out| ios::app); // // assertFile(outf,"ErrorMsgLog.txt"); // outf<<"$$ERROR MESSAGE LOG FILE: equal number error: "<<lasterrNum<<endl; //} //Il find() non esiste... } // store the last Msg read outf<<endl; outf<<"message number: "<<nummsg++<<endl; outf<<"Error number: "<<lasterrNum<<endl; outf<<"File: "<<lastnfile<<endl; outf<<"Line: "<<lastnline<<endl; outf<<"visualized message: "<<endl; outf<<outString; outf.close(); } int ErrVisualize::retVal() { return retValue; } // This instruction is relevant to the intilisation of the ErrVisualize singleton. // it is necessary to initilise the singleton first to use it ErrVisualize ErrVisualize::Err(true); // instatiation of the singleton! DebugInfo=true: enable all Debug info
[ "thewolfmanu@8d742ff4-5afa-cc76-88a1-f39302f5df42" ]
[ [ [ 1, 326 ] ] ]
338bce3489af529d6f48cd1c24b42f03779da0e7
27c6eed99799f8398fe4c30df2088f30ae317aff
/rtt-tool/qdoc3/ccodeparser.cpp
70ade870d1f28ce259ffd6a1b34f27a1350ecb6c
[]
no_license
lit-uriy/ysoft
ae67cd174861e610f7e1519236e94ffb4d350249
6c3f077ff00c8332b162b4e82229879475fc8f97
refs/heads/master
2021-01-10T08:16:45.115964
2009-07-16T00:27:01
2009-07-16T00:27:01
51,699,806
0
0
null
null
null
null
UTF-8
C++
false
false
2,419
cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the tools applications 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$ ** ****************************************************************************/ /* ccodeparser.cpp */ #include "ccodeparser.h" QT_BEGIN_NAMESPACE CCodeParser::CCodeParser() { } CCodeParser::~CCodeParser() { } QString CCodeParser::language() { return QLatin1String("C"); } QString CCodeParser::headerFileNameFilter() { return QLatin1String("*.ch *.h"); } QString CCodeParser::sourceFileNameFilter() { return QLatin1String("*.c"); } QT_END_NAMESPACE
[ "lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330" ]
[ [ [ 1, 73 ] ] ]
536ecd76b0b620afe6e04730c48350d479f4ae11
c04ce4f22fc46c4d44fc425275403592bc6f067a
/wolf/src/game/render/rObject.cpp
9f5862be83f7cc41e3b28b976dfd6a5c69a139cd
[]
no_license
allenh1/wolfenstein-reloaded
0161953173f053cc1ee4e03555def208ea98a34b
4db98d1a9e5bf51f88c58d9acae6d7f6850baf1d
refs/heads/master
2020-04-10T03:30:04.121502
2010-07-09T17:14:50
2010-07-09T17:14:50
32,124,233
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
7,283
cpp
/* ************************************************************************** Wolfenstein Reloaded Developed by Morgan Jones <[email protected]>, Hunter Allen <[email protected]> File Description: Base class for game objects ************************************************************************** Copyright © 2010 Morgan Jones, Hunter Allen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** */ #include "rObject.h" rPoint::rPoint() { _x = _y = _z = 0; } rPoint::rPoint(float x, float y, float z) { setCoords( x, y, z ); } void rPoint::setCoords(float x, float y, float z) { _x = x; _y = y; _z = z; } float rPoint::xPos() { return _x; } float rPoint::yPos() { return _y; } float rPoint::zPos() { return _z; } rTexture::rTexture() { _texid = 0xffffffff; _file = NULL; } rTexture::~rTexture() { release(); } rTexture::rTexture(tFile * file) { _texid = 0xffffffff; _file = file; } GLuint rTexture::textureID() { return _texid; } void rTexture::load() { if( _file == NULL ) return; /* Variables */ char * data = NULL; size_t length = 0; GLuint format = 0; SDL_RWops * rw = NULL; SDL_Surface * temp = NULL, *surface = NULL; bool freeIt = true; /* Get data and load it into SDL */ data = _file->data( length ); /* Read/write from memory */ if( data != NULL ) rw = SDL_RWFromMem( data, length ); else rw = NULL; /* Load it as an SDL_Surface */ temp = IMG_Load_RW( rw, 1 ); /* Check the image. If the surface is NULL, the image won't work. Fill it with white. */ if( temp == NULL ) { temp = SDL_CreateRGBSurface( SDL_SWSURFACE, 64, 64, 32, 0, 0, 0, 0 ); if( temp == NULL ) { cerr << "Fallback failed: File " << _file->path().leaf() << " failed to load (surface creation error)." << endl; return; } if( SDL_FillRect( temp, NULL, 0xffffffff ) != 0 ) { cerr << "Fallback failed: File " << _file->path().leaf() << " failed to load (rectangle filling error)." << endl; return; } } /* Normalize image */ surface = SDL_DisplayFormat( temp ); /* If the normalization doesn't work, use the old one. */ if( surface == NULL ) { surface = temp; surface->refcount++; freeIt = false; } /* Free memory */ if( data ) { delete[] data; data = NULL; } if( temp && freeIt ) { SDL_FreeSurface( temp ); temp = NULL; } /* Set texture parameters */ glGenTextures( 1, &_texid ); glBindTexture( GL_TEXTURE_2D, _texid ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); /* Determine pixel format */ if( surface->format->BitsPerPixel == 32 ) format = GL_RGBA; else format = GL_RGB; /* Make the texture - finally */ SDL_LockSurface( surface ); glTexImage2D( GL_TEXTURE_2D, 0, format, surface->w, surface->h, 0, format, GL_BYTE, surface->pixels ); SDL_UnlockSurface( surface ); /* Free the surface */ if( surface ) { SDL_FreeSurface( surface ); surface = NULL; } } void rTexture::load(tFile * file) { _file = file; load(); } void rTexture::release() { if( _texid == 0xffffffff ) return; glDeleteTextures( 1, &_texid ); } rPoly::rPoly() { _visible = true; } rPoly::rPoly(rTexture texture) { _visible = true; setTexture( texture ); } void rPoly::addVertex(rVertex vertex) { _vertices.push_back( vertex ); } void rPoly::setTexture(rTexture texture) { _texture = texture; } void rPoly::changeVisibility(bool visibility) { _visible = visibility; } rTexture rPoly::texture() { return _texture; } bool rPoly::isVisible() { return _visible; } vector <rVertex> * rPoly::vertices() { return &_vertices; } rObject::rObject() { _coords.setCoords( 0, 0, 0 ); } rObject::rObject(rPoint coords) { setCoords( coords ); } void rObject::addPoly(rPoly poly) { _polys.push_back( poly ); } void rObject::setCoords(rPoint coords) { _coords = coords; } void rObject::setColor(tColor color) { _color = color; } void rObject::recalcPolys() { /* Set initial polys if we haven't yet */ if( _polys.empty() ) this->setInitialPolys(); /* Make "bags" of coordinates */ vector <float> xBag; vector <float> yBag; vector <float> zBag; /* Add numbers */ for( vector <rPoly>::iterator it = _polys.begin(); it != _polys.end(); it++ ) { vector <rVertex> * vertices = it->vertices(); for( vector <rVertex>::iterator ti = vertices->begin(); ti != vertices->end(); ti++ ) { xBag.push_back( ti->xPos() ); yBag.push_back( ti->yPos() ); zBag.push_back( ti->zPos() ); } } /* Determine maximum and minimuum */ float max_x = *max_element( xBag.begin(), xBag.end() ); float max_y = *max_element( yBag.begin(), yBag.end() ); float max_z = *max_element( zBag.begin(), zBag.end() ); float min_x = *min_element( xBag.begin(), xBag.end() ); float min_y = *min_element( yBag.begin(), yBag.end() ); float min_z = *min_element( zBag.begin(), zBag.end() ); /* Set vertices */ _ctr = rVertex( max_x - (max_x - min_x) / 2.0, max_y - (max_y - min_y) / 2.0, max_z - (max_z - min_z) / 2.0 ); _max = rVertex( max_x + _ctr.xPos(), max_y + _ctr.yPos(), max_z + _ctr.zPos() ); _min = rVertex( min_x + _ctr.xPos(), min_y + _ctr.yPos(), min_z + _ctr.zPos() ); /* Recalculate polygon absolute positions using updated center point */ for( vector <rPoly>::iterator it = _polys.begin(); it != _polys.end(); it++ ) { vector <rVertex> * vertices = it->vertices(); for( vector <rVertex>::iterator ti = vertices->begin(); ti != vertices->end(); ti++ ) ti->setCoords( ti->xPos() + _ctr.xPos(), ti->yPos() + _ctr.yPos(), ti->zPos() + _ctr.zPos() ); } }
[ "maclover100@14159fd0-a646-01e2-d422-a234b5f98ae5", "hunterallen40@14159fd0-a646-01e2-d422-a234b5f98ae5" ]
[ [ [ 1, 5 ], [ 7, 276 ] ], [ [ 6, 6 ] ] ]
b3a7a3114c0755828abc61ffd6ee89e3be022ffd
6caf1a340711c6c818efc7075cc953b2f1387c04
/client/DlgMain.cpp
4b033a00e75058e2d80b82f4414f4c15c1cfc451
[]
no_license
lbrucher/timelis
35c68061bea68cc31ce1c68e3adbc23cb7f930b1
0fa9f8f5ef28fe02ca620c441783a1ff3fc17bde
refs/heads/master
2021-01-01T18:18:37.988944
2011-08-18T19:39:19
2011-08-18T19:39:19
2,229,915
2
1
null
null
null
null
UTF-8
C++
false
false
7,578
cpp
// $Id: DlgMain.cpp,v 1.1 2005/01/11 14:42:24 lbrucher Exp $ // #include "stdafx.h" #include "DlgMain.h" #include "DlgPauses.h" #include "DlgTasks.h" #include "WorkDay.h" #include "RecTimeSheet.h" #include "RecPauses.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define WM_REFRESHDAYLABEL (WM_USER+1) BEGIN_MESSAGE_MAP(CDlgMain, CDialog) //{{AFX_MSG_MAP(CDlgMain) ON_BN_CLICKED(IDC_BUTPAUSERESUME, OnPauseResume) ON_BN_CLICKED(IDC_BUTSTARTFINISH, OnStartFinish) ON_BN_CLICKED(IDC_BUTTASKS, OnTasks) ON_BN_CLICKED(IDC_BUTMANAGE, OnManage) ON_BN_CLICKED(IDC_BUTPAUSES, OnButPauses) ON_BN_CLICKED(IDC_BUTADDTASK, OnButAddTask) ON_MESSAGE(WM_REFRESHDAYLABEL, OnRefreshDayLabel) //}}AFX_MSG_MAP END_MESSAGE_MAP() // //////////////////////////////////////////////////////////////////////////// // CDlgMain::CDlgMain(CWnd* pParent ) : CDialog(CDlgMain::IDD, pParent) { //{{AFX_DATA_INIT(CDlgMain) //}}AFX_DATA_INIT } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgMain) DDX_Control(pDX, IDC_BUTADDTASK, m_ButAddTask); DDX_Control(pDX, IDC_TASKS, m_Tasks); DDX_Control(pDX, IDC_TASK_UNTIL, m_TaskUntil); DDX_Control(pDX, IDC_TASK_FROM, m_TaskFrom); DDX_Control(pDX, IDC_PAUSE_UNTIL, m_PauseUntil); DDX_Control(pDX, IDC_PAUSE_FROM, m_PauseFrom); DDX_Control(pDX, IDC_DAY_LABEL, m_DayLabel); DDX_Control(pDX, IDC_DAY_UNTIL, m_DayUntil); DDX_Control(pDX, IDC_DAY_FROM, m_DayFrom); DDX_Control(pDX, IDC_BUTPAUSES, m_ButPauses); DDX_Control(pDX, IDC_BUTMANAGE, m_ButManage); DDX_Control(pDX, IDC_BUTTASKS, m_ButTasks); DDX_Control(pDX, IDC_BUTSTARTFINISH, m_ButStartFinish); DDX_Control(pDX, IDC_BUTPAUSERESUME, m_ButPauseResume); //}}AFX_DATA_MAP } // //////////////////////////////////////////////////////////////////////////// // BOOL CDlgMain::OnInitDialog() { CDialog::OnInitDialog(); CWorkDay* pDay = CWorkDay::getCurrentDay(); if (pDay == NULL) { // DAY m_ButStartFinish.EnableWindow(TRUE); m_ButStartFinish.SetWindowText("Start Day"); m_DayFrom.EnableWindow(TRUE); m_DayUntil.EnableWindow(FALSE); Time2CEdit(GetNowTime(), m_DayFrom); // PAUSES m_ButPauseResume.EnableWindow(FALSE); m_ButPauseResume.SetWindowText("Pause"); m_ButPauses.EnableWindow(FALSE); m_PauseFrom.EnableWindow(FALSE); m_PauseUntil.EnableWindow(FALSE); // TASKS m_ButTasks.EnableWindow(FALSE); m_ButAddTask.EnableWindow(FALSE); m_Tasks.EnableWindow(FALSE); m_TaskFrom.EnableWindow(FALSE); m_TaskUntil.EnableWindow(FALSE); } else { // DAY m_ButStartFinish.EnableWindow(TRUE); m_ButStartFinish.SetWindowText("Finish Day"); m_DayFrom.EnableWindow(FALSE); Time2CEdit(pDay->getRec()->m_StartTime, m_DayFrom); m_DayUntil.EnableWindow(TRUE); Time2CEdit(GetNowTime(), m_DayUntil); // PAUSES m_ButPauseResume.EnableWindow(TRUE); m_ButPauses.EnableWindow(TRUE); if (pDay->isPaused()) { m_ButPauseResume.SetWindowText("Resume"); m_PauseFrom.EnableWindow(FALSE); Time2CEdit(pDay->getPausedTime(), m_PauseFrom); m_PauseUntil.EnableWindow(TRUE); Time2CEdit(GetNowTime(), m_PauseUntil); } else { m_ButPauseResume.SetWindowText("Pause"); m_PauseFrom.EnableWindow(TRUE); Time2CEdit(GetNowTime(), m_PauseFrom); m_PauseUntil.EnableWindow(TRUE); m_PauseUntil.SetWindowText(""); } // TASKS m_ButTasks.EnableWindow(TRUE); m_ButAddTask.EnableWindow(FALSE); m_Tasks.EnableWindow(FALSE); m_TaskFrom.EnableWindow(FALSE); m_TaskUntil.EnableWindow(FALSE); } refreshDayLabel(); UpdateData(FALSE); SetForegroundWindow(); return FALSE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::refreshDayLabel() { if (CWorkDay::getCurrentDay() == NULL) { m_DayLabel.SetWindowText("Day not started yet."); } else { CString sTemp; sTemp.Format("%s, so far: %s.", GetDisplayDate(CWorkDay::getCurrentDay()->getRec()->m_StartTime), GetDisplayTime(CWorkDay::getCurrentDay()->getTotalWorkTime())); m_DayLabel.SetWindowText(sTemp); } } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::OnStartFinish() { if ( CWorkDay::getCurrentDay() == NULL ) { COleDateTime startDate = CEditTime2Date(m_DayFrom, GetNowTime()); if ( CWorkDay::startDay(startDate) == NULL ) return; } else { COleDateTime finishDate = CEditTime2AdjustedDate(m_DayUntil, CWorkDay::getCurrentDay()->getRec()->m_StartTime); CDlgTasks dlg(CWorkDay::getCurrentDay(), &finishDate); LockWindow(&dlg, true); int ret = dlg.DoModal(); LockWindow(&dlg, false); if (ret != IDOK) return; CWorkDay::endDay( Time2AdjustedDate(dlg.m_sFinished, CWorkDay::getCurrentDay()->getRec()->m_StartTime) ); } EndDialog(IDOK); } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::OnPauseResume() { if (CWorkDay::getCurrentDay() == NULL) { AfxMessageBox("ERROR, day not started"); return; } if ( CWorkDay::getCurrentDay()->isPaused() ) { CWorkDay::getCurrentDay()->pauseOrResume( CEditTime2AdjustedDate(m_PauseUntil, CWorkDay::getCurrentDay()->getRec()->m_StartTime) ); } else { CString sPauseEnd; m_PauseUntil.GetWindowText(sPauseEnd); if (sPauseEnd.IsEmpty()) { CWorkDay::getCurrentDay()->pauseOrResume( CEditTime2AdjustedDate(m_PauseFrom, CWorkDay::getCurrentDay()->getRec()->m_StartTime) ); } else { COleDateTime dtFrom = CEditTime2AdjustedDate(m_PauseFrom, CWorkDay::getCurrentDay()->getRec()->m_StartTime); COleDateTime dtTo = CEditTime2AdjustedDate(m_PauseUntil, CWorkDay::getCurrentDay()->getRec()->m_StartTime); long sheeterID = CWorkDay::getCurrentDay()->getRec()->m_ID; CRecPauses::AddPause(sheeterID, dtFrom, dtTo); // Notify app that pauses may have changed. // theApp.GetMainWnd()->PostMessage(WM_PAUSESCHANGED, 0, LPARAM(sheeterID)); AfxGetMainWnd()->PostMessage(WM_PAUSESCHANGED, 0, LPARAM(sheeterID)); } } EndDialog(IDOK); } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::OnTasks() { CDlgTasks dlg(CWorkDay::getCurrentDay(), NULL); LockWindow(&dlg, true); dlg.DoModal(); LockWindow(&dlg, false); } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::OnManage() { AfxGetMainWnd()->PostMessage(WM_DLG_MANAGE); EndDialog(IDOK); } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::OnButPauses() { if (CWorkDay::getCurrentDay() == NULL) return; CDlgPauses dlg(CWorkDay::getCurrentDay()->getRec()->m_ID, this); dlg.DoModal(); //refreshDayLabel(); PostMessage(WM_REFRESHDAYLABEL); } // //////////////////////////////////////////////////////////////////////////// // void CDlgMain::OnButAddTask() { } // //////////////////////////////////////////////////////////////////////////// // LRESULT CDlgMain::OnRefreshDayLabel( WPARAM wParam, LPARAM lParam ) { refreshDayLabel(); return 0; }
[ [ [ 1, 287 ] ] ]
d670ad384524feb061dbd42369e9f669a59823f0
8a88075abf60e213a490840bebee97df01b8827a
/implementation/geometry/include/geometry/geometric_object_concept.hpp
04f8498d8e3bbf99ddda77d171d32c49429b7eac
[]
no_license
DavidGeorge528/minigeolib
e078f1bbc874c09584ae48e1c269f5f90789ebfb
58233609203953acf1c0346cd48950d2212b8922
refs/heads/master
2020-05-20T09:36:53.921996
2009-04-23T16:25:30
2009-04-23T16:25:30
33,925,133
0
1
null
null
null
null
UTF-8
C++
false
false
881
hpp
#ifndef GEOMETRY_GEOMETRIC_OBJECT_CONCEPT_HPP #define GEOMETRY_GEOMETRIC_OBJECT_CONCEPT_HPP #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> namespace geometry { // DOC template< typename GO, typename Tag> class GeometricObject { public: // Require coordinate system alias. typedef typename GO::coord_system coord_system; // Require unit type alias typedef typename GO::unit_type unit_type; // Require unit traits type alias typedef typename GO::unit_traits_type unit_traits_type; typedef typename GO::tag tag; // Require unit type traits uses unit type BOOST_STATIC_ASSERT( (boost::is_same< unit_type, typename unit_traits_type::unit_type>::value)); // Require expected tag BOOST_STATIC_ASSERT( (boost::is_same< tag, Tag>::value)); }; } // geometry #endif // GEOMETRY_GEOMETRIC_OBJECT_CONCEPT_HPP
[ "cpitis@834bb202-e8be-11dd-9d8c-a70aa0a93a20" ]
[ [ [ 1, 35 ] ] ]
8156ca5c265081eec0c0eeb0b3bdafb5de20b574
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Application/SysCAD/RenamePageDlg.cpp
c0993c8cc3432db218964cdf205733bf7f7471c1
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
// RenamePageDlg.cpp : implementation file // #include "stdafx.h" #include "SysCAD.h" #include "RenamePageDlg.h" // CRenamePageDlg dialog IMPLEMENT_DYNAMIC(CRenamePageDlg, CDialog) CRenamePageDlg::CRenamePageDlg(LPCTSTR OldName, CWnd* pParent /*=NULL*/) : CDialog(CRenamePageDlg::IDD, pParent) , m_OldName(OldName) , m_NewName(OldName) { } CRenamePageDlg::~CRenamePageDlg() { } void CRenamePageDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_OLDNAME2, m_NewName); DDX_Text(pDX, IDC_OLDNAME, m_OldName); } BEGIN_MESSAGE_MAP(CRenamePageDlg, CDialog) END_MESSAGE_MAP() // CRenamePageDlg message handlers
[ [ [ 1, 37 ] ] ]
e5d559410ee3fd875a44ccd9287145135b6d3272
0b0c77ef944917bffa2b4902b01bf2e8e8fd0b56
/SoftwareSerial/SoftwareSerial.h
5754b7edf4654f856b5ee6ff204c61b3b2ca9593
[]
no_license
cyberreefguru/legacy_arduino
d24f6db5bf4b2b71d74a16e45d2525cb4d90a43a
663800deb6f3a4eb5cf043f5051d2bcfa75ae2d7
refs/heads/master
2020-04-11T02:36:36.003147
2011-07-30T22:43:13
2011-07-30T22:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,718
h
/* SoftwareSerial.h (formerly NewSoftSerial.h) - Multi-instance software serial library for Arduino/Wiring -- Interrupt-driven receive and other improvements by ladyada (http://ladyada.net) -- Tuning, circular buffer, derivation from class Print/Stream, multi-instance support, porting to 8MHz processors, various optimizations, PROGMEM delay tables, inverse logic and direct port writing by Mikal Hart (http://www.arduiniana.org) -- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com) -- 20MHz processor support by Garrett Mace (http://www.macetech.com) -- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA The latest version of this library can always be found at http://arduiniana.org. */ #ifndef SoftwareSerial_h #define SoftwareSerial_h #include <inttypes.h> #include <Stream.h> /****************************************************************************** * Definitions ******************************************************************************/ #define _SS_MAX_RX_BUFF 64 // RX buffer size #define _SS_VERSION 11 // software version of this library #ifndef GCC_VERSION #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif class SoftwareSerial : public Stream { private: // per object data uint8_t _receivePin; uint8_t _receiveBitMask; volatile uint8_t *_receivePortRegister; uint8_t _transmitBitMask; volatile uint8_t *_transmitPortRegister; uint16_t _rx_delay_centering; uint16_t _rx_delay_intrabit; uint16_t _rx_delay_stopbit; uint16_t _tx_delay; uint16_t _buffer_overflow:1; uint16_t _inverse_logic:1; // static data static char _receive_buffer[_SS_MAX_RX_BUFF]; static volatile uint8_t _receive_buffer_tail; static volatile uint8_t _receive_buffer_head; static SoftwareSerial *active_object; // private methods void recv(); uint8_t rx_pin_read(); void tx_pin_write(uint8_t pin_state); void setTX(uint8_t transmitPin); void setRX(uint8_t receivePin); // private static method for timing static inline void tunedDelay(uint16_t delay); public: // public methods SoftwareSerial(); SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false); ~SoftwareSerial(); void begin(long speed); bool listen(); void end(); bool is_listening() { return this == active_object; } bool overflow() { bool ret = _buffer_overflow; _buffer_overflow = false; return ret; } static int library_version() { return _SS_VERSION; } static void enable_timer0(bool enable); int peek(); virtual void write(uint8_t byte); virtual int read(); virtual int available(); virtual void flush(); // public only for easy access by interrupt handlers static inline void handle_interrupt(); }; // Arduino 0012 workaround #undef int #undef char #undef long #undef byte #undef float #undef abs #undef round #endif
[ [ [ 1, 114 ] ] ]
8cf523babe7d69605cfefff88c8aa0351725bd61
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/databaseserver/CampusDBCtrl.cpp
8f67669fa56b61872ebf687b38e07ab2c5407790
[]
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
UTF-8
C++
false
false
12,165
cpp
// CampusDBCtrl.cpp: implementation of the CCampusDBCtrl class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CampusDBCtrl.h" #if __VER >= 15 // __CAMPUS #include "dptrans.h" extern APP_INFO g_appInfo; #include "DPCoreSrvr.h" extern CDPCoreSrvr g_dpCoreSrvr; ////////////////////////////////////////////////////////////////////// // CCampusDBCtrl Construction/Destruction ////////////////////////////////////////////////////////////////////// CCampusDBCtrl::CCampusDBCtrl() :m_pLogQuery( NULL ) { } CCampusDBCtrl::~CCampusDBCtrl() { SAFE_DELETE( m_pLogQuery ); } void CCampusDBCtrl::Handler( LPDB_OVERLAPPED_PLUS pov, DWORD dwCompletionKey ) { CAr ar( pov->lpBuf, pov->uBufSize ); switch( pov->nQueryMode ) { case CAMPUS_LOAD: CreateLogQuery(); LoadAllCampus(); break; case CAMPUS_SEND: SendAllCampus( dwCompletionKey ); break; case CAMPUS_ADD_MEMBER: AddCampusMember( ar ); break; case CAMPUS_REMOVE_MEMBER: RemoveCampusMember( ar ); break; case CAMPUS_UPDATE_POINT: UpdateCampusPoint( ar ); break; } } void CCampusDBCtrl::CreateLogQuery() { m_pLogQuery = new CQuery; const char* pass = CDbManager::GetInstance().DB_ADMIN_PASS_LOG; if( FALSE == m_pLogQuery->Connect( 3, DSN_NAME_LOG, DB_ADMIN_ID_LOG, pass ) ) { ::AfxMessageBox( "Can't connect db: CCampusDBCtrl.CreateLogQuery" ); SAFE_DELETE( m_pLogQuery ); ASSERT( 0 ); } } void CCampusDBCtrl::LoadAllCampus() { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_Campus_Load @serverindex = '%02d'", g_appInfo.dwSys ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } while( pQuery->Fetch() ) { CCampus* pCampus = new CCampus; pCampus->SetCampusId( pQuery->GetInt( "idCampus" ) ); CCampusHelper::GetInstance()->AddCampus( pCampus ); } sprintf( szQuery, "usp_CampusMember_Load @serverindex = '%02d'", g_appInfo.dwSys ); if( pQuery->Exec( szQuery ) == FALSE ) { CCampusHelper::GetInstance()->Clear(); WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } u_long idCampus; while( pQuery->Fetch() ) { CCampusMember* pMember = new CCampusMember; pMember->SetPlayerId( pQuery->GetInt( "m_idPlayer" ) ); pMember->SetLevel( pQuery->GetInt( "nMemberLv" ) ); idCampus = pQuery->GetInt( "idCampus" ); CCampus* pCampus = CCampusHelper::GetInstance()->GetCampus( idCampus ); if( pCampus ) { pCampus->AddMember( pMember ); if( pMember->GetLevel() == CAMPUS_MASTER ) pCampus->SetMaster( pMember->GetPlayerId() ); CCampusHelper::GetInstance()->AddPlayerId2CampusId( pMember->GetPlayerId(), idCampus ); } else { WriteLog( "LoadAllCampus(): Player's campus not found - %d, %d", pMember->GetPlayerId(), idCampus ); SAFE_DELETE( pMember ); } } } void CCampusDBCtrl::AddCampusMember( CAr & ar ) { u_long idMaster, idPupil; int nMasterPoint, nPupilPoint; ar >> idMaster >> nMasterPoint >> idPupil >> nPupilPoint; if( nMasterPoint < 0 || nPupilPoint < 0 || CCampusHelper::GetInstance()->GetCampus( CCampusHelper::GetInstance()->GetCampusIdByPlayerId( idPupil ) ) ) return; CCampus* pCampus = CCampusHelper::GetInstance()->GetCampus( CCampusHelper::GetInstance()->GetCampusIdByPlayerId( idMaster ) ); if( pCampus ) { if( pCampus->GetPupilNum() >= CCampusHelper::GetInstance()->GetMaxPupilNum( nMasterPoint ) ) return; CCampusMember* pCM = new CCampusMember; pCM->SetLevel( CAMPUS_PUPIL ); pCM->SetPlayerId( idPupil ); if( pCampus->AddMember( pCM ) ) { if( CCampusHelper::GetInstance()->AddPlayerId2CampusId( idPupil, pCampus->GetCampusId() ) ) { UpdateCampusId( idPupil, pCampus->GetCampusId() ); InsertCampusMember( pCampus->GetCampusId(), idPupil, CAMPUS_PUPIL ); } else { Error( "AddPlayerId2CampusId() fail" ); pCampus->RemoveMember( pCM->GetPlayerId() ); SAFE_DELETE( pCM ); return; } } else { SAFE_DELETE( pCM ); return; } } else { pCampus = new CCampus; pCampus->SetMaster( idMaster ); u_long idCampus = CCampusHelper::GetInstance()->AddCampus( pCampus ); if( idCampus > 0 ) { CCampusMember* pMaster = new CCampusMember; CCampusMember* pPupil = new CCampusMember; pMaster->SetLevel( CAMPUS_MASTER ); pMaster->SetPlayerId( idMaster ); pPupil->SetLevel( CAMPUS_PUPIL ); pPupil->SetPlayerId( idPupil ); if( pCampus->AddMember( pMaster ) && pCampus->AddMember( pPupil ) && CCampusHelper::GetInstance()->AddPlayerId2CampusId( idMaster, idCampus ) && CCampusHelper::GetInstance()->AddPlayerId2CampusId( idPupil, idCampus ) ) { UpdateCampusId( idMaster, idCampus ); UpdateCampusId( idPupil, idCampus ); InsertCampus( idCampus ); InsertCampusMember( idCampus, idMaster, CAMPUS_MASTER ); InsertCampusMember( idCampus, idPupil, CAMPUS_PUPIL ); } else { Error( "AddMember failed!" ); SAFE_DELETE( pMaster ); SAFE_DELETE( pPupil ); CCampusHelper::GetInstance()->RemoveCampus( idCampus ); return; } } else { Error( "new campus failed! campus exist" ); SAFE_DELETE( pCampus ); return; } } LogUpdateCampusMember( pCampus->GetCampusId(), idMaster, idPupil, 'T' ); CDPTrans::GetInstance()->SendAddCampusMember( pCampus->GetCampusId(), idMaster, idPupil ); } void CCampusDBCtrl::RemoveCampusMember( CAr & ar ) { u_long idCampus, idPlayer; ar >> idCampus >> idPlayer; CCampus* pCampus = CCampusHelper::GetInstance()->GetCampus( idCampus ); if( pCampus && pCampus->IsMember( idPlayer ) ) { if( pCampus->IsMaster( idPlayer ) ) { vector<u_long> vecMember = pCampus->GetAllMemberPlayerId(); for( vector<u_long>::iterator it = vecMember.begin(); it != vecMember.end(); ++it ) { CCampusHelper::GetInstance()->RemovePlayerId2CampusId( *it ); UpdateCampusId( *it, 0 ); if( *it != idPlayer ) { DeleteCampusMember( *it, CAMPUS_PUPIL ); LogUpdateCampusMember( idCampus, idPlayer, *it, 'F' ); } } CCampusHelper::GetInstance()->RemoveCampus( idCampus ); DeleteCampus( idCampus ); } else { CCampusHelper::GetInstance()->RemovePlayerId2CampusId( idPlayer ); pCampus->RemoveMember( idPlayer ); UpdateCampusId( idPlayer, 0 ); DeleteCampusMember( idPlayer, CAMPUS_PUPIL ); LogUpdateCampusMember( idCampus, pCampus->GetMaster(), idPlayer, 'F' ); if( pCampus->GetMemberSize() < 2 ) { CCampusHelper::GetInstance()->RemovePlayerId2CampusId( pCampus->GetMaster() ); UpdateCampusId( pCampus->GetMaster(), 0 ); CCampusHelper::GetInstance()->RemoveCampus( idCampus ); DeleteCampus( idCampus ); } } CDPTrans::GetInstance()->SendRemoveCampusMember( idCampus, idPlayer ); } else Error( "RemoveCampusMember fail" ); } void CCampusDBCtrl::UpdateCampusPoint( CAr & ar ) { u_long idPlayer; int nCampusPoint; BOOL bAdd; char chState; ar >> idPlayer >> nCampusPoint >> bAdd >> chState; int nPrevPoint, nCurrPoint; nPrevPoint = nCurrPoint = 0; if( bAdd ) { nCurrPoint = UpdateCampusPoint( idPlayer, nCampusPoint ); nPrevPoint = nCurrPoint - nCampusPoint; } else { nCurrPoint = UpdateCampusPoint( idPlayer, -(nCampusPoint) ); nPrevPoint = nCurrPoint + nCampusPoint; } LogUpdateCampusPoint( idPlayer, nPrevPoint, nCurrPoint, chState ); CDPTrans::GetInstance()->SendUpdateCampusPoint( idPlayer, nCurrPoint ); } void CCampusDBCtrl::SendAllCampus( DPID dpId ) { if( !CCampusHelper::GetInstance()->IsEmpty() ) CDPTrans::GetInstance()->SendAllCampus( dpId ); } void CCampusDBCtrl::InsertCampus( u_long idCampus ) { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_Campus_Insert @idCampus = %d, @serverindex = '%02d'", idCampus, g_appInfo.dwSys ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } void CCampusDBCtrl::DeleteCampus( u_long idCampus ) { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_Campus_Delete @idCampus = %d, @serverindex = '%02d'", idCampus, g_appInfo.dwSys ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } void CCampusDBCtrl::InsertCampusMember( u_long idCampus, u_long idPlayer, int nMemberLv ) { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_CampusMember_Insert @idCampus = %d, @serverindex = '%02d', @m_idPlayer = '%07d', @nMemberLv = %d", idCampus, g_appInfo.dwSys, idPlayer, nMemberLv ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } void CCampusDBCtrl::DeleteCampusMember( u_long idPlayer, int nMemberLv ) { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_CampusMember_Delete @serverindex = '%02d', @m_idPlayer = '%07d', @nMemberLv = %d", g_appInfo.dwSys, idPlayer, nMemberLv ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } int CCampusDBCtrl::UpdateCampusPoint( u_long idPlayer, int nCampusPoint ) { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; g_DbManager.DBQryCharacter( szQuery, "U5", idPlayer, g_appInfo.dwSys, '\0', "", nCampusPoint ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return INT_MAX; } int nTotalPoint = INT_MAX; if( pQuery->Fetch() ) nTotalPoint = pQuery->GetInt( "m_nCampusPoint" ); return nTotalPoint; } void CCampusDBCtrl::UpdateCampusId( u_long idPlayer, u_long idCampus ) { CQuery* pQuery = GetQueryObject(); char szQuery[QUERY_SIZE] = {0, }; g_DbManager.DBQryCharacter( szQuery, "U6", idPlayer, g_appInfo.dwSys, '\0', "", idCampus ); if( pQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } void CCampusDBCtrl::LogUpdateCampusMember( u_long idCampus, u_long idMaster, u_long idPupil, char chState ) { char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_CampusLog_Insert @m_idMaster = '%07d', @serverindex = '%02d', @idCampus = %d, @m_idPupil = '%07d', @chState = '%c'", idMaster, g_appInfo.dwSys, idCampus, idPupil, chState ); if( m_pLogQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } void CCampusDBCtrl::LogUpdateCampusPoint( u_long idPlayer, int nPrevPoint, int nCurrPoint, char chState ) { char szQuery[QUERY_SIZE] = {0, }; sprintf( szQuery, "usp_CampusPointLog_Insert @m_idPlayer = '%07d', @serverindex = '%02d', @chState = '%c', @nPrevPoint = %0d, @nCurrPoint = %d", idPlayer, g_appInfo.dwSys, chState, nPrevPoint, nCurrPoint ); if( m_pLogQuery->Exec( szQuery ) == FALSE ) { WriteLog( "%s, %d\t%s", __FILE__, __LINE__, szQuery ); return; } } ////////////////////////////////////////////////////////////////////// // CCampusHelper Construction/Destruction ////////////////////////////////////////////////////////////////////// CCampusHelper::CCampusHelper() { m_pCampusMng = new CCampusMng; if( !m_CampusDBCtrl.CreateDbHandler() ) Error( "CCampusHelper - m_CampusDBCtrl.CreateDbHandler()" ); } CCampusHelper::~CCampusHelper() { SAFE_DELETE( m_pCampusMng ); m_CampusDBCtrl.CloseDbHandler(); } CCampusHelper* CCampusHelper::GetInstance() { static CCampusHelper sCH; return & sCH; } int CCampusHelper::GetMaxPupilNum( int nCampusPoint ) { if( nCampusPoint >= 0 && nCampusPoint < MIN_LV2_POINT ) return 1; else if( nCampusPoint >= MIN_LV2_POINT && nCampusPoint < MIN_LV3_POINT ) return 2; else if( nCampusPoint >= MIN_LV3_POINT ) return 3; return 0; } #endif // __CAMPUS
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 401 ] ] ]
8b76a210651fe22c4e2fb31fc0d07793714f9b2a
8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab
/src-ginga-editing/ncl30-generator-cpp/src/CompoundActionGenerator.cpp
9919f6d9d21c47640304f6f988a0059eae16c105
[]
no_license
BrunoSSts/ginga-wac
7436a9815427a74032c9d58028394ccaac45cbf9
ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c
refs/heads/master
2020-05-20T22:21:33.645904
2011-10-17T12:34:32
2011-10-17T12:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,380
cpp
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file CompoundActionGenerator.cpp * @author Caio Viel * @date 29-01-10 */ #include "../include/CompoundActionGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generate { string CompoundActionGenerator::generateCode() { string ret = "<compoundAction operator=\""; short op = this->getOperator(); if (op == OP_PAR) { ret += "par\" "; } else if (op == OP_SEQ) { ret += "seq\" "; } else if (op == OP_EXCL) { ret += "excl\" "; } string delay = this->getDelay(); if (delay != "0") { ret += "delay=\"" + delay + "\" "; } ret += ">\n"; vector<Action*>* actions = this->getActions(); vector<Action*>::iterator it; it = actions->begin(); while (it != actions->end()) { Action* action = *it; if (action->instanceOf("SimpleAction")) { ret+= static_cast<SimpleActionGenerator*>(action)->generateCode() + "\n"; } else if (action->instanceOf("CompoundAction")) { ret+= static_cast<CompoundActionGenerator*>(action)->generateCode() + "\n"; } it++; } ret += "</compoundAction>\n"; return ret; } } } } } }
[ [ [ 1, 103 ] ] ]
3f9d9e809e9e69f13719ad88515c7bc102647c2a
3cad09dde08a7f9f4fe4acbcb2ffd4643a642957
/opencv/win/tests/cv/src/aimgwarp.cpp
c4a8747b233a884f8a11aecc02e01d546984533b
[]
no_license
gmarcotte/cos436-eye-tracker
420ad9c37cf1819a238c0379662dee71f6fd9b0f
05d0b010bae8dcf06add2ae93534851668d4eff4
refs/heads/master
2021-01-23T13:47:38.533817
2009-01-15T02:40:43
2009-01-15T02:40:43
32,219,880
0
0
null
null
null
null
UTF-8
C++
false
false
65,010
cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "cvtest.h" static const int imgwarp_depths[] = { CV_8U, CV_16U, CV_32F, -1 }; static const int imgwarp_channels[] = { 1, 3, 4, -1 }; static const CvSize imgwarp_sizes[] = {{320, 240}, {1024,768}, {-1,-1}}; static const double imgwarp_resize_coeffs[] = { 0.5, 0.333, 2, 2.9 }; static const char* imgwarp_resize_methods[] = { "nearest", "linear", "cubic", "area", 0 }; static const char* imgwarp_resize_param_names[] = { "method", "coeff", "size", "channels", "depth", 0 }; static const double imgwarp_affine_rotate_scale[][4] = { {0.5,0.5,30.,1.4}, {0.5,0.5,-130,0.4}, {-1,-1,-1,-1} }; static const char* imgwarp_affine_param_names[] = { "rotate_scale", "size", "channels", "depth", 0 }; static const double imgwarp_perspective_shift_vtx[][8] = { {0.03,0.01,0.04,0.02,0.01,0.01,0.01,0.02}, {-1} }; static const char* imgwarp_perspective_param_names[] = { "shift_vtx", "size", "channels", "depth", 0 }; class CV_ImgWarpBaseTestImpl : public CvArrTest { public: CV_ImgWarpBaseTestImpl( const char* test_name, const char* test_funcs, bool warp_matrix ); protected: int read_params( CvFileStorage* fs ); int prepare_test_case( int test_case_idx ); void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); void fill_array( int test_case_idx, int i, int j, CvMat* arr ); int interpolation; int max_interpolation; double spatial_scale_zoom, spatial_scale_decimate; }; CV_ImgWarpBaseTestImpl::CV_ImgWarpBaseTestImpl( const char* test_name, const char* test_funcs, bool warp_matrix ) : CvArrTest( test_name, test_funcs, "" ) { test_array[INPUT].push(NULL); if( warp_matrix ) test_array[INPUT].push(NULL); test_array[INPUT_OUTPUT].push(NULL); test_array[REF_INPUT_OUTPUT].push(NULL); max_interpolation = 4; interpolation = 0; element_wise_relative_error = false; spatial_scale_zoom = 0.01; spatial_scale_decimate = 0.005; size_list = whole_size_list = imgwarp_sizes; depth_list = imgwarp_depths; cn_list = imgwarp_channels; default_timing_param_names = 0; } int CV_ImgWarpBaseTestImpl::read_params( CvFileStorage* fs ) { int code = CvArrTest::read_params( fs ); return code; } void CV_ImgWarpBaseTestImpl::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) { CvArrTest::get_minmax_bounds( i, j, type, low, high ); if( CV_MAT_DEPTH(type) == CV_32F ) { *low = cvScalarAll(-10.); *high = cvScalarAll(10); } } void CV_ImgWarpBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CvRNG* rng = ts->get_rng(); int depth = cvTsRandInt(rng) % 3; int cn = cvTsRandInt(rng) % 3 + 1; CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : CV_32F; cn += cn == 2; types[INPUT][0] = types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(depth, cn); if( test_array[INPUT].size() > 1 ) types[INPUT][1] = cvTsRandInt(rng) & 1 ? CV_32FC1 : CV_64FC1; interpolation = cvTsRandInt(rng) % max_interpolation; } void CV_ImgWarpBaseTestImpl::fill_array( int test_case_idx, int i, int j, CvMat* arr ) { if( i != INPUT || j != 0 ) CvArrTest::fill_array( test_case_idx, i, j, arr ); } int CV_ImgWarpBaseTestImpl::prepare_test_case( int test_case_idx ) { int code = CvArrTest::prepare_test_case( test_case_idx ); CvMat* img = &test_mat[INPUT][0]; int i, j, cols = img->cols; int type = CV_MAT_TYPE(img->type), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); double scale = depth == CV_16U ? 1000. : 255.*0.5; double space_scale = spatial_scale_decimate; float* buffer; if( code <= 0 ) return code; if( test_mat[INPUT_OUTPUT][0].cols >= img->cols && test_mat[INPUT_OUTPUT][0].rows >= img->rows ) space_scale = spatial_scale_zoom; buffer = (float*)cvAlloc( img->cols*cn*sizeof(buffer[0]) ); for( i = 0; i < img->rows; i++ ) { uchar* ptr = img->data.ptr + i*img->step; switch( cn ) { case 1: for( j = 0; j < cols; j++ ) buffer[j] = (float)((sin((i+1)*space_scale)*sin((j+1)*space_scale)+1.)*scale); break; case 2: for( j = 0; j < cols; j++ ) { buffer[j*2] = (float)((sin((i+1)*space_scale)+1.)*scale); buffer[j*2+1] = (float)((sin((i+j)*space_scale)+1.)*scale); } break; case 3: for( j = 0; j < cols; j++ ) { buffer[j*3] = (float)((sin((i+1)*space_scale)+1.)*scale); buffer[j*3+1] = (float)((sin(j*space_scale)+1.)*scale); buffer[j*3+2] = (float)((sin((i+j)*space_scale)+1.)*scale); } break; case 4: for( j = 0; j < cols; j++ ) { buffer[j*4] = (float)((sin((i+1)*space_scale)+1.)*scale); buffer[j*4+1] = (float)((sin(j*space_scale)+1.)*scale); buffer[j*4+2] = (float)((sin((i+j)*space_scale)+1.)*scale); buffer[j*4+3] = (float)((sin((i-j)*space_scale)+1.)*scale); } break; default: assert(0); } switch( depth ) { case CV_8U: for( j = 0; j < cols*cn; j++ ) ptr[j] = (uchar)cvRound(buffer[j]); break; case CV_16U: for( j = 0; j < cols*cn; j++ ) ((ushort*)ptr)[j] = (ushort)cvRound(buffer[j]); break; case CV_32F: for( j = 0; j < cols*cn; j++ ) ((float*)ptr)[j] = (float)buffer[j]; break; default: assert(0); } } cvFree( &buffer ); return code; } CV_ImgWarpBaseTestImpl imgwarp_base( "warp", "", false ); class CV_ImgWarpBaseTest : public CV_ImgWarpBaseTestImpl { public: CV_ImgWarpBaseTest( const char* test_name, const char* test_funcs, bool warp_matrix ); }; CV_ImgWarpBaseTest::CV_ImgWarpBaseTest( const char* test_name, const char* test_funcs, bool warp_matrix ) : CV_ImgWarpBaseTestImpl( test_name, test_funcs, warp_matrix ) { size_list = whole_size_list = 0; depth_list = 0; cn_list = 0; } ///////////////////////// class CV_ResizeTest : public CV_ImgWarpBaseTest { public: CV_ResizeTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_ResizeTest::CV_ResizeTest() : CV_ImgWarpBaseTest( "warp-resize", "cvResize", false ) { default_timing_param_names = imgwarp_resize_param_names; } int CV_ResizeTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { start_write_param( fs ); write_real_list( fs, "coeff", imgwarp_resize_coeffs, CV_DIM(imgwarp_resize_coeffs) ); write_string_list( fs, "method", imgwarp_resize_methods ); } return code; } void CV_ResizeTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CvRNG* rng = ts->get_rng(); CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); CvSize sz; sz.width = (cvTsRandInt(rng) % sizes[INPUT][0].width) + 1; sz.height = (cvTsRandInt(rng) % sizes[INPUT][0].height) + 1; if( cvTsRandInt(rng) & 1 ) { int xfactor = cvTsRandInt(rng) % 10 + 1; int yfactor = cvTsRandInt(rng) % 10 + 1; if( cvTsRandInt(rng) & 1 ) yfactor = xfactor; sz.width = sizes[INPUT][0].width / xfactor; sz.width = MAX(sz.width,1); sz.height = sizes[INPUT][0].height / yfactor; sz.height = MAX(sz.height,1); sizes[INPUT][0].width = sz.width * xfactor; sizes[INPUT][0].height = sz.height * yfactor; } if( cvTsRandInt(rng) & 1 ) sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = sz; else { sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = sizes[INPUT][0]; sizes[INPUT][0] = sz; } } void CV_ResizeTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); const char* method_str = cvReadString( find_timing_param( "method" ), "linear" ); double coeff = cvReadReal( find_timing_param( "coeff" ), 1. ); CvSize size = sizes[INPUT][0]; size.width = cvRound(size.width*coeff); size.height = cvRound(size.height*coeff); sizes[INPUT_OUTPUT][0] = whole_sizes[INPUT_OUTPUT][0] = size; interpolation = strcmp( method_str, "nearest" ) == 0 ? CV_INTER_NN : strcmp( method_str, "linear" ) == 0 ? CV_INTER_LINEAR : strcmp( method_str, "cubic" ) == 0 ? CV_INTER_CUBIC : CV_INTER_AREA; } void CV_ResizeTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { sprintf( ptr, "coeff=%.3f,", cvReadReal( find_timing_param( "coeff" ), 1. ) ); ptr += strlen(ptr); sprintf( ptr, "method=%s,", cvReadString( find_timing_param( "method" ), "linear" ) ); ptr += strlen(ptr); params_left -= 2; CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_ResizeTest::run_func() { cvResize( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], interpolation ); } double CV_ResizeTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 1e-1; } void CV_ResizeTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* src = &test_mat[INPUT][0]; CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; int i, j, k; CvMat* x_idx = cvCreateMat( 1, dst->cols, CV_32SC1 ); CvMat* y_idx = cvCreateMat( 1, dst->rows, CV_32SC1 ); int* x_tab = x_idx->data.i; int elem_size = CV_ELEM_SIZE(src->type); int drows = dst->rows, dcols = dst->cols; if( interpolation == CV_INTER_NN ) { for( j = 0; j < dcols; j++ ) { int t = (j*src->cols*2 + MIN(src->cols,dcols) - 1)/(dcols*2); t -= t >= src->cols; x_idx->data.i[j] = t*elem_size; } for( j = 0; j < drows; j++ ) { int t = (j*src->rows*2 + MIN(src->rows,drows) - 1)/(drows*2); t -= t >= src->rows; y_idx->data.i[j] = t; } } else { double scale_x = (double)src->cols/dcols; double scale_y = (double)src->rows/drows; for( j = 0; j < dcols; j++ ) { double f = ((j+0.5)*scale_x - 0.5); i = cvRound(f); x_idx->data.i[j] = (i < 0 ? 0 : i >= src->cols ? src->cols - 1 : i)*elem_size; } for( j = 0; j < drows; j++ ) { double f = ((j+0.5)*scale_y - 0.5); i = cvRound(f); y_idx->data.i[j] = i < 0 ? 0 : i >= src->rows ? src->rows - 1 : i; } } for( i = 0; i < drows; i++ ) { uchar* dptr = dst->data.ptr + dst->step*i; const uchar* sptr0 = src->data.ptr + src->step*y_idx->data.i[i]; for( j = 0; j < dcols; j++, dptr += elem_size ) { const uchar* sptr = sptr0 + x_tab[j]; for( k = 0; k < elem_size; k++ ) dptr[k] = sptr[k]; } } cvReleaseMat( &x_idx ); cvReleaseMat( &y_idx ); } CV_ResizeTest warp_resize_test; ///////////////////////// void cvTsRemap( const CvMat* src, CvMat* dst, CvMat* dst0, const CvMat* mapx, const CvMat* mapy, int interpolation=CV_INTER_LINEAR ) { int x, y, k; int drows = dst->rows, dcols = dst->cols; int srows = src->rows, scols = src->cols; uchar* sptr0 = src->data.ptr; int depth = CV_MAT_DEPTH(src->type), cn = CV_MAT_CN(src->type); int elem_size = CV_ELEM_SIZE(src->type); int step = src->step / CV_ELEM_SIZE(depth); int delta; if( interpolation != CV_INTER_CUBIC ) { delta = 0; scols -= 1; srows -= 1; } else { delta = 1; scols = MAX(scols - 3, 0); srows = MAX(srows - 3, 0); } for( y = 0; y < drows; y++ ) { uchar* dptr = dst->data.ptr + dst->step*y; const float* mx = (const float*)(mapx->data.ptr + mapx->step*y); const float* my = (const float*)(mapy->data.ptr + mapy->step*y); for( x = 0; x < dcols; x++, dptr += elem_size ) { float xs = mx[x]; float ys = my[x]; int ixs = cvFloor(xs); int iys = cvFloor(ys); if( (unsigned)(ixs - delta) >= (unsigned)scols || (unsigned)(iys - delta) >= (unsigned)srows ) { for( k = 0; k < elem_size; k++ ) dptr[k] = 0; if( dst0 ) { uchar* dptr0 = dst0->data.ptr + dst0->step*y + x*elem_size; for( k = 0; k < elem_size; k++ ) dptr0[k] = 0; } continue; } xs -= ixs; ys -= iys; switch( depth ) { case CV_8U: { const uchar* sptr = sptr0 + iys*step + ixs*cn; for( k = 0; k < cn; k++ ) { float v00 = sptr[k]; float v01 = sptr[cn + k]; float v10 = sptr[step + k]; float v11 = sptr[step + cn + k]; v00 = v00 + xs*(v01 - v00); v10 = v10 + xs*(v11 - v10); v00 = v00 + ys*(v10 - v00); dptr[k] = (uchar)cvRound(v00); } } break; case CV_16U: { const ushort* sptr = (const ushort*)sptr0 + iys*step + ixs*cn; for( k = 0; k < cn; k++ ) { float v00 = sptr[k]; float v01 = sptr[cn + k]; float v10 = sptr[step + k]; float v11 = sptr[step + cn + k]; v00 = v00 + xs*(v01 - v00); v10 = v10 + xs*(v11 - v10); v00 = v00 + ys*(v10 - v00); ((ushort*)dptr)[k] = (ushort)cvRound(v00); } } break; case CV_32F: { const float* sptr = (const float*)sptr0 + iys*step + ixs*cn; for( k = 0; k < cn; k++ ) { float v00 = sptr[k]; float v01 = sptr[cn + k]; float v10 = sptr[step + k]; float v11 = sptr[step + cn + k]; v00 = v00 + xs*(v01 - v00); v10 = v10 + xs*(v11 - v10); v00 = v00 + ys*(v10 - v00); ((float*)dptr)[k] = (float)v00; } } break; default: assert(0); } } } } ///////////////////////// class CV_WarpAffineTest : public CV_ImgWarpBaseTest { public: CV_WarpAffineTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_WarpAffineTest::CV_WarpAffineTest() : CV_ImgWarpBaseTest( "warp-affine", "cvWarpAffine", true ) { //spatial_scale_zoom = spatial_scale_decimate; test_array[TEMP].push(NULL); test_array[TEMP].push(NULL); spatial_scale_decimate = spatial_scale_zoom; default_timing_param_names = imgwarp_affine_param_names; } int CV_WarpAffineTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "rotate_scale", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; imgwarp_affine_rotate_scale[i][0] >= 0; i++ ) { cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); cvWriteRawData( fs, imgwarp_affine_rotate_scale[i], 4, "d" ); cvEndWriteStruct(fs); } cvEndWriteStruct(fs); } return code; } void CV_WarpAffineTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); CvSize sz = sizes[INPUT][0]; // run for the second time to get output of a different size CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); sizes[INPUT][0] = sz; sizes[INPUT][1] = cvSize( 3, 2 ); sizes[TEMP][0] = sizes[TEMP][1] = sizes[INPUT_OUTPUT][0]; types[TEMP][0] = types[TEMP][1] = CV_32FC1; } void CV_WarpAffineTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); sizes[INPUT][1] = whole_sizes[INPUT][1] = cvSize(3,2); sizes[TEMP][0] = whole_sizes[TEMP][0] = sizes[TEMP][1] = whole_sizes[TEMP][1] = cvSize(0,0); types[INPUT][1] = CV_64FC1; interpolation = CV_INTER_LINEAR; } void CV_WarpAffineTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { double coeffs[4]; const CvFileNode* node = find_timing_param( "rotate_scale" ); assert( node && CV_NODE_IS_SEQ(node->tag) ); cvReadRawData( ts->get_file_storage(), node, coeffs, "4d" ); sprintf( ptr, "fx=%.2f,fy=%.2f,angle=%.1fdeg,scale=%.1f,", coeffs[0], coeffs[1], coeffs[2], coeffs[3] ); ptr += strlen(ptr); params_left -= 4; CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_WarpAffineTest::run_func() { cvWarpAffine( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &test_mat[INPUT][1], interpolation ); } double CV_WarpAffineTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; } int CV_WarpAffineTest::prepare_test_case( int test_case_idx ) { CvRNG* rng = ts->get_rng(); int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); const CvMat* src = &test_mat[INPUT][0]; const CvMat* dst = &test_mat[INPUT_OUTPUT][0]; CvMat* mat = &test_mat[INPUT][1]; CvPoint2D32f center; double scale, angle; if( code <= 0 ) return code; if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) { double buf[6]; CvMat tmp = cvMat( 2, 3, mat->type, buf ); center.x = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->cols); center.y = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->rows); angle = cvTsRandReal(rng)*360; scale = ((double)dst->rows/src->rows + (double)dst->cols/src->cols)*0.5; cv2DRotationMatrix( center, angle, scale, mat ); cvRandArr( rng, &tmp, CV_RAND_NORMAL, cvScalarAll(1.), cvScalarAll(0.01) ); cvMaxS( &tmp, 0.9, &tmp ); cvMinS( &tmp, 1.1, &tmp ); cvMul( &tmp, mat, mat, 1. ); } else { double coeffs[4]; const CvFileNode* node = find_timing_param( "rotate_scale" ); assert( node && CV_NODE_IS_SEQ(node->tag) ); cvReadRawData( ts->get_file_storage(), node, coeffs, "4d" ); center.x = (float)(coeffs[0]*src->cols); center.y = (float)(coeffs[1]*src->rows); angle = coeffs[2]; scale = coeffs[3]; cv2DRotationMatrix( center, angle, scale, mat ); } return code; } void CV_WarpAffineTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* src = &test_mat[INPUT][0]; CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; CvMat* mapx = &test_mat[TEMP][0]; CvMat* mapy = &test_mat[TEMP][1]; int x, y; double m[6], tm[6]; CvMat srcAb = cvMat(2, 3, CV_64FC1, tm ), A, b, invA, invAb, dstAb = cvMat( 2, 3, CV_64FC1, m ); //cvInvert( &tM, &M, CV_LU ); // [R|t] -> [R^-1 | -(R^-1)*t] cvTsConvert( &test_mat[INPUT][1], &srcAb ); cvGetCols( &srcAb, &A, 0, 2 ); cvGetCol( &srcAb, &b, 2 ); cvGetCols( &dstAb, &invA, 0, 2 ); cvGetCol( &dstAb, &invAb, 2 ); cvInvert( &A, &invA, CV_SVD ); cvGEMM( &invA, &b, -1, 0, 0, &invAb ); for( y = 0; y < dst->rows; y++ ) { float* mx = (float*)(mapx->data.ptr + y*mapx->step); float* my = (float*)(mapy->data.ptr + y*mapy->step); for( x = 0; x < dst->cols; x++ ) { mx[x] = (float)(x*m[0] + y*m[1] + m[2]); my[x] = (float)(x*m[3] + y*m[4] + m[5]); } } cvTsRemap( src, dst, dst0, mapx, mapy ); } CV_WarpAffineTest warp_affine_test; ///////////////////////// class CV_WarpPerspectiveTest : public CV_ImgWarpBaseTest { public: CV_WarpPerspectiveTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_WarpPerspectiveTest::CV_WarpPerspectiveTest() : CV_ImgWarpBaseTest( "warp-perspective", "cvWarpPerspective", true ) { //spatial_scale_zoom = spatial_scale_decimate; test_array[TEMP].push(NULL); test_array[TEMP].push(NULL); spatial_scale_decimate = spatial_scale_zoom; default_timing_param_names = imgwarp_perspective_param_names; } int CV_WarpPerspectiveTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "shift_vtx", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; imgwarp_perspective_shift_vtx[i][0] >= 0; i++ ) { cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); cvWriteRawData( fs, imgwarp_perspective_shift_vtx[i], 8, "d" ); cvEndWriteStruct(fs); } cvEndWriteStruct(fs); } return code; } void CV_WarpPerspectiveTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); CvSize sz = sizes[INPUT][0]; // run for the second time to get output of a different size CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); sizes[INPUT][0] = sz; sizes[INPUT][1] = cvSize( 3, 3 ); sizes[TEMP][0] = sizes[TEMP][1] = sizes[INPUT_OUTPUT][0]; types[TEMP][0] = types[TEMP][1] = CV_32FC1; } void CV_WarpPerspectiveTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); sizes[INPUT][1] = whole_sizes[INPUT][1] = cvSize(3,3); sizes[TEMP][0] = whole_sizes[TEMP][0] = sizes[TEMP][1] = whole_sizes[TEMP][1] = cvSize(0,0); types[INPUT][1] = CV_64FC1; interpolation = CV_INTER_LINEAR; } void CV_WarpPerspectiveTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_WarpPerspectiveTest::run_func() { cvWarpPerspective( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &test_mat[INPUT][1], interpolation ); } double CV_WarpPerspectiveTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; } int CV_WarpPerspectiveTest::prepare_test_case( int test_case_idx ) { CvRNG* rng = ts->get_rng(); int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); const CvMat* src = &test_mat[INPUT][0]; const CvMat* dst = &test_mat[INPUT_OUTPUT][0]; CvMat* mat = &test_mat[INPUT][1]; CvPoint2D32f s[4], d[4]; int i; if( code <= 0 ) return code; s[0] = cvPoint2D32f(0,0); d[0] = cvPoint2D32f(0,0); s[1] = cvPoint2D32f(src->cols-1,0); d[1] = cvPoint2D32f(dst->cols-1,0); s[2] = cvPoint2D32f(src->cols-1,src->rows-1); d[2] = cvPoint2D32f(dst->cols-1,dst->rows-1); s[3] = cvPoint2D32f(0,src->rows-1); d[3] = cvPoint2D32f(0,dst->rows-1); if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) { float buf[16]; CvMat tmp = cvMat( 1, 16, CV_32FC1, buf ); cvRandArr( rng, &tmp, CV_RAND_NORMAL, cvScalarAll(0.), cvScalarAll(0.1) ); for( i = 0; i < 4; i++ ) { s[i].x += buf[i*4]*src->cols/2; s[i].y += buf[i*4+1]*src->rows/2; d[i].x += buf[i*4+2]*dst->cols/2; d[i].y += buf[i*4+3]*dst->rows/2; } } else { double coeffs[8]; const CvFileNode* node = find_timing_param( "shift_vtx" ); assert( node && CV_NODE_IS_SEQ(node->tag) ); cvReadRawData( ts->get_file_storage(), node, coeffs, "8d" ); for( i = 0; i < 4; i++ ) { d[i].x += (float)(coeffs[i*2]*src->cols*(i == 0 || i == 3 ? 1 : -1)); d[i].y += (float)(coeffs[i*2+1]*src->rows*(i == 0 || i == 1 ? 1 : -1)); } } cvWarpPerspectiveQMatrix( s, d, mat ); return code; } void CV_WarpPerspectiveTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* src = &test_mat[INPUT][0]; CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; CvMat* mapx = &test_mat[TEMP][0]; CvMat* mapy = &test_mat[TEMP][1]; int x, y; double m[9], tm[9]; CvMat srcM = cvMat(3, 3, CV_64FC1, tm ), dstM = cvMat( 3, 3, CV_64FC1, m ); //cvInvert( &tM, &M, CV_LU ); // [R|t] -> [R^-1 | -(R^-1)*t] cvTsConvert( &test_mat[INPUT][1], &srcM ); cvInvert( &srcM, &dstM, CV_SVD ); for( y = 0; y < dst->rows; y++ ) { float* mx = (float*)(mapx->data.ptr + y*mapx->step); float* my = (float*)(mapy->data.ptr + y*mapy->step); for( x = 0; x < dst->cols; x++ ) { double xs = x*m[0] + y*m[1] + m[2]; double ys = x*m[3] + y*m[4] + m[5]; double ds = x*m[6] + y*m[7] + m[8]; ds = ds ? 1./ds : 0; xs *= ds; ys *= ds; mx[x] = (float)xs; my[x] = (float)ys; } } cvTsRemap( src, dst, dst0, mapx, mapy ); } CV_WarpPerspectiveTest warp_perspective_test; ///////////////////////// void cvTsInitUndistortMap( const CvMat* _a0, const CvMat* _k0, CvMat* mapx, CvMat* mapy ) { int u, v; double a[9], k[5]={0,0,0,0,0}; CvMat _a = cvMat(3, 3, CV_64F, a); CvMat _k = cvMat(_k0->rows,_k0->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(_k0->type)),k); double fx, fy, cx, cy, ifx, ify, cxn, cyn; cvTsConvert( _a0, &_a ); cvTsConvert( _k0, &_k ); fx = a[0]; fy = a[4]; cx = a[2]; cy = a[5]; ifx = 1./fx; ify = 1./fy; cxn = (mapy->cols - 1)*0.5; cyn = (mapy->rows - 1)*0.5; for( v = 0; v < mapy->rows; v++ ) { float* mx = (float*)(mapx->data.ptr + v*mapx->step); float* my = (float*)(mapy->data.ptr + v*mapy->step); for( u = 0; u < mapy->cols; u++ ) { double x = (u - cx)*ifx; double y = (v - cy)*ify; double x2 = x*x, y2 = y*y; double r2 = x2 + y2; double cdist = 1 + (k[0] + (k[1] + k[4]*r2)*r2)*r2; double x1 = x*cdist + k[2]*2*x*y + k[3]*(r2 + 2*x2); double y1 = y*cdist + k[3]*2*x*y + k[2]*(r2 + 2*y2); mx[u] = (float)(x1*fx + cxn); my[u] = (float)(y1*fy + cyn); } } } static double remap_undistort_params[] = { 0.5, 0.5, 0.5, 0.5, 0.01, -0.01, 0.001, -0.001 }; class CV_RemapTest : public CV_ImgWarpBaseTest { public: CV_RemapTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); void fill_array( int test_case_idx, int i, int j, CvMat* arr ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_RemapTest::CV_RemapTest() : CV_ImgWarpBaseTest( "warp-remap", "cvRemap", false ) { //spatial_scale_zoom = spatial_scale_decimate; test_array[INPUT].push(NULL); test_array[INPUT].push(NULL); spatial_scale_decimate = spatial_scale_zoom; //default_timing_param_names = imgwarp_perspective_param_names; support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; default_timing_param_names = 0; } int CV_RemapTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "params", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; i < 8; i++ ) cvWriteReal( fs, 0, remap_undistort_params[i] ); cvEndWriteStruct(fs); } return code; } void CV_RemapTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); types[INPUT][1] = types[INPUT][2] = CV_32FC1; interpolation = CV_INTER_LINEAR; } void CV_RemapTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) { if( i != INPUT ) CV_ImgWarpBaseTestImpl::fill_array( test_case_idx, i, j, arr ); } void CV_RemapTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); types[INPUT][1] = types[INPUT][2] = CV_32FC1; interpolation = CV_INTER_LINEAR; } void CV_RemapTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_RemapTest::run_func() { cvRemap( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], test_array[INPUT][1], test_array[INPUT][2], interpolation ); } double CV_RemapTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; } int CV_RemapTest::prepare_test_case( int test_case_idx ) { CvRNG* rng = ts->get_rng(); int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); const CvMat* src = &test_mat[INPUT][0]; double a[9] = {0,0,0,0,0,0,0,0,1}, k[4]; CvMat _a = cvMat( 3, 3, CV_64F, a ); CvMat _k = cvMat( 4, 1, CV_64F, k ); double sz = MAX(src->rows, src->cols); if( code <= 0 ) return code; if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) { double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; a[2] = (src->cols - 1)*0.5 + cvTsRandReal(rng)*10 - 5; a[5] = (src->rows - 1)*0.5 + cvTsRandReal(rng)*10 - 5; a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); a[4] = aspect_ratio*a[0]; k[0] = cvTsRandReal(rng)*0.06 - 0.03; k[1] = cvTsRandReal(rng)*0.06 - 0.03; if( k[0]*k[1] > 0 ) k[1] = -k[1]; k[2] = cvTsRandReal(rng)*0.004 - 0.002; k[3] = cvTsRandReal(rng)*0.004 - 0.002; } else { int i; a[2] = (src->cols - 1)*remap_undistort_params[0]; a[5] = (src->rows - 1)*remap_undistort_params[1]; a[0] = sz/remap_undistort_params[2]; a[4] = sz/remap_undistort_params[3]; for( i = 0; i < 4; i++ ) k[i] = remap_undistort_params[i+4]; } cvTsInitUndistortMap( &_a, &_k, &test_mat[INPUT][1], &test_mat[INPUT][2] ); return code; } void CV_RemapTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; int nr = interpolation == CV_INTER_CUBIC ? 3 : 3, nc = nr; CvMat part; cvTsRemap( &test_mat[INPUT][0], dst, dst0, &test_mat[INPUT][1], &test_mat[INPUT][2], interpolation ); nr = MIN(nr, dst->rows); nc = MIN(nc, dst->cols); cvGetRows( dst, &part, dst->rows - nr, dst->rows ); cvTsZero( &part ); cvGetRows( dst0, &part, dst->rows - nr, dst->rows ); cvTsZero( &part ); cvGetCols( dst, &part, dst->cols - nc, dst->cols ); cvTsZero( &part ); cvGetCols( dst0, &part, dst->cols - nc, dst->cols ); cvTsZero( &part ); } CV_RemapTest remap_test; ////////////////////////////// undistort ///////////////////////////////// class CV_UndistortTest : public CV_ImgWarpBaseTest { public: CV_UndistortTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); void fill_array( int test_case_idx, int i, int j, CvMat* arr ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_UndistortTest::CV_UndistortTest() : CV_ImgWarpBaseTest( "warp-undistort", "cvUndistort2", false ) { //spatial_scale_zoom = spatial_scale_decimate; test_array[INPUT].push(NULL); test_array[INPUT].push(NULL); spatial_scale_decimate = spatial_scale_zoom; //default_timing_param_names = imgwarp_perspective_param_names; support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; default_timing_param_names = 0; } int CV_UndistortTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "params", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; i < 8; i++ ) cvWriteReal( fs, 0, remap_undistort_params[i] ); cvEndWriteStruct(fs); } return code; } void CV_UndistortTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CvRNG* rng = ts->get_rng(); CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); int type = types[INPUT][0]; type = CV_MAKETYPE( CV_8U, CV_MAT_CN(type) ); types[INPUT][0] = types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = type; types[INPUT][1] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; types[INPUT][2] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; sizes[INPUT][1] = cvSize(3,3); sizes[INPUT][2] = cvTsRandInt(rng)%2 ? cvSize(4,1) : cvSize(1,4); interpolation = CV_INTER_LINEAR; } void CV_UndistortTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) { if( i != INPUT ) CV_ImgWarpBaseTestImpl::fill_array( test_case_idx, i, j, arr ); } void CV_UndistortTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); types[INPUT][1] = types[INPUT][2] = CV_32FC1; interpolation = CV_INTER_LINEAR; } void CV_UndistortTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_UndistortTest::run_func() { cvUndistort2( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &test_mat[INPUT][1], &test_mat[INPUT][2] ); } double CV_UndistortTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; } int CV_UndistortTest::prepare_test_case( int test_case_idx ) { CvRNG* rng = ts->get_rng(); int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); const CvMat* src = &test_mat[INPUT][0]; double k[4], a[9] = {0,0,0,0,0,0,0,0,1}; double sz = MAX(src->rows, src->cols); CvMat* _a0 = &test_mat[INPUT][1], *_k0 = &test_mat[INPUT][2]; CvMat _a = cvMat(3,3,CV_64F,a); CvMat _k = cvMat(_k0->rows,_k0->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(_k0->type)),k); if( code <= 0 ) return code; if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) { double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; a[2] = (src->cols - 1)*0.5 + cvTsRandReal(rng)*10 - 5; a[5] = (src->rows - 1)*0.5 + cvTsRandReal(rng)*10 - 5; a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); a[4] = aspect_ratio*a[0]; k[0] = cvTsRandReal(rng)*0.06 - 0.03; k[1] = cvTsRandReal(rng)*0.06 - 0.03; if( k[0]*k[1] > 0 ) k[1] = -k[1]; if( cvTsRandInt(rng)%4 != 0 ) { k[2] = cvTsRandReal(rng)*0.004 - 0.002; k[3] = cvTsRandReal(rng)*0.004 - 0.002; } else k[2] = k[3] = 0; } else { int i; a[2] = (src->cols - 1)*remap_undistort_params[0]; a[5] = (src->rows - 1)*remap_undistort_params[1]; a[0] = sz/remap_undistort_params[2]; a[4] = sz/remap_undistort_params[3]; for( i = 0; i < 4; i++ ) k[i] = remap_undistort_params[i+4]; } cvTsConvert( &_a, _a0 ); cvTsConvert( &_k, _k0 ); return code; } void CV_UndistortTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* src = &test_mat[INPUT][0]; CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; CvMat* mapx = cvCreateMat( dst->rows, dst->cols, CV_32FC1 ); CvMat* mapy = cvCreateMat( dst->rows, dst->cols, CV_32FC1 ); CvMat part; int nr = 2, nc = nr; cvTsInitUndistortMap( &test_mat[INPUT][1], &test_mat[INPUT][2], mapx, mapy ); cvTsRemap( src, dst, dst0, mapx, mapy, interpolation ); nr = MIN(nr, dst->rows); nc = MIN(nc, dst->cols); cvGetRows( dst, &part, 0, nr ); cvTsZero( &part ); cvGetRows( dst0, &part, 0, nr ); cvTsZero( &part ); cvGetRows( dst, &part, dst->rows - nr, dst->rows ); cvTsZero( &part ); cvGetRows( dst0, &part, dst->rows - nr, dst->rows ); cvTsZero( &part ); cvGetCols( dst, &part, 0, nc ); cvTsZero( &part ); cvGetCols( dst0, &part, 0, nc ); cvTsZero( &part ); cvGetCols( dst, &part, dst->cols - nc, dst->cols ); cvTsZero( &part ); cvGetCols( dst0, &part, dst->cols - nc, dst->cols ); cvTsZero( &part ); cvReleaseMat( &mapx ); cvReleaseMat( &mapy ); } CV_UndistortTest undistort_test; class CV_UndistortMapTest : public CvArrTest { public: CV_UndistortMapTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); void fill_array( int test_case_idx, int i, int j, CvMat* arr ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_UndistortMapTest::CV_UndistortMapTest() : CvArrTest( "warp-undistort-map", "cvInitUndistortMap", "" ) { test_array[INPUT].push(NULL); test_array[INPUT].push(NULL); test_array[OUTPUT].push(NULL); test_array[OUTPUT].push(NULL); test_array[REF_OUTPUT].push(NULL); test_array[REF_OUTPUT].push(NULL); element_wise_relative_error = false; support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; default_timing_param_names = 0; } int CV_UndistortMapTest::write_default_params( CvFileStorage* fs ) { int code = CvArrTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "params", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; i < 8; i++ ) cvWriteReal( fs, 0, remap_undistort_params[i] ); cvEndWriteStruct(fs); } return code; } void CV_UndistortMapTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CvRNG* rng = ts->get_rng(); CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); int depth = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; CvSize sz = sizes[OUTPUT][0]; types[INPUT][0] = types[INPUT][1] = depth; types[OUTPUT][0] = types[OUTPUT][1] = types[REF_OUTPUT][0] = types[REF_OUTPUT][1] = CV_32F; sizes[INPUT][0] = cvSize(3,3); sizes[INPUT][1] = cvTsRandInt(rng)%2 ? cvSize(4,1) : cvSize(1,4); sz.width = MAX(sz.width,16); sz.height = MAX(sz.height,16); sizes[OUTPUT][0] = sizes[OUTPUT][1] = sizes[REF_OUTPUT][0] = sizes[REF_OUTPUT][1] = sz; } void CV_UndistortMapTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) { if( i != INPUT ) CvArrTest::fill_array( test_case_idx, i, j, arr ); } void CV_UndistortMapTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); } void CV_UndistortMapTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_UndistortMapTest::run_func() { cvInitUndistortMap( &test_mat[INPUT][0], &test_mat[INPUT][1], test_array[OUTPUT][0], test_array[OUTPUT][1] ); } double CV_UndistortMapTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { return 1e-4; } int CV_UndistortMapTest::prepare_test_case( int test_case_idx ) { CvRNG* rng = ts->get_rng(); int code = CvArrTest::prepare_test_case( test_case_idx ); const CvMat* mapx = &test_mat[OUTPUT][0]; double k[4], a[9] = {0,0,0,0,0,0,0,0,1}; double sz = MAX(mapx->rows, mapx->cols); CvMat* _a0 = &test_mat[INPUT][0], *_k0 = &test_mat[INPUT][1]; CvMat _a = cvMat(3,3,CV_64F,a); CvMat _k = cvMat(_k0->rows,_k0->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(_k0->type)),k); if( code <= 0 ) return code; if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) { double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; a[2] = (mapx->cols - 1)*0.5 + cvTsRandReal(rng)*10 - 5; a[5] = (mapx->rows - 1)*0.5 + cvTsRandReal(rng)*10 - 5; a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); a[4] = aspect_ratio*a[0]; k[0] = cvTsRandReal(rng)*0.06 - 0.03; k[1] = cvTsRandReal(rng)*0.06 - 0.03; if( k[0]*k[1] > 0 ) k[1] = -k[1]; k[2] = cvTsRandReal(rng)*0.004 - 0.002; k[3] = cvTsRandReal(rng)*0.004 - 0.002; } else { int i; a[2] = (mapx->cols - 1)*remap_undistort_params[0]; a[5] = (mapx->rows - 1)*remap_undistort_params[1]; a[0] = sz/remap_undistort_params[2]; a[4] = sz/remap_undistort_params[3]; for( i = 0; i < 4; i++ ) k[i] = remap_undistort_params[i+4]; } cvTsConvert( &_a, _a0 ); cvTsConvert( &_k, _k0 ); return code; } void CV_UndistortMapTest::prepare_to_validation( int /*test_case_idx*/ ) { cvTsInitUndistortMap( &test_mat[INPUT][0], &test_mat[INPUT][1], &test_mat[REF_OUTPUT][0], &test_mat[REF_OUTPUT][1] ); } CV_UndistortMapTest undistortmap_test; ////////////////////////////// GetRectSubPix ///////////////////////////////// static const CvSize rectsubpix_sizes[] = {{11, 11}, {21,21}, {41,41},{-1,-1}}; static void cvTsGetQuadrangeSubPix( const CvMat* src, CvMat* dst, double* a ) { int y, x, k, cn; int sstep = src->step / sizeof(float); int scols = src->cols, srows = src->rows; assert( CV_MAT_DEPTH(src->type) == CV_32F && CV_ARE_TYPES_EQ(src, dst)); cn = CV_MAT_CN(dst->type); for( y = 0; y < dst->rows; y++ ) for( x = 0; x < dst->cols; x++ ) { float* d = (float*)(dst->data.ptr + y*dst->step) + x*cn; float sx = (float)(a[0]*x + a[1]*y + a[2]); float sy = (float)(a[3]*x + a[4]*y + a[5]); int ix = cvFloor(sx), iy = cvFloor(sy); int dx = cn, dy = sstep; const float* s; sx -= ix; sy -= iy; if( (unsigned)ix >= (unsigned)(scols-1) ) ix = ix < 0 ? 0 : scols - 1, sx = 0, dx = 0; if( (unsigned)iy >= (unsigned)(srows-1) ) iy = iy < 0 ? 0 : srows - 1, sy = 0, dy = 0; s = src->data.fl + sstep*iy + ix*cn; for( k = 0; k < cn; k++, s++ ) { float t0 = s[0] + sx*(s[dx] - s[0]); float t1 = s[dy] + sx*(s[dy + dx] - s[dy]); d[k] = t0 + sy*(t1 - t0); } } } class CV_GetRectSubPixTest : public CV_ImgWarpBaseTest { public: CV_GetRectSubPixTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); void fill_array( int test_case_idx, int i, int j, CvMat* arr ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); CvPoint2D32f center; }; CV_GetRectSubPixTest::CV_GetRectSubPixTest() : CV_ImgWarpBaseTest( "warp-subpix-rect", "cvGetRectSubPix", false ) { //spatial_scale_zoom = spatial_scale_decimate; spatial_scale_decimate = spatial_scale_zoom; //default_timing_param_names = imgwarp_perspective_param_names; support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; default_timing_param_names = 0; } int CV_GetRectSubPixTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "rect_size", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; rectsubpix_sizes[i].width > 0; i++ ) { cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); cvWriteInt( fs, 0, rectsubpix_sizes[i].width ); cvWriteInt( fs, 0, rectsubpix_sizes[i].height ); cvEndWriteStruct(fs); } cvEndWriteStruct(fs); } return code; } void CV_GetRectSubPixTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { CvRNG* rng = ts->get_rng(); CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); int src_depth = cvTsRandInt(rng) % 2, dst_depth; int cn = cvTsRandInt(rng) % 2 ? 3 : 1; CvSize src_size, dst_size; dst_depth = src_depth = src_depth == 0 ? CV_8U : CV_32F; if( src_depth < CV_32F && cvTsRandInt(rng) % 2 ) dst_depth = CV_32F; types[INPUT][0] = CV_MAKETYPE(src_depth,cn); types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(dst_depth,cn); src_size = sizes[INPUT][0]; dst_size.width = cvRound(sqrt(cvTsRandReal(rng)*src_size.width) + 1); dst_size.height = cvRound(sqrt(cvTsRandReal(rng)*src_size.height) + 1); dst_size.width = MIN(dst_size.width,src_size.width); dst_size.height = MIN(dst_size.width,src_size.height); sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = dst_size; center.x = (float)(cvTsRandReal(rng)*src_size.width); center.y = (float)(cvTsRandReal(rng)*src_size.height); interpolation = CV_INTER_LINEAR; } void CV_GetRectSubPixTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) { if( i != INPUT ) CV_ImgWarpBaseTestImpl::fill_array( test_case_idx, i, j, arr ); } void CV_GetRectSubPixTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); interpolation = CV_INTER_LINEAR; } void CV_GetRectSubPixTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_GetRectSubPixTest::run_func() { cvGetRectSubPix( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], center ); } double CV_GetRectSubPixTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int in_depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); int out_depth = CV_MAT_DEPTH(test_mat[INPUT_OUTPUT][0].type); return in_depth >= CV_32F ? 1e-3 : out_depth >= CV_32F ? 1e-2 : 1; } int CV_GetRectSubPixTest::prepare_test_case( int test_case_idx ) { return CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); } void CV_GetRectSubPixTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* src0 = &test_mat[INPUT][0]; CvMat* dst0 = &test_mat[REF_INPUT_OUTPUT][0]; CvMat* src = src0, *dst = dst0; int ftype = CV_MAKETYPE(CV_32F,CV_MAT_CN(src0->type)); double a[] = { 1, 0, center.x - dst->cols*0.5 + 0.5, 0, 1, center.y - dst->rows*0.5 + 0.5 }; if( CV_MAT_DEPTH(src->type) != CV_32F ) { src = cvCreateMat( src0->rows, src0->cols, ftype ); cvTsConvert( src0, src ); } if( CV_MAT_DEPTH(dst->type) != CV_32F ) dst = cvCreateMat( dst0->rows, dst0->cols, ftype ); cvTsGetQuadrangeSubPix( src, dst, a ); if( dst != dst0 ) { cvTsConvert( dst, dst0 ); cvReleaseMat( &dst ); } if( src != src0 ) cvReleaseMat( &src ); } CV_GetRectSubPixTest subpix_rect_test; class CV_GetQuadSubPixTest : public CV_ImgWarpBaseTest { public: CV_GetQuadSubPixTest(); protected: void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); void run_func(); int prepare_test_case( int test_case_idx ); void prepare_to_validation( int /*test_case_idx*/ ); double get_success_error_level( int test_case_idx, int i, int j ); int write_default_params(CvFileStorage* fs); void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); void print_timing_params( int test_case_idx, char* ptr, int params_left ); }; CV_GetQuadSubPixTest::CV_GetQuadSubPixTest() : CV_ImgWarpBaseTest( "warp-subpix-quad", "cvGetQuadSubPix", true ) { //spatial_scale_zoom = spatial_scale_decimate; spatial_scale_decimate = spatial_scale_zoom; //default_timing_param_names = imgwarp_affine_param_names; support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; default_timing_param_names = 0; } int CV_GetQuadSubPixTest::write_default_params( CvFileStorage* fs ) { int code = CV_ImgWarpBaseTest::write_default_params( fs ); if( code < 0 ) return code; if( ts->get_testing_mode() == CvTS::TIMING_MODE ) { int i; start_write_param( fs ); cvStartWriteStruct( fs, "rotate_scale", CV_NODE_SEQ+CV_NODE_FLOW ); for( i = 0; imgwarp_affine_rotate_scale[i][0] >= 0; i++ ) { cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); cvWriteRawData( fs, imgwarp_affine_rotate_scale[i], 4, "d" ); cvEndWriteStruct(fs); } cvEndWriteStruct(fs); } return code; } void CV_GetQuadSubPixTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) { int min_size = 4; CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); CvSize sz = sizes[INPUT][0], dsz; CvRNG* rng = ts->get_rng(); int msz, src_depth = cvTsRandInt(rng) % 2, dst_depth; int cn = cvTsRandInt(rng) % 2 ? 3 : 1; dst_depth = src_depth = src_depth == 0 ? CV_8U : CV_32F; if( src_depth < CV_32F && cvTsRandInt(rng) % 2 ) dst_depth = CV_32F; types[INPUT][0] = CV_MAKETYPE(src_depth,cn); types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(dst_depth,cn); sz.width = MAX(sz.width,min_size); sz.height = MAX(sz.height,min_size); sizes[INPUT][0] = sz; msz = MIN( sz.width, sz.height ); dsz.width = cvRound(sqrt(cvTsRandReal(rng)*msz) + 1); dsz.height = cvRound(sqrt(cvTsRandReal(rng)*msz) + 1); dsz.width = MIN(dsz.width,msz); dsz.height = MIN(dsz.width,msz); dsz.width = MAX(dsz.width,min_size); dsz.height = MAX(dsz.height,min_size); sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = dsz; sizes[INPUT][1] = cvSize( 3, 2 ); } void CV_GetQuadSubPixTest::get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) { CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, whole_sizes, are_images ); sizes[INPUT][1] = whole_sizes[INPUT][1] = cvSize(3,2); sizes[TEMP][0] = whole_sizes[TEMP][0] = sizes[TEMP][1] = whole_sizes[TEMP][1] = cvSize(0,0); types[INPUT][1] = CV_64FC1; interpolation = CV_INTER_LINEAR; } void CV_GetQuadSubPixTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) { double coeffs[4]; const CvFileNode* node = find_timing_param( "rotate_scale" ); assert( node && CV_NODE_IS_SEQ(node->tag) ); cvReadRawData( ts->get_file_storage(), node, coeffs, "4d" ); sprintf( ptr, "fx=%.2f,fy=%.2f,angle=%.1fdeg,scale=%.1f,", coeffs[0], coeffs[1], coeffs[2], coeffs[3] ); ptr += strlen(ptr); params_left -= 4; CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); } void CV_GetQuadSubPixTest::run_func() { cvGetQuadrangleSubPix( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &test_mat[INPUT][1] ); } double CV_GetQuadSubPixTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { int in_depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); //int out_depth = CV_MAT_DEPTH(test_mat[INPUT_OUTPUT][0].type); return in_depth >= CV_32F ? 1e-2 : 4; } int CV_GetQuadSubPixTest::prepare_test_case( int test_case_idx ) { CvRNG* rng = ts->get_rng(); int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); const CvMat* src = &test_mat[INPUT][0]; CvMat* mat = &test_mat[INPUT][1]; CvPoint2D32f center; double scale, angle; if( code <= 0 ) return code; if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) { double a[6]; CvMat A = cvMat( 2, 3, CV_64FC1, a ); center.x = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->cols); center.y = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->rows); angle = cvTsRandReal(rng)*360; scale = cvTsRandReal(rng)*0.2 + 0.9; // y = Ax + b -> x = A^-1(y - b) = A^-1*y - A^-1*b scale = 1./scale; angle = angle*(CV_PI/180.); a[0] = a[4] = cos(angle)*scale; a[1] = sin(angle)*scale; a[3] = -a[1]; a[2] = center.x - a[0]*center.x - a[1]*center.y; a[5] = center.y - a[3]*center.x - a[4]*center.y; cvTsConvert( &A, mat ); } return code; } void CV_GetQuadSubPixTest::prepare_to_validation( int /*test_case_idx*/ ) { CvMat* src0 = &test_mat[INPUT][0]; CvMat* dst0 = &test_mat[REF_INPUT_OUTPUT][0]; CvMat* src = src0, *dst = dst0; int ftype = CV_MAKETYPE(CV_32F,CV_MAT_CN(src0->type)); double a[6], dx = (dst0->cols - 1)*0.5, dy = (dst0->rows - 1)*0.5; CvMat A = cvMat( 2, 3, CV_64F, a ); if( CV_MAT_DEPTH(src->type) != CV_32F ) { src = cvCreateMat( src0->rows, src0->cols, ftype ); cvTsConvert( src0, src ); } if( CV_MAT_DEPTH(dst->type) != CV_32F ) dst = cvCreateMat( dst0->rows, dst0->cols, ftype ); cvTsConvert( &test_mat[INPUT][1], &A ); a[2] -= a[0]*dx + a[1]*dy; a[5] -= a[3]*dx + a[4]*dy; cvTsGetQuadrangeSubPix( src, dst, a ); if( dst != dst0 ) { cvTsConvert( dst, dst0 ); cvReleaseMat( &dst ); } if( src != src0 ) cvReleaseMat( &src ); } CV_GetQuadSubPixTest warp_subpix_quad_test; /* End of file. */
[ "garrett.marcotte@45935db4-cf16-11dd-8ca8-e3ff79f713b6" ]
[ [ [ 1, 1941 ] ] ]
2753fe1637e866f26f72ca50bffc79c73d111d47
aee9f4a7a277c3f44eac40072adb81dc52db3079
/Code/core/ComponentBlobDetectionMinMax.cpp
6cffb0e12876b5a977144977504407a75e7bdb09
[]
no_license
SiChiTong/swistrackplus
1a1bbc7dd8457ec908ced0cae3e30ef1f0d85551
7746c32dcfdbe1988c82e7a1561534c519ac0872
refs/heads/master
2020-04-05T02:31:55.840432
2010-06-01T14:12:46
2010-06-01T14:12:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,087
cpp
#include "ComponentBlobDetectionMinMax.h" #define THISCLASS ComponentBlobDetectionMinMax #include "DisplayEditor.h" #define PI 3.14159265358979 THISCLASS::ComponentBlobDetectionMinMax(SwisTrackCore *stc): Component(stc, wxT("BlobDetectionMinMax")), mMinArea(0), mMaxArea(1000000), mMaxNumber(10), mParticles(), mDisplayOutput(wxT("Output"), wxT("Particles")) { // Data structure relations mCategory = &(mCore->mCategoryParticleDetection); AddDataStructureRead(&(mCore->mDataStructureImageBinary)); AddDataStructureWrite(&(mCore->mDataStructureParticles)); AddDisplay(&mDisplayOutput); // Read the XML configuration file Initialize(); } THISCLASS::~ComponentBlobDetectionMinMax() { } void THISCLASS::OnStart() { OnReloadConfiguration(); return; } void THISCLASS::OnReloadConfiguration() { mMinArea = GetConfigurationInt(wxT("MinArea"), 1); mMaxArea = GetConfigurationInt(wxT("MaxArea"), 1000); mMaxNumber = GetConfigurationInt(wxT("MaxNumber"), 10); mAreaSelection = GetConfigurationBool(wxT("AreaBool"), false); mMinCompactness = GetConfigurationDouble(wxT("MinCompactness"), 1); mMaxCompactness = GetConfigurationDouble(wxT("MaxCompactness"), 1000); mCompactnessSelection = GetConfigurationBool(wxT("CompactnessBool"), false); mMinOrientation = GetConfigurationDouble(wxT("MinOrientation"), -90); mMaxOrientation = GetConfigurationDouble(wxT("MaxOrientation"), 90); mOrientationSelection = GetConfigurationBool(wxT("OrientationBool"), false); // Check for stupid configurations if (mMaxNumber < 1) { AddError(wxT("Max number of particles must be greater or equal to 1")); } if (mMinArea > mMaxArea) { AddError(wxT("The min area must be smaller than the max area.")); } } void THISCLASS::OnStep() { std::vector<Particle> rejectedparticles; // Get and check input image IplImage *inputimage = cvCloneImage(mCore->mDataStructureImageBinary.mImage); IplImage *outputImage = mCore->mDataStructureImageBinary.mImage; //mCore->mDataStructureImageBinary.mImage; if (! inputimage) { AddError(wxT("No input image.")); return; } if (inputimage->nChannels != 1) { AddError(wxT("The input image is not a grayscale image.")); return; } cvZero(outputImage); // We clear the ouput vector mParticles.clear(); // Initialization Particle tmpParticle; // Used to put the calculated value in memory CvMoments moments; // Used to calculate the moments std::vector<Particle>::iterator j; // Iterator used to stock the particles by size // We allocate memory to extract the contours from the binary image CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contour = 0; // Init blob extraxtion CvContourScanner blobs = cvStartFindContours(inputimage, storage, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_NONE); // This is used to correct the position in case of ROI CvRect rectROI; if (inputimage->roi != NULL) { rectROI = cvGetImageROI(inputimage); } else { rectROI.x = 0; rectROI.y = 0; } while ((contour = cvFindNextContour(blobs)) != NULL) { // Computing the moments cvMoments(contour, &moments); // Computing particle area tmpParticle.mArea = moments.m00; tmpParticle.mCenter.x = (float)(rectROI.x + (moments.m10 / moments.m00 + 0.5)); // moments using Green theorem tmpParticle.mCenter.y = (float)(rectROI.y + (moments.m01 / moments.m00 + 0.5)); // m10 = x direction, m01 = y direction, m00 = area as edicted in theorem // Selection based on area if ((mAreaSelection == false) || ((tmpParticle.mArea <= mMaxArea) && (tmpParticle.mArea >= mMinArea))) { tmpParticle.mCompactness = GetContourCompactness(contour); if ((mCompactnessSelection == false) || ((tmpParticle.mCompactness > mMinCompactness) && (tmpParticle.mCompactness < mMaxCompactness))) { double tempValue = cvGetCentralMoment(&moments, 2, 0) - cvGetCentralMoment(&moments, 0, 2); tmpParticle.mOrientation = atan(2 * cvGetCentralMoment(&moments, 1, 1) / (tempValue + sqrt(tempValue * tempValue + 4 * cvGetCentralMoment(&moments, 1, 1) * cvGetCentralMoment(&moments, 1, 1)))); if ((mOrientationSelection == false) || (((tmpParticle.mOrientation > mMinOrientation) && (tmpParticle.mOrientation < mMaxOrientation)) || ((tmpParticle.mOrientation > mMinOrientation + PI) && (tmpParticle.mOrientation < mMaxOrientation + PI)) || ((tmpParticle.mOrientation > mMinOrientation - PI) && (tmpParticle.mOrientation < mMaxOrientation - PI)))) { cvDrawContours(outputImage, contour, cvScalarAll(255), cvScalarAll(255), 0, CV_FILLED); // Check if we have already enough particles if (mParticles.size() == mMaxNumber) { // If the particle is bigger than the smallest stored particle, store it, else do nothing if (tmpParticle.mArea > mParticles.back().mArea) { // Find the place were it must be inserted, sorted by size for (j = mParticles.begin(); (j != mParticles.end()) && (tmpParticle.mArea < (*j).mArea); j++); // Fill unused values tmpParticle.mID = -1; tmpParticle.mIDCovariance = -1; // Insert the particle mParticles.insert(j, tmpParticle); // Remove the smallest one mParticles.pop_back(); } } else { // The particle is added at the correct place // Find the place were it must be inserted, sorted by size for (j = mParticles.begin(); (j != mParticles.end()) && (tmpParticle.mArea < (*j).mArea); j++); // Fill unused values tmpParticle.mID = -1; tmpParticle.mIDCovariance = -1; // Insert the particle mParticles.insert(j, tmpParticle); } } } } else { rejectedparticles.push_back(tmpParticle); } cvRelease((void**)&contour); } contour = cvEndFindContours(&blobs); // If we need to display the particles /* if(trackingimg->GetDisplay()) { for(j=rejectedparticles.begin();j!=rejectedparticles.end();j++) { trackingimg->DrawCircle(cvPoint((int)(((*j).p).x),(int)(((*j).p).y)),CV_RGB(255,0,0)); } for(j=particles.begin();j!=particles.end();j++) { trackingimg->DrawCircle(cvPoint((int)(((*j).p).x),(int)(((*j).p).y)),CV_RGB(0,255,0)); trackingimg->Cover(cvPoint((int)(((*j).p).x),(int)(((*j).p).y)),CV_RGB(255,0,0),2); } } */ cvReleaseImage(&inputimage); cvRelease((void**)&contour); cvReleaseMemStorage(&storage); // Set these particles mCore->mDataStructureParticles.mParticles = &mParticles; // Let the DisplayImage know about our image DisplayEditor de(&mDisplayOutput); if (de.IsActive()) { de.SetParticles(&mParticles); de.SetMainImage(mCore->mDataStructureImageBinary.mImage); } } void THISCLASS::OnStepCleanup() { mCore->mDataStructureParticles.mParticles = 0; } void THISCLASS::OnStop() { } double THISCLASS::GetContourCompactness(const void* contour) { double l = cvArcLength(contour, CV_WHOLE_SEQ, 1); return fabs(12.56*cvContourArea(contour) / (l*l)); }
[ "root@newport-ril-server.(none)" ]
[ [ [ 1, 195 ] ] ]
6abe30141cd612a6f25c6d1a5738e03af311fb0e
bb625ce36ed37acb5a8e660ec03001e9f23626cc
/WepPinhole/stdafx.cpp
20dd9f038215fa070878a9927bc6bc0e52b8bc03
[]
no_license
crayzyivan/weppinhole
5010f6f9319a81ec5f5277f8a7dd952a20d37c87
58923bf0667471257679a6f34a353412364609d5
refs/heads/master
2021-01-10T13:14:59.582556
2010-06-25T02:46:40
2010-06-25T02:46:40
43,535,806
1
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
// stdafx.cpp : source file that includes just the standard includes // WepPinhole.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 8 ] ] ]
dd00fd7c9d14513dc181f2d33b46ffe026d54176
84ca111e2739d866aac5f779824afd1f0bcf2842
/LoginDialog.h
32b7bcb5d36026bf677dd62b83d63503d0c140d5
[]
no_license
radtek/photoupload
0193989c016d35de774315acc562598ddb1ccf40
0291fd9fbed728aa07e1bebb578da58906fa0b8e
refs/heads/master
2020-09-27T13:13:47.706353
2009-09-24T22:20:11
2009-09-24T22:20:11
226,525,120
1
0
null
2019-12-07T14:15:57
2019-12-07T14:15:56
null
UTF-8
C++
false
false
872
h
#pragma once #include ".\uploadmanager.h" // LoginDialog dialog class LoginDialog : public CDialog { DECLARE_DYNAMIC(LoginDialog) public: LoginDialog(CWnd* pParent = NULL); // standard constructor virtual ~LoginDialog(); // Dialog Data enum { IDD = IDD_LOGINDIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support private: CString username; CString password; HICON icon; bool save; const UploadManager::LoginResult* previousResult; protected: DECLARE_MESSAGE_MAP() virtual BOOL OnInitDialog(); protected: virtual void OnOK(); public: void SetResult(const UploadManager::LoginResult* result); const CString GetUsername() const { return this->username; } const CString GetPassword() const { return this->password; } bool GetPersistLogin() const { return this->save; } };
[ [ [ 1, 39 ] ] ]
1f3ccdefc941c963d26a177e16d3024c62b08c25
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/svn/qrrepo/private/serializer.cpp
2c5dc6153aafc7e666ad9da01a70b4e54e768569
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
8,904
cpp
#include "serializer.h" #include <QtCore/QDir> #include <QtCore/QDebug> #include <QtCore/QPointF> #include <QtGui/QPolygon> #include "../../utils/outFile.h" #include "../../utils/xmlUtils.h" using namespace qrRepo; using namespace details; using namespace utils; using namespace qReal; Serializer::Serializer(QString const& saveDirName, bool failSafeMode) : mWorkingDir(saveDirName + "/save"), mFailSafe(failSafeMode) { } void Serializer::setWorkingDir(QString const &workingDir) { mWorkingDir = workingDir + "/save"; } void Serializer::saveToDisk(QList<LogicObject*> const &objects) const { // clearDir(mWorkingDir); foreach (LogicObject *object, objects) { QString filePath = createDirectory(object->id()); QDomDocument doc; QDomElement root = doc.createElement("LogicObject"); doc.appendChild(root); root.setAttribute("id", object->id().toString()); root.appendChild(idListToXml("parents", object->parents(), doc)); root.appendChild(idListToXml("children", object->children(), doc)); root.appendChild(propertiesToXml(object, doc)); OutFile out(filePath); doc.save(out(), 2); } } void Serializer::loadFromDisk(QHash<qReal::Id, LogicObject*> &objectsHash) { loadFromDisk(mWorkingDir, objectsHash); } void Serializer::loadFromDisk(QString const &currentPath, QHash<qReal::Id, LogicObject*> &objectsHash) { QDir dir(currentPath); if (dir.exists()) { foreach (QFileInfo fileInfo, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) { QString path = fileInfo.filePath(); if (fileInfo.isDir()) loadFromDisk(path, objectsHash); else if (fileInfo.isFile()) { QDomDocument doc = xmlUtils::loadDocument(path); LogicObject *object = parseLogicObject(doc.documentElement()); Q_ASSERT(object); // Пока требуем, что все объекты в репозитории загружаемы. if (object != NULL) objectsHash.insert(object->id(), object); } } } } LogicObject *Serializer::parseLogicObject(QDomElement const &elem) { QString id = elem.attribute("id", ""); if (id == "") return NULL; LogicObject object(Id::loadFromString(id)); foreach (Id parent, loadIdList(elem, "parents")) if (!mFailSafe || !object.parents().contains(parent)) object.addParent(parent); foreach (Id child, loadIdList(elem, "children")) if (!mFailSafe || !object.children().contains(child)) object.addChild(child); if (!loadProperties(elem, object)) return NULL; return new LogicObject(object); } bool Serializer::loadProperties(QDomElement const &elem, LogicObject &object) { QDomNodeList propertiesList = elem.elementsByTagName("properties"); if (propertiesList.count() != 1) { qDebug() << "Incorrect element: children list must appear once"; return false; } QDomElement properties = propertiesList.at(0).toElement(); QDomElement property = properties.firstChildElement(); while (!property.isNull()) { if (property.hasAttribute("type")) { // Тогда это список. Немного кривовато, зато унифицировано со // списками детей/родителей. if (property.attribute("type", "") == "qReal::IdList") { QString key = property.tagName(); IdList value = loadIdList(properties, property.tagName()); object.setProperty(key, IdListHelper::toVariant(value)); } else { Q_ASSERT(!"Unknown list type"); } } else { QString type = property.tagName(); QString key = property.attribute("key", ""); if (key == "") return false; QString valueStr = property.attribute("value", ""); QVariant value = parseValue(type, valueStr); object.setProperty(key, value); } property = property.nextSiblingElement(); } return true; } IdList Serializer::loadIdList(QDomElement const &elem, QString const &name) { QDomNodeList list = elem.elementsByTagName(name); if (list.count() != 1) { qDebug() << "Incorrect element: " + name + " list must appear once"; return IdList(); } IdList result; QDomElement elements = list.at(0).toElement(); QDomElement element = elements.firstChildElement(); while (!element.isNull()) { QString elementStr = element.attribute("id", ""); if (elementStr == "") { qDebug() << "Incorrect Child XML node"; return IdList(); } result.append(Id::loadFromString(elementStr)); element = element.nextSiblingElement(); } return result; } QVariant Serializer::parseValue(QString const &typeName, QString const &valueStr) { if (typeName.toLower() == "int") { return QVariant(valueStr.toInt()); } else if (typeName.toLower() == "uint") { return QVariant(valueStr.toUInt()); } else if (typeName.toLower() == "double") { return QVariant(valueStr.toDouble()); } else if (typeName.toLower() == "bool") { return QVariant(valueStr.toLower() == "true"); } else if (typeName == "QString") { return QVariant(valueStr); } else if (typeName.toLower() == "char") { return QVariant(valueStr[0]); } else if (typeName == "QPointF") { return QVariant(parsePointF(valueStr)); } else if (typeName == "QPolygon") { QStringList const points = valueStr.split(" : ", QString::SkipEmptyParts); QPolygon result; foreach (QString str, points) { QPointF point = parsePointF(str); result << point.toPoint(); } return QVariant(result); } else if (typeName == "qReal::Id") { return Id::loadFromString(valueStr).toVariant(); } else { Q_ASSERT(!"Unknown property type"); return QVariant(); } } QPointF Serializer::parsePointF(QString const &str) { double x = str.section(", ", 0, 0).toDouble(); double y = str.section(", ", 1, 1).toDouble(); return QPointF(x, y); } void Serializer::clearDir(QString const &path) { QDir dir(path); if (dir.exists()) { foreach (QFileInfo fileInfo, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) { if (fileInfo.isDir()) { clearDir(fileInfo.filePath()); dir.rmdir(fileInfo.fileName()); } else dir.remove(fileInfo.fileName()); } } } QString Serializer::serializeQVariant(QVariant const &v) { switch (v.type()) { case QVariant::Int: return QString("%1").arg(v.toInt()); case QVariant::UInt: return QString("%1").arg(v.toUInt()); case QVariant::Double: return QString("%1").arg(v.toDouble()); case QVariant::Bool: return QString("%1").arg(v.toBool()); case QVariant::String: return v.toString(); case QVariant::Char: return v.toChar(); case QVariant::PointF: return serializeQPointF(v.toPointF()); case QVariant::Polygon: return serializeQPolygon(v.value<QPolygon>()); case QVariant::UserType: if (v.userType() == QMetaType::type("qReal::Id")) return v.value<qReal::Id>().toString(); // Если нет, идём в default и там ругаемся. default: qDebug() << v; Q_ASSERT(!"Unsupported QVariant type."); return ""; } } QString Serializer::serializeQPointF(QPointF const &p) { return QString("%1").arg(p.x()) + ", " + QString("%1").arg(p.y()); } QString Serializer::serializeQPolygon(QPolygon const &p) { QString result(""); foreach (QPoint point, p) { result += serializeQPointF(point) + " : "; } return result; } QString Serializer::createDirectory(Id const &id) const { QString dirName = mWorkingDir; QStringList partsList = id.toString().split('/'); Q_ASSERT(partsList.size() >=1 && partsList.size() <= 5); for (int i = 1; i < partsList.size() - 1; ++i) { dirName += "/" + partsList[i]; } QDir dir; dir.rmdir(mWorkingDir); dir.mkpath(dirName); return dirName + "/" + partsList[partsList.size() - 1]; } QDomElement Serializer::idListToXml(QString const &attributeName, IdList const &idList, QDomDocument &doc) { QDomElement result = doc.createElement(attributeName); foreach (Id id, idList) { QDomElement element = doc.createElement("object"); element.setAttribute("id", id.toString()); result.appendChild(element); } return result; } QDomElement Serializer::propertiesToXml(LogicObject* const object, QDomDocument &doc) { QDomElement result = doc.createElement("properties"); QMapIterator<QString, QVariant> i = object->propertiesIterator(); while (i.hasNext()) { i.next(); QString typeName = i.value().typeName(); if (typeName == "qReal::IdList") { QDomElement list = idListToXml(i.key(), i.value().value<IdList>(), doc); list.setAttribute("type", "qReal::IdList"); result.appendChild(list); } else { QDomElement property = doc.createElement(i.value().typeName()); property.setAttribute("key", i.key()); QString value = serializeQVariant(i.value()); property.setAttribute("value", value); result.appendChild(property); } } return result; }
[ [ [ 1, 297 ] ] ]
619881a10dfa1a42cf17531bcea3772324606686
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/dvr/Net/TcpSocket.h
5730fb0f17c4e48fca067f9af769a3ed44690b72
[]
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
GB18030
C++
false
false
4,551
h
/* * Copyright (c) 2009, 浙江亿蛙技术股份有限公司 * All rights reserved. * * 类名称:TCP客户端类 * 摘 要:TCP方式传输。 * */ ////////////////////////////////////////////////////////////////////////// #if !defined(AFX_TCPSOCKET_H__8E1B116D_3800_4C99_A666_8413ABE8E9F7__INCLUDED_) #define AFX_TCPSOCKET_H__8E1B116D_3800_4C99_A666_8413ABE8E9F7__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifdef WIN32 #pragma comment( lib, "Ws2_32.lib") #ifdef NETSDK_VERSION_SSL #pragma comment( lib, "libeay32.lib") #pragma comment( lib, "ssleay32.lib") #endif #endif #if (defined(WIN32) && !(defined(NETSDK_VERSION_SSL))) #include "../../TPLayer_IOCP/TPTCPClient.h" #include "../../TPLayer_IOCP/TPTCPServer.h" #else #include "../../TPLayer_Select/TPTCPClient.h" #include "../../TPLayer_Select/TPTCPServer.h" using namespace NET_TOOL; #endif #ifndef HEADER_SIZE #define HEADER_SIZE 32 #endif // 断线回调函数 typedef int (__stdcall *OnDisConnectFunc)(void *userdata); // 重新已连接回调函数 typedef int (__stdcall *OnReConnectFunc)(void *userdata); // 非指定消息回调处理函数 typedef int (__stdcall *OnNormalPacketFunc)(unsigned char *pbuf, int nlen, void *userdata); // 接收回调函数(用在码流统计) typedef int (__stdcall *OnRecPacketFunc)(unsigned char *pbuf, int nlen, void *userdata); // 侦听回调函数 typedef void (__stdcall *OnListenSockFunc)(void* caller, char *ip, int port, int type, void *value, void *userdata); ////////////////////////////////////////////////////////////////////////// class CTcpSocket : virtual public TPTCPServer, virtual public TPTCPClient, public ITPListener { public: CTcpSocket(); virtual ~CTcpSocket(); int CreateRecvBuf(unsigned int nRecvSize); // 创建接收缓冲 public: static int InitNetwork(); static int ClearNetwork(); public: // client void SetCallBack(OnDisConnectFunc cbDisConnect, OnReConnectFunc cbReconnect, OnNormalPacketFunc cbNormalPacket, OnRecPacketFunc cbReceivePacket, void* userdata); void SetKeepLife(unsigned char *szLifePacket, int nBufLen, unsigned int nKeepLifeTime=10); int ConnectHost(const char *szIp, int nPort, int nTimeOut = 1500); void Disconnect(); int WriteData(char *pBuf, int nLen); int Heartbeat(); public: // server int StartListen(const char *szIp, int nPort, OnListenSockFunc cbListenSock, void *userdata); int StopListen(); virtual int DealNewSocket(SOCKET newsock, int connId, char* ip, int port); int SetSocket(SOCKET newsock, int connId, const char* ip, int port, OnListenSockFunc cbListen, void* listenuserdata, void* pListenSocket); int ResponseReg(bool bAccept); public: // event virtual int onData(int nEngineId, int nConnId, unsigned char* data, int nLen); virtual int onDealData(int nEngineId, int nConnId, unsigned char* buffer, int nLen); virtual int onSendDataAck(int nEngineId, int nConnId, int nId); virtual int onConnect(int nEngineId, int nConnId, char* szIp, int nPort); virtual int onClose(int nEngineId, int nConnId); virtual int onDisconnect(int nEngineId, int nConnId); virtual int onReconnect(int nEngineId, int nConnId); public: int SetIsReConn(int nEnable); int SetIsDetectDisconn(int nEnable); int GetIsOnline(); void DealSpecialPacket(unsigned char *pbuf, int nlen); int CloseSubConn(); // 关闭子连接 int ConnectSubConn(); // 子连接重连 #ifdef NETSDK_VERSION_SSL int SetSSL(int nEnable); #endif private: int GetData(unsigned char* buf, int len); #ifdef NETSDK_VERSION_BOGUSSSL int DealSSL(); #endif public: OS_EVENT m_hRecEvent; // 同步接收数据的事件 unsigned char m_registerAck[64]; int m_nRegisterLen; #ifdef NETSDK_VERSION_BOGUSSSL OS_EVENT m_hSpecialEvent; int m_nSSL; #endif private: OnDisConnectFunc m_pDisConnect; OnReConnectFunc m_pReconnect; OnNormalPacketFunc m_pNormalPacket; OnRecPacketFunc m_pRecvPakcet; void* m_pUserData; OnListenSockFunc m_pListenSockFunc; void* m_pListenUserData; void* m_pListenSocket; // 简易缓冲管理 unsigned int m_nWritePos; unsigned int m_nReadPos; unsigned char *m_pPacketBuf; unsigned int m_nBufSize; CReadWriteMutex m_csBuffer; CReadWriteMutex m_csOutCallBack; }; #endif // !defined(AFX_TCPSOCKET_H__8E1B116D_3800_4C99_A666_8413ABE8E9F7__INCLUDED_)
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 171 ] ] ]
99ca650762616a8954e813e8ec5605d3b30afb46
4eb798236579b3a57c9960e0d4acfe825cac5e4a
/Cluster.cpp
6aef5e5f52740e3f3367cbae81898d74407d42be
[]
no_license
gclaret/kmeans-cw
1a985e19ee20c9cd1e2310bfeea950e54a4993ca
6e2a765e230b36df602a97f6f0f788bc2c1081b2
refs/heads/master
2021-01-01T15:44:45.026218
2011-12-20T23:22:09
2011-12-20T23:22:09
39,042,975
0
0
null
null
null
null
UTF-8
C++
false
false
2,300
cpp
#include "Cluster.h" Cluster::Cluster(QColor c, int id) { this->id = id; this->colour = c; points = new vector<Point *>(); randomInit(); } Cluster::Cluster(QColor c, int id, double _x, double _y) { this->id = id; this->colour = c; points = new vector<Point *>(); centroid = new Point(_x, _y); } Cluster::~Cluster() { delete centroid; points->clear(); } void Cluster::randomInit() { int x_coord = rand() % 350; int y_coord = rand() % 350; centroid = new Point(x_coord, y_coord); } Point *Cluster::getCentroid() { return centroid; } void Cluster::updateCentroid() { int count = 0; double x_sum = 0.0; double y_sum = 0.0; for (std::vector<Point *>::iterator it = points->begin(); it != points->end(); ++it) { x_sum += (*it)->getX(); y_sum += (*it)->getY(); count++; } // need to account for if we have no points better than this. delete the cluster maybe or reallocate it randomly [TODO] if (count == 0) { centroid->setX(0); centroid->setY(0); } else { centroid->setX(x_sum/count); centroid->setY(y_sum/count); } points->clear(); } int Cluster::getNumberOfPoints() const { return points->size(); } void Cluster::clearPoints() { points->clear(); } vector<Point *> *Cluster::getPoints() const { return points; } QColor Cluster::getColour() const { return colour; } void Cluster::addPoint(Point *p) { points->push_back(p); /*for (vector<Point *>::iterator it = points->begin(); it != points->end(); ++it) { cout << (*it)->getX() << ", " << (*it)->getY() << endl; }*/ } void Cluster::removePoint(Point *p) { for (vector<Point *>::iterator it = points->begin(); it != points->end(); ++ it) { if (*(*it) == *p) { points->erase(it); return; } } } ostream &operator<<(ostream &output, const Cluster &c) { output << "["; for (vector<Point *>::iterator it = c.getPoints()->begin(); it != c.getPoints()->end(); ++ it) { output << *(*it) << ", "; } output << "]"; return output; }
[ [ [ 1, 116 ] ] ]
04267b106c9b866f567a09d409b3e99c268553f7
31d36971c94cb81c58b9f0b2f991ee7fb1034a47
/PisteEngine/PisteInput.cpp
cd585568dfbf094a052e03a9450b9de031eca420
[]
no_license
stt/pk2
e23a80f985fcb13ae57eb5cba8352be68291e3fe
8ca3fb99a21fdbf80ffda079051c5fb5c5b71341
refs/heads/master
2023-04-22T19:09:37.115934
2010-09-09T21:39:25
2010-09-09T21:39:25
897,109
11
4
null
null
null
null
ISO-8859-1
C++
false
false
36,271
cpp
/* PisteEngine - PisteInput 2.0 09.12.2001 Janne Kivilahti / Piste Gamez Versio 2.0 ---------- Kontrollit = näppäimistön, hiiren tai peliohjaimen luku yhdellä aliohjelmalla Lisätty vakiokontrollit (esimerkkejä: PI_KB_A, PI_KB_UP, PI_HIIRI_VASEN_NAPPI, PI_PELIOHJAIN1_NAPPI_1) Mahdollistavat sen, että käyttjä voi valita itse kontrollit. Selkeyttää myös koodia. UCHAR PisteInput_Lue_Kontrolli(); Kertoo minkä kontrollin pelaaja on valinnut. bool PisteInput_Lue_Kontrolli(UCHAR kontrolli); // Palauttaa TRUE jos käyttäjä on aktivoinut kontrollin. Kertoo onko pelaaja painanut kontrollia (hiiren nappi, peliohjaimen nappi tai näppäin) char *PisteInput_Lue_Kontrollin_Nimi(UCHAR kontrolli); Palauttaa kontrollin nimen. Esim. 'arrow left' /* /* INCLUDES ----------------------------------------------------------------------------------*/ #include "PisteInput.h" #include "PisteLog.h" /* DEFINES -----------------------------------------------------------------------------------*/ #define DIKEYDOWN(data,n) (data[n] & 0x80) #define MOUSE_LEFT_BUTTON 0 #define MOUSE_RIGHT_BUTTON 1 /* TYPE DEFINITIONS --------------------------------------------------------------------------*/ typedef unsigned short USHORT; typedef unsigned short WORD; typedef unsigned char UCHAR; typedef unsigned char BYTE; struct PELIOHJAIN { LPDIRECTINPUTDEVICE2 lpdijoy; bool available; char nimi[80]; DIJOYSTATE joystick_state; GUID joystickGUID; }; /* VARIABLES ---------------------------------------------------------------------------------*/ LPDIRECTINPUT PI_lpdi = NULL; LPDIRECTINPUTDEVICE PI_lpdikey = NULL; LPDIRECTINPUTDEVICE PI_lpdimouse = NULL; HWND PI_main_window_handle = NULL; // globally track main window HINSTANCE PI_hinstance_app = NULL; // globally track hinstance HDC PI_global_dc = NULL; // tracks a global dc UCHAR PI_keyboard_state[256]; DIMOUSESTATE PI_mouse_state; bool PI_mouse_available = true; bool PI_mouse_button; PELIOHJAIN PI_joysticks[PI_MAX_PELIOHJAIMIA]; int PI_joystick_index = 0; bool PI_unload = true; /* METHODS -----------------------------------------------------------------------------------*/ BOOL CALLBACK PisteInput_Enum_Ohjaimet(LPCDIDEVICEINSTANCE lpddi, LPVOID guid_ptr) { //*(GUID*)guid_ptr = lpddi->guidInstance; PI_joysticks[PI_joystick_index].joystickGUID = lpddi->guidInstance; strcpy(PI_joysticks[PI_joystick_index].nimi, (char *)lpddi->tszProductName); PI_joystick_index++; if (PI_joystick_index < PI_MAX_PELIOHJAIMIA) return(DIENUM_CONTINUE); return(DIENUM_STOP); } bool PisteInput_Alusta_Ohjain(int index) { LPDIRECTINPUTDEVICE temp; if (FAILED(PI_lpdi->CreateDevice(PI_joysticks[index].joystickGUID, &temp, NULL))) { PisteLog_Kirjoita("[Error] Piste Input: Gamepad - Create device failed! \n"); return false; } if (FAILED(temp->QueryInterface(IID_IDirectInputDevice2,(void**) &PI_joysticks[index].lpdijoy))) { PisteLog_Kirjoita("[Error] Piste Input: Gamepad - Create device failed! \n"); return false; } if (FAILED(temp->Release())) { PisteLog_Kirjoita("[Error] Piste Input: Gamepad - Releasing DirectInputDevice 1 failed! \n"); return false; } if (FAILED(PI_joysticks[index].lpdijoy->SetCooperativeLevel(PI_main_window_handle, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE ))) { PisteLog_Kirjoita("[Error] Piste Input: Gamepad - Releasing DirectInputDevice 1 failed! \n"); return false; } if (FAILED(PI_joysticks[index].lpdijoy->SetDataFormat(&c_dfDIJoystick))) { PisteLog_Kirjoita("[Error] Piste Input: Gamepad - Set dataformat failed! \n"); return false; } DIPROPRANGE joy_axis_range; //Määritellään x-akseli joy_axis_range.lMin = -PI_OHJAIN_XY; joy_axis_range.lMax = PI_OHJAIN_XY; joy_axis_range.diph.dwSize = sizeof(DIPROPRANGE); joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); joy_axis_range.diph.dwObj = DIJOFS_X; joy_axis_range.diph.dwHow = DIPH_BYOFFSET; PI_joysticks[index].lpdijoy->SetProperty(DIPROP_RANGE, &joy_axis_range.diph); //Määritellään y-akseli joy_axis_range.lMin = -PI_OHJAIN_XY; joy_axis_range.lMax = PI_OHJAIN_XY; joy_axis_range.diph.dwSize = sizeof(DIPROPRANGE); joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); joy_axis_range.diph.dwObj = DIJOFS_Y; joy_axis_range.diph.dwHow = DIPH_BYOFFSET; PI_joysticks[index].lpdijoy->SetProperty(DIPROP_RANGE, &joy_axis_range.diph); DIPROPDWORD dead_angle; dead_angle.diph.dwSize = sizeof(dead_angle); dead_angle.diph.dwHeaderSize = sizeof(dead_angle.diph); dead_angle.diph.dwObj = DIJOFS_X; dead_angle.diph.dwHow = DIPH_BYOFFSET; dead_angle.dwData = 5000; //= 10% PI_joysticks[index].lpdijoy->SetProperty(DIPROP_DEADZONE, &dead_angle.diph); dead_angle.diph.dwSize = sizeof(dead_angle); dead_angle.diph.dwHeaderSize = sizeof(dead_angle.diph); dead_angle.diph.dwObj = DIJOFS_Y; dead_angle.diph.dwHow = DIPH_BYOFFSET; dead_angle.dwData = 5000; //= 10% PI_joysticks[index].lpdijoy->SetProperty(DIPROP_DEADZONE, &dead_angle.diph); if (FAILED(PI_joysticks[index].lpdijoy->Acquire())) { PisteLog_Kirjoita("[Error] Piste Input: Gamepad - Acquiring device failed! \n"); return false; } return true; } bool PisteInput_Alusta_Ohjaimet() { //LPDIRECTINPUTDEVICE temp; if (FAILED(PI_lpdi->EnumDevices(DIDEVTYPE_JOYSTICK, PisteInput_Enum_Ohjaimet, /*&PI_joystickGUID*/NULL, DIEDFL_ATTACHEDONLY))) { PisteLog_Kirjoita("[Error] Piste Input: Gamepads - Enumerating failed! \n"); return false; } for (int i=0; i < PI_MAX_PELIOHJAIMIA; i++) { if (PI_joysticks[i].nimi != NULL) { if (PisteInput_Alusta_Ohjain(i)) { PI_joysticks[i].available = true; } else { PI_joysticks[i].available = false; } } else PI_joysticks[i].available = false; } /* if (FAILED(PI_lpdi->CreateDevice(PI_joystickGUID, &temp, NULL))) return false; if (FAILED(temp->QueryInterface(IID_IDirectInputDevice2,(void**) &PI_lpdijoy))) return false; if (FAILED(temp->Release())) return false; if (FAILED(PI_lpdijoy->SetCooperativeLevel(PI_main_window_handle, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE ))) return false; if (FAILED(PI_lpdijoy->SetDataFormat(&c_dfDIJoystick))) return false; DIPROPRANGE joy_axis_range; //Määritellään x-akseli joy_axis_range.lMin = -PI_OHJAIN_XY; joy_axis_range.lMax = PI_OHJAIN_XY; joy_axis_range.diph.dwSize = sizeof(DIPROPRANGE); joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); joy_axis_range.diph.dwObj = DIJOFS_X; joy_axis_range.diph.dwHow = DIPH_BYOFFSET; PI_lpdijoy->SetProperty(DIPROP_RANGE, &joy_axis_range.diph); //Määritellään y-akseli joy_axis_range.lMin = -PI_OHJAIN_XY; joy_axis_range.lMax = PI_OHJAIN_XY; joy_axis_range.diph.dwSize = sizeof(DIPROPRANGE); joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); joy_axis_range.diph.dwObj = DIJOFS_Y; joy_axis_range.diph.dwHow = DIPH_BYOFFSET; PI_lpdijoy->SetProperty(DIPROP_RANGE, &joy_axis_range.diph); DIPROPDWORD dead_angle; dead_angle.diph.dwSize = sizeof(dead_angle); dead_angle.diph.dwHeaderSize = sizeof(dead_angle.diph); dead_angle.diph.dwObj = DIJOFS_X; dead_angle.diph.dwHow = DIPH_BYOFFSET; dead_angle.dwData = 5000; //= 10% PI_lpdijoy->SetProperty(DIPROP_DEADZONE, &dead_angle.diph); dead_angle.diph.dwSize = sizeof(dead_angle); dead_angle.diph.dwHeaderSize = sizeof(dead_angle.diph); dead_angle.diph.dwObj = DIJOFS_Y; dead_angle.diph.dwHow = DIPH_BYOFFSET; dead_angle.dwData = 5000; //= 10% PI_lpdijoy->SetProperty(DIPROP_DEADZONE, &dead_angle.diph); if (FAILED(PI_lpdijoy->Acquire())) return false; */ return true; } bool PisteInput_Alusta_Keyboard() { if (FAILED(PI_lpdi->CreateDevice(GUID_SysKeyboard, &PI_lpdikey, NULL))) { PisteLog_Kirjoita("[Error] Piste Input: Keyboard - Create Device failed! \n"); return false; } if (FAILED(PI_lpdikey->SetCooperativeLevel(PI_main_window_handle, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE /* | DISCL_FOREGROUND*/))) { PisteLog_Kirjoita("[Error] Piste Input: Keyboard - Set cooperative level failed! \n"); return false; } if (FAILED(PI_lpdikey->SetDataFormat(&c_dfDIKeyboard))) { PisteLog_Kirjoita("[Error] Piste Input: Keyboard - Set data format failed! \n"); return false; } if (FAILED(PI_lpdikey->Acquire())) { PisteLog_Kirjoita("[Error] Piste Input: Keyboard - Acquire failed! \n"); return false; } return true; } bool PisteInput_Alusta_Mouse() { if (FAILED(PI_lpdi->CreateDevice(GUID_SysMouse, &PI_lpdimouse, NULL))) { PisteLog_Kirjoita("[Warning] Piste Input: No mouse available! \n"); PI_mouse_available = false; } if (PI_mouse_available) { if (FAILED(PI_lpdimouse->SetCooperativeLevel(PI_main_window_handle, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))) { PisteLog_Kirjoita("[Error] Piste Input: Mouse - Set cooperative level failed! \n"); PI_mouse_available = false; } if (FAILED(PI_lpdimouse->SetDataFormat(&c_dfDIMouse))) { PisteLog_Kirjoita("[Error] Piste Input: Mouse - Set data format failed! \n"); PI_mouse_available = false; } if (FAILED(PI_lpdimouse->Acquire())) { PisteLog_Kirjoita("[Error] Piste Input: Mouse - Acquire failed! \n"); PI_mouse_available = false; } } return PI_mouse_available; } int PisteInput_Alusta(HWND &main_window_handle, HINSTANCE &hinstance_app) { if (PI_unload) { PI_main_window_handle = (HWND &) main_window_handle; PI_hinstance_app = (HINSTANCE &) hinstance_app; if (FAILED(DirectInputCreate(PI_hinstance_app, DIRECTINPUT_VERSION, &PI_lpdi, NULL))) { PisteLog_Kirjoita("[Error] Piste Input: DirectInputCreate failed! \n"); return PI_VIRHE; } /* Näppäimistön asennus */ if (!PisteInput_Alusta_Keyboard()) return PI_VIRHE; /* Hiiren asennus */ if (!PisteInput_Alusta_Mouse()) PI_mouse_available = false; //return PI_VIRHE; /* Ohjainten asennus */ PisteInput_Alusta_Ohjaimet(); PI_unload = false; } return 0; } bool PisteInput_Onko_Hiiri() { return PI_mouse_available; } bool PisteInput_Onko_Ohjain(int ohjain) { return PI_joysticks[ohjain].available; } bool PisteInput_Keydown(int key) { if (DIKEYDOWN(PI_keyboard_state, key)) return true; return false; } bool PisteInput_Hiiri_Vasen() { PI_mouse_button = false; if (PI_mouse_available) { if (PI_mouse_state.rgbButtons[MOUSE_LEFT_BUTTON] & 0x80) PI_mouse_button = true; } return PI_mouse_button; } bool PisteInput_Hiiri_Oikea() { PI_mouse_button = false; if (PI_mouse_available) { if (PI_mouse_state.rgbButtons[MOUSE_RIGHT_BUTTON] & 0x80) PI_mouse_button = true; } return PI_mouse_button; } int PisteInput_Hiiri_X(int x) { if (PI_mouse_available) x += PI_mouse_state.lX; return x; } int PisteInput_Hiiri_Y(int y) { if (PI_mouse_available) y += PI_mouse_state.lY; return y; } int PisteInput_Ohjain_X(int ohjain) { int x = 0; if (PI_joysticks[ohjain].available) x = PI_joysticks[ohjain].joystick_state.lX; return x; } int PisteInput_Ohjain_Y(int ohjain) { int y = 0; if (PI_joysticks[ohjain].available) y += PI_joysticks[ohjain].joystick_state.lY; return y; } bool PisteInput_Ohjain_Nappi(int ohjain, int index) { bool painettu = false; if (PI_joysticks[ohjain].available) { if (PI_joysticks[ohjain].joystick_state.rgbButtons[index] & 0x80) painettu = true; } return painettu; } char *PisteInput_Ohjain_Nimi(int ohjain) { return PI_joysticks[ohjain].nimi; } bool PisteInput_Hae_Ohjaimet() { bool ok = false; for(int ohjain=0; ohjain < PI_MAX_PELIOHJAIMIA; ohjain++) { if (PI_joysticks[ohjain].available) { if (FAILED(PI_joysticks[ohjain].lpdijoy->Poll())) { PisteLog_Kirjoita("[Warning] Piste Input: Lost control of game pad! \n"); PI_joysticks[ohjain].available = false; } if (FAILED(PI_joysticks[ohjain].lpdijoy->GetDeviceState(sizeof(DIJOYSTATE),(LPVOID)&PI_joysticks[ohjain].joystick_state))) { PisteLog_Kirjoita("[Warning] Piste Input: Lost control of game pad! \n"); PI_joysticks[ohjain].available = false; } if (PI_joysticks[ohjain].available) ok = true; } } return ok; } bool PisteInput_Hae_Nappaimet() { HRESULT result; bool ok = true; while (result = PI_lpdikey->GetDeviceState(sizeof(PI_keyboard_state), (LPVOID) PI_keyboard_state) == DIERR_INPUTLOST) { if (FAILED(result = PI_lpdikey->Acquire())) { PisteLog_Kirjoita("[Warning] Piste Input: Lost control of keyboard! \n"); ok = false; } } return ok; } bool PisteInput_Hae_Hiiri() { if (PI_mouse_available) { if (FAILED(PI_lpdimouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&PI_mouse_state))) { PisteLog_Kirjoita("[Warning] Piste Input: Lost control of mouse! \n"); PI_mouse_available = false; } } return PI_mouse_available; } char PisteInput_Lue_Nappaimisto(void) { if (DIKEYDOWN(PI_keyboard_state, DIK_RSHIFT)) { if (DIKEYDOWN(PI_keyboard_state, DIK_A)) return('ä'); if (DIKEYDOWN(PI_keyboard_state, DIK_1)) return('!'); if (DIKEYDOWN(PI_keyboard_state, DIK_ADD)) return('?'); if (DIKEYDOWN(PI_keyboard_state, DIK_O)) return('ö'); } if (DIKEYDOWN(PI_keyboard_state, DIK_RMENU)) { if (DIKEYDOWN(PI_keyboard_state, DIK_O)) return('å'); if (DIKEYDOWN(PI_keyboard_state, DIK_A)) return('ä'); } if (DIKEYDOWN(PI_keyboard_state, DIK_A)) return('a'); if (DIKEYDOWN(PI_keyboard_state, DIK_B)) return('b'); if (DIKEYDOWN(PI_keyboard_state, DIK_C)) return('c'); if (DIKEYDOWN(PI_keyboard_state, DIK_D)) return('d'); if (DIKEYDOWN(PI_keyboard_state, DIK_E)) return('e'); if (DIKEYDOWN(PI_keyboard_state, DIK_F)) return('f'); if (DIKEYDOWN(PI_keyboard_state, DIK_G)) return('g'); if (DIKEYDOWN(PI_keyboard_state, DIK_H)) return('h'); if (DIKEYDOWN(PI_keyboard_state, DIK_I)) return('i'); if (DIKEYDOWN(PI_keyboard_state, DIK_J)) return('j'); if (DIKEYDOWN(PI_keyboard_state, DIK_K)) return('k'); if (DIKEYDOWN(PI_keyboard_state, DIK_L)) return('l'); if (DIKEYDOWN(PI_keyboard_state, DIK_M)) return('m'); if (DIKEYDOWN(PI_keyboard_state, DIK_N)) return('n'); if (DIKEYDOWN(PI_keyboard_state, DIK_O)) return('o'); if (DIKEYDOWN(PI_keyboard_state, DIK_P)) return('p'); if (DIKEYDOWN(PI_keyboard_state, DIK_Q)) return('q'); if (DIKEYDOWN(PI_keyboard_state, DIK_R)) return('r'); if (DIKEYDOWN(PI_keyboard_state, DIK_S)) return('s'); if (DIKEYDOWN(PI_keyboard_state, DIK_T)) return('t'); if (DIKEYDOWN(PI_keyboard_state, DIK_U)) return('u'); if (DIKEYDOWN(PI_keyboard_state, DIK_V)) return('v'); if (DIKEYDOWN(PI_keyboard_state, DIK_W)) return('w'); if (DIKEYDOWN(PI_keyboard_state, DIK_X)) return('x'); if (DIKEYDOWN(PI_keyboard_state, DIK_Y)) return('y'); if (DIKEYDOWN(PI_keyboard_state, DIK_Z)) return('z'); if (DIKEYDOWN(PI_keyboard_state, DIK_0)) return('0'); if (DIKEYDOWN(PI_keyboard_state, DIK_1)) return('1'); if (DIKEYDOWN(PI_keyboard_state, DIK_2)) return('2'); if (DIKEYDOWN(PI_keyboard_state, DIK_3)) return('3'); if (DIKEYDOWN(PI_keyboard_state, DIK_4)) return('4'); if (DIKEYDOWN(PI_keyboard_state, DIK_5)) return('5'); if (DIKEYDOWN(PI_keyboard_state, DIK_6)) return('6'); if (DIKEYDOWN(PI_keyboard_state, DIK_7)) return('7'); if (DIKEYDOWN(PI_keyboard_state, DIK_8)) return('8'); if (DIKEYDOWN(PI_keyboard_state, DIK_9)) return('9'); if (DIKEYDOWN(PI_keyboard_state, DIK_SPACE)) return(' '); if (DIKEYDOWN(PI_keyboard_state, DIK_PERIOD)) return('.'); if (DIKEYDOWN(PI_keyboard_state, DIK_COMMA)) return(','); if (DIKEYDOWN(PI_keyboard_state, DIK_MINUS)) return('-'); if (DIKEYDOWN(PI_keyboard_state, DIK_ADD)) return('+'); if (DIKEYDOWN(PI_keyboard_state, DIK_SEMICOLON)) return(':'); if (DIKEYDOWN(PI_keyboard_state, DIK_RETURN)) return('\n'); return('\0'); } UCHAR PisteInput_Lue_Kontrolli() { if (DIKEYDOWN(PI_keyboard_state, DIK_A)) return PI_KB_A; if (DIKEYDOWN(PI_keyboard_state, DIK_B)) return PI_KB_B; if (DIKEYDOWN(PI_keyboard_state, DIK_C)) return PI_KB_C; if (DIKEYDOWN(PI_keyboard_state, DIK_D)) return PI_KB_D; if (DIKEYDOWN(PI_keyboard_state, DIK_E)) return PI_KB_E; if (DIKEYDOWN(PI_keyboard_state, DIK_F)) return PI_KB_F; if (DIKEYDOWN(PI_keyboard_state, DIK_G)) return PI_KB_G; if (DIKEYDOWN(PI_keyboard_state, DIK_H)) return PI_KB_H; if (DIKEYDOWN(PI_keyboard_state, DIK_I)) return PI_KB_I; if (DIKEYDOWN(PI_keyboard_state, DIK_J)) return PI_KB_J; if (DIKEYDOWN(PI_keyboard_state, DIK_K)) return PI_KB_K; if (DIKEYDOWN(PI_keyboard_state, DIK_L)) return PI_KB_L; if (DIKEYDOWN(PI_keyboard_state, DIK_M)) return PI_KB_M; if (DIKEYDOWN(PI_keyboard_state, DIK_N)) return PI_KB_N; if (DIKEYDOWN(PI_keyboard_state, DIK_O)) return PI_KB_O; if (DIKEYDOWN(PI_keyboard_state, DIK_P)) return PI_KB_P; if (DIKEYDOWN(PI_keyboard_state, DIK_Q)) return PI_KB_Q; if (DIKEYDOWN(PI_keyboard_state, DIK_R)) return PI_KB_R; if (DIKEYDOWN(PI_keyboard_state, DIK_S)) return PI_KB_S; if (DIKEYDOWN(PI_keyboard_state, DIK_T)) return PI_KB_T; if (DIKEYDOWN(PI_keyboard_state, DIK_U)) return PI_KB_U; if (DIKEYDOWN(PI_keyboard_state, DIK_V)) return PI_KB_V; if (DIKEYDOWN(PI_keyboard_state, DIK_W)) return PI_KB_W; if (DIKEYDOWN(PI_keyboard_state, DIK_X)) return PI_KB_X; if (DIKEYDOWN(PI_keyboard_state, DIK_Y)) return PI_KB_Y; if (DIKEYDOWN(PI_keyboard_state, DIK_Z)) return PI_KB_Z; if (DIKEYDOWN(PI_keyboard_state, DIK_0)) return PI_KB_0; if (DIKEYDOWN(PI_keyboard_state, DIK_1)) return PI_KB_1; if (DIKEYDOWN(PI_keyboard_state, DIK_2)) return PI_KB_2; if (DIKEYDOWN(PI_keyboard_state, DIK_3)) return PI_KB_3; if (DIKEYDOWN(PI_keyboard_state, DIK_4)) return PI_KB_4; if (DIKEYDOWN(PI_keyboard_state, DIK_5)) return PI_KB_5; if (DIKEYDOWN(PI_keyboard_state, DIK_6)) return PI_KB_6; if (DIKEYDOWN(PI_keyboard_state, DIK_7)) return PI_KB_7; if (DIKEYDOWN(PI_keyboard_state, DIK_8)) return PI_KB_8; if (DIKEYDOWN(PI_keyboard_state, DIK_9)) return PI_KB_9; if (DIKEYDOWN(PI_keyboard_state, DIK_RETURN)) return PI_KB_ENTER; if (DIKEYDOWN(PI_keyboard_state, DIK_SPACE)) return PI_KB_SPACE; if (DIKEYDOWN(PI_keyboard_state, DIK_RSHIFT)) return PI_KB_RSHIFT; if (DIKEYDOWN(PI_keyboard_state, DIK_LSHIFT)) return PI_KB_LSHIFT; if (DIKEYDOWN(PI_keyboard_state, DIK_RALT)) return PI_KB_RALT; if (DIKEYDOWN(PI_keyboard_state, DIK_LALT)) return PI_KB_LALT; if (DIKEYDOWN(PI_keyboard_state, DIK_RCONTROL)) return PI_KB_RCONTROL; if (DIKEYDOWN(PI_keyboard_state, DIK_LCONTROL)) return PI_KB_LCONTROL; if (DIKEYDOWN(PI_keyboard_state, DIK_PRIOR)) return PI_KB_PAGEUP; if (DIKEYDOWN(PI_keyboard_state, DIK_NEXT)) return PI_KB_PAGEDOWN; if (DIKEYDOWN(PI_keyboard_state, DIK_BACKSPACE)) return PI_KB_BACKSPACE; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPADENTER)) return PI_KB_NUMPADENTER; if (DIKEYDOWN(PI_keyboard_state, DIK_UP)) return PI_KB_UP; if (DIKEYDOWN(PI_keyboard_state, DIK_DOWN)) return PI_KB_DOWN; if (DIKEYDOWN(PI_keyboard_state, DIK_LEFT)) return PI_KB_LEFT; if (DIKEYDOWN(PI_keyboard_state, DIK_RIGHT)) return PI_KB_RIGHT; if (DIKEYDOWN(PI_keyboard_state, DIK_F1)) return PI_KB_F1; if (DIKEYDOWN(PI_keyboard_state, DIK_F2)) return PI_KB_F2; if (DIKEYDOWN(PI_keyboard_state, DIK_F3)) return PI_KB_F3; if (DIKEYDOWN(PI_keyboard_state, DIK_F4)) return PI_KB_F4; if (DIKEYDOWN(PI_keyboard_state, DIK_F5)) return PI_KB_F5; if (DIKEYDOWN(PI_keyboard_state, DIK_F6)) return PI_KB_F6; if (DIKEYDOWN(PI_keyboard_state, DIK_F7)) return PI_KB_F7; if (DIKEYDOWN(PI_keyboard_state, DIK_F8)) return PI_KB_F8; if (DIKEYDOWN(PI_keyboard_state, DIK_F9)) return PI_KB_F9; if (DIKEYDOWN(PI_keyboard_state, DIK_F10)) return PI_KB_F10; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD0)) return PI_KB_NUMPAD_0; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD1)) return PI_KB_NUMPAD_1; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD2)) return PI_KB_NUMPAD_2; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD3)) return PI_KB_NUMPAD_3; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD4)) return PI_KB_NUMPAD_4; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD5)) return PI_KB_NUMPAD_5; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD6)) return PI_KB_NUMPAD_6; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD7)) return PI_KB_NUMPAD_7; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD8)) return PI_KB_NUMPAD_8; if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD9)) return PI_KB_NUMPAD_9; if (PisteInput_Hiiri_Vasen()) return PI_HIIRI_VASEN_NAPPI; if (PisteInput_Hiiri_Oikea()) return PI_HIIRI_OIKEA_NAPPI; if (PisteInput_Ohjain_X(PI_PELIOHJAIN_1) < 0) return PI_OHJAIN1_VASEMMALLE; if (PisteInput_Ohjain_X(PI_PELIOHJAIN_1) > 0) return PI_OHJAIN1_OIKEALLE; if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_1) < 0) return PI_OHJAIN1_YLOS; if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_1) > 0) return PI_OHJAIN1_ALAS; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_1)) return PI_OHJAIN1_NAPPI1; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_2)) return PI_OHJAIN1_NAPPI2; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_3)) return PI_OHJAIN1_NAPPI3; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_4)) return PI_OHJAIN1_NAPPI4; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_5)) return PI_OHJAIN1_NAPPI5; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_6)) return PI_OHJAIN1_NAPPI6; if (PisteInput_Ohjain_X(PI_PELIOHJAIN_2) < 0) return PI_OHJAIN2_VASEMMALLE; if (PisteInput_Ohjain_X(PI_PELIOHJAIN_2) > 0) return PI_OHJAIN2_OIKEALLE; if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_2) < 0) return PI_OHJAIN2_YLOS; if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_2) > 0) return PI_OHJAIN2_ALAS; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_1)) return PI_OHJAIN2_NAPPI1; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_2)) return PI_OHJAIN2_NAPPI2; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_3)) return PI_OHJAIN2_NAPPI3; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_4)) return PI_OHJAIN2_NAPPI4; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_5)) return PI_OHJAIN2_NAPPI5; if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_6)) return PI_OHJAIN2_NAPPI6; return 0; } bool PisteInput_Lue_Kontrolli(UCHAR k) { switch(k) { case PI_KB_A : if (DIKEYDOWN(PI_keyboard_state, DIK_A)) return true;break; case PI_KB_B : if (DIKEYDOWN(PI_keyboard_state, DIK_B)) return true;break; case PI_KB_C : if (DIKEYDOWN(PI_keyboard_state, DIK_C)) return true;break; case PI_KB_D : if (DIKEYDOWN(PI_keyboard_state, DIK_D)) return true;break; case PI_KB_E : if (DIKEYDOWN(PI_keyboard_state, DIK_E)) return true;break; case PI_KB_F : if (DIKEYDOWN(PI_keyboard_state, DIK_F)) return true;break; case PI_KB_G : if (DIKEYDOWN(PI_keyboard_state, DIK_G)) return true;break; case PI_KB_H : if (DIKEYDOWN(PI_keyboard_state, DIK_H)) return true;break; case PI_KB_I : if (DIKEYDOWN(PI_keyboard_state, DIK_I)) return true;break; case PI_KB_J : if (DIKEYDOWN(PI_keyboard_state, DIK_J)) return true;break; case PI_KB_K : if (DIKEYDOWN(PI_keyboard_state, DIK_K)) return true;break; case PI_KB_L : if (DIKEYDOWN(PI_keyboard_state, DIK_L)) return true;break; case PI_KB_M : if (DIKEYDOWN(PI_keyboard_state, DIK_M)) return true;break; case PI_KB_N : if (DIKEYDOWN(PI_keyboard_state, DIK_N)) return true;break; case PI_KB_O : if (DIKEYDOWN(PI_keyboard_state, DIK_O)) return true;break; case PI_KB_P : if (DIKEYDOWN(PI_keyboard_state, DIK_P)) return true;break; case PI_KB_Q : if (DIKEYDOWN(PI_keyboard_state, DIK_Q)) return true;break; case PI_KB_R : if (DIKEYDOWN(PI_keyboard_state, DIK_R)) return true;break; case PI_KB_S : if (DIKEYDOWN(PI_keyboard_state, DIK_S)) return true;break; case PI_KB_T : if (DIKEYDOWN(PI_keyboard_state, DIK_T)) return true;break; case PI_KB_U : if (DIKEYDOWN(PI_keyboard_state, DIK_U)) return true;break; case PI_KB_V : if (DIKEYDOWN(PI_keyboard_state, DIK_V)) return true;break; case PI_KB_W : if (DIKEYDOWN(PI_keyboard_state, DIK_W)) return true;break; case PI_KB_X : if (DIKEYDOWN(PI_keyboard_state, DIK_X)) return true;break; case PI_KB_Y : if (DIKEYDOWN(PI_keyboard_state, DIK_Y)) return true;break; case PI_KB_Z : if (DIKEYDOWN(PI_keyboard_state, DIK_Z)) return true;break; case PI_KB_0 : if (DIKEYDOWN(PI_keyboard_state, DIK_0)) return true;break; case PI_KB_1 : if (DIKEYDOWN(PI_keyboard_state, DIK_1)) return true;break; case PI_KB_2 : if (DIKEYDOWN(PI_keyboard_state, DIK_2)) return true;break; case PI_KB_3 : if (DIKEYDOWN(PI_keyboard_state, DIK_3)) return true;break; case PI_KB_4 : if (DIKEYDOWN(PI_keyboard_state, DIK_4)) return true;break; case PI_KB_5 : if (DIKEYDOWN(PI_keyboard_state, DIK_5)) return true;break; case PI_KB_6 : if (DIKEYDOWN(PI_keyboard_state, DIK_6)) return true;break; case PI_KB_7 : if (DIKEYDOWN(PI_keyboard_state, DIK_7)) return true;break; case PI_KB_8 : if (DIKEYDOWN(PI_keyboard_state, DIK_8)) return true;break; case PI_KB_9 : if (DIKEYDOWN(PI_keyboard_state, DIK_9)) return true;break; case PI_KB_ENTER : if (DIKEYDOWN(PI_keyboard_state, DIK_RETURN)) return true;break; case PI_KB_SPACE : if (DIKEYDOWN(PI_keyboard_state, DIK_SPACE)) return true;break; case PI_KB_RSHIFT : if (DIKEYDOWN(PI_keyboard_state, DIK_RSHIFT)) return true;break; case PI_KB_LSHIFT : if (DIKEYDOWN(PI_keyboard_state, DIK_LSHIFT)) return true;break; case PI_KB_RALT : if (DIKEYDOWN(PI_keyboard_state, DIK_RALT)) return true;break; case PI_KB_LALT : if (DIKEYDOWN(PI_keyboard_state, DIK_LALT)) return true;break; case PI_KB_RCONTROL : if (DIKEYDOWN(PI_keyboard_state, DIK_RCONTROL)) return true;break; case PI_KB_LCONTROL : if (DIKEYDOWN(PI_keyboard_state, DIK_LCONTROL)) return true;break; case PI_KB_PAGEUP : if (DIKEYDOWN(PI_keyboard_state, DIK_PRIOR)) return true;break; case PI_KB_PAGEDOWN : if (DIKEYDOWN(PI_keyboard_state, DIK_NEXT)) return true;break; case PI_KB_BACKSPACE : if (DIKEYDOWN(PI_keyboard_state, DIK_BACKSPACE)) return true;break; case PI_KB_NUMPADENTER : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPADENTER)) return true;break; case PI_KB_UP : if (DIKEYDOWN(PI_keyboard_state, DIK_UP)) return true;break; case PI_KB_DOWN : if (DIKEYDOWN(PI_keyboard_state, DIK_DOWN)) return true;break; case PI_KB_LEFT : if (DIKEYDOWN(PI_keyboard_state, DIK_LEFT)) return true;break; case PI_KB_RIGHT : if (DIKEYDOWN(PI_keyboard_state, DIK_RIGHT)) return true;break; case PI_KB_F1 : if (DIKEYDOWN(PI_keyboard_state, DIK_F1)) return true;break; case PI_KB_F2 : if (DIKEYDOWN(PI_keyboard_state, DIK_F2)) return true;break; case PI_KB_F3 : if (DIKEYDOWN(PI_keyboard_state, DIK_F3)) return true;break; case PI_KB_F4 : if (DIKEYDOWN(PI_keyboard_state, DIK_F4)) return true;break; case PI_KB_F5 : if (DIKEYDOWN(PI_keyboard_state, DIK_F5)) return true;break; case PI_KB_F6 : if (DIKEYDOWN(PI_keyboard_state, DIK_F6)) return true;break; case PI_KB_F7 : if (DIKEYDOWN(PI_keyboard_state, DIK_F7)) return true;break; case PI_KB_F8 : if (DIKEYDOWN(PI_keyboard_state, DIK_F8)) return true;break; case PI_KB_F9 : if (DIKEYDOWN(PI_keyboard_state, DIK_F9)) return true;break; case PI_KB_F10 : if (DIKEYDOWN(PI_keyboard_state, DIK_F10)) return true;break; case PI_KB_NUMPAD_0 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD0)) return true;break; case PI_KB_NUMPAD_1 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD1)) return true;break; case PI_KB_NUMPAD_2 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD2)) return true;break; case PI_KB_NUMPAD_3 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD3)) return true;break; case PI_KB_NUMPAD_4 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD4)) return true;break; case PI_KB_NUMPAD_5 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD5)) return true;break; case PI_KB_NUMPAD_6 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD6)) return true;break; case PI_KB_NUMPAD_7 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD7)) return true;break; case PI_KB_NUMPAD_8 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD8)) return true;break; case PI_KB_NUMPAD_9 : if (DIKEYDOWN(PI_keyboard_state, DIK_NUMPAD9)) return true;break; case PI_HIIRI_VASEN_NAPPI : if (PisteInput_Hiiri_Vasen()) return true;break; case PI_HIIRI_OIKEA_NAPPI : if (PisteInput_Hiiri_Oikea()) return true;break; case PI_OHJAIN1_VASEMMALLE : if (PisteInput_Ohjain_X(PI_PELIOHJAIN_1) < 0) return true;break; case PI_OHJAIN1_OIKEALLE : if (PisteInput_Ohjain_X(PI_PELIOHJAIN_1) > 0) return true;break; case PI_OHJAIN1_YLOS : if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_1) < 0) return true;break; case PI_OHJAIN1_ALAS : if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_1) > 0) return true;break; case PI_OHJAIN1_NAPPI1 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_1)) return true;break; case PI_OHJAIN1_NAPPI2 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_2)) return true;break; case PI_OHJAIN1_NAPPI3 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_3)) return true;break; case PI_OHJAIN1_NAPPI4 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_4)) return true;break; case PI_OHJAIN1_NAPPI5 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_5)) return true;break; case PI_OHJAIN1_NAPPI6 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_1,PI_OHJAIN_NAPPI_6)) return true;break; case PI_OHJAIN2_VASEMMALLE : if (PisteInput_Ohjain_X(PI_PELIOHJAIN_2) < 0) return true;break; case PI_OHJAIN2_OIKEALLE : if (PisteInput_Ohjain_X(PI_PELIOHJAIN_2) > 0) return true;break; case PI_OHJAIN2_YLOS : if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_2) < 0) return true;break; case PI_OHJAIN2_ALAS : if (PisteInput_Ohjain_Y(PI_PELIOHJAIN_2) > 0) return true;break; case PI_OHJAIN2_NAPPI1 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_1)) return true;break; case PI_OHJAIN2_NAPPI2 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_2)) return true;break; case PI_OHJAIN2_NAPPI3 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_3)) return true;break; case PI_OHJAIN2_NAPPI4 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_4)) return true;break; case PI_OHJAIN2_NAPPI5 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_5)) return true;break; case PI_OHJAIN2_NAPPI6 : if (PisteInput_Ohjain_Nappi(PI_PELIOHJAIN_2,PI_OHJAIN_NAPPI_6)) return true;break; default : break; } return false; } char *PisteInput_Lue_Kontrollin_Nimi(UCHAR k) { switch(k) { case PI_KB_A : return "a";break; case PI_KB_B : return "b";break; case PI_KB_C : return "c";break; case PI_KB_D : return "d";break; case PI_KB_E : return "e";break; case PI_KB_F : return "f";break; case PI_KB_G : return "g";break; case PI_KB_H : return "h";break; case PI_KB_I : return "i";break; case PI_KB_J : return "j";break; case PI_KB_K : return "k";break; case PI_KB_L : return "l";break; case PI_KB_M : return "m";break; case PI_KB_N : return "n";break; case PI_KB_O : return "o";break; case PI_KB_P : return "p";break; case PI_KB_Q : return "q";break; case PI_KB_R : return "r";break; case PI_KB_S : return "s";break; case PI_KB_T : return "t";break; case PI_KB_U : return "u";break; case PI_KB_V : return "v";break; case PI_KB_W : return "w";break; case PI_KB_X : return "x";break; case PI_KB_Y : return "y";break; case PI_KB_Z : return "z";break; case PI_KB_0 : return "0";break; case PI_KB_1 : return "1";break; case PI_KB_2 : return "2";break; case PI_KB_3 : return "3";break; case PI_KB_4 : return "4";break; case PI_KB_5 : return "5";break; case PI_KB_6 : return "6";break; case PI_KB_7 : return "7";break; case PI_KB_8 : return "8";break; case PI_KB_9 : return "9";break; case PI_KB_ENTER : return "return";break; case PI_KB_SPACE : return "space";break; case PI_KB_RSHIFT : return "right shift";break; case PI_KB_LSHIFT : return "left shift";break; case PI_KB_RALT : return "right alt";break; case PI_KB_LALT : return "left alt";break; case PI_KB_RCONTROL : return "right control";break; case PI_KB_LCONTROL : return "left control";break; case PI_KB_PAGEUP : return "page up";break; case PI_KB_PAGEDOWN : return "page down";break; case PI_KB_BACKSPACE : return "backspace";break; case PI_KB_NUMPADENTER : return "numpad enter";break; case PI_KB_UP : return "arrow up";break; case PI_KB_DOWN : return "arrow down";break; case PI_KB_LEFT : return "arrow left";break; case PI_KB_RIGHT : return "arrow right";break; case PI_KB_F1 : return "f1";break; case PI_KB_F2 : return "f2";break; case PI_KB_F3 : return "f3";break; case PI_KB_F4 : return "f4";break; case PI_KB_F5 : return "f5";break; case PI_KB_F6 : return "f6";break; case PI_KB_F7 : return "f7";break; case PI_KB_F8 : return "f8";break; case PI_KB_F9 : return "f9";break; case PI_KB_F10 : return "f10";break; case PI_KB_NUMPAD_0 : return "numpad 0";break; case PI_KB_NUMPAD_1 : return "numpad 1";break; case PI_KB_NUMPAD_2 : return "numpad 2";break; case PI_KB_NUMPAD_3 : return "numpad 3";break; case PI_KB_NUMPAD_4 : return "numpad 4";break; case PI_KB_NUMPAD_5 : return "numpad 5";break; case PI_KB_NUMPAD_6 : return "numpad 6";break; case PI_KB_NUMPAD_7 : return "numpad 7";break; case PI_KB_NUMPAD_8 : return "numpad 8";break; case PI_KB_NUMPAD_9 : return "numpad 9";break; case PI_HIIRI_VASEN_NAPPI : return "left mouse button";break; case PI_HIIRI_OIKEA_NAPPI : return "right mouse button";break; case PI_OHJAIN1_VASEMMALLE : return "joystic 1 left";break; case PI_OHJAIN1_OIKEALLE : return "joystic 1 right";break; case PI_OHJAIN1_YLOS : return "joystic 1 up";break; case PI_OHJAIN1_ALAS : return "joystic 1 down";break; case PI_OHJAIN1_NAPPI1 : return "joystic 1 button 1";break; case PI_OHJAIN1_NAPPI2 : return "joystic 1 button 2";break; case PI_OHJAIN1_NAPPI3 : return "joystic 1 button 3";break; case PI_OHJAIN1_NAPPI4 : return "joystic 1 button 4";break; case PI_OHJAIN1_NAPPI5 : return "joystic 1 button 5";break; case PI_OHJAIN1_NAPPI6 : return "joystic 1 button 6";break; case PI_OHJAIN2_VASEMMALLE : return "joystic 2 left";break; case PI_OHJAIN2_OIKEALLE : return "joystic 2 right";break; case PI_OHJAIN2_YLOS : return "joystic 2 up";break; case PI_OHJAIN2_ALAS : return "joystic 2 down";break; case PI_OHJAIN2_NAPPI1 : return "joystic 2 button 1";break; case PI_OHJAIN2_NAPPI2 : return "joystic 2 button 2";break; case PI_OHJAIN2_NAPPI3 : return "joystic 2 button 3";break; case PI_OHJAIN2_NAPPI4 : return "joystic 2 button 4";break; case PI_OHJAIN2_NAPPI5 : return "joystic 2 button 5";break; case PI_OHJAIN2_NAPPI6 : return "joystic 2 button 6";break; default : break; } return " "; } int PisteInput_Lopeta() { if (!PI_unload) { for (int i=0;i<PI_MAX_PELIOHJAIMIA;i++) if (PI_joysticks[i].lpdijoy) { PI_joysticks[i].lpdijoy->Unacquire(); PI_joysticks[i].lpdijoy->Release(); PI_joysticks[i].lpdijoy = NULL; } if (PI_lpdimouse) { PI_lpdimouse->Unacquire(); PI_lpdimouse->Release(); PI_lpdimouse = NULL; } if (PI_lpdikey) { PI_lpdikey->Unacquire(); PI_lpdikey->Release(); PI_lpdikey = NULL; } if (PI_lpdi) { PI_lpdi->Release(); PI_lpdi = NULL; } PI_unload = true; } return 0; }
[ "samuli@samuli-laptop.(none)" ]
[ [ [ 1, 925 ] ] ]
14520eb6224fd0838e6ca6c178a295980c4c7809
29c5bc6757634a26ac5103f87ed068292e418d74
/src/tlclasses/CSubMenu.h
626e6a7523c8cf7b76441990938a08aaae019193
[]
no_license
drivehappy/tlapi
d10bb75f47773e381e3ba59206ff50889de7e66a
56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9
refs/heads/master
2021-03-19T07:10:57.343889
2011-04-18T22:58:29
2011-04-18T22:58:29
32,191,364
5
0
null
null
null
null
UTF-8
C++
false
false
362
h
#pragma once #include "CRunicCore.h" namespace TLAPI { #pragma pack(1) struct CGameUI; // // Unsure of the breakoff on the derived classes here // This is an abstract class struct CSubMenu : CRunicCore { PVOID unk0; PVOID vtable_iInventoryListener; PVOID CEGUISheetPropertySet[7]; }; #pragma pack() };
[ "drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522" ]
[ [ [ 1, 25 ] ] ]
e4a2b4b7590d02d5edede396fc70bf1f209491e9
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXDragDockContext.h
4a876bdc3a78894f472e830a3f002e9eba81ceab
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,061
h
// =================================================================================== // Class Specification : COXDragDockContext // =================================================================================== // Header file : OXDragDockContext.h // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // Some portions Copyright (C)1994-5 Micro Focus Inc, 2465 East Bayshore Rd, Palo Alto, CA 94303. // ////////////////////////////////////////////////////////////////////////// // Properties: // NO Abstract class (does not have any objects) // YES Derived from CDockContext // NO Is a Cwnd. // NO Two stage creation (constructor & Create()) // NO Has a message map // NO Needs a resource (template) // NO Persistent objects (saveable on disk) // NO Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // // This replaces the MFC CDockContext class. It provides the "dragging" user interface, // and includes some extra features that try to indicate exactly where a bar will // dock. // // The gateway MFC gives us to work with is: // 1) CControlBar::EnableDocking() creates the dock context for the control bar - so it's // important to use the COX...Frame.. implementation of EnableDocking(). // // 2) Other than the constructor/destructor, the only function access outside this class // is to StartDrag(CPoint pt), called when we want to start dragging the control bar. // // The other important tie-ins are the call to Dock/Float control bar which we need to handle // with the same interpretation of parameters as the existing MFC implementation. // Remark: // // Prerequisites (necessary conditions): // *** ///////////////////////////////////////////////////////////////////////////// #ifndef __DRAGDOCKCTXT_H__ #define __DRAGDOCKCTXT_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" #include <afxpriv.h> class COXSizeDockBar; class OX_CLASS_DECL COXDragDockContext : public CDockContext { // Data members ------------------------------------------------------------- public: CRect m_rectDragDock; // rectangle indicating where we'll dock protected: CRect m_rectDragHorzAlone; CRect m_rectDragVertAlone; COXSizeDockBar* m_pTargetDockBar; CPoint m_ptStart; private : // Member functions --------------------------------------------------------- public: COXDragDockContext(CControlBar* pBar); // --- In : // --- Out : // --- Returns : // --- Effect : Constructor of object // It will initialize the internal state virtual void StartDrag(CPoint pt); // --- In : pt : point where dragging starts // --- Out : // --- Returns : // --- Effect : only thing called externally virtual void ToggleDocking(); // --- In : // --- Out : // --- Returns : // --- Effect : called to toggle docking void Move(CPoint pt); // --- In : pt : point to where window has moved // --- Out : // --- Returns : // --- Effect : called when mouse has moved void EndDrag(); // --- In : // --- Out : // --- Returns : // --- Effect : drop window void CancelDrag(); // --- In : // --- Out : // --- Returns : // --- Effect : drag cancelled void OnKey(int nChar, BOOL bDown); // --- In : // --- Out : // --- Returns : // --- Effect : keyboardhit BOOL Track(); // --- In : // --- Out : // --- Returns : // --- Effect : called when window is dragged void DrawFocusRect(BOOL bRemoveRect = FALSE); // --- In : bRemoveRect : whether or not to erase the previous focus rect // --- Out : // --- Returns : // --- Effect : draws a rectangle to indicate focus void UpdateState(BOOL* pFlag, BOOL bNewValue); // --- In : // --- Out : // --- Returns : // --- Effect : Update the focus state of the dragged window DWORD CanDock(); // --- In : // --- Out : // --- Returns :whether or not the window can be docked // --- Effect : CDockBar* GetDockBar(); // --- In : // --- Out : // --- Returns : the dockbar where docking will take place // --- Effect : virtual ~COXDragDockContext(); // --- In : // --- Out : // --- Returns : // --- Effect : Destructor of object protected: private: }; #endif // __DRAGDOCKCTXT_H__
[ [ [ 1, 175 ] ] ]
bb73aa419fe5876f0928763306c4a1f18ba0bf25
521721c2e095daf757ad62a267b1c0f724561935
/bsScene.h
a471a446594b8a9fc480f1125815fb726f65fbd8
[]
no_license
MichaelSPG/boms
251922d78f2db85ece495e067bd56a1e9fae14b1
23a13010e0aaa79fea3b7cf1b23e2faab02fa5d4
refs/heads/master
2021-01-10T16:23:51.722062
2011-12-08T00:04:33
2011-12-08T00:04:33
48,052,727
1
0
null
null
null
null
UTF-8
C++
false
false
4,326
h
#pragma once #include <vector> #include <Common/Base/hkBase.h> #include "bsContactCounter.h" class bsCamera; class bsDx11Renderer; class bsRenderable; class bsHavokManager; class hkpWorld; struct bsCoreCInfo; struct bsFrameStatistics; class hkJobQueue; class bsEntity; /* A scene represents a collection of entities. A scene must always contain at least one camera (created by default). All the entities in a scene is owned by that scene, and upon destruction of a scene, all of the entities in it will also be destroyed. If you do not want specific entities to be destroyed when the scene is destroyed, remove them before destroying the scene by calling removeEntity(). */ class bsScene { public: bsScene(bsDx11Renderer* renderer, bsHavokManager* havokManager, const bsCoreCInfo& cInfo); ~bsScene(); /* Adds an entity to the scene, and to the physics world if it contains physics components. */ void addEntity(bsEntity& entity); /* Removes an entity from the scene, and from the physical world if it contains physics components. */ void removeEntity(bsEntity& entityToRemove); inline bsDx11Renderer* getRenderer() const { return mDx11Renderer; } inline bsCamera* getCamera() const { return mCamera; } /* Returns a vector containing every entity currently in the scene. */ inline const std::vector<bsEntity*>& getEntities() const { return mEntities; } inline hkpWorld* getPhysicsWorld() const { return mPhysicsWorld; } void update(float deltaTimeMs, bsFrameStatistics& framStatistics); /* Enabled or disables stepping of physics. This can be used to closely inspect the state of the world during a frame without the physics affecting objects, making it easier to take screenshots or similar of explosions, etc. */ inline void setStepPhysicsEnabled(bool stepPhysics) { mStepPhysics = stepPhysics; } inline bool isStepPhysicsEnabled() const { return mStepPhysics; } /* Sets the time scale of the physics world. Making sudden non-small changes to this value is not encouraged as it will reduce the stability of the simulation. Larger values (over 1) will also reduce the stability. Default is 1. */ inline void setTimeScale(float newTimeScale) { mTimeScale = newTimeScale; } inline float getTimeScale() const { return mTimeScale; } /* Sets the amount of physics steps to perform per second, and the size of each step in ms. The step size will set to 1000 / stepsPerSecond. Making sudden non-small changes to this value is not encouraged as it will reduce the stability of the simulation. */ void setPhysicsFrequency(float stepsPerSecond) { mPhysicsFrequency = stepsPerSecond; mPhysicsStepSizeMs = 1000.0f / stepsPerSecond; } float getPhysicsFrequency() const { return mPhysicsFrequency; } private: /* This recursively removes entityToRemove and all of its children, all of the children's children, and so on, from the scene. This function can also delete all the entities it removes. */ void removeEntityAndChildrenRecursively(bsEntity& entityToRemove, bool deleteAfterRemoving); /* Increments the amount of created entities and returns it. Used to assign unique IDs to entities. */ inline unsigned int getNewId() { return ++mNumCreatedEntities; } /* Creates a Havok world. */ void createPhysicsWorld(hkJobQueue& jobQueue); /* Synchronizes all active (non-sleeping) rigid bodies with their entities. The two parameters are output parameters and will contain information about the current state of the physics simulation. */ void synchronizeActiveEntities(unsigned int* totalActiveRigidBodies, unsigned int* totalActiveSimulationIslands); bsCamera* mCamera; std::vector<bsEntity*> mEntities; unsigned int mNumCreatedEntities; bsDx11Renderer* mDx11Renderer; hkpWorld* mPhysicsWorld; bsContactCounter mContactCounter; bsHavokManager* mHavokManager; //Whether physics should be stepped. bool mStepPhysics; float mTimeScale; //Number of physics steps to perform per second. float mPhysicsFrequency; //Size of each physics step, in milliseconds. float mPhysicsStepSizeMs; };
[ "ivarboms@gTest/Application.objmail.com", "[email protected]" ]
[ [ [ 1, 6 ], [ 9, 14 ], [ 18, 19 ], [ 27, 30 ], [ 33, 35 ], [ 39, 39 ], [ 41, 41 ], [ 44, 44 ], [ 46, 56 ], [ 61, 61 ], [ 63, 69 ], [ 71, 71 ], [ 119, 119 ], [ 129, 131 ], [ 133, 134 ], [ 139, 139 ], [ 142, 142 ], [ 145, 148 ], [ 150, 150 ], [ 152, 153 ], [ 156, 157 ], [ 167, 167 ] ], [ [ 7, 8 ], [ 15, 17 ], [ 20, 26 ], [ 31, 32 ], [ 36, 38 ], [ 40, 40 ], [ 42, 43 ], [ 45, 45 ], [ 57, 60 ], [ 62, 62 ], [ 70, 70 ], [ 72, 118 ], [ 120, 128 ], [ 132, 132 ], [ 135, 138 ], [ 140, 141 ], [ 143, 144 ], [ 149, 149 ], [ 151, 151 ], [ 154, 155 ], [ 158, 166 ] ] ]
0d2475d3ee3ff8eca89d3149f919cff291e996b1
8aa65aef3daa1a52966b287ffa33a3155e48cc84
/Source/Common/TimeCounter.h
a70996cd9e8cc22e181da15de53696689e89f31a
[]
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
1,153
h
#pragma once namespace P3D { /* High precision time counter. */ class TimeCounter { static uint64 GetTickCount(); public: TimeCounter(); /* Reset time counting. */ void Reset() { _lastTickTime = 0; _startTick = GetTickCount(); _lastTick = _startTick; _ticks = 0; } float Tick() { uint64 tick = GetTickCount(); _lastTickTime=float(((tick - _lastTick)*1000.0f)/_ticksPerSec); _lastTick=tick; _ticks++; return _lastTickTime; } double GetTotalTime() const { return double(((_lastTick - _startTick)*1000.0f)/_ticksPerSec); } float GetLastTick() const { return _lastTickTime; } /* Return count of calls to Tick since call to Reset. */ uint GetTicks() const { return _ticks; } protected: float _lastTickTime; uint _ticks; uint64 _startTick; uint64 _lastTick; uint64 _ticksPerSec; }; }
[ "vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1" ]
[ [ [ 1, 51 ] ] ]
22346699f479df2b75584511fdb2bcd2159bd2f4
a96b15c6a02225d27ac68a7ed5f8a46bddb67544
/SetGame/GazaFrameSheetCollection.cpp
c1e2e81ad6f5b31649ff3402fe2107dbef7db54b
[]
no_license
joelverhagen/Gaza-2D-Game-Engine
0dca1549664ff644f61fe0ca45ea6efcbad54591
a3fe5a93e5d21a93adcbd57c67c888388b402938
refs/heads/master
2020-05-15T05:08:38.412819
2011-04-03T22:22:01
2011-04-03T22:22:01
1,519,417
3
0
null
null
null
null
UTF-8
C++
false
false
3,496
cpp
#include "GazaFrameSheetCollection.hpp" namespace Gaza { FrameSheetCollection::FrameSheetCollection() { } FrameSheetCollection::~FrameSheetCollection() { for(unsigned int i = 0; i < frameSheets.size(); i++) { delete frameSheets[i]; } frameSheets.clear(); } void FrameSheetCollection::addFrameSheet(FrameSheet * frameSheet) { frameSheets.push_back(frameSheet); } Frame * FrameSheetCollection::getFrame(const std::string &name) { Frame * frame = 0; for(unsigned int i = 0; i < frameSheets.size(); i++) { frame = frameSheets[i]->getFrame(name); if(frame != 0) { break; } } return frame; } std::vector<Frame *> FrameSheetCollection::getAnimationFrameList(const std::string &name) { if(animationFrameLists.find(name) == animationFrameLists.end()) { return std::vector<Frame *>(); } return animationFrameLists[name]; } bool FrameSheetCollection::addAnimationFrameList(const std::string &name, const std::vector<Frame *> &frames) { if(animationFrameLists.find(name) == animationFrameLists.end()) { Logger::getInstance()->write("A list of Frames with name \""+name+"\" does not exist."); return false; } for(unsigned int i = 0; i < frames.size(); i++) { addAnimationFrame(name, frames[i]); } return true; } bool FrameSheetCollection::addAnimationFrameList(const std::string &name, const std::vector<std::string> &frameNames) { if(animationFrameLists.find(name) == animationFrameLists.end()) { Logger::getInstance()->write("A list of Frames with name \""+name+"\" does not exist."); return false; } for(unsigned int i = 0; i < frameNames.size(); i++) { addAnimationFrame(name, frameNames[i]); } return true; } bool FrameSheetCollection::newAnimationFrameList(const std::string &name) { if(animationFrameLists.find(name) != animationFrameLists.end()) { Logger::getInstance()->write("A list of Frames with name \""+name+"\" already exists."); return false; } animationFrameLists[name] = std::vector<Frame *>(); return true; } bool FrameSheetCollection::addAnimationFrame(const std::string &name, Frame * frame) { if(animationFrameLists.find(name) == animationFrameLists.end()) { Logger::getInstance()->write("A list of Frames with name \""+name+"\" does not exist."); return false; } animationFrameLists[name].push_back(frame); return true; } bool FrameSheetCollection::addAnimationFrame(const std::string &name, const std::string &frameName) { Frame * frame = getFrame(frameName); if(frame == 0) { return false; } return addAnimationFrame(name, frame); } int FrameSheetCollection::getFrameSheetCount() { return frameSheets.size(); } int FrameSheetCollection::getFrameCount() { int sum = 0; for(unsigned int i = 0; i < frameSheets.size(); i++) { sum += frameSheets[i]->getFrameCount(); } return sum; } std::vector<std::string> FrameSheetCollection::getFrameNames() { std::vector<std::string> names; for(unsigned int i = 0; i < frameSheets.size(); i++) { std::vector<std::string> currentNames = frameSheets[i]->getFrameNames(); for(unsigned int j = 0; j < currentNames.size(); j++) { names.push_back(currentNames[j]); } } return names; } void FrameSheetCollection::clearFrameSheets() { frameSheets.clear(); } }
[ [ [ 1, 148 ] ] ]
d9c522dd2e20c2935c310ad4c7ee2713f80dab79
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/ToolsAndUtilities/Localise/HelloWorld_Application.cpp
9288bc1dc55798794b9b6974b000a94bdf0c9ee2
[]
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
1,105
cpp
// HelloWorld_CExampleApplication.cpp // ---------------------------------- // // Copyright (c) 2000 Symbian Ltd. All rights reserved. // //////////////////////////////////////////////////////////////////////// // // Source file for the implementation of the // application class - CExampleApplication // //////////////////////////////////////////////////////////////////////// #include "HelloWorld.h" const TUid KUidHelloWorld = { 0xE800005A }; // The function is called by the UI framework to ask for the // application's UID. The returned value is defined by the // constant KUidHelloWorlde and must match the second value // defined in the project definition file. // TUid CExampleApplication::AppDllUid() const { return KUidHelloWorld; } // This function is called by the UI framework at // application start-up. It creates an instance of the // document class. // CApaDocument* CExampleApplication::CreateDocumentL() { return new (ELeave) CExampleDocument(*this); }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 36 ] ] ]
fce84b594842167db2595dcc6eff892290eb9160
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/PlasmaRound.cpp
ffbb9183d13913af341bf1ae5d47caca0e75f224
[]
no_license
danishcake/FusionForever
8fc3b1a33ac47177666e6ada9d9d19df9fc13784
186d1426fe6b3732a49dfc8b60eb946d62aa0e3b
refs/heads/master
2016-09-05T16:16:02.040635
2010-04-24T11:05:10
2010-04-24T11:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,751
cpp
#include "StdAfx.h" #include "PlasmaRound.h" #include "Puff.h" #include "Ricochet.h" bool PlasmaRound::initialised_ = false; int PlasmaRound::fill_dl_ = 0; int PlasmaRound::fill_verts_index_ = 0; PlasmaRound::PlasmaRound(Vector3f _position) :Projectile() { if(!initialised_) { InitialiseGraphics(); initialised_ = true; } fill_.GetFillVerts() = Datastore::Instance().GetVerts(fill_verts_index_); fill_.SetDisplayList(fill_dl_); fill_.SetFillColor(GLColor(255, 255, 255)); damage_ = 45.0; lifetime_ = 4.0; velocity_.y = 450; position_ = _position; mass_ = 25; } PlasmaRound::~PlasmaRound(void) { } void PlasmaRound::InitialiseGraphics() { boost::shared_ptr<std::vector<Vector3f>> temp_fill = boost::shared_ptr<std::vector<Vector3f>>(new std::vector<Vector3f>()); temp_fill->push_back(Vector3f( 1.5f, -1.5f, 0)); temp_fill->push_back(Vector3f( 1.5f, 4, 0)); temp_fill->push_back(Vector3f(-1.5f, 4, 0)); temp_fill->push_back(Vector3f( 1.5f, 4, 0)); temp_fill->push_back(Vector3f(-1.5f, 4, 0)); temp_fill->push_back(Vector3f(-1.5f, -1.5f, 0)); fill_verts_index_ = Datastore::Instance().AddVerts(temp_fill); fill_dl_ = Filled::CreateFillDisplayList(temp_fill); } void PlasmaRound::Hit(std::vector<Decoration_ptr>& _spawn, std::vector<Projectile_ptr>& /*_projectile_spawn*/) { Decoration_ptr spark = Decoration_ptr(new Ricochet(angle_ , false)); spark->SetPosition(position_); Decoration_ptr spark2 = Decoration_ptr(new Ricochet(angle_ , false)); spark2->SetPosition(position_); Decoration_ptr puff = Decoration_ptr(new Puff()); puff->SetPosition(position_); _spawn.push_back(puff); _spawn.push_back(spark); _spawn.push_back(spark2); }
[ "EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "[email protected]" ]
[ [ [ 1, 47 ], [ 49, 61 ] ], [ [ 48, 48 ] ] ]
1d00f3bc456baac011c5a0e79c52ccd2ae8b263a
45c0d7927220c0607531d6a0d7ce49e6399c8785
/GlobeFactory/src/gfx/material_def/animated.cc
7fe0f16ec40c935230f79705028269bc1877b7db
[]
no_license
wavs/pfe-2011-scia
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
refs/heads/master
2021-01-25T07:08:36.552423
2011-01-17T20:23:43
2011-01-17T20:23:43
39,025,134
0
0
null
null
null
null
UTF-8
C++
false
false
4,120
cc
#include "animated.hh" #include "../material_mng.hh" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ AnimatedMaterial::AnimatedMaterial(const std::string& parFilename, unsigned parFrameCount, float parFrameTime, const Timer* parTimer) : MultiMaterial(parFilename, MaterialEnum::ANIMATED, parFrameCount), MFrameTime(parFrameTime), MLastTime(0.0f), MCur(0), MTimer(parTimer) { } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ AnimatedMaterial::~AnimatedMaterial() { for (unsigned i = 0; i < MSize; ++i) MaterialMng::get()->UnloadMaterial(MChilds[i]); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void AnimatedMaterial::PreRender() { if (MTimer->ElapsSince(MLastTime) >= MFrameTime) { MCur = (MCur + 1) % MSize; MLastTime = MTimer->GetTimeFromCreation(); } MaterialMng& matMng = *MaterialMng::get(); matMng.PreRenderForMaterialType(matMng.GetMaterialType(MChilds[MCur])); matMng.PreRenderForMaterial(MChilds[MCur]); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void AnimatedMaterial::PostRender() { MaterialMng& matMng = *MaterialMng::get(); matMng.PostRenderForMaterial(MChilds[MCur]); matMng.PostRenderForMaterialType(matMng.GetMaterialType(MChilds[MCur])); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ AnimatedMaterialDescriptor::AnimatedMaterialDescriptor() : MTimer(Clock::get()->CreateTimer()) { } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ AnimatedMaterialDescriptor::~AnimatedMaterialDescriptor() { Clock::get()->DeleteTimer(MTimer); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ AnimatedMaterial* AnimatedMaterialDescriptor::Load(unsigned parCfgFileId) const { ConfigMng* cfgMng = ConfigMng::get(); const int* frameCount = cfgMng->GetOptionInt(parCfgFileId, "frameCount"); const float* frameTime = cfgMng->GetOptionFloat(parCfgFileId, "frameTime"); if (frameCount == NULL || *frameCount <= 0) { LOG_ERROR("AnimMaterial", cfgMng->GetFilename(parCfgFileId) + " : bad frameCount variable"); return NULL; } if (frameTime == NULL) { LOG_ERROR("AnimMaterial", cfgMng->GetFilename(parCfgFileId) + " : no frameTime variable"); return NULL; } AnimatedMaterial* mat = new AnimatedMaterial(cfgMng->GetFilename(parCfgFileId), *frameCount, *frameTime, MTimer); for (int i = 0; i < *frameCount; ++i) { const std::string* cur = cfgMng->GetOptionStr(parCfgFileId, misc::ToString(i)); if (cur == NULL) { LOG_ERROR("AnimMaterial", cfgMng->GetFilename(parCfgFileId) + " : frame(" + misc::ToString(i) + ") badly defined"); return NULL; } mat->SetFrame(static_cast<unsigned>(i), MaterialMng::get()->LoadMaterial(*cur)); } return mat; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------
[ "creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc" ]
[ [ [ 1, 113 ] ] ]
c2b829799504951159f1474dbebb183aa536d2dd
7643faa5275b93395ac1f5ab1f3b1983710a3d1b
/libspeedtest/preferences.h
3a7af653de385e9aefe91a19f137f0cc20555e63
[]
no_license
AlexGidarakos/QSpeedTest
6ff4d3d12587ccd138d50c209a71fa0d17652e3d
576daf9598a6acded5f4d6b6b0b6071a1b843de3
refs/heads/master
2020-12-24T21:27:28.170518
2010-08-01T18:55:01
2010-08-01T18:55:01
59,162,063
2
0
null
null
null
null
UTF-8
C++
false
false
1,346
h
/* Copyright 2010 Aleksandros Gidarakos This file is part of QSpeedTest. QSpeedTest 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. QSpeedTest 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 QSpeedTest. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PREFERENCES_H #define PREFERENCES_H #include "libspeedtest_global.h" #include <QtCore/QSettings> #include <QtCore/QFile> class LIBSPEEDTEST_EXPORT Preferences : public QSettings { Q_OBJECT public: explicit Preferences(QSettings::Format format, QSettings::Scope scope, const QString &company, const QString &program, QObject *parent) : QSettings(format, scope, company, program, parent) {} void init(); private: inline bool _exists() const { return QFile::exists(fileName()); } bool _loadOk(); bool _restoreEmbeddedOk(); signals: void message(QString); }; #endif // PREFERENCES_H
[ [ [ 1, 42 ] ] ]
0bedee0ec57736fd5d934a9c4ca278e10e2e02e2
f64b888affed8c6db2cc56d4618c72c923fe1a7c
/include/lockmgr/config.hxx
3845d983dc862feb295b1013c78bb9dbfa622e29
[ "BSD-2-Clause" ]
permissive
wilx/lockmgr
64ca319f87ccf96214d9c4a3e1095f783fb355d8
9932287c6a49199730abfb4332f85c9ca05d9511
refs/heads/master
2021-01-10T02:19:35.039497
2008-06-09T11:24:32
2008-06-09T11:24:32
36,984,337
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
hxx
// Copyright (c) 2008, Václav Haisman // // 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. // // 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. #if ! defined (LOCKMANAGER_LOCKMGR_INTERNAL_CONFIG_HXX) #define LOCKMANAGER_LOCKMGR_INTERNAL_CONFIG_HXX #if defined (__unix) || defined (__unix__) # define LOCKMANAGER_UNIX 1 #endif #if defined (__CYGWIN__) || defined (__CYGWIN32__) # if ! defined (WIN32) # define WIN32 # endif #endif #endif // LOCKMANAGER_LOCKMGR_INTERNAL_CONFIG_HXX
[ [ [ 1, 42 ] ] ]
a8f2372fa236530e12ba540938a20e111cf8a719
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/gccxml_bin/v09/win32/share/gccxml-0.9/Vc9/PlatformSDK/PropIdl.h
7a1c9d3c2d08cfccbe3d9c09a65fc74c7184ba63
[]
no_license
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
39,287
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0499 */ /* Compiler settings for propidl.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __propidl_h__ #define __propidl_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IPropertyStorage_FWD_DEFINED__ #define __IPropertyStorage_FWD_DEFINED__ typedef interface IPropertyStorage IPropertyStorage; #endif /* __IPropertyStorage_FWD_DEFINED__ */ #ifndef __IPropertySetStorage_FWD_DEFINED__ #define __IPropertySetStorage_FWD_DEFINED__ typedef interface IPropertySetStorage IPropertySetStorage; #endif /* __IPropertySetStorage_FWD_DEFINED__ */ #ifndef __IEnumSTATPROPSTG_FWD_DEFINED__ #define __IEnumSTATPROPSTG_FWD_DEFINED__ typedef interface IEnumSTATPROPSTG IEnumSTATPROPSTG; #endif /* __IEnumSTATPROPSTG_FWD_DEFINED__ */ #ifndef __IEnumSTATPROPSETSTG_FWD_DEFINED__ #define __IEnumSTATPROPSETSTG_FWD_DEFINED__ typedef interface IEnumSTATPROPSETSTG IEnumSTATPROPSETSTG; #endif /* __IEnumSTATPROPSETSTG_FWD_DEFINED__ */ /* header files for imported files */ #include "objidl.h" #include "oaidl.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_propidl_0000_0000 */ /* [local] */ //+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (c) Microsoft Corporation. All rights reserved. // //-------------------------------------------------------------------------- #if ( _MSC_VER >= 800 ) #if _MSC_VER >= 1200 #pragma warning(push) #endif #pragma warning(disable:4201) /* Nameless struct/union */ #pragma warning(disable:4237) /* obsolete member named 'bool' */ #endif #if ( _MSC_VER >= 1020 ) #pragma once #endif typedef struct tagVersionedStream { GUID guidVersion; IStream *pStream; } VERSIONEDSTREAM; typedef struct tagVersionedStream *LPVERSIONEDSTREAM; // Flags for IPropertySetStorage::Create #define PROPSETFLAG_DEFAULT ( 0 ) #define PROPSETFLAG_NONSIMPLE ( 1 ) #define PROPSETFLAG_ANSI ( 2 ) // (This flag is only supported on StgCreatePropStg & StgOpenPropStg #define PROPSETFLAG_UNBUFFERED ( 4 ) // (This flag causes a version-1 property set to be created #define PROPSETFLAG_CASE_SENSITIVE ( 8 ) // Flags for the reservied PID_BEHAVIOR property #define PROPSET_BEHAVIOR_CASE_SENSITIVE ( 1 ) #ifdef MIDL_PASS // This is the PROPVARIANT definition for marshaling. typedef struct tag_inner_PROPVARIANT PROPVARIANT; #else // This is the standard C layout of the PROPVARIANT. typedef struct tagPROPVARIANT PROPVARIANT; #endif typedef struct tagCAC { ULONG cElems; CHAR *pElems; } CAC; typedef struct tagCAUB { ULONG cElems; UCHAR *pElems; } CAUB; typedef struct tagCAI { ULONG cElems; SHORT *pElems; } CAI; typedef struct tagCAUI { ULONG cElems; USHORT *pElems; } CAUI; typedef struct tagCAL { ULONG cElems; LONG *pElems; } CAL; typedef struct tagCAUL { ULONG cElems; ULONG *pElems; } CAUL; typedef struct tagCAFLT { ULONG cElems; FLOAT *pElems; } CAFLT; typedef struct tagCADBL { ULONG cElems; DOUBLE *pElems; } CADBL; typedef struct tagCACY { ULONG cElems; CY *pElems; } CACY; typedef struct tagCADATE { ULONG cElems; DATE *pElems; } CADATE; typedef struct tagCABSTR { ULONG cElems; BSTR *pElems; } CABSTR; typedef struct tagCABSTRBLOB { ULONG cElems; BSTRBLOB *pElems; } CABSTRBLOB; typedef struct tagCABOOL { ULONG cElems; VARIANT_BOOL *pElems; } CABOOL; typedef struct tagCASCODE { ULONG cElems; SCODE *pElems; } CASCODE; typedef struct tagCAPROPVARIANT { ULONG cElems; PROPVARIANT *pElems; } CAPROPVARIANT; typedef struct tagCAH { ULONG cElems; LARGE_INTEGER *pElems; } CAH; typedef struct tagCAUH { ULONG cElems; ULARGE_INTEGER *pElems; } CAUH; typedef struct tagCALPSTR { ULONG cElems; LPSTR *pElems; } CALPSTR; typedef struct tagCALPWSTR { ULONG cElems; LPWSTR *pElems; } CALPWSTR; typedef struct tagCAFILETIME { ULONG cElems; FILETIME *pElems; } CAFILETIME; typedef struct tagCACLIPDATA { ULONG cElems; CLIPDATA *pElems; } CACLIPDATA; typedef struct tagCACLSID { ULONG cElems; CLSID *pElems; } CACLSID; #ifdef MIDL_PASS // This is the PROPVARIANT padding layout for marshaling. typedef BYTE PROPVAR_PAD1; typedef BYTE PROPVAR_PAD2; typedef ULONG PROPVAR_PAD3; #else // This is the standard C layout of the structure. typedef WORD PROPVAR_PAD1; typedef WORD PROPVAR_PAD2; typedef WORD PROPVAR_PAD3; #define tag_inner_PROPVARIANT #endif #ifndef MIDL_PASS struct tagPROPVARIANT { union { #endif struct tag_inner_PROPVARIANT { VARTYPE vt; PROPVAR_PAD1 wReserved1; PROPVAR_PAD2 wReserved2; PROPVAR_PAD3 wReserved3; /* [switch_type] */ union { /* Empty union arm */ CHAR cVal; UCHAR bVal; SHORT iVal; USHORT uiVal; LONG lVal; ULONG ulVal; INT intVal; UINT uintVal; LARGE_INTEGER hVal; ULARGE_INTEGER uhVal; FLOAT fltVal; DOUBLE dblVal; VARIANT_BOOL boolVal; // _VARIANT_BOOL bool; SCODE scode; CY cyVal; DATE date; FILETIME filetime; CLSID *puuid; CLIPDATA *pclipdata; BSTR bstrVal; BSTRBLOB bstrblobVal; BLOB blob; LPSTR pszVal; LPWSTR pwszVal; IUnknown *punkVal; IDispatch *pdispVal; IStream *pStream; IStorage *pStorage; LPVERSIONEDSTREAM pVersionedStream; LPSAFEARRAY parray; CAC cac; CAUB caub; CAI cai; CAUI caui; CAL cal; CAUL caul; CAH cah; CAUH cauh; CAFLT caflt; CADBL cadbl; CABOOL cabool; CASCODE cascode; CACY cacy; CADATE cadate; CAFILETIME cafiletime; CACLSID cauuid; CACLIPDATA caclipdata; CABSTR cabstr; CABSTRBLOB cabstrblob; CALPSTR calpstr; CALPWSTR calpwstr; CAPROPVARIANT capropvar; CHAR *pcVal; UCHAR *pbVal; SHORT *piVal; USHORT *puiVal; LONG *plVal; ULONG *pulVal; INT *pintVal; UINT *puintVal; FLOAT *pfltVal; DOUBLE *pdblVal; VARIANT_BOOL *pboolVal; DECIMAL *pdecVal; SCODE *pscode; CY *pcyVal; DATE *pdate; BSTR *pbstrVal; IUnknown **ppunkVal; IDispatch **ppdispVal; LPSAFEARRAY *pparray; PROPVARIANT *pvarVal; } ; } ; #ifndef MIDL_PASS DECIMAL decVal; }; }; #endif #ifdef MIDL_PASS // This is the LPPROPVARIANT definition for marshaling. typedef struct tag_inner_PROPVARIANT *LPPROPVARIANT; typedef const PROPVARIANT *REFPROPVARIANT; #else // This is the standard C layout of the PROPVARIANT. typedef struct tagPROPVARIANT * LPPROPVARIANT; #ifndef _REFPROPVARIANT_DEFINED #define _REFPROPVARIANT_DEFINED #ifdef __cplusplus #define REFPROPVARIANT const PROPVARIANT & #else #define REFPROPVARIANT const PROPVARIANT * __MIDL_CONST #endif #endif #endif // MIDL_PASS // Reserved global Property IDs #define PID_DICTIONARY ( 0 ) #define PID_CODEPAGE ( 0x1 ) #define PID_FIRST_USABLE ( 0x2 ) #define PID_FIRST_NAME_DEFAULT ( 0xfff ) #define PID_LOCALE ( 0x80000000 ) #define PID_MODIFY_TIME ( 0x80000001 ) #define PID_SECURITY ( 0x80000002 ) #define PID_BEHAVIOR ( 0x80000003 ) #define PID_ILLEGAL ( 0xffffffff ) // Range which is read-only to downlevel implementations #define PID_MIN_READONLY ( 0x80000000 ) #define PID_MAX_READONLY ( 0xbfffffff ) // Property IDs for the DiscardableInformation Property Set #define PIDDI_THUMBNAIL 0x00000002L // VT_BLOB // Property IDs for the SummaryInformation Property Set #define PIDSI_TITLE 0x00000002L // VT_LPSTR #define PIDSI_SUBJECT 0x00000003L // VT_LPSTR #define PIDSI_AUTHOR 0x00000004L // VT_LPSTR #define PIDSI_KEYWORDS 0x00000005L // VT_LPSTR #define PIDSI_COMMENTS 0x00000006L // VT_LPSTR #define PIDSI_TEMPLATE 0x00000007L // VT_LPSTR #define PIDSI_LASTAUTHOR 0x00000008L // VT_LPSTR #define PIDSI_REVNUMBER 0x00000009L // VT_LPSTR #define PIDSI_EDITTIME 0x0000000aL // VT_FILETIME (UTC) #define PIDSI_LASTPRINTED 0x0000000bL // VT_FILETIME (UTC) #define PIDSI_CREATE_DTM 0x0000000cL // VT_FILETIME (UTC) #define PIDSI_LASTSAVE_DTM 0x0000000dL // VT_FILETIME (UTC) #define PIDSI_PAGECOUNT 0x0000000eL // VT_I4 #define PIDSI_WORDCOUNT 0x0000000fL // VT_I4 #define PIDSI_CHARCOUNT 0x00000010L // VT_I4 #define PIDSI_THUMBNAIL 0x00000011L // VT_CF #define PIDSI_APPNAME 0x00000012L // VT_LPSTR #define PIDSI_DOC_SECURITY 0x00000013L // VT_I4 // Property IDs for the DocSummaryInformation Property Set #define PIDDSI_CATEGORY 0x00000002 // VT_LPSTR #define PIDDSI_PRESFORMAT 0x00000003 // VT_LPSTR #define PIDDSI_BYTECOUNT 0x00000004 // VT_I4 #define PIDDSI_LINECOUNT 0x00000005 // VT_I4 #define PIDDSI_PARCOUNT 0x00000006 // VT_I4 #define PIDDSI_SLIDECOUNT 0x00000007 // VT_I4 #define PIDDSI_NOTECOUNT 0x00000008 // VT_I4 #define PIDDSI_HIDDENCOUNT 0x00000009 // VT_I4 #define PIDDSI_MMCLIPCOUNT 0x0000000A // VT_I4 #define PIDDSI_SCALE 0x0000000B // VT_BOOL #define PIDDSI_HEADINGPAIR 0x0000000C // VT_VARIANT | VT_VECTOR #define PIDDSI_DOCPARTS 0x0000000D // VT_LPSTR | VT_VECTOR #define PIDDSI_MANAGER 0x0000000E // VT_LPSTR #define PIDDSI_COMPANY 0x0000000F // VT_LPSTR #define PIDDSI_LINKSDIRTY 0x00000010 // VT_BOOL // FMTID_MediaFileSummaryInfo - Property IDs #define PIDMSI_EDITOR 0x00000002L // VT_LPWSTR #define PIDMSI_SUPPLIER 0x00000003L // VT_LPWSTR #define PIDMSI_SOURCE 0x00000004L // VT_LPWSTR #define PIDMSI_SEQUENCE_NO 0x00000005L // VT_LPWSTR #define PIDMSI_PROJECT 0x00000006L // VT_LPWSTR #define PIDMSI_STATUS 0x00000007L // VT_UI4 #define PIDMSI_OWNER 0x00000008L // VT_LPWSTR #define PIDMSI_RATING 0x00000009L // VT_LPWSTR #define PIDMSI_PRODUCTION 0x0000000AL // VT_FILETIME (UTC) #define PIDMSI_COPYRIGHT 0x0000000BL // VT_LPWSTR // PIDMSI_STATUS value definitions enum PIDMSI_STATUS_VALUE { PIDMSI_STATUS_NORMAL = 0, PIDMSI_STATUS_NEW = ( PIDMSI_STATUS_NORMAL + 1 ) , PIDMSI_STATUS_PRELIM = ( PIDMSI_STATUS_NEW + 1 ) , PIDMSI_STATUS_DRAFT = ( PIDMSI_STATUS_PRELIM + 1 ) , PIDMSI_STATUS_INPROGRESS = ( PIDMSI_STATUS_DRAFT + 1 ) , PIDMSI_STATUS_EDIT = ( PIDMSI_STATUS_INPROGRESS + 1 ) , PIDMSI_STATUS_REVIEW = ( PIDMSI_STATUS_EDIT + 1 ) , PIDMSI_STATUS_PROOF = ( PIDMSI_STATUS_REVIEW + 1 ) , PIDMSI_STATUS_FINAL = ( PIDMSI_STATUS_PROOF + 1 ) , PIDMSI_STATUS_OTHER = 0x7fff } ; #define PRSPEC_INVALID ( 0xffffffff ) #define PRSPEC_LPWSTR ( 0 ) #define PRSPEC_PROPID ( 1 ) typedef struct tagPROPSPEC { ULONG ulKind; /* [switch_type] */ union { PROPID propid; LPOLESTR lpwstr; /* Empty union arm */ } ; } PROPSPEC; typedef struct tagSTATPROPSTG { LPOLESTR lpwstrName; PROPID propid; VARTYPE vt; } STATPROPSTG; // Macros for parsing the OS Version of the Property Set Header #define PROPSETHDR_OSVER_KIND(dwOSVer) HIWORD( (dwOSVer) ) #define PROPSETHDR_OSVER_MAJOR(dwOSVer) LOBYTE(LOWORD( (dwOSVer) )) #define PROPSETHDR_OSVER_MINOR(dwOSVer) HIBYTE(LOWORD( (dwOSVer) )) #define PROPSETHDR_OSVERSION_UNKNOWN 0xFFFFFFFF typedef struct tagSTATPROPSETSTG { FMTID fmtid; CLSID clsid; DWORD grfFlags; FILETIME mtime; FILETIME ctime; FILETIME atime; DWORD dwOSVersion; } STATPROPSETSTG; extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0000_v0_0_s_ifspec; #ifndef __IPropertyStorage_INTERFACE_DEFINED__ #define __IPropertyStorage_INTERFACE_DEFINED__ /* interface IPropertyStorage */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IPropertyStorage; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("00000138-0000-0000-C000-000000000046") IPropertyStorage : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE ReadMultiple( /* [in] */ ULONG cpspec, /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[ ], /* [size_is][out] */ __RPC__out_ecount_full(cpspec) PROPVARIANT rgpropvar[ ]) = 0; virtual HRESULT STDMETHODCALLTYPE WriteMultiple( /* [in] */ ULONG cpspec, /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[ ], /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPVARIANT rgpropvar[ ], /* [in] */ PROPID propidNameFirst) = 0; virtual HRESULT STDMETHODCALLTYPE DeleteMultiple( /* [in] */ ULONG cpspec, /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[ ]) = 0; virtual HRESULT STDMETHODCALLTYPE ReadPropertyNames( /* [in] */ ULONG cpropid, /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[ ], /* [size_is][out] */ __RPC__out_ecount_full(cpropid) LPOLESTR rglpwstrName[ ]) = 0; virtual HRESULT STDMETHODCALLTYPE WritePropertyNames( /* [in] */ ULONG cpropid, /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[ ], /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const LPOLESTR rglpwstrName[ ]) = 0; virtual HRESULT STDMETHODCALLTYPE DeletePropertyNames( /* [in] */ ULONG cpropid, /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[ ]) = 0; virtual HRESULT STDMETHODCALLTYPE Commit( /* [in] */ DWORD grfCommitFlags) = 0; virtual HRESULT STDMETHODCALLTYPE Revert( void) = 0; virtual HRESULT STDMETHODCALLTYPE Enum( /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum) = 0; virtual HRESULT STDMETHODCALLTYPE SetTimes( /* [in] */ __RPC__in const FILETIME *pctime, /* [in] */ __RPC__in const FILETIME *patime, /* [in] */ __RPC__in const FILETIME *pmtime) = 0; virtual HRESULT STDMETHODCALLTYPE SetClass( /* [in] */ __RPC__in REFCLSID clsid) = 0; virtual HRESULT STDMETHODCALLTYPE Stat( /* [out] */ __RPC__out STATPROPSETSTG *pstatpsstg) = 0; }; #else /* C style interface */ typedef struct IPropertyStorageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IPropertyStorage * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IPropertyStorage * This); ULONG ( STDMETHODCALLTYPE *Release )( IPropertyStorage * This); HRESULT ( STDMETHODCALLTYPE *ReadMultiple )( IPropertyStorage * This, /* [in] */ ULONG cpspec, /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[ ], /* [size_is][out] */ __RPC__out_ecount_full(cpspec) PROPVARIANT rgpropvar[ ]); HRESULT ( STDMETHODCALLTYPE *WriteMultiple )( IPropertyStorage * This, /* [in] */ ULONG cpspec, /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[ ], /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPVARIANT rgpropvar[ ], /* [in] */ PROPID propidNameFirst); HRESULT ( STDMETHODCALLTYPE *DeleteMultiple )( IPropertyStorage * This, /* [in] */ ULONG cpspec, /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[ ]); HRESULT ( STDMETHODCALLTYPE *ReadPropertyNames )( IPropertyStorage * This, /* [in] */ ULONG cpropid, /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[ ], /* [size_is][out] */ __RPC__out_ecount_full(cpropid) LPOLESTR rglpwstrName[ ]); HRESULT ( STDMETHODCALLTYPE *WritePropertyNames )( IPropertyStorage * This, /* [in] */ ULONG cpropid, /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[ ], /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const LPOLESTR rglpwstrName[ ]); HRESULT ( STDMETHODCALLTYPE *DeletePropertyNames )( IPropertyStorage * This, /* [in] */ ULONG cpropid, /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[ ]); HRESULT ( STDMETHODCALLTYPE *Commit )( IPropertyStorage * This, /* [in] */ DWORD grfCommitFlags); HRESULT ( STDMETHODCALLTYPE *Revert )( IPropertyStorage * This); HRESULT ( STDMETHODCALLTYPE *Enum )( IPropertyStorage * This, /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum); HRESULT ( STDMETHODCALLTYPE *SetTimes )( IPropertyStorage * This, /* [in] */ __RPC__in const FILETIME *pctime, /* [in] */ __RPC__in const FILETIME *patime, /* [in] */ __RPC__in const FILETIME *pmtime); HRESULT ( STDMETHODCALLTYPE *SetClass )( IPropertyStorage * This, /* [in] */ __RPC__in REFCLSID clsid); HRESULT ( STDMETHODCALLTYPE *Stat )( IPropertyStorage * This, /* [out] */ __RPC__out STATPROPSETSTG *pstatpsstg); END_INTERFACE } IPropertyStorageVtbl; interface IPropertyStorage { CONST_VTBL struct IPropertyStorageVtbl *lpVtbl; }; #ifdef COBJMACROS #define IPropertyStorage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IPropertyStorage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IPropertyStorage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IPropertyStorage_ReadMultiple(This,cpspec,rgpspec,rgpropvar) \ ( (This)->lpVtbl -> ReadMultiple(This,cpspec,rgpspec,rgpropvar) ) #define IPropertyStorage_WriteMultiple(This,cpspec,rgpspec,rgpropvar,propidNameFirst) \ ( (This)->lpVtbl -> WriteMultiple(This,cpspec,rgpspec,rgpropvar,propidNameFirst) ) #define IPropertyStorage_DeleteMultiple(This,cpspec,rgpspec) \ ( (This)->lpVtbl -> DeleteMultiple(This,cpspec,rgpspec) ) #define IPropertyStorage_ReadPropertyNames(This,cpropid,rgpropid,rglpwstrName) \ ( (This)->lpVtbl -> ReadPropertyNames(This,cpropid,rgpropid,rglpwstrName) ) #define IPropertyStorage_WritePropertyNames(This,cpropid,rgpropid,rglpwstrName) \ ( (This)->lpVtbl -> WritePropertyNames(This,cpropid,rgpropid,rglpwstrName) ) #define IPropertyStorage_DeletePropertyNames(This,cpropid,rgpropid) \ ( (This)->lpVtbl -> DeletePropertyNames(This,cpropid,rgpropid) ) #define IPropertyStorage_Commit(This,grfCommitFlags) \ ( (This)->lpVtbl -> Commit(This,grfCommitFlags) ) #define IPropertyStorage_Revert(This) \ ( (This)->lpVtbl -> Revert(This) ) #define IPropertyStorage_Enum(This,ppenum) \ ( (This)->lpVtbl -> Enum(This,ppenum) ) #define IPropertyStorage_SetTimes(This,pctime,patime,pmtime) \ ( (This)->lpVtbl -> SetTimes(This,pctime,patime,pmtime) ) #define IPropertyStorage_SetClass(This,clsid) \ ( (This)->lpVtbl -> SetClass(This,clsid) ) #define IPropertyStorage_Stat(This,pstatpsstg) \ ( (This)->lpVtbl -> Stat(This,pstatpsstg) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IPropertyStorage_INTERFACE_DEFINED__ */ #ifndef __IPropertySetStorage_INTERFACE_DEFINED__ #define __IPropertySetStorage_INTERFACE_DEFINED__ /* interface IPropertySetStorage */ /* [unique][uuid][object] */ typedef /* [unique] */ __RPC_unique_pointer IPropertySetStorage *LPPROPERTYSETSTORAGE; EXTERN_C const IID IID_IPropertySetStorage; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0000013A-0000-0000-C000-000000000046") IPropertySetStorage : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Create( /* [in] */ __RPC__in REFFMTID rfmtid, /* [unique][in] */ __RPC__in_opt const CLSID *pclsid, /* [in] */ DWORD grfFlags, /* [in] */ DWORD grfMode, /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg) = 0; virtual HRESULT STDMETHODCALLTYPE Open( /* [in] */ __RPC__in REFFMTID rfmtid, /* [in] */ DWORD grfMode, /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg) = 0; virtual HRESULT STDMETHODCALLTYPE Delete( /* [in] */ __RPC__in REFFMTID rfmtid) = 0; virtual HRESULT STDMETHODCALLTYPE Enum( /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum) = 0; }; #else /* C style interface */ typedef struct IPropertySetStorageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IPropertySetStorage * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IPropertySetStorage * This); ULONG ( STDMETHODCALLTYPE *Release )( IPropertySetStorage * This); HRESULT ( STDMETHODCALLTYPE *Create )( IPropertySetStorage * This, /* [in] */ __RPC__in REFFMTID rfmtid, /* [unique][in] */ __RPC__in_opt const CLSID *pclsid, /* [in] */ DWORD grfFlags, /* [in] */ DWORD grfMode, /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg); HRESULT ( STDMETHODCALLTYPE *Open )( IPropertySetStorage * This, /* [in] */ __RPC__in REFFMTID rfmtid, /* [in] */ DWORD grfMode, /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg); HRESULT ( STDMETHODCALLTYPE *Delete )( IPropertySetStorage * This, /* [in] */ __RPC__in REFFMTID rfmtid); HRESULT ( STDMETHODCALLTYPE *Enum )( IPropertySetStorage * This, /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum); END_INTERFACE } IPropertySetStorageVtbl; interface IPropertySetStorage { CONST_VTBL struct IPropertySetStorageVtbl *lpVtbl; }; #ifdef COBJMACROS #define IPropertySetStorage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IPropertySetStorage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IPropertySetStorage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IPropertySetStorage_Create(This,rfmtid,pclsid,grfFlags,grfMode,ppprstg) \ ( (This)->lpVtbl -> Create(This,rfmtid,pclsid,grfFlags,grfMode,ppprstg) ) #define IPropertySetStorage_Open(This,rfmtid,grfMode,ppprstg) \ ( (This)->lpVtbl -> Open(This,rfmtid,grfMode,ppprstg) ) #define IPropertySetStorage_Delete(This,rfmtid) \ ( (This)->lpVtbl -> Delete(This,rfmtid) ) #define IPropertySetStorage_Enum(This,ppenum) \ ( (This)->lpVtbl -> Enum(This,ppenum) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IPropertySetStorage_INTERFACE_DEFINED__ */ #ifndef __IEnumSTATPROPSTG_INTERFACE_DEFINED__ #define __IEnumSTATPROPSTG_INTERFACE_DEFINED__ /* interface IEnumSTATPROPSTG */ /* [unique][uuid][object] */ typedef /* [unique] */ __RPC_unique_pointer IEnumSTATPROPSTG *LPENUMSTATPROPSTG; EXTERN_C const IID IID_IEnumSTATPROPSTG; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("00000139-0000-0000-C000-000000000046") IEnumSTATPROPSTG : public IUnknown { public: virtual /* [local] */ HRESULT STDMETHODCALLTYPE Next( /* [in] */ ULONG celt, /* [length_is][size_is][out] */ STATPROPSTG *rgelt, /* [out] */ ULONG *pceltFetched) = 0; virtual HRESULT STDMETHODCALLTYPE Skip( /* [in] */ ULONG celt) = 0; virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0; virtual HRESULT STDMETHODCALLTYPE Clone( /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum) = 0; }; #else /* C style interface */ typedef struct IEnumSTATPROPSTGVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IEnumSTATPROPSTG * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IEnumSTATPROPSTG * This); ULONG ( STDMETHODCALLTYPE *Release )( IEnumSTATPROPSTG * This); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Next )( IEnumSTATPROPSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ STATPROPSTG *rgelt, /* [out] */ ULONG *pceltFetched); HRESULT ( STDMETHODCALLTYPE *Skip )( IEnumSTATPROPSTG * This, /* [in] */ ULONG celt); HRESULT ( STDMETHODCALLTYPE *Reset )( IEnumSTATPROPSTG * This); HRESULT ( STDMETHODCALLTYPE *Clone )( IEnumSTATPROPSTG * This, /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum); END_INTERFACE } IEnumSTATPROPSTGVtbl; interface IEnumSTATPROPSTG { CONST_VTBL struct IEnumSTATPROPSTGVtbl *lpVtbl; }; #ifdef COBJMACROS #define IEnumSTATPROPSTG_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IEnumSTATPROPSTG_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IEnumSTATPROPSTG_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IEnumSTATPROPSTG_Next(This,celt,rgelt,pceltFetched) \ ( (This)->lpVtbl -> Next(This,celt,rgelt,pceltFetched) ) #define IEnumSTATPROPSTG_Skip(This,celt) \ ( (This)->lpVtbl -> Skip(This,celt) ) #define IEnumSTATPROPSTG_Reset(This) \ ( (This)->lpVtbl -> Reset(This) ) #define IEnumSTATPROPSTG_Clone(This,ppenum) \ ( (This)->lpVtbl -> Clone(This,ppenum) ) #endif /* COBJMACROS */ #endif /* C style interface */ /* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSTG_RemoteNext_Proxy( IEnumSTATPROPSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSTG *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched); void __RPC_STUB IEnumSTATPROPSTG_RemoteNext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IEnumSTATPROPSTG_INTERFACE_DEFINED__ */ #ifndef __IEnumSTATPROPSETSTG_INTERFACE_DEFINED__ #define __IEnumSTATPROPSETSTG_INTERFACE_DEFINED__ /* interface IEnumSTATPROPSETSTG */ /* [unique][uuid][object] */ typedef /* [unique] */ __RPC_unique_pointer IEnumSTATPROPSETSTG *LPENUMSTATPROPSETSTG; EXTERN_C const IID IID_IEnumSTATPROPSETSTG; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0000013B-0000-0000-C000-000000000046") IEnumSTATPROPSETSTG : public IUnknown { public: virtual /* [local] */ HRESULT STDMETHODCALLTYPE Next( /* [in] */ ULONG celt, /* [length_is][size_is][out] */ STATPROPSETSTG *rgelt, /* [out] */ ULONG *pceltFetched) = 0; virtual HRESULT STDMETHODCALLTYPE Skip( /* [in] */ ULONG celt) = 0; virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0; virtual HRESULT STDMETHODCALLTYPE Clone( /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum) = 0; }; #else /* C style interface */ typedef struct IEnumSTATPROPSETSTGVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IEnumSTATPROPSETSTG * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IEnumSTATPROPSETSTG * This); ULONG ( STDMETHODCALLTYPE *Release )( IEnumSTATPROPSETSTG * This); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Next )( IEnumSTATPROPSETSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ STATPROPSETSTG *rgelt, /* [out] */ ULONG *pceltFetched); HRESULT ( STDMETHODCALLTYPE *Skip )( IEnumSTATPROPSETSTG * This, /* [in] */ ULONG celt); HRESULT ( STDMETHODCALLTYPE *Reset )( IEnumSTATPROPSETSTG * This); HRESULT ( STDMETHODCALLTYPE *Clone )( IEnumSTATPROPSETSTG * This, /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum); END_INTERFACE } IEnumSTATPROPSETSTGVtbl; interface IEnumSTATPROPSETSTG { CONST_VTBL struct IEnumSTATPROPSETSTGVtbl *lpVtbl; }; #ifdef COBJMACROS #define IEnumSTATPROPSETSTG_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IEnumSTATPROPSETSTG_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IEnumSTATPROPSETSTG_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IEnumSTATPROPSETSTG_Next(This,celt,rgelt,pceltFetched) \ ( (This)->lpVtbl -> Next(This,celt,rgelt,pceltFetched) ) #define IEnumSTATPROPSETSTG_Skip(This,celt) \ ( (This)->lpVtbl -> Skip(This,celt) ) #define IEnumSTATPROPSETSTG_Reset(This) \ ( (This)->lpVtbl -> Reset(This) ) #define IEnumSTATPROPSETSTG_Clone(This,ppenum) \ ( (This)->lpVtbl -> Clone(This,ppenum) ) #endif /* COBJMACROS */ #endif /* C style interface */ /* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSETSTG_RemoteNext_Proxy( IEnumSTATPROPSETSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSETSTG *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched); void __RPC_STUB IEnumSTATPROPSETSTG_RemoteNext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IEnumSTATPROPSETSTG_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_propidl_0000_0004 */ /* [local] */ typedef /* [unique] */ __RPC_unique_pointer IPropertyStorage *LPPROPERTYSTORAGE; WINOLEAPI PropVariantCopy ( PROPVARIANT * pvarDest, const PROPVARIANT * pvarSrc ); WINOLEAPI PropVariantClear ( PROPVARIANT * pvar ); WINOLEAPI FreePropVariantArray ( ULONG cVariants, PROPVARIANT * rgvars ); #define _PROPVARIANTINIT_DEFINED_ # ifdef __cplusplus inline void PropVariantInit ( PROPVARIANT * pvar ) { memset ( pvar, 0, sizeof(PROPVARIANT) ); } # else # define PropVariantInit(pvar) memset ( (pvar), 0, sizeof(PROPVARIANT) ) # endif #ifndef _STGCREATEPROPSTG_DEFINED_ WINOLEAPI StgCreatePropStg( IUnknown* pUnk, REFFMTID fmtid, const CLSID *pclsid, DWORD grfFlags, DWORD dwReserved, IPropertyStorage **ppPropStg ); WINOLEAPI StgOpenPropStg( IUnknown* pUnk, REFFMTID fmtid, DWORD grfFlags, DWORD dwReserved, IPropertyStorage **ppPropStg ); WINOLEAPI StgCreatePropSetStg( IStorage *pStorage, DWORD dwReserved, IPropertySetStorage **ppPropSetStg); #define CCH_MAX_PROPSTG_NAME 31 __checkReturn WINOLEAPI FmtIdToPropStgName( const FMTID *pfmtid, __out_ecount(CCH_MAX_PROPSTG_NAME+1) LPOLESTR oszName ); WINOLEAPI PropStgNameToFmtId( __in __nullterminated const LPOLESTR oszName, FMTID *pfmtid ); #endif #ifndef _SERIALIZEDPROPERTYVALUE_DEFINED_ #define _SERIALIZEDPROPERTYVALUE_DEFINED_ typedef struct tagSERIALIZEDPROPERTYVALUE // prop { DWORD dwType; BYTE rgb[1]; } SERIALIZEDPROPERTYVALUE; #endif EXTERN_C SERIALIZEDPROPERTYVALUE* __stdcall StgConvertVariantToProperty( __in const PROPVARIANT* pvar, USHORT CodePage, __out_bcount_opt(*pcb) SERIALIZEDPROPERTYVALUE* pprop, __inout ULONG* pcb, PROPID pid, __reserved BOOLEAN fReserved, __out_opt ULONG* pcIndirect); #ifdef __cplusplus class PMemoryAllocator; EXTERN_C BOOLEAN __stdcall StgConvertPropertyToVariant( __in const SERIALIZEDPROPERTYVALUE* pprop, USHORT CodePage, __out PROPVARIANT* pvar, __in PMemoryAllocator* pma); #endif #if _MSC_VER >= 1200 #pragma warning(pop) #else #pragma warning(default:4201) /* Nameless struct/union */ #pragma warning(default:4237) /* keywords bool, true, false, etc.. */ #endif extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0004_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0004_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * ); unsigned long __RPC_USER LPSAFEARRAY_UserSize( unsigned long *, unsigned long , LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserMarshal( unsigned long *, unsigned char *, LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserUnmarshal(unsigned long *, unsigned char *, LPSAFEARRAY * ); void __RPC_USER LPSAFEARRAY_UserFree( unsigned long *, LPSAFEARRAY * ); unsigned long __RPC_USER BSTR_UserSize64( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal64( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal64(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree64( unsigned long *, BSTR * ); unsigned long __RPC_USER LPSAFEARRAY_UserSize64( unsigned long *, unsigned long , LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserMarshal64( unsigned long *, unsigned char *, LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserUnmarshal64(unsigned long *, unsigned char *, LPSAFEARRAY * ); void __RPC_USER LPSAFEARRAY_UserFree64( unsigned long *, LPSAFEARRAY * ); /* [local] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSTG_Next_Proxy( IEnumSTATPROPSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ STATPROPSTG *rgelt, /* [out] */ ULONG *pceltFetched); /* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSTG_Next_Stub( IEnumSTATPROPSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSTG *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched); /* [local] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSETSTG_Next_Proxy( IEnumSTATPROPSETSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ STATPROPSETSTG *rgelt, /* [out] */ ULONG *pceltFetched); /* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSETSTG_Next_Stub( IEnumSTATPROPSETSTG * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSETSTG *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 1260 ] ] ]
4bab60adf2fbb6c975f5b39c3a6a19cd17b0e599
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/WorkLayer/IEMonitor.cpp
b216e38975559b01ebb5f916070329e2a342bbdf
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
GB18030
C++
false
false
6,280
cpp
/* * $Id: IEMonitor.cpp 9073 2008-12-18 04:38:51Z dgkang $ * * this file is part of easyMule * Copyright (C)2002-2007 VeryCD Dev Team ( strEmail.Format("%s@%s", "devteam", "easymule.org") / http://www.easymule.org ) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either * version 2 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. */ // IEMonitor.cpp Added by Soar Chin (8/31/2007) #include "StdAfx.h" #include ".\iemonitor.h" #include "Preferences.h" #include "otherfunctions.h" #include "resource.h" bool CIEMonitor::m_bFirstRun = true; bool CIEMonitor::m_bIEMenu = true; bool CIEMonitor::m_bMonitor = false; bool CIEMonitor::m_bEd2k = true; bool CIEMonitor::m_bAlt = false; WORD CIEMonitor::m_wLangID = 0; CIEMonitor::CIEMonitor(void) { } CIEMonitor::~CIEMonitor(void) { } BOOL CIEMonitor::RegisterLibrary(LPCTSTR szName) { typedef HRESULT (_stdcall *FNDLLRS)(void); HMODULE hLib = ::LoadLibrary(szName); if(hLib == NULL) return FALSE; FNDLLRS m_pfnRegServer = (FNDLLRS)GetProcAddress(hLib, "DllRegisterServer"); if(m_pfnRegServer == NULL) { FreeLibrary(hLib); return FALSE; } m_pfnRegServer(); FreeLibrary(hLib); return TRUE; } BOOL CIEMonitor::UnregisterLibrary(LPCTSTR szName) { typedef HRESULT (_stdcall *FNDLLRS)(void); HMODULE hLib = ::LoadLibrary(szName); if(hLib == NULL) return FALSE; FNDLLRS m_pfnUnregServer = (FNDLLRS)GetProcAddress(hLib, "DllUnregisterServer"); if(m_pfnUnregServer == NULL) { FreeLibrary(hLib); return FALSE; } m_pfnUnregServer(); FreeLibrary(hLib); return TRUE; } void CIEMonitor::ApplyChanges( void ) { BOOL bNeedReg = FALSE; if(m_bFirstRun) { bNeedReg = CheckForUpdate(thePrefs.GetMuleDirectory(EMULE_MODULEDIR) + _T("IE2EM.dll")); } if(bNeedReg || !IsRegistered()) RegisterAll(); if(m_bFirstRun || m_bIEMenu != thePrefs.GetAddToIEMenu() || m_bMonitor != thePrefs.GetMonitorLinks() || m_bEd2k != thePrefs.GetMonitorEd2k() || m_wLangID != thePrefs.GetLanguageID()) { m_bIEMenu = thePrefs.GetAddToIEMenu(); m_bMonitor = thePrefs.GetMonitorLinks(); m_bEd2k = thePrefs.GetMonitorEd2k(); m_wLangID = thePrefs.GetLanguageID(); CRegKey regkey; CRegKey subkey; regkey.Create(HKEY_CURRENT_USER, _T("Software\\easyMule")); TCHAR szPath[512]; DWORD count = 512; if(regkey.QueryStringValue(_T("InstallPath"), szPath, &count) != ERROR_SUCCESS) { _tcscpy(szPath, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR)); INT len = _tcslen(szPath); if(len > 3 && szPath[len - 1] == '\\') szPath[len - 1] = 0; regkey.SetStringValue(_T("InstallPath"), szPath); } regkey.Close(); CString strPath = thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR) + _T("IE2EM.htm"); regkey.Create(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Internet Explorer\\MenuExt")); TCHAR szName[1024]; DWORD dwLen = 1024; BOOL bFound = FALSE; for(INT i = 0; regkey.EnumKey(i, szName, &dwLen) != ERROR_NO_MORE_ITEMS; i ++) { subkey.Open(regkey, szName); TCHAR szValue[1024]; ULONG uLen = 1024; subkey.QueryStringValue(NULL, szValue, &uLen); if(strPath == szValue) { bFound = TRUE; break; } subkey.Close(); dwLen = 1024; } if(bFound) { subkey.Close(); regkey.RecurseDeleteKey(szName); } if(m_bIEMenu) { subkey.Create(regkey, GetResString(IDS_IEMENUEXT)); subkey.SetStringValue(NULL, strPath); subkey.SetDWORDValue(_T("Contexts"), 0x22); subkey.Close(); } regkey.Close(); regkey.Create(HKEY_CURRENT_USER, _T("Software\\easyMule")); if(m_bMonitor) regkey.SetDWORDValue(_T("Monitor"), 1); else regkey.SetDWORDValue(_T("Monitor"), 0); regkey.Close(); } m_bFirstRun = false; } BOOL CIEMonitor::CheckForUpdate( CString realpath ) { CString oldpath = realpath + _T(".old"); CString newpath = realpath + _T(".new"); if(!PathFileExists(newpath)) return FALSE; if(PathFileExists(realpath)) { if(PathFileExists(oldpath)) { if(_tremove(oldpath) != 0) return FALSE; } if(_trename(realpath, oldpath) != 0) { return FALSE; } UnregisterLibrary(realpath); } _trename(newpath, realpath); return TRUE; } void CIEMonitor::RegisterAll( void ) { RegisterLibrary(thePrefs.GetMuleDirectory(EMULE_MODULEDIR) + _T("IE2EM.dll")); } BOOL CIEMonitor::IsRegistered( void ) { CRegKey checkkey; return checkkey.Open(HKEY_CLASSES_ROOT, _T("CLSID\\{A0867FD1-79E7-456C-8B41-165A2504FD86}")) == ERROR_SUCCESS && checkkey.Open(HKEY_CLASSES_ROOT, _T("CLSID\\{48618374-565F-4CA0-B8CD-6F496C997FAF}")) == ERROR_SUCCESS && checkkey.Open(HKEY_CLASSES_ROOT, _T("CLSID\\{0A0DDBD3-6641-40B9-873F-BBDD26D6C14E}")) == ERROR_SUCCESS && checkkey.Open(HKEY_CLASSES_ROOT, _T("IE2EM.IE2EMUrlTaker")) == ERROR_SUCCESS && checkkey.Open(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects\\{0A0DDBD3-6641-40B9-873F-BBDD26D6C14E}")) == ERROR_SUCCESS && IsPathOk(); } BOOL CIEMonitor::IsPathOk( void ) { CRegKey checkkey; if(checkkey.Open(HKEY_CLASSES_ROOT, _T("CLSID\\{48618374-565F-4CA0-B8CD-6F496C997FAF}\\InprocServer32")) != ERROR_SUCCESS) return FALSE; TCHAR szVal[MAX_PATH]; ULONG len = MAX_PATH; checkkey.QueryStringValue(NULL, szVal, &len); //VC-dgkang 2008年6月11日 //应该忽略字符串大小写敏感比较 CString tcs; tcs = thePrefs.GetMuleDirectory(EMULE_MODULEDIR) + _T("IE2EM.dll"); return !tcs.CompareNoCase(szVal); //return thePrefs.GetMuleDirectory(EMULE_MODULEDIR) + _T("IE2EM.dll") == szVal; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 211 ] ] ]
b3d1b2905fdad98c444b5bfaa5294a64c6012968
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/tests/XSValueTest/XSValueTest.hpp
1044e0d0fa174959ae007862f46808e91b994e1f
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,833
hpp
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: XSValueTest.hpp,v 1.3 2004/09/08 13:57:06 peiyongz Exp $ * $Log: XSValueTest.hpp,v $ * Revision 1.3 2004/09/08 13:57:06 peiyongz * Apache License Version 2.0 * * Revision 1.2 2004/08/24 16:00:15 peiyongz * To build on AIX/Win2003-ecl * * Revision 1.1 2004/08/19 17:17:21 peiyongz * XSValueTest * * */ #if !defined(XSVALUE_TEST_HPP) #define XSVALUE_TEST_HPP // --------------------------------------------------------------------------- // Includes for all the program files to see // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <iostream> #else #include <iostream.h> #endif #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_USE // --------------------------------------------------------------------------- // This is a simple class that lets us do easy (though not terribly efficient) // trancoding of XMLCh data to local code page for display. // --------------------------------------------------------------------------- class StrX { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- StrX(const XMLCh* const toTranscode) { fUnicodeForm = XMLString::replicate(toTranscode); fLocalForm = XMLString::transcode(toTranscode); } StrX(const char* const toTranscode) { // Call the private transcoding method fLocalForm = XMLString::replicate(toTranscode); fUnicodeForm = XMLString::transcode(toTranscode); } ~StrX() { XMLString::release(&fLocalForm); XMLString::release(&fUnicodeForm); } // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const char* localForm() const { return fLocalForm; } const XMLCh* unicodeForm() const { return fUnicodeForm; } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- StrX(const StrX&); StrX & operator=(const StrX &); // ----------------------------------------------------------------------- // Private data members // // fLocalForm // This is the local code page form of the string. // // fUnicodeForm // This is the Unicode XMLCh format of the string. // ----------------------------------------------------------------------- XMLCh* fUnicodeForm; char* fLocalForm; }; #define UniForm(str) StrX(str).unicodeForm() #define LocForm(str) StrX(str).localForm() inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& target, const StrX& toDump) { target << toDump.localForm(); return target; } #endif
[ [ [ 1, 122 ] ] ]
48b7cad0af52e5e80dfa9c5996339d7215d85b12
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Tests/TestMarshal/DlgProxy.cpp
cdf2d254df7522a26284aacd357d2de7098bdc6c
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,079
cpp
// DlgProxy.cpp : implementation file // #include "stdafx.h" #include "TestMarshal.h" #include "DlgProxy.h" #include "TestMarshalDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTestMarshalDlgAutoProxy IMPLEMENT_DYNCREATE(CTestMarshalDlgAutoProxy, CCmdTarget) CTestMarshalDlgAutoProxy::CTestMarshalDlgAutoProxy() { EnableAutomation(); // To keep the application running as long as an automation // object is active, the constructor calls AfxOleLockApp. AfxOleLockApp(); // Get access to the dialog through the application's // main window pointer. Set the proxy's internal pointer // to point to the dialog, and set the dialog's back pointer to // this proxy. ASSERT (AfxGetApp()->m_pMainWnd != NULL); ASSERT_VALID (AfxGetApp()->m_pMainWnd); ASSERT_KINDOF(CTestMarshalDlg, AfxGetApp()->m_pMainWnd); m_pDialog = (CTestMarshalDlg*) AfxGetApp()->m_pMainWnd; m_pDialog->m_pAutoProxy = this; } CTestMarshalDlgAutoProxy::~CTestMarshalDlgAutoProxy() { // To terminate the application when all objects created with // with automation, the destructor calls AfxOleUnlockApp. // Among other things, this will destroy the main dialog if (m_pDialog != NULL) m_pDialog->m_pAutoProxy = NULL; AfxOleUnlockApp(); } void CTestMarshalDlgAutoProxy::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CCmdTarget::OnFinalRelease(); } BEGIN_MESSAGE_MAP(CTestMarshalDlgAutoProxy, CCmdTarget) //{{AFX_MSG_MAP(CTestMarshalDlgAutoProxy) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CTestMarshalDlgAutoProxy, CCmdTarget) //{{AFX_DISPATCH_MAP(CTestMarshalDlgAutoProxy) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() // Note: we add support for IID_ITestMarshal to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .ODL file. // {2C971345-9D63-4000-AF61-FC31A1A64F0F} static const IID IID_ITestMarshal = { 0x2c971345, 0x9d63, 0x4000, { 0xaf, 0x61, 0xfc, 0x31, 0xa1, 0xa6, 0x4f, 0xf } }; BEGIN_INTERFACE_MAP(CTestMarshalDlgAutoProxy, CCmdTarget) INTERFACE_PART(CTestMarshalDlgAutoProxy, IID_ITestMarshal, Dispatch) END_INTERFACE_MAP() // The IMPLEMENT_OLECREATE2 macro is defined in StdAfx.h of this project // {7035768B-1B4C-4A35-900F-1A360495CC61} IMPLEMENT_OLECREATE2(CTestMarshalDlgAutoProxy, "TestMarshal.Application", 0x7035768b, 0x1b4c, 0x4a35, 0x90, 0xf, 0x1a, 0x36, 0x4, 0x95, 0xcc, 0x61) ///////////////////////////////////////////////////////////////////////////// // CTestMarshalDlgAutoProxy message handlers
[ [ [ 1, 88 ] ] ]
832a8278534ce47e5a2fd7ffae5b9ddb67d40317
41371839eaa16ada179d580f7b2c1878600b718e
/SPOJ/seletivas/SUDOIME.cpp
97c9d41b3b0b154a7a356fea32a3badafb3f913b
[]
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
714
cpp
#include <cstdio> int main(void){ int i, inst, j, NO, t, s, sq1, v; bool hl[9][10], hc[9][10], hs[9][10]; scanf("%d",&t); for(inst = 1; inst <= t; inst++){ printf("Instancia %d\n",inst); for(i = 0; i < 9; i++) for(j = 0; j < 9; j++) hl[i][j] = hc[i][j] = hs[i][j] = 0; for(i = 0; i < 9; i++){ sq1 = 3*(i/3); for(j = 0; j < 9; j++){ s = sq1 + j/3; scanf("%d",&v); if(v > 9) continue; hl[i][v] = 1; hc[j][v] = 1; hs[s][v] = 1; } } for(NO = i =0; !NO && i < 9; i++) for(j = 1; j < 10; j++) if(!hl[i][j] || !hc[i][j] || !hs[i][j]){ NO = 1; break; } if(NO) puts("NAO\n"); else puts("SIM\n"); } return 0; }
[ [ [ 1, 32 ] ] ]
51ee7500b8ed5a759f2364bc70a9b4805e8893ec
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Core/GameOptionsState.cpp
fbb5ca7154ca45db9807422957f0d6139167fbbf
[]
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
3,212
cpp
#include "OUAN_Precompiled.h" #include "GameOptionsState.h" #include "../Application.h" #include "../GUI/GUISubsystem.h" #include "../GUI/GUIOptionsMenu.h" #include "../Graphics/RenderSubsystem.h" #include "../Audio/AudioSubsystem.h" #include "../Utils/Utils.h" #include "GameStateManager.h" #include "MainMenuState.h" using namespace OUAN; /// Default constructor GameOptionsState::GameOptionsState() :GameState() ,mClickChannel(-1) ,mMusicChannel(-1) { } /// Destructor GameOptionsState::~GameOptionsState() { } /// init main menu's resources void GameOptionsState::init(ApplicationPtr app) { using namespace CEGUI; GameState::init(app); mGUI= BOOST_PTR_CAST(GUIOptionsMenu,mApp->getGUISubsystem()->createGUI(GUI_LAYOUT_OPTIONS)); mGUI->initGUI(shared_from_this()); Utils::TTexturedRectangleDesc desc; desc.leftCorner=desc.bottomCorner=-1.0; desc.rightCorner=desc.topCorner=1.0; desc.renderQueue=Ogre::RENDER_QUEUE_9; desc.axisAlignedBox=Ogre::AxisAlignedBox::BOX_INFINITE; desc.materialName=OPTIONS_MATERIAL_NAME; desc.materialGroup=OPTIONS_GROUP; desc.textureName=OPTIONS_IMG; desc.sceneNodeName=OPTIONS_SCREENNODE; Utils::createTexturedRectangle(desc,mScreen,mApp->getRenderSubsystem()); if (!mApp->getAudioSubsystem()->isLoaded("CLICK")) mApp->getAudioSubsystem()->load("CLICK",AUDIO_RESOURCES_GROUP_NAME); //mApp->getAudioSubsystem()->load("MUSIC",AUDIO_RESOURCES_GROUP_NAME); //mApp->getAudioSubsystem()->playMusic("MUSIC",mMusicChannel,true); } /// Clean up main menu's resources void GameOptionsState::cleanUp() { GameState::cleanUp(); //mApp->getGUISubsystem()->unbindAllEvents(); mGUI->destroy(); mApp->getGUISubsystem()->destroyGUI(); //if (mMusicChannel!=-1) // mApp->getAudioSubsystem()->stopMusic(mMusicChannel); //mApp->getAudioSubsystem()->unload("MUSIC"); Utils::destroyTexturedRectangle(mScreen,OPTIONS_MATERIAL_NAME,mApp->getRenderSubsystem()); } /// pause state void GameOptionsState::pause() { } /// resume state void GameOptionsState::resume() { GameState::resume(); if (!mApp->getAudioSubsystem()->isLoaded("CLICK")) mApp->getAudioSubsystem()->load("CLICK",AUDIO_RESOURCES_GROUP_NAME); } /// process input events /// @param app the parent application void GameOptionsState::handleEvents() { } /// Update game according to the current state /// @param app the parent app void GameOptionsState::update(long elapsedTime) { GameState::update(elapsedTime); } void GameOptionsState::backToMenu() { mApp->getGameStateManager()->popState(); //GameStatePtr nextState(new MainMenuState()); //mApp->getGameStateManager()->changeState(nextState,mApp); } bool GameOptionsState::keyPressed( const OIS::KeyEvent& e ) { if (mGUI.get()) { return mGUI->keyPressed(e); } return false; } bool GameOptionsState::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id) { if (mGUI.get()) { return mGUI->mousePressed(e,id); } return false; } bool GameOptionsState::buttonPressed( const OIS::JoyStickEvent &e, int button ) { if (mGUI.get()) { return mGUI->buttonPressed(e,button); } return false; }
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039", "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 33 ], [ 36, 60 ], [ 63, 80 ], [ 82, 95 ], [ 97, 130 ] ], [ [ 34, 35 ], [ 61, 62 ], [ 96, 96 ] ], [ [ 81, 81 ] ] ]
2906cea08d6d091c2e92a42efb788fa938d16446
f0c08b3ddefc91f1fa342f637b0e947a9a892556
/branches/develop/calcioIA/Calcio/Logger.h
1d788bde7a8dce87192d79a56ae7ca4878cd9063
[]
no_license
BackupTheBerlios/coffeestore-svn
1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f
ddee83284fe9875bf0d04e6b7da7a2113e85a040
refs/heads/master
2021-01-01T05:30:22.345767
2009-10-11T08:55:35
2009-10-11T08:55:35
40,725,038
0
0
null
null
null
null
UTF-8
C++
false
false
587
h
#ifndef LOGGER_H #define LOGGER_H #include <sstream> class LoggerWriter { public: virtual ~LoggerWriter(); virtual void write(const std::string line) = 0; }; class Logger { public: ~Logger(); static void setWriter(LoggerWriter& writer); template <typename T> Logger& operator << (const T& t) { _buffer << t; return *this; } static bool loggingEnabled(); private: std::ostringstream _buffer; }; #define LOG_STD if (!Logger::loggingEnabled()); else Logger() #define LOG_ELEM(name, value) #name << " [" << value << "] " #endif
[ "fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb" ]
[ [ [ 1, 37 ] ] ]
ddb8655deb075b8efc857245b76795e020a8aed0
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrBox2Circle2.h
3b704e2e5bb033c6e6cd75dd56555e92b39a4533
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
2,277
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4INTRBOX2CIRCLE2_H #define WM4INTRBOX2CIRCLE2_H #include "Wm4FoundationLIB.h" #include "Wm4Intersector.h" #include "Wm4Box2.h" #include "Wm4Circle2.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntrBox2Circle2 : public Intersector<Real,Vector2<Real> > { public: IntrBox2Circle2 (const Box2<Real>& rkBox, const Circle2<Real>& rkCircle); // object access const Box2<Real>& GetBox () const; const Circle2<Real>& GetCircle () const; // static test-intersection query virtual bool Test (); // dynamic find-intersection query virtual bool Find (Real fTMax, const Vector2<Real>& rkVelocity0, const Vector2<Real>& rkVelocity1); // intersection set for dynamic find-intersection query const Vector2<Real>& GetContactPoint () const; private: using Intersector<Real,Vector2<Real> >::IT_EMPTY; using Intersector<Real,Vector2<Real> >::IT_POINT; using Intersector<Real,Vector2<Real> >::IT_OTHER; using Intersector<Real,Vector2<Real> >::m_iIntersectionType; using Intersector<Real,Vector2<Real> >::m_fContactTime; // Support for dynamic Find. Both functions return -1 if the objects are // initially intersecting, 0 if no intersection, or +1 if they intersect // at some positive time. int TestVertexRegion (Real fCx, Real fCy, Real fVx, Real fVy, Real fEx, Real fEy, Real& rfIx, Real& rfIy); int TestEdgeRegion (Real fCx, Real fCy, Real fVx, Real fVy, Real fEx, Real fEy, Real& rfIx, Real& rfIy); // the objects to intersect const Box2<Real>& m_rkBox; const Circle2<Real>& m_rkCircle; // point of intersection Vector2<Real> m_kContactPoint; }; typedef IntrBox2Circle2<float> IntrBox2Circle2f; typedef IntrBox2Circle2<double> IntrBox2Circle2d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 72 ] ] ]
0cb599755a519bd81398e08cc5a3752886b17da2
c70941413b8f7bf90173533115c148411c868bad
/dev/unit_tests/src/vtxtestsOgreBase.cpp
96c637817024a5e56b67440afa073bd0b9ca2758
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,786
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "vtxtestsOgreBase.h" #include "OgreRenderWindow.h" #include "OgreRoot.h" #include "OgreD3D9Plugin.h" #include "OgreGLPlugin.h" namespace vtx { namespace tests { //----------------------------------------------------------------------- OgreBase::OgreBase() : mOgreRoot(NULL) { } //----------------------------------------------------------------------- void OgreBase::startOgre() { // disable ogre cout logging (new Ogre::LogManager())->createLog("ogre.log", true, false, false); mOgreRoot = new Ogre::Root("", "ogre.cfg", "ogre.log"); // ogre plugins Ogre::D3D9Plugin* d3d9_plugin = new Ogre::D3D9Plugin(); Ogre::Root::getSingleton().installPlugin(d3d9_plugin); // load settings from ogre.cfg if(!mOgreRoot->restoreConfig()) if(!mOgreRoot->showConfigDialog()) delete mOgreRoot; // override floating point mode Ogre::RenderSystem* render_system = mOgreRoot->getRenderSystem(); if(render_system->getName() == "Direct3D9 Rendering Subsystem") render_system->setConfigOption("Floating-point mode", "Consistent"); mOgreWindow = mOgreRoot->initialise(true, "vektrix unit test - press SHIFT + ESC to exit"); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); mOgreScene = mOgreRoot->createSceneManager(Ogre::ST_GENERIC); mOgreCamera = mOgreScene->createCamera("MainCamera"); mOgreCamera->setAutoAspectRatio(true); mOgreCamera->setNearClipDistance(1); mOgreViewport = mOgreWindow->addViewport(mOgreCamera); mOgreViewport->setBackgroundColour(Ogre::ColourValue(0.4f, 0.4f, 0.4f)); // register Ogre listener mOgreRoot->addFrameListener(this); Ogre::WindowEventUtilities::addWindowEventListener(mOgreWindow, this); } //----------------------------------------------------------------------- void OgreBase::startOgreRendering() { mOgreRoot->startRendering(); } //----------------------------------------------------------------------- void OgreBase::stopOgre() { delete mOgreRoot; mOgreRoot = NULL; } //----------------------------------------------------------------------- bool OgreBase::frameStarted(const Ogre::FrameEvent& evt) { if(!mOgreWindow) return true; return !mOgreWindow->isClosed(); } //----------------------------------------------------------------------- }}
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 104 ] ] ]
bd65855ef70de9f1d44421768dd1ef9c2bf63e78
fd47272bb959679789cf1c65afa778569886232f
/Utility/ShadeRecord.cpp
800e0745bf807734fd9c458bb955ee38057b75b5
[]
no_license
dicta/ray
5aeed98fe0cc76b7a5dea2c4b93c38caf0485b6c
5e6290077a92b8468877a8b6751f1ed13da81a43
refs/heads/master
2021-01-17T16:16:21.768537
2011-09-26T06:03:12
2011-09-28T04:36:22
2,471,865
0
0
null
null
null
null
UTF-8
C++
false
false
439
cpp
/* * ShadeRecord.cpp * RayTracer * * Created by Eric Saari on 12/30/10. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #include "ShadeRecord.h" ShadeRecord::ShadeRecord() : normal(), hitPoint(), localHitPoint(), material(), depth(0), samplePoint(), lightNormal(), wi(), tracer(NULL), tu(0), tv(0), dpdu(), dpdv() { } ShadeRecord::~ShadeRecord() { tracer = NULL; }
[ "esaari1@13d0956a-e706-368b-88ec-5b7e5bac2ff7" ]
[ [ [ 1, 31 ] ] ]
2038590058c9de53d8bd6519ef6ffcdf3e2efb1e
c497f6d85bdbcbb21e93ae701c5570f16370f0ae
/Sync/Lets_try_all_engine/backup/Clear/SatDbMac.hpp
ed11fbfb3af983cf651b94dc13375de69beef631
[]
no_license
mfkiwl/gpsgyan_fork
91b380cf3cfedb5d1aac569c6284bbf34c047573
f7c850216c16b49e01a0653b70c1905b5b6c2587
refs/heads/master
2021-10-15T08:32:53.606124
2011-01-19T16:24:18
2011-01-19T16:24:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
120
hpp
/* The minimum Elevation angle */ # define MIN_ELV_ANGLE 1 # define M_ZERO 0 # define M_ONE 1 # define M_TWO 2
[ "priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7" ]
[ [ [ 1, 6 ] ] ]
14db6b02cde40e32921d071c459e68ab42dd4ad8
d504537dae74273428d3aacd03b89357215f3d11
/src/Video/TextureRenderer.cpp
6c54b1ff7218d55119fd4dd3e66d435ab9457a2d
[]
no_license
h0MER247/e6
1026bf9aabd5c11b84e358222d103aee829f62d7
f92546fd1fc53ba783d84e9edf5660fe19b739cc
refs/heads/master
2020-12-23T05:42:42.373786
2011-02-18T16:16:24
2011-02-18T16:16:24
237,055,477
1
0
null
2020-01-29T18:39:15
2020-01-29T18:39:14
null
UTF-8
C++
false
false
9,829
cpp
#include "TextureRenderer.h" #include <uuids.h> //#define CheckPointer(pmt,e) if (!(pmt)) return e; struct __declspec(uuid("{71771540-2017-11cf-ae26-0020afd79767}")) CLSID_TextureRenderer; //----------------------------------------------------------------------------- // CTextureRenderer constructor //----------------------------------------------------------------------------- //LPCTSTR ctName = TEXT("Texture Renderer"); TCHAR * ctName = TEXT("Texture Renderer"); CTextureRenderer::CTextureRenderer( LPDIRECT3DTEXTURE9 tex, LPUNKNOWN pUnk, HRESULT *phr ) : CBaseVideoRenderer(__uuidof(CLSID_TextureRenderer), ctName, pUnk, phr) , m_bUseDynamicTextures(FALSE) , m_pTexture(tex) //, m_TextureFormat(0) { // Store and AddRef the texture for our use. ASSERT(phr); if (phr) *phr = S_OK; } //----------------------------------------------------------------------------- // CTextureRenderer destructor //----------------------------------------------------------------------------- CTextureRenderer::~CTextureRenderer() { if ( m_pTexture ) m_pTexture->Release(); } HRESULT CTextureRenderer::setTexture(LPDIRECT3DTEXTURE9 tex) { if ( tex ) { D3DSURFACE_DESC desc; if ( tex->GetLevelDesc( 0, &desc ) == S_OK ) { //if ( ( desc.Width != m_lVidWidth ) || ( desc.Height != m_lVidHeight ) ) //{ // return E_FAIL ; //} m_lVidWidth = desc.Width; m_lVidHeight = desc.Height; m_TextureFormat = desc.Format; } } if ( m_pTexture ) m_pTexture->Release(); m_pTexture = tex; if ( m_pTexture ) m_pTexture->AddRef(); return S_OK; } //----------------------------------------------------------------------------- // CheckMediaType: This method forces the graph to give us an R8G8B8 video // type, making our copy to texture memory trivial. //----------------------------------------------------------------------------- HRESULT CTextureRenderer::CheckMediaType(const CMediaType *pmt) { HRESULT hr = E_FAIL; VIDEOINFO *pvi=0; CheckPointer(pmt,E_POINTER); // Reject the connection if this is not a video type if( *pmt->FormatType() != FORMAT_VideoInfo ) { return E_INVALIDARG; } // Only accept RGB24 video pvi = (VIDEOINFO *)pmt->Format(); if(IsEqualGUID( *pmt->Type(), MEDIATYPE_Video) && IsEqualGUID( *pmt->Subtype(), MEDIASUBTYPE_RGB24)) { hr = S_OK; } return hr; } //----------------------------------------------------------------------------- // SetMediaType: Graph connection has been made. // ppp new policy: // since we got no texture here, just store input video properties // //----------------------------------------------------------------------------- HRESULT CTextureRenderer::SetMediaType(const CMediaType *pmt) { // HRESULT hr; UINT uintWidth = 2; UINT uintHeight = 2; // Retrive the size of this media type VIDEOINFO *pviBmp; // Bitmap info header pviBmp = (VIDEOINFO *)pmt->Format(); m_lVidWidth = pviBmp->bmiHeader.biWidth; m_lVidHeight = abs(pviBmp->bmiHeader.biHeight); m_lVidPitch = (m_lVidWidth * 3 + 3) & ~(3); // We are forcing RGB24 // D3DCAPS9 caps; // // here let's check if we can use dynamic textures // ZeroMemory( &caps, sizeof(D3DCAPS9)); // hr = g_pd3dDevice->GetDeviceCaps( &caps ); // if( caps.Caps2 & D3DCAPS2_DYNAMICTEXTURES ) // { // m_bUseDynamicTextures = TRUE; // } // // if( caps.TextureCaps & D3DPTEXTURECAPS_POW2 ) // { // while( (LONG)uintWidth < m_lVidWidth ) // { // uintWidth = uintWidth << 1; // } // while( (LONG)uintHeight < m_lVidHeight ) // { // uintHeight = uintHeight << 1; // } /////PPP??? UpgradeGeometry( m_lVidWidth, uintWidth, m_lVidHeight, uintHeight); // } // else // { // uintWidth = m_lVidWidth; // uintHeight = m_lVidHeight; // } // // // Create the texture that maps to this media type // hr = E_UNEXPECTED; // if( m_bUseDynamicTextures ) // { // hr = g_pd3dDevice->CreateTexture(uintWidth, uintHeight, 1, D3DUSAGE_DYNAMIC, // D3DFMT_X8R8G8B8,D3DPOOL_DEFAULT, // &g_pTexture, NULL); // // g_pachRenderMethod = g_achDynTextr; // if( FAILED(hr)) // { // m_bUseDynamicTextures = FALSE; // } // } // if( FALSE == m_bUseDynamicTextures ) // { // hr = g_pd3dDevice->CreateTexture(uintWidth, uintHeight, 1, 0, // D3DFMT_X8R8G8B8,D3DPOOL_MANAGED, // &g_pTexture, NULL); //// g_pachRenderMethod = g_achCopy; // } // if( FAILED(hr)) // { // //MG::NG_DebugLog(TEXT("Could not create the D3DX texture! hr=0x%x"), hr); // return hr; // } // // // CreateTexture can silently change the parameters on us // D3DSURFACE_DESC ddsd; // ZeroMemory(&ddsd, sizeof(ddsd)); // // if ( FAILED( hr = g_pTexture->GetLevelDesc( 0, &ddsd ) ) ) { // //MG::NG_DebugLog(TEXT("Could not get level Description of D3DX texture! hr = 0x%x"), hr); // return hr; // } // // // CComPtr<IDirect3DSurface9> pSurf; // // if (SUCCEEDED(hr = g_pTexture->GetSurfaceLevel(0, &pSurf))) // pSurf->GetDesc(&ddsd); // // // Save format info // g_TextureFormat = ddsd.Format; // // if (g_TextureFormat != D3DFMT_X8R8G8B8 && // g_TextureFormat != D3DFMT_A1R5G5B5) { // // MG::NG_DebugLog(TEXT("Texture is format we can't handle! Format = 0x%x"), g_TextureFormat); // return VFW_E_TYPE_NOT_ACCEPTED; // } return S_OK; } //----------------------------------------------------------------------------- // DoRenderSample: A sample has been delivered. Copy it to the texture. //----------------------------------------------------------------------------- HRESULT CTextureRenderer::DoRenderSample( IMediaSample * pSample ) { BYTE *pBmpBuffer, *pTxtBuffer; // Bitmap buffer, texture buffer LONG lTxtPitch; // Pitch of bitmap, texture BYTE * pbS = NULL; DWORD * pdwS = NULL; DWORD * pdwD = NULL; UINT row, col, dwordWidth; CheckPointer(pSample,E_POINTER); CheckPointer(m_pTexture,E_UNEXPECTED); // Get the video bitmap buffer pSample->GetPointer( &pBmpBuffer ); // Lock the Texture D3DLOCKED_RECT d3dlr; DWORD lockFlag = 0; if ( m_bUseDynamicTextures ) { lockFlag = D3DLOCK_DISCARD; } if ( FAILED(m_pTexture->LockRect(0, &d3dlr, 0,lockFlag))) return E_FAIL; // Get the texture buffer & pitch pTxtBuffer = static_cast<byte *>(d3dlr.pBits); lTxtPitch = d3dlr.Pitch; // Copy the bits if (m_TextureFormat == D3DFMT_X8R8G8B8) { // Instead of copying data bytewise, we use DWORD alignment here. // We also unroll loop by copying 4 pixels at once. // // original BYTE array is [b0][g0][r0][b1][g1][r1][b2][g2][r2][b3][g3][r3] // // aligned DWORD array is [b1 r0 g0 b0][g2 b2 r1 g1][r3 g3 b3 r2] // // We want to transform it to [ff r0 g0 b0][ff r1 g1 b1][ff r2 g2 b2][ff r3 b3 g3] // below, bitwise operations do exactly this. dwordWidth = m_lVidWidth / 4; // aligned width of the row, in DWORDS // (pixel by 3 bytes over sizeof(DWORD)) for( row = 0; row< (UINT)m_lVidHeight; row++) { pdwS = ( DWORD*)pBmpBuffer; pdwD = ( DWORD*)pTxtBuffer; for( col = 0; col < dwordWidth; col ++ ) { pdwD[0] = pdwS[0] | 0xFF000000; pdwD[1] = ((pdwS[1]<<8) | 0xFF000000) | (pdwS[0]>>24); pdwD[2] = ((pdwS[2]<<16) | 0xFF000000) | (pdwS[1]>>16); pdwD[3] = 0xFF000000 | (pdwS[2]>>8); pdwD +=4; pdwS +=3; } // we might have remaining (misaligned) bytes here pbS = (BYTE*) pdwS; for( col = 0; col < (UINT)m_lVidWidth % 4; col++) { *pdwD = 0xFF000000 | (pbS[2] << 16) | (pbS[1] << 8) | (pbS[0]); pdwD++; pbS += 3; } pBmpBuffer += m_lVidPitch; pTxtBuffer += lTxtPitch; }// for rows } if (m_TextureFormat == D3DFMT_A1R5G5B5) { for(int y = 0; y < m_lVidHeight; y++ ) { BYTE *pBmpBufferOld = pBmpBuffer; BYTE *pTxtBufferOld = pTxtBuffer; for (int x = 0; x < m_lVidWidth; x++) { *(WORD *)pTxtBuffer = (WORD) (0x8000 + ((pBmpBuffer[2] & 0xF8) << 7) + ((pBmpBuffer[1] & 0xF8) << 2) + (pBmpBuffer[0] >> 3)); pTxtBuffer += 2; pBmpBuffer += 3; } pBmpBuffer = pBmpBufferOld + m_lVidPitch; pTxtBuffer = pTxtBufferOld + lTxtPitch; } } // Unlock the Texture if (FAILED(m_pTexture->UnlockRect(0))) return E_FAIL; return S_OK; }
[ [ [ 1, 302 ] ] ]
2be367be302ff24ed2602267c1fc8e52d492a5fa
49b6646167284329aa8644c8cf01abc3d92338bd
/SEP2_M6/Functor/CallBackThrower.cpp
b1783002d1cf3f2fbc304edde81aca5f0e042c72
[]
no_license
StiggyB/javacodecollection
9d017b87b68f8d46e09dcf64650bd7034c442533
bdce3ddb7a56265b4df2202d24bf86a06ecfee2e
refs/heads/master
2020-08-08T22:45:47.779049
2011-10-24T12:10:08
2011-10-24T12:10:08
32,143,796
0
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
/** * Functor Pattern. * * SE2 (+ SY and PL) Project SoSe 2011 * * Authors: Rico Flaegel, * Tell Mueller-Pettenpohl, * Torsten Krane, * Jan Quenzel * * This class generalize all different classes for * one callback type. * */ #include "CallBackThrower.h" CallBackThrower::CallBackThrower() { } CallBackThrower::~CallBackThrower() { }
[ "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1", "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1" ]
[ [ [ 1, 12 ] ], [ [ 13, 24 ] ] ]
81d30bcef5a3b94a26df12a3dee93237e35b982d
bf4f0fc16bd1218720c3f25143e6e34d6aed1d4e
/Compatibility.cpp
c9df1c5f05a6fcf660dafafb567e2320b2ddbd6d
[]
no_license
shergin/downright
4b0f161700673d7eb49459e4fde2b7d095eb91bb
6cc40cd35878e58f4ae8bae8d5e58256e6df4ce8
refs/heads/master
2020-07-03T13:34:20.697914
2009-09-29T19:15:07
2009-09-29T19:15:07
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,540
cpp
#include "StdAfx.h" #include "compatibility.h" #include "StringTool.h" CCompatibility::CCompatibility(void) { m_nStrings=0; m_Type=0; } CCompatibility::~CCompatibility(void) { } CCompatibility& CCompatibility::operator = (const CCompatibility &obj) { m_nStrings=obj.m_nStrings; m_Type=obj.m_Type; // implementation m_Actions=obj.m_Actions; m_Strings.RemoveAll(); m_Strings.SetSize(m_nStrings); for(int i=0;i<m_nStrings;i++) { m_Strings.SetAtGrow(i,const_cast<CString&>(obj.m_Strings[i])); } // end of implementation return *this; } void CCompatibility::operator = (CString s) { m_nStrings=0; long length=s.GetLength(); // определяем тип if(length<3)return; if(s.GetAt(1)!='|')return; switch(s.GetAt(0)) { case '1':m_Type=1;break; case '2':m_Type=2;break; default:return; } s.Delete(0,2); length-=2; CString temp; TCHAR ch=0; int p=0; for(int i=0;i<length;i++) { ch=s.GetAt(i); if((ch=='|')||(i+1==length)) { if(ch!='|')temp+=ch; m_Strings.SetAtGrow(m_nStrings,FromSafe(temp)); TRACE(temp+_T(" %i \n"),m_nStrings); m_nStrings++; temp.Empty(); } else temp+=ch; } } CCompatibility::operator CString() { if( m_Type<1 || m_Type>2 )return _T(""); if(m_nStrings<=0)return _T(""); CString result; if(m_Type==1)result=_T("1|"); if(m_Type==2)result=_T("2|"); for(int i=0;i<m_nStrings;i++) { result+=ToSafe(m_Strings[i]); if(i+1!=m_nStrings)result+=_T("|"); } return result; }
[ [ [ 1, 79 ] ] ]
bbaec4ea473fdd9073fb61e22add76a6bc67c3fd
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/romtools/rofsbuild/r_coreimage.h
68596c6de6b7796aaf4695db04f277ecec897ce7
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,805
h
/* * Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef __R_COREIMAGE_H__ #define __R_COREIMAGE_H__ class TRomNode; class E32Rofs; /** @internalComponent MRofsImage is the interface used to access information held within an image. This interface used to remove the dependency between processing of extensions and kernel commands in the obey file */ class MRofsImage { public: /** Gets the root directory node from the image @return TRomNode* the first node in the directory tree */ virtual TRomNode* RootDirectory() = 0; /** Copies the specified directory tree. @param aSourceDirectory The directory that is to be copied @return The copied directory tree. */ virtual TRomNode* CopyDirectory(TRomNode*& aSourceDirectory)=0; /** Sets the root directory to be the specified node. @param aDir The node that is to be set as the root directory */ virtual void SetRootDirectory(TRomNode* aDir) = 0; /** Gets the filename of the core image @returns The filename of the core image file */ virtual const char* RomFileName() const = 0; /** Gets the size of the image file @returns size of file */ virtual TInt Size() const = 0; #ifdef __LINUX__ virtual ~MRofsImage(){} #endif }; const int K_ID_SIZE=4; /** Size of the image header identifier */ /** @internalComponent Provides the access the actual core image file. All file operations to the core image file are through this class. */ class RCoreImageReader { public: /** Image Type read from header of image file */ enum TImageType { /** Format of file has not been recognised */ E_UNKNOWN, /** File is a core RofsImage file */ E_ROFS, /** File is an extension RofsImage file */ E_ROFX }; RCoreImageReader(const char *aFilename); ~RCoreImageReader(); TBool Open(); TImageType ReadImageType(); TInt ReadCoreHeader(TRofsHeader& aHeader); TInt ReadExtensionHeader(TExtensionRofsHeader& aHeader); TInt ReadDirEntry(TRofsDir& aDir); TInt ReadDirEntry(TRofsDir& aDir, size_t aFilePos); size_t FilePosition(); void SetFilePosition(size_t aFilePos); TInt ReadRofEntry(TRofsEntry& aEntry); TInt ReadRofEntry(TRofsEntry& aEntry, size_t aFilePos); TInt ReadRofEntryName(TUint16* aName, int aLength); TBool IsValidPosition(size_t aFilePos); const char* Filename() const ; private: TInt ReadIdentifier(); TInt ImageError(int aBytesRead, int aExpected, char* aInfo); /** Image type of the file being read */ TImageType iImageType; /** File object of core image being read */ ifstream iCoreImage; /** Filename of core image file */ string iFilename; /** Image type identifier read from image header */ TUint8 iIdentifier[K_ID_SIZE]; }; /** @internalComponent Processes the core image file to create a directory tree. It is used when the coreimage option has been specified either on the command line or in the obey file. It implements the MRofsImage so it can be used by the extension image processing. */ class CCoreImage : public MRofsImage { public: CCoreImage(RCoreImageReader* aReader); virtual TInt ProcessImage(); void Display(ostream* aOut); virtual ~CCoreImage(); // Implementation of MRofsImage TRomNode* RootDirectory(); TRomNode* CopyDirectory(TRomNode*& aSourceDirectory); void SetRootDirectory(TRomNode* aDir); const char* RomFileName() const; TInt Size() const; protected: void SaveDirInfo(TRofsHeader& header); void SaveDirInfo(TExtensionRofsHeader& header); TInt ProcessDirectory(long aAdjustment); TInt CreateRootDir(); long DirTreeOffset(); /** used to read the core image file*/ RCoreImageReader *iReader; private: /** The node for the root directory */ TRomNode *iRootDirectory; /** The first node in list of file entries */ TRomBuilderEntry *iFileEntries; /** Offset to the directory tree in the core image */ long iDirTreeOffset; /** Size of the directory tree in the core image */ long iDirTreeSize; /** Offset to the file entries of the directory in the core image */ long iDirFileEntriesOffset; /** Size of the file entries block of the directory */ long iDirFileEntriesSize; /** Filename of the rom image file */ string iRomFileName; /** Size of image */ TInt iImageSize; }; /** @internalComponent Used for handling a single directory entry in the core image. This class allows the directory tree to be created recursively. */ class TDirectoryEntry { public: TDirectoryEntry(long filePos, RCoreImageReader* aReader, TRomNode* aCurrentDir); ~TDirectoryEntry(); TInt Process(long adjustment); private: TInt CreateFileEntry(const char* aName, TRofsEntry& aRofsEntry); TInt AddSubDirs(long endDirPos); TInt AddFiles(long startPos, int size); /** Handle to core image file */ RCoreImageReader* iReader; /** Node for the current directory */ TRomNode* iCurrentDir; /** Current position in the file */ long iFilePos; /** The references in the extension directory tree are relative the core image and not the actual offset in the file. This variable holds the difference between the entries in the directory tree and the actual file position. This allows the same methods to be used for both core and extension images. */ long iAdjustment; }; #endif
[ "none@none" ]
[ [ [ 1, 206 ] ] ]
7be160f12e77e16f0c1fbf4a9f6414ffa5ccb4f8
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SRC/DRIVERS/DISPLAY/DISPLAY_DRV/blt.cpp
57e88c6c98ec8490a7dd1020b0e9ce5aec788c9c
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
50,197
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // // // Copyright (c) Samsung Electronics. Co. LTD. All rights reserved. // /*++ THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: blt.cpp Abstract: accelerated bitblt/rectangle for S3C6410 FIMGSE-2D Functions: Notes: --*/ #include "precomp.h" #include <dispperf.h> /// For Support Stretched Blt using HW DDGPESurf *gpScratchSurf; GPESurf *oldSrcSurf; SCODE S3C6410Disp::BltPrepare(GPEBltParms *pBltParms) { RECTL rectl; int iSwapTmp; BOOL bRotate = FALSE; static bool bIsG2DReady = false; DEBUGMSG (GPE_ZONE_INIT, (TEXT("%s\r\n"), _T(__FUNCTION__))); DispPerfStart(pBltParms->rop4); //< This will be '0' when not defined DO_DISPPERF DispPerfParam(pBltParms); // default to base EmulatedBlt routine pBltParms->pBlt = &GPE::EmulatedBlt; // catch all // see if we need to deal with cursor // check for destination overlap with cursor and turn off cursor if overlaps if (pBltParms->pDst == m_pPrimarySurface) // only care if dest is main display surface { if (m_CursorVisible && !m_CursorDisabled) { if (pBltParms->prclDst != NULL) // make sure there is a valid prclDst { rectl = *pBltParms->prclDst; // if so, use it // There is no guarantee of a well ordered rect in blitParamters // due to flipping and mirroring. if(rectl.top > rectl.bottom) { iSwapTmp = rectl.top; rectl.top = rectl.bottom; rectl.bottom = iSwapTmp; } if(rectl.left > rectl.right) { iSwapTmp = rectl.left; rectl.left = rectl.right; rectl.right = iSwapTmp; } } else { rectl = m_CursorRect; // if not, use the Cursor rect - this forces the cursor to be turned off in this case } if (m_CursorRect.top <= rectl.bottom && m_CursorRect.bottom >= rectl.top && m_CursorRect.left <= rectl.right && m_CursorRect.right >= rectl.left) { CursorOff(); m_CursorForcedOff = TRUE; } } } // check for source overlap with cursor and turn off cursor if overlaps if (pBltParms->pSrc == m_pPrimarySurface) // only care if source is main display surface { if (m_CursorVisible && !m_CursorDisabled) { if (pBltParms->prclSrc != NULL) // make sure there is a valid prclSrc { rectl = *pBltParms->prclSrc; // if so, use it } else { rectl = m_CursorRect; // if not, use the CUrsor rect - this forces the cursor to be turned off in this case } if (m_CursorRect.top < rectl.bottom && m_CursorRect.bottom > rectl.top && m_CursorRect.left < rectl.right && m_CursorRect.right > rectl.left) { CursorOff(); m_CursorForcedOff = TRUE; } } } // Fast Code entrance with Font Bitblt that not supported by other emulation code and acceleration hw // if(pBltParms->rop4 == 0xAAF0) { return S_OK; } if(pBltParms->pSrc && pBltParms->pSrc->IsRotate() || pBltParms->pDst && pBltParms->pDst->IsRotate() ) { bRotate = TRUE; pBltParms->pBlt = &GPE::EmulatedBltRotate; // catch all } // To extract 2d_accel_lib.lib totally, using preprocess statement #if USE_SECEMUL_LIBRARY if( m_G2DControlArgs.UseSWAccel && !bRotate ) { SECEmulatedBltSelect16(pBltParms); //< This can be overideded by HW acceleration. SECEmulatedBltSelect2416(pBltParms); SECEmulatedBltSelect1624(pBltParms); if(pBltParms->pBlt != (SCODE (GPE::*)(GPEBltParms *))&GPE::EmulatedBlt) { DispPerfType(DISPPERF_ACCEL_EMUL); } } #endif if( m_VideoPowerState != VideoPowerOff && // to avoid hanging while bring up display H/W m_G2DControlArgs.HWOnOff) { AcceleratedBltSelect(pBltParms); m_oG2D->WaitForIdle(); //< Wait for Fully Empty Command Fifo for all BitBlt request to synchronize with SW BitBlt } DEBUGMSG(GPE_ZONE_BLT_HI, (TEXT("--%s\r\n"), _T(__FUNCTION__))); return S_OK; } // This function would be used to undo the setting of clip registers etc SCODE S3C6410Disp::BltComplete(GPEBltParms *pBltParms) { DEBUGMSG (GPE_ZONE_BLT_HI, (TEXT("++%s()\r\n"), _T(__FUNCTION__))); // see if cursor was forced off because of overlap with source or destination and turn back on if (m_CursorForcedOff) { m_CursorForcedOff = FALSE; CursorOn(); } if(gpScratchSurf) { pBltParms->pSrc = oldSrcSurf; delete gpScratchSurf; gpScratchSurf=NULL; } DispPerfEnd(0); DEBUGMSG(GPE_ZONE_BLT_HI, (TEXT("--%s()\r\n"), _T(__FUNCTION__))); return S_OK; } /** * @fn SCODE S3C6410Disp::AcceleratedSolidFIll(GPEBltParms *pBltParms) * @brief Rectangle Solid Filling Function. Solid Fill has no Source Rectangle * @param pBltParms Blit Parameter Information Structure * @sa GPEBltParms * @note ROP : 0xF0F0 * @note Using Information : DstSurface, ROP, Solidcolor * @note SW ColorFill faster than HW ColorFill x2 times for 16Bpp */ SCODE S3C6410Disp::AcceleratedSolidFill(GPEBltParms *pBltParms) { PRECTL prclDst = pBltParms->prclDst; DEBUGMSG(GPE_ZONE_BLT_LO, (TEXT("++%s()\r\n"), _T(__FUNCTION__))); /** * Prepare Source & DestinationSurface Information */ DWORD dwTopStrideStartAddr = 0; // When Screen is rotated, ScreenHeight and ScreenWidth always has initial surface property. m_descDstSurface.dwHoriRes = SURFACE_WIDTH(pBltParms->pDst); /// Set Destination Surface Information if(pBltParms->pDst->InVideoMemory() ) { m_descDstSurface.dwBaseaddr = (m_VideoMemoryPhysicalBase + pBltParms->pDst->OffsetInVideoMemory()); /// If surface is created by user temporary, that has no screen width and height. m_descDstSurface.dwVertRes = (pBltParms->pDst->ScreenHeight() != 0 ) ? pBltParms->pDst->ScreenHeight() : pBltParms->pDst->Height(); } else { dwTopStrideStartAddr = m_dwPhyAddrOfSurface[1] + pBltParms->prclDst->top * ABS(pBltParms->pDst->Stride()); m_descDstSurface.dwBaseaddr = dwTopStrideStartAddr; m_descDstSurface.dwVertRes = RECT_HEIGHT(pBltParms->prclDst); pBltParms->prclDst->top = 0; pBltParms->prclDst->bottom = m_descDstSurface.dwVertRes; } m_oG2D->SetSrcSurface(&m_descDstSurface); // Fill dummy value m_oG2D->SetDstSurface(&m_descDstSurface); if(pBltParms->prclClip) { m_oG2D->SetClipWindow(pBltParms->prclClip); } else { if(pBltParms->pDst->IsRotate()) { RotateRectl(prclDst); } m_oG2D->SetClipWindow(prclDst); } m_oG2D->SetFgColor(pBltParms->solidColor); m_oG2D->Set3rdOperand(G2D_OPERAND3_FG); switch(pBltParms->rop4 & 0xFF) { // Pat Copy case 0xF0: m_oG2D->SetRopEtype(ROP_PAT_ONLY); break; // Pat Invert case 0x5A: m_oG2D->SetRopEtype(ROP_DST_XOR_PAT); break; } EnterCriticalSection(&m_cs2D); m_oG2D->BitBlt(prclDst, prclDst, ROT_0); LeaveCriticalSection(&m_cs2D); if(pBltParms->pDst->IsRotate()) { RotateRectlBack(prclDst); } DEBUGMSG(GPE_ZONE_BLT_LO, (TEXT("--%s()\r\n"), _T(__FUNCTION__))); return S_OK; } /** * @fn SCODE S3C6410Disp::AcceleratedPatFIll(GPEBltParms *pBltParms) * @brief Rectangle Pattern Filling Function. only 8x8x16bpp pattern * @param pBltParms Blit Parameter Information Structure * @sa GPEBltParms * @note ROP : 0xF0F0, 0x5A5A * @note Using Information : DstSurface, ROP, Pattern Brush */ // TODO: BitBlt with Pattern memory when used with small size pattern SCODE S3C6410Disp::AcceleratedPatFill(GPEBltParms *pBltParms) { PRECTL prclDst = pBltParms->prclDst; DEBUGMSG(GPE_ZONE_BLT_LO, (TEXT("++%s()\r\n"), _T(__FUNCTION__))); /** * Prepare Source & DestinationSurface Information */ DWORD dwTopStrideStartAddr = 0; // When Screen is rotated, ScreenHeight and ScreenWidth always has initial surface property. m_descDstSurface.dwHoriRes = SURFACE_WIDTH(pBltParms->pDst); /// Set Destination Surface Information if(pBltParms->pDst->InVideoMemory() ) { m_descDstSurface.dwBaseaddr = (m_VideoMemoryPhysicalBase + pBltParms->pDst->OffsetInVideoMemory()); /// If surface is created by user temporary, that has no screen width and height. m_descDstSurface.dwVertRes = (pBltParms->pDst->ScreenHeight() != 0 ) ? pBltParms->pDst->ScreenHeight() : pBltParms->pDst->Height(); } else { dwTopStrideStartAddr = m_dwPhyAddrOfSurface[1] + pBltParms->prclDst->top * ABS(pBltParms->pDst->Stride()); m_descDstSurface.dwBaseaddr = dwTopStrideStartAddr; m_descDstSurface.dwVertRes = RECT_HEIGHT(pBltParms->prclDst); pBltParms->prclDst->top = 0; pBltParms->prclDst->bottom = m_descDstSurface.dwVertRes; } m_oG2D->SetSrcSurface(&m_descDstSurface); // Fill dummy value m_oG2D->SetDstSurface(&m_descDstSurface); if(pBltParms->prclClip) { m_oG2D->SetClipWindow(pBltParms->prclClip); } else { if(pBltParms->pDst->IsRotate()) { RotateRectl(prclDst); } m_oG2D->SetClipWindow(prclDst); } m_oG2D->SetFgColor(pBltParms->solidColor); m_oG2D->Set3rdOperand(G2D_OPERAND3_FG); switch(pBltParms->rop4 & 0xFF) { // Pat Copy case 0xF0: m_oG2D->SetRopEtype(ROP_PAT_ONLY); break; // Pat Invert case 0x5A: m_oG2D->SetRopEtype(ROP_DST_XOR_PAT); break; } EnterCriticalSection(&m_cs2D); m_oG2D->BitBlt(prclDst, prclDst, ROT_0); LeaveCriticalSection(&m_cs2D); if(pBltParms->pDst->IsRotate()) { RotateRectlBack(prclDst); } DEBUGMSG(GPE_ZONE_BLT_LO, (TEXT("--%s()\r\n"), _T(__FUNCTION__))); return S_OK; } // This function will be supported in the future SCODE S3C6410Disp::AcceleratedDestInvert(GPEBltParms *pBltParms) { int dstX = pBltParms->prclDst->left; int dstY = pBltParms->prclDst->top; int width = RECT_WIDTH(pBltParms->prclDst); int height = RECT_HEIGHT(pBltParms->prclDst); return S_OK; } // Do NOTHING. SCODE S3C6410Disp::NullBlt(GPEBltParms *pBltParms) { return S_OK; } /// From Frame Buffer to Frame Buffer Directly /// Constraints /// Source Surface's width is same with Destination Surface's width. /// Source and Dest must be in Video FrameBuffer Region /// In Surface Format /// ScreenHeight and ScreenWidth means logical looking aspect for application /// Height and Width means real data format. /** * @fn SCODE S3C6410Disp::AcceleratedSrcCopyBlt(GPEBltParms *pBltParms) * @brief Do Blit with SRCCOPY, SRCAND, SRCPAINT, SRCINVERT * @param pBltParms Blit Parameter Information Structure * @sa GPEBltParms * @note ROP : 0xCCCC(SRCCOPY), 0x8888(SRCAND), 0x6666(SRCINVERT), 0XEEEE(SRCPAINT) * @note Using Information : DstSurface, ROP, Solidcolor */ SCODE S3C6410Disp::AcceleratedSrcCopyBlt (GPEBltParms *pBltParms) { PRECTL prclSrc, prclDst; RECT rectlSrcBackup; RECT rectlDstBackup; BOOL bHWSuccess = FALSE; prclSrc = pBltParms->prclSrc; prclDst = pBltParms->prclDst; // Set Destination Offset In Video Memory, this point is Dest lefttop point /** * Prepare Source & Destination Surface Information */ DWORD dwTopStrideStartAddr = 0; /// !!!!Surface Width may not match to Real Data format!!!! /// !!!!Set Width by Scan Stride Size!!!! m_descSrcSurface.dwHoriRes = SURFACE_WIDTH(pBltParms->pSrc); m_descDstSurface.dwHoriRes = SURFACE_WIDTH(pBltParms->pDst); if(pBltParms->pDst->IsRotate()) { RotateRectl(prclDst); //< RotateRectl rotate rectangle with screen rotation information if(pBltParms->prclClip) { RotateRectl(pBltParms->prclClip); } } if(pBltParms->pSrc->IsRotate()) { RotateRectl(prclSrc); } if (pBltParms->bltFlags & BLT_TRANSPARENT) { RETAILMSG(0,(TEXT("TransparentMode Color : %d\n"), pBltParms->solidColor)); // turn on transparency & set comparison color m_oG2D->SetTransparentMode(1, pBltParms->solidColor); } switch (pBltParms->rop4) { case 0x6666: // SRCINVERT RETAILMSG(DISP_ZONE_2D, (TEXT("SRCINVERT\r\n"))); m_oG2D->SetRopEtype(ROP_SRC_XOR_DST); break; case 0x8888: // SRCAND RETAILMSG(DISP_ZONE_2D, (TEXT("SRCAND\r\n"))); m_oG2D->SetRopEtype(ROP_SRC_AND_DST); break; case 0xCCCC: // SRCCOPY RETAILMSG(DISP_ZONE_2D, (TEXT("SRCCOPY\r\n"))); m_oG2D->SetRopEtype(ROP_SRC_ONLY); break; case 0xEEEE: // SRCPAINT RETAILMSG(DISP_ZONE_2D, (TEXT("SRCPAINT\r\n"))); m_oG2D->SetRopEtype(ROP_SRC_OR_DST); break; } /// Check Source Rectangle Address /// HW Coordinate limitation is 2040 /// 1. Get the Top line Start Address /// 2. Set the base offset to Top line Start Address /// 3. Recalulate top,bottom rectangle /// 4. Do HW Bitblt CopyRect(&rectlSrcBackup, (LPRECT)pBltParms->prclSrc); CopyRect(&rectlDstBackup, (LPRECT)pBltParms->prclDst); /// Destination's Region can have negative coordinate, especially for left, top point /// In this case, For both destination, source's rectangle must be clipped again to use HW. ClipDestDrawRect(pBltParms); /// Set Source Surface Information if(pBltParms->pSrc == pBltParms->pDst) // OnScreen BitBlt { if((pBltParms->pSrc)->InVideoMemory() ) { m_descSrcSurface.dwBaseaddr = (m_VideoMemoryPhysicalBase + pBltParms->pDst->OffsetInVideoMemory()); /// If surface is created by user temporary, that has no screen width and height. m_descSrcSurface.dwVertRes = (pBltParms->pSrc->ScreenHeight() != 0 ) ? pBltParms->pSrc->ScreenHeight() : pBltParms->pSrc->Height(); m_descDstSurface.dwBaseaddr = m_descSrcSurface.dwBaseaddr; m_descDstSurface.dwVertRes = m_descSrcSurface.dwVertRes; } else { dwTopStrideStartAddr = m_dwPhyAddrOfSurface[0]; m_descSrcSurface.dwBaseaddr = dwTopStrideStartAddr; m_descSrcSurface.dwVertRes = (pBltParms->pSrc->ScreenHeight() != 0 ) ? pBltParms->pSrc->ScreenHeight() : pBltParms->pSrc->Height(); m_descDstSurface.dwBaseaddr = m_descSrcSurface.dwBaseaddr; m_descDstSurface.dwVertRes = m_descSrcSurface.dwVertRes; } } else // OffScreen BitBlt { if(pBltParms->pSrc->InVideoMemory() ) { m_descSrcSurface.dwBaseaddr = (m_VideoMemoryPhysicalBase + pBltParms->pSrc->OffsetInVideoMemory()); /// If surface is created by user temporary, that has no screen width and height. m_descSrcSurface.dwVertRes = (pBltParms->pSrc->ScreenHeight() != 0 ) ? pBltParms->pSrc->ScreenHeight() : pBltParms->pSrc->Height(); } else { dwTopStrideStartAddr = m_dwPhyAddrOfSurface[0] + pBltParms->prclSrc->top * ABS(pBltParms->pSrc->Stride()); m_descSrcSurface.dwBaseaddr = dwTopStrideStartAddr; m_descSrcSurface.dwVertRes = RECT_HEIGHT(pBltParms->prclSrc); pBltParms->prclSrc->top = 0; pBltParms->prclSrc->bottom = m_descSrcSurface.dwVertRes; } /// Set Destination Surface Information if(pBltParms->pDst->InVideoMemory() ) { m_descDstSurface.dwBaseaddr = (m_VideoMemoryPhysicalBase + pBltParms->pDst->OffsetInVideoMemory()); /// If surface is created by user temporary, that has no screen width and height. m_descDstSurface.dwVertRes = (pBltParms->pDst->ScreenHeight() != 0 ) ? pBltParms->pDst->ScreenHeight() : pBltParms->pDst->Height(); } else { dwTopStrideStartAddr = m_dwPhyAddrOfSurface[1] + pBltParms->prclDst->top * ABS(pBltParms->pDst->Stride()); m_descDstSurface.dwBaseaddr = dwTopStrideStartAddr; m_descDstSurface.dwVertRes = RECT_HEIGHT(pBltParms->prclDst); pBltParms->prclDst->top = 0; pBltParms->prclDst->bottom = m_descDstSurface.dwVertRes; } } /// Transparency does not relate with alpha blending m_oG2D->SetAlphaMode(G2D_NO_ALPHA_MODE); /// No transparecy with alphablend m_oG2D->SetAlphaValue(0xff); m_oG2D->Set3rdOperand(G2D_OPERAND3_PAT); /// Real Register Surface Description setting will be done in HWBitBlt bHWSuccess = HWBitBlt(pBltParms, &m_descSrcSurface, &m_descDstSurface); CopyRect((LPRECT)pBltParms->prclSrc, &rectlSrcBackup); CopyRect((LPRECT)pBltParms->prclDst, &rectlDstBackup); if(pBltParms->pDst->IsRotate()) { RotateRectlBack(prclDst); if(pBltParms->prclClip) { RotateRectlBack(pBltParms->prclClip); } } if(pBltParms->pSrc->IsRotate()) { RotateRectlBack(prclSrc); } if (pBltParms->bltFlags & BLT_TRANSPARENT) { m_oG2D->SetTransparentMode(0, pBltParms->solidColor); // turn off Transparency } if(!bHWSuccess) { return EmulatedBlt(pBltParms); } return S_OK; } /** * @fn void S3C6410Disp::AcceleratedBltSelect(GpeBltParms *pBltParms) * @brief Select appropriate hardware acceleration function or software emulation function. * if there's no appropriate accelerated function, * Leave Blit funciton to intial setting, EmulatedBlt(generic Bit blit emulator) * @param pBltParms Blit Parameter Information Structure * @sa GPEBltParms */ SCODE S3C6410Disp::AcceleratedBltSelect(GPEBltParms *pBltParms) { if ((pBltParms->pBlt != (SCODE (GPE::*)(GPEBltParms *))&GPE::EmulatedBlt) && !m_G2DControlArgs.OverrideEmulFunc) { if(pBltParms->pSrc && pBltParms->pDst && (pBltParms->pSrc->Rotate() != pBltParms->pDst->Rotate())) { // In this case we will use HW, the rotation case RETAILMSG(FALSE,(TEXT("AlreadySelected But Rotation:0x%x\n"),pBltParms->pBlt)); } else { // Already Some Accelerated or Emulated Function is assigned. RETAILMSG(FALSE,(TEXT("AlreadySelected:0x%x\n"),pBltParms->pBlt)); return S_OK; } } if((pBltParms->rop4 != 0xCCCC) && (pBltParms->rop4 != 0xEEEE) && (pBltParms->rop4 != 0x6666) && (pBltParms->rop4 != 0x8888) && (pBltParms->rop4 != 0xF0F0) && (pBltParms->rop4 != 0x5A5A) ) { return S_OK; } if(pBltParms->rop4 == 0xF0F0 && !m_G2DControlArgs.UseFillRect) { return S_OK; } if(!m_G2DControlArgs.UseStretchBlt && (pBltParms->bltFlags & BLT_STRETCH)) //< can support Stretch Blit { return S_OK; } if(pBltParms->pLookup) { return S_OK; } if(!m_G2DControlArgs.UseAlphaBlend && (pBltParms->bltFlags & BLT_ALPHABLEND)) { return S_OK; } if(pBltParms->pDst) { m_descDstSurface.dwColorMode = GetHWColorFormat(pBltParms->pDst); if(m_descDstSurface.dwColorMode == G2D_COLOR_UNUSED) { RETAILMSG(DISP_ZONE_2D, (TEXT("2D HW does not support this color format\r\n"))); return S_OK; } } if(pBltParms->pSrc) { m_descSrcSurface.dwColorMode = GetHWColorFormat(pBltParms->pSrc); if(m_descSrcSurface.dwColorMode == G2D_COLOR_UNUSED) { RETAILMSG(DISP_ZONE_2D, (TEXT("2D HW does not support this color format\r\n"))); return S_OK; } } if(pBltParms->bltFlags & BLT_ALPHABLEND) //< Our HW can support AlphaBlend blit for 16bpp, 32bpp { //DumpBltParms(pBltParms); if(!pBltParms->pSrc) { return S_OK; } if(!(( &pBltParms->blendFunction != 0) && ( pBltParms->blendFunction.BlendFlags == 0) ) ) { RETAILMSG(DISP_ZONE_TEMP, (TEXT("AlphaBlend BitBlt with HW request is rejected.\r\n"))); RETAILMSG(DISP_ZONE_TEMP, (TEXT("SrcFormat:%d, BlendFunction : 0x%x Op(%d), Flag(%d),SourceConstantAlpha(%d),AlphaFormat(%d)\r\n"), pBltParms->pSrc->Format(), pBltParms->blendFunction, pBltParms->blendFunction.BlendOp, pBltParms->blendFunction.BlendFlags, pBltParms->blendFunction.SourceConstantAlpha, pBltParms->blendFunction.AlphaFormat)); return S_OK; } #if G2D_BYPASS_2STEP_PROCESS_PPA_AFTER_SCA if(pBltParms->blendFunction.SourceConstantAlpha != 0xFF && pBltParms->blendFunction.AlphaFormat == 1) { return S_OK; } #endif #if G2D_BYPASS_SOURCECONSTANT_ALPHABLEND // if(pBltParms->blendFunction.SourceConstantAlpha != 0xFF) { return S_OK; } #endif #if G2D_BYPASS_PERPIXEL_ALPHABLEND if(pBltParms->blendFunction.AlphaFormat == 1) { return S_OK; } #endif } if(!(pBltParms->bltFlags & BLT_ALPHABLEND)) { if(m_descSrcSurface.dwColorMode == G2D_COLOR_ARGB_8888) // We cannot do this { #if G2D_BYPASS_ALPHADIBTEST return S_OK; #else m_descSrcSurface.dwColorMode = G2D_COLOR_XRGB_8888; // Force to change RETAILMSG(DISP_ZONE_2D, (TEXT("Src change from ARGB to XRGB.\r\n"))); #endif } if(m_descDstSurface.dwColorMode == G2D_COLOR_ARGB_8888) // We cannot do this { #if G2D_BYPASS_ALPHADIBTEST return S_OK; #else m_descDstSurface.dwColorMode = G2D_COLOR_XRGB_8888; // Force to change RETAILMSG(DISP_ZONE_2D, (TEXT("Dst change from ARGB to XRGB.\r\n"))); #endif } } if(pBltParms->pConvert) //< Emulate if color conversion required { if(!pBltParms->pSrc) { return S_OK; } } if(pBltParms->prclClip && (pBltParms->prclClip->left == pBltParms->prclClip->right) && (pBltParms->prclClip->top == pBltParms->prclClip->bottom)) { // Just skip, there is no image flushing to screen // SW bitblt takes this case, and it can skip more efficiently. // RETAILMSG(DISP_ZONE_TEMP, (TEXT("Skip, no image to bitblt\r\n"))); // pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::NullBlt; return S_OK; } /// Odd case do nothing if(pBltParms->pSrc && pBltParms->prclSrc) { if((pBltParms->prclSrc->right == pBltParms->prclSrc->left) || (pBltParms->prclSrc->bottom == pBltParms->prclSrc->top)) { // RETAILMSG(DISP_ZONE_TEMP, (TEXT("Skip, no image to bitblt\r\n"))); // pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::NullBlt; return S_OK; } } if(pBltParms->pDst && pBltParms->prclDst) { /// Odd case do nothing if ((pBltParms->prclDst->right == pBltParms->prclDst->left) || (pBltParms->prclDst->bottom == pBltParms->prclDst->top)) { // RETAILMSG(DISP_ZONE_TEMP, (TEXT("Skip, no image to bitblt\r\n"))); // pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::NullBlt; return S_OK; } } /** * Check if source and destination regions' coordinates has positive value. * * **/ if ((pBltParms->bltFlags & BLT_STRETCH)) // Stretch Bllitting with X or Y axis mirroring { //DumpBltParms(pBltParms); if(!pBltParms->prclDst || !pBltParms->prclSrc) { return S_OK; } else { if ((pBltParms->prclDst->left < 0) || (pBltParms->prclDst->right <0 ) || (pBltParms->prclDst->top <0 ) || (pBltParms->prclDst->bottom <0)) { return S_OK; } if ((pBltParms->prclSrc->left < 0) || (pBltParms->prclSrc->right <0 ) || (pBltParms->prclSrc->top <0 ) || (pBltParms->prclSrc->bottom <0)) { return S_OK; } } if((RECT_HEIGHT(pBltParms->prclDst) > pBltParms->pDst->Height()) || (RECT_WIDTH(pBltParms->prclDst) > pBltParms->pDst->Width())) { return S_OK; } } /// Prevent Condition Check Fail Case m_dwPhyAddrOfSurface[0] = NULL; m_dwPhyAddrOfSurface[1] = NULL; // select accelerated function based on rop value switch (pBltParms->rop4) { case 0xCCCC: // SRCCOPY /// There are no image to draw. if( pBltParms->prclDst && (pBltParms->prclDst->right < 0 || pBltParms->prclDst->bottom < 0 || pBltParms->prclDst->top > pBltParms->pDst->Height() || pBltParms->prclDst->left > SURFACE_WIDTH(pBltParms->pDst)) ) { return S_OK; } if( pBltParms->prclDst && pBltParms->pSrc && (SURFACE_WIDTH(pBltParms->pDst) < MAX_2DHW_WIDTH) && (SURFACE_WIDTH(pBltParms->pSrc) < MAX_2DHW_WIDTH) #if G2D_BLT_OPTIMIZE && (ABS(RECT_WIDTH(pBltParms->prclSrc))*ABS(RECT_HEIGHT(pBltParms->prclSrc)*BYTES_PER_PIXEL(pBltParms->pSrc)) > G2D_COMPROMISE_LIMIT) #endif ) { if( ( (pBltParms->pSrc)->InVideoMemory() || (m_G2DControlArgs.CachedBlt && (m_dwPhyAddrOfSurface[0] = ValidatePAContinuityOfSurf(pBltParms->pSrc))) ) && ( pBltParms->pDst->InVideoMemory() || (m_G2DControlArgs.CachedBlt && (m_dwPhyAddrOfSurface[1] = ValidatePAContinuityOfSurf(pBltParms->pDst))) ) && (ABS(RECT_HEIGHT(pBltParms->prclSrc)) < MAX_2DHW_HEIGHT) && (ABS(RECT_WIDTH(pBltParms->prclSrc)) < MAX_2DHW_WIDTH) ) { // negative Stride for Alaphblend will be treated on HWBitBlt as Flip after Copy if(pBltParms->bltFlags & BLT_ALPHABLEND) { DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } else if(pBltParms->pSrc->Stride() > 0) { DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedSrcCopyBlt; } else if(pBltParms->pDst->Rotate() != DMDO_0 && pBltParms->pSrc->Rotate() != pBltParms->pDst->Rotate()) // DMDO_0=0, DMDO_90=1, DMDO_180=2, DMDO_270=4 { // Copy&Flip Whole Source Image into Temporary area // BitBlt from temporary area to Screen, This can treat Negative Stride Case. DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } return S_OK; } else{ if( (pBltParms->pSrc)->InVideoMemory() ){ RETAILMSG(DISP_ZONE_WARNING,(TEXT("INVideo:SRCCOPY!!!!!!\r\n"))); } else // Source is not in video memory, and not contiguous { // negative Stride for Alaphblend will be treated on HWBitBlt as Flip after Copy if(pBltParms->bltFlags & BLT_ALPHABLEND) { //DumpBltParms(pBltParms); DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } /// If Stretch is needed, HW is more efficient. /// so in this case, copy va to pa's scratched buffer, then use HW else if(pBltParms->bltFlags & BLT_STRETCH) { DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } else if(pBltParms->pDst->Rotate() != DMDO_0 && pBltParms->pSrc->Rotate() != pBltParms->pDst->Rotate()) // DMDO_0=0, DMDO_90=1, DMDO_180=2, DMDO_270=4 { // Copy&Flip Whole Source Image into Temporary area // BitBlt from temporary area to Screen, This can treat Negative Stride Case. DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } // Other case we cannot treat, maybe that's just SRCCOPY without any rotation, alphablend, stretch RETAILMSG(DISP_ZONE_WARNING,(TEXT("NotInVideo:SRCCOPY\r\n"))); } } } return S_OK; case 0x6666: // SRCINVERT case 0x8888: // SRCAND case 0xEEEE: // SRCPAINT if( pBltParms->prclDst && ((pBltParms->prclDst->left >= 0) && (pBltParms->prclDst->top >= 0) && (pBltParms->prclDst->right >= 0 ) && (pBltParms->prclDst->bottom >= 0 )) && pBltParms->pSrc && (SURFACE_WIDTH(pBltParms->pDst) < MAX_2DHW_WIDTH) && (SURFACE_WIDTH(pBltParms->pSrc) < MAX_2DHW_WIDTH) #if G2D_BLT_OPTIMIZE && (ABS(RECT_WIDTH(pBltParms->prclSrc))*ABS(RECT_HEIGHT(pBltParms->prclSrc)*BYTES_PER_PIXEL(pBltParms->pSrc)) > G2D_COMPROMISE_LIMIT) #endif ) { if( ( (pBltParms->pSrc)->InVideoMemory() || (m_G2DControlArgs.CachedBlt && (m_dwPhyAddrOfSurface[0] = ValidatePAContinuityOfSurf(pBltParms->pSrc))) ) && ( pBltParms->pDst->InVideoMemory() || (m_G2DControlArgs.CachedBlt && (m_dwPhyAddrOfSurface[1] = ValidatePAContinuityOfSurf(pBltParms->pDst))) ) && (ABS(RECT_HEIGHT(pBltParms->prclSrc)) < MAX_2DHW_HEIGHT) && (ABS(RECT_WIDTH(pBltParms->prclSrc)) < MAX_2DHW_WIDTH) ) { // negative Stride for Alaphblend will be treated on HWBitBlt as Flip after Copy if(pBltParms->bltFlags & BLT_ALPHABLEND) { DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } else if(pBltParms->pSrc->Stride() > 0) { DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedSrcCopyBlt; } else if(pBltParms->pDst->Rotate() != DMDO_0 && pBltParms->pSrc->Rotate() != pBltParms->pDst->Rotate()) // DMDO_0=0, DMDO_90=1, DMDO_180=2, DMDO_270=4 { // Copy&Flip Whole Source Image into Temporary area // BitBlt from temporary area to Screen DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } return S_OK; } else{ if( (pBltParms->pSrc)->InVideoMemory() ){ RETAILMSG(FALSE,(TEXT("INVideo:ROP:0x%x\r\n"), pBltParms->rop4)); } else { // negative Stride for Alaphblend will be treated on HWBitBlt as Flip after Copy if(pBltParms->bltFlags & BLT_ALPHABLEND) { DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedAlphaSrcCopyBlt; } RETAILMSG(FALSE,(TEXT("NotInVideo:ROP:0x%x\r\n"), pBltParms->rop4)); } } } return S_OK; case 0xF0F0: // PATCOPY case 0x5A5A: // PATINVERT if( pBltParms->solidColor != -1) // must be a solid colored brush { if(pBltParms->prclDst && ( (pBltParms->prclDst->left >= 0) && (pBltParms->prclDst->left < MAX_2DHW_XCOORD) && (pBltParms->prclDst->top >= 0) && (pBltParms->prclDst->top < MAX_2DHW_YCOORD) && (pBltParms->prclDst->right >= 0 ) && (pBltParms->prclDst->right < MAX_2DHW_YCOORD) && (pBltParms->prclDst->bottom >= 0 ) && (pBltParms->prclDst->bottom < MAX_2DHW_YCOORD) ) && (SURFACE_WIDTH(pBltParms->pDst) < MAX_2DHW_WIDTH) #if G2D_BLT_OPTIMIZE && (ABS(RECT_WIDTH(pBltParms->prclDst))*ABS(RECT_HEIGHT(pBltParms->prclDst)*BYTES_PER_PIXEL(pBltParms->pDst)) > G2D_COMPROMISE_LIMIT) #endif ) { if( ( pBltParms->pDst->InVideoMemory() || (m_G2DControlArgs.CachedBlt && (m_dwPhyAddrOfSurface[1] = ValidatePAContinuityOfSurf(pBltParms->pDst))) ) && (ABS(RECT_HEIGHT(pBltParms->prclDst)) < MAX_2DHW_HEIGHT) && (ABS(RECT_WIDTH(pBltParms->prclDst)) < MAX_2DHW_WIDTH) ) { DumpBltParms(pBltParms); DispPerfType(DISPPERF_ACCEL_HARDWARE); pBltParms->pBlt = (SCODE (GPE::*)(struct GPEBltParms *)) &S3C6410Disp::AcceleratedSolidFill; return S_OK; } } } return S_OK; default: // unsupported ROP4 to accelerate return S_OK; } return S_OK; } #define PFN_SHIEFT UserKInfo[KINX_PFN_SHIFT] #define MAX_SUPPORTED_PFN (MAXDWORD>>PFN_SHIEFT) #define PAGE_MASK (PAGE_SIZE-1) #define DBGMSG_SRCC (FALSE) /** * @fn SCODE S3C6410DISP::ValidatePAContinuityOfSurf(GPESurf *pTargetSurf) * @brief If possible, clean dcahce for Source Rectangle * @param pTargetSurf Surface pointer of Target Surface * @sa GPESurf * @note for support cb to ncnb bitblt * @note Bitmap image has top-down or bottom-up style memory region, * we can determine that by stride as positive(top-down) or as negative(bottom-up) * bottom-up bitmap mean buffer's start address is last addres of image buffer * image's start address is calculated as (Buffer address + Stride(negative) * height) * @return DWORD PhysAddressofSurface */ DWORD S3C6410Disp::ValidatePAContinuityOfSurf( GPESurf *pTargetSurf ) { BOOL m_fLocked; LPVOID m_lpvLockedAddress; DWORD m_dwLockedSize; DWORD dwLength = 0; DWORD dwSrcSurfaceSize = 0; PDWORD m_pdwPhysAddress = 0; PDWORD m_pdwPhysLength; PBYTE * m_ppVirtAddress; PVOID pUseBufferPtr = 0; PVOID pVirtualStartPtr = 0; // Normally negative stride can be found on system memory bitmap image. or DIB if(pTargetSurf->Stride() < 0) { RETAILMSG(DBGMSG_SRCC, (TEXT("Currently we cannot handle bottom-up bitmap using HW\r\n"))); return NULL; } // Check the start address // Check if data is allocated across different pages // usable macros // VM_PAGE_OFST_MASK // VM_PAGE_SHIFT // VM_PAGE_SIZE // uCount++; ASSERT(m_pdwPhysAddress==0); ASSERT((PAGE_MASK & PAGE_SIZE) == 0 ); dwLength = pTargetSurf->Height() * ABS(pTargetSurf->Stride()); RETAILMSG(DBGMSG_SRCC,(TEXT("TargetSurf 0x%x, Height : %d, Stride : %d\r\n"),pTargetSurf->Buffer(), pTargetSurf->Height(), pTargetSurf->Stride())); //< XPositive, yPositive // Todo: Check the Data Size // if size is not big to get efficiency. return false #if (_WIN32_WCE < 600) if(pTargetSurf->Stride() < 0) { pUseBufferPtr = MapPtrToProcess((PDWORD)((DWORD)pTargetSurf->Buffer() - dwLength + ABS(pTargetSurf->Stride())), (HANDLE)GetCurrentProcessId()); pVirtualStartPtr = MapPtrToProcess(pUseBufferPtr, (HANDLE)GetCurrentProcessId()); } else { pUseBufferPtr = MapPtrToProcess((PDWORD)pTargetSurf->Buffer(), (HANDLE)GetCurrentProcessId()); pVirtualStartPtr = MapPtrToProcess(pUseBufferPtr, (HANDLE)GetCurrentProcessId());; } #else if(pTargetSurf->Stride() < 0) { pUseBufferPtr = (PDWORD)((DWORD)pTargetSurf->Buffer() - dwLength + ABS(pTargetSurf->Stride())); pVirtualStartPtr = pUseBufferPtr; } else { pUseBufferPtr = (PDWORD)pTargetSurf->Buffer(); pVirtualStartPtr = pUseBufferPtr; } #endif UINT nPages = ADDRESS_AND_SIZE_TO_SPAN_PAGES( pUseBufferPtr, dwLength ); m_pdwPhysAddress = new DWORD[3*nPages]; // It's really sturcture {m_pdwPhysAddress, m_pdwPhysLength, m_ppVirtAddress} if (m_pdwPhysAddress) { m_pdwPhysLength = m_pdwPhysAddress + nPages; m_ppVirtAddress = (PBYTE *)(m_pdwPhysAddress + 2*nPages); RETAILMSG(DBGMSG_SRCC,(TEXT("pUseBufferPtr:0x%x, dwLength:%d, m_pdwPhysAddress:0x%x.\r\n"), pUseBufferPtr, dwLength, m_pdwPhysAddress)); m_fLocked = LockPages( pUseBufferPtr, dwLength, m_pdwPhysAddress, LOCKFLAG_QUERY_ONLY); // Src to Dst if (!m_fLocked) { // Create table for Physical Address and length. RETAILMSG(DBGMSG_SRCC,(TEXT("LockPages is Failed : %d\r\n"), GetLastError() )); FreePhysAddress(m_pdwPhysAddress); return NULL; } m_lpvLockedAddress = pUseBufferPtr; m_dwLockedSize = dwLength; RETAILMSG(DBGMSG_SRCC,(TEXT("pVirtualStartPtr:0x%x.\r\n"), pVirtualStartPtr)); /// Get each Physical address pages from pagelocked information for (DWORD dwIndex = 0; dwIndex< nPages; dwIndex++) { if (m_pdwPhysAddress[dwIndex] > MAX_SUPPORTED_PFN) { ASSERT(FALSE); FreePhysAddress(m_pdwPhysAddress); return NULL; //< NULL is FAIL } DWORD dwSize = min((PAGE_SIZE - ((DWORD)pUseBufferPtr & PAGE_MASK)),dwLength) ; m_pdwPhysAddress[dwIndex] = (m_pdwPhysAddress[dwIndex]<<PFN_SHIEFT) + ((DWORD)pUseBufferPtr & PAGE_MASK); m_pdwPhysLength[dwIndex] = dwSize; m_ppVirtAddress[dwIndex] = (PBYTE)pUseBufferPtr; dwLength -= dwSize; pUseBufferPtr = (PBYTE)pUseBufferPtr+dwSize; RETAILMSG(DBGMSG_SRCC,(TEXT("dwIndex : %d, m_pdwPhysAddress[%d]:0x%x, m_pdwPhysLength[%d]:%d, dwSize:%d, pUseBufferPtr(PageEnd):0x%x.\r\n"), dwIndex, dwIndex, m_pdwPhysAddress[dwIndex], dwIndex, m_pdwPhysLength[dwIndex], dwSize, pUseBufferPtr )); } /// Check if Source Pages is contiguous in Physical memory address. DWORD dwRead = 1; while (dwRead < nPages) { if (m_pdwPhysAddress[dwRead - 1] + m_pdwPhysLength[dwRead - 1] == m_pdwPhysAddress[dwRead]) { // m_dwBlocks and m_dwBlocks+1 is contiguous. dwRead++; } else { // No match, We cannot use HW RETAILMSG(DBGMSG_SRCC,(TEXT("Source Memory Blocks is not congiuous : Go Emul path\r\n"))); FreePhysAddress(m_pdwPhysAddress); return NULL; //< NULL is Fail } } // Merge to one big contiguous memory block if(nPages > 1) { for(dwRead = 1 ; dwRead < nPages; dwRead++) { m_pdwPhysLength[0] += m_pdwPhysLength[dwRead]; } } } else { RETAILMSG(DBGMSG_SRCC,(TEXT("Not Enough Memory for m_pdwPhysAddress\r\n"))); FreePhysAddress(m_pdwPhysAddress); return NULL; //< NULL is Fail } // uPossibleCount ++; // RETAILMSG(TRUE,(TEXT("DCache Clean , Available Flow Count : %d avail. / %d Total \r\n"),uPossibleCount, uCount)); RETAILMSG(DBGMSG_SRCC,(TEXT("CacheFlush Start : 0x%x length : %d\r\n"), (PBYTE)pVirtualStartPtr, pTargetSurf->Height() * ABS(pTargetSurf->Stride()))); // Just Contiguous Source Surface can use HW // Cache flush for all surface region CacheRangeFlush( (PBYTE)pVirtualStartPtr, pTargetSurf->Height() * ABS(pTargetSurf->Stride()), CACHE_SYNC_WRITEBACK); RETAILMSG(DBGMSG_SRCC,(TEXT("m_pdwPhysAddress[0] : 0x%x\r\n"), m_pdwPhysAddress[0])); m_dwSourceSurfacePA = m_pdwPhysAddress[0]; //< Just leave for compatiblilty FreePhysAddress(m_pdwPhysAddress); return m_dwSourceSurfacePA; } void S3C6410Disp::FreePhysAddress(DWORD *m_pdwPhysAddress) { if(m_pdwPhysAddress) { delete [] m_pdwPhysAddress; m_pdwPhysAddress=NULL; } } void S3C6410Disp::ClipDestDrawRect(GPEBltParms *pBltParms) { if(pBltParms->pDst->InVideoMemory() ) { if(pBltParms->prclDst->left < 0) { pBltParms->prclSrc->left -= pBltParms->prclDst->left; pBltParms->prclDst->left = 0; } if(pBltParms->prclDst->top < 0) { pBltParms->prclSrc->top -= pBltParms->prclDst->top; pBltParms->prclDst->top = 0; } } } DWORD S3C6410Disp::GetHWColorFormat(GPESurf *pSurf) { DWORD dw2DHWColorFormat = G2D_COLOR_UNUSED; if(pSurf) { GPEFormat * pFormat; pFormat = pSurf->FormatPtr(); if (pSurf->Format() == gpe16Bpp) { if (pFormat->m_pPalette) { if (pFormat->m_PaletteEntries == 3 && pFormat->m_pPalette[0] == 0x0000f800 && // R pFormat->m_pPalette[1] == 0x000007e0 && // G pFormat->m_pPalette[2] == 0x0000001f) // B { dw2DHWColorFormat = G2D_COLOR_RGB_565; } else if (pFormat->m_PaletteEntries == 3 && pFormat->m_pPalette[0] == 0x00007c00 && // R pFormat->m_pPalette[1] == 0x000003e0 && // G pFormat->m_pPalette[2] == 0x0000001f) // B { dw2DHWColorFormat = G2D_COLOR_UNUSED;//G2D_COLOR_ARGB_1555; } else if (pFormat->m_PaletteEntries == 4 && pFormat->m_pPalette[3] == 0x00008000 && // A pFormat->m_pPalette[0] == 0x00007c00 && // R pFormat->m_pPalette[1] == 0x000003e0 && // G pFormat->m_pPalette[2] == 0x0000001f) // B { dw2DHWColorFormat = G2D_COLOR_ARGB_1555; } else { DEBUGMSG(GPE_ZONE_HW, (TEXT("pFormat->m_PaletteEntries=%08x\r\n"), pFormat->m_PaletteEntries)); for (int i=0; i<pFormat->m_PaletteEntries; i++) { DEBUGMSG(GPE_ZONE_HW, (TEXT("%d : 0x%08x\r\n"), i, pFormat->m_pPalette[i])); } dw2DHWColorFormat = G2D_COLOR_UNUSED; } } else { DEBUGMSG(GPE_ZONE_HW, (TEXT("Surface Format HAS NO PALETTE, we assume it's RGBx555\r\n"))); dw2DHWColorFormat = G2D_COLOR_UNUSED;//G2D_COLOR_ARGB_1555; } } else if (pSurf->Format() == gpe32Bpp) { if (pFormat->m_pPalette) { if (pFormat->m_PaletteEntries == 4 && pFormat->m_pPalette[3] == 0xff000000 && // A pFormat->m_pPalette[0] == 0x00ff0000 && // R pFormat->m_pPalette[1] == 0x0000ff00 && // G pFormat->m_pPalette[2] == 0x000000ff) // B { dw2DHWColorFormat = G2D_COLOR_ARGB_8888; } else if (//pFormat->m_PaletteEntries == 3 && pFormat->m_pPalette[0] == 0x00ff0000 && // R pFormat->m_pPalette[1] == 0x0000ff00 && // G pFormat->m_pPalette[2] == 0x000000ff) // B { dw2DHWColorFormat = G2D_COLOR_XRGB_8888; } else if (pFormat->m_PaletteEntries == 4 && pFormat->m_pPalette[3] == 0x000000ff && // A pFormat->m_pPalette[0] == 0xff000000 && // R pFormat->m_pPalette[1] == 0x00ff0000 && // G pFormat->m_pPalette[2] == 0x0000ff00) // B { dw2DHWColorFormat = G2D_COLOR_RGBA_8888; } else if (//pFormat->m_PaletteEntries == 3 && pFormat->m_pPalette[0] == 0xff000000 && // R pFormat->m_pPalette[1] == 0x00ff0000 && // G pFormat->m_pPalette[2] == 0x0000ff00) // B { dw2DHWColorFormat = G2D_COLOR_RGBX_8888; } else { DEBUGMSG(GPE_ZONE_HW, (TEXT("pFormat->m_PaletteEntries=%08x\r\n"), pFormat->m_PaletteEntries)); for (int i = 0; i<pFormat->m_PaletteEntries; i++) { DEBUGMSG(GPE_ZONE_HW, (TEXT("%d : 0x%08x\r\n"), i, pFormat->m_pPalette[i])); } dw2DHWColorFormat = G2D_COLOR_UNUSED; } } else { DEBUGMSG(GPE_ZONE_HW, (TEXT("Surface Format HAS NO PALETTE, we assume it as ABGR8888 and use ARGB8888\r\n"))); //dw2DHWColorFormat = G2D_COLOR_UNUSED; dw2DHWColorFormat = G2D_COLOR_ARGB_8888; } } DEBUGMSG(GPE_ZONE_HW, (TEXT("Surface:0x%x, GPEFormat:%d, HWColorMode:%d\n\r"), pSurf, pSurf->Format(), dw2DHWColorFormat)); return dw2DHWColorFormat; } RETAILMSG(DISP_ZONE_ERROR, (TEXT("Illegal Surface\n\r"))); return dw2DHWColorFormat; }
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 1257 ] ] ]
083ac4948e33fda9868efd8c4666c212543da5f7
3ec3b97044e4e6a87125470cfa7eef535f26e376
/timorg-chuzzle_bejeweled_clone/object_base.cpp
f26a4cede03d74f23d3984877d8ddde17441c977
[]
no_license
strategist922/TINS-Is-not-speedhack-2010
6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af
718b9d037606f0dbd9eb6c0b0e021eeb38c011f9
refs/heads/master
2021-01-18T14:14:38.724957
2010-10-17T14:04:40
2010-10-17T14:04:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
192
cpp
#include "object_base.h" OBJECT_BASE::OBJECT_BASE() { alive = true; } bool OBJECT_BASE::is_alive() { return alive; } void OBJECT_BASE::kill() { alive = false; }
[ [ [ 1, 16 ] ] ]
155114d1a0eb80bd2fac051dab441f1174c5da9f
e744c4dacc3b9c4a44a725e2601c678f29826ace
/project/jni/debug.cpp
6e4462f2429c0210952676bf7a2cb762df68e6bc
[]
no_license
jcayzac/androido3d
298559ebbe657482afe6b3b616561a1127320388
3466ed0ec790d8cbfe24cb5a4e72f1b432726e81
refs/heads/master
2016-09-06T06:31:09.984535
2010-12-28T01:45:39
2010-12-28T01:45:39
1,816,466
6
0
null
null
null
null
UTF-8
C++
false
false
12,812
cpp
/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ #include <jni.h> #include <android/log.h> #include <string> #define LOG_TAG "libo3djni" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #include "core/cross/buffer.h" #include "core/cross/draw_element.h" #include "core/cross/effect.h" #include "core/cross/element.h" #include "core/cross/material.h" #include "core/cross/param_array.h" #include "core/cross/primitive.h" #include "core/cross/render_node.h" #include "core/cross/sampler.h" #include "core/cross/shape.h" #include "core/cross/skin.h" #include "core/cross/texture.h" #include "core/cross/transform.h" void DumpMultiLineString(const std::string& str) { size_t pos = 0; int line_num = 1; for(;;) { size_t start = pos; pos = str.find_first_of('\n', pos); std::string line = str.substr(start, pos - start); DLOG(INFO) << line_num << ": " << line; if (pos == std::string::npos) { break; } ++pos; ++line_num; } } void DumpPoint3(const o3d::Point3& v, const char* label) { LOGI("%s: %.3f, %.3f, %.3f\n", label, v[0], v[1], v[2]); } void DumpVector3(const o3d::Vector3& v, const char* label) { LOGI("%s: %.3f, %.3f, %.3f\n", label, v[0], v[1], v[2]); } void DumpFloat3(const o3d::Float3& v, const char* label) { LOGI("%s: %.3f, %.3f, %.3f\n", label, v[0], v[1], v[2]); } void DumpVector4(const o3d::Vector4& v, const char* label) { LOGI("%s: %.3f, %.3f, %.3f, %.3f\n", label, v[0], v[1], v[2], v[3]); } void DumpFloat4(const o3d::Float4& v, const char* label) { LOGI("%s: %.3f, %.3f, %.3f, %.3f\n", label, v[0], v[1], v[2], v[3]); } void DumpParams(const o3d::ParamObject* obj, const std::string& indent) { if (obj) { const o3d::NamedParamRefMap& params = obj->params(); for (o3d::NamedParamRefMap::const_iterator it = params.begin(); it != params.end(); ++it) { o3d::Param* param = it->second; o3d::Param* input = param->input_connection(); std::string value = "--na--"; char buf[256]; if (param->IsA(o3d::ParamFloat::GetApparentClass())) { float v = static_cast<o3d::ParamFloat*>(param)->value(); sprintf(buf, "%.3f", v); value = buf; } else if (param->IsA(o3d::ParamFloat2::GetApparentClass())) { o3d::Float2 v = static_cast<o3d::ParamFloat2*>(param)->value(); sprintf(buf, "%.3f, %.3f", v[0], v[1]); value = buf; } else if (param->IsA(o3d::ParamFloat3::GetApparentClass())) { o3d::Float3 v = static_cast<o3d::ParamFloat3*>(param)->value(); sprintf(buf, "%.3f, %.3f, %.3f", v[0], v[1], v[2]); value = buf; } else if (param->IsA(o3d::ParamFloat4::GetApparentClass())) { o3d::Float4 v = static_cast<o3d::ParamFloat4*>(param)->value(); sprintf(buf, "%.3f, %.3f, %.3f, %.3f", v[0], v[1], v[2], v[3]); value = buf; } else if (param->IsA(o3d::ParamMatrix4::GetApparentClass())) { o3d::Matrix4 v = static_cast<o3d::ParamMatrix4*>(param)->value(); value = ""; for (size_t ii = 0; ii < 4; ++ii) { sprintf(buf, "[%.3f, %.3f, %.3f, %.3f]", v[ii][0], v[ii][1], v[ii][2], v[ii][3]); value += buf; } } else if (param->IsA(o3d::ParamBoundingBox::GetApparentClass())) { o3d::BoundingBox v = static_cast<o3d::ParamBoundingBox*>(param)->value(); sprintf(buf, "%s [%.3f, %.3f, %.3f], [%.3f, %.3f, %.3f]", v.valid() ? "valid" : "**invalid**", v.min_extent()[0], v.min_extent()[1], v.min_extent()[2],v.max_extent()[0], v.max_extent()[1], v.max_extent()[2]); value = buf; } else if (param->IsA(o3d::ParamInteger::GetApparentClass())) { int v = static_cast<o3d::ParamInteger*>(param)->value(); sprintf(buf, "%d", v); value = buf; } else if (param->IsA(o3d::ParamBoolean::GetApparentClass())) { bool v = static_cast<o3d::ParamBoolean*>(param)->value(); value = v ? "true" : "false"; } else if (param->IsA(o3d::ParamString::GetApparentClass())) { value = static_cast<o3d::ParamString*>(param)->value(); } else if (param->IsA(o3d::ParamMaterial::GetApparentClass())) { o3d::Material* v = static_cast<o3d::ParamMaterial*>(param)->value(); value = v ? v->name() : "NULL"; } else if (param->IsA(o3d::ParamEffect::GetApparentClass())) { o3d::Effect* v = static_cast<o3d::ParamEffect*>(param)->value(); value = v ? v->name() : "NULL"; } else if (param->IsA(o3d::ParamTexture::GetApparentClass())) { o3d::Texture* v = static_cast<o3d::ParamTexture*>(param)->value(); value = v ? v->name() : "NULL"; } else if (param->IsA(o3d::ParamSampler::GetApparentClass())) { o3d::Sampler* v = static_cast<o3d::ParamSampler*>(param)->value(); value = v ? v->name() : "NULL"; } else if (param->IsA(o3d::ParamSkin::GetApparentClass())) { o3d::Skin* v = static_cast<o3d::ParamSkin*>(param)->value(); value = v ? v->name() : "NULL"; } else if (param->IsA(o3d::ParamStreamBank::GetApparentClass())) { o3d::StreamBank* v = static_cast<o3d::ParamStreamBank*>(param)->value(); value = v ? v->name() : "NULL"; } else if (param->IsA(o3d::ParamParamArray::GetApparentClass())) { o3d::ParamArray* v = static_cast<o3d::ParamParamArray*>(param)->value(); value = v ? v->name() : "NULL"; } if (input) { LOGI("%s:Param: %s [%s] <- %s.%s\n", indent.c_str(), param->name().c_str(), param->GetClass()->name(), input->owner()->name().c_str(), input->name().c_str()); } else { LOGI("%s:Param: %s [%s] = %s\n", indent.c_str(), param->name().c_str(), param->GetClass()->name(), value.c_str()); } } } } void DumpRenderNode( const o3d::RenderNode* render_node, const std::string& indent) { if (render_node) { LOGI("%s%s\n", indent.c_str(), render_node->GetClass()->name()); DumpParams(render_node, indent + " "); const o3d::RenderNodeRefArray& children = render_node->children(); if (!children.empty()) { std::string inner = indent + " "; for (size_t ii = 0; ii < children.size(); ++ii) { DumpRenderNode(children[ii], inner); } } } } void DumpDrawElement( const o3d::DrawElement* drawelement, const std::string& indent) { if (drawelement) { LOGI("%sDrawElement: %s\n", indent.c_str(), drawelement->name().c_str()); DumpParams(drawelement, indent + " "); } } void DumpElement(const o3d::Element* element, const std::string& indent) { if (element) { const char* pre = indent.c_str(); LOGI("%sElement: %s\n", indent.c_str(), element->name().c_str()); DumpParams(element, indent + " "); if (element->IsA(o3d::Primitive::GetApparentClass())) { const o3d::Primitive* prim = down_cast<const o3d::Primitive*>(element); LOGI("%s num_primitives: %d\n", pre, prim->number_primitives()); LOGI("%s num_vertices: %d\n", pre, prim->number_vertices()); LOGI("%s prim_type: %d\n", pre, prim->primitive_type()); LOGI("%s start index: %d\n", pre, prim->start_index()); LOGI("%s indexbuffer: %s\n", pre, prim->index_buffer()->name().c_str()); o3d::StreamBank* sb = prim->stream_bank(); const o3d::StreamParamVector& params = sb->vertex_stream_params(); for (size_t jj = 0; jj < params.size(); ++jj) { const o3d::ParamVertexBufferStream* param = params[jj]; const o3d::Stream& stream = param->stream(); const o3d::Field& field = stream.field(); const o3d::Buffer* buffer = field.buffer(); LOGI("%s stream: s:%d si:%d start:%d numv:%d buf:%s:%s\n", pre, stream.semantic(), stream.semantic_index(), stream.start_index(), stream.GetMaxVertices(), buffer->name().c_str(), buffer->GetClass()->name()); unsigned num = std::min(buffer->num_elements(), 5u); float floats[5 * 4]; field.GetAsFloats(0, floats, field.num_components(), num); for (unsigned elem = 0; elem < num; ++elem) { float* v = &floats[elem * field.num_components()]; switch (field.num_components()) { case 1: LOGI("%s %d: %.3f\n", pre, elem, v[0]); break; case 2: LOGI("%s %d: %.3f, %.3f\n", pre, elem, v[0], v[1]); break; case 3: LOGI("%s %d: %.3f, %.3f, %.3f\n", pre, elem, v[0], v[1], v[2]); break; case 4: LOGI("%s %d: %.3f, %.3f, %.3f, %.3f\n", pre, elem, v[0], v[1], v[2], v[3]); break; } } const o3d::Param* input = param->input_connection(); if (input) { const o3d::ParamObject* owner = input->owner(); LOGI("%s input: %s:%s:%s:%s\n", pre, owner->name().c_str(), owner->GetClass()->name(), input->name().c_str(), input->GetClass()->name()); if (owner->IsA(o3d::SkinEval::GetApparentClass())) { const o3d::SkinEval* se = down_cast<const o3d::SkinEval*>(owner); LOGI("%s se skin: %s\n", pre, se->skin()->name().c_str()); LOGI("%s se mats: %s\n", pre,se->matrices()->name().c_str()); const o3d::ParamArray* pa = se->matrices(); LOGI("%s pa size: %d\n", pre, pa->size()); for (size_t pp = 0; pp < pa->size(); ++pp) { o3d::Param* mp = pa->GetUntypedParam(pp); o3d::Param* inp = mp->input_connection(); LOGI("%s %d: <- %s:%s\n", pre, pp, inp ? inp->owner()->name().c_str() : "-", inp ? inp->name().c_str() : "-"); } LOGI("%s -skineval-\n", pre); DumpParams(se, indent + " "); } } } } const o3d::DrawElementRefArray& draw_elements = element->GetDrawElementRefs(); if (!draw_elements.empty()) { std::string inner = indent + " "; for (size_t ii = 0; ii < draw_elements.size(); ++ii) { DumpDrawElement(draw_elements[ii], inner); } } } } void DumpShape(const o3d::Shape* shape, const std::string& indent) { if (shape) { LOGI("%sShape: %s\n", indent.c_str(), shape->name().c_str()); // const o3d::ElementRefArray& elements = shape->GetElementRefs(); // if (!elements.empty()) { // std::string inner = indent + " "; // for (size_t ii = 0; ii < elements.size(); ++ii) { // DumpElement(elements[ii], inner); // } // } } } void DumpTransform(const o3d::Transform* transform, const std::string& indent) { if (transform) { LOGI("%sTransform: %s\n", indent.c_str(), transform->name().c_str()); DumpParams(transform, indent + " "); const o3d::TransformRefArray& children = transform->GetChildrenRefs(); if (!children.empty()) { std::string inner = indent + " "; for (size_t ii = 0; ii < children.size(); ++ii) { DumpTransform(children[ii], inner); } } const o3d::ShapeRefArray& shapes = transform->GetShapeRefs(); if (!shapes.empty()) { std::string inner = indent + " "; for (size_t ii = 0; ii < shapes.size(); ++ii) { DumpShape(shapes[ii], inner); } } } } void DumpMatrix(const o3d::Matrix4& mat) { for (int ii = 0; ii < 4; ++ii) { LOGI(" %.3f, %.3f, %.3f, %.3f\n", mat[ii][0], mat[ii][1], mat[ii][2], mat[ii][3]); } } bool EndsWith(const std::string& str, const std::string& end) { return str.size() >= end.size() && str.substr(str.size() - end.size()).compare(end) == 0; }
[ [ [ 1, 313 ] ] ]
5fee7a161b3dc929dac8cbadb56167848ecf3716
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TEST_MyGUI_Source/MyGUIEngine/src/MyGUI_ComboBox.cpp
f8dfcdb551ef7be23692bedf83afcf3c265c37ae
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
10,250
cpp
/*! @file @author Albert Semenov @date 12/2007 @module */ #include "MyGUI_ComboBox.h" #include "MyGUI_ControllerManager.h" #include "MyGUI_InputManager.h" #include "MyGUI_WidgetManager.h" #include "MyGUI_Gui.h" #include "MyGUI_ControllerFadeAlpha.h" #include "MyGUI_List.h" #include "MyGUI_Button.h" #include "MyGUI_WidgetSkinInfo.h" #include "MyGUI_LayerManager.h" namespace MyGUI { const float COMBO_ALPHA_MAX = ALPHA_MAX; const float COMBO_ALPHA_MIN = ALPHA_MIN; const float COMBO_ALPHA_COEF = 4.0f; ComboBox::ComboBox(const IntCoord& _coord, char _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String & _name) : Edit(_coord, _align, _info, _parent, _creator, _name), mButton(null), mList(null), mListShow(false), mMaxHeight(0), mItemIndex(ITEM_NONE), mModeDrop(false), mDropMouse(false), mShowSmooth(false) { // парсим свойства const MapString & param = _info->getParams(); MapString::const_iterator iter = param.find("HeightList"); if (iter != param.end()) mMaxHeight = utility::parseInt(iter->second); iter = param.find("ListSmoothShow"); if (iter != param.end()) setSmoothShow(utility::parseBool(iter->second)); std::string listSkin, listLayer; iter = param.find("ListSkin"); if (iter != param.end()) listSkin = iter->second; iter = param.find("ListLayer"); if (iter != param.end()) listLayer = iter->second; // ручками создаем список mList = static_cast<ListPtr>(WidgetManager::getInstance().createWidget(List::_getType(), listSkin, IntCoord(), ALIGN_DEFAULT, null, this, "")); // присоединяем виджет с уровню и не добавляем себе LayerManager::getInstance().attachToLayerKeeper(listLayer, mList); //mList = static_cast<List>(_createWidget(List::_getType(), listSkin, IntCoord(), ALIGN_DEFAULT, listLayer, "")); mList->_setOwner(this); mList->hide(); mList->eventKeyLostFocus = newDelegate(this, &ComboBox::notifyListLostFocus); mList->eventListSelectAccept = newDelegate(this, &ComboBox::notifyListSelectAccept); mList->eventListMouseItemActivate = newDelegate(this, &ComboBox::notifyListMouseItemActivate); mList->eventListChangePosition = newDelegate(this, &ComboBox::notifyListChangePosition); // парсим кнопку for (VectorWidgetPtr::iterator iter=mWidgetChild.begin(); iter!=mWidgetChild.end(); ++iter) { if ((*iter)->_getInternalString() == "Button") { mButton = castWidget<Button>(*iter); mButton->eventMouseButtonPressed = newDelegate(this, &ComboBox::notifyButtonPressed); } } MYGUI_ASSERT(null != mButton, "Child Button not found in skin (combobox must have Button)"); // корректируем высоту списка if (mMaxHeight < (int)mList->getFontHeight()) mMaxHeight = (int)mList->getFontHeight(); // подписываем дочерние классы на скролл mWidgetUpper->eventMouseWheel = newDelegate(this, &ComboBox::notifyMouseWheel); mWidgetUpper->eventMouseButtonPressed = newDelegate(this, &ComboBox::notifyMousePressed); //mWidgetCursor->eventMouseWheel = newDelegate(this, &ComboBox::notifyMouseWheel); //mWidgetCursor->eventMouseButtonPressed = newDelegate(this, &ComboBox::notifyMousePressed); // подписываемся на изменения текста eventEditTextChange = newDelegate(this, &ComboBox::notifyEditTextChange); } ComboBox::~ComboBox() { // чтобы теперь удалить, виджет должен быть в нашем списке mWidgetChild.push_back(mList); WidgetManager::getInstance().destroyWidget(mList); } void ComboBox::notifyButtonPressed(MyGUI::WidgetPtr _sender, bool _left) { if (false == _left) return; mDropMouse = true; if (mListShow) hideList(); else showList(); } void ComboBox::notifyListLostFocus(MyGUI::WidgetPtr _sender, MyGUI::WidgetPtr _new) { if (mDropMouse) { mDropMouse = false; WidgetPtr focus = InputManager::getInstance().getMouseFocusWidget(); // кнопка сама уберет список if (focus == mButton) return; // в режиме дропа все окна учавствуют if ( (mModeDrop) && (focus == mWidgetUpper) ) return; } hideList(); } void ComboBox::notifyListSelectAccept(MyGUI::WidgetPtr _widget) { std::string str; size_t pos = mList->getItemSelect(); if (pos != ITEM_NONE) { mItemIndex = pos; str = mList->getItem(pos); } Edit::setCaption(str); mDropMouse = false; InputManager::getInstance().setKeyFocusWidget(this); if (mModeDrop) eventComboAccept(this); } void ComboBox::notifyListChangePosition(MyGUI::WidgetPtr _widget, size_t _position) { eventComboChangePosition(this, _position); } void ComboBox::_onKeyButtonPressed(int _key, Char _char) { Edit::_onKeyButtonPressed(_key, _char); // при нажатии вниз, показываем лист if (_key == OIS::KC_DOWN) { // выкидываем список только если мыша свободна if (false == InputManager::getInstance().isCaptureMouse()) { showList(); } } // нажат ввод в окне редиктирования else if (_key == OIS::KC_RETURN) { eventComboAccept(this); } } void ComboBox::notifyListMouseItemActivate(MyGUI::WidgetPtr _widget, size_t _position) { if (_position != ITEM_NONE) { mItemIndex = _position; Edit::setCaption(mList->getItem(_position)); } InputManager::getInstance().setKeyFocusWidget(this); if (mModeDrop) eventComboAccept(this); } void ComboBox::notifyMouseWheel(MyGUI::WidgetPtr _sender, int _rel) { if (mList->getItemCount() == 0) return; if (InputManager::getInstance().getKeyFocusWidget() != this) return; if (InputManager::getInstance().isCaptureMouse()) return; if (_rel > 0) { if (mItemIndex != 0) { if (mItemIndex == ITEM_NONE) mItemIndex = 0; else mItemIndex --; Edit::setCaption(mList->getItem(mItemIndex)); mList->setItemSelect(mItemIndex); mList->beginToIndex(mItemIndex); eventComboChangePosition(this, mItemIndex); } } else if (_rel < 0) { if ((mItemIndex+1) < mList->getItemCount()) { if (mItemIndex == ITEM_NONE) mItemIndex = 0; else mItemIndex ++; Edit::setCaption(mList->getItem(mItemIndex)); mList->setItemSelect(mItemIndex); mList->beginToIndex(mItemIndex); eventComboChangePosition(this, mItemIndex); } } } void ComboBox::notifyMousePressed(MyGUI::WidgetPtr _sender, bool _left) { // обязательно отдаем отцу, а то мы у него в наглую отняли Edit::notifyMousePressed(_sender, _left); mDropMouse = true; // показываем список if (mModeDrop) notifyButtonPressed(null, _left); } void ComboBox::notifyEditTextChange(MyGUI::WidgetPtr _sender) { // сбрасываем выделенный элемент if (ITEM_NONE != mItemIndex) { mItemIndex = ITEM_NONE; mList->setItemSelect(mItemIndex); mList->beginToStart(); eventComboChangePosition(this, mItemIndex); } } void ComboBox::showList() { // пустой список не показываем if (mList->getItemCount() == 0) return; mListShow = true; int height = mList->getListMaxHeight(); if (height > mMaxHeight) height = mMaxHeight; // берем глобальные координаты выджета IntCoord coord(WidgetManager::convertToGlobal(IntPoint(), this), mCoord.size()); //показываем список вверх if ((coord.top + coord.height + height) > (int)Gui::getInstance().getViewHeight()) { coord.height = height; coord.top -= coord.height; } // показываем список вниз else { coord.top += coord.height; coord.height = height; } mList->setPosition(coord); if (mShowSmooth) { ControllerManager::getInstance().addItem( mList, new ControllerFadeAlpha(COMBO_ALPHA_MAX, COMBO_ALPHA_COEF, ControllerFadeAlpha::ACTION_NONE, true)); } else mList->show(); InputManager::getInstance().setKeyFocusWidget(mList); } void ComboBox::hideList() { mListShow = false; if (mShowSmooth) { ControllerManager::getInstance().addItem( mList, new ControllerFadeAlpha(COMBO_ALPHA_MIN, COMBO_ALPHA_COEF, ControllerFadeAlpha::ACTION_HIDE, false)); } else mList->hide(); } void ComboBox::setItemSelect(size_t _index) { MYGUI_ASSERT(_index < mList->getItemCount(), "setComboItemIndex: index " << _index <<" out of range"); mItemIndex = _index; Edit::setCaption(mList->getItem(_index)); Edit::updateView(0); // hook for update } size_t ComboBox::getItemCount() { return mList->getItemCount(); } const Ogre::DisplayString & ComboBox::getItem(size_t _index) { MYGUI_ASSERT(_index < mList->getItemCount(), "getItemString: index " << _index <<" out of range"); return mList->getItem(_index); } void ComboBox::setItem(size_t _index, const Ogre::DisplayString & _item) { MYGUI_ASSERT(_index < mList->getItemCount(), "setItemString: index " << _index <<" out of range"); mList->setItem(_index, _item); mItemIndex = ITEM_NONE; mList->setItemSelect(mItemIndex); } void ComboBox::insertItem(size_t _index, const Ogre::DisplayString & _item) { mList->insertItem(_index, _item); mItemIndex = ITEM_NONE; mList->setItemSelect(mItemIndex); } void ComboBox::deleteItem(size_t _index) { mList->deleteItem(_index); mItemIndex = ITEM_NONE; mList->setItemSelect(mItemIndex); } void ComboBox::addItem(const Ogre::DisplayString& _item) { mList->addItem(_item); mItemIndex = ITEM_NONE; mList->setItemSelect(mItemIndex); } void ComboBox::deleteAllItems() { mItemIndex = ITEM_NONE; mList->deleteAllItems(); } void ComboBox::setComboModeDrop(bool _drop) { mModeDrop = _drop; setEditStatic(mModeDrop); } } // namespace MyGUI
[ [ [ 1, 325 ] ] ]
39146cc137e00fb9fecbea26ee1508e956478de8
113b284df51a798c943e36aaa21273e7379391a9
/VolumeGadget/VolumeControlDLL/VolumeControlDLL.cpp
2680d82b7f88083b11bc52f2fcf972360dd08bd9
[]
no_license
ccMatrix/desktopgadgets
bf171b75b446faf16443202c06e98c0a4b5eef7c
f5fa36e042ce274910f62e5d3510072ae07acf5e
refs/heads/master
2020-12-25T19:26:10.514144
2010-03-01T23:24:15
2010-03-01T23:24:15
32,254,664
1
1
null
null
null
null
ISO-8859-1
C++
false
false
1,430
cpp
// VolumeControlDLL.cpp : Implementierung von DLL-Exporten. #include "stdafx.h" #include "resource.h" #include "VolumeControlDLL.h" class CVolumeControlDLLModule : public CAtlDllModuleT< CVolumeControlDLLModule > { public : DECLARE_LIBID(LIBID_VolumeControlDLLLib) DECLARE_REGISTRY_APPID_RESOURCEID(IDR_VOLUMECONTROLDLL, "{41F7464B-33B2-4A8D-8C53-80AD776033E5}") }; CVolumeControlDLLModule _AtlModule; // DLL-Einstiegspunkt extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { hInstance; return _AtlModule.DllMain(dwReason, lpReserved); } // Wird verwendet, um festzustellen, ob die DLL von OLE entladen werden kann STDAPI DllCanUnloadNow(void) { return _AtlModule.DllCanUnloadNow(); } // Gibt eine Klassenfactory zurück, um für den angeforderten Typ ein Objekt zu erstellen STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _AtlModule.DllGetClassObject(rclsid, riid, ppv); } // DllRegisterServer - Fügt Einträge in die Systemregistrierung hinzu STDAPI DllRegisterServer(void) { // Registriert Objekt, Typelib und alle Schnittstellen in Typelib HRESULT hr = _AtlModule.DllRegisterServer(); return hr; } // DllUnregisterServer - Entfernt Einträge aus der Systemregistrierung STDAPI DllUnregisterServer(void) { HRESULT hr = _AtlModule.DllUnregisterServer(); return hr; }
[ "codename.matrix@e00a1d1f-563d-0410-a555-bbce3309907e" ]
[ [ [ 1, 53 ] ] ]
c36b40469e380c3c6c6cdb21f8f5d82bd53586f2
0271b1f1070ef9bbbff89a14e925cd5f26e53a49
/580 Final/Project/Plug-In/VoronoiTmp/VoronoiTmp/VoronoiTmp/voronoiShatter.cpp
1960793458e4883cee748a39b9cf63f451255078
[]
no_license
satychary/voronoi-shattering-csci-580-final-project
e8ff142089a835bc85164ee4be2a26e9ffdc42e2
4d5d454288ce7d93f52b0ad8e3ea84c19adf697a
refs/heads/master
2020-05-18T00:49:01.443211
2011-12-01T11:34:41
2011-12-01T11:34:41
33,340,435
0
0
null
null
null
null
UTF-8
C++
false
false
3,490
cpp
#include "voronoiShatter.h" VoronoiShatter::VoronoiShatter(void) { currentKey = 1; } VoronoiShatter::~VoronoiShatter(void) { } // Description: // get the tetrahedron form our pool by key // Arguments: // key -- key for map retrieving // tetra -- referenced, returned as the tetra associated with key // Return Value; // true -- if success // false -- if key is not exist bool VoronoiShatter::getTetra(int key, Tetrahedron &tetra) { TetraMapItr result = tetraPool.find(key); if(result != tetraPool.end()){ tetra = result->second; return true; } else return false; } // Description: // add tetra to our pool // Arguments: // tetra -- tetra to be added // Return Value; // true -- if success // false -- if there is already a tetra with same key, // and our pool remain unchanged bool VoronoiShatter::addTetra(Tetrahedron &tetra) { // set currentKey tetra.key = currentKey; // set incident for vertices tetra.v1.incidentTetra = currentKey; tetra.v2.incidentTetra = currentKey; tetra.v3.incidentTetra = currentKey; tetra.v4.incidentTetra = currentKey; TetraMapItem newItem(currentKey, tetra); currentKey++; return tetraPool.insert(newItem).second; } // Description: // delete a tetra from our pool by key // Arguments: // key -- key of tetra to delete // Return Value; // void void VoronoiShatter::deleteTetra(int key) { tetraPool.erase(key); } // Description: // update tetra in our pool // Arguments: // tetra -- tetra to be updated // Return Value; // true -- if success // false -- if tetra not found bool VoronoiShatter::updateTetra(Tetrahedron &tetra) { TetraMapItr newTetra = tetraPool.find(tetra.key); if(newTetra != tetraPool.end()){ newTetra->second = tetra; return true; } else return false; } // Description: // get the first tetra form our pool // Arguments: // tetra -- referenced, retruned as the first tetra // Return Value; // true -- if success // false -- if our pool is currently empty bool VoronoiShatter::firstTetra(Tetrahedron &tetra) { TetraMapItr result= tetraPool.begin(); if(result != tetraPool.end()){ tetra = result->second; return true; } else return false; } // Description: // get AND delete a tetra from our pool by key // Arguments: // key -- key to retrieve // tetra -- referenced, returned as the tetra associated with key // Return Value; bool VoronoiShatter::popTetra(int key, Tetrahedron &tetra) { if(getTetra(key, tetra)){ deleteTetra(key); return true; } else return false; } // Description: // get the size of current pool // Arguments: // // Return Value; int VoronoiShatter::getTetraNum() { return tetraPool.size(); } // Description: // get current pool // Arguments: // // Return Value; TetraMap VoronoiShatter::getPool() { return tetraPool; } // Description: // set bounding box // Arguments: // bbx -- bounding box to set // Return Value; void VoronoiShatter::setBoundingBox(MBoundingBox bbx) { boundingBox = bbx; } // Description: // set transform matrix // Arguments: // mx -- transform matrix to set // Return Value; void VoronoiShatter::setTransformMatrix(MMatrix mx) { tMatrix = mx; } // Description: // set mesh // Arguments: // mesh -- mesh to be set // Return Value; void VoronoiShatter::setMesh(MDagPath mesh) { vMesh = mesh; }
[ "[email protected]@4f6fa130-d070-310d-0fd1-0289c6893db4" ]
[ [ [ 1, 169 ] ] ]
c9ca0066e0e36173dbab47bfe52657a1243d6f28
f13f46fbe8535a7573d0f399449c230a35cd2014
/JelloMan/ForceField.h
e407b07292897d4f1026bed69e95bee6a4075589
[]
no_license
fangsunjian/jello-man
354f1c86edc2af55045d8d2bcb58d9cf9b26c68a
148170a4834a77a9e1549ad3bb746cb03470df8f
refs/heads/master
2020-12-24T16:42:11.511756
2011-06-14T10:16:51
2011-06-14T10:16:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
926
h
#pragma once #include "D3DUtil.h" #include "Vector3.h" #include "ISerializable.h" class PhysX; class ForceField : public ISerializable { public: /* CONSTRUCTOR - DESTRUCTOR*/ ForceField(); virtual ~ForceField(); /* GENERAL */ void Create(PhysX* pPhysX, const Vector3& force, const Vector3& dimensions, const Vector3& position); /* GETTERS */ NxForceField* GetNxForceField() const { return m_pForceField; } /* SERIALIZE */ virtual void Serialize(Serializer* pSerializer) const; virtual void Deserialize(Serializer* pSerializer); virtual DWORD GetUniqueIdentifier() const { return SerializeTypes::PhysXForceField; } private: /* DATAMEMBERS */ NxForceField* m_pForceField; Vector3 m_Force; Vector3 m_Dimensions; Vector3 m_Position; PhysX* m_pPhysX; /* COPY & ASSIGNMENT */ ForceField(const ForceField&); ForceField& operator=(const ForceField&); };
[ [ [ 1, 45 ] ] ]
292e0d1001247ed00abe4cd8f5703de60af3524e
14e30c5f520f0ed28117914101d9bdf2f3d5dac7
/project/source/mesh/mesh_obj.cpp
675d57ccbcdc3d73406ec866f31ba7e8f0445876
[]
no_license
danielePiracci/arlight
f356eb5a162d0cd62a759720cbc6da41a820642f
15a68c4c80c97f2fe7458e7ddf03f3e1063e25a4
refs/heads/master
2016-08-11T13:45:35.252916
2011-01-24T20:22:50
2011-01-24T20:22:50
44,962,821
0
0
null
null
null
null
UTF-8
C++
false
false
9,779
cpp
/// \file mesh/mesh_obj.cpp /// \author Juan Carlos De Abreu ([email protected]) /// \date 2010/08/21 /// \version 1.0 /// /// \brief This file implements the DissertationProject::MeshObj class, /// declared at mesh/mesh_obj.h. #include "mesh/mesh_obj.h" #include "mesh/face.h" #include "mesh/group.h" #include "tchar.h" #include "util/string.h" #include "cmath" BEGIN_PROJECT_NAMESPACE(); MeshObj::MeshObj() { } MeshObj::~MeshObj() { } void MeshObj::Load(const std::string& file_path) { // Try to open the file FILE *f = fopen(file_path.c_str(), "r"); // Check if the file was open if (f == NULL) { // TODO: Report the error in the Log // PRINT_LOG(TYPE_ERROR, "The file \"%s\" not was found!", lpszPathName); return; } const int MAX_LONG = 200; _TCHAR str[MAX_LONG]; Group g; // To save the data temporaly of the groups // To mantain the refences of the model local to each group Face refIndex; refIndex.normal = 1; refIndex.texture = 1; refIndex.vertex = 1; // Load the data in the file while (fgets(str, MAX_LONG, f) != NULL) { // Obtain the type of line _TCHAR lineType[MAX_LONG]; sscanf(str, "%s", lineType); // Check if is a comment line if (strcmp(lineType, "#") == 0) { // Do anything ... // Process the next line continue; } // Check if is a begin group line if (strcmp(lineType, "g") == 0) { // Check if a have a previus group if (g.vertexList.size() > 0) { // Check if the material was defined to the group //if(strcmp(g.mat.name.c_str(), "") == 0) { if (g.mat.size() == 0) { // Add the last material defined // TODO: Check how to add the materials to the application. // g.mat.push_back(MATERIAL(_T("SceneNavigator_Default__"))); // g.matIndex.push_back(0); } // Add the group to the groupList groupList.push_back(g); // Update the index reference ... refIndex.normal += g.normalList.size(); refIndex.vertex += g.vertexList.size(); refIndex.texture += g.textureList.size(); } g = Group(); // Process the next line continue; } // Check if is a pathFile of materials if (strcmp(lineType, "mtllib") == 0) { // Obtain the path of the file that have the mtllib sscanf(str, "%*s %s", str); // Load the material library // TODO: todo add this functionality and check how to make the changes. // LOAD_MATERIALS(GetAPathFromOne(file_path, str)); // Process the next line continue; } // Check if is an use of a material if (strcmp(lineType, "usemtl") == 0) { // Obtain the material name sscanf(str, "%*s %s", str); // TODO: Check how to to make the load of the materials in the application. // g.mat.push_back(MATERIAL(str)); g.matIndex.push_back(g.faceList.size()); // Process the next line continue; } // Check if is a definition of a vertex if (strcmp(lineType, "v") == 0) { // To save the information of the vertex vec3f v; // Obtain the definition of a vertex sscanf(str, "%*s %f %f %f", &v.x, &v.y, &v.z); // Add the vertex to the vertexList g.vertexList.push_back(v); // Process the next line continue; } // Check if is a definition of a normal of a vextex if (strcmp(lineType, "vn") == 0) { // To save the information of the normal vec3f v; // Obtain the definition of a vertex sscanf(str, "%*s %f %f %f", &v.x, &v.y, &v.z); // Add the normal to the normalList g.normalList.push_back(v); // Process the next line continue; } // Check if is a definition of a texture coord of a vextex if (strcmp(lineType, "vt") == 0) { // To save the information of a texture coord //vec2f v; vec3f v; // Obtain the definition of a texture coord sscanf(str, "%*s %f %f", &v.x, &v.y); // Add the texture coord to the textureList g.textureList.push_back(v); // Process the next line continue; } // Check if is a definition of a face if (strcmp(lineType, "f") == 0) { // To save the information of the face Face f; // Determin how many vertex have the face int nSlash = 0; for (int i = 0; i < (int)strlen(str); ++i) if (str[i] == '/') nSlash++; // If the face has more than 3 vertex .. if (nSlash > 6) { vec3i tmp; // Check if have a coord of texture if (strstr(str, "//") == NULL) { // Obtain the index of the face sscanf(str, "%*s %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d", &f.vertex.x, &f.texture.x, &f.normal.x, &f.vertex.y, &f.texture.y, &f.normal.y, &f.vertex.z, &f.texture.z, &f.normal.z, &tmp.x, &tmp.y, &tmp.z); } else { // Obtain the index of the face sscanf(str, "%*s %d//%d %d//%d %d//%d %d//%d", &f.vertex.x, &f.normal.x, &f.vertex.y, &f.normal.y, &f.vertex.z, &f.normal.z, &tmp.x, &tmp.z); } // Change the range of the index to [0..n-1] f.vertex -= refIndex.vertex; f.normal -= refIndex.normal; f.texture -= refIndex.texture; tmp.x -= refIndex.vertex.x; tmp.y -= refIndex.texture.x; tmp.z -= refIndex.normal.x; // Add the face to the faceList g.faceList.push_back(f); f.vertex.y = f.vertex.z; f.vertex.z = tmp.x; f.texture.y = f.texture.z; f.texture.z = tmp.y; f.normal.y = f.normal.z; f.normal.z = tmp.z; g.faceList.push_back(f); } else { // Check if have a coord of texture if (strstr(str, "//") == NULL) { // Obtain the index of the face sscanf(str, "%*s %d/%d/%d %d/%d/%d %d/%d/%d", &f.vertex.x, &f.texture.x, &f.normal.x, &f.vertex.y, &f.texture.y, &f.normal.y, &f.vertex.z, &f.texture.z, &f.normal.z); } else { // Obtain the index of the face sscanf(str, "%*s %d//%d %d//%d %d//%d", &f.vertex.x, &f.normal.x, &f.vertex.y, &f.normal.y, &f.vertex.z, &f.normal.z); } // Change the range of the index to [0..n-1] f.vertex -= refIndex.vertex; f.normal -= refIndex.normal; f.texture -= refIndex.texture; // Add the face to the faceList g.faceList.push_back(f); } // Process the next line continue; } // TODO: If the line is the unknown type report a warning // PRINT_LOG(TYPE_WARNING, "The file %s has a unknown line \"%s\"", lpszPathName, str); } // Check if the material was defined to the group if (g.mat.size() == 0) { // Add the last material defined // TODO: Add this line to the load of materials. // g.mat.push_back(MATERIAL(_T("SceneNavigator_Default__"))); g.matIndex.push_back(0); } // Add the last group to groupList groupList.push_back(g); // Close th file fclose(f); // Normalize the model process(); } void MeshObj::process() { // Check if i have a groplist if(groupList.size() <= 0) { // TODO: print a error message on the log. // PRINT_LOG(TYPE_ERROR, "The model don't have a data in the groupList"); return; } vec3f vMin, vMax; // Initialize the bounding box vMin = groupList[0].vertexList[0]; vMax = groupList[0].vertexList[0]; // Obtain the number of groups const int nGroups = static_cast<int> (groupList.size()); // Search value of the vertex of the bouding box for(int i = 0; i < nGroups; ++i) { // Obtain the number of vertex of the group i const int nVertex = static_cast<int> (groupList[i].vertexList.size()); for(int j = 0; j < nVertex; ++j) { // Obtain the vertex const vec3f v = groupList[i].vertexList[j]; // Check if out of the bounding box, then update this values if(v.x < vMin.x) vMin.x = v.x; if(v.y < vMin.y) vMin.y = v.y; if(v.z < vMin.z) vMin.z = v.z; if(v.x > vMax.x) vMax.x = v.x; if(v.y > vMax.y) vMax.y = v.y; if(v.z > vMax.z) vMax.z = v.z; } } // calculate the center of the model const vec3f center = (vMin + vMax) / 2.f; // Calculate the axis with more diference in the object float maxDistance = 1.f / (std::max(vMax.x - vMin.x, std::max(vMax.y - vMin.y, vMax.z - vMin.z))); // Translate the object to (0,0,0) and scale for(int i = 0; i < nGroups; ++i) { // Obtain the number of vertex of the group i const int nVertex = static_cast<int> (groupList[i].vertexList.size()); // Translate and scale the vertex of the group i for(int j = 0; j < nVertex; ++j) { // NOTE: Check how to delete this operation and keep everything else working. groupList[i].vertexList[j] -= center; groupList[i].vertexList[j] *= maxDistance; } } // Translate the bounding box to the center vMin -= center; vMax -= center; // Scale the model vMin *= maxDistance; vMax *= maxDistance; // Create all display list of the model //createGridDL(); //createPointDL(); createSurfaceDL(); //createBoundingBoxDL(); } void MeshObj::createSurfaceDL() { const int kNumberOfGroups = static_cast<int> (groupList.size()); for (int i = 0; i < kNumberOfGroups; ++i) groupList[i].createDL(); } void MeshObj::drawSurface(int renderMode) { for (int i = 0; i < (int)groupList.size(); ++i) groupList[i].drawDL(renderMode); } END_PROJECT_NAMESPACE();
[ "jcabreur@db05138c-34b8-7cfb-67b9-2db12d2e1ab0" ]
[ [ [ 1, 314 ] ] ]
881cb8204fc9a4c24b6717c18311cf67867c2f21
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/RecollectionBenchmark/behaviours/GoToDisposal.h
649ebf4ca545c8889e66205e7dabedebc2032e8e
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,177
h
// Class automatically generated by Dev-C++ New Class wizard #ifndef behaviours_GoToDisposal_H #define behaviours_GoToDisposal_H #include "AbstractBehaviour.h" #include "WorldInfo.h" #include <list> #include <behaviours/UnloadGarbage.h> #include <behaviours/FindLine.h> #include <behaviours/PositionInLine.h> #include <behaviours/GoToBase.h> namespace behaviours { /** * No description */ class GoToDisposal : public AbstractBehaviour { public: GoToDisposal(WorldInfo * wi, robotapi::IRobot * robot, robotapi::ITrashBin * tb, robotapi::IDifferentialWheels * wheels, std::vector<robotapi::IDistanceSensor*> & fss, robotapi::IServo * gate, robotapi::IServo * cont); ~GoToDisposal(); void sense(); void action(); private: bool onMark(); bool inLine(); bool inPosition(); void correctOrientation(); behaviours::AbstractBehaviour * disposalBehaviours [4]; robotapi::IDifferentialWheels * wheels; robotapi::IServo * cont; robotapi::IRobot * robot; robotapi::ITrashBin * trashbin; std::vector<robotapi::IDistanceSensor*> * fss; WorldInfo * wi; }; } #endif // GOTODISPOSAL_H
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 51 ] ] ]
f43f92a2987a047bbf7105ac04a8209d2bd576b5
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/DOMProcessingInstruction.hpp
291e21af3245d7f2795bae3bc54d4d2827d2f889
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
4,168
hpp
#ifndef DOMProcessingInstruction_HEADER_GUARD_ #define DOMProcessingInstruction_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMProcessingInstruction.hpp,v 1.8 2004/09/26 15:38:02 gareth Exp $ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMNode.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * The <code>DOMProcessingInstruction</code> interface represents a "processing * instruction", used in XML as a way to keep processor-specific information * in the text of the document. * * @since DOM Level 1 */ class CDOM_EXPORT DOMProcessingInstruction: public DOMNode { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMProcessingInstruction() {}; //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented constructors and operators */ //@{ DOMProcessingInstruction(const DOMProcessingInstruction &); DOMProcessingInstruction & operator = (const DOMProcessingInstruction &); //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMProcessingInstruction() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMProcessingInstruction interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 1 */ //@{ // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** * The target of this processing instruction. * * XML defines this as being the * first token following the markup that begins the processing instruction. * * @since DOM Level 1 */ virtual const XMLCh * getTarget() const = 0; /** * The content of this processing instruction. * * This is from the first non * white space character after the target to the character immediately * preceding the <code>?&gt;</code>. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly. * @since DOM Level 1 */ virtual const XMLCh * getData() const = 0; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- /** * Sets the content of this processing instruction. * * This is from the first non * white space character after the target to the character immediately * preceding the <code>?&gt;</code>. * @param data The string containing the processing instruction * @since DOM Level 1 */ virtual void setData(const XMLCh * data) = 0; //@} }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 121 ] ] ]
d42217475f866c111e8fa80cab14adc068666d6e
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/XPanel/XBoolean.h
512aa34c6509d444c88aa7442abb56b8dc4d9560
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
364
h
// Copyright (C) 1999 - 2002 David Forstenlechner #if defined (_MSC_VER) && (_MSC_VER >= 1000) #pragma once #endif #ifndef _INC_XBOOLEAN_3E3569DB0125_INCLUDED #define _INC_XBOOLEAN_3E3569DB0125_INCLUDED #include "XControl.h" class XBoolean : public XControl { public: XBoolean(); }; #endif /* _INC_XBOOLEAN_3E3569DB0125_INCLUDED */
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 20 ] ] ]
57b7251a2929fe43eec1ed01269c0f4e9b0802c2
a2ba072a87ab830f5343022ed11b4ac365f58ef0
/ urt-bumpy-q3map2 --username [email protected]/libs/entityxml.h
609a1b2181fc05f62c3b8c68bcc4d009afa939a0
[]
no_license
Garey27/urt-bumpy-q3map2
7d0849fc8eb333d9007213b641138e8517aa092a
fcc567a04facada74f60306c01e68f410cb5a111
refs/heads/master
2021-01-10T17:24:51.991794
2010-06-22T13:19:24
2010-06-22T13:19:24
43,057,943
0
0
null
null
null
null
UTF-8
C++
false
false
1,904
h
#if !defined(INCLUDED_ENTITYXML_H) #define INCLUDED_ENTITYXML_H #include "ientity.h" #include "xml/ixml.h" #include "xml/xmlelement.h" class entity_import : public XMLImporter { Entity& m_entity; public: entity_import(Entity& entity) : m_entity(entity) { } void pushElement(const XMLElement& element) { if(strcmp(element.name(), "epair") == 0) m_entity.setKeyValue(element.attribute("key"), element.attribute("value")); } void popElement(const char* name) { } std::size_t write(const char* data, std::size_t length) { return length; } }; class entity_export : public XMLExporter { class ExportXMLVisitor : public Entity::Visitor { XMLImporter& m_importer; public: ExportXMLVisitor(XMLImporter& importer) : m_importer(importer) { } void visit(const char* key, const char* value) { StaticElement element("epair"); element.insertAttribute("key", key); element.insertAttribute("value", value); m_importer.pushElement(element); m_importer.popElement(element.name()); } }; const Entity& m_entity; public: entity_export(const Entity& entity) : m_entity(entity) { } void exportXML(XMLImporter& observer) { ExportXMLVisitor visitor(observer); m_entity.forEachKeyValue(visitor); } }; inline void entity_copy(Entity& entity, const Entity& other) { entity_export exporter(other); entity_import importer(entity); exporter.exportXML(importer); } template<typename EntityType> class EntityConstruction { public: typedef EntityClass* type; static type get(const EntityType& entity) { return &entity.getEntity().getEntityClass(); } static void copy(EntityType& entity, const EntityType& other) { entity_copy(entity.getEntity(), other.getEntity()); } }; #endif
[ [ [ 1, 88 ] ] ]
bca632e515413c3cbf32a0adb59bf2ac799d86ee
b03c23324d8f048840ecf50875b05835dedc8566
/engin3d/src/Input/Keyboard.h
a35cca186624543ddd6d8d09cd7ee22cf837dae8
[]
no_license
carlixyz/engin3d
901dc61adda54e6098a3ac6637029efd28dd768e
f0b671b1e75a02eb58a2c200268e539154cd2349
refs/heads/master
2018-01-08T16:49:50.439617
2011-06-16T00:13:26
2011-06-16T00:13:26
36,534,616
0
0
null
null
null
null
UTF-8
C++
false
false
930
h
#ifndef KEYBOARD_H #define KEYBOARD_H #include <Windows.h> #include "GenericDevice.h" #include "ois\includes\OISInputManager.h" #include "ois\includes\OISException.h" #include "ois\includes\OISKeyboard.h" #include "ois\includes\OISEvents.h" class cKeyboard : public cGenericDevice, public OIS::KeyListener { private: OIS::Keyboard* mpOISKeyboard; //OIS Device static const unsigned kuiInputChanelSize = 256; //Channel size bool mabInputBuffer[kuiInputChanelSize]; //Input buffer bool mbIsValid; // Device is valid public: cKeyboard() : mbIsValid(false) { ; } void Init(); void Deinit(void); void Update(void); float Check(unsigned luiEntry); inline bool IsValid(void) { return mbIsValid; } // Listeners for the keyboard bool keyPressed( const OIS::KeyEvent &lArg ); bool keyReleased( const OIS::KeyEvent &lArg ); }; #endif
[ "manolopm@8d52fbf8-9d52-835b-178e-190adb01ab0c", "[email protected]" ]
[ [ [ 1, 6 ], [ 11, 36 ] ], [ [ 7, 10 ] ] ]
83c7430ff9fa6a08c8e3bd12f48269df7b752126
559770fbf0654bc0aecc0f8eb33843cbfb5834d9
/haina/codes/beluga/client/symbian/BelugaDb/inc/contact/CTagIterator.h
883191566962f844ed2557f65f38ecf41f73c214
[]
no_license
CMGeorge/haina
21126c70c8c143ca78b576e1ddf352c3d73ad525
c68565d4bf43415c4542963cfcbd58922157c51a
refs/heads/master
2021-01-11T07:07:16.089036
2010-08-18T09:25:07
2010-08-18T09:25:07
49,005,284
1
0
null
null
null
null
UTF-8
C++
false
false
743
h
/* ============================================================================ Name : CTagIterator.h Author : shaochuan.yang Copyright : haina Description : Tag Entity Iterator ============================================================================ */ #ifndef __CTAGITERATOR_H__ #define __CTAGITERATOR_H__ #include <glib.h> #include "CDbEntityIterator.h" #include "CTagDb.h" class CTagIterator : public CDbEntityIterator { public: CTagIterator(CEntityDb * pEntityDb): CDbEntityIterator(pEntityDb) { } ~CTagIterator() { } IMPORT_C gint32 Current(CDbEntity ** pEntity); IMPORT_C gint32 Next(gboolean * pSuccess); IMPORT_C gint32 Prev(gboolean * pSuccess); }; #endif
[ "shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d" ]
[ [ [ 1, 35 ] ] ]
935642a3b3c21ba511995bc1ec266964a8c7520e
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor-0.32/deditor.cpp
44dd106f44912e73d326a29c7835decf78674a2d
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
#include "StdAfx.h" #include ".\diagram\deditor.h" bool CDEditor::AdjustRect(CRect& rect) { return false; }
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 7 ] ] ]
54850c18b1c27d9349a6ec72afe4b93135254745
2627604c0d9ffa5e5fea160c874428ffa67c1076
/memory_based_dissimilarity_matrix.h
03edcb35b1d5b17188a99e235eaf32385a315de9
[]
no_license
mvlevin/linkageclustering
c9e1b7ff9342dc3105b6851ac5fbbb8869714100
32c86863aa1bc8c28e0a6d690033b23732967084
refs/heads/master
2016-08-04T07:03:07.636936
2010-05-13T13:31:37
2010-05-13T13:31:37
32,219,956
0
0
null
null
null
null
UTF-8
C++
false
false
3,030
h
// Copyright 2010 Michael Levin // // Example class representing a sparse // square dissimilarity matrix in memory. #ifndef MEMORY_BASED_SIMILARITY_MATRIX_H_ #define MEMORY_BASED_SIMILARITY_MATRIX_H_ #include <vector> using std::vector; namespace LinkageClustering { // Represents a sparse square dissimilarity matrix in memory. // // Stored as a vector of rows. // Each row is stored as a vector of pairs (index, dissimilarity) // for all such indices that dissimilarity is non-zero. // // param DissimilarityValueType_ - type to use for storage of matrix // cells value. Can be, for example, std::size_t, unsigned long long // or double. template<class DissimilarityValueType_> class MemoryBasedDissimilarityMatrix { public: // The following typedefs, iterator class and methods are required to use the GetLinkageSequence // algorithm with a dissimilarity matrix. // See compute_linkage_sequence.h for details. typedef unsigned int IndexType; typedef DissimilarityValueType_ DissimilarityValueType; // Represents an iterator over a row of the matrix. // // Fulfills the interface needed for a DissimilarityIterator // in the GetLinkageSequence algorithm. // See compute_linkage_sequence.h for details. class RowIterator { public: typedef typename vector<pair<IndexType, DissimilarityValueType> >::const_iterator Iterator; // Initialize with iterators to begin and end of the row's underlying vector. RowIterator(Iterator begin, Iterator end) : iterator_(begin), end_(end) {} // Returns the index of the current column of the matrix. IndexType GetToIndex() const { return iterator_->first; } // Returns the value of the current cell of the matrix. DissimilarityValueType GetDissimilarity() const { return iterator_->second; } // Returns true if all the non-zero elements are passed. bool Done() const { return iterator_ == end_; } // Moves to the next non-zero element in the row. void Next() { ++iterator_; } private: Iterator iterator_; Iterator end_; }; MemoryBasedDissimilarityMatrix( vector< vector<pair<IndexType, DissimilarityValueType> > >& sparse_matrix) { // So that we don't copy this huge vector. sparse_matrix_.swap(sparse_matrix); } // Returns number of rows in the matrix. IndexType GetRowCount() const { return sparse_matrix_.size(); } // Returns RowIterator GetRowIterator(IndexType index) const { return RowIterator( sparse_matrix_[index].begin(), sparse_matrix_[index].end()); } private: // The underlying sparse matrix is stored as a vector of sparse rows. // Each row consists of an ordered by index list of pairs (index, dissimilarity) // for each such index that dissimilarity is non-zero. vector< vector<pair<IndexType, DissimilarityValueType> > > sparse_matrix_; }; } // namespace LinkageClustering #endif // MEMORY_BASED_SIMILARITY_MATRIX_H_
[ "mlevin@localhost" ]
[ [ [ 1, 86 ] ] ]
da4144f65b4166f016e679412ffdfb080f258e75
b83c990328347a0a2130716fd99788c49c29621e
/include/boost/interprocess/detail/move.hpp
c56048bae4a3cc156f04d99ac086eaac71473fd5
[ "BSL-1.0" ]
permissive
SpliFF/mingwlibs
c6249fbb13abd74ee9c16e0a049c88b27bd357cf
12d1369c9c1c2cc342f66c51d045b95c811ff90c
refs/heads/master
2021-01-18T03:51:51.198506
2010-06-13T15:13:20
2010-06-13T15:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,817
hpp
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright David Abrahams, Vicente Botet, Ion Gaztanaga 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/move for documentation. // ////////////////////////////////////////////////////////////////////////////// // // Parts of this file come from Adobe's Move library: // // Copyright 2005-2007 Adobe Systems Incorporated // Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt // or a copy at http://stlab.adobe.com/licenses.html) // ////////////////////////////////////////////////////////////////////////////// //! \file #ifndef BOOST_INTERPROCESS_MOVE_HPP #define BOOST_INTERPROCESS_MOVE_HPP #include <boost/config.hpp> #include <algorithm> //copy, copy_backward #include <memory> //uninitialized_copy #include <iterator> //std::iterator #include <boost/mpl/if.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/has_trivial_destructor.hpp> namespace boost { namespace interprocess { namespace move_detail { template <class T> struct identity { typedef T type; }; template <class T, class U> class is_convertible { typedef char true_t; class false_t { char dummy[2]; }; static true_t dispatch(U); static false_t dispatch(...); static T trigger(); public: enum { value = sizeof(dispatch(trigger())) == sizeof(true_t) }; }; } //namespace move_detail { } //namespace interprocess { } //namespace boost { #if !defined(BOOST_HAS_RVALUE_REFS) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) namespace boost { namespace interprocess { ////////////////////////////////////////////////////////////////////////////// // // struct rv // ////////////////////////////////////////////////////////////////////////////// template <class T> class rv : public T { rv(); ~rv(); rv(rv const&); void operator=(rv const&); public: //T &get() { return *this; } }; ////////////////////////////////////////////////////////////////////////////// // // move_detail::is_rv // ////////////////////////////////////////////////////////////////////////////// namespace move_detail { template <class T> struct is_rv { static const bool value = false; }; template <class T> struct is_rv< rv<T> > { static const bool value = true; }; } //namespace move_detail { ////////////////////////////////////////////////////////////////////////////// // // is_movable // ////////////////////////////////////////////////////////////////////////////// template<class T> class is_movable { public: static const bool value = move_detail::is_convertible<T, rv<T>&>::value; }; template<class T> class is_movable< rv<T> > { public: static const bool value = false; }; ////////////////////////////////////////////////////////////////////////////// // // move() // ////////////////////////////////////////////////////////////////////////////// template <class T> typename boost::disable_if<is_movable<T>, T&>::type move(T& x) { return x; } template <class T> typename enable_if<is_movable<T>, rv<T>&>::type move(T& x) { return reinterpret_cast<rv<T>& >(x); } template <class T> typename enable_if<is_movable<T>, rv<T>&>::type move(const rv<T>& x) { return const_cast<rv<T>& >(x); } ////////////////////////////////////////////////////////////////////////////// // // forward() // ////////////////////////////////////////////////////////////////////////////// template <class T> typename enable_if<boost::interprocess::move_detail::is_rv<T>, T &>::type forward(const typename move_detail::identity<T>::type &x) { return const_cast<T&>(x); } /* template <class T> typename enable_if<boost::interprocess::move_detail::is_rv<T>, T &>::type forward(typename move_detail::identity<T>::type &x) { return x; } template <class T> typename disable_if<boost::interprocess::move_detail::is_rv<T>, T &>::type forward(typename move_detail::identity<T>::type &x) { return x; } */ template <class T> typename disable_if<boost::interprocess::move_detail::is_rv<T>, const T &>::type forward(const typename move_detail::identity<T>::type &x) { return x; } ////////////////////////////////////////////////////////////////////////////// // // BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION // ////////////////////////////////////////////////////////////////////////////// #define BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION(TYPE)\ operator boost::interprocess::rv<TYPE>&() \ { return reinterpret_cast<boost::interprocess::rv<TYPE>& >(*this); }\ // #define BOOST_INTERPROCESS_RV_REF(TYPE)\ boost::interprocess::rv< TYPE >& \ // #define BOOST_INTERPROCESS_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ boost::interprocess::rv< TYPE<ARG1, ARG2> >& \ // #define BOOST_INTERPROCESS_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ boost::interprocess::rv< TYPE<ARG1, ARG2, ARG3> >& \ // #define BOOST_INTERPROCESS_FWD_REF(TYPE)\ const TYPE & \ // } //namespace interprocess { } //namespace boost #else //BOOST_HAS_RVALUE_REFS #include <boost/type_traits/remove_reference.hpp> namespace boost { namespace interprocess { ////////////////////////////////////////////////////////////////////////////// // // is_movable // ////////////////////////////////////////////////////////////////////////////// //! For compilers with rvalue references, this traits class returns true //! if T && is convertible to T. //! //! For other compilers returns true if T is convertible to <i>boost::interprocess::rv<T>&</i> template<class T> class is_movable { public: static const bool value = move_detail::is_convertible<T&&, T>::value; }; ////////////////////////////////////////////////////////////////////////////// // // move // ////////////////////////////////////////////////////////////////////////////// #if defined(BOOST_MOVE_DOXYGEN_INVOKED) //! This function provides a way to convert a reference into a rvalue reference //! in compilers with rvalue reference. For other compilers converts T & into //! <i>boost::interprocess::rv<T> &</i> so that move emulation is activated. template <class T> inline rvalue_reference move (input_reference); #else template <class T> inline typename remove_reference<T>::type&& move(T&& t) { return t; } #endif ////////////////////////////////////////////////////////////////////////////// // // forward // ////////////////////////////////////////////////////////////////////////////// #if defined(BOOST_MOVE_DOXYGEN_INVOKED) //! This function provides limited form of forwarding that is usually enough for //! in-place construction and avoids the exponential overloading necessary for //! perfect forwarding in C++03. //! //! For compilers with rvalue references this function provides perfect forwarding. //! //! Otherwise: //! * If input_reference binds to const boost::interprocess::rv<T> & then it output_reference is //! boost::rev<T> & //! //! * Else, input_reference is equal to output_reference is equal to input_reference. template <class T> inline output_reference forward(input_reference); #else template <class T> inline T&& forward (typename move_detail::identity<T>::type&& t) { return t; } #endif ////////////////////////////////////////////////////////////////////////////// // // BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION // ////////////////////////////////////////////////////////////////////////////// //! This macro expands to nothing for compilers with rvalue references. //! Otherwise expands to: //! \code //! operator boost::interprocess::rv<TYPE>&() //! { return static_cast<boost::interprocess::rv<TYPE>& >(*this); } //! \endcode #define BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION(TYPE)\ // #define BOOST_INTERPROCESS_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ TYPE<ARG1, ARG2> && \ // #define BOOST_INTERPROCESS_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ TYPE<ARG1, ARG2, ARG3> && \ // //! This macro expands to <i>T&&</i> for compilers with rvalue references. //! Otherwise expands to <i>boost::interprocess::rv<T> &</i>. #define BOOST_INTERPROCESS_RV_REF(TYPE)\ TYPE && \ // //! This macro expands to <i>T&&</i> for compilers with rvalue references. //! Otherwise expands to <i>const T &</i>. #define BOOST_INTERPROCESS_FWD_REF(TYPE)\ TYPE && \ // } //namespace interprocess { } //namespace boost { #endif //BOOST_HAS_RVALUE_REFS namespace boost { namespace interprocess { ////////////////////////////////////////////////////////////////////////////// // // move_iterator // ////////////////////////////////////////////////////////////////////////////// //! Class template move_iterator is an iterator adaptor with the same behavior //! as the underlying iterator except that its dereference operator implicitly //! converts the value returned by the underlying iterator's dereference operator //! to an rvalue reference. Some generic algorithms can be called with move //! iterators to replace copying with moving. template <class It> class move_iterator { public: typedef It iterator_type; typedef typename std::iterator_traits<iterator_type>::value_type value_type; #if defined(BOOST_HAS_RVALUE_REFS) || defined(BOOST_MOVE_DOXYGEN_INVOKED) typedef value_type && reference; #else typedef typename boost::mpl::if_ < boost::interprocess::is_movable<value_type> , boost::interprocess::rv<value_type>& , value_type & >::type reference; #endif typedef typename std::iterator_traits<iterator_type>::pointer pointer; typedef typename std::iterator_traits<iterator_type>::difference_type difference_type; typedef typename std::iterator_traits<iterator_type>::iterator_category iterator_category; move_iterator() {} explicit move_iterator(It i) : m_it(i) {} template <class U> move_iterator(const move_iterator<U>& u) : m_it(u.base()) {} iterator_type base() const { return m_it; } reference operator*() const { #if defined(BOOST_HAS_RVALUE_REFS) return *m_it; #else return boost::interprocess::move(*m_it); #endif } pointer operator->() const { return m_it; } move_iterator& operator++() { ++m_it; return *this; } move_iterator<iterator_type> operator++(int) { move_iterator<iterator_type> tmp(*this); ++(*this); return tmp; } move_iterator& operator--() { --m_it; return *this; } move_iterator<iterator_type> operator--(int) { move_iterator<iterator_type> tmp(*this); --(*this); return tmp; } move_iterator<iterator_type> operator+ (difference_type n) const { return move_iterator<iterator_type>(m_it + n); } move_iterator& operator+=(difference_type n) { m_it += n; return *this; } move_iterator<iterator_type> operator- (difference_type n) const { return move_iterator<iterator_type>(m_it - n); } move_iterator& operator-=(difference_type n) { m_it -= n; return *this; } reference operator[](difference_type n) const { #if defined(BOOST_HAS_RVALUE_REFS) return m_it[n]; #else return boost::interprocess::move(m_it[n]); #endif } friend bool operator==(const move_iterator& x, const move_iterator& y) { return x.base() == y.base(); } friend bool operator!=(const move_iterator& x, const move_iterator& y) { return x.base() != y.base(); } friend bool operator< (const move_iterator& x, const move_iterator& y) { return x.base() < y.base(); } friend bool operator<=(const move_iterator& x, const move_iterator& y) { return x.base() <= y.base(); } friend bool operator> (const move_iterator& x, const move_iterator& y) { return x.base() > y.base(); } friend bool operator>=(const move_iterator& x, const move_iterator& y) { return x.base() >= y.base(); } friend difference_type operator-(const move_iterator& x, const move_iterator& y) { return x.base() - y.base(); } friend move_iterator operator+(difference_type n, const move_iterator& x) { return move_iterator(x.base() + n); } private: It m_it; }; //is_move_iterator namespace move_detail { template <class I> struct is_move_iterator { static const bool value = false; }; template <class I> struct is_move_iterator< ::boost::interprocess::move_iterator<I> > { static const bool value = true; }; } //namespace move_detail { ////////////////////////////////////////////////////////////////////////////// // // move_iterator // ////////////////////////////////////////////////////////////////////////////// //! //! <b>Returns</b>: move_iterator<It>(i). template<class It> move_iterator<It> make_move_iterator(const It &it) { return move_iterator<It>(it); } ////////////////////////////////////////////////////////////////////////////// // // back_move_insert_iterator // ////////////////////////////////////////////////////////////////////////////// //! A move insert iterator that move constructs elements at the //! back of a container template <typename C> // C models Container class back_move_insert_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void> { C* container_m; public: typedef C container_type; explicit back_move_insert_iterator(C& x) : container_m(&x) { } back_move_insert_iterator& operator=(typename C::reference x) { container_m->push_back(boost::interprocess::move(x)); return *this; } back_move_insert_iterator& operator*() { return *this; } back_move_insert_iterator& operator++() { return *this; } back_move_insert_iterator& operator++(int) { return *this; } }; //! //! <b>Returns</b>: back_move_insert_iterator<C>(x). template <typename C> // C models Container inline back_move_insert_iterator<C> back_move_inserter(C& x) { return back_move_insert_iterator<C>(x); } ////////////////////////////////////////////////////////////////////////////// // // front_move_insert_iterator // ////////////////////////////////////////////////////////////////////////////// //! A move insert iterator that move constructs elements int the //! front of a container template <typename C> // C models Container class front_move_insert_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void> { C* container_m; public: typedef C container_type; explicit front_move_insert_iterator(C& x) : container_m(&x) { } front_move_insert_iterator& operator=(typename C::reference x) { container_m->push_front(boost::interprocess::move(x)); return *this; } front_move_insert_iterator& operator*() { return *this; } front_move_insert_iterator& operator++() { return *this; } front_move_insert_iterator& operator++(int) { return *this; } }; //! //! <b>Returns</b>: front_move_insert_iterator<C>(x). template <typename C> // C models Container inline front_move_insert_iterator<C> front_move_inserter(C& x) { return front_move_insert_iterator<C>(x); } ////////////////////////////////////////////////////////////////////////////// // // insert_move_iterator // ////////////////////////////////////////////////////////////////////////////// template <typename C> // C models Container class move_insert_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void> { C* container_m; typename C::iterator pos_; public: typedef C container_type; explicit move_insert_iterator(C& x, typename C::iterator pos) : container_m(&x), pos_(pos) {} move_insert_iterator& operator=(typename C::reference x) { pos_ = container_m->insert(pos_, boost::interprocess::move(x)); ++pos_; return *this; } move_insert_iterator& operator*() { return *this; } move_insert_iterator& operator++() { return *this; } move_insert_iterator& operator++(int) { return *this; } }; //! //! <b>Returns</b>: move_insert_iterator<C>(x, it). template <typename C> // C models Container inline move_insert_iterator<C> move_inserter(C& x, typename C::iterator it) { return move_insert_iterator<C>(x, it); } ////////////////////////////////////////////////////////////////////////////// // // move // ////////////////////////////////////////////////////////////////////////////// //! <b>Effects</b>: Moves elements in the range [first,last) into the range [result,result + (last - //! first)) starting from first and proceeding to last. For each non-negative integer n < (last-first), //! performs *(result + n) = boost::interprocess::move (*(first + n)). //! //! <b>Effects</b>: result + (last - first). //! //! <b>Requires</b>: result shall not be in the range [first,last). //! //! <b>Complexity</b>: Exactly last - first move assignments. template <typename I, // I models InputIterator typename O> // O models OutputIterator O move(I f, I l, O result) { while (f != l) { *result = boost::interprocess::move(*f); ++f; ++result; } return result; } ////////////////////////////////////////////////////////////////////////////// // // move_backward // ////////////////////////////////////////////////////////////////////////////// //! <b>Effects</b>: Moves elements in the range [first,last) into the range //! [result - (last-first),result) starting from last - 1 and proceeding to //! first. For each positive integer n <= (last - first), //! performs *(result - n) = boost::interprocess::move(*(last - n)). //! //! <b>Requires</b>: result shall not be in the range [first,last). //! //! <b>Returns</b>: result - (last - first). //! //! <b>Complexity</b>: Exactly last - first assignments. template <typename I, // I models BidirectionalIterator typename O> // O models BidirectionalIterator O move_backward(I f, I l, O result) { while (f != l) { --l; --result; *result = boost::interprocess::move(*l); } return result; } ////////////////////////////////////////////////////////////////////////////// // // uninitialized_move // ////////////////////////////////////////////////////////////////////////////// //! <b>Effects</b>: //! \code //! for (; first != last; ++result, ++first) //! new (static_cast<void*>(&*result)) //! typename iterator_traits<ForwardIterator>::value_type(boost::interprocess::move(*first)); //! \endcode //! //! <b>Returns</b>: result template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_move(I f, I l, F r /// @cond ,typename enable_if<is_movable<typename std::iterator_traits<I>::value_type> >::type* = 0 /// @endcond ) { typedef typename std::iterator_traits<I>::value_type input_value_type; while (f != l) { ::new(static_cast<void*>(&*r)) input_value_type(boost::interprocess::move(*f)); ++f; ++r; } return r; } /// @cond template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_move(I f, I l, F r, typename disable_if<is_movable<typename std::iterator_traits<I>::value_type> >::type* = 0) { return std::uninitialized_copy(f, l, r); } ////////////////////////////////////////////////////////////////////////////// // // uninitialized_copy_or_move // ////////////////////////////////////////////////////////////////////////////// namespace move_detail { template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_move_move_iterator(I f, I l, F r, typename enable_if< is_movable<typename I::value_type> >::type* = 0) { return boost::interprocess::uninitialized_move(f, l, r); } template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_move_move_iterator(I f, I l, F r, typename disable_if< is_movable<typename I::value_type> >::type* = 0) { return std::uninitialized_copy(f.base(), l.base(), r); } } //namespace move_detail { template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_copy_or_move(I f, I l, F r, typename enable_if< move_detail::is_move_iterator<I> >::type* = 0) { return boost::interprocess::move_detail::uninitialized_move_move_iterator(f, l, r); } /// @endcond //! <b>Effects</b>: //! \code //! for (; first != last; ++result, ++first) //! new (static_cast<void*>(&*result)) //! typename iterator_traits<ForwardIterator>::value_type(*first); //! \endcode //! //! <b>Returns</b>: result //! //! <b>Note</b>: This function is provided because //! <i>std::uninitialized_copy</i> from some STL implementations //! is not compatible with <i>move_iterator</i> template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_copy_or_move(I f, I l, F r /// @cond ,typename disable_if< move_detail::is_move_iterator<I> >::type* = 0 /// @endcond ) { return std::uninitialized_copy(f, l, r); } ///has_trivial_destructor_after_move<> == true_type ///specialization for optimizations template <class T> struct has_trivial_destructor_after_move : public boost::has_trivial_destructor<T> {}; } //namespace interprocess { } //namespace boost { #endif //#ifndef BOOST_INTERPROCESS_MOVE_HPP
[ [ [ 1, 747 ] ] ]
63de589bb33e88c6f6ed3f4ee382c2337850ab49
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/cms/cbear.berlios.de/windows/registry/root.hpp
c2068eb7c20a30da2c682ac77bbdface8df716ac
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
1,586
hpp
#ifndef CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_ROOT_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_ROOT_HPP_INCLUDED #include <cbear.berlios.de/windows/registry/path.hpp> namespace cbear_berlios_de { namespace windows { namespace registry { template<class Char> class root: public path_base<Char, root<Char> > { public: typedef Char char_type; typedef path_base<char_type, root> base_type; typedef typename base_type::value_list_type value_list_type; typedef typename base_type::key_list_type key_list_type; registry::hkey hkey; root() {} explicit root(const registry::hkey &hkey): hkey(hkey) {} typedef typename base_type::create_options_type create_options_type; void create(const create_options_type &Options) { this->base_type::create(this->hkey, Options); } void delete_(const sam &Sam) { this->base_type::delete_(this->hkey, Sam); } }; template<class Char> class root_list: public std::vector<root<Char> > { public: typedef Char char_type; typedef root<char_type> root_type; root_list &operator()(const root_type &R) { this->push_back(R); return *this; } typedef typename root_type::create_options_type create_options_type; void create(const create_options_type &Options) { for(range::sub_range<root_list>::type R(*this); !R.empty(); R.begin()++) { R.begin()->create(Options); } } void delete_(const sam &Sam) { for(range::sub_range<root_list>::type R(*this); !R.empty(); R.begin()++) { R.begin()->delete_(Sam); } } }; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 76 ] ] ]
ccde23266485d2527bc894938a8d2093ac1c97d7
8c4d8b2646a9c96ec7f1178a7f2716823fb99984
/ficha6_naps/ficha6_naps.cpp
faf1e7d51e4d562d66539900629f711e1c655d9e
[]
no_license
MiguelCosta/cg-trabalho
c93987ff8c2ec8ac022b936e620594a4f420789d
b293ca8d55d9c4938b66a0561695be0079bd50ac
refs/heads/master
2020-07-08T13:02:35.644637
2011-05-23T13:57:47
2011-05-23T13:57:47
32,185,313
0
0
null
null
null
null
UTF-8
C++
false
false
10,245
cpp
#include <stdlib.h> #include <GL/glut.h> // include para a bib devil // n�o esquecer de adicionar a lib (devil.lib) ao projecto #include <IL/il.h> #include <math.h> #define ANG2RAD 3.14159265358979323846/360.0 #define COWBOYS 8 #define RAIO_COWBOYS 5 #define INDIOS 16 #define RAIO_INDIOS 25 #define ARVORES 1000 #define STEP_COWBOY 1.0f #define STEP_INDIO 0.5f float step = 0.0; float height = 2.0f; float x = 0.0f; float z = 0.0f; float camX = 00, camY = 30, camZ = 40; float cX = 0, cY = 0, cZ = 0; float ang = 0; int startX, startY, tracking = 0; int alpha = 0, beta = 45, r = 50; unsigned int img_text, img_height; int text_w, text_h, height_w, height_h; unsigned int text_id; unsigned char *text_data, *height_data; int grid_n; void changeSize(int w, int h) { // Prevent a divide by zero, when window is too short // (you cant make a window with zero width). if(h == 0) h = 1; // compute window's aspect ratio float ratio = w * 1.0 / h; // Reset the coordinate system before modifying glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Set the viewport to be the entire window glViewport(0, 0, w, h); // Set the correct perspective gluPerspective(45,ratio,1,1000); // return to the model view matrix mode glMatrixMode(GL_MODELVIEW); } float h(float x, float z) { return height_data[(int) x + (int) z * height_w] / 2.0; } void heightedVertex(float mult, float x, float z) { glVertex3f(mult*x, h(x, z), mult*z); } void drawPlane() { float grid_width = 256 / (float) grid_n; float color[] = {0.2,0.8,0.2,1.0}; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color); int x = 0, y = 0; glPolygonMode(GL_BACK, GL_LINE); glPushMatrix(); glBindTexture(GL_TEXTURE_2D, text_id); glTranslatef(-128, 0, -128); for(x = 0; x < height_h; x++) { glBegin(GL_TRIANGLE_STRIP); for(y = 0; y < height_w; y++) { glTexCoord2f(y, 0); heightedVertex(grid_width, (x+1), y); glTexCoord2f(y, 1); heightedVertex(grid_width, x, y); } glEnd(); } glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); } void drawTree() { glPushMatrix(); glRotatef(-90,1.0,0.0,0.0); float color[] = {1.0,1.0,0.5,1.0}; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color); glutSolidCone(0.25,4,5,1); float color2[] = {0.0, 0.5 + rand() * 0.5f/RAND_MAX,0.0,1.0}; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color2); glTranslatef(0.0,0.0,2.0); glutSolidCone(2.0,5.0,5,1); glPopMatrix(); } void placeTrees() { float r = 35.0; float alpha; float rr; float x,z; srand(31457); int arvores = 0; while (arvores < ARVORES) { rr = rand() * 150.0/ RAND_MAX; alpha = rand() * 6.28 / RAND_MAX; x = cos(alpha) * (rr + r); z = sin(alpha) * (rr + r); if (fabs(x) < 128 && fabs(z) < 128) { glPushMatrix(); glTranslatef(x,h(x+128, z+128),z); drawTree(); glPopMatrix(); arvores++; } } } void drawDonut() { glPushMatrix(); glTranslatef(0.0,0.5,0.0); float color[] = {1.0,0.0,1.0,1.0}; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color); glutSolidTorus(0.5,1.25,8,16); glPopMatrix(); } void drawIndios() { float angulo; float color[] = {1.0,0.0,0.0,1.0}; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color); for (int i = 0; i < INDIOS; i++) { angulo = i * 360.0/INDIOS + step * STEP_INDIO; glPushMatrix(); glRotatef(angulo,0.0,1.0,0.0); glTranslatef(0.0,0.0,RAIO_INDIOS); glutSolidTeapot(1); glPopMatrix(); } } void drawCowboys() { float angulo; float color[] = {0.0,0.0,1.0,1.0}; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color); for (int i = 0; i < COWBOYS; i++) { angulo = i * 360.0/COWBOYS + step * STEP_COWBOY; glPushMatrix(); glRotatef(-angulo,0.0,1.0,0.0); glTranslatef(RAIO_COWBOYS,0.0,0.0); glutSolidTeapot(1); glPopMatrix(); } } void drawScene() { drawPlane(); placeTrees(); drawDonut(); // move teapots up so that they are placed on top of the ground plane glTranslatef(0.0,1.0,0.0); drawCowboys(); drawIndios(); } float camH(float x, float z) { double intX, intZ; float fracX, fracZ; fracX = modf(x, &intX); fracZ = modf(z, &intZ); float alt1, alt2; alt1 = h(intX, intZ) * (1 - fracZ) + h(intX, intZ + 1) * fracZ; alt2 = h(intX + 1, intZ) * (1 - fracZ) + h(intX + 1, intZ + 1) * fracZ; return alt1 * (1 - fracX) + alt2 * fracX; } /*float alturaCamara(float x, float z){ double intX, intZ; float fracX, fracZ; fracX = modf(x, &intX); fracZ = modf(z, &intZ); float alt1, alt2; alt1 = mapa->h(intX, intZ) * (1 - fracZ) + mapa->h(intX, intZ + 1) * fracZ; alt2 = mapa->h(intX + 1, intZ) * (1 - fracZ) + mapa->h(intX + 1, intZ + 1) * fracZ; return alt1 * (1 - fracX) + alt2 * fracX; }*/ void renderScene(void) { float pos[4] = {-1.0, 1.0, 1.0, 0.0}; glClearColor(0.0f,0.0f,0.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); #define CAM 0 #if CAM == 1 gluLookAt(camX, h(camX+128, camZ+128) + 10, camZ, 0, 0, 0, 0.0f,1.0f,0.0f); #else camY = h(cX+128, cZ+128) + 2; gluLookAt(cX, camY, cZ, cX + cos(ang), camY, cZ + sin(ang), 0.0f,1.0f,0.0f); #endif glLightfv(GL_LIGHT1,GL_POSITION, pos); drawScene(); step++; // End of frame glutSwapBuffers(); } // escrever fun��o de processamento do teclado void processKeys(unsigned char key, int xx, int yy) { switch(key) { case 'a': case 'A': ang-=0.02; break; case 'd': case 'D': ang+=0.02; break; case 'w': case 'W': cX += 0.3*cos(ang); cZ += 0.3*sin(ang); break; case 's': case 'S': cX -= 0.5 *cos(ang); cZ -= 0.5*sin(ang); break; } } void processMouseButtons(int button, int state, int xx, int yy) { if (state == GLUT_DOWN) { startX = xx; startY = yy; if (button == GLUT_LEFT_BUTTON) tracking = 1; else if (button == GLUT_RIGHT_BUTTON) tracking = 2; else tracking = 0; } else if (state == GLUT_UP) { if (tracking == 1) { alpha += (xx - startX); beta += (yy - startY); } else if (tracking == 2) { r -= yy - startY; if (r < 3) r = 3.0; } tracking = 0; } } void processMouseMotion(int xx, int yy) { int deltaX, deltaY; int alphaAux, betaAux; int rAux; if (!tracking) return; deltaX = xx - startX; deltaY = yy - startY; if (tracking == 1) { alphaAux = alpha + deltaX; betaAux = beta + deltaY; if (betaAux > 85.0) betaAux = 85.0; else if (betaAux < -85.0) betaAux = -85.0; rAux = r; } else if (tracking == 2) { alphaAux = alpha; betaAux = beta; rAux = r - deltaY; if (rAux < 3) rAux = 3; } camX = rAux * sin(alphaAux * 3.14 / 180.0) * cos(betaAux * 3.14 / 180.0); camZ = rAux * cos(alphaAux * 3.14 / 180.0) * cos(betaAux * 3.14 / 180.0); camY = rAux * sin(betaAux * 3.14 / 180.0); } void init() { // Colocar aqui load da imagem que representa o mapa de alturas ilInit(); ilGenImages(1, &img_height); ilBindImage(img_height); ilLoadImage("terreno2.jpg"); ilConvertImage(IL_LUMINANCE,IL_UNSIGNED_BYTE); height_w = ilGetInteger(IL_IMAGE_WIDTH); height_h = ilGetInteger(IL_IMAGE_HEIGHT); height_data = ilGetData(); // Colocar aqui o c�digo para carregar a imagem e criar uma textura ilGenImages(1, &img_text); ilBindImage(img_text); ilLoadImage("relva1.jpg"); ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); text_w = ilGetInteger(IL_IMAGE_WIDTH); text_h = ilGetInteger(IL_IMAGE_HEIGHT); text_data = ilGetData(); grid_n = height_w; glGenTextures(1,&text_id); // unsigned int texID - variavel global; glBindTexture(GL_TEXTURE_2D,text_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, text_w, text_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, text_data); // alguns settings para OpenGL glEnable(GL_DEPTH_TEST); //glEnable(GL_CULL_FACE); // inicializa��o da luz glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); } int main(int argc, char **argv) { // inicializa��o glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA); glutInitWindowPosition(100,100); glutInitWindowSize(800,600); glutCreateWindow("CG@DI-UM"); // registo de fun��es glutDisplayFunc(renderScene); glutIdleFunc(renderScene); glutReshapeFunc(changeSize); // p�r aqui registo da fun��es do teclado e rato glutKeyboardFunc(processKeys); glutMouseFunc(processMouseButtons); glutMotionFunc(processMouseMotion); // alguns settings para OpenGL glEnable(GL_DEPTH_TEST); //glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); // inicializa��o da luz glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); init(); // entrar no ciclo do GLUT glutMainLoop(); return 0; }
[ "andvieira.16@db629c75-4b32-85d7-0afe-a27431d4d09a" ]
[ [ [ 1, 450 ] ] ]
f845fa5792fe65d54afee37411eb7c5ad0e97fd1
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/Swc/swc/CMenuSpawn.h
c7f511043977b0a51876035e1ab7cb762c526f54
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,493
h
// MenuSpawn.h: interface for the CMenuSpawn class. // ////////////////////////////////////////////////////////////////////// /* * <F> CMenuSpawn.h 1.0 23/09/2003 * * Copyright 2003 Francisco Campos. All rights reserved. * BEYONDATA PROPRIETARY. Use is subject to license terms. </F> * * \|||/ * |o_o| * ----o00o-------o00o--- **/ #if !defined(AFX_MENUSPAWN_H__BB6F2F01_91FA_11D1_8B78_0000B43382FE__INCLUDED_) #define AFX_MENUSPAWN_H__BB6F2F01_91FA_11D1_8B78_0000B43382FE__INCLUDED_ #pragma once class CMenuSpawn { public: struct ToolBarData { // struct for toolbar resource; guess you already know it ;) WORD wVersion; WORD wWidth; WORD wHeight; WORD wItemCount; }; struct SpawnItem { int iImageIdx; int iCmd; char cText[128]; }; struct ImageItem { int iImageIdx; int iCmd; }; struct FlotMenu { int iCmd; int Width; int iSubMenu; }; public: bool IsSpawnMenu(CMenu pMenu, const int iItem, const bool bByPos); bool GetMenuItemText(LPSTR csText, CMenu * pMenu, const int cmd, bool bByPos); void SetBackBitmap(const int iRes, COLORREF crBackColor); void SetBackBitmap(const int iRes); void SetTextColor(const COLORREF crNormal, const COLORREF crSelected); bool FindKeyboardShortcut(UINT nChar, UINT nFlags, HMENU pMenu, LRESULT &lRes); bool SetFont(LOGFONT * lf); HFONT hMenuFont, hGuiFont; CSize szImage; bool MeasureItem(LPMEASUREITEMSTRUCT lpm); bool DrawItem(LPDRAWITEMSTRUCT lp); int FindImageItem(const int cmd); SpawnItem * AddSpawnItem(const char * txt, const int cmd); void RemapMenu(HMENU pMenu); void AddImageItem(const int idx, WORD cmd); CImageCtrl ilList; CImageCtrl ilOther; COLORREF crMenuText, crMenuTextSel; COLORREF cr3dFace, crMenu, crHighlight, cr3dHilight, cr3dShadow, crGrayText; COLORREF m_clrBtnFace, m_clrBtnHilight, m_clrBtnShadow; int iSpawnItem; SpawnItem ** pSpawnItem; int iImageItem; ImageItem * pImageItem; FlotMenu fltMenu; bool bIsPopup; bool bBackBitmap; CBitmap bmpBack; bool LoadToolBarResource(unsigned int resId, UINT uBitmap=-1); bool AddToolBarResource(unsigned int resId, UINT uBitmap=-1); void EnableMenuItems(CMenu * pMenu, CWin * pParent); CMenuSpawn(); CMenuSpawn(const bool _IsPopup); virtual ~CMenuSpawn(); protected: void Init(); }; #endif // !defined(AFX_MENUSPAWN_H__BB6F2F01_91FA_11D1_8B78_0000B43382FE__INCLUDED_)
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 98 ] ] ]
061a6e14afad17d9ec38a3611d9cbc25afbf7bce
38fbddb35eb46ad1b65f4e9ed3d2d2c9fd717f42
/cob_trajectory_controller/common/include/cob_trajectory_controller/BSplineND.h
5cc8dd9b2ce404d8a41157cb90127ca87c703f73
[]
no_license
amixpal/cob_driver
75b8279043efc8d65319f548e9fe16feb2529f0a
8eba2c9fde7cb40765740f549586234dd251c9a1
refs/heads/master
2021-01-17T22:05:19.459569
2011-05-26T16:09:01
2011-05-26T16:09:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,253
h
//----------------------------------------------- // Neobotix /*********************************************************************** * * * written by Felix Geibel May 2009 * * at Fraunhofer IPA * * * * based on BSpline2d by Neobotix (see below) * * * ***********************************************************************/ // www.neobotix.de // Copyright (c) 2003. All rights reserved. // author: Bertram Rohrmoser //----------------------------------------------- #ifndef BSPLINE_ND_H #define BSPLINE_ND_H //----------------------------------------------- #include <vector> #include <cmath> #include <assert.h> #define BSPLINE_TINY 1e-20 /** * Implements a BSpline curve as a template class. * a PointND type needs the following operators: * operator=, copy constructor, p1 += p2, p1 * scalar * there needs to be a function Distance(p1,p2) * there needs to be a member function p1.zero() */ template <class PointND> class BSplineND { public: //----------------------- Interface BSplineND(); ~BSplineND(); void setCtrlPoints(const std::vector<PointND>& ctrlPointVec ); // main functions bool ipoWithConstSampleDist(double dIpoDist, std::vector<PointND>& ipoVec); bool ipoWithNumSamples(int iNumPts, std::vector<PointND>& ipoVec); void eval(double dPos, PointND& point); double getMaxdPos() const { return m_dLength; } private: //----------------------- Parameters double m_iGrad; //----------------------- Variables std::vector<PointND> m_CtrlPointVec; std::vector<double> m_KnotVec; double m_dLength; //----------------------- Member functions double evalBasis(double t, unsigned int i, int n); }; /***************************************************************************** * * * Implementierung bei TemplateKlassen im Headerfile * * * *****************************************************************************/ template <class PointND> inline BSplineND<PointND>::BSplineND() { m_iGrad = 3; m_dLength = 0; } //----------------------------------------------- template <class PointND> BSplineND<PointND>::~BSplineND() { } //----------------------------------------------- template <class PointND> void BSplineND<PointND>::setCtrlPoints(const std::vector<PointND>& ctrlPointVec ) { int iNumCtrlPoint; int i; double d; m_CtrlPointVec = ctrlPointVec; iNumCtrlPoint = m_CtrlPointVec.size(); if (iNumCtrlPoint < m_iGrad) { return; } m_KnotVec.resize( iNumCtrlPoint + m_iGrad ); // Calculate knots for(i = 0; i< m_iGrad; i++) { m_KnotVec[i] = 0; } int iNumInternalKnots = iNumCtrlPoint - m_iGrad; for(i=0; i<iNumInternalKnots; i++) { double Distance1 = 0.0; for(unsigned int k = 0; k < m_CtrlPointVec[i+1].size(); k++) { Distance1 += (m_CtrlPointVec[i+1].at(k) - m_CtrlPointVec[i+2].at(k)) * (m_CtrlPointVec[i+1].at(k) - m_CtrlPointVec[i+2].at(k)); } d= m_KnotVec[i+m_iGrad-1] + sqrt(Distance1); // OLD WITH JOINTD d= m_KnotVec[i+m_iGrad-1] + Distance( m_CtrlPointVec[i+1], m_CtrlPointVec[i+2] ); m_KnotVec[i+m_iGrad] = d; } double Distance2 = 0.0; for(unsigned int k = 0; k < m_CtrlPointVec[iNumInternalKnots+1].size(); k++) { Distance2 += ( m_CtrlPointVec[iNumInternalKnots+1].at(k) - m_CtrlPointVec[iNumInternalKnots+2].at(k)) * ( m_CtrlPointVec[iNumInternalKnots+1].at(k) - m_CtrlPointVec[iNumInternalKnots+2].at(k)); } d = m_KnotVec[iNumCtrlPoint-1] + sqrt(Distance2); // OLD WITH JOINTD d = m_KnotVec[iNumCtrlPoint-1] + Distance( m_CtrlPointVec[iNumInternalKnots+1], m_CtrlPointVec[iNumInternalKnots+2] ); for(i = 0; i< m_iGrad; i++) { m_KnotVec[i+iNumCtrlPoint] = d; } // This is not the arc-length but the maximum of the spline parameter. // eval(m_dLength, Point) should return the last point of the spline m_dLength = d; } //----------------------------------------------- template <class PointND> void BSplineND<PointND>::eval(double dPos, PointND& point) { double dFak; for(unsigned int i = 0; i<point.size(); i++) point.at(i) = 0.0; for(unsigned int i = 0; i < m_CtrlPointVec.size(); i++) { dFak = evalBasis(dPos, i, m_iGrad); for(unsigned int j = 0; j<point.size(); j++) point.at(j) += m_CtrlPointVec[i][j] * dFak; // !!!! TODO this might be wrong due to change from JointD to std::vector } } //----------------------------------------------- template <class PointND> bool BSplineND<PointND>::ipoWithConstSampleDist(double dIpoDist, std::vector<PointND >& ipoVec) { PointND buf = m_CtrlPointVec.front(); int iNumOfPoints; double dPos; //int iStart, iNextStart; if (m_CtrlPointVec.size() < m_iGrad) { ipoVec = m_CtrlPointVec; return false; } // Felix: Dies ist falsch? m_KnotVec.back() enthält nicht die tatsächliche // Bogenlänge entlang des Splines. Folge: Ergebnisvektor ist am Ende abge- // schnitten. iNumOfPoints = m_KnotVec.back() / dIpoDist + 2; ipoVec.resize(iNumOfPoints); // Calculate x- and y-coordinates dPos = 0; for(int i=0; i < iNumOfPoints -1 ; i++) { eval(dPos, buf); ipoVec[i] = buf; dPos += dIpoDist; } ipoVec.back() = m_CtrlPointVec.back(); return true; } /* //----------------------------------------------- //Florian bool BSplineND<PointND>::ipoWithConstSampleDist(double dIpoDist, OmniPath& ipoVec) { Neo::Vector2D buf; int iNumOfPoints; int iNumOfCtrlPoints; double dPos, viewang; double dx, dy, da; int i; bool bRet = true; int iStart, iNextStart; iNumOfCtrlPoints = m_OmniCtrlPointVec.getSize(); if ( iNumOfCtrlPoints < m_iGrad ) { bRet = false; iNumOfPoints = m_OmniCtrlPointVec.getSize(); ipoVec.clearVec(); for(i=0; i<iNumOfPoints; i++) { ipoVec.addFrame(m_OmniCtrlPointVec.m_VecPathPnt[i].Frm,m_OmniCtrlPointVec.m_VecPathPnt[i].ViewAng); } if ( iNumOfCtrlPoints < 2 ) { return bRet; } } else { iNumOfPoints = m_KnotVec.back() / dIpoDist + 2; ipoVec.m_VecPathPnt.resize(iNumOfPoints); // Calculate x- and y-coordinates dPos = 0; iStart = 0; for(i=0; i < iNumOfPoints -1 ; i++) { // eval(dPos, buf); eval(dPos, buf, iStart, iNextStart, viewang); iStart = iNextStart; ipoVec.m_VecPathPnt[i].Frm.x() = buf.x(); ipoVec.m_VecPathPnt[i].Frm.y() = buf.y(); ipoVec.m_VecPathPnt[i].ViewAng=viewang; dPos += dIpoDist; } ipoVec.m_VecPathPnt.back().Frm.x() = m_OmniCtrlPointVec.m_VecPathPnt.back().Frm.x(); ipoVec.m_VecPathPnt.back().Frm.y() = m_OmniCtrlPointVec.m_VecPathPnt.back().Frm.y(); ipoVec.m_VecPathPnt.back().ViewAng = m_OmniCtrlPointVec.m_VecPathPnt.back().ViewAng; } // Calculate angle for(i=0; i < iNumOfPoints-1; i++) { dx = ipoVec.m_VecPathPnt[i+1].Frm.x() - ipoVec.m_VecPathPnt[i].Frm.x(); dy = ipoVec.m_VecPathPnt[i+1].Frm.y() - ipoVec.m_VecPathPnt[i].Frm.y(); da = atan2(dy, dx); MathSup::normalizePi(da); ipoVec.m_VecPathPnt[i].Frm.a() = da; } ipoVec.m_VecPathPnt.back().Frm.a() = da; return bRet; } */ //----------------------------------------------- template <class PointND> bool BSplineND<PointND>::ipoWithNumSamples(int iNumOfPoints, std::vector<PointND >& ipoVec) { PointND buf; double dPos, dInc; if (m_CtrlPointVec.size() < m_iGrad) { ipoVec = m_CtrlPointVec; return false; } dInc = m_KnotVec.back() / (double)(iNumOfPoints-1); ipoVec.resize(iNumOfPoints); // Calculate x- and y-coordinates dPos = 0; for(int i=0; i < iNumOfPoints -1 ; i++) { eval(dPos, buf); ipoVec[i] = buf; dPos += dInc; } ipoVec.back() = m_CtrlPointVec.back(); return true; } template <class PointND> double BSplineND<PointND>::evalBasis(double u, unsigned int i, int n) { assert(i >= 0); assert(i < m_KnotVec.size() - 1 ); if (n==1) { if ( (m_KnotVec[i]<=u) && ( u<m_KnotVec[i+1]) ) { return 1.0; } else { return 0.0; } } else { double N; double dNum1, dNum2; double dDen1, dDen2; dDen1 = u - m_KnotVec[i]; dNum1 = m_KnotVec[i+n-1] - m_KnotVec[i]; dDen2 = m_KnotVec[i+n] - u; dNum2 = m_KnotVec[i+n] - m_KnotVec[i+1]; if ( (fabs(dNum1) > BSPLINE_TINY)&&(fabs(dNum2) > BSPLINE_TINY) ) { N = dDen1 / dNum1 * evalBasis(u, i , n-1); N += dDen2 / dNum2 * evalBasis(u, i+1 , n-1); } else if ( (fabs(dNum1) < BSPLINE_TINY)&&(fabs(dNum2) > BSPLINE_TINY) ) { N = dDen2 / dNum2 * evalBasis(u, i+1 , n-1); } else if ((fabs(dNum1) > BSPLINE_TINY)&&(fabs(dNum2) < BSPLINE_TINY)) { N = dDen1 / dNum1 * evalBasis(u, i , n-1); } else { N = 0; } return N; } } #endif
[ [ [ 1, 357 ] ] ]
4315bcb0183daa6e538163b5bf21f99b6ed1a64e
48a5ca3c8319ddc1bbe36854ccdf5a8e4985dcee
/ht-chess/src/MoveSelector.h
557c5607fbe463b344ce1d9a1e2003127c41661c
[]
no_license
MagnusPihl/ht-chess
0d873042ef9cd3047ba2b6fba1e70e1ccbb3a68b
2c8e636d9dde1769544617086def02c378ec83b0
refs/heads/master
2020-11-26T18:29:43.206540
2008-05-26T15:35:37
2008-05-26T15:35:37
32,142,844
0
0
null
null
null
null
UTF-8
C++
false
false
19,824
h
#ifndef MOVESELECTOR_H #define MOVESELECTOR_H #include <vector> #include "Move.h" #include "Piece.h" #include "Evaluator.h" #include "GameConfiguration.h" #if USE_MINIMAX_ONLY == 1 class MiniMax { private: MoveGenerator moveGen; LayeredStack<Move, 1> moves; Evaluator evaluator; #if USE_TIME_CONSTRAINT == 1 int timeStarted; #endif int miniMax(Board &board, Move &path, bool isMaximizer=true, int curDepth=0, int maxDepth=100) { int boardState; /*#if USE_TIME_CONSTRAINT == 1 if (SDL_GetTicks() - timeStarted > MAX_SEARCH_TIME) { printf("timeeee\n"); } #endif */ if ( /*#if USE_TIME_CONSTRAINT == 1 (SDL_GetTicks() - timeStarted > MAX_SEARCH_TIME) || #endif */ (curDepth == maxDepth) || (((boardState = board.isCheckmate()) & (IS_STALEMATE | IS_CHECKMATE)) != 0)) //if leaf { return evaluator(board, curDepth, boardState); } else if(isMaximizer) //if maximizer { int bestMove = -10000; int curMove; moveGen.generateMoves(board, WHITE, moves); for(LayeredStack<Move,1>::iterator itr = moves.begin(); itr != moves.end(); ++itr) { moves.setReturnPoint(); (*itr).execute(board); curMove = miniMax(board, path, false, curDepth+1, maxDepth); if(curMove > bestMove) { bestMove = curMove; if(curDepth == 0) path = (*itr); } (*itr).unexecute(board); moves.rollBack(); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 test().movesGenerated += moves.size(); #endif return bestMove; } else //if minimizer { int bestMove = 10000; int curMove; moveGen.generateMoves(board, BLACK, moves); for(LayeredStack<Move,1>::iterator itr = moves.begin(); itr != moves.end(); ++itr) { moves.setReturnPoint(); (*itr).execute(board); curMove = miniMax(board, path, true, curDepth+1, maxDepth); if(curMove < bestMove) { bestMove = curMove; if(curDepth == 0) path = (*itr); } (*itr).unexecute(board); moves.rollBack(); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 test().movesGenerated += moves.size(); #endif return bestMove; } } public: Move operator()(Board &board, bool isMaximizer=true, int maxDepth=DEFAULT_PLY) { Move path; #if TEST_PERFORMANCE == 1 #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().movesGenerated = 0; #endif #if PRINT_SEARCH_TIME == 1 test().time = SDL_GetTicks(); #endif #if PRINT_NUMBER_OF_EVALUATIONS == 1 test().evaluations = 0; #endif #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().movesGenerated = 0; #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 test().cutoffs = 0; #endif #if USE_EVALUATION_CACHING == 1 #if PRINT_CACHE_RETRIEVALS == 1 test().cacheRetrievals = 0; #endif #if PRINT_CACHE_RETRIEVALS == 1 test().cacheRetrievals = 0; #endif #endif #endif /*#if USE_TIME_CONSTRAINT == 1 timeStarted = SDL_GetTicks(); #endif*/ moves.clear(); miniMax(board, path, isMaximizer, 0, maxDepth); #if TEST_PERFORMANCE == 1 #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().out << "movesGenerated = [movesGenerated, " << test().movesGenerated << "];" << std::endl; #endif #if PRINT_SEARCH_TIME == 1 test().out << "searchTime = [searchTime, " << SDL_GetTicks() - test().time << "];" << std::endl; #endif #if PRINT_NUMBER_OF_EVALUATIONS == 1 test().out << "evaluations = [evaluations, " << test().evaluations << "];" << std::endl; #endif #if USE_EVALUATION_CACHING == 1 #if PRINT_CACHE_SIZE == 1 test().out << "cacheSize = [cacheSize, " << evaluator.cache.getSize() << "];" << std::endl; #endif #if PRINT_CACHE_RETRIEVALS == 1 test().out << "cacheRetrievals = [cacheRetrievals, " << test().cacheRetrievals << "];" << std::endl; #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 test().out << "cutoffs = [cutoffs, " << test().cutoffs << "];" << std::endl; #endif #endif #endif #if CLEAR_CACHE_ON_NON_REVERSABLE_MOVE == 1 if (path.getContent() != NO_PIECE) { evaluator.clearCache(); } #endif return path; } }; /*class AlphaBeta { private: MoveGenerator moveGen; Evaluator evaluator; int alphaBeta(Board &board, Move &path, bool isMaximizer=true, int curDepth=0, int maxDepth=100, int alpha=-100000, int beta=100000) { if(curDepth == maxDepth || board.isCheckmate() || board.isStalemate()) //if leaf { return evaluator(board, curDepth); } else if(isMaximizer) //if maximizer { std::vector<Move> moveList; moveGen.generateMoves(board, WHITE, moveList, moveList); for(std::vector<Move>::iterator itr = moveList.begin(); itr != moveList.end() && alpha < beta; itr++) { (*itr).execute(board); int V = alphaBeta(board, path, false, curDepth+1, maxDepth, alpha, beta); if(V > alpha) { alpha = V; if(curDepth==0) path = (*itr); } (*itr).unexecute(board); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 test().movesGenerated += moves.size(); #endif return alpha; } else //if minimizer { std::vector<Move> moveList; moveGen.generateMoves(board, BLACK, moveList, moveList); for(std::vector<Move>::iterator itr = moveList.begin(); itr != moveList.end() && alpha < beta; itr++) { (*itr).execute(board); int V = alphaBeta(board, path, true, curDepth+1, maxDepth, alpha, beta); if(V < beta) { beta = V; if(curDepth==0) path = (*itr); } (*itr).unexecute(board); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 test().movesGenerated += moves.size(); #endif return beta; } } public: Move operator()(Board &board, bool isMaximizer=true, int maxDepth=DEFAULT_PLY) { Move path; alphaBeta(board, path, isMaximizer, 0, maxDepth); return path; } };*/ #else class AlphaBetaOptimized { private: MoveGenerator moveGen; Evaluator evaluator; LayeredStack<Move, STACK_SIZE> moveList; Move nextMove[2]; //0 == WHITE, 1 == BLACK #if USE_TIME_CONSTRAINT == 1 int timeStarted; #endif int alphaBeta(Board &board, Move &path, bool isMaximizer, int curDepth, int maxDepth, int alpha, int beta) { #if PRINT_NUMBER_OF_CUTOFFS == 1 && USE_MINIMAX_ONLY == 0 int cutoffs = 0; #endif /*#if USE_TIME_CONSTRAINT == 1 if (SDL_GetTicks() - timeStarted > MAX_SEARCH_TIME) { printf("time\n"); } #endif*/ int boardState; if( #if USE_TIME_CONSTRAINT == 1 (SDL_GetTicks() - timeStarted > MAX_SEARCH_TIME) || #endif (curDepth == maxDepth) || (((boardState = board.isCheckmate()) & (IS_CHECKMATE | IS_STALEMATE)) != 0)) //if leaf { return evaluator(board, curDepth, boardState); } else if(isMaximizer) //if maximizer { moveGen.generateMoves(board, WHITE, moveList); LayeredStack<Move, STACK_SIZE>::iterator itr; for(itr = moveList.begin(); (itr != moveList.end()) && (alpha < beta); ++itr) { #if PRINT_NUMBER_OF_CUTOFFS == 1 && USE_MINIMAX_ONLY == 0 cutoffs++; #endif moveList.setReturnPoint(); (*itr).execute(board); int V = alphaBeta(board, path, false, curDepth+1, maxDepth, alpha, beta); if(V > alpha) { alpha = V; if(curDepth==2) nextMove[0] = (*itr); } (*itr).unexecute(board); moveList.rollBack(); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().movesGenerated[test().iteration-1] += moveList.size(); #else test().movesGenerated += moveList.size(); #endif #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().cutoffs[test().iteration-1] += moveList.size() - cutoffs; #else test().cutoffs += moveList.size() - cutoffs; #endif #endif return alpha; } else //if minimizer { moveGen.generateMoves(board, BLACK, moveList); for(LayeredStack<Move, STACK_SIZE>::iterator itr = moveList.begin(); (itr != moveList.end()) && (alpha < beta); ++itr) { #if PRINT_NUMBER_OF_CUTOFFS == 1 && USE_MINIMAX_ONLY == 0 cutoffs++; #endif moveList.setReturnPoint(); (*itr).execute(board); int V = alphaBeta(board, path, true, curDepth+1, maxDepth, alpha, beta); if(V < beta) { beta = V; if(curDepth==2) nextMove[1] = (*itr); } (*itr).unexecute(board); moveList.rollBack(); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().movesGenerated[test().iteration-1] += moveList.size(); #else test().movesGenerated += moveList.size(); #endif #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().cutoffs[test().iteration-1] += moveList.size() - cutoffs; #else test().cutoffs += moveList.size() - cutoffs; #endif #endif return beta; } } int alphaBeta(Board &board, Move &path, bool isMaximizer=true, int maxDepth=100, int alpha=-100000, int beta=100000) { #if PRINT_NUMBER_OF_CUTOFFS == 1 && USE_MINIMAX_ONLY == 0 int cutoffs = 0; #endif if(isMaximizer) //if maximizer { moveGen.generateMoves(board, WHITE, moveList); for(LayeredStack<Move, STACK_SIZE>::iterator itr = moveList.begin(); (itr != moveList.end()) && (alpha < beta); ++itr) { #if PRINT_NUMBER_OF_CUTOFFS == 1 && USE_MINIMAX_ONLY == 0 cutoffs++; #endif moveList.setReturnPoint(); (*itr).execute(board); int V = alphaBeta(board, path, false, 1, maxDepth, alpha, beta); if(V > alpha) { alpha = V; moveList.setValue(itr, V); path = (*itr); } (*itr).unexecute(board); moveList.rollBack(); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().movesGenerated[test().iteration-1] += moveList.size(); #else test().movesGenerated += moveList.size(); #endif #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().cutoffs[test().iteration-1] += moveList.size() - cutoffs; #else test().cutoffs += moveList.size() - cutoffs; #endif #endif return alpha; } else //if minimizer { moveGen.generateMoves(board, BLACK, moveList); for(LayeredStack<Move, STACK_SIZE>::iterator itr = moveList.begin(); (itr != moveList.end()) && (alpha < beta); ++itr) { #if PRINT_NUMBER_OF_CUTOFFS == 1 cutoffs++; #endif moveList.setReturnPoint(); (*itr).execute(board); int V = alphaBeta(board, path, true, 1, maxDepth, alpha, beta); if(V < beta) { beta = V; moveList.setValue(itr, V); path = (*itr); } (*itr).unexecute(board); moveList.rollBack(); } #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().movesGenerated[test().iteration-1] += moveList.size(); #else test().movesGenerated += moveList.size(); #endif #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().cutoffs[test().iteration-1] += moveList.size() - cutoffs; #else test().cutoffs += moveList.size() - cutoffs; #endif #endif return beta; } } public: //ofstream moveFile; AlphaBetaOptimized() { /*moveList.resize(100*DEFAULT_PLY); killerMoveList.resize(50*DEFAULT_PLY);*/ //moveFile.open("moves.txt"); } Move operator()(Board &board, bool isMaximizer=true, int maxDepth=DEFAULT_PLY) { Move path; moveList.clear(); #if USE_TIME_CONSTRAINT == 1 timeStarted = SDL_GetTicks(); #endif #if PRINT_SEARCH_TIME == 1 && TEST_PERFORMANCE == 1 #if USE_ITERATIVE_DEEPENING == 1 test().time[0] = SDL_GetTicks(); #else test().time = SDL_GetTicks(); #endif #endif if (isMaximizer) { moveGen.generateMoves(board, WHITE , moveList); } else { moveGen.generateMoves(board, BLACK , moveList); } #if USE_ITERATIVE_DEEPENING == 1 for(int i = 2; i <= maxDepth; ++i) { #if TEST_PERFORMANCE == 1 #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().movesGenerated[i-2] = 0; #endif #if PRINT_NUMBER_OF_EVALUATIONS == 1 test().evaluations[i-2] = 0; #endif #if USE_EVALUATION_CACHING == 1 && PRINT_CACHE_RETRIEVALS == 1 test().cacheRetrievals[i-2] = 0; #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 test().cutoffs[i-2] = 0; #endif test().iteration = (i-1); #endif /*#if USE_TIME_CONSTRAINT == 1 if (SDL_GetTicks() - timeStarted > MAX_SEARCH_TIME) { printf("time %i\n", i); break; } #endif*/ alphaBeta(board, path, isMaximizer, i); #if USE_UNSORTED_STACK == 0 moveList.sort(); #endif #if PRINT_SEARCH_TIME == 1 && TEST_PERFORMANCE == 1 test().time[i-2] = (SDL_GetTicks() - test().time[i-2]); if (i != maxDepth) { test().time[i-1] = SDL_GetTicks(); } #endif #if USE_EVALUATION_CACHING == 1 && PRINT_CACHE_SIZE == 1 && TEST_PERFORMANCE == 1 test().cacheSize[i-2] = evaluator.cache.getSize(); #endif } #if TEST_PERFORMANCE == 1 #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().out << "movesGenerated = [movesGenerated, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().movesGenerated[i] << "; "; } test().out << test().movesGenerated[maxDepth-2] << "]];" << std::endl; #endif #if PRINT_SEARCH_TIME == 1 test().out << "searchTime = [searchTime, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().time[i] << "; "; } test().out << test().time[maxDepth-2] << "]];" << std::endl; #endif #if PRINT_NUMBER_OF_EVALUATIONS == 1 test().out << "evaluations = [evaluations, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().evaluations[i] << "; "; } test().out << test().evaluations[maxDepth-2] << "]];" << std::endl; #endif #if USE_EVALUATION_CACHING == 1 && PRINT_CACHE_RETRIEVALS == 1 test().out << "cacheRetrievals = [cacheRetrievals, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().cacheRetrievals[i] << "; "; } test().out << test().cacheRetrievals[maxDepth-2] << "]];" << std::endl; #endif #if USE_EVALUATION_CACHING == 1 && PRINT_CACHE_SIZE == 1 test().out << "cacheSize = [cacheSize, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().cacheSize[i] << "; "; } test().out << test().cacheSize[maxDepth-2] << "]];" << std::endl; #endif #if USE_EVALUATION_CACHING == 1 && PRINT_CACHE_CLEARS == 1 test().out << "cacheClears = [cacheClears, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().cacheClears[i] << "; "; } test().out << test().cacheClears[maxDepth-2] << "]];" << std::endl; #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 test().out << "cutoffs = [cutoffs, ["; for(int i = 0; i < (maxDepth-2); ++i) { test().out << test().cutoffs[i] << "; "; } test().out << test().cutoffs[maxDepth-2] << "]];" << std::endl; #endif #endif #else #if TEST_PERFORMANCE == 1 #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().movesGenerated = 0; #endif #if PRINT_NUMBER_OF_EVALUATIONS == 1 test().evaluations = 0; #endif #if USE_EVALUATION_CACHING == 1 #if PRINT_CACHE_RETRIEVALS == 1 test().cacheRetrievals = 0; #endif #if PRINT_CACHE_CLEARS == 1 test().cacheClears = 0; #endif #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 test().cutoffs = 0; #endif #endif alphaBeta(board, path, isMaximizer, maxDepth); #if TEST_PERFORMANCE == 1 #if PRINT_NUMBER_OF_MOVES_GENERATED == 1 test().out << "movesGenerated = [movesGenerated, " << test().movesGenerated << "];" << std::endl; #endif #if PRINT_SEARCH_TIME == 1 test().out << "searchTime = [searchTime, " << (SDL_GetTicks() - test().time) << "];" << std::endl; #endif #if PRINT_NUMBER_OF_EVALUATIONS == 1 test().out << "evaluations = [evaluations, " << test().evaluations << "];" << std::endl; #endif #if PRINT_NUMBER_OF_CUTOFFS == 1 test().out << "cutoffs = [cutoffs, " << test().cutoffs << "];" << std::endl; #endif #if USE_EVALUATION_CACHING == 1 #if PRINT_CACHE_RETRIEVALS == 1 test().out << "cacheRetrievals = [cacheRetrievals, " << test().cacheRetrievals << "];" << std::endl; #endif #if PRINT_CACHE_SIZE == 1 test().out << "cacheSize = [cacheSize, " << evaluator.cache.getSize() << "];" << std::endl; #endif #if PRINT_CACHE_CLEARS == 1 test().out << "cacheClears = [cacheClears, " << test().cacheClears << "];" << std::endl; #endif #endif #endif #endif #if CLEAR_CACHE_ON_NON_REVERSABLE_MOVE == 1 if (path.getContent() != NO_PIECE) { evaluator.clearCache(); } #endif return path; } }; class StaticMoveSelector { private: std::vector<Move> moveList; int listPos; public: StaticMoveSelector() { listPos = 0; //Insert some moves } void setMoveList(std::vector<Move> moves) { moveList = moves; listPos = 0; } Move operator()() { return moveList[listPos++]; } }; #endif #endif
[ "magnus.pihl@afdedcdd-3e49-0410-aff0-259e14133cc1", "[email protected]@afdedcdd-3e49-0410-aff0-259e14133cc1" ]
[ [ [ 1, 7 ], [ 20, 20 ], [ 40, 40 ], [ 50, 50 ], [ 55, 56 ], [ 75, 75 ], [ 77, 77 ], [ 82, 83 ], [ 87, 87 ], [ 94, 95 ], [ 98, 98 ], [ 139, 140 ], [ 176, 176 ], [ 180, 180 ], [ 182, 182 ], [ 189, 189 ], [ 191, 191 ], [ 199, 199 ], [ 208, 208 ], [ 215, 215 ], [ 217, 217 ], [ 221, 221 ], [ 237, 238 ], [ 247, 247 ], [ 249, 249 ], [ 251, 251 ], [ 274, 274 ], [ 287, 287 ], [ 330, 330 ], [ 332, 332 ], [ 334, 334 ], [ 362, 362 ], [ 372, 373 ], [ 430, 430 ], [ 458, 458 ], [ 469, 469 ], [ 481, 481 ], [ 496, 496 ], [ 502, 502 ], [ 504, 504 ], [ 515, 516 ], [ 547, 547 ], [ 581, 581 ], [ 590, 590 ], [ 599, 599 ], [ 687, 687 ], [ 689, 689 ], [ 700, 700 ], [ 706, 706 ], [ 713, 715 ] ], [ [ 8, 19 ], [ 21, 39 ], [ 41, 49 ], [ 51, 54 ], [ 57, 74 ], [ 76, 76 ], [ 78, 81 ], [ 84, 86 ], [ 88, 93 ], [ 96, 97 ], [ 99, 138 ], [ 141, 175 ], [ 177, 179 ], [ 181, 181 ], [ 183, 188 ], [ 190, 190 ], [ 192, 198 ], [ 200, 207 ], [ 209, 214 ], [ 216, 216 ], [ 218, 220 ], [ 222, 236 ], [ 239, 246 ], [ 248, 248 ], [ 250, 250 ], [ 252, 273 ], [ 275, 286 ], [ 288, 329 ], [ 331, 331 ], [ 333, 333 ], [ 335, 361 ], [ 363, 371 ], [ 374, 429 ], [ 431, 457 ], [ 459, 468 ], [ 470, 480 ], [ 482, 495 ], [ 497, 501 ], [ 503, 503 ], [ 505, 514 ], [ 517, 546 ], [ 548, 580 ], [ 582, 589 ], [ 591, 598 ], [ 600, 686 ], [ 688, 688 ], [ 690, 699 ], [ 701, 705 ], [ 707, 712 ] ] ]
e4382037f926173e16af5be943556d8180d28317
036205456b03f717177170d91cc3e75080548aaa
/util/search.cc
076f5e0f4a739881c363ff113ab7862d0d86a0cb
[]
no_license
androidsercan/experimental-toolkit-in-c
e877e051fc9546048eaf4287e49865192890d91c
ac545219ed3fcca865c147b0f53e13bff5829fd1
refs/heads/master
2016-08-12T05:04:36.608456
2011-12-14T15:18:04
2011-12-14T15:18:04
43,951,774
0
0
null
null
null
null
UTF-8
C++
false
false
76
cc
// $Id: search.cc 3575 2011-06-10 07:33:40Z haowu $ #include "search.h"
[ [ [ 1, 3 ] ] ]
aa89b78e6b4324cf14846d4ceac72b958f8fa20f
6b99c157ea698e70fca17073c680638f8e516d08
/ComConnection.cpp
071a121793f2c5f05906e9761a808ee941518788
[]
no_license
melagabri/sendelf
3aef89b2e3e7d0424e738fbe87701672d6026fbf
beb17f02ceef3f71cf9e13cae545abe77c282764
refs/heads/master
2021-01-10T06:30:37.130626
2009-10-10T16:39:39
2009-10-10T16:39:39
54,057,363
0
0
null
null
null
null
UTF-8
C++
false
false
2,410
cpp
#include "StdAfx.h" #include "ComConnection.h" #include "globals.h" #define FTDI_PACKET_SIZE 3968 CComConnection::CComConnection(void) : gecko(INVALID_HANDLE_VALUE) { if (hInstGecko == NULL) { throw TEXT("Cannot load the required dll's for USB Gecko."); } // Find the functions FT_Open = (Func_FT_Open) GetProcAddress(hInstGecko, "FT_Open"); FT_GetComPortNumber = (Func_FT_GetComPortNumber) GetProcAddress(hInstGecko, "FT_GetComPortNumber"); FT_Close = (Func_FT_Close) GetProcAddress(hInstGecko, "FT_Close"); } CComConnection::~CComConnection(void) { if (gecko != INVALID_HANDLE_VALUE) { CloseHandle(gecko); } if (hInstGecko != NULL) { FreeLibrary(hInstGecko); } } void CComConnection::Connect() { HANDLE ftHandle; ULONG res = FT_Open(0, &ftHandle); if (res != 0) { throw TEXT("Cannot start driver needed for USB Gecko"); } LONG portnumber; res = FT_GetComPortNumber(ftHandle, &portnumber); FT_Close(ftHandle); if (res != 0) { throw TEXT("Cannot find correct COM portnumber"); } TCHAR comport[5]; wsprintf(comport, L"COM%d", portnumber); gecko = CreateFile(comport, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (gecko == INVALID_HANDLE_VALUE) { throw TEXT("Cannot open port"); } DCB dcb; GetCommState(gecko, &dcb); dcb.BaudRate = 115200; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; SetCommState(gecko, &dcb); COMMTIMEOUTS timeouts; GetCommTimeouts(gecko, &timeouts); memset(&timeouts, 0, sizeof(COMMTIMEOUTS)); timeouts.ReadIntervalTimeout = MAXDWORD; if (!SetCommTimeouts(gecko, &timeouts)) { throw TEXT("Cannot set timeouts on port."); } if (!SetCommMask(gecko, 0)) { throw TEXT("Cannot set event mask on port."); } PurgeComm(gecko, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_TXABORT | PURGE_RXABORT); } void CComConnection::Send(const char *buffer, int length) { DWORD res; int left = length; while (left) { int chunk = left; if (chunk > FTDI_PACKET_SIZE) chunk = FTDI_PACKET_SIZE; if (!WriteFile(gecko, buffer, chunk, &res, NULL)) { throw TEXT("Error while writing to USB Gecko"); } left -= res; buffer += res; } } void CComConnection::Disconnect() { if (gecko != INVALID_HANDLE_VALUE) { CloseHandle(gecko); gecko = INVALID_HANDLE_VALUE; } }
[ [ [ 1, 100 ] ] ]
b881973d52ac5253bc858f6c25aa3ff009f8418d
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/src/MeshCollision.cpp
4b4a463fc7dfd566b172a9e8528bc576775e695d
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
7,390
cpp
/*******************************************************************************/ /** * @file MeshCollision.cpp. * * @brief メッシュデータ衝突判定クラスソースファイル. * * @date 2008/07/18. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #include "Ngl/MeshCollision.h" #include <cassert> using namespace Ngl; /** 非衝突 */ const PlaneCollisionReport MeshCollision::NOT_COLLISION = PLANECOLLISIONREPORT_NOT_COLLISION; /*===========================================================================*/ /** * @brief 衝突判定データを作成する * * @param[in] info メッシュ情報構造体の参照. * @param[in] vertices 頂点バッファデータのポインタ. * @param[in] indices インデックスバッファデータのポインタ * @return なし. */ void MeshCollision::create( const MeshInfo& info, IBuffer* vertices, IBuffer* indices ) { assert( vertices != NULL ); assert( indices != NULL ); // 面データ情報を設定 info_ = info; // すでに平面が生成されている場合はクリアする if( planeArray_.empty() == false ){ planeArray_.clear(); } // 配列のサイズを設定 planeArray_.resize( sizeof( Plane ) * ( info_.numIndices/ 3 ) ); // 頂点データを取得 vertices_.resize( sizeof( Vector3 ) * info_.numVertices ); vertices->getData( (void*)&vertices_[ 0 ] ); // インデックスデータを取得 indices_.resize( sizeof( unsigned short ) * info_.numIndices ); indices->getData( (void*)&indices_[ 0 ] ); // ポリゴンを作成する for( unsigned int i=0; i<( info_.numIndices/3 ); i++ ){ // ポリゴンの3頂点を取得する planeArray_[i].createFromPoints( vertices_[ indices_[ i*3+0 ] ], vertices_[ indices_[ i*3+1 ] ], vertices_[ indices_[ i*3+2 ] ] ); } } /*===========================================================================*/ /** * @brief 線分との衝突判定 * * @param[in] line0 線分の始点. * @param[in] line1 線分の終点. * @return 衝突結果構造体の参照. */ const PlaneCollisionReport& MeshCollision::line( const float* line0, const float* line1 ) { // すべてのポリゴンと線分との衝突判定を行う for( unsigned int i=0; i<info_.numIndices/3; ++i ){ const PlaneCollisionReport& param = polygonAndLine( i, line0, line1 ); // 衝突していたか if( param.isCollision == true ){ return param; } } return NOT_COLLISION; } /*===========================================================================*/ /** * @brief 指定のポリゴンと線分との衝突判定 * * @param[in] polygonNo ポリゴンデータ番号. * @param[in] line0 線分の始点. * @param[in] line1 線分の終点. * @return 衝突結果構造体の参照. */ const PlaneCollisionReport& MeshCollision::polygonAndLine( int polygonNo, const float* line0, const float* line1 ) { // 裏面のポリゴンとは衝突判定しない if( planeArray_[ polygonNo ].getClassifyPoint( line0 ) == Plane::BEHIND_PLANE ){ return NOT_COLLISION; } // ポリゴンの3頂点を取得する Vector3 vert[3]; vert[0] = vertices_[ indices_[ polygonNo*3+0 ] ]; vert[1] = vertices_[ indices_[ polygonNo*3+1 ] ]; vert[2] = vertices_[ indices_[ polygonNo*3+2 ] ]; // ポリゴンと線分の衝突判定を行う return collision_.polygonAndLine( vert, 3, planeArray_[polygonNo], line0, line1 ); } /*===========================================================================*/ /** * @brief 3D線との衝突判定 * * @param[in] rayPos 3D線の始点座標. * @param[in] rayDir 3D線の方向. * @return 面データ衝突パラメーター. */ const PlaneCollisionReport& MeshCollision::ray( const float* rayPos, const float* rayDir ) { // 全ポリゴンとレイの衝突判定をする for( unsigned int i=0; i<info_.numIndices/3; i++ ){ const PlaneCollisionReport& param = polygonAndRay( i, rayPos, rayDir ); // 衝突していた if( param.isCollision == true ){ return param; } } // 衝突していなかった return NOT_COLLISION; } /*===========================================================================*/ /** * @brief 指定のポリゴンと3D線との衝突判定 * * @param[in] polygonNo ポリゴンデータ番号. * @param[in] rayPos 3D線の始点座標. * @param[in] rayDir 3D線の方向. * @return 面データ衝突パラメーター. */ const PlaneCollisionReport& MeshCollision::polygonAndRay( int polygonNo, const float* rayPos, const float* rayDir ) { // 裏面のポリゴンとは衝突判定をしない if( planeArray_[ polygonNo ].getClassifyPoint( rayPos ) == Plane::BEHIND_PLANE ){ return NOT_COLLISION; } // ポリゴンの3頂点を取得する Vector3 vert[3]; vert[0] = vertices_[ indices_[ polygonNo*3+0 ] ]; vert[1] = vertices_[ indices_[ polygonNo*3+1 ] ]; vert[2] = vertices_[ indices_[ polygonNo*3+2 ] ]; // ポリゴンとレイの衝突判定を行う return collision_.polygonAndRay( vert, 3, planeArray_[ polygonNo ], rayPos, rayDir ); } /*===========================================================================*/ /** * @brief 球体との衝突判定 * * @param[in] center 球体の中心位置. * @param[in] radius 球体の半径. * @return 面データ衝突パラメーター. */ const PlaneCollisionReport& MeshCollision::sphere( const float* center, float radius ) { // 全ポリゴンと球体との衝突判定を行う for( unsigned int i = 0; i<info_.numIndices/3; i++ ){ const PlaneCollisionReport& param = polygonAndSphere( i, center, radius ); // 衝突していたか if( param.isCollision == true ){ return param; } } // 衝突していなかった return NOT_COLLISION; } /*===========================================================================*/ /** * @brief 指定のポリゴンと球体との衝突判定 * * @param[in] polygonNo ポリゴンデータ番号. * @param[in] center 球体の中心位置. * @param[in] radius 球体の半径. * @return 面データ衝突パラメーター. */ const PlaneCollisionReport& MeshCollision::polygonAndSphere( int polygonNo, const float* center, float radius ) { // 球体がポリゴンと交差しないか調べる if( planeArray_[ polygonNo ].getClassifySphere( center, radius ) != Plane::INTERSECTS_PLANE ){ return NOT_COLLISION; } // ポリゴンの3頂点を取得する Vector3 vert[3] = { vertices_[ indices_[ polygonNo*3+0 ] ], vertices_[ indices_[ polygonNo*3+1 ] ], vertices_[ indices_[ polygonNo*3+2 ] ] }; // ポリゴンと球体が衝突しているか const PlaneCollisionReport& param = collision_.polygonAndSphere( vert, 3, planeArray_[ polygonNo ], center, radius ); // 衝突しているか if( param.isCollision == true ){ // 衝突していた return param; } // ポリゴンのエッジと球体が衝突しているか return collision_.polygonEdgeAndSphere( vert, 3, center, radius ); } /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 241 ] ] ]
ee3b5e0f82eef179e94e84ddfde10ed301a57ad8
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestlist/src/bctestlistcontainer.cpp
88b08cdd7228d7eba3fd129c3246c8d9bf76bab8
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
3,499
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: container * */ #include "bctestlistcontainer.h" #include "bctestlistbasecase.h" // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // C++ default Constructor // --------------------------------------------------------------------------- // CBCTestListContainer::CBCTestListContainer() { } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestListContainer::~CBCTestListContainer() { delete iControl; iControl = NULL; } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestListContainer::ConstructL( const TRect& aRect ) { CreateWindowL(); SetRect( aRect ); ActivateL(); } // ---------------------------------------------------------------------------- // CBCTestListContainer::Draw // Fills the window's rectangle. // ---------------------------------------------------------------------------- // void CBCTestListContainer::Draw( const TRect& aRect ) const { CWindowGc& gc = SystemGc(); gc.SetPenStyle( CGraphicsContext::ENullPen ); gc.SetBrushColor( KRgbGray ); gc.SetBrushStyle( CGraphicsContext::ESolidBrush ); gc.DrawRect( aRect ); } // --------------------------------------------------------------------------- // CBCTestListContainer::CountComponentControls // --------------------------------------------------------------------------- // TInt CBCTestListContainer::CountComponentControls() const { if ( iControl ) { return 1; } else { return 0; } } // --------------------------------------------------------------------------- // CBCTestListContainer::ComponentControl // --------------------------------------------------------------------------- // CCoeControl* CBCTestListContainer::ComponentControl( TInt ) const { return iControl; } // --------------------------------------------------------------------------- // CBCTestListContainer::SetControl // --------------------------------------------------------------------------- // void CBCTestListContainer::SetControl( CCoeControl* aControl ) { iControl = aControl; if ( iControl ) { iControl->SetExtent( Rect().iTl, Rect().Size() ); iControl->ActivateL(); DrawNow(); } } // --------------------------------------------------------------------------- // CBCTestListContainer::ResetControl // --------------------------------------------------------------------------- // void CBCTestListContainer::ResetControl() { delete iControl; iControl = NULL; }
[ "none@none" ]
[ [ [ 1, 115 ] ] ]
413bd6da5935b3a893a0c803748298c4325edc00
57855d23617d6a65298c2ae3485ba611c51809eb
/Zen/test/Engine/src/SoundTests.cpp
bf550be95061f9e7b9612be4ace6ef428b022658
[]
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
22,870
cpp
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Zen Unit Tests // // Copyright (C) 2001 - 2010 Tony Richards // Copyright (C) 2008 - 2010 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 "Suite.hpp" #include "SoundTests.hpp" #include <Zen/Core/Math/Vector3.hpp> #include <Zen/Core/Plugins/I_PluginManager.hpp> #include <Zen/Engine/Sound/I_SoundManager.hpp> #include <Zen/Engine/Sound/I_SoundService.hpp> #include <Zen/Engine/Sound/I_SoundResource.hpp> #include <Zen/Engine/Sound/I_SoundSource.hpp> #include <Zen/Engine/Resource/I_ResourceManager.hpp> #include <Zen/Engine/Resource/I_ResourceService.hpp> #include <boost/filesystem.hpp> #include <conio.h> //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Zen { namespace UnitTests { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Register the suite CPPUNIT_TEST_SUITE_REGISTRATION(SoundTests); //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::setUp() { boost::filesystem::path configPath = boost::filesystem::system_complete ( boost::filesystem::path("Engine/SoundTests.xml", boost::filesystem::native) ).normalize(); m_pApp = Zen::Plugins::I_PluginManager::getSingleton() .installApplication(configPath); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::tearDown() { m_pApp.reset(); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testOpenALServiceLoad() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZOpenAL", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testOpenALResourceServiceLoad() { Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZOpenAL", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testOpenALResourceLoad() { Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZOpenAL", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "sirabhorn.ogg"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testOpenALSourceCreation() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZOpenAL", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZOpenAL", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "sirabhorn.ogg"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); Zen::Engine::Sound::I_SoundSource::pSoundSource_type pSound = pSoundService->createSource(pSoundResource); char input(' '); while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "Unit Test - SoundTests::testOpenALSourceCreation() : Is music playing through the sound card successfully? (Y/N) : "; std::cin.get(input); } pSound->stop(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound source is not playing through the sound card.", CPPUNIT_ASSERT(input == 'Y' || input == 'y') ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testOpenALSourceMotion() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZOpenAL", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZOpenAL", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "thunder.wav"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); Zen::Engine::Sound::I_SoundSource::pSoundSource_type pSound = pSoundService->createSource(pSoundResource,Zen::Math::Point3(100.0f,0.0f,0.0f)); char input(' '); while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "\n Unit Test - SoundTests::testOpenALSourceMotion() : Is thunder playing to your right? (Y/N) : "; std::cin.get(input); } pSound->setPosition(Zen::Math::Point3(-100.0f,0.0f,0.0f)); pSound->stop(); pSound->play(); input = ' '; while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "\n Unit Test - SoundTests::testOpenALSourceMotion() : Is thunder playing to your left? (Y/N) : "; std::cin.get(input); } pSound->stop(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound source is not moving.", CPPUNIT_ASSERT(input == 'Y' || input == 'y') ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testOpenALListenerMotion() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZOpenAL", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZOpenAL", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "thunder.wav"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); Zen::Engine::Sound::I_SoundSource::pSoundSource_type pSound = pSoundService->createSource(pSoundResource,Zen::Math::Point3(0.0f,0.0f,0.0f)); Math::Matrix4 yourLocation; yourLocation = pSoundService->getListenMatrix(); Math::Point3 pos; yourLocation.getPosition(pos); std::cout << "\n Position was:" << boost::int32_t(pos.m_x) << "," << boost::int32_t(pos.m_y) << "," << boost::int32_t(pos.m_z); pos = Math::Point3(100.0f,0.0f,0.0f); yourLocation.setPosition(pos); pSoundService->setListenMatrix(yourLocation); yourLocation.getPosition(pos); std::cout << "and is now" << boost::int32_t(pos.m_x) << "," << boost::int32_t(pos.m_y) << "," << boost::int32_t(pos.m_z); pSound->play(); pSound->setLooping(true); char input(' '); while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "\n Unit Test - SoundTests::testOpenALListenerMotion() : Is thunder playing to your right? (Y/N) : "; std::cin.get(input); } pos = Math::Point3(-100.0f,0.0f,0.0f); yourLocation.setPosition(pos); pSoundService->setListenMatrix(yourLocation); pSoundService->processEvents(0); input = ' '; while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "/n Unit Test - SoundTests::testOpenALListenerMotion() : Is thunder playing to your left? (Y/N) : "; std::cin.get(input); } pSound->stop(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZOpenAL Sound listener is not moving.", CPPUNIT_ASSERT(input == 'Y' || input == 'y') ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testFMODServiceLoad() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZFMOD", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testFMODResourceServiceLoad() { Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZFMOD", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testFMODResourceLoad() { Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZFMOD", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "sirabhorn.ogg"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testFMODSourceCreation() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZFMOD", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZFMOD", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "sirabhorn.ogg"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); Zen::Engine::Sound::I_SoundSource::pSoundSource_type pSound = pSoundService->createSource(pSoundResource); pSoundService->processEvents(0); char input(' '); while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "Unit Test - SoundTests::testFMODSourceCreation() : Is music playing through the sound card successfully? (Y/N) : "; std::cin.get(input); } pSound->stop(); pSoundService->processEvents(0); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound source is not playing through the sound card.", CPPUNIT_ASSERT(input == 'Y' || input == 'y') ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testFMODSourceMotion() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZFMOD", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZFMOD", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "thunder.wav"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); Zen::Engine::Sound::I_SoundSource::pSoundSource_type pSound = pSoundService->createSource(pSoundResource,Zen::Math::Point3(100.0f,0.0f,0.0f)); char input(' '); while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "\n Unit Test - SoundTests::testFMODSourceMotion() : Is thunder playing to your right? (Y/N) : "; std::cin.get(input); } pSound->setPosition(Zen::Math::Point3(-100.0f,0.0f,0.0f)); pSound->stop(); pSound->play(); pSoundService->processEvents(0); input = ' '; while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "\n Unit Test - SoundTests::testFMODSourceMotion() : Is thunder playing to your left? (Y/N) : "; std::cin.get(input); } pSound->stop(); pSoundService->processEvents(0); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound source is not moving.", CPPUNIT_ASSERT(input == 'Y' || input == 'y') ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void SoundTests::testFMODListenerMotion() { Zen::Engine::Sound::I_SoundManager::config_type soundConfig; Zen::Engine::Resource::I_ResourceManager::config_type resourceConfig; Zen::Engine::Sound::I_SoundManager::pService_type pSoundService = Zen::Engine::Sound::I_SoundManager::getSingleton() .create("ZFMOD", soundConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound service was not loaded.", CPPUNIT_ASSERT(pSoundService.isValid()) ); Zen::Engine::Resource::I_ResourceManager::pResourceService_type pResourceService = Zen::Engine::Resource::I_ResourceManager::getSingleton() .create("ZFMOD", resourceConfig); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource service was not loaded.", CPPUNIT_ASSERT(pResourceService.isValid()) ); pResourceService->addResourceLocation("Engine/resources/sound", "", "", true); resourceConfig["fileName"] = "thunder.wav"; typedef Zen::Memory::managed_ptr<Zen::Engine::Sound::I_SoundResource> pSoundResource_type; pSoundResource_type pSoundResource = pResourceService ->loadResource(resourceConfig) .as<pSoundResource_type>(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound resource was not loaded.", CPPUNIT_ASSERT(pSoundResource.isValid()) ); Zen::Engine::Sound::I_SoundSource::pSoundSource_type pSound = pSoundService->createSource(pSoundResource,Zen::Math::Point3(0.0f,0.0f,0.0f)); Math::Matrix4 yourLocation; yourLocation = pSoundService->getListenMatrix(); Math::Point3 pos; yourLocation.getPosition(pos); pos = Math::Point3(100.0f,0.0f,0.0f); yourLocation.setPosition(pos); pSoundService->setListenMatrix(yourLocation); yourLocation.getPosition(pos); pSound->play(); pSound->setLooping(true); pSoundService->processEvents(0); char input(' '); while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "\n Unit Test - SoundTests::testFMODListenerMotion() : Is thunder playing to your right? (Y/N) : "; std::cin.get(input); } pos = Math::Point3(-100.0f,0.0f,0.0f); yourLocation.setPosition(pos); pSoundService->setListenMatrix(yourLocation); pSoundService->processEvents(0); input = ' '; while(input != 'Y' && input != 'N' && input != 'y' && input != 'n') { std::cout << "/n Unit Test - SoundTests::testFMODListenerMotion() : Is thunder playing to your left? (Y/N) : "; std::cin.get(input); } pSound->stop(); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "ZFMOD Sound listener is not moving.", CPPUNIT_ASSERT(input == 'Y' || input == 'y') ); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace UnitTests } // namespace Zen //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
[ [ [ 1, 611 ] ] ]
54fbbad57436c4c77b586a40d03a767422075afc
842997c28ef03f8deb3422d0bb123c707732a252
/src/uslsext/USDataIOTask.cpp
79dc0cea42cbe1969161ada039ba1c1ab53f1acd
[]
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,437
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <uslsext/USDataIOTask.h> //================================================================// // USDataIOTask //================================================================// //----------------------------------------------------------------// void USDataIOTask::Execute () { if ( this->mState == LOADING ) { this->mData->Load ( this->mFilename ); } else if ( this->mState == SAVING ) { this->mData->Save ( this->mFilename ); } this->mState = IDLE; } //----------------------------------------------------------------// void USDataIOTask::LoadData ( cc8* filename, USData& target ) { if ( this->mState == IDLE ) { this->SetFilename ( filename ); this->SetData ( &target ); this->mState = LOADING; this->Start (); } } //----------------------------------------------------------------// void USDataIOTask::SaveData ( cc8* filename, USData& target ) { if ( this->mState == IDLE ) { this->SetFilename ( filename ); this->SetData ( &target ); this->mState = SAVING; this->Start (); } } //----------------------------------------------------------------// USDataIOTask::USDataIOTask () : mState ( IDLE ) { } //----------------------------------------------------------------// USDataIOTask::~USDataIOTask () { }
[ [ [ 1, 58 ] ] ]
e6b8b6c55708b5540f8ed62472af8efa4f1936e9
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qtoolbox.h
3fdcb0ae454347a99a9f29a30a78e39c7c3177e7
[ "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
5,599
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 QTOOLBOX_H #define QTOOLBOX_H #include <QtGui/qframe.h> #include <QtGui/qicon.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_TOOLBOX class QToolBoxPrivate; class Q_GUI_EXPORT QToolBox : public QFrame { Q_OBJECT Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged) Q_PROPERTY(int count READ count) public: explicit QToolBox(QWidget *parent = 0, Qt::WindowFlags f = 0); ~QToolBox(); int addItem(QWidget *widget, const QString &text); int addItem(QWidget *widget, const QIcon &icon, const QString &text); int insertItem(int index, QWidget *widget, const QString &text); int insertItem(int index, QWidget *widget, const QIcon &icon, const QString &text); void removeItem(int index); void setItemEnabled(int index, bool enabled); bool isItemEnabled(int index) const; void setItemText(int index, const QString &text); QString itemText(int index) const; void setItemIcon(int index, const QIcon &icon); QIcon itemIcon(int index) const; #ifndef QT_NO_TOOLTIP void setItemToolTip(int index, const QString &toolTip); QString itemToolTip(int index) const; #endif int currentIndex() const; QWidget *currentWidget() const; QWidget *widget(int index) const; int indexOf(QWidget *widget) const; int count() const; public Q_SLOTS: void setCurrentIndex(int index); void setCurrentWidget(QWidget *widget); Q_SIGNALS: void currentChanged(int index); protected: bool event(QEvent *e); virtual void itemInserted(int index); virtual void itemRemoved(int index); void showEvent(QShowEvent *e); void changeEvent(QEvent *); #ifdef QT3_SUPPORT public: QT3_SUPPORT_CONSTRUCTOR QToolBox(QWidget *parent, const char *name, Qt::WindowFlags f = 0); inline QT3_SUPPORT void setItemLabel(int index, const QString &text) { setItemText(index, text); } inline QT3_SUPPORT QString itemLabel(int index) const { return itemText(index); } inline QT3_SUPPORT QWidget *currentItem() const { return widget(currentIndex()); } inline QT3_SUPPORT void setCurrentItem(QWidget *item) { setCurrentIndex(indexOf(item)); } inline QT3_SUPPORT void setItemIconSet(int index, const QIcon &icon) { setItemIcon(index, icon); } inline QT3_SUPPORT QIcon itemIconSet(int index) const { return itemIcon(index); } inline QT3_SUPPORT int removeItem(QWidget *item) { int i = indexOf(item); removeItem(i); return i; } inline QT3_SUPPORT QWidget *item(int index) const { return widget(index); } QT3_SUPPORT void setMargin(int margin) { setContentsMargins(margin, margin, margin, margin); } QT3_SUPPORT int margin() const { int margin; int dummy; getContentsMargins(&margin, &dummy, &dummy, &dummy); return margin; } #endif private: Q_DECLARE_PRIVATE(QToolBox) Q_DISABLE_COPY(QToolBox) Q_PRIVATE_SLOT(d_func(), void _q_buttonClicked()) Q_PRIVATE_SLOT(d_func(), void _q_widgetDestroyed(QObject*)) }; inline int QToolBox::addItem(QWidget *item, const QString &text) { return insertItem(-1, item, QIcon(), text); } inline int QToolBox::addItem(QWidget *item, const QIcon &iconSet, const QString &text) { return insertItem(-1, item, iconSet, text); } inline int QToolBox::insertItem(int index, QWidget *item, const QString &text) { return insertItem(index, item, QIcon(), text); } #endif // QT_NO_TOOLBOX QT_END_NAMESPACE QT_END_HEADER #endif // QTOOLBOX_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 148 ] ] ]
d06669d5e681cd381d459c050b01044e79f9d1b6
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/System/Io/IStream/hkIStream.inl
2f994d9033bfbe451ec4268438967200a6243e8a
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,598
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ HK_FORCE_INLINE hkIstream& hkIstream::operator>> (signed char& c) { return (*this) >> reinterpret_cast<char&>(c); } HK_FORCE_INLINE hkIstream& hkIstream::operator>> (unsigned char& c) { return (*this) >> reinterpret_cast<char&>(c); } HK_FORCE_INLINE hkIstream& hkIstream::get( char& c ) { return (*this) >> c; } HK_FORCE_INLINE hkStreamReader* hkIstream::getStreamReader() { return m_streamReader; } /* * 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, 43 ] ] ]
40ae49e695ccb640fcb39657af27438712ef90a7
24c456d31966a458a32eb61bc9425a5b66caeaaa
/script.cpp
90a0c2dc158fae4536b1ba528b1e2290a734671f
[]
no_license
tjssmy/Cuviewer-2.0
577852960a58addb3cd38bbd0f7101334b83f0d2
bc11760c2010e9b2cbe59697e9ed6e0d43d3fbd2
refs/heads/master
2021-01-10T18:27:34.483338
2011-11-28T14:22:58
2011-11-28T14:22:58
2,772,012
0
1
null
null
null
null
UTF-8
C++
false
false
13,145
cpp
/** script.cpp * Carleton University Department of Electronics * Copyright (C) 2001 Bryan Wan and Cliff Dugal */ #include <qapplication.h> #include <QPixmap> #include <QDir> #include <QFile> #include <QTextStream> #include <QMessageBox> #include <QVariant> #include <qgl.h> #include "include/cuvcommonstructs.h" #include "script.h" #include "viewdata.h" /** Constructor initilize Script @param: g The number of gradations to generate @param: type The bin pattern to produce */ Script::Script(QFile * file,CUViewDoc * cvd) { scriptfile = file; cuviewDoc = cvd; allowLoad = true; } Script::~Script() { } void Script::setFileLoad(bool allow) { allowLoad = allow; } QStringList Script::getFilenameList() { return filenamelist; } void Script::setFilenameList(QStringList filelist) { filenamelist = filelist; } /** @brief Writes the script to a file The writeScript method writes all settings related to the cuviewDoc to a file given by scriptfile. The settings written to the file are listed below in the order which it was written: - Camera position - Camera aim - Camera up - Outline colour - Outline mode - Twosided mode - Antialias mode - Perspective mode - Smooth shading mode - Transparency mode - Gamma mode - Wireframe mode - Opaque wireframe mode - Ambient lighting - Diffuse lighting - */ void Script::writeScript() { //write everything to scriptfile QString filename = scriptfile->fileName(); scriptfile->remove(); scriptfile->setFileName(filename); qDebug( "writing script file: %s", qPrintable(scriptfile->fileName())); if(scriptfile->open(QIODevice::ReadWrite)){ GLfloat* toFill = new GLfloat[3]; QTextStream ts(scriptfile); ts << QString("script data for cuviewer, do not edit.\n"); cuviewDoc->cameraPos(toFill); ts << QString("camera_position_xyz %1 %2 %3\n") .arg((float)toFill[0]).arg((float)toFill[1]).arg((float)toFill[2]); cuviewDoc->cameraAim(toFill); ts << QString("camera_aim_xyz %1 %2 %3\n") .arg((float)toFill[0]).arg((float)toFill[1]).arg((float)toFill[2]); cuviewDoc->cameraUp(toFill); ts << QString("camera_up_xyz %1 %2 %3\n") .arg((float)toFill[0]).arg((float)toFill[1]).arg((float)toFill[2]); cuviewDoc->outlineColor(toFill); ts << QString("outlinecolor_rbg %1 %2 %3\n") .arg((float)toFill[0]).arg((float)toFill[1]).arg((float)toFill[2]); ts << QString("outline %1\n").arg((int)cuviewDoc->outline()); ts << QString("twosided %1\n").arg((int)cuviewDoc->twoSided()); ts << QString("aa %1\n").arg((int)cuviewDoc->antialias()); ts << QString("view %1\n").arg((int)cuviewDoc->perspective()); ts << QString("smoothshaded %1\n").arg((int)cuviewDoc->smoothShaded()); ts << QString("transparency %1\n").arg((int)cuviewDoc->transparency()); // ts << QString("fog %1\n").arg((int)cuviewDoc->fog()); ts << QString("gamma %1\n").arg((int)cuviewDoc->gamma()); ts << QString("wireframe %1\n").arg((int)cuviewDoc->wireframe()); ts << QString("opaquewf %1\n").arg((int)cuviewDoc->opaqueWireframe()); ts << QString("lighting %1\n").arg((int)cuviewDoc->lighting()); ts << QString("diffuse %1\n").arg((int)cuviewDoc->light()); ts << QString("binWindow %1\n").arg((int)cuviewDoc->binWindow()); ts << QString("linewidth %1\n").arg((int)cuviewDoc->lineWidth()); ts << QString("spheretess %1\n").arg((int)cuviewDoc->sphereTess()); ts << QString("clipping %1\n").arg((double)cuviewDoc->clipPerspNear()); ts << QString("fov %1\n").arg((float)cuviewDoc->fov()); ts << QString("ambientv %1\n").arg((float)cuviewDoc->ambient()); ts << QString("diffusev %1\n").arg((float)cuviewDoc->diffuse()); ts << QString("background %1\n").arg((float)cuviewDoc->background()); ts << QString("gammav %1\n").arg((float)cuviewDoc->gammaLevel()); ts << QString("binwindowindex %1\n").arg((int)cuviewDoc->binWindowIndex()); ts << "loadfilelist " << QString::number(filenamelist.count()) << "\n"; for ( QStringList::Iterator it = filenamelist.begin(); it != filenamelist.end(); ++it ) { ts << *it << "\n"; } int translateCount=0,scaleCount=0,rotateCount=0 ,tileCount=0; for(int i=0;i<cuviewDoc->scenes();i++){ if(cuviewDoc->hasTiles(i)) ++tileCount; if(cuviewDoc->hasTranslated(i)) ++translateCount; if(cuviewDoc->hasScaled(i)) ++scaleCount; if(cuviewDoc->hasRotated(i)) ++rotateCount; } int toFilli[3]; ts << QString("tile_count_index_xyz %1 ").arg(tileCount); for(int i=0;i<cuviewDoc->scenes();i++) if(cuviewDoc->hasTiles(i)){ cuviewDoc->getTiles(i,toFilli,toFill); ts << QString("%1 %2 %3 %4 %5 %6 %7 ").arg((int)i) .arg(toFilli[0]).arg(toFilli[1]).arg(toFilli[2]) .arg(toFill[0]).arg(toFill[1]).arg(toFill[2]); } ts << "\n"; ts << QString("translate_count_index_xyz %1 ").arg(translateCount); for(int i=0;i<cuviewDoc->scenes();i++) if(cuviewDoc->hasTranslated(i)){ cuviewDoc->getTranslatef(i,toFill); ts << QString("%1 %2 %3 %4 ").arg((int)i) .arg(toFill[0]).arg(toFill[1]).arg(toFill[2]); } ts << "\n"; ts << QString("scale_count_index_xyz %1 ").arg(scaleCount); for(int i=0;i<cuviewDoc->scenes();i++) if(cuviewDoc->hasScaled(i)){ cuviewDoc->getScalef(i,toFill); ts << QString("%1 %2 %3 %4 ").arg((int)i) .arg(toFill[0]).arg(toFill[1]).arg(toFill[2]); } ts << "\n"; ts << QString("rotate_count_index_xyz %1 ").arg(rotateCount); for(int i=0;i<cuviewDoc->scenes();i++) if(cuviewDoc->hasRotated(i)){ cuviewDoc->getRotatef(i,toFill); ts << QString("%1 %2 %3 %4 ").arg((int)i) .arg(toFill[0]).arg(toFill[1]).arg(toFill[2]); } ts << "\n"; ts << QString("scene_count_visibility %1 ") .arg((int)cuviewDoc->scenes()); for(int i=0;i<cuviewDoc->scenes();i++){ ts << " " << QString::number((int)cuviewDoc->isVisible(i)); } ts << "\n"; ts << QString("light_sources %1 ") .arg((int)cuviewDoc->getLightSources()); for(int i=0;i<cuviewDoc->getLightSources();i++){ cuviewDoc->getTranslateLight(i,toFill); ts << QString(" %1 %2 %3 %4 ").arg(cuviewDoc->specular()) .arg(toFill[0]).arg(toFill[1]).arg(toFill[2]-1); } ts << "\n"; ts << QString("window_size %1 %2") .arg((int) ((QWidget*)cuviewDoc->parent())->width()) .arg((int) ((QWidget*)cuviewDoc->parent())->height()); ts << "\n"; delete toFill; } } /** @brief Reads a script The readScript method reads a script file that was generated from the writeScript method. */ void Script::readScript() { //Load script file if(scriptfile->exists()){ if(scriptfile->open(QIODevice::ReadOnly)){ QTextStream ts(scriptfile); GLfloat* toFill = new GLfloat[3], *toFill2 = new GLfloat[3]; QString pad; double value,value1,value2; ts.readLine(); if(ts.atEnd()){ qDebug("Error: Script file reached end too soon"); return; } //Read all cuviewDoc settings. ts >> pad >> toFill[0] >> toFill[1] >> toFill[2]; cuviewDoc->cameraTranslate(toFill,true); ts >> pad >> toFill[0] >> toFill[1] >> toFill[2]; ts >> pad >> toFill2[0] >> toFill2[1] >> toFill2[2]; cuviewDoc->setCameraAimAndUp(toFill,toFill2); ts >> pad >> toFill[0] >> toFill[1] >> toFill[2]; cuviewDoc->setOutlineColor(toFill); ts >> pad >> value; cuviewDoc->setOutline((bool)value); ts >> pad >> value; cuviewDoc->setTwoSided((bool)value); ts >> pad >> value; cuviewDoc->setAntialias((bool)value); ts >> pad >> value; cuviewDoc->setPerspective((bool)value); ts >> pad >> value; cuviewDoc->setSmoothShaded((bool)value); ts >> pad >> value; cuviewDoc->setTransparency((bool)value); // ts >> pad >> value.asInt(); // cuviewDoc->setFog(value.toBool()); ts >> pad >> value; cuviewDoc->setGamma((bool)value); ts >> pad >> value; cuviewDoc->setWireframe((bool)value); ts >> pad >> value; cuviewDoc->setOpaqueWireframe((bool)value); ts >> pad >> value; cuviewDoc->setLighting((bool)value); ts >> pad >> value; cuviewDoc->setLight((bool)value); ts >> pad >> value; cuviewDoc->setBinWindow((bool)value); ts >> pad >> value; cuviewDoc->setLineWidth((int)value); ts >> pad >> value; cuviewDoc->setSphereTess((unsigned char)value); ts >> pad >> value; cuviewDoc->setClipPerspNear(value); cuviewDoc->setClipOrthoNear(value/5.0); ts >> pad >> value; cuviewDoc->setFov(value); ts >> pad >> value; cuviewDoc->setAmbient(value); ts >> pad >> value; cuviewDoc->setDiffuse(value); ts >> pad >> value; cuviewDoc->setBackground(value); ts >> pad >> value; cuviewDoc->setGammaLevel(value); ts >> pad >> value; cuviewDoc->setBinWindowIndex((unsigned char)value); if(!cuviewDoc->binWindowColors((unsigned char)value)){ qDebug("Invalid bin palette index"); } int count=0, scene=0; bool oldscriptformat=true; ts >> pad; // loadfilelist if (pad=="loadfilelist"){ oldscriptformat=false; ts >> count; QString temp; temp = ts.readLine(); if(!count) return; for(int i=0;i<count;i++){ temp = ts.readLine(); if (allowLoad) filenamelist += temp; } count=0; //reset count } int toFilli[3]; //read tiles cuviewDoc->setEditMode(true); if (!oldscriptformat){ ts >> pad; } ts >> count; for(int i=0;i<count;i++){ ts >> scene >> toFilli[0] >> toFilli[1] >> toFilli[2]; ts >> value >> value1 >> value2; toFill[0] = value; toFill[1] = value1; toFill[2] = value2; cuviewDoc->setSceneEditing(scene,true); cuviewDoc->tileScenes(scene,toFilli[0],toFilli[1],toFilli[2], toFill[0],toFill[1],toFill[2],false); cuviewDoc->setSceneEditing(scene,false); } //read translated scenes ts >> pad >> count; for(int i=0;i<count;i++){ ts >> scene >> value >> value1 >> value2; toFill[0] = value; toFill[1] = value1; toFill[2] = value2; cuviewDoc->setSceneEditing(scene,true); cuviewDoc->translateScene(scene,toFill[0],toFill[1],toFill[2]); cuviewDoc->setSceneEditing(scene,false); } //read scaled scenes ts >> pad >> count; for(int i=0;i<count;i++){ ts >> scene >> value >> value1 >> value2; toFill[0] = value; toFill[1] = value1; toFill[2] = value2; cuviewDoc->setSceneEditing(scene,true); cuviewDoc->scaleScene(scene,toFill[0],toFill[1],toFill[2]); cuviewDoc->setSceneEditing(scene,false); } //read rotated scenes ts >> pad >> count; for(int i=0;i<count;i++){ ts >> scene >> value >> value1 >> value2; toFill[0] = value; toFill[1] = value1; toFill[2] = value2; cuviewDoc->setSceneEditing(scene,true); cuviewDoc->rotateScene(scene,toFill[0],toFill[1],toFill[2]); cuviewDoc->setSceneEditing(scene,false); } //read scene visibility ts >> pad >> value; int scenes = (int)value; for(int i=0;i<scenes;i++){ ts >> value; cuviewDoc->setSceneVisible(i,(bool)value); } //read lightsources num specular_shine position[3] bool editing; ts >> pad >> value; int lightsources = (int)value; for(int i=0;i<lightsources;i++){ ts >> value; cuviewDoc->setSpecular(value); ts >> value >> value1 >> value2; toFill[0] = value; toFill[1] = value1; toFill[2] = value2; editing = cuviewDoc->getEditLightMode(i); cuviewDoc->setEditLightMode(i,true); cuviewDoc->translateLight(i,toFill[0],toFill[1],toFill[2]); cuviewDoc->setEditLightMode(i,editing); } cuviewDoc->setEditMode(false); ts >> pad >> value; int width = (int)value; ts >> value; int height = (int)value; ((QWidget*)cuviewDoc->parent())->resize(width,height); ts.setDevice(0); scriptfile->close(); delete toFill; delete toFill2; } else qDebug( "Can't open script file. Check file permissions"); } }
[ [ [ 1, 25 ], [ 29, 46 ], [ 48, 52 ], [ 55, 77 ], [ 79, 80 ], [ 84, 84 ], [ 182, 185 ], [ 204, 220 ], [ 223, 224 ], [ 226, 228 ], [ 230, 232 ], [ 234, 247 ], [ 250, 297 ], [ 299, 302 ], [ 304, 386 ], [ 389, 396 ] ], [ [ 26, 28 ], [ 47, 47 ], [ 53, 54 ], [ 78, 78 ], [ 81, 83 ], [ 85, 181 ], [ 186, 203 ], [ 221, 222 ], [ 225, 225 ], [ 229, 229 ], [ 233, 233 ], [ 248, 249 ], [ 298, 298 ], [ 303, 303 ], [ 387, 388 ] ] ]
489e1652897964050cb065844d36b406e2226e24
6d25f0b33ccaadd65b35f77c442b80097a2fce8e
/gbt/cart.h
e2f46f60fb16293b5c616b62bbda556d777b8107
[]
no_license
zhongyunuestc/felix-academic-project
8b282d3a783aa48a6b56ff6ca73dc967f13fd6cf
cc71c44fba50a5936b79f7d75b5112d247af17fe
refs/heads/master
2021-01-24T10:28:38.604955
2010-03-20T08:33:59
2010-03-20T08:33:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,635
h
#ifndef __GBTREE__CART #define __GBTREE__CART #include <iostream> #include <cstdlib> #include <vector> #include <algorithm> #include <ext/hash_set> #include <ext/hash_map> #include <functional> #include "common.h" #include "tree.h" struct CartParam { int nLeafNodes; int minNode; int maxDepth; double sample; double splitRate; CartParam() : nLeafNodes(20), minNode(50), maxDepth(9), sample(0.4), splitRate(0.1) {} friend std::ostream& operator<<(std::ostream &f, const CartParam &v); }; inline std::ostream& operator<<(std::ostream &f, const CartParam &c) { return f << "nLeafNodes = " << c.nLeafNodes << "\nminNode = " << c.minNode << "\nmaxDepth = " << c.maxDepth << "\nsample = " << c.sample << "\nsplitRate = " << c.splitRate << std::endl; } struct MartParam { int debugLevel; int nIters; double learningRate; double samplePrec; CartParam cartParam; MartParam() : debugLevel(0), nIters(400), learningRate(0.01), samplePrec(0.4) {} }; typedef std::vector<Node*> TreeVec; struct MartModel { double learningRate; TreeVec treeVec; }; struct NodeSplit { int begin, end, bound; double improve; }; struct Buffer { char* buf; size_t size; Buffer(size_t s=0) : size(s) { if(size!=0) buf = new char[size]; else buf = NULL; } ~Buffer() { if(buf!=NULL) delete[] buf; } void resize(size_t newsize) { if(buf!=NULL) delete[] buf; size = newsize; if(newsize!=0) buf = new char[newsize]; else buf = NULL; } template <typename T> T* get() { return (T*)buf; } }; //Node* fit_cart(int data_num, int dim_num, const double* data, const double* target, // const CartParam& cart_param, double* fit_target=NULL); // w[i] should be positive //Node* fit_cart(const DataSet& dataset, const double* w, const double* target, const CartParam& cart_param, double *fit_target=NULL, int** buf=NULL); Node* fit_cart(const FVectors& x, int nDims, const doubles_t& w, const doubles_t& target, const CartParam& cart_param, doubles_t& fit_target, int** buf=NULL); /* inline Node* fit_cart(const FVectors& x, int nDims, const doubles_t& w, const doubles_t& target, const CartParam& cart_param, double *fit_target=NULL, int** buf=NULL) { DataSet d; d.data_num = x.size(); d.dim_num = nDims; d.feature = new double*[d.data_num]; for(int i=0;i<d.data_num;i++) { d.feature[i] = new double[nDims]; assert(x[i].size()<=nDims); std::fill(d.feature[i], d.feature[i]+nDims, 0); for(int j=0;j<x[i].size();j++) { d.feature[i][j] = x[i][j]; } } double *_w = new double[d.data_num], *_target = new double[d.data_num]; std::copy(w.begin(), w.end(), _w); std::copy(target.begin(), target.end(), _target); Node* root = fit_cart(d, _w, _target, cart_param, fit_target, buf); delete[] _w; delete[] _target; for(int i=0;i<d.data_num;i++) { delete[] d.feature[i]; } delete[] d.feature; return root; } */ typedef __gnu_cxx::hash_map<int, int> int2int_t; struct FeatureIndex { FeatureIndex(size_t aDatas = 0, int aDims = 0) : nDatas(aDatas), nDims(aDims) { if(nDatas!=0) ind = new int[aDatas*aDims]; else ind = NULL; } ~FeatureIndex() { if(ind!=NULL) delete[] ind; } int* getDim(int d) { return ind+d*nDatas; } const int* getDim(int d) const { return ind+d*nDatas; } FeatureIndex* getSample(const ints_t& sampleList) const; size_t nDatas; int nDims; int* ind; }; template <typename VecType> FeatureIndex* buildFeatureIndex(const std::vector<VecType>& x, int nd); template <typename VecType> struct FeatureComp : public std::binary_function<int, int, bool> { int fid; const std::vector<VecType>& feature; FeatureComp(int feature_id, const std::vector<VecType>& f) : fid(feature_id), feature(f) {} bool operator()(const int& a, const int& b) const { return feature[a][fid]<feature[b][fid]; } }; template <typename VecType1, typename VecType2, typename VecType3, typename VecType4> class Cart { public: typedef std::vector<VecType1> Features; Cart(const CartParam& param) : cartParam(param) {} CartParam cartParam; Node* fit(const Features& x, int nd, const VecType2& w, const VecType3& target, VecType4& fit_target, FeatureIndex& buf); private: void splitNode(const Features& feature, const VecType3& y, const VecType2& weight, int begin, int end, Node& node, NodeSplit& split); int nDatas, nDims, nFeatures; ints_t find; int *pind; }; #include <cart_imp.h> #endif
[ "Felix.Guozq@fe1a0076-fbb2-11de-b7cb-b1160b2c2156" ]
[ [ [ 1, 163 ] ] ]
788eae22d7dc094fccfb528d55fcc7b6c12fd3f1
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/AppProts/exampleclient/httpexampleutils.cpp
73690536dfdfbde740b29088fdef942c50a692b7
[]
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
5,270
cpp
// HTTPEXAMPLEUTILS.CPP // // Copyright (c) 2001 Symbian Ltd. All rights reserved. // // for StartC32() #include <c32comm.h> #include "httpexampleutils.h" // PDD names for the physical device drivers that are loaded in wins or arm #if defined (__WINS__) #define PDD_NAME _L("ECDRV") #else #define PDD_NAME _L("EUART1") #define PDD2_NAME _L("EUART2") #define PDD3_NAME _L("EUART3") #define PDD4_NAME _L("EUART4") #endif #define LDD_NAME _L("ECOMM") const TInt KMaxUserEntrySize = 128; void CHttpExampleUtils::InitCommsL() { TInt ret = User::LoadPhysicalDevice(PDD_NAME); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); #ifndef __WINS__ ret = User::LoadPhysicalDevice(PDD2_NAME); ret = User::LoadPhysicalDevice(PDD3_NAME); ret = User::LoadPhysicalDevice(PDD4_NAME); #endif ret = User::LoadLogicalDevice(LDD_NAME); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); ret = StartC32(); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); } CHttpExampleUtils* CHttpExampleUtils::NewL(const TDesC& aTestName) { CHttpExampleUtils* me = new (ELeave) CHttpExampleUtils(aTestName); return me; } CHttpExampleUtils::CHttpExampleUtils(const TDesC& aTestName) : iTest(aTestName) { iTest.Start(KNullDesC); } CHttpExampleUtils::~CHttpExampleUtils() { iTest.End(); iTest.Close(); } RTest& CHttpExampleUtils::Test() { return iTest; } void CHttpExampleUtils::PressAnyKey() { iTest.Printf(TRefByValue<const TDesC>_L("\nPress a key")); iTest.Getch(); } TInt CHttpExampleUtils::GetSelection(const TDesC& aPrompt, const TDesC& aValidChoices) // // Present the user with a list of options, and get their selection { TKeyCode key = EKeyNull; iTest.Console()->SetPos (0, iTest.Console()->WhereY ()); iTest.Console()->Printf(_L("%S "), &aPrompt); iTest.Console()->Printf(_L("[%S] :"), &aValidChoices); TInt retVal = KErrNotFound; while (retVal == KErrNotFound) { key = iTest.Getch(); // Check that key is in the list of valid choices retVal = aValidChoices.Locate((TChar)key); } iTest.Console()->Printf(_L("%c\n\n"), key); return retVal; } void CHttpExampleUtils::LogIt(TRefByValue<const TDesC> aFmt, ...) { VA_LIST list; VA_START(list,aFmt); TBuf<KMaxFileName + 4> buf; // 4 for the log prompt buf.Zero(); buf.Append(_L("> ")); buf.AppendFormatList(aFmt,list); VA_END(list); iTest.Printf(_L("%S\n"), &buf); } void CHttpExampleUtils::GetAnEntry(const TDesC& ourPrompt, TDes& currentstring) { TBuf16<KMaxUserEntrySize> ourLine; TBuf<KMaxUserEntrySize> tempstring; //tempstring is a unicode descriptor //create a temporary buffer where the //unicode strings are stored in order to //be displayed ourLine.Zero (); tempstring.Copy(currentstring); //Copy current string to Unicode buffer TKeyCode key = EKeyNull; //current string buffer is 8 bits wide. //Unicode string bufffer (tempstring) is 16 bits wide. FOREVER { if (ourLine.Length () == 0) { iTest.Console()->SetPos (0, iTest.Console()->WhereY ()); iTest.Console()->Printf (_L ("%S"), &ourPrompt); if (tempstring.Length () != 0) //get tempstring's number of items iTest.Console()->Printf (_L (" = %S"), &tempstring); //if not zero print them to iTest.Console() iTest.Console()->Printf (_L (" : ")); iTest.Console()->ClearToEndOfLine (); } key = iTest.Getch(); if (key == EKeyBackspace) { if (ourLine.Length() !=0) { ourLine.SetLength(ourLine.Length()-1); iTest.Console()->Printf (_L ("%c"), key); iTest.Console()->SetPos(iTest.Console()->WhereX(),iTest.Console()->WhereY()); iTest.Console()->ClearToEndOfLine(); } // end if (ourLine.Length() !=0) } // end if (key == KeyBackSpace) if (key == EKeyDelete) { ourLine.Zero(); iTest.Console()->SetPos (0, iTest.Console()->WhereY ()); iTest.Console()->ClearToEndOfLine (); tempstring.Copy(ourLine); break; } if (key == EKeyEnter) break; if (key < ' ') // ascii code thats not a printable character { continue; } ourLine.Append (key); iTest.Console()->Printf (_L ("%c"), key); iTest.Console()->SetPos(iTest.Console()->WhereX(),iTest.Console()->WhereY()); iTest.Console()->ClearToEndOfLine(); if (ourLine.Length () == ourLine.MaxLength ()) break; } // end of for statement if ((key == EKeyEnter) && (ourLine.Length () == 0)) tempstring.Copy (currentstring); //copy contents of 8 bit "ourLine" descriptor iTest.Console()->SetPos (0, iTest.Console()->WhereY ()); iTest.Console()->ClearToEndOfLine (); if ((key == EKeyEnter) && (ourLine.Length() !=0)) tempstring.Copy(ourLine); if (tempstring.Length () != 0) //if temstring length is not zero { iTest.Console()->Printf (_L (" Entered = %S\n"), &tempstring); //print the contents to iTest.Console() LogIt(_L ("%S = %S\n"), &ourPrompt, &tempstring); } iTest.Console()->Printf (_L ("\n")); currentstring.Copy(tempstring); //copy 16 bit tempstring descriptor back }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 186 ] ] ]
60b65b2419c06fc8a04dc58ec221c14af796de77
c7f1dcc066955e698ab5a42acf1ed50680bf4d0b
/samples/ThisThunk/MainDlg.cpp
9934150eccc6e6231d536df9c943016fa48d646b
[]
no_license
wjcsharp/pdl-titilima
8618082d734e5c1d051b2fab5e975ab15e8bbdd8
2bb4f618b00d2d57b509a64d792eff7d1208d380
refs/heads/master
2020-04-20T16:20:11.236062
2010-11-25T10:17:01
2010-11-25T10:17:01
32,128,071
0
1
null
null
null
null
UTF-8
C++
false
false
1,272
cpp
#include "MainDlg.h" #include "resource.h" CMainDlg::CMainDlg(void) : LDialog(IDD_DLG_MAIN) { m_thunk.CreateThunk(this, &CMainDlg::ThreadProc); } CMainDlg::~CMainDlg(void) { m_thunk.DestroyThunk(); } PDL_BEGIN_MSGMAP(CMainDlg) PROCESS_CLOSE(OnClose) PROCESS_COMMAND(OnCommand) PROCESS_INITDIALOG(OnInitDialog) PDL_END_MSGMAP(LDialog) void CMainDlg::OnClose(BOOL& bHandled) { EndDialog(0); } void CMainDlg::OnCommand( WORD wNotifyCode, WORD wID, HWND hWndCtrl, BOOL& bHandled) { switch (wID) { case IDC_BTN_START: { HANDLE hThread = ::CreateThread(NULL, 0, m_thunk, NULL, 0, NULL); ::CloseHandle(hThread); } break; case IDOK: { EndDialog(0); } break; default: bHandled = FALSE; } } BOOL CMainDlg::OnInitDialog(HWND hCtrlFocus, LPARAM lParam, BOOL& bHandled) { m_pb = GetDlgItem(IDC_PROGRESS); m_pb.SetRange32(0, 10); m_pb.SetStep(1); return FALSE; } DWORD WINAPI CMainDlg::ThreadProc(PVOID param) { m_pb.SetPos(0); for (int i = 0; i < 10; ++i) { m_pb.StepIt(); ::Sleep(1000); } return 0; }
[ "titilima@89554c5a-91f9-11de-87e2-8d177609176d" ]
[ [ [ 1, 67 ] ] ]
25710f2b6c77c3b09a11ad58f1c031e5fbfbf4d8
00c36cc82b03bbf1af30606706891373d01b8dca
/OpenGUI/OpenGUI_WidgetManager.h
4ad5b0c920d787827c6cc68d225fd69a305082c7
[ "BSD-3-Clause" ]
permissive
VB6Hobbyst7/opengui
8fb84206b419399153e03223e59625757180702f
640be732a25129a1709873bd528866787476fa1a
refs/heads/master
2021-12-24T01:29:10.296596
2007-01-22T08:00:22
2007-01-22T08:00:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,970
h
// OpenGUI (http://opengui.sourceforge.net) // This source code is released under the BSD License // See LICENSE.TXT for details #ifndef DCA429BB_8BCE_4042_A4DA_558D1A0AAE00 #define DCA429BB_8BCE_4042_A4DA_558D1A0AAE00 #include "OpenGUI_PreRequisites.h" #include "OpenGUI_Exports.h" #include "OpenGUI_String.h" #include "OpenGUI_Singleton.h" #include "OpenGUI_Value.h" #include "OpenGUI_XML.h" namespace OpenGUI { class System; // forward declaration class Widget; // forward declaration class ScreenManager; // forward declaration class WidgetCollection; // forward declaration //! Widget factory callback declaration/template typedef Widget* WidgetFactoryCallback(); //! Provides Widget registration and definition functionality class OPENGUI_API WidgetManager : public Singleton<WidgetManager> { friend class System; //so System can create and destroy us friend class ScreenManager; // need access via ScreenManager::_Screen_XMLNode_Load() WidgetManager(); // private constructor ~WidgetManager(); // private destructor public: //Reimplementation required for this style of singleton implementation to work across DLLs //! Retrieve the current singleton, if one exists. If none exists, this will cause an error. static WidgetManager& getSingleton( void ); //Reimplementation required for this style of singleton implementation to work across DLLs //! Retrieve a pointer to the current singleton, if one exists. If none exists, this will return 0. static WidgetManager* getSingletonPtr( void ); //! Create a Widget that was registered under the given \c Name and optionally \c Library Widget* CreateRawWidget( const String& Name, const String& Library = "" ); //! Creates and initializes a Widget that was previously defined by DefineWidget() Widget* CreateDefinedWidget( const String& Name ); //! Defines a new Widget under the given \c Name with the given \c propertyList, using \c BaseName and \c BaseLibrary as the source void DefineWidget( const String& Name, const ValueList& propertyList, const String& BaseName, const String& BaseLibrary ); //! Undefines an existing Widget definition by \c Name void UndefineWidget( const String& Name ); //! Register a Widget factory void RegisterWidgetFactory( const String& Name, const String& Library, WidgetFactoryCallback* factoryCallback ); //! Unregister a Widget factory void UnregisterWidgetFactory( const String& Name, const String& Library ); //! inner type of WidgetRegPairList typedef std::pair<String, String> WidgetRegPair; //! return type of GetRegisteredWidgets() typedef std::list<WidgetRegPair> WidgetRegPairList; //! returns a pair list of all registered widgets WidgetRegPairList GetRegisteredWidgets(); //! return type of GetDefinedWidgets() typedef std::list<String> WidgetDefList; //! returns a list of all defined widgets WidgetDefList GetDefinedWidgets(); //! returns the number of registered widgets across the number of libraries, as well as the number of widget definitions void getStats( size_t& RegWidgets, size_t& RegLibs, size_t& DefWidgets ); private: typedef std::map<String, WidgetFactoryCallback*> WidgetFactoryMap; typedef std::map<String, WidgetFactoryMap> LibraryMap; LibraryMap mLibraryMap; struct WidgetDefinition { String Name; String Library; ValueList Properties; }; typedef std::map<String, WidgetDefinition> WidgetDefinitionMap; WidgetDefinitionMap mWidgetDefinitionMap; // XML tag handlers for <WidgetDef> tags static bool _WidgetDef_XMLNode_Load( const XMLNode& node, const String& nodePath ); static bool _WidgetDef_XMLNode_Unload( const XMLNode& node, const String& nodePath ); static void _Widget_XMLNode_IntoContainer( const XMLNode& widgetNode, WidgetCollection& widgetContainer ); }; }//namespace OpenGUI{ #endif // DCA429BB_8BCE_4042_A4DA_558D1A0AAE00
[ "zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59" ]
[ [ [ 1, 90 ] ] ]
a7a289aec5e9ad0b225d3d4f3d79245d66c8c15c
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/CppUnit/include/cppunit/basic.h
9044ea28a75cd534b4a67bbd77e4ca3d8ff11282
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
GB18030
C++
false
false
9,934
h
/* ------------------------------------------------------------------------- // 文件名 : cppunit/basic.h // 创建者 : 许式伟 // 创建时间 : 2003-11-8 0:45:03 // 功能描述 : // // $Id: basic.h,v 1.24 2007/05/22 07:35:08 xuehua Exp $ // -----------------------------------------------------------------------*/ #ifndef __CPPUNIT_BASIC_H__ #define __CPPUNIT_BASIC_H__ // ------------------------------------------------------------------------- #ifndef __CPPUNIT_PLATAPI_H__ #include "platapi.h" #endif #if !defined(W2A) #include <atlbase.h> #endif #ifndef _STRING_ #include <string> #endif #ifndef _INC_CRTDBG #include <crtdbg.h> #endif // ------------------------------------------------------------------------- // class TestCase class TestCase : public TestFixture { }; // ------------------------------------------------------------------------- // _CppUnit_GetModuleHandleEx inline HMODULE _CppUnit_GetModuleHandleEx(LPCVOID lpAddress) { MEMORY_BASIC_INFORMATION mInfo; VirtualQuery(lpAddress, &mInfo, sizeof(mInfo)); return (HMODULE)mInfo.AllocationBase; } // ------------------------------------------------------------------------- // _CppUnit_GetModuleName inline VOID _DummyFunction() {} inline LPCWSTR _CppUnit_GetModuleName() { static WCHAR szModule[_MAX_PATH]; static int cch = GetModuleFileNameW( _CppUnit_GetModuleHandleEx((void*)_DummyFunction), szModule, _MAX_PATH); return szModule; } // ------------------------------------------------------------------------- // _CppUnit_Abort #if defined(_DEBUG) #define _CppUnit_Abort() _ASSERTE(!"CppUnit Error: Program abort!!!") #else #define _CppUnit_Abort() _CppUnit_TestRunnerError("CppUnit Error: Program abort!!!") #endif // ========================================================================= // // TestApp app(rununitConsole); // app.AddUnit(szDllName); // // ------------------------------------------------------------------------- // class TestApp class TestApp { private: LPCSTR m_name; public: TestApp(EnumRunUnitType runtype = rununitNone, LPCSTR name = NULL) { m_name = name; _CppUnit_Initialize(runtype); _CppUnit_FilterCase(_CppUnit_GetModuleName(), NULL, NULL); } ~TestApp() { try { _CppUnit_RunTests_ByName(__argc, __wargv, m_name); } catch (...) { _CppUnit_Abort(); } _CppUnit_Terminate(); } static HRESULT AddUnit(LPCSTR szDll) { return LoadLibraryA(szDll) ? S_OK : E_ACCESSDENIED; } static HRESULT AddUnit(LPCWSTR szDll) { USES_CONVERSION; return LoadLibraryA(W2A(szDll)) ? S_OK : E_ACCESSDENIED; } }; // ========================================================================= // // CPPUNIT_TEST_SUITE(TestCaseClass); // CPPUNIT_TEST(testMethod1); // CPPUNIT_TEST(testMethod2); // ... // CPPUNIT_TEST_SUITE_END(); // // ------------------------------------------------------------------------- // class TestFixtureCreator template <class TestFixtureType> class TestFixtureCreator { public: static void makeFixture(TestFixture** ppv) { *ppv = new TestFixtureType(); } }; // ------------------------------------------------------------------------- #define CPPUNIT_TEST_SUITE(ATestFixtureType) \ public: \ typedef ATestFixtureType TestFixtureType; \ static const char* __getFixtureName() \ { \ return #ATestFixtureType; \ } \ static void addTestsToSuite(TestSuiteBuilderContextBase* baseContext ) \ { \ TestSuiteBuilderContextType* context; \ _CppUnit_CreateTestSuiteBuilderContext(baseContext, &context) #define CPPUNIT_TEST(testMethod) \ _CppUnit_AddTest( \ context, \ __getFixtureName(), \ #testMethod, \ (FnTestMethod)&TestFixtureType::testMethod \ ) #define CPPUNIT_TEST_EXCEPTION(testMethod, ExceptionType) #define CPPUNIT_TEST_SUITE_END() \ _CppUnit_DeleteTestSuiteBuilderContext(context); \ } \ \ static void suite(TestSuite** ppSuite) \ { \ _CppUnit_SuiteEx( \ TestFixtureCreator<TestFixtureType>::makeFixture, \ TestFixtureType::addTestsToSuite, \ __getFixtureName(), \ _CppUnit_GetModuleName(), \ ppSuite); \ } \ private: /* dummy typedef so that the macro can still end with ';'*/ \ typedef int CppUnitDummyTypedefForSemiColonEnding__ // ========================================================================= // // CPPUNIT_REPORT(msg); or // CPPUNIT_ASSERT(cond); or // CPPUNIT_ASSERT_OK(hr); or // CPPUNIT_ASSERT_EQ(x, y); // // ------------------------------------------------------------------------- // CPPUNIT_REPORT #define CPPUNIT_REPORT(szMsg) \ if (_CppUnit_IsDebugMode()) \ _RPTF0(_CRT_ASSERT, szMsg); \ else \ _CppUnit_Fail("Expression: " szMsg, __FILE__, __LINE__) // ------------------------------------------------------------------------- // CPPUNIT_ASSERT #define CPPUNIT_ASSERT(condition) \ do { \ if ( !(condition) ) \ CPPUNIT_REPORT("CPPUNIT_ASSERT(" #condition ");"); \ } while (0) #define CPPUNIT_ASSERT_OK(hr) \ do { \ if ( !(condition) ) \ CPPUNIT_REPORT("CPPUNIT_ASSERT_OK(" #hr ");"); \ } while (0) // ------------------------------------------------------------------------- // CPPUNIT_ASSERT_EQUAL template <class T> inline STDMETHODIMP_(BOOL) _CppUnit_IsEqualDbg(const T& x, const T& y) { return x == y; } inline STDMETHODIMP_(BOOL) _CppUnit_IsEqualDbg(const char* x, const char* y) { return strcmp(x, y) == 0; } inline STDMETHODIMP_(BOOL) _CppUnit_IsEqualDbg(const WCHAR* x, const WCHAR* y) { return wcscmp(x, y) == 0; } #define CPPUNIT_ASSERT_EQUAL(expected, actual) \ do { \ if ( !_CppUnit_IsEqualDbg(expected, actual) ) \ CPPUNIT_REPORT("CPPUNIT_ASSERT_EQUAL(" #expected "," #actual ");"); \ } while (0) #define CPPUNIT_ASSERT_EQ(expected, actual) CPPUNIT_ASSERT_EQUAL(expected, actual) // ========================================================================= // // CPPUNIT_PROC_REGISTRATION(ModuleInit, ModuleTerm); // #define CPPUNIT_PROC_REGISTRATION(fnInit, fnTerm) \ static HRESULT _CppUnit_RegisterProcedure__ ## fnInit = \ _CppUnit_RegisterProcedure(fnInit, fnTerm) // ========================================================================= // // CPPUNIT_TEST_SUITE_REGISTRATION_DBG(TestCaseClass); or // CPPUNIT_TEST_SUITE_REGISTRATION(TestCaseClass); or // CPPUNIT_TEST_SUITE_REGISTRATION_BYNAME(TestCaseClass, SuiteName); // // ------------------------------------------------------------------------- // class AutoRegisterTestSuite template <class TestFixtureType> class AutoRegisterTestSuite { private: TestFactory* m_factory; public: AutoRegisterTestSuite() { // TestFixtureType::suite是一个创建suite的函数指针, // 被m_factory 保存并被其 makeTest 函数调用 _CppUnit_CreateTestSuiteFactory(TestFixtureType::suite, &m_factory); _CppUnit_RegisterFactory1(m_factory); } ~AutoRegisterTestSuite() { _CppUnit_UnregisterFactory1(m_factory); _CppUnit_DeleteTestSuiteFactory(m_factory); } }; template <class TestFixtureType> class AutoRegisterTestSuite_ByName { private: TestFactory* m_factory; public: AutoRegisterTestSuite_ByName(const char* strName) : m_strName(strName) { _CppUnit_CreateTestSuiteFactory(TestFixtureType::suite, &m_factory); _CppUnit_RegisterFactory_ByName(m_factory, m_strName); } ~AutoRegisterTestSuite_ByName() { _CppUnit_UnregisterFactory_ByName(m_factory, m_strName); _CppUnit_DeleteTestSuiteFactory(m_factory); } private: std::string m_strName; }; #define CPPUNIT_TEST_SUITE_REGISTRATION(TestFixtureType) \ static AutoRegisterTestSuite<TestFixtureType> \ TestFixtureType ## AutoRegister__ ## __LINE__ #define CPPUNIT_TEST_SUITE_REGISTRATION_BYNAME(TestFixtureType, SuiteName) \ static AutoRegisterTestSuite_ByName<TestFixtureType> \ TestFixtureType ## AutoRegister__ ## __LINE__ ## __ByName__(SuiteName) // ------------------------------------------------------------------------- #if defined(_DEBUG) || defined(X_RELEASE_CASE) #define CPPUNIT_TEST_SUITE_REGISTRATION_DBG(TestFixtureType) \ CPPUNIT_TEST_SUITE_REGISTRATION(TestFixtureType) #else #define CPPUNIT_TEST_SUITE_REGISTRATION_DBG(TestFixtureType) #endif #if defined(_DEBUG) || defined(X_RELEASE_CASE) #define CPPUNIT_PROC_REGISTRATION_DBG(fnInit, fnTerm) \ CPPUNIT_PROC_REGISTRATION(fnInit, fnTerm) #else #define CPPUNIT_PROC_REGISTRATION_DBG(fnInit, fnTerm) #endif // ========================================================================= // $Log: basic.h,v $ // Revision 1.18 2005/03/15 03:34:26 xushiwei // 1、_CppUnit_RunAllTests - 增加/run:<testclass>.<testmethod>参数支持。 // 2、_CppUnit_FilterCase - 支持修改部分Filter参数。 // 3、_CppUnit_Initialize参数改为EnumRunUnitType runtype。 // // Revision 1.17 2005/03/10 03:33:21 xushiwei // 增加_CppUnit_RegisterProcedure。 // 引入新宏: CPPUNIT_PROC_REGISTRATION_DBG/CPPUNIT_PROC_REGISTRATION。 // // Revision 1.16 2005/01/21 01:58:26 xushiwei // TestApp::AddUnit返回值由void改为HRESULT。 // #endif /* __CPPUNIT_BASIC_H__ */
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 334 ] ] ]
ac046859156acb5ed5a844094ac23fc926170ef6
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/gameswf/gameswf_abc.cpp
b3df916f07be1a6516e280d93838184265db69be
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
13,634
cpp
// gameswf_abc.cpp -- Vitaly Alexeev <[email protected]> 2008 // This source code has been donated to the Public Domain. Do // whatever you want with it. // do_abc tag reader/parser #include "gameswf/gameswf_abc.h" #include "gameswf/gameswf_stream.h" #include "gameswf/gameswf_log.h" #include "gameswf/gameswf_movie_def.h" namespace gameswf { void metadata_info::read(stream* in, abc_def* abc) { assert(0&&"todo"); } // traits_info // { // u30 name // u8 kind // u8 data[] // u30 metadata_count // u30 metadata[metadata_count] // } void traits_info::read(stream* in, abc_def* abc) { // The value can not be zero, and the multiname entry specified must be a QName. m_name = in->read_vu30(); assert(m_name != 0 && abc->m_multiname[m_name].is_qname()); IF_VERBOSE_PARSE(log_msg(" traits: name='%s'\n", abc->get_multiname(m_name))); Uint8 b = in->read_u8(); m_kind = b & 0x0F; m_attr = b >> 4; switch (m_kind) { case Trait_Slot : case Trait_Const : trait_slot.m_slot_id = in->read_vu30(); trait_slot.m_type_name = in->read_vu30(); assert(trait_slot.m_type_name < abc->m_multiname.size()); trait_slot.m_vindex = in->read_vu30(); if (trait_slot.m_vindex != 0) { // This field exists only when vindex is non-zero. trait_slot.m_vkind = in->read_u8(); } break; case Trait_Class : trait_class.m_slot_id = in->read_vu30(); trait_class.m_classi = in->read_vu30(); assert(trait_class.m_classi < abc->m_class.size()); break; case Trait_Function : trait_function.m_slot_id = in->read_vu30(); trait_function.m_function = in->read_vu30(); assert(trait_function.m_function < abc->m_method.size()); break; case Trait_Method : case Trait_Getter : case Trait_Setter : trait_method.m_disp_id = in->read_vu30(); trait_method.m_method = in->read_vu30(); assert(trait_method.m_method < abc->m_method.size()); break; default: assert(false && "invalid kind of traits"); break; } if (m_attr & ATTR_Metadata) { assert(0 && "test"); int n = in->read_vu30(); m_metadata.resize(n); for (int i = 0; i < n; i++) { m_metadata[i] = in->read_vu30(); } } } // instance_info // { // u30 name // u30 super_name // u8 flags // u30 protectedNs // u30 intrf_count // u30 interface[intrf_count] // u30 iinit // u30 trait_count // traits_info trait[trait_count] // } void instance_info::read(stream* in, abc_def* abc) { m_name = in->read_vu30(); m_super_name = in->read_vu30(); m_flags = in->read_u8(); if (m_flags & CONSTANT_ClassProtectedNs) { m_protectedNs = in->read_vu30(); } int i, n; n = in->read_vu30(); m_interface.resize(n); for (i = 0; i < n; i++) { m_interface[i] = in->read_vu30(); } m_iinit = in->read_vu30(); IF_VERBOSE_PARSE(log_msg(" name='%s', supername='%s', ns='%s'\n", abc->get_multiname(m_name), abc->get_multiname(m_super_name), abc->get_namespace(m_protectedNs))); n = in->read_vu30(); m_trait.resize(n); for (i = 0; i < n; i++) { traits_info* trait = new traits_info(); trait->read(in, abc); m_trait[i] = trait; } } void class_info::read(stream* in, abc_def* abc) { // This is an index into the method array of the abcFile m_cinit = in->read_vu30(); assert(m_cinit < abc->m_method.size()); int n = in->read_vu30(); m_trait.resize(n); for (int i = 0; i < n; i++) { traits_info* trait = new traits_info(); trait->read(in, abc); m_trait[i] = trait; } } void script_info::read(stream* in, abc_def* abc) { // The init field is an index into the method array of the abcFile m_init = in->read_vu30(); assert(m_init < abc->m_method.size()); int n = in->read_vu30(); m_trait.resize(n); for (int i = 0; i < n; i++) { traits_info* trait = new traits_info(); trait->read(in, abc); m_trait[i] = trait; } } // exception_info // { // u30 from // u30 to // u30 target // u30 exc_type // u30 var_name // } void except_info::read(stream* in, abc_def* abc) { m_from = in->read_vu30(); m_to = in->read_vu30(); m_target = in->read_vu30(); m_exc_type = in->read_vu30(); m_var_name = in->read_vu30(); } abc_def::abc_def(player* player) { } abc_def::~abc_def() { } // abcFile // { // u16 minor_version // u16 major_version // cpool_info cpool_info // u30 method_count // method_info method[method_count] // u30 metadata_count // metadata_info metadata[metadata_count] // u30 class_count // instance_info instance[class_count] // class_info class[class_count] // u30 script_count // script_info script[script_count] // u30 method_body_count // method_body_info method_body[method_body_count] // } void abc_def::read(stream* in, movie_definition_sub* m) { int eof = in->get_tag_end_position(); int i, n; Uint16 minor_version = in->read_u16(); Uint16 major_version = in->read_u16(); assert(minor_version == 16 && major_version == 46); // read constant pool read_cpool(in); assert(in->get_position() < eof); // read method_info n = in->read_vu30(); m_method.resize(n); IF_VERBOSE_PARSE(log_msg("method_info count: %d\n", n)); for (i = 0; i < n; i++) { as_3_function* info = new as_3_function(this, i, m->get_player()); info->read(in); m_method[i] = info; } assert(in->get_position() < eof); // read metadata_info n = in->read_vu30(); m_metadata.resize(n); IF_VERBOSE_PARSE(log_msg("metadata_info count: %d\n", n)); for (i = 0; i < n; i++) { assert(0 && "test"); metadata_info* info = new metadata_info(); info->read(in, this); m_metadata[i] = info; } assert(in->get_position() < eof); // read instance_info & class_info n = in->read_vu30(); m_instance.resize(n); IF_VERBOSE_PARSE(log_msg("instance_info count: %d\n", n)); for (i = 0; i < n; i++) { IF_VERBOSE_PARSE(log_msg("instance_info[%d]:\n", i)); instance_info* info = new instance_info(); info->read(in, this); m_instance[i] = info; } assert(in->get_position() < eof); // class_info m_class.resize(n); IF_VERBOSE_PARSE(log_msg("class_info count: %d\n", n)); for (i = 0; i < n; i++) { IF_VERBOSE_PARSE(log_msg("class_info[%d]\n", i)); class_info* info = new class_info(); info->read(in, this); m_class[i] = info; } assert(in->get_position() < eof); // read script_info n = in->read_vu30(); m_script.resize(n); IF_VERBOSE_PARSE(log_msg("script_info count: %d\n", n)); for (i = 0; i < n; i++) { IF_VERBOSE_PARSE(log_msg("script_info[%d]\n", i)); script_info* info = new script_info(); info->read(in, this); m_script[i] = info; } assert(in->get_position() < eof); // read body_info n = in->read_vu30(); for (i = 0; i < n; i++) { int method_index = in->read_vu30(); m_method[method_index]->read_body(in); } assert(in->get_position() == eof); } // cpool_info // { // u30 int_count // s32 integer[int_count] // u30 uint_count // u32 uinteger[uint_count] // u30 double_count // d64 double[double_count] // u30 string_count // string_info string[string_count] // u30 namespace_count // namespace_info namespace[namespace_count] // u30 ns_set_count // ns_set_info ns_set[ns_set_count] // u30 multiname_count // multiname_info multiname[multiname_count] // } void abc_def::read_cpool(stream* in) { int n; // integer pool n = in->read_vu30(); if (n > 0) { m_integer.resize(n); m_integer[0] = 0; // default value for (int i = 1; i < n; i++) { m_integer[i] = in->read_vs32(); IF_VERBOSE_PARSE(log_msg("cpool_info: integer[%d]=%d\n", i, m_integer[i])); } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no integer pool\n")); } // uinteger pool n = in->read_vu30(); if (n > 0) { m_uinteger.resize(n); m_uinteger[0] = 0; // default value for (int i = 1; i < n; i++) { m_uinteger[i] = in->read_vu32(); IF_VERBOSE_PARSE(log_msg("cpool_info: uinteger[%d]=%d\n", i, m_uinteger[i])); } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no uinteger pool\n")); } // double pool n = in->read_vu30(); if (n > 0) { m_double.resize(n); m_double[0] = 0; // default value for (int i = 1; i < n; i++) { m_double[i] = in->read_double(); IF_VERBOSE_PARSE(log_msg("cpool_info: double[%d]=%f\n", i, m_double[i])); } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no double pool\n")); } // string pool n = in->read_vu30(); if (n > 0) { m_string.resize(n); m_string[0] = ""; // default value for (int i = 1; i < n; i++) { int len = in->read_vs32(); in->read_string_with_length(len, &m_string[i]); IF_VERBOSE_PARSE(log_msg("cpool_info: string[%d]='%s'\n", i, m_string[i].c_str())); } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no string pool\n")); } // namespace pool n = in->read_vu30(); if (n > 0) { m_namespace.resize(n); namespac ns; m_namespace[0] = ns; // default value for (int i = 1; i < n; i++) { ns.m_kind = static_cast<namespac::kind>(in->read_u8()); ns.m_name = in->read_vu30(); m_namespace[i] = ns; // User-defined namespaces have kind CONSTANT_Namespace or // CONSTANT_ExplicitNamespace and a non-empty name. // System namespaces have empty names and one of the other kinds switch (ns.m_kind) { case namespac::CONSTANT_Namespace: case namespac::CONSTANT_ExplicitNamespace: // assert(*get_string(ns.m_name) != 0); break; case namespac::CONSTANT_PackageNamespace: case namespac::CONSTANT_PackageInternalNs: case namespac::CONSTANT_ProtectedNamespace: case namespac::CONSTANT_StaticProtectedNs: case namespac::CONSTANT_PrivateNs: // assert(*get_string(ns.m_name) == 0); break; default: assert(0); } IF_VERBOSE_PARSE(log_msg("cpool_info: namespace[%d]='%s', kind=0x%02X\n", i, get_string(ns.m_name), ns.m_kind)); } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no namespace pool\n")); } // namespace sets pool n = in->read_vu30(); if (n > 0) { m_ns_set.resize(n); array<int> ns; m_ns_set[0] = ns; // default value for (int i = 1; i < n; i++) { int count = in->read_vu30(); ns.resize(count); for (int j = 0; j < count; j++) { ns[j] = in->read_vu30(); } m_ns_set[i] = ns; } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no namespace sets\n")); } // multiname pool n = in->read_vu30(); if (n > 0) { m_multiname.resize(n); multiname mn; m_multiname[0] = mn; // default value for (int i = 1; i < n; i++) { Uint8 kind = in->read_u8(); mn.m_kind = kind; switch (kind) { case multiname::CONSTANT_QName: case multiname::CONSTANT_QNameA: { mn.m_ns = in->read_vu30(); mn.m_name = in->read_vu30(); IF_VERBOSE_PARSE(log_msg("cpool_info: multiname[%d]='%s', ns='%s'\n", i, get_string(mn.m_name), get_namespace(mn.m_ns))); break; } case multiname::CONSTANT_RTQName: assert(0&&"todo"); break; case multiname::CONSTANT_RTQNameA: assert(0&&"todo"); break; case multiname::CONSTANT_RTQNameL: assert(0&&"todo"); break; case multiname::CONSTANT_RTQNameLA: assert(0&&"todo"); break; case multiname::CONSTANT_Multiname: case multiname::CONSTANT_MultinameA: mn.m_ns_set = in->read_vu30(); mn.m_name = in->read_vu30(); IF_VERBOSE_PARSE(log_msg("cpool_info: multiname[%d]='%s', ns_set='%s'\n", i, get_string(mn.m_name), "todo")); break; case multiname::CONSTANT_MultinameL: case multiname::CONSTANT_MultinameLA: mn.m_ns_set = in->read_vu30(); IF_VERBOSE_PARSE(log_msg("cpool_info: multiname[%d]=MultinameL, ns_set='%s'\n", i, get_string(mn.m_name), "todo")); break; default: assert(0); } m_multiname[i] = mn; } } else { IF_VERBOSE_PARSE(log_msg("cpool_info: no multiname pool\n")); } } // get class constructor // 'name' is the fully-qualified name of the ActionScript 3.0 class // with which to associate this symbol. // The class must have already been declared by a DoABC tag. as_function* abc_def::get_class_constructor(tu_string& name) const { // find instance_info by name instance_info* ii = find_instance(name); if (ii != NULL) { // 'ii->m_iinit' is an index into the method array of the abcFile; // it references the method that is invoked whenever // an object of this class is constructed. return m_method[ii->m_iinit].get_ptr(); } return NULL; } instance_info* abc_def::find_instance(const tu_string& class_name) const { //TODO return m_instance[0].get_ptr(); } }; // end namespace gameswf // Local Variables: // mode: C++ // c-basic-offset: 8 // tab-width: 8 // indent-tabs-mode: t // End:
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 573 ] ] ]
3d476ff54b4d93b9f6bb26a66bc8a38367574840
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/calls/wscCallsParser.cpp
8d6b302e1130abb559883feeafb7e7b6ddde7316
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
1,805
cpp
#include "wscCallsParser.h" #include "wsiCallsHandler.h" #include <wcpp/lang/wscThrowable.h> #include <wcpp/io/wsiInputStream.h> #include <wcpp/lang/helper/ws_str_buffer.h> #include <boost/regex.hpp> #include <string> const ws_char * const wscCallsParser::s_class_name = "wcpp.calls.wscCallsParser"; wscCallsParser::wscCallsParser(wsiCallsHandler * ch) { } wscCallsParser::~wscCallsParser(void) { } ws_result wscCallsParser::parse(wsiInputStream * is) { WS_THROW( wseUnsupportedOperationException , "" ); } ws_int wscCallsParser::SkipSpaces(wsiInputStream * is) { if (is==WS_NULL) return -1; for (;;) { const ws_int c = is->Read(); switch (c) { case ' ': case '\t': case 0x0a: case 0x0d: break; default: return c; } } } ws_int wscCallsParser::ReadString(wsiInputStream * is, ws_str_buffer & buf) { if (is==WS_NULL) return -1; for (;;) { const ws_int c = is->Read(); if ((0<=c) && (c<=255)) { if (c=='"') { return c; } else { buf += ((ws_char)c); } } else { return -1; } } } ws_int wscCallsParser::ReadSymbol(wsiInputStream * is, ws_str_buffer & buf) { if (is==WS_NULL) return -1; for (;;) { const ws_int c = is->Read(); if ( (('a'<=c) && (c<='z')) || (('A'<=c) && (c<='Z')) || (('0'<=c) && (c<='9')) || (c=='_') ) { buf += static_cast<ws_char>(c); } else { return c; } } }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 88 ] ] ]
cf61cb4d7745c02acf2b552167fd6bde231d8988
14d51a21038a3d46f2fc019bbb161022a9f4854f
/LhpHtmlView.h
8bcfa17a04445ee11e401f7bd41cd16e1d41dbfc
[]
no_license
toraleap/w3plus
44246d8e7373c07ac430ebc66409ba8aae4be59f
a34a9e4fad93f763ea8423f684f04a4e5b466a98
refs/heads/master
2021-01-01T15:50:08.091393
2011-02-18T05:38:32
2011-02-18T05:38:32
32,132,245
0
0
null
null
null
null
GB18030
C++
false
false
2,942
h
#pragma once #include <afxhtml.h> #include <comdef.h> #include "DocHostSite.h" class CLhpHtmlView : public CHtmlView { DECLARE_DYNCREATE(CLhpHtmlView) DECLARE_DISPATCH_MAP() DECLARE_MESSAGE_MAP() public: CLhpHtmlView(BOOL isview = TRUE); virtual ~CLhpHtmlView(); public: enum CONTEXT_MENU_MODE // 上下文菜单 { NoContextMenu, // 无菜单 DefaultMenu, // 默认菜单 TextSelectionOnly, // 仅文本选择菜单 CustomMenu // 自定义菜单 }; protected: CONTEXT_MENU_MODE m_ContextMenuMode; // 上下文菜单模式 CString m_DefaultMsgBoxTitle; // 默认MessageBox标题 DWORD m_HostInfoFlag; // 浏览器的一些设置如是否有滚动条等 BOOL m_IsView; // 是否是视图 CComPtr<IHTMLDocument2> m_spDoc; public: // 更改浏览器的一些设置如是否有滚动条等 void SetHostInfoFlag(DWORD dwFlag); public: // 当在一个窗体上创建时(当作窗体的一个控件)可以指定一个控件ID按指定的控件大小位置 BOOL CreateFromStatic(UINT nID, CWnd* pParent); BOOL Create(CRect rect, CWnd* pParent, UINT nID); public: virtual BOOL CreateControlSite(COleControlContainer* pContainer,COleControlSite** ppSite, UINT nID, REFCLSID clsid); // 定制宿主信息 virtual HRESULT OnGetHostInfo(DOCHOSTUIINFO * pInfo); // 上下文菜单 virtual HRESULT OnShowContextMenu(DWORD dwID, LPPOINT ppt,LPUNKNOWN pcmdtReserved, LPDISPATCH pdispReserved); // 设置脚本扩展 virtual HRESULT OnGetExternal(LPDISPATCH *lppDispatch); protected: const CString GetSystemErrorMessage(DWORD dwError); CString GetNextToken(CString& strSrc, const CString strDelim,BOOL bTrim = FALSE, BOOL bFindOneOf = TRUE); BOOL SetScriptDocument(); const CString GetLastError() const; BOOL GetJScript(CComPtr<IDispatch>& spDisp); BOOL GetJScripts(CComPtr<IHTMLElementCollection>& spColl); CString ScanJScript(CString& strAText, CStringArray& args); public: BOOL JScriptOK(); public: BOOL CallJScript(const CString strFunc,_variant_t* pVarResult = NULL); BOOL CallJScript(const CString strFunc,const CString strArg1,_variant_t* pVarResult = NULL); BOOL CallJScript(const CString strFunc,const CString strArg1,const CString strArg2,_variant_t* pVarResult = NULL); BOOL CallJScript(const CString strFunc,const CString strArg1,const CString strArg2,const CString strArg3,_variant_t* pVarResult = NULL); BOOL CallJScript(const CString strFunc,const CStringArray& paramArray,_variant_t* pVarResult = NULL); protected: virtual void PostNcDestroy(); virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual void OnDocumentComplete(LPCTSTR lpszURL); public: afx_msg void OnDestroy(); afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); };
[ "[email protected]@00efcefc-f4bc-333f-9454-5c8bce538679" ]
[ [ [ 1, 84 ] ] ]
f83f97f93c9f329bdc0fa7c5067b040d0b89cac8
a96faf238d7d30a64b3cff7d8c7532074123f3be
/src/clmain.h
635f642f88453a16210cfdf4c5100d6871b0fc9c
[]
no_license
RangelReale/chordlive
0c93a8bd0a29c44ba0c7c206e353c2c77bbe8164
5529f61bdd10deed1cd5c8070f9bd9557f318719
refs/heads/master
2023-06-12T18:14:35.768988
2009-06-22T23:58:31
2009-06-22T23:58:31
37,156,240
0
0
null
null
null
null
UTF-8
C++
false
false
512
h
#ifndef H__CLMAIN__H #define H__CLMAIN__H #include <wx/wx.h> #include "clpanel.h" class CLMain : public wxFrame { DECLARE_CLASS(CLMain) DECLARE_EVENT_TABLE() private: void onFileImport(wxCommandEvent &event); void onFileExit(wxCommandEvent &event); void onHelpAbout(wxCommandEvent &event); CLPanel *song_; public: enum { ID_FRAME = 10000, ID_PANEL, IDM_FILE_IMPORT, IDM_FILE_EXIT, IDM_HELP_ABOUT }; CLMain(); }; #endif // H__CLMAIN__H
[ "hitnrun@82bcaf60-b05e-4c88-ae40-7279958f80f4" ]
[ [ [ 1, 29 ] ] ]
e34e5c91f9c3ab59cbc11521adc68e826f9809bd
4fdc157f7d6c5af784c3492909d848a0371e5877
/vision_PO/robot/Strategy.cpp
1807c3fd88c6ac244b153f6d0a7ed35176f49f16
[]
no_license
moumen19/robotiquecartemere
d969e50aedc53844bb7c512ff15e6812b8b469de
8333bb0b5c1b1396e1e99a870af2f60c9db149b0
refs/heads/master
2020-12-24T17:17:14.273869
2011-02-11T15:44:38
2011-02-11T15:44:38
34,446,411
0
0
null
null
null
null
UTF-8
C++
false
false
2,051
cpp
/* * * Bureau d'étude Robotique M2 ISEN 2010-2011 * * DELBERGUE Julien * JACQUEL Olivier * PIETTE Ferdinand ([email protected]) * * Fichier Strategy.cpp * */ #include "Strategy.hpp" /** * Constructeur * @param environment - le module de stockage de donnees de l'environnement * @param constraint - le module de contraintes */ Strategy::Strategy(Data & environment, Constraint & constraint) : a_constraint(constraint), a_environmentData(environment) { a_strategySave = NONE; _DEBUG("Initialisation du module de strategie", INFORMATION); } /** * Destructeur */ Strategy::~Strategy() { _DEBUG("Destruction du module de strategie", INFORMATION); } /** * Methode qui initialise la strategie * @param strategy - la strategie */ void Strategy::init(Strat strategy) { a_strategySave = strategy; this->set(strategy); } /** * Methode retournant la strategie en cours * @return la strategie en cours */ Strat Strategy::get() { return this->a_strategy; } /** * Methode definissant la strategie a adopter * @param strategie - la strategie a adopter */ void Strategy::set(Strat strategy) { if(this->a_strategy == NONE) _DEBUG("La strategie n'a pas ete initialisee", WARNING); switch(strategy) { case BAU_ON: bau_on(); break; case BAU_OFF: bau_off(); break; case GO_AHEAD: go_ahead(); break; default: break; } } /** * Strategie BAU active */ void Strategy::bau_on() { if(this->get() != BAU_ON) { _DEBUG("Strategie BAU_ON active", INFORMATION); this->a_strategySave = this->a_strategy; this->a_strategy = BAU_ON; } } /** * Strategie BAU desactive */ void Strategy::bau_off() { if(this->a_strategySave != this->get()) { _DEBUG("Strategie BAU_OFF active", INFORMATION); this->set(a_strategySave); } } /** * Strategie principale */ void Strategy::go_ahead() { _DEBUG("Strategy GO_AHEAD active", INFORMATION); this->a_strategy = GO_AHEAD; }
[ "ferdinand.piette@308fe9b9-b635-520e-12eb-2ef3f824b1b6" ]
[ [ [ 1, 113 ] ] ]
d1bdd08115e426e78c930bdaea199a90ef5a39d1
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/Swc/samples/Mdi/Mdi.cpp
37337dbf4d305f2db3c53cd49ec3e99a658a9e14
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,011
cpp
// Mdi.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #include <time.h> #include <stdio.h> HHOOK CHookMenu::hHook=NULL; // BeyonClass.cpp : Defines the entry point for the application. // #define HELLO 0x1111 #define IDPANEL0 60 #define IDPANEL1 20 #define IDPANEL2 20 int Panels[]={ IDPANEL0,IDPANEL1,IDPANEL2}; class ChildHello : public CChildWnd { HWND m_edit; public: ChildHello(HWND hWnd=NULL): CChildWnd(hWnd) {} BOOL OnCreate(LPCREATESTRUCT lpCreateStruct) { m_edit= CreateWindowEx(0,"EDIT","", WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL, 0,0,100,100,GetSafeHwnd(),(HMENU)HELLO,GetModuleHandle(NULL),NULL); return 0; } BOOL OnSize(UINT nType,long x, long y) { CRect rc1; GetClientRect(rc1); HWND hW=GetChild(); ::SetWindowPos(hW,NULL,rc1.left,rc1.top,rc1.Width(),rc1.Height(),SWP_NOZORDER); return TRUE; } void OnChangeEdit1(int wHp, int wLp, HWND hControl) { } BEGIN_MSG_MAP() ON_WM_CREATE(OnCreate) ON_WM_SIZE(OnSize) ON_COMMAND_CONTROL(HELLO,EN_CHANGE, OnChangeEdit1) END_MSG_MAP(CChildWnd) }; class CAbout : public CDialog { CEdit m_edit; public: CAbout(){}; ~CAbout(){}; virtual BOOL OnInitDialog(HWND wParam,LPARAM lParam); virtual BOOL OnOK(WPARAM wParam, LPARAM lParam, HWND hWnd); virtual BOOL OnCancel(WPARAM wParam, LPARAM lParam, HWND hWnd); BEGIN_MSG_MAP() ON_WM_INITDIALOG(OnInitDialog) ON_COMMAND(IDOK,OnOK) ON_COMMAND(IDCANCEL,OnCancel) END_MSG_MAP(CDialog) }; BOOL CAbout::OnInitDialog(HWND wParam,LPARAM lParam) { LINK_Control(IDC_EDIT,m_edit); return TRUE; } BOOL CAbout ::OnOK(WPARAM wParam, LPARAM lParam, HWND hWnd) { char* lpText=(char*)malloc(200); m_edit.GetWindowText(lpText,20); MsgBox(lpText); CDialog::OnOK(); return TRUE; } BOOL CAbout ::OnCancel(WPARAM wParam, LPARAM lParam, HWND hWnd) { CDialog::OnCancel(); return TRUE; } class CWinFrame: public CFrameMDI { CToolBarCtrlEx m_ToolBar; CToolBarCtrlEx m_ToolBar1; CListView m_up; CMiniFrame m_Mini; public: CWinFrame(HWND hWnd=NULL):CFrameMDI(hWnd){} BOOL OnClose(); BOOL OnCreate(LPCREATESTRUCT lpCreateStruct); BOOL OnSize(UINT nType,long x, long y); void OnNew(WPARAM wParam, LPARAM lParam, HWND hWnd) { ChildHello* child=new ChildHello(); if (!child->LoadFrame(IDR_MENUHELLO,GetSafeClientHwnd())) return; } void OnExit(WPARAM wParam, LPARAM lParam, HWND hWnd) { SendMessage(WM_CLOSE,0,0); } void Cascade(WPARAM wParam, LPARAM lParam, HWND hWnd) { MDICascade(); } void OnToolBar(WPARAM wParam, LPARAM lParam, HWND hWnd) { OnShowBand(m_ToolBar.GetSafeHwnd()); } void OnFileClose(WPARAM wParam, LPARAM lParam, HWND hWnd) { OnCloseChild(); } void OnFileOpen(WPARAM wParam, LPARAM lParam, HWND hWnd) { CFileOpen co(this); co.DoModal(TRUE); } void OnAbout(WPARAM wParam, LPARAM lParam, HWND hWnd) { CAbout cb; cb.DoModal(this,(LPCTSTR)IDD_ABOUTBOX); } void OnTitle(WPARAM wParam, LPARAM lParam, HWND hWnd) { MDITile(); } /* virtual LRESULT OnMeasureItem(LPMEASUREITEMSTRUCT lpms) { return CFrame::OnMeasureItem(lpms); } virtual BOOL OnDrawItem(LPDRAWITEMSTRUCT lpds) { return CFrame::OnDrawItem(lpds); } */ BEGIN_MSG_MAP() ON_WM_CREATE(OnCreate) ON_COMMAND(ID_FILE_NEW,OnNew) ON_WM_SIZE(OnSize) ON_COMMAND(ID_WINDOW_CASCADE,Cascade) ON_COMMAND(ID_TOOLBAR,OnToolBar) ON_COMMAND(IDM_EXIT,OnExit) ON_COMMAND(ID_FILE_CLOSE,OnFileClose) ON_COMMAND(ID_FILE_OPEN,OnFileOpen) ON_COMMAND(ID_WINDOW_TILE_HORZ,OnTitle) ON_COMMAND(IDM_ABOUT,OnAbout); ON_WM_CLOSE(OnClose) // ON_WM_DRAWITEM(OnDrawItem) // ON_WM_MEASUREITEM(OnMeasureItem) END_MSG_MAP(CFrameMDI) }; BOOL CWinFrame::OnSize(UINT nType,long x, long y) { CFrameMDI::OnSize(nType,x,y); return TRUE; } BOOL CWinFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { CFrameMDI::OnCreate(lpCreateStruct); if (!CreateExBars(Panels,3)) return -1; if ( !m_ToolBar.Create(m_ReBar->GetSafeHwnd(),IDR_TOOLBAR)) return -1; if ( !m_ToolBar1.Create(m_ReBar->GetSafeHwnd(),IDR_TOOLBAR1)) return -1; //m_ToolBar.AddButtonText(ID_FILE_NEW, _T("Hola")); m_ToolBar.LoadToolBar(IDR_TOOLBAR); m_ToolBar1.LoadToolBar(IDR_TOOLBAR1); AddBar(&m_ToolBar, IDR_TOOLBAR); AddBar(&m_ToolBar1, IDR_TOOLBAR1); m_ToolBar.AddTrueColor(IDB_TOOLBAR,TB_SETIMAGELIST); m_ToolBar1.AddTrueColor(IDr_BITMAP1,TB_SETIMAGELIST); SetPanelText(0,_T("Ready") ); SetIcon(theApp->LoadIcon((LPCSTR)IDI_SMALL),FALSE); // COOLMENU SUPPORT cSpawn.LoadToolBarResource(IDR_TOOLBAR,IDB_TOOLBAR); // cSpawn.AddToolBarResource(IDR_SYSTEMBAR); cSpawn.AddToolBarResource(IDR_TOOLBAR1); // CreateDockBars(); return 0; } BOOL CWinFrame::OnClose() { int resp=MsgBox("Esta seguro de Salir","Close",MB_YESNO); if (resp==IDYES) return CWin::OnDestroy(); return FALSE; } class CAppMain :public CApp { public: int InitInstance(); ~CAppMain() { CHookMenu::UnInstallHook(); } }; int CAppMain::InitInstance() { CHookMenu::InstallHook(); m_WinMain=(CFrame*)new CWinFrame(); if (m_WinMain->LoadFrame(IDC_WINCLASS)== FALSE) return -1; SetMenuResource((LPCTSTR)IDC_WINCLASS); LoadMenu((LPCTSTR)IDC_WINCLASS); // m_WinMain->cSpawn.RemapMenu(m_Menu.GetHandleMenu()); // 3D HIGHLIGHT CODE m_WinMain->ShowWindow(); m_WinMain->UpdateWindow(); hAccelTable = LoadAccelerators( (LPCTSTR)IDC_WINCLASS); return Run(); } int PASCAL WinMain(HINSTANCE hinstace, HINSTANCE PrehInstance, LPSTR cmdLine, int show) { CAppMain cpMain; if (theApp==0) return 0; theApp->LoadMain(hinstace, PrehInstance, cmdLine, show); return theApp->InitInstance(); }
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 294 ] ] ]
6077788d34117062431018cd240cc2eb5933df2c
ebba8dfe112e93bad2be3551629d632ee4681de9
/apps/28apps/28blobs/src/FBO/ofTextureAdv.h
0a83f6893a6e9b6b17444d783afad068b2af6988
[]
no_license
lucasdupin/28blobs
8499a4c249b5ac4c7731313e0d418dc051610de4
5a6dd8a9b084468a38f5045a2367a1dbf6d21609
refs/heads/master
2016-08-03T12:27:08.348430
2009-06-20T04:39:03
2009-06-20T04:39:03
219,034
2
0
null
null
null
null
UTF-8
C++
false
false
931
h
#ifndef _IMAGE_TEXTURE_ADV_H_ #define _IMAGE_TEXTURE_ADV_H_ #include "ofMain.h" #include "ofFBOTexture.h" #define GRID_X 12 #define GRID_Y 8 class ofTextureAdv : public ofFBOTexture { public : ofTextureAdv(); ~ofTextureAdv(); void allocate(int w, int h, int internalGlDataType); void clear(); void loadData(unsigned char * data, int w, int h, int glDataType); void setPoint(int which, float x, float y); void setPoints(ofPoint pts[4]); void setPoints(ofPoint inputPts[4], ofPoint outputPts[4]); void draw(); void draw(float x, float y) { ofTexture::draw(x,y); }; void draw(float x, float y, float w, float h) { ofTexture::draw(x,y,w,h); }; void allocate(int w, int h, bool clear){ ofFBOTexture::allocate(w,h, clear); }; int width, height; protected: void updatePoints(); ofPoint quad[4]; ofPoint utQuad[4]; ofPoint * grid; ofPoint * coor; }; #endif
[ [ [ 1, 44 ] ] ]
2d4b3db0e92283d5a6cc99abfcb5087a7ff26dd9
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/CasePort.cpp
7affc271cc9f84bbe1f05ee217cecb8826024228
[]
no_license
Issam-Engineer/tp4infoinsa
3538644b40d19375b6bb25f030580004ed4a056d
1576c31862ffbc048890e72a81efa11dba16338b
refs/heads/master
2021-01-10T17:53:31.102683
2011-01-27T07:46:51
2011-01-27T07:46:51
55,446,817
0
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
/** *\file CasePort.cpp *\brief File which contains the functions and code of the CasePort class *\author Maxime HAVEZ *\author Gareth THIVEUX *\version 1.0 */ #include "CasePort.h" CasePort::CasePort(int c){ _hauteur = 0; _accessible = false; _couleur = c; _nbTresors = 0; }
[ "garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6", "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 7 ], [ 9, 10 ], [ 13, 13 ], [ 15, 16 ] ], [ [ 8, 8 ], [ 11, 12 ], [ 14, 14 ] ] ]
dce6ac456b40d7c95bf97d4a1244d890ad0c163a
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WP_WTraits/WP_WTraits.cpp
08bcf9c40a24920c6cc9c33f2c3e4cd874340eda
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
55,828
cpp
// WKHelper.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include <tchar.h> #include <math.h> #include <atlbase.h> #include "HookCode.h" #include "WP_WTraits.h" #include "DLGOptions.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern HWND hLastFocusWnd; extern HWND hLastActiveWnd; extern char g_szStartUpWindowName[256]; extern char g_szApplications[MAX_APPS][(10+MAX_APP_NAME)]; extern long g_IzWndAttachInProgress; char g_DefDockTitle[128]={0}; void CheckWindwOnTop(HWND hwndDlg); WKCallbackInterface*& WKGetPluginContainer() { static WKCallbackInterface* pCallback=0; return pCallback; } void WINAPI SetLastFocusWnd(HWND h) { if(h!=0){ hLastFocusWnd=h; } } HWND& WINAPI GetLastFocusWnd() { //FLOG1("Retrieving last focus window: %08x",hLastFocusWnd); return hLastFocusWnd; } char szRetranslationBuffer[1024]=""; char* _pl(const char* szText) { WKGetPluginContainer()->GetTranslation(szText,szRetranslationBuffer,sizeof(szRetranslationBuffer)); return szRetranslationBuffer; } CWKHekperInfoLocal plugData; HANDLE hHookerEventDone=NULL; HANDLE hHookerEventStop=NULL; HANDLE hPluginStop=0; WKCallbackInterface* pCallbackInterface=NULL; DWORD dwHookerThreadInThisDLL=0; extern HINSTANCE g_hinstDll; extern CWKHekperInfo hookData; extern DWORD dwHookerThread; extern RECT rtScreenSize; extern UINT msgGetScreenshot; extern DWORD dwSnapWindowTimeData; extern HWND hLastNCHittestWnd; extern DWORD dwLastNCHittestRes; BOOL IsPointInRect(LONG lX,LONG lY,RECT& rt) { if(lX<rt.left){ return FALSE; } if(lY<rt.top){ return FALSE; } if(lX>rt.right){ return FALSE; } if(lY>rt.bottom){ return FALSE; } return TRUE; } #define INTERSECT_TYPE_NONE 0x00 #define INTERSECT_TYPE_VERT 0x01 #define INTERSECT_TYPE_HORZ 0x02 BOOL IsRectIntersected(RECT& rect, RECT& rectWith,int iDrebezg) { RECT rt; rt.left=rectWith.left-iDrebezg; rt.top=rectWith.top-iDrebezg; rt.right=rectWith.right+iDrebezg; rt.bottom=rectWith.bottom+iDrebezg; if(rt.left>rt.right){ LONG lTmp=rt.left; rt.left=rt.right; rt.right=lTmp; } if(rt.top>rt.bottom){ LONG lTmp=rt.bottom; rt.bottom=rt.top; rt.top=lTmp; } int iRes=INTERSECT_TYPE_NONE; if((rect.left<rt.right && rect.left>rt.left) || (rect.right<rt.right && rect.right>rt.left)){ iRes|=INTERSECT_TYPE_VERT; } if((rect.top<rt.bottom && rect.top>rt.top) || (rect.bottom<rt.bottom && rect.bottom>rt.top)){ iRes|=INTERSECT_TYPE_HORZ; } if(IsPointInRect(rect.left,rect.top,rt) || IsPointInRect(rect.right,rect.top,rt) || IsPointInRect(rect.left,rect.bottom,rt) || IsPointInRect(rect.right,rect.bottom,rt)){ iRes|=INTERSECT_TYPE_VERT; iRes|=INTERSECT_TYPE_HORZ; } return iRes; } BOOL TestSticknessWithRect(RECT& rect, RECT& rectWith,int iStickness) { int iIsectType=IsRectIntersected(rect,rectWith,iStickness); if(iIsectType==INTERSECT_TYPE_NONE){ return FALSE; } BOOL bChanged=0; int iWidth=(rect.right-rect.left); int iHeight=(rect.bottom-rect.top); if(iIsectType & INTERSECT_TYPE_HORZ){ if(fabs(double(rect.left-rectWith.left))<iStickness && rect.left!=rectWith.left){ bChanged=TRUE; rect.left=rectWith.left; } if(fabs(double(rect.right-rectWith.left))<iStickness && rect.right!=rectWith.left){ bChanged=TRUE; rect.left=rectWith.left-iWidth; } if(fabs(double(rect.left-rectWith.right))<iStickness && rect.left!=rectWith.right){ bChanged=TRUE; rect.left=rectWith.right; } if(fabs(double(rect.right-rectWith.right))<iStickness && rect.right!=rectWith.right){ bChanged=TRUE; rect.left=rectWith.right-iWidth; } } if(iIsectType & INTERSECT_TYPE_VERT){ if(fabs(double(rect.top-rectWith.top))<iStickness && rect.top!=rectWith.top){ bChanged=TRUE; rect.top=rectWith.top; } if(fabs(double(rect.bottom-rectWith.top))<iStickness && rect.bottom!=rectWith.top){ bChanged=TRUE; rect.top=rectWith.top-iHeight; } if(fabs(double(rect.top-rectWith.bottom))<iStickness && rect.top!=rectWith.bottom){ bChanged=TRUE; rect.top=rectWith.bottom; } if(fabs(double(rect.bottom-rectWith.bottom))<iStickness && rect.bottom!=rectWith.bottom){ bChanged=TRUE; rect.top=rectWith.bottom-iHeight; } } if(bChanged){ rect.right=rect.left+iWidth; rect.bottom=rect.top+iHeight; } return bChanged; } #define MAX_ENUMEDWINDOWS 50 int iCurrentRectWindow=0; RECT rActiveWindowsRect[MAX_ENUMEDWINDOWS]; HWND rActiveWindowsHwnd[MAX_ENUMEDWINDOWS]; BOOL CALLBACK EnumActiveWindowsProc(HWND hwnd, LPARAM lParam) { if(::IsWindowVisible(hwnd) && hwnd!=(HWND)lParam){ if(!::IsZoomed(hwnd)){ WINDOWPLACEMENT wndPl; memset(&wndPl,0,sizeof(wndPl)); wndPl.length=sizeof(wndPl); if(::GetWindowPlacement(hwnd,&wndPl)){ if(wndPl.showCmd==SW_SHOWNORMAL){ if(iCurrentRectWindow<MAX_ENUMEDWINDOWS){ if(!IsWindowsSystemWnd(hwnd,1) && IsWindowStylesOk(hwnd)){ ::GetWindowRect(hwnd,&rActiveWindowsRect[iCurrentRectWindow]); rActiveWindowsHwnd[iCurrentRectWindow]=hwnd; iCurrentRectWindow++; } }else{ return FALSE; } } } } } return TRUE; } void SetCorrectWindowPos(HWND hWin) { if(hWin==NULL || !IsWindow(hWin)){ return; } if(IsZoomed(hWin)){ return; } int iTriggered=0; RECT pos,posBackup; BOOL bRes=FALSE; HWND hWinWith=NULL; memset(rActiveWindowsRect,0,MAX_ENUMEDWINDOWS*sizeof(RECT)); iCurrentRectWindow=0; if(!::GetWindowRect(hWin,&pos) || (pos.left==-32000 && pos.top==-32000)){ return; } TRACE2("Snapping window x=%i, y=%i\n",pos.left,pos.top); if((DWORD)::GetProp(hWin,"WKP_INVIS")==1){ return; } // Есть ли у окна владелец BOOL bChild=FALSE; DWORD dwStyle=::GetWindowLong(hWin,GWL_STYLE); if(::GetParent(hWin)!=NULL || (dwStyle & WS_CHILD)!=0){//::GetAncestor(hWin,GA_PARENT)!=NULL bChild=TRUE; } memcpy(&posBackup,&pos,sizeof(posBackup)); int iWidth=(pos.right-pos.left); int iHeight=(pos.bottom-pos.top); if(rtScreenSize.left==0 && rtScreenSize.right==0 && rtScreenSize.top==0 && rtScreenSize.bottom==0){ ::SystemParametersInfo(SPI_GETWORKAREA,0,&rtScreenSize,0); } if(iWidth>0 && iHeight>0 && (iWidth<rtScreenSize.right-rtScreenSize.left) && (iHeight<rtScreenSize.bottom-rtScreenSize.top)){ if(!bChild && (hookData.bSnapToScreen && hookData.iSnapToScreenStickness>0)){ BOOL bSingleRes=TestSticknessWithRect(pos,rtScreenSize,hookData.iSnapToScreenStickness); if(bSingleRes){ iTriggered=2; } bRes|=bSingleRes; } if(hookData.bSnapToScreenForce && ((pos.left<rtScreenSize.left)||(pos.top<rtScreenSize.top)||(pos.right>rtScreenSize.right)||(pos.bottom>rtScreenSize.bottom))){ // Принудительно вертаем внутрь экрана BOOL bScreenRes=FALSE; // Сдвигаем только если окно помещается внутрь монитора обоими краями if(pos.left<rtScreenSize.left){ bScreenRes|=TRUE; iTriggered=3; pos.left=rtScreenSize.left; } if(pos.top<rtScreenSize.top){ bScreenRes|=TRUE; iTriggered=4; pos.top=rtScreenSize.top; } if(pos.right>rtScreenSize.right){ bScreenRes|=TRUE; iTriggered=5; pos.left=rtScreenSize.right-iWidth; } if(pos.bottom>rtScreenSize.bottom){ bScreenRes|=TRUE; iTriggered=6; pos.top=rtScreenSize.bottom-iHeight; } if(bScreenRes){ pos.right=pos.left+iWidth; pos.bottom=pos.top+iHeight; } bRes|=bScreenRes; } } if(!bChild && hookData.bSnapMovements && hookData.iStickness>0){ // Не чаще раза в 0.5 секунды if(GetTickCount()-dwSnapWindowTimeData>500){ dwSnapWindowTimeData=GetTickCount(); ::EnumWindows(EnumActiveWindowsProc,LPARAM(hWin)); for(int i=0;i<iCurrentRectWindow;i++){ if(rActiveWindowsRect[i].left!=rtScreenSize.left || rActiveWindowsRect[i].right!=rtScreenSize.right || rActiveWindowsRect[i].top!=rtScreenSize.top || rActiveWindowsRect[i].bottom!=rtScreenSize.bottom){ BOOL bSingleRes=TestSticknessWithRect(pos,rActiveWindowsRect[i],hookData.iStickness); bRes|=bSingleRes; // Test if(bSingleRes){ iTriggered=1; hWinWith=rActiveWindowsHwnd[i]; // ::SetWindowPos(hWinWith,hWin,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW|SWP_NOACTIVATE); if(GetAsyncKeyState(VK_RWIN)<0){ HDC dcScreen=::CreateDC("DISPLAY", NULL, NULL, NULL); ::FrameRect(dcScreen,&rActiveWindowsRect[i],(HBRUSH)::GetStockObject(BLACK_BRUSH)); ::DeleteDC(dcScreen); } } } } } } if(bRes){ // Смотрим что ничего не изменилось RECT pos2; ::GetWindowRect(hWin,&pos2); if((pos.right-pos.left)!=(pos2.right-pos2.left)){ return; } if((pos.bottom-pos.top)!=(pos2.bottom-pos2.top)){ return; } if(IsZoomed(hWin)){ return; } ::SetWindowPos(hWin,NULL,pos.left,pos.top,pos.right-pos.left,pos.bottom-pos.top,SWP_NOZORDER|SWP_ASYNCWINDOWPOS|SWP_NOACTIVATE); } } bool PatternMatch(const char* s, const char* mask) { const char* cp=0; const char* mp=0; for (; *s&&*mask!='*'; mask++,s++){ if (*mask!=*s && *mask!='?'){ return 0; } } for (;;) { if (!*s){ while (*mask=='*'){ mask++; } return !*mask; } if (*mask=='*'){ if (!*++mask){ return 1; } mp=mask; cp=s+1; continue; } if (*mask==*s||*mask=='?'){ mask++; s++; continue; } mask=mp; s=cp++; } return true; } void SkipBlanks(const char*& szPos) { while(*szPos==' ' || *szPos=='\t' || *szPos=='\r' || *szPos=='\n'){ szPos++; } } bool PatternMatchList(const char* s, const char* mask, int& iCurrentAction) { if(mask==NULL || *mask==NULL){ return false; } if(s==NULL || *s==NULL){ return false; } const char* szPos=mask; SkipBlanks(szPos); if(szPos==NULL || *szPos==NULL){ return false; } int iDefAction=iCurrentAction; while(szPos!=NULL && *szPos!=0){ SkipBlanks(szPos); iCurrentAction=iDefAction; const char* szPos2=strpbrk(szPos,"\r\n"); if(szPos2==NULL){ szPos2=szPos+(strlen(szPos)); } if(szPos2<=szPos){ break; } char szMask[256]; memset(szMask,0,sizeof(szMask)); memcpy(szMask,szPos,size_t(szPos2-szPos)); if(szMask[0]!=0){ const char* szPattern=szMask; if(memicmp(szMask,"Floater:",8)==0){ iCurrentAction=9; szPattern=szMask+8; } if(memicmp(szMask,"Minimize:",9)==0){ iCurrentAction=5; szPattern=szMask+9; } if(memicmp(szMask,"Rollup:",7)==0){ iCurrentAction=WKGetPluginContainer()->getOption(-1)?7:8; szPattern=szMask+7; } if(memicmp(szMask,"Hide:",5)==0){ iCurrentAction=3; szPattern=szMask+5; } if(memicmp(szMask,"Close:",6)==0){ iCurrentAction=10; szPattern=szMask+6; } if(memicmp(szMask,"Tray:",5)==0){ iCurrentAction=2; szPattern=szMask+5; } SkipBlanks(szPattern); if(PatternMatch(s,szPattern)){ return true; } } szPos=szPos2; } return false; } bool PatternMatchList2(const char* s, const char* mask) { if(mask==NULL || *mask==NULL){ return false; } if(s==NULL || *s==NULL){ return false; } const char* szPos=mask; SkipBlanks(szPos); if(szPos==NULL || *szPos==NULL){ return false; } while(szPos!=NULL && *szPos!=0){ SkipBlanks(szPos); const char* szPos2=strpbrk(szPos,";"); if(szPos2==NULL){ szPos2=szPos+(strlen(szPos)); } if(szPos2<=szPos){ break; } char szMask[256]; memset(szMask,0,sizeof(szMask)); memcpy(szMask,szPos,size_t(szPos2-szPos)); if(szMask[0]!=0){ const char* szPattern=szMask; SkipBlanks(szPattern); if(PatternMatch(s,szPattern)){ return true; } } szPos=szPos2; if(*szPos==';'){ szPos++; } } return false; } BOOL IsWindowInChain(HWND hChild, HWND hTest) { if(hChild==0){ return 0; } while(hTest!=hChild){ HWND hPre=::GetWindow(hChild,GW_OWNER); if(hPre==0){ hPre=::GetParent(hChild); } if(hPre==0){ return 0; } hChild=hPre; } return 1; } // Forward declaration - from <winuser.h> #ifndef STATE_SYSTEM_OFFSCREEN #define CCHILDREN_TITLEBAR 5 #define STATE_SYSTEM_UNAVAILABLE 0x00000001 // Disabled #define STATE_SYSTEM_INVISIBLE 0x00008000 #define STATE_SYSTEM_OFFSCREEN 0x00010000 typedef struct tagTITLEBARINFO { DWORD cbSize; RECT rcTitleBar; DWORD rgstate[CCHILDREN_TITLEBAR+1]; } TITLEBARINFO, *PTITLEBARINFO, *LPTITLEBARINFO; #endif typedef BOOL (WINAPI *_GetTitleBarInfo)(HWND hwnd, PTITLEBARINFO pti); typedef UINT (WINAPI *_RealGetWindowClass)(HWND hwnd, LPTSTR pszType, UINT cchType); HWND hWndNoDups=0; DWORD WINAPI AutoHideWindow_InThread(LPVOID pData) { TRACETHREAD; HWND hWin=(HWND)pData; if(hWin==NULL || pCallbackInterface==NULL){ return 0; } if(hWndNoDups==hWin || !IsWindow(hWin)){ return 0; } hWndNoDups=hWin; HINSTANCE hUser32=LoadLibrary("User32.dll"); // Первый этап - есть кнопка Minimize/Maximize TITLEBARINFO iTI; memset(&iTI,0,sizeof(iTI)); iTI.cbSize=sizeof(iTI); _GetTitleBarInfo tbi=NULL; if(hUser32){ // Считываем данные о заголовке окна tbi=(_GetTitleBarInfo)GetProcAddress(hUser32,"GetTitleBarInfo"); } if(!tbi || (*tbi)(hWin,&iTI)){ // Смотрим на кнопки... if(((iTI.rgstate[2] & STATE_SYSTEM_UNAVAILABLE)==0 && (iTI.rgstate[3] & STATE_SYSTEM_UNAVAILABLE)==0) && ((iTI.rgstate[2] & STATE_SYSTEM_INVISIBLE)==0 && (iTI.rgstate[3] & STATE_SYSTEM_INVISIBLE)==0) && ((iTI.rgstate[2] & STATE_SYSTEM_OFFSCREEN)==0 && (iTI.rgstate[3] & STATE_SYSTEM_OFFSCREEN)==0)){ // Второй этап - заголовок char szTitle[256]=""; memset(szTitle,0,sizeof(szTitle)); ::GetWindowText(hWin,szTitle,sizeof(szTitle)-1); // Смотрим на заголовок if(szTitle[0]!=0){ // Определяем префик действия int iCurrentAction=2; if(PatternMatchList(szTitle,hookData.szAutoMinimizeTitle,iCurrentAction)){ if(hookData.iINACTSEC==0){// Ожидание - если пользователь кликнул в трей, то чтоб успело прийти по адресу сообщение //Sleep(500); WaitForSingleObject(hHookerEventStop,500); }else{ //Sleep(hookData.iINACTSEC*1000); WaitForSingleObject(hHookerEventStop,hookData.iINACTSEC*1000); } if(pCallbackInterface && IsWindow(hWin)){ // Если приложение все еще не активно, то делаем что мы хотели! HWND hCurActiveWnd=::GetForegroundWindow(); // но! Если активное приложение - чилд нужного, то все равно ничего не делаем! if(!IsWindowInChain(hCurActiveWnd,hWin)){ if(pCallbackInterface && pCallbackInterface->GetWKState()==0){// Если в багдаде все еще спокойно... pCallbackInterface->ProcessWindow(hWin,iCurrentAction); ::SetForegroundWindow(hCurActiveWnd); } } } } } } } if(hUser32){ FreeLibrary(hUser32); } return 0; } #include <multimon.h> /*typedef struct IPv6_tagMONITORINFO { DWORD cbSize; RECT rcMonitor; RECT rcWork; DWORD dwFlags; } IPv6_MONITORINFO, *IPv6_LPMONITORINFO; #define MONITOR_DEFAULTTONEAREST 0x00000002 #if !defined(HMONITOR_DECLARED) && (_WIN32_WINNT < 0x0500) DECLARE_HANDLE(HMONITOR); #define HMONITOR_DECLARED #endif*/ RECT GetScreenRect(RECT* rtBase, BOOL* bMultiMonsOut) { static CRect rtRes(0,0,0,0); static BOOL bMultyMons=FALSE; if(rtRes.Width()==0 && rtRes.Height()==0){ if(rtBase!=NULL && GetSystemMetrics(80/*SM_CMONITORS*/)>1){ MONITORINFO mi; memset(&mi,0,sizeof(mi)); mi.cbSize = sizeof(mi); HMONITOR hMonitor=NULL; hMonitor = MonitorFromRect(rtBase, MONITOR_DEFAULTTONEAREST); if(hMonitor != NULL){ bMultyMons=TRUE; ::GetMonitorInfo(hMonitor, &mi); rtRes=mi.rcWork; } } if(rtRes.Width()==0 && rtRes.Height()==0){ bMultyMons=FALSE; CRect DesktopDialogRect; ::SystemParametersInfo(SPI_GETWORKAREA,0,&DesktopDialogRect,0); rtRes=DesktopDialogRect; } } if(bMultiMonsOut){ *bMultiMonsOut=bMultyMons; } return rtRes; } // 10 - вытянуть по горизонтали // 11 - вытянуть по вертикали // 12 - приклеить по горизонтали // 13 - приклеить по вертикали // 15 - вытянуть ul // 16 - вытянуть ur // 17 - вытянуть dl // 18 - вытянуть dr // 19 - приклеить ul // 20 - приклеить ur // 21 - приклеить dl // 22 - приклеить dr // 23 - Закрыть приложение long g_lSpanWindowAction=0; long g_lSpanWindowActionDsc=0; DWORD WINAPI SpanWindow_InThread(LPVOID pData) { TRACETHREAD; HWND SpanWindowHwnd=(HWND)pData; SimpleTracker lock(g_IzWndAttachInProgress); if(SpanWindowHwnd){ static long lc=0; if(lc>0){ // Уже идет обработка // и перемещение окна return 0; } SimpleTracker lock(lc); // Ждем пока средняя кнопка мыши не будет отпущена while(GetAsyncKeyState(VK_RBUTTON)<0 || GetAsyncKeyState(VK_MBUTTON)<0){ Sleep(200); } // Проверяем что мы все еще над границей окна POINT curpoint; GetCursorPos(&curpoint); int lRes=SendMessage(SpanWindowHwnd,WM_NCHITTEST,0,MAKELONG(curpoint.x,curpoint.y)); if(lRes==0 || !(lRes>=HTLEFT && lRes<=HTBORDER)){ return 0; } RECT rt,rtBackup,rtScreen,rtParentOrig; rtParentOrig.left=rtParentOrig.top=rtParentOrig.right=rtParentOrig.bottom=0; ::GetWindowRect(SpanWindowHwnd,&rt); rtBackup.left=rt.left; rtBackup.top=rt.top; rtBackup.right=rt.right; rtBackup.bottom=rt.bottom; HWND hParent=GetParent(SpanWindowHwnd); if(hParent){ ::GetWindowRect(hParent,&rtScreen); rtParentOrig.left=rtScreen.left; rtParentOrig.top=rtScreen.top; rtParentOrig.right=rtScreen.right; rtParentOrig.bottom=rtScreen.bottom; // Переводим в клиентские координаты POINT pt; pt.x=rt.left; pt.y=rt.top; ScreenToClient(hParent,&pt); rt.left=pt.x; rt.top=pt.y; pt.x=rt.right; pt.y=rt.bottom; ScreenToClient(hParent,&pt); rt.right=pt.x; rt.bottom=pt.y; // Трудный выбор. у Максимизированного приложения - к паренту, иначе - к экрану rtScreen.right-=rtScreen.left; rtScreen.bottom-=rtScreen.top; rtScreen.top=0; rtScreen.left=0; if(GetWindow(SpanWindowHwnd,GW_OWNER)==0){ rtParentOrig.left=rtParentOrig.top=rtParentOrig.right=rtParentOrig.bottom=0; }else{ rtScreen=GetScreenRect(&rt,NULL); // Перводим координаты DWORD dwW=rtScreen.right-rtScreen.left; DWORD dwH=rtScreen.bottom-rtScreen.top; rtScreen.left=rtScreen.left-rtParentOrig.left; rtScreen.top=rtScreen.top-rtParentOrig.top; rtScreen.right=rtScreen.left+dwW; rtScreen.bottom=rtScreen.top+dwH; } }else{ rtScreen=GetScreenRect(&rt,NULL); } if(g_lSpanWindowAction==10 || g_lSpanWindowAction==12 || g_lSpanWindowAction>=15){ if(g_lSpanWindowAction==12 || g_lSpanWindowAction>=19){ if(g_lSpanWindowActionDsc==HTLEFT || g_lSpanWindowAction==15 || g_lSpanWindowAction==17 || g_lSpanWindowAction==19 || g_lSpanWindowAction==21){ rt.left=rtScreen.left; rt.right=rt.left+(rtBackup.right-rtBackup.left); }else{ rt.right=rtScreen.right; rt.left=rt.right-(rtBackup.right-rtBackup.left); } } if(g_lSpanWindowAction==10 || (g_lSpanWindowAction>=15 && g_lSpanWindowAction<19)){ // Читаем свойсвта... DWORD dwPropL=(DWORD)::GetProp(SpanWindowHwnd,"WKP_OLDWNDLEFT"); DWORD dwPropR=(DWORD)::GetProp(SpanWindowHwnd,"WKP_OLDWNDRIGHT"); if(dwPropL==0 && dwPropR==0){ ::SetProp(SpanWindowHwnd,"WKP_OLDWNDLEFT",(HANDLE)rt.left); ::SetProp(SpanWindowHwnd,"WKP_OLDWNDRIGHT",(HANDLE)rt.right); rt.left=rtScreen.left; rt.right=rtScreen.right; }else{ rt.left=dwPropL; rt.right=dwPropR; ::RemoveProp(SpanWindowHwnd,"WKP_OLDWNDLEFT"); ::RemoveProp(SpanWindowHwnd,"WKP_OLDWNDRIGHT"); } } } if(g_lSpanWindowAction==11 || g_lSpanWindowAction==13 || g_lSpanWindowAction>=15){ if(g_lSpanWindowAction==13 || g_lSpanWindowAction>=19){ if(g_lSpanWindowActionDsc==HTTOP || g_lSpanWindowAction==15 || g_lSpanWindowAction==16 || g_lSpanWindowAction==19 || g_lSpanWindowAction==20){ rt.top=rtScreen.top; rt.bottom=rt.top+(rtBackup.bottom-rtBackup.top); }else{ rt.bottom=rtScreen.bottom; rt.top=rt.bottom-(rtBackup.bottom-rtBackup.top); } }else if(g_lSpanWindowAction==11 || (g_lSpanWindowAction>=15 && g_lSpanWindowAction<19)){ DWORD dwPropT=(DWORD)::GetProp(SpanWindowHwnd,"WKP_OLDWNDTOP"); DWORD dwPropB=(DWORD)::GetProp(SpanWindowHwnd,"WKP_OLDWNDBOTTOM"); if(dwPropT==0 && dwPropB==0){ ::SetProp(SpanWindowHwnd,"WKP_OLDWNDTOP",(HANDLE)rt.top); ::SetProp(SpanWindowHwnd,"WKP_OLDWNDBOTTOM",(HANDLE)rt.bottom); rt.top=rtScreen.top; rt.bottom=rtScreen.bottom; }else{ rt.top=dwPropT; rt.bottom=dwPropB; ::RemoveProp(SpanWindowHwnd,"WKP_OLDWNDTOP"); ::RemoveProp(SpanWindowHwnd,"WKP_OLDWNDBOTTOM"); } } } ::MoveWindow(SpanWindowHwnd,rt.left+rtParentOrig.left,rt.top+rtParentOrig.top,rt.right-rt.left,rt.bottom-rt.top,TRUE); } return 0; } // WMUSER+... // 0 - бездействие // 1 - установить хуки // 2 - подогнать окно из pHookAction_HWND // 3 - спрятать в трей // 4 - проверить и спрятать если сходится паттерн // 5 - показать WK-menu на активном окне // 6 - Rollup window // 7 - спрятать целиком // 8 - appinfo // 9 - qrun с окна // 10 - вытянуть по горизонтали // 11 - вытянуть по вертикали // 12 - приклеить по горизонтали // 13 - приклеить по вертикали // 14 - snapwindow // 15 - вытянуть ul // 16 - вытянуть ur // 17 - вытянуть dl // 18 - вытянуть dr // 19 - приклеить ul // 20 - приклеить ur // 21 - приклеить dl // 22 - приклеить dr // 23 - создать ярлык // 24 - убить приложение // 25 - во флоатер anyway // 26 - в tray anyway // 27 - сменить онтоп // 30 - запаузить/распаузить ВК // 31 - список рисентофолдеров // 35 - опдейт рисентов // wParam=HWND // lParam=Additional info #define SAVE_REGKEY "SOFTWARE\\WiredPlane\\WireKeys\\WKHelper" CRITICAL_SECTION csMainThread; DWORD WINAPI GlobalHooker_WKHelper(LPVOID pData) { TRACETHREAD; ::EnterCriticalSection(&csMainThread); // Создаем очередь сообщений MSG msg; ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); SetEvent(hHookerEventDone);// Чтобы сцепить ожидающих while(GetMessage(&msg,0,0,0)>0){ if(msg.message==WM_CLOSE || (msg.message==WM_ENABLE && msg.wParam==0)){ dwHookerThread=0; BOOL bResult=SetHook(FALSE,0); } if(msg.message==WM_ENABLE && msg.wParam!=0){ char szHookLibPath[MAX_PATH]={0}; WKGetPluginContainer()->GetWKPluginsDirectory(szHookLibPath,MAX_PATH); BOOL bResult=SetHook(TRUE,szHookLibPath); dwHookerThread=dwHookerThreadInThisDLL; /*if(!bResult && pCallbackInterface){ pCallbackInterface->ShowPopup("WKHelper plugin failed to initialize itself","Plugin error",5000); }*/ } if(msg.message==WM_COMMAND){ if(msg.lParam==0){ memset(g_szStartUpWindowName,0,sizeof(g_szStartUpWindowName)); GetWindowText((HWND)msg.wParam,g_szStartUpWindowName,sizeof(g_szStartUpWindowName)-1); WKPluginOptions(0); } } if(msg.message>=WM_USER && pCallbackInterface!=NULL){ if(msg.message-WM_USER==999){ pCallbackInterface->Sound(0); } HWND pHookAction_HWND=(HWND)msg.wParam; DWORD lHookerDesiredActionDsc=(DWORD)msg.lParam; DWORD lHookerDesiredAction=msg.message-WM_USER; if(pHookAction_HWND!=NULL){ #ifdef _DEBUG /*if(lHookerDesiredAction>=10 && lHookerDesiredAction<=22){ char s[1000]=""; sprintf(s,"Приклеиваем окно... %i",lHookerDesiredAction); pCallbackInterface->ShowOSD(s,9000); }*/ #endif /*if(lHookerDesiredAction==10 || lHookerDesiredAction==11 && lCurrentThreadActionInProgress==lHookerDesiredAction){ continue; }*/ static long lCurrentThreadActionInProgress=lHookerDesiredAction; if(lHookerDesiredAction==23){ pCallbackInterface->ProcessWindow(pHookAction_HWND,11); lHookerDesiredAction=0; } if(lHookerDesiredAction==24){ pCallbackInterface->ProcessWindow(pHookAction_HWND,12); lHookerDesiredAction=0; } if(lHookerDesiredAction==25){ pCallbackInterface->ProcessWindow(pHookAction_HWND,14); lHookerDesiredAction=0; } if(lHookerDesiredAction==26){ pCallbackInterface->ProcessWindow(pHookAction_HWND,15); lHookerDesiredAction=0; } if(lHookerDesiredAction==27){ pCallbackInterface->ProcessWindow(pHookAction_HWND,1); CheckWindwOnTop(pHookAction_HWND); lHookerDesiredAction=0; } if(lHookerDesiredAction==14){ // Проверяем подходит ли заголовок if(strlen(plugData.szExclusions)>0){ char szTitle[256]=""; ::GetWindowText(pHookAction_HWND,szTitle,sizeof(szTitle)); if(strlen(szTitle)>0 && PatternMatchList2(szTitle,plugData.szExclusions)){ lHookerDesiredAction=0; } } } if(lHookerDesiredAction==2 || lHookerDesiredAction==6 || lHookerDesiredAction==7){ // Ждем пока правая кнопка мыши не будет отпущена while(GetAsyncKeyState(VK_RBUTTON)<0){ Sleep(200); } } if(lHookerDesiredAction==2 || lHookerDesiredAction==7){ pCallbackInterface->ProcessWindow(pHookAction_HWND,(lHookerDesiredAction==7)?3:2); } if(lHookerDesiredAction==3){ if(pCallbackInterface->GetWKState()==0){// Если в багдаде все спокойно... pCallbackInterface->ShowWKMenu(pHookAction_HWND); } } if(lHookerDesiredAction==14){ SetCorrectWindowPos(pHookAction_HWND); } if(lHookerDesiredAction==6){ pCallbackInterface->ProcessWindow(pHookAction_HWND,WKGetPluginContainer()->getOption(-1)?7:8); } if(lHookerDesiredAction==8){ pCallbackInterface->ShowAppInfo(pHookAction_HWND); } if(lHookerDesiredAction==9){ pCallbackInterface->AddQrunFromHWND(pHookAction_HWND); } if(lHookerDesiredAction>=10 && lHookerDesiredAction<=22 && lHookerDesiredAction!=14){ g_lSpanWindowAction=lHookerDesiredAction; g_lSpanWindowActionDsc=lHookerDesiredActionDsc; FORK(SpanWindow_InThread,pHookAction_HWND); } if(lHookerDesiredAction==4){ if(pCallbackInterface->GetWKState()==0 && pCallbackInterface->GetWKMainWindow()){// Если в багдаде все спокойно... FORK(AutoHideWindow_InThread,pHookAction_HWND); } } if(lHookerDesiredAction==30){ pCallbackInterface->PauseWKCompletely(msg.lParam); lHookerDesiredAction=0; } if(lHookerDesiredAction>=31 && lHookerDesiredAction<=34){ ::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)pHookAction_HWND); char sz[128]={0}; sprintf(sz,"[ID=@PLUGIN-WP_OpenWithExt-%i]",lHookerDesiredAction-31); pCallbackInterface->StartQuickRunByNameX(sz,0,0,0); lHookerDesiredAction=0; } if(lHookerDesiredAction==35){ DWORD dwTID=(DWORD)pCallbackInterface->getOptionEx(1346,0); if(dwTID){ PostThreadMessage(dwTID,WM_TIMECHANGE,0,0); } lHookerDesiredAction=0; } lCurrentThreadActionInProgress=0; } } hLastNCHittestWnd=0; dwLastNCHittestRes=0; SetEvent(hHookerEventDone); if(msg.message==WM_CLOSE || msg.message==WM_QUIT){ break; } } ::LeaveCriticalSection(&csMainThread); SetEvent(hHookerEventStop); return 0; } DWORD WINAPI GetThreadHandle() { return dwHookerThreadInThisDLL; } void CheckWndForMin(HWND hWind); void CheckWKPause(); DWORD WINAPI GlobalHooker_WKHelper_Timer(LPVOID) { hLastActiveWnd=0; while(WaitForSingleObject(hPluginStop,1000)!=WAIT_OBJECT_0){ HWND hwndNew=GetForegroundWindow(); if(hLastActiveWnd!=hwndNew){ if(WKUtils::isWKUpAndRunning()){ if(hookData.bCatchAutoMinimize && dwHookerThread>0){ if(IsWindowVisible(hwndNew)){ DWORD dwStyle=::GetWindowLong(hLastActiveWnd,GWL_STYLE); DWORD dwStyleEx=::GetWindowLong(hLastActiveWnd,GWL_EXSTYLE); if(GetAsyncKeyState(VK_SHIFT)>=0 && ::GetParent(hLastActiveWnd)==NULL && (dwStyle & WS_CHILD)==0){//(dwStyleEx & WS_EX_APPWINDOW)!=0 && ::GetAncestor(hwnd,GA_PARENT)==NULL && (dwStyleEx & WS_EX_TOOLWINDOW)==0 && PostThreadMessage(dwHookerThread,WM_USER+4,WPARAM(hLastActiveWnd),0); } } } if(hookData.szAutoMinToTray[0]!=0 || hookData.szAutoMinToFloat[0]!=0){ //char c[100]={0};GetWindowText((HWND)hLastActiveWnd,c,100); //char s[100]={0};GetClassName((HWND)hLastActiveWnd,s,100); WINDOWPLACEMENT pl; memset(&pl,0,sizeof(pl)); pl.length=sizeof(pl); if(::GetWindowPlacement(hLastActiveWnd,&pl) && pl.showCmd==SW_SHOWMINIMIZED){ CheckWndForMin(hLastActiveWnd); } } } CheckWKPause(); hLastActiveWnd=hwndNew; } } return 0; } extern char szItem_ToTray[64]; extern char szItem_Compl[64]; extern char szItem_AddMenu[64]; extern char szItem_FavMenu[64]; extern char szItem_OnTopState[64]; extern char szItem_ToTitle[64]; extern char szItem_Info[64]; extern char szItem_QRun[64]; extern char szItem_SCut[64]; extern char szItem_Kill[64]; extern HWND g_WKWnd; HANDLE hHookerThread=0; int WINAPI WKPluginInit(WKCallbackInterface* init) { if(init){ // Version... char szVer[32]=""; init->GetWKVersion(szVer); DWORD dwBuild=MAKEWORD(szVer[30],szVer[31]); if(dwBuild<348){ init->ShowAlert("Sorry, this plugin can be used with WireKeys 3.4.8 and higher only","Plugin error"); return 0; } } pCallbackInterface=init; strcpy(szItem_ToTray,_pl("Hide to tray")); strcpy(szItem_Compl,_pl("Hide completely")); strcpy(szItem_AddMenu,_pl("Additional menu")); strcpy(szItem_FavMenu,_pl("Recent folders")); strcpy(szItem_OnTopState,_pl("Change 'on top'")); strcpy(szItem_ToTitle,_pl("Rollup to title")); strcpy(szItem_Info,_pl("Application info")); strcpy(szItem_QRun,_pl("Add to quick-run")); strcpy(szItem_SCut,_pl("Create shortcut")); strcpy(szItem_Kill,_pl("Kill application")); strcat(szItem_AddMenu,"\t..."); strcat(szItem_FavMenu,"\t..."); // Screenshoting... msgGetScreenshot=RegisterWindowMessage("WK_GETSNAP"); // Working thread... g_WKWnd=init->GetWKMainWindow(); DWORD dwThread=0,dwHookerThreadInThisDLL2=0; hHookerEventDone=::CreateEvent(NULL,FALSE,FALSE,NULL); hHookerEventStop=::CreateEvent(NULL,FALSE,FALSE,NULL); hPluginStop=::CreateEvent(NULL,FALSE,FALSE,NULL); hHookerThread=::CreateThread(NULL, 0, GlobalHooker_WKHelper, NULL, 0, &dwHookerThreadInThisDLL); HANDLE hHookerThread2=::CreateThread(NULL, 0, GlobalHooker_WKHelper_Timer, NULL, 0, &dwHookerThreadInThisDLL2); CloseHandle(hHookerThread2); WaitForSingleObject(hHookerEventDone,INFINITE); PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,1,0); return 1; } extern HHOOK g_hhook1; extern HHOOK g_hhook2; extern HHOOK g_hhook3; extern HHOOK g_hhook4; void SetDefValues() { hookData.iStickness=30; hookData.bSnapMovements=0; hookData.bCatchRollDock=1; hookData.bCatchRollExpand=1; hookData.bSnapToScreen=0; hookData.iSnapToScreenStickness=15; hookData.iINACTSEC=1; hookData.bInjectItems=1; hookData.bOntopicon=0; hookData.bSnapToScreenForce=0; hookData.bInjectIt1=1; hookData.bInjectIt2=0; hookData.bInjectIt3=0; hookData.bInjectIt4=1; hookData.bInjectIt5=1; hookData.bInjectIt6=0; hookData.bInjectIt7=1; hookData.bBlockFocuStealing=0; } int WINAPI WKPluginStart() { ::InitializeCriticalSection(&csMainThread); ::SystemParametersInfo(SPI_GETWORKAREA,0,&rtScreenSize,0); g_hhook1 = NULL; g_hhook2 = NULL; g_hhook3 = NULL; g_hhook4 = NULL; memset(&plugData,0,sizeof(plugData)); memset(&hookData,0,sizeof(hookData)); memset(g_szApplications,0,sizeof(g_szApplications[0])*MAX_APPS); SetDefValues(); /*// Reading from registry... CRegKey key; if(key.Open(HKEY_CURRENT_USER, SAVE_REGKEY)==ERROR_SUCCESS && key.m_hKey!=NULL){ DWORD lSize = sizeof(hookData),dwType=0; RegQueryValueEx(key.m_hKey,"WKHelperOptions",NULL, &dwType,(LPBYTE)(&hookData), &lSize); }*/ return 1; } BOOL SaveToReg() { /*if(!isMemEmpty(&hookData,sizeof(hookData))){ // Saving to registry... CRegKey key; if(key.Open(HKEY_CURRENT_USER, SAVE_REGKEY)!=ERROR_SUCCESS){ key.Create(HKEY_CURRENT_USER, SAVE_REGKEY); } if(key.m_hKey!=NULL){ RegSetValueEx(key.m_hKey,"WKHelperOptions",0,REG_BINARY,(BYTE*)(&hookData),sizeof(hookData)); } }*/ return TRUE; } int WINAPI WKPluginStop() { SaveToReg(); dwHookerThread=0; SetEvent(hPluginStop); //---------------------- if(!pCallbackInterface->getOption(WKOPT_ISSHUTDOWN)){ PostThreadMessage(dwHookerThreadInThisDLL,WM_CLOSE,0,0); ::WaitForSingleObject(hHookerEventStop,2000); //::EnterCriticalSection(&csMainThread); //::LeaveCriticalSection(&csMainThread); } DWORD dwTRes=0; if(GetExitCodeThread(hHookerThread,&dwTRes) && dwTRes==STILL_ACTIVE){ //TerminateThread(hHookerThread,66); //SuspendThread(hHookerThread); } ::CloseHandle(hHookerEventDone); ::CloseHandle(hHookerEventStop); ::CloseHandle(hHookerThread); ::DeleteCriticalSection(&csMainThread); pCallbackInterface=0; return 1; } int WINAPI WKDesktopSwitching(BOOL bPaused) { if(bPaused){ PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,0,0); }else{ PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,1,0); } return 1; } int WINAPI _WKPluginPause(BOOL bPaused) { if(bPaused){ PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,0,0); }else{ PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,1,0); } ::WaitForSingleObject(hHookerEventDone,500); return 1; } extern HWND hOpenedOptions; DWORD WINAPI CallOptions(LPVOID pData) { static BOOL bInProc=0; if(bInProc){ ::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hOpenedOptions); return 0; } bInProc++; HWND hParent=(HWND)pData; PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,0,0); ::WaitForSingleObject(hHookerEventDone,500); DialogBox(g_hinstDll,MAKEINTRESOURCE(IDD_OPTIONS),(HWND)(WKGetPluginContainer()->getOptionEx(2,0)),OptionsDialogProc); if(!WKUtils::isWKUpAndRunning()){ return 0; } SaveToReg(); PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,1,0); ::WaitForSingleObject(hHookerEventDone,500); // Pushing changed options back into WireKeys if(pCallbackInterface){ pCallbackInterface->PushMyOptions(0); } bInProc--; return 1; } HFONT hfCreated=0; HWND hOpenedOptions2=0; int CALLBACK OptionsDialogProc2(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { if(uMsg==WM_INITDIALOG){ ::SetWindowLong(hwndDlg,GWL_EXSTYLE,WS_EX_APPWINDOW|::GetWindowLong(hwndDlg,GWL_EXSTYLE)); PostMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hwndDlg); hOpenedOptions=hwndDlg; // Локализация ::SetWindowText(GetDlgItem(hwndDlg,IDC_STATIC99),_pl("Written by Ilja Razinkov @2008")); ::SetWindowText(hwndDlg,_pl("True docking")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_EDIT),""); ::SetWindowText(GetDlgItem(hwndDlg,IDC_BT_UP),_pl("Move up")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_BT_DOWN),_pl("Move down")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_BT_REM),_pl("Remove")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_BT_ADD),_pl("Add")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_STATIC_M),_pl("Here you can type window`s titles. Noted windows will be docked to the specified screen edges. To type title mask, use '*' as a wildcard for partial matches")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_CHECK_L),_pl("Left")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_CHECK_R),_pl("Right")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_CHECK_T),_pl("Top")); ::SetWindowText(GetDlgItem(hwndDlg,IDC_CHECK_B),_pl("Bottom")); ::SetWindowText(GetDlgItem(hwndDlg,IDOPTIONS),_pl("Options")); if(g_DefDockTitle[0]!=0){ ::SetWindowText(GetDlgItem(hwndDlg,IDC_EDIT),g_DefDockTitle); } g_DefDockTitle[0]=0; LOGFONT lg; HFONT hf=(HFONT)::SendMessage(GetDlgItem(hwndDlg,IDC_LIST),WM_GETFONT,0,0); ::GetObject(hf,sizeof(lg),&lg); strcpy(lg.lfFaceName,"Courier"); hfCreated=CreateFontIndirect(&lg); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),WM_SETFONT,WPARAM(hfCreated),0); int iCI=0; while(g_szApplications[iCI][0]!=0 && iCI<MAX_APPS){ SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_ADDSTRING,0,(LPARAM)g_szApplications[iCI]); iCI++; } } if(uMsg==WM_NCDESTROY){ ::DeleteObject(hfCreated); hfCreated=0; } if(uMsg==WM_KEYDOWN){ if(GetKeyState(VK_CONTROL)<0){ if(wParam==VK_RETURN){ uMsg=WM_COMMAND; wParam=IDOK; } } } if(uMsg==WM_DROPFILES){ HDROP hDropInfo=(HDROP)wParam; char szFilePath[MAX_PATH]="",szD[MAX_PATH]={0},szP[MAX_PATH]={0};; DragQueryFile(hDropInfo, 0, szFilePath, sizeof(szFilePath)); _splitpath(szFilePath,szD,szP,0,0); strcpy(szFilePath,szD); strcat(szFilePath,szP); ::SetWindowText(GetDlgItem(hwndDlg,IDC_EDIT),szFilePath); } if(uMsg==WM_SYSCOMMAND && wParam==SC_CLOSE){ EndDialog(hwndDlg,1); return TRUE; } if(uMsg==WM_COMMAND && wParam==IDC_BT_UP){ int iCurSel=SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETCURSEL,0,0); if(iCurSel!=LB_ERR && iCurSel>0){ char szCur[MAX_APP_NAME+5]={0}; char szNext[MAX_APP_NAME+5]={0}; SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETTEXT,iCurSel,(LPARAM)szCur); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_DELETESTRING,iCurSel,0); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_INSERTSTRING,iCurSel-1,(LPARAM)szCur); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_SETCURSEL,iCurSel-1,0); } return TRUE; } if(uMsg==WM_COMMAND && wParam==IDC_BT_DOWN){ int iCurSel=SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETCURSEL,0,0); if(iCurSel!=LB_ERR){ char szCur[MAX_APP_NAME+5]={0}; char szNext[MAX_APP_NAME+5]={0}; SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETTEXT,iCurSel,(LPARAM)szCur); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETTEXT,iCurSel+1,(LPARAM)szNext); if(szNext[0]!=0){ SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_DELETESTRING,iCurSel+1,0); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_INSERTSTRING,iCurSel,(LPARAM)szNext); } } return TRUE; } if(uMsg==WM_COMMAND && wParam==IDC_BT_REM){ int iCurSel=SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETCURSEL,0,0); if(iCurSel!=LB_ERR){ SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_DELETESTRING,iCurSel,0); SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_SETCURSEL,iCurSel>1?iCurSel-1:0,0); } return TRUE; } if(uMsg==WM_COMMAND && wParam==IDC_BT_ADD){ char szCur[MAX_APP_NAME]={0}; ::GetWindowText(GetDlgItem(hwndDlg,IDC_EDIT),szCur,sizeof(szCur)); if(szCur[0]!=0){ BOOL bL=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_L), BM_GETCHECK, 0, 0); BOOL bR=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_R), BM_GETCHECK, 0, 0); BOOL bT=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_T), BM_GETCHECK, 0, 0); BOOL bB=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_B), BM_GETCHECK, 0, 0); if((bL && bR) || (bT && bB) || (bL+bR+bT+bB==0)){ return TRUE; } memmove(szCur+5,szCur,strlen(szCur)); szCur[0]=szCur[1]=szCur[2]=szCur[3]='.'; szCur[4]=' '; if(bL){ szCur[0]='L'; } if(bR){ szCur[1]='R'; } if(bT){ szCur[2]='T'; } if(bB){ szCur[3]='B'; } SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_ADDSTRING,0,(LPARAM)szCur); ::SetWindowText(GetDlgItem(hwndDlg,IDC_EDIT),""); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_T), BM_SETCHECK, 0, 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_L), BM_SETCHECK, 0, 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_B), BM_SETCHECK, 0, 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_R), BM_SETCHECK, 0, 0); } return TRUE; } if(uMsg==WM_COMMAND && LOWORD(wParam)==IDC_LIST && HIWORD(wParam)==LBN_SELCHANGE){ int iCurSel=SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETCURSEL,0,0); if(iCurSel!=LB_ERR){ char szCur[MAX_PATH+5]={0}; SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETTEXT,iCurSel,(LPARAM)szCur); ::SetWindowText(GetDlgItem(hwndDlg,IDC_EDIT),szCur+5); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_L), BM_SETCHECK, szCur[0]=='L', 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_R), BM_SETCHECK, szCur[1]=='R', 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_T), BM_SETCHECK, szCur[2]=='T', 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_CHECK_B), BM_SETCHECK, szCur[3]=='B', 0); } } if(uMsg==WM_COMMAND && wParam==IDOPTIONS){ WKGetPluginContainer()->ShowPluginPrefernces(); return TRUE; } if(uMsg==WM_COMMAND && wParam==IDOK){ int iCI=0; while(iCI<MAX_APPS){ g_szApplications[iCI][0]=0; SendMessage(GetDlgItem(hwndDlg,IDC_LIST),LB_GETTEXT,iCI,(LPARAM)g_szApplications[iCI]); iCI++; } EndDialog(hwndDlg,0); return TRUE; } return FALSE; } DWORD WINAPI CallOptions2(LPVOID pData) { HWND hParent=(HWND)pData; static BOOL bInProc=0; if(bInProc){ ::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hOpenedOptions2); return 0; } bInProc++; DialogBox(g_hinstDll,MAKEINTRESOURCE(IDD_OPT_DIALOG2),(HWND)(WKGetPluginContainer()->getOptionEx(2,0)),OptionsDialogProc2); if(!WKUtils::isWKUpAndRunning()){ return 0; } DWORD dwError=GetLastError(); WKGetPluginContainer()->PushMyOptions(0); bInProc--; return 1; } int WINAPI WKPluginOptions(HWND hParent) { CallOptions(hParent); return 1; } char szHotkeyStrPresentation[32]={0}; int WINAPI WKGetPluginFunctionHints(long iPluginFunction, long lHintCode, void*& pOut) { if(iPluginFunction==4){ strcpy(szHotkeyStrPresentation,"%0-2,489"); pOut=szHotkeyStrPresentation; return 1; } if(iPluginFunction==3){ strcpy(szHotkeyStrPresentation,"%0-2,488"); pOut=szHotkeyStrPresentation; return 1; } if(iPluginFunction==2){ strcpy(szHotkeyStrPresentation,"%0-2,490"); pOut=szHotkeyStrPresentation; return 1; } return 0; }; int WINAPI WKGetPluginFunctionCommonDesc(long iPluginFunction, WKPluginFunctionDsc* stuff) { if(iPluginFunction==4){ stuff->dwItemMenuPosition=0; strcpy(stuff->szItemName,"Minimize window to tray"); stuff->dwDefaultHotkey=0; return 1; } if(iPluginFunction==3){ stuff->dwItemMenuPosition=0; strcpy(stuff->szItemName,"Rollup window"); stuff->dwDefaultHotkey=0; return 1; } if(iPluginFunction==2){ stuff->dwItemMenuPosition=0; strcpy(stuff->szItemName,"Show hot menu"); stuff->dwDefaultHotkey=0; return 1; } if(iPluginFunction>4 || stuff==NULL){ return 0; } if(iPluginFunction==0){ strcpy(stuff->szItemName,"Autohide windows"); stuff->dwItemMenuPosition=WKITEMPOSITION_TRAY|WKITEMPOSITION_PLUGIN; stuff->hItemBmp=::LoadBitmap(g_hinstDll,MAKEINTRESOURCE(IDB_BM_ICON)); stuff->dwDefaultHotkey=0; }else{ strcpy(stuff->szItemName,"Autodock windows"); stuff->dwItemMenuPosition=WKITEMPOSITION_TRAY|WKITEMPOSITION_PLUGIN; stuff->hItemBmp=::LoadBitmap(g_hinstDll,MAKEINTRESOURCE(IDB_BM_ICON1)); stuff->dwDefaultHotkey=0; } return 1; } int WINAPI WKGetPluginFunctionActualDesc(long iPluginFunction, WKPluginFunctionActualDsc* stuff) { if(iPluginFunction>4 || stuff==NULL){ return 0; } return 1; } int WINAPI WKCallPluginFunction(long iPluginFunction, WKPluginFunctionStuff* stuff) { POINT pt; GetCursorPos(&pt); DWORD lHookerDesiredAction=0; HWND hLastWnd=WindowFromPoint(pt); if(iPluginFunction==4){ lHookerDesiredAction=2; PostThreadMessage(dwHookerThread,WM_USER+lHookerDesiredAction,WPARAM(hLastWnd),LPARAM(0)); return 1; } if(iPluginFunction==3){ lHookerDesiredAction=6; PostThreadMessage(dwHookerThread,WM_USER+lHookerDesiredAction,WPARAM(hLastWnd),LPARAM(0)); return 1; } if(iPluginFunction==2){ lHookerDesiredAction=3; PostThreadMessage(dwHookerThread,WM_USER+lHookerDesiredAction,WPARAM(hLastWnd),LPARAM(0)); return 1; } if(iPluginFunction==1){ if(stuff->hForegroundWindow!=0){ GetWindowText(stuff->hForegroundWindow,g_DefDockTitle,sizeof(g_DefDockTitle)); } CallOptions2(0); return 1; } WKPluginOptions(0); return 1; } int WINAPI GetPluginDsc(WKPluginDsc* dsc) { OSVERSIONINFOEX winfo; ZeroMemory(&winfo, sizeof(OSVERSIONINFOEX)); winfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); dsc->bLoadPluginByDefault=TRUE; dsc->bResidentPlugin=TRUE; //strcpy(dsc->szTitle,"Windows helper"); strcpy(dsc->szDesk,"This plugin allows you to minimize windows by right clicking its minimize button, make all windows sticky and much more"); dsc->hPluginBmp=::LoadBitmap(g_hinstDll,MAKEINTRESOURCE(IDB_BM_ICON)); dsc->dwVersionHi=1; dsc->dwVersionLo=1; return 1; } int WINAPI WKPluginOptionsManager(int iAction, WKOptionsCallbackInterface* pOptionsCallback, DWORD dwParameter) { if(iAction==OM_STARTUP_ADD){ //pOptionsCallback->AddStringOption("amin2tray","Minimize matching applications to tray icon instead of taskbar","Use ';' as delimiter between different titles, Use '*' as a wildcard for partial matches","",0,0); //pOptionsCallback->AddStringOption("amin2float","Minimize matching applications to floater instead of taskbar","Use ';' as delimiter between different titles, Use '*' as a wildcard for partial matches","",0,0); pOptionsCallback->AddStringOption("cautominStr","","","",0,0); pOptionsCallback->AddBoolOption("cautomin","","",FALSE,0); pOptionsCallback->AddNumberOption("iINACTSEC","","",0,0,1000,0); //pOptionsCallback->AddBoolOption("focusSteal","Do not allow other windows to steal keyboard focus while typing","",FALSE,0); pOptionsCallback->AddActionOption("options","Define windows that plugin must hide automatically",0,0); pOptionsCallback->AddActionOption("options3","Define windows that should be minimized to tray",0,0); pOptionsCallback->AddActionOption("options4","Define windows that should be minimized to floater",0,0); pOptionsCallback->AddActionOption("options2","Define windows that plugin must dock automatically",1,0); pOptionsCallback->AddBoolOption("bSnapMovements","Snap windows to each other","",FALSE,0); pOptionsCallback->AddNumberOptionEx("iStickness","Snap distance (pixels)","",0,0,1000,0,"bSnapMovements"); pOptionsCallback->AddBoolOption("bSnapToScreen","Snap windows to screen edges","",FALSE,0); pOptionsCallback->AddNumberOptionEx("iSnapToScreenStickness","Snap distance (pixels)","",0,0,1000,0,"bSnapToScreen"); pOptionsCallback->AddBoolOption("s2screenForce","Force windows to be inside the screen","This feature can be temporarily disabled. Just press and hold 'Shift' key when you want to move window beyond screen borders",FALSE,0); pOptionsCallback->AddBoolOptionEx("s3screenForce","Force windows to be inside the screen always - regardless of windows type","",FALSE,0,"s2screenForce"); pOptionsCallback->AddStringOptionEx("forceexclusions","Exclude matching windows from incidence of this plugin","If this plugin corrupts the look-and-feel of some windows, then you can put window title in this field. Use ';' as delimiter between different titles, Use '*' as a wildcard for partial matches","",0,0,"s2screenForce"); pOptionsCallback->AddBoolOption("ontopicon","Change icon of 'on top' windows","",0,OL_ACTIVEWND); pOptionsCallback->AddBoolOption("inject","Add commands to a window system menu","",TRUE,OL_ACTIVEWND); pOptionsCallback->AddBoolOptionEx("inject1","'Hide to tray' item","",TRUE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOptionEx("inject3","'Rollup to title' item","",FALSE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOptionEx("inject6","'Create shortcut' item","",FALSE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOptionEx("inject2","'Hide completely' item","",FALSE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOptionEx("inject5","'Add to quick-run' item","",TRUE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOptionEx("inject4","'Application info' item","",TRUE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOptionEx("inject7","'Kill application' item","",TRUE,OL_ACTIVEWND,"inject"); pOptionsCallback->AddBoolOption("replexk","Replace default hotkeys with custom one","",TRUE,OL_EXPLORERHK); //pOptionsCallback->AddTip("rclickt","Mouse gestures",OL_ACTIVEWND); pOptionsCallback->AddBoolOption("rooldock","Window border: Left click to dock","",TRUE,OL_ACTIVEWND); pOptionsCallback->AddBoolOption("roolexpand","Window border: Right click to expand","",TRUE,OL_ACTIVEWND); pOptionsCallback->AddStringOption("disableall","Disable WireKeys when one of this windows is active","Use ';' as delimiter between different titles, Use '*' as a wildcard for partial matches","",0); pOptionsCallback->AddTip("otheropt","Other options can be found under 'Active windows' preferences folder",0); pOptionsCallback->AddBinOption("items"); pOptionsCallback->AddBinOption("amin2tray"); pOptionsCallback->AddBinOption("amin2float"); } if(iAction==OM_STARTUP_ADD || iAction==OM_OPTIONS_SET){ if(iAction==OM_OPTIONS_SET){ PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,0,0); DWORD dwRes=WaitForSingleObject(hHookerEventDone,500); } hookData.bSnapMovements=pOptionsCallback->GetBoolOption("bSnapMovements"); hookData.iStickness=pOptionsCallback->GetBoolOption("iStickness"); hookData.bSnapToScreen=pOptionsCallback->GetBoolOption("bSnapToScreen"); hookData.iSnapToScreenStickness=pOptionsCallback->GetBoolOption("iSnapToScreenStickness"); hookData.bInjectIt1=pOptionsCallback->GetBoolOption("inject1"); hookData.bInjectIt2=pOptionsCallback->GetBoolOption("inject2"); hookData.bInjectIt3=pOptionsCallback->GetBoolOption("inject3"); hookData.bInjectIt4=pOptionsCallback->GetBoolOption("inject4"); hookData.bInjectIt5=pOptionsCallback->GetBoolOption("inject5"); hookData.bInjectIt6=pOptionsCallback->GetBoolOption("inject6"); hookData.bInjectIt7=pOptionsCallback->GetBoolOption("inject7"); hookData.bCatchAutoMinimize=pOptionsCallback->GetBoolOption("cautomin"); hookData.bAllowReplaceExplorerKeys=pOptionsCallback->GetBoolOption("replexk"); pOptionsCallback->GetStringOption("cautominStr",hookData.szAutoMinimizeTitle,sizeof(hookData.szAutoMinimizeTitle)); pOptionsCallback->GetStringOption("disableall",hookData.szAutoDisalbe,sizeof(hookData.szAutoDisalbe)); hookData.bSnapToScreenForce=pOptionsCallback->GetBoolOption("s2screenForce"); hookData.bSnapToScreenForceFull=pOptionsCallback->GetBoolOption("s3screenForce"); hookData.bCatchRollDock=pOptionsCallback->GetBoolOption("rooldock"); hookData.bCatchRollExpand=pOptionsCallback->GetBoolOption("roolexpand"); hookData.bInjectItems=pOptionsCallback->GetBoolOption("inject"); hookData.bOntopicon=pOptionsCallback->GetBoolOption("ontopicon"); hookData.bBlockFocuStealing=0;//pOptionsCallback->GetBoolOption("focusSteal"); hookData.iINACTSEC=pOptionsCallback->GetNumberOption("iINACTSEC"); pOptionsCallback->GetBinOption("amin2tray",hookData.szAutoMinToTray,sizeof(hookData.szAutoMinToTray)); pOptionsCallback->GetBinOption("amin2float",hookData.szAutoMinToFloat,sizeof(hookData.szAutoMinToFloat)); pOptionsCallback->GetStringOption("forceexclusions",plugData.szExclusions,sizeof(plugData.szExclusions)); pOptionsCallback->GetBinOption("items",g_szApplications,MAX_APPS*sizeof(g_szApplications[0])); if(iAction==OM_OPTIONS_SET){ PostThreadMessage(dwHookerThreadInThisDLL,WM_ENABLE,1,0); DWORD dwRes=WaitForSingleObject(hHookerEventDone,500); } } if(iAction==OM_OPTIONS_GET){ pOptionsCallback->SetBoolOption("bSnapMovements",hookData.bSnapMovements); pOptionsCallback->SetBoolOption("iStickness",hookData.iStickness); pOptionsCallback->SetBoolOption("bSnapToScreen",hookData.bSnapToScreen); pOptionsCallback->SetBoolOption("iSnapToScreenStickness",hookData.iSnapToScreenStickness); pOptionsCallback->SetBoolOption("inject1",hookData.bInjectIt1); pOptionsCallback->SetBoolOption("inject2",hookData.bInjectIt2); pOptionsCallback->SetBoolOption("inject3",hookData.bInjectIt3); pOptionsCallback->SetBoolOption("inject4",hookData.bInjectIt4); pOptionsCallback->SetBoolOption("inject5",hookData.bInjectIt5); pOptionsCallback->SetBoolOption("inject6",hookData.bInjectIt6); pOptionsCallback->SetBoolOption("inject7",hookData.bInjectIt7); pOptionsCallback->SetBoolOption("cautomin",hookData.bCatchAutoMinimize); pOptionsCallback->SetBoolOption("replexk",hookData.bAllowReplaceExplorerKeys); pOptionsCallback->SetStringOption("cautominStr",hookData.szAutoMinimizeTitle); pOptionsCallback->SetStringOption("disableall",hookData.szAutoDisalbe); pOptionsCallback->SetBoolOption("s2screenForce",hookData.bSnapToScreenForce); pOptionsCallback->SetBoolOption("s3screenForce",hookData.bSnapToScreenForceFull); pOptionsCallback->SetBoolOption("rooldock",hookData.bCatchRollDock); pOptionsCallback->SetBoolOption("roolexpand",hookData.bCatchRollExpand); pOptionsCallback->SetBoolOption("inject",hookData.bInjectItems); pOptionsCallback->SetBoolOption("ontopicon",hookData.bOntopicon); //pOptionsCallback->SetBoolOption("focusSteal",hookData.bBlockFocuStealing); pOptionsCallback->SetNumberOption("iINACTSEC",hookData.iINACTSEC); pOptionsCallback->SetBinOption("amin2tray",hookData.szAutoMinToTray,sizeof(hookData.szAutoMinToTray)); pOptionsCallback->SetBinOption("amin2float",hookData.szAutoMinToFloat,sizeof(hookData.szAutoMinToFloat)); pOptionsCallback->SetStringOption("forceexclusions",plugData.szExclusions); pOptionsCallback->SetBinOption("items",g_szApplications,MAX_APPS*sizeof(g_szApplications[0])); } return 1; } #ifndef NOSTUB_VC6 #define COMPILE_MULTIMON_STUBS #include <multimon.h> #endif
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 1570 ] ] ]
8a90b8187f043d5c479e6679acbd6320f7bcc358
21da454a8f032d6ad63ca9460656c1e04440310e
/tools/wcpp_vc9_projects/test.utest.win32/TestSession.cpp
ae506adea2206d63a10dc5a178d99848e1b12819
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include "stdafx.h" #undef GetFreeSpace #include "TestSession.h" #include <wcpp/wscom/main/WSCOM_main.h> #include <wcpp/io/wscFile.h> #include "utOutputStream.h" #include "utInputStream.h" TestSession::TestSession(void) { WSCOM::WS_InitRuntime(); ws_ptr<wsiServiceManager> servMgr; ws_ptr<wsiFile> file; wscFile::New( &file , ws_str("D:\\temp\\wscom") ); WSCOM::WS_InitWSCOM( &servMgr , file , WS_NULL ); m_ServMgr.Set( servMgr ); utInputStream::Init(); utOutputStream::Init(); } TestSession::~TestSession(void) { ws_ptr<wsiServiceManager> servMgr; m_ServMgr.Get( &servMgr ); m_ServMgr.Set(WS_NULL); WSCOM::WS_ShutdownWSCOM( servMgr ); // servMgr.Detach(); }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 33 ] ] ]
f58ae62895084284bc5c7d5b65b60ef597858630
20bf3095aa164d0d3431b73ead8a268684f14976
/cpp-labs/S2-1.CPP
5b311c30ab0647a282b54554d90205eb2784d671
[]
no_license
collage-lab/mcalab-cpp
eb5518346f5c3b7c1a96627c621a71cc493de76d
c642f1f009154424f243789014c779b9fc938ce4
refs/heads/master
2021-08-31T10:28:59.517333
2006-11-10T23:57:09
2006-11-10T23:57:21
114,954,399
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
#include<iostream.h> #include<conio.h> void main() { int i,j,n,k=-1; clrscr(); cout<<"Number of lines to be printed:-"; cin>>n; clrscr(); for(i=0;i<n;i++) { cout<<"1"; for(j=1;j<=k;j++) { cout<<" 0"; } k=k+2; if(i>0) cout<<" 1"; cout<<"\n"; } getch(); }
[ [ [ 1, 26 ] ] ]
3acd5bb6997ef70c9232779c180590690e7beb03
59166d9d1eea9b034ac331d9c5590362ab942a8f
/osgDynamicTexture/DynamicTexture.h
54b764c6825e96fb7cc4fd37b992b735b18a5a14
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
547
h
#ifndef _DYNAMIC_TEXTURE_H_ #define _DYNAMIC_TEXTURE_H_ #include <osg/Group> #include <osg/Referenced> #include <osg/ref_ptr> #include <osg/Image> class DynamicTexture : public osg::Referenced { public: DynamicTexture(); ~DynamicTexture(); osg::ref_ptr< osg::Group > getRootNode() { return m_rootNode.get(); } private: /*methods*/ void buildScene(); //добавить текстуру void AddTexture(); osg::ref_ptr<osg::Group> m_rootNode; osg::ref_ptr<osg::Image> image0; }; #endif //_DYNAMIC_TEXTURE_H_
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 29 ] ] ]
7e59cd26716282ae5f8d7942d894bb72819eb1b8
9a3a3c13df229fb0178331a07c9d6e651384ba54
/codebase/ix/IndexNode.cc
b5ac96f08004973989f2b32d632175101e6a5873
[]
no_license
nnathanuci/qe
ce717590ea10bafeab82271d0f69d53f1fc43b8f
91fb1b638d778b7629a8b9797152de1a7d579544
refs/heads/master
2016-09-05T13:22:31.907511
2011-06-03T18:44:55
2011-06-03T18:44:55
1,833,391
0
0
null
null
null
null
UTF-8
C++
false
false
36,341
cc
#include <iostream> #include <cstdio> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <iostream> #include <algorithm> #include <vector> #include "IndexNode.h" using namespace std; std::ostream& operator<<(std::ostream& os, const Entry& entry) { if(entry.getMode() == TypeInt) { os << "<V: " << entry.getKey() << " P->" << entry.getPage() ; if (entry.isData()) os << " S: " << entry.getSlot( ) << "> "; os << "> "; } else if(entry.getMode() == TypeReal) { os << "<V: " << entry.getKeyReal() << " P->" << entry.getPage() ; if (entry.isData()) os << " S: " << entry.getSlot( ); os << "> "; } return os; } std::ostream& operator<<(std::ostream& os, const IndexNode& node) { os << "[ L: " << node.left << " R: " << node.right << " F: " << node.free_offset << " T: " << node.type << " C: " << node.num_entries << " N: " << node.getPage_num() << " ]:::: "; for (unsigned int iter = 0; iter < node.num_entries ; iter++) os << node.entries[iter]; os << std::endl; return os; } /*Insert directly into the entry list of this node*/ RC IndexNode::insert_entry(Entry e) { if ( (num_entries > 2*D ) ) return -1; if (this->type == TYPE_DATA) { entries[num_entries].setIsData(true); entries[num_entries].setSlot( e.getSlot() ); free_offset += sizeof(int); } else entries[num_entries].setIsData(false); if(e.getMode() == TypeInt) entries[num_entries].setKey ( e.getKey () ); else if(e.getMode() == TypeReal) entries[num_entries].setKey ( e.getKeyReal() ); entries[num_entries].setPage( e.getPage() ); num_entries++; free_offset += 2*sizeof(int); std::stable_sort (entries, entries+num_entries, compare_entrys); return 0; } /*Remove directly from the entry list of this node*/ RC IndexNode::remove_entry(Entry e) { Entry *found = NULL;//= (Entry*) bsearch ( &key, (entries), num_entries, sizeof(Entry), compare_entrys ); if(e.getMode() == TypeInt) for (unsigned int i = 0; i < num_entries; i++) if (entries[i].getKey() == e.getKey()) found = &entries[i]; if(e.getMode() == TypeReal) for (unsigned int i = 0; i < num_entries; i++) if (entries[i].getKeyReal() == e.getKeyReal()) found = &entries[i]; if ( found == NULL ) return -1; entries[found - entries] = entries[num_entries - 1]; num_entries--; free_offset -= 2*sizeof(int); if (this->type == TYPE_DATA) { free_offset -= sizeof(int); } std::stable_sort (entries, entries + num_entries, compare_entrys); return 0; } /*Remove directly from the entry list of this node*/ RC IndexNode::remove_entry_by_page(Entry e) { Entry *found = NULL;//= (Entry*) bsearch ( &key, (entries), num_entries, sizeof(Entry), compare_entrys ); for (unsigned int i = 0; i < num_entries; i++) if (entries[i].getPage() == e.getPage()) found = &entries[i]; if ( found == NULL ) return -1; entries[found - entries] = entries[num_entries - 1]; num_entries--; free_offset -= 2*sizeof(int); if (this->type == TYPE_DATA) { free_offset -= sizeof(int); } std::stable_sort (entries, entries + num_entries, compare_entrys); return 0; } RC IndexNode::find_entry( Entry& e ) { Entry *found = NULL;//= (Entry*) bsearch ( &key, (entries), num_entries, sizeof(Entry), compare_entrys ); if(e.getMode() == TypeInt) for (unsigned int i = 0; i < num_entries; i++) if (entries[i].getKey() == e.getKey()) found = &entries[i]; if(e.getMode() == TypeReal) for (unsigned int i = 0; i < num_entries; i++) if (entries[i].getKeyReal() == e.getKeyReal()) found = &entries[i]; if ( found == NULL ) return -1; e.setPage((*found).getPage()); e.setSlot((*found).getSlot()); return 0; } RC IndexNode::find(int key, RID& r_val, bool is_index) { Entry e; e.setKey(key); RC ret = tree_search(ROOT_PAGE, e, r_val, is_index); return ret; } RC IndexNode::find(float key, RID& r_val, bool is_index) { Entry e; e.setKey(key); e.setMode(TypeReal); return tree_search_real(ROOT_PAGE, e, r_val, is_index); } RC IndexNode::get_leftmost_data_node(RID& r_val) { unsigned char* root[PF_PAGE_SIZE]; handle.ReadNode(ROOT_PAGE, root); this->read_node(root, ROOT_PAGE); unsigned int left_page = this->getLeft(); while (left_page != ROOT_PAGE) { handle.ReadNode(left_page, root); this->read_node(root, left_page); left_page = this->getLeft(); } r_val.pageNum = this->getPage_num(); return 0; } RC IndexNode::tree_search_real(unsigned int nodePointer, Entry key, RID& r_val, bool ret_index_page) { unsigned char* root[PF_PAGE_SIZE]; handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (num_entries < 1) return -1; float leftmost_key = this->entries[0].getKeyReal(); Entry rightmost_entry = (this->entries[this->num_entries - 1]); RC ret = -2; if ( this->getType() == TYPE_DATA ) { Entry e; e.setMode(TypeReal); e.setKey(key.getKeyReal()); RC rc = find_entry(e); if (ret_index_page) r_val.pageNum = this->getPage_num();//e.getPage() else r_val.pageNum = e.getPage(); r_val.slotNum = e.getSlot(); return rc; } else { if( key.getKeyReal() < leftmost_key ) ret = this->tree_search_real(this->left, key, r_val, ret_index_page); else if( key.getKeyReal() >= rightmost_entry.getKeyReal() ) ret = this->tree_search_real(rightmost_entry.getPage(), key, r_val, ret_index_page); else { float left = leftmost_key; float right = entries[1].getKeyReal(); int iter = 0; bool found = false; while (!found && iter < (num_entries - 1)) { if (left <= key.getKeyReal() && right > key.getKeyReal() ) { ret = this->tree_search_real(entries[iter].getPage(), key, r_val, ret_index_page); found = true; } iter++; left = right; right = entries[iter+1].getKeyReal(); } } } return ret; } RC IndexNode::tree_search(unsigned int nodePointer, Entry key, RID& r_val, bool ret_index_page) { unsigned char* root[PF_PAGE_SIZE]; handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (num_entries < 1) return -1; int leftmost_key = this->entries[0].getKey(); Entry rightmost_entry = (this->entries[this->num_entries - 1]); RC ret = -2; if ( this->getType() == TYPE_DATA ) { Entry e; e.setKey(key.getKey()); RC rc = find_entry(e); if (ret_index_page) r_val.pageNum = this->getPage_num();//e.getPage() else r_val.pageNum = e.getPage(); r_val.slotNum = e.getSlot(); return rc; } else { if( key.getKey() < leftmost_key ) ret = this->tree_search(this->left, key, r_val, ret_index_page); else if( key.getKey() >= rightmost_entry.getKey() ) ret = this->tree_search(rightmost_entry.getPage(), key, r_val, ret_index_page ); else { int left = leftmost_key; int right = entries[1].getKey(); int iter = 0; bool found = false; while (!found && iter < (num_entries - 1)) { if (left <= key.getKey() && right > key.getKey() ) { ret = this->tree_search(entries[iter].getPage(), key, r_val, ret_index_page); found = true; } iter++; left = right; right = entries[iter+1].getKey(); } } } return ret; } RC IndexNode::insert(int key, unsigned int r_ptr, unsigned int slot) { unsigned char* read_buffer [PF_PAGE_SIZE] = {0}; Entry to_insert (key , r_ptr); to_insert.setSlot(slot); //No root. if (handle.GetNumberOfPages() == 0) new_page(read_buffer); RC ret = IndexNode::insert_tree( ROOT_PAGE, to_insert); return ret; } RC IndexNode::insert(float key, unsigned int r_ptr, unsigned int slot) { unsigned char* read_buffer [PF_PAGE_SIZE] = {0}; Entry to_insert (key , r_ptr); to_insert.setMode(TypeReal); to_insert.setSlot(slot); //No root. if (handle.GetNumberOfPages() == 0) new_page(read_buffer); return IndexNode::insert_tree_real( ROOT_PAGE, to_insert); } RC IndexNode::insert_tree(unsigned int nodePointer, Entry to_insert) { unsigned char* read_buffer [PF_PAGE_SIZE] = {0}; unsigned char* write_buffer [PF_PAGE_SIZE] = {0}; unsigned int search_parent = this->page_num; handle.ReadNode(nodePointer, read_buffer); this->read_node(read_buffer, nodePointer); if ( type == TYPE_DATA ) { this->insert_entry( to_insert ); if (num_entries <= 2*D ) //Usual case, insert entry at leaf node. { this->write_node(write_buffer); handle.WriteNode(nodePointer, write_buffer); } else //data node is full, must split. { unsigned char* buffer [PF_PAGE_SIZE] = {0}; bool new_root = false; if(page_num == ROOT_PAGE) //Data page split was a root page. { new_root = true; unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode left_neighbor(handle, pid); left_neighbor = (*this); left_neighbor.setPage_num(pid); (*this) = left_neighbor; } unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode right_neighbor(handle, pid); unsigned int midpoint = (floor((float)this->num_entries/2)); unsigned int entries_at_start = this->num_entries; for (unsigned int iter = midpoint; iter < entries_at_start ; iter++) right_neighbor.insert_entry( this->entries[iter] ); for (unsigned int iter = entries_at_start - 1; iter >= midpoint; iter--) this->remove_entry(entries[iter]); if (this->getRight() != ROOT_PAGE) { handle.ReadNode(this->getRight(), buffer); IndexNode right_of_right(handle, this->getRight()); right_of_right.read_node(buffer, this->getRight()); right_of_right.setLeft(right_neighbor.getPage_num()); right_of_right.write_node(buffer); handle.WriteNode(right_of_right.getPage_num(), buffer); } right_neighbor.setRight(this->getRight()); right_neighbor.setLeft(this->getPage_num()); this->setRight(pid); right_neighbor.write_node(buffer); handle.WriteNode(right_neighbor.getPage_num(), buffer); this->write_node(buffer); handle.WriteNode(this->getPage_num(), buffer); if(new_root) { handle.ReadNode(ROOT_PAGE, buffer); IndexNode root(handle, ROOT_PAGE); root.setType(TYPE_INDEX); root.setLeft(this->page_num); Entry r; r.setKey(right_neighbor.entries[0].getKey()); r.setPage(right_neighbor.getPage_num()); r.setIsData(false); root.insert_entry(r); (*this) = root; this->write_node(write_buffer); handle.WriteNode(ROOT_PAGE, write_buffer); } else { Entry* newChild = new Entry(); newChild->setKey(right_neighbor.entries[0].getKey()); newChild->setPage(right_neighbor.getPage_num()); this->newchildtry = newChild; } } } else { Entry leftmost_entry = entries[0]; Entry rightmost_entry = (this->entries[this->num_entries - 1]); if( to_insert.getKey() < leftmost_entry.getKey() ) this->insert_tree(this->left, to_insert); else if( to_insert.getKey() >= rightmost_entry.getKey() ) this->insert_tree(rightmost_entry.getPage(), to_insert ); else { Entry left = leftmost_entry; Entry right = entries[1]; int iter = 0; bool inserted = false; while (!inserted && iter < (num_entries - 1)) { if (left.getKey() <= to_insert.getKey() && right.getKey() > to_insert.getKey() ) this->insert_tree(entries[iter].getPage(), to_insert ); iter++; left = right; right.setKey(entries[iter+1].getKey()); } } if (newchildtry != NULL) { to_insert = *newchildtry; insert_entry( to_insert ); if (num_entries <= 2*D ) //Usual case,didn't split child. { this->write_node(write_buffer); handle.WriteNode(page_num, write_buffer); delete(newchildtry); this->newchildtry = NULL; } else //index node is full, must split. { unsigned char* buffer [PF_PAGE_SIZE] = {0}; bool new_root = false; if(page_num == ROOT_PAGE) //Data page split was a root page. { new_root = true; unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode left_neighbor(handle, pid); left_neighbor = (*this); left_neighbor.setPage_num(pid); (*this) = left_neighbor; } unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode right_neighbor(handle, pid); right_neighbor.setType(TYPE_INDEX); unsigned int midpoint = (floor((float)this->num_entries/2)); unsigned int entries_at_start = this->num_entries; //Skip the index node to be added above. for (unsigned int iter = midpoint ; iter < entries_at_start ; iter++) right_neighbor.insert_entry( this->entries[iter] ); for (unsigned int iter = entries_at_start - 1; iter >= midpoint; iter--) this->remove_entry(entries[iter]); this->setRight(pid); right_neighbor.setLeft(right_neighbor.entries[0].getPage()); right_neighbor.write_node(buffer); handle.WriteNode(right_neighbor.getPage_num(), buffer); this->write_node(buffer); handle.WriteNode(this->getPage_num(), buffer); if(new_root) { handle.ReadNode(ROOT_PAGE, buffer); IndexNode root(handle, ROOT_PAGE); root.setType(TYPE_INDEX); root.setLeft(this->page_num); Entry r; r.setKey(right_neighbor.entries[0].getKey()); r.setPage(right_neighbor.getPage_num()); r.setIsData(false); root.insert_entry(r); (*this) = root; this->write_node(write_buffer); handle.WriteNode(ROOT_PAGE, write_buffer); } else { Entry* newChild = new Entry(); newChild->setKey(right_neighbor.entries[0].getKey()); newChild->setPage(right_neighbor.getPage_num()); this->newchildtry = newChild; } right_neighbor.remove_entry(entries[0]); right_neighbor.write_node(buffer); handle.WriteNode(right_neighbor.getPage_num(), buffer); } } } handle.ReadNode(search_parent, read_buffer); this->read_node(read_buffer, search_parent); return 0; } RC IndexNode::insert_tree_real(unsigned int nodePointer, Entry to_insert) { unsigned char* read_buffer [PF_PAGE_SIZE] = {0}; unsigned char* write_buffer [PF_PAGE_SIZE] = {0}; unsigned int search_parent = this->page_num; handle.ReadNode(nodePointer, read_buffer); this->read_node(read_buffer, nodePointer); to_insert.setMode(TypeReal); if ( type == TYPE_DATA ) { this->insert_entry( to_insert ); if (num_entries <= 2*D ) //Usual case, insert entry at leaf node. { this->write_node(write_buffer); handle.WriteNode(nodePointer, write_buffer); } else //data node is full, must split. { unsigned char* buffer [PF_PAGE_SIZE] = {0}; bool new_root = false; if(page_num == ROOT_PAGE) //Data page split was a root page. { new_root = true; unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode left_neighbor(handle, pid); left_neighbor = (*this); left_neighbor.setPage_num(pid); left_neighbor.setKeymode(TypeReal); (*this) = left_neighbor; } unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode right_neighbor(handle, pid); right_neighbor.setKeymode(TypeReal); unsigned int midpoint = (floor((float)this->num_entries/2)); unsigned int entries_at_start = this->num_entries; for (unsigned int iter = midpoint; iter < entries_at_start ; iter++) right_neighbor.insert_entry( this->entries[iter] ); for (unsigned int iter = entries_at_start - 1; iter >= midpoint; iter--) this->remove_entry(entries[iter]); if (this->getRight() != ROOT_PAGE) { handle.ReadNode(this->getRight(), buffer); IndexNode right_of_right(handle, this->getRight()); right_of_right.setKeymode(TypeReal); right_of_right.read_node(buffer, this->getRight()); right_of_right.setLeft(right_neighbor.getPage_num()); right_of_right.write_node(buffer); handle.WriteNode(right_of_right.getPage_num(), buffer); } right_neighbor.setRight(this->getRight()); right_neighbor.setLeft(this->getPage_num()); this->setRight(pid); right_neighbor.write_node(buffer); handle.WriteNode(right_neighbor.getPage_num(), buffer); this->write_node(buffer); handle.WriteNode(this->getPage_num(), buffer); if(new_root) { handle.ReadNode(ROOT_PAGE, buffer); IndexNode root(handle, ROOT_PAGE); root.setType(TYPE_INDEX); root.setLeft(this->page_num); root.setKeymode(TypeReal); Entry r; r.setIsData(false); r.setMode(TypeReal); r.setKey(right_neighbor.entries[0].getKeyReal()); r.setPage(right_neighbor.getPage_num()); root.insert_entry(r); (*this) = root; this->write_node(write_buffer); handle.WriteNode(ROOT_PAGE, write_buffer); } else { Entry* newChild = new Entry(); newChild->setMode(TypeReal); newChild->setKey(right_neighbor.entries[0].getKeyReal()); newChild->setPage(right_neighbor.getPage_num()); this->newchildtry = newChild; } } } else { Entry leftmost_entry = entries[0]; leftmost_entry.setMode(TypeReal); Entry rightmost_entry = (this->entries[this->num_entries - 1]); rightmost_entry.setMode(TypeReal); if( to_insert.getKeyReal() < leftmost_entry.getKeyReal() ) this->insert_tree_real(this->left, to_insert); else if( to_insert.getKeyReal() >= rightmost_entry.getKeyReal() ) this->insert_tree_real(rightmost_entry.getPage(), to_insert ); else { Entry left = leftmost_entry; left.setMode(TypeReal); Entry right = entries[1]; right.setMode(TypeReal); int iter = 0; bool inserted = false; while (!inserted && iter < (num_entries - 1)) { if (left.getKeyReal() <= to_insert.getKeyReal() && right.getKeyReal() > to_insert.getKeyReal() ) this->insert_tree_real(entries[iter].getPage(), to_insert ); iter++; left = right; right.setKey(entries[iter+1].getKeyReal()); } } if (newchildtry != NULL) { to_insert = *newchildtry; to_insert.setMode(TypeReal); insert_entry( to_insert ); if (num_entries <= 2*D ) //Usual case,didn't split child. { this->write_node(write_buffer); handle.WriteNode(page_num, write_buffer); delete(newchildtry); this->newchildtry = NULL; } else //index node is full, must split. { unsigned char* buffer [PF_PAGE_SIZE] = {0}; bool new_root = false; if(page_num == ROOT_PAGE) //Data page split was a root page. { new_root = true; unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode left_neighbor(handle, pid); left_neighbor.setKeymode(TypeReal); left_neighbor = (*this); left_neighbor.setPage_num(pid); (*this) = left_neighbor; } unsigned int pid = 0; handle.NewNode( (const void*)buffer, pid ); IndexNode right_neighbor(handle, pid); right_neighbor.setType(TYPE_INDEX); right_neighbor.setKeymode(TypeReal); unsigned int midpoint = (floor((float)this->num_entries/2)); unsigned int entries_at_start = this->num_entries; //Skip the index node to be added above. for (unsigned int iter = midpoint ; iter < entries_at_start ; iter++) right_neighbor.insert_entry( this->entries[iter] ); for (unsigned int iter = entries_at_start - 1; iter >= midpoint; iter--) this->remove_entry(entries[iter]); this->setRight(pid); right_neighbor.setLeft(right_neighbor.entries[0].getPage()); right_neighbor.write_node(buffer); handle.WriteNode(right_neighbor.getPage_num(), buffer); this->write_node(buffer); handle.WriteNode(this->getPage_num(), buffer); if(new_root) { handle.ReadNode(ROOT_PAGE, buffer); IndexNode root(handle, ROOT_PAGE); root.setType(TYPE_INDEX); root.setLeft(this->page_num); root.setKeymode(TypeReal); Entry r; r.setMode(TypeReal); r.setKey(right_neighbor.entries[0].getKeyReal()); r.setPage(right_neighbor.getPage_num()); root.insert_entry(r); (*this) = root; this->write_node(write_buffer); handle.WriteNode(ROOT_PAGE, write_buffer); } else { Entry* newChild = new Entry(); newChild->setMode(TypeReal); newChild->setKey(right_neighbor.entries[0].getKeyReal()); newChild->setPage(right_neighbor.getPage_num()); this->newchildtry = newChild; } right_neighbor.remove_entry(entries[0]); right_neighbor.write_node(buffer); handle.WriteNode(right_neighbor.getPage_num(), buffer); } } } handle.ReadNode(search_parent, read_buffer); this->read_node(read_buffer, search_parent); return 0; } RC IndexNode::remove(int key) { /* unsigned char* read_buffer [PF_PAGE_SIZE] = {0}; unsigned char* write_buffer [PF_PAGE_SIZE] = {0}; RID r_val; RC ret = find( key, r_val, true); if (ret) return ret; handle.ReadNode(r_val.pageNum, read_buffer); this->read_node(read_buffer, r_val.pageNum); Entry to_remove; to_remove.setKey(key); this->remove_entry(to_remove); this->write_node(write_buffer); handle.WriteNode(r_val.pageNum, write_buffer); return 0; */ Entry e; e.setKey(key); int remove_i_e = 0; unsigned int remove_left; return tree_remove(ROOT_PAGE, e, remove_i_e, remove_left); } RC IndexNode::remove(float key) { /* unsigned char* read_buffer [PF_PAGE_SIZE] = {0}; unsigned char* write_buffer [PF_PAGE_SIZE] = {0}; RID r_val; RC ret = find( key, r_val, true); if (ret) return ret; handle.ReadNode(r_val.pageNum, read_buffer); this->read_node(read_buffer, r_val.pageNum); Entry to_remove; to_remove.setMode(TypeReal); to_remove.setKey(key); if ( (ret = this->remove_entry(to_remove)) ) return ret; this->write_node(write_buffer); handle.WriteNode(r_val.pageNum, write_buffer); return 0; */ Entry e; e.setKey(key); int remove_i_e = 0; unsigned int remove_left; return tree_remove_real(ROOT_PAGE, e, remove_i_e, remove_left); } RC IndexNode::tree_remove(unsigned int nodePointer, Entry key, int& remove_i_e, unsigned int& remove_left) { unsigned char* root[PF_PAGE_SIZE]; unsigned char* write_buffer [PF_PAGE_SIZE] = {0}; handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (num_entries < 1) return -1; int leftmost_key = this->entries[0].getKey(); Entry rightmost_entry = (this->entries[this->num_entries - 1]); RC ret = 0; if ( this->getType() == TYPE_DATA ) { Entry e; e.setKey(key.getKey()); RC rc = remove_entry(e); if (rc) return rc; if (this->num_entries <= 0) { remove_i_e = 1; unsigned char* temp[PF_PAGE_SIZE]; IndexNode left_N(this->handle, this->getLeft()); handle.ReadNode(this->getLeft(), temp); left_N.read_node(temp, this->getLeft()); IndexNode right_N(this->handle, this->getRight()); handle.ReadNode(this->getRight(), temp); right_N.read_node(temp, this->getRight()); if (this->getLeft() != 0) { this->setType(TYPE_DELETED); if (this->getLeft() != 0) { left_N.setRight(this->getRight()); left_N.write_node(write_buffer); handle.WriteNode(this->getLeft(), write_buffer); } if (this->getRight() != 0) { right_N.setLeft(this->getLeft()); right_N.write_node(write_buffer); handle.WriteNode(this->getRight(), write_buffer); } } } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); } else if ( this->getType() == TYPE_INDEX ) { if( key.getKey() < leftmost_key ) //ignore call to remove index entry. { ret = tree_remove(this->left, key, remove_i_e, remove_left); handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (remove_i_e == 2) { this->setLeft(remove_left); remove_i_e = 0; } if (this->num_entries <= 0) { remove_i_e = 2; remove_left = this->getLeft(); this->setType(2); } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); remove_i_e = 0; } else if( key.getKey() >= rightmost_entry.getKey() ) { ret = this->tree_remove(rightmost_entry.getPage(), key, remove_i_e, remove_left); handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (this->page_num != ROOT_PAGE) { if (remove_i_e == 1) { remove_entry_by_page(rightmost_entry); remove_i_e = 0; } } if (remove_i_e == 2) { this->entries[this->num_entries - 1].setPage(remove_left); remove_i_e = 0; } if (this->num_entries <= 0 ) { remove_i_e = 2; remove_left = this->getLeft(); this->setType(2); } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); } else { int left = leftmost_key; int right = entries[1].getKey(); int iter = 0; bool found = false; while (!found && iter < (num_entries - 1)) { if (left <= key.getKey() && right > key.getKey() ) { Entry temp_rem = entries[iter]; ret = this->tree_remove(entries[iter].getPage(), key, remove_i_e, remove_left); handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); found = true; if (remove_i_e == 1) { remove_entry_by_page(temp_rem); remove_i_e = 0; } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); remove_i_e = 0; } iter++; left = right; right = entries[iter+1].getKey(); } } } /*Weird contingencies arise when doing lazy delete at the root*/ if (this->getPage_num() == ROOT_PAGE && this->num_entries > 0) { rightmost_entry = (this->entries[this->num_entries - 1]); char temp[PF_PAGE_SIZE]; handle.ReadNode(rightmost_entry.getPage(), temp); IndexNode tempNode(handle, rightmost_entry.getPage()); tempNode.read_node(temp, rightmost_entry.getPage()); if (tempNode.getType() == TYPE_DELETED) { tempNode.setType(TYPE_DATA); tempNode.write_node(write_buffer); handle.WriteNode(tempNode.getPage_num(), write_buffer); } handle.ReadNode(nodePointer, temp); this->read_node(temp, nodePointer); } if (this->getPage_num() == ROOT_PAGE && this->num_entries > 0) { rightmost_entry = (this->entries[this->num_entries - 1]); char temp[PF_PAGE_SIZE]; IndexNode right_N(handle, rightmost_entry.getPage()); handle.ReadNode(rightmost_entry.getPage(), temp); right_N.read_node(temp, rightmost_entry.getPage()); if (this->getLeft() != ROOT_PAGE) { IndexNode left_N(handle, this->getLeft()); handle.ReadNode(this->getLeft(), temp); left_N.read_node(temp, this->getLeft()); if (right_N.num_entries <= 0 && left_N.num_entries <= 0 ) { right_N.setType(TYPE_DELETED); left_N.setType(TYPE_DELETED); this->setType(TYPE_DATA); this->setFree_offset(0); this->num_entries = 0; this->setLeft(ROOT_PAGE); right_N.write_node(write_buffer); handle.WriteNode(right_N.getPage_num(), write_buffer); left_N.write_node(write_buffer); handle.WriteNode(left_N.getPage_num(), write_buffer); this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); } } } return ret; } RC IndexNode::tree_remove_real(unsigned int nodePointer, Entry key, int& remove_i_e, unsigned int& remove_left) { unsigned char* root[PF_PAGE_SIZE]; unsigned char* write_buffer [PF_PAGE_SIZE] = {0}; handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (num_entries < 1) return -1; float leftmost_key = this->entries[0].getKeyReal(); Entry rightmost_entry = (this->entries[this->num_entries - 1]); RC ret = 0; if ( this->getType() == TYPE_DATA ) { Entry e; e.setKey(key.getKeyReal()); e.setMode(TypeReal); RC rc = remove_entry(e); if (rc) return rc; if (this->num_entries <= 0) { remove_i_e = 1; unsigned char* temp[PF_PAGE_SIZE]; IndexNode left_N(this->handle, this->getLeft()); handle.ReadNode(this->getLeft(), temp); left_N.read_node(temp, this->getLeft()); IndexNode right_N(this->handle, this->getRight()); handle.ReadNode(this->getRight(), temp); right_N.read_node(temp, this->getRight()); if (this->getLeft() != 0) { this->setType(TYPE_DELETED); if (this->getLeft() != 0) { left_N.setRight(this->getRight()); left_N.write_node(write_buffer); handle.WriteNode(this->getLeft(), write_buffer); } if (this->getRight() != 0) { right_N.setLeft(this->getLeft()); right_N.write_node(write_buffer); handle.WriteNode(this->getRight(), write_buffer); } } } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); } else if ( this->getType() == TYPE_INDEX ) { if( key.getKeyReal() < leftmost_key ) //ignore call to remove index entry. { ret = tree_remove_real(this->left, key, remove_i_e, remove_left); handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (remove_i_e == 2) { this->setLeft(remove_left); remove_i_e = 0; } if (this->num_entries <= 0) { remove_i_e = 2; remove_left = this->getLeft(); this->setType(2); } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); remove_i_e = 0; } else if( key.getKeyReal() >= rightmost_entry.getKeyReal() ) { ret = this->tree_remove_real(rightmost_entry.getPage(), key, remove_i_e, remove_left); handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); if (this->page_num != ROOT_PAGE) { if (remove_i_e == 1) { remove_entry_by_page(rightmost_entry); remove_i_e = 0; } } if (remove_i_e == 2) { this->entries[this->num_entries - 1].setPage(remove_left); remove_i_e = 0; } if (this->num_entries <= 0 ) { remove_i_e = 2; remove_left = this->getLeft(); this->setType(2); } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); } else { float left = leftmost_key; float right = entries[1].getKeyReal(); int iter = 0; bool found = false; while (!found && iter < (num_entries - 1)) { if (left <= key.getKeyReal() && right > key.getKeyReal() ) { Entry temp_rem = entries[iter]; temp_rem.setMode(TypeReal); ret = this->tree_remove_real(entries[iter].getPage(), key, remove_i_e, remove_left); handle.ReadNode(nodePointer, root); this->read_node(root, nodePointer); found = true; if (remove_i_e == 1) { remove_entry_by_page(temp_rem); remove_i_e = 0; } else remove_i_e = 0; this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); remove_i_e = 0; } iter++; left = right; right = entries[iter+1].getKeyReal(); } } } /*Weird contingencies arise when doing lazy delete at the root*/ if (this->getPage_num() == ROOT_PAGE && this->num_entries > 0) { rightmost_entry = (this->entries[this->num_entries - 1]); char temp[PF_PAGE_SIZE]; handle.ReadNode(rightmost_entry.getPage(), temp); IndexNode tempNode(handle, rightmost_entry.getPage()); tempNode.read_node(temp, rightmost_entry.getPage()); if (tempNode.getType() == TYPE_DELETED) { tempNode.setType(TYPE_DATA); tempNode.write_node(write_buffer); handle.WriteNode(tempNode.getPage_num(), write_buffer); } handle.ReadNode(nodePointer, temp); this->read_node(temp, nodePointer); } if (this->getPage_num() == ROOT_PAGE && this->num_entries > 0) { rightmost_entry = (this->entries[this->num_entries - 1]); char temp[PF_PAGE_SIZE]; IndexNode right_N(handle, rightmost_entry.getPage()); handle.ReadNode(rightmost_entry.getPage(), temp); right_N.read_node(temp, rightmost_entry.getPage()); if (this->getLeft() != ROOT_PAGE && this->num_entries > 0) { IndexNode left_N(handle, this->getLeft()); handle.ReadNode(this->getLeft(), temp); left_N.read_node(temp, this->getLeft()); if (right_N.num_entries <= 0 && left_N.num_entries <= 0 ) { right_N.setType(TYPE_DELETED); left_N.setType(TYPE_DELETED); this->setType(TYPE_DATA); this->setFree_offset(0); this->num_entries = 0; this->setLeft(ROOT_PAGE); right_N.write_node(write_buffer); handle.WriteNode(right_N.getPage_num(), write_buffer); left_N.write_node(write_buffer); handle.WriteNode(left_N.getPage_num(), write_buffer); this->write_node(write_buffer); handle.WriteNode(this->getPage_num(), write_buffer); } } } return ret; } void* IndexNode::new_page(void* p) { unsigned int* page_trailer = ((unsigned int*) p ) + (ENTRY_TRAILER_START / sizeof(unsigned int)) ; *page_trailer = left = 0; page_trailer++; *page_trailer = right = 0; page_trailer++; *page_trailer = free_offset = 0; page_trailer++; *page_trailer = type = 0; page_trailer++; *page_trailer = num_entries = 0; page_trailer++; return p; } void* IndexNode::write_node(void* p) { int* page = (int*) p; int* page_trailer = ((int*) p ) + (ENTRY_TRAILER_START / sizeof(int)) ; if (keymode == TypeInt) { for (unsigned int iter = 0; iter < num_entries ; iter++ ) { entries[iter].write_int_entry(page); if (type == TYPE_DATA) page+=3; else page+=2; } } else if (keymode == TypeReal) { for (unsigned int iter = 0; iter < num_entries ; iter++) { //cout << "Write " << entries[iter] ; entries[iter].write_real_entry(page); if (type == TYPE_DATA) page+=3; else page+=2; } } *page_trailer = left; page_trailer++; *page_trailer = right; page_trailer++; *page_trailer = free_offset; page_trailer++; *page_trailer = type; page_trailer++; *page_trailer = num_entries; page_trailer++; return p; } IndexNode IndexNode::read_node(void* p , unsigned int page_num) { this->setPage_num(page_num); int* page = (int*) p; int* page_trailer = ((int*) p ) + (ENTRY_TRAILER_START / sizeof(int)) ; left = *page_trailer; page_trailer++; right = *page_trailer; page_trailer++; free_offset = *page_trailer ; page_trailer++; type = *page_trailer; page_trailer++; num_entries = *page_trailer ; page_trailer++; if (keymode == TypeInt) { for (unsigned int iter = 0; iter < num_entries ; iter++ ) { entries[iter].read_int_entry(page,type ); if (type == TYPE_DATA) page+=3; else page+=2; } } else if (keymode == TypeReal) { for (unsigned int iter = 0; iter < num_entries ; iter++ ) { entries[iter].read_real_entry(page, type); //cout << "Write " << entries[iter] ; if (type == TYPE_DATA) page+=3; else page+=2; } } return *(this); }
[ [ [ 1, 1380 ] ] ]
396eacda19f6849fcc2ba425c88f62b8294243ce
e4bad8b090b8f2fd1ea44b681e3ac41981f50220
/trunk/gui/helloPrj/hello/Release/moc_SlidComp.cpp
ea3816289443e0ff7344313e63dec0a92634c5ec
[]
no_license
BackupTheBerlios/abeetles-svn
92d1ce228b8627116ae3104b4698fc5873466aff
803f916bab7148290f55542c20af29367ef2d125
refs/heads/master
2021-01-22T12:02:24.457339
2007-08-15T11:18:14
2007-08-15T11:18:14
40,670,857
0
0
null
null
null
null
UTF-8
C++
false
false
2,440
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'SlidComp.h' ** ** Created: Sun 17. Jun 21:54:19 2007 ** by: The Qt Meta Object Compiler version 59 (Qt 4.3.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../SlidComp.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'SlidComp.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 59 #error "This file was generated using the moc from 4.3.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif static const uint qt_meta_data_SlidComp[] = { // content: 1, // revision 0, // classname 0, 0, // classinfo 2, 10, // methods 0, 0, // properties 0, 0, // enums/sets // signals: signature, parameters, type, tag, flags 19, 10, 9, 9, 0x05, // slots: signature, parameters, type, tag, flags 37, 10, 9, 9, 0x0a, 0 // eod }; static const char qt_meta_stringdata_SlidComp[] = { "SlidComp\0\0newValue\0valueChanged(int)\0" "setValue(int)\0" }; const QMetaObject SlidComp::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_SlidComp, qt_meta_data_SlidComp, 0 } }; const QMetaObject *SlidComp::metaObject() const { return &staticMetaObject; } void *SlidComp::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_SlidComp)) return static_cast<void*>(const_cast< SlidComp*>(this)); return QWidget::qt_metacast(_clname); } int SlidComp::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: setValue((*reinterpret_cast< int(*)>(_a[1]))); break; } _id -= 2; } return _id; } // SIGNAL 0 void SlidComp::valueChanged(int _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); }
[ "ibart@60a5a0de-1a2f-0410-942a-f28f22aea592" ]
[ [ [ 1, 81 ] ] ]
d1b2b5b74e2a17f1f93bb51544195ec4da9710b4
38d9a3374e52b67ca01ed8bbf11cd0b878cce2a5
/branches/tbeta/CCV-fid/addons/ofxNCore/src/Modules/ofxNCoreVision.cpp
118340a8c37c0842e37f0d1bc19080e26f8b00dd
[]
no_license
hugodu/ccv-tbeta
8869736cbdf29685a62d046f4820e7a26dcd05a7
246c84989eea0b5c759944466db7c591beb3c2e4
refs/heads/master
2021-04-01T10:39:18.368714
2011-03-09T23:05:24
2011-03-09T23:05:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
49,719
cpp
/* * ofxNCoreVision.cpp * NUI Group Community Core Vision * * Created by NUI Group Dev Team A on 2/1/09. * Copyright 2009 NUI Group. All rights reserved. * */ #include "ofxNCoreVision.h" #include "../Controls/gui.h" /****************************************************************************** * The setup function is run once to perform initializations in the application *****************************************************************************/ void ofxNCoreVision::_setup(ofEventArgs &e) { //set the title ofSetWindowTitle(" Community Core Vision "); //create filter if ( filter == NULL ){filter = new ProcessFilters();} //fiducial Filters------------------------------------------------------------------------ if ( filter_fiducial == NULL ){filter_fiducial = new ProcessFilters();} //---------added by Stefan Schlupek----------- //Load Settings from config.xml file loadXMLSettings(); //GLUT Bug: http://www.mathies.com/glfaq/GLToolkitFAQ.html#II //removes the 'x' button on windows which causes a crash due to a GLUT bug #ifdef TARGET_WIN32 //Get rid of 'x' button HWND hwndConsole = FindWindowA(NULL, " Community Core Vision "); HMENU hMnu = ::GetSystemMenu(hwndConsole, FALSE); RemoveMenu(hMnu, SC_CLOSE, MF_BYCOMMAND); #endif if(printfToFile) { /***************************************************************************************************** * LOGGING ******************************************************************************************************/ /* alright first we need to get time and date so our logs can be ordered */ time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (fileName,80,"../logs/log_%B_%d_%y_%H_%M_%S.txt",timeinfo); FILE *stream ; sprintf(fileName, ofToDataPath(fileName).c_str()); if((stream = freopen(fileName, "w", stdout)) == NULL){} /******************************************************************************************************/ } printf("printfToFile %i!\n", printfToFile); printf("Undistort %i!\n", bUndistort); //Setup Window Properties ofSetWindowShape(winWidth,winHeight); ofSetVerticalSync(false); //Set vertical sync to false for better performance? printf("freedom?\n"); //load camera/video initDevice(); printf("freedom2?\n"); //set framerate ofSetFrameRate(camRate * 1.3); //This will be based on camera fps in the future /***************************************************************************************************** * Allocate images (needed for drawing/processing images) ******************************************************************************************************/ processedImg.allocate(camWidth, camHeight); //main Image that'll be processed. processedImg.setUseTexture(false); //We don't need to draw this so don't create a texture sourceImg.allocate(camWidth, camHeight); //Source Image sourceImg.setUseTexture(false); //We don't need to draw this so don't create a texture /******************************************************************************************************/ /***************************************************************************************************** * Allocate Fiducial_images ******************************************************************************************************/ //---------added by Stefan Schlupek----------- processedImg_fiducial.allocate(camWidth, camHeight); //main Image that'll be processed. processedImg_fiducial.setUseTexture(false); //We don't need to draw this so don't create a texture printf("camWidth:%f camHeight:%f \n",camWidth ,camHeight); undistortedImg.allocate(camWidth, camHeight); // processedImg.allocate(camWidth, camHeight); //main Image that'll be processed. //--------------------------- //Fonts - Is there a way to dynamically change font size? verdana.loadFont("verdana.ttf", 8, true, true); //Font used for small images bigvideo.loadFont("verdana.ttf", 13, true, true); //Font used for big images. //Static Images background.loadImage("images/background.jpg"); //Main (Temp?) Background printf("freedom3?\n"); //GUI Controls controls = ofxGui::Instance(this); setupControls(); printf("freedom4?\n"); //Setup Calibration calib.setup(camWidth, camHeight, &tracker); //added by Stefan Schlupek calib.calibrate.init_UDP_calibrate_connection(calibration_udp_host,calibration_udp_port); //----- //Allocate Filters filter->allocate( camWidth, camHeight ); //Allocate Fiducial_Filters filter_fiducial->allocate( camWidth, camHeight ); //the filters need this Information for right backround Initialization at the different modes filter->backgroundMode= backgroundMode; filter_fiducial->backgroundMode= backgroundMode; //---------added by Stefan Schlupek----------- /***************************************************************************************************** * Startup Modes ******************************************************************************************************/ //If Standalone Mode (not an addon) if (bStandaloneMode) { printf("Starting in standalone mode...\n\n"); showConfiguration = true; } if (bMiniMode) { showConfiguration = true; bShowInterface = false; printf("Starting in Mini Mode...\n\n"); ofSetWindowShape(190, 200); //minimized size filter->bMiniMode = bMiniMode; //------------------------------------------ filter_fiducial->bMiniMode = bMiniMode; //---------added by Stefan Schlupek----------- } else{ bShowInterface = true; printf("Starting in full mode...\n\n"); } #ifdef TARGET_WIN32 //get rid of the console window //FreeConsole(); #endif printf("Community Core Vision is setup!\n\n"); //----added by Stefan Schlupek //load a background Image as reference for Image Processing if(backgroundMode == "LOAD" )loadBackground(); /**************************************************************** * FiducialFinder Settings ****************************************************************/ //detect finger is off by default //fidfinder.detectFinger= true; fidfinder.maxFingerSize = 25; fidfinder.minFingerSize = 5; fidfinder.fingerSensitivity = 0.05f;//from 0 to 2.0f // factor for Fiducial Drawing. The ImageSize is hardcoded 320x240 Pixel!(Look at ProcessFilters.h at the draw() Method fiducialDrawFactor_Width = 320 / static_cast<float>(filter->camWidth);//camWidth; fiducialDrawFactor_Height = 240 / static_cast<float>(filter->camHeight);//camHeight; if(fiducialTreePath != ""){ fidfinder.initTree( fiducialTreePath.c_str() ); } myTUIO.setFiducialModus(bTrackFiducials);//TUIO Sender flag to avoid udp traffic if not needed //-------------------------- //UDP Alive Connections ofAddListener(udp_alive_connection.onUDP_makeAndSaveBackground,this,&ofxNCoreVision::makeAndSaveBackground); udp_alive_connection.init_Connections();// = new UDP_Alive(myTUIO.host_name,);//(string _host, int port_in,int port_out,string host_out); printf("udp_alive_connection host %s, in port %i, out port %i, outHost %s\n",udp_alive_connection.host.c_str(),udp_alive_connection.udp_in_port,udp_alive_connection.udp_out_port,udp_alive_connection.udp_out_host.c_str()); //Sleep(2000); } /**************************************************************** * Load/Save config.xml file Settings ****************************************************************/ void ofxNCoreVision::loadXMLSettings() { // TODO: a seperate XML to map keyboard commands to action message = "Loading config.xml..."; // Can this load via http? if ( XML.loadFile("data/config.xml")){ message = "Settings Loaded!\n\n";} else{ message = "No Settings Found...\n\n"; //FAIL } cout << message << endl; //-------------------------------------------------------------- // START BINDING XML TO VARS //-------------------------------------------------------------- bcamera = XML.getValue("CONFIG:CAMERA_0:USECAMERA", 1); deviceModel = XML.getValue("CONFIG:CAMERA_0:DEVICE_MODEL", ""); deviceID = XML.getValue("CONFIG:CAMERA_0:DEVICE", 0); camWidth = XML.getValue("CONFIG:CAMERA_0:WIDTH", 320); camHeight = XML.getValue("CONFIG:CAMERA_0:HEIGHT", 240); camRate = XML.getValue("CONFIG:CAMERA_0:FRAMERATE", 0); videoFileName = XML.getValue("CONFIG:VIDEO:FILENAME", "test_videos/RearDI.m4v"); maxBlobs = XML.getValue("CONFIG:BLOBS:MAXNUMBER", 20); bShowLabels = XML.getValue("CONFIG:BOOLEAN:LABELS",0); bDrawOutlines = XML.getValue("CONFIG:BOOLEAN:OUTLINES",0); //bAutoBackground = XML.getValue("CONFIG:BOOLEAN:LEARNBG",0); backgroundMode = XML.getValue("CONFIG:BACKGROUND:STARTUPMODE","AUTO"); backgroundImagePath = XML.getValue("CONFIG:BACKGROUND:IMAGE",""); filter->bLearnBackground = backgroundMode == "AUTO";//= XML.getValue("CONFIG:BOOLEAN:LEARNBG",0); filter->bVerticalMirror = XML.getValue("CONFIG:BOOLEAN:VMIRROR",0); filter->bHorizontalMirror = XML.getValue("CONFIG:BOOLEAN:HMIRROR",0); //fmv settings ffmvMemoryChannel = XML.getValue("CONFIG:FFMV:MEMORY_CHANNEL",0); //Logging printfToFile = XML.getValue("CONFIG:BOOLEAN:PRINTFTOFILE",0); //Filters filter->bTrackDark = XML.getValue("CONFIG:BOOLEAN:TRACKDARK", 0); filter->bHighpass = XML.getValue("CONFIG:BOOLEAN:HIGHPASS",1); filter->bAmplify = XML.getValue("CONFIG:BOOLEAN:AMPLIFY", 1); filter->bSmooth = XML.getValue("CONFIG:BOOLEAN:SMOOTH", 1); filter->bDynamicBG = XML.getValue("CONFIG:BOOLEAN:DYNAMICBG", 1); //MODES bGPUMode = XML.getValue("CONFIG:BOOLEAN:GPU", 0); bMiniMode = XML.getValue("CONFIG:BOOLEAN:MINIMODE",0); //CONTROLS tracker.MIN_MOVEMENT_THRESHOLD = XML.getValue("CONFIG:INT:MINMOVEMENT",0); MIN_BLOB_SIZE = XML.getValue("CONFIG:INT:MINBLOBSIZE",2); MAX_BLOB_SIZE = XML.getValue("CONFIG:INT:MAXBLOBSIZE",100); backgroundLearnRate = XML.getValue("CONFIG:INT:BGLEARNRATE", 0.01f); //Filter Settings filter->threshold = XML.getValue("CONFIG:INT:THRESHOLD",0); filter->highpassBlur = XML.getValue("CONFIG:INT:HIGHPASSBLUR",0); filter->highpassNoise = XML.getValue("CONFIG:INT:HIGHPASSNOISE",0); filter->highpassAmp = XML.getValue("CONFIG:INT:HIGHPASSAMP",0); filter->smooth = XML.getValue("CONFIG:INT:SMOOTH",0); //NETWORK SETTINGS bTUIOMode = XML.getValue("CONFIG:BOOLEAN:TUIO",0); myTUIO.bOSCMode = XML.getValue("CONFIG:BOOLEAN:OSCMODE",1); myTUIO.bTCPMode = XML.getValue("CONFIG:BOOLEAN:TCPMODE",1); myTUIO.bHeightWidth = XML.getValue("CONFIG:BOOLEAN:HEIGHTWIDTH",0); tmpLocalHost = XML.getValue("CONFIG:NETWORK:LOCALHOST", "localhost"); tmpPort = XML.getValue("CONFIG:NETWORK:TUIOPORT_OUT", 3333); tmpFlashPort = XML.getValue("CONFIG:NETWORK:TUIOFLASHPORT_OUT", 3000); networkInterface = XML.getValue("CONFIG:NETWORK:NETWORK_INTERFACE_NR", 0); myTUIO.setup(tmpLocalHost.c_str(), tmpPort, tmpFlashPort,camWidth,camHeight); //have to convert tmpLocalHost to a const char* myTUIO.setNetworkInterface (networkInterface); udp_alive_connection.udp_in_port = XML.getValue("CONFIG:NETWORK:UDP_ALIVE:IN_PORT", 100000); udp_alive_connection.udp_out_port = XML.getValue("CONFIG:NETWORK:UDP_ALIVE:OUT_PORT", 100001); udp_alive_connection.udp_out_host = XML.getValue("CONFIG:NETWORK:UDP_ALIVE:OUT_HOST", "127.0.0.2"); udp_alive_connection.host = myTUIO.host_name; bUndistort = XML.getValue("CONFIG:BOOLEAN:UNDISTORT", 0); //-------------------------------------------------------------- bTrackFiducials = XML.getValue("CONFIG:FIDUCIAL:TRACKING",0); fiducialTreePath = XML.getValue("CONFIG:FIDUCIAL:TREE_FILE",""); //Fiducial_Filters filter_fiducial->bLearnBackground = filter->bLearnBackground;//XML.getValue("LEARNBG",0); filter_fiducial->bVerticalMirror = filter->bVerticalMirror;//XML.getValue("VMIRROR",0); filter_fiducial->bHorizontalMirror = filter->bHorizontalMirror;//XML.getValue("HMIRROR",0); //XML.pushTag("CONFIG:FIDUCIAL" , 0); filter_fiducial->bTrackDark = XML.getValue("CONFIG:FIDUCIAL:BOOLEAN:TRACKDARK", 0); filter_fiducial->bHighpass = XML.getValue("CONFIG:FIDUCIAL:BOOLEAN:HIGHPASS",0); filter_fiducial->bAmplify = XML.getValue("CONFIG:FIDUCIAL:BOOLEAN:AMPLIFY", 1); filter_fiducial->bSmooth = XML.getValue("CONFIG:FIDUCIAL:BOOLEAN:SMOOTH", 1); filter_fiducial->bDynamicBG = XML.getValue("CONFIG:BOOLEAN:DYNAMICBG", 1);//!!! synchron with normal filter //Filter Settings filter_fiducial->threshold = XML.getValue("CONFIG:FIDUCIAL:INT:THRESHOLD",0); filter_fiducial->highpassBlur = XML.getValue("CONFIG:FIDUCIAL:INT:HIGHPASSBLUR",0); filter_fiducial->highpassNoise = XML.getValue("CONFIG:FIDUCIAL:INT:HIGHPASSNOISE",0); filter_fiducial->highpassAmp = XML.getValue("CONFIG:FIDUCIAL:INT:HIGHPASSAMP",0); filter_fiducial->smooth = XML.getValue("CONFIG:FIDUCIAL:INT:SMOOTH",0); //XML.popTag(); char* temp = new char[255]; strcpy (temp,const_cast<char*>(XML.getValue("CONFIG:NETWORK:TUIO_SOURCE_APPLICATION","DEFAULT").c_str() ) ); myTUIO.tuio_source_application = temp; myTUIO.setup_tuio_source_String();// calibration_udp_port = XML.getValue("CONFIG:NETWORK:CALIBRATION_UDP_PORT", 0); calibration_udp_host = XML.getValue("CONFIG:NETWORK:CALIBRATION_HOST", "localhost"); // position of the propertiesPanel string xmlPath; xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:SOURCE_PROPERTIES:X": "CONFIG:PROPERTIESPANEL:SOURCE_PROPERTIES:X" ; source_properties_panel_pos.x = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:SOURCE_PROPERTIES:Y": "CONFIG:PROPERTIESPANEL:SOURCE_PROPERTIES:Y" ; source_properties_panel_pos.y = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:GPU_PROPERTIES:X": "CONFIG:PROPERTIESPANEL:GPU_PROPERTIES:X" ; gpu_properties_panel_pos.x = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:GPU_PROPERTIES:Y": "CONFIG:PROPERTIESPANEL:GPU_PROPERTIES:Y" ; gpu_properties_panel_pos.y = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:COMMUNICATION:X": "CONFIG:PROPERTIESPANEL:COMMUNICATION:X" ; communication_properties_panel_pos.x = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:COMMUNICATION:Y": "CONFIG:PROPERTIESPANEL:COMMUNICATION:Y" ; communication_properties_panel_pos.y = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:CALIBRATION:X": "CONFIG:PROPERTIESPANEL:CALIBRATION:X" ; calibration_properties_panel_pos.x = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:CALIBRATION:Y": "CONFIG:PROPERTIESPANEL:CALIBRATION:Y" ; calibration_properties_panel_pos.y = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:FILES:X": "CONFIG:PROPERTIESPANEL:FILES:X" ; files_properties_panel_pos.x = XML.getValue(xmlPath,0); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:PROPERTIESPANEL:FILES:Y": "CONFIG:PROPERTIESPANEL:FILES:Y" ; files_properties_panel_pos.y = XML.getValue(xmlPath,0); //----added by Stefan Schlupek xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:WINDOW:WIDTH": "CONFIG:WINDOW:WIDTH" ; winWidth = XML.getValue(xmlPath, 950); xmlPath = bTrackFiducials ? "CONFIG:FIDUCIAL:WINDOW:HEIGHT": "CONFIG:WINDOW:HEIGHT" ; winHeight = XML.getValue(xmlPath, 600); // END XML SETUP } void ofxNCoreVision::saveSettings() { XML.setValue("CONFIG:CAMERA_0:USECAMERA", bcamera); XML.setValue("CONFIG:CAMERA_0:DEVICE", deviceID); XML.setValue("CONFIG:CAMERA_0:WIDTH", camWidth); XML.setValue("CONFIG:CAMERA_0:HEIGHT", camHeight); XML.setValue("CONFIG:CAMERA_0:FRAMERATE", camRate); XML.setValue("CONFIG:BOOLEAN:PRESSURE",bShowPressure); XML.setValue("CONFIG:BOOLEAN:LABELS",bShowLabels); XML.setValue("CONFIG:BOOLEAN:OUTLINES",bDrawOutlines); //XML.setValue("CONFIG:BOOLEAN:LEARNBG", filter->bLearnBackground ); XML.setValue("CONFIG:BOOLEAN:VMIRROR", filter->bVerticalMirror); XML.setValue("CONFIG:BOOLEAN:HMIRROR", filter->bHorizontalMirror); XML.setValue("CONFIG:BOOLEAN:PRINTFTOFILE", printfToFile); XML.setValue("CONFIG:BOOLEAN:TRACKDARK", filter->bTrackDark); XML.setValue("CONFIG:BOOLEAN:HIGHPASS", filter->bHighpass); XML.setValue("CONFIG:BOOLEAN:AMPLIFY", filter->bAmplify); XML.setValue("CONFIG:BOOLEAN:SMOOTH", filter->bSmooth); XML.setValue("CONFIG:BOOLEAN:DYNAMICBG", filter->bDynamicBG); XML.setValue("CONFIG:BOOLEAN:GPU", bGPUMode); XML.setValue("CONFIG:INT:MINMOVEMENT", tracker.MIN_MOVEMENT_THRESHOLD); XML.setValue("CONFIG:INT:MINBLOBSIZE", MIN_BLOB_SIZE); XML.setValue("CONFIG:INT:MAXBLOBSIZE", MAX_BLOB_SIZE); XML.setValue("CONFIG:INT:BGLEARNRATE", backgroundLearnRate); XML.setValue("CONFIG:INT:THRESHOLD", filter->threshold); XML.setValue("CONFIG:INT:HIGHPASSBLUR", filter->highpassBlur); XML.setValue("CONFIG:INT:HIGHPASSNOISE", filter->highpassNoise); XML.setValue("CONFIG:INT:HIGHPASSAMP", filter->highpassAmp); XML.setValue("CONFIG:INT:SMOOTH", filter->smooth); XML.setValue("CONFIG:BOOLEAN:MINIMODE", bMiniMode); XML.setValue("CONFIG:BOOLEAN:TUIO",bTUIOMode); XML.setValue("CONFIG:BOOLEAN:HEIGHTWIDTH", myTUIO.bHeightWidth); XML.setValue("CONFIG:BOOLEAN:OSCMODE", myTUIO.bOSCMode); XML.setValue("CONFIG:BOOLEAN:TCPMODE", myTUIO.bTCPMode); // XML.setValue("CONFIG:NETWORK:LOCALHOST", myTUIO.localHost); // XML.setValue("CONFIG:NETWORK:TUIO_PORT_OUT",myTUIO.TUIOPort); //fiducial settings XML.setValue("CONFIG:FIDUCIAL:INT:THRESHOLD", filter_fiducial->threshold); XML.setValue("CONFIG:FIDUCIAL:INT:SMOOTH", filter_fiducial->smooth ); XML.setValue("CONFIG:FIDUCIAL:INT:HIGHPASSAMP", filter_fiducial->highpassAmp); XML.setValue("CONFIG:FIDUCIAL:BOOLEAN:SMOOTH", filter_fiducial->bSmooth); XML.setValue("CONFIG:FIDUCIAL:BOOLEAN:AMPLIFY", filter_fiducial->bAmplify); //calibration_udp_port = XML.getValue("CONFIG:NETWORK:CALIBRATION_UDP_PORT", 0); //calibration_udp_host = XML.getValue("CONFIG:NETWORK:CALIBRATION_HOST", "localhost"); //-- XML.saveFile("config.xml"); } /************************************************ * Init Device ************************************************/ //Init Device (camera/video) void ofxNCoreVision::initDevice(){ //save/update log file if(printfToFile) if((stream = freopen(fileName, "a", stdout)) == NULL){} //Pick the Source - camera or video if (bcamera) { //check if a firefly, ps3 camera, or other is plugged in #ifdef TARGET_WIN32 /****PS3 - PS3 camera only****/ if(ofxPS3::getDeviceCount() > 0 && PS3 == NULL && deviceModel=="PS3"){ PS3 = new ofxPS3(); PS3->listDevices(); PS3->initPS3(camWidth, camHeight, camRate); camWidth = PS3->getCamWidth(); camHeight = PS3->getCamHeight(); printf("PS3 Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, PS3->getCamWidth(), PS3->getCamHeight()); return; } /****ffmv - firefly camera only****/ else if(ofxffmv::getDeviceCount() > 0 && ffmv == NULL && deviceModel=="FFMV"){ ffmv = new ofxffmv(); ffmv->setDeviceID(deviceID);//Here we could change the Camera ffmv->listDevices(); //here we set the Memeory Chanel to restore camera settings from the driver ffmv->setMemoryChannel(ffmvMemoryChannel); ffmv->initFFMV(camWidth,camHeight,camRate); printf("FFMV Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, ffmv->getCamWidth(), ffmv->getCamHeight()); camWidth = ffmv->getCamWidth(); camHeight = ffmv->getCamHeight(); return; } else if( vidGrabber == NULL ) { vidGrabber = new ofVideoGrabber(); vidGrabber->listDevices(); vidGrabber->setDeviceID(deviceID); vidGrabber->setVerbose(true); vidGrabber->initGrabber(camWidth,camHeight); printf("vidGrabber Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, vidGrabber->width, vidGrabber->height); camWidth = vidGrabber->width; camHeight = vidGrabber->height; return; } else if( dsvl == NULL) { dsvl = new ofxDSVL(); dsvl->initDSVL(); printf("DSVL Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, dsvl->getCamWidth(), dsvl->getCamHeight()); camWidth = dsvl->getCamWidth(); camHeight = dsvl->getCamHeight(); return; } #else if( vidGrabber == NULL ) { vidGrabber = new ofVideoGrabber(); vidGrabber->listDevices(); vidGrabber->setDeviceID(deviceID); vidGrabber->setVerbose(true); vidGrabber->initGrabber(camWidth,camHeight); printf("Camera Mode\nAsked for %i by %i - actual size is %i by %i \n\n", camWidth, camHeight, vidGrabber->width, vidGrabber->height); camWidth = vidGrabber->width; camHeight = vidGrabber->height; return; } #endif }else{ if( vidPlayer == NULL ) { vidPlayer = new ofVideoPlayer(); vidPlayer->loadMovie( videoFileName ); vidPlayer->play(); vidPlayer->setLoopState(OF_LOOP_NORMAL); printf("Video Mode\n\n"); camHeight = vidPlayer->height; camWidth = vidPlayer->width; return; } } } /****************************************************************************** * The update function runs continuously. Use it to update states and variables *****************************************************************************/ void ofxNCoreVision::_update(ofEventArgs &e) { //save/update log file if(printfToFile) if((stream = freopen(fileName, "a", stdout)) == NULL){} if(udp_alive_connection.isOUTConnected){ udp_alive_connection.readMessage(); } if(exited) return; bNewFrame = false; if (bcamera) //if camera { #ifdef TARGET_WIN32 if(PS3!=NULL)//ps3 camera { bNewFrame = PS3->isFrameNew(); } else if(ffmv!=NULL) { ffmv->grabFrame(); bNewFrame = true; } else if(vidGrabber !=NULL) { vidGrabber->grabFrame(); bNewFrame = vidGrabber->isFrameNew(); } else if(dsvl !=NULL) { bNewFrame = dsvl->isFrameNew(); } #else vidGrabber->grabFrame(); bNewFrame = vidGrabber->isFrameNew(); #endif } else //if video { vidPlayer->idleMovie(); bNewFrame = vidPlayer->isFrameNew(); } //if no new frame, return if(!bNewFrame){ return; } else//else process camera frame { ofBackground(0, 0, 0); // Calculate FPS of Camera frames++; float time = ofGetElapsedTimeMillis(); if (time > (lastFPSlog + 1000)) { fps = frames; frames = 0; lastFPSlog = time; }//End calculation float beforeTime = ofGetElapsedTimeMillis(); if (bGPUMode) { grabFrameToGPU(filter->gpuSourceTex); filter->applyGPUFilters(); contourFinder.findContours(filter->gpuReadBackImageGS, (MIN_BLOB_SIZE * 2) + 1, ((camWidth * camHeight) * .4) * (MAX_BLOB_SIZE * .001), maxBlobs, false); //---added by Stefan Schlupek if(!bCalibration){ deleteOutsideBlobs(); } if(bTrackFiducials){ grabFrameToGPU(filter_fiducial->gpuSourceTex); filter_fiducial->applyGPUFilters(); fidfinder.findFiducials( filter_fiducial->gpuReadBackImageGS ); prepareFiducialPositions(); } //---------- } else { grabFrameToCPU(); filter->applyCPUFilters( processedImg ); contourFinder.findContours(processedImg, (MIN_BLOB_SIZE * 2) + 1, ((camWidth * camHeight) * .4) * (MAX_BLOB_SIZE * .001), maxBlobs, false); //---added by Stefan Schlupek //Map points to undistortion map? if(!bCalibration){ deleteOutsideBlobs(); } if(bTrackFiducials){ filter_fiducial->applyCPUFilters( processedImg_fiducial ); fidfinder.findFiducials( processedImg_fiducial ); // printf("fiducialsList.preerase!!!!%d\n\n", fidfinder.fiducialsList.size()); prepareFiducialPositions(); } //---------- } //Track found contours/blobss tracker.track(&contourFinder); //get DSP time differenceTime = ofGetElapsedTimeMillis() - beforeTime; //Dynamic Background subtraction LearRate if (filter->bDynamicBG) { filter->fLearnRate = backgroundLearnRate * .0001; //If there are no blobs, add the background faster. if (contourFinder.nBlobs > 0) //If there ARE blobs, add the background slower. { filter->fLearnRate = backgroundLearnRate * .0001; } }//End Background Learning rate if (bTUIOMode) { //Start sending OSC //myTUIO.sendTUIO(&getBlobs()); myTUIO.sendTUIO(&getBlobs(), &fidfinder.fiducialsList); } } } /******************************************* * added by Stefan Schlupek * Delete blobs that outside of the calibration area. * should be in the ContourFinder.findContours() Method but i came into big trouble * with the Compiler when i'm trying to implement it ( Calibration instance as parameter for the findcontours() Method doesn't work * don't know what problems the compiler has , i think it's an include problem ********************************************/ void ofxNCoreVision::deleteOutsideBlobs(){ //to delete the blobs outside the tracking area vector<Blob>::iterator it = contourFinder.blobs.begin(); int t ; while( it != contourFinder.blobs.end() ) { Blob b = *it; vector2df pt= vector2df(b.centroid.x, b.centroid.y); // printf("Blob.pt:%f:%f\n", pt.X,pt.Y); t = calib.calibrate.findTriangleWithin(pt); if(t == -1) { contourFinder.blobs.erase(it); }else{ ++it; } }//while contourFinder.nBlobs = contourFinder.blobs.size(); } /** Delete Fiducials who are outside the calibration area and map the position from the FiducalTracker **/ void ofxNCoreVision::prepareFiducialPositions(){ //mapFiducialsToScreenPosition();// calib.calibrate.cameraToScreenPosition(x,y); //fidfinder.fiducialsList int t ; //printf("fiducialsList.prerase:%d\n", fidfinder.fiducialsList.size()); for (std::list<ofxFiducial>::iterator fiducial = fidfinder.fiducialsList.begin(); fiducial != fidfinder.fiducialsList.end(); ) { //getCameraToScreenX() float x = fiducial->getX(); float y = fiducial->getY(); vector2df pt = vector2df(x, y); //printf("-fiducial:%p:\n", &fiducial); // printf("-fiducial.back:%p:\n", & fidfinder.fiducialsList.back()); //printf("fiducial.pt:%f:%f\n", pt.X,pt.Y); t = calib.calibrate.findTriangleWithin(pt); if(t == -1) { //printf("fiducialsList.erase!!!!\n"); fiducial = fidfinder.fiducialsList.erase(fiducial); //++it; // printf("fiducialsList.erase2!!!!%d\n", fidfinder.fiducialsList.size()); }else{ //weired bug: there could be the case that we findTriangleWithin, but the vector values in the cameraToScreenMap are 0.00000000 // as at creation time of the map, the point seemed not to be in a triangle //is this a rounding error? so we have to check this (perhaps in vector2df::isOnSameSide() ) calib.calibrate.cameraToScreenPosition(x,y); if(x== NULL && y == NULL){ fiducial = fidfinder.fiducialsList.erase(fiducial); }else{ fiducial->setCameraToScreenPosition(x,y); ++fiducial; } } //calib.calibrate.cameraToScreenPosition(x,y); } } /************************************************ * Input Device Stuff ************************************************/ //get pixels from camera void ofxNCoreVision::getPixels(){ //printf("getPixels\n"); #ifdef TARGET_WIN32 if(PS3!=NULL){ sourceImg.setFromPixels(PS3->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; //if(bUndistort) {undistortImage( processedImg);} if(bTrackFiducials){processedImg_fiducial = sourceImg;} if(bUndistort){undistortedImg = sourceImg;} } else if(ffmv != NULL){ processedImg.setFromPixels(ffmv->fcImage[0].pData, camWidth, camHeight); //if(bUndistort) {undistortImage( processedImg);} if(bTrackFiducials){processedImg_fiducial.setFromPixels(ffmv->fcImage[0].pData, camWidth, camHeight);} if(bUndistort){undistortedImg = processedImg;} } else if(vidGrabber != NULL ) { sourceImg.setFromPixels(vidGrabber->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; //if(bUndistort) {undistortImage( processedImg);} if(bTrackFiducials){processedImg_fiducial = sourceImg;} if(bUndistort){undistortedImg = sourceImg;} } else if(dsvl!=NULL) { if(dsvl->getNumByes() != 1){ //if not grayscale sourceImg.setFromPixels(dsvl->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; //if(bUndistort) {undistortImage( processedImg);} if(bTrackFiducials){processedImg_fiducial = sourceImg;} if(bUndistort){undistortedImg = sourceImg;} } else{//if grayscale processedImg.setFromPixels(dsvl->getPixels(), camWidth, camHeight); //if(bUndistort) {undistortImage( processedImg);} if(bTrackFiducials){processedImg_fiducial.setFromPixels(dsvl->getPixels(), camWidth, camHeight);} if(bUndistort){undistortedImg = processedImg;} } } #endif } //Grab frame from CPU void ofxNCoreVision::grabFrameToCPU() { //printf("grabFrameToCPU\n"); //Set sourceImg as new camera/video frame if (bcamera) { #ifdef TARGET_WIN32 getPixels(); #else sourceImg.setFromPixels(vidGrabber->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; if(bTrackFiducials){processedImg_fiducial = sourceImg;} #endif } else { sourceImg.setFromPixels(vidPlayer->getPixels(), camWidth, camHeight); //convert to grayscale processedImg = sourceImg; //if(bUndistort) {undistortImage( processedImg);} if(bTrackFiducials){processedImg_fiducial = sourceImg;} } } //Grab frame from GPU void ofxNCoreVision::grabFrameToGPU(GLuint target) { //grab the frame to a raw openGL texture if (bcamera) { glEnable(GL_TEXTURE_2D); //glPixelStorei(1); glBindTexture(GL_TEXTURE_2D, target); #ifdef TARGET_WIN32 if(PS3!=NULL) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, PS3->getPixels()); } else if(ffmv != NULL){ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_LUMINANCE, GL_UNSIGNED_BYTE, ffmv->fcImage[0].pData); } else if(vidGrabber!=NULL) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, vidGrabber->getPixels()); } else if(dsvl!=NULL) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, dsvl->getPixels()); } #else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, vidGrabber->getPixels()); #endif glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D,0); } else { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, target); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, camWidth, camHeight, GL_RGB, GL_UNSIGNED_BYTE, vidPlayer->getPixels()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D,0); } } /****************************************************************************** * The draw function paints the textures onto the screen. It runs after update. *****************************************************************************/ void ofxNCoreVision::_draw(ofEventArgs &e) { if(exited) return; if (showConfiguration) { //if calibration if (bCalibration) { //Don't draw main interface calib.passInContourFinder(contourFinder.nBlobs, contourFinder.blobs); calib.doCalibration(); //---Added by Stefan Schlupek //here we could triger the UDP message for highlighting the selected Finger. calib.calibrate.calibrationStep if(currCalibrationStep != calib.calibrate.calibrationStep){ currCalibrationStep = calib.calibrate.calibrationStep; char* message = new char[256]; sprintf(message,"calibrate|POINT|%s|%d",myTUIO.tuio_source_String,calib.calibrate.calibrationStep); int sent = calib.calibrate.udpConnection.Send(message,strlen(message)+1); delete message; } //----------------- } //if mini mode else if (bMiniMode) { drawMiniMode(); } //if full mode else if (bShowInterface) { drawFullMode(); if(bDrawOutlines || bShowLabels) drawFingerOutlines(); //----Added by Stefan Schlupek if(bTrackFiducials){drawFiducials();} //------------------------------ } //draw gui controls if (!bCalibration && !bMiniMode) {controls->draw();} } } void ofxNCoreVision::drawFullMode(){ ofSetColor(0xFFFFFF); //Draw Background Image background.draw(0, 0); //Draw arrows ofSetColor(187, 200, 203); ofFill(); ofTriangle(680, 420, 680, 460, 700, 440); ofTriangle(70, 420, 70, 460, 50, 440); ofSetColor(255, 255, 0); ofSetColor(0xFFFFFF); //Draw Image Filters To Screen if (bGPUMode) { filter->drawGPU(); if(bTrackFiducials){filter_fiducial->drawGPU_fiducial();} } else { filter->draw(); //filter_fiducial->draw(720,30,320,240); if(bTrackFiducials){filter_fiducial->draw_fiducial();} //cout << "<<<<<<<<<<<<" <<calib.getCalibrationUtils()->camCalib.distortionCoeffs[0] << endl; if(bUndistort){ if(filter->bVerticalMirror || filter->bHorizontalMirror) undistortedImg.mirror(filter->bVerticalMirror, filter->bHorizontalMirror); undistortImage( undistortedImg); /* undistortedImg.undistort( calib.getCalibrationUtils()->camCalib.distortionCoeffs[0], calib.getCalibrationUtils()->camCalib.distortionCoeffs[1], calib.getCalibrationUtils()->camCalib.distortionCoeffs[2], calib.getCalibrationUtils()->camCalib.distortionCoeffs[3], calib.getCalibrationUtils()->camCalib.camIntrinsics[0], calib.getCalibrationUtils()->camCalib.camIntrinsics[4], calib.getCalibrationUtils()->camCalib.camIntrinsics[2], calib.getCalibrationUtils()->camCalib.camIntrinsics[5] ); */ undistortedImg.draw(winWidth-180,winHeight-140,160,120);//winWidth,winHeight }//Undistort } ofSetColor(0x000000); if (bShowPressure) { bigvideo.drawString("Pressure Map", 140, 20); } else { bigvideo.drawString("Source Image", 140, 20); } bigvideo.drawString("Tracked Image", 475, 20); if(bTrackFiducials){bigvideo.drawString("Fiducial_Tracked Image", 830, 20);} /* //draw link to tbeta website ofSetColor(79, 79, 79); ofFill(); ofRect(721, 586, 228, 14); ofSetColor(0xFFFFFF); ofDrawBitmapString("| ~ |tbeta.nuigroup.com", 725, 596); */ //Display Application information in bottom right string str = "Calc. Time [ms]: "; str+= ofToString(differenceTime, 0)+"\n\n"; if (bcamera) { string str2 = "Camera [Res]: "; str2+= ofToString(camWidth, 0) + " x " + ofToString(camHeight, 0) + "\n"; string str4 = "Camera [fps]: "; str4+= ofToString(fps, 0)+"\n"; ofSetColor(0xFFFFFF); verdana.drawString(str + str2 + str4, 740, 410); } else { string str2 = "Video [Res]: "; str2+= ofToString(vidPlayer->width, 0) + " x " + ofToString(vidPlayer->height, 0) + "\n"; string str4 = "Video [fps]: "; str4+= ofToString(fps, 0)+"\n"; ofSetColor(0xFFFFFF); verdana.drawString(str + str2 + str4, 740, 410); } if (bTUIOMode) { //Draw Port and IP to screen ofSetColor(0xffffff); char buf[256]; if(myTUIO.bOSCMode) sprintf(buf, "Sending OSC messages to:\nHost: %s\nPort: %i", myTUIO.localHost, myTUIO.TUIOPort); else{ if(myTUIO.bIsConnected) sprintf(buf, "Sending TCP messages to:\nPort: %i", myTUIO.TUIOFlashPort); else sprintf(buf, "Could not bind or send TCP to:\nPort: %i", myTUIO.TUIOFlashPort); } verdana.drawString(buf, 740, 480); } ofSetColor(0xFF0000); verdana.drawString("Press spacebar to toggle fast mode", 730, 472); } void ofxNCoreVision::drawMiniMode() { //black background ofSetColor(0,0,0); ofRect(0,0,ofGetWidth(), ofGetHeight()); //draw outlines if (bDrawOutlines){ for (int i=0; i<contourFinder.nBlobs; i++) { contourFinder.blobs[i].drawContours(0,0, camWidth, camHeight+175, ofGetWidth(), ofGetHeight()); } } //draw grey rectagles for text information ofSetColor(128,128,128); ofFill(); ofRect(0,ofGetHeight() - 83, ofGetWidth(), 20); ofRect(0,ofGetHeight() - 62, ofGetWidth(), 20); ofRect(0,ofGetHeight() - 41, ofGetWidth(), 20); ofRect(0,ofGetHeight() - 20, ofGetWidth(), 20); //draw text ofSetColor(250,250,250); verdana.drawString("Calc. Time [ms]: " + ofToString(differenceTime,0),10, ofGetHeight() - 70 ); if (bcamera){ verdana.drawString("Camera [fps]: " + ofToString(fps,0),10, ofGetHeight() - 50 ); } else { verdana.drawString("Video [fps]: " + ofToString(fps,0),10, ofGetHeight() - 50 ); } verdana.drawString("Blob Count: " + ofToString(contourFinder.nBlobs,0),10, ofGetHeight() - 29 ); verdana.drawString("Sending TUIO: " ,10, ofGetHeight() - 9 ); //draw green tuio circle if((myTUIO.bIsConnected || myTUIO.bOSCMode) && bTUIOMode)//green = connected ofSetColor(0x00FF00); else ofSetColor(0xFF0000); //red = not connected ofFill(); ofCircle(ofGetWidth() - 17 , ofGetHeight() - 10, 5); ofNoFill(); } void ofxNCoreVision::drawFingerOutlines() { //Find the blobs for drawing for (int i=0; i<contourFinder.nBlobs; i++) { if (bDrawOutlines) { //Draw contours (outlines) on the source image contourFinder.blobs[i].drawContours(40, 30, camWidth, camHeight, MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT); } if (bShowLabels) //Show ID label; { float xpos = contourFinder.blobs[i].centroid.x * (MAIN_WINDOW_WIDTH/camWidth); float ypos = contourFinder.blobs[i].centroid.y * (MAIN_WINDOW_HEIGHT/camHeight); ofSetColor(0xCCFFCC); char idStr[1024]; sprintf(idStr, "id: %i", contourFinder.blobs[i].id); verdana.drawString(idStr, xpos + 365, ypos + contourFinder.blobs[i].boundingRect.height/2 + 45); } } ofSetColor(0xFFFFFF); } /*------------------------------------------------------------------------- added by Stefan Schlupek */ void ofxNCoreVision::drawFiducials(){ //you can use this method for the FidicialFinder /*for(int f=0; f<fidfinder._fiducials.size() ;f++) { fidfinder._fiducials[f].draw( 20, 20 ); }*/ //use this method for the FiducialTracker //to get fiducial info you can use the fiducial getter methods char idStr[1024]; //sprintf(idStr, "scaleWidth: %f", fiducialDrawFactor_Width); //verdana.drawString(idStr, 730, 562); for (list<ofxFiducial>::iterator fiducial = fidfinder.fiducialsList.begin(); fiducial != fidfinder.fiducialsList.end(); fiducial++) { //Nasty hack: hardcoded Position of the offset to draw into the right position fiducial->drawScaled(40,30,fiducialDrawFactor_Width,fiducialDrawFactor_Height); //fiducial->drawCorners( 40, 30 );//draw corners fiducial->drawCornersScaled( 40, 30 ,fiducialDrawFactor_Width,fiducialDrawFactor_Height);//draw corners /* ofSetColor(0,0,255);//set color to blue //if mouse (- 20 to compensate for drawing at 20) is inside fiducial then fill if (fiducial->isPointInside(mouseX - 20, mouseY - 20)) ofFill(); else ofNoFill();// else dont ofCircle(mouseX, mouseY, 10);//draw mouse position */ ofSetColor(255,255,255);//reset color to white //like this one below //cout << "fiducial " << fiducial->getId() << " found at ( " << fiducial->getX() << "," << fiducial->getY() << " )" << endl; //take a good look at the fiducial class to get all the info and a few helper functions } //draw the fingers for (list<ofxFinger>::iterator finger = fidfinder.fingersList.begin(); finger != fidfinder.fingersList.end(); finger++) { finger->draw(20, 20); } } //---------------------------------------------- void ofxNCoreVision::saveBackground(){ ofImage bgImg; bgImg.allocate(camWidth,camHeight,OF_IMAGE_GRAYSCALE); bgImg.setFromPixels(filter->floatBgImg.getPixels(),camWidth, camHeight,OF_IMAGE_GRAYSCALE); bgImg.saveImage(backgroundImagePath); } //Method for POCO Event system. didn't get a version realized with no arguments 02.09.10 by stefan Schlupek void ofxNCoreVision::makeAndSaveBackground(char &args){ grabFrameToCPU(); if(filter->bVerticalMirror || filter->bHorizontalMirror) processedImg.mirror(filter->bVerticalMirror, filter->bHorizontalMirror); filter->setCPUBackgroundImage(processedImg); filter_fiducial->setCPUBackgroundImage(processedImg); saveBackground(); } void ofxNCoreVision::loadBackground(){ ofImage bgImg; ofxCvGrayscaleImage bgImgBW; if (bGPUMode) { //TODO !!!! }else{ bgImg.loadImage(backgroundImagePath); bgImg.setImageType(OF_IMAGE_GRAYSCALE); bgImgBW.allocate(camWidth, camHeight); bgImgBW.setFromPixels( bgImg.getPixels(),camWidth, camHeight); filter->setCPUBackgroundImage(bgImgBW); filter_fiducial->setCPUBackgroundImage(bgImgBW); } } //ofxCvGrayscaleImage void ofxNCoreVision::undistortImage( ofxCvImage &img){ img.undistort( calib.getCalibrationUtils()->camCalib.distortionCoeffs[0], calib.getCalibrationUtils()->camCalib.distortionCoeffs[1], calib.getCalibrationUtils()->camCalib.distortionCoeffs[2], calib.getCalibrationUtils()->camCalib.distortionCoeffs[3], calib.getCalibrationUtils()->camCalib.camIntrinsics[0], calib.getCalibrationUtils()->camCalib.camIntrinsics[4], calib.getCalibrationUtils()->camCalib.camIntrinsics[2], calib.getCalibrationUtils()->camCalib.camIntrinsics[5] ); } /***************************************************************************** * KEY EVENTS *****************************************************************************/ void ofxNCoreVision::_keyPressed(ofKeyEventArgs &e) { // detect escape key if(e.key==0x1b) { exited=true; } if (showConfiguration) { switch (e.key) { case 'a': filter->threshold++; controls->update(appPtr->trackedPanel_threshold, kofxGui_Set_Int, &appPtr->filter->threshold, sizeof(int)); break; case 'z': filter->threshold--; controls->update(appPtr->trackedPanel_threshold, kofxGui_Set_Int, &appPtr->filter->threshold, sizeof(int)); break; case 'b': filter->bLearnBackground = true; filter_fiducial->bLearnBackground = true; break; case 'o': bDrawOutlines ? bDrawOutlines = false : bDrawOutlines = true; controls->update(appPtr->trackedPanel_outlines, kofxGui_Set_Bool, &appPtr->bDrawOutlines, sizeof(bool)); break; case 'h': filter->bHorizontalMirror ? filter->bHorizontalMirror = false : filter->bHorizontalMirror = true; controls->update(appPtr->propertiesPanel_flipH, kofxGui_Set_Bool, &appPtr->filter->bHorizontalMirror, sizeof(bool)); break; case 'j': filter->bVerticalMirror ? filter->bVerticalMirror = false : filter->bVerticalMirror = true; filter_fiducial->bVerticalMirror ? filter_fiducial->bVerticalMirror = false : filter_fiducial->bVerticalMirror = true; controls->update(appPtr->propertiesPanel_flipV, kofxGui_Set_Bool, &appPtr->filter->bVerticalMirror, sizeof(bool)); break; case 't': myTUIO.bOSCMode = !myTUIO.bOSCMode; myTUIO.bTCPMode = false; bTUIOMode = myTUIO.bOSCMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'f': myTUIO.bOSCMode = false; myTUIO.bTCPMode = !myTUIO.bTCPMode; bTUIOMode = myTUIO.bTCPMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'g': bGPUMode ? bGPUMode = false : bGPUMode = true; controls->update(appPtr->gpuPanel_use, kofxGui_Set_Bool, &appPtr->bGPUMode, sizeof(bool)); filter->bLearnBackground = true; filter_fiducial->bLearnBackground = true; break; case 'v': if (bcamera && vidGrabber != NULL) vidGrabber->videoSettings(); break; case 'l': bShowLabels ? bShowLabels = false : bShowLabels = true; controls->update(appPtr->trackedPanel_ids, kofxGui_Set_Bool, &appPtr->bShowLabels, sizeof(bool)); break; case 'p': bShowPressure ? bShowPressure = false : bShowPressure = true; break; case ' ': if (bMiniMode && !bCalibration) // NEED TO ADD HERE ONLY GO MINI MODE IF NOT CALIBRATING { bMiniMode = false; bShowInterface = true; filter->bMiniMode = bMiniMode; filter_fiducial->bMiniMode = bMiniMode; //ofSetWindowShape(950,600); //default size ofSetWindowShape(winWidth,winHeight); } else if(!bCalibration) { bMiniMode = true; bShowInterface = false; filter->bMiniMode = bMiniMode; filter_fiducial->bMiniMode = bMiniMode; ofSetWindowShape(190,200); //minimized size } break; case 'x': //Exit Calibrating if (bCalibration) { bShowInterface = true; bCalibration = false; calib.calibrating = false; tracker.isCalibrating = false; if (bFullscreen == true) ofToggleFullscreen(); bFullscreen = false; //added by stefan Schlupek-------- char* message = new char[512]; sprintf(message,"%s|%s","calibrate|OFF",myTUIO.tuio_source_String); int sent = calib.calibrate.udpConnection.Send(message,strlen(message)+1); currCalibrationStep = -1; //int sent = calib.calibrate.udpConnection.Send(message.c_str(),message.length()); delete message; //-------------- } break; case 's': saveBackground(); break; } } } void ofxNCoreVision::_keyReleased(ofKeyEventArgs &e) { if (showConfiguration) { if ( e.key == 'c' && !bCalibration) { bShowInterface = false; //Enter/Exit Calibration bCalibration = true; calib.calibrating = true; tracker.isCalibrating = true; if (bFullscreen == false) ofToggleFullscreen(); bFullscreen = true; //added by stefan Schlupek-------- char* message = new char[512]; //calibrate|ON|TUIOSource Name@adress|X Points|Y POints) sprintf(message,"calibrate|ON|%s|%d|%d", myTUIO.tuio_source_String, calib.calibrate.GRID_X, calib.calibrate.GRID_Y); int sent = calib.calibrate.udpConnection.Send(message,strlen(message)+1); //int sent = calib.calibrate.udpConnection.Send(message.c_str(),message.length()); cout <<"UDP.Message:" << message << endl; printf("UDP.Message:%s!\n",message); delete message; //-------------- } } if ( e.key == '~' || e.key == '`' && !bMiniMode && !bCalibration) showConfiguration = !showConfiguration; } /***************************************************************************** * MOUSE EVENTS *****************************************************************************/ void ofxNCoreVision::_mouseDragged(ofMouseEventArgs &e) { if (showConfiguration) controls->mouseDragged(e.x, e.y, e.button); //guilistener } void ofxNCoreVision::_mousePressed(ofMouseEventArgs &e) { if (showConfiguration) { controls->mousePressed(e.x, e.y, e.button); //guilistener if (e.x > 722 && e.y > 586){ofLaunchBrowser("http://tbeta.nuigroup.com");} } } void ofxNCoreVision::_mouseReleased(ofMouseEventArgs &e) { if (showConfiguration) controls->mouseReleased(e.x, e.y, 0); //guilistener } /***************************************************************************** * Getters *****************************************************************************/ std::map<int, Blob> ofxNCoreVision::getBlobs(){ return tracker.getTrackedBlobs(); } /***************************************************************************** * ON EXIT *****************************************************************************/ void ofxNCoreVision::_exit(ofEventArgs &e) { //save/update log file if((stream = freopen(fileName, "a", stdout)) == NULL){} saveSettings(); #ifdef TARGET_WIN32 if(PS3!=NULL) delete PS3; if(ffmv!=NULL) delete ffmv; if(dsvl!=NULL) delete dsvl; #endif if(vidGrabber!=NULL) delete vidGrabber; if(vidPlayer !=NULL) delete vidPlayer; // -------------------------------- SAVE STATE ON EXIT printf("Vision module has exited!\n"); }
[ "schlupek@463ed9da-a5aa-4e33-a7e2-2d3b412cff85" ]
[ [ [ 1, 1381 ] ] ]
97b32b4404587025ee9c652ac1ea3db8a10098f9
4f2f895838d91319d50c50f831ddc1f5acf20425
/wtpm/turing4/tape.cpp
a51ce0cd5dc8a9628f37d1ecc115f335ce884ff5
[]
no_license
iurisilvio/mtpooh
c25c3c69ff472e78ea4620c79c945f948240900d
88a51607a8a561e856fc6508c4f7f3f5f806e0a3
refs/heads/master
2021-01-10T10:24:55.341551
2010-07-09T05:27:00
2010-07-09T05:27:00
36,733,103
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
cpp
#include "machine.h" bool tape::read(FILE* fin) { bool startedReading = false; for(int i=pos; ; ++i) { int c = fgetc(fin); if (c < 0) { vet[i]='#'; return (i != 0); } if (c == '#') { return true; } else if (c == '\r' || c == '\n') { if (startedReading) { return true; } else { --i; } } else { startedReading = true; vet[i] = c; ++my_usedSize; } } } char tape::get() { return vet[pos]; } void tape::set(result r) { vet[pos] = r.insert; if (r.insert == '#' && pos == (my_usedSize - 1)) { while (vet[my_usedSize - 1] == '#') { --my_usedSize; } } else if (r.insert != '#' && pos > (my_usedSize - 1)) { my_usedSize = pos + 1; } pos += r.dir; } tape::tape(int n) { vet.resize(n); for(int i=0; i<n; ++i) vet[i]='#'; pos=0; my_usedSize = 0; } int tape::usedSize() const { return my_usedSize; }
[ "cesarkawakami@00e71aeb-c903-d59a-6020-541d7a38dfe8", "rsalmeidafl@00e71aeb-c903-d59a-6020-541d7a38dfe8", "damnerd@00e71aeb-c903-d59a-6020-541d7a38dfe8" ]
[ [ [ 1, 2 ], [ 37, 38 ], [ 40, 43 ], [ 45, 45 ], [ 62, 62 ], [ 64, 67 ], [ 71, 71 ] ], [ [ 3, 36 ], [ 39, 39 ], [ 44, 44 ], [ 46, 61 ], [ 63, 63 ], [ 69, 70 ], [ 72, 76 ] ], [ [ 68, 68 ] ] ]
93f9f1958e815078dbdc3bbd775e220aa8883e26
a6a3df5a00bf2389f723e6cb8bd69fc3c0618301
/Notify.h
34b4e100ec67c897dfa479d28381a5b685ff7052
[]
no_license
libfetion/libfetion-gui-wince
4de482e3451faf0bba885b14b57fc01b2bb980cd
b69456b10d888ff3b7421b401887a69333c72c12
refs/heads/master
2020-04-16T08:02:28.921130
2011-03-14T14:55:39
2011-03-14T14:55:39
32,465,759
0
1
null
null
null
null
UTF-8
C++
false
false
1,596
h
#pragma once #ifdef WIN32_PLATFORM_PSPC // 为了与WM2003兼容 #ifndef NOTIF_NUM_SOFTKEYS #define SHNF_HASMENU 0x00000040 #define SHNF_ALERTONUPDATE 0x00000200 #define SHNF_WANTVKTTALK 0x00000400 #define SHNN_ACTIVATE (SHNN_FIRST-5) #define NOTIF_SOFTKEY_FLAGS_DISMISS 0x0000 #define NOTIF_SOFTKEY_FLAGS_HIDE 0x0001 #define NOTIF_SOFTKEY_FLAGS_STAYOPEN 0x0002 #define NOTIF_SOFTKEY_FLAGS_SUBMIT_FORM 0x0004 #define NOTIF_SOFTKEY_FLAGS_DISABLED 0x0008 #define SHNUM_SOFTKEYS 0x0020 #define SHNUM_TODAYKEY 0x0040 #define SHNUM_TODAYEXEC 0x0080 #define SHNUM_SOFTKEYCMDS 0x0100 #define SHNUM_FLAGS 0x0200 struct SOFTKEYCMD { WPARAM wpCmd; DWORD grfFlags; }; struct SOFTKEYMENU { HMENU hMenu; SOFTKEYCMD *prgskc; UINT cskc; }; struct SOFTKEYNOTIFY { LPCTSTR pszTitle; SOFTKEYCMD skc; }; struct SHNOTIFICATIONDATA2: public SHNOTIFICATIONDATA { union { SOFTKEYMENU skm; SOFTKEYNOTIFY rgskn[2]; }; PCTSTR pszTodaySK; PCTSTR pszTodayExec; }; #else #define SHNOTIFICATIONDATA2 SHNOTIFICATIONDATA #endif #endif class CNotify { public: CNotify(void); ~CNotify(void); // 播放指定的声音 static void Nodify(HWND hwnd, LPCWSTR strPath, int iPeriod, BOOL bNoSound = FALSE, BOOL bVibe = FALSE, UINT Styles = 0); static void CNotify::CreateAndAddNotification(HWND hwnd, CString szTitle, CString szNotify); static void RemoveNotification(); private: static void StartViberate(bool bVibe); static void StopViberate(bool bVibe); };
[ "shikun.z@8f3339bc-7e71-11dd-a943-c76e4c82ec5c", "gladyeti@8f3339bc-7e71-11dd-a943-c76e4c82ec5c" ]
[ [ [ 1, 47 ], [ 49, 63 ], [ 65, 65 ], [ 67, 72 ] ], [ [ 48, 48 ], [ 64, 64 ], [ 66, 66 ] ] ]
dde8f1ddc74d4172016d503f1edf60df6f74e140
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/WebKitTestRunner/InjectedBundle/Bindings/JSWrappable.h
e302f435ed52849bf9b93b6371a45c0a3d41b13d
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,910
h
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef JSWrappable_h #define JSWrappable_h #include <JavaScriptCore/JavaScriptCore.h> #include <wtf/RefCounted.h> namespace WTR { class JSWrappable : public RefCounted<JSWrappable> { public: virtual ~JSWrappable() { } virtual JSClassRef wrapperClass() = 0; }; inline JSValueRef JSValueMakeStringOrNull(JSContextRef context, JSStringRef stringOrNull) { return stringOrNull ? JSValueMakeString(context, stringOrNull) : JSValueMakeNull(context); } } // namespace WTR #endif // JSWrappable_h
[ [ [ 1, 47 ] ] ]
e1479515d7018303ad4aad64196eb537ed55e983
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/stdafx.h
af4095c014ef5d71b9eb27188c4f8acb742f6394
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
3,072
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #ifndef _stdafx_h_ #define _stdafx_h_ #pragma once #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. #define WINVER 0x0500 //needs IDC_HAND #endif #ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. #define _WIN32_WINNT 0x0501 //Need This for WS_EX_LAYERED #endif #ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. #define _WIN32_IE 0x0500 // need this for SHGetFolderPath #endif #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <afxmt.h> //CCriticalSection (afx MultiThreading) #include <math.h> #include <shlwapi.h> #include <afxinet.h> #include <afxole.h> //DragDrop Files #include <gdiplus.h>//Used in Paste Picture (Save as jpg) #pragma comment(lib, "gdiplus.lib") #include <string> #include <vector> #include <set> #include <map> namespace std { typedef basic_string< TCHAR > tstring; typedef vector<tstring> tstringvector; }; #ifndef HDF_SORTUP #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif #define countof(x) (sizeof(x) / sizeof(x[0])) #ifndef _RELEASE #define ALOG_ACTIVE #endif #include "ALog/ALog.h" #endif #ifndef _RELEASE #include "UnitTest.h" #endif //#include "ExceptionHandler.h" //=== For CTextFileBase #define PEK_TX_TECHLEVEL 1
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 98 ] ] ]
8425b22d378e19347ce2aff06e6c8476f9e9bfae
555ce7f1e44349316e240485dca6f7cd4496ea9c
/DirectShowFilters/StreamingServer/Source/TSBuffer.h
3cbae699f92a3984b1a37ab8a2a1ea74801ac233
[]
no_license
Yura80/MediaPortal-1
c71ce5abf68c70852d261bed300302718ae2e0f3
5aae402f5aa19c9c3091c6d4442b457916a89053
refs/heads/master
2021-04-15T09:01:37.267793
2011-11-25T20:02:53
2011-11-25T20:11:02
2,851,405
2
0
null
null
null
null
UTF-8
C++
false
false
1,847
h
/** * TSBuffer.h * Copyright (C) 2005 nate * Copyright (C) 2006 bear * * This file is part of TSFileSource, a directshow push source filter that * provides an MPEG transport stream output. * * TSFileSource 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. * * TSFileSource 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 TSFileSource; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * nate can be reached on the forums at * http://forums.dvbowners.com/ */ #ifndef TSBUFFER_H #define TSBUFFER_H #include <vector> #include "FileReader.h" #include "CriticalSection.h" enum ChannelType { TV = 0, Radio = 1, }; class CTSBuffer { public: CTSBuffer(); virtual ~CTSBuffer(); void SetFileReader(FileReader *pFileReader); void Clear(); long Count(); void SetChannelType(int channelType); HRESULT Require(long nBytes, BOOL bIgnoreDelay = FALSE); HRESULT DequeFromBuffer(BYTE *pbData, long lDataLength); HRESULT ReadFromBuffer(BYTE *pbData, long lDataLength, long lOffset); int m_loopCount; protected: FileReader *m_pFileReader; std::vector<BYTE *> m_Array; long m_lItemOffset; Mediaportal::CCriticalSection m_BufferLock; long m_lTSBufferItemSize; ChannelType m_eChannelType; int debugcount; int m_ParserLock; }; #endif
[ [ [ 1, 33 ], [ 40, 48 ], [ 50, 61 ], [ 63, 68 ] ], [ [ 34, 39 ], [ 49, 49 ], [ 62, 62 ] ] ]
d240a93d37f6ab2561ab3a5ec748b6c1720c34ee
81fbd79838fc45e5c8e765804aac752f5a0c4b2e
/libraries/AP_Compass/.svn/text-base/AP_Compass_HMC5843.cpp.svn-base
150978d18a0a011ab4b59fb7a802d53fd0eb65e7
[]
no_license
BUUAVTeam/Quadrotor
cf0900c4dd1de172e25d3bc670ad13858e7044f3
97807d15746cbe74c9cd99d967fca2fa96763664
refs/heads/master
2016-09-05T08:54:27.065596
2011-01-10T23:10:06
2011-01-10T23:10:06
1,156,781
0
1
null
null
null
null
UTF-8
C++
false
false
6,986
// -*- tab-width: 4; Mode: C++; c-basic-offset: 3; indent-tabs-mode: t -*- /* AP_Compass_HMC5843.cpp - Arduino Library for HMC5843 I2C magnetometer Code by Jordi Muñoz and Jose Julio. DIYDrones.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Sensor is conected to I2C port Sensor is initialized in Continuos mode (10Hz) Variables: heading : magnetic heading heading_x : magnetic heading X component heading_y : magnetic heading Y component mag_x : Raw X axis magnetometer data mag_y : Raw Y axis magnetometer data mag_z : Raw Z axis magnetometer data last_update : the time of the last successful reading Methods: init() : Initialization of I2C and sensor read() : Read Sensor data calculate(float roll, float pitch) : Calculate tilt adjusted heading set_orientation(const Matrix3f &rotation_matrix) : Set orientation of compass set_offsets(int x, int y, int z) : Set adjustments for HardIron disturbances set_declination(float radians) : Set heading adjustment between true north and magnetic north To do : code optimization Mount position : UPDATED Big capacitor pointing backward, connector forward */ // AVR LibC Includes #include <math.h> #include "WConstants.h" #include <Wire.h> #include "AP_Compass_HMC5843.h" #define COMPASS_ADDRESS 0x1E #define ConfigRegA 0x00 #define ConfigRegB 0x01 #define magGain 0x20 #define PositiveBiasConfig 0x11 #define NegativeBiasConfig 0x12 #define NormalOperation 0x10 #define ModeRegister 0x02 #define ContinuousConversion 0x00 #define SingleConversion 0x01 // Constructors //////////////////////////////////////////////////////////////// AP_Compass_HMC5843::AP_Compass_HMC5843() : orientation(0), declination(0.0) { // mag x y z offset initialisation offset[0] = 0; offset[1] = 0; offset[2] = 0; // initialise orientation matrix orientation_matrix = ROTATION_NONE; } // Public Methods ////////////////////////////////////////////////////////////// bool AP_Compass_HMC5843::init(int initialise_wire_lib) { unsigned long currentTime = millis(); // record current time int numAttempts = 0; int success = 0; if( initialise_wire_lib != 0 ) Wire.begin(); delay(10); // calibration initialisation calibration[0] = 1.0; calibration[1] = 1.0; calibration[2] = 1.0; while( success == 0 && numAttempts < 5 ) { // record number of attempts at initialisation numAttempts++; // force positiveBias (compass should return 715 for all channels) Wire.beginTransmission(COMPASS_ADDRESS); Wire.send(ConfigRegA); Wire.send(PositiveBiasConfig); if (0 != Wire.endTransmission()) continue; // compass not responding on the bus delay(50); // set gains Wire.beginTransmission(COMPASS_ADDRESS); Wire.send(ConfigRegB); Wire.send(magGain); Wire.endTransmission(); delay(10); Wire.beginTransmission(COMPASS_ADDRESS); Wire.send(ModeRegister); Wire.send(SingleConversion); Wire.endTransmission(); delay(10); // read values from the compass read(); delay(10); // calibrate if( abs(mag_x) > 500 && abs(mag_x) < 1000 && abs(mag_y) > 500 && abs(mag_y) < 1000 && abs(mag_z) > 500 && abs(mag_z) < 1000) { calibration[0] = fabs(715.0 / mag_x); calibration[1] = fabs(715.0 / mag_y); calibration[2] = fabs(715.0 / mag_z); // mark success success = 1; } // leave test mode Wire.beginTransmission(COMPASS_ADDRESS); Wire.send(ConfigRegA); Wire.send(NormalOperation); Wire.endTransmission(); delay(50); Wire.beginTransmission(COMPASS_ADDRESS); Wire.send(ModeRegister); Wire.send(ContinuousConversion); // Set continuous mode (default to 10Hz) Wire.endTransmission(); // End transmission delay(50); } return(success); } // Read Sensor data void AP_Compass_HMC5843::read() { int i = 0; byte buff[6]; Wire.beginTransmission(COMPASS_ADDRESS); Wire.send(0x03); //sends address to read from Wire.endTransmission(); //end transmission //Wire.beginTransmission(COMPASS_ADDRESS); Wire.requestFrom(COMPASS_ADDRESS, 6); // request 6 bytes from device while(Wire.available()) { buff[i] = Wire.receive(); // receive one byte i++; } Wire.endTransmission(); //end transmission if (i==6) // All bytes received? { // MSB byte first, then LSB, X,Y,Z mag_x = -((((int)buff[0]) << 8) | buff[1]) * calibration[0]; // X axis mag_y = ((((int)buff[2]) << 8) | buff[3]) * calibration[1]; // Y axis mag_z = -((((int)buff[4]) << 8) | buff[5]) * calibration[2]; // Z axis last_update = millis(); // record time of update } } void AP_Compass_HMC5843::calculate(float roll, float pitch) { float headX; float headY; float cos_roll; float sin_roll; float cos_pitch; float sin_pitch; Vector3f rotmagVec; cos_roll = cos(roll); // Optimizacion, se puede sacar esto de la matriz DCM? sin_roll = sin(roll); cos_pitch = cos(pitch); sin_pitch = sin(pitch); // rotate the magnetometer values depending upon orientation if( orientation == 0 ) rotmagVec = Vector3f(mag_x+offset[0],mag_y+offset[1],mag_z+offset[2]); else rotmagVec = orientation_matrix*Vector3f(mag_x+offset[0],mag_y+offset[1],mag_z+offset[2]); // Tilt compensated magnetic field X component: headX = rotmagVec.x*cos_pitch+rotmagVec.y*sin_roll*sin_pitch+rotmagVec.z*cos_roll*sin_pitch; // Tilt compensated magnetic field Y component: headY = rotmagVec.y*cos_roll-rotmagVec.z*sin_roll; // magnetic heading heading = atan2(-headY,headX); // Declination correction (if supplied) if( declination != 0.0 ) { heading = heading + declination; if (heading > M_PI) // Angle normalization (-180 deg, 180 deg) heading -= (2.0 * M_PI); else if (heading < -M_PI) heading += (2.0 * M_PI); } // Optimization for external DCM use. Calculate normalized components heading_x = cos(heading); heading_y = sin(heading); } void AP_Compass_HMC5843::set_orientation(const Matrix3f &rotation_matrix) { orientation_matrix = rotation_matrix; if( orientation_matrix == ROTATION_NONE ) orientation = 0; else orientation = 1; } void AP_Compass_HMC5843::set_offsets(int x, int y, int z) { offset[0] = x; offset[1] = y; offset[2] = z; } void AP_Compass_HMC5843::set_declination(float radians) { declination = radians; }
[ [ [ 1, 232 ] ] ]
240e23daa9c4cb7e4083135d4082bf3c61b0c6cf
f6a8ffe1612a9a39fc1daa4e7849cad56ec351f0
/ChromaKeyer/trunk/ChromaKeyer/ChromaKey.h
181f94271ae6b937fa7f4b49d3d91506dcdc847d
[]
no_license
comebackfly/c-plusplus-programming
03e097ec5b85a4bf1d8fdd47041a82d7b6ca0753
d9b2fb3caa60459fe459cacc5347ccc533b4b1ec
refs/heads/master
2021-01-01T18:12:09.667814
2011-07-18T22:30:31
2011-07-18T22:30:31
35,753,632
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
#pragma once #include "ImageObject.h" class ChromaKey { public: ChromaKey(void); ~ChromaKey(void); void setKeyColor(int color); void setDischargedImage(ImageObject dischargedImage); void setBackgroundImage(ImageObject backgroundImage); ImageObject* keyImage(ImageObject* dischargedImage, ImageObject* backgroundImage, int b, int g, int r, int tolerance); private: int keyColor; ImageObject* dischargedImage; ImageObject* backgroundImage; };
[ "[email protected]@5f9f56c3-fb77-04ef-e3c5-e71eb3e36737" ]
[ [ [ 1, 20 ] ] ]