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
b9119305197d3683d0f1e2efe05eff129ceb05b3
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/LWcommon/LWSceneGraph.h
8fc43c9647d7f760591d9c6a701501581cc3e845
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
1,199
h
#ifndef LWCOMMON_LWSCENEGRAPH_H_HEADER_INCLUDED_C136776D #define LWCOMMON_LWSCENEGRAPH_H_HEADER_INCLUDED_C136776D #include "Singleton.h" #include "lwrender.h" #include <string> class LWSceneGraph; typedef Singleton<LWSceneGraph> LWSceneGraphSingleton; /** * Singleton to provide common tasks of scene graph access. * @author David Forstenlechner * @date 2002-2003 */ class LWSceneGraph : public LWSceneGraphSingleton { public: /** * Item types in scene. */ enum ItemType { Object=LWI_OBJECT, ///< Object Item Type Light=LWI_LIGHT, ///< Light Item Type Camera=LWI_CAMERA, ///< Camera Item Type Bone=LWI_BONE ///< Bone Item Type }; /** * Searches for the last Item of the specified Type * in the Scene Graph. * @param TypeToSearch Type of Item to search the last entry for. * @return Returns NULL if no item of the specified Type found in Scene. */ LWItemID FindLastOfType(ItemType TypeToSearch); std::string GetItemName(LWItemID nameFor); LWItemID AddNull(std::string & ItemName); }; #endif /* LWCOMMON_LWSCENEGRAPH_H_HEADER_INCLUDED_C136776D */
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 43 ] ] ]
7ec7db0e2009419dab85b154a8a0d0587e3ac473
34a68e61a469b94063bc98465557072897a9aa88
/render/2d/util/DrawConsole.h
c9b57da83ca0dab10dc20fd2cce5b47b1793b708
[]
no_license
CneoC/shinzui
f83bfc9cbd9a05480d5323a21339d83e4d403dd9
5a2b79b430b207500766849bd58538e6a4aff2f8
refs/heads/master
2020-05-03T11:00:52.671613
2010-01-25T00:05:55
2010-01-25T00:05:55
377,430
1
0
null
null
null
null
UTF-8
C++
false
false
1,548
h
////////////////////////////////////////////////////////////////////////// // // This file is part of Shinzui. // // Shinzui 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. // // Shinzui 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 Shinzui. If not, see <http://www.gnu.org/licenses/>. // ////////////////////////////////////////////////////////////////////////// // // Console.h // Copyright (c) 2009 Coen Campman // ////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __RENDER_DRAWCONSOLE_H__ #define __RENDER_DRAWCONSOLE_H__ #include "render/Renderer.h" #include "render/2d/FontUtil.h" #include "resources/font/FontResource.h" namespace console { class Console; } namespace render { class DrawConsole : public render::Renderer { public: DrawConsole(core::Core *pCore, const console::Console &console); ~DrawConsole(); virtual void render(double delta); protected: const console::Console & m_console; render::FontUtil * m_pFontUtil; resources::FontResource m_font; }; } #endif //__RENDER_DRAWCONSOLE_H__
[ "[email protected]", "coen@.(none)" ]
[ [ [ 1, 24 ], [ 27, 28 ], [ 31, 35 ], [ 37, 49 ], [ 51, 57 ], [ 59, 59 ] ], [ [ 25, 26 ], [ 29, 30 ], [ 36, 36 ], [ 50, 50 ], [ 58, 58 ] ] ]
306ed56a904709bbfa6e5d1bc0ecc06bd0b333d8
55d6f54f463bf0f97298eb299674e2065863b263
/debugage.cpp
0e9eaff052fe049e7f78d60b55f48edb262573b0
[]
no_license
Coinche/CoinchePAV
a344e69b096ef5fd4e24c98af1b24de2a99235f0
134cac106ee8cea78abc5b29b23a32706b2aad08
refs/heads/master
2020-06-01T09:35:51.793153
2011-12-01T19:57:12
2011-12-01T19:57:12
2,729,958
0
0
null
null
null
null
ISO-8859-1
C++
false
false
9,583
cpp
#include <iostream> #include <fstream> #include <exception> #include <string> #include <assert.h> #include "debugage.h" ///////////////////////////////////////////////////////////////////////////////////////////////////// //Debugage ///////////////////////////////////////////////////////////////////////////////////////////////////// bool Debugage::debugage(){ std::ofstream outfile ("log.txt"); outfile << "Début du débogage" << std::endl; outfile.close(); bool status = true; status &= test_T_ANNONCE(); status &= test_T_CARTE(); status &= test_T_MMAIN(); status &= test_T_REGLES(); std::ofstream outfile2 ("log.txt",std::ios_base::app); outfile2 << "Fin du débogage" << std::endl; outfile2.close(); return status; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //T_Annonce ///////////////////////////////////////////////////////////////////////////////////////////////////// bool Debugage::test_T_ANNONCE(){ // Visualisations std::string tab ( " "); std::ofstream outfile ("log.txt",std::ios_base::app); outfile << tab <<"Test de la classe Annonce" << std::endl; std::cout << tab << "Test de la classe Annonce" << std::endl; bool status = true; try{ //Constructeur Annonce pj(QUATRE_VINGT,CARREAU); Couleur car = pj.get_couleur(); Hauteur hau = pj.get_hauteur(); assert(pj.get_couleur() == CARREAU); assert(pj.get_hauteur() == QUATRE_VINGT); //Comparaison Annonce bg(CENT_SOIXANTE_DIX,TREFLE); assert(bg > pj); } catch(std::exception const& e){ std::cerr << "ERREUR : " << e.what() << std::endl; outfile << "test_ANNONCE : " << "ERREUR : " << e.what() << std::endl; status = false; } outfile.close(); if(status) { std::cout << tab << "T_ANNONCE : Le test s'est déroulé sans problème" << std::endl; } else { std::cout << tab << "T_ANNONCE Le test à détecté des problèmes. Voir le fichier log.txt" << std::endl; } return status; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //T_CARTE ///////////////////////////////////////////////////////////////////////////////////////////////////// bool Debugage::test_T_CARTE(){ // Visualisations std::string tab ( " "); std::ofstream outfile ("log.txt",std::ios_base::app); outfile << tab <<"Test de la classe Carte" << std::endl; std::cout << tab << "Test de la classe Carte" << std::endl; //Tests bool status = true; try{ //Createur Carte tt(ROI,CARREAU); Valeur val = tt.get_valeur(); Couleur coul = tt.get_couleur(); assert(tt.get_valeur() == ROI); assert(tt.get_couleur() == CARREAU); //CreateurParCopie Carte ttcopie(tt); //Triparcouleur Carte moinsforte(DAME,CARREAU); assert(Carte::triParCouleur(moinsforte,tt)); //triParCouleur(tt,moinsforte) doit renvoyer true //operateurEgalEgal assert(ttcopie==tt); } catch(std::exception const& e){ std::cerr << "ERREUR : " << e.what() << std::endl; outfile << "testCARTE : " << "ERREUR : " << e.what() << std::endl; status = false; } outfile.close(); if(status) { std::cout << tab << "T_CARTE : Le test s'est déroulé sans problème" << std::endl; } else { std::cout << tab << "T_CARTE Le test à détecté des problèmes. Voir le fichier log.txt" << std::endl; } return status; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //T_MMAIN ///////////////////////////////////////////////////////////////////////////////////////////////////// bool Debugage::test_T_MMAIN(){ // Visualisations std::string tab ( " "); std::ofstream outfile ("log.txt",std::ios_base::app); outfile << tab <<"Test de la classe Main" << std::endl; std::cout << tab << "Test de la classe Main" << std::endl; //Tests bool status = true; try{ //Createur Main mainj2; assert( mainj2.empty() ); //push_back mainj2.push_back( Carte(ROI,CARREAU) ); //size assert(mainj2.size() == 1); //CreateurParCopie Main maincopie(mainj2); assert(maincopie == mainj2); //contient assert( mainj2.contient(Carte(ROI,CARREAU)) ); //extraire assert(mainj2.extraire(CARREAU) == mainj2); //Triparcouleur mainj2.push_back( Carte(DAME,CARREAU) ); Main mainTriee; mainTriee.push_back( Carte(DAME,CARREAU) ); mainTriee.push_back( Carte(ROI,CARREAU) ); mainj2.trierParCouleur(); assert( mainj2 == mainTriee); } catch(std::exception const& e){ std::cerr << "ERREUR : " << e.what() << std::endl; outfile << "testMAIN : " << "ERREUR : " << e.what() << std::endl; status = false; } outfile.close(); if(status) { std::cout << tab << "T_MAIN : Le test s'est déroulé sans problème" << std::endl; } else { std::cout << tab << "T_MAIN Le test à détecté des problèmes. Voir le fichier log.txt" << std::endl; } return status; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //T_REGLES ///////////////////////////////////////////////////////////////////////////////////////////////////// bool Debugage::test_T_REGLES(){ // Visualisations std::string tab ( " "); std::ofstream outfile ("log.txt",std::ios_base::app); outfile << tab <<"Test de la classe Regles" << std::endl; std::cout << tab << "Test de la classe Regles" << std::endl; //Tests bool status = true; try{ //methode Annonces Possibles Encheres encherActuelles; encherActuelles.push_back(Annonce(QUATRE_VINGT,COEUR)); encherActuelles.push_back(Annonce(PASSE,CARREAU)); encherActuelles.push_back(Annonce(PASSE,CARREAU)); encherActuelles.push_back(Annonce(PASSE,CARREAU)); std::pair<std::vector<Couleur>, std::vector<Hauteur> > annoncesSorties = Regles::AnnoncesPossibles(encherActuelles); for(unsigned int i=0; i<annoncesSorties.first.size(); i++) { assert(annoncesSorties.first[i] != COEUR); } for(unsigned int j=0; j<annoncesSorties.second.size(); j++) { assert(annoncesSorties.second[j] != QUATRE_VINGT); } //méthode valeur(carte) Carte valetdecarreau(VALET, CARREAU); Carte nefledecoeur(NEUF, COEUR); assert(Regles::valeur(valetdecarreau, CARREAU) == 20 ); assert(Regles::valeur(valetdecarreau, TREFLE) == 2 ); assert(Regles::valeur(nefledecoeur, COEUR) == 14 ); assert(Regles::valeur(nefledecoeur, PIQUE) == 0); //méthode valeur(pli) Pli plipli; plipli.push_back(valetdecarreau); plipli.push_back(nefledecoeur); Carte roidecarreau(ROI,CARREAU); plipli.push_back(roidecarreau); assert(Regles::valeur(plipli, CARREAU) == 24); assert(Regles::valeur(plipli, TREFLE) == 6 ); //methode comparer assert(Regles::comparer(valetdecarreau, roidecarreau, CARREAU) == 1); assert(Regles::comparer(valetdecarreau, roidecarreau, TREFLE) == 0); assert(Regles::comparer(valetdecarreau, nefledecoeur , TREFLE) == 2); //Méthode valides Main mainjoueur; Carte septdecarreau(SEPT,CARREAU); mainjoueur.push_back(septdecarreau); Carte neufdecarreau(NEUF,CARREAU); mainjoueur.push_back(neufdecarreau); Carte roidetrefle(ROI,TREFLE); mainjoueur.push_back(roidetrefle); Main MainvalideCARREAU; MainvalideCARREAU.push_back(neufdecarreau); MainvalideCARREAU.push_back(septdecarreau); Main MainvalidePIQUE; MainvalidePIQUE.push_back(septdecarreau); MainvalidePIQUE.push_back(neufdecarreau); Main MainvalideTREFLE; MainvalideTREFLE.push_back(septdecarreau); MainvalideTREFLE.push_back(neufdecarreau); Main mainsortieCARREAU = Regles::valides(mainjoueur, CARREAU, plipli); Main mainsortiePIQUE = Regles::valides(mainjoueur, PIQUE, plipli); Main mainsortieTREFLE = Regles::valides(mainjoueur, TREFLE, plipli); bool testcarreau = (mainsortieCARREAU == MainvalideCARREAU); bool testpique = (mainsortiePIQUE == MainvalidePIQUE); bool testtrefle = (mainsortieTREFLE == MainvalideTREFLE); assert(testcarreau); assert(testpique); assert(testtrefle); //Verification de la situation où on doit monter à l'atout, bien que le partenaire est maître. Pli plipli2; plipli2.push_back(Carte(HUIT,TREFLE)); plipli2.push_back(Carte(ROI,PIQUE)); Main maindujoueur; maindujoueur.push_back(Carte(DAME,CARREAU)); maindujoueur.push_back(Carte(HUIT,PIQUE)); Main mainValideManuel; mainValideManuel.push_back(Carte(DAME,CARREAU)); mainValideManuel.push_back(Carte(HUIT,PIQUE)); Main mainvalide = Regles::valides(maindujoueur, CARREAU, plipli2); assert(mainvalide.size() !=0 ); assert(mainvalide == mainValideManuel); } catch(std::exception const& e){ std::cerr << "ERREUR : " << e.what() << std::endl; outfile << "testRegles: " << "ERREUR : " << e.what() << std::endl; status = false; } outfile.close(); if(status) { std::cout << tab << "T_REGLES : Le test s'est déroulé sans problème" << std::endl; } else { std::cout << tab << "T_REGLES Le test à détecté des problèmes. Voir le fichier log.txt" << std::endl; } return status; }
[ "lucas@graham.(none)", "[email protected]" ]
[ [ [ 1, 205 ], [ 207, 212 ], [ 214, 273 ], [ 278, 278 ], [ 282, 283 ], [ 287, 288 ], [ 292, 311 ] ], [ [ 206, 206 ], [ 213, 213 ], [ 274, 277 ], [ 279, 281 ], [ 284, 286 ], [ 289, 291 ], [ 312, 312 ] ] ]
65152664a232104e86880ebf2a91889f7ec1ef19
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/WorkLayer/UpdateInfo.cpp
8ddb96055c612df6e3ff73976ab17986265b1a93
[]
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
4,519
cpp
/* * $Id: UpdateInfo.cpp 5279 2008-04-10 04:35:49Z huby $ * * this file is part of easyMule * Copyright (C)2002-2008 VeryCD Dev Team ( strEmail.Format("%s@%s", "emuledev", "verycd.com") / 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. */ // UpdateInfo.cpp : 实现文件 // #include "stdafx.h" #include "emule.h" #include "emuleDlg.h" #include "UpdateInfo.h" #include "SharedFilesCtrl.h" #include "SharedFilesWnd.h" // CUpdateInfo CUpdateInfo::CUpdateInfo() { } CUpdateInfo::~CUpdateInfo() { } // CUpdateInfo 成员函数 void CUpdateInfo::Serialize(CArchive& ar) { if (ar.IsStoring()) { ar<<m_Hash; } else { ar>>m_Hash; } } BOOL CUpdateInfo::OpenUpdateInfo(void) { CFile file; if (file.Open(GetUpdateInfoFile(), CFile::modeRead)) { try { CArchive ar(&file, CArchive::load); Serialize(ar); } catch (CException* e) { e->Delete(); ASSERT(0); } file.Close(); return TRUE; } return FALSE; } void CUpdateInfo::SaveUpdateInfo(void) { CFile file; if (file.Open(GetUpdateInfoFile(), CFile::modeCreate | CFile::modeReadWrite )) { try { CArchive ar(&file, CArchive::store); Serialize(ar); } catch (CException* e) { e->Delete(); ASSERT(0); } } file.Close(); } void CUpdateInfo::SetUpdateHash(CString hash) { m_Hash = hash; SaveUpdateInfo(); } CString CUpdateInfo::GetUpdateHash(void) { if(OpenUpdateInfo()) { return m_Hash; } return NULL; } CString CUpdateInfo::GetUpdateInfoFile(void) { return thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("update.dat"); } BOOL CUpdateInfo::isUpdateFile(CString hash) { CString oldhash = GetUpdateHash(); if(oldhash.IsEmpty()) { return FALSE; } if(oldhash.Compare(hash) == 0) { return TRUE; } return FALSE; } int CUpdateInfo::GetUpdateState(const uchar* hash) { //共享文件列表 const CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(hash); if(file) { if (file->IsPartFile()) { return UPDATE_DOWNLOADING; //在共享列表中,但是没有下载完成。 } else { return UPDATE_DOWNLOADED; //在共享列表中有,已经下载完。 } } else { //下载列表 if ((file = CGlobalVariable::downloadqueue->GetFileByID(hash)) != NULL) { return UPDATE_DOWNLOADING; //在下载列表中,肯定没有下载完成 } else { return UPDATE_NODOWNLOAD; //尚未下载 } } } BOOL CUpdateInfo::UpdateInfoFileExists(void) { return PathFileExists(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("update.dat")); } int CUpdateInfo::Compare(CString hash) { CString oldhash = GetUpdateHash(); return oldhash.Compare(hash); } BOOL CUpdateInfo::DeleteUpdate(CString hash) { uchar UpdateHash[16]; CPartFile* pPartFile; if(!strmd4(hash,UpdateHash)) { return FALSE; } CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(UpdateHash); try { //共享列表中是否有 if(file) { if(file->IsPartFile()) { //共享列表有,但未下载完,移除 pPartFile = DYNAMIC_DOWNCAST(CPartFile,file); if( pPartFile ) { pPartFile->DeleteFile(); } } else { //共享列表有,已经下载完成未安装,移除 DeleteFile(file->GetFilePath()); theApp.emuledlg->sharedfileswnd->sharedfilesctrl.RemoveFile(file); CGlobalVariable::sharedfiles->RemoveFile(file); } } if ((pPartFile = CGlobalVariable::downloadqueue->GetFileByID(UpdateHash)) != NULL) { //共享列表没有,但未下载完,移除 pPartFile->DeleteFile(); } } catch (CException* e) { e->Delete(); return FALSE; } return FALSE; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 232 ] ] ]
4a8c9e3841d1f3edd441211c233db650f93f4d38
72071dfcccdab286fce3b0d4483d9e075f0a2ae3
/SDLScoreSystem.cpp
254a6da8dba0fe80f799c7ebeb61a009aeba79da
[]
no_license
rickumali/RicksTetris
bc824d25ca6403cd12891aa2eae59fc5c6c41a9c
76128d72f0cfb75ff4d619784c70fec9562d5c71
refs/heads/master
2016-09-06T04:27:15.587789
2011-12-23T18:17:10
2011-12-23T18:17:10
3,043,175
2
0
null
null
null
null
UTF-8
C++
false
false
4,255
cpp
#include "SDL/SDL.h" #include "SDL_ttf.h" #include "SDLScoreSystem.h" #include "Constants.h" #include "OriginalNintendoScoring.h" // Constructor SDLScoreSystem::SDLScoreSystem(SDL_Surface *surface_in, TTF_Font *font_in) { surface = surface_in; font = font_in; scoresystem = new OriginalNintendoScoring(); } void SDLScoreSystem::add_lines_to_score(int rows) { (void) scoresystem->add_lines_to_score(rows); } void SDLScoreSystem::set_current_score(int score) { scoresystem->set_current_score(score); } void SDLScoreSystem::add_to_current_score(int score) { scoresystem->add_to_current_score(score); } int SDLScoreSystem::get_current_score() { return(scoresystem->get_current_score()); } /* * Writes the score to the scoring area. * It blanks out the score line, THEN it draws * the message into the blacked out area. */ void SDLScoreSystem::write_score() { const int X_OFFSET = 17; const int Y_OFFSET = 5; Uint32 blackColor = SDL_MapRGB(surface->format, 0, 0, 0); SDL_Color textColor = {0, 255, 0}; char s[20]; sprintf(s, "Score: %10d", scoresystem->get_current_score()); SDL_Surface *message = TTF_RenderText_Solid( font, s, textColor); // This is the entire blank area of the scoring line SDL_Rect status_line_offset; status_line_offset.x = X_OFFSET * GRID_SIZE; status_line_offset.y = Y_OFFSET * GRID_SIZE; status_line_offset.h = 1 * GRID_SIZE - 1; status_line_offset.w = 30 * GRID_SIZE - 1; // This is the area for the message SDL_Rect text_offset; text_offset.x = X_OFFSET * GRID_SIZE; text_offset.y = Y_OFFSET * GRID_SIZE; SDL_FillRect (surface, &status_line_offset, blackColor); SDL_BlitSurface (message, NULL, surface, &text_offset); SDL_FreeSurface(message); } void SDLScoreSystem::write_score_to_file() { scoresystem->write_score_to_file(); } int SDLScoreSystem::get_level() { return(scoresystem->get_level()); } void SDLScoreSystem::increment_level() { scoresystem->increment_level(); } /* * Writes the Game Over message. */ void SDLScoreSystem::write_gameover() { const int X_OFFSET = 13; const int Y_OFFSET = 7; Uint32 blackColor = SDL_MapRGB(surface->format, 0, 0, 0); SDL_Color textColor = {250, 0, 0}; char s[40]; sprintf(s, "Game Over! (q = quit; n = start new)"); SDL_Surface *message = TTF_RenderText_Solid( font, s, textColor); // This is the entire blank area of the level line SDL_Rect status_line_offset; status_line_offset.x = X_OFFSET * GRID_SIZE; status_line_offset.y = Y_OFFSET * GRID_SIZE; status_line_offset.h = 1 * GRID_SIZE - 1; status_line_offset.w = 30 * GRID_SIZE - 1; // This is the area for the message SDL_Rect text_offset; text_offset.x = X_OFFSET * GRID_SIZE; text_offset.y = Y_OFFSET * GRID_SIZE; SDL_FillRect (surface, &status_line_offset, blackColor); SDL_BlitSurface (message, NULL, surface, &text_offset); SDL_FreeSurface(message); } /* * Writes the level to the level display area. * It blanks out the line, THEN it draws * the message into the blacked out area. */ void SDLScoreSystem::write_level() { const int X_OFFSET = 17; const int Y_OFFSET = 6; Uint32 blackColor = SDL_MapRGB(surface->format, 0, 0, 0); SDL_Color textColor = {0, 255, 0}; char s[20]; if (get_level() > 999999) sprintf(s, "Level: Past million!"); else sprintf(s, "Level: %11d", get_level()); SDL_Surface *message = TTF_RenderText_Solid( font, s, textColor); // This is the entire blank area of the level line SDL_Rect status_line_offset; status_line_offset.x = X_OFFSET * GRID_SIZE; status_line_offset.y = Y_OFFSET * GRID_SIZE; status_line_offset.h = 1 * GRID_SIZE - 1; status_line_offset.w = 30 * GRID_SIZE - 1; // This is the area for the message SDL_Rect text_offset; text_offset.x = X_OFFSET * GRID_SIZE; text_offset.y = Y_OFFSET * GRID_SIZE; SDL_FillRect (surface, &status_line_offset, blackColor); SDL_BlitSurface (message, NULL, surface, &text_offset); SDL_FreeSurface(message); }
[ [ [ 1, 138 ] ] ]
0815582dd9b6772d7c9b17cb7aed4f33cbacbbda
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CXI/11121.cpp
fa7d7a1e6827a7a4a99c52b077fff83940f8dad1
[]
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
447
cpp
///////////////////////////////// // 11121 - Base -2 ///////////////////////////////// #include<cstdio> #include<algorithm> char q[100], top; unsigned int i,t; int n, res; int main(void){ scanf("%u",&t); for(i = 1; t--; i++){ scanf("%d",&n); top = 0; do{ res = n/-2; if(n<0 && n&1) res++; q[top++] = (n-(res*-2))+'0'; n = res; }while(n); q[top] = 0; std::reverse(q,q+top); printf("Case #%u: %s\n",i,q); } return 0; }
[ [ [ 1, 24 ] ] ]
7dcb621e7d0b3eb027b10fb12a6b43f67e0e4c22
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Network/Mcl/Src/CMclSemaphore.cpp
0c8ef62a379334744621c06100d314fada41685f
[]
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
1,453
cpp
// // FILE: CMclSemaphore.cpp // // Copyright (c) 1997 by Aaron Michael Cohen and Mike Woodring // ///////////////////////////////////////////////////////////////////////// #include "CMclSemaphore.h" // constructor creates a semaphore object... CMclSemaphore::CMclSemaphore( int nInitialCount, int nMaximumCount, LPCTSTR lpName, LPSECURITY_ATTRIBUTES lpSemaphoreAttributes) { m_hHandle = ::CreateSemaphore( lpSemaphoreAttributes, nInitialCount, nMaximumCount, lpName); if (CMclIsValidHandle(m_hHandle)) { if (lpName) m_dwStatus = GetLastError(); else m_dwStatus = NO_ERROR; } else { m_dwStatus = GetLastError(); ThrowError(m_dwStatus); } } // constructor opens an existing named semaphore... CMclSemaphore::CMclSemaphore( LPCTSTR lpName, BOOL bInheritHandle, DWORD dwDesiredAccess) { m_hHandle = ::OpenSemaphore( dwDesiredAccess, bInheritHandle, lpName); if (CMclIsValidHandle(m_hHandle)) { m_dwStatus = NO_ERROR; } else { m_dwStatus = GetLastError(); } } // increase the count on a semaphore... BOOL CMclSemaphore::Release( LONG lReleaseCount, LONG *plPreviousCount) { LONG lPreviousCount; BOOL bStatus = ::ReleaseSemaphore( m_hHandle, lReleaseCount, &lPreviousCount); if (bStatus && plPreviousCount) { *plPreviousCount = lPreviousCount; } return bStatus; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 47 ] ] ]
71db7e4151f45735b9c832b9a8ab303f3814d423
5f7273a931999525149553cfded2582f11b16b48
/JVMVersion.cpp
de2b338fda8e38f4f7abdaab01ddb9e3b7d3d1c7
[ "MIT" ]
permissive
gtoubassi/JavaLaunch
e1cacec6a15dc3f8d22cdab3ef78cb98fef9bac1
acad9ff8caafac5c75aaed39a189a0913979254f
refs/heads/master
2020-05-30T07:42:01.874391
2004-10-14T03:52:45
2004-10-14T03:52:45
2,500,923
1
0
null
null
null
null
UTF-8
C++
false
false
3,340
cpp
/* Copyright (c) 2004, Garrick Toubassi 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 "JVMVersion.h" // 1.4.2_05-b04 // part 1 = 1 // part 2 = 4 // part 3 = 2 // part 4 = 5 // part 5 = 4 // All unspecified parts are assummed 0 const char *versionSeparators = "._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; JVMVersion::JVMVersion(const char *vers) { versionString = vers; char *versBuffer = strdup(vers); int i = 0; for (char *cp = strtok(versBuffer, "._"); cp != NULL && versionParts.size() < 5; cp = strtok(NULL, "._"), i++) { versionParts.push_back(atoi(cp)); } free(versBuffer); } const std::string& JVMVersion::version() const { return versionString; } // Returns true if all parts that are specified within this JVMVersion are // equal to the equivalent parts in 'other'. For example: // // JVMVersion("1.4") == JVMVersion("1.4.1") == false // JVMVersion("1.4").matchSpecified(JVMVersion("1.4.1")) == true // JVMVersion("1.4.1").matchSpecified(JVMVersion("1.4")) == false bool JVMVersion::matchSpecified(const JVMVersion& other) const { for (int i = 0; i < versionParts.size(); i++) { if (i >= other.versionParts.size()) { return false; } if (versionParts[i] != other.versionParts[i]) { return false; } } return true; } bool JVMVersion::operator<(const JVMVersion& other) const { for (int i = 0; i < 5; i++) { int part = i < versionParts.size() ? versionParts[i] : 0; int otherPart = i < other.versionParts.size() ? other.versionParts[i] : 0; if (part > otherPart) { return false; } if (part < otherPart) { return true; } } return false; } bool JVMVersion::operator<=(const JVMVersion& other) const { return (*this < other) || (*this == other); } bool JVMVersion::operator>(const JVMVersion& other) const { return !(*this <= other); } bool JVMVersion::operator>=(const JVMVersion& other) const { return !(*this < other); } bool JVMVersion::operator==(const JVMVersion& other) const { for (int i = 0; i < 5; i++) { int part = i < versionParts.size() ? versionParts[i] : 0; int otherPart = i < other.versionParts.size() ? other.versionParts[i] : 0; if (part != otherPart) { return false; } } return true; }
[ "gtoubassi" ]
[ [ [ 1, 114 ] ] ]
b43c2a390d6f185802f7cb058d74de9e551f1149
c32ec5a3e7133bf16595feb6b6b8d405db913a71
/TrinaSolar_RFID/Document/[LF-HF] HID SDK for WAP family - V4.1.5 - P1/Samples/Cpp/StdAfx.cpp
5f99b654c2452431b4be8ce02a056ffd34af5176
[]
no_license
PawelStasiolek/kris-svn
fb31916e034f9c737b4c3625c7d544f212740f7b
debbb199ffd5a9f1745c68f5803003e25c42a2d1
refs/heads/master
2021-01-17T12:22:39.808327
2011-10-09T14:24:40
2011-10-09T14:24:40
36,716,127
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
// stdafx.cpp : source file that includes just the standard includes // Reader Terminal.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ [ [ 1, 6 ] ] ]
771c3f7ac44a87a30ea8f0afbfd6bc626cbc7200
9420f67e448d4990326fd19841dd3266a96601c3
/ mcvr/mcvr/MarsagliaGenerator.h
440b5aa1cb52d115887577ac680b1bfe8f3e16e2
[]
no_license
xrr/mcvr
4d8d7880c2fd50e41352fae1b9ede0231cf970a2
b8d3b3c46cfddee281e099945cee8d844cea4e23
refs/heads/master
2020-06-05T11:59:27.857504
2010-02-24T19:32:21
2010-02-24T19:32:21
32,275,830
0
0
null
null
null
null
UTF-8
C++
false
false
329
h
#pragma once #include "GaussianGenerator.h" #include "UniformGenerator.h" class MarsagliaGenerator : public GaussianGenerator { bool _cached; double _cache; void Init(void); public: MarsagliaGenerator(void); MarsagliaGenerator(UniformGenerator*); ~MarsagliaGenerator(void); double Next(double, double); };
[ "romain.rousseau@fa0ec5f0-0fe6-11df-8179-3f26cfb4ba5f" ]
[ [ [ 1, 16 ] ] ]
1e7256b6b6ce463c257c7fc020ba1f8939eb0698
c6dca462f8e982b2a327285cf084d08fa7f27dd8
/include/liblearning/deeplearning/self_related_network_objective.h
f7541044c89618ecfe1e6956718a08a7f2181f4b
[]
no_license
nagyistoce/liblearning
2a7e94344f15c5af105974207ece68822102524b
ac0a77dce09ad72f32b2cae067f4616e49d60697
refs/heads/master
2021-01-01T16:59:44.689918
2010-08-20T12:07:22
2010-08-20T12:07:22
32,806,608
0
0
null
null
null
null
UTF-8
C++
false
false
532
h
#ifndef SELF_RELATED_NETWORK_OBJECTIVE_H #define SELF_RELATED_NETWORK_OBJECTIVE_H #include "network_objective.h" class self_related_network_objective:public network_objective { protected: public: self_related_network_objective(); virtual ~self_related_network_objective(); virtual tuple<double, VectorXd> value_diff(deep_auto_encoder & net) = 0; virtual double value(deep_auto_encoder & net) = 0; virtual self_related_network_objective * clone() = 0; }; #endif /* OBJECTIVE_H_ */
[ [ [ 1, 29 ] ] ]
63eef454a662c72c5b92166e942f5878ffe392db
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/include/symbian-r6/Nav2ErrorSymbian.h
5ea578dec460a274bd624baab8270d9b9d51673a
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,182
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef Nav2ErrorSymbian_H #define Nav2ErrorSymbian_H #include "Nav2Error.h" namespace isab { namespace Nav2Error { class Nav2ErrorTableSymbian : public Nav2ErrorTable { void ConstructFromResourceL(TInt aResourceId); Nav2ErrorTableSymbian(); public: Nav2ErrorTableSymbian(TInt aResourceId); static class Nav2ErrorTableSymbian* NewLC(TInt aResourceId); static class Nav2ErrorTableSymbian* NewL(TInt aResourceId); virtual ~Nav2ErrorTableSymbian(); }; } /* namespace Nav2Error */ } /* namespace isab */ #endif /* Nav2ErrorSymbian_H */
[ [ [ 1, 36 ] ] ]
37dee5c32ca9f1bb7bbbb76e56b74df504423371
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Components/Optimizers/ConjugateGradient/elxConjugateGradient.hxx
2bcbff8f93143a7794f79dad9069ed4742ba8a1a
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
18,117
hxx
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxConjugateGradient_hxx #define __elxConjugateGradient_hxx #include "elxConjugateGradient.h" #include <iomanip> #include <string> #include "vnl/vnl_math.h" namespace elastix { using namespace itk; /** * ********************* Constructor **************************** */ template <class TElastix> ConjugateGradient<TElastix> ::ConjugateGradient() { this->m_LineOptimizer = LineOptimizerType::New(); this->SetLineSearchOptimizer( this->m_LineOptimizer ); this->m_EventPasser = EventPassThroughType::New(); this->m_EventPasser->SetCallbackFunction( this, &Self::InvokeIterationEvent ); this->m_LineOptimizer->AddObserver( IterationEvent(), this->m_EventPasser ); this->m_LineOptimizer->AddObserver( StartEvent(), this->m_EventPasser ); this->m_SearchDirectionMagnitude = 0.0; this->m_StartLineSearch = false; this->m_GenerateLineSearchIterations = false; this->m_StopIfWolfeNotSatisfied = true; this->m_WolfeIsStopCondition = false; } // end Constructor /** * ***************** InvokeIterationEvent ************************ */ template <class TElastix> void ConjugateGradient<TElastix>:: InvokeIterationEvent(const EventObject & event) { if( typeid( event ) == typeid( StartEvent ) ) { this->m_StartLineSearch = true; this->m_SearchDirectionMagnitude = this->m_LineOptimizer->GetLineSearchDirection().magnitude(); } else { this->m_StartLineSearch = false; } if ( this->m_GenerateLineSearchIterations ) { this->InvokeEvent( IterationEvent() ); } this->m_StartLineSearch = false; } // end InvokeIterationEvent /** * ***************** StartOptimization ************************ */ template <class TElastix> void ConjugateGradient<TElastix>:: StartOptimization(void) { /** Check if the entered scales are correct and != [ 1 1 1 ...] */ this->SetUseScales(false); const ScalesType & scales = this->GetScales(); if ( scales.GetSize() == this->GetInitialPosition().GetSize() ) { ScalesType unit_scales( scales.GetSize() ); unit_scales.Fill(1.0); if (scales != unit_scales) { /** only then: */ this->SetUseScales(true); } } this->Superclass1::StartOptimization(); } //end StartOptimization /** * ***************** LineSearch ************************ */ template <class TElastix> void ConjugateGradient<TElastix>:: LineSearch( const ParametersType searchDir, double & step, ParametersType & x, MeasureType & f, DerivativeType & g ) { /** Call the superclass's implementation and ignore a * LineSearchError. Just report the error and assume convergence. */ try { this->Superclass1::LineSearch(searchDir, step, x, f, g); } catch ( ExceptionObject& err ) { if ( this->GetLineSearchOptimizer() == 0 ) { throw err; } else if ( this->GetStopCondition() != LineSearchError ) { throw err; } else { xl::xout["error"] << err << std::endl; xl::xout["error"] << "The error is ignored and convergence is assumed." << std::endl; step = 0.0; x = this->GetScaledCurrentPosition(); f = this->GetCurrentValue(); g = this->GetCurrentGradient(); } } } // end LineSearch /** * ***************** DeterminePhase ***************************** * * This method gives only sensible output if it is called * during iterating */ template <class TElastix> std::string ConjugateGradient<TElastix>:: DeterminePhase(void) const { if ( this->GetInLineSearch() ) { return std::string("LineOptimizing"); } return std::string("Main"); } // end DeterminePhase /** * ***************** BeforeRegistration *********************** */ template <class TElastix> void ConjugateGradient<TElastix>:: BeforeRegistration(void) { using namespace xl; /** Add target cells to xout["iteration"].*/ xout["iteration"].AddTargetCell("1a:SrchDirNr"); xout["iteration"].AddTargetCell("1b:LineItNr"); xout["iteration"].AddTargetCell("2:Metric"); xout["iteration"].AddTargetCell("3:StepLength"); xout["iteration"].AddTargetCell("4a:||Gradient||"); xout["iteration"].AddTargetCell("4b:||SearchDir||"); xout["iteration"].AddTargetCell("4c:DirGradient"); xout["iteration"].AddTargetCell("5:Phase"); xout["iteration"].AddTargetCell("6a:Wolfe1"); xout["iteration"].AddTargetCell("6b:Wolfe2"); xout["iteration"].AddTargetCell("7:LinSrchStopCondition"); /** Format the metric and stepsize as floats */ xout["iteration"]["2:Metric"] << std::showpoint << std::fixed; xout["iteration"]["3:StepLength"] << std::showpoint << std::fixed; xout["iteration"]["4a:||Gradient||"] << std::showpoint << std::fixed; xout["iteration"]["4b:||SearchDir||"] << std::showpoint << std::fixed; xout["iteration"]["4c:DirGradient"] << std::showpoint << std::fixed; /** Check in the parameter file whether line search iterations should * be generated */ this->m_GenerateLineSearchIterations = false; //bool std::string generateLineSearchIterations = "false"; this->m_Configuration->ReadParameter( generateLineSearchIterations, "GenerateLineSearchIterations", 0 ); if ( generateLineSearchIterations == "true" ) { this->m_GenerateLineSearchIterations = true; } } // end BeforeRegistration /** * ***************** BeforeEachResolution *********************** */ template <class TElastix> void ConjugateGradient<TElastix> ::BeforeEachResolution(void) { /** Get the current resolution level.*/ unsigned int level = static_cast<unsigned int>( this->m_Registration->GetAsITKBaseType()->GetCurrentLevel() ); /** Set the maximumNumberOfIterations.*/ unsigned int maximumNumberOfIterations = 100; this->m_Configuration->ReadParameter( maximumNumberOfIterations, "MaximumNumberOfIterations", this->GetComponentLabel(), level, 0 ); this->SetMaximumNumberOfIterations( maximumNumberOfIterations ); /** Set the maximumNumberOfIterations used for a line search.*/ unsigned int maximumNumberOfLineSearchIterations = 20; this->m_Configuration->ReadParameter( maximumNumberOfLineSearchIterations, "MaximumNumberOfLineSearchIterations", this->GetComponentLabel(), level, 0 ); this->m_LineOptimizer->SetMaximumNumberOfIterations( maximumNumberOfLineSearchIterations ); /** Set the length of the initial step, used to bracket the minimum. */ double stepLength = 1.0; this->m_Configuration->ReadParameter( stepLength, "StepLength", this->GetComponentLabel(), level, 0 ); this->m_LineOptimizer->SetInitialStepLengthEstimate(stepLength); /** Set the LineSearchValueTolerance */ double lineSearchValueTolerance = 0.0001; this->m_Configuration->ReadParameter( lineSearchValueTolerance, "LineSearchValueTolerance", this->GetComponentLabel(), level, 0 ); this->m_LineOptimizer->SetValueTolerance(lineSearchValueTolerance); /** Set the LineSearchGradientTolerance */ double lineSearchGradientTolerance = 0.9; this->m_Configuration->ReadParameter( lineSearchGradientTolerance, "LineSearchGradientTolerance", this->GetComponentLabel(), level, 0 ); this->m_LineOptimizer->SetGradientTolerance(lineSearchGradientTolerance); /** Set the GradientMagnitudeTolerance */ double gradientMagnitudeTolerance = 0.000001; this->m_Configuration->ReadParameter( gradientMagnitudeTolerance, "GradientMagnitudeTolerance", this->GetComponentLabel(), level, 0 ); this->SetGradientMagnitudeTolerance(gradientMagnitudeTolerance); /** Set the ValueTolerance */ double valueTolerance = 0.00001; this->m_Configuration->ReadParameter( valueTolerance, "ValueTolerance", this->GetComponentLabel(), level, 0 ); this->SetValueTolerance(valueTolerance); /** Set the definition of beta */ std::string betaDefinition = "DaiYuanHestenesStiefel"; this->m_Configuration->ReadParameter( betaDefinition, "ConjugateGradientType", this->GetComponentLabel(), level, 0 ); this->SetBetaDefinition(betaDefinition); /** Just guess this one: */ this->SetMaxNrOfItWithoutImprovement(10); /** Check whether to stop optimisation if Wolfe conditions are not satisfied. */ this->m_StopIfWolfeNotSatisfied = true; std::string stopIfWolfeNotSatisfied = "true"; this->m_Configuration->ReadParameter( stopIfWolfeNotSatisfied, "StopIfWolfeNotSatisfied", this->GetComponentLabel(), level, 0 ); if ( stopIfWolfeNotSatisfied == "false") { this->m_StopIfWolfeNotSatisfied = false; } this->m_WolfeIsStopCondition = false; this->m_SearchDirectionMagnitude = 0.0; this->m_StartLineSearch = false; } // end BeforeEachResolution /** * ***************** AfterEachIteration ************************* */ template <class TElastix> void ConjugateGradient<TElastix> ::AfterEachIteration(void) { using namespace xl; /** Print some information. */ if ( this->GetStartLineSearch() ) { xout["iteration"]["1b:LineItNr"] << "start"; } else { /** * If we are in a line search iteration the current line search * iteration number is printed. * If we are in a "main" iteration (no line search) the last * line search iteration number (so the number of line search * iterations minus one) is printed out. */ xout["iteration"]["1b:LineItNr"] << this->m_LineOptimizer->GetCurrentIteration(); } if ( this->GetInLineSearch() ) { xout["iteration"]["2:Metric"] << this->m_LineOptimizer->GetCurrentValue(); xout["iteration"]["3:StepLength"] << this->m_LineOptimizer->GetCurrentStepLength(); LineOptimizerType::DerivativeType cd; this->m_LineOptimizer->GetCurrentDerivative(cd); xout["iteration"]["4a:||Gradient||"] << cd.magnitude(); xout["iteration"]["7:LinSrchStopCondition"] << "---"; } // end if in line search else { xout["iteration"]["2:Metric"] << this->GetCurrentValue(); xout["iteration"]["3:StepLength"] << this->GetCurrentStepLength(); xout["iteration"]["4a:||Gradient||"] << this->GetCurrentGradient().magnitude(); xout["iteration"]["7:LinSrchStopCondition"] << this->GetLineSearchStopCondition(); } // end else (not in line search) xout["iteration"]["1a:SrchDirNr"] << this->GetCurrentIteration(); xout["iteration"]["5:Phase"] << this->DeterminePhase(); xout["iteration"]["4b:||SearchDir||"] << this->m_SearchDirectionMagnitude ; xout["iteration"]["4c:DirGradient"] << this->m_LineOptimizer->GetCurrentDirectionalDerivative(); if ( this->m_LineOptimizer->GetSufficientDecreaseConditionSatisfied() ) { xout["iteration"]["6a:Wolfe1"] << "true"; } else { xout["iteration"]["6a:Wolfe1"] << "false"; } if ( this->m_LineOptimizer->GetCurvatureConditionSatisfied() ) { xout["iteration"]["6b:Wolfe2"] << "true"; } else { xout["iteration"]["6b:Wolfe2"] << "false"; } if ( !(this->GetInLineSearch()) ) { /** Set the initial step length estimate for the next line search * to the result of the last iteration */ this->m_LineOptimizer->SetInitialStepLengthEstimate( this->GetCurrentStepLength() ); /** If new samples: compute a new gradient and value. These * will be used in the computation of a new search direction */ if ( this->GetNewSamplesEveryIteration() ) { this->SelectNewSamples(); try { this->GetScaledValueAndDerivative( this->GetScaledCurrentPosition(), this->m_CurrentValue, this->m_CurrentGradient ); } catch ( ExceptionObject& err ) { this->m_StopCondition = MetricError; this->StopOptimization(); throw err; } } //end if new samples every iteration } // end if not in line search } // end AfterEachIteration /** * ***************** AfterEachResolution ************************* */ template <class TElastix> void ConjugateGradient<TElastix> ::AfterEachResolution(void) { /** typedef enum { MetricError, LineSearchError, MaximumNumberOfIterations, GradientMagnitudeTolerance, ValueTolerance, Unknown } */ std::string stopcondition; if ( this->m_WolfeIsStopCondition ) { stopcondition = "Wolfe conditions are not satisfied"; } else { switch( this->GetStopCondition() ) { case MetricError : stopcondition = "Error in metric"; break; case LineSearchError : stopcondition = "Error in LineSearch"; break; case MaximumNumberOfIterations : stopcondition = "Maximum number of iterations has been reached"; break; case GradientMagnitudeTolerance : stopcondition = "The gradient magnitude has (nearly) vanished"; break; case ValueTolerance : stopcondition = "Almost no decrease in function value anymore"; break; case InfiniteBeta : stopcondition = "The beta factor became infinite"; break; default: stopcondition = "Unknown"; break; } } // end else /** Print the stopping condition */ elxout << "Stopping condition: " << stopcondition << "." << std::endl; } // end AfterEachResolution /** * ******************* AfterRegistration ************************ */ template <class TElastix> void ConjugateGradient<TElastix> ::AfterRegistration(void) { /** Print the best metric value */ double bestValue = this->GetCurrentValue(); elxout << std::endl << "Final metric value = " << bestValue << std::endl; } // end AfterRegistration /** * *********************** TestConvergence ***************** */ template <class TElastix> bool ConjugateGradient<TElastix> ::TestConvergence( bool firstLineSearchDone ) { bool convergence = this->Superclass1::TestConvergence( firstLineSearchDone ); /** Stop if the Wolfe conditions are not satisfied * NB: this check is only done when 'convergence' wasn't true already */ if ( this->m_StopIfWolfeNotSatisfied && !convergence && firstLineSearchDone) { if ( (!(this->m_LineOptimizer->GetCurvatureConditionSatisfied())) || (!(this->m_LineOptimizer->GetSufficientDecreaseConditionSatisfied())) ) { /** Stop the optimisation */ this->m_WolfeIsStopCondition = true; convergence = true; } } return convergence; } // end TestConvergence /** * ***************** GetLineSearchStopCondition ***************** */ template <class TElastix> std::string ConjugateGradient<TElastix> ::GetLineSearchStopCondition(void) const { /** Must be repeated here; otherwise the StopconditionTypes of the * GenericConjugateGradientOptimizer and the LineSearchOptimizer * are mixed up. */ typedef enum { StrongWolfeConditionsSatisfied, MetricError, MaximumNumberOfIterations, StepTooSmall, StepTooLarge, IntervalTooSmall, RoundingError, AscentSearchDirection, Unknown } LineSearchStopConditionType; std::string stopcondition; LineSearchStopConditionType lineSearchStopCondition = static_cast<LineSearchStopConditionType>( this->m_LineOptimizer->GetStopCondition() ) ; switch( lineSearchStopCondition ) { case StrongWolfeConditionsSatisfied : stopcondition = "WolfeSatisfied"; break; case MetricError : stopcondition = "MetricError"; break; case MaximumNumberOfIterations : stopcondition = "MaxNrIterations"; break; case StepTooSmall : stopcondition = "StepTooSmall"; break; case StepTooLarge : stopcondition = "StepTooLarge"; break; case IntervalTooSmall : stopcondition = "IntervalTooSmall"; break; case RoundingError : stopcondition = "RoundingError"; break; case AscentSearchDirection : stopcondition = "AscentSearchDir"; break; default: stopcondition = "Unknown"; break; } return stopcondition; } // end GetLineSearchStopCondition } // end namespace elastix #endif // end #ifndef __elxConjugateGradient_hxx
[ [ [ 1, 599 ] ] ]
6243bf5870c65af50988cd06592e2e72d26db6ba
cc97070bb192c613fae05f301713a9ed47e89278
/proto.h
0dbb32b535ae1accb838e40ebb9753b2aeca4a39
[]
no_license
username0x0a/facebook-protocol
257f39264ad801b3108d5d97c6ec7216d34053e3
a97982e0187330326f1c40c709cba5eef60ceea9
refs/heads/master
2021-06-15T06:45:42.371823
2011-04-20T02:16:48
2011-04-20T02:16:48
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
7,162
h
/* Facebook plugin for Miranda Instant Messenger _____________________________________________ Copyright © 2009-11 Michal Zelinka This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. File name : $HeadURL: https://[email protected]/svn/trunk/facebook/proto.h $ Revision : $Revision: 91 $ Last change by : $Author: n3weRm0re.ewer $ Last change on : $Date: 2011-01-08 11:10:34 +0100 (Sat, 08 Jan 2011) $ */ #pragma once class FacebookProto : public PROTO_INTERFACE { public: FacebookProto( const char *proto_name, const TCHAR *username ); ~FacebookProto( ); __inline void* operator new( size_t size ) { return calloc( 1, size ); } __inline void operator delete( void* p ) { free( p ); } inline const char* ModuleName( ) const { return m_szModuleName; } inline bool isOnline( ) { return ( m_iStatus != ID_STATUS_OFFLINE && m_iStatus != ID_STATUS_CONNECTING ); } inline bool isOffline( ) { return ( m_iStatus == ID_STATUS_OFFLINE ); } //PROTO_INTERFACE virtual HANDLE __cdecl AddToList( int flags, PROTOSEARCHRESULT* psr ); virtual HANDLE __cdecl AddToListByEvent( int flags, int iContact, HANDLE hDbEvent ); virtual int __cdecl Authorize( HANDLE hDbEvent ); virtual int __cdecl AuthDeny( HANDLE hDbEvent, const PROTOCHAR* szReason ); virtual int __cdecl AuthRecv( HANDLE hContact, PROTORECVEVENT* ); virtual int __cdecl AuthRequest( HANDLE hContact, const PROTOCHAR* szMessage ); virtual HANDLE __cdecl ChangeInfo( int iInfoType, void* pInfoData ); virtual HANDLE __cdecl FileAllow( HANDLE hContact, HANDLE hTransfer, const PROTOCHAR* szPath ); virtual int __cdecl FileCancel( HANDLE hContact, HANDLE hTransfer ); virtual int __cdecl FileDeny( HANDLE hContact, HANDLE hTransfer, const PROTOCHAR* szReason ); virtual int __cdecl FileResume( HANDLE hTransfer, int* action, const PROTOCHAR** szFilename ); virtual DWORD_PTR __cdecl GetCaps( int type, HANDLE hContact = NULL ); virtual HICON __cdecl GetIcon( int iconIndex ); virtual int __cdecl GetInfo( HANDLE hContact, int infoType ); virtual HANDLE __cdecl SearchBasic( const PROTOCHAR* id ); virtual HANDLE __cdecl SearchByEmail( const PROTOCHAR* email ); virtual HANDLE __cdecl SearchByName( const PROTOCHAR* nick, const PROTOCHAR* firstName, const PROTOCHAR* lastName ); virtual HWND __cdecl SearchAdvanced( HWND owner ); virtual HWND __cdecl CreateExtendedSearchUI( HWND owner ); virtual int __cdecl RecvContacts( HANDLE hContact, PROTORECVEVENT* ); virtual int __cdecl RecvFile( HANDLE hContact, PROTOFILEEVENT* ); virtual int __cdecl RecvMsg( HANDLE hContact, PROTORECVEVENT* ); virtual int __cdecl RecvUrl( HANDLE hContact, PROTORECVEVENT* ); virtual int __cdecl SendContacts( HANDLE hContact, int flags, int nContacts, HANDLE* hContactsList ); virtual HANDLE __cdecl SendFile( HANDLE hContact, const PROTOCHAR* szDescription, PROTOCHAR** ppszFiles ); virtual int __cdecl SendMsg( HANDLE hContact, int flags, const char* msg ); virtual int __cdecl SendUrl( HANDLE hContact, int flags, const char* url ); virtual int __cdecl SetApparentMode( HANDLE hContact, int mode ); virtual int __cdecl SetStatus( int iNewStatus ); virtual HANDLE __cdecl GetAwayMsg( HANDLE hContact ); virtual int __cdecl RecvAwayMsg( HANDLE hContact, int mode, PROTORECVEVENT* evt ); virtual int __cdecl SendAwayMsg( HANDLE hContact, HANDLE hProcess, const char* msg ); virtual int __cdecl SetAwayMsg( int iStatus, const PROTOCHAR* msg ); virtual int __cdecl UserIsTyping( HANDLE hContact, int type ); virtual int __cdecl OnEvent( PROTOEVENTTYPE iEventType, WPARAM wParam, LPARAM lParam ); //////////////////////// // Services int __cdecl GetName( WPARAM, LPARAM ); int __cdecl GetStatus( WPARAM, LPARAM ); int __cdecl SetStatus( WPARAM, LPARAM ); INT_PTR __cdecl GetMyAwayMsg( WPARAM, LPARAM ); int __cdecl SetMyAwayMsg( WPARAM, LPARAM ); INT_PTR __cdecl SvcCreateAccMgrUI( WPARAM, LPARAM ); INT_PTR __cdecl GetMyAvatar(WPARAM, LPARAM ); // Events int __cdecl OnModulesLoaded(WPARAM, LPARAM); int __cdecl OnOptionsInit(WPARAM, LPARAM); int __cdecl OnBuildStatusMenu(WPARAM wParam,LPARAM lParam); int __cdecl OnBuildContactMenu(WPARAM,LPARAM); int __cdecl OnContactDeleted(WPARAM,LPARAM); int __cdecl OnMind(WPARAM,LPARAM); int __cdecl OnPreShutdown(WPARAM,LPARAM); int __cdecl OnIdleChanged(WPARAM,LPARAM); // Loops bool NegotiateConnection( ); BYTE GetPollRate( ); void __cdecl MessageLoop(void *); void __cdecl UpdateLoop(void *); void __cdecl KillThreads(void *); // Processing threads void __cdecl ProcessBuddyList( void* ); void __cdecl ProcessMessages( void* ); void __cdecl ProcessFeeds( void* ); void ProcessAvatar(HANDLE,const std::string*,bool force=false); // Worker threads void __cdecl SignOn(void *); void __cdecl SignOff(void *); void __cdecl GetAwayMsgWorker(void *); void __cdecl SetAwayMsgWorker(void *); void __cdecl UpdateContactWorker(void *); void __cdecl UpdateAvatarWorker(void *); void __cdecl SendMsgWorker(void *); void __cdecl SendTypingWorker(void *); // TODO: Thread required? void __cdecl CloseChatWorker(void *); // TODO: Thread required? // Contacts handling bool IsMyContact(HANDLE); HANDLE ContactIDToHContact(std::string); HANDLE AddToContactList(facebook_user*); void SetAllContactStatuses(int); bool ContactNeedsUpdate(facebook_user*); // JSON parser facebook_json_parser parcy; // Connection client facebook_client facy; // TODO: Refactor to "client" and make dynamic int __cdecl Test( WPARAM, LPARAM ); // Helpers std::string GetAvatarFolder(); bool AvatarExists( std::string user_id ); void ToggleStatusMenuItems( BOOL bEnable ); // Handles, Locks HGENMENU m_hMenuRoot; HANDLE m_hStatusMind; HANDLE signon_lock_; HANDLE avatar_lock_; HANDLE log_lock_; HANDLE update_loop_lock_; HANDLE message_loop_lock_; HANDLE m_hNetlibUser; HANDLE m_hUpdLoop; time_t m_tUpdLoop; HANDLE m_hMsgLoop; time_t m_tMsgLoop; std::string def_avatar_folder_; HANDLE hAvatarFolder_; // Information providing int Log(const char *fmt,...); int NotifyEvent(TCHAR* title, TCHAR* info, HANDLE contact, DWORD flags, TCHAR* url=NULL); };
[ [ [ 1, 195 ] ] ]
8b7c4be31e24c9a426885ccd6e6c90b45d6d942d
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/GLM_GTX_norm.h
457dce155c09b4f004c35be45352b195e5028556
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
768
h
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2008 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2008-10-22 // Updated : 2009-01-16 // Licence : This source is under MIT License /////////////////////////////////////////////////////////////////////////////////////////////////// // Dependency: // - GLM core /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_gtx_norm_api #define glm_gtx_norm_api #include "gtx/norm.hpp" namespace glm { using GLM_GTX_norm; } #endif//glm_gtx_norm_api
[ [ [ 1, 22 ] ] ]
e0b964f98370e5a77e4c5ececfb6005887adc4a2
6debdf46efa2d21882607240fe8233be29ff4381
/src/table.h
8d1c0b92a0d8d17c753627a9b8dd3f5c63a53b25
[]
no_license
maciek-slon/KODA
ebc1856e3a258b4e24bf8bd4046d98b20e0e7397
8d672101b839b112b3b4069efdb37f31dc5796a6
refs/heads/master
2020-03-30T01:53:22.184046
2011-01-27T12:38:40
2011-01-27T12:38:40
1,274,030
1
0
null
null
null
null
UTF-8
C++
false
false
2,122
h
// // table.h // // (c) Copyright 2000-2002 William A. McKee. All rights reserved. // // Please send question and comments to [email protected] // // April 29, 2000 - Created. // // March 26, 2002 - Compiled against GNU C++ compiler // // Table template class // // - a light weight class for maintaining variable sized arrays // template <class T> class Table { private : T * data; int base; int size; int limit; void resize (int i) { if (size == 0) base = i; if (i < base) { int d = base - i; if (size + d >= limit) { while (size + d >= limit) { if (limit == 0) limit = 1; else limit *= 2; } } T * tmp = new T [limit]; int j; for (j = 0; j < size; j++) tmp [j + d] = data [j]; for (j = size; j + d < limit; j++) tmp [j + d] = T (); for (j = 0; j < d; j++) tmp [j] = T (); delete [] data; data = tmp; size += d; base -= d; } if (i - base >= limit) { while (i - base >= limit) { if (limit == 0) limit = 1; else limit *= 2; } T * tmp = new T [limit]; int j; for (j = 0; j < size; j++) tmp [j] = data [j]; for (j = size; j < limit; j++) tmp [j] = T (); delete [] data; data = tmp; } if (i + 1 - base > size) size = i + 1 - base; } public : Table () { data = NULL; base = 0; size = 0; limit = 0; } ~Table () { delete [] data; } T & operator [] (int rhs) { resize (rhs); return data [rhs - base]; } int Base () { return base; } int Summit () { return size + base - 1; } };
[ [ [ 1, 92 ] ] ]
2a5184e8d85eae5335545b9e9e8b44c9adb4abc0
c0bd82eb640d8594f2d2b76262566288676b8395
/src/shared/LocationVector.h
d1eeeb9253ad620944458f7bd9d08376cb009a28
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
3,976
h
#ifndef _LOCATIONVECTOR_H #define _LOCATIONVECTOR_H /////////////////////////////////////////////////////////// // Location vector class (X, Y, Z, O) // By Burlex ////////////////////////////////////////////////////////// class LocationVector { public: // Constructors LocationVector(float X, float Y, float Z) : x(X), y(Y), z(Z), o(0) {} LocationVector(float X, float Y, float Z, float O) : x(X), y(Y), z(Z), o(O) {} LocationVector() : x(0), y(0), z(0), o(0) {} // (dx * dx + dy * dy + dz * dz) float DistanceSq(const LocationVector & comp) { float delta_x = comp.x - x; float delta_y = comp.y - y; float delta_z = comp.z - z; return (powf(delta_x, 2) + powf(delta_y, 2) + powf(delta_z, 2)); } float DistanceSq(const float &X, const float &Y, const float &Z) { float delta_x = X - x; float delta_y = Y - y; float delta_z = Z - z; return (powf(delta_x, 2) + powf(delta_y, 2) + powf(delta_z, 2)); } // sqrt(dx * dx + dy * dy + dz * dz) float Distance(const LocationVector & comp) { float delta_x = comp.x - x; float delta_y = comp.y - y; float delta_z = comp.z - z; return sqrtf(powf(delta_x, 2) + powf(delta_y, 2) + powf(delta_z, 2)); } float Distance(const float &X, const float &Y, const float &Z) { float delta_x = X - x; float delta_y = Y - y; float delta_z = Z - z; return sqrtf(powf(delta_x, 2) + powf(delta_y, 2) + powf(delta_z, 2)); } float Distance2DSq(const LocationVector & comp) { float delta_x = comp.x - x; float delta_y = comp.y - y; return (powf(delta_x, 2) + powf(delta_y, 2)); } float Distance2DSq(const float & X, const float & Y) { float delta_x = X - x; float delta_y = Y - y; return (powf(delta_x, 2) + powf(delta_y, 2)); } float Distance2D(LocationVector & comp) { float delta_x = comp.x - x; float delta_y = comp.y - y; return sqrtf(powf(delta_x, 2) + powf(delta_y, 2)); } float Distance2D(const float & X, const float & Y) { float delta_x = X - x; float delta_y = Y - y; return sqrtf(powf(delta_x, 2) + powf(delta_y, 2)); } // atan2(dx / dy) float CalcAngTo(const LocationVector & dest) { float dx = dest.x - x; float dy = dest.y - y; if(dy != 0.0f) return atan2(dy, dx); else return 0.0f; } float CalcAngFrom(const LocationVector & src) { float dx = x - src.x; float dy = y - src.y; if(dy != 0.0f) return atan2(dy, dx); else return 0.0f; } void ChangeCoords(float X, float Y, float Z, float O) { x = X; y = Y; z = Z; o = O; } void ChangeCoords(float X, float Y, float Z) { x = X; y = Y; z = Z; } // add/subtract/equality vectors LocationVector & operator += (const LocationVector & add) { x += add.x; y += add.y; z += add.z; o += add.o; return *this; } LocationVector & operator -= (const LocationVector & sub) { x -= sub.x; y -= sub.y; z -= sub.z; o -= sub.o; return *this; } LocationVector & operator = (const LocationVector & eq) { x = eq.x; y = eq.y; z = eq.z; o = eq.o; return *this; } bool operator == (const LocationVector & eq) { if(eq.x == x && eq.y == y && eq.z == z) return true; else return false; } float x; float y; float z; float o; }; #endif
[ [ [ 1, 162 ] ] ]
9749a7a35ab2aab9eb322739bd7f72d4102dfe71
89147ec4f5c9a5cf4ad59c83517da2179a2f040e
/allpalin/allpalin.cpp
97ebf4773cc8f6aecec7fe7babf3b9355dcf2448
[]
no_license
swarnaprakash/my-acm-problemset
3f977867a6637a28b486021634e30efabe30ef52
e07654590c2691839b01291e5237082971b8cc85
refs/heads/master
2016-09-05T10:39:59.726651
2011-09-04T15:01:01
2011-09-04T15:01:01
2,323,366
0
0
null
null
null
null
UTF-8
C++
false
false
858
cpp
// Author swarnaprakash #include<cstdio> #include<cstring> #include<cstdlib> #include<set> using namespace std; set<int> pal; void fun(char *); int main() { char a[10]; char i,j,k,x; for(x='0';x<='9';++x) { for(i='0';i<='9';++i) for(j='0';j<='9';++j) for(k='0';k<='9';++k) { a[0]=a[6]=i; a[1]=a[5]=j; a[2]=a[4]=k; a[3]=x; a[7]=0; fun(a); a[0]=a[7]=i; a[1]=a[6]=j; a[2]=a[5]=k; a[3]=a[4]=x; a[8]=0; fun(a); } } for(set<int>::iterator it=pal.begin();it!=pal.end();++it) printf("%d\n",*it); return 0; } void fun(char *a) { int i; for(i=strlen(a)-1;i>=0 && a[i]=='0';--i); a[i+1]=0; //Remove trailing zeros int n=atoi(a); if(n>0 && n<=100000000) pal.insert(n); }
[ [ [ 1, 58 ] ] ]
a9d44c06f3794ba4431fa8e1db9fd95554b73dd5
c13ef26a8b4b1e196c6c593a73520787a7c15b80
/samples_atistream/NBody/NBody.hpp
c81900c0c48e51817994e5c816c9e0cd1aa2e492
[]
no_license
ajaykumarkannan/simulation-opencl
73072dcdacf5f3c93e0c038caedb60b479839327
53d00629358d3a2b1135f4daf0c327436fd9ed79
refs/heads/master
2021-01-23T08:39:00.347158
2010-03-09T15:43:50
2010-03-09T15:43:50
37,275,925
0
0
null
null
null
null
UTF-8
C++
false
false
10,886
hpp
/* ============================================================ Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved. Redistribution and use of this material is permitted under the following conditions: Redistributions must retain the above copyright notice and all terms of this license. In no event shall anyone redistributing or accessing or using this material commence or participate in any arbitration or legal action relating to this material against Advanced Micro Devices, Inc. or any copyright holders or contributors. The foregoing shall survive any expiration or termination of this license or any agreement or access or use related to this material. ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL. THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERA TION, OR THAT IT IS FREE FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS (US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES, OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S. MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED, EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS, INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS, COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to computer software and technical data, respectively. Use, duplication, distribution or disclosure by the U.S. Government and/or DOD agencies is subject to the full extent of restrictions in all applicable regulations, including those found at FAR52.227 and DFARS252.227 et seq. and any successor regulations thereof. Use of this material by the U.S. Government and/or DOD agencies is acknowledgment of the proprietary rights of any copyright holders and contributors, including those of Advanced Micro Devices, Inc., as well as the provisions of FAR52.227-14 through 23 regarding privately developed and/or commercial computer software. This license forms the entire agreement regarding the subject matter hereof and supersedes all proposals and prior discussions and writings between the parties with respect thereto. This license does not affect any ownership, rights, title, or interest in, or relating to, this material. No terms of this license can be modified or waived, and no breach of this license can be excused, unless done so in a writing signed by all affected parties. Each term of this license is separately enforceable. If any term of this license is determined to be or becomes unenforceable or illegal, such term shall be reformed to the minimum extent necessary in order for this license to remain in effect in accordance with its terms as modified by such reformation. This license shall be governed by and construed in accordance with the laws of the State of Texas without regard to rules on conflicts of law of any state or jurisdiction or the United Nations Convention on the International Sale of Goods. All disputes arising out of this license shall be subject to the jurisdiction of the federal and state courts in Austin, Texas, and all defenses are hereby waived concerning personal jurisdiction and venue of these courts. ============================================================ */ #ifndef NBODY_H_ #define NBODY_H_ #if defined(__APPLE__) || defined(__MACOSX) #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <SDKUtil/SDKCommon.hpp> #include <SDKUtil/SDKApplication.hpp> #include <SDKUtil/SDKCommandArgs.hpp> #include <SDKUtil/SDKFile.hpp> #define GROUP_SIZE 64 #define ITER 5 /** * NBody * Class implements OpenCL NBody sample * Derived from SDKSample base class */ class NBody : public SDKSample { cl_double setupTime; /**< time taken to setup OpenCL resources and building kernel */ cl_double kernelTime; /**< time taken to run kernel and read result back */ size_t maxWorkGroupSize; /**< Max allowed work-items in a group */ cl_uint maxDimensions; /**< Max group dimensions allowed */ size_t* maxWorkItemSizes; /**< Max work-items sizes in each dimensions */ cl_ulong totalLocalMemory; /**< Max local memory allowed */ cl_ulong usedLocalMemory; /**< Used local memory */ cl_float delT; /**< dT (timestep) */ cl_float espSqr; /**< Softening Factor*/ cl_float* initPos; /**< initial position */ cl_float* initVel; /**< initial velocity */ cl_float* vel; /**< Output velocity */ cl_float* refPos; /**< Reference position */ cl_float* refVel; /**< Reference velocity */ cl_context context; /**< CL context */ cl_device_id *devices; /**< CL device list */ cl_mem updatedPos; /**< Position of partciles */ cl_mem updatedVel; /**< Velocity of partciles */ cl_command_queue commandQueue; /**< CL command queue */ cl_program program; /**< CL program */ cl_kernel kernel; /**< CL kernel */ cl_int numParticles; private: float random(float randMax, float randMin); int compareArray(const float* mat0, const float* mat1, unsigned int size); public: /** * Constructor * Initialize member variables * @param name name of sample (string) */ explicit NBody(std::string name) : SDKSample(name), setupTime(0), kernelTime(0), delT(0.005f), espSqr(50.0f), initPos(NULL), initVel(NULL), vel(NULL), refPos(NULL), refVel(NULL), devices(NULL), maxWorkItemSizes(NULL) { numParticles = 64; } /** * Constructor * Initialize member variables * @param name name of sample (const char*) */ explicit NBody(const char* name) : SDKSample(name), setupTime(0), kernelTime(0), delT(0.005f), espSqr(50.0f), initPos(NULL), initVel(NULL), vel(NULL), refPos(NULL), refVel(NULL), devices(NULL), maxWorkItemSizes(NULL) { numParticles = 64; } ~NBody(); /** * Allocate and initialize host memory array with random values * @return 1 on success and 0 on failure */ int setupNBody(); /** * OpenCL related initialisations. * Set up Context, Device list, Command Queue, Memory buffers * Build CL kernel program executable * @return 1 on success and 0 on failure */ int setupCL(); /** * Set values for kernels' arguments * @return 1 on success and 0 on failure */ int setupCLKernels(); /** * Enqueue calls to the kernels * on to the command queue, wait till end of kernel execution. * Get kernel start and end time if timing is enabled * @return 1 on success and 0 on failure */ int runCLKernels(); /** * Reference CPU implementation of Binomial Option * for performance comparison */ void nBodyCPUReference(); /** * Override from SDKSample. Print sample stats. */ void printStats(); /** * Override from SDKSample. Initialize * command line parser, add custom options */ int initialize(); /** * Override from SDKSample, adjust width and height * of execution domain, perform all sample setup */ int setup(); /** * Override from SDKSample * Run OpenCL NBody */ int run(); /** * Override from SDKSample * Cleanup memory allocations */ int cleanup(); /** * Override from SDKSample * Verify against reference implementation */ int verifyResults(); }; #endif // NBODY_H_
[ "juergen.broder@c62875e2-cac2-11de-a9c8-2fbcfba63733" ]
[ [ [ 1, 270 ] ] ]
66cac9bfd2498774a720fbd2c48db292bb232ea1
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Application/SysCAD/NeutralCommon.h
35a6a51e879e9e4a15389b4f9716f9f5f4bb8479
[]
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
4,265
h
#pragma once #ifndef __DBBASE_H #include "dbbase.h" #endif #include "grfdoc.h" //--------------------------------------------------------------------------- const int CommonDBMaxTagLen = 61; const int CommonDBMaxDescLen = 256; const int CommonDBMaxLibraryLen = 256; const int CommonDBMaxPhNmLen = 64; //--------------------------------------------------------------------------- class CDblTriPt; class CFltTriPt; class CDblTriPt { public: CDblTriPt(); CDblTriPt(const CDblTriPt & D); CDblTriPt(const CFltTriPt & D); CDblTriPt(double X, double Y, double Z); CDblTriPt & operator=(const CDblTriPt & D); CDblTriPt operator+(const CDblTriPt & D); CDblTriPt operator-(const CDblTriPt & D); double m_X, m_Y, m_Z; }; inline CDblTriPt::CDblTriPt() { m_X=m_Y=m_Z=0; } inline CDblTriPt::CDblTriPt (const CDblTriPt & D) { m_X=D.m_X; m_Y=D.m_Y; m_Z=D.m_Z; } inline CDblTriPt::CDblTriPt(double X, double Y, double Z) { m_X=X; m_Y=Y; m_Z=Z; } inline CDblTriPt & CDblTriPt::operator=(const CDblTriPt & D) { m_X=D.m_X; m_Y=D.m_Y; m_Z=D.m_Z; return *this; } inline CDblTriPt CDblTriPt::operator+(const CDblTriPt & D) { return CDblTriPt(m_X+D.m_X, m_Y+D.m_Y, m_Z+D.m_Z); } inline CDblTriPt CDblTriPt::operator-(const CDblTriPt & D) { return CDblTriPt(m_X-D.m_X, m_Y-D.m_Y, m_Z-D.m_Z); } //--------------------------------------------------------------------------- class CNeutralGroups : public CFileRec { public: CNeutralGroups(KWDatabase* pDB_); virtual void Init(); virtual int Read() { return BaseRead(); }; virtual int Write(BOOL AddNew = TRUE) { return BaseWrite(AddNew); }; protected: static BOOL bDoneInit; public: char m_sGroup[CommonDBMaxTagLen]; char m_sDescription[CommonDBMaxDescLen]; CDblTriPt m_Lo; CDblTriPt m_Hi; CDblTriPt m_AlignLo; CDblTriPt m_AlignHi; }; //--------------------------------------------------------------------------- class CNeutralGroupTagEditor { public: CNeutralGroupTagEditor(); int FindOldTag(LPCTSTR RqdTag) { return FindOldTag(m_pOldTags, RqdTag); }; int FindNewTag(LPCTSTR RqdTag) { return FindNewTag(m_pNewTags, RqdTag); }; CString AdjustTag(LPCTSTR OldTag); CString AdjustTagWild(LPCTSTR OldTag); static int FindOldTag(CStringArray * OldTags, LPCTSTR RqdTag); static int FindNewTag(CStringArray * NewTags, LPCTSTR RqdTag); static CString AdjustTag(LPCTSTR OldTag, long FixupRule, CString & String1, CString & String2, CStringArray * OldTags, CStringArray * NewTags); static CString AdjustTagWild(LPCTSTR OldTag, long FixupRule, CString & String1, CString & String2, CStringArray * OldTags, CStringArray * NewTags); protected: long m_iFixupRule; CString m_sString1; CString m_sString2; CStringArray * m_pOldTags; CStringArray * m_pNewTags; }; //--------------------------------------------------------------------------- class CNeutralGroupInserts : public CFileRec { public: CNeutralGroupInserts(KWDatabase* pDB_); //virtual ~CNeutralGroupInserts(); virtual void Init(); virtual int Read() { return BaseRead(); }; virtual int Write(BOOL AddNew = TRUE) { return BaseWrite(AddNew); }; protected: static BOOL bDoneInit; public: char m_sLibrary[CommonDBMaxLibraryLen]; char m_sGroup[CommonDBMaxTagLen]; char m_sInsertPg[CommonDBMaxPhNmLen]; CDblTriPt m_Insert; CDblTriPt m_Scale; CDblTriPt m_TagPt; CDblTriPt m_TagScale; double m_TagRotation; BOOL m_TagVisible; int m_iFixupRule; char m_sFixupString1[CommonDBMaxTagLen]; char m_sFixupString2[CommonDBMaxTagLen]; }; //--------------------------------------------------------------------------- class CNeutralGrpDescItem { public: CString m_sGroup; CString m_Desc; }; class CNeutralGrpDescList : public CList<CNeutralGrpDescItem , CNeutralGrpDescItem&> {}; //---------------------------------------------------------------------------
[ [ [ 1, 104 ], [ 110, 121 ] ], [ [ 105, 109 ] ] ]
2027f131ab3d2177de99c03d3b68bf9db6b471d3
60b362ba672a29bedf3d44abf11138dd71742c5d
/project/start/ex5-Project/Level.h
98773402382df155fefcb2ac86b6c55eb40c8039
[]
no_license
AndreyShamis/oop1
9e04882ab6969cc542e99422b84114157d4b20f3
861da0e7a70eba21e4b7ee39e355c21a864ce8b1
refs/heads/master
2016-09-06T14:15:47.867525
2011-03-16T22:20:04
2011-03-16T22:20:04
32,789,848
0
0
null
null
null
null
UTF-8
C++
false
false
355
h
/* This class provide level indication object for more inforamtion about all function look to cpp file */ #pragma once #include "Objects.h" #include "Sprite.h" #include <vector> using namespace std ; class Level : public Objects { public: Level(); void Draw(); void setLevel(const int &level); private: int _level; };
[ "[email protected]@915c7e4a-0830-d67a-7742-9bd6d4e428b7" ]
[ [ [ 1, 24 ] ] ]
48911528028b9f7dd4767427af6e585885da6548
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/databaseserver/HousingDBCtrl.cpp
0339cb612c5b78118828a36c3e629caa6b3293a9
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
6,439
cpp
#include "stdafx.h" #if __VER >= 13 // __HOUSING #include "HousingDBCtrl.h" #include "Housing.h" #include "dptrans.h" extern AppInfo g_appInfo; //////////////////////////////////////////////////////////////////// /// CHousingDBCtrl ///////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// CHousingDBCtrl::CHousingDBCtrl(void) { } CHousingDBCtrl::~CHousingDBCtrl(void) { } void CHousingDBCtrl::Handler( LPDB_OVERLAPPED_PLUS pov, DWORD dwCompletionKey ) { CAr ar( pov->lpBuf, pov->uBufSize ); switch( pov->nQueryMode ) { case QUERY_HOUSING_LOAD: { DWORD dwPlayerId; ar >> dwPlayerId; LoadHousingInfo( dwPlayerId, dwCompletionKey ); } break; case QUERY_HOUSING_INSERT_LIST: { DWORD dwPlayerId, dwItemId; ar >> dwPlayerId >> dwItemId; InsertFurnitureList( dwPlayerId, dwItemId, dwCompletionKey ); } break; case QUERY_HOUSING_SETUP_FURNITURE: { DWORD dwPlayerId; HOUSINGINFO housingInfo; ar >> dwPlayerId; housingInfo.Serialize( ar ); SetupFurniture( dwPlayerId, housingInfo, dwCompletionKey ); } break; case QUERY_HOUSING_SET_VISITALLOW: { DWORD dwPlayerId, dwTargetId; BOOL bAllow; ar >> dwPlayerId >> dwTargetId >> bAllow; SetVisitAllow( dwPlayerId, dwTargetId, bAllow, dwCompletionKey ); } break; case QUERY_HOUSING_GM_REMOVEALL: { DWORD dwPlayerId; ar >> dwPlayerId; CHousing* pHousing = CHousingMng::GetInstance()->GetHousing( dwPlayerId ); if( pHousing ) pHousing->ProcessExpiredFurniture( time_null(), TRUE ); } break; } } void CHousingDBCtrl::LoadHousingInfo( DWORD dwPlayerId, DPID dpId ) { CHousing* pHousing = CHousingMng::GetInstance()->GetHousing( dwPlayerId ); if( !pHousing ) { pHousing = CHousingMng::GetInstance()->CreateHousing( dwPlayerId ); if( !pHousing ) // 생성 실패시 그냥 리턴.. return; // DB 로딩... CQuery* pQuery = GetQueryObject(); if( pQuery->Execute( "usp_Housing_Load '%02d', '%07d'", g_appInfo.dwSys, dwPlayerId ) ) { while( pQuery->Fetch() ) { HOUSINGINFO housingInfo; housingInfo.dwItemId = static_cast<DWORD>( pQuery->GetInt( "ItemIndex" ) ); housingInfo.tKeepTime = static_cast<time_t>( pQuery->GetInt64( "tKeepTime" ) ); housingInfo.bSetup = static_cast<BOOL>( pQuery->GetInt( "bSetup" ) ); housingInfo.vPos.x = pQuery->GetFloat( "x_Pos" ); housingInfo.vPos.y = pQuery->GetFloat( "y_Pos" ); housingInfo.vPos.z = pQuery->GetFloat( "z_Pos" ); housingInfo.fAngle = pQuery->GetFloat( "fAngle" ); ItemProp* pItemProp = prj.GetItemProp( housingInfo.dwItemId ); if( pItemProp && pItemProp->dwItemKind1 == IK1_HOUSING ) pHousing->SetFurnitureList( housingInfo, TRUE ); } if( pQuery->MoreResults() ) { while( pQuery->Fetch() ) pHousing->SetVisitAllow( pQuery->GetInt( "f_idPlayer" ), TRUE ); } } } // 하우징 정보를 월드서버에 전달... CDPTrans::GetInstance()->SendHousingLoadInfo( dwPlayerId, pHousing, dpId ); } void CHousingDBCtrl::InsertFurnitureList( DWORD dwPlayerId, DWORD dwItemId, DPID dpId ) { HOUSINGINFO housingInfo( dwItemId ); // 저장 정보를 만든다. // int n = sizeof(time_t); // time_t size가 4바이트로 나온다. // VS2003에서는 __int64라고 생각되는데..., 그래서 일단 __int64로 강제 casting if( GetQueryObject()->Execute( "usp_Housing_Insert '%02d', '%07d', %d, %I64d", g_appInfo.dwSys, dwPlayerId, housingInfo.dwItemId, static_cast<__int64>(housingInfo.tKeepTime) ) ) { CHousingMng::GetInstance()->SetFurnitureList( dwPlayerId, housingInfo, TRUE ); CDPTrans::GetInstance()->SendHousingFurnitureList( dwPlayerId, housingInfo, TRUE, dpId ); } else CDPTrans::GetInstance()->SendHousingDBFailed( dwPlayerId, housingInfo.dwItemId, dpId ); } void CHousingDBCtrl::SetupFurniture( DWORD dwPlayerId, HOUSINGINFO housingInfo, DPID dpId ) { if( GetQueryObject()->Execute( "usp_Housing_Update '%02d', '%07d', %d, %d, %f, %f, %f, %f", g_appInfo.dwSys, dwPlayerId, housingInfo.dwItemId, housingInfo.bSetup, housingInfo.vPos.x, housingInfo.vPos.y, housingInfo.vPos.z, housingInfo.fAngle ) ) { CHousingMng::GetInstance()->SetupFurniture( dwPlayerId, housingInfo ); CDPTrans::GetInstance()->SendHousingSetupFurniture( dwPlayerId, housingInfo, dpId ); } else CDPTrans::GetInstance()->SendHousingDBFailed( dwPlayerId, NULL_ID, dpId ); } void CHousingDBCtrl::DeleteFurnitureList( DWORD dwPlayerId, HOUSINGINFO housingInfo ) { if( GetQueryObject()->Execute( "usp_Housing_Del '%02d', '%07d', %d", g_appInfo.dwSys, dwPlayerId, housingInfo.dwItemId ) ) { CHousingMng::GetInstance()->SetFurnitureList( dwPlayerId, housingInfo, FALSE ); CDPTrans::GetInstance()->SendHousingFurnitureList( dwPlayerId, housingInfo, FALSE, DPID_ALLPLAYERS ); } } void CHousingDBCtrl::SetVisitAllow( DWORD dwPlayerId, DWORD dwTargetId, BOOL bAllow, DPID dpId ) { if( GetQueryObject()->Execute( "%s '%02d', '%07d', '%07d'", bAllow? "usp_Housing_Visit_Insert": "usp_Housing_Visit_Delete", g_appInfo.dwSys, dwPlayerId, dwTargetId ) ) { CHousingMng::GetInstance()->SetVisitAllow( dwPlayerId, dwTargetId, bAllow ); CDPTrans::GetInstance()->SendHousingSetVisitAllow( dwPlayerId, dwTargetId, bAllow, dpId ); } else CDPTrans::GetInstance()->SendHousingDBFailed( dwPlayerId, NULL_ID, dpId ); } void CHousingDBCtrl::OnTimer() { CHousingMng::GetInstance()->ProcessRemoveExpiredFurniture(); } //////////////////////////////////////////////////////////////////// /// CHousingDBMng ////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// CHousingDBMng::CHousingDBMng(void) { if( !m_HousingDBCtrl.CreateDbHandler( MIN(1) ) ) Error( "CHousingDBMng - m_HousingDBCtrl.CreateDbHandler()" ); } CHousingDBMng::~CHousingDBMng(void) { m_HousingDBCtrl.CloseDbHandler(); } CHousingDBMng* CHousingDBMng::GetInstance() { static CHousingDBMng sHousingDBMng; return & sHousingDBMng; } void CHousingDBMng::DeleteFurnitureList( DWORD dwPlayerId, HOUSINGINFO housingInfo ) { m_HousingDBCtrl.DeleteFurnitureList( dwPlayerId, housingInfo ); } #endif // __HOUSING
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 201 ] ] ]
3cff09a5e1a3a8ad7c1aa8ac1d0a0969da928bdf
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaInstructions/HasMorePropertiesRegisterInstruction.cpp
b196fdfabc279e0de47d494e5a96f47f008cd43c
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
#include "TessaInstructionHeader.h" namespace TessaInstructions { HasMorePropertiesRegisterInstruction::HasMorePropertiesRegisterInstruction(TessaInstruction* registerInstruction) { this->registerInstruction = registerInstruction; } void HasMorePropertiesRegisterInstruction::print() { printf("%s HasMorePropertiesIndex Register %s\n", this->getPrintPrefix().c_str(), registerInstruction->getOperandString().c_str() ); } void HasMorePropertiesRegisterInstruction::visit(TessaVisitorInterface* tessaVisitor) { tessaVisitor->visit(this); } TessaInstruction* HasMorePropertiesRegisterInstruction::getRegisterInstruction() { return this->registerInstruction; } bool HasMorePropertiesRegisterInstruction::producesValue() { return true; } }
[ [ [ 1, 26 ] ] ]
84b24e4c2af02333d45b25081b110f810288f14c
f95341dd85222aa39eaa225262234353f38f6f97
/ScreenSavers/Flurry/Sources/Flurry/AboutBox.h
2b4bd70525f953d95e7f6755fb1cc94a11d3fb81
[]
no_license
Templier/threeoaks
367b1a0a45596b8fe3607be747b0d0e475fa1df2
5091c0f54bd0a1b160ddca65a5e88286981c8794
refs/heads/master
2020-06-03T11:08:23.458450
2011-10-31T04:33:20
2011-10-31T04:33:20
32,111,618
0
0
null
null
null
null
UTF-8
C++
false
false
3,342
h
/////////////////////////////////////////////////////////////////////////////////////////////// // // Flurry : CAboutBox Class // // Declaration of CAboutBox // // Copyright (c) 2003, Matt Ginzton // Copyright (c) 2005-2008, Julien Templier // All rights reserved. // /////////////////////////////////////////////////////////////////////////////////////////////// // * $LastChangedRevision$ // * $LastChangedDate$ // * $LastChangedBy$ /////////////////////////////////////////////////////////////////////////////////////////////// // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // o Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // o Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // o Neither the name of the author nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "resource.h" // main symbols #include <atlhost.h> #include <vector> namespace Flurry { class CAboutBox : public CDialogImpl<CAboutBox> { public: // "factory" static void AutomaticDoModal (void) { CAboutBox* pAboutBox = new CAboutBox; pAboutBox->DoModal(); delete pAboutBox; } // constructors CAboutBox() {}; ~CAboutBox() {}; enum { IDD = IDD_ABOUTBOX }; protected: BEGIN_MSG_MAP(CAboutBox) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDCANCEL, OnDismiss) // bind both IDOK and IDCANCEL to the dismiss function, as well as WM_CLOSE COMMAND_ID_HANDLER(IDOK, OnDismiss) // of OK and CANCEL, CANCEL is preferred because then Esc works as well as Enter COMMAND_ID_HANDLER(IDC_CREDITS, OnCredits) // Show Credits dialog END_MSG_MAP() // Handler prototypes: LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnDismiss(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnCredits(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); }; }
[ "julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d" ]
[ [ [ 1, 84 ] ] ]
f17e331bc7ccc11d2ec7930cd5c1fdf5470ef98b
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/Font.cpp
9753d5332708280f7e823bf879060f6360e9f4a7
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
9,752
cpp
#include <Halak/PCH.h> #include <Halak/Font.h> #include <Halak/Assert.h> #include <Halak/FontLibrary.h> #include <Halak/FontString.h> #include <Halak/Math.h> #include <Halak/NumericLimits.h> #include <Halak/String.h> #include <Halak/Internal/FontCache.h> #include <Halak/Internal/GlyphTable.h> #include <Halak/Glyph.h> #include <Halak/TypingContext.h> namespace Halak { const Font::GlyphDictionary Font::EmptyGlyphs; Font::Font() : library(nullptr), revision(0), color(Color(0, 0, 0, 255)), strokeColor(Color(0, 0, 0, 255)), glowColor(Color(0, 0, 255)), spacing(1.0f), parametersPointer(new FontCacheParameters()), parameters(*parametersPointer), cache(nullptr) { } Font::Font(FontLibrary* library) : library(library), revision(0), color(Color(0, 0, 0, 255)), strokeColor(Color(0, 0, 0, 255)), glowColor(Color(0, 0, 255)), spacing(1.0f), parametersPointer(new FontCacheParameters()), parameters(*parametersPointer), cache(nullptr) { } Font::Font(const Font& original) : library(original.library), revision(original.revision), color(original.color), strokeColor(original.strokeColor), glowColor(original.glowColor), spacing(original.spacing), parametersPointer(new FontCacheParameters(original.parameters)), parameters(*parametersPointer), cache(original.cache) { } Font::~Font() { delete parametersPointer; } Vector2 Font::Measure(const String& text) { return Measure(text, NumericLimits::MaxFloat); } Vector2 Font::Measure(const String& text, float boundary) { return Measure(FontString(This<Font>(), text), boundary); } Vector2 Font::Measure(const FontString& fontString) { return Measure(fontString, NumericLimits::MaxFloat); } Vector2 Font::Measure(const FontString& fontString, float boundary) { HKAssert(fontString.GetFont() == this); TypingContext context(fontString, boundary); Vector2 result = Vector2::Zero; while (context.MoveNext()) { const Vector2 current = context.GetPosition(); result.X = Math::Max(result.X, current.X + context.GetRegularGlyph()->GetAdvance().X); result.Y = Math::Max(result.Y, current.Y + GetLineHeight()); } return result; } void Font::SetLibrary(FontLibrary* value) { if (library != value) { library = value; cache.Reset(); revision++; } } const String& Font::GetFace() const { return parameters.Face; } void Font::SetFace(const String& value) { if (parameters.Face != value) { parameters.Face = value; cache.Reset(); revision++; } } float Font::GetSize() const { return parameters.FontSize; } void Font::SetSize(float value) { value = Math::Max(value, 0.0f); if (parameters.FontSize != value) { parameters.FontSize = value; cache.Reset(); revision++; } } float Font::GetStrokeSize() const { return parameters.StrokeSize; } void Font::SetStrokeSize(float value) { value = Math::Max(value, 0.0f); if (parameters.StrokeSize != value) { parameters.StrokeSize = value; cache.Reset(); revision++; } } float Font::GetWeights() const { return parameters.Weights; } void Font::SetWeights(float value) { value = Math::Max(value, 0.0f); if (parameters.Weights != value) { parameters.Weights = value; cache.Reset(); revision++; } } bool Font::GetBold() const { return parameters.Weights > 0.0f; } void Font::SetBold(bool value) { if (GetBold() != value) { parameters.Weights = value ? 1.0f : 0.0f; cache.Reset(); revision++; } } float Font::GetShear() const { return parameters.Shear; } void Font::SetShear(float value) { value = Math::Max(value, 0.0f); if (parameters.Shear != value) { parameters.Shear = value; cache.Reset(); revision++; } } bool Font::GetItalic() const { return parameters.Shear > 0.0f; } void Font::SetItalic(bool value) { if (GetItalic() != value) { parameters.Shear = value ? 0.2f : 0.0f; cache.Reset(); revision++; } } int Font::GetGlowSize() const { return parameters.GlowSize; } void Font::SetGlowSize(int value) { value = Math::Max(value, 0); if (parameters.GlowSize != value) { parameters.GlowSize = value; cache.Reset(); revision++; } } float Font::GetGlowSpread() const { return parameters.GlowSpread; } void Font::SetGlowSpread(float value) { value = Math::Max(value, 0.0001f); if (parameters.GlowSpread != value) { parameters.GlowSpread = value; cache.Reset(); revision++; } } float Font::GetGlowThickness() const { return parameters.GlowThickness; } void Font::SetGlowThickness(float value) { value = Math::Clamp(value, 0.0001f, 0.9999f); if (parameters.GlowThickness != value) { parameters.GlowThickness = value; cache.Reset(); revision++; } } float Font::GetScale() const { return parameters.Scale; } void Font::SetScale(float value) { value = Math::Max(value, 0.0f); if (parameters.Scale != value) { parameters.Scale = value; cache.Reset(); revision++; } } bool Font::GetHinting() const { return parameters.Hinting; } void Font::SetHinting(bool value) { if (parameters.Hinting != value) { parameters.Hinting = value; cache.Reset(); revision++; } } bool Font::GetIgnoreBitmap() const { return parameters.IgnoreBitmap; } void Font::SetIgnoreBitmap(bool value) { if (parameters.IgnoreBitmap != value) { parameters.IgnoreBitmap = value; cache.Reset(); revision++; } } void Font::SetColor(Color value) { if (color != value) { color = value; revision++; } } void Font::SetStrokeColor(Color value) { if (strokeColor != value) { strokeColor = value; revision++; } } void Font::SetGlowColor(Color value) { if (glowColor != value) { glowColor = value; revision++; } } void Font::SetSpacing(float value) { value = Math::Max(value, 0.0f); if (spacing != value) { spacing = value; revision++; } } const Glyph* Font::GetRegularGlyph(uint32 code) const { return GetCache()->GetGlyph(code); } const Glyph* Font::GetStrokedGlyph(uint32 code) const { if (const GlyphTable* t = GetCache()->GetStrokedGlyphTable()) return t->Find(code); else return nullptr; } const Glyph* Font::GetGlowGlyph(uint32 code) const { if (const GlyphTable* t = GetCache()->GetGlowGlyphTable()) return t->Find(code); else return nullptr; } float Font::GetAscender() const { return GetCache()->GetAscender(); } float Font::GetDescender() const { return GetCache()->GetDescender(); } float Font::GetLineHeight() const { return GetCache()->GetLineHeight(); } const Font::GlyphDictionary& Font::GetCachedRegularGlyphs() const { FontCache* c = GetCache(); if (c && c->GetRegularGlyphTable()) return c->GetRegularGlyphTable()->GetGlyphs(); else return EmptyGlyphs; } const Font::GlyphDictionary& Font::GetCachedStrokedGlyphs() const { FontCache* c = GetCache(); if (c && c->GetStrokedGlyphTable()) return c->GetStrokedGlyphTable()->GetGlyphs(); else return EmptyGlyphs; } const Font::GlyphDictionary& Font::GetCachedGlowGlyphs() const { FontCache* c = GetCache(); if (c && c->GetGlowGlyphTable()) return c->GetGlowGlyphTable()->GetGlyphs(); else return EmptyGlyphs; } FontCache* Font::GetCache() const { if (cache == nullptr && library) cache = library->GetCache(parameters); return cache; } }
[ [ [ 1, 414 ] ] ]
6efa6ef1f176b5265814a7bd580f90880cf8250b
f7be460272b02f7b582430396ede89dc14b50b88
/meshinformationgroupbox.h
bad94c76c22938a4db0d42a7d59840364906d318
[ "MIT" ]
permissive
ShenRen/stlviewer
400934c125e557342bd3d8e81c1974e0a51082a9
3ed2415af299ace5564f6486344c04a680d625ea
refs/heads/master
2021-01-15T22:14:20.658542
2011-01-18T20:54:29
2011-01-18T20:54:29
99,892,752
1
0
null
null
null
null
UTF-8
C++
false
false
1,588
h
// Copyright (c) 2009 Olivier Crave // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef MESHINFORMATIONGROUPBOX_H #define MESHINFORMATIONGROUPBOX_H #include <QtGui/QGroupBox> #include "stlfile.h" class QLabel; class MeshInformationGroupBox : public QGroupBox { Q_OBJECT public: MeshInformationGroupBox(QWidget *parent = 0); ~MeshInformationGroupBox(); void reset(); void setValues(const StlFile::Stats stats); private: QLabel *numFacets, *numPoints; }; #endif // MESHINFORMATIONGROUPBOX_H
[ "cravesoft@939d4a90-b6fe-4fe1-83ef-7ae222a9c67a" ]
[ [ [ 1, 44 ] ] ]
3d65922b42ce9112923163520954df12feee099f
fef287a56e4b1b403e7c0df80e0385a35f428df9
/CSCI3081/Simulator/trunk/src/simulator.cpp
0c7d9e6af3c2bd32924a6603d7ed12223c140728
[]
no_license
Magneticmagnum/link2432-school
1fbb36b4eec105cc3c9454269175be6b533ea87f
2a89b4a1f5ce0c40c7de0f86dc513be5eea19d26
refs/heads/master
2020-05-17T09:54:17.062501
2011-02-11T20:56:39
2011-02-11T20:56:39
35,382,569
0
0
null
null
null
null
UTF-8
C++
false
false
2,738
cpp
/* * simulator.cpp * * Created on: Oct 8, 2010 * Author: Joe Houlton, Maya Pevzner */ #include <iostream> #include <stdio.h> #include "Scheduler.h" #include "Refrigerator.h" #include "WaterHeater.h" #include "Dishwasher.h" #include "Toaster.h" #include "Microwave.h" #include "Oven.h" #include "Stove.h" #include "Television.h" #include "HairDryer.h" #include "Xbox.h" #include "House.h" #include "PersonSM.h" #include "Clock.h" #include "ConfigFile.h" #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> using log4cxx::Logger; using log4cxx::LoggerPtr; using log4cxx::PropertyConfigurator; using log4cxx::File; int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s <model-spec-file.txt> <person-spec-file.txt>", argv[0]); return 0; } // Set up the logger. LoggerPtr log(Logger::getLogger("Main")); PropertyConfigurator::configure(File("log.config")); // Run the simulator. LOG4CXX_INFO(log, "Simulator started. Log file opened."); // Create Models & register Models with House. House *house = House::getInstance(); house->registerModelFactory("Dishwasher", &construct<Dishwasher> ); house->registerModelFactory("HairDryer", &construct<HairDryer> ); house->registerModelFactory("Microwave", &construct<Microwave> ); house->registerModelFactory("Oven", &construct<Oven> ); house->registerModelFactory("Refrigerator", &construct<Refrigerator> ); house->registerModelFactory("Stove", &construct<Stove> ); house->registerModelFactory("Television", &construct<Television> ); house->registerModelFactory("Toaster", &construct<Toaster> ); house->registerModelFactory("WaterHeater", &construct<WaterHeater> ); house->registerModelFactory("Xbox", &construct<Xbox> ); house->registerModelFactory("PersonSM", &construct<PersonSM> ); house->registerModelFactory("Clock", &construct<Clock> ); // Load config file, configure Models, and register Models with Scheduler. Scheduler sched; std::cout << "Scheduler created" << std::endl; house->loadConfig(argv[1], sched); std::cout << "Loaded house config file" << std::endl; PersonSM* johndoe = (PersonSM*) (house->getModel("JohnDoe")); johndoe->loadStateFile(argv[2]); Clock* clock = (Clock*) (house->getModel("Clock")); clock->registerScheduler(&sched); std::cout << "Loaded state file" << std::endl; // Call the Scheduler's run() method, wait for it to complete. std::cout << "Running scheduler ticks" << std::endl; int simTime = 3 * 1440; // run for 3 days sched.run(simTime); // Exit simulator. LOG4CXX_INFO(log, "Simulator exited. Log file closed."); std::cout << "Simulation completed." << std::endl; return 0; }
[ "link2432@d57f46eb-fc38-1307-7c4f-d472210b1a9e" ]
[ [ [ 1, 83 ] ] ]
35c5998d75b3a3250be9d291c1feb9320bc3697a
ffa46b6c97ef6e0c03e034d542fa94ba02d519e5
/qfinddialog.h
70241f3a9ef413b9525426606d782c46fc34089b
[]
no_license
jason-cpc/chmcreator
50467a2bc31833aef931e24be1ac68f5c06efd97
5da66666a9df47c5cf67b71bfb115b403f41b72b
refs/heads/master
2021-12-04T11:22:23.616758
2010-07-20T23:50:15
2010-07-20T23:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
708
h
#ifndef FINDDIALOG_H #define FINDDIALOG_H #include <QDialog> QT_BEGIN_NAMESPACE class QCheckBox; class QDialogButtonBox; class QGroupBox; class QLabel; class QLineEdit; class QPushButton; QT_END_NAMESPACE //! [0] class FindDialog : public QDialog { Q_OBJECT public: FindDialog(QWidget *parent = 0); private: QLabel *label; QLineEdit *lineEdit; QCheckBox *caseCheckBox; QCheckBox *fromStartCheckBox; QCheckBox *wholeWordsCheckBox; QCheckBox *searchSelectionCheckBox; QCheckBox *backwardCheckBox; QDialogButtonBox *buttonBox; QPushButton *findButton; QPushButton *moreButton; QWidget *extension; }; //! [0] #endif
[ "zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb" ]
[ [ [ 1, 38 ] ] ]
b4abe2d230c13299b259b51ca181237b72f4a80c
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/dependencies/OgreNewt_153/src/OgreNewt_Body.cpp
fce9ff57004974092386cc434ea86927abefdac8
[]
no_license
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,441
cpp
#include "OgreNewt_Body.h" #include "OgreNewt_Tools.h" namespace OgreNewt { Body::Body( const World* W, CollisionPtr col, int bodytype ) { m_world = W; m_collision = col; m_type = bodytype; m_node = NULL; m_matid = NULL; m_userdata = NULL; m_forcecallback = NULL; m_transformcallback = NULL; m_buoyancycallback = NULL; m_body = NewtonCreateBody( m_world->getNewtonWorld(), col->getNewtonCollision() ); NewtonBodySetUserData( m_body, this ); NewtonBodySetDestructorCallback( m_body, newtonDestructor ); } Body::~Body() { if (m_body) { if (NewtonBodyGetUserData(m_body)) { NewtonBodySetDestructorCallback( m_body, NULL ); NewtonDestroyBody( m_world->getNewtonWorld(), m_body ); } } } // destructor callback void _CDECL Body::newtonDestructor( const NewtonBody* body ) { //newton wants to destroy the body.. so first find it. OgreNewt::Body* me; me = (OgreNewt::Body*)NewtonBodyGetUserData( body ); // remove destructor callback NewtonBodySetDestructorCallback( body, NULL ); // remove the user data NewtonBodySetUserData( body, NULL ); //now delete the object. delete me; } // transform callback void _CDECL Body::newtonTransformCallback( const NewtonBody* body, const float* matrix ) { Ogre::Quaternion orient; Ogre::Vector3 pos; OgreNewt::Body* me; me = (OgreNewt::Body*) NewtonBodyGetUserData( body ); OgreNewt::Converters::MatrixToQuatPos( matrix, orient, pos ); if (me->m_transformcallback) me->m_transformcallback( me, orient, pos ); } void _CDECL Body::newtonForceTorqueCallback( const NewtonBody* body ) { OgreNewt::Body* me = (OgreNewt::Body*)NewtonBodyGetUserData( body ); if (me->m_forcecallback) me->m_forcecallback( me ); } void _CDECL Body::newtonAutoactiveCallback(const NewtonBody* body, unsigned state) { OgreNewt::Body* me = (OgreNewt::Body*)NewtonBodyGetUserData( body ); if (me->m_autoactivecallback) me->m_autoactivecallback( me, state ); } void Body::standardForceCallback( OgreNewt::Body* me ) { //apply a simple gravity force. Ogre::Real mass; Ogre::Vector3 inertia; me->getMassMatrix(mass, inertia); Ogre::Vector3 force(0,-9.8,0); force *= mass; me->addForce( force ); } void Body::standardTransformCallback( OgreNewt::Body* me, const Ogre::Quaternion& orient, const Ogre::Vector3& pos ) { me->m_node->setOrientation( orient ); me->m_node->setPosition( pos ); } int _CDECL Body::newtonBuoyancyCallback(const int collisionID, void *context, const float* globalSpaceMatrix, float* globalSpacePlane) { OgreNewt::Body* me = (OgreNewt::Body*)context; Ogre::Quaternion orient; Ogre::Vector3 pos; OgreNewt::Converters::MatrixToQuatPos( globalSpaceMatrix, orient, pos ); // call our user' function to get the plane. Ogre::Plane theplane; if (me->m_buoyancycallback(collisionID, me, orient, pos, theplane)) { globalSpacePlane[0] = theplane.normal.x; globalSpacePlane[1] = theplane.normal.y; globalSpacePlane[2] = theplane.normal.z; globalSpacePlane[3] = theplane.d; return 1; } return 0; } // attachToNode void Body::attachToNode( Ogre::Node* node ) { m_node = node; if (m_body) { setCustomTransformCallback( &Body::standardTransformCallback ); } } void Body::setPositionOrientation( const Ogre::Vector3& pos, const Ogre::Quaternion& orient ) { if (m_body) { float matrix[16]; OgreNewt::Converters::QuatPosToMatrix( orient, pos, &matrix[0] ); NewtonBodySetMatrix( m_body, &matrix[0] ); if (m_node) { m_node->setOrientation( orient ); m_node->setPosition( pos ); } } } // set mass matrix void Body::setMassMatrix( Ogre::Real mass, const Ogre::Vector3& inertia ) { if (m_body) NewtonBodySetMassMatrix( m_body, (float)mass, (float)inertia.x, (float)inertia.y, (float)inertia.z ); } void Body::setMass(Ogre::Real mass) { if (m_body) { Ogre::Vector3 center = Ogre::Vector3::ZERO; Ogre::Vector3 inertia = Ogre::Vector3::ZERO; NewtonConvexCollisionCalculateInertialMatrix(m_collision->getNewtonCollision(), &inertia.x, &center.x); NewtonBodySetMassMatrix(m_body, (float)mass, (float)inertia.x, (float)inertia.y, (float)inertia.z); } } // basic gravity callback void Body::setStandardForceCallback() { setCustomForceAndTorqueCallback( standardForceCallback ); } // custom user force callback void Body::setCustomForceAndTorqueCallback( ForceCallback callback ) { if (!m_forcecallback) { m_forcecallback = callback; NewtonBodySetForceAndTorqueCallback( m_body, newtonForceTorqueCallback ); } else { if (m_forcecallback != callback) m_forcecallback = callback; } } // custom user force callback void Body::setCustomTransformCallback( TransformCallback callback ) { if (!m_transformcallback) { m_transformcallback = callback; NewtonBodySetTransformCallback( m_body, newtonTransformCallback ); } else { if (m_transformcallback != callback) m_transformcallback = callback; } } // set callback for auto activate / deactivate void Body::setAutoactiveCallback ( autoactiveCallback callback ) { if (!m_autoactivecallback) { m_autoactivecallback = callback; NewtonBodySetAutoactiveCallback( m_body, newtonAutoactiveCallback ); } else { // if (m_autoactivecallback != callback) // no need for this, setting it is quick and will not be called often, plus it keeps me from needing to include another file. :) m_autoactivecallback = callback; } } //set collision void Body::setCollision(CollisionPtr col) { NewtonBodySetCollision( m_body, col->getNewtonCollision() ); m_collision = col; } //get collision CollisionPtr Body::getCollision() const { return m_collision; } //get material group ID const OgreNewt::MaterialID* Body::getMaterialGroupID() const { if (m_matid) return m_matid; else return NULL; } // get position and orientation void Body::getPositionOrientation( Ogre::Vector3& pos, Ogre::Quaternion& orient ) const { float matrix[16]; NewtonBodyGetMatrix( m_body, matrix ); OgreNewt::Converters::MatrixToQuatPos( matrix, orient, pos ); } void Body::getMassMatrix( Ogre::Real& mass, Ogre::Vector3& inertia ) const { NewtonBodyGetMassMatrix( m_body, &mass, &inertia.x, &inertia.y, &inertia.z ); } void Body::getInvMass( Ogre::Real& mass, Ogre::Vector3& inertia ) const { NewtonBodyGetInvMass( m_body, &mass, &inertia.x, &inertia.y, &inertia.z ); } Ogre::Vector3 Body::getOmega() const { Ogre::Vector3 ret; NewtonBodyGetOmega( m_body, &ret.x ); return ret; } Ogre::Vector3 Body::getVelocity() const { Ogre::Vector3 ret; NewtonBodyGetVelocity( m_body, &ret.x ); return ret; } Ogre::Vector3 Body::getAngularDamping() const { Ogre::Vector3 ret; NewtonBodyGetAngularDamping( m_body, &ret.x ); return ret; } Ogre::Vector3 Body::getCenterOfMass() const { Ogre::Vector3 ret; NewtonBodyGetCentreOfMass( m_body, &ret.x ); return ret; } void Body::addBouyancyForce( Ogre::Real fluidDensity, Ogre::Real fluidLinearViscosity, Ogre::Real fluisAngularViscosity, const Ogre::Vector3& gravity, buoyancyPlaneCallback callback ) { // call the newton function. if (callback) m_buoyancycallback = callback; else m_buoyancycallback = NULL; NewtonBodyAddBuoyancyForce( m_body, fluidDensity, fluidLinearViscosity, fluisAngularViscosity, &gravity.x, newtonBuoyancyCallback, this ); m_buoyancycallback = NULL; } void Body::addGlobalForce( const Ogre::Vector3& force, const Ogre::Vector3& pos ) { Ogre::Vector3 bodypos; Ogre::Quaternion bodyorient; getPositionOrientation( bodypos, bodyorient ); Ogre::Vector3 topoint = pos - bodypos; Ogre::Vector3 torque = topoint.crossProduct( force ); addForce( force ); addTorque( torque ); } void Body::addLocalForce( const Ogre::Vector3& force, const Ogre::Vector3& pos ) { Ogre::Vector3 bodypos; Ogre::Quaternion bodyorient; getPositionOrientation( bodypos, bodyorient ); Ogre::Vector3 globalforce = bodyorient * force; Ogre::Vector3 globalpoint = (bodyorient * pos) + bodypos; addGlobalForce( globalforce, globalpoint ); } // -------------------------------------------------------------------------------------- }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013", "natoka@4c79e8ff-cfd4-0310-af45-a38c79f83013", "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 82 ], [ 91, 107 ], [ 110, 142 ], [ 144, 162 ], [ 165, 175 ], [ 189, 226 ], [ 242, 245 ], [ 247, 357 ] ], [ [ 83, 90 ], [ 108, 109 ], [ 143, 143 ], [ 163, 164 ], [ 180, 181 ], [ 227, 241 ], [ 246, 246 ] ], [ [ 176, 179 ], [ 182, 188 ] ] ]
12fb536785736376d725f3e993411273463960fa
9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e
/src/function.cpp
bcc484a646e5273556b46e4178e985c751db9bf8
[]
no_license
correosdelbosque/veryie
e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff
6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1
refs/heads/master
2021-01-10T13:17:59.755108
2010-06-16T04:23:26
2010-06-16T04:23:26
53,365,953
1
1
null
null
null
null
GB18030
C++
false
false
38,536
cpp
#include "stdafx.h" #include "VeryIE.h" #include "resource.h" // main symbols #include "wininet.h" //for INTERNET_MAX_PATH_LENGTH #include "mainfrm.h" #include "MenuData.h" // #include <sys\stat.h> //for struct stat #include <direct.h> //for mkdir //############################################################## #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif //############################################################## #define MAX_INI 512 #define _NULL -1 //############################################################## //for plugin CString _GetPlugInSection(CString strFileName, CString strSection) { CString strOut; strOut.Empty(); char tmp[INTERNET_MAX_PATH_LENGTH]; if (::GetPrivateProfileString("General", strSection, NULL, tmp, INTERNET_MAX_PATH_LENGTH, strFileName)) strOut = tmp; return strOut; } //0:not 1:script 2:exe int _GetPlugInType(CString strFileName) { CString strTemp2 = GET_FILE(strFileName); strTemp2.MakeLower(); if (strTemp2.Left(10)=="plugin.ini") { CString strType = _GetPlugInSection(strFileName,"Type"); strType.MakeUpper(); if (strType=="BUTTON" || strType=="M2PLUGIN_BUTTON") { CString strSection = _GetPlugInSection(strFileName,"ModuleType"); strSection.MakeUpper(); if (strSection=="SCRIPT") return 1; else if (strSection=="EXE") return 2; } } return 0; } CString _GetPlugInIconPath(CString strFileName) { CString strOut; strOut.Empty(); char tmp[INTERNET_MAX_PATH_LENGTH]; if (::GetPrivateProfileString("General", "HotIcon", NULL, tmp, INTERNET_MAX_PATH_LENGTH, strFileName)==FALSE) { if (::GetPrivateProfileString("General", "Icon", NULL, tmp, INTERNET_MAX_PATH_LENGTH, strFileName)==FALSE) return strOut; } strOut = strFileName.Left(strFileName.ReverseFind('\\')+1) + tmp; return strOut; } CString _GetPlugInName(CString strFileName) { return _GetPlugInSection(strFileName, "Name" ); } CString _GetPlugInComments(CString strFileName) { return _GetPlugInSection(strFileName, "Comments" ); } CString _GetPlugInFileName(CString strFileName) { return _GetPlugInSection(strFileName, "FileName" ); } //############################################################## //file common function char* _FileGetBuffer(CString filename) { CFile f; if( f.Open(filename, CFile::modeRead|CFile::shareDenyNone) == FALSE) return NULL; DWORD len = f.GetLength(); if (len<=0) return NULL; char* tmp = (char*)malloc(len+1); f.Read(tmp, len); tmp[len]=0; f.Close(); return tmp; } BOOL _BrowserPath(CWnd* pParentWnd, CString& m_strPath) { LPMALLOC pMalloc; if (::SHGetMalloc(&pMalloc)!= NOERROR) return FALSE; CString str; LOADSTR(str ,IDS_SELECT_PATH); BROWSEINFO bInfo; LPITEMIDLIST pidl; ZeroMemory ( (PVOID) &bInfo,sizeof (BROWSEINFO)); bInfo.hwndOwner = pParentWnd->GetSafeHwnd(); bInfo.pszDisplayName = m_strPath.GetBuffer (MAX_PATH); bInfo.lpszTitle = str;//_T("Select Path:"); bInfo.ulFlags = BIF_RETURNFSANCESTORS|BIF_RETURNONLYFSDIRS; bInfo.lpfn = NULL;//!BrowseCtrlCallback; // address of callback function bInfo.lParam = NULL;//!(LPARAM)this; // pass address of object to callback function if ((pidl = ::SHBrowseForFolder(&bInfo)) == NULL) return FALSE; m_strPath.ReleaseBuffer(); //!m_iImageIndex = bInfo.iImage; if (::SHGetPathFromIDList(pidl,m_strPath.GetBuffer(MAX_PATH)) == FALSE) { pMalloc ->Free(pidl); pMalloc ->Release(); return FALSE; } m_strPath.ReleaseBuffer(); pMalloc ->Free(pidl); pMalloc ->Release(); return TRUE; } //############################################################## BOOL _FileIsExist(CString strPath) { //必须这样做,因为 末尾带 \ 的 FindFirstFile stat 中不能用 int nSlash = strPath.ReverseFind('\\'); if( nSlash == strPath.GetLength()-1) strPath = strPath.Left(nSlash); /* WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile( strPath, &fd ); if ( hFind != INVALID_HANDLE_VALUE ) FindClose( hFind ); return hFind != INVALID_HANDLE_VALUE; */ struct stat stat_buf; if (stat(strPath, &stat_buf) >= 0) return TRUE; else return FALSE; } void _CreateFullDir(const char *dir) { struct stat stat_buf; char *p; char parent[MAX_PATH]; int length; if (_FileIsExist(dir)) return; if ( strlen(dir) == 0) return; p = strchr(dir,'\\'); while(p) { length = p-dir; STRNCPY(parent,dir,length); //make dir if (stat(parent, &stat_buf) < 0 && strlen(parent) > 2)//can not mkdir("c:") { if ( mkdir(parent)!=0 ) return; } //move to next if (*(p+1)==0) return; p = strchr(p+1,'\\'); } //for c:\\aa\bb\cc\\dd,mow create dd if (stat(dir, &stat_buf) < 0 && strlen(dir) > 2)//can not mkdir("c:") { if ( mkdir(dir)!=0 ) return; } } //####################################################################### //国际 URL #define IS_1URL(strUrl) ( strUrl.Right(5)==".com/" || \ strUrl.Right(5)==".net/" || \ strUrl.Right(5)==".org/" || \ strUrl.Right(5)==".edu/" || \ strUrl.Right(4)==".com" || \ strUrl.Right(4)==".net" || \ strUrl.Right(4)==".org" || \ strUrl.Right(4)==".edu" ) //2级 URL #define IS_2URL(nDot,strUrl) ( (nDot=strUrl.Find(".com."))>0 || \ (nDot=strUrl.Find(".net."))>0 || \ (nDot=strUrl.Find(".org."))>0 || \ (nDot=strUrl.Find(".edu."))>0 ) //############################################################## CString _StringGetUpUrl(CString strUrl) { if (!strUrl || strUrl.GetLength()<=0) return strUrl; if (strUrl=="about:blank") return strUrl; //if (strUrl.Left(6)=="res://") // return strUrl; // must have / and \\ int c,b; c = strUrl.Find('/'); if (c==5 || c==6 || c==4) // file:/// http:// https:// ftp:// { c = '/'; b = 8; // https:// } else if (strUrl.Find('\\')>=0) { c = '\\'; if (strUrl.GetAt(1)==':') b = 3; // c:\a\b else b = 2; // \\server1 } else return strUrl; // int len = strUrl.GetLength(); int pos1 = strUrl.Find(c,b); //get first c int pos2 = strUrl.ReverseFind(c); if ( (pos1<0) || (pos1+1==len && b!=3) )// \\server1 \\server1\ ,must except c:\temp\ { if (c=='/') { // http://mail.qwe.com/ , http://ror.cn/, http://mail.qwe.com.cn/ if( (strUrl.Left(7)=="http://" && strUrl.Left(11)!="http://www.") || (strUrl.Left(8)=="https://" && strUrl.Left(12)!="https://www.") ) { int nDot=0; CString strTemp; if ( IS_1URL(strUrl) ) { // http://login.bj.yahoo.com/ nDot = strUrl.ReverseFind('.'); strTemp = strUrl.Left(nDot); nDot = strTemp.ReverseFind('.'); } else if ( IS_2URL(nDot, strUrl) ) { strTemp = strUrl.Left(nDot); nDot = strTemp.ReverseFind('.'); } else if ( strUrl.Find('.') < strUrl.ReverseFind('.')) // http://news.sh.cn/ { int pos1 = strUrl.Find("://"); pos1 += 3; strTemp = strUrl.Mid(pos1); if (strTemp.FindOneOf("abcdefghijklmnopqrstuvwxyz")>=0) //http://127.0.0.1/ nDot = strUrl.Find('.',pos1); } //replace str as www if (nDot>0) { // http://news.newscn.com/ => http://www.newscn.com/ int pos1 = strUrl.Find("://"); pos1 += 3; strTemp = strUrl.Left(pos1); strTemp += "www"; strTemp += strUrl.Mid(nDot); strUrl = strTemp; } } } return strUrl; } else if (pos2+1==len)// \\server1\mail\xxx\ { strUrl = strUrl.Left(pos2); pos2 = strUrl.ReverseFind(c); } strUrl = strUrl.Left(pos2+1); // \\server1\mail\xxx return strUrl; } CString _StringGetRootUrl(CString strUrl) { if (!strUrl || strUrl.GetLength()<1) return strUrl; if (!IS_URL(strUrl)) return strUrl; int nIndex = 0; CString strUrlUp; while(nIndex < 100) { strUrlUp = _StringGetUpUrl(strUrl); if (strUrlUp == strUrl) break; strUrl = strUrlUp; // nIndex++; } return strUrl; } //only for http:// and https:// CString _StringGetTopUrl(CString strUrl) { CString strTop; strTop.Empty(); if (!IS_HTTP(strUrl)) return strTop; int p1 = strUrl.Find("://"); p1+=3; int p2 = strUrl.Find("/",p1); if (p2<0) { strTop = strUrl + "/"; return strTop; } strTop = strUrl.Left(p2+1); return strTop; } //############################################################## //return add ok or not BOOL _GroupAddItem(CString strName, CString strUrl, BOOL bState, DWORD dwProperty, CString filename) { char state[10]="state",name[9]="name",url[8]="url",download[13]="download"; // x+5 char num[15]; int i=0; char tmp[INTERNET_MAX_PATH_LENGTH]; BOOL r = TRUE, bNeedAdd=TRUE; DWORD dwPropertyTemp; CString strNameTemp,strUrlTemp; //get if exist the url while(r) { itoa(i, name+4, 10); itoa(i, url+3, 10); r = ::GetPrivateProfileString("Group", name, NULL, tmp, INTERNET_MAX_PATH_LENGTH, filename); if (r) { strNameTemp = tmp; r = ::GetPrivateProfileString("Group", url, NULL, tmp, INTERNET_MAX_PATH_LENGTH, filename); if (r) { strUrlTemp = tmp; itoa(i, download+8, 10); dwPropertyTemp = ::GetPrivateProfileInt("Group", download, DEFAULT_PROPERTY, filename); if (strName==strNameTemp && strUrl==strUrlTemp && dwProperty==dwPropertyTemp) { r = FALSE;//no use add the item bNeedAdd = FALSE; } } } i++; } if (bNeedAdd) { if (i>0) i--; itoa(i, state+5, 10); itoa(i, name+4, 10); itoa(i, url+3, 10); itoa(i, download+8, 10); // ::WritePrivateProfileString("Group", name, strName, filename); ::WritePrivateProfileString("Group", url, strUrl, filename); if (bState==0) { itoa( 0, num, 10); ::WritePrivateProfileString("Group", state, num, filename); } if (dwProperty != DEFAULT_PROPERTY) { ultoa( dwProperty, num, 10); ::WritePrivateProfileString("Group", download, num, filename); } } return bNeedAdd; } //############################################################## DWORD _RegGetDword(HKEY hKeyRoot, LPCSTR lpSubKey, LPCSTR lpValueName) { DWORD sz; HKEY hKey; DWORD dwSize = sizeof(sz); if(RegOpenKey(hKeyRoot, _T(lpSubKey), &hKey) != ERROR_SUCCESS) return NULL; if (RegQueryValueEx(hKey, _T(lpValueName), NULL, NULL, (LPBYTE)&sz, &dwSize) != ERROR_SUCCESS) sz = NULL; RegCloseKey(hKey); return sz; } BOOL _RegSetDword(HKEY hKeyRoot, LPCSTR lpSubKey, LPCSTR lpValueName, DWORD dwValue) { BOOL bRet=FALSE; HKEY hKey; DWORD dwSize = sizeof(dwValue); if(RegOpenKey(hKeyRoot, _T(lpSubKey), &hKey) != ERROR_SUCCESS) { if(RegCreateKey(hKeyRoot, _T(lpSubKey), &hKey) != ERROR_SUCCESS) return bRet; } if (RegSetValueEx(hKey, _T(lpValueName), NULL, REG_DWORD, (LPBYTE)(&dwValue), dwSize) == ERROR_SUCCESS) bRet = TRUE; RegCloseKey(hKey); return bRet; } CString _RegGetString(HKEY hKeyRoot, LPCSTR lpSubKey, LPCSTR lpValueName) { CString strRet; HKEY hKey; TCHAR sz[MAX_PATH]; DWORD dwSize = sizeof(sz); strRet.Empty(); memset(sz,0,MAX_PATH); if(RegOpenKey(hKeyRoot, _T(lpSubKey), &hKey) != ERROR_SUCCESS) return strRet; if (RegQueryValueEx(hKey, _T(lpValueName), NULL, NULL, (LPBYTE)sz, &dwSize) == ERROR_SUCCESS) strRet = sz; RegCloseKey(hKey); return strRet; } BOOL _RegSetString(HKEY hKeyRoot, LPCSTR lpSubKey, LPCSTR lpValueName, LPCSTR lpValue) { HKEY hKey; if(RegOpenKey(hKeyRoot, _T(lpSubKey), &hKey) != ERROR_SUCCESS) { if(RegCreateKey(hKeyRoot, _T(lpSubKey), &hKey) != ERROR_SUCCESS) return FALSE; } RegSetValueEx(hKey, _T(lpValueName), 0, REG_SZ, (LPBYTE)lpValue, strlen(lpValue)); RegCloseKey(hKey); return TRUE; } void _RegDeletePath(HKEY hKey, CString strPath) { TCHAR sz[MAX_PATH]; HKEY hKeySub; DWORD dwSize = MAX_PATH; LONG lRet; if (RegOpenKey(hKey, strPath, &hKeySub) != ERROR_SUCCESS) return ; //not i++, for that have delete one while(RegEnumKey(hKeySub, 0, sz, dwSize) == ERROR_SUCCESS) { lRet = RegDeleteKey(hKeySub,sz); if (lRet != ERROR_SUCCESS) _RegDeletePath(hKeySub, sz); } RegCloseKey(hKeySub); //delete the path RegDeleteKey(hKey,strPath); } //############################################################## void _SetClipString(CString str) { int len = str.GetLength(); if ( !::OpenClipboard(NULL) ) return; // Remove the current Clipboard contents if( !EmptyClipboard() ) return; HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, len+1); if (hData == NULL) return; strcpy((LPSTR)GlobalLock(hData), (LPCSTR)str); GlobalUnlock(hData); // For the appropriate data formats... SetClipboardData( CF_TEXT, hData ); CloseClipboard(); //GlobalFree(hData); } CString _GetClipString() { CString strUrl; strUrl.Empty(); if ( !::OpenClipboard(NULL) ) return strUrl; // For the appropriate data formats... HGLOBAL hData = ::GetClipboardData( CF_TEXT); if ( hData == NULL ) { CloseClipboard(); return strUrl; } // ... DWORD nSize = GlobalSize(hData); if (nSize > 0) { char *str = (char*)GlobalLock(hData); strUrl = str; } GlobalUnlock(hData); CloseClipboard(); return strUrl; } //############################################################## #ifdef _WRITE_LNG_FILE_ #define LNG_FILE "c:/English.ini" #define STR_NOTICE \ "//#################################################\r\n\ //\r\n\ // VeryIE Language File.\r\n\ //\r\n\ // 1. Only the string after = need to be translated\r\n\ // 2. Reserve these chars: \\r \\n \\t &\r\n\ //\r\n\ //#################################################" void _FileWriteBuffer(CString filename, char *str) { CFile f; if( f.Open(filename, CFile::modeWrite|CFile::modeCreate|CFile::shareDenyNone) == FALSE) return; f.Write(str,strlen(str)); f.Close(); } void _FileAppendBuffer(CString filename, char *str) { CFile f; if( f.Open(filename, CFile::modeWrite|CFile::shareDenyNone) == FALSE) return; f.SeekToEnd(); f.Write(str,strlen(str)); f.Close(); } void _WriteStringTable() { char num[10]; CString filename = LNG_FILE; // int i; CString str; //write information DeleteFile(filename); _FileWriteBuffer(filename,STR_NOTICE); ::WritePrivateProfileSection("Information", NULL, filename); ::WritePrivateProfileString("Information", "Language", "", filename); ::WritePrivateProfileString("Information", "Translator", "", filename); //write general string _FileAppendBuffer(filename,"\r\n"); ::WritePrivateProfileSection("StringGeneral", NULL, filename); ::WritePrivateProfileString("StringGeneral", "1", "&OK", filename); ::WritePrivateProfileString("StringGeneral", "2", "&Cancel", filename); //string table _FileAppendBuffer(filename,"\r\n"); ::WritePrivateProfileSection("StringTable", NULL, filename); for (i=105;i<61400;i++) { if (i>=59136 && i<=59141) continue; LOADSTR(str ,i); if (str.GetLength() && str!=" " && str!="0") { itoa(i,num,10); if (str.Find('\r')>=0) str.Replace("\r","\\r"); if (str.Find('\n')>=0) str.Replace("\n","\\n"); ::WritePrivateProfileString("StringTable", num, str, filename); } } } #define IS_NUM(x) (x>='0' && x<='9') #define IS_NAME(strText) \ ( (strText.Left(4)=="List" && IS_NUM(strText.GetAt(4))) || \ (strText.Left(4)=="Tree" && IS_NUM(strText.GetAt(4))) || \ (strText.Left(4)=="Spin" && IS_NUM(strText.GetAt(4))) || \ (strText.Left(4)=="Slider" && IS_NUM(strText.GetAt(6))) || \ (strText.Left(3)=="Tab" && IS_NUM(strText.GetAt(3))) ) void _WriteDlgString(CWnd *pDlg, CString strDomain) { char num[10]; CString filename = LNG_FILE; // int id; CWnd *pWnd=NULL; CString strText; _FileAppendBuffer(filename,"\r\n"); ::WritePrivateProfileSection(strDomain, NULL, filename); pDlg->GetWindowText(strText); if (strText.GetLength()) ::WritePrivateProfileString(strDomain, "Caption", strText, filename); // pWnd = pDlg->GetNextDlgGroupItem(NULL); while(pWnd) { pWnd->GetWindowText(strText); if (strText.GetLength() && strText!="..." && strText!="0" && !IS_NAME(strText)) { id = pWnd->GetDlgCtrlID(); if (id>10 && id<65535) { if (strText.Find('\r')>=0) strText.Replace("\r","\\r"); if (strText.Find('\n')>=0) strText.Replace("\n","\\n"); itoa(id,num,10); ::WritePrivateProfileString(strDomain, num, strText, filename); } } pWnd = pWnd->GetNextWindow(); } } void _WriteDlgComboBox(CWnd *pDlg, CString strDomain) { char num[10]; CString filename = LNG_FILE; // int id; CWnd *pWnd=NULL; CString strText; //::WritePrivateProfileSection(strDomain, NULL, filename); //pDlg->GetWindowText(strText); //if (strText.GetLength()) // ::WritePrivateProfileString(strDomain, "Caption", strText, filename); // pWnd = pDlg->GetNextDlgGroupItem(NULL); while(pWnd) { id = pWnd->GetDlgCtrlID(); if (id>10 && id<65535) { CString str; strText.Empty(); CComboBox *pCb = (CComboBox *)pWnd; int count = pCb->GetCount(); if (count) { for (int i=0; i<count; i++) { pCb->GetLBText(i,str); strText += "\\n"; strText += str; } if (strText.GetLength()) { id = pWnd->GetDlgCtrlID(); itoa(id,num,10); ::WritePrivateProfileString(strDomain, num, strText, filename); } } } pWnd = pWnd->GetNextWindow(); } } void _WriteMenuString(CMenu *pMenu, CString strDomain) { char num[10]; char buf[MAX_INI]; CString filename = LNG_FILE; // CMenu *pSubMenu; int value,j,nID; UINT i=0,itemCount,state; static char aIndex[5]; static char nIndex=_NULL; char key[10]=""; CString strName; nIndex++; if (nIndex==0) { _FileAppendBuffer(filename,"\r\n"); ::WritePrivateProfileSection(strDomain, NULL, filename); } // itemCount = pMenu->GetMenuItemCount(); for(i=0;i<itemCount;i++) { state=pMenu->GetMenuState(i,MF_BYPOSITION); if(state&MF_POPUP) { aIndex[nIndex] = i; aIndex[nIndex+1] = _NULL; j=0; key[0]=0; while( (value=aIndex[j++]) != _NULL) { strcat(key,"X"); itoa(value, num, 10); strcat(key,num); } pMenu->GetMenuString( i, buf, countof(buf)-1, MF_BYPOSITION); strName = buf; strName.Replace("\t","\\t"); if (strName.GetLength()) ::WritePrivateProfileString(strDomain, key, strName, filename); pSubMenu = pMenu->GetSubMenu(i); if (pSubMenu) _WriteMenuString(pSubMenu,strDomain); } else if(state&MF_SEPARATOR) ; else { nID = pMenu->GetMenuItemID(i); itoa(nID,num,10); pMenu->GetMenuString( i, buf, countof(buf)-1, MF_BYPOSITION); CString strName; strName = buf; strName.Replace("\t","\\t"); ::WritePrivateProfileString(strDomain, num, strName, filename); } } nIndex--; if (nIndex>-1) aIndex[nIndex] = _NULL; } void _WriteAllMenuString() { CMenu menu; // menu.LoadMenu(IDR_MAINFRAME); _WriteMenuString(&menu, "MenuMain"); // menu.LoadMenu(IDR_DRAG_IMG); _WriteMenuString(menu.GetSubMenu(0), "MenuDragImage"); // menu.LoadMenu(IDR_DRAG_LINK); _WriteMenuString(menu.GetSubMenu(0), "MenuDragLink"); // menu.LoadMenu(IDR_DRAG_TEXT); _WriteMenuString(menu.GetSubMenu(0), "MenuDragText"); // menu.LoadMenu(IDR_RFAV_FOLDER); _WriteMenuString(menu.GetSubMenu(0), "MenuFavFolder"); // menu.LoadMenu(IDR_RFAV_URL); _WriteMenuString(menu.GetSubMenu(0), "MenuFavUrl"); // menu.LoadMenu(IDR_RTAB); _WriteMenuString(menu.GetSubMenu(0), "MenuTab"); // menu.LoadMenu(IDR_TRAYMENU); _WriteMenuString(menu.GetSubMenu(0), "MenuTray"); } #endif //_WRITE_LNG_FILE_ //############################################################## void _InitLanguageFile(LPCSTR lpFileName) { FREENULL(g_strLngBuf); if (!theApp.m_bUseLngFile) return; g_strLngBuf = _FileGetBuffer(lpFileName); if (g_strLngBuf == NULL) { theApp.m_bUseLngFile = FALSE; } } DWORD _GetPrivateProfileString( LPCSTR lpAppName, LPCSTR lpKeyName, LPCSTR lpDefault, LPSTR lpReturnedString, DWORD nSize, LPCSTR lpFileName ) { char strTemp[50]; char *p1,*p2; sprintf(strTemp,"[%s]",lpAppName); p1 = strstr(g_strLngBuf,strTemp); if (p1) { p1 += strlen(strTemp); p2 = strstr(p1,"]\r"); sprintf(strTemp,"\r\n%s=",lpKeyName); p1 = strstr(p1,strTemp); if ( p1 && (!p2 || (p2 && p1<p2)) ) { p1 += strlen(strTemp); p2 = strchr(p1,'\r'); if (p2) { int len = min( (DWORD)(p2-p1), nSize); STRNCPY(lpReturnedString, p1, len); return len; } } } if (lpDefault) { strcpy(lpReturnedString, lpDefault); return strlen(lpDefault); } else { *lpReturnedString = 0; return 0; } } void _LoadString(CString &str, UINT id) { char num[10]; char buf[MAX_INI]; itoa(id,num,10); if (_GetPrivateProfileString("StringTable", num, NULL, buf, MAX_INI, theApp.m_strLngFile)) { str = buf; if (str.Find("\\r")>=0) str.Replace("\\r","\r"); if (str.Find("\\n")>=0) str.Replace("\\n","\n"); } else str.LoadString(id); } void _LoadDlgString(CWnd *pDlg, CString strDomain) { char num[10]; char buf[MAX_INI]; // int id; CWnd *pWnd=NULL; CString strText; DWORD r; if (_GetPrivateProfileString(strDomain, "Caption", NULL, buf, MAX_INI, theApp.m_strLngFile)) pDlg->SetWindowText(buf); // pWnd = pDlg->GetNextDlgGroupItem(NULL); while(pWnd) { id = pWnd->GetDlgCtrlID(); itoa(id,num,10); if (id<10) { if (_GetPrivateProfileString("StringGeneral", num, NULL, buf, MAX_INI, theApp.m_strLngFile)) pWnd->SetWindowText(buf); } else { if (r = _GetPrivateProfileString(strDomain, num, NULL, buf, MAX_INI, theApp.m_strLngFile)) { if (*buf=='\\' && *(buf+1)=='n')//combo box { char str[MAX_INI]; char *pos1,*pos2; int i=0,len; CComboBox *pCb = (CComboBox *)pWnd; int nCurSel = pCb->GetCurSel(); pCb->ResetContent(); pos1 = buf + 2; while (1) { pos2 = strstr(pos1,"\\n"); if (!pos2) pos2 = buf + r; len = pos2 - pos1; STRNCPY(str,pos1,len); pCb->InsertString(i,str); i++; pos1 = pos2+2; if (pos1>=buf+r) break; } pCb->SetCurSel(nCurSel); } else if ( strstr(buf,"\\r") || strstr(buf,"\\n")) { CString str=buf; str.Replace("\\r","\r"); str.Replace("\\n","\n"); pWnd->SetWindowText(str); } else pWnd->SetWindowText(buf); } } pWnd = pWnd->GetNextWindow(); } } void _GetMenuItemString(CString &strName, int nID) { if (nID==0) { LOADSTR(strName,IDS_NONE); return ; } CMenu * pMenu = pmf->GetMenu(); // MENUITEMINFO mii; CMenuData* pmd; if(pMenu!=NULL) { mii.fMask = MIIM_DATA|MIIM_TYPE; // get the state of the menu item mii.dwTypeData = NULL; mii.cch = 0; mii.dwItemData = NULL; mii.cbSize = sizeof(mii); pMenu->GetMenuItemInfo(nID, &mii, FALSE); pmd = (CMenuData*)(mii.dwItemData); if(mii.fType & MFT_OWNERDRAW && pmd!=NULL) strName = pmd->m_szMenuText; else strName = ""; } strName.Remove('&'); int pos = strName.Find('\t'); if (pos>=0) strName = strName.Left(pos); } void _LoadMenuString2ComboBox(CMenu *pMenu, CComboBox *pCb) { char num[10]; char buf[MAX_INI]; // CMenu *pSubMenu; int value,j,nID; UINT i=0,itemCount,state; char key[10]=""; CString strName,strPop; static int index=0; static char aIndex[5]; static char nIndex=_NULL; static CString strIndex[5]; BOOL r = TRUE; BOOL bNeedReadRes = TRUE; // if (pMenu == pmf->GetMenu()) { CString strItem; LOADSTR(strItem,IDS_NONE); pCb->InsertString(0,strItem); index=1; } // nIndex++; // itemCount = pMenu->GetMenuItemCount(); for(i=0;i<itemCount;i++) { state=pMenu->GetMenuState(i,MF_BYPOSITION); if(state&MF_POPUP) { bNeedReadRes = TRUE; aIndex[nIndex] = i; aIndex[nIndex+1] = _NULL; if (theApp.m_bUseLngFile) { j=0; key[0]=0; while( (value=aIndex[j++]) != _NULL) { strcat(key,"X"); itoa(value, num, 10); strcat(key,num); } r = _GetPrivateProfileString("MenuMain", key, NULL, buf, MAX_INI, theApp.m_strLngFile); if (r) bNeedReadRes = FALSE; } //read string from res if (bNeedReadRes) pMenu->GetMenuString( i, buf, countof(buf)-1, MF_BYPOSITION);//::GetMenuString(hSubMenu, i, name, countof(name)-1, MF_BYPOSITION); // { CString strName; strName = buf; strName.Replace("\\t","\t"); strName.Remove('&'); int pos = strName.Find('\t'); if (pos>=0) strName = strName.Left(pos); if (strName.GetLength()) strIndex[nIndex] = strName; } // pSubMenu = pMenu->GetSubMenu(i); if (pSubMenu) _LoadMenuString2ComboBox(pSubMenu, pCb); } else if(state&MF_SEPARATOR) ; else { nID = pMenu->GetMenuItemID(i); //undo close if (nID>=B_UNDO && nID<=B_UNDO+MAX_UNDO) goto _myexit; //add url to this fav if (nID>=B_ADDTO_FAV && nID<=E_ADDTO_FAV) goto _myexit; //add url to this group if (nID>=B_ADDTO_GROUP && nID<=E_ADDTO_GROUP) goto _myexit; //search if (nID>=B_SEARCH && nID<=E_SEARCH) goto _myexit; // CString strPop; strPop.Empty(); j=0; while(strIndex[j].GetLength()) { strPop += strIndex[j]; strPop += " \\ "; j++; } _GetMenuItemString(strName,nID); strName = strPop + strName; if (strName.GetLength()) { pCb->InsertString(index,strName); pCb->SetItemData(index,nID); index++; } } } _myexit: nIndex--; if (nIndex>-1) { aIndex[nIndex] = _NULL; strIndex[nIndex] = ""; } } void _LoadMenuString(CMenu *pMenu, CString strDomain) { char num[10]; char buf[MAX_INI]; // CMenu *pSubMenu; int value,j,nID; UINT i=0,itemCount,state; static char aIndex[5]; static char nIndex=_NULL; char key[10]=""; CString strName; BOOL r = TRUE; nIndex++; // itemCount = pMenu->GetMenuItemCount(); for(i=0;i<itemCount;i++) { state=pMenu->GetMenuState(i,MF_BYPOSITION); if(state&MF_POPUP) { aIndex[nIndex] = i; aIndex[nIndex+1] = _NULL; j=0; key[0]=0; while( (value=aIndex[j++]) != _NULL) { strcat(key,"X"); itoa(value, num, 10); strcat(key,num); } r = _GetPrivateProfileString(strDomain, key, NULL, buf, MAX_INI, theApp.m_strLngFile); if (r) { strName = buf; strName.Replace("\\t","\t"); pMenu->ModifyMenu( i, MF_BYPOSITION|MF_STRING, 0, strName); } pSubMenu = pMenu->GetSubMenu(i); if (pSubMenu) _LoadMenuString(pSubMenu,strDomain); } else if(state&MF_SEPARATOR) ; else { nID = pMenu->GetMenuItemID(i); itoa(nID,num,10); r = _GetPrivateProfileString(strDomain, num, NULL, buf, MAX_INI, theApp.m_strLngFile); if (r) { strName = buf; strName.Replace("\\t","\t"); pMenu->ModifyMenu( i, MF_BYPOSITION|MF_STRING, nID, strName); } } } nIndex--; if (nIndex>-1) aIndex[nIndex] = _NULL; } int GetPopMenuIconID(char aIndex[5]) { switch (aIndex[0]) { case 0://file { switch (aIndex[1]) { case 0: return 9; case 19:return 65; } } break; case 2://view menu { switch (aIndex[1]) { case 4: return 8; case 5:return 14; case 9:return 27; } } break; case 4://group { switch (aIndex[1]) { case 2: return 69; } } break; case 5://tools { switch (aIndex[1]) { case 0: return 26; case 2: return 37; case 3: return 33; case 4: return 10; case 7: return 38; case 8: return 25; } } break; } return -1; } int GetMenuIconID(int nID) { switch (nID) { case ID_GO_BACK: return 0; case ID_GO_FORWARD: return 1; case ID_RTAB_STOP: case ID_VIEW_STOP: return 2; case ID_RTAB_REFRESH: case ID_VIEW_REFRESH: return 3; case ID_FILE_NEW_S: return 4; case ID_GO_START_PAGE: return 4; case ID_ALL_PAGE_LINKS: return 5; case ID_FAVORITES_DROPDOWN: return 6; case ID_FILE_PRINT: return 7; //8FONT-ok case ID_FILE_NEW_BLANK: return 9; //case ID_OPTIONS_LOADIMAGE: return 10; case ID_VIEW_FULLSCREEN: return 11; case ID_VIEW_HIS: return 12; case ID_TOOLS_EMAIL: return 13; //14ENCODING-ok case ID_GO_UP_PAGE: return 15; case ID_VIEW_AUTOHIDE: return 16; //17 WEBPROXY //18 PROXY case ID_FILE_WORKOFFLINE: return 19; case ID_EDIT_EDIT: return 20; case ID_FILE_OPENF: return 21; //22 STOP OPEN case ID_VIEW_FOLDER: return 23; case ID_VIEW_EXPLOREBAR_RESOURCE: return 24; //25 skin case ID_TOOLS_AUTOSCROLL_USEAUTOSCROLLING: return 26; case ID_EDIT_UNDOCLOSE: return 27; //case ID_RTAB_AUTOSAVE: case ID_FILE_SAVEAS: return 28; case ID_EDIT_COPY: return 29; case ID_OPTIONS_VeryIEOPTIONS:return 30; case ID_VIEW_STOP_ALL: return 31; case ID_VIEW_REFRESHALL: return 32; case ID_TOOLS_SETBG: return 33; case ID_ORGGROUP: return 34; case ID_EDIT_FIND: return 35; //36 NEXT case ID_SC_FILLFORM: return 37; case ID_TOOLS_ALL: return 38; //38 CLEAN HIS case ID_EDIT_PASTE: return 39; //IDB_SYSMENU //case ID_VIEW_WIN_MIN: case ID_WINDOW_MIN: return 40; //case ID_VIEW_WIN_RESTORE: case ID_WINDOW_RESTOR: return 41; //case ID_VIEW_WIN_CLOSE: case ID_FILE_CLOSE_1: case ID_FILE_CLOSE_2: return 42; //case ID_VIEW_WIN_CLOSEALL: case ID_FILE_CLOSEALL: return 43; //case ID_VIEW_WIN_NEXT: case ID_TAB_NEXT: return 44; //case ID_VIEW_WIN_PRE: case ID_TAB_PRE: return 45; case ID_TOOLS_COLLECT: return 46; case ID_APP_EXIT: return 47; case ID_VIEW_LOCKTOOLBAR: return 48; case ID_EDIT_CUT: return 49; //case ID_FILE_WORKOFFLINE: return 50; //51 add here fav //52 open all fav case ID_RTAB_ADDFAV: case ID_FAVORITES_ADDTOFAVORITES: return 53; case ID_FAVORITES_ORGNIZEFAVORITES: return 54; case ID_WINDOW_TILE_VERT: return 55; case ID_WINDOW_TILE_HORZ: return 56; case ID_WINDOW_CASCADE: return 57; case ID_HELP_HELP: return 58; case ID_HELP_HOMEPAGE: return 59; case ID_APP_ABOUT: return 60; case ID_TOOLS_SYNC: return 61; //62 case ID_FAVORITES_IMPORTFAVORITES: return 63; case ID_FAVORITES_EXPORTFAVORITES: return 64; //65 case ID_FILE_SENDPAGEBYEMAIL: return 66; case ID_FILE_SENDLINKBYEMAIL: return 67; case ID_TOOLS_ADDR: return 68; // case ID_ADDTO_IE: return 71; default: return -1; } } void _LoadMenuStringOwnerDraw(CMenu *pMenu, CString strDomain,CImageList *imgList) { char num[10]; char buf[MAX_INI]; // CMenu *pSubMenu; int value,j,nID; UINT i=0,itemCount,state; static char aIndex[5]; static char nIndex=_NULL; char key[10]=""; CString strName; BOOL r = TRUE; BOOL bNeedReadRes = TRUE; // CMenuData * md = NULL; MENUITEMINFO mii; nIndex++; // itemCount = pMenu->GetMenuItemCount(); for(i=0;i<itemCount;i++) { md= new CMenuData; md->m_pImgList = imgList; // state=pMenu->GetMenuState(i,MF_BYPOSITION); if(state&MF_POPUP) { bNeedReadRes = TRUE; aIndex[nIndex] = i; aIndex[nIndex+1] = _NULL; if (theApp.m_bUseLngFile) { j=0; key[0]=0; while( (value=aIndex[j++]) != _NULL) { strcat(key,"X"); itoa(value, num, 10); strcat(key,num); } OutputDebugString(key); r = _GetPrivateProfileString(strDomain, key, NULL, buf, MAX_INI, theApp.m_strLngFile); if (r) { strName = buf; strName.Replace("\\t","\t"); pMenu->ModifyMenu( i, MF_BYPOSITION|MF_STRING|MF_POPUP, (UINT)pMenu->GetSubMenu(i)->m_hMenu, strName); // SetMenuText(strName,md); bNeedReadRes = FALSE; } } //read string from res if (bNeedReadRes) { pMenu->GetMenuString( i, buf, countof(buf)-1, MF_BYPOSITION);//::GetMenuString(hSubMenu, i, name, countof(name)-1, MF_BYPOSITION); SetMenuText(buf,md); } md->m_nBitmap = GetPopMenuIconID(aIndex); // mii.cbSize = sizeof(mii); mii.fMask = MIIM_DATA|MIIM_TYPE; mii.fType = MFT_STRING|MFT_OWNERDRAW; mii.dwItemData = (DWORD)md; ::SetMenuItemInfo(pMenu->m_hMenu, i, TRUE, &mii); // pSubMenu = pMenu->GetSubMenu(i); if (pSubMenu) _LoadMenuStringOwnerDraw(pSubMenu,strDomain,imgList); } else if(state&MF_SEPARATOR) { md->m_pImgList = NULL; md->m_nBitmap = -1; mii.cbSize = sizeof(mii); mii.fMask = MIIM_DATA|MIIM_TYPE; mii.fType = MF_SEPARATOR|MFT_OWNERDRAW; mii.dwItemData = (DWORD)md; ::SetMenuItemInfo(pMenu->m_hMenu, i, TRUE, &mii); } else { bNeedReadRes = TRUE; nID = pMenu->GetMenuItemID(i); if (theApp.m_bUseLngFile) { itoa(nID,num,10); r = _GetPrivateProfileString(strDomain, num, NULL, buf, MAX_INI, theApp.m_strLngFile); if (r) { strName = buf; strName.Replace("\\t","\t"); pMenu->ModifyMenu( i, MF_BYPOSITION|MF_STRING, nID, strName); SetMenuText(strName,md); bNeedReadRes = FALSE; } } // if (bNeedReadRes) { pMenu->GetMenuString( i, buf, countof(buf)-1, MF_BYPOSITION); SetMenuText(buf,md); } md->m_nBitmap = GetMenuIconID(nID); // mii.cbSize = sizeof(mii); mii.fMask = MIIM_DATA|MIIM_TYPE; mii.fType = MFT_STRING|MFT_OWNERDRAW; mii.dwItemData = (DWORD)md; ::SetMenuItemInfo(pMenu->m_hMenu, i, TRUE, &mii); } } nIndex--; if (nIndex>-1) aIndex[nIndex] = _NULL; } //############################################################## int MSGBOX(UINT nIDPrompt, UINT nType , UINT nIDHelp ) { if (theApp.m_bUseLngFile==FALSE) return AfxMessageBox(nIDPrompt,nType,nIDHelp); else { CString str; _LoadString(str,nIDPrompt); return AfxMessageBox(str,nType,nIDHelp); } } int MSGBOX(LPCTSTR lpszText, UINT nType , UINT nIDHelp ) { return AfxMessageBox(lpszText,nType,nIDHelp); } //############################################################## BOOL _OpenFtpUrl(CString strUrl) { if (pmf->m_nFtpOpenType==0) return FALSE; else if (pmf->m_nFtpOpenType==1) { /*TCHAR szPath[MAX_PATH]; ExpandEnvironmentStrings("%windir%\\explorer.exe", szPath, MAX_PATH); strApp = szPath;*/ ShellExecute(NULL, "open", "IEXPLORE.EXE", strUrl, "", SW_SHOWNORMAL ); return FALSE; } else if (pmf->m_nFtpOpenType==2 && pmf->m_strFtpExePath.GetLength()) { CString strApp; CString strPath; strApp = pmf->m_strFtpExePath; strPath = strApp; int i = strPath.ReverseFind('\\'); strPath = strPath.Left(i+1); //better add ftp:// at head if (strUrl.Left(7)=="http://") strUrl = strUrl.Right(strUrl.GetLength()-7); if (strUrl.Left(6)!="ftp://") strUrl = "ftp://" + strUrl; if((UINT)ShellExecute(NULL, "open", strApp , strUrl, strPath, SW_SHOW )<=32) MSGBOX(IDS_TIP_OPEN_FTP_ERR); else return FALSE; } return TRUE; } //############################################################## void _LoadFormUrl(CListCtrl *pCtrl) { char* tmp = _FileGetBuffer(theApp.m_strFormDataPath); if (tmp==NULL) return; // char *head,*tail; char pUrl[512]; head = tmp; int i=0; DWORD len = strlen(tmp); while(1) { if (*head == NULL) break; else if (*head == '[') { tail = strstr(head,"]"); len = tail-(head+1); STRNCPY(pUrl,head+1,len ); pCtrl->InsertItem(i,pUrl); i++; head = tail+ 3;// ]\r\n } else { tail = strstr(head,"\r\n"); if (!tail) break; head = tail+ 2;// \r\n } } free(tmp); } CString _GetSameFormUrl(CString strRoot) { CString strCur; strCur.Empty(); char* tmp = _FileGetBuffer(theApp.m_strFormDataPath); if (tmp==NULL) return strCur; // char *head,*tail; char pUrl[512]; head = tmp; int i=0; DWORD len = strlen(tmp); while(1) { if (*head == NULL) break; else if (*head == '[') { tail = strstr(head,"]"); len = tail-(head+1); STRNCPY(pUrl,head+1,len ); strCur = pUrl; strCur = _StringGetRootUrl(strCur); if (strCur.CompareNoCase(strRoot)==0) { strCur = pUrl; break; } i++; head = tail+ 3;// ]\r\n } else { tail = strstr(head,"\r\n"); if (!tail) break; head = tail+ 2;// \r\n } } free(tmp); return strCur; } //############################################################## char NUMS[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; #define IS_09azAZ(c) ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ) //# => %23 void _CharFormat(char *p) { char c; while(*p) { if ( IS_09azAZ(*p) ) p++;//do nothing else { c = *p; memmove(p+3,p+1,strlen(p+1)+1); *p = '%'; *(p+1) = NUMS[(c & 0xf0)>>4]; *(p+2) = NUMS[ c & 0x0f]; p+=3; } } } void _AsciiFormat(CString& strAscii) { int nLen = strAscii.GetLength(); for (int i=0; i<nLen; i++) { if ( !IS_09azAZ(strAscii.GetAt(i)) ) break; } if (i == nLen) return;//no use format LPSTR pAsciiBuf = strAscii.GetBuffer(nLen*3+1); _CharFormat(pAsciiBuf); strAscii.ReleaseBuffer(); } void _Ascii2Utf8(CString& strAscii) { int nAsciiLen,nTransLen,length; LPSTR pAsciiBuf; LPSTR pTransBuf; nAsciiLen = strAscii.GetLength(); nTransLen = nAsciiLen*3 + 1; pAsciiBuf = strAscii.GetBuffer(nTransLen); pTransBuf = (LPSTR)GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT,nTransLen); length = MultiByteToWideChar(CP_ACP,0,pAsciiBuf,nAsciiLen, (LPWSTR)pTransBuf,nTransLen); length = WideCharToMultiByte(CP_UTF8,0,(LPWSTR)pTransBuf,length, pAsciiBuf,nTransLen,NULL,NULL); *(pAsciiBuf+length) = 0; //# => %23 _CharFormat(pAsciiBuf); strAscii.ReleaseBuffer(); // GlobalFree(pTransBuf); }
[ "songbohr@af2e6244-03f2-11de-b556-9305e745af9e" ]
[ [ [ 1, 1609 ] ] ]
05517f9e6b9133eae295c9eb0fad412e4041e4f2
3d677d3bcbd5322bd814adae4d6c6cf45dc67666
/JuceLibraryCode/modules/juce_graphics/native/juce_win32_DirectWriteTypeLayout.cpp
507bad4f11633e9ed65241e5f0f6658de1fe3de9
[]
no_license
sonic59/JuceS2Text
281e5fc7fa31e715b4d7b1459181637e4f684974
e116dc0dfc20222028bab0180f6b93b2f8a2c40c
refs/heads/master
2016-09-10T18:40:38.239670
2011-11-25T17:37:21
2011-11-25T17:37:21
2,850,515
0
0
null
null
null
null
UTF-8
C++
false
false
17,289
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ //================================================================================================== #if JUCE_USE_DIRECTWRITE namespace DirectWriteTypeLayout { class CustomDirectWriteTextRenderer : public ComBaseClassHelper <IDWriteTextRenderer> { public: CustomDirectWriteTextRenderer (IDWriteFontCollection* const fontCollection_) : fontCollection (fontCollection_), currentLine (-1), lastOriginY (-10000.0f) { resetReferenceCount(); } JUCE_COMRESULT QueryInterface (REFIID refId, void** result) { #if ! JUCE_MINGW if (refId == __uuidof (IDWritePixelSnapping)) { AddRef(); *result = dynamic_cast <IDWritePixelSnapping*> (this); return S_OK; } #else jassertfalse; // need to find a mingw equivalent of __uuidof to make this possible #endif return ComBaseClassHelper<IDWriteTextRenderer>::QueryInterface (refId, result); } JUCE_COMRESULT IsPixelSnappingDisabled (void* /*clientDrawingContext*/, BOOL* isDisabled) { *isDisabled = FALSE; return S_OK; } JUCE_COMRESULT GetCurrentTransform (void*, DWRITE_MATRIX*) { return S_OK; } JUCE_COMRESULT GetPixelsPerDip (void*, FLOAT*) { return S_OK; } JUCE_COMRESULT DrawUnderline (void*, FLOAT, FLOAT, DWRITE_UNDERLINE const*, IUnknown*) { return S_OK; } JUCE_COMRESULT DrawStrikethrough (void*, FLOAT, FLOAT, DWRITE_STRIKETHROUGH const*, IUnknown*) { return S_OK; } JUCE_COMRESULT DrawInlineObject (void*, FLOAT, FLOAT, IDWriteInlineObject*, BOOL, BOOL, IUnknown*) { return E_NOTIMPL; } JUCE_COMRESULT DrawGlyphRun (void* clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_GLYPH_RUN_DESCRIPTION const* runDescription, IUnknown* clientDrawingEffect) { TextLayout* const layout = static_cast<TextLayout*> (clientDrawingContext); if (baselineOriginY != lastOriginY) { lastOriginY = baselineOriginY; ++currentLine; // The x value is only correct when dealing with LTR text if (currentLine == layout->getNumLines()) return S_OK; layout->getLine (currentLine).lineOrigin = Point<float> (baselineOriginX, baselineOriginY); } if (currentLine < 0) return S_OK; TextLayout::Line& glyphLine = layout->getLine (currentLine); DWRITE_FONT_METRICS dwFontMetrics; glyphRun->fontFace->GetMetrics (&dwFontMetrics); glyphLine.ascent = jmax (glyphLine.ascent, scaledFontSize (dwFontMetrics.ascent, dwFontMetrics, glyphRun)); glyphLine.descent = jmax (glyphLine.descent, scaledFontSize (dwFontMetrics.descent, dwFontMetrics, glyphRun)); int styleFlags = 0; const String fontName (getFontName (glyphRun, styleFlags)); TextLayout::Run* const glyphRunLayout = new TextLayout::Run (Range<int> (runDescription->textPosition, runDescription->textPosition + runDescription->stringLength), glyphRun->glyphCount); glyphLine.runs.add (glyphRunLayout); glyphRun->fontFace->GetMetrics (&dwFontMetrics); const float totalHeight = std::abs ((float) dwFontMetrics.ascent) + std::abs ((float) dwFontMetrics.descent); const float fontHeightToEmSizeFactor = (float) dwFontMetrics.designUnitsPerEm / totalHeight; glyphRunLayout->font = Font (fontName, glyphRun->fontEmSize / fontHeightToEmSizeFactor, styleFlags); glyphRunLayout->colour = getColourOf (static_cast<ID2D1SolidColorBrush*> (clientDrawingEffect)); const Point<float> lineOrigin (layout->getLine (currentLine).lineOrigin); float x = baselineOriginX - lineOrigin.x; for (UINT32 i = 0; i < glyphRun->glyphCount; ++i) { const float advance = glyphRun->glyphAdvances[i]; if ((glyphRun->bidiLevel & 1) != 0) x -= advance; // RTL text glyphRunLayout->glyphs.add (TextLayout::Glyph (glyphRun->glyphIndices[i], Point<float> (x, baselineOriginY - lineOrigin.y), advance)); if ((glyphRun->bidiLevel & 1) == 0) x += advance; // LTR text } return S_OK; } private: IDWriteFontCollection* const fontCollection; int currentLine; float lastOriginY; static float scaledFontSize (int n, const DWRITE_FONT_METRICS& metrics, const DWRITE_GLYPH_RUN* glyphRun) noexcept { return (std::abs ((float) n) / (float) metrics.designUnitsPerEm) * glyphRun->fontEmSize; } static Colour getColourOf (ID2D1SolidColorBrush* d2dBrush) { if (d2dBrush == nullptr) return Colours::black; const D2D1_COLOR_F colour (d2dBrush->GetColor()); return Colour::fromFloatRGBA (colour.r, colour.g, colour.b, colour.a); } String getFontName (DWRITE_GLYPH_RUN const* glyphRun, int& styleFlags) const { ComSmartPtr<IDWriteFont> dwFont; HRESULT hr = fontCollection->GetFontFromFontFace (glyphRun->fontFace, dwFont.resetAndGetPointerAddress()); jassert (dwFont != nullptr); if (dwFont->GetWeight() == DWRITE_FONT_WEIGHT_BOLD) styleFlags &= Font::bold; if (dwFont->GetStyle() == DWRITE_FONT_STYLE_ITALIC) styleFlags &= Font::italic; ComSmartPtr<IDWriteFontFamily> dwFontFamily; hr = dwFont->GetFontFamily (dwFontFamily.resetAndGetPointerAddress()); jassert (dwFontFamily != nullptr); // Get the Font Family Names ComSmartPtr<IDWriteLocalizedStrings> dwFamilyNames; hr = dwFontFamily->GetFamilyNames (dwFamilyNames.resetAndGetPointerAddress()); jassert (dwFamilyNames != nullptr); UINT32 index = 0; BOOL exists = false; hr = dwFamilyNames->FindLocaleName (L"en-us", &index, &exists); if (! exists) index = 0; UINT32 length = 0; hr = dwFamilyNames->GetStringLength (index, &length); HeapBlock <wchar_t> name (length + 1); hr = dwFamilyNames->GetString (index, name, length + 1); return String (name); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomDirectWriteTextRenderer); }; //================================================================================================== float getFontHeightToEmSizeFactor (const Font& font, IDWriteFontCollection& dwFontCollection) { BOOL fontFound = false; uint32 fontIndex; dwFontCollection.FindFamilyName (font.getTypefaceName().toWideCharPointer(), &fontIndex, &fontFound); if (! fontFound) fontIndex = 0; ComSmartPtr<IDWriteFontFamily> dwFontFamily; HRESULT hr = dwFontCollection.GetFontFamily (fontIndex, dwFontFamily.resetAndGetPointerAddress()); ComSmartPtr<IDWriteFont> dwFont; hr = dwFontFamily->GetFirstMatchingFont (DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, dwFont.resetAndGetPointerAddress()); ComSmartPtr<IDWriteFontFace> dwFontFace; hr = dwFont->CreateFontFace (dwFontFace.resetAndGetPointerAddress()); DWRITE_FONT_METRICS dwFontMetrics; dwFontFace->GetMetrics (&dwFontMetrics); const float totalHeight = (float) (std::abs (dwFontMetrics.ascent) + std::abs (dwFontMetrics.descent)); return dwFontMetrics.designUnitsPerEm / totalHeight; } void setTextFormatProperties (const AttributedString& text, IDWriteTextFormat* const format) { DWRITE_TEXT_ALIGNMENT alignment = DWRITE_TEXT_ALIGNMENT_LEADING; DWRITE_WORD_WRAPPING wrapType = DWRITE_WORD_WRAPPING_WRAP; switch (text.getJustification().getOnlyHorizontalFlags()) { case Justification::left: break; case Justification::right: alignment = DWRITE_TEXT_ALIGNMENT_TRAILING; break; case Justification::horizontallyCentred: alignment = DWRITE_TEXT_ALIGNMENT_CENTER; break; case Justification::horizontallyJustified: break; // DirectWrite cannot justify text, default to left alignment default: jassertfalse; break; // Illegal justification flags } switch (text.getWordWrap()) { case AttributedString::none: wrapType = DWRITE_WORD_WRAPPING_NO_WRAP; break; case AttributedString::byWord: break; case AttributedString::byChar: break; // DirectWrite doesn't support wrapping by character, default to word-wrap default: jassertfalse; break; // Illegal flags! } format->SetTextAlignment (alignment); format->SetWordWrapping (wrapType); // DirectWrite does not automatically set reading direction // This must be set correctly and manually when using RTL Scripts (Hebrew, Arabic) if (text.getReadingDirection() == AttributedString::rightToLeft) format->SetReadingDirection (DWRITE_READING_DIRECTION_RIGHT_TO_LEFT); } void addAttributedRange (const AttributedString::Attribute& attr, IDWriteTextLayout* textLayout, const int textLen, ID2D1DCRenderTarget* const renderTarget, IDWriteFontCollection* const fontCollection) { DWRITE_TEXT_RANGE range; range.startPosition = attr.range.getStart(); range.length = jmin (attr.range.getLength(), textLen - attr.range.getStart()); if (attr.getFont() != nullptr) { textLayout->SetFontFamilyName (attr.getFont()->getTypefaceName().toWideCharPointer(), range); const float fontHeightToEmSizeFactor = getFontHeightToEmSizeFactor (*attr.getFont(), *fontCollection); textLayout->SetFontSize (attr.getFont()->getHeight() * fontHeightToEmSizeFactor, range); } if (attr.getColour() != nullptr) { ComSmartPtr<ID2D1SolidColorBrush> d2dBrush; renderTarget->CreateSolidColorBrush (D2D1::ColorF (D2D1::ColorF (attr.getColour()->getFloatRed(), attr.getColour()->getFloatGreen(), attr.getColour()->getFloatBlue(), attr.getColour()->getFloatAlpha())), d2dBrush.resetAndGetPointerAddress()); // We need to call SetDrawingEffect with a legimate brush to get DirectWrite to break text based on colours textLayout->SetDrawingEffect (d2dBrush, range); } } void createLayout (TextLayout& layout, const AttributedString& text, IDWriteFactory* const directWriteFactory, ID2D1Factory* const direct2dFactory, IDWriteFontCollection* const fontCollection) { // To add color to text, we need to create a D2D render target // Since we are not actually rendering to a D2D context we create a temporary GDI render target D2D1_RENDER_TARGET_PROPERTIES d2dRTProp = D2D1::RenderTargetProperties (D2D1_RENDER_TARGET_TYPE_SOFTWARE, D2D1::PixelFormat (DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE), 0, 0, D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE, D2D1_FEATURE_LEVEL_DEFAULT); ComSmartPtr<ID2D1DCRenderTarget> renderTarget; HRESULT hr = direct2dFactory->CreateDCRenderTarget (&d2dRTProp, renderTarget.resetAndGetPointerAddress()); Font defaultFont; const float defaultFontHeightToEmSizeFactor = getFontHeightToEmSizeFactor (defaultFont, *fontCollection); jassert (directWriteFactory != nullptr); ComSmartPtr<IDWriteTextFormat> dwTextFormat; hr = directWriteFactory->CreateTextFormat (defaultFont.getTypefaceName().toWideCharPointer(), fontCollection, DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, defaultFont.getHeight() * defaultFontHeightToEmSizeFactor, L"en-us", dwTextFormat.resetAndGetPointerAddress()); setTextFormatProperties (text, dwTextFormat); const int textLen = text.getText().length(); ComSmartPtr<IDWriteTextLayout> dwTextLayout; hr = directWriteFactory->CreateTextLayout (text.getText().toWideCharPointer(), textLen, dwTextFormat, layout.getWidth(), 1.0e7f, dwTextLayout.resetAndGetPointerAddress()); const int numAttributes = text.getNumAttributes(); for (int i = 0; i < numAttributes; ++i) addAttributedRange (*text.getAttribute (i), dwTextLayout, textLen, renderTarget, fontCollection); UINT32 actualLineCount = 0; hr = dwTextLayout->GetLineMetrics (nullptr, 0, &actualLineCount); layout.ensureStorageAllocated (actualLineCount); HeapBlock <DWRITE_LINE_METRICS> dwLineMetrics (actualLineCount); hr = dwTextLayout->GetLineMetrics (dwLineMetrics, actualLineCount, &actualLineCount); int lastLocation = 0; for (UINT32 i = 0; i < actualLineCount; ++i) { const Range<int> lineStringRange (lastLocation, (int) lastLocation + dwLineMetrics[i].length); lastLocation = dwLineMetrics[i].length; TextLayout::Line* glyphLine = new TextLayout::Line(); layout.addLine (glyphLine); glyphLine->stringRange = lineStringRange; } ComSmartPtr<CustomDirectWriteTextRenderer> textRenderer (new CustomDirectWriteTextRenderer (fontCollection)); hr = dwTextLayout->Draw (&layout, textRenderer, 0, 0); } } #endif bool TextLayout::createNativeLayout (const AttributedString& text) { #if JUCE_USE_DIRECTWRITE const Direct2DFactories& factories = Direct2DFactories::getInstance(); if (factories.d2dFactory != nullptr && factories.systemFonts != nullptr) { DirectWriteTypeLayout::createLayout (*this, text, factories.directWriteFactory, factories.d2dFactory, factories.systemFonts); return true; } #else (void) text; #endif return false; }
[ [ [ 1, 354 ] ] ]
fb201d63fe1df800589dbc384d2c04e0980078e0
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SampleFoundation/BumpMaps/BumpMaps.cpp
c3bff538b668d30fd06c202f46faac14233d6501
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
13,152
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "BumpMaps.h" SE_WINDOW_APPLICATION(BumpMaps); SE_REGISTER_INITIALIZE(BumpMaps); //---------------------------------------------------------------------------- BumpMaps::BumpMaps() : SEWindowApplication3("BumpMaps", 0, 0, 800, 600, SEColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)) { m_fLight0Height = 4.0f; m_Light0Color = SEColorRGB::SE_RGB_WHITE; } //---------------------------------------------------------------------------- bool BumpMaps::OnInitialize() { if( !SEWindowApplication3::OnInitialize() ) { return false; } // If you want to deploy your application, then add your resource // directories to system searching list as you choose. SESystem::SE_InsertDirectory("./Data/seif"); SESystem::SE_InsertDirectory("./Data/seof"); #if defined(SE_USING_OES2) SESystem::SE_InsertDirectory("./Data/sesp/ESSL"); #else SESystem::SE_InsertDirectory("./Data/sesp/Cg"); #endif m_spCamera->SetFrustum(-0.55f, 0.55f, -0.4125f, 0.4125f, 1.0f, 100.0f); SEVector3f tempCLoc(0.0f, 9.0f, -20.0f); SEVector3f tempCDir(0.0f, -0.2f, 1.0f); tempCDir.Normalize(); SEVector3f tempCUp(0.0f, 1.0f, 0.0f); SEVector3f tempCRight = tempCUp.Cross(tempCDir); tempCRight.Normalize(); tempCUp = tempCDir.Cross(tempCRight); tempCUp.Normalize(); m_spCamera->SetFrame(tempCLoc, tempCRight, tempCUp, tempCDir); CreateScene(); // initial update of objects m_spScene->UpdateGS(); m_spScene->UpdateRS(); // initial culling of scene m_Culler.SetCamera(m_spCamera); m_Culler.ComputeUnculledSet(m_spScene); #if defined(SE_USING_OES2) InitializeCameraMotion(0.1f, 0.01f); #else InitializeCameraMotion(0.01f, 0.001f); #endif InitializeObjectMotion(m_spScene); return true; } //---------------------------------------------------------------------------- void BumpMaps::OnTerminate() { m_spScene = 0; m_spModelRoot = 0; m_spWireframe = 0; m_spLight0 = 0; m_spLight0Node = 0; SEWindowApplication3::OnTerminate(); } //---------------------------------------------------------------------------- void BumpMaps::OnIdle() { // Light0 motion. static double dCurTime = 0.0; static double dLastTime = 0.0; static double dDiffTime = 0.0; static float fAngel0 = 0.0f; static float fAngel0Speed = 2.0f; static float fRadius0 = 4.0f; dCurTime = SESystem::SE_GetTime(); dDiffTime = dCurTime - dLastTime; dLastTime = dCurTime; fAngel0 += fAngel0Speed*(float)dDiffTime; SEMatrix3f mat3fRot; mat3fRot.FromEulerAnglesXYZ(0.0f, -fAngel0Speed, 0.0f); m_spLight0Node->Local.SetRotate(m_spLight0Node->Local.GetRotate() *mat3fRot); float fX = fRadius0*SEMathf::Cos(fAngel0); float fZ = fRadius0*SEMathf::Sin(fAngel0); m_spLight0Node->Local.SetTranslate(SEVector3f(fX, m_fLight0Height, fZ)); m_spLight0Node->UpdateGS(); MeasureTime(); if( MoveCamera() ) { m_Culler.ComputeUnculledSet(m_spScene); } if( MoveObject() ) { m_spScene->UpdateGS(); m_Culler.ComputeUnculledSet(m_spScene); } m_pRenderer->ClearBuffers(); if( m_pRenderer->BeginScene() ) { m_pRenderer->DrawScene(m_Culler.GetVisibleSet()); DrawFrameRate(8, GetHeight()-8, SEColorRGBA::SE_RGBA_WHITE); m_pRenderer->EndScene(); } m_pRenderer->DisplayBackBuffer(); UpdateFrameCount(); } //---------------------------------------------------------------------------- bool BumpMaps::OnKeyDown(unsigned char ucKey, int iX, int iY) { if( SEWindowApplication3::OnKeyDown(ucKey, iX, iY) ) { return true; } if( ucKey == 'w' || ucKey == 'W' ) { m_spWireframe->Enabled = !m_spWireframe->Enabled; return true; } switch( ucKey ) { case 's': case 'S': TestStreaming(m_spScene, 128, 128, 640, 480, "BumpMaps.seof"); return true; } return false; } //---------------------------------------------------------------------------- void BumpMaps::CreateScene() { m_spScene = SE_NEW SENode; m_spWireframe = SE_NEW SEWireframeState; m_spScene->AttachGlobalState(m_spWireframe); CreateModels(); CreateLights(); m_spModelRoot->AttachLight(m_spLight0); m_spScene->AttachChild(m_spLight0Node); m_spScene->AttachChild(m_spModelRoot); m_spScene->UpdateGS(); m_spScene->UpdateRS(); } //---------------------------------------------------------------------------- void BumpMaps::CreateLights() { // Create light0(point light). m_spLight0 = SE_NEW SELight(SELight::LT_POINT); m_spLight0->Ambient = m_Light0Color*0.5f; m_spLight0->Diffuse = m_Light0Color; m_spLight0->Specular = m_Light0Color*0.5f; m_spLight0->Linear = 0.02f; m_spLight0->Quadratic = 0.02f; // Create light0's node. m_spLight0Node = SE_NEW SELightNode(m_spLight0); m_spLight0Node->Local.SetTranslate(SEVector3f(0.0f, m_fLight0Height, 0.0f)); // Create a sphere to represent the light0's source. SEAttributes tempAttr; tempAttr.SetPositionChannels(3); tempAttr.SetColorChannels(0, 3); float fRadius = 0.2f; SETriMesh* pPLightSphere = SEStandardMesh(tempAttr).Sphere(8, 8, fRadius); m_spLight0Node->AttachChild(pPLightSphere); SEVertexBuffer* pVBuffer = pPLightSphere->VBuffer; int iVCount = pVBuffer->GetVertexCount(); for( int i = 0; i < iVCount; i++ ) { pVBuffer->Color3(0, i) = m_Light0Color; } SEVertexColor3Effect* pLightSphereEffect = SE_NEW SEVertexColor3Effect; pPLightSphere->AttachEffect(pLightSphereEffect); } //---------------------------------------------------------------------------- void BumpMaps::CreateModels() { // polished gold. SEMaterialState* pGoldMaterial = SE_NEW SEMaterialState; pGoldMaterial->Ambient = SEColorRGB(0.24725f, 0.2245f, 0.0645f); pGoldMaterial->Diffuse = SEColorRGB(0.34615f, 0.3143f, 0.0903f); pGoldMaterial->Specular = SEColorRGB(0.797357f, 0.723991f, 0.208006f); pGoldMaterial->Shininess = 83.2f; // polished red. SEMaterialState* pRedMaterial = SE_NEW SEMaterialState; pRedMaterial->Ambient = SEColorRGB(0.8f, 0.0f, 0.0f); pRedMaterial->Diffuse = SEColorRGB(0.8f, 0.0f, 0.0f); pRedMaterial->Specular = SEColorRGB(1.0f, 1.0f, 1.0f); pRedMaterial->Shininess = 83.2f; // polished blue. SEMaterialState* pBlueMaterial = SE_NEW SEMaterialState; pBlueMaterial->Ambient = SEColorRGB(0.0f, 0.0f, 0.8f); pBlueMaterial->Diffuse = SEColorRGB(0.0f, 0.0f, 0.8f); pBlueMaterial->Specular = SEColorRGB(1.0f, 1.0f, 1.0f); pBlueMaterial->Shininess = 83.2f; // polished white. SEMaterialState* pWhiteMaterial = SE_NEW SEMaterialState; pWhiteMaterial->Ambient = SEColorRGB(0.2f, 0.2f, 0.2f); pWhiteMaterial->Diffuse = SEColorRGB(0.8f, 0.8f, 0.8f); pWhiteMaterial->Specular = SEColorRGB(1.0f, 1.0f, 1.0f); pWhiteMaterial->Shininess = 100.0f; // polished copper. SEMaterialState* pCopperMaterial = SE_NEW SEMaterialState; pCopperMaterial->Ambient = SEColorRGB(0.2295f, 0.08825f, 0.0275f); pCopperMaterial->Diffuse = SEColorRGB(0.5508f, 0.2118f, 0.066f); pCopperMaterial->Specular = SEColorRGB(0.580594f, 0.223257f, 0.0695701f); pCopperMaterial->Shininess = 51.2f; // We apply this texture effect as a post-lighting effect, // so the src output fragments should be modulated with dst buffer pixels. SETextureEffect* pTextureWoodEffect = SE_NEW SETextureEffect("wood512"); SEAlphaState* pAState = pTextureWoodEffect->GetBlending(0); pAState->SrcBlend = SEAlphaState::SBF_DST_COLOR; pAState->DstBlend = SEAlphaState::DBF_ZERO; // We apply this bump map effect as a lighting effect, // When UpdateRS is called, geometry object's default lighting effect will // be replaced by the bump map effect. SEBumpMapL1Effect* pBumpMapRockEffect = SE_NEW SEBumpMapL1Effect("rock", "rocknormal"); SENode* pRoot = SE_NEW SENode; SEAttributes tempAttr; tempAttr.SetPositionChannels(3); tempAttr.SetNormalChannels(3); tempAttr.SetTCoordChannels(0, 2); #if defined(SE_USING_OES2) SEGeometry::GeometryLightingMode eLMode = SEGeometry::GLM_PIPELINE_VERTEX; #else SEGeometry::GeometryLightingMode eLMode = SEGeometry::GLM_PIPELINE_PIXEL; #endif float fExtend = 8.0f; SEStandardMesh tempSM(tempAttr); // floor. SETriMesh* pMesh = tempSM.Rectangle(4, 4, fExtend, fExtend); pMesh->LightingMode = eLMode; pMesh->AttachGlobalState(pWhiteMaterial); pMesh->AttachEffect(pTextureWoodEffect); pMesh->GenerateNormals(); pMesh->GenerateTangents(0, 1, 2); SEMatrix3f mat3fRot; mat3fRot.FromEulerAnglesXYZ(SEMathf::PI/2.0f, 0.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pRoot->AttachChild(pMesh); // far wall. pMesh = SE_NEW SETriMesh(pMesh->VBuffer, pMesh->IBuffer); pMesh->LightingMode = SEGeometry::GLM_USER; pMesh->AttachGlobalState(pWhiteMaterial); pMesh->AttachEffect(pBumpMapRockEffect); pMesh->Local.SetTranslate(SEVector3f(0.0f, fExtend, fExtend)); pRoot->AttachChild(pMesh); // left wall. pMesh = SE_NEW SETriMesh(pMesh->VBuffer, pMesh->IBuffer); pMesh->LightingMode = SEGeometry::GLM_USER; pMesh->AttachGlobalState(pWhiteMaterial); pMesh->AttachEffect(pBumpMapRockEffect); mat3fRot.FromEulerAnglesXYZ(0.0f, -SEMathf::PI/2.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pMesh->Local.SetTranslate(SEVector3f(-fExtend, fExtend, 0.0f)); pRoot->AttachChild(pMesh); // right wall. pMesh = SE_NEW SETriMesh(pMesh->VBuffer, pMesh->IBuffer); pMesh->LightingMode = SEGeometry::GLM_USER; pMesh->AttachGlobalState(pWhiteMaterial); pMesh->AttachEffect(pBumpMapRockEffect); mat3fRot.FromEulerAnglesXYZ(0.0f, SEMathf::PI/2.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pMesh->Local.SetTranslate(SEVector3f(fExtend, fExtend, 0.0f)); pRoot->AttachChild(pMesh); // sphere. pMesh = tempSM.Sphere(32, 32, 1.0f); pMesh->LightingMode = eLMode; pMesh->AttachGlobalState(pGoldMaterial); pMesh->GenerateNormals(); pMesh->Local.SetTranslate(SEVector3f(0.0f, 1.0f, 0.0f)); pRoot->AttachChild(pMesh); // cylinder. pMesh = tempSM.Cylinder(8, 32, 1.0f, 2.0f, false); pMesh->LightingMode = eLMode; pMesh->AttachGlobalState(pRedMaterial); pMesh->GenerateNormals(); mat3fRot.FromEulerAnglesXYZ(SEMathf::PI/2.0f, 0.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pMesh->Local.SetTranslate(SEVector3f(2.0f, 1.0f, 1.0f)); pRoot->AttachChild(pMesh); // box. pMesh = tempSM.Box(0.6f, 0.6f, 0.6f); pMesh->LightingMode = eLMode; pMesh->AttachGlobalState(pBlueMaterial); pMesh->GenerateNormals(); mat3fRot.FromEulerAnglesXYZ(0.0f, SEMathf::PI/3.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pMesh->Local.SetTranslate(SEVector3f(-1.6f, 0.6f, -1.0f)); pRoot->AttachChild(pMesh); // torus. pMesh = tempSM.Torus(32, 32, 1.0f, 0.2f); pMesh->LightingMode = eLMode; pMesh->AttachGlobalState(pCopperMaterial); pMesh->GenerateNormals(); mat3fRot.FromEulerAnglesXYZ(SEMathf::PI/2.0f, 0.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pMesh->Local.SetTranslate(SEVector3f(0.0f, 0.2f, 0.0f)); pRoot->AttachChild(pMesh); // tetrahedron. pMesh = tempSM.Tetrahedron(); pMesh->LightingMode = eLMode; pMesh->AttachGlobalState(pWhiteMaterial); pMesh->GenerateNormals(); mat3fRot.FromEulerAnglesXYZ(-SEMathf::PI/2.0f, 0.0f, 0.0f); pMesh->Local.SetRotate(mat3fRot); pMesh->Local.SetTranslate(SEVector3f(1.8f, 1.0f/3.0f, -0.8f)); pRoot->AttachChild(pMesh); m_spModelRoot = pRoot; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 370 ] ] ]
3533fb480754182e53926b5e6237423a37bd588f
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/coreplugin/generalsettings.h
8f8d7265a47474a84ce6ddcb46cff170915d1e18
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
h
/** ****************************************************************************** * * @file generalsettings.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * Parts by Nokia Corporation ([email protected]) Copyright (C) 2009. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup CorePlugin Core Plugin * @{ * @brief The Core GCS plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef GENERALSETTINGS_H #define GENERALSETTINGS_H #include <coreplugin/dialogs/ioptionspage.h> #include <QtCore/QPointer> #include <QtGui/QWidget> namespace Core { namespace Internal { namespace Ui { class GeneralSettings; } class GeneralSettings : public IOptionsPage { Q_OBJECT public: GeneralSettings(); QString id() const; QString trName() const; QString category() const; QString trCategory() const; QWidget* createPage(QWidget *parent); void apply(); void finish(); private slots: void resetInterfaceColor(); void resetExternalEditor(); void showHelpForExternalEditor(); #ifdef Q_OS_UNIX void resetTerminal(); #endif private: Ui::GeneralSettings *m_page; QPointer<QWidget> m_dialog; }; } // namespace Internal } // namespace Core #endif // GENERALSETTINGS_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 74 ] ] ]
83de8d913721d3cfc5c092082b709ab380e222ef
f0da2c3ab8426f8bcdd8c3625c805a25f04aa89d
/armagic/ARSceneNode.cpp
3f97d9bbee6932e63a30fa9df80ddea38631a54d
[]
no_license
sanyaade-augmented-reality/armagic
81e557978936c396333be0261e45d869da680e6d
eb5132d280685e2f8db4ae1f3fbe624b1876bf73
refs/heads/master
2016-09-06T17:12:20.458558
2010-07-06T22:57:18
2010-07-06T22:57:18
34,191,493
0
0
null
null
null
null
UTF-8
C++
false
false
1,029
cpp
#include "ARSceneNode.h" using namespace irr::core; ARSceneNode::ARSceneNode(irr::IrrlichtDevice* device, const std::string& patt, const std::string& model, const std::string& texture, const float scale) { device_ = device; driver_ = device_->getVideoDriver(); smgr_ = device_->getSceneManager(); // Node node_ = smgr_->addAnimatedMeshSceneNode(smgr_->getMesh(model.c_str())); node_->setMaterialTexture(0, driver_->getTexture(texture.c_str())); node_->setRotation(vector3df(0,180,0)); node_->setMaterialFlag(irr::video::EMF_LIGHTING, false); node_->setAnimationSpeed(15); node_->setScale(vector3df(scale, scale, scale)); // Pattern pattId_ = arLoadPatt(patt.c_str()); } ARSceneNode::ARSceneNode(irr::IrrlichtDevice* device, const std::string& patt, irr::scene::IAnimatedMeshSceneNode* node) { driver_ = device->getVideoDriver(); smgr_ = device->getSceneManager(); node_ = node; pattId_ = arLoadPatt(patt.c_str()); } ARSceneNode::~ARSceneNode() { delete node_; }
[ "leochatain@22892e45-cd4f-0d29-0166-6a0decb81ae3" ]
[ [ [ 1, 35 ] ] ]
b2ee8e90eabdafcbbe00c57659f2e34c554b9b71
753fbd0173d85d6fdd7a6b406c5ae55f4215aa70
/NativeDemo/main.cpp
7f6852dd2778054ff8ba5c35affc9a6f63665aa2
[]
no_license
MetaCipher/simplefontengineopengl
34ebf4297c4dc7d326ff53aa3c73b261dbf8442b
dccde5372a449127da5cad4061dd229bcbb8a2ef
refs/heads/master
2021-01-22T09:54:53.922836
2007-11-10T18:58:42
2007-11-10T18:58:42
32,318,135
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include "Helper.hpp" #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:Demo") int Demo() { if(OnInit() == false) { return -1; } SDL_Event Event; while(Running) { while(SDL_PollEvent(&Event)) { OnEvent(&Event); } OnRender(); } FontEngine.OnCleanup(); SDL_Quit(); return 1; }
[ "farris.shane@7c90bf9e-413d-0410-a83f-3989eb8f22bf" ]
[ [ [ 1, 26 ] ] ]
6c95cb23e21bc8fad8620748bf2036d8204349c3
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/Constraint/Chain/Powered/hkpPoweredChainData.h
ab350d65965dfe7c38b3e45adbcaab28c57dfe66
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,471
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_POWERED_CHAIN_H #define HK_DYNAMICS2_POWERED_CHAIN_H #include <Physics/ConstraintSolver/Solve/hkpSolverResults.h> #include <Physics/ConstraintSolver/Constraint/Atom/hkpConstraintAtom.h> #include <Physics/Dynamics/Constraint/Chain/hkpConstraintChainData.h> #include <Physics/Dynamics/Action/hkpArrayAction.h> /// hkPowereChainData connects a series of bodies by 6d constraints. /// /// The powered chain is essentially composed of a hkpBallSocketChainData with angular motors added on top of it. /// /// hkpPoweredChainData is suited to the accurate simulation of character limbs. /// This constraints also allows for motors with a torque limit to model real human muscles. class hkpPoweredChainData : public hkpConstraintChainData { public: HK_DECLARE_REFLECTION(); HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CONSTRAINT); hkpPoweredChainData(); ~hkpPoweredChainData(); /// Not implemented. Returns always true. hkBool isValid() const { return true; } /// Get type from this constraint. virtual int getType() const; /// Returns the number of stored constraint infos. virtual int getNumConstraintInfos() { return m_infos.getSize(); } /// Adds a constraint info to the chain. /// \param pivotInA Pivot point in bodyA's local space. /// \param pivotInB Pivot point in bodyB's local space. /// \param aTc Relative orientation of the two bodies to be enforced. Specifies orientation of bodyB reference direction in relation to bodyA's space. /// \param bTc Relative orientation of the motors' space. Specifies orientation of the motors in bodyB's space. /// \param switchBodies When set the link is 'reversed' and treates bodyB as bodyA and the other way around. /// \param motor Motor that is to be used by the constraints. The motor specifies the maximum forces exerted at the constraint, and /// error correction parameters. void addConstraintInfoInBodySpace(const hkVector4& pivotInA, const hkVector4& pivotInB, const hkQuaternion& aTc, class hkpConstraintMotor* xMotor, class hkpConstraintMotor* yMotor, class hkpConstraintMotor* zMotor); /// This is disables processing of a motor in a chain. An excluded motor is always processed by the iterative solver before other constraints in the chain. static void HK_CALL enableMotor(class hkpConstraintChainInstance* instance, int constraintIndex, int motorIndex); /// This is re-enables processing of a motor in a chain. Initially all motors are enabled. static void HK_CALL disableMotor(class hkpConstraintChainInstance* instance, int constraintIndex, int motorIndex); public: struct Runtime { // Stores hkpSolverResults [6 * m_infos.getSize()] // hkp3dAngularMotorSolverInfo::Status [m_infos.getSize()] // flags for angular constraints // hkQuaternion [m_infos.getSize()] // motor's runtime data }; inline const Runtime* getRuntime( hkpConstraintRuntime* runtime ) { return reinterpret_cast<Runtime*>(runtime); } inline hkpSolverResults* getSolverResults(hkpConstraintRuntime* runtime) { return reinterpret_cast<hkpSolverResults*>( runtime ); } // assuming we always want solver results // -- other wise swap the order of solverResults and externalRuntimeData inline hkp3dAngularMotorSolverInfo::Status* getConstraintFlags(hkpConstraintRuntime* runtime) { return reinterpret_cast<hkp3dAngularMotorSolverInfo::Status*>( hkAddByteOffset(runtime, m_infos.getSize() * 6 * sizeof(hkpSolverResults) )); } inline hkReal* getMotorRuntimeQuaternions( hkpConstraintRuntime* runtime) { return reinterpret_cast<hkReal*>( hkAddByteOffset( getConstraintFlags(runtime), HK_NEXT_MULTIPLE_OF(4, m_infos.getSize() * sizeof(hkp3dAngularMotorSolverInfo::Status)) ) ); } public: // // Internal functions // /// Interface implementation. virtual void buildJacobian( const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ); /// Interface implementation. virtual void getConstraintInfo( hkpConstraintData::ConstraintInfo& infoOut ) const; /// Interface implementation. virtual void getRuntimeInfo( hkBool wantRuntime, hkpConstraintData::RuntimeInfo& infoOut ) const; public: /// Serialization ctor. hkpPoweredChainData(hkFinishLoadedObjectFlag f); public: struct hkpBridgeAtoms m_atoms; struct ConstraintInfo { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpPoweredChainData::ConstraintInfo ); HK_DECLARE_REFLECTION(); /// Constraint's pivot point in bodyA's space. hkVector4 m_pivotInA; /// Constraint's pivot point in bodyB's space. hkVector4 m_pivotInB; /// Relative orientation of the two bodies to be enforced. Specifies orientation of bodyB's reference direction in relation to bodyA's space. hkQuaternion m_aTc; /// Specifies the reference frame of the constraint in the bodyB's space (or bodyA's space when m_switchBodies == true). hkQuaternion m_bTc; /// Pointers to motors for the angular constraints. // Those cannot be HK_NULL because we take tau/damping from them. class hkpConstraintMotor* m_motors[3]; /// When set to true, it switches the roles of bodyA and bodyB: /// The target m_aTb quaternion is interpreted as m_bTa; the constraint space is aligned to the body A instead of body B. /// Note that the pivot vectors are not swapped. hkBool m_switchBodies; }; /// Constraint infos for the chain's constraints. hkArray<struct ConstraintInfo> m_infos; /// Solver tau, this overrides the global value from hkpSolverInfo when processing the ball-socket part of the constraint. /// The angular parts use the tau/dumping values from the motors. hkReal m_tau; /// Solver damping, this overrides the global value from hkpSolverInfo. /// The angular parts use the tau/dumping values from the motors. hkReal m_damping; /// Constraint force mixing parameter. /// /// Adding this value makes the constraint softer and it behaves in a spring-like manner. /// This is achieved by adding this value to the diagonal of the constraint matrix for the linear velocity equations. /// /// Should be zero or tiny, e.g. a fraction of HK_REAL_EPSILON. When this value is zero, then some chain configurations /// may result in a division by zero when solving. hkReal m_cfmLinAdd; //+default(0.1f*1.19209290e-07f) /// Constraint force mixing parameter, See m_cfmLinAdd for more details. /// /// Multiplication factor for the diagonal value of the constraint matrix for the linear velocity equations. /// This parameter should be equal or greater than 1.0f. For visible effect try the value of 1.5f. You might set this value to as high as 10.0f. /// Note that in chains, you'd usually leave this parameter at 1.0f (as you rearely want to affect the ball-and-socket part of the chain) and /// increase the angular-part cfm instead. hkReal m_cfmLinMul; //+default(1.0f) /// Constraint force mixing parameter, see m_cfmLinAdd for more details. /// /// Should be zero or tiny, e.g. a fraction of HK_REAL_EPSILON. When this value is zero, then some chain configurations /// may result in a division by zero when solving. hkReal m_cfmAngAdd; //+default(0.1f*1.19209290e-07F) /// Constraint force mixing parameter, see m_cfmLinAdd for more details. /// /// Multiplication factor for the diagonal value of the constraint matrix for the angular velocity equations. /// This parameter should be equal or greater than 1.0f. For visible effect try the value of 1.5f. You might set this value to as high as 10.0f. hkReal m_cfmAngMul; //+default(1.0f) /// Specifies the maximum distance error in constraints allowed before the stabilization algorithm kicks in. /// The algorithm eliminates explosions in may cases, but due to its nature it yields incorrect results in certain use cases. /// It is disabled by default. hkReal m_maxErrorDistance; }; #endif // HK_DYNAMICS2_POWERED_CHAIN_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 207 ] ] ]
2b701d99cb50167fed69f211b39ae7f6c3a63350
c1c3866586c56ec921cd8c9a690e88ac471adfc8
/Practise_2005/BitOperation/stdafx.cpp
abdae6e3379fb13b1a64308f162b8ba334dfd87a
[]
no_license
rtmpnewbie/lai3d
0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f
b44c9edfb81fde2b40e180a651793fec7d0e617d
refs/heads/master
2021-01-10T04:29:07.463289
2011-03-22T17:51:24
2011-03-22T17:51:24
36,842,700
1
0
null
null
null
null
GB18030
C++
false
false
272
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // BitOperation.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5" ]
[ [ [ 1, 8 ] ] ]
5e4baf9d304ca1bea7657e44f27171736fc8fed9
928b250a42ffbe1d1c1009b4af7fd3f6a1f46266
/forlijia/forlijia/forlijia/FilterAddress.h
9acbf97369affccc0f497a248725c557b55f82da
[]
no_license
jimcoly/comyitian
81044cc6e5d06613e1f2bda8b658457e8337ab8f
6f70e202907be1071d3310bfe1441567ebffed1e
refs/heads/master
2020-05-31T17:54:26.448254
2011-09-01T07:28:07
2011-09-01T07:28:07
33,866,360
0
0
null
null
null
null
UTF-8
C++
false
false
343
h
#include "filterwords.h" #pragma once class FilterAddressHeader { public: FilterAddressHeader(void); ~FilterAddressHeader(void); public: bool process(std::wstring &str); private: FilterWords *m_shengFilter; FilterWords *m_shiFilter; FilterWords *m_quFilter; FilterWords *m_xianFilter; FilterWords *m_zhenFilter; };
[ "sdy63420@3919fc08-f352-11de-9907-777483041811" ]
[ [ [ 1, 18 ] ] ]
6244c195ae7e511ee4675b25397eb86340cb609d
30898d899aa49d5801dab4f0df19fca18a2d4d02
/yltk/yltkDataTimeStamp.h
18c816eccc542f8df0c94e48dc6f41885f6c93e3
[]
no_license
jackyko1991/vtkpythonext
c278987c7c61f7e610eec277ca3c9e42df097fa5
6d20ce2071581064616064a36243646a96e4c75e
refs/heads/master
2021-01-10T19:32:45.869634
2011-03-20T03:15:55
2011-03-20T03:15:55
40,592,349
2
1
null
null
null
null
UTF-8
C++
false
false
4,403
h
#ifndef __yltkDataTimeStamp_h #define __yltkDataTimeStamp_h #include <iostream> #include "yltkRealTimeClock.h" namespace yltk{ /** \class DataTimeStamp * \brief DataTimeStamp provides periods of validity for data. * * A time stamp consists of two time values. They indicate respectively when a * particular data object was acquired and when its data will no longer be * valid. The purpose of the time stamp is to make sure that at any given * moment the toolkit is only managing information whose validity has not * expired. For example, the information of position for a tracked surgical * instrument will be valid from the moment it was acquired until a new data is * made available. The acquisition rate of a tracker will make possible to * define an expiration time for the position information associated with that * particular surgical instrument. * * \warning Clock precision is unfortunately platform-dependent. It is known * that Unix systems will provide time resolution of fractions of milliseconds, * while Microsoft Windows will only provide milliseconds. Users must be aware * of the particular capabilities of the platform they are using for running * the software. * * \warning DataTimeStamp are a mechanism for holding relative time periods. They * are not reliable as a mechanism for absolute time synchronization. For * example, they can not be used for networking synchronization or even * multi-machine communications. Times will only be valid inside * the current machine, and probably the current process. * * */ class DataTimeStamp { public: typedef double TimePeriodType; /** Define the longest time period on the machine */ static TimePeriodType GetLongestPossibleTime(); /** Get the zero time period on the machine */ static TimePeriodType GetZeroValue(); /** Compute the intersection of two time stamps */ static DataTimeStamp ComputeOverlap( DataTimeStamp t1, DataTimeStamp t2 ); /** Constructor and destructor */ DataTimeStamp(); virtual ~DataTimeStamp(); /** Copy one time stamp into another */ const DataTimeStamp & operator=( const DataTimeStamp & inputTimeStamp ); /** This method sets both the Start time and the Expiration time of the * TimeStamp. The StartTime is set to the current time value as returned by * the function clock(). The ExpirationTime is set to the StartTime plus the * number of millisecondsToExpire argument provided by the user */ void SetStartTimeNowAndExpireAfter( TimePeriodType millisecondsToExpire); /** Returns the time in milliseconds at which this stamp started to be valid. * This is the time at which the SetStartTimeNowAndExpireAfter() was invoked * last time. */ TimePeriodType GetStartTime() const; /** Returns the time in milliseconds at which this stamp will expire. This * time is computed when the SetStartTimeNowAndExpireAfter() method is * invoked. The ExpirationTime is equal to the StartTime plus the value of * millisecondsToExpire provided as argument to that method. */ TimePeriodType GetExpirationTime() const; /** This method returns 'true' is the current TimeStamp is still valid at the * time in milliseconds indicated in the argument. The purpose of this method * is to evaluate what data objects are usable at a particular time snapshot. * For example, this method will be used for selecting the display mode of * objects that are intended to be presented in a scene rendering at the time * specified in the argument. * */ bool IsValidAtTime( TimePeriodType milliseconds ) const; /** This method returns 'true' is the current TimeStamp is valid at the * time when this method is called. * */ bool IsValidNow( ) const; void Print(std::ostream& os, yltk::Indent indent) const; protected: void PrintHeader(std::ostream& os, yltk::Indent indent) const; void PrintTrailer(std::ostream& yltkNotUsed(os), yltk::Indent yltkNotUsed(indent)) const; /** Print the object information in a stream. */ virtual void PrintSelf( std::ostream& os, yltk::Indent indent ) const; private: TimePeriodType m_StartTime; TimePeriodType m_ExpirationTime; }; std::ostream& operator<<(std::ostream& os, const DataTimeStamp& o); } #endif
[ "summit.chocice@6ba1a03e-a7e1-11de-9ca8-173d21a9ba08" ]
[ [ [ 1, 116 ] ] ]
556d1c899e3af6d485c6b838711bf1ed228767cf
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-wx/Plugins/WebBrowser/webconnect/nsptr.h
92a6a706391b445554a6f7da0ca28953a8174e93
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,115
h
/////////////////////////////////////////////////////////////////////////////// // Name: nsptr.h // Purpose: wxwebconnect: embedded web browser control library // Author: Benjamin I. Williams // Modified by: // Created: 2006-10-08 // RCS-ID: // Copyright: (C) Copyright 2006-2009, Kirix Corporation, All Rights Reserved. // Licence: wxWindows Library Licence, Version 3.1 /////////////////////////////////////////////////////////////////////////////// #ifndef __WXWEBCONNECT_NSPTR_H #define __WXWEBCONNECT_NSPTR_H class ns_smartptr_unknown { public: virtual nsresult qi(const nsIID& iid, void** result) const = 0; }; template <class T> class ns_smartptr : public ns_smartptr_unknown { public: T* p; public: ns_smartptr() { p = 0; } ns_smartptr(T* const& _p) { p = _p; if (p) { p->AddRef(); } } ns_smartptr(const ns_smartptr<T>& c) { p = c.p; if (p) { p->AddRef(); } } ns_smartptr(const ns_smartptr_unknown& u) { u.qi(T::GetIID(), (void**)&p); } ~ns_smartptr() { if (p) { p->Release(); } } operator nsISupports**() const { return static_cast<nsISupports*>(p); } operator T*() const { return p; } T* operator->() const { return p; } bool operator!() const { return (p == 0); } operator bool() const { return (p != 0); } bool operator()() const { return (p != 0); } ns_smartptr<T>& operator=(const ns_smartptr<T>& c) { if (p) { p->Release(); } p = c.p; if (p) { p->AddRef(); } return *this; } ns_smartptr<T>& operator=(T* _p) { if (p) { p->Release(); } p = _p; if (p) { p->AddRef(); } return *this; } ns_smartptr<T>& operator=(const ns_smartptr_unknown& u) { if (p) { p->Release(); p = 0; } u.qi(T::GetIID(), (void**)&p); return *this; } bool empty() const { return (p == 0); } void clear() { if (p) { p->Release(); } p = 0; } nsresult qi(const nsIID& iid, void** result) const { if (!p) { *result = 0; return NS_ERROR_NO_INTERFACE; } return p->QueryInterface(iid, result); } }; class nsRequestInterface : public ns_smartptr_unknown { public: nsRequestInterface(nsISupports* p) { ptr.p = p; p->AddRef(); } nsRequestInterface(ns_smartptr_unknown& u) { static nsIID nsISupportsIID = NS_ISUPPORTS_IID; u.qi(nsISupportsIID, (void**)&ptr.p); } nsresult qi(const nsIID& iid, void** result) const { if (ptr) { ns_smartptr<nsIInterfaceRequestor> factory_ptr = ptr; if (!factory_ptr) { *result = 0; return NS_ERROR_NO_INTERFACE; } return factory_ptr->GetInterface(iid, result); } return NS_ERROR_NULL_POINTER; } public: ns_smartptr<nsISupports> ptr; }; class nsToSmart : public ns_smartptr_unknown { public: nsToSmart(nsISupports* _ptr) : ptr(_ptr) { } nsresult qi(const nsIID& iid, void** result) const { if (!ptr) return NS_ERROR_NULL_POINTER; return ptr->QueryInterface(iid, result); } public: nsISupports* ptr; }; #endif
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 233 ] ] ]
9ba5396de45410f652cb60718ff17ff01c9cf4e8
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Graphics/WmlImage.cpp
e1eefd7792189eee01060a9fbd98c3ad57b69fdb
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
12,694
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlImage.h" using namespace Wml; using namespace std; WmlImplementRTTI(Image,Object); WmlImplementStream(Image); int Image::ms_aiBytesPerPixel[Image::IT_QUANTITY] = { 2, 3, 2, 4 }; // support for sharing images map<string,Image*>* Image::ms_pkImages = NULL; namespace Wml { class _ImageInitTerm { public: _ImageInitTerm () { Image::ms_pkImages = new map<string,Image*>; } ~_ImageInitTerm () { Image::ms_pkImages->clear(); delete Image::ms_pkImages; Image::ms_pkImages = NULL; } }; } static _ImageInitTerm _forceWmlImageInitTerm; //---------------------------------------------------------------------------- Image::Image (Type eType, int iWidth, int iHeight, unsigned char* aucData, const char* acImageName, bool bRequirePowerOfTwo) { if ( bRequirePowerOfTwo ) { assert( System::IsPowerOfTwo(iWidth) && System::IsPowerOfTwo(iHeight) ); } m_eType = eType; m_iWidth = iWidth; m_iHeight = iHeight; m_iQuantity = iWidth*iHeight; m_aucData = aucData; if ( acImageName ) { SetName(acImageName); } else { // Generate the unique image name. char acFilename[32]; sprintf(acFilename,"image%u.mif",m_uiID); SetName(acFilename); } } //---------------------------------------------------------------------------- Image::Image () { SetDefault(); } //---------------------------------------------------------------------------- Image::~Image () { // remove image from map SetName(0); delete[] m_aucData; } //---------------------------------------------------------------------------- void Image::SetDefault () { m_eType = IT_QUANTITY; m_iWidth = 0; m_iHeight = 0; m_iQuantity = 0; m_aucData = NULL; } //---------------------------------------------------------------------------- void Image::SetName (const char* acFilename) { if ( m_acName != acFilename ) // yes, this is intended to be ptr compare { if ( m_acName ) { // Image is in the map, remove the map entry. RemoveAt(m_acName); } if ( acFilename ) { // Add image to map with filename. Object::SetName(acFilename); SetAt(acFilename,this); } } } //---------------------------------------------------------------------------- Image* Image::Load (const char* acFilename, bool bRequirePowerOfTwo) { if ( !acFilename ) return 0; // Determine if image is already in memory and can be shared. Image* pkImage = GetAt(acFilename); if ( pkImage ) return pkImage; FILE* pkFile = fopen(acFilename,"rb"); if ( !pkFile ) return 0; int iType, iWidth, iHeight; int iScanned = fscanf(pkFile,"Magic3D Image File#%d#%d#%d#",&iType, &iWidth,&iHeight); if ( iScanned == EOF || iScanned != 3 || iType >= IT_QUANTITY || iWidth == 0 || iHeight == 0 ) { fclose(pkFile); return 0; } Type eType = (Type) iType; int iQuantity = iWidth*iHeight; int iSize = ms_aiBytesPerPixel[eType]*iQuantity; unsigned char* aucData = new unsigned char[iSize]; int iRead = (int)fread(aucData,sizeof(unsigned char),iSize,pkFile); if ( iRead != iSize ) { delete[] aucData; fclose(pkFile); return 0; } fclose(pkFile); if ( bRequirePowerOfTwo ) { if ( !System::IsPowerOfTwo(iWidth) || !System::IsPowerOfTwo(iHeight) ) { pkFile = fopen("ImageNotPowerOfTwo.txt","wt"); assert( pkFile ); fprintf(pkFile,"An image dimension is not power of two."); fprintf(pkFile," Width = %d Height = %d\n",iWidth,iHeight); fclose(pkFile); } } return new Image(eType,iWidth,iHeight,aucData,acFilename, bRequirePowerOfTwo); } //---------------------------------------------------------------------------- bool Image::Save (const char* acFilename) { if ( !acFilename ) return false; FILE* pkFile = fopen(acFilename,"wb"); if ( !pkFile ) return false; // write header char acHeader[64]; sprintf(acHeader,"Magic3D Image File#%d#%d#%d#",(int)m_eType,m_iWidth, m_iHeight); fwrite(acHeader,sizeof(char),strlen(acHeader),pkFile); // write data int iSize = ms_aiBytesPerPixel[m_eType]*m_iQuantity; fwrite(m_aucData,sizeof(unsigned char),iSize,pkFile); fclose(pkFile); return true; } //---------------------------------------------------------------------------- bool Image::SetAt (const char* acName, Image* pkImage) { if ( ms_pkImages ) { pair<map<string,Image*>::iterator,bool> kResult = ms_pkImages->insert(make_pair(string(acName),pkImage)); return kResult.second; } return false; } //---------------------------------------------------------------------------- Image* Image::GetAt (const char* acName) { if ( ms_pkImages ) { map<string,Image*>::iterator kIter = ms_pkImages->find(string(acName)); if ( kIter != ms_pkImages->end() ) return kIter->second; } return NULL; } //---------------------------------------------------------------------------- bool Image::RemoveAt (const char* acName) { if ( ms_pkImages ) { ms_pkImages->erase(string(acName)); return true; } return false; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // streaming //---------------------------------------------------------------------------- Object* Image::Factory (Stream& rkStream) { // NOTE. The structure of this factory is slightly different than the // other classes. The difference allows sharing of images. Currently // Image is top-level (no classes derived from it). Image has no // Object-derived members, so pkLink normally would have one element, // the object itself. If the to-be-loaded image already exists in the // image map, then pkLink has that image object replace pkObject. Image* pkObject = new Image; Stream::Link* pkLink = new Stream::Link(pkObject); pkObject->Load(rkStream,pkLink); if ( pkObject != pkLink->GetObject() ) { // Image is already in memory, just share it. delete pkObject; pkObject = (Image*) pkLink->GetObject(); } return pkObject; } //---------------------------------------------------------------------------- void Image::Load (Stream& rkStream, Stream::Link* pkLink) { Object::Load(rkStream,pkLink); if ( GetName() ) { if ( System::FileExists(GetName()) ) { // File exists. Read the image from it. Image* pkImage = Load(GetName()); assert( pkImage ); // If fails, perhaps no read permission? pkLink->SetObject(pkImage); } else { // File does not exist. Rather than assert, I dump the error // to a log file. A likely problem is that GetName() is only a // partial pathname and the application has changed the working // directory. FILE* pkLog; if ( System::FileExists("ImageLoadFailed.txt") ) { // Log file was created earlier, just dump the error." pkLog = fopen("ImageLoadFailed.txt","at"); fprintf(pkLog,"%s\n",GetName()); } else { pkLog = fopen("ImageLoadFailed.txt","wt"); assert( pkLog ); fprintf(pkLog,"Image loading failed. A likely problem "); fprintf(pkLog,"is that the image name is only a\n"); fprintf(pkLog,"partial pathname and the application has "); fprintf(pkLog,"changed the working directory.\n"); fprintf(pkLog,"Failed loads:\n\n"); fprintf(pkLog,"%s\n",GetName()); } fclose(pkLog); SetDefault(); } return; } // native data StreamReadEnum(rkStream,m_eType); StreamRead(rkStream,m_iWidth); StreamRead(rkStream,m_iHeight); StreamRead(rkStream,m_iQuantity); StreamRead(rkStream,m_aucData); if ( m_aucData ) { int iBytes = ms_aiBytesPerPixel[m_eType]*m_iWidth*m_iHeight; m_aucData = new unsigned char[iBytes]; StreamRead(rkStream,m_aucData,iBytes); } } //---------------------------------------------------------------------------- void Image::Link (Stream& rkStream, Stream::Link* pkLink) { Object::Link(rkStream,pkLink); } //---------------------------------------------------------------------------- bool Image::Register (Stream& rkStream) { return Object::Register(rkStream); } //---------------------------------------------------------------------------- void Image::Save (Stream& rkStream) { Object::Save(rkStream); // If the image was loaded from a file, the filename was stored in the // Object name field. If the name field was set explicitly, then if ( GetName() ) { if ( !System::FileExists(GetName()) ) { // File does not exist. Write the image to it. bool bSaved = Save(GetName()); assert( bSaved ); // If fails, perhaps no write permission? } // else: File exists, assume it is this image. return; } // native data StreamWriteEnum(rkStream,m_eType); StreamWrite(rkStream,m_iWidth); StreamWrite(rkStream,m_iHeight); StreamWrite(rkStream,m_iQuantity); StreamWrite(rkStream,m_aucData); if ( m_aucData ) { int iBytes = ms_aiBytesPerPixel[m_eType]*m_iWidth*m_iHeight; StreamWrite(rkStream,m_aucData,iBytes); } } //---------------------------------------------------------------------------- StringTree* Image::SaveStrings () { StringTree* pkTree = new StringTree(4,0,1,0); // strings pkTree->SetString(0,MakeString(&ms_kRTTI,GetName())); switch ( m_eType ) { case IT_RGBA4444: pkTree->SetString(1,MakeString("type = RGBA4444")); break; case IT_RGB888: pkTree->SetString(1,MakeString("type = RGB888")); break; case IT_RGBA5551: pkTree->SetString(1,MakeString("type = RGBA5551")); break; case IT_RGBA8888: pkTree->SetString(1,MakeString("type = RGBA8888")); break; default: // IT_QUANTITY break; } pkTree->SetString(2,MakeString("width =",m_iWidth)); pkTree->SetString(3,MakeString("height =",m_iHeight)); // children pkTree->SetChild(0,Object::SaveStrings()); return pkTree; } //---------------------------------------------------------------------------- int Image::GetMemoryUsed () const { int iBaseSize = sizeof(Image) - sizeof(Object); int iDynaSize = m_iQuantity*sizeof(m_aucData[0]); int iTotalSize = iBaseSize + iDynaSize + Object::GetMemoryUsed(); return iTotalSize; } //---------------------------------------------------------------------------- int Image::GetDiskUsed () const { int iSize = Object::GetDiskUsed(); if ( GetName() ) { // image is stored externally from the scene graph return iSize; } iSize += StreamBytesEnum(m_eType) + sizeof(m_iWidth) + sizeof(m_iHeight) + sizeof(m_iQuantity); iSize += sizeof(m_aucData); if ( m_aucData ) { int iBytes = ms_aiBytesPerPixel[m_eType]*m_iWidth*m_iHeight; iSize += iBytes*sizeof(m_aucData[0]); } return iSize; } //----------------------------------------------------------------------------
[ [ [ 1, 427 ] ] ]
ad26dc2240242edaef27ea9594b2155f4f312092
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/CaseIle.cpp
fa3584c35aac33c19134872c3e4aff87955423aa
[]
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
252
cpp
/** *\file CaseIle.cpp *\brief File which contains the functions and code of the CaseIle class *\author Maxime HAVEZ *\author Gareth THIVEUX *\version 1.0 */ #include "CaseIle.h" CaseIle::CaseIle(){ _hauteur = 3; _accessible = false; }
[ "garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6", "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 7 ], [ 9, 14 ] ], [ [ 8, 8 ] ] ]
18cf295db75a71301133219199c71567de8c4b43
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/Xbox360/scrn.cpp
69a17eba1d23044f27fd22954fb08de9b4dcbd5a
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
3,564
cpp
// Screen Window // Simplify screen reinit routine by regret /* changelog: update 6: add fake fullscreen update 5: add scrnSwitchFull to switch fullscreen, scrnExit will not be called update 4: simplify enter/exit fullscreen routine update 3: do not delete screen in scrnInit update 2: add simpleReinitScrn update 1: source cleanup */ #include "burner.h" #include "cheat.h" #include "cartridge.h" #include "vid_directx_support.h" #include "InGameOptions.h" #ifndef NO_AUTOFIRE #include "autofire.h" #endif RECT SystemWorkArea = { 0, 0, 1280, 720 }; // Work area on the desktop int nWindowPosX = -1, nWindowPosY = -1; // Window position int bAutoPause = 0; int nSavestateSlot = 1; bool bShowOnTop = false; bool bFullscreenOnStart = false; bool bFakeFullscreen = false; static TCHAR* szClass = _T(APP_TITLE); // Window class name HWND hScrnWnd = NULL; // Handle to the screen window HWND hVideoWnd = NULL; // Handle to the video window static bool bMaximised; static int nPrevWidth, nPrevHeight; int nWindowSize = 0; static bool bDrag = false; static int nDragX, nDragY; static int nOldWindowX, nOldWindowY; static int nLeftButtonX, nLeftButtonY; extern void dx9SetTargets(); extern void simpleReinitScrn(const bool& reinitVid); extern void doResetDX9(); extern HXUIOBJ hInGameOptionsScene; //int nScrnVisibleOffset[4] = { 0, 0, 0, 0 }; // scrn visible offset bool useDialogs() { return false; } void setPauseModeScreen(bool bPause) { bRunPause = bPause; bAltPause = bPause; if (bPause) { audio.blank(); } else { GameInpCheckMouse(); } } void setPauseMode(bool bPause) { bRunPause = bPause; bAltPause = bPause; if (bPause) { audio.blank(); XUIMessage xuiMsg; InGameMenuStruct msgData; InGameMenuFirstFunc( &xuiMsg, &msgData, 1 ); XuiSendMessage( hInGameOptionsScene, &xuiMsg ); while (bRunPause) { pDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_STENCIL | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB( 255, 0, 0, 0 ), 1.0, 0 ); // Update XUI app.RunFrame(); // Render XUI app.Render(); // Update XUI Timers XuiTimersRun(); // Present the frame. pDevice->Present( NULL, NULL, NULL, NULL ); } } else { GameInpCheckMouse(); } simpleReinitScrn(true); } // Returns true if a VidInit is needed when the window is resized static inline bool vidInitNeeded() { if (nVidSelect == VID_D3D) { return true; } return false; } // Refresh the contents of the window when re-sizing it static inline void refreshWindow(bool bInitialise) { } // simply reinit screen, added by regret void simpleReinitScrn(const bool& reinitVid) { scrnSize(); // need for dx9 blitter if (reinitVid || vidInitNeeded()) { VidReinit(); } } bool bLoading = false; static int scrnRegister() { return 0; } int scrnTitle() { return 0; } int scrnSize() { return 0; } // Init the screen window (create it) int scrnInit() { return 0; } // Exit the screen window (destroy it) int scrnExit() { return 0; } // ==> switch fullscreen, added by regret int scrnSwitchFull() { return 0; } // fake fullscreen int scrnFakeFullscreen() { return 0; } // set fullscreen (for opengl) int scrnSetFull(const bool& full) { return 0; } // <== switch fullscreen void __cdecl scrnReinit() { simpleReinitScrn(true); }
[ [ [ 1, 208 ] ] ]
b644a2df5014ffecec2e2641a83158a8bc1b2613
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CLicenseProtocol.h
3918c57816ede4f99d3b75b44052c14fd57a9619
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
5,374
h
/* CLicenseProtocol.h Implementazione delle funzioni per il servizio delle licenze. Luca Piergentili, 02/06/00 [email protected] */ #ifndef _CLICENSEPROTOCOL_H #define _CLICENSEPROTOCOL_H 1 #include "typedef.h" #include <stdlib.h> #include "strcpyn.h" #include "CPop3.h" #include "CListenSock.h" #include "CConnectSock.h" #include "CLicenseService.h" // 0x8000 through 0xBFFF #define WM_LICENSEPROTOCOL WM_USER + 0x8000 + 1 struct SOCKETINFO { SOCKET socket; char ip[32]; }; class CListeningLicenseProtocolSocket; /* CLicenseListeningWnd Definisce la finestra a cui indirizzare i messaggi wsa ed il codice per l'elaborazione dei messaggi. I socket in collegamento (che generano i messaggi wsa) vengono inseriti in una lista ed associati ad un thread che si occupa dell'elaborazione (il thread si occupa di attivare il codice del protocollo delle licenze definito sotto da CLicenseProtocol). */ class CLicenseListeningWnd : public CFrameWnd { DECLARE_DYNCREATE(CLicenseListeningWnd) public: CLicenseListeningWnd(CListeningLicenseProtocolSocket* pSocket = NULL,CWnd* pMainWnd = NULL,UINT nWsa = (UINT)-1); virtual ~CLicenseListeningWnd() {} CWnd* GetListeningWnd (void) {return(this);} private: LONG OnLicense (UINT wParam,LONG lParam); HICON m_hIcon; CWnd* m_pMainWnd; UINT m_nWsa; SOCKETINFO m_SocketInfo; DECLARE_MESSAGE_MAP() }; /* CLicenseProtocol Deriva da CPop3 per la gestione del protocollo (POP3) e da CLicenseService per la gestione dei dati relativi al servizio delle licenze (accesso al database delle licenze). Implementa il servizio delle licenze derivandolo da quello relativo al protocollo (POP3) e duplicando le funzioni basiche per intercettare i comandi non gestiti dal protocollo originale (POP3) ed implementarli in proprio (accede ai dati derivando dalla classe per l'accesso al database). */ class CLicenseProtocol : public CPop3, public CLicenseService { public: CLicenseProtocol(const char* pDomain,const char* pMailpath,const char* pDatapath,const char* pLogpath) : CPop3(pDomain,pMailpath,pDatapath,pLogpath), CLicenseService(pDatapath) {} virtual ~CLicenseProtocol() {} // servizio virtual const char* StartService (CSock* pSocket); virtual void ResetService (CSock* pSocket = NULL); virtual const char* ParseCommand (POP3STATE& pop3state,const char* pCommand,int nLen); // utenti BOOLEAN CreateUser (const char* pCommand); BOOLEAN DeleteUser (const char* pCommand); BOOLEAN ValidateUser (const char* pCommand); BOOLEAN ChangeUserPass (const char* pCommand); // etichette const char* GetLabel (const char* pCommand); BOOLEAN PutLabel (const char* pCommand); BOOLEAN RemoveLabel (const char* pCommand); }; /* CConnectedLicenseProtocolSocket Classe per il socket in collegamento. La classe definisce l'oggetto usato per i socket che si collegano al socket in ascolto sul lato server (implementato tramite la CListeningLicenseProtocolSocket). Allo scopo deriva da CConnectSock per il socket in collegamento e da CLicenseProtocol per le operazioni che vengono svolte dal socket in collegamento. */ class CConnectedLicenseProtocolSocket : public CConnectSock, public CLicenseProtocol { public: CConnectedLicenseProtocolSocket(const char* pDomain,const char* pMailpath,const char* pDatapath,const char* pLogpath) : CLicenseProtocol(pDomain,pMailpath,pDatapath,pLogpath) {} virtual ~CConnectedLicenseProtocolSocket() {} }; /* CListeningLicenseProtocolSocket Classe per la gestione della lista dei socket in collegamento. La classe viene usata per creare l'oggetto in grado di gestire le connessioni TCP/IP sul lato server. Allo scopo deriva da CLicenseListeningWnd per la finestra/gestore dei messaggi wsa e da CListenSock per il socket in ascolto. */ class CListeningLicenseProtocolSocket : public CLicenseListeningWnd, public CListenSock { public: CListeningLicenseProtocolSocket(CWnd* pWnd,UINT nWsa,UINT nPort,const char* pDomain,const char* pMailpath,const char* pDatapath,const char* pLogpath) : CLicenseListeningWnd(this,pWnd,nWsa), CListenSock(CLicenseListeningWnd::GetListeningWnd()/*pWnd*/,WM_LICENSEPROTOCOL/*nWsa*/,nPort) { strcpyn(domain,pDomain,sizeof(domain)); strcpyn(mailpath,pMailpath,sizeof(mailpath)); strcpyn(datapath,pDatapath,sizeof(datapath)); if(pLogpath && *pLogpath) strcpyn(logpath,pLogpath,sizeof(logpath)); else memset(logpath,'\0',sizeof(logpath)); } virtual ~CListeningLicenseProtocolSocket(); // gestione degli elementi della lista CConnectedLicenseProtocolSocket* Insert(WORD); CConnectedLicenseProtocolSocket* FindSocket(SOCKET); CConnectedLicenseProtocolSocket* FindThread(DWORD); void Remove(SOCKET); BOOL PreDelete(ITERATOR iter) { delete ((CConnectedLicenseProtocolSocket*)iter->data); return(TRUE); } const char* Signature(void) {return("CListeningLicenseProtocolSocket");} int Size(void) {return(-1);} private: char domain[(HOSTNAME_SIZE*2) + 1]; // dominio POP3 char mailpath[_MAX_PATH + 1]; // pathname x mail char datapath[_MAX_PATH + 1]; // pathname x base dati char logpath[_MAX_PATH + 1]; // pathname x log unsigned long flags; // flags POP3 }; #endif // _CLICENSEPROTOCOL_H
[ [ [ 1, 157 ] ] ]
783669b7ed09c70c10edb83a226d38384f8afb4c
6563f129d9e39a4640b1b2e2cf82eb29fec13bb7
/taskbar.h
9529f430fafbd1a8d4f499b2d3b1463fefa49586
[]
no_license
n8wachT/win7shell
b19d516cfa3f0ce93d2051b5e0f185689753e055
e3218f46b6cec7d01bd5cbf22e72feb43ada9f60
refs/heads/master
2021-04-28T07:09:36.444272
2011-11-09T17:47:07
2011-11-09T17:47:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,073
h
#ifndef taskbar_h__ #define taskbar_h__ #include <Windows.h> #include <Shobjidl.h> #include <string> #include <vector> class iTaskBar { public: iTaskBar(); ~iTaskBar(); bool Reset(HWND WinampWnd); HRESULT SetImageList(HIMAGELIST ImageList); HRESULT ThumbBarUpdateButtons(std::vector<THUMBBUTTON>& buttons, bool first); void SetProgressState(TBPFLAG newstate); void SetIconOverlay(HICON icon, std::wstring text); void SetProgressValue(ULONGLONG completed, ULONGLONG total); void SetWindowAttr(bool enable, bool flip, bool peek); private: HWND mWinampWnd; TBPFLAG progressbarstate; ITaskbarList3* pTBL; }; inline void iTaskBar::SetProgressValue( ULONGLONG completed, ULONGLONG total ) { pTBL->SetProgressValue(mWinampWnd, completed, total); } inline void iTaskBar::SetProgressState( TBPFLAG newstate ) { if (newstate != progressbarstate) { pTBL->SetProgressState(mWinampWnd, newstate); progressbarstate = newstate; } } #endif // taskbar_h__
[ "[email protected]@ff8e3a26-89a2-11de-b505-999d5b087335" ]
[ [ [ 1, 44 ] ] ]
e96520c9faf7efc9f15adba02593cae69393d6f0
c1eae8224c4d3d380cc83ff6b218ba2a9df8d687
/Source Codes/MeshUI/MeshLib/BasicElement.h
d840ead83becefc96dcaa525f8b038b8e6ab8e92
[]
no_license
pizibing/noise-removal
15bad5c0fe1b3b5fb3f8b775040fc3dfeb48e49b
c087356bfa07305ce7ac6cce8745b1e676d6dc42
refs/heads/master
2016-09-06T17:40:15.754799
2010-03-05T06:47:59
2010-03-05T06:47:59
34,849,474
1
0
null
null
null
null
UTF-8
C++
false
false
6,419
h
/* ================== Library Information ================== */ // [Name] // MeshLib Library // // [Developer] // Xu Dong // State Key Lab of CAD&CG, Zhejiang University // // [Date] // 2005-08-05 // // [Goal] // A general, flexible, versatile and easy-to-use mesh library for research purpose. // Supporting arbitrary polygonal meshes as input, but with a // primary focus on triangle meshes. /* ================== File Information ================== */ // [Name] // BasicElement.h // // [Developer] // Xu Dong // State Key Lab of CAD&CG, Zhejiang University // // [Date] // 2005-08-05 // // [Goal] // Defining 2 kinds of basic elements and 3 kinds of auxiliary elements // 2 kinds of basic elements -- Edge & Face // 3 kinds of auxiliary elements -- Point & Line & Polygon #include "Macro.h" #include "BasicDataType.h" #pragma once #include <vector> using namespace std; /* ================== Basic Element - Mesh Edge ================== */ class Edge { private: VertexID v1, v2; public: Edge(VertexID v1 = -1, VertexID v2 = -1) { this->v1 = v1; this->v2 = v2; } void set(VertexID v1, VertexID v2) { this->v1 = v1; this->v2 = v2; } VertexID getV1() { return v1; } VertexID getV2() { return v2; } bool operator==(const Edge &edge) { if (edge.v1==v1 && edge.v2==v2) return true; if (edge.v1==v2 && edge.v2==v1) return true; return false; } void operator=(const Edge &edge) { v1=edge.v1; v2=edge.v2; } }; /* ================== Basic Element - Mesh Face ================== */ // This class is used for defining new faces. // The orientation of the vertices is: v1 v2 v3 .. vn class Face { private: vector<VertexID> v; public: // Constructor Face() { v.clear(); } Face(vector<VertexID>& fv) { set(fv); } // Initializer void set(vector<VertexID> fv) { v.clear(); v = fv; } // Method VertexID getV(size_t vNum) const { if (vNum>=v.size() || vNum<0) return -1; return v[vNum]; } size_t getVertexNum() const { return v.size(); } // Operator void operator =(const Face &face) { v.clear(); size_t nv = face.getVertexNum(); for (size_t i = 0; i < nv; ++ i) { v[i] = face.getV(i); } } bool operator ==(const Face &face) { size_t nv = face.getVertexNum(); if(nv != getVertexNum()) return false; for (size_t i = 0; i < nv; ++ i) { if (face.getV(i) != getV(i)) return false; } return true; } }; /* ================== Auxiliary Element - Point ================== */ class Point { private: Coord v; public: Point() {} Point(const Coord& coord) { for(int i = 0; i < 3; i ++) v[i] = coord[i]; } void setCoord(const Coord& coord) { for(int i = 0; i < 3; i ++) v[i] = coord[i]; } void setCoord(const Coord coord) { for(int i = 0; i < 3; i ++) v[i] = coord[i]; } void setCoord(const Coord* _coord) { if(_coord == NULL) return; for(int i = 0; i < 3; i ++) v[i] = (*_coord)[i]; } void getCoord(Coord& coord) { for(int i = 0; i < 3; i ++) coord[i] = v[i]; } void getCoord(Coord* _coord) { if(_coord == NULL) return; for(int i = 0; i < 3; i ++) (*_coord)[i] = v[i]; } }; /* ================== Auxiliary Element - Line ================== */ class Line { private: Coord coords[2]; public: Line() {} Line(const Coord coord1, const Coord coord2) { for (int i=0; i<3; i++) { coords[0][i] = coord1[i]; coords[1][i] = coord2[i]; } } void setCoords(const Coord& coord1, const Coord& coord2) { for(int i = 0; i < 3; i ++) { coords[0][i] = coord1[i]; coords[1][i] = coord2[i]; } } void setCoords(const Coord coord1, const Coord coord2) { for(int i = 0; i < 3; i ++) { coords[0][i] = coord1[i]; coords[1][i] = coord2[i]; } } void setCoords(const Coord* _coords) { if (_coords==NULL) return; for (int i=0; i<3; i++) { coords[0][i] = _coords[0][i]; coords[1][i] = _coords[1][i]; } } void getCoords(Coord& coord1, Coord& coord2) { for(int i = 0; i < 3; i ++) { coord1[i] = coords[0][i]; coord2[i] = coords[1][i]; } } void getCoords(Coord* coord1, Coord* coord2) { for(int i = 0; i < 3; i ++) { (*coord1)[i] = coords[0][i]; (*coord2)[i] = coords[1][i]; } } void getCoords(Coord* _coords) { if (_coords==NULL) return; for (int i=0; i<3; i++) { _coords[0][i] = coords[0][i]; _coords[1][i] = coords[1][i]; } } }; /* ================== Auxiliary Element - Polygon ================== */ class Polygon { private: Coord coords[3]; public: Polygon() {} Polygon(const Coord coord1, const Coord coord2, const Coord coord3) { for (int i=0; i<3; i++) { coords[0][i] = coord1[i]; coords[1][i] = coord2[i]; coords[2][i] = coord3[i]; } } void setCoords(const Coord& coord1, const Coord& coord2, const Coord& coord3) { for(int i = 0; i < 3; i ++) { coords[0][i] = coord1[i]; coords[1][i] = coord2[i]; coords[2][i] = coord3[i]; } } void setCoords(const Coord coord1, const Coord coord2, const Coord coord3) { for(int i = 0; i < 3; i ++) { coords[0][i] = coord1[i]; coords[1][i] = coord2[i]; coords[2][i] = coord3[i]; } } void setCoords(const Coord* _coords) { if (_coords==NULL) return; for (int i=0; i<3; i++) { coords[0][i] = _coords[0][i]; coords[1][i] = _coords[1][i]; coords[2][i] = _coords[2][i]; } } void getCoords(Coord& coord1, Coord& coord2, Coord& coord3) { for(int i = 0; i < 3; i ++) { coord1[i] = coords[0][i]; coord2[i] = coords[1][i]; coord3[i] = coords[2][i]; } } void getCoords(Coord* coord1, Coord* coord2, Coord* coord3) { for(int i = 0; i < 3; i ++) { (*coord1)[i] = coords[0][i]; (*coord2)[i] = coords[1][i]; (*coord3)[i] = coords[2][i]; } } void getCoords(Coord* _coords) { if (_coords==NULL) return; for (int i=0; i<3; i++) { _coords[0][i] = coords[0][i]; _coords[1][i] = coords[1][i]; _coords[2][i] = coords[2][i]; } } };
[ "weihongyu1987@f7207f0a-2814-11df-8e46-3928208ddfa0" ]
[ [ [ 1, 328 ] ] ]
5d4492f9cd2c229975ae6faaf42f7f294ef94ea9
44e10950b3bf454080553a5da36bf263e6a62f8f
/src/Entity/Entity.h
64c61d47b4dd0f1f1a04d46effa5024ed3195195
[]
no_license
ptrefall/ste6246tradingagent
a515d88683bf5f55f862c0b3e539ad6144a260bb
89c8e5667aec4c74aef3ffe47f19eb4a1b17b318
refs/heads/master
2020-05-18T03:50:47.216489
2011-12-20T19:02:32
2011-12-20T19:02:32
32,448,454
1
0
null
null
null
null
UTF-8
C++
false
false
880
h
#pragma once #include <Totem/ComponentHandler.h> #include <Totem/PropertyHandler.h> #include <Totem/PropertyListHandler.h> #include <Totem/Addons/TemplateEventHandler.h> #include <Totem/Addons/DelegateHandler.h> #include <Irrlicht\irrlicht.h> class Entity : public Totem::ComponentHandler<Entity>, public Totem::PropertyHandler<>, public Totem::PropertyListHandler<>, public Totem::Addon::TemplateEventHandler, public Totem::Addon::DelegateHandler { public: /// Constructor Entity(Totem::ComponentFactory &factory, irr::scene::ITerrainSceneNode& terrain) #pragma warning(suppress: 4355) : Totem::ComponentHandler<Entity>(*this, factory), terrain(terrain) { } /// Destructor virtual ~Entity() {} irr::scene::ITerrainSceneNode &getTerrain() { return terrain; } protected: irr::scene::ITerrainSceneNode& terrain; };
[ "[email protected]@92bc644c-bee7-7203-82ab-e16328aa9dbe" ]
[ [ [ 1, 32 ] ] ]
db152ed489857403250eb40f84979ecacbdeb6d4
4e2521c67a15b6ea8414be8faca7d3dc7b5fe426
/mainwindow.cpp
1cc096692c8338ecb1864df9118d42bd06e6e235
[]
no_license
joshuaeckroth/NeuralNetworkSimulator
ca6685f7b15b46fc0a34da41e6834f36f5fbc401
7f4b5e9eb17ed0b99a8ce719697ba3f17c00bdcd
refs/heads/master
2021-01-25T08:54:48.252098
2010-02-18T17:33:26
2010-02-18T17:33:26
514,045
1
1
null
null
null
null
UTF-8
C++
false
false
2,748
cpp
#include <vector> using namespace std; #include "mainwindow.h" #include "ui_mainwindow.h" #include "networkmanager.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); config = new Config(); connect(ui->configButton, SIGNAL(clicked()), config, SLOT(show())); connect(config, SIGNAL(accepted()), this, SLOT(newConfig())); connect(config, SIGNAL(accepted()), this, SLOT(restart())); plot = new QwtPlot(ui->centralWidget); ui->verticalLayout->addWidget(plot); networkManager = new NetworkManager(plot); networkManager->networksFromConfig(config); plot->setAxisTitle(QwtPlot::yLeft, QString("Error")); plot->setAxisTitle(QwtPlot::xBottom, QString("Epoch")); plot->replot(); connect(ui->resumeButton, SIGNAL(clicked()), this, SLOT(resume())); connect(ui->resumeButton, SIGNAL(clicked()), networkManager, SLOT(resume())); connect(ui->pauseButton, SIGNAL(clicked()), this, SLOT(pause())); connect(ui->pauseButton, SIGNAL(clicked()), networkManager, SLOT(pause())); connect(ui->restartButton, SIGNAL(clicked()), this, SLOT(restart())); connect(ui->restartButton, SIGNAL(clicked()), networkManager, SLOT(restart())); connect(networkManager, SIGNAL(stopped()), this, SLOT(stopped())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void MainWindow::resume() { mutex.lock(); ui->resumeButton->setText("Resume"); ui->resumeButton->setDisabled(true); ui->pauseButton->setDisabled(false); ui->restartButton->setDisabled(false); mutex.unlock(); } void MainWindow::pause() { mutex.lock(); ui->resumeButton->setText("Resume"); ui->resumeButton->setDisabled(false); ui->pauseButton->setDisabled(true); ui->restartButton->setDisabled(false); mutex.unlock(); } void MainWindow::restart() { mutex.lock(); ui->resumeButton->setText("Start"); ui->resumeButton->setDisabled(false); ui->pauseButton->setDisabled(true); ui->restartButton->setDisabled(true); mutex.unlock(); } void MainWindow::stopped() { mutex.lock(); ui->resumeButton->setText("Start"); ui->resumeButton->setDisabled(true); ui->pauseButton->setDisabled(true); ui->restartButton->setDisabled(false); mutex.unlock(); } void MainWindow::newConfig() { mutex.lock(); networkManager->networksFromConfig(config); mutex.unlock(); }
[ [ [ 1, 101 ] ] ]
44786fd95da98320d3803f31519be01bf321b089
c497f6d85bdbcbb21e93ae701c5570f16370f0ae
/GPS/YumaSat/trunk/YumaSat/Lets_try_all_engine/CarrGenMac.hpp
d918ed38c7a290af3acc648090ba289c74a28ff4
[]
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
201
hpp
/* The minimum Elevation angle */ /* GPS Theory and Application , Parkinson & Spliker Vol1 : Pg 453*/ # define CARR_CYCLCE_RESOLUTION 64 # define Q_OFFSET CARR_CYCLCE_RESOLUTION*0.75
[ "priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7" ]
[ [ [ 1, 10 ] ] ]
40ddc5c6223f4e7ab6d6037c024caeaff1413d4a
8a88075abf60e213a490840bebee97df01b8827a
/implementation/ogl_render/include/ogl_render/impl/hcommands_3d.hpp
fdd27ff91a77a94b3355bacf612e640e80059a8c
[]
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
1,139
hpp
#ifndef OGLRENDER_HCOMMANDS_3_HPP #define OGLRENDER_HCOMMANDS_3_HPP #include "ogl_render/impl/commands.hpp" #include "geometry/homogenous/hcoord_system.hpp" #include "geometry/vertex.hpp" #include <boost/type_traits/is_same.hpp> #include <boost/static_assert.hpp> namespace ogl_render { namespace impl { template< typename UT> struct commands< geometry::hcoord_system< 3, float, UT> > { private: typedef geometry::hcoord_system< 3, float, UT> coord_system; public: BOOST_STATIC_ASSERT( (boost::is_same< float, typename UT::unit_type>::value)); static void vertex( const geometry::vertex< coord_system>& v) { glVertex4f( v.x(), v.y(), v.z(), v.w()); } }; template< typename UT> struct commands< geometry::hcoord_system< 3, double, UT> > { private: typedef geometry::hcoord_system< 3, double, UT> coord_system; public: BOOST_STATIC_ASSERT( (boost::is_same< double, typename UT::unit_type>::value)); static void vertex( const geometry::vertex< coord_system>& v) { glVertex4d( v.x(), v.y(), v.z(), v.w()); } }; } // impl } // ogl_render #endif // OGLRENDER_HCOMMANDS_3_HPP
[ "cpitis@834bb202-e8be-11dd-9d8c-a70aa0a93a20" ]
[ [ [ 1, 47 ] ] ]
d0eaf3bea2f1e66172b946ce63ca3d8bbcae41cd
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SEEffects/SEMaterialTexture2L1Effect.h
04c519a1e43c23080583e5b3723d918dc4da4671
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,789
h
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #ifndef Swing_MaterialTexture2L1Effect_H #define Swing_MaterialTexture2L1Effect_H #include "SEFoundationLIB.h" #include "SEShaderEffect.h" namespace Swing { //---------------------------------------------------------------------------- // Description: // Author:Sun Che // Date:20100228 //---------------------------------------------------------------------------- class SE_FOUNDATION_API SEMaterialTexture2L1Effect : public SEShaderEffect { SE_DECLARE_RTTI; SE_DECLARE_NAME_ID; SE_DECLARE_STREAM; public: SEMaterialTexture2L1Effect(const std::string& rT0, const std::string& rT1); virtual ~SEMaterialTexture2L1Effect(void); protected: // streaming SEMaterialTexture2L1Effect(void); }; typedef SESmartPointer<SEMaterialTexture2L1Effect> SEMaterialTexture2L1EffectPtr; } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 55 ] ] ]
c5c4f5a5f5a4b86d7c7922240629af1365579230
4891542ea31c89c0ab2377428e92cc72bd1d078f
/Arcanoid/Arcanoid/Sprite.h
1e9c19627e5a2a9257e338cec35423f372e3261a
[]
no_license
koutsop/arcanoid
aa32c46c407955a06c6d4efe34748e50c472eea8
5bfef14317e35751fa386d841f0f5fa2b8757fb4
refs/heads/master
2021-01-18T14:11:00.321215
2008-07-17T21:50:36
2008-07-17T21:50:36
33,115,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,417
h
/* * author: koutsop */ #ifndef SPRITE_H #define SPRITE_H #include <string> #include <allegro.h> //Eidea den exw giati xriazete ala stamata na peta la8oi h allgero #include "Point.h" #include "Oblong.h" #include "AnimationFilm.h" class Sprite : public Oblong { private: char frameNo; bool isVisible; Point position; AnimationFilm* currFilm; public: void SetFrame(char i); void Display(BITMAP *bitmap); Point GetPosition(void) const { return position; } void SetPosition(Point point) { position = point; } void SetPosition(int x, int y); char GetFrame(void) const { return frameNo; } bool IsVisible(void) const { return isVisible; } AnimationFilm * GetFilm(void) { return currFilm; } void SetVisibility(bool v) { isVisible = v; } /* @target: Kanei arnitiko elenxo. Dhl den epikaliptontai * :se sxesh me to epikaliptontai * @return: true an epikaliptontai alios false */ bool CollisionCheck(Sprite* s); virtual void Collide(Sprite *s) = 0; /* @target: Einai h Move gia to ekatos8e sprite */ virtual void Move(const int dx, const int dy); Sprite(Point point, AnimationFilm* film); Sprite(int x, int y, AnimationFilm* film); Sprite(const Point * const point, AnimationFilm* film); Sprite(int upper_x, int upper_y, int down_x, int down_y); virtual~Sprite(){} }; #endif
[ "koutsop@5c4dd20e-9542-0410-abe3-ad2d610f3ba4", "apixkernel@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 3 ], [ 5, 6 ], [ 8, 9 ], [ 11, 14 ], [ 16, 18 ], [ 20, 23 ], [ 25, 25 ], [ 27, 40 ], [ 42, 52 ], [ 55, 67 ] ], [ [ 4, 4 ], [ 7, 7 ], [ 10, 10 ], [ 15, 15 ], [ 19, 19 ], [ 24, 24 ], [ 26, 26 ], [ 41, 41 ], [ 53, 54 ], [ 68, 69 ] ] ]
2b588f7a8aa5255cdc7af68ad0ef6d45793a9728
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Shape/Convex/ConvexTranslate/hkpConvexTranslateShape.inl
14f106c76355c885e1db6ecd91493e7cf2a87639
[]
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
2,479
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. * */ inline const hkpConvexShape* hkpConvexTranslateShape::getChildShape() const { return static_cast<const hkpConvexShape*>(m_childShape.getChild()); } inline const hkVector4& hkpConvexTranslateShape::getTranslation() const { return m_translation; } inline hkVector4& hkpConvexTranslateShape::getTranslation() { return m_translation; } inline void hkpConvexTranslateShape::initializeSpu( const hkpConvexShape* childShape, const hkVector4& translation, hkReal radius ) { m_type = HK_SHAPE_CONVEX_TRANSLATE; m_childShape = childShape; m_radius = radius; m_translation = translation; m_translation(3) = 0; m_childShapeSize = 0; } HK_FORCE_INLINE hkpConvexTranslateShape::hkpConvexTranslateShape( const hkpConvexShape* childShape, const hkVector4& translation, hkpShapeContainer::ReferencePolicy ref ) : hkpConvexTransformShapeBase( HK_SHAPE_CONVEX_TRANSLATE, childShape->getRadius(), childShape, ref) { HK_ASSERT2(0x6acf0520, childShape != HK_NULL, "Child shape cannot be NULL"); #if defined(HK_DEBUG) if (childShape->getContainer() != HK_NULL) { HK_WARN_ONCE(0x6acf0521, "You have two translate shapes on top of each other. Slight performance decrease."); } #endif hkVector4 t; t.setXYZ0(translation); m_translation = t; m_childShapeSize = 0; } /* * 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, 62 ] ] ]
ae473a44ce063eb8709c19e8bc4abb28e2e6bbda
abc56cb83780a83bd2fb1db4775797eb00bac67c
/3rdparty/VSML/vsml.cpp
03cc09a6c82616ae2c771e601b11648e1e5d2d68
[]
no_license
fluffyfreak/Cookie
2b641d36e6466e90512a147c3f8e012890e65517
00d61dc77b097dac12aea31e0184cbe55266787f
refs/heads/master
2021-01-21T16:28:27.167691
2011-08-05T06:09:57
2011-08-05T06:09:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,255
cpp
#include "vsml.h" #include <math.h> // This var keeps track of the single instance of VSML VSML* VSML::gInstance = 0; #define M_PI 3.14159265358979323846f static inline float DegToRad(float degrees) { return (float)(degrees * (M_PI / 180.0f)); }; // Singleton implementation // use this function to get the instance of VSML VSML* VSML::getInstance (void) { if (0 != gInstance) return gInstance; else gInstance = new VSML(); return gInstance; } // VSML constructor VSML::VSML(): mInit(false), mBlocks(false) { } // VSML destructor VSML::~VSML() { } // send the buffer data and offsets to VSML void VSML::initUniformBlock(GLuint buffer, GLuint modelviewOffset, GLuint projOffset) { mInit = true; mBlocks = true; mBuffer = buffer; mOffset[MODELVIEW] = modelviewOffset; mOffset[PROJECTION] = projOffset; } // send the uniform locations to VSML void VSML::initUniformLocs(GLuint modelviewLoc, GLuint projLoc) { mInit = true; mBlocks = false; mUniformLoc[MODELVIEW] = modelviewLoc; mUniformLoc[PROJECTION] = projLoc; } // glPushMatrix implementation void VSML::pushMatrix(MatrixTypes aType) { float *aux = (float *)malloc(sizeof(float) * 16); memcpy(aux, mMatrix[aType], sizeof(float) * 16); mMatrixStack[aType].push_back(aux); } // glPopMatrix implementation void VSML::popMatrix(MatrixTypes aType) { float *m = mMatrixStack[aType][mMatrixStack[aType].size()-1]; memcpy(mMatrix[aType], m, sizeof(float) * 16); mMatrixStack[aType].pop_back(); free(m); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glLoadIdentity implementation void VSML::loadIdentity(MatrixTypes aType) { setIdentityMatrix(mMatrix[aType]); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glMultMatrix implementation void VSML::multMatrix(MatrixTypes aType, float *aMatrix) { float *a, *b, res[16]; a = mMatrix[aType]; b = aMatrix; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { res[j*4 + i] = 0.0f; for (int k = 0; k < 4; ++k) { res[j*4 + i] += a[k*4 + i] * b[j*4 + k]; } } } memcpy(mMatrix[aType], res, 16 * sizeof(float)); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glLoadMatrix implementation void VSML::loadMatrix(MatrixTypes aType, float *aMatrix) { memcpy(mMatrix[aType], aMatrix, 16 * sizeof(float)); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glTranslate implementation with matrix selection void VSML::translate(MatrixTypes aType, float x, float y, float z) { float mat[16]; setIdentityMatrix(mat); mat[12] = x; mat[13] = y; mat[14] = z; multMatrix(aType,mat); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glTranslate on the MODELVIEW matrix void VSML::translate(float x, float y, float z) { translate(MODELVIEW, x,y,z); } // glScale implementation with matrix selection void VSML::scale(MatrixTypes aType, float x, float y, float z) { float mat[16]; setIdentityMatrix(mat,4); mat[0] = x; mat[5] = y; mat[10] = z; multMatrix(aType,mat); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glScale on the MODELVIEW matrix void VSML::scale(float x, float y, float z) { scale(MODELVIEW, x, y, z); } // glRotate implementation with matrix selection void VSML::rotate(MatrixTypes aType, float angle, float x, float y, float z) { float mat[16]; float radAngle = DegToRad(angle); float co = cos(radAngle); float si = sin(radAngle); float x2 = x*x; float y2 = y*y; float z2 = z*z; mat[0] = x2 + (y2 + z2) * co; mat[4] = x * y * (1 - co) - z * si; mat[8] = x * z * (1 - co) + y * si; mat[12]= 0.0f; mat[1] = x * y * (1 - co) + z * si; mat[5] = y2 + (x2 + z2) * co; mat[9] = y * z * (1 - co) - x * si; mat[13]= 0.0f; mat[2] = x * z * (1 - co) - y * si; mat[6] = y * z * (1 - co) + x * si; mat[10]= z2 + (x2 + y2) * co; mat[14]= 0.0f; mat[3] = 0.0f; mat[7] = 0.0f; mat[11]= 0.0f; mat[15]= 1.0f; multMatrix(aType,mat); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(aType); #endif } // glRotate implementation in the MODELVIEW matrix void VSML::rotate(float angle, float x, float y, float z) { rotate(MODELVIEW,angle,x,y,z); } // gluLookAt implementation void VSML::lookAt(float xPos, float yPos, float zPos, float xLook, float yLook, float zLook, float xUp, float yUp, float zUp) { float dir[3], right[3], up[3]; up[0] = xUp; up[1] = yUp; up[2] = zUp; dir[0] = (xLook - xPos); dir[1] = (yLook - yPos); dir[2] = (zLook - zPos); normalize(dir); crossProduct(dir,up,right); normalize(right); crossProduct(right,dir,up); normalize(up); float *viewMatrix,mat[16]; viewMatrix = mMatrix[MODELVIEW]; viewMatrix[0] = right[0]; viewMatrix[4] = right[1]; viewMatrix[8] = right[2]; viewMatrix[12] = 0.0f; viewMatrix[1] = up[0]; viewMatrix[5] = up[1]; viewMatrix[9] = up[2]; viewMatrix[13] = 0.0f; viewMatrix[2] = -dir[0]; viewMatrix[6] = -dir[1]; viewMatrix[10] = -dir[2]; viewMatrix[14] = 0.0f; viewMatrix[3] = 0.0f; viewMatrix[7] = 0.0f; viewMatrix[11] = 0.0f; viewMatrix[15] = 1.0f; setIdentityMatrix(mat,4); mat[12] = -xPos; mat[13] = -yPos; mat[14] = -zPos; multMatrix(MODELVIEW, mat); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(MODELVIEW); #endif } // gluPerspective implementation void VSML::perspective(float fov, float ratio, float nearp, float farp) { float *projMatrix = mMatrix[PROJECTION]; float f = 1.0f / tan (fov * (M_PI / 360.0f)); setIdentityMatrix(projMatrix,4); projMatrix[0] = f / ratio; projMatrix[1 * 4 + 1] = f; projMatrix[2 * 4 + 2] = (farp + nearp) / (nearp - farp); projMatrix[3 * 4 + 2] = (2.0f * farp * nearp) / (nearp - farp); projMatrix[2 * 4 + 3] = -1.0f; projMatrix[3 * 4 + 3] = 0.0f; #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(PROJECTION); #endif } // glOrtho implementation void VSML::ortho(float left, float right, float bottom, float top, float nearp, float farp) { float *m = mMatrix[PROJECTION]; setIdentityMatrix(m,4); m[0 * 4 + 0] = 2 / (right - left); m[1 * 4 + 1] = 2 / (top - bottom); m[2 * 4 + 2] = -2 / (farp - nearp); m[3 * 4 + 0] = -(right + left) / (right - left); m[3 * 4 + 1] = -(top + bottom) / (top - bottom); m[3 * 4 + 2] = -(farp + nearp) / (farp - nearp); #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(PROJECTION); #endif } // glFrustum implementation void VSML::frustum(float left, float right, float bottom, float top, float nearp, float farp) { float *m = mMatrix[PROJECTION]; setIdentityMatrix(m,4); m[0 * 4 + 0] = 2 * nearp / (right-left); m[1 * 4 + 1] = 2 * nearp / (top - bottom); m[2 * 4 + 0] = (right + left) / (right - left); m[2 * 4 + 1] = (top + bottom) / (top - bottom); m[2 * 4 + 2] = (farp + nearp) / (farp - nearp); m[2 * 4 + 3] = -1.0f; m[3 * 4 + 2] = 2 * farp * nearp / (farp-nearp); m[3 * 4 + 3] = 0.0f; #ifdef VSML_ALWAYS_SEND_TO_OPENGL matrixToGL(PROJECTION); #endif } // returns a pointer to the requested matrix float * VSML::get(MatrixTypes aType) { return mMatrix[aType]; } /* ----------------------------------------------------- SEND MATRICES TO OPENGL ------------------------------------------------------*/ // to be used with uniform blocks void VSML::matrixToBuffer(MatrixTypes aType) { if (mInit && mBlocks) { glBindBuffer(GL_UNIFORM_BUFFER,mBuffer); glBufferSubData(GL_UNIFORM_BUFFER, mOffset[aType], 16 * sizeof(float), mMatrix[aType]); glBindBuffer(GL_UNIFORM_BUFFER,0); } } // to be used with uniform variables void VSML::matrixToUniform(MatrixTypes aType) { if (mInit && !mBlocks) { glUniformMatrix4fv(mUniformLoc[aType], 1, false, mMatrix[aType]); } } // universal void VSML::matrixToGL(MatrixTypes aType) { if (mInit) { if (mBlocks) { glBindBuffer(GL_UNIFORM_BUFFER,mBuffer); glBufferSubData(GL_UNIFORM_BUFFER, mOffset[aType], 16 * sizeof(float), mMatrix[aType]); glBindBuffer(GL_UNIFORM_BUFFER,0); } else { glUniformMatrix4fv(mUniformLoc[aType], 1, false, mMatrix[aType]); } } } // ----------------------------------------------------- // AUX functions // ----------------------------------------------------- // sets the square matrix mat to the identity matrix, // size refers to the number of rows (or columns) void VSML::setIdentityMatrix( float *mat, int size) { // fill matrix with 0s for (int i = 0; i < size * size; ++i) mat[i] = 0.0f; // fill diagonal with 1s for (int i = 0; i < size; ++i) mat[i + i * size] = 1.0f; } // res = a cross b; void VSML::crossProduct( float *a, float *b, float *res) { res[0] = a[1] * b[2] - b[1] * a[2]; res[1] = a[2] * b[0] - b[2] * a[0]; res[2] = a[0] * b[1] - b[0] * a[1]; } // Normalize a vec3 void VSML::normalize(float *a) { float mag = sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); a[0] /= mag; a[1] /= mag; a[2] /= mag; }
[ "psastras@psastras-PC.(none)" ]
[ [ [ 1, 437 ] ] ]
5b2414312db943494088d6308ef4c8f8470a1fc7
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/STLPort-4.0/test/regression/lwrbnd2.cpp
5ec6d6bbdd95f576d0a989a3830afddd808d4808
[ "LicenseRef-scancode-stlport-4.5" ]
permissive
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
868
cpp
// STLport regression testsuite component. // To compile as a separate example, please #define MAIN. #include <algorithm> #include <iostream> #include <cstring> #ifdef MAIN #define lwrbnd2_test main #endif #if !defined (STLPORT) || defined(__STL_USE_NAMESPACES) using namespace std; #endif static bool char_str_less(const char* a_, const char* b_) { return ::strcmp(a_, b_) < 0 ? 1 : 0; } int lwrbnd2_test(int, char**) { cout<<"Results of lwrbnd2_test:"<<endl; char* str [] = { "a", "a", "b", "b", "q", "w", "z" }; const unsigned strCt = sizeof(str)/sizeof(str[0]); // DEC C++ generates incorrect template instatiation code // for "d" so must cast cout << "d can be inserted at index: " <<(lower_bound((char**)str, (char**)str + strCt, (const char *)"d", char_str_less) - str) << endl; return 0; }
[ [ [ 1, 34 ] ] ]
3bbf61d84357c091e4190e50a1fb7883de257b7e
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/FingerSuite/Common/atlcplapplet.h
36fa88326e5e3aec3391cb9443df7d966b41f7c8
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
20,485
h
#ifndef __ATLCPLAPPLET_H__ #define __ATLCPLAPPLET_H__ ///////////////////////////////////////////////////////////////////////////// // atlcplapplet.h - Control Panel applet // // Written by Bjarke Viksoe ([email protected]) // Copyright (c) 2007 Bjarke Viksoe. // // This code may be used in compiled form in any way you desire. This // source file may be redistributed by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name is included. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability if it causes any damage to you or your // computer whatsoever. It's free, so don't hassle me about it. // // Beware of bugs. // #pragma once #ifndef __cplusplus #error ATL requires C++ compilation (use a .cpp suffix) #endif #ifndef __ATLAPP_H__ #error atlcplapplet.h requires atlapp.h to be included first #endif #include <cpl.h> typedef struct tagATLCPLAPPLETREG { int iIndex; BOOL bOnlyCurrentUser; DWORD dwCategory; DWORD dwRunLevel; UINT uTaskRegID; } ATLCPLAPPLETREG; #define DECLARE_APPLET_CATEGORY(x) enum { APPLET_CATEGORY = x }; #define DECLARE_APPLET_RUNLEVEL(x) enum { APPLET_RUNLEVEL = x }; #define DECLARE_APPLET_RESOURCEID(x) enum { APPLET_TASK_REGISTRYID = x }; typedef struct tagATLCPLAPPLETINFO { LPCTSTR pstrCanonicalName; UINT uNameRes; UINT uInfoRes; UINT uTaskRes; UINT uKeywordsRes; UINT uIconRes; BOOL bDynamic; DWORD dwFlags; ULONG_PTR lData; DWORD dwHelpContext; HRESULT (*pfnUpdateRegistry)(int iIndex, BOOL bRegister); BOOL (*pfnCreateInstance)(HWND hWnd, LONG_PTR lData, LPCTSTR pstrData); VOID (*pfnGetAppletInfo)(int iLevel, tagATLCPLAPPLETINFO* pInfo); } ATLCPLAPPLETINFO; extern ATLCPLAPPLETINFO _pAtlApplets[]; #define BEGIN_CPLAPPLET_MAP() \ ATLCPLAPPLETINFO _pAtlApplets[] = { #define CPLAPPLET_ENTRY(applclass, cname, name) \ { _T(cname), IDS_##name, IDS_Description_##name, IDS_Task_##name, IDS_Keywords_##name, IDI_##name, FALSE, 0, 0L, 0, &applclass::UpdateRegistry, &applclass::CreateInstance, &applclass::GetAppletInfo }, #define CPLAPPLET_ENTRY_EX(applclass, cname, name, info, task, keywords, icon, flags, data, helpctx) \ { _T(cname), name, info, task, keywords, icon, TRUE, flags, data, helpctx, &applclass::UpdateRegistry, &applclass::CreateInstance, &applclass::GetAppletInfo }, #define CPLAPPLET_ENTRY_CLASS(applclass) \ { NULL, CPL_DYNAMIC_RES, CPL_DYNAMIC_RES, 0, 0, CPL_DYNAMIC_RES, TRUE, 0, 0L, 0, &applclass::UpdateRegistry, &applclass::CreateInstance, &applclass::GetAppletInfo }, #define END_CPLAPPLET_MAP() \ { 0 } }; typedef enum CPLAPPLETINFO { CPLINFO_NAME = 1, CPLINFO_INFO, CPLINFO_ICON, CPLINFO_DATA, CPLINFO_HELPCONTEXT, }; template< class T > class CCPlAppletBase { public: enum { APPLET_CATEGORY = 0x05 }; enum { APPLET_RUNLEVEL = 0x00 }; enum { APPLET_TASK_REGISTRYID = 0 }; static HRESULT UpdateRegistry(int iIndex, BOOL bRegister) { ATLCPLAPPLETREG RegInfo = { iIndex, FALSE, T::APPLET_CATEGORY, T::APPLET_RUNLEVEL, T::APPLET_TASK_REGISTRYID }; return _Applets.UpdateRegistry(bRegister, &RegInfo); } static BOOL CreateInstance(HWND hWnd, LONG_PTR lData, LPCTSTR pstrData) { T* pObject = new T(); if( pObject == NULL ) return FALSE; BOOL bRes = pObject->ShowApplet(hWnd, lData, pstrData); delete pObject; return bRes; } static VOID GetAppletInfo(int /*iLevel*/, ATLCPLAPPLETINFO* /*pInfo*/) { } }; class CCPlAppletModule { public: HWND m_hwndCPl; CCPlAppletModule() : m_hwndCPl(NULL) { } LONG CPlApplet(HWND hwndCPl, UINT msg, LPARAM lParam1, LPARAM lParam2) { m_hwndCPl = hwndCPl; switch( msg ) { case CPL_INIT: CPlApplet_Init(); return 1; case CPL_EXIT: CPlApplet_Exit(); return 0; case CPL_GETCOUNT: return CPlApplet_GetCount(); case CPL_DBLCLK: CPlApplet_DblClick((int) lParam1, hwndCPl); return 0; #ifndef _WIN32_WCE case CPL_INQUIRE: CPlApplet_Inquire((int) lParam1, (CPLINFO*) lParam2); return 0; #endif // !_WIN32_WCE case CPL_NEWINQUIRE: CPlApplet_NewInquire((int) lParam1, (NEWCPLINFO*) lParam2); return 0; #ifndef _WIN32_WCE #if (WINVER >= 0x0400) case CPL_STARTWPARMSA: { #ifdef _UNICODE WCHAR wszCommand[100] = { 0 }; ::MultiByteToWideChar(CP_ACP, 0, (LPCSTR) lParam2, -1, wszCommand, (sizeof(wszCommand) / sizeof(WCHAR)) -1); LPCWSTR pstrCommand = wszCommand; #else LPCSTR pstrCommand = (LPCSTR) lParam2; #endif // _UNICODE return (LONG) CPlApplet_StartWithParams((int) lParam1, hwndCPl, pstrCommand); } case CPL_STARTWPARMSW: { #ifdef _UNICODE LPCWSTR pstrCommand = (LPCWSTR) lParam2; #else CHAR szCommand[200] = { 0 }; ::WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) lParam2, -1, szCommand, sizeof(szCommand) - 1, NULL, NULL); LPCSTR pstrCommand = szCommand; #endif // _UNICODE return (LONG) CPlApplet_StartWithParams((int) lParam1, hwndCPl, pstrCommand); } #endif // (WINVER >= 0x0400) #endif // !_WIN32_WCE case CPL_STOP: CPlApplet_Stop((int) lParam1); return 0; } return 0; } HRESULT RegisterApplets() { HRESULT Hr = S_OK; #ifndef _WIN32_WCE int iIndex = 0; for( const ATLCPLAPPLETINFO* pObjects = _pAtlApplets; (*pObjects).pfnCreateInstance != NULL; pObjects++ ) { if( FAILED( Hr = pObjects->pfnUpdateRegistry(iIndex++, TRUE) ) ) return Hr; } #endif // !_WIN32_WCE return Hr; } HRESULT UnregisterApplets() { HRESULT Hr = S_OK, HrRes = S_OK; #ifndef _WIN32_WCE int iIndex = 0; for( const ATLCPLAPPLETINFO* pObjects = _pAtlApplets; (*pObjects).pfnCreateInstance != NULL; pObjects++ ) { if( FAILED( Hr = pObjects->pfnUpdateRegistry(iIndex++, FALSE) ) ) HrRes = Hr; } #endif // !_WIN32_WCE return HrRes; } HWND GetOwnerHWND() { return m_hwndCPl; } BOOL ChangeAppletInfo(int iIndex, CPLAPPLETINFO Type, UINT uResID) { ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount()); if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return FALSE; switch( Type ) { case CPLINFO_NAME: _pAtlApplets[iIndex].uNameRes = uResID; break; case CPLINFO_INFO: _pAtlApplets[iIndex].uInfoRes = uResID; break; case CPLINFO_ICON: _pAtlApplets[iIndex].uIconRes = uResID; break; case CPLINFO_DATA: _pAtlApplets[iIndex].lData = (LONG_PTR) uResID; break; case CPLINFO_HELPCONTEXT: _pAtlApplets[iIndex].dwHelpContext = uResID; break; default: return FALSE; } _pAtlApplets[iIndex].bDynamic = TRUE; return TRUE; } HRESULT UpdateRegistry(BOOL bRegister, ATLCPLAPPLETREG* pRegInfo) { #ifndef _WIN32_WCE OSVERSIONINFO osvi = { 0 };; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); ::GetVersionEx(&osvi); bool bIsVista = (osvi.dwMajorVersion >= 6); bool bIsWin98 = ((osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS && osvi.dwMajorVersion >= 5) || (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && (osvi.dwMinorVersion >= 90 || osvi.dwMajorVersion > 4))); bool bIsWinXP = ((osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) && ((osvi.dwMajorVersion > 5) || ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion >= 1)))); TCHAR szDllFile[MAX_PATH] = { 0 }; ::GetModuleFileName(ModuleHelper::GetModuleInstance(), szDllFile, MAX_PATH); ATLCPLAPPLETINFO Info = _pAtlApplets[pRegInfo->iIndex]; _pAtlApplets[pRegInfo->iIndex].pfnGetAppletInfo(1, &Info); // Create a friendly name for the dll filename. No spaces and funny characters. LPCTSTR pSep = _FindLastOf(szDllFile, '\\'); if( pSep == NULL ) return E_FAIL; TCHAR szDllName[MAX_PATH] = { 0 }; ::lstrcpy(szDllName, pSep + 1); TCHAR szFriendlyName[MAX_PATH] = { 0 }; ::lstrcpy(szFriendlyName, pSep + 1); for( LPTSTR p = szFriendlyName; *p != '\0'; p = ::CharNext(p) ) { if( *p == '.' ) { *p = '\0'; break; } if( !IsCharAlphaNumeric(*p) ) *p = '_'; } HRESULT Hr = S_OK; if( bIsVista ) { HKEY hKeyRoot = HKEY_LOCAL_MACHINE; if( pRegInfo->bOnlyCurrentUser ) hKeyRoot = HKEY_CURRENT_USER; CRegKey reg; LONG lRes = reg.Create(hKeyRoot, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Cpls")); if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes); if( bRegister ) { ::RegSetValueEx(reg, szFriendlyName, NULL, REG_EXPAND_SZ, (CONST BYTE*) szDllFile, (lstrlen(szDllFile) + 1) * sizeof(TCHAR)); if( pRegInfo->dwRunLevel > 0 ) { CRegKey regSub; if( regSub.Create(reg, szDllName) == ERROR_SUCCESS ) { ::RegSetValueEx(regSub, _T("RunLevel"), NULL, REG_DWORD, (CONST BYTE*) &pRegInfo->dwRunLevel, sizeof(DWORD)); regSub.Close(); } } } else { reg.DeleteValue(szFriendlyName); reg.DeleteSubKey(szDllName); } reg.Close(); // Register canonical name lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.ApplicationName"), KEY_ALL_ACCESS); if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes); if( bRegister ) { ::RegSetValueEx(reg, szDllFile, NULL, REG_SZ, (CONST BYTE*) Info.pstrCanonicalName, (lstrlen(Info.pstrCanonicalName) + 1) * sizeof(TCHAR)); } else { reg.DeleteValue(szDllFile); } reg.Close(); TCHAR szGUID[50] = { 0 }; DWORD dwCategory = pRegInfo->dwCategory; TCHAR szTaskFileUrl[MAX_PATH + 20] = { 0 }; if( pRegInfo->uTaskRegID == 0 ) { GUID AppGUID, TaskGUID; ::CoCreateGuid(&AppGUID); ::CoCreateGuid(&TaskGUID); WCHAR wszGUID[50], wszTaskGUID[50]; ::StringFromGUID2(AppGUID, wszGUID, 50); ::StringFromGUID2(TaskGUID, wszTaskGUID, 50); WCHAR wszBuffer[1025] = { 0 }; ::wsprintfW(wszBuffer, L"\xfeff<?xml version=\"1.0\" encoding=\"UTF-16\" ?>\n" L"<applications xmlns=\"http://schemas.microsoft.com/windows/cpltasks/v1\" xmlns:sh=\"http://schemas.microsoft.com/windows/tasks/v1\">" L"<application id=\"%s\">" L"<sh:task id=\"%s\" needsElevation=\"%s\">" #ifdef _UNICODE L"<sh:name>@%s,-%ld</sh:name>" L"<sh:keywords>@%s,-%ld</sh:keywords>" L"<sh:command>%%systemroot%%\\system32\\control.exe /name %s</sh:command>" #else L"<sh:name>@%hs,-%ld</sh:name>" L"<sh:keywords>@%hs,-%ld</sh:keywords>" L"<sh:command>%%systemroot%%\\system32\\control.exe /name %hs</sh:command>" #endif // _UNICODE L"</sh:task>" L"<category id=\"%ld\">" L"<sh:task idref=\"%s\"/>" L"</category>" L"</application>" L"</applications>", wszGUID, wszTaskGUID, pRegInfo->dwRunLevel == 0 ? L"false" : L"true", szDllName, Info.uTaskRes, szDllName, Info.uKeywordsRes, Info.pstrCanonicalName, pRegInfo->dwCategory, wszTaskGUID); ::wsprintf(szGUID, _T("%ws"), wszGUID); ::lstrcpy(szTaskFileUrl, szDllFile); ::wsprintf(_FindLastOf(szTaskFileUrl, '.'), _T("_cpl%d.xml"), pRegInfo->iIndex + 1); if( bRegister ) { HANDLE hFile = ::CreateFile(szTaskFileUrl, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if( hFile == INVALID_HANDLE_VALUE ) return HRESULT_FROM_WIN32(::GetLastError()); DWORD dwWritten = 0; ::WriteFile(hFile, wszBuffer, lstrlenW(wszBuffer) * sizeof(WCHAR), &dwWritten, NULL); ::CloseHandle(hFile); } else { ::DeleteFile(szTaskFileUrl); } } else { // Load the XML resource. // Here we assume it is UTF-8 encoded (or latin-1) and embedded in the "XML" resource // type section. HRSRC hResource = ::FindResource(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(pRegInfo->uTaskRegID), _T("XML")); if( hResource == NULL ) return TYPE_E_FIELDNOTFOUND; HGLOBAL hGlobal = ::LoadResource(ModuleHelper::GetResourceInstance(), hResource); if( hGlobal == NULL ) return E_OUTOFMEMORY; DWORD dwSize = ::SizeofResource(ModuleHelper::GetResourceInstance(), hResource); LPVOID pVoid = ::LockResource(hGlobal); LPSTR pstr = (LPSTR) malloc(dwSize + 1); memcpy(pstr, pVoid, dwSize); FreeResource(hGlobal); pstr[dwSize] = '\0'; LPSTR pstrCategory = strstr(pstr, "<category id=\""); if( pstrCategory != NULL ) dwCategory = (DWORD) atol(pstrCategory + 14); LPSTR pstrGUID = strstr(pstr, "<application id=\""); if( pstrGUID == NULL ) return TYPE_E_ELEMENTNOTFOUND; BYTE bGUID[50] = { 0 }; memcpy(bGUID, pstrGUID + 17, 38); ::wsprintf(szGUID, _T("%hs"), bGUID); ::wsprintf(szTaskFileUrl, _T("%s,-%ld"), szDllFile, pRegInfo->uTaskRegID); free(pstr); } // Set the ApplicationName (canonical name) lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.Software.AppId"), KEY_ALL_ACCESS); if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes); if( bRegister ) { ::RegSetValueEx(reg, szDllFile, NULL, REG_SZ, (CONST BYTE*) szGUID, (lstrlen(szGUID) + 1) * sizeof(TCHAR)); } else { reg.DeleteValue(szDllFile); } reg.Close(); // Set the TaskFileUrl lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.Software.TasksFileUrl"), KEY_ALL_ACCESS); if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes); if( bRegister ) { ::RegSetValueEx(reg, szDllFile, NULL, REG_SZ, (CONST BYTE*) szTaskFileUrl, (lstrlen(szTaskFileUrl) + 1) * sizeof(TCHAR)); } else { reg.DeleteValue(szDllFile); } reg.Close(); // Set the Category lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.ControlPanel.Category"), KEY_ALL_ACCESS); if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes); if( bRegister ) { ::RegSetValueEx(reg, szDllFile, NULL, REG_DWORD, (CONST BYTE*) &dwCategory, sizeof(DWORD)); } else { reg.DeleteValue(szDllFile); } reg.Close(); } else if( bIsWin98 ) { HKEY hKeyRoot = HKEY_LOCAL_MACHINE; if( pRegInfo->bOnlyCurrentUser ) hKeyRoot = HKEY_CURRENT_USER; CRegKey reg; LONG lRes = reg.Create(hKeyRoot, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Cpls")); if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes); if( bRegister ) { ::RegSetValueEx(reg, szFriendlyName, NULL, REG_EXPAND_SZ, (CONST BYTE*) szDllFile, (lstrlen(szDllFile) + 1) * sizeof(TCHAR)); } else { reg.DeleteValue(szFriendlyName); } reg.Close(); // Set the Category on Windows XP if( bIsWinXP ) { lRes = reg.Create(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\{305CA226-D286-468e-B848-2B2E8E697B74} 2")); if( lRes == ERROR_SUCCESS ) { if( bRegister ) { ::RegSetValueEx(reg, szDllFile, NULL, REG_DWORD, (CONST BYTE*) &pRegInfo->dwCategory, sizeof(DWORD)); } else { reg.DeleteValue(szDllFile); } } } } else { BOOL bRes = ::WritePrivateProfileString(_T("MMCPL"), szFriendlyName, (bRegister ? szDllFile : NULL), _T("control.ini")); if( !bRes ) Hr = HRESULT_FROM_WIN32(::GetLastError()); } return Hr; #else return S_OK; #endif // !_WIN32_WCE } void CPlApplet_Init() { } void CPlApplet_Exit() { } void CPlApplet_Stop(int iIndex) { ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount()); if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return; } void CPlApplet_DblClick(int iIndex, HWND hWnd) { ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount()); if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return; LONG_PTR lData = _pAtlApplets[iIndex].lData; _pAtlApplets[iIndex].pfnCreateInstance(hWnd, lData, _T("")); } #ifndef _WIN32_WCE BOOL CPlApplet_StartWithParams(int iIndex, HWND hWnd, LPCTSTR pstrText) { ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount()); if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return FALSE; LONG_PTR lData = _pAtlApplets[iIndex].lData; return _pAtlApplets[iIndex].pfnCreateInstance(hWnd, lData, pstrText); } #endif // !_WIN32_WCE LONG CPlApplet_GetCount() { LONG nCount = 0; const ATLCPLAPPLETINFO* pObjects = _pAtlApplets; while( (*pObjects).pfnCreateInstance != NULL ) pObjects++, nCount++; return nCount; } #ifndef _WIN32_WCE void CPlApplet_Inquire(int iIndex, CPLINFO* pInfo) { ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount()); if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return; _pAtlApplets[iIndex].pfnGetAppletInfo(0, &_pAtlApplets[iIndex]); pInfo->idIcon = _pAtlApplets[iIndex].uIconRes; pInfo->idInfo = _pAtlApplets[iIndex].uInfoRes; pInfo->idName = _pAtlApplets[iIndex].uNameRes; pInfo->lData = _pAtlApplets[iIndex].lData; } #endif // !_WIN32_WCE void CPlApplet_NewInquire(int iIndex, NEWCPLINFO* pInfo) { ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount()); if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return; _pAtlApplets[iIndex].pfnGetAppletInfo(1, &_pAtlApplets[iIndex]); ::ZeroMemory(pInfo, sizeof(NEWCPLINFO)); pInfo->dwSize = sizeof(NEWCPLINFO); ::LoadString(ModuleHelper::GetResourceInstance(), _pAtlApplets[iIndex].uNameRes, pInfo->szName, sizeof(pInfo->szName) / sizeof(TCHAR)); ::LoadString(ModuleHelper::GetResourceInstance(), _pAtlApplets[iIndex].uInfoRes, pInfo->szInfo, sizeof(pInfo->szInfo) / sizeof(TCHAR)); pInfo->hIcon = ::LoadIcon(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(_pAtlApplets[iIndex].uIconRes)); pInfo->dwFlags = _pAtlApplets[iIndex].dwFlags; pInfo->dwHelpContext = _pAtlApplets[iIndex].dwHelpContext; pInfo->lData = _pAtlApplets[iIndex].lData; } LPTSTR _FindLastOf(LPTSTR pstr, TCHAR ch) const { LPTSTR pSep = NULL; for( LPTSTR p = pstr; *p != '\0'; p = ::CharNext(p) ) { if( *p == ch ) pSep = p; } return pSep; } }; extern CCPlAppletModule _Applets; #endif __ATLCPLAPPLET_H__
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 540 ] ] ]
65a4345eb81cac5a180d123eb0434cd22f1b190b
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/MiniMule/SystemInfo.cpp
8f4394165a23c956cb2712ed2ed5a509704d6c73
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
497
cpp
// modified by Stulle #include "stdafx.h" #include "SystemInfo.h" CSystemInfo::CSystemInfo(){ CSysInfo::Init(); } CSystemInfo::~CSystemInfo(){ } int CSystemInfo::GetCpuUsage(){ return cpu.GetUsage( &sys, &upTime ); } uint32 CSystemInfo::GetMemoryUsage(){ return CSysInfo::GetProcessMemoryUsageInt(); } int CSystemInfo::GetGlobalCpuUsage(){ return sys; } uint64 CSystemInfo::GetGlobalMemoryUsage(){ return CSysInfo::GetTotalPhys()-CSysInfo::GetAvailPhys(); }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 28 ] ] ]
f09937955ea2148bd4bebeb6aaa28116565449ed
097c5aee657c0a538c001d7af10ed466a9d48bce
/miniBenchArm/cosbiCpuid.cpp
6b10f718ed6bac3db1bd110c2cfe267892a3ca47
[]
no_license
sspeng/miniBench
711380a27c0a93960fb20a7d9ff902c6e40659cd
d37e76188beb9861106baee68d0a7f901b35c710
refs/heads/master
2020-03-20T09:05:52.929763
2011-08-15T05:29:11
2011-08-15T05:29:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,621
cpp
#include "cosbiCpuid.h" /* COSBI: Comprehensive Open Source Benchmarking Initiative Copyright (c) 2007 Van Smith This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. The current web address of the GNU General Public License is: http://www.gnu.org/licenses/gpl.html You can contact the authors of this software at: [email protected] See www.vanshardware.com or www.cosbi.org for more contact details. All code disabled for port to ARM CPU. Rick C. Hodgin August, 2011 */ enumCentaurCpuidLevel getCentaurCpuidLevel() { return eCentaurCpuidNotSupported; } bool isCentaurPadlockAesAvailable() { return(false); } bool isCentaurPadlockAes2Available() { return(false); } bool isCentaurPadlockHashEngineAvailable() { return(false); } bool isCentaurPadlockRandomNumberGeneratorAvailable() { return(false); } bool isCentaurPadlockMontgomeryMultiplierAvailable() { return(false); }
[ [ [ 1, 61 ] ] ]
93fe9a16a7f146fbb54126802e299bdd62a9efde
f7c9f93a80011976bcd0967b70076b710d6197b2
/VisualizationApp/src/animation/particleSystem.h
9e4b6d78c10c8372fa88c7bdd8dfc245b54b2ec0
[]
no_license
UnforeseenOcean/TheJanusMachine
5b59fe7139b5547018ca6aca452a6322a58606b5
e4bfa410daa0a7b004aa95d1323e79026ec1625f
refs/heads/master
2021-01-18T23:33:07.018388
2011-09-06T08:52:37
2011-09-06T08:52:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
#pragma once #include "ofMain.h" #include "ofVec3f.h" #include "Particle.h" class particleSystem { public: vector<Particle> particles; void setup(int numParticles); void drawAll(); void updateAll(float turbulence); void updateAll(); void calculate(); ofVec3f avgPosition; ofVec3f avgVelocity; ofVec3f stdDevPosition; ofVec3f stdDevVelocity; float pctLocked; };
[ [ [ 1, 3 ], [ 5, 13 ], [ 15, 20 ], [ 25, 29 ] ], [ [ 4, 4 ], [ 21, 24 ] ], [ [ 14, 14 ] ] ]
9d99f4e59e807c7b534a22dd90f0c59f5014990c
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/MyQtLog/ui_myqtlog.h
4ffa747ec3237314aec2e4183ec693b50eccf2a8
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
1,873
h
/******************************************************************************** ** Form generated from reading UI file 'myqtlog.ui' ** ** Created: Fri Feb 25 15:20:44 2011 ** by: Qt User Interface Compiler version 4.7.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MYQTLOG_H #define UI_MYQTLOG_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHeaderView> #include <QtGui/QTextBrowser> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_MyQtLogClass { public: QVBoxLayout *verticalLayout; QTextBrowser *logBrs; void setupUi(QWidget *MyQtLogClass) { if (MyQtLogClass->objectName().isEmpty()) MyQtLogClass->setObjectName(QString::fromUtf8("MyQtLogClass")); MyQtLogClass->resize(400, 300); verticalLayout = new QVBoxLayout(MyQtLogClass); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); logBrs = new QTextBrowser(MyQtLogClass); logBrs->setObjectName(QString::fromUtf8("logBrs")); verticalLayout->addWidget(logBrs); retranslateUi(MyQtLogClass); QMetaObject::connectSlotsByName(MyQtLogClass); } // setupUi void retranslateUi(QWidget *MyQtLogClass) { MyQtLogClass->setWindowTitle(QApplication::translate("MyQtLogClass", "MyQtLog", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class MyQtLogClass: public Ui_MyQtLogClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MYQTLOG_H
[ "[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 63 ] ] ]
0cf5eb4d2cd1d6492308c6f91875d9eae584f677
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/devicesrv/SystemSW/vibra_api/src/HwResManTest.cpp
3e83b9f5250769b3480d15ae66b5995573b93411
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
10,893
cpp
/* * Copyright (c) 2002 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: HwResManTest class member functions * */ // INCLUDE FILES #include <Stiftestinterface.h> #include "HwResManTest.h" #include <e32svr.h> // EXTERNAL DATA STRUCTURES //extern ?external_data; // EXTERNAL FUNCTION PROTOTYPES //extern ?external_function( ?arg_type,?arg_type ); // CONSTANTS //const ?type ?constant_var = ?constant; // MACROS //#define ?macro ?macro_def // LOCAL CONSTANTS AND MACROS //const ?type ?constant_var = ?constant; //#define ?macro_name ?macro_def // MODULE DATA STRUCTURES //enum ?declaration //typedef ?declaration // LOCAL FUNCTION PROTOTYPES //?type ?function_name( ?arg_type, ?arg_type ); // FORWARD DECLARATIONS //class ?FORWARD_CLASSNAME; // ============================= LOCAL FUNCTIONS =============================== // ----------------------------------------------------------------------------- // ?function_name ?description. // ?description // Returns: ?value_1: ?description // ?value_n: ?description_line1 // ?description_line2 // ----------------------------------------------------------------------------- // /* ?type ?function_name( ?arg_type arg, // ?description ?arg_type arg) // ?description { ?code // ?comment // ?comment ?code } */ // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CHwResManTest::CHwResManTest // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CHwResManTest::CHwResManTest() { } // ----------------------------------------------------------------------------- // CHwResManTest::ConstructL // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // void CHwResManTest::ConstructL() { iLog = CStifLogger::NewL( KHwResManTestLogPath, KHwResManTestLogFile); // Sample how to use logging iLog->Log(_L("HwResManTest logging starts!")); /* Create and install active scheduler */ myActiveScheduler = new CActiveScheduler; CActiveScheduler::Install(myActiveScheduler); iSession = CRepository::NewL(KCRUidVibraCtrl); } //----------------------------------------------------------------------------- // CHwResManTest::SendTestClassVersion // Method used to send version of test class //----------------------------------------------------------------------------- // void CHwResManTest::SendTestModuleVersion() { TVersion moduleVersion; moduleVersion.iMajor = TEST_MODULE_VERSION_MAJOR; moduleVersion.iMinor = TEST_MODULE_VERSION_MINOR; moduleVersion.iBuild = TEST_MODULE_VERSION_BUILD; TFileName moduleName; moduleName = _L("HwResManTest.dll"); TBool newVersionOfMethod = ETrue; CTestModuleIf &test=TestModuleIf(); test.SendTestModuleVersion(moduleVersion, moduleName, newVersionOfMethod); test.SetBehavior(CTestModuleIf::ETestLeaksHandles); } // ----------------------------------------------------------------------------- // CHwResManTest::NewL // Two-phased constructor. // ----------------------------------------------------------------------------- // CHwResManTest* CHwResManTest::NewL() { CHwResManTest* self = new (ELeave) CHwResManTest; CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop(); return self; } // Destructor CHwResManTest::~CHwResManTest() { delete iLog; delete iSession; /* Uninstall active scheduler */ CActiveScheduler::Install(NULL); /* Delete active scheduler */ delete myActiveScheduler; } // ----------------------------------------------------------------------------- // CHwResManTest::InitL // InitL is used to initialize the Test Module. // ----------------------------------------------------------------------------- // TInt CHwResManTest::InitL( TFileName& /*aIniFile*/, TBool /*aFirstTime*/ ) { return KErrNone; } // ----------------------------------------------------------------------------- // CHwResManTest::GetTestCasesL // GetTestCases is used to inquire test cases from the Test Module. Test // cases are stored to array of test cases. The Test Framework will be // the owner of the data in the RPointerArray after GetTestCases return // and it does the memory deallocation. // ----------------------------------------------------------------------------- // TInt CHwResManTest::GetTestCasesL( const TFileName& /*aConfig*/, RPointerArray<TTestCaseInfo>& aTestCases ) { // Loop through all test cases and create new // TTestCaseInfo items and append items to aTestCase array for( TInt i = 0; Case(i).iMethod != NULL; i++ ) { // Allocate new TTestCaseInfo from heap for a testcase definition. TTestCaseInfo* newCase = new( ELeave ) TTestCaseInfo(); // PushL TTestCaseInfo to CleanupStack. CleanupStack::PushL( newCase ); // Set number for the testcase. // When the testcase is run, this comes as a parameter to RunTestCaseL. newCase->iCaseNumber = i; // Set title for the test case. This is shown in UI to user. newCase->iTitle.Copy( Case(i).iCaseName ); // Append TTestCaseInfo to the testcase array. After appended // successfully the TTestCaseInfo object is owned (and freed) // by the TestServer. User::LeaveIfError(aTestCases.Append ( newCase ) ); // Pop TTestCaseInfo from the CleanupStack. CleanupStack::Pop( newCase ); } return KErrNone; } // ----------------------------------------------------------------------------- // CHwResManTest::RunTestCaseL // RunTestCaseL is used to run an individual test case specified // by aTestCase. Test cases that can be run may be requested from // Test Module by GetTestCases method before calling RunTestCase. // ----------------------------------------------------------------------------- // TInt CHwResManTest::RunTestCaseL( const TInt aCaseNumber, const TFileName& /*aConfig*/, TTestResult& aResult ) { SendTestModuleVersion(); // Return value TInt execStatus = KErrNone; // Get the pointer to test case function TCaseInfo tmp = Case ( aCaseNumber ); iLog->Log(_L("Starting testcase [%S]"), &tmp.iCaseName); // Check that case number was valid if ( tmp.iMethod != NULL ) { // Valid case was found, call it via function pointer iMethod = tmp.iMethod; execStatus = ( this->*iMethod )( aResult ); } else { // Valid case was not found, return error. execStatus = KErrNotFound; } // Return case execution status (not the result of the case execution) return execStatus; } void CHwResManTest::VibraModeChanged(CHWRMVibra::TVibraModeState aStatus) { RDebug::Print(_L("CHwResManTest - VibraModeChanged to: %d"), aStatus); modeUpdated = true; myMode = aStatus; switch(aStatus) { case CHWRMVibra::EVibraModeUnknown: { iLog->Log(_L("HwResManTest Vibra Mode changed to EVibraModeUnknown")); } break; case CHWRMVibra::EVibraModeON: { iLog->Log(_L("HwResManTest Vibra Mode changed to EVibraModeON")); } break; case CHWRMVibra::EVibraModeOFF: { iLog->Log(_L("HwResManTest Vibra Mode changed to EVibraModeOFF")); } break; default: iLog->Log(_L("HwResManTest Vibra Mode changed to %d"), aStatus); } } void CHwResManTest::VibraStatusChanged(CHWRMVibra::TVibraStatus aStatus) { RDebug::Print(_L("CHwResManTest - VibraStatusChanged to: %d"), aStatus); statusUpdated = true; myStatus = aStatus; switch(aStatus) { case CHWRMVibra::EVibraStatusUnknown: { iLog->Log(_L("HwResManTest Vibra status changed to EVibraStatusUnknown")); } break; case CHWRMVibra::EVibraStatusNotAllowed: { iLog->Log(_L("HwResManTest Vibra status changed to EVibraStatusNotAllowed")); } break; case CHWRMVibra::EVibraStatusStopped: { iLog->Log(_L("HwResManTest Vibra status changed to EVibraStatusStopped")); } break; case CHWRMVibra::EVibraStatusOn: { iLog->Log(_L("HwResManTest Vibra status changed to EVibraStatusOn")); } break; default: iLog->Log(_L("HwResManTest Vibra status changed to %d"), aStatus); } } void CHwResManTest::InitTestVariables() { modeUpdated = false; myMode = CHWRMVibra::EVibraModeUnknown; statusUpdated = false; myStatus = CHWRMVibra::EVibraStatusUnknown; } TInt CHwResManTest::RunTestVibra( CHWRMVibra* iVibra, TInt howLong, TInt whatIntensity) { TInt errorStatus; TRAP(errorStatus, iVibra->StartVibraL(howLong, whatIntensity)); iLog->Log(_L("HwResManTest Vibra start for %d seconds with intensity %d Error:%d"), howLong/1000, whatIntensity, errorStatus); return errorStatus; } TInt CHwResManTest::RunTestVibra( CHWRMVibra* iVibra, TInt howLong) { TInt errorStatus; TRAP(errorStatus, iVibra->StartVibraL(howLong)); iLog->Log(_L("HwResManTest Vibra start for %d seconds with default intensity Error:%d"), howLong/1000, errorStatus); return errorStatus; } TInt CHwResManTest::StopTestVibra(CHWRMVibra* iVibra) { TInt errorStatus; TRAP(errorStatus, iVibra->StopVibraL()); iLog->Log(_L("HwResManTest Vibra stop called Error:%d"),errorStatus); return errorStatus; } // ========================== OTHER EXPORTED FUNCTIONS ========================= // ----------------------------------------------------------------------------- // LibEntryL is a polymorphic Dll entry point // Returns: CTestModuleBase*: Pointer to Test Module object // ----------------------------------------------------------------------------- // EXPORT_C CTestModuleBase* LibEntryL() { return CHwResManTest::NewL(); } // End of File
[ "none@none" ]
[ [ [ 1, 386 ] ] ]
60e26d721072db192b66bb8ce40f69fd527eb538
2fb8c63d1ee7108c00bc9af656cd6ecf7174ae1b
/src/decomp/lzham_polar_codes.h
99adfaa838fa433b28b29aaf978bbc772f2fccf9
[ "MIT" ]
permissive
raedwulf/liblzham
542aca151a21837c14666f1d16957e61ba9c095d
01ce0ec2d78f4fda767122baa02ba612ed966440
refs/heads/master
2021-01-10T19:58:22.981658
2011-08-24T11:55:26
2011-08-24T11:55:26
2,227,012
3
0
null
null
null
null
UTF-8
C++
false
false
399
h
// File: lzham_polar_codes.h // See Copyright Notice and license at the end of include/lzham.h #pragma once namespace lzham { const uint cPolarMaxSupportedSyms = 600; uint get_generate_polar_codes_table_size(); bool generate_polar_codes(void* pContext, uint num_syms, const uint16* pFreq, uint8* pCodesizes, uint& max_code_size, uint& total_freq_ret); } // namespace lzham
[ [ [ 1, 13 ] ] ]
5cdaab3f03c036636c2eb340937e73a36bd8c91b
502efe97b985c69d6378d9c428c715641719ee03
/src/moaicore/MOAIThread.cpp
3fbb6cab2572c512159c216c88924b044a5d1c58
[]
no_license
neojjang/moai-beta
c3933bca2625bca4f4da26341de6b855e41b9beb
6bc96412d35192246e35bff91df101bd7c7e41e1
refs/heads/master
2021-01-16T20:33:59.443558
2011-09-19T23:45:06
2011-09-19T23:45:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,812
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAIActionMgr.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAIThread.h> //----------------------------------------------------------------// /** @name blockOnAction @text Skip updating current thread until the specified action is no longer busy. A little more efficient that spinlocking from Lua. @in MOAIAction blocker @out nil */ int MOAIThread::_blockOnAction ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "U" )) return 0; MOAIAction* current = MOAIActionMgr::Get ().GetCurrentAction (); if ( !current ) return 0; MOAIAction* blocker = state.GetLuaObject < MOAIAction >( 1 ); if ( !blocker ) return 0; current->SetBlocker ( blocker ); return lua_yield ( state, 0 ); } //----------------------------------------------------------------// /** @name currentThread @text Returns the currently running thread (if any). @out MOAIThread currentThread Current thread or nil. */ int MOAIThread::_currentThread ( lua_State* L ) { USLuaState state ( L ); MOAIAction* current = MOAIActionMgr::Get ().GetCurrentAction (); if ( !current ) return 0; current->PushLuaUserdata ( state ); return 1; } //----------------------------------------------------------------// /** @name run @text Starts a thread with a function and passes parameters to it. @in MOAIThread self @in function threadFunc @in ... @out nil */ int MOAIThread::_run ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIThread, "UF" ) if ( MOAIActionMgr::Get ().GetThreadInfoEnabled ()) { // Get a copy of the function's debug info and store it so we can // refer to it in any debugging info regarding this thread. lua_Debug ar; lua_pushvalue ( state, 2 ); lua_getinfo ( state, ">Snl", &ar ); bool isC = strcmp ( ar.what, "C" ) == 0; if ( !ar.what ) { ar.what = "??"; } if ( !ar.source ) { if ( isC ) { ar.source = "@?"; } else { ar.source = "@<string>"; } } self->mFuncName.clear (); if ( ar.name ) { self->mFuncName.write ( "%s:%s%s:%d", ar.what, ar.name, ar.source, ar.linedefined ); } else { self->mFuncName.write ( "%s:%s:%d", ar.what, ar.source, ar.linedefined ); } } self->mNarg = lua_gettop ( state ) - 2; self->mState = lua_newthread ( state ); self->mRef.SetRef ( state, -1, false ); lua_pop ( state, 1 ); lua_xmove ( state, self->mState, self->mNarg + 1 ); self->Start (); return 0; } //================================================================// // MOAIThread //================================================================// //----------------------------------------------------------------// bool MOAIThread::IsDone () { return this->mRef.IsNil (); } //----------------------------------------------------------------// MOAIThread::MOAIThread () : mState ( 0 ), mNarg ( 0 ) { RTTI_SINGLE ( MOAIAction ) } //----------------------------------------------------------------// MOAIThread::~MOAIThread () { } //----------------------------------------------------------------// void MOAIThread::OnUpdate ( float step ) { UNUSED ( step ); if ( this->mState ) { int result = lua_resume ( this->mState, this->mNarg ); this->mNarg = 0; if ( result != LUA_YIELD ) { if ( result != 0 ) { cc8* msg = lua_tostring ( this->mState, -1 ); USLog::Print ( "%s\n", msg ); lua_pop ( this->mState, 1 ); USLuaStateHandle state ( this->mState ); state.PrintStackTrace ( USLog::CONSOLE, 0 ); } this->mRef.Clear (); this->mState = 0; this->Stop (); } } } //----------------------------------------------------------------// void MOAIThread::RegisterLuaClass ( USLuaState& state ) { luaL_Reg regTable [] = { { "blockOnAction", _blockOnAction }, { "currentThread", _currentThread }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIThread::RegisterLuaFuncs ( USLuaState& state ) { MOAIAction::RegisterLuaFuncs ( state ); luaL_Reg regTable [] = { { "run", _run }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); lua_getglobal ( state, "coroutine" ); lua_getfield ( state, -1, "create" ); lua_setfield ( state, -3, "create" ); lua_getfield ( state, -1, "resume" ); lua_setfield ( state, -3, "resume" ); lua_pop ( state, 1 ); } //----------------------------------------------------------------// STLString MOAIThread::ToString () { return mFuncName; }
[ "[email protected]", "Patrick@agile.(none)", "[email protected]", "[email protected]" ]
[ [ [ 1, 4 ], [ 6, 59 ], [ 93, 108 ], [ 115, 144 ], [ 146, 189 ] ], [ [ 5, 5 ] ], [ [ 60, 60 ], [ 68, 68 ], [ 83, 83 ], [ 92, 92 ] ], [ [ 61, 67 ], [ 69, 82 ], [ 84, 91 ], [ 109, 114 ], [ 145, 145 ], [ 190, 194 ] ] ]
174de4d8f177cdd4ac5db8ca64680f4bd3013183
8fd82049c092a6b80f63f402aca243096eb7b3c8
/MFCMailServer/MFCMailServer/stdafx.cpp
793e15229597b2bdf734801d588d64f2b7032d98
[]
no_license
phucnh/laptrinhmang-k52
47965acb82750b600b543cc5c43d00f59ce5bc54
b27a8a02f9ec8bf953b617402dce37293413bb0f
refs/heads/master
2021-01-18T22:22:24.692192
2010-12-09T02:00:10
2010-12-09T02:00:10
32,262,504
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
// stdafx.cpp : source file that includes just the standard includes // MFCMailServer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #include "Smtp.h" INT pop3RequestId = 0; INT smtpRequestId = 0; CString logMessage; CPop3* serverPop3Socket; INT nPop3ConnectionsCount = 0; CSmtp* serverSmtpSocket; INT nSmtpConnectionsCount = 0; INT settingPop3Port = 110; INT settingSmtpPort = 25; CSMTPProcessList m_SMTPConnectionsList; CPOP3ProcessList m_POP3ConnectionsList; //Bien cua DAL DAL* dal; CString GetCurrentTimeStr() { CTime tDateTime = CTime::GetCurrentTime(); return tDateTime.Format("%m/%d/%Y %H:%M:%S"); }
[ "nguyenhongphuc.hut@e1f3f65c-33eb-5b6a-8ef2-7789ca584060" ]
[ [ [ 1, 34 ] ] ]
acace451f38cddf5ad1ff71793ff7acc6027a57a
a223f79e86853af3cabbaa25f2eb620e34fe7f51
/Include/KhaosEngine/KhaosApp.h
9d3b7e57f804050ddb6cefe0ed9c68f37544c724
[]
no_license
raistlin969/Khaos
4a100f42f7317cb33f84eedd79051b115bf17ca7
b29b6d69604805b743f7685e90a87225427d7023
refs/heads/master
2021-01-13T02:04:03.140528
2011-05-16T17:17:22
2011-05-16T17:17:22
1,708,771
0
0
null
null
null
null
UTF-8
C++
false
false
2,655
h
#pragma once #include "stdafx.h" #include "Utility/Optional.h" class KhaosApp { protected: HINSTANCE _hinstance; bool _windowed_mode; //true if windowed, false if fullscreen bool _running; //true if everything is init and game is in main loop bool _quit_requested; //true if app should run exit sequence bool _quitting; //true if exit sequence is running CRect _window_size; //current client window size CRect _desktop_size; //desktop size int _color_depth; //current color depth (16 or 32) int _has_modal_dialog; //determines if modal dialog is up protected: // int PumpUntilMessage(UINT msg_end, WPARAM* wp, LPARAM* lp); // int EatSpecificMessage(UINT msg_type, Optional<LPARAM> lp, Optional<WPARAM> wp); // void FlashWhileMinimized(); public: KhaosApp(); HWND GetHwnd(); HINSTANCE GetInstance() { return _hinstance; } //virtuals virtual bool InitInstance(HINSTANCE hinstance, LPWSTR command_line, HWND hwnd = NULL, int screen_width = SCREEN_WIDTH, int screen_height = SCREEN_HEIGHT); //pure virtuals virtual TCHAR* GetGameTitle() = 0; virtual TCHAR* GetGameAppDirectory() = 0; virtual HICON GetIcon() = 0; //directx stuff static HRESULT CALLBACK OnCreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); static bool CALLBACK IsDeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); static HRESULT CALLBACK SwapChainResized( ID3D11Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); static void CALLBACK FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ); static void CALLBACK SwapChainRelease( void* pUserContext ); static void CALLBACK OnDestroyDevice( void* pUserContext ); static void CALLBACK OnUpdateGame(double fTime, float fElapsedTime, void* pUserContext); static bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); //msg proc static LRESULT CALLBACK MsgProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, bool* no_further_processing, void* user_context); //main loop processing void AbortGame() { _quitting = true; } int GetExitCode() { return DXUTGetExitCode(); } bool IsRunning() { return _running; } void SetQuitting(bool quitting) { _quitting = quitting; } }; extern KhaosApp* g_app;
[ [ [ 1, 60 ] ] ]
41484d9408a6f63fac039f5df0877428781a36d9
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/include/Ngl/Manager/EntityVisitorMemFun.h
7d4eb71023c5f637cfe3ef6d043cddd1fdd4057b
[]
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
1,216
h
/*******************************************************************************/ /** * @file EntityVisitorMemFun.h. * * @brief 引数なし関数ポインタ訪問者クラス定義. * * @date 2008/07/16. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_ENTITYVISITORMEMFUN_H_ #define _NGL_ENTITYVISITORMEMFUN_H_ #include "IEntityVisitor.h" namespace Ngl{ /** * @class EntityVisitorMemFun. * @brief 引数なし関数ポインタ訪問者クラス. * @tparam Entity 訪問した要素. * @tparam MemFun 訪問関数ポインタ( void 関数() ). */ template < typename Entity, typename void (Entity::*MenFun)() > class EntityVisitorMemFun : public IEntityVisitor<Entity*> { public: /*=========================================================================*/ /** * @brief 訪問する * * @param[in] entity 訪問した要素. * @return なし. */ void visit( Entity* entity ) { (entity->*MemFun)(); } }; } // namespace Ngl #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 55 ] ] ]
d92ea1ff8397f563de8c6cd940edb6833dc49a73
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Jiki/Jiki.cpp
cc886e3b7c1f68a4d7fb37301fe9db2a0c7ac21b
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
ISO-8859-1
C++
false
false
43,211
cpp
#include ".\jiki.h" #include "..\\Management\\GameControl.h" #include "..\\Light\\Light.h" #include "..\\Event\\GameOverEvt.h" #include "..\\Stage\\Checkpoint\\CheckpointController.h" #include "..\\Collision\\Rect.h" #include "..\\Object\\Ashiba.h" #include "..\\Object\\AshibaTenbin.h" #include "..\\Event\\ResetMobEvt.h" #include "..\\Event\\RestoreTekiAfterCheckpoint.h" #include "..\\Effect\\HitEffect.h" //?±??¾’ï½°?¼?®?ï¾?¾žï½°?? int Jiki::sAniData[][ANIFR] = { { 0, 1, 2, 3, 4, 5, 6, 7,99}, // WALK { 0, 1, 2, 1, 3, 4, 5, 4,99}, // TEISHI { 0, 1, 2, 3, 4,99}, // HANTEN { 0, 1, 2,99}, // KOGEKI_START { 3, 4, 5, 6,99}, // KOGEKI { 3, 4, 5, 6, 7, 8, 9,99}, // KOGEKI_END { 0, 1, 2, 3, 4,99}, // KOGEKI_STAN { 0, 1,99}, // JUMP_START { 2, 3, 4,99}, // JUMP_UP { 5, 6, 7,99}, // JUMP_DOWN { 8, 0,99}, // JUMP_END { 0, 1,99}, // DRILL_START { 2, 3,99}, // DRILL { 4, 5, 6, 7, 8,99}, // DRILL_END { 0, 1, 2, 1,99}, // FUYU { 0, 1,99}, // DAMAGE { 2, 3,99}, // DAMAGE_END { 0, 1, 2, 3,99}, // HISATU { 3, 99 }, // DEAD { 3, 99 }, // MAKUDOWN { 3, 99 }, // FADEOUT { 0, 1, 2, 1, 3, 4, 5, 4,99}, // FADEIN }; //?Œï¾šï½°?‘ごとの?±??¾’ï½°?¼?®?è£œé–“時間 double Jiki::sAniTime[][ANIFR] = { { 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2}, // WALK { 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2}, // TEISHI { 0.12, 0.12, 0.12, 0.12, 0.12}, // HANTEN { 0.06, 0.06, 0.08}, // KOGEKI_START { 0.08, 0.08, 0.08, 0.08}, // KOGEKI { 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13},// KOGEKI_END { 0.2, 0.2, 0.2, 0.2, 0.2}, // KOGEKI_STAN { 0.2, 0.2}, // JUMP_START { 0.2, 0.2, 0.2}, // JUMP_UP { 0.2, 0.2, 0.2}, // JUMP_DOWN { 0.2, 0.2}, // JUMP_END { 0.2, 0.2}, // DRILL_START { 0.2, 0.2}, // DRILL { 0.2, 0.2, 0.2, 0.2, 0.2}, // DRILL_END { 0.2, 0.2, 0.2, 0.2}, // FUYU { 0.2, 0.2}, // DAMAGE { 0.2, 0.2}, // DAMAGE_END { 0.2, 0.2, 0.2, 0.2}, // HISATU { 0.2 }, // DEAD { 0.2 }, // MAKUDOWN { 0.2 }, // FADEOUT { 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2}, // FADEIN }; //?¸?žï¾—フィ?¯?¸ char Jiki::sGraphic[][GRAME] = { "graphics\\heroine\\heroine_work.png", // WALK "graphics\\heroine\\heroine_stend.png", // TEISHI "graphics\\heroine\\heroine_turn.png", // HANTEN "graphics\\heroine\\heroine_attack.png", // KOGEKI_START "graphics\\heroine\\heroine_attack.png", // KOGEKI "graphics\\heroine\\heroine_attack.png", // KOGEKI_END "graphics\\heroine\\heroin_stan.png", // KOGEKI_STAN "graphics\\heroine\\heroine_jump.png", // JUMP_START "graphics\\heroine\\heroine_jump.png", // JUMP_UP "graphics\\heroine\\heroine_jump.png", // JUMP_DOWN "graphics\\heroine\\heroine_jump.png", // JUMP_END "graphics\\heroine\\heroine_drillkick.png", // DRILL_START "graphics\\heroine\\heroine_drillkick.png", // DRILL "graphics\\heroine\\heroine_drillkick.png", // DRILL_END "graphics\\heroine\\heroine_fall.png", // FUYU "graphics\\heroine\\heroin_damage.png", // DAMAGE "graphics\\heroine\\heroin_damage.png", // DAMAGE_END "graphics\\heroine\\heroin_ special.png", // HISATU "graphics\\heroine\\heroin_damage.png", // DEAD "graphics\\heroine\\heroin_damage.png", // MAKUDOWN "graphics\\heroine\\heroin_damage.png", // FADEOUT "graphics\\heroine\\heroine_stend.png", // FADEIN }; //当たり判定ï¾?¾žï½°?? int Jiki::sHitX[][4][TENSU] = { { { 40, 57, 89,-1}, //ä¸? { 62, -1}, //ä¸? { 90, 90, 90, 90, 90, 90,-1}, //å‰? { 31, 19, -1}, //å¾? } }; int Jiki::sHitY[][4][TENSU] = { { {118,118,118,-1 }, //ä¸? { 0, -1}, //ä¸? {117, 110, 95, 65, 40, 25, -1}, //å‰? {115, 11, -1}, //å¾? } }; // チェイン float Jiki::sChainMultSp[] = { 1.2f, 1.3f, 1.4f, 1.5f, 1.7f, 1.9f }; // チェイン float Jiki::sChainMultShoSp[] = { 1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f }; Jiki::Jiki(int rXPx, int rYPy) { // 設定定数 LIFE_MAX = GI("LIFE_MAX"); LIFE_SHOKI = GI("LIFE_SHOKI"); EMP_SHOKI = GF("EMP_SHOKI"); HERSIZE = GI("HERSIZE"); DAMAGE_SP = GF("DAMAGE_SP"); EMP_DOWN = GF("EMP_DOWN"); EMP_MAX = GF("EMP_MAX"); TEN_DOWN2 = GF("TEN_DOWN2"); TEN_UP2 = GF("TEN_UP2"); TEN_MAX = GF("TEN_MAX"); EMP_UP = GF("EMP_UP"); SPANI = GF("SPANI"); SPWALK = GF("SPWALK"); ACCKOGEKI = GF("ACCKOGEKI"); STAN_TIME = GF("STAN_TIME"); STAN_ANI = GF("STAN_ANI"); JUMP_SHOSP = GF("JUMP_SHOSP"); DRILL_SP = GF("DRILL_SP"); FUYU_SP = GF("FUYU_SP"); HISATU_TIME = GF("HISATU_TIME"); MUTEKI_TIME = GF("MUTEKI_TIME"); TENMETU_TIME = GF("TENMETU_TIME"); END_TIME = GF("END_TIME"); DRILL_HEIGTH = GF("DRILL_HEIGTH"); HANTEN_TIME = GF("HANTEN_TIME"); HISATU_LTSP = GF("HISATU_LTSP"); HISATU_HRSP = GF("HISATU_HRSP"); HISATU_FADE = GF("HISATU_FADE"); TEN_UTIME = GF("TEN_UTIME"); TEN_UP1 = GF("TEN_UP1"); TEN_DTIME = GF("TEN_DTIME"); TEN_DOWN1 = GF("TEN_DOWN1"); HER_DIE_TIME = GF("HER_DIE_TIME"); mInterface = new InterfaceView(this, GAMECONTROL->GetMaku()); mX = rXPx; mY = rYPy; mZ = 100.0f; mSpX = 0; mSpY = 0; mAccX = 0; mAccY = 0; mSizeX = HERSIZE; mSizeY = HERSIZE; //??¾žï¾’ï½°?¼?? ResetTempParams(); //?¹?žï½°?¼?žé¡? ResetLife(); ResetTension(); ResetEmpacy(); //SE mDmSE = false; mDmSETimer = 0; mTenSE = false; mHisatuSE = false; collisionEnabled = true; mNoDamage = false; mChainIdx = 0; // 当たり判å®? AddFrame(FR_ARUKI); AddFrame(FR_TACHI); AddFrame(FR_JUMP); AddFrame(FR_DRILL); AddFrame(FR_KOGEKI); AddFrame(FR_HISATU); AddFrame(FR_DISABLE); AddCircle(FR_ARUKI, SP->GRID_BOGYO, 64, 37, 16); AddCircle(FR_ARUKI, SP->GRID_BOGYO, 67, 65, 12); AddCircle(FR_ARUKI, SP->GRID_BOGYO, 69, 99, 20); AddCircle(FR_ARUKI, SP->GRID_HOUSE, mSizeX/2, mSizeY/2, 2); AddIndexedRect(FR_ARUKI, SP->GRID_BOUND, 0, 35, 80, 85, 118); AddCircle(FR_TACHI, SP->GRID_BOGYO, 63, 37, 16); AddCircle(FR_TACHI, SP->GRID_BOGYO, 63, 67, 16); AddCircle(FR_TACHI, SP->GRID_BOGYO, 63, 98, 20); AddCircle(FR_TACHI, SP->GRID_HOUSE, mSizeX/2, mSizeY/2, 2); AddIndexedRect(FR_TACHI, SP->GRID_BOUND, 0, 35, 80, 85, 118); AddCircle(FR_JUMP, SP->GRID_BOGYO, 53, 34, 16); AddCircle(FR_JUMP, SP->GRID_BOGYO, 59, 62, 12); AddCircle(FR_JUMP, SP->GRID_BOGYO, 57, 95, 20); AddCircle(FR_JUMP, SP->GRID_HOUSE, mSizeX/2, mSizeY/2, 2); AddIndexedRect(FR_JUMP, SP->GRID_BOUND, 0, 35, 80, 85, 118); AddCircle(FR_DRILL, SP->GRID_BOGYO, 76, 44, 16); AddCircle(FR_DRILL, SP->GRID_BOGYO, 53, 67, 16); AddCircle(FR_DRILL, SP->GRID_KOUGEKI, 25, 95, 24); AddCircle(FR_DRILL, SP->GRID_HOUSE, mSizeX/2, mSizeY/2, 2); AddIndexedRect(FR_DRILL, SP->GRID_BOUND, 0, 10, 80, 85, 118); AddCircle(FR_KOGEKI, SP->GRID_BOGYO, 55, 38, 16); AddCircle(FR_KOGEKI, SP->GRID_BOGYO, 55, 69, 16); AddCircle(FR_KOGEKI, SP->GRID_BOGYO, 55, 101, 16); AddCircle(FR_KOGEKI, SP->GRID_KOUGEKI, 24, 92, 24); AddCircle(FR_KOGEKI, SP->GRID_HOUSE, mSizeX/2, mSizeY/2, 2); AddIndexedRect(FR_KOGEKI, SP->GRID_BOUND, 0, 35, 80, 85, 118); AddCircle(FR_HISATU, SP->GRID_KOUGEKI, 58, 68, 48); AddCircle(FR_HISATU, SP->GRID_HOUSE, mSizeX/2, mSizeY/2, 2); AddIndexedRect(FR_HISATU, SP->GRID_BOUND, 0, 35, 80, 85, 118); SetCurFrame(FR_ARUKI); } void Jiki::ResetEmpacy(){ mEmp = EMP_SHOKI; mEmpTeki = 0; } void Jiki::ResetLife(){ mLife = LIFE_SHOKI; } void Jiki::ResetTension(){ mTen = 0; mTenTime = 0; mTenFl = false; } void Jiki::ResetTempParams() { //?±??¾’ï½°?¼?®?? mAniTimer = 0; mAniNoX = 0; mAniNoY = 0; //?½??½°??½½ //SetSuperWait(3.0f); mStatus = WALK; mMuki = 1; //?¹?žï½°?‘ï½µ?°?Šï¾žï½° mGmOvFl = 0; // ãƒ?ƒ¡ãƒ¼ã‚¸ mDgMutekiFl = 0; mDgMapFl = false; mDamageTimer = 0; //mTenmetuTimer = 0; mAlphaVal = 1.0f; mAlphaTimer = 0.0f; //?—ï½²?? mAkaTimer = 0; mAkaTimer2 = 0; mStanTimer = 0; mStanAni = 0; mAoTimer = 0; mMidTimer = 0; mAniTeishi = false; mMidFl = false; mHozonY = mY; mDrillFl = 0; mHisatuTime = 0; mHsX = 0; mHsY = 0; //?Œï½ª?°??¾? mFadeFl = 0; mFadeFl2 = false; //足場 mAshibaFl = false; mCurAshiba = NULL; mAshiSpX = 0; //強風 mKazeAccX = 0; // ??½¬?°?¼?žï½´?Œï½ª?¸?? mChargeFx = NULL; } Jiki::~Jiki(void) { delete mInterface; } // ?º?˜ï½¼?žï½®?ç”¨ã€è?機ã??»?²?½?žã‚’返す int Jiki::GetSizeX() { return HERSIZE; } /* 基本?¸?—スの??½½?¸ã‚’ã?っきり行いまã? */ void Jiki::RunTask() { Collidable::RunTask(); LightResponseAble::RunTask(); } /* ?‹ï¾›ï½²?ã«??¾žï¾’ï½°?¼?žã‚’与えã‚? */ void Jiki::InflictDamage() { if( mDgMutekiFl == 0 && !mHouseProtected){ if( mStatus != DAMAGE && mStatus != DAMAGE_END && mStatus != DEAD && mStatus != FADEIN && mStatus != FADEOUT && mSuperStatus == CONTROL && !mNoDamage){ // SE GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_kougekimeityuu.wav"); mStatus = DAMAGE; mDgMutekiFl = 1; mDgMapFl= true; mAniNoX = 0; mSpY = DAMAGE_SP; // 足場から降りã‚? if( mCurAshiba ) { mCurAshiba->GetOff(this); mCurAshiba = NULL; } mDmSETimer = 0; SetTransparent(true); //?´?ï¾Šï¾Ÿï½¼?° mEmp -= EMP_DOWN; if( mEmp <= 0 ){ Die(); } if( mEmp > EMP_MAX ) mEmp = EMP_MAX; //??¾ï½¼?®?? mTen -= TEN_DOWN2; if( mTen < 0 ) mTen = 0; if( mTen > TEN_MAX ) mTen = TEN_MAX; ResetChain(); } } } /* ?‹ï¾›ï½²?ã???¾ï½¼?®?or??¾ï¾Šï¾Ÿï½¼?°ã‚’上げã‚? */ void Jiki::IncreaseTensEmpa() { //??¾ï½¼?®?? if( mStatus == KOGEKI || mStatus == KOGEKI_START || mStatus == KOGEKI_END || mStatus == DRILL || mStatus == DRILL_START ){ RestoreTension(TEN_UP2, false); } //?´?ï¾Šï¾Ÿï½¼?° if( mStatus == HISATU ){ mEmpTeki++; if( mEmpTeki == EMP_UP ){ mEmpTeki = 0; RestoreEmpacy(1, false); } } } /* すべての当たり判定をオフにする */ void Jiki::DisableCollision() { collisionEnabled = false; SetCurFrame( FR_DISABLE ); } /* すべての当たり判定をオンにする */ void Jiki::EnableCollision() { collisionEnabled = true; } /* ヒロインを演å?モードにする (停止) */ void Jiki::SetSuperWait(float rTime) { SetLightResponse(false); DisableCollision(); mSuperStatus = WAIT; mSuperWaitTimer = rTime; } /* ヒロインを操作モードにする (普é€? */ void Jiki::SetSuperControl() { SetLightResponse(true); EnableCollision(); mSuperStatus = CONTROL; } /* ヒロインをいったん止める */ void Jiki::SetSuperPause() { SetLightResponse(false); DisableCollision(); mSuperStatus = PAUSE; mSpX = 0; mSpY = 0; mAccX = 0; mAccY = SP->GRAVITY; } void Jiki::Move() { //?ï½¯?Œï¾Ÿã¨ã®å½“たり判å®? MapAtHt(); //?±??¾’ï½°?¼?®?? int no; bool dosa_end = false; mAniNoY = mStatus; // チェインに反映させã‚?歩きと攻æ’??み) float mfactor = 1.0f; if( mStatus == KOGEKI || mStatus == KOGEKI_END || mStatus == KOGEKI_START || mStatus == WALK || mStatus == HANTEN ) { mfactor = sChainMultSp[mChainIdx]; } mAniTimer += SP->FrameTime; if( mAniTimer >= sAniTime[mAniNoY][mAniNoX]/mfactor ){ mAniTimer = 0; if( !mAniTeishi ) mAniNoX++; no = sAniData[mAniNoY][mAniNoX]; if( no == 99 ){ mAniNoX = 0; dosa_end = true; } } no = sAniData[mAniNoY][mAniNoX]; mAniTeishi = false; //?´?Œï½ª?¸????±??¾’ï½°?¼?®?? if( mStatus == KOGEKI_STAN && mAniNoX > 2 ){ WAIT_TIMER(mStanTimer, STAN_ANI) mStanTimer = 0; mStanAni++; if( mStanAni > 4 ) mStanAni = 0; WAIT_END } // スーパã?スãƒ??タス switch( mSuperStatus ){ case WAIT: { mStatus = TEISHI; mSpX = 0; mAccX = 0; // タイマã? mSuperWaitTimer -= SP->FrameTime; if( mSuperWaitTimer < 0 ){ mSuperWaitTimer = 0; SetSuperControl(); } break; } case PAUSE: { mStatus = TEISHI; mSpX = 0; mAccX = 0; break; } case CONTROL: { //?½??½°??½½ switch( mStatus ){ //æ­©ã? case WALK : mSpX = SPWALK*sChainMultSp[mChainIdx] * GetMukiMult(); break; //攻æ’??—ï½²??µ¤) case KOGEKI_START : mSpX = SPWALK*sChainMultSp[mChainIdx] * GetMukiMult(); mAccX = 0; //開始ア??¾’ï½°?¼?®?ãŒçµ‚わったら攻æ’?¸ if( dosa_end ){ mStatus = KOGEKI; //SE GAMECONTROL->GetSoundController()->LoopSE("audio\\se\\se_hiroin_tijoukougeki.wav"); } break; case KOGEKI : mAccX = (float)( ACCKOGEKI / SP->FRAMERATE ) * GetMukiMult(); //mSpX += mAccX * GetMukiMult(); break; case KOGEKI_STAN : mAkaTimer2 += SP->FrameTime; mSpX = 0; mAccX = 0; //?±??¾’ï½°?¼?®??+を停止 if( mAniNoX == 4 ) mAniTeishi = true; //歩きに戻ã? if( mAkaTimer2 >= STAN_TIME ){ mStatus = WALK; } break; //停止・反転(?—ï½²??’) case TEISHI : mSpX = 0; mAccX = 0; break; case HANTEN : mSpX = 0; mAccX = 0; //反転?±??¾’ï½°?¼?®?ãŒçµ‚わったら向きを変えて歩きへ if( dosa_end ){ mMuki = !mMuki; mStatus = WALK; } break; //?¼?žï½¬?ï¾Œï¾??—ï½²??·? case JUMP_START : // 足場に乗ってã?‚‹å ´åˆã?、まず降りる if(mCurAshiba) mCurAshiba->GetOff(this); mCurAshiba = NULL; mSpX = 0; mAccX = 0; //開始ア??¾’ï½°?¼?®?ãŒçµ‚わったら?¼?žï½¬?ï¾Œï¾Ÿã¸ if( dosa_end ){ mSpY = JUMP_SHOSP*sChainMultShoSp[mChainIdx]; mStatus = JUMP_UP; } break; case JUMP_UP : //前が当たってなã?™‚のX if( mHitFl[2] == SP->CHIP_NOHIT ) mSpX = SPWALK * sChainMultSp[mChainIdx] * GetMukiMult(); //?±??¾’ï½°?¼?®??+を停止 if( mAniNoX == 2 ) mAniTeishi = true; //頂点に達したら落下へ if( mSpY >= 0 ){ mStatus = JUMP_DOWN; mAniNoX = 0; } break; case JUMP_DOWN : //前が当たってなã?™‚のX if( mHitFl[2] == SP->CHIP_NOHIT ){ mSpX = SPWALK * GetMukiMult(); } //?±??¾’ï½°?¼?®??+を停止 if( mAniNoX == 2 ) mAniTeishi = true; break; //??¾žï¾˜ï¾™ï½·?¯?¸ case DRILL_START : if( mDrillFl == 2 ){ mSpX = DRILL_SP * GetMukiMult(); mSpY = DRILL_SP; } //開始ア??¾’ï½°?¼?®?ãŒçµ‚わったら??¾žï¾˜ï¾™ï½·?¯?¸ã¸ if( dosa_end ){ mStatus = DRILL; } break; case DRILL : if( mDrillFl == 2 ){ mSpX = DRILL_SP * GetMukiMult(); mSpY = DRILL_SP; } break; //æµ®é? case FUYU : mSpX = 0; mAccX = 0; mAccY = 0; mSpY = FUYU_SP; break; //??¾žï¾’ï½°?¼?? case DAMAGE : mDgMapFl = true; //後が当たってなã?™‚のX if( mHitFl[3] != SP->CHIP_HIT && mHitFl[3] != SP->CHIP_GMNGAIRT && mHitFl[3] != SP->CHIP_GMNGAILT && mHitFl[3] != SP->CHIP_KGHIT ) mSpX = SPWALK * -GetMukiMult(); if( mAniNoX == 1 ){ mAniTeishi = true; // SE if( !mDmSE ){//?´?ï¾Šï¾Ÿï½¼?°ãŒæ¸›ã‚‹ WAIT_TIMER( mDmSETimer, 0.2 ) GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_hiroin_damage.wav"); mDmSE = true; WAIT_END } } break; case DAMAGE_END : mSpX = 0; mAccX = 0; mDmSE = false; mDmSETimer = 0; //終äº?½±??¾’ï½°?¼?®?ãŒçµ‚わったら歩きへ if( mGmOvFl == 0 ){ if( dosa_end ){ mStatus = WALK; mDgMutekiFl = 2; mDgMapFl = false; } }else{ if( dosa_end ) { mAniNoX = 1; if( mGmOvFl == 1 ) mGmOvFl = 2; } } break; //終äº?‹•ä½? case KOGEKI_END : /* mSpX = SPWALK*sChainMultSp[mChainIdx] * GetMukiMult(); mAccX = 0; if( dosa_end ){ mStatus = WALK; } break;*/ case JUMP_END : case DRILL_END : //歩きに戻ã? mSpX = 0; mAccX = 0; if( dosa_end ){ mStatus = WALK; } break; //å¿?®ºæŠ? case HISATU : { mHisatuTime += SP->FrameTime; //?—ï½²???速度減å°? CONTROLLIGHT->SetSpX( GAMECONTROL->GetDXController()->GetMouseState().lX / HISATU_LTSP ); CONTROLLIGHT->SetSpY( GAMECONTROL->GetDXController()->GetMouseState().lY / HISATU_LTSP ); //?½?¸?›ï½°?™ã‚’?—ï½²??¨çµ±ä¸? int scpx = GAMECONTROL->GetStageManager()->GetCurScrollPointer(); mHsX = CONTROLLIGHT->GetX() - HERSIZE/2; mHsY = CONTROLLIGHT->GetY() - HERSIZE/2; //?‹ï¾›ï½²?ã?ç§»å‹? float sax = mHsX - (mX- scpx); float say = mHsY - mY; if( mHsX > mX - scpx && sax > HISATU_HRSP ) mSpX = sax/HISATU_HRSP; if( mHsX < mX - scpx && sax < HISATU_HRSP ) mSpX = sax/HISATU_HRSP; if( mHsX == mX - scpx ) { mSpX = 0; mAccX = 0; } if( mHsY > mY && say > HISATU_HRSP ) mSpY = say/HISATU_HRSP; if( mHsY < mY && say < HISATU_HRSP ) mSpY = say/HISATU_HRSP; if( mHsY == mY ) mSpY = 0; // 速度限界 if( mSpX > GF("HISATSU_MAXSP") ) mSpX = GF("HISATSU_MAXSP"); if( mSpX < -GF("HISATSU_MAXSP") ) mSpX = -GF("HISATSU_MAXSP"); if( mSpY > GF("HISATSU_MAXSP") ) mSpY = GF("HISATSU_MAXSP"); if( mSpY < -GF("HISATSU_MAXSP") ) mSpY = -GF("HISATSU_MAXSP"); //?‹ï¾›ï½²?ã?向き if( mSpX < 0 ){ mMuki = 0;//â†? } if( mSpX >= 0 ){ mMuki = 1;//â†? } //当たり判定â? GAMECONTROL->GetStageManager()->GetCurMap()->SuperAtariHantei( mX, mY, mMuki, mSpX, mSpY, mAccX, mAccY, sHitX[0], sHitY[0], HERSIZE, HERSIZE, mHitFl, mKabeIchi); if( mHitFl[2] == SP->CHIP_HIT || mHitFl[2] == SP->CHIP_GMNGAIRT || mHitFl[2] == SP->CHIP_GMNGAILT || mHitFl[2] == SP->CHIP_KGHIT){ if( mSpX * -GetMukiMult() < 0 ) { mSpX = 0;//å‰? mAccX = 0; if( mMuki ){ mX = mKabeIchi[2] - sHitX[0][2][0]; } else{ mX = mKabeIchi[2] - ( HERSIZE - sHitX[0][2][0]); } } } if( mHitFl[0] == SP->CHIP_AMHIT || mHitFl[0] == SP->CHIP_KGHIT || mHitFl[0] == SP->CHIP_HIT ){ if( mSpY >= 0 ) { mSpY = 0;//ä¸? mAccY = 0; //if(!mCurAshiba && mHitFl[0] != SP->CHIP_KGHIT) mY = (float)mKabeIchi[0] - sHitY[0][0][0]; } } if( mHitFl[1] == SP->CHIP_HIT || mHitFl[1] == SP->CHIP_KGHIT ){ if( mSpY < 0 ) { mSpY = 0;//ä¸? mAccY = 0; mY = mKabeIchi[1] - sHitY[0][1][0]; } } //時間がきたら終äº? if( mHisatuTime > HISATU_TIME ){ GAMECONTROL->GetFader()->SetSpeed( 0.03 ); GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOff(); if( !mHisatuSE ){//SE GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_hiroin_hissatu_end.wav"); GAMECONTROL->GetSoundController()->SetBGM(GAMECONTROL->GetStageManager()->GetCurrentStage()->GetBGM()); mHisatuSE = true; } //å¿?®ºæŠ?µ‚äº?¾Œï½ª?°??¾? if( !mFadeFl2 && GAMECONTROL->GetFader()->FadeOut() ){ mHisatuTime = 0; mStatus = JUMP_DOWN; mAniNoX = 0; mX += mSpX; mSpX = SPWALK * -GetMukiMult(); mTen = 0; mEmpTeki = 0; //?—ï½²???速度戻ã? CONTROLLIGHT->SetSpX( GAMECONTROL->GetDXController()->GetMouseState().lX ); CONTROLLIGHT->SetSpY( GAMECONTROL->GetDXController()->GetMouseState().lY ); //l->TurnOff(); mDgMapFl = false; mDgMutekiFl = 0; mFadeFl2 = true; mHisatuSE = false; } } mChargeFx->SetPos(mX + HERSIZE/2, mY + HERSIZE/2); break; } case DEAD: WAIT_TIMER(mAlphaTimer, HER_DIE_TIME) mLife--; if( mLife == 0){ mGmOvFl = 1; mStatus = DAMAGE_END; } else{ mStatus = FADEOUT; } WAIT_END break; case FADEOUT: if( GAMECONTROL->GetFader()->FadeOut()){ mStatus = FADEIN; Stage* curStage = GAMECONTROL->GetStageManager()->GetCurrentStage(); GAMECONTROL->GetSoundController()->ResetSEs(); // ?‹ï¾›ï½²?ã?位置をチェãƒ?‚¯ãƒã‚¤ãƒ³ãƒˆã«èª¿æ•´ int restorePointX = curStage->GetCheckpointController()->GetStartPointX(mX + HERSIZE/2); int restorePointY = curStage->GetCheckpointController()->GetStartPointY(mX + HERSIZE/2); GAMECONTROL->GetStageManager()->GetCurMap()->SetScrollP( restorePointX - GI("SCRSZX")/2); mY = restorePointY - HERSIZE; mX = restorePointX - HERSIZE/2; // 透æ?にする SetTransparent(true); // 当たり判定を有効に戻ã? EnableCollision(); // ?—ï½²??“ä½œã‚’戻ã? SetLightResponse(true); // ãƒ?ƒ³ã‚·ãƒ§ãƒ³ã¨ã‚¨ãƒ³ãƒ‘シーをリセãƒ?ƒˆ ResetEmpacy(); ResetTension(); // 現在出てるものをå?部消す GAMECONTROL->GetEventManager()->Request(new ResetMobEvt()); // 敵を復活地に従って復活させã‚? GAMECONTROL->GetEventManager()->Request(new RestoreTekiAfterCheckpoint( mX + HERSIZE/2 )); //制限時間リセ?¯?? GAMECONTROL->GetStageManager()->GetCurrentStage()->GetSeigenJikan()->SeigenJikanReset(); } break; case FADEIN: if( GAMECONTROL->GetFader()->FadeIn() ){ mStatus = WALK; // 無敵にする mDgMutekiFl = 2; mDgMapFl = false; GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOn(); GAMECONTROL->GetSoundController()->SetBGM(GAMECONTROL->GetStageManager()->GetCurrentStage()->GetBGM()); } } break; } } //?Œï½ª?°??¾? Fade(); //SE?™ï½°?Œï¾Ÿçµ‚äº? if( mStatus != KOGEKI ) GAMECONTROL->GetSoundController()->StopSE("audio\\se\\se_hiroin_tijoukougeki.wav"); if( mStatus != DRILL && mStatus != DRILL_START ) GAMECONTROL->GetSoundController()->StopSE("audio\\se\\se_hiroin_kuutyuukougeki.wav"); //??¾žï¾’ï½°?¼?? if( mDgMutekiFl == 2 ){ mDamageTimer += SP->FrameTime; //mTenmetuTimer += SP->FrameTime; //無敵時間 if( mDamageTimer > MUTEKI_TIME ){ mDamageTimer = 0; //mTenmetuTimer =0; mDgMutekiFl = 0; SetTransparent(false); } } //ç§»å‹? if( (mStatus != HISATU && mStatus != TEISHI) || mSuperStatus != CONTROL) mSpY += mAccY;//常に重力が代入されてã?‚‹ if( !(mHitFl[2]==SP->CHIP_GMNGAILT || mHitFl[2]==SP->CHIP_GMNGAIRT|| mHitFl[2]==SP->CHIP_HIT || mHitFl[3]==SP->CHIP_GMNGAILT || mHitFl[3]==SP->CHIP_GMNGAIRT || mHitFl[3]==SP->CHIP_HIT )) mSpX += mAccX+mKazeAccX; mX += mSpX + mAshiSpX; mY += mSpY; //// 足場 mAshiSpX = 0; if( mStatus == HISATU && mCurAshiba ){ mCurAshiba->GetOff(this); mCurAshiba = NULL; } //if( mCurAshiba && !(mHitFl[2]==SP->CHIP_GMNGAILT || mHitFl[2]==SP->CHIP_GMNGAIRT|| mHitFl[2]==SP->CHIP_HIT || //mHitFl[3]==SP->CHIP_GMNGAILT || mHitFl[3]==SP->CHIP_GMNGAIRT || mHitFl[3]==SP->CHIP_HIT )){ // mX += mCurAshiba->GetSpX(); //} //?±??¾’ï½°?¼?®?no更新 mAniNoY = mStatus; no = sAniData[mAniNoY][mAniNoX]; //描画(点æ»? int scr = (int)(GAMECONTROL->GetStageManager()->GetCurScrollPointer()); /*if( mTenmetuTimer > TENMETU_TIME ){ if( mTenmetuTimer > TENMETU_TIME*2 ) mTenmetuTimer = 0; }else{*/ DX_DRAWALPHA(sGraphic[mStatus], (int)mX - scr, (int)mY, HERSIZE*no, HERSIZE*mMuki, HERSIZE+HERSIZE*no, HERSIZE+HERSIZE*mMuki, mAlphaVal); //} if( mStatus == KOGEKI_STAN && mAniNoX > 2 ){ DX_DRAW("graphics\\effect\\staneffect.png", ((int)mX + HERSIZE/2*!mMuki + 25*GetMukiMult()) - scr, (int)mY, 56*mStanAni, 0, 56+56*mStanAni, 56); } collisionFrames(); Gameover(); //SE(??¾ï½¼?®?? if( mTen >= TEN_MAX ){ if( !mTenSE ){ mTenSE = true; GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_tensyon_maxn.wav"); } }else{ mTenSE = false; } mKazeAccX = 0; mHouseProtected = false; } /* ?—ï½²??¨ã®å½“たり判å®? */ int Jiki::GetAtHtPointX() { return (int)mX + HERSIZE/2; } int Jiki::GetAtHtPointY() { return (int)mY + HERSIZE/2; } bool Jiki::GetMuki() { return mMuki; } /* ?—ï½²???処ç? */ void Jiki::ResponseAka()//---------------------?—ï½²??µ¤ { UnTeishi();//歩きå?é–? AoCheck();//反転 Hisatu();//å¿?®ºæŠ? //攻æ’? if( mStatus == WALK ){ mStatus = KOGEKI_START; mSpX = 0; mAniNoX = 0; mAkaTimer = 0; } mAkaTimer += SP->FrameTime; //強制終äº? if( mAkaTimer > END_TIME && mStatus == KOGEKI ){ mAkaTimer = 0; mAkaTimer2 = 0; mStanTimer = 0; mStatus = KOGEKI_STAN; mAniNoX = 0; } //??¾žï¾˜ï¾™ï½·?¯?¸ if( mDrillFl == 1 ){//?‘回の?¼?žï½¬?ï¾Œï¾Ÿã«ä¸?º¦ã—か使えません if( mY+HERSIZE <= mHozonY-DRILL_HEIGTH && mMidFl ){ if( mStatus == JUMP_UP || mStatus == JUMP_DOWN ){ mDrillFl = 2; mMidTimer = 0; mStatus = DRILL_START; mAniNoX = 0; mMidFl = false; //SE GAMECONTROL->GetSoundController()->LoopSE("audio\\se\\se_hiroin_kuutyuukougeki.wav"); } } } MidCheck();//?¼?žï½¬?ï¾Œï¾? //??¾ï½¼?®?? if( !mTenFl ){ mTenFl = !mTenFl; mTenTime = 0; } Tension(); } void Jiki::ResponseAo()//----------------------?—ï½²??’ { AkaCheck();//攻æ’? MidCheck();//?¼?žï½¬?ï¾Œï¾? Hisatu();//å¿?®ºæŠ? //停止 if( mStatus == WALK ){ mStatus = TEISHI; mAniNoX = 0; mAoTimer = 0; } mAoTimer += SP->FrameTime; //æµ®é? if( mStatus == JUMP_DOWN ){ mStatus = FUYU; mAniNoX = 0; mMidFl = false; } //??¾žï¾˜ï¾™ï½·?¯?¸ã¯?‘回の?¼?žï½¬?ï¾Œï¾Ÿã«ä¸?º¦ã—か使えません if( mDrillFl == 1 ) mDrillFl = 0; //??¾ï½¼?®?? if( !mTenFl ){ mTenFl = !mTenFl; mTenTime = 0; } Tension(); } void Jiki::ResponseMidori()//------------------?—ï½²??·? { UnTeishi();//歩きå?é–? AkaCheck();//攻æ’? AoCheck();//反転 Hisatu();//å¿?®ºæŠ? //?¼?žï½¬?ï¾Œï¾? if( mStatus == WALK ){ mStatus = JUMP_START; mAniNoX = 0; mMidTimer = 0; //SE GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_hiroin_junp.wav"); //?‘回の?¼?žï½¬?ï¾Œï¾Ÿã«ä¸?º¦ã—か使えません if( mDrillFl == 0 ) mDrillFl = 1; } mMidTimer += SP->FrameTime; mMidFl = true; //??¾ï½¼?®?? if( !mTenFl ){ mTenFl = !mTenFl; mTenTime = 0; } Tension(); } void Jiki::ResponseMushoku()//-----------------?—ï½²??„¡è‰² { UnTeishi();//歩きå?é–? AkaCheck();//攻æ’? AoCheck();//反転 MidCheck();//?¼?žï½¬?ï¾Œï¾? Hisatu();//å¿?®ºæŠ? //??¾ï½¼?®?? if( !mTenFl ){ mTenFl = !mTenFl; mTenTime = 0; } Tension(); } void Jiki::NoLight()//-------------------------?—ï½²??ªã? { UnTeishi();//歩きå?é–? AkaCheck();//攻æ’? AoCheck();//反転 MidCheck();//?¼?žï½¬?ï¾Œï¾? //??¾ï½¼?®?? if( mTenFl ){ mTenFl = !mTenFl; mTenTime = 0; } Tension(); } /* ?—ï½²???処ç?そã?ä»? */ //å¿?®ºæŠ? void Jiki::Hisatu() { //??¾ï½¼?®?MAX??½½?ï¾Ÿï½°?½æŠ¼ã—でå¿?®ºæŠ? if( mStatus == WALK ){ if( GAMECONTROL->GetDXController()->KeyPush( DIK_SPACE ) && mTen >= TEN_MAX ){ mStatus = TEISHI; //mTenmetuTimer = 0; mFadeFl = 1; //GAMECONTROL->GetFader()->SetSpeed( HISATU_FADE ); GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOff(); mDgMutekiFl = 1; SetTransparent(false); //SE GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_hiroin_hissatu.wav"); } } } //攻æ’?Š¶æ…‹ã‹ã‚‰çµ‚äº?‹•作へ(?—ï½²??µ¤) void Jiki::AkaCheck(){ //攻æ’? if( mStatus == KOGEKI ){ mAkaTimer = 0; mAniNoX = 0; mStatus = KOGEKI_END; } //??¾žï¾˜ï¾™ï½·?¯?¸ if( mStatus == DRILL ){ mAniNoX = 0; mStatus = JUMP_DOWN; } } //反転??½ª?¯?¸(?—ï½²??’) void Jiki::AoCheck() { //HANTEN_TIME以å†?§åè»¢ if( mAoTimer <= HANTEN_TIME && mAoTimer > 0.0f && mStatus == WALK ){ Hanten(); } else{ mAoTimer = 0; } //æµ®é? if( mStatus == FUYU ){ mAniNoX = 0; mStatus = JUMP_DOWN; } } //停止状態から歩き状態に戻ã??—ï½²??’) void Jiki::UnTeishi() { if( mStatus == TEISHI && mFadeFl != 1 ){ mStatus = WALK; } } //?¼?žï½¬?ï¾Œï¾Ÿã‹ã‚‰ç€åœ°å‹•作へ(?—ï½²??·? void Jiki::MidCheck() { if( mStatus == JUMP_UP ){ mMidTimer = 0; mSpY = 0; } } /* ?‹ï¾›ï½²?ã?向き( + or - ) */ int Jiki::GetMukiMult() { if( mMuki == 0 ) return -1; else return 1; } /* ?ï½¯?Œï¾Ÿã¨ã®å½“たり判å®? */ void Jiki::MapAtHt() { GAMECONTROL->GetStageManager()->GetCurMap()->SuperAtariHantei( mX, mY, mMuki, mSpX, mSpY, mAccX, mAccY, sHitX[0], sHitY[0], HERSIZE, HERSIZE, mHitFl, mKabeIchi); //当たり判定ã?対å¿?------------------------------- if( (mHitFl[0] == SP->CHIP_AMHIT && mSpY >= 0) || mHitFl[0] == SP->CHIP_KGHIT || mCurAshiba ){//ä¸? if(!mCurAshiba && mHitFl[0] != SP->CHIP_KGHIT) mY = (float)mKabeIchi[0] - sHitY[0][0][0]; mSpY = 0; mAccY = 0; if( mStatus != JUMP_START ) mDrillFl = 0; mMidFl = false; mHozonY = mY+HERSIZE; switch( mStatus ){ case JUMP_DOWN ://?¼?žï½¬?ï¾Œï¾? mStatus = JUMP_END; mAniNoX = 0; break; case DRILL ://??¾žï¾˜ï¾? case DRILL_START: mStatus = DRILL_END; mAniNoX = 0; break; case FUYU://æµ®é? mStatus = TEISHI; mAniNoX = 0; mAoTimer = 0; break; case DAMAGE://??¾žï¾’ï½°?¼?? if( mDgMapFl ){ mStatus = DAMAGE_END; mAniNoX = 0; } break; } } else { //å¿?®ºæŠ?¸­ä»¥å¤–ã?常に重力 if( mStatus != HISATU ) mAccY = SP->GRAVITY; //下ã?当たり判定なしâ?落ä¸? if( mStatus == WALK ){ mStatus = JUMP_DOWN; mAniNoX = 0; } } if( mHitFl[1] == SP->CHIP_HIT || mHitFl[1] == SP->CHIP_KGHIT ){ //ä¸? switch( mStatus ){ case JUMP_UP : case DRILL: case DRILL_END: case DRILL_START: if( mSpY < 0 ){ mSpY = 0; mY = mKabeIchi[1] - sHitY[0][1][0]; } break; } } else if( mHitFl[1] == SP->CHIP_GMNGAIDN && mStatus!=DEAD && mStatus!=FADEOUT && mStatus!=FADEIN && mStatus!=DAMAGE_END) { Die(); } if( mHitFl[2] == SP->CHIP_HIT || mHitFl[2] == SP->CHIP_GMNGAIRT || mHitFl[2] == SP->CHIP_GMNGAILT || mHitFl[2] == SP->CHIP_KGHIT){//å‰? switch( mStatus ){ case JUMP_UP : case JUMP_DOWN ://?¼?žï½¬?ï¾Œï¾Ÿä¸­ case FUYU : mSpX = 0; mAccX = 0; break; case DRILL_START : case DRILL ://??¾žï¾˜ï¾™ä¸­ mDrillFl = 0; mSpX = 0; mAccX = 0; if( mHitFl[2] == SP->CHIP_GMNGAIRT ) mX = mKabeIchi[2] - sHitX[0][2][0]; if( mHitFl[2] == SP->CHIP_GMNGAILT ) mX = mKabeIchi[2] - (HERSIZE - sHitX[0][2][0]); break; //case DAMAGE ://??¾žï¾’ï½°?¼?? // if( mDgMapFl ){ // Hanten(); // } // break; case WALK : case KOGEKI: case KOGEKI_END: case KOGEKI_START: Hanten(); break; } } if( mHitFl[3] == SP->CHIP_HIT || mHitFl[3] == SP->CHIP_GMNGAIRT || mHitFl[3] == SP->CHIP_GMNGAILT|| mHitFl[3] == SP->CHIP_KGHIT) {//å¾? switch( mStatus ){ case DAMAGE://??¾žï¾’ï½°?¼?? if( mDgMapFl ){ mSpX = 0; mAccX = 0; mAniTimer = 0; } break; } } //攻æ’?ˆ¤å®šã??ï½¯?Œï¾???¾žï¾’ï½°?¼?? for( int i=0; i < 4; i++ ){ if( mHitFl[i] == SP->CHIP_KGHIT && mStatus != HISATU ){ InflictDamage(); } } } //反転動作に入ã‚? void Jiki::Hanten() { if( mStatus != HANTEN && mStatus != HISATU && mStatus != DAMAGE && mStatus != DAMAGE_END && mStatus != FADEOUT && mStatus != FADEIN && mStatus != DEAD && mSuperStatus == CONTROL ){ mAoTimer = 0; mAniNoX = 0; mStatus = HANTEN; } } // 歩き中の場合反転しますã?ã€?©ºä¸­ã®å ´åˆã?Xを軸にして跳ね返りますã? void Jiki::HantenOrRebound() { switch( mStatus ){ case WALK: case KOGEKI: case KOGEKI_END: case KOGEKI_START: Hanten(); break; case JUMP_DOWN: case JUMP_START: case JUMP_UP: case JUMP_END: case DRILL_START: case DRILL: case DRILL_END: case FUYU: mMuki *= -1; break; } } /* 敵との当たり判定用?Œï¾šï½°?? */ void Jiki::collisionFrames(){ if( !collisionEnabled ) return; //当たり判定ã??Œï¾šï½°?? switch(mStatus){ case WALK: case DAMAGE: case KOGEKI_END: case KOGEKI_STAN: case DRILL_END: SetCurFrame(FR_ARUKI); break; case TEISHI: case HANTEN: SetCurFrame(FR_TACHI); break; case KOGEKI: SetCurFrame(FR_KOGEKI); break; case JUMP_UP: case JUMP_DOWN: case JUMP_START: case JUMP_END: case FUYU: SetCurFrame(FR_JUMP); break; case DRILL: case DRILL_START: SetCurFrame(FR_DRILL); break; case HISATU : if( mHisatuTime > HISATU_TIME ) SetCurFrame(FR_DISABLE); else SetCurFrame(FR_HISATU); default: break; }//switch /*char buffer[6]; sprintf(buffer,"%d",pCollision->GetIndex()); SHOW(0, 0, buffer);*/ } void Jiki::CollisionResponse(ICollidable* rCollObject, int rThisGroupId, int rOpGroupId) { } /* ?—ï½²??§ã®??¾ï½¼?®?å¢—æ¸? */ void Jiki::Tension() { mTenTime += SP->FrameTime; //å¿?®ºæŠ?¸­?¼?žï½®?¼?žï½®ã«??¾ï½¼?®?ãŒä¸‹ãŒã£ã¦ã? if( mStatus == HISATU ){ mTenTime = 0; mTen -= ( TEN_MAX/HISATU_TIME ) *SP->FrameTime/2; }else{ //??¾ï½¼?®?å¢? if( mTenFl ) { if( mTenTime > TEN_UTIME ){ mTenTime = 0; RestoreTension(TEN_UP1, false); } }else{ //??¾ï½¼?®?æ¸? if( mTenTime > TEN_DTIME ){ mTenTime = 0; mTen -= TEN_DOWN1; } } } } /* ?Œï½ª?°??¾žå?ç? */ void Jiki::Fade() { //å¿?®ºæŠ?–‹å§‹ï¾Œï½ª?°??¾? if( mFadeFl == 1 ){ mChargeFx = new ChargeEffect(mX+HERSIZE/2, mY+HERSIZE/2); SetSuperPause(); GAMECONTROL->GetMobManager()->Request(mChargeFx, false); mFadeFl = 2; } else if( mFadeFl == 2 && mChargeFx->IsChargeCompleted() ){ mStatus = HISATU; SetSuperControl(); mAniNoX = 0; mHisatuTime = 0; mHisatuMuki = GAMECONTROL->GetDXController()->GetMouseState().lX; GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOn(); mFadeFl = 0; //BGM GAMECONTROL->GetSoundController()->SetBGM(SoundController::HISATU); } //å¿?®ºæŠ?µ‚äº?¾Œï½ª?°??¾? if( mFadeFl2 && GAMECONTROL->GetFader()->FadeIn() ){ mFadeFl2 = false; GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOn(); GAMECONTROL->GetFader()->SetSpeed( GF("FADE_INCR") ); //BGM GAMECONTROL->GetMobManager()->Remove(mChargeFx); mChargeFx = NULL; } if( mChargeFx ) mChargeFx->SetPos(mX + HERSIZE/2, mY + HERSIZE/2); } /* ?¹?žï½°?‘ï½µ?°?Šï¾žï½° */ void Jiki::Gameover() { if( mGmOvFl == 2 ){ if( GAMECONTROL->GetMaku()->IsClosed()){ mGmOvFl = 3; GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOff(); //BGM GAMECONTROL->GetSoundController()->PauseBGM(); } GAMECONTROL->GetMaku()->Close(); } if( mGmOvFl == 3 && GAMECONTROL->GetFader()->FadeOut() ){ mGmOvFl = 0; GAMECONTROL->GetEventManager()->Request(new GameOverEvt()); } } /* ?‹ï¾›ï½²?ã‚’歩き状態に戻ã? */ void Jiki::HrWalk() { if( mStatus == HISATU ){ mHisatuTime = HISATU_TIME + 10; } } /* 残機ä¸??減るã€?の場合ã?ゲーãƒ?‚ªãƒ¼ãƒã? */ void Jiki::Die() { ResetTempParams(); mChainIdx = 0; mStatus = DEAD; mSpX = 0.0f; mAccX = 0.0f; DisableCollision(); SetLightResponse(false); SetTransparent(true); GAMECONTROL->GetUserLightControl()->GetControlLight()->TurnOff(); GAMECONTROL->GetSoundController()->SetBGM(SoundController::LIFE0); } /* 半é?明にしまã? */ void Jiki::SetTransparent(bool mOnOff) { mAlphaVal = mOnOff ? GF("HER_TRSP_A") : 1.0f; } /** \return 死ぬところã? */ bool Jiki::IsDying() { return (mStatus==DEAD || mStatus==MAKUDOWN || mStatus==FADEOUT || mStatus==FADEIN || (mStatus == DAMAGE_END && mGmOvFl)); } /* \return 操作モードか */ bool Jiki::IsControl() { return (mSuperStatus == CONTROL); } /* チェインã‚?個増やã? */ void Jiki::IncrementChain() { if( mChainIdx < MAX_CHAIN ) mChainIdx++; // 打撃?´?Œï½ª?¸??‚‚出しまã? MakeHitEffect(); } /* チェインã‚?に戻ã? */ void Jiki::ResetChain() { mChainIdx=0; } /* チェインレベルを返す */ int Jiki::GetChainLv() { return mChainIdx; } /* 時期の足å…?«æ‰“æ’ƒ?´?Œï½ª?¸??‚’出ã? */ void Jiki::MakeHitEffect(){ // 出現座標ã?計ç®? int efx, efy; switch( mStatus ){ case KOGEKI: efx = GetMuki() ? GetX() + 120 : efx = GetX(); efy = GetY() + 70; break; case DRILL: case DRILL_START: case DRILL_END: efx = GetMuki() ? GetX() + 120 : efx = GetX(); efy = GetY() + 120; break; default: return; } // ?˜ï½¸?´?½?? GAMECONTROL->GetMobManager()->Request( new HitEffect( efx, efy ), true ); } /* * \return ?‹ï¾›ï½²?ãŒä½•か特別なことをやってã?‚‹çŠ¶æ…‹ã§ã‚ã‚Šã€æ™®æ®µã®å‡¦ç?«ä¾‹å¤–してã?‚‹ã? */ bool Jiki::IsBusy() { return mHisatuTime > HISATU_TIME; } /* ?—ï½²?ŒUP */ void Jiki::RestoreEmpacy(int n, bool SEdelayed) { if( mEmp < EMP_MAX ) { mEmp += n; //SE if( SEdelayed ) GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_enpacy_up_delayed.wav"); else GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_enpacy_up.wav"); } if( mEmp > EMP_MAX ) mEmp = EMP_MAX; } /* ??¾ï½¼?®?UP */ void Jiki::RestoreTension(int n, bool SEdelayed) { bool fl = false; if( mTen < TEN_MAX ) { mTen += n; fl = true; //SE if( SEdelayed ) GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_tensyon_up_delayed.wav"); else GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_tensyon_up.wav"); } if( mTen >= TEN_MAX && fl )//SE if( SEdelayed ) GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_tensyon_maxn.wav"); else GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_tensyon_maxn_delayed.wav"); if( mTen > TEN_MAX ) mTen = TEN_MAX; } /* 残機UP */ void Jiki::RestoreLife(int n, bool SEdelayed) { if( mLife < LIFE_MAX ) { mLife += n; //SE if( SEdelayed ) GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_zanki_up_delayed.wav"); else GAMECONTROL->GetSoundController()->PlaySE("audio\\se\\se_zanki_up.wav"); } if( mLife > LIFE_MAX ) mLife = LIFE_MAX; } bool Jiki::IsStageclearable() { return mStatus != HISATU && mFadeFl2 == 0; } void Jiki::ToggleNoDamageMode() { mNoDamage = !mNoDamage; }
[ "cat2.silly.affection@c9935178-01ba-11df-8f7b-bfe16de6f99b", "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 1 ], [ 13, 13 ], [ 40, 40 ], [ 67, 67 ], [ 94, 94 ], [ 98, 98 ], [ 100, 100 ], [ 107, 108 ], [ 110, 110 ], [ 175, 175 ], [ 178, 178 ], [ 186, 188 ], [ 196, 196 ], [ 260, 260 ], [ 265, 265 ], [ 270, 270 ], [ 273, 273 ], [ 281, 281 ], [ 297, 297 ], [ 309, 309 ], [ 318, 318 ], [ 325, 325 ], [ 334, 334 ], [ 350, 350 ], [ 358, 358 ], [ 365, 365 ], [ 375, 375 ], [ 380, 380 ], [ 385, 385 ], [ 413, 413 ], [ 425, 425 ], [ 452, 452 ], [ 455, 455 ], [ 461, 461 ], [ 483, 483 ], [ 492, 492 ], [ 500, 500 ], [ 517, 517 ], [ 520, 520 ], [ 526, 526 ], [ 530, 530 ], [ 547, 547 ], [ 549, 549 ], [ 556, 556 ], [ 565, 565 ], [ 573, 573 ], [ 575, 575 ], [ 581, 581 ], [ 589, 589 ], [ 592, 592 ], [ 602, 602 ], [ 606, 606 ], [ 611, 611 ], [ 617, 617 ], [ 631, 631 ], [ 640, 640 ], [ 643, 643 ], [ 650, 650 ], [ 665, 665 ], [ 681, 681 ], [ 692, 692 ], [ 701, 701 ], [ 706, 706 ], [ 710, 710 ], [ 716, 716 ], [ 734, 734 ], [ 736, 736 ], [ 739, 739 ], [ 742, 742 ], [ 748, 748 ], [ 767, 767 ], [ 774, 774 ], [ 778, 779 ], [ 781, 783 ], [ 792, 792 ], [ 799, 799 ], [ 827, 829 ], [ 836, 836 ], [ 839, 839 ], [ 842, 842 ], [ 845, 845 ], [ 849, 849 ], [ 852, 852 ], [ 855, 855 ], [ 876, 876 ], [ 879, 879 ], [ 885, 885 ], [ 899, 899 ], [ 901, 901 ], [ 921, 921 ], [ 926, 926 ], [ 942, 942 ], [ 959, 959 ], [ 977, 977 ], [ 979, 979 ], [ 982, 982 ], [ 985, 985 ], [ 987, 987 ], [ 997, 997 ], [ 1007, 1008 ], [ 1022, 1022 ], [ 1024, 1024 ], [ 1033, 1033 ], [ 1036, 1037 ], [ 1039, 1039 ], [ 1050, 1050 ], [ 1057, 1057 ], [ 1061, 1061 ], [ 1070, 1070 ], [ 1073, 1074 ], [ 1077, 1077 ], [ 1079, 1079 ], [ 1086, 1086 ], [ 1095, 1095 ], [ 1104, 1104 ], [ 1107, 1108 ], [ 1110, 1110 ], [ 1112, 1112 ], [ 1114, 1114 ], [ 1123, 1123 ], [ 1126, 1127 ], [ 1129, 1129 ], [ 1131, 1131 ], [ 1141, 1141 ], [ 1144, 1144 ], [ 1148, 1148 ], [ 1166, 1166 ], [ 1169, 1169 ], [ 1176, 1176 ], [ 1183, 1183 ], [ 1186, 1186 ], [ 1194, 1194 ], [ 1202, 1202 ], [ 1212, 1212 ], [ 1223, 1223 ], [ 1234, 1234 ], [ 1241, 1242 ], [ 1250, 1250 ], [ 1255, 1255 ], [ 1261, 1261 ], [ 1267, 1267 ], [ 1277, 1277 ], [ 1279, 1279 ], [ 1286, 1286 ], [ 1304, 1304 ], [ 1307, 1307 ], [ 1314, 1314 ], [ 1325, 1325 ], [ 1341, 1341 ], [ 1343, 1343 ], [ 1354, 1354 ], [ 1364, 1364 ], [ 1375, 1375 ], [ 1401, 1401 ], [ 1407, 1407 ], [ 1458, 1458 ], [ 1465, 1465 ], [ 1470, 1470 ], [ 1477, 1477 ], [ 1487, 1487 ], [ 1492, 1492 ], [ 1511, 1511 ], [ 1525, 1525 ], [ 1546, 1546 ], [ 1558, 1558 ], [ 1573, 1575 ], [ 1579, 1579 ], [ 1587, 1587 ], [ 1602, 1602 ], [ 1609, 1609 ], [ 1614, 1614 ], [ 1630, 1630 ], [ 1634, 1634 ], [ 1655, 1655 ], [ 1661, 1661 ], [ 1666, 1670 ], [ 1672, 1675 ], [ 1680, 1688 ], [ 1690, 1696 ], [ 1701, 1703 ], [ 1708, 1714 ], [ 1716, 1719 ], [ 1724, 1726 ] ], [ [ 2, 12 ], [ 14, 39 ], [ 41, 66 ], [ 68, 93 ], [ 95, 97 ], [ 99, 99 ], [ 101, 106 ], [ 109, 109 ], [ 111, 174 ], [ 176, 177 ], [ 179, 185 ], [ 189, 195 ], [ 197, 259 ], [ 261, 264 ], [ 266, 269 ], [ 271, 272 ], [ 274, 280 ], [ 282, 296 ], [ 298, 308 ], [ 310, 317 ], [ 319, 324 ], [ 326, 333 ], [ 335, 349 ], [ 351, 357 ], [ 359, 364 ], [ 366, 374 ], [ 376, 379 ], [ 381, 384 ], [ 386, 412 ], [ 414, 424 ], [ 426, 451 ], [ 453, 454 ], [ 456, 460 ], [ 462, 482 ], [ 484, 491 ], [ 493, 499 ], [ 501, 516 ], [ 518, 519 ], [ 521, 525 ], [ 527, 529 ], [ 531, 546 ], [ 548, 548 ], [ 550, 555 ], [ 557, 564 ], [ 566, 572 ], [ 574, 574 ], [ 576, 580 ], [ 582, 588 ], [ 590, 591 ], [ 593, 601 ], [ 603, 605 ], [ 607, 610 ], [ 612, 616 ], [ 618, 630 ], [ 632, 639 ], [ 641, 642 ], [ 644, 649 ], [ 651, 664 ], [ 666, 680 ], [ 682, 691 ], [ 693, 700 ], [ 702, 705 ], [ 707, 709 ], [ 711, 715 ], [ 717, 733 ], [ 735, 735 ], [ 737, 738 ], [ 740, 741 ], [ 743, 747 ], [ 749, 766 ], [ 768, 773 ], [ 775, 777 ], [ 780, 780 ], [ 784, 791 ], [ 793, 798 ], [ 800, 826 ], [ 830, 835 ], [ 837, 838 ], [ 840, 841 ], [ 843, 844 ], [ 846, 848 ], [ 850, 851 ], [ 853, 854 ], [ 856, 875 ], [ 877, 878 ], [ 880, 884 ], [ 886, 898 ], [ 900, 900 ], [ 902, 920 ], [ 922, 925 ], [ 927, 941 ], [ 943, 958 ], [ 960, 976 ], [ 978, 978 ], [ 980, 981 ], [ 983, 984 ], [ 986, 986 ], [ 988, 996 ], [ 998, 1006 ], [ 1009, 1021 ], [ 1023, 1023 ], [ 1025, 1032 ], [ 1034, 1035 ], [ 1038, 1038 ], [ 1040, 1049 ], [ 1051, 1056 ], [ 1058, 1060 ], [ 1062, 1069 ], [ 1071, 1072 ], [ 1075, 1076 ], [ 1078, 1078 ], [ 1080, 1085 ], [ 1087, 1094 ], [ 1096, 1103 ], [ 1105, 1106 ], [ 1109, 1109 ], [ 1111, 1111 ], [ 1113, 1113 ], [ 1115, 1122 ], [ 1124, 1125 ], [ 1128, 1128 ], [ 1130, 1130 ], [ 1132, 1140 ], [ 1142, 1143 ], [ 1145, 1147 ], [ 1149, 1165 ], [ 1167, 1168 ], [ 1170, 1175 ], [ 1177, 1182 ], [ 1184, 1185 ], [ 1187, 1193 ], [ 1195, 1201 ], [ 1203, 1211 ], [ 1213, 1222 ], [ 1224, 1233 ], [ 1235, 1240 ], [ 1243, 1249 ], [ 1251, 1254 ], [ 1256, 1260 ], [ 1262, 1266 ], [ 1268, 1276 ], [ 1278, 1278 ], [ 1280, 1285 ], [ 1287, 1303 ], [ 1305, 1306 ], [ 1308, 1313 ], [ 1315, 1324 ], [ 1326, 1340 ], [ 1342, 1342 ], [ 1344, 1353 ], [ 1355, 1363 ], [ 1365, 1374 ], [ 1376, 1400 ], [ 1402, 1406 ], [ 1408, 1457 ], [ 1459, 1464 ], [ 1466, 1469 ], [ 1471, 1476 ], [ 1478, 1486 ], [ 1488, 1491 ], [ 1493, 1510 ], [ 1512, 1524 ], [ 1526, 1545 ], [ 1547, 1557 ], [ 1559, 1572 ], [ 1576, 1578 ], [ 1580, 1586 ], [ 1588, 1601 ], [ 1603, 1608 ], [ 1610, 1613 ], [ 1615, 1629 ], [ 1631, 1633 ], [ 1635, 1654 ], [ 1656, 1660 ], [ 1662, 1665 ], [ 1671, 1671 ], [ 1676, 1679 ], [ 1689, 1689 ], [ 1697, 1700 ], [ 1704, 1707 ], [ 1715, 1715 ], [ 1720, 1723 ], [ 1727, 1737 ] ] ]
52f7d4091359128737a6ecaafd1fb89b7e869055
de1e5905af557c6155ee50f509758a549e458ef3
/src/treesynth/Eliot/rt_treesynth++_levs.cpp
00f9a74f3c31b33ff9e175d27bb1302f42453bf3
[]
no_license
alltom/taps
f15f0a5b234db92447a581f3777dbe143d78da6c
a3c399d932314436f055f147106d41a90ba2fd02
refs/heads/master
2021-01-13T01:46:24.766584
2011-09-03T23:20:12
2011-09-03T23:20:12
2,486,969
1
0
null
null
null
null
UTF-8
C++
false
false
27,986
cpp
/* Treesynth Includes left tree, randflip and ancestor versus predecessor search precedence Real-time No "Again?" prompt No writing output to file Has pruning, but so far parameters are hard coded Includes different options for reading the source file */ #include <stdlib.h> #include <time.h> #include <math.h> #include <assert.h> #include <iostream> #include <sndfile.h> #include "daub.h" #include "Stk.h" #include "RtAudio.h" using namespace std; #define OUR_T float #define CUTOFF (1 << 18) #define MAX_TREE_SIZE (CUTOFF << 1) // arbitrary, was 4194304 struct Node { int *cs; int cslength; }; // global variables Node *tnew_data; OUR_T * tree = new OUR_T[MAX_TREE_SIZE]; OUR_T * lefttree = new OUR_T[MAX_TREE_SIZE]; // optional OUR_T *tnew = new OUR_T[MAX_TREE_SIZE]; bool leftinit = false; // whether lefttree has been initialized short levels; // number of levels in the tree int *lengths; // vector with number of nodes for each level int *sums; // sum of lengths of previous levels so we know where next level starts // treesynth knobs int npredecessors = 3; // number of predecessors checked (dummy value of 3) float kfactor = 0.3f; // the thing that actually determines npredecessors bool randflip = false; // whether first 2 coefficients are copied in order or randomly double percentage = .25; // percentage of nodes to be considered when learning new tree double epsilon; // closeness threshold; calculated from percentage bool ancfirst = true; // whether learning is first done on ancestors or predecessors int startlevel = 1; int stoplevel = 10; // changed later in the program enum TheReadModes { RM_STOP = 0x0, RM_WRAP = 0x1, RM_BOUNCE = 0x2, RM_STATIONARY = 0x4, // maybe this is an action instead of a direction? RM_FORWARD = 0x8, RM_BACKWARD = 0x10, RM_RANDOM = 0x20, // don't or this in RM_ACTION_MASK = 0x7, RM_DIRECTION_MASK = ~RM_ACTION_MASK }; int rm_mode = RM_FORWARD | RM_STATIONARY; // what direction and what to do at boundary int rm_next_pos = 0; // the next read position int rm_next_length = CUTOFF; // the amount of data to read next // global audio buffer #define TS_BIG_BUFFER_SIZE CUTOFF #define TS_BIG_BUFFER_COUNT 16 OUR_T g_big_buffer[TS_BIG_BUFFER_COUNT][TS_BIG_BUFFER_SIZE]; // shouldn't the "2" be "g_max_data_count"? yes. now it's TS_BIG_BUFFER_COUNT int g_write_index = 0; int g_read_index = 0; #define TS_BUFFER_SIZE 2048 OUR_T * g_audio_begin = NULL; OUR_T * g_audio_end = NULL; int g_buffer_size = TS_BUFFER_SIZE; unsigned int g_data_count = 0; unsigned int g_max_data_count = 2; int g_ready = 0; // for filling up buffers before anything is played // functions prototypes int audio_cb( char * buffer, int buffer_size, void * user_data ); bool audio_initialize( unsigned int srate ); void set_next_pos( const char * filename ); //----------------------------------------------------------------------------- // name: double pow( int, int ) // desc: HACK: for pow(int, int) //----------------------------------------------------------------------------- double pow( int x, int n ) { return pow( (double)x, (double)n ); } //----------------------------------------------------------------------------- // name: int our_min( int, int ) // desc: basic minimum function (return minimum of 2 arguments) //----------------------------------------------------------------------------- int our_min(int a, int b) { // basic minimum function if(a < b) return a; else return b; } //----------------------------------------------------------------------------- // name: short maximum( short *, int ) // desc: return value of maximum element in an array //----------------------------------------------------------------------------- short maximum(short *array, int size) { // return value of maximum element in 'short' array if(size <= 0) return 0; short max = array[0]; int index = 1; while(index < size) { if(array[index] > max) max = array[index]; index++; } return max; } //----------------------------------------------------------------------------- // name: int lg( int ) // desc: floor of base 2 log for positive integers only //----------------------------------------------------------------------------- int lg( int n ) { // floor of base 2 log...didn't find in math.h (didn't look for it much, either) if( n <= 0 ) { cerr << "Sorry, I'm a hack and only compute approximate logs of positive integers" << endl; exit(2); } int log = 0; int result = 1; while( result <= n ) { result *= 2; log += 1; } return log - 1; } //----------------------------------------------------------------------------- // name: int compare( void *, void * ) // desc: compare two values...for use in FindEpsilon //----------------------------------------------------------------------------- int compare( const void *arg1, const void *arg2 ) { OUR_T left = *( (OUR_T *)arg1 ); OUR_T right = *( (OUR_T *)arg2 ); if( left < right ) return -1; else if( left == right ) return 0; else return 1; } //----------------------------------------------------------------------------- // name: double FindEpsilon( OUR_T *, int, double ) // desc: finds threshold epsilon, based on percentage of values preferred to // lie within epsilon of some given node value (randomness measure) //----------------------------------------------------------------------------- double FindEpsilon( OUR_T * tree, int size, double P ) { assert( P > 0.0 ); OUR_T * our_tree = new OUR_T[size]; memcpy( our_tree, tree, size * sizeof(OUR_T) ); // find the L1 norm for( int i = 1; i < size; i++ ) our_tree[i] = fabs(our_tree[i]); // sort it qsort( our_tree, size, sizeof(OUR_T), compare ); int index = (int)(P * size + .5); if( index >= size ) index = size-1; cout << size << " " << P << " " << index << endl; return 2.0 * (double)our_tree[index]; } int *cands; bool *in; short *S; short *L; //----------------------------------------------------------------------------- // name: Ancestors( int, int, float, int ) // desc: Part 1 of CandidateSet; ancestor search //----------------------------------------------------------------------------- short Ancestors( int lev, int nod, float epsilon, int csl ) { // Part 1 // Compare ancestors of given node in tnew_data with ancestors of // selected nodes in tree (AND LEFTTREE?) OUR_T ancTnew, ancTree; // float for(int w = 0; w < csl; w++) { OUR_T sum = 0; L[w] = 0; //if(S[w] != M2) // in[w] = false; if(in[w]) { // if w is in the existing candidate set for(short v = lev; v >= 1; v--) { ancTnew = tnew[sums[v] + (int)(nod/pow(2, lev-v))]; ancTree = tree[sums[v] + (int)(cands[w]/pow(2, lev-v))]; OUR_T s = ancTnew - ancTree; // float if(s < 0) // convoluted way because apparently s *= -1; // abs(_) converts to an integer sum += s; if(((float)(sum)/(lev-v+1)) <= epsilon/2) // epsilon, not epsilon/N L[w]++; else break; } // end of for v } // end of if } // end of for w short M1 = maximum(L, csl); return M1; } //----------------------------------------------------------------------------- // name: Predecessors( int, int, float, int ) // desc: Part 2 of CandidateSet; predecessor search //----------------------------------------------------------------------------- short Predecessors( int lev, int nod, float epsilon, int csl ) { // Part 2 // similar to part 1 but with predecessors instead of ancestors // determine number of predecessors to check in general for given node in tnew_data int npred = our_min(npredecessors, nod); OUR_T predTnew, predTree; for(int q = 0; q < csl; q++) { S[q] = 0; // eliminate nodes from candidate set based on whether their L-value is M1 //if( L[q] != M1 ) // in[q] = false; if(in[q]){ // determine number of predecessors for given node in tree //int np = our_min(npred, cands[q]); // find and compare np predecessors of tree and tnew for(int z = 1; z <= npred; z++) { // npred instead of np // figure out where to get stuff from predTnew = tnew[sums[lev] + nod - z]; if( cands[q] - z >= 0 ) predTree = tree[sums[lev] + cands[q] - z]; else if( lengths[lev] + cands[q] - z >= 0 && lefttree ) predTree = lefttree[sums[lev] + lengths[lev] + cands[q] - z]; else break; OUR_T diff = predTnew - predTree; if(diff < 0) diff *= -1; if(diff <= epsilon) S[q]++; else break; } // end of for z } // end of else } // end of for q short M2 = maximum(S, csl); return M2; } //----------------------------------------------------------------------------- // name: CandidateSet( int, int, float ) // desc: the very important function for doing the actual learning //----------------------------------------------------------------------------- void CandidateSet(int lev, int nod, float epsilon) { // Find candidate set and update node in tnew_data // Create empty candidate set int csl = 2 * tnew_data[sums[lev-1]+(nod/2)].cslength; int i; for( i = 0; i < csl/2; i++) { // insert candidate cands[i] = 2*tnew_data[sums[lev-1]+(nod/2)].cs[i]; cands[i+csl/2] = 2*tnew_data[sums[lev-1]+(nod/2)].cs[i] + 1; // verify candidate if(cands[i] < lengths[lev]) in[i] = true; else in[i] = false; if(cands[i+csl/2] < lengths[lev]) in[i+csl/2] = true; else in[i+csl/2] = false; } // Do ancestor or predecessor processing short M1 = 0, M2 = 0; if( ancfirst ) { M1 = Ancestors( lev, nod, epsilon, csl ); for( i = 0; i < csl; i++ ) if( L[i] != M1 ) in[i] = false; M2 = Predecessors( lev, nod, epsilon, csl ); } else { M2 = Predecessors( lev, nod, epsilon, csl ); for( i = 0; i < csl; i++ ) if( S[i] != M2 ) in[i] = false; M1 = Ancestors( lev, nod, epsilon, csl ); } // Return all nodes s.t. L = M1 and S = M2 tnew_data[sums[lev] + nod].cs = new int[csl]; int index = 0; for(int c = 0; c < csl; c++) { if( in[c] && L[c] == M1 && S[c] == M2 ) { tnew_data[sums[lev] + nod].cs[index++] = cands[c]; } } tnew_data[sums[lev] + nod].cslength = index; // Back up if cslength is not positive (which should not happen) if( index <= 0 ) { cerr << "Uh-oh " << lev << "-" << nod << " " << index << endl; // copy all candidates regardless of whether they passed the test or not // (these are all the children of the nodes in the parent's candidate set) index = 0; for(int c = 0; c < csl; c++ ) tnew_data[sums[lev] + nod].cs[index++] = cands[c]; tnew_data[sums[lev] + nod].cslength = index; } // garbage collection if(nod % 2 == 1) delete [] tnew_data[sums[lev-1]+(nod/2)].cs; if(lev == levels - 2 && nod > 0) delete [] tnew_data[sums[lev] + (nod-1)].cs; } // end of CandidateSet char ifilename[1024] = "orig.wav"; char ofilename[1024] = "syn.wav"; char leftfile[1024] = ""; SF_INFO info; SNDFILE *sfread; SNDFILE *sfwrite; //----------------------------------------------------------------------------- // name: int ReadSoundFile( char, float *, int ) // desc: Reads given sound file into data array //----------------------------------------------------------------------------- int ReadSoundFile( char filename[], float * data, int datasize ) { if( !sfread ) { sfread = sf_open( filename, SFM_READ, &info ); if( !sfread ) { cerr << "rt_treesynth++: cannot open file '" << filename << "', quitting" << endl; char x[256]; cin.getline( x, 256 ); exit(1); } } datasize = rm_next_length; sf_seek( sfread, rm_next_pos, SEEK_SET ); int itemsread = sf_read_float( sfread, data, datasize ); set_next_pos( filename ); // rt audio if( !audio_initialize( info.samplerate ) ) { // 44100 cerr << "rt_treesynth++: cannot open audio interface, quitting" << endl; char x[256]; cin.getline( x, 256 ); exit(1); } return itemsread; } //----------------------------------------------------------------------------- // name: int WriteSoundFile( char, float *, int ) // desc: writes synthesized sound to file or to buffer for audio_cb to play //----------------------------------------------------------------------------- int WriteSoundFile( char filename[], float * data, int datasize ) { if( false ) { if( !sfwrite ) { sfwrite = sf_open( filename, SFM_WRITE, &info ); if( !sfwrite ) { cerr << "rt_treesynth++: cannot open file '" << filename << "', quitting" << endl; char x; cin >> x; exit(1); } } int itemswritten = sf_write_float( sfwrite, data, datasize ); if( itemswritten <= 0 ) { cerr << "rt_treesynth++: cannot write to file '" << filename << "', quitting" << endl; char x; cin >> x; exit(3); } //sf_close( sfwrite ); return itemswritten; } else { while( g_data_count >= g_max_data_count ) #ifdef __WINDOWS_DS__ Sleep( 10 ); #else usleep( 10000 ); #endif // set the buffer to write OUR_T * next_buffer = g_big_buffer[g_write_index++]; g_write_index %= g_max_data_count; // copy the data memcpy( next_buffer, data, datasize * sizeof(OUR_T) ); // increment data count g_data_count++; } return 0; } //----------------------------------------------------------------------------- // name: bool parse_args( int argc, char ** argv ) // desc: Read and decipher arguments //----------------------------------------------------------------------------- bool parse_args( int argc, char ** argv ) { int index = 1; while( argc > index ) { if( !strncmp( argv[index], "-p", 2 ) ) { if( argc > ++index ) { percentage = atof( argv[index++] ); if( percentage > 1.0 ) percentage /= 100.0; if( percentage > 1.0 ) { cout << "uh... percentage needs to be smaller" << endl; return 1; } } } else if( !strncmp( argv[index], "-o", 2 ) ) { if( argc > ++index ) strcpy( ofilename, argv[index++] ); } else if( !strncmp( argv[index], "-k", 2 ) ) { if( argc > ++index ) { kfactor = atof( argv[index++] ); // kfactors used to be npredecessors if( kfactor > 1 ) kfactor = 0.5; } } else if( !strncmp( argv[index], "-l", 2 ) ) { if( argc > ++index ) strcpy( leftfile, argv[index++] ); } else if( !strncmp( argv[index], "-r", 2 ) ) { randflip = true; index++; } else if( !strncmp( argv[index], "-a", 2 ) ) { if( argc > ++index ) ancfirst = !( !strncmp( argv[index++], "0", 2 ) ); } else { strcpy( ifilename, argv[index++] ); } } cout << "input file: " << ifilename << endl; cout << "left file: " << (strncmp( leftfile, "", 2 ) ? leftfile : ifilename) << endl; return true; } //----------------------------------------------------------------------------- // name: bool setup( void ) // desc: read sound files, initialize global values, allocate // memory, set up original wavelet trees, initialize root of new tree //----------------------------------------------------------------------------- bool setup( void ) { // Read wav files static int items, litems; int cutoff = CUTOFF; cerr << "cutoff " << cutoff << endl; float *orig = new float[cutoff], *left = new float[cutoff]; items = ReadSoundFile( ifilename, orig, cutoff ); if( !leftinit ) { if( strncmp( leftfile, "", 2 ) ) litems = ReadSoundFile( leftfile, left, cutoff ); else litems = ReadSoundFile( ifilename, left, cutoff ); leftinit = true; } // Copy signals into trees levels = lg( our_min( items, litems ) ); cerr << "levels: " << levels << endl; //lengths = new int[levels]; if(!stoplevel) stoplevel = levels - 2; cerr << "startlevel: " << startlevel << "; stoplevel: " << stoplevel << endl; sums = new int[levels + 1]; int i; for( i = 0; i <= levels; i++ ) { if( i == 0 ) sums[i] = 1; else sums[i] = 2 * sums[i-1]; } lengths = sums; assert( sums[levels] == pow(2, levels) ); int start = ( items - sums[levels] ) / 2; // take middle values int lstart = litems - sums[levels]; // take rightmost values for( i = 0; i < sums[levels]; i++ ) { tree[i] = (OUR_T)(orig[start + i]); if( litems > 0 ) lefttree[i] = (OUR_T)(left[lstart + i]); } // Wavelet decompositions pwtset( 10 ); wt1( tree, sums[levels], 1, *pwt ); wt1( lefttree, sums[levels], 1, *pwt ); // Calculate nearness threshold (epsilon) and print related values cout << "p: " << percentage << endl; cout << "epsilon: " << (epsilon = FindEpsilon( tree, sums[levels], percentage )) << endl; //cout << "k: " << npredecessors << endl; cout << "kfactor: " << kfactor << endl; // Allocate memory for things needed in CandidateSet tnew_data = new Node[(sums[levels])]; cands = new int[lengths[levels-1]]; in = new bool[lengths[levels-1]]; L = new short[lengths[levels-1]]; S = new short[lengths[levels-1]]; // Copy root of tnew, since that's always the same tnew[0] = tree[0]; // approximation tnew[1] = tree[1]; // root // Return return true; } //----------------------------------------------------------------------------- // name: treesynth( ) [formerly main( )] // desc: does wavelet tree learning to build the new tree, calls WriteSoundFile //----------------------------------------------------------------------------- void treesynth( void ) { // Decipher arguments // Read sound files // Make wavelet trees // *** What to do with signal lengths that are not powers of 2? // *** What about level sizes? // ****** Looks like I have to cut-off the input signal to have power-2 length // otherwise, this doesn't reconstruct signals correctly. // ****** Pick "middle" portion if cutting off? // Book-keeping // levels: number of levels in the decomposition // lengths[i] = length of level i (i==0 -> root) // sums[i] = start index of level i or number of array elements upto but not including level i // But in this case, sums[i] = lengths[i] (see /* ... */ in for loop below) // All of the above is in SETUP. // Set up candidate set for root (also always the same, but gets deleted) tnew_data[1].cs = new int[1]; tnew_data[1].cs[0] = 0; tnew_data[1].cslength = 1; // Synthesize new tree //tnew = OUR_T[(sums[levels])]; if( startlevel <= 1 ) { for(int n = 0; n < lengths[1]; n++) { // try copying randomly instead of in order // (so instead of LR it could be LL or RR or RL) if( randflip ) { int random = (int)(rand()/(RAND_MAX + 1.0) * lengths[1]); tnew[sums[1]+n] = tree[sums[1]+random]; } else tnew[sums[1]+n] = tree[sums[1]+n]; } } else { int l, n; for( l = 1; l <= startlevel; l++ ) { for( n = 0; n < lengths[l]; n++ ) { tnew[sums[l]+n] = tree[sums[l]+n]; if( l == startlevel - 1 ) { tnew_data[sums[l]+n].cs = new int[lengths[l]]; tnew_data[sums[l]+n].cslength = lengths[l]; for( int q = 0; q < lengths[l]; q++ ) tnew_data[sums[l]+n].cs[q] = q; } } } } // Breadth-first part int lev; for(lev = startlevel; lev <= stoplevel; lev++) { if( lev >= levels - 1 ) break; cout << "Processing level " << lev << " "; cout << "k is " << (npredecessors = (int)(lengths[lev] * kfactor)) << endl; for(int nod = 0; nod < lengths[lev]; nod++) { CandidateSet(lev, nod, epsilon); if(tnew_data[sums[lev]+nod].cslength == 0) { cerr << "Double Uh-oh " << lev << "-" << nod << endl; } // Randomly choose a node from candidate set and steal its children int randPick = (int)(rand()/(RAND_MAX + 1.0) * tnew_data[sums[lev]+nod].cslength); randPick = tnew_data[sums[lev]+nod].cs[randPick]; // left child tnew[sums[lev+1] + 2*nod] = tree[sums[lev+1] + 2*randPick]; // right child: changed to make sure nodes referred to are within limits if(2*nod + 1 < lengths[lev+1]) { if( 2*randPick + 1 < lengths[lev+1] ) tnew[sums[lev+1] + 2*nod + 1] = tree[sums[lev+1] + 2*randPick + 1]; else { tnew[sums[lev+1] + 2*nod + 1] = tree[sums[lev+1] + 2*randPick]; if( randPick > 0 ) { tnew[sums[lev+1] + 2*nod] = tree[sums[lev+1] + 2*randPick - 1]; } } } // if it's stoplevel, copy all descendants if( lev == stoplevel ) { int l, m = 2, p; for( l = lev + 2; l < levels; l++ ) { m = 2*m; for( p = 0; p < m; p++ ) { tnew[sums[l] + m*nod + p] = tree[sums[l] + m*randPick + p]; } } } // yeah... } } // Reconstruct new tree wt1( tnew, sums[levels], -1, *pwt ); // Print int written = WriteSoundFile( ofilename, tnew, sums[levels] ); //cout << written << " samples written to " << ofilename << endl; } //----------------------------------------------------------------------------- // name: MAIN // desc: the central nervous system //----------------------------------------------------------------------------- int main( int argc, char ** argv ) { srand(time(0)); parse_args( argc, argv ); while( g_data_count < g_max_data_count ) { if( setup() ) treesynth(); else { cerr << "rt_treesynth++: set up failed, quitting" << endl; exit(5); } } g_ready = 1; //char again; while( true ) { //cout << "Again? "; //cin >> again; //if( again == 'n' ) // break; //else { for( int t = 0; t < sums[levels]; t++ ) { lefttree[t] = tnew[t]; tnew[t] = 0.0; } if( setup() ) treesynth(); else { cerr << "rt_treesynth++: set up failed, quitting" << endl; exit(5); } //} } return 0; } // audio interface RtAudio * g_audio = NULL; unsigned int g_srate = 0; //----------------------------------------------------------------------------- // name: audio_cb() // desc: audio callback //----------------------------------------------------------------------------- int audio_cb( char * buffer, int buffer_size, void * user_data ) { // if not ready, play wavelet tree? (just for fun) if( !g_ready ) { memcpy( buffer, tree, buffer_size * sizeof(OUR_T) ); return 0; } // copy out if( !g_data_count ) { // no data to playback yet - silence the buffer memset( buffer, 0, buffer_size * sizeof(OUR_T) ); } else { // initialize the read pointers if( !g_audio_begin ) { g_audio_begin = g_big_buffer[g_read_index++]; g_audio_end = g_audio_begin + sums[levels]; // TS_BIG_BUFFER_SIZE g_read_index %= g_max_data_count; } // copy the data out memcpy( buffer, g_audio_begin, buffer_size * sizeof(OUR_T) ); // increment the read pointer g_audio_begin += buffer_size; // check to see if at end if( g_audio_begin >= g_audio_end ) { // reset g_audio_begin = NULL; g_data_count--; } } return 0; } //----------------------------------------------------------------------------- // name: audio_initialize( ) // desc: set up audio capture and playback and initializes any application data //----------------------------------------------------------------------------- bool audio_initialize( unsigned int srate ) { if( g_audio ) return TRUE; Stk::setSampleRate( g_srate = srate ); try { // open the audio device for capture and playback g_audio = new RtAudio( 0, 1, 0, 0, RTAUDIO_FLOAT32, g_srate, &g_buffer_size, 4 ); } catch( StkError & e ) { // exception fprintf( stderr, "%s\n", e.getMessage() ); fprintf( stderr, "error: cannot open audio device for capture/playback...\n" ); return false; } // set the audio callback g_audio->setStreamCallback( audio_cb, NULL ); // start the audio g_audio->startStream( ); return true; } //----------------------------------------------------------------------------- // name: set_next_pos( const char * ) // desc: set next position to read from in source sound file //----------------------------------------------------------------------------- void set_next_pos( const char * filename ) { int action = rm_mode & RM_ACTION_MASK; int direction = rm_mode & RM_DIRECTION_MASK; cerr << "reading samples '" << rm_next_pos << "' - '" << (rm_next_pos+rm_next_length) << "'" << endl; // don't do anything if stationary if( action == RM_STATIONARY ) return; // advance to the next frame switch( direction ) { case RM_FORWARD: rm_next_pos += rm_next_length; break; case RM_BACKWARD: rm_next_pos -= rm_next_length; break; case RM_RANDOM: rm_next_pos = (int)( rand()/(float)RAND_MAX * (info.frames-rm_next_length) ); if( rm_next_pos < 0 ) rm_next_pos = 0; break; default: cerr << "no!!!!!!" << endl; exit(1); } // passed the end if( rm_next_pos >= info.frames ) { switch( action ) { case RM_STOP: { cerr << "rt_treesynth++: cannot read no mo' file '" << filename << "', stopping"<< endl; char x[256]; cin.getline( x, 256 ); exit(1); break; } case RM_WRAP: cerr << "warping!" << endl; rm_next_pos = 0; break; case RM_BOUNCE: cerr << "bouncing!" << endl; assert( direction == RM_FORWARD ); rm_mode = RM_BACKWARD | action; rm_next_pos -= rm_next_length*2; break; default: cerr << "no!!!!" << endl; exit(1); } } else if( rm_next_pos < 0 && direction == RM_BACKWARD ) // passed the beginning { switch( action ) { case RM_STOP: { cerr << "rt_treesynth++: cannot read no mo' file '" << filename << "', stopping"<< endl; char x[256]; cin.getline( x, 256 ); exit(1); break; } case RM_WRAP: cerr << "warping!!" << endl; rm_next_pos = info.frames - ( info.frames % rm_next_length ); break; case RM_BOUNCE: cerr << "boucing!!" << endl; assert( direction == RM_BACKWARD ); rm_mode = RM_FORWARD | action; rm_next_pos = rm_next_length; break; default: cerr << "no!!!!!" << endl; exit(1); } } // make sure we are legal if( rm_next_pos < 0 ) rm_next_pos = 0; }
[ [ [ 1, 935 ] ] ]
098f420c006ad6a3f36a450c4b2a931f98f54c10
99226699a8b6f4ebd5c2772abb7e133bebf6e929
/dac_dma.cpp
3a108a7d836afb728808a282f926b432e2230fe0
[]
no_license
talexa/Theremin
d103eb5f0be76c33899fb5b44e51830aa2d715c7
c9ba7cecd2766f03c3e26c1abf7491b18c786874
refs/heads/master
2021-01-02T08:14:14.394759
2011-12-01T15:00:26
2011-12-01T15:00:26
2,310,001
0
0
null
null
null
null
UTF-8
C++
false
false
6,978
cpp
/* Written By: Tim Alexander Objective: Audio Output on Mbed based on WaveTable This phase of the program will output audio from Pin 18 (Analog Out) The Onboard DAC is a 10-bit model, for simplicity we are sticking to an 8 bits of precision waveform This gives 2^8 or 256 Steps in a Sine Wave having 1 Period The Output Frequencies are going to be modeled on a traditional Piano, except the 2 Highest Octaves This gives us a frequency range from 27Hz at the lowest key to ~1kHz at the highest key, in steppings as close as possible to the Piano Piano Keys are calculated to the 3 decimal place but a Digital Device is restricted to non-fractional frequencies Since it will take 256 Steps to iterate a wave, what must be calculated is the time between updating the DAC Output with the next step in the Wave Table For instance to do the lowest key on the Piano(27Hz) we have to cycle the waveform 27 times per second. Since each waveform is 256 updates per second, this is calculated as 256 * 27 = 6912 updates per second for the DAC 256 * 1000 = 256000 updates for the highest key in our spectrum Ideally this is going to be done with the DMA Controller so that the CPU does not have to do so much work This can be done with Double Buffering: CNT_ENA bit and DBLBUF_ENA bits are set in the DACCTRL Register Writes to DACR register are written to a buffer, and then transferred out on the next counter tick The DMA Counter is configured as Follows: Rate is set in PCLK_DAC register The Counter is Decremented from the value in the DACCNTVAL register When the value in the counter reaches zero, it will reset to the value DACCNTVAL Need to set up DMA as in the ADC section..... */ #define OUTPUT_BUFFER_LENGTH 360 #include "mbed.h" #include "MODDMA.h" AnalogOut output(p18); DigitalOut led1(LED1); MODDMA dac_dma; //Creating DMA Object for DAC Output MODDMA_Config *conf0, *conf1; void TC0_callback(void); void ERR0_callback(void); void TC1_callback(void); void ERR1_callback(void); int wave_table[2][OUTPUT_BUFFER_LENGTH]; int NoteVal = 152; /* * Determining the value for DACCNTVAL * PCLK is set to Oscillate at 24Mhz, can be reduced at intervals but not necessary since our lowest note works np * The formula is in general with f being the intended output frequency * DACCNTVAL = 24Mhz/(f * WaveTableSize) * These Count values are going to be stored in the NoteBuffer[] Array as defined below * See Piano Key Frequencies.pdf in GitHub Repo for a full list */ uint16_t NoteBuffer[] = { 358, //Middle C 338, 319, 301, 284, 268, 253, 239, 226, 213 //A4 }; int main() { /* * Generation of a Sine Wave of 360 Points */ for (int i = 0; i <= 90; i++) wave_table[0][i] = (512 * sin(3.14159/180.0 * i)) + 512; for (int i = 91; i <= 180; i++) wave_table[0][i] = wave_table[0][180 - i]; for (int i = 181; i <= 270; i++) wave_table[0][i] = 512 - (wave_table[0][i - 180] - 512); for (int i = 271; i < 360; i++) wave_table[0][i] = 512 - (wave_table[0][360 - i] - 512); /* * First Thing to do is modify wave table to work with DAC Hardware. * Since I am double buffering with DMA then I need to duplicate the wavetable. * As specified in LPC17xx user manual(p583), the DACR Register controls the Voltage Output. In our wavetable we only have naive voltage values. * Bit 16 of the DACR is the Power Bit, because we are operating well below the update speed we can set this to 1 for Power Mode * Bits 15:6 of the DACR is the VALUE field which contains the voltage output. * Bits 5:0 of the DACR are reserved, and should not contain any value * * Because of the above situation we have to condition our values to accomodate the hardware * * wave_table[i] = (1 << 16) | (wavetable[i] << 6) & 0xFFC0 * * (1<<16) sets the DAC in Power Mode which Gives a settling time of 2.5us and max current of 350uA and a max update rate of 400kHz * (wavetable[i] << 6) & 0xFFCO shifts the array data into the VALUE field * */ for(int i = 0; i < OUTPUT_BUFFER_LENGTH; i++){ wave_table[0][i] = (1 << 16) | (wave_table[0][i] << 6) & 0xFFC0; wave_table[1][i] = wave_table[0][i]; } // Prepare the GPDMA system for buffer0. conf0 = new MODDMA_Config; conf0 ->channelNum ( MODDMA::Channel_0 ) ->srcMemAddr ( (uint32_t) &wave_table[0] ) ->dstMemAddr ( MODDMA::DAC ) ->transferSize ( OUTPUT_BUFFER_LENGTH ) ->transferType ( MODDMA::m2p ) ->dstConn ( MODDMA::DAC ) ->attach_tc ( &TC0_callback ) ->attach_err ( &ERR0_callback ) ; // config end // Prepare the GPDMA system for buffer1. conf1 = new MODDMA_Config; conf1 ->channelNum ( MODDMA::Channel_1 ) ->srcMemAddr ( (uint32_t) &wave_table[1]) ->dstMemAddr ( MODDMA::DAC ) ->transferSize ( OUTPUT_BUFFER_LENGTH ) ->transferType ( MODDMA::m2p ) ->dstConn ( MODDMA::DAC ) ->attach_tc ( &TC1_callback ) ->attach_err ( &ERR1_callback ) ; // config end //Load the Configuration Settings into the DMA Controller if(!dac_dma.Prepare(conf0)){ error("Conf0 could not be prepared, check configuration settings"); } LPC_DAC->DACCNTVAL = NoteVal; //Begin DMA Transfers and Counter LPC_DAC->DACCTRL |= (3UL << 2); while(1) { if(NoteVal < 1200){ wait_ms(1); NoteVal++; LPC_DAC->DACCNTVAL = NoteVal; } if(NoteVal >= 1200){ for(int i = 1200;i>152;i--){ wait_ms(1); NoteVal--; LPC_DAC->DACCNTVAL = NoteVal; } } } } void TC0_callback(void){ //Get Configuration Pointer and Shut Down DMA Channel MODDMA_Config *config = dac_dma.getConfig(); dac_dma.Disable( (MODDMA::CHANNELS)config->channelNum()); //Swaps to Buffer 1 dac_dma.Prepare(conf1); //Resets IRQ Flags if (dac_dma.irqType() == MODDMA::TcIrq) dac_dma.clearTcIrq(); } void TC1_callback(void){ //Get Configuration Pointer and Shut Down DMA Channel MODDMA_Config *config = dac_dma.getConfig(); dac_dma.Disable( (MODDMA::CHANNELS)config->channelNum()); //Swaps to Buffer 1 dac_dma.Prepare(conf0); //Resets IRQ Flags if (dac_dma.irqType() == MODDMA::TcIrq) dac_dma.clearTcIrq(); } //Configuration 0 Error Callback void ERR0_callback(void){ error("DMA_0 Failed"); } void ERR1_callback(void){ error("DMA_1 Failed"); }
[ "azul@Azul.(none)" ]
[ [ [ 1, 202 ] ] ]
878cfde990a8233ff043f802775dc7d21bc57c9a
13d4ffd16d80e339a34b4e826c293331983ca6c6
/probing.cpp
e3316b4e111b5e8cdc3e7a6132b854a88d0a57ed
[]
no_license
AlexeyMz/Hopscotch-Hashing
c1a1b2be216c80c65083409e3534a667953c3b15
a8c8407426a5e2dc70761ace5cee31e3ed5bdf74
refs/heads/master
2020-12-25T11:58:32.070580
2011-05-07T16:57:08
2011-05-07T16:57:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,568
cpp
#include <iostream> #include"probing.hpp" using namespace std; probing::probing(){ segments_arys = new Bucket[MAX_SEGMENTS]; } void probing::trial(){ Bucket* temp; for(int i=0;i<20;i++){ temp=segments_arys+i; if(temp->_key != NULL ) cout<<"Key:"<<*temp->_key<<" Data:"<<*temp->_data<<"Array index:"<<i<<endl; else cout<<"NULL at:"<<i<<endl; } cout<<"--------------------"<<endl; } int* probing::remove(int *key){ int* rc = NULL; unsigned int hash = ((*key)&(MAX_SEGMENTS-1)); Bucket* start_bucket = segments_arys+hash; start_bucket->lock(); if (!(start_bucket->_key==NULL)){ if (*key == *(start_bucket->_key)){ rc = start_bucket->_data; start_bucket->_key=NULL; start_bucket->_data=NULL; start_bucket->isNULL = 1; start_bucket->unlock(); return rc; } } if((start_bucket->_key==NULL)&&((start_bucket->isNULL)==0)){ start_bucket->unlock(); return NULL; } unsigned int start = hash+1; for(unsigned int i = start;(i&(MAX_SEGMENTS-1)) != hash;i++){ unsigned int temp = (i&(MAX_SEGMENTS-1)); Bucket* check_bucket = segments_arys+temp; if(!(check_bucket->_key==NULL)){ if (*key == *(check_bucket->_key)){ rc = check_bucket->_data; check_bucket->_key=NULL; check_bucket->_data=NULL; check_bucket->isNULL = 1; start_bucket->unlock(); return rc; } } if((check_bucket->_key==NULL)&&((check_bucket->isNULL)==0)){ start_bucket->unlock(); return NULL; } } start_bucket->unlock(); return NULL; } bool probing::contains(int* key){ unsigned int hash = ((*key)&(MAX_SEGMENTS-1)); Bucket *start_bucket = segments_arys+hash; if(!(start_bucket->_key==NULL)){ if (*key == *(start_bucket->_key)) return true; } if((start_bucket->_key==NULL)&&((start_bucket->isNULL)==0)) return false; unsigned int start = hash+1; for(unsigned int i = start;(i&(MAX_SEGMENTS-1)) != hash;i++){ unsigned int temp = (i&(MAX_SEGMENTS-1)); Bucket* check_bucket = segments_arys+temp; if(!(check_bucket->_key==NULL)){ if (*key == *(check_bucket->_key)) return true; } if((check_bucket->_key==NULL)&&((check_bucket->isNULL)==0)) return false; } return false; } bool probing::add(int *key,int *data){ unsigned int hash=((*key)&(MAX_SEGMENTS-1)); Bucket* start_bucket=segments_arys+hash; Bucket* probe_bucket; start_bucket->lock(); if(contains(key)){ start_bucket->unlock(); return false; } if(start_bucket->_key==NULL){ start_bucket->_key=key; start_bucket->_data=data; start_bucket->unlock(); return true; } for(int i=hash+1;(i&MAX_SEGMENTS-1)!=hash;i++){ probe_bucket=segments_arys+(i&(MAX_SEGMENTS-1)); if(probe_bucket->_key==NULL){ probe_bucket->lock(); if(probe_bucket->_key==NULL){ probe_bucket->_key=key; probe_bucket->_data=data; probe_bucket->unlock(); start_bucket->unlock(); return true; } else{ probe_bucket->unlock(); } } } start_bucket->unlock(); cout<<"Call Resize"<<endl; return false; }
[ [ [ 1, 143 ] ] ]
4b56c09a8feac38275d05c684ea1bd1cbe3f4244
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/qbuttons.hpp
f8e063344fcee63c6a169681f66ab9276124c8cb
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
8,560
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'QButtons.pas' rev: 6.00 #ifndef QButtonsHPP #define QButtonsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <QMenus.hpp> // Pascal unit #include <QExtCtrls.hpp> // Pascal unit #include <Types.hpp> // Pascal unit #include <QStdCtrls.hpp> // Pascal unit #include <QGraphics.hpp> // Pascal unit #include <QForms.hpp> // Pascal unit #include <QControls.hpp> // Pascal unit #include <QTypes.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <Qt.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Qbuttons { //-- type declarations ------------------------------------------------------- #pragma pack(push, 1) struct TCMButtonPressed { unsigned Msg; Qcontrols::TControl* Control; int Index; } ; #pragma pack(pop) #pragma option push -b- enum TButtonLayout { blGlyphLeft, blGlyphRight, blGlyphTop, blGlyphBottom }; #pragma option pop #pragma option push -b- enum TButtonState { bsUp, bsDisabled, bsDown, bsExclusive }; #pragma option pop typedef Shortint TNumGlyphs; class DELPHICLASS TSpeedButton; class PASCALIMPLEMENTATION TSpeedButton : public Qcontrols::TGraphicControl { typedef Qcontrols::TGraphicControl inherited; private: int FGroupIndex; void *FGlyph; bool FDown; bool FDragging; bool FAllowAllUp; TButtonLayout FLayout; int FSpacing; bool FTransparent; int FMargin; bool FFlat; bool FMouseInControl; WideString FCaption; void __fastcall GlyphChanged(System::TObject* Sender); void __fastcall UpdateExclusive(void); Qgraphics::TBitmap* __fastcall GetGlyph(void); void __fastcall SetGlyph(Qgraphics::TBitmap* Value); TNumGlyphs __fastcall GetNumGlyphs(void); void __fastcall SetNumGlyphs(TNumGlyphs Value); void __fastcall SetDown(bool Value); void __fastcall SetFlat(bool Value); void __fastcall SetAllowAllUp(bool Value); void __fastcall SetGroupIndex(int Value); void __fastcall SetLayout(TButtonLayout Value); void __fastcall SetSpacing(int Value); void __fastcall SetTransparent(bool Value); void __fastcall SetMargin(int Value); bool __fastcall IsGlyphStored(void); protected: TButtonState FState; DYNAMIC void __fastcall ActionChange(System::TObject* Sender, bool CheckDefaults); void __fastcall ButtonPressed(TSpeedButton* Sender, int GroupIndex); DYNAMIC void __fastcall DblClick(void); DYNAMIC void __fastcall EnabledChanged(void); virtual WideString __fastcall GetText(); DYNAMIC void __fastcall FontChanged(void); virtual void __fastcall Loaded(void); DYNAMIC void __fastcall MouseDown(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseEnter(Qcontrols::TControl* AControl); DYNAMIC void __fastcall MouseLeave(Qcontrols::TControl* AControl); DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall Paint(void); virtual void __fastcall SetText(const WideString Value); DYNAMIC void __fastcall TextChanged(void); DYNAMIC bool __fastcall WantKey(int Key, Classes::TShiftState Shift, const WideString KeyText); public: __fastcall virtual TSpeedButton(Classes::TComponent* AOwner); __fastcall virtual ~TSpeedButton(void); DYNAMIC void __fastcall Click(void); __published: __property Action ; __property Anchors = {default=3}; __property bool AllowAllUp = {read=FAllowAllUp, write=SetAllowAllUp, default=0}; __property Constraints ; __property int GroupIndex = {read=FGroupIndex, write=SetGroupIndex, default=0}; __property bool Down = {read=FDown, write=SetDown, default=0}; __property DragMode = {default=0}; __property Caption ; __property Enabled = {default=1}; __property bool Flat = {read=FFlat, write=SetFlat, default=0}; __property Font ; __property Qgraphics::TBitmap* Glyph = {read=GetGlyph, write=SetGlyph, stored=IsGlyphStored}; __property TButtonLayout Layout = {read=FLayout, write=SetLayout, default=0}; __property int Margin = {read=FMargin, write=SetMargin, default=-1}; __property TNumGlyphs NumGlyphs = {read=GetNumGlyphs, write=SetNumGlyphs, default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property ShowHint ; __property int Spacing = {read=FSpacing, write=SetSpacing, default=4}; __property bool Transparent = {read=FTransparent, write=SetTransparent, default=1}; __property Visible = {default=1}; __property OnClick ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; }; #pragma option push -b- enum TBitBtnKind { bkCustom, bkOK, bkCancel, bkHelp, bkYes, bkNo, bkClose, bkAbort, bkRetry, bkIgnore, bkAll }; #pragma option pop class DELPHICLASS TBitBtn; class PASCALIMPLEMENTATION TBitBtn : public Qstdctrls::TButton { typedef Qstdctrls::TButton inherited; private: Qgraphics::TCanvas* FCanvas; void *FGlyph; TBitBtnKind FKind; TButtonLayout FLayout; int FSpacing; int FMargin; bool FModifiedGlyph; void __fastcall SetGlyph(Qgraphics::TBitmap* Value); Qgraphics::TBitmap* __fastcall GetGlyph(void); TNumGlyphs __fastcall GetNumGlyphs(void); void __fastcall SetNumGlyphs(TNumGlyphs Value); void __fastcall GlyphChanged(System::TObject* Sender); bool __fastcall IsCustom(void); bool __fastcall IsCustomCaption(void); void __fastcall SetKind(TBitBtnKind Value); TBitBtnKind __fastcall GetKind(void); void __cdecl PaintHook(Qt::QPainterH* p, Types::PRect R); void __fastcall SetLayout(TButtonLayout Value); void __fastcall SetSpacing(int Value); void __fastcall SetMargin(int Value); protected: DYNAMIC void __fastcall ActionChange(System::TObject* Sender, bool CheckDefaults); virtual void __fastcall CreateWidget(void); virtual void __fastcall InitWidget(void); DYNAMIC void __fastcall EnabledChanged(void); DYNAMIC void __fastcall FontChanged(void); public: __fastcall virtual TBitBtn(Classes::TComponent* AOwner); __fastcall virtual ~TBitBtn(void); DYNAMIC void __fastcall Click(void); __published: __property Action ; __property Anchors = {default=3}; __property Cancel = {stored=IsCustom, default=0}; __property Caption = {stored=IsCustomCaption}; __property Constraints ; __property Default = {stored=IsCustom, default=0}; __property Enabled = {default=1}; __property Qgraphics::TBitmap* Glyph = {read=GetGlyph, write=SetGlyph, stored=IsCustom}; __property TBitBtnKind Kind = {read=GetKind, write=SetKind, default=0}; __property TButtonLayout Layout = {read=FLayout, write=SetLayout, default=0}; __property int Margin = {read=FMargin, write=SetMargin, default=-1}; __property ModalResult = {stored=IsCustom, default=0}; __property TNumGlyphs NumGlyphs = {read=GetNumGlyphs, write=SetNumGlyphs, stored=IsCustom, default=1}; __property ParentShowHint = {default=1}; __property ShowHint = {default=0}; __property int Spacing = {read=FSpacing, write=SetSpacing, default=4}; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnEnter ; __property OnExit ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TBitBtn(Qt::QWidgetH* ParentWidget) : Qstdctrls::TButton(ParentWidget) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- static const Word CM_BUTTONPRESSED = 0xb064; extern PACKAGE Types::TRect __fastcall DrawButtonFace(Qgraphics::TCanvas* Canvas, const Types::TRect &Client, int BevelWidth, bool IsDown, bool IsFocused, bool Flat = false, Qgraphics::TColor FillColor = (Qgraphics::TColor)(0xfffffffe), Qgraphics::TBrushStyle FillStyle = (Qgraphics::TBrushStyle)(0x0)); } /* namespace Qbuttons */ using namespace Qbuttons; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // QButtons
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 227 ] ] ]
8eaec0806b3b1d65f25a1bad24634def6b4b700b
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Samples/Tornado/App.h
0244694fe2e7f8a041e74af05385b3f7c12bce79
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
882
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: App.h Version: 0.02 --------------------------------------------------------------------------- */ #pragma once #include "FrameworkWin32.h" #include "ScenePartitionerQuadTree.h" #include "MyInputListener.h" #include "MyWindow.h" using namespace nGENE::Application; using nGENE::ScenePartitionerQuadTree; using nGENE::CharacterController; class App: public FrameworkWin32 { private: ScenePartitionerQuadTree* m_pPartitioner; MyInputListener* m_pInputListener; CameraThirdPerson* m_pCamera; GUIFont* m_pFont; MyWindow m_Window; public: App() {} ~App() {} void createApplication(); CameraThirdPerson* getCamera() const; };
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 46 ] ] ]
5cb545f137fdb06c15df6e87b1d3e7ae37976b6a
5095bbe94f3af8dc3b14a331519cfee887f4c07e
/APSVis/source/depth child.h
cf07a1edc8a1f1e922113cfee9b139532c9eb0a5
[]
no_license
sativa/apsim_development
efc2b584459b43c89e841abf93830db8d523b07a
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
refs/heads/master
2020-12-24T06:53:59.364336
2008-09-17T05:31:07
2008-09-17T05:31:07
64,154,433
0
0
null
null
null
null
UTF-8
C++
false
false
1,513
h
//--------------------------------------------------------------------------- #ifndef depth childH #define depth childH #include "chart child.h" #include "TDepth_prop_form.h" #include <general\date_class.h> #include <chart\high_level\apsim_depth_chart.h> // ------------------------------------------------------------------ // Short description: // This class encapsulates a depth MDI child window. It is // derived from the MDI chart child base. // Notes: // Changes: // DPH 25/7/97 // ------------------------------------------------------------------ class Depth_child : public TChart_child { private: TDepth_prop_form* Property_form; void Add_xy_to_chart (TComboBox* X_variable, TComboBox* Y_variable, Depth_chart* Chart_ptr, bool Is_predicted); void Get_start_end_date (Table_base& Table_obj, GDate& Start_date, GDate& End_date); virtual void Setup_filter (Record_filter& Fil); protected: virtual High_level_chart_base* Create_chart_object (void); virtual void Setup_chart_object (High_level_chart_base* Chart_ptr, bool Is_predicted); virtual void Setup_properties (Database& DB); virtual bool Show_properties (void); public: __fastcall Depth_child(TComponent *Owner); }; #endif
[ "devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8" ]
[ [ [ 1, 48 ] ] ]
15124801e47e99c4335a8a59f4816a1f2fb917ee
04fec4cbb69789d44717aace6c8c5490f2cdfa47
/include/wx/msw/mdi.h
20b54ca697decb33a3998f761627dd22fe3858e7
[]
no_license
aaryanapps/whiteTiger
04f39b00946376c273bcbd323414f0a0b675d49d
65ed8ffd530f20198280b8a9ea79cb22a6a47acd
refs/heads/master
2021-01-17T12:07:15.264788
2010-10-11T20:20:26
2010-10-11T20:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,708
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/msw/mdi.h // Purpose: MDI (Multiple Document Interface) classes // Author: Julian Smart // Modified by: // Created: 01/02/97 // RCS-ID: $Id: mdi.h 45498 2007-04-16 13:03:05Z VZ $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_MDI_H_ #define _WX_MDI_H_ #include "wx/frame.h" extern WXDLLEXPORT_DATA(const wxChar) wxStatusLineNameStr[]; class WXDLLEXPORT wxMDIClientWindow; class WXDLLEXPORT wxMDIChildFrame; // --------------------------------------------------------------------------- // wxMDIParentFrame // --------------------------------------------------------------------------- class WXDLLEXPORT wxMDIParentFrame : public wxFrame { public: wxMDIParentFrame(); wxMDIParentFrame(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE | wxVSCROLL | wxHSCROLL, const wxString& name = wxFrameNameStr) { Create(parent, id, title, pos, size, style, name); } virtual ~wxMDIParentFrame(); bool Create(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE | wxVSCROLL | wxHSCROLL, const wxString& name = wxFrameNameStr); // accessors // --------- // Get the active MDI child window (Windows only) wxMDIChildFrame *GetActiveChild() const; // Get the client window wxMDIClientWindow *GetClientWindow() const { return m_clientWindow; } // Create the client window class (don't Create the window, // just return a new class) virtual wxMDIClientWindow *OnCreateClient(void); // MDI windows menu wxMenu* GetWindowMenu() const { return m_windowMenu; } void SetWindowMenu(wxMenu* menu) ; virtual void DoMenuUpdates(wxMenu* menu = NULL); // MDI operations // -------------- virtual void Cascade(); virtual void Tile(wxOrientation orient = wxHORIZONTAL); virtual void ArrangeIcons(); virtual void ActivateNext(); virtual void ActivatePrevious(); // handlers // -------- // Responds to colour changes void OnSysColourChanged(wxSysColourChangedEvent& event); void OnSize(wxSizeEvent& event); void OnIconized(wxIconizeEvent& event); bool HandleActivate(int state, bool minimized, WXHWND activate); bool HandleCommand(WXWORD id, WXWORD cmd, WXHWND control); // override window proc for MDI-specific message processing virtual WXLRESULT MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam); virtual WXLRESULT MSWDefWindowProc(WXUINT, WXWPARAM, WXLPARAM); virtual bool MSWTranslateMessage(WXMSG* msg); protected: #if wxUSE_MENUS_NATIVE virtual void InternalSetMenuBar(); #endif // wxUSE_MENUS_NATIVE virtual WXHICON GetDefaultIcon() const; // set the size of the MDI client window to match the frame size void UpdateClientSize(); wxMDIClientWindow * m_clientWindow; wxMDIChildFrame * m_currentChild; wxMenu* m_windowMenu; // true if MDI Frame is intercepting commands, not child bool m_parentFrameActive; private: friend class WXDLLEXPORT wxMDIChildFrame; DECLARE_EVENT_TABLE() DECLARE_DYNAMIC_CLASS(wxMDIParentFrame) DECLARE_NO_COPY_CLASS(wxMDIParentFrame) }; // --------------------------------------------------------------------------- // wxMDIChildFrame // --------------------------------------------------------------------------- class WXDLLEXPORT wxMDIChildFrame : public wxFrame { public: wxMDIChildFrame() { Init(); } wxMDIChildFrame(wxMDIParentFrame *parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString& name = wxFrameNameStr) { Init(); Create(parent, id, title, pos, size, style, name); } virtual ~wxMDIChildFrame(); bool Create(wxMDIParentFrame *parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString& name = wxFrameNameStr); virtual bool IsTopLevel() const { return false; } // MDI operations virtual void Maximize(bool maximize = true); virtual void Restore(); virtual void Activate(); // Implementation only from now on // ------------------------------- // Handlers bool HandleMDIActivate(long bActivate, WXHWND, WXHWND); bool HandleWindowPosChanging(void *lpPos); bool HandleCommand(WXWORD id, WXWORD cmd, WXHWND control); bool HandleGetMinMaxInfo(void *mmInfo); virtual WXLRESULT MSWWindowProc(WXUINT message, WXWPARAM wParam, WXLPARAM lParam); virtual WXLRESULT MSWDefWindowProc(WXUINT message, WXWPARAM wParam, WXLPARAM lParam); virtual bool MSWTranslateMessage(WXMSG *msg); virtual void MSWDestroyWindow(); bool ResetWindowStyle(void *vrect); void OnIdle(wxIdleEvent& event); virtual bool Show(bool show = true); protected: virtual void DoGetScreenPosition(int *x, int *y) const; virtual void DoGetPosition(int *x, int *y) const; virtual void DoSetClientSize(int width, int height); virtual void InternalSetMenuBar(); virtual bool IsMDIChild() const { return true; } virtual void DetachMenuBar(); virtual WXHICON GetDefaultIcon() const; // common part of all ctors void Init(); private: bool m_needsInitialShow; // Show must be called in idle time after Creation bool m_needsResize; // flag which tells us to artificially resize the frame DECLARE_EVENT_TABLE() DECLARE_DYNAMIC_CLASS_NO_COPY(wxMDIChildFrame) }; // --------------------------------------------------------------------------- // wxMDIClientWindow // --------------------------------------------------------------------------- class WXDLLEXPORT wxMDIClientWindow : public wxWindow { public: wxMDIClientWindow() { Init(); } wxMDIClientWindow(wxMDIParentFrame *parent, long style = 0) { Init(); CreateClient(parent, style); } // Note: this is virtual, to allow overridden behaviour. virtual bool CreateClient(wxMDIParentFrame *parent, long style = wxVSCROLL | wxHSCROLL); // Explicitly call default scroll behaviour void OnScroll(wxScrollEvent& event); protected: virtual void DoSetSize(int x, int y, int width, int height, int sizeFlags = wxSIZE_AUTO); void Init() { m_scrollX = m_scrollY = 0; } int m_scrollX, m_scrollY; private: DECLARE_EVENT_TABLE() DECLARE_DYNAMIC_CLASS_NO_COPY(wxMDIClientWindow) }; #endif // _WX_MDI_H_
[ [ [ 1, 238 ] ] ]
071f38285a01ce7e3a877a71c3e98eecd6eef183
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/include/GameObject/GameObjectOgreBox2D.h
69776b4cecd698d8684558f6f7b02e6d7578cdee
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
5,897
h
/*============================================================================= GameObjectOgreBox2D.h Author: Matt King =============================================================================*/ #ifndef GAME_OBJECT_OGRE_BOX2D_H #define GAME_OBJECT_OGRE_BOX2D_H #include <Box2D/Box2D.h> #include "GameObjectOgre.h" #include "OgreB2DebugDraw.h" #include "ManualObjectHelper.h" /// Structure to represent a contact point. struct ContactPoint { b2Contact* contact; b2Fixture* fixtureA; b2Fixture* fixtureB; b2Vec2 normal; b2Vec2 position; b2PointState state; }; /// Structure to represent PostSolve contact point. struct PostSolveData { b2Contact* contact; const b2ContactImpulse* impulse; ~PostSolveData() { delete impulse; } }; /// Structure to represent PreSolve contact point. struct PreSolveData { b2Contact* contact; const b2Manifold* oldManifold; }; /// The default value of friction for all Box2D objects in the game. const static double DEFAULT_FRICTION = 0.4; /// Group of Static map objects, objects in the same group of a negative number /// will never collide. const static signed short STATIC_MAP_GROUP = -10; /// This extends GameObjectOgre and adds a Box2D component. class GameObjectOgreBox2D : public GameObjectOgre { friend class GameObjectOgreBox2DCreator; public: /// Constructor grabs the reference from the OgreFramework of the b2World. /// The object is not initialized until Initialize is called and will only /// be initialized if the body doesn't equal 0. GameObjectOgreBox2D(Ogre::String name = "GameObjectOgreBox2D", b2Body* body = 0, Ogre::Entity* entity = 0); /// Tells the b2World to destroy the b2Body associated with this object. virtual ~GameObjectOgreBox2D(); /// Updates the DebugDraw if it is enabled and calls it's parent's class /// update method. /// All children of the class must call this Update function before /// their own. This pattern should extend through all children. virtual bool Update(double timeSinceLastFrame); /// Each class that extends this class should call this HandleMessage before /// their own in case this class can handle the message. /// If you want this class to do something with a message and its children /// to something with it as well just return false for that message. virtual bool HandleMessage(const KGBMessage message); /// Initializes the object if the b2Body exists. When the object is initialized /// it can update the Ogre graphics with the b2Body parameters. /// All children of the class must call this Initialize function before /// their own. This pattern should extend through all children. virtual bool Initialize(); /// This creates a manual object out of the b2Body's fixtures and shapes so /// that the DebugDraw doesn't have to every frame. virtual bool InitializeDebugDraw(Ogre::ColourValue color = Ogre::ColourValue(1,1,1,1), Ogre::String materialName = "debugDraw"); /// Updates the DebugDraw scenenode and mesh. virtual void UpdateDebugDraw(); /// Called when two fixtures begin to touch. /// Contact fixture is the fixture in this Object's body. /// Collided fixture is the fixture that hit this Object's body. /// By default this does nothing. virtual void BeginContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture){} /// Called when two fixtures cease to touch. /// Contact fixture is the fixture in this Object's body. /// Collided fixture is the fixture that hit this Object's body. /// By default this does nothing. virtual void EndContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture){} virtual void PostSolve(b2Contact* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture, const b2ContactImpulse* impulse){} /// You cannot create/destroy Box2D entities inside this callback. virtual void PreSolve(b2Contact* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture, const b2Manifold* manifold){} /// Sets the scene node to be positioned the same as as the Box2D body /// this object has. virtual bool UpdateGraphics(double timeSinceLastFrame); /// Updates the manual object of this object if the fixtures in the b2body have /// changed. virtual void RedrawDebug(); /*========================================================================= Starting Getters and Setters. =========================================================================*/ bool GetDebugDrawInitialized(){ return debugDrawInitialized_;} void SetDebugDrawOn() { debugSceneNode_->setVisible(true); debugDrawOn_ = true; } void SetDebugDrawOff() { debugSceneNode_->setVisible(false); debugDrawOn_ = false; } /// Sets the b2Body for this GameObjectOgreBox2D. virtual void SetBody(b2Body* b){ body_ = b;} /// Returns the b2Body for this GameObjectOgreBox2D. virtual b2Body* GetBody(){ return body_; } /// Returns the body's position. virtual b2Vec2 GetBodyPosition(){ return body_->GetPosition(); } void SetBodyPosition(b2Vec2 pos) { body_->SetTransform(pos, body_->GetAngle()); } void SetBodyAngle(float32 angle) { body_->SetTransform(body_->GetPosition(), angle); } protected: /// Box2D body for this Object b2Body* body_; /// Reference to the b2World b2World* world_; float prevAngle; /// ManualObject which holds all the shapes for each fixture in the body Ogre::ManualObject* manualObject_; /// ManualObject which holds all the shapes for each fixture in the body bool debugDrawInitialized_; bool debugDrawOn_; Ogre::SceneNode* debugSceneNode_; Ogre::String debugMaterialName_; Ogre::ColourValue debugColor_; float32 previousAngle_; bool wasAwake_; }; #endif
[ "mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
[ [ [ 1, 188 ] ] ]
a5e2fadf7fff79ca7e5e91a653c5cf8177ba5044
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/OdometryCalibration/protocol/Packet.h
866813de700c6ce06e570fa60aec1d0d64821621
[]
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,566
h
// Class automatically generated by Dev-C++ New Class wizard #ifndef PACKET_H #define PACKET_H #define PACKET_SIZE_BYTES 1 #define MAX_PACKET_SIZE 257 #define MIN_PACKET_SIZE 5 #define DESTINY_FIELD 1 #define ORIGIN_FIELD 2 #define COMMAND_FIELD 3 #define DATA_FIELD 4 namespace protocol { /** * No description */ class Packet { public: // class constructors Packet(); Packet(char * data, unsigned char length); // class destructor ~Packet(); void setDestinationId(char id); void setDestinationGroup(char group); void setOriginId(char id); void setOriginGroup(char group); char getDestinationId(); char getDestinationGroup(); char getOriginId(); char getOriginGroup(); bool checkCRC(); void calculateCRC(); void setBroadcast(); void setGroupBroadcast(); bool isResponse(); void setResponse(); void setCommand(char command); char getCommand(); bool isACK(); char * getData(); char getDataLength(); char getCharData(); short getShortData(); int getIntData(); void addData(char * data,char length); void addData(char data); void addData(short data); void addData(int data); char * getPacket(); char getActualLength(); void clear(); void print(); protected: void resetDataIdx(); private: char packet [MAX_PACKET_SIZE]; char actualLength; int dataIdx; void setGroup(int field, char group); void setId(int field, char id); char getGroup(int field); char getId(int field); }; } #endif // PACKET_H
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 72 ] ] ]
603541722189a10948f48542341c31d598bcae7f
98b881cb18524391a8f633436c673006d92226ba
/parser/scanner.cpp
eba88dff18a81c32dc96632f38803e1adb7bc19d
[]
no_license
endSly/LEC-Compiler
6cf7cb692a51608bc24bd8a04980c1404961d4a5
73f52fabc46890ff677652f620e2b4a4e609a33f
refs/heads/master
2016-09-11T06:49:30.472382
2011-01-19T21:29:42
2011-01-19T21:29:42
1,169,008
1
0
null
null
null
null
UTF-8
C++
false
false
54,763
cpp
#line 2 "/Users/endika/LEC-Compiler/parser/scanner.cpp" #line 4 "/Users/endika/LEC-Compiler/parser/scanner.cpp" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern yy_size_t yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */ yy_size_t yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 23 #define YY_END_OF_BUFFER 24 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[81] = { 0, 0, 0, 24, 21, 1, 1, 21, 22, 14, 22, 10, 11, 14, 13, 15, 13, 21, 14, 16, 7, 15, 12, 15, 22, 21, 21, 21, 6, 21, 21, 21, 21, 8, 9, 21, 0, 15, 0, 18, 0, 14, 21, 16, 13, 17, 0, 16, 20, 21, 21, 21, 21, 21, 21, 21, 18, 0, 0, 19, 21, 17, 21, 21, 21, 21, 2, 21, 17, 0, 21, 21, 21, 0, 17, 5, 21, 21, 4, 3, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 5, 1, 1, 6, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 1, 17, 18, 19, 20, 1, 21, 22, 22, 23, 22, 22, 22, 22, 22, 24, 22, 22, 22, 22, 22, 22, 22, 22, 25, 22, 22, 22, 22, 22, 22, 22, 22, 1, 1, 1, 26, 22, 1, 27, 22, 22, 28, 29, 22, 22, 22, 22, 22, 22, 30, 31, 32, 33, 34, 22, 35, 36, 37, 38, 22, 22, 39, 22, 22, 40, 1, 41, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[42] = { 0, 1, 2, 3, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 4, 2, 1, 1, 1, 2, 4, 4, 4, 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2 } ; static yyconst flex_int16_t yy_base[86] = { 0, 0, 0, 118, 37, 313, 313, 38, 96, 42, 0, 313, 313, 43, 56, 60, 64, 61, 74, 68, 313, 80, 81, 87, 0, 97, 100, 103, 104, 107, 110, 117, 129, 313, 313, 133, 137, 141, 93, 90, 84, 149, 153, 154, 159, 166, 58, 114, 0, 167, 171, 172, 184, 185, 191, 192, 313, 68, 55, 313, 208, 35, 209, 213, 223, 226, 51, 227, 231, 224, 243, 246, 250, 39, 36, 251, 258, 264, 268, 271, 313, 296, 300, 304, 42, 308 } ; static yyconst flex_int16_t yy_def[86] = { 0, 80, 1, 80, 81, 80, 80, 81, 82, 81, 83, 80, 80, 81, 81, 81, 81, 81, 81, 80, 80, 81, 81, 81, 84, 81, 81, 81, 81, 81, 81, 81, 81, 80, 80, 81, 81, 81, 82, 85, 80, 81, 81, 81, 81, 81, 80, 80, 84, 81, 81, 81, 81, 81, 81, 81, 80, 85, 85, 80, 81, 80, 81, 81, 81, 81, 85, 81, 81, 80, 81, 81, 81, 80, 80, 81, 81, 81, 81, 81, 0, 80, 80, 80, 80, 80 } ; static yyconst flex_int16_t yy_nxt[355] = { 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 4, 25, 26, 27, 28, 29, 4, 4, 4, 4, 30, 31, 4, 4, 4, 4, 4, 32, 33, 34, 36, 36, 36, 36, 48, 36, 36, 36, 36, 61, 74, 36, 36, 74, 66, 37, 36, 36, 66, 36, 41, 36, 69, 36, 36, 36, 36, 36, 42, 36, 43, 58, 61, 44, 36, 45, 42, 36, 43, 36, 46, 44, 47, 36, 36, 36, 36, 41, 36, 59, 36, 41, 36, 58, 36, 36, 56, 37, 37, 39, 36, 36, 36, 36, 37, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 80, 36, 36, 80, 36, 36, 36, 80, 36, 49, 46, 80, 47, 50, 51, 36, 36, 80, 36, 53, 36, 52, 36, 80, 36, 54, 36, 36, 36, 80, 36, 36, 80, 80, 37, 36, 36, 80, 36, 36, 36, 36, 36, 36, 55, 80, 36, 36, 36, 80, 42, 45, 43, 36, 36, 36, 36, 36, 36, 36, 36, 36, 80, 80, 45, 36, 80, 80, 80, 36, 36, 36, 36, 36, 36, 80, 62, 60, 36, 36, 36, 36, 36, 36, 80, 80, 80, 63, 80, 36, 36, 64, 80, 80, 37, 36, 36, 36, 36, 65, 36, 67, 36, 67, 80, 80, 68, 36, 37, 37, 36, 36, 36, 36, 36, 36, 36, 73, 36, 73, 36, 36, 74, 80, 36, 68, 80, 70, 71, 68, 36, 80, 36, 36, 80, 36, 37, 36, 36, 36, 36, 36, 80, 72, 36, 36, 80, 36, 36, 36, 80, 36, 80, 36, 80, 36, 36, 36, 36, 80, 36, 75, 36, 76, 80, 80, 36, 77, 80, 36, 80, 80, 80, 80, 80, 80, 80, 78, 79, 35, 80, 80, 35, 38, 38, 38, 38, 40, 40, 80, 40, 57, 57, 80, 57, 3, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80 } ; static yyconst flex_int16_t yy_chk[355] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 7, 4, 7, 84, 9, 13, 9, 13, 61, 74, 4, 7, 73, 66, 7, 9, 13, 58, 14, 13, 14, 61, 15, 17, 15, 17, 16, 14, 16, 14, 57, 46, 14, 15, 17, 16, 18, 16, 18, 19, 16, 19, 21, 22, 21, 22, 18, 18, 40, 23, 18, 23, 39, 21, 22, 38, 21, 22, 8, 25, 23, 25, 26, 23, 26, 27, 28, 27, 28, 29, 25, 29, 30, 26, 30, 3, 27, 28, 0, 31, 29, 31, 0, 30, 25, 47, 0, 47, 26, 27, 31, 32, 0, 32, 30, 35, 29, 35, 0, 36, 30, 36, 32, 37, 0, 37, 35, 0, 0, 31, 36, 41, 0, 41, 37, 42, 43, 42, 43, 32, 0, 44, 41, 44, 0, 43, 42, 43, 45, 49, 45, 49, 44, 50, 51, 50, 51, 0, 0, 45, 49, 0, 0, 0, 50, 51, 52, 53, 52, 53, 0, 49, 45, 54, 55, 54, 55, 52, 53, 0, 0, 0, 50, 0, 54, 55, 51, 0, 0, 52, 60, 62, 60, 62, 53, 63, 60, 63, 60, 0, 0, 60, 62, 54, 55, 64, 63, 64, 65, 67, 65, 67, 69, 68, 69, 68, 64, 69, 0, 65, 67, 0, 62, 63, 68, 70, 0, 70, 71, 0, 71, 65, 72, 75, 72, 75, 70, 0, 64, 71, 76, 0, 76, 72, 75, 0, 77, 0, 77, 0, 78, 76, 78, 79, 0, 79, 70, 77, 71, 0, 0, 78, 72, 0, 79, 0, 0, 0, 0, 0, 0, 0, 76, 77, 81, 0, 0, 81, 82, 82, 82, 82, 83, 83, 0, 83, 85, 85, 0, 85, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[24] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, }; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "/Users/endika/LEC-Compiler/parser/scanner.l" #line 2 "/Users/endika/LEC-Compiler/parser/scanner.l" #ifndef HAVE_UNISTD_H #define YY_NO_UNISTD_H #endif #include <string> #include "ast/AST.h" #ifdef _WIN32 #include "win_parser.hpp" #else #include "parser.hpp" #endif #define TOKEN(t) (yylval.token = t) #define SAVE_TOKEN yylval.string = new std::string(yytext, yyleng) #ifdef _WIN32 extern "C" { extern int yylex(); /* This function is called whenever the lexer reaches EOF. Return 1 to indicate that we have not reset "yyin" to point to a new file. */ int yywrap() { return 1; } char* yyget_text() { return yytext; } int yytest() { return 0; } } #else extern "C" { int yywrap() { return 1; } } #endif // _WIN32 using namespace ast; #line 618 "/Users/endika/LEC-Compiler/parser/scanner.cpp" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); yy_size_t yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 65 "/Users/endika/LEC-Compiler/parser/scanner.l" #line 803 "/Users/endika/LEC-Compiler/parser/scanner.cpp" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 81 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 80 ); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) yylineno++; ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: /* rule 1 can match eol */ YY_RULE_SETUP #line 67 "/Users/endika/LEC-Compiler/parser/scanner.l" { } YY_BREAK case 2: YY_RULE_SETUP #line 68 "/Users/endika/LEC-Compiler/parser/scanner.l" { } YY_BREAK case 3: YY_RULE_SETUP #line 70 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_RETURN; } YY_BREAK case 4: YY_RULE_SETUP #line 71 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_IMPORT; } YY_BREAK case 5: YY_RULE_SETUP #line 72 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_CLASS; } YY_BREAK case 6: YY_RULE_SETUP #line 74 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_INTERCALATE; } YY_BREAK case 7: YY_RULE_SETUP #line 75 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_SEMICOLON; } YY_BREAK case 8: YY_RULE_SETUP #line 77 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_OP_BRACE; } YY_BREAK case 9: YY_RULE_SETUP #line 78 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_CL_BRACE; } YY_BREAK case 10: YY_RULE_SETUP #line 79 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_OP_PARENT; } YY_BREAK case 11: YY_RULE_SETUP #line 80 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_CL_PARENT; } YY_BREAK case 12: YY_RULE_SETUP #line 81 "/Users/endika/LEC-Compiler/parser/scanner.l" { return T_ASSIGNAMENT; } YY_BREAK case 13: YY_RULE_SETUP #line 83 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_BINARY_OP_ADD; } YY_BREAK case 14: YY_RULE_SETUP #line 84 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_BINARY_OP_MUL; } YY_BREAK case 15: YY_RULE_SETUP #line 85 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_BINARY_OP_LOG; } YY_BREAK case 16: YY_RULE_SETUP #line 87 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_INTEGER; } YY_BREAK case 17: YY_RULE_SETUP #line 88 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_DECIMAL; } YY_BREAK case 18: /* rule 18 can match eol */ YY_RULE_SETUP #line 89 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_STRING; } YY_BREAK case 19: YY_RULE_SETUP #line 90 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_CHARACTER; } YY_BREAK case 20: YY_RULE_SETUP #line 92 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_VARIDENTIFIER; } YY_BREAK case 21: YY_RULE_SETUP #line 93 "/Users/endika/LEC-Compiler/parser/scanner.l" { SAVE_TOKEN; return T_IDENTIFIER; } YY_BREAK case 22: YY_RULE_SETUP #line 95 "/Users/endika/LEC-Compiler/parser/scanner.l" printf("Syntax error at line:%i!\n", yylineno); yyterminate(); exit(1); YY_BREAK case 23: YY_RULE_SETUP #line 97 "/Users/endika/LEC-Compiler/parser/scanner.l" ECHO; YY_BREAK #line 1009 "/Users/endika/LEC-Compiler/parser/scanner.cpp" case YY_STATE_EOF(INITIAL): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 81 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 81 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 80); return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register yy_size_t number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; if ( c == '\n' ){ --yylineno; } (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return 0; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); if ( c == '\n' ) yylineno++; ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ yy_size_t yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ /* We do not touch yylineno unless the option is enabled. */ yylineno = 1; (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 97 "/Users/endika/LEC-Compiler/parser/scanner.l"
[ [ [ 1, 587 ], [ 589, 591 ], [ 595, 598 ], [ 600, 603 ], [ 607, 609 ], [ 612, 904 ], [ 906, 2017 ] ], [ [ 588, 588 ], [ 592, 594 ], [ 599, 599 ], [ 604, 606 ], [ 610, 611 ], [ 905, 905 ] ] ]
ced5700b8c6b6c869fd6fef6c6fbe767670beec6
21da454a8f032d6ad63ca9460656c1e04440310e
/src/net/worldscale/pimap/wscPimapPacket.h
c5cf48c15cbc29a0425b780e77cd0672e2c99752
[]
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
2,163
h
#pragma once #include "wsiPimapPacket.h" #include <wcpp/lang/wscObject.h> #define WS_ClassName_OF_wscPimapPacket "net.worldscale.pimap.wscPimapPacket" class wscPimapPacket : public wscObject , public wsiPimapPacket { WS_IMPL_QUERY_INTERFACE_BEGIN( wscPimapPacket ) WS_IMPL_QUERY_INTERFACE_BODY( wsiPimapPacket ) WS_IMPL_QUERY_INTERFACE_END() public: static const ws_char * const s_class_name; private: struct t_pimap_head { ws_uint8 version; ws_uint8 flag; ws_uint8 xor; ws_uint8 transId; ws_uint32 userId; ws_uint32 key; ws_uint16 func; ws_uint16 addlen; }; t_pimap_head m_head; static const int MAX_PARAM_NUMBER = 32; struct t_pimap_param { ws_uint8 type; ws_uint32 value; ws_safe_ptr<wsiString> string; }; t_pimap_param m_param[ MAX_PARAM_NUMBER ]; public: wscPimapPacket(void); ~wscPimapPacket(void); protected: WS_METHOD( ws_uint8 , GetVersion )(void); WS_METHOD( ws_uint8 , GetFlag )(void); WS_METHOD( ws_uint8 , GetXOR )(void); WS_METHOD( ws_uint8 , GetTransID )(void); WS_METHOD( ws_uint32 , GetUserID )(void); WS_METHOD( ws_uint32 , GetKey )(void); WS_METHOD( ws_uint16 , GetFunction )(void); WS_METHOD( ws_uint16 , GetAddLen )(void); WS_METHOD( void , SetVersion )(ws_uint8 value); WS_METHOD( void , SetFlag )(ws_uint8 value); WS_METHOD( void , SetXOR )(ws_uint8 value); WS_METHOD( void , SetTransID )(ws_uint8 value); WS_METHOD( void , SetUserID )(ws_uint32 value); WS_METHOD( void , SetKey )(ws_uint32 value); WS_METHOD( void , SetFunction )(ws_uint16 value); WS_METHOD( void , SetAddLen )(ws_uint16 value); WS_METHOD( void , PutParam )(ws_uint8 id, ws_uint8 type, ws_uint32 value); WS_METHOD( void , PutParam )(ws_uint8 id, ws_uint8 type, wsiString * str); WS_METHOD( ws_result, GetParam )(ws_uint8 id, ws_uint8 & type, ws_uint32 & value, wsiString ** str); };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 71 ] ] ]
00eb78165a10acc6aca5451aed61426ce6713414
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/WeirdTimes.cpp
fa41f648949e74a346ba41c35d27f34605c3b2b1
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
3,812
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "WeirdTimes.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() class WeirdTimes { public: vector <int> hourValues(vector <int> minuteValues, int K) { } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arr0[] = {22, 11, 33}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; int Arr2[] = {0, 1, 3 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, hourValues(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arr2[] = {1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, hourValues(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {2, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 20; int Arr2[] = {0, 20 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, hourValues(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {1, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 20; int Arr2[] = {0, 19 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, hourValues(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 15, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arr2[] = {-1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, hourValues(Arg0, Arg1)); } void test_case_5() { int Arr0[] = {45, 12, 0, 3, 2, 7, 4, 9, 23, 6, 17, 33}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 12345; int Arr2[] = {0, 1, 2, 2, 3, 3, 4, 5, 12, 13, 18, 18 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(5, Arg2, hourValues(Arg0, Arg1)); } void test_case_6() { int Arr0[] = {43, 58}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 318; int Arr2[] = {-1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(6, Arg2, hourValues(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { WeirdTimes ___test; ___test.run_test(-1); } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 60 ] ] ]
700daa3d43c2b19c6c9e0e4ef8ed72624f810819
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/include/Externs/ParticleUniverseBoxColliderExternTokens.h
e324bc467167eb5671e7c0fe2f0687a8a144c03c
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,823
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_BOX_COLLIDER_EXTERN_TOKENS_H__ #define __PU_BOX_COLLIDER_EXTERN_TOKENS_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseExternTokens.h" #include "ParticleUniverseAttachableTokens.h" namespace ParticleUniverse { /** The BoxColliderExternTranslator parses 'BoxColliderExtern' tokens */ class _ParticleUniverseExport BoxColliderExternTranslator : public ScriptTranslator { public: BoxColliderExternTranslator(void){}; ~BoxColliderExternTranslator(void){}; virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node); virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node); }; //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- /** */ class _ParticleUniverseExport BoxColliderExternWriter : public AttachableWriter, ExternWriter { public: BoxColliderExternWriter(void) {}; virtual ~BoxColliderExternWriter(void) {}; /** @see ScriptWriter::write */ virtual void write(ParticleScriptSerializer* serializer , const IElement* element); }; } #endif
[ [ [ 1, 51 ] ] ]
3bba5fcdb07b52ce49b9a50654cc6e81909d7d65
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/ServerModule/GameServer/RequestSocket.cpp
37312c7a681c18272e13dcb937395c421a707c65
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
7,795
cpp
#include "stdafx.h" #include ".\requestsocket.h" #include ".\InitParamter.h" #include "GameServiceHelperContainer.h" CRequestSocket::CRequestSocket(void) { m_pIEventService = NULL; m_pParentContainer = NULL; m_pGameServiceParameter = NULL; m_pInitParamter = NULL; } CRequestSocket::~CRequestSocket(void) { if (m_ClientSocketHelper.GetInterface()!=NULL) { m_ClientSocketHelper->CloseSocket(false); m_ClientSocketHelper.CloseInstance(); } } //接口查询 void * __cdecl CRequestSocket::QueryInterface(const IID & Guid, DWORD dwQueryVer) { QUERYINTERFACE(IClientSocketSink,Guid,dwQueryVer); return NULL; } //网络连接消息 bool __cdecl CRequestSocket::OnSocketConnect(int iErrorCode, LPCTSTR pszErrorDesc, IClientSocket * pIClientSocke) { GT_ASSERT(m_pIEventService!=NULL); TCHAR szDescribe[128]=TEXT(""); if(iErrorCode == 0) { _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】中心服务器连接成功"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Normal); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】正在请求登陆信息"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Normal); CMD_CS_GetLoaderServerInfo sendData; //变量定义 TCHAR szWriteBuffer[256]=TEXT(""); CXOREncrypt::EncryptData(m_pInitParamter->m_szLoaderServerPass,szWriteBuffer,sizeof(szWriteBuffer)); lstrcpyn(sendData.szLoaderServerPass,szWriteBuffer,CountArray(sendData.szLoaderServerPass)); sendData.wServerID = m_pInitParamter->m_wServerID; return SendData(MDM_CS_SERVER_REQUEST, SUB_CS_GET_LOADERSERVERINFO, &sendData, sizeof(sendData)); } else { _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】CenterServer连接失败"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Warning); return false; } } //网络读取消息 bool __cdecl CRequestSocket::OnSocketRead(CMD_Command Command, void * pBuffer, WORD wDataSize, IClientSocket * pIClientSocke) { switch(Command.wMainCmdID) { case MDM_CS_SERVER_REQUEST: return OnSocketServerRequest(Command, pBuffer, wDataSize); default: break; } return false; } //网络关闭消息 bool __cdecl CRequestSocket::OnSocketClose(IClientSocket * pIClientSocke, bool bCloseByServer) { GT_ASSERT(m_pIEventService!=NULL); TCHAR szDescribe[128]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】CenterServer连接断开"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Exception); return true; } //设置事件 bool CRequestSocket::SetEventService(IUnknownEx * pIUnknownEx) { GT_ASSERT(pIUnknownEx!=NULL); m_pIEventService=GET_OBJECTPTR_INTERFACE(pIUnknownEx,IEventService); GT_ASSERT(m_pIEventService!=NULL); return (m_pIEventService!=NULL); } //设置 bool CRequestSocket::SetParentContainer(CGameServiceHelperContainer *pParent, tagGameServiceParameter* pGameServiceParameter, CInitParamter* pInitParamter) { m_pParentContainer = pParent; m_pGameServiceParameter = pGameServiceParameter; m_pInitParamter = pInitParamter; return (m_pParentContainer!=NULL); } //连接服务器 bool CRequestSocket::Connect(DWORD dwServerIP, WORD wPort) { CloseSocket(false); //连接对象 if (m_ClientSocketHelper.GetInterface()==NULL) { //创建对象 bool bSuccess=m_ClientSocketHelper.CreateInstance(); if (bSuccess==false) { GT_ASSERT(m_pIEventService!=NULL); TCHAR szDescribe[128]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】CenterServer连接对象创建失败"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Exception); return false; } //设置接口 IClientSocketSink * pIClientSocketSink=GET_MYSELF_INTERFACE(IClientSocketSink); GT_ASSERT(pIClientSocketSink!=NULL); if (m_ClientSocketHelper->SetSocketSink(pIClientSocketSink)==false) { GT_ASSERT(m_pIEventService!=NULL); TCHAR szDescribe[128]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】CenterServer连接对象回调接口设置失败"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Exception); return false; } } //请求处理 GT_ASSERT(m_ClientSocketHelper.GetInterface()!=NULL); return m_ClientSocketHelper->Connect(dwServerIP,wPort); } //发送函数 bool CRequestSocket::SendData(WORD wMainCmdID, WORD wSubCmdID, void * pData, WORD wDataSize) { //请求处理 GT_ASSERT(m_ClientSocketHelper.GetInterface()!=NULL); return m_ClientSocketHelper->SendData(wMainCmdID,wSubCmdID,pData,wDataSize); } //关闭连接 bool CRequestSocket::CloseSocket(bool bNotify) { //关闭连接 if (m_ClientSocketHelper.GetInterface()!=NULL) { m_ClientSocketHelper->CloseSocket(false); } return true; } bool __cdecl CRequestSocket::OnSocketServerRequest(CMD_Command Command, void * pBuffer, WORD wDataSize) { switch(Command.wSubCmdID) { case SUB_CS_GET_LOADERSERVERINFO_SUCCESS: { GT_ASSERT(wDataSize >= sizeof(CMD_CS_LoaderServerInfo)); CMD_CS_LoaderServerInfo *pInfo = (CMD_CS_LoaderServerInfo*)pBuffer; GT_ASSERT(m_pIEventService!=NULL); TCHAR szDescribe[128]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】请求登陆信息成功"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Normal); GT_ASSERT(m_pGameServiceParameter); memcpy(m_pGameServiceParameter, pInfo, sizeof(CMD_CS_LoaderServerInfo)); CXOREncrypt::CrevasseData(pInfo->GameUserDBInfo.szDataBasePipeName,m_pInitParamter->m_szGameUserDBPipeName,CountArray(m_pInitParamter->m_szGameUserDBPipeName)); CXOREncrypt::CrevasseData(pInfo->GameUserDBInfo.szDataBaseUser,m_pInitParamter->m_szGameUserDBUser,CountArray(m_pInitParamter->m_szGameUserDBUser)); CXOREncrypt::CrevasseData(pInfo->GameUserDBInfo.szDataBasePass,m_pInitParamter->m_szGameUserDBPass,CountArray(m_pInitParamter->m_szGameUserDBPass)); m_pInitParamter->m_wGameUserDBPort = pInfo->GameUserDBInfo.wDataBasePort; struct in_addr in; in.S_un.S_addr = pInfo->GameUserDBInfo.dwDataBaseAddr; strcpy(m_pInitParamter->m_szGameUserDBAddr,inet_ntoa(in)); strcpy(m_pInitParamter->m_szGameUserDBName, szGameUserDB); CXOREncrypt::CrevasseData(pInfo->GameScoreDBInfo.szDataBasePipeName,m_pInitParamter->m_szServerInfoDBPipeName,CountArray(m_pInitParamter->m_szServerInfoDBPipeName)); CXOREncrypt::CrevasseData(pInfo->GameScoreDBInfo.szDataBaseUser,m_pInitParamter->m_szServerInfoDBUser,CountArray(m_pInitParamter->m_szServerInfoDBUser)); CXOREncrypt::CrevasseData(pInfo->GameScoreDBInfo.szDataBasePass,m_pInitParamter->m_szServerInfoDBPass,CountArray(m_pInitParamter->m_szServerInfoDBPass)); m_pInitParamter->m_wServerInfoDBPort = pInfo->GameScoreDBInfo.wDataBasePort; in.S_un.S_addr = pInfo->GameScoreDBInfo.dwDataBaseAddr; strcpy(m_pInitParamter->m_szServerInfoDBAddr,inet_ntoa(in)); strcpy(m_pInitParamter->m_szServerInfoDBName, szGameUserDB); GT_ASSERT(m_pParentContainer!=NULL); m_pParentContainer->OnRequestInfoOk(0,0); return true; } case SUB_CS_GET_LOADERSERVERINFO_FAILD: { GT_ASSERT(m_pIEventService!=NULL); TCHAR szDescribe[128]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】启动服务失败"),(LONG)m_pInitParamter->m_wServerID); m_pIEventService->ShowEventNotify(szDescribe,Level_Exception); return true; } default: break; } return false; }
[ [ [ 1, 212 ] ] ]
edac4604f78d1e9fab4af0bc4aced9fea6b08e99
3bfe835203f793ee00bdf261c26992b1efea69ed
/fall08/cs460/cloth/cloth/Cloth.h
8c73f021d38bf0276828f3c6aeefc0d3124c766e
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
UTF-8
C++
false
false
746
h
#pragma once #include "AutoList.h" #include "Vertex.h" class Cloth : public AutoList< Cloth > { public: Cloth( float _width, float _height, int resX, int resY, D3DXVECTOR3 pos = D3DXVECTOR3( 0.f, 0.f, 0.f ) ); ~Cloth( void ); float GetWidth( void ) const; float GetHeight( void ) const; int GetResX( void ) const; int GetResY( void ) const; VertVec &GetVertices( void ); void UpdateNormals( void ); int GetNumNodes( void ) const; const D3DXVECTOR3 &GetPos( void ) const; ColoredVertex &GetVertex( int r, int c ); private: VertVec vertices; float width, height; int resX, resY; D3DXVECTOR3 pos; };
[ [ [ 1, 30 ] ] ]
cbd94182b75b61616b149fdf8a58619a8a2aa72f
8fa4334746f35b9103750bb23ec2b8d38e93cbe9
/coding/qt/forum/forum/main.cpp
f5b89bd612de226d10dcbc8d6f97a1a8aa99480b
[]
no_license
zhzengj/testrepo
620b22b2cf1e8ff10274a9d0c6491816cecaec3b
daf8bd55fd347220f07bfd7d15b02b01a516479b
refs/heads/master
2016-09-11T00:50:57.846600
2011-10-16T07:59:48
2011-10-16T07:59:48
2,365,453
0
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
#include "stdafx.h" #include "forum.h" #include "japplication.h" int main(int argc, char *argv[]) { JApplication a(argc, argv); a.loadInfo("data/load.xml"); forum w; w.show(); int res = a.exec(); a.saveInfo(); return res; }
[ [ [ 1, 15 ] ] ]
bd12b63c1b1981ab26543aa92958dd33351e3013
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavobjects/systemalarms.cpp
d3c514df2e079d5f4221fb1c6c3779ecf8626f4c
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,713
cpp
/** ****************************************************************************** * * @file systemalarms.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVObjectsPlugin UAVObjects Plugin * @{ * * @note Object definition file: systemalarms.xml. * This is an automatically generated file. * DO NOT modify manually. * * @brief The UAVUObjects GCS plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "systemalarms.h" #include "uavobjectfield.h" const QString SystemAlarms::NAME = QString("SystemAlarms"); /** * Constructor */ SystemAlarms::SystemAlarms(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME) { // Create fields QList<UAVObjectField*> fields; QStringList AlarmElemNames; AlarmElemNames.append("OutOfMemory"); AlarmElemNames.append("StackOverflow"); AlarmElemNames.append("CPUOverload"); AlarmElemNames.append("EventSystem"); AlarmElemNames.append("SDCard"); AlarmElemNames.append("Telemetry"); AlarmElemNames.append("ManualControl"); AlarmElemNames.append("Actuator"); AlarmElemNames.append("Stabilization"); AlarmElemNames.append("AHRSComms"); QStringList AlarmEnumOptions; AlarmEnumOptions.append("OK"); AlarmEnumOptions.append("Warning"); AlarmEnumOptions.append("Error"); AlarmEnumOptions.append("Critical"); fields.append( new UAVObjectField(QString("Alarm"), QString(""), UAVObjectField::ENUM, AlarmElemNames, AlarmEnumOptions) ); // Initialize object initializeFields(fields, (quint8*)&data, NUMBYTES); // Set the default field values setDefaultFieldValues(); } /** * Get the default metadata for this object */ UAVObject::Metadata SystemAlarms::getDefaultMetadata() { UAVObject::Metadata metadata; metadata.flightAccess = ACCESS_READWRITE; metadata.gcsAccess = ACCESS_READWRITE; metadata.gcsTelemetryAcked = 1; metadata.gcsTelemetryUpdateMode = UAVObject::UPDATEMODE_ONCHANGE; metadata.gcsTelemetryUpdatePeriod = 0; metadata.flightTelemetryAcked = 1; metadata.flightTelemetryUpdateMode = UAVObject::UPDATEMODE_PERIODIC; metadata.flightTelemetryUpdatePeriod = 4000; metadata.loggingUpdateMode = UAVObject::UPDATEMODE_PERIODIC; metadata.loggingUpdatePeriod = 1000; return metadata; } /** * Initialize object fields with the default values. * If a default value is not specified the object fields * will be initialized to zero. */ void SystemAlarms::setDefaultFieldValues() { } /** * Get the object data fields */ SystemAlarms::DataFields SystemAlarms::getData() { QMutexLocker locker(mutex); return data; } /** * Set the object data fields */ void SystemAlarms::setData(const DataFields& data) { QMutexLocker locker(mutex); // Get metadata Metadata mdata = getMetadata(); // Update object if the access mode permits if ( mdata.gcsAccess == ACCESS_READWRITE ) { this->data = data; emit objectUpdatedAuto(this); // trigger object updated event emit objectUpdated(this); } } /** * Create a clone of this object, a new instance ID must be specified. * Do not use this function directly to create new instances, the * UAVObjectManager should be used instead. */ UAVDataObject* SystemAlarms::clone(quint32 instID) { SystemAlarms* obj = new SystemAlarms(); obj->initialize(instID, this->getMetaObject()); return obj; } /** * Static function to retrieve an instance of the object. */ SystemAlarms* SystemAlarms::GetInstance(UAVObjectManager* objMngr, quint32 instID) { return dynamic_cast<SystemAlarms*>(objMngr->getObject(SystemAlarms::OBJID, instID)); }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 142 ] ] ]
96013b2449cd940b1d715d10296dc9cca57b13db
0454def9ffc8db9884871a7bccbd7baa4322343b
/src/plugins/shared/QUSimpleTask.h
b588189259783809a3c81dacf97d40e86e052b71
[]
no_license
escaped/uman
e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3
bedc1c6c4fc464be4669f03abc9bac93e7e442b0
refs/heads/master
2016-09-05T19:26:36.679240
2010-07-26T07:55:31
2010-07-26T07:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,317
h
#ifndef QUABSTRACTTASK_H_ #define QUABSTRACTTASK_H_ #include <QObject> #include <QIcon> #include "QUSongInterface.h" #include "QUTaskPlugin.h" #include "QUSmartSetting.h" class QUSimpleTask: public QObject, public QUTask { Q_OBJECT Q_INTERFACES(QUTask) public: QUSimpleTask(QObject *parent = 0); virtual QIcon icon() const { return _icon; } virtual QString description() const { return _description; } virtual QString toolTip() const { return _toolTip; } virtual int group() const { return _group; } // a simple task is not configurable virtual bool isConfigurable() const { return false; } virtual int configure(QWidget *parent) { return 0; } // a simple task has no smart settings virtual QList<QUSmartSettingInterface*> smartSettings() const { return QList<QUSmartSettingInterface*>(); } virtual void provideData(const QVariant &data, TaskDataTypes type = UndefinedData) {} private: QIcon _icon; QString _description; QString _toolTip; int _group; protected: void setIcon(const QIcon &icon) { _icon = icon; } void setDescription(const QString &description) { _description = description; } void setToolTip(const QString &toolTip) { _toolTip = toolTip; } void setGroup(int group) { _group = group; } }; #endif /*QUABSTRACTTASK_H_*/
[ [ [ 1, 44 ] ] ]
e0b396277315d7d78f06752f4c1def54e41e033e
f69b9ae8d4c17d3bed264cefc5a82a0d64046b1c
/src/assay_editor/AssayDialog.cxx
d9f81b1230f79a04d17672cfab7e8022ed62b738
[]
no_license
lssgufeng/proteintracer
611501cf8001ff9d4bf5e7aa645c24069cce675f
055cc953d6bf62d17eb9435117f44b3f3d9b8f3f
refs/heads/master
2016-08-09T22:20:40.978584
2009-06-07T22:08:14
2009-06-07T22:08:14
55,025,270
0
0
null
null
null
null
UTF-8
C++
false
false
14,877
cxx
/*============================================================================== Copyright (c) 2009, André Homeyer 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==============================================================================*/ #include <assay_editor/AssayDialog.h> #include <sstream> #include <vector> #include <FL/Fl.H> #include <FL/Fl_Box.H> #include <FL/Fl_Group.H> #include <FL/fl_ask.H> #include <itkComposeRGBImageFilter.h> #include <itkFlipImageFilter.h> #include <itkImage.h> #include <itkImageFileReader.h> #include <itkRescaleIntensityImageFilter.h> #include <Scan.h> #include <analyzers/AnalyzerRegistry.h> #include <gui/common.h> #include <images.h> #include <io/AssayIO.h> using std::auto_ptr; using std::cout; using std::endl; using std::string; using std::stringstream; using std::vector; using PT::AnalyzerRegistry; using PT::Assay; using PT::ImageIndex; using PT::ImageKey; using PT::ImageMetadata; using PT::RGBImage; using PT::Scan; using PT::UCharImage; using PT::UShortImage; using PT::Visualization; AssayDialog::AssayDialog(int x, int y, int width, int height) : Fl_Group(x, y, width, height), scan_(NULL), assay_(0), visualizer_(0) { // create user interface { static const int BIG_MARGIN = 15; static const int BUTTON_HEIGHT = 25; static const int INPUT_HEIGHT = 25; static const int LABEL_HEIGHT = 14; static const int MEDIUM_MARGIN = 10; static const int SETTINGS_WIDTH = 280; static const int SMALL_MARGIN = 5; static const int STATUSBAR_HEIGHT = 26; static const int STATUSBAR_LOCATION_BOX_WIDTH = 100; static const int STATUSBAR_ZOOM_BOX_WIDTH = 100; static const int VISUALIZATION_WIDGETS_HEIGHT = BIG_MARGIN + BUTTON_HEIGHT + INPUT_HEIGHT * 2 + LABEL_HEIGHT * 2 + MEDIUM_MARGIN * 3; // create settings group Fl_Group* settingsGroup; { settingsGroup = new Fl_Group( x, y, SETTINGS_WIDTH, height - STATUSBAR_HEIGHT); settingsGroup->box(FL_FLAT_BOX); analyzerChoice_ = new Fl_Choice( settingsGroup->x() + MEDIUM_MARGIN, settingsGroup->y() + BIG_MARGIN + LABEL_HEIGHT, settingsGroup->w() - 2 * MEDIUM_MARGIN, INPUT_HEIGHT); analyzerChoice_->label("Analysis Method"); analyzerChoice_->align(FL_ALIGN_LEFT | FL_ALIGN_TOP); analyzerChoice_->callback(fltk_member_cb<AssayDialog, &AssayDialog::selectAnalyzer>, this); // fill analyzer choice { const vector<string>& analyzerNames = AnalyzerRegistry::getAnalyzerNames(); Fl_Menu_Item* menuItems = new Fl_Menu_Item[analyzerNames.size() + 1]; vector<string>::const_iterator it = analyzerNames.begin(); vector<string>::const_iterator end = analyzerNames.end(); for (int i = 0; it != end; ++i, ++it) { const std::string& name = *it; menuItems[i].text = name.c_str(); menuItems[i].shortcut_ = 0; menuItems[i].callback_ = 0; menuItems[i].user_data_ = 0; menuItems[i].flags = FL_MENU_VALUE; menuItems[i].labeltype_ = FL_NORMAL_LABEL; menuItems[i].labelfont_ = FL_HELVETICA; menuItems[i].labelsize_ = 14; menuItems[i].labelcolor_ = FL_BLACK; } // add closing item menuItems[analyzerNames.size()].text = 0; analyzerChoice_->menu(menuItems); } int pty = analyzerChoice_->y() + analyzerChoice_->h() + MEDIUM_MARGIN; parameterTable_ = new ParameterTable( analyzerChoice_->x(), pty, analyzerChoice_->w(), settingsGroup->y() + settingsGroup->h() - pty - VISUALIZATION_WIDGETS_HEIGHT); parameterTable_->setEventHandler(this); settingsGroup->resizable(parameterTable_); imageSelector_ = new ImageSelector( parameterTable_->x(), parameterTable_->y() + parameterTable_->h() + BIG_MARGIN, parameterTable_->w(), LABEL_HEIGHT + INPUT_HEIGHT); imageSelector_->setEventHandler(this); visualizationChoice_ = new Fl_Choice( imageSelector_->x(), imageSelector_->y() + imageSelector_->h() + MEDIUM_MARGIN + LABEL_HEIGHT, imageSelector_->w(), INPUT_HEIGHT); visualizationChoice_->label("Visualization"); visualizationChoice_->align(FL_ALIGN_LEFT | FL_ALIGN_TOP); computeVisualizationButton_ = new Fl_Button( visualizationChoice_->x(), visualizationChoice_->y() + visualizationChoice_->h() + MEDIUM_MARGIN, visualizationChoice_->w(), BUTTON_HEIGHT); computeVisualizationButton_->label("Compute Visualization"); computeVisualizationButton_->callback(fltk_member_cb<AssayDialog, &AssayDialog::computeVisualization>, this); settingsGroup->end(); } // create image viewer { Fl_Group* imageViewerGroup = new Fl_Group( settingsGroup->x() + settingsGroup->w(), settingsGroup->y(), width - settingsGroup->w(), settingsGroup->h()); imageViewerGroup->box(FL_DOWN_BOX); this->resizable(imageViewerGroup); imageViewer_ = new ImageViewer( imageViewerGroup->x() + 2, imageViewerGroup->y() + 2, imageViewerGroup->w() - 4, imageViewerGroup->h() - 4); imageViewer_->setEventHandler(this); imageViewerGroup->resizable(imageViewer_); imageViewerGroup->end(); } // create status bar { Fl_Group* statusBar = new Fl_Group( x - 2, y + height - STATUSBAR_HEIGHT, width + 4, STATUSBAR_HEIGHT + 2); statusBar->box(FL_ENGRAVED_BOX); statusbarPixelLabelBox_ = new Fl_Box( statusBar->x() + SMALL_MARGIN, statusBar->y() + (statusBar->h() - LABEL_HEIGHT) / 2, statusBar->w() - STATUSBAR_LOCATION_BOX_WIDTH - STATUSBAR_ZOOM_BOX_WIDTH - 2 * SMALL_MARGIN, LABEL_HEIGHT); statusbarPixelLabelBox_->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE); statusBar->resizable(statusbarPixelLabelBox_); statusbarPixelLocationBox_ = new Fl_Box( statusbarPixelLabelBox_->x() + statusbarPixelLabelBox_->w(), statusbarPixelLabelBox_->y(), STATUSBAR_LOCATION_BOX_WIDTH, statusbarPixelLabelBox_->h()); statusbarPixelLocationBox_->align(FL_ALIGN_CENTER | FL_ALIGN_INSIDE); statusbarZoomBox_ = new Fl_Box( statusbarPixelLocationBox_->x() + statusbarPixelLocationBox_->w(), statusbarPixelLocationBox_->y(), STATUSBAR_ZOOM_BOX_WIDTH, statusbarPixelLocationBox_->h()); statusbarZoomBox_->align(FL_ALIGN_CENTER | FL_ALIGN_INSIDE); statusBar->end(); } this->Fl_Group::end(); } // create default assay const string& analyzerName = AnalyzerRegistry::getDefaultAnalyzerName(); auto_ptr<Assay> assay = AnalyzerRegistry::createAssay(analyzerName); setAssay(assay); } void AssayDialog::setScan(const Scan* scan) { scan_ = scan; imageSelector_->setImageSeriesSet(scan_); showStandardVisualization(); } void initMenuItem(Fl_Menu_Item* menuItem, const char* name) { // text values of menu items are not changed internally so this // const cast is safe menuItem->text = const_cast<char*>(name); menuItem->shortcut_ = 0; menuItem->callback_ = 0; menuItem->user_data_ = 0; menuItem->flags = FL_MENU_VALUE; menuItem->labeltype_ = FL_NORMAL_LABEL; menuItem->labelfont_ = FL_HELVETICA; menuItem->labelsize_ = 14; menuItem->labelcolor_ = FL_BLACK; } void AssayDialog::setAssay(std::auto_ptr<Assay> assay) { assert(assay.get() != 0); assay_ = assay; // set analyzer choice const string& name = assay_->getAnalyzerName(); const Fl_Menu_Item* menuItem = analyzerChoice_->find_item(name.c_str()); analyzerChoice_->value(menuItem); // set parameter table parameterTable_->setParameterSet(assay_.get()); // create new visualizer and replace old one const string& analyzerName = assay_->getAnalyzerName(); visualizer_ = AnalyzerRegistry::createVisualizer(analyzerName); // fill visualizer choice widgets { const vector<string>& visualizationNames = visualizer_->getVisualizationNames(); assert(visualizationNames.size() > 0); Fl_Menu_Item* menuItems = new Fl_Menu_Item[visualizationNames.size() + 1]; for (int i = 0; i < visualizationNames.size(); ++i) { initMenuItem(&menuItems[i], visualizationNames[i].c_str()); } initMenuItem(&menuItems[visualizationNames.size()], 0); visualizationChoice_->copy(menuItems); delete[] menuItems; // just updating the menu items does not redraw the Fl_Choice visualizationChoice_->redraw(); } showStandardVisualization(); } const Assay& AssayDialog::getAssay() { return *assay_; } void AssayDialog::showStandardVisualization() { if (visualizer_.get() != NULL) { visualizationChoice_->value(0); computeVisualization(); } } int AssayDialog::handle(int event) { switch(event) { case FL_SHORTCUT: { int key = Fl::event_key(); if (key == FL_F + 5) { computeVisualization(); } return 1; } default: return Fl_Group::handle(event); } } void AssayDialog::handleEvent(const ImageViewerEvent &event) { updateStatusbar(); } void AssayDialog::handleEvent(const ImageSelectorEvent &event) { showStandardVisualization(); } void AssayDialog::selectAnalyzer() { const string& selection = analyzerChoice_->text(); auto_ptr<Assay> assay = AnalyzerRegistry::createAssay(selection); setAssay(assay); } void AssayDialog::updateStatusbar() { ImageIndex mousePos = imageViewer_->getMousePosition(); int x = mousePos[0]; int y = mousePos[1]; // update label box if (visualization_.get() != 0) { string label = visualization_->getPixelLabel(x, y); statusbarPixelLabelBox_->copy_label(label.c_str()); } else { statusbarPixelLabelBox_->copy_label(""); } // update location box if (x >= 0 && y >= 0) { stringstream text; text << x << ", " << y; statusbarPixelLocationBox_->copy_label(text.str().c_str()); } else { statusbarPixelLocationBox_->copy_label(""); } // update zoom box stringstream zoomText; zoomText << imageViewer_->getZoom() << " %"; statusbarZoomBox_->copy_label(zoomText.str().c_str()); } void AssayDialog::computeVisualization() { assert(visualizer_.get() != 0); if (scan_ != 0) { if (visualizationChoice_->text()) { try { string visualizationName(visualizationChoice_->text()); ImageKey imageKey = imageSelector_->getSelection(); const ImageMetadata& imageMetadata = scan_->getImageMetadata(imageKey); auto_ptr<Visualization> visualization = visualizer_->createVisualization(visualizationName, *assay_.get(), imageMetadata); assert(visualization.get() != 0); assert(visualization->getImage().IsNotNull()); if (visualization_.get() != 0 && imageKey.location == visualization_->getImageKey().location) { imageViewer_->setImageAndRetainFocus(visualization->getImage()); } else { imageViewer_->setImage(visualization->getImage()); } this->visualization_ = visualization; } catch (PT::VisualizerException& e) { stringstream messageStream; messageStream << "Visualization failed..." << endl << endl << e.what(); string message = messageStream.str(); fl_message(message.c_str()); } } } }
[ "andre.homeyer@localhost" ]
[ [ [ 1, 429 ] ] ]
a7624a38022ed249bb9b8eeb0edfad5d6dba99ef
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/messagingmw/BCTForSendUIAPI/inc/SendUIAPITest.h
3c50974e44a45db14183f40672c9e87149ec5e5f
[]
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
16,544
h
/* * Copyright (c) 2002 - 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: ?Description * */ #ifndef SENDUIAPITEST_H #define SENDUIAPITEST_H // INCLUDES #include <StifLogger.h> #include <TestScripterInternal.h> #include <StifTestModule.h> #include <TestclassAssert.h> #include <cmessagedata.h> //#include <bc_plat.h> // CONSTANTS //const ?type ?constant_var = ?constant; // MACROS //#define ?macro ?macro_def #if ! defined( __SERIES60_31__ ) && ! defined( __SERIES60_30__ ) #define TEST_CLASS_VERSION_MAJOR 32 #else if #define TEST_CLASS_VERSION_MAJOR 30 #endif #define TEST_CLASS_VERSION_MINOR 9 #define TEST_CLASS_VERSION_BUILD 38 // Logging path _LIT( KSendUIAPITestLogPath, "\\logs\\testframework\\SendUIAPITest\\" ); // Log file _LIT( KSendUIAPITestLogFile, "SendUIAPITest.txt" ); _LIT( KSendUIAPITestLogFileWithTitle, "SendUIAPITest_[%S].txt" ); // FUNCTION PROTOTYPES //?type ?function_name(?arg_list); // FORWARD DECLARATIONS //class ?FORWARD_CLASSNAME; class CMessageAddress; class CMessageData; class CSendUIAPITest; class CSendingServiceInfo; // DATA TYPES //enum ?declaration //typedef ?declaration //extern ?data_type; // CLASS DECLARATION /** * CSendUIAPITest test class for STIF Test Framework TestScripter. * ?other_description_lines * * @lib ?library * @since ?Series60_version */ NONSHARABLE_CLASS(CSendUIAPITest) : public CScriptBase { public: // Constructors and destructor /** * Two-phased constructor. */ static CSendUIAPITest* NewL( CTestModuleIf& aTestModuleIf ); /** * Destructor. */ virtual ~CSendUIAPITest(); public: // New functions /** * ?Function to create CMessageData object * @since ?Series60_version * @param ?void ?no input param * @CMessageData* ?CMessageData pointer object */ CMessageData* InitL(void); public: // Functions from base classes /** * From CScriptBase Runs a script line. * @since ?Series60_version * @param aItem Script line containing method name and parameters * @return Symbian OS error code */ virtual TInt RunMethodL( CStifItemParser& aItem ); protected: // New functions /** * ?member_description. * @since ?Series60_version * @param ?arg1 ?description * @return ?description */ //?type ?member_function( ?type ?arg1 ); protected: // Functions from base classes /** * From ?base_class ?member_description */ //?type ?member_function(); private: /** * C++ default constructor. */ CSendUIAPITest( CTestModuleIf& aTestModuleIf ); /** * By default Symbian 2nd phase constructor is private. */ void ConstructL(); // Prohibit copy constructor if not deriving from CBase. // ?classname( const ?classname& ); // Prohibit assigment operator if not deriving from CBase. // ?classname& operator=( const ?classname& ); /** * Frees all resources allocated from test methods. * @since ?Series60_version */ void Delete(); /** * Test methods are listed below. */ /** * Example test method. * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt ExampleL( CStifItemParser& aItem ); /** * Method used to log version of test class */ void SendTestClassVersion(); /** * Method used to call SetSubjectL of CMessageData */ virtual TInt MsgDataSetSubjectL( TPtrC& aSubject ); /** * Method used to call SubjectL of CMessageData and Compare */ virtual TInt MsgDataCompSubjectL( TPtrC& aSubject ); /** * Test Case for Calling CMessageData's NewL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataNewL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's SetSubjectL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataSetSubjectL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's Subject fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataSubjectL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AppendAttachmentL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataAppendAttachmentL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AttachmentArray fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataAttachmentArrayL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's ClearAttachmentArray fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataClearAttachmentArrayL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AppendToAddressL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataAppendToAddressL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's ToAddressArray fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataToAddressArrayL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AppendCcAddressL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataAppendCcAddressL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's CcAddressArray fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataCcAddressArrayL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AppendBccAddressL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataAppendBccAddressL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's BccAddressArray fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataBccAddressArrayL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's SetBodyTextL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataSetBodyTextL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's BodyText fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMessageDataBodyTextL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AppendAttachmentHandleL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestAppendAttachmentHandleL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's AttachmentHandleArray fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestAttachmentHandleArrayL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's DataType fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestDataTypeL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's ClearAddresses fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt ClearAddressesL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's ExternalizeL and InternalizeL funs * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestExternalizeLnInternalizeL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's ExternalizeL fun * @since ?Series60_version * @param void * @return Symbian OS error code. */ virtual TInt ExternalizeL( void ); /** * Test Case for Calling CMessageData's InternalizeL fun * @since ?Series60_version * @param void * @return Symbian OS error code. */ virtual TInt InternalizeL( void ); /** * Test Case for Calling CMessageData's SetOpaqueDataL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestSetOpaqueDataL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageData's OpaqueDataL fun * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestOpaqueDataL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's NewL Construction * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestCMessageAddressNewL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's SetAddressL * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMsgAdrsSetAddressL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's Address * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMsgAdrsAddress( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's SetAliasL * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMsgAdrsSetAliasL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's AliasL * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMsgAdrsAlias( CStifItemParser& aItem ); /** * Test Case for Calling TSendingCapabilities functions * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestTSendingCapabilities( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's ExternalizeL * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMsgAdrsExternalizeL( CStifItemParser& aItem ); /** * Test Case for Calling CMessageAddress's InternalizeL * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestMsgAdrsInternalizeL( CStifItemParser& aItem ); /** * Test Case for Calling CSendingServiceInfo's CopyLC functions * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestCopyLC( CStifItemParser& aItem ); /** * Test Case for Calling CSendingServiceInfo's SetTechnologyTypeId functions * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestSetTechnologyTypeIdL( CStifItemParser& aItem ); /** * Test Case for Calling CSendingServiceInfo's ServiceID functions * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestServiceIDL( CStifItemParser& aItem ); /** * Test Case for Calling CSendingServiceInfo's ServiceProviderID functions * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestServiceProviderIDL( CStifItemParser& aItem ); /** * Test Case for Calling CSendingServiceInfo's ServiceCapabilities functions * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ virtual TInt TestServiceCapabilitiesL( CStifItemParser& aItem ); //ADD NEW METHOD DEC HERE //[TestMethods] - Do not remove public: // Data // ?one_line_short_description_of_data //?data_declaration; protected: // Data // ?one_line_short_description_of_data //?data_declaration; private: // Data //CMessageData memeber variable CMessageData* iMessageData; //Buffer to read and write from stream CBufBase* ibuffer; //CMessageAddress variable CMessageAddress* iMessageAddress; //Buffer to read and write from stream CBufBase* iMsgAdrbuffer; //?data_declaration; // Reserved pointer for future extension //TAny* iReserved; public: // Friend classes //?friend_class_declaration; protected: // Friend classes //?friend_class_declaration; private: // Friend classes //?friend_class_declaration; }; #endif // SendUIAPITest_H // End of File
[ "none@none" ]
[ [ [ 1, 510 ] ] ]
e063b50cca3b6d5bdcfd1bc797f6734a222aeec6
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/plugins/GSdx/GSCapture.h
bb35cfc8b52a8fb9430c9ed5f3bb0d92b9300809
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
h
/* * Copyright (C) 2007-2009 Gabest * http://www.gabest.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #pragma once #include "GSCaptureDlg.h" #include "GSVector.h" class GSCapture : protected CCritSec { bool m_capturing; GSVector2i m_size; CComPtr<IGraphBuilder> m_graph; CComPtr<IBaseFilter> m_src; public: GSCapture(); virtual ~GSCapture(); bool BeginCapture(int fps); bool DeliverFrame(const void* bits, int pitch, bool rgba); bool EndCapture(); bool IsCapturing() {return m_capturing;} GSVector2i GetSize() {return m_size;} };
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 44 ] ] ]
e39d4f2c47e480263e9da087c3b6cc5a5b53c4a7
3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c
/zju.finished/1102.cpp
e674416173092e16671d73c5a0acb4bfe951c335
[]
no_license
usherfu/zoj
4af6de9798bcb0ffa9dbb7f773b903f630e06617
8bb41d209b54292d6f596c5be55babd781610a52
refs/heads/master
2021-05-28T11:21:55.965737
2009-12-15T07:58:33
2009-12-15T07:58:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
cpp
#include<iostream> using namespace std; enum { SIZ = 1028, MAXV = 99999999, ALP = 'Z' - 'A' + 1, }; int num, len; char gen[SIZ][SIZ]; char ans[SIZ]; int tmp[SIZ][ALP+1]; int compute(int p){ int i,j,l=num; for(i=0; i<num; i++){ for(j=0; j<ALP; j++){ tmp[i][j] = (gen[i][p]!=(j+'A')); } tmp[i][ALP] = 0; } while(l>1){ for(i=0; i<l; i+=2){ tmp[l][ALP] = MAXV; for(j=0; j<ALP; j++){ tmp[l][j] = tmp[i][j] + tmp[i+1][j]; // same // different int t=min(tmp[i][j]+tmp[i+1][ALP]+1,tmp[i][ALP]+tmp[i+1][j]+1); tmp[l][j] = min(t, tmp[l][j]); tmp[l][ALP] = min(tmp[l][ALP], tmp[l][j]); } for(j=0; j<=ALP;j++){ tmp[i/2][j] = tmp[l][j]; } } l/=2; } for(i=0; i<ALP; i++){ if(tmp[0][i] == tmp[0][ALP]){ ans[p] = i + 'A'; } } return tmp[0][ALP]; } void fun(){ if(num == 1){ printf("%s 0\n", gen[0]); return; } int j, sum = 0; for(j=0; j<len; j++){ sum += compute(j); } ans[len] = 0; printf("%s %d\n", ans, sum); } int readIn(){ scanf("%d%d",&num, &len); for(int i=0; i<num; i++){ scanf("%s", gen[i]); } return num; } int main(){ while(readIn() > 0){ fun(); } return 0; }
[ [ [ 1, 68 ] ] ]
4d729aae3e5e11718b730a10b84af27accfab4b6
831c55b8b44c63ae9d14987a61917bc0b20d8078
/branches/processor-symbol-cache/src/client/windows/crash_generation/crash_generation_server.cc
dbdf0014baf47599ee941c3cb545122d771f0f96
[ "FSFUL", "BSD-3-Clause" ]
permissive
rickfillion/Google-Breakpad
b1273f0d3668510315933c6e5a06ff181b925233
f0cc73a221f67d1c62fb26116cbbb3cfb0b072ff
refs/heads/master
2020-12-30T19:37:37.147738
2011-07-07T20:53:52
2011-07-07T20:53:52
2,705,549
0
0
null
null
null
null
UTF-8
C++
false
false
27,194
cc
// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "client/windows/crash_generation/crash_generation_server.h" #include <Windows.h> #include <cassert> #include "client/windows/common/auto_critical_section.h" #include "processor/scoped_ptr.h" namespace google_breakpad { // Output buffer size. const size_t kOutBufferSize = 64; // Input buffer size. const size_t kInBufferSize = 64; // Access flags for the client on the dump request event. const DWORD kDumpRequestEventAccess = EVENT_MODIFY_STATE; // Access flags for the client on the dump generated event. const DWORD kDumpGeneratedEventAccess = EVENT_MODIFY_STATE | SYNCHRONIZE; // Access flags for the client on the mutex. const DWORD kMutexAccess = SYNCHRONIZE; // Attribute flags for the pipe. const DWORD kPipeAttr = FILE_FLAG_FIRST_PIPE_INSTANCE | PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED; // Mode for the pipe. const DWORD kPipeMode = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT; // For pipe I/O, execute the callback in the wait thread itself, // since the callback does very little work. The callback executes // the code for one of the states of the server state machine and // the code for all of the states perform async I/O and hence // finish very quickly. const ULONG kPipeIOThreadFlags = WT_EXECUTEINWAITTHREAD; // Dump request threads will, most likely, generate dumps. That may // take some time to finish, so specify WT_EXECUTELONGFUNCTION flag. const ULONG kDumpRequestThreadFlags = WT_EXECUTEINWAITTHREAD | WT_EXECUTELONGFUNCTION; // Maximum delay during server shutdown if some work items // are still executing. const int kShutdownDelayMs = 10000; // Interval for each sleep during server shutdown. const int kShutdownSleepIntervalMs = 5; static bool ValidateClientRequest(const ProtocolMessage& msg) { return msg.tag == MESSAGE_TAG_REGISTRATION_REQUEST && msg.pid != 0 && msg.thread_id != NULL && msg.exception_pointers != NULL && msg.assert_info != NULL; } CrashGenerationServer::CrashGenerationServer( const wchar_t* pipe_name, OnClientConnectedCallback connect_callback, void* connect_context, OnClientDumpRequestCallback dump_callback, void* dump_context, OnClientExitedCallback exit_callback, void* exit_context, bool generate_dumps, const std::wstring* dump_path) : pipe_name_(pipe_name), pipe_(NULL), pipe_wait_handle_(NULL), server_alive_handle_(NULL), connect_callback_(connect_callback), connect_context_(connect_context), dump_callback_(dump_callback), dump_context_(dump_context), exit_callback_(exit_callback), exit_context_(exit_context), generate_dumps_(generate_dumps), dump_generator_(NULL), server_state_(IPC_SERVER_STATE_INITIAL), shutting_down_(false), overlapped_(), client_info_(NULL), cleanup_item_count_(0) { InitializeCriticalSection(&clients_sync_); if (dump_path) { dump_generator_.reset(new MinidumpGenerator(*dump_path)); } } CrashGenerationServer::~CrashGenerationServer() { // Indicate to existing threads that server is shutting down. shutting_down_ = true; // Unregister wait on the pipe. if (pipe_wait_handle_) { // Wait for already executing callbacks to finish. UnregisterWaitEx(pipe_wait_handle_, INVALID_HANDLE_VALUE); } // Close the pipe to avoid further client connections. if (pipe_) { CloseHandle(pipe_); } // Request all ClientInfo objects to unregister all waits. // New scope to hold the lock for the shortest time. { AutoCriticalSection lock(&clients_sync_); std::list<ClientInfo*>::iterator iter; for (iter = clients_.begin(); iter != clients_.end(); ++iter) { ClientInfo* client_info = *iter; client_info->UnregisterWaits(); } } // Now that all waits have been unregistered, wait for some time // for all pending work items to finish. int total_wait = 0; while (cleanup_item_count_ > 0) { Sleep(kShutdownSleepIntervalMs); total_wait += kShutdownSleepIntervalMs; if (total_wait >= kShutdownDelayMs) { break; } } // Clean up all the ClientInfo objects. // New scope to hold the lock for the shortest time. { AutoCriticalSection lock(&clients_sync_); std::list<ClientInfo*>::iterator iter; for (iter = clients_.begin(); iter != clients_.end(); ++iter) { ClientInfo* client_info = *iter; delete client_info; } } if (server_alive_handle_) { // Release the mutex before closing the handle so that clients requesting // dumps wait for a long time for the server to generate a dump. ReleaseMutex(server_alive_handle_); CloseHandle(server_alive_handle_); } DeleteCriticalSection(&clients_sync_); } bool CrashGenerationServer::Start() { server_state_ = IPC_SERVER_STATE_INITIAL; server_alive_handle_ = CreateMutex(NULL, TRUE, NULL); if (!server_alive_handle_) { return false; } // Event to signal the client connection and pipe reads and writes. overlapped_.hEvent = CreateEvent(NULL, // Security descriptor. TRUE, // Manual reset. FALSE, // Initially signaled. NULL); // Name. if (!overlapped_.hEvent) { return false; } // Register a callback with the thread pool for the client connection. RegisterWaitForSingleObject(&pipe_wait_handle_, overlapped_.hEvent, OnPipeConnected, this, INFINITE, kPipeIOThreadFlags); pipe_ = CreateNamedPipe(pipe_name_.c_str(), kPipeAttr, kPipeMode, 1, kOutBufferSize, kInBufferSize, 0, NULL); if (!pipe_) { return false; } // Signal the event to start a separate thread to handle // client connections. return SetEvent(overlapped_.hEvent) != FALSE; } // If the server thread serving clients ever gets into the // ERROR state, reset the event, close the pipe and remain // in the error state forever. Error state means something // that we didn't account for has happened, and it's dangerous // to do anything unknowingly. void CrashGenerationServer::HandleErrorState() { assert(server_state_ == IPC_SERVER_STATE_ERROR); // If the server is shutting down anyway, don't clean up // here since shut down process will clean up. if (shutting_down_) { return; } if (pipe_wait_handle_) { UnregisterWait(pipe_wait_handle_); pipe_wait_handle_ = NULL; } if (pipe_) { CloseHandle(pipe_); pipe_ = NULL; } if (overlapped_.hEvent) { CloseHandle(overlapped_.hEvent); overlapped_.hEvent = NULL; } } // When the server thread serving clients is in the INITIAL state, // try to connect to the pipe asynchronously. If the connection // finishes synchronously, directly go into the CONNECTED state; // otherwise go into the CONNECTING state. For any problems, go // into the ERROR state. void CrashGenerationServer::HandleInitialState() { assert(server_state_ == IPC_SERVER_STATE_INITIAL); if (!ResetEvent(overlapped_.hEvent)) { server_state_ = IPC_SERVER_STATE_ERROR; return; } bool success = ConnectNamedPipe(pipe_, &overlapped_) != FALSE; // From MSDN, it is not clear that when ConnectNamedPipe is used // in an overlapped mode, will it ever return non-zero value, and // if so, in what cases. assert(!success); DWORD error_code = GetLastError(); switch (error_code) { case ERROR_IO_PENDING: server_state_ = IPC_SERVER_STATE_CONNECTING; break; case ERROR_PIPE_CONNECTED: if (SetEvent(overlapped_.hEvent)) { server_state_ = IPC_SERVER_STATE_CONNECTED; } else { server_state_ = IPC_SERVER_STATE_ERROR; } break; default: server_state_ = IPC_SERVER_STATE_ERROR; break; } } // When the server thread serving the clients is in the CONNECTING state, // try to get the result of the asynchronous connection request using // the OVERLAPPED object. If the result indicates the connection is done, // go into the CONNECTED state. If the result indicates I/O is still // INCOMPLETE, remain in the CONNECTING state. For any problems, // go into the DISCONNECTING state. void CrashGenerationServer::HandleConnectingState() { assert(server_state_ == IPC_SERVER_STATE_CONNECTING); DWORD bytes_count = 0; bool success = GetOverlappedResult(pipe_, &overlapped_, &bytes_count, FALSE) != FALSE; if (success) { server_state_ = IPC_SERVER_STATE_CONNECTED; return; } if (GetLastError() != ERROR_IO_INCOMPLETE) { server_state_ = IPC_SERVER_STATE_DISCONNECTING; } } // When the server thread serving the clients is in the CONNECTED state, // try to issue an asynchronous read from the pipe. If read completes // synchronously or if I/O is pending then go into the READING state. // For any problems, go into the DISCONNECTING state. void CrashGenerationServer::HandleConnectedState() { assert(server_state_ == IPC_SERVER_STATE_CONNECTED); DWORD bytes_count = 0; memset(&msg_, 0, sizeof(msg_)); bool success = ReadFile(pipe_, &msg_, sizeof(msg_), &bytes_count, &overlapped_) != FALSE; // Note that the asynchronous read issued above can finish before the // code below executes. But, it is okay to change state after issuing // the asynchronous read. This is because even if the asynchronous read // is done, the callback for it would not be executed until the current // thread finishes its execution. if (success || GetLastError() == ERROR_IO_PENDING) { server_state_ = IPC_SERVER_STATE_READING; } else { server_state_ = IPC_SERVER_STATE_DISCONNECTING; } } // When the server thread serving the clients is in the READING state, // try to get the result of the async read. If async read is done, // go into the READ_DONE state. For any problems, go into the // DISCONNECTING state. void CrashGenerationServer::HandleReadingState() { assert(server_state_ == IPC_SERVER_STATE_READING); DWORD bytes_count = 0; bool success = GetOverlappedResult(pipe_, &overlapped_, &bytes_count, FALSE) != FALSE; if (success && bytes_count == sizeof(ProtocolMessage)){ server_state_ = IPC_SERVER_STATE_READ_DONE; return; } DWORD error_code = GetLastError(); // We should never get an I/O incomplete since we should not execute this // unless the Read has finished and the overlapped event is signaled. If // we do get INCOMPLETE, we have a bug in our code. assert(error_code != ERROR_IO_INCOMPLETE); server_state_ = IPC_SERVER_STATE_DISCONNECTING; } // When the server thread serving the client is in the READ_DONE state, // validate the client's request message, register the client by // creating appropriate objects and prepare the response. Then try to // write the response to the pipe asynchronously. If that succeeds, // go into the WRITING state. For any problems, go into the DISCONNECTING // state. void CrashGenerationServer::HandleReadDoneState() { assert(server_state_ == IPC_SERVER_STATE_READ_DONE); if (!ValidateClientRequest(msg_)) { server_state_ = IPC_SERVER_STATE_DISCONNECTING; return; } scoped_ptr<ClientInfo> client_info( new ClientInfo(this, msg_.pid, msg_.dump_type, msg_.thread_id, msg_.exception_pointers, msg_.assert_info)); if (!client_info->Initialize()) { server_state_ = IPC_SERVER_STATE_DISCONNECTING; return; } if (!RespondToClient(client_info.get())) { server_state_ = IPC_SERVER_STATE_DISCONNECTING; return; } // Note that the asynchronous write issued by RespondToClient function // can finish before the code below executes. But it is okay to change // state after issuing the asynchronous write. This is because even if // the asynchronous write is done, the callback for it would not be // executed until the current thread finishes its execution. server_state_ = IPC_SERVER_STATE_WRITING; client_info_ = client_info.release(); } // When the server thread serving the clients is in the WRITING state, // try to get the result of the async write. If the async write is done, // go into the WRITE_DONE state. For any problems, go into the // DISONNECTING state. void CrashGenerationServer::HandleWritingState() { assert(server_state_ == IPC_SERVER_STATE_WRITING); DWORD bytes_count = 0; bool success = GetOverlappedResult(pipe_, &overlapped_, &bytes_count, FALSE) != FALSE; if (success) { server_state_ = IPC_SERVER_STATE_WRITE_DONE; return; } DWORD error_code = GetLastError(); // We should never get an I/O incomplete since we should not execute this // unless the Write has finished and the overlapped event is signaled. If // we do get INCOMPLETE, we have a bug in our code. assert(error_code != ERROR_IO_INCOMPLETE); server_state_ = IPC_SERVER_STATE_DISCONNECTING; } // When the server thread serving the clients is in the WRITE_DONE state, // try to issue an async read on the pipe. If the read completes synchronously // or if I/O is still pending then go into the READING_ACK state. For any // issues, go into the DISCONNECTING state. void CrashGenerationServer::HandleWriteDoneState() { assert(server_state_ == IPC_SERVER_STATE_WRITE_DONE); server_state_ = IPC_SERVER_STATE_READING_ACK; DWORD bytes_count = 0; bool success = ReadFile(pipe_, &msg_, sizeof(msg_), &bytes_count, &overlapped_) != FALSE; if (success) { return; } DWORD error_code = GetLastError(); if (error_code != ERROR_IO_PENDING) { server_state_ = IPC_SERVER_STATE_DISCONNECTING; } } // When the server thread serving the clients is in the READING_ACK state, // try to get result of async read. Go into the DISCONNECTING state. void CrashGenerationServer::HandleReadingAckState() { assert(server_state_ == IPC_SERVER_STATE_READING_ACK); DWORD bytes_count = 0; bool success = GetOverlappedResult(pipe_, &overlapped_, &bytes_count, FALSE) != FALSE; if (success) { // The connection handshake with the client is now complete; perform // the callback. if (connect_callback_) { connect_callback_(connect_context_, client_info_); } } else { DWORD error_code = GetLastError(); // We should never get an I/O incomplete since we should not execute this // unless the Read has finished and the overlapped event is signaled. If // we do get INCOMPLETE, we have a bug in our code. assert(error_code != ERROR_IO_INCOMPLETE); } server_state_ = IPC_SERVER_STATE_DISCONNECTING; } // When the server thread serving the client is in the DISCONNECTING state, // disconnect from the pipe and reset the event. If anything fails, go into // the ERROR state. If it goes well, go into the INITIAL state and set the // event to start all over again. void CrashGenerationServer::HandleDisconnectingState() { assert(server_state_ == IPC_SERVER_STATE_DISCONNECTING); // Done serving the client. client_info_ = NULL; overlapped_.Internal = NULL; overlapped_.InternalHigh = NULL; overlapped_.Offset = 0; overlapped_.OffsetHigh = 0; overlapped_.Pointer = NULL; if (!ResetEvent(overlapped_.hEvent)) { server_state_ = IPC_SERVER_STATE_ERROR; return; } if (!DisconnectNamedPipe(pipe_)) { server_state_ = IPC_SERVER_STATE_ERROR; return; } // If the server is shutting down do not connect to the // next client. if (shutting_down_) { return; } server_state_ = IPC_SERVER_STATE_INITIAL; if (!SetEvent(overlapped_.hEvent)) { server_state_ = IPC_SERVER_STATE_ERROR; } } bool CrashGenerationServer::PrepareReply(const ClientInfo& client_info, ProtocolMessage* reply) const { reply->tag = MESSAGE_TAG_REGISTRATION_RESPONSE; reply->pid = GetCurrentProcessId(); if (CreateClientHandles(client_info, reply)) { return true; } if (reply->dump_request_handle) { CloseHandle(reply->dump_request_handle); } if (reply->dump_generated_handle) { CloseHandle(reply->dump_generated_handle); } if (reply->server_alive_handle) { CloseHandle(reply->server_alive_handle); } return false; } bool CrashGenerationServer::CreateClientHandles(const ClientInfo& client_info, ProtocolMessage* reply) const { HANDLE current_process = GetCurrentProcess(); if (!DuplicateHandle(current_process, client_info.dump_requested_handle(), client_info.process_handle(), &reply->dump_request_handle, kDumpRequestEventAccess, FALSE, 0)) { return false; } if (!DuplicateHandle(current_process, client_info.dump_generated_handle(), client_info.process_handle(), &reply->dump_generated_handle, kDumpGeneratedEventAccess, FALSE, 0)) { return false; } if (!DuplicateHandle(current_process, server_alive_handle_, client_info.process_handle(), &reply->server_alive_handle, kMutexAccess, FALSE, 0)) { return false; } return true; } bool CrashGenerationServer::RespondToClient(ClientInfo* client_info) { ProtocolMessage reply; if (!PrepareReply(*client_info, &reply)) { return false; } if (!AddClient(client_info)) { return false; } DWORD bytes_count = 0; bool success = WriteFile(pipe_, &reply, sizeof(reply), &bytes_count, &overlapped_) != FALSE; return success || GetLastError() == ERROR_IO_PENDING; } // The server thread servicing the clients runs this method. The method // implements the state machine described in ReadMe.txt along with the // helper methods HandleXXXState. void CrashGenerationServer::HandleConnectionRequest() { switch (server_state_) { case IPC_SERVER_STATE_ERROR: HandleErrorState(); break; case IPC_SERVER_STATE_INITIAL: HandleInitialState(); break; case IPC_SERVER_STATE_CONNECTING: HandleConnectingState(); break; case IPC_SERVER_STATE_CONNECTED: HandleConnectedState(); break; case IPC_SERVER_STATE_READING: HandleReadingState(); break; case IPC_SERVER_STATE_READ_DONE: HandleReadDoneState(); break; case IPC_SERVER_STATE_WRITING: HandleWritingState(); break; case IPC_SERVER_STATE_WRITE_DONE: HandleWriteDoneState(); break; case IPC_SERVER_STATE_READING_ACK: HandleReadingAckState(); break; case IPC_SERVER_STATE_DISCONNECTING: HandleDisconnectingState(); break; default: assert(false); // This indicates that we added one more state without // adding handling code. server_state_ = IPC_SERVER_STATE_ERROR; break; } } bool CrashGenerationServer::AddClient(ClientInfo* client_info) { HANDLE request_wait_handle = NULL; if (!RegisterWaitForSingleObject(&request_wait_handle, client_info->dump_requested_handle(), OnDumpRequest, client_info, INFINITE, kDumpRequestThreadFlags)) { return false; } client_info->set_dump_request_wait_handle(request_wait_handle); // OnClientEnd will be called when the client process terminates. HANDLE process_wait_handle = NULL; if (!RegisterWaitForSingleObject(&process_wait_handle, client_info->process_handle(), OnClientEnd, client_info, INFINITE, WT_EXECUTEONLYONCE)) { return false; } client_info->set_process_exit_wait_handle(process_wait_handle); // New scope to hold the lock for the shortest time. { AutoCriticalSection lock(&clients_sync_); clients_.push_back(client_info); } return true; } // static void CALLBACK CrashGenerationServer::OnPipeConnected(void* context, BOOLEAN) { assert (context); CrashGenerationServer* obj = reinterpret_cast<CrashGenerationServer*>(context); obj->HandleConnectionRequest(); } // static void CALLBACK CrashGenerationServer::OnDumpRequest(void* context, BOOLEAN) { assert(context); ClientInfo* client_info = reinterpret_cast<ClientInfo*>(context); CrashGenerationServer* crash_server = client_info->crash_server(); assert(crash_server); crash_server->HandleDumpRequest(*client_info); ResetEvent(client_info->dump_requested_handle()); } // static void CALLBACK CrashGenerationServer::OnClientEnd(void* context, BOOLEAN) { assert(context); ClientInfo* client_info = reinterpret_cast<ClientInfo*>(context); CrashGenerationServer* crash_server = client_info->crash_server(); assert(crash_server); InterlockedIncrement(&crash_server->cleanup_item_count_); if (!QueueUserWorkItem(CleanupClient, context, WT_EXECUTEDEFAULT)) { InterlockedDecrement(&crash_server->cleanup_item_count_); } } // static DWORD WINAPI CrashGenerationServer::CleanupClient(void* context) { assert(context); ClientInfo* client_info = reinterpret_cast<ClientInfo*>(context); CrashGenerationServer* crash_server = client_info->crash_server(); assert(crash_server); if (crash_server->exit_callback_) { crash_server->exit_callback_(crash_server->exit_context_, client_info); } crash_server->DoCleanup(client_info); InterlockedDecrement(&crash_server->cleanup_item_count_); return 0; } void CrashGenerationServer::DoCleanup(ClientInfo* client_info) { assert(client_info); // Start a new scope to release lock automatically. { AutoCriticalSection lock(&clients_sync_); clients_.remove(client_info); } delete client_info; } void CrashGenerationServer::HandleDumpRequest(const ClientInfo& client_info) { // Generate the dump only if it's explicitly requested by the // server application; otherwise the server might want to generate // dump in the callback. if (generate_dumps_) { if (!GenerateDump(client_info)) { return; } } if (dump_callback_) { dump_callback_(dump_context_, &client_info); } SetEvent(client_info.dump_generated_handle()); } bool CrashGenerationServer::GenerateDump(const ClientInfo& client) { assert(client.pid() != 0); assert(client.process_handle()); // We have to get the address of EXCEPTION_INFORMATION from // the client process address space. EXCEPTION_POINTERS* client_ex_info = NULL; if (!client.GetClientExceptionInfo(&client_ex_info)) { return false; } DWORD client_thread_id = 0; if (!client.GetClientThreadId(&client_thread_id)) { return false; } return dump_generator_->WriteMinidump(client.process_handle(), client.pid(), client_thread_id, GetCurrentThreadId(), client_ex_info, client.assert_info(), client.dump_type(), true); } } // namespace google_breakpad
[ "ted.mielczarek@4c0a9323-5329-0410-9bdc-e9ce6186880e" ]
[ [ [ 1, 821 ] ] ]
c2f6be0414176cac070f4d74f3e16da25d8ea249
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nphysics/src/nphysics/nphygeomtrans_cmds.cc
7ece26a5401769ea9f4896f42fbee7ea77bd2221
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,472
cc
//----------------------------------------------------------------------------- // nphygeomtrans_cmds.cc // (C) 2003 Conjurer Services, S.A. //----------------------------------------------------------------------------- #include "precompiled/pchnphysics.h" #include "kernel/npersistserver.h" //------------------------------------------------------------------------------ /** @scriptclass nphygeomtrans @cppclass nPhyGeomTrans @superclass nPhysicsGeom @classinfo A Geometry Transform is a geometry that encapsulates another geom. */ NSCRIPT_INITCMDS_BEGIN(nPhyGeomTrans) NSCRIPT_ADDCMD('DDDG', void, AddGeometry, 1, (nPhysicsGeom*), 0, ()); NSCRIPT_INITCMDS_END() //------------------------------------------------------------------------------ /** Object persistency. */ bool nPhyGeomTrans::SaveCmds(nPersistServer* ps) { if( !nPhysicsGeom::SaveCmds(ps) ) return false; nPhysicsGeom* geometry(this->GetGeometry()); if( !geometry ) return true; nCmd* cmd(ps->GetCmd( this, 'DDDG')); n_assert2( cmd, "Error command not found" ); cmd->In()->SetO(geometry); /// Setting if the object it's enabled ps->PutCmd(cmd); return true; } //----------------------------------------------------------------------------- // EOF //-----------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 56 ] ] ]
f38ac92ef84b48acb284b210c60ec8ed5002457f
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/CoreEngine/MovableTextOverlay.h
27fa0d81ae58b92fd744d4d8b3edfc798e29ab72
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
4,083
h
#ifndef __MovableTextOverlay_H__ #define __MovableTextOverlay_H__ #include "Ogre.h" #include "OgreFont.h" #include "OgreFontManager.h" using namespace Ogre; namespace HovUni { class MovableTextOverlayAttributes { public: MovableTextOverlayAttributes(const Ogre::String & name, const Ogre::Camera *cam, const Ogre::String & fontName = "BlueHighway", int charHeight = 16, const Ogre::ColourValue & color = Ogre::ColourValue::White, const Ogre::String & materialName = ""); ~MovableTextOverlayAttributes(); void setFontName(const Ogre::String & fontName); void setMaterialName(const Ogre::String & materialName); void setColor(const Ogre::ColourValue & color); void setCharacterHeight(unsigned int height); const Ogre::String& getName() const {return mName;} const Ogre::Camera* getCamera() const {return mpCam;} const Ogre::Font* getFont() const {return mpFont;} const Ogre::String& getFontName() const {return mFontName;} const Ogre::String& getMaterialName() const {return mMaterialName;} const Ogre::ColourValue& getColor() const {return mColor;} const Ogre::Real getCharacterHeight() const {return mCharHeight;} const Ogre::String mName; const Ogre::Camera *mpCam; Ogre::Font* mpFont; Ogre::String mFontName; Ogre::String mMaterialName; Ogre::ColourValue mColor; Ogre::Real mCharHeight; }; class MovableTextOverlay { public: MovableTextOverlay(const Ogre::String & name, const Ogre::String & caption, const Ogre::MovableObject *mov, MovableTextOverlayAttributes *attrs); virtual ~MovableTextOverlay(); void setCaption(const Ogre::String & caption); void setUpdateFrequency(Ogre::Real updateFrequency) {mUpdateFrequency = updateFrequency;} void setAttributes(MovableTextOverlayAttributes *attrs) { mAttrs = attrs; _updateOverlayAttrs(); } const Ogre::String& getName() const {return mName;} const Ogre::String& getCaption() const {return mCaption;} const Ogre::Real getUpdateFrequency() const {return mUpdateFrequency;} const bool isOnScreen() const {return mOnScreen;} const bool isEnabled() const {return mEnabled;} const MovableTextOverlayAttributes* getAttributes() const {return mAttrs;} void enable(bool enable); void update(Ogre::Real timeSincelastFrame); // Needed for RectLayoutManager. int getPixelsTop() {return (int) (Ogre::OverlayManager::getSingleton().getViewportHeight() * (mpOvContainer->getTop()));} int getPixelsBottom() {return (int) (Ogre::OverlayManager::getSingleton().getViewportHeight() * (mpOvContainer->getTop() + mpOvContainer->getHeight()));} int getPixelsLeft() {return (int) (Ogre::OverlayManager::getSingleton().getViewportWidth() * mpOvContainer->getLeft());} int getPixelsRight() {return (int) (Ogre::OverlayManager::getSingleton().getViewportWidth() * (mpOvContainer->getLeft() + mpOvContainer->getWidth()));} void setPixelsTop(int px) {mpOvContainer->setTop((Ogre::Real)px / Ogre::OverlayManager::getSingleton().getViewportHeight());} // end protected: void _computeTextWidth(); void _updateOverlayAttrs(); void _getMinMaxEdgesOfTopAABBIn2D(Ogre::Real& MinX, Ogre::Real& MinY, Ogre::Real& MaxX, Ogre::Real& MaxY); void _getScreenCoordinates(const Ogre::Vector3& position, Ogre::Real& x, Ogre::Real& y); const Ogre::String mName; const Ogre::MovableObject* mpMov; Ogre::Overlay* mpOv; Ogre::OverlayContainer* mpOvContainer; Ogre::OverlayElement* mpOvText; // true if mpOvContainer is visible, false otherwise bool mEnabled; // true if mTextWidth needs to be recalculated bool mNeedUpdate; // Text width in pixels Ogre::Real mTextWidth; // the Text Ogre::String mCaption; // true if the upper vertices projections of the MovableObject are on screen bool mOnScreen; // the update frequency in seconds // mpOvContainer coordinates get updated each mUpdateFrequency seconds. Ogre::Real mUpdateFrequency; // the Font/Material/Color text attributes MovableTextOverlayAttributes *mAttrs; }; } #endif /* __MovableTextOverlay_H__ */
[ "dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 112 ] ] ]
6b005d0ffea624f5caeedb57f1b4f4847fcb89c5
7c93f9e101f6bba916bc1a967eb8e787afe9be92
/7z920/CPP/Common/MyCom.h
91107dbbf8e8b78af12d79f32634cef73a8e75a3
[]
no_license
ditupao/vx7zip
95759f909368c14f5b8f9a3cbee18a54dc3eae78
13fa94305e8d3491f9d920351e5d1534957a1c06
refs/heads/master
2016-08-11T10:55:47.619762
2011-06-05T09:50:51
2011-06-05T09:50:51
47,533,061
0
0
null
null
null
null
UTF-8
C++
false
false
5,930
h
// MyCom.h #ifndef __MYCOM_H #define __MYCOM_H #include "MyWindows.h" #ifndef RINOK #define RINOK(x) { HRESULT __result_ = (x); if (__result_ != S_OK) return __result_; } #endif template <class T> class CMyComPtr { T* _p; public: // typedef T _PtrClass; CMyComPtr() { _p = NULL;} CMyComPtr(T* p) {if ((_p = p) != NULL) p->AddRef(); } CMyComPtr(const CMyComPtr<T>& lp) { if ((_p = lp._p) != NULL) _p->AddRef(); } ~CMyComPtr() { if (_p) _p->Release(); } void Release() { if (_p) { _p->Release(); _p = NULL; } } operator T*() const { return (T*)_p; } // T& operator*() const { return *_p; } T** operator&() { return &_p; } T* operator->() const { return _p; } T* operator=(T* p) { if (p != 0) p->AddRef(); if (_p) _p->Release(); _p = p; return p; } T* operator=(const CMyComPtr<T>& lp) { return (*this = lp._p); } bool operator!() const { return (_p == NULL); } // bool operator==(T* pT) const { return _p == pT; } // Compare two objects for equivalence void Attach(T* p2) { Release(); _p = p2; } T* Detach() { T* pt = _p; _p = NULL; return pt; } #ifdef _MY_WIN32 HRESULT CoCreateInstance(REFCLSID rclsid, REFIID iid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL) { return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, iid, (void**)&_p); } #endif /* HRESULT CoCreateInstance(LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL) { CLSID clsid; HRESULT hr = CLSIDFromProgID(szProgID, &clsid); ATLASSERT(_p == NULL); if (SUCCEEDED(hr)) hr = ::CoCreateInstance(clsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&_p); return hr; } */ template <class Q> HRESULT QueryInterface(REFGUID iid, Q** pp) const { return _p->QueryInterface(iid, (void**)pp); } }; ////////////////////////////////////////////////////////// inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr) { *bstr = ::SysAllocString(src); return (*bstr != 0) ? S_OK : E_OUTOFMEMORY; } class CMyComBSTR { public: BSTR m_str; CMyComBSTR(): m_str(NULL) {} CMyComBSTR(LPCOLESTR src) { m_str = ::SysAllocString(src); } // CMyComBSTR(int nSize) { m_str = ::SysAllocStringLen(NULL, nSize); } // CMyComBSTR(int nSize, LPCOLESTR sz) { m_str = ::SysAllocStringLen(sz, nSize); } CMyComBSTR(const CMyComBSTR& src) { m_str = src.MyCopy(); } /* CMyComBSTR(REFGUID src) { LPOLESTR szGuid; StringFromCLSID(src, &szGuid); m_str = ::SysAllocString(szGuid); CoTaskMemFree(szGuid); } */ ~CMyComBSTR() { ::SysFreeString(m_str); } CMyComBSTR& operator=(const CMyComBSTR& src) { if (m_str != src.m_str) { if (m_str) ::SysFreeString(m_str); m_str = src.MyCopy(); } return *this; } CMyComBSTR& operator=(LPCOLESTR src) { ::SysFreeString(m_str); m_str = ::SysAllocString(src); return *this; } unsigned int Length() const { return ::SysStringLen(m_str); } operator BSTR() const { return m_str; } BSTR* operator&() { return &m_str; } BSTR MyCopy() const { int byteLen = ::SysStringByteLen(m_str); BSTR res = ::SysAllocStringByteLen(NULL, byteLen); memcpy(res, m_str, byteLen); return res; } /* void Attach(BSTR src) { m_str = src; } BSTR Detach() { BSTR s = m_str; m_str = NULL; return s; } */ void Empty() { ::SysFreeString(m_str); m_str = NULL; } bool operator!() const { return (m_str == NULL); } }; ////////////////////////////////////////////////////////// class CMyUnknownImp { public: ulong __m_RefCount; CMyUnknownImp(): __m_RefCount(0) {} }; #define MY_QUERYINTERFACE_BEGIN STDMETHOD(QueryInterface) \ (REFGUID iid, void **outObject) { #define MY_QUERYINTERFACE_ENTRY(i) if (iid == IID_ ## i) \ { *outObject = (void *)(i *)this; AddRef(); return S_OK; } #define MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) if (iid == IID_IUnknown) \ { *outObject = (void *)(IUnknown *)(i *)this; AddRef(); return S_OK; } #define MY_QUERYINTERFACE_BEGIN2(i) MY_QUERYINTERFACE_BEGIN \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ MY_QUERYINTERFACE_ENTRY(i) #define MY_QUERYINTERFACE_END return E_NOINTERFACE; } #define MY_ADDREF_RELEASE \ STDMETHOD_(ulong, AddRef)() { return ++__m_RefCount; } \ STDMETHOD_(ulong, Release)() { if (--__m_RefCount != 0) \ return __m_RefCount; delete this; return 0; } #define MY_UNKNOWN_IMP_SPEC(i) \ MY_QUERYINTERFACE_BEGIN \ i \ MY_QUERYINTERFACE_END \ MY_ADDREF_RELEASE #define MY_UNKNOWN_IMP MY_QUERYINTERFACE_BEGIN \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(IUnknown) \ MY_QUERYINTERFACE_END \ MY_ADDREF_RELEASE #define MY_UNKNOWN_IMP1(i) MY_UNKNOWN_IMP_SPEC( \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ MY_QUERYINTERFACE_ENTRY(i) \ ) #define MY_UNKNOWN_IMP2(i1, i2) MY_UNKNOWN_IMP_SPEC( \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ MY_QUERYINTERFACE_ENTRY(i1) \ MY_QUERYINTERFACE_ENTRY(i2) \ ) #define MY_UNKNOWN_IMP3(i1, i2, i3) MY_UNKNOWN_IMP_SPEC( \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ MY_QUERYINTERFACE_ENTRY(i1) \ MY_QUERYINTERFACE_ENTRY(i2) \ MY_QUERYINTERFACE_ENTRY(i3) \ ) #define MY_UNKNOWN_IMP4(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC( \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ MY_QUERYINTERFACE_ENTRY(i1) \ MY_QUERYINTERFACE_ENTRY(i2) \ MY_QUERYINTERFACE_ENTRY(i3) \ MY_QUERYINTERFACE_ENTRY(i4) \ ) #define MY_UNKNOWN_IMP5(i1, i2, i3, i4, i5) MY_UNKNOWN_IMP_SPEC( \ MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ MY_QUERYINTERFACE_ENTRY(i1) \ MY_QUERYINTERFACE_ENTRY(i2) \ MY_QUERYINTERFACE_ENTRY(i3) \ MY_QUERYINTERFACE_ENTRY(i4) \ MY_QUERYINTERFACE_ENTRY(i5) \ ) #endif
[ [ [ 1, 225 ] ] ]
0a7e17fca086e80efc7b8198b4d823b894b562a1
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_core/maths/juce_Expression.cpp
8d9fab04d2e97ea9944bbd892a04a912fd0775b6
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
40,776
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== class Expression::Term : public SingleThreadedReferenceCountedObject { public: Term() {} virtual ~Term() {} virtual Type getType() const noexcept = 0; virtual Term* clone() const = 0; virtual ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0; virtual String toString() const = 0; virtual double toDouble() const { return 0; } virtual int getInputIndexFor (const Term*) const { return -1; } virtual int getOperatorPrecedence() const { return 0; } virtual int getNumInputs() const { return 0; } virtual Term* getInput (int) const { return nullptr; } virtual ReferenceCountedObjectPtr<Term> negated(); virtual ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/, double /*overallTarget*/, Term* /*topLevelTerm*/) const { jassertfalse; return nullptr; } virtual String getName() const { jassertfalse; // You shouldn't call this for an expression that's not actually a function! return String::empty; } virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth) { for (int i = getNumInputs(); --i >= 0;) getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth); } class SymbolVisitor { public: virtual ~SymbolVisitor() {} virtual void useSymbol (const Symbol&) = 0; }; virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth) { for (int i = getNumInputs(); --i >= 0;) getInput(i)->visitAllSymbols (visitor, scope, recursionDepth); } private: JUCE_DECLARE_NON_COPYABLE (Term); }; //============================================================================== class Expression::Helpers { public: typedef ReferenceCountedObjectPtr<Term> TermPtr; // This helper function is needed to work around VC6 scoping bugs static inline const TermPtr& getTermFor (const Expression& exp) noexcept { return exp.term; } static void checkRecursionDepth (const int depth) { if (depth > 256) throw EvaluationError ("Recursive symbol references"); } friend class Expression::Term; // (also only needed as a VC6 workaround) //============================================================================== /** An exception that can be thrown by Expression::evaluate(). */ class EvaluationError : public std::exception { public: EvaluationError (const String& description_) : description (description_) { DBG ("Expression::EvaluationError: " + description); } String description; }; //============================================================================== class Constant : public Term { public: Constant (const double value_, const bool isResolutionTarget_) : value (value_), isResolutionTarget (isResolutionTarget_) {} Type getType() const noexcept { return constantType; } Term* clone() const { return new Constant (value, isResolutionTarget); } TermPtr resolve (const Scope&, int) { return this; } double toDouble() const { return value; } TermPtr negated() { return new Constant (-value, isResolutionTarget); } String toString() const { String s (value); if (isResolutionTarget) s = "@" + s; return s; } double value; bool isResolutionTarget; }; //============================================================================== class BinaryTerm : public Term { public: BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_) { jassert (left_ != nullptr && right_ != nullptr); } int getInputIndexFor (const Term* possibleInput) const { return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1); } Type getType() const noexcept { return operatorType; } int getNumInputs() const { return 2; } Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); } virtual double performFunction (double left, double right) const = 0; virtual void writeOperator (String& dest) const = 0; TermPtr resolve (const Scope& scope, int recursionDepth) { return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(), right->resolve (scope, recursionDepth)->toDouble()), false); } String toString() const { String s; const int ourPrecendence = getOperatorPrecedence(); if (left->getOperatorPrecedence() > ourPrecendence) s << '(' << left->toString() << ')'; else s = left->toString(); writeOperator (s); if (right->getOperatorPrecedence() >= ourPrecendence) s << '(' << right->toString() << ')'; else s << right->toString(); return s; } protected: const TermPtr left, right; TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const { jassert (input == left || input == right); if (input != left && input != right) return nullptr; const Term* const dest = findDestinationFor (topLevelTerm, this); if (dest == nullptr) return new Constant (overallTarget, false); return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm); } }; //============================================================================== class SymbolTerm : public Term { public: explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {} TermPtr resolve (const Scope& scope, int recursionDepth) { checkRecursionDepth (recursionDepth); return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1); } Type getType() const noexcept { return symbolType; } Term* clone() const { return new SymbolTerm (symbol); } String toString() const { return symbol; } String getName() const { return symbol; } void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth) { checkRecursionDepth (recursionDepth); visitor.useSymbol (Symbol (scope.getScopeUID(), symbol)); getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1); } void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/) { if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID) symbol = newName; } String symbol; }; //============================================================================== class Function : public Term { public: explicit Function (const String& functionName_) : functionName (functionName_) {} Function (const String& functionName_, const Array<Expression>& parameters_) : functionName (functionName_), parameters (parameters_) {} Type getType() const noexcept { return functionType; } Term* clone() const { return new Function (functionName, parameters); } int getNumInputs() const { return parameters.size(); } Term* getInput (int i) const { return getTermFor (parameters [i]); } String getName() const { return functionName; } TermPtr resolve (const Scope& scope, int recursionDepth) { checkRecursionDepth (recursionDepth); double result = 0; const int numParams = parameters.size(); if (numParams > 0) { HeapBlock<double> params ((size_t) numParams); for (int i = 0; i < numParams; ++i) params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble(); result = scope.evaluateFunction (functionName, params, numParams); } else { result = scope.evaluateFunction (functionName, nullptr, 0); } return new Constant (result, false); } int getInputIndexFor (const Term* possibleInput) const { for (int i = 0; i < parameters.size(); ++i) if (getTermFor (parameters.getReference(i)) == possibleInput) return i; return -1; } String toString() const { if (parameters.size() == 0) return functionName + "()"; String s (functionName + " ("); for (int i = 0; i < parameters.size(); ++i) { s << getTermFor (parameters.getReference(i))->toString(); if (i < parameters.size() - 1) s << ", "; } s << ')'; return s; } const String functionName; Array<Expression> parameters; }; //============================================================================== class DotOperator : public BinaryTerm { public: DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {} TermPtr resolve (const Scope& scope, int recursionDepth) { checkRecursionDepth (recursionDepth); EvaluationVisitor visitor (right, recursionDepth + 1); scope.visitRelativeScope (getSymbol()->symbol, visitor); return visitor.output; } Term* clone() const { return new DotOperator (getSymbol(), right); } String getName() const { return "."; } int getOperatorPrecedence() const { return 1; } void writeOperator (String& dest) const { dest << '.'; } double performFunction (double, double) const { return 0.0; } void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth) { checkRecursionDepth (recursionDepth); visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol)); SymbolVisitingVisitor v (right, visitor, recursionDepth + 1); try { scope.visitRelativeScope (getSymbol()->symbol, v); } catch (...) {} } void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth) { checkRecursionDepth (recursionDepth); getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth); SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1); try { scope.visitRelativeScope (getSymbol()->symbol, visitor); } catch (...) {} } private: //============================================================================== class EvaluationVisitor : public Scope::Visitor { public: EvaluationVisitor (const TermPtr& input_, const int recursionCount_) : input (input_), output (input_), recursionCount (recursionCount_) {} void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); } const TermPtr input; TermPtr output; const int recursionCount; private: JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor); }; class SymbolVisitingVisitor : public Scope::Visitor { public: SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_) : input (input_), visitor (visitor_), recursionCount (recursionCount_) {} void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); } private: const TermPtr input; SymbolVisitor& visitor; const int recursionCount; JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor); }; class SymbolRenamingVisitor : public Scope::Visitor { public: SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_) : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {} void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); } private: const TermPtr input; const Symbol& symbol; const String newName; const int recursionCount; JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor); }; SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); } JUCE_DECLARE_NON_COPYABLE (DotOperator); }; //============================================================================== class Negate : public Term { public: explicit Negate (const TermPtr& input_) : input (input_) { jassert (input_ != nullptr); } Type getType() const noexcept { return operatorType; } int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; } int getNumInputs() const { return 1; } Term* getInput (int index) const { return index == 0 ? input.getObject() : nullptr; } Term* clone() const { return new Negate (input->clone()); } TermPtr resolve (const Scope& scope, int recursionDepth) { return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false); } String getName() const { return "-"; } TermPtr negated() { return input; } TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const { (void) input_; jassert (input_ == input); const Term* const dest = findDestinationFor (topLevelTerm, this); return new Negate (dest == nullptr ? new Constant (overallTarget, false) : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm)); } String toString() const { if (input->getOperatorPrecedence() > 0) return "-(" + input->toString() + ")"; else return "-" + input->toString(); } private: const TermPtr input; }; //============================================================================== class Add : public BinaryTerm { public: Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {} Term* clone() const { return new Add (left->clone(), right->clone()); } double performFunction (double lhs, double rhs) const { return lhs + rhs; } int getOperatorPrecedence() const { return 3; } String getName() const { return "+"; } void writeOperator (String& dest) const { dest << " + "; } TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const { const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); if (newDest == nullptr) return nullptr; return new Subtract (newDest, (input == left ? right : left)->clone()); } private: JUCE_DECLARE_NON_COPYABLE (Add); }; //============================================================================== class Subtract : public BinaryTerm { public: Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {} Term* clone() const { return new Subtract (left->clone(), right->clone()); } double performFunction (double lhs, double rhs) const { return lhs - rhs; } int getOperatorPrecedence() const { return 3; } String getName() const { return "-"; } void writeOperator (String& dest) const { dest << " - "; } TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const { const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); if (newDest == nullptr) return nullptr; if (input == left) return new Add (newDest, right->clone()); else return new Subtract (left->clone(), newDest); } private: JUCE_DECLARE_NON_COPYABLE (Subtract); }; //============================================================================== class Multiply : public BinaryTerm { public: Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {} Term* clone() const { return new Multiply (left->clone(), right->clone()); } double performFunction (double lhs, double rhs) const { return lhs * rhs; } String getName() const { return "*"; } void writeOperator (String& dest) const { dest << " * "; } int getOperatorPrecedence() const { return 2; } TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const { const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); if (newDest == nullptr) return nullptr; return new Divide (newDest, (input == left ? right : left)->clone()); } private: JUCE_DECLARE_NON_COPYABLE (Multiply); }; //============================================================================== class Divide : public BinaryTerm { public: Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {} Term* clone() const { return new Divide (left->clone(), right->clone()); } double performFunction (double lhs, double rhs) const { return lhs / rhs; } String getName() const { return "/"; } void writeOperator (String& dest) const { dest << " / "; } int getOperatorPrecedence() const { return 2; } TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const { const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); if (newDest == nullptr) return nullptr; if (input == left) return new Multiply (newDest, right->clone()); else return new Divide (left->clone(), newDest); } private: JUCE_DECLARE_NON_COPYABLE (Divide); }; //============================================================================== static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm) { const int inputIndex = topLevel->getInputIndexFor (inputTerm); if (inputIndex >= 0) return topLevel; for (int i = topLevel->getNumInputs(); --i >= 0;) { Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm); if (t != nullptr) return t; } return nullptr; } static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged) { { Constant* const c = dynamic_cast<Constant*> (term); if (c != nullptr && (c->isResolutionTarget || ! mustBeFlagged)) return c; } if (dynamic_cast<Function*> (term) != nullptr) return nullptr; int i; const int numIns = term->getNumInputs(); for (i = 0; i < numIns; ++i) { Constant* const c = dynamic_cast<Constant*> (term->getInput (i)); if (c != nullptr && (c->isResolutionTarget || ! mustBeFlagged)) return c; } for (i = 0; i < numIns; ++i) { Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged); if (c != nullptr) return c; } return nullptr; } static bool containsAnySymbols (const Term* const t) { if (t->getType() == Expression::symbolType) return true; for (int i = t->getNumInputs(); --i >= 0;) if (containsAnySymbols (t->getInput (i))) return true; return false; } //============================================================================== class SymbolCheckVisitor : public Term::SymbolVisitor { public: SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {} void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; } bool wasFound; private: const Symbol& symbol; JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor); }; //============================================================================== class SymbolListVisitor : public Term::SymbolVisitor { public: SymbolListVisitor (Array<Symbol>& list_) : list (list_) {} void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); } private: Array<Symbol>& list; JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor); }; //============================================================================== class Parser { public: //============================================================================== Parser (String::CharPointerType& stringToParse) : text (stringToParse) { } TermPtr readUpToComma() { if (text.isEmpty()) return new Constant (0.0, false); const TermPtr e (readExpression()); if (e == nullptr || ((! readOperator (",")) && ! text.isEmpty())) throw ParseError ("Syntax error: \"" + String (text) + "\""); return e; } private: String::CharPointerType& text; //============================================================================== static inline bool isDecimalDigit (const juce_wchar c) noexcept { return c >= '0' && c <= '9'; } bool readChar (const juce_wchar required) noexcept { if (*text == required) { ++text; return true; } return false; } bool readOperator (const char* ops, char* const opType = nullptr) noexcept { text = text.findEndOfWhitespace(); while (*ops != 0) { if (readChar ((juce_wchar) (uint8) *ops)) { if (opType != nullptr) *opType = *ops; return true; } ++ops; } return false; } bool readIdentifier (String& identifier) noexcept { text = text.findEndOfWhitespace(); String::CharPointerType t (text); int numChars = 0; if (t.isLetter() || *t == '_') { ++t; ++numChars; while (t.isLetterOrDigit() || *t == '_') { ++t; ++numChars; } } if (numChars > 0) { identifier = String (text, (size_t) numChars); text = t; return true; } return false; } Term* readNumber() noexcept { text = text.findEndOfWhitespace(); String::CharPointerType t (text); const bool isResolutionTarget = (*t == '@'); if (isResolutionTarget) { ++t; t = t.findEndOfWhitespace(); text = t; } if (*t == '-') { ++t; t = t.findEndOfWhitespace(); } if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1]))) return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget); return nullptr; } TermPtr readExpression() { TermPtr lhs (readMultiplyOrDivideExpression()); char opType; while (lhs != nullptr && readOperator ("+-", &opType)) { TermPtr rhs (readMultiplyOrDivideExpression()); if (rhs == nullptr) throw ParseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\""); if (opType == '+') lhs = new Add (lhs, rhs); else lhs = new Subtract (lhs, rhs); } return lhs; } TermPtr readMultiplyOrDivideExpression() { TermPtr lhs (readUnaryExpression()); char opType; while (lhs != nullptr && readOperator ("*/", &opType)) { TermPtr rhs (readUnaryExpression()); if (rhs == nullptr) throw ParseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\""); if (opType == '*') lhs = new Multiply (lhs, rhs); else lhs = new Divide (lhs, rhs); } return lhs; } TermPtr readUnaryExpression() { char opType; if (readOperator ("+-", &opType)) { TermPtr term (readUnaryExpression()); if (term == nullptr) throw ParseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\""); if (opType == '-') term = term->negated(); return term; } return readPrimaryExpression(); } TermPtr readPrimaryExpression() { TermPtr e (readParenthesisedExpression()); if (e != nullptr) return e; e = readNumber(); if (e != nullptr) return e; return readSymbolOrFunction(); } TermPtr readSymbolOrFunction() { String identifier; if (readIdentifier (identifier)) { if (readOperator ("(")) // method call... { Function* const f = new Function (identifier); ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC) TermPtr param (readExpression()); if (param == nullptr) { if (readOperator (")")) return func.release(); throw ParseError ("Expected parameters after \"" + identifier + " (\""); } f->parameters.add (Expression (param)); while (readOperator (",")) { param = readExpression(); if (param == nullptr) throw ParseError ("Expected expression after \",\""); f->parameters.add (Expression (param)); } if (readOperator (")")) return func.release(); throw ParseError ("Expected \")\""); } else if (readOperator (".")) { TermPtr rhs (readSymbolOrFunction()); if (rhs == nullptr) throw ParseError ("Expected symbol or function after \".\""); if (identifier == "this") return rhs; return new DotOperator (new SymbolTerm (identifier), rhs); } else // just a symbol.. { jassert (identifier.trim() == identifier); return new SymbolTerm (identifier); } } return nullptr; } TermPtr readParenthesisedExpression() { if (! readOperator ("(")) return nullptr; const TermPtr e (readExpression()); if (e == nullptr || ! readOperator (")")) return nullptr; return e; } JUCE_DECLARE_NON_COPYABLE (Parser); }; }; //============================================================================== Expression::Expression() : term (new Expression::Helpers::Constant (0, false)) { } Expression::~Expression() { } Expression::Expression (Term* const term_) : term (term_) { jassert (term != nullptr); } Expression::Expression (const double constant) : term (new Expression::Helpers::Constant (constant, false)) { } Expression::Expression (const Expression& other) : term (other.term) { } Expression& Expression::operator= (const Expression& other) { term = other.term; return *this; } #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS Expression::Expression (Expression&& other) noexcept : term (static_cast <ReferenceCountedObjectPtr<Term>&&> (other.term)) { } Expression& Expression::operator= (Expression&& other) noexcept { term = static_cast <ReferenceCountedObjectPtr<Term>&&> (other.term); return *this; } #endif Expression::Expression (const String& stringToParse) { String::CharPointerType text (stringToParse.getCharPointer()); Helpers::Parser parser (text); term = parser.readUpToComma(); } Expression Expression::parse (String::CharPointerType& stringToParse) { Helpers::Parser parser (stringToParse); return Expression (parser.readUpToComma()); } double Expression::evaluate() const { return evaluate (Expression::Scope()); } double Expression::evaluate (const Expression::Scope& scope) const { try { return term->resolve (scope, 0)->toDouble(); } catch (Helpers::EvaluationError&) {} return 0; } double Expression::evaluate (const Scope& scope, String& evaluationError) const { try { return term->resolve (scope, 0)->toDouble(); } catch (Helpers::EvaluationError& e) { evaluationError = e.description; } return 0; } Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); } Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); } Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); } Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); } Expression Expression::operator-() const { return Expression (term->negated()); } Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); } Expression Expression::function (const String& functionName, const Array<Expression>& parameters) { return Expression (new Helpers::Function (functionName, parameters)); } Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const { ScopedPointer<Term> newTerm (term->clone()); Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true); if (termToAdjust == nullptr) termToAdjust = Helpers::findTermToAdjust (newTerm, false); if (termToAdjust == nullptr) { newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false)); termToAdjust = Helpers::findTermToAdjust (newTerm, false); } jassert (termToAdjust != nullptr); const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust); if (parent == nullptr) { termToAdjust->value = targetValue; } else { const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm)); if (reverseTerm == nullptr) return Expression (targetValue); termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble(); } return Expression (newTerm.release()); } Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const { jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_")); if (oldSymbol.symbolName == newName) return *this; Expression e (term->clone()); e.term->renameSymbol (oldSymbol, newName, scope, 0); return e; } bool Expression::referencesSymbol (const Expression::Symbol& symbolToCheck, const Scope& scope) const { Helpers::SymbolCheckVisitor visitor (symbolToCheck); try { term->visitAllSymbols (visitor, scope, 0); } catch (Helpers::EvaluationError&) {} return visitor.wasFound; } void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const { try { Helpers::SymbolListVisitor visitor (results); term->visitAllSymbols (visitor, scope, 0); } catch (Helpers::EvaluationError&) {} } String Expression::toString() const { return term->toString(); } bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); } Expression::Type Expression::getType() const noexcept { return term->getType(); } String Expression::getSymbolOrFunction() const { return term->getName(); } int Expression::getNumInputs() const { return term->getNumInputs(); } Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); } //============================================================================== ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated() { return new Helpers::Negate (this); } //============================================================================== Expression::ParseError::ParseError (const String& message) : description (message) { DBG ("Expression::ParseError: " + message); } //============================================================================== Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_) : scopeUID (scopeUID_), symbolName (symbolName_) { } bool Expression::Symbol::operator== (const Symbol& other) const noexcept { return symbolName == other.symbolName && scopeUID == other.scopeUID; } bool Expression::Symbol::operator!= (const Symbol& other) const noexcept { return ! operator== (other); } //============================================================================== Expression::Scope::Scope() {} Expression::Scope::~Scope() {} Expression Expression::Scope::getSymbolValue (const String& symbol) const { throw Helpers::EvaluationError ("Unknown symbol: " + symbol); } double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const { if (numParams > 0) { if (functionName == "min") { double v = parameters[0]; for (int i = 1; i < numParams; ++i) v = jmin (v, parameters[i]); return v; } else if (functionName == "max") { double v = parameters[0]; for (int i = 1; i < numParams; ++i) v = jmax (v, parameters[i]); return v; } else if (numParams == 1) { if (functionName == "sin") return sin (parameters[0]); else if (functionName == "cos") return cos (parameters[0]); else if (functionName == "tan") return tan (parameters[0]); else if (functionName == "abs") return std::abs (parameters[0]); } } throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\""); } void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const { throw Helpers::EvaluationError ("Unknown symbol: " + scopeName); } String Expression::Scope::getScopeUID() const { return String::empty; } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 1179 ] ] ]
d5070212e11cb9bc83d4501da7c67963a9368eef
dba70d101eb0e52373a825372e4413ed7600d84d
/RendererComplement/include/DefaultPipeline.h
36e83a80d26495a5ab9f74ffa10993f3413d6bba
[]
no_license
nustxujun/simplerenderer
2aa269199f3bab5dc56069caa8162258e71f0f96
466a43a1e4f6e36e7d03722d0d5355395872ad86
refs/heads/master
2021-03-12T22:38:06.759909
2010-10-02T03:30:26
2010-10-02T03:30:26
32,198,944
0
0
null
null
null
null
GB18030
C++
false
false
1,652
h
#ifndef _DefaultPipeline_H_ #define _DefaultPipeline_H_ #include"Prerequisites.h" #include "Pipeline.h" #include "Rasterizer.h" #include "PipelinePlus.h" #include "DataCollector.h" namespace RCP { class DefaultPipeline: public Pipeline { typedef std::vector<Vertex> VertexList; public: public: DefaultPipeline(); virtual ~DefaultPipeline(); virtual void initImpl() ; void execute(const RenderData& renderData); protected: void vertexProcessing(const RenderData& elem,VertexList& verVec); void primitiveAssembly(const RenderData& elem,const VertexList& verVec); //返回true则说明通过,false则剔除 bool culling(const Primitive& prim,CullMode fm); bool checkPointInScreen(const Vector4& point); void generateNewVertex(Vertex& newVertex,const Vertex& vert1, const Vertex& vert2,float dist1, float dist2); void clipping(const Primitive& prim,Primitive prims[5]); void clippingPoint(const Primitive& prim,Primitive& resultPrim); void clippingLine(const Primitive& prim,Primitive& resultPrim); void clippingTriangle(const Primitive& prim,Primitive prims[5]); void rasterize(Primitive& prim); void homogeneousDivide(Vertex& vert); void viewportMapping(Vector4& pos,const Viewport* vp); void setOtherState(const std::map<std::string,Any>& p); void setVertexShader(VertexShader* vs); void setPixelShader(PixelShader* ps); private: Rasterizer mRasterizer; DataCollector mDataCollector; VertexShader* mVertexShader; VertexList mVertexList; //裁減空間 Vector4 mPlane[6]; }; } #endif//_DefaultPipeline_H_
[ "[email protected]@c2606ca0-2ebb-fda8-717c-293879e69bc3" ]
[ [ [ 1, 62 ] ] ]
af43436c4703e5a8604fedb830f9a1dced671be2
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-shared/Util.cpp
1e1b1c53719cb4b51a446ddb2fa7b0734919ee39
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
8,822
cpp
/* * ArcEmu MMORPG Server * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "Common.h" using namespace std; vector<string> StrSplit(const string &src, const string &sep) { vector<string> r; string s; for (string::const_iterator i = src.begin(); i != src.end(); i++) { if (sep.find(*i) != string::npos) { if (s.length()) r.push_back(s); s = ""; } else { s += *i; } } if (s.length()) r.push_back(s); return r; } void SetThreadName(const char* format, ...) { // This isn't supported on nix? va_list ap; va_start(ap, format); #ifdef WIN32 char thread_name[200]; vsnprintf(thread_name, 200, format, ap); THREADNAME_INFO info; info.dwType = 0x1000; info.dwThreadID = GetCurrentThreadId(); info.dwFlags = 0; info.szName = thread_name; __try { #ifdef _WIN64 RaiseException(0x406D1388, 0, sizeof(info)/sizeof(DWORD), (ULONG_PTR*)&info); #else RaiseException(0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info); #endif } __except(EXCEPTION_CONTINUE_EXECUTION) { } #endif va_end(ap); } time_t convTimePeriod ( uint32 dLength, char dType ) { time_t rawtime = 0; if (dLength == 0) return rawtime; struct tm * ti = localtime( &rawtime ); switch(dType) { case 'h': // hours ti->tm_hour += dLength; break; case 'd': // days ti->tm_mday += dLength; break; case 'w': // weeks ti->tm_mday += 7 * dLength; break; case 'm': // months ti->tm_mon += dLength; break; case 'y': // years // are leap years considered ? do we care ? ti->tm_year += dLength; break; default: // minutes ti->tm_min += dLength; break; } return mktime(ti); } int32 GetTimePeriodFromString(const char * str) { uint32 time_to_ban = 0; char * p = (char*)str; uint32 multiplier; string number_temp; uint32 multipliee; number_temp.reserve(10); while(*p != 0) { // always starts with a number. if(!isdigit(*p)) break; number_temp.clear(); while(isdigit(*p) && *p != 0) { number_temp += *p; ++p; } // try and find a letter if(*p == 0) break; // check the type switch(tolower(*p)) { case 'y': multiplier = TIME_YEAR; // eek! break; case 'm': multiplier = TIME_MONTH; break; case 'd': multiplier = TIME_DAY; break; case 'h': multiplier = TIME_HOUR; break; default: return -1; break; } ++p; multipliee = atoi(number_temp.c_str()); time_to_ban += (multiplier * multipliee); } return time_to_ban; } const char * szDayNames[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; const char * szMonthNames[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; void MakeIntString(char * buf, int num) { if(num<10) { buf[0] = '0'; //itoa(num, &buf[1], 10); sprintf(&buf[1], "%u", num); } else { //itoa(num,buf,10); sprintf(buf,"%u",num); } } void MakeIntStringNoZero(char * buf, int num) { //itoa(num,buf,10); sprintf(buf,"%u",num); } string ConvertTimeStampToString(uint32 timestamp) { int seconds = (int)timestamp; int mins=0; int hours=0; int days=0; int months=0; int years=0; if(seconds >= 60) { mins = seconds / 60; if(mins) { seconds -= mins*60; if(mins >= 60) { hours = mins / 60; if(hours) { mins -= hours*60; if(hours >= 24) { days = hours/24; if(days) { hours -= days*24; if(days >= 30) { months = days / 30; if(months) { days -= months*30; if(months >= 12) { years = months / 12; if(years) { months -= years*12; } } } } } } } } } } char szTempBuf[100]; string szResult; if(years) { MakeIntStringNoZero(szTempBuf, years); szResult += szTempBuf; szResult += " years, "; } if(months) { MakeIntStringNoZero(szTempBuf, months); szResult += szTempBuf; szResult += " months, "; } if(days) { MakeIntStringNoZero(szTempBuf, days); szResult += szTempBuf; szResult += " days, "; } if(hours) { MakeIntStringNoZero(szTempBuf, hours); szResult += szTempBuf; szResult += " hours, "; } if(mins) { MakeIntStringNoZero(szTempBuf, mins); szResult += szTempBuf; szResult += " minutes, "; } if(seconds) { MakeIntStringNoZero(szTempBuf, seconds); szResult += szTempBuf; szResult += " seconds"; } return szResult; } string ConvertTimeStampToDataTime(uint32 timestamp) { char szTempBuf[100]; time_t t = (time_t)timestamp; tm * pTM = localtime(&t); string szResult; szResult += szDayNames[pTM->tm_wday]; szResult += ", "; MakeIntString(szTempBuf, pTM->tm_mday); szResult += szTempBuf; szResult += " "; szResult += szMonthNames[pTM->tm_mon]; szResult += " "; MakeIntString(szTempBuf, pTM->tm_year+1900); szResult += szTempBuf; szResult += ", "; MakeIntString(szTempBuf, pTM->tm_hour); szResult += szTempBuf; szResult += ":"; MakeIntString(szTempBuf, pTM->tm_min); szResult += szTempBuf; szResult += ":"; MakeIntString(szTempBuf, pTM->tm_sec); szResult += szTempBuf; return szResult; } #ifdef WIN32 static char _StringConversionStorage[2048]; #endif // win32 only // cebernic added it // for multilanguage supports // -------------------------------------------------------------------------------------------------- SERVER_DECL const char* _StringToUTF8(const char* pASCIIBuf) { #ifdef WIN32 DWORD UniCodeLen=MultiByteToWideChar(CP_ACP, 0, pASCIIBuf, -1, 0, 0); std::vector <wchar_t> vWCH(UniCodeLen); MultiByteToWideChar(CP_ACP, 0, pASCIIBuf, -1, &vWCH[0], UniCodeLen); DWORD dwUtf8Len=WideCharToMultiByte(CP_UTF8, 0, &vWCH[0], UniCodeLen , NULL, NULL, NULL, NULL ); ASSERT( dwUtf8Len+1 < 2048 ); memset(_StringConversionStorage,0,(sizeof(char)*dwUtf8Len)+1); WideCharToMultiByte(CP_UTF8, 0, &vWCH[0], UniCodeLen , _StringConversionStorage, dwUtf8Len, NULL, NULL ); return &_StringConversionStorage[0]; #else return &pASCIIBuf[0]; #endif } SERVER_DECL const char* _StringToANSI(const char* pUtf8Buf) { #ifdef WIN32 DWORD UniCodeLen=MultiByteToWideChar(CP_UTF8, 0, pUtf8Buf, -1, NULL,0 ); std::vector <wchar_t> vWCH(UniCodeLen); MultiByteToWideChar(CP_UTF8, 0, pUtf8Buf, -1, &vWCH[0] , UniCodeLen ); DWORD dwASCIILen=WideCharToMultiByte(CP_ACP, 0, &vWCH[0], UniCodeLen , NULL ,NULL , NULL, NULL ); ASSERT( dwASCIILen+1 < 2048 ); memset(_StringConversionStorage,0,(sizeof(char)*dwASCIILen)+1); WideCharToMultiByte(CP_ACP, 0, &vWCH[0], UniCodeLen , _StringConversionStorage, dwASCIILen, NULL, NULL ); return &_StringConversionStorage[0]; #else return &pUtf8Buf[0]; #endif } SERVER_DECL bool _IsStringUTF8(const char *str) { int i; unsigned char cOctets; // octets to go in this UTF-8 encoded character unsigned char chr; bool bAllAscii= TRUE; long iLen = (long)strlen(str); cOctets= 0; for( i=0; i <iLen; i++ ) { chr = (unsigned char)str[i]; if( (chr & 0x80) != 0 ) bAllAscii= FALSE; if( cOctets == 0 ) { if( chr>= 0x80 ) { do { chr <<= 1; cOctets++; } while( (chr & 0x80) != 0 ); cOctets--; if( cOctets == 0 ) return FALSE; } } else { if( (chr & 0xC0) != 0x80 ) return FALSE; cOctets--; } } if( cOctets> 0 ) return FALSE; if( bAllAscii ) return FALSE; return TRUE; }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 4, 313 ] ], [ [ 2, 3 ], [ 314, 395 ] ] ]
3009e8a3eb13f6e5c42574568aeb64f166955d6f
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/validators/schema/XUtil.hpp
9f3eea78493db4c806edca771c2d1af554eb46d0
[ "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,164
hpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: XUtil.hpp,v $ * Revision 1.6 2004/09/08 13:56:58 peiyongz * Apache License Version 2.0 * * Revision 1.5 2004/01/29 11:52:31 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.4 2002/11/04 14:49:42 tng * C++ Namespace Support. * * Revision 1.3 2002/05/21 19:31:45 tng * DOM Reorganization: modify to use the new DOM interface and remove obsolete code in XUtil. * * Revision 1.2 2002/02/06 22:21:49 knoaman * Use IDOM for schema processing. * * Revision 1.1.1.1 2002/02/01 22:22:50 peiyongz * sane_include * * Revision 1.3 2001/11/02 14:13:45 knoaman * Add support for identity constraints. * * Revision 1.2 2001/05/11 13:27:39 tng * Copyright update. * * Revision 1.1 2001/03/30 16:06:00 tng * Schema: XUtil, added by Pei Yong Zhang * */ #if !defined(XUTIL_HPP) #define XUTIL_HPP #include <xercesc/dom/DOMElement.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMNamedNodeMap.hpp> #include <xercesc/dom/DOMNode.hpp> XERCES_CPP_NAMESPACE_BEGIN class DOMNode; class DOMElement; /** * Some useful utility methods. */ class VALIDATORS_EXPORT XUtil { public: // Finds and returns the first child element node. static DOMElement* getFirstChildElement(const DOMNode* const parent); // Finds and returns the first child node with the given qualifiedname. static DOMElement* getFirstChildElementNS(const DOMNode* const parent , const XMLCh** const elemNames , const XMLCh* const uriStr , unsigned int length); // Finds and returns the next sibling element node. static DOMElement* getNextSiblingElement(const DOMNode* const node); static DOMElement* getNextSiblingElementNS(const DOMNode* const node , const XMLCh** const elemNames , const XMLCh* const uriStr , unsigned int length); private: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- // This class cannot be instantiated. XUtil() {}; ~XUtil() {}; }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 97 ] ] ]
ca2bfdaa89eb5834c2e49fc9d4ba8b3f89c67141
f71ec73f66cbdc16ae955feb30e32d392e1b3008
/Softimage/keyvisQMenu/cppsrc/QPNode.cpp
f93594bb7f7c2b69d41d8b4bfc5f04b186222996
[]
no_license
code-google-com/keyvis-dev
ce7b7fbb2c4fbfee3000b46acfc8302d7a92dce5
4d8295a37b9ce25f3294536f8da8661ecc9b680a
refs/heads/master
2021-01-10T20:33:41.776421
2011-09-22T08:46:00
2011-09-22T08:46:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,869
cpp
#pragma once #include "QPNode.h" using namespace System; //________________________________________________________________________ QPNode::QPNode(void) // Standard Constructor { this->nodeString = nullptr; this->nodeList = nullptr; } //________________________________________________________________________ QPNode::QPNode(String^ argString) // Constructor, creates a linked tree of QPNodes out of a recursive string: "[...][...][...][...]" { //Windows::Forms::MessageBox::Show("argString = " + argString); this->nodeString = ""; this->nodeList = gcnew Collections::Generic::List<QPNode^>(); Text::StringBuilder^ argStr = gcnew Text::StringBuilder(argString); // StringBuilder is used for dynamic strings String^ nodeStr; // used as return value from findNextNode String^ restStr; // used as return value from findNextNode do { if(!findNextNode(argStr->ToString() /*param*/ , nodeStr /*return value*/, restStr /*return value*/)) { // string contains no "[ ]" this->nodeString = nodeStr; break; // if leading character(s) not enclosed by brackets are found, the rest of the string is ignored: "abc[def][ghi]" -> "abc" } else { // [ ] found String^ nodeStrNoBrackets = nodeStr->Substring(1, nodeStr->Length - 2); // remove enclosing [ ] QPNode^ node = gcnew QPNode(nodeStrNoBrackets); // recursively create a new sub-node with the content of the [ ] this->nodeList->Add(node); } argStr->Remove(0, nodeStr->Length); // remove the leading node we just handled } while (argStr->Length); // loop until nothing's left of the string } //________________________________________________________________________ bool QPNode::findNextNode(String^ argStr, String^% nodeStr, String^% restStr) // findNextNode seeks next [...] and returns: true if a [...] is found , which means the QPNode has sub-list/no string, "branch" // false if no [...] is found, which means the QPNode has string/no sub-list, "leaf" { int level = 0; int start = 0; int end = argStr->Length; bool isNode = false; for(int i = start; i < argStr->Length; i++) { if(argStr[i] == '[') { if(level == 0 && i > start) // when argStr is "a[b][c]" : a is returned, rest discarded { isNode = false; end = i; break; } if(level == 0) { start = i; // first "[" is remembered... always 0 isNode = true; } level++; continue; } if(argStr[i] == ']') { level--; if(level == 0) { end = i + 1; break; // [...]... : last "]" was found } } } if(level != 0) // syntax error: not as many "[" as "]" { isNode = false; nodeStr = ""; restStr = ""; return isNode; } nodeStr = argStr->Substring(start, end - start); restStr = argStr->Substring(end); return isNode; }
[ "[email protected]@a75dab56-0351-11df-afd9-7791053e64b7" ]
[ [ [ 1, 101 ] ] ]
4f97427309852362638740af0574d91a249fc093
f0da2c3ab8426f8bcdd8c3625c805a25f04aa89d
/armagic/EventHandler.h
85ac3e1e067ba0811b65098058d890cffa2f62a5
[]
no_license
sanyaade-augmented-reality/armagic
81e557978936c396333be0261e45d869da680e6d
eb5132d280685e2f8db4ae1f3fbe624b1876bf73
refs/heads/master
2016-09-06T17:12:20.458558
2010-07-06T22:57:18
2010-07-06T22:57:18
34,191,493
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
h
#ifndef ARMAGIC_EVENT_HANDLER_H_ #define ARMAGIC_EVENT_HANDLER_H_ #include <irrlicht.h> using namespace irr; class EventHandler : public IEventReceiver { public: EventHandler() { for (u32 i = 0; i < KEY_KEY_CODES_COUNT; ++i) KeyIsDown[i] = false; } virtual bool OnEvent(const SEvent& event) { // Remember whether each key is down or up if (event.EventType == irr::EET_KEY_INPUT_EVENT) KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown; else if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) { switch (event.MouseInput.Event) { case EMIE_LMOUSE_PRESSED_DOWN: MouseState.LeftButtonDown = true; break; case EMIE_LMOUSE_LEFT_UP: MouseState.LeftButtonDown = false; break; case EMIE_MOUSE_MOVED: MouseState.Position.X = event.MouseInput.X; MouseState.Position.Y = event.MouseInput.Y; break; default: // We won't use the wheel break; } } return false; } // This is used to check whether a key is being held down virtual bool IsKeyDown(EKEY_CODE keyCode) const { return KeyIsDown[keyCode]; } virtual bool IsMouseClicked() { bool ret = MouseState.LeftButtonDown; MouseState.LeftButtonDown = false; return ret; } core::position2di getMousePosition() const { return MouseState.Position; } private: struct SMouseState { core::position2di Position; bool LeftButtonDown; SMouseState() : LeftButtonDown(false) { } } MouseState; bool KeyIsDown[KEY_KEY_CODES_COUNT]; }; #endif
[ "leochatain@22892e45-cd4f-0d29-0166-6a0decb81ae3" ]
[ [ [ 1, 67 ] ] ]
8b06354dc2498dae7bbb21ea1d40c071e1f23bc7
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameSDK/GameCore/Source/XObject.cpp
fd5f3e6005717bef96ac7e0a16fed434aef72533
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
GB18030
C++
false
false
3,728
cpp
#include "stdafx.h" #include "XObject.h" #include "XObjectPool.h" CORE_API _uint32 dwTlsIndex = TLS_OUT_OF_INDEXES; namespace XGC { ////////////////////////////////////////////////////////////////////////// // CXObject CXObject::CXObject() : m_nID( INVALID_OBJID ) , m_nParentID( INVALID_OBJID ) , m_bIsParent( true ) , m_bIsTypeList( true ) , m_nStatus( OBJST_NORMAL ) { // 自动列表 m_nID = CXObjectPool::GetInstance().AddObj( this ); } CXObject::CXObject( bool bIsParent, bool bIsTypeList ) : m_nID( INVALID_OBJID ) , m_nParentID( INVALID_OBJID ) , m_bIsParent( bIsParent ) , m_bIsTypeList( bIsTypeList ) , m_nStatus( OBJST_NORMAL ) { m_nID = CXObjectPool::GetInstance().AddObj( this ); } CXObject::~CXObject() { CXObjectPool::GetInstance().DelObj( m_nID ); ThisTriggerMgr()->TriggerEvent( m_nID, trigger_event_destroy, true ); } bool CXObject::AddChild( identifier nID, bool bChangeParent /*= true*/ ) { CXObject* pObj = CXObjectPool::GetInstance().GetObj( nID ); return AddChild( pObj, bChangeParent ); } bool CXObject::AddChild( CXObject* pObj, bool bChangeParent /*= true*/ ) { ASSERT_POINTER( pObj ); if( !pObj ) return false; if( PreAddChild( pObj ) ) { if( m_bIsParent && bChangeParent ) { CXObject* pParent = CXObjectPool::GetInstance().GetObj( pObj->GetParent() ); if( pParent ) { pParent->RemoveChild( pObj ); } pObj->SetParent( m_nID ); } m_ChildList.insert( pObj->GetObjID() ); // 插入到分类表中 if( m_bIsTypeList ) { CChildList& tl = m_TypeList[pObj->GetType()]; tl.insert( pObj->GetObjID() ); } OnAddChild( pObj ); return true; } return false; } // 删除子对象ID void CXObject::RemoveChild( identifier nID, bool bRelease ) { CXObject* pObj = CXObjectPool::GetInstance().GetObj( nID ); return RemoveChild( pObj, bRelease ); } void CXObject::RemoveChild( CXObject* pObj, bool bRelease /* = false */ ) { ASSERT_POINTER( pObj ); _uint32 nID = pObj->GetObjID(); CChildList::iterator iter = m_ChildList.find( nID ); if( iter != m_ChildList.end() && PreRemoveChild( pObj, bRelease ) ) { OnRemoveChild( pObj, bRelease ); m_ChildList.erase( iter ); if( m_bIsTypeList ) { // 分类表中删除 CChildList& tl = m_TypeList[pObj->GetType()]; tl.erase( nID ); } // 根据指示销毁对象 if( bRelease && m_bIsParent ) { pObj->Destroy(); } } } bool CXObject::Destroy() { CXObject* pParent = CXObjectPool::GetInstance().GetObj( GetParent() ); m_nStatus |= OBJST_DESTROY; if( pParent ) { pParent->RemoveChild( this ); } OnDestroy(); DestroyAllChild(); delete this; return true; } void CXObject::DestroyAllChild() { CXObjectPool& objlist = CXObjectPool::GetInstance(); while( !m_ChildList.empty() ) { int nID = *m_ChildList.begin(); CXObject* pObj = objlist.GetObj( nID ); if( !pObj || !pObj->Destroy() ) { return; } } } //---------------------------------------------------// // [9/21/2009 Albert] // Description: 销毁所有子对象 //---------------------------------------------------// void CXObject::DestroyAllChild( int nType ) { CXObjectPool& objlist = CXObjectPool::GetInstance(); CTypeList::iterator iter = m_TypeList.find( nType ); if( iter == m_TypeList.end() ) return; CChildList &tl = iter->second; while( !tl.empty() ) { int nID = *tl.begin(); CXObject* pObj = objlist.GetObj( nID ); if( !pObj || !pObj->Destroy() ) { return; } } } }
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 161 ] ] ]